2023-08-28 14:58:24 -07:00
|
|
|
//! Functions for setting up our WebSocket and WebRTC connections for communications with the
|
|
|
|
//! engine.
|
|
|
|
|
2024-09-19 14:06:29 -07:00
|
|
|
use std::sync::{Arc, Mutex};
|
2023-08-28 14:58:24 -07:00
|
|
|
|
2023-09-20 16:59:03 -05:00
|
|
|
use anyhow::{anyhow, Result};
|
2023-09-15 20:45:28 -07:00
|
|
|
use dashmap::DashMap;
|
2023-08-28 14:58:24 -07:00
|
|
|
use futures::{SinkExt, StreamExt};
|
2024-09-19 14:06:29 -07:00
|
|
|
use indexmap::IndexMap;
|
|
|
|
use kcmc::{
|
|
|
|
websocket::{
|
|
|
|
BatchResponse, FailureWebSocketResponse, ModelingCmdReq, ModelingSessionData, OkWebSocketResponseData,
|
|
|
|
SuccessWebSocketResponse, WebSocketRequest, WebSocketResponse,
|
|
|
|
},
|
|
|
|
ModelingCmd,
|
2024-09-18 17:04:04 -05:00
|
|
|
};
|
|
|
|
use kittycad_modeling_cmds as kcmc;
|
2024-04-15 17:18:32 -07:00
|
|
|
use tokio::sync::{mpsc, oneshot, RwLock};
|
2023-08-28 14:58:24 -07:00
|
|
|
use tokio_tungstenite::tungstenite::Message as WsMsg;
|
|
|
|
|
2023-09-17 21:57:43 -07:00
|
|
|
use crate::{
|
|
|
|
engine::EngineManager,
|
|
|
|
errors::{KclError, KclErrorDetails},
|
2024-10-09 19:38:40 -04:00
|
|
|
executor::{DefaultPlanes, IdGenerator},
|
2023-09-17 21:57:43 -07:00
|
|
|
};
|
2023-08-28 14:58:24 -07:00
|
|
|
|
2024-03-01 14:43:11 -05:00
|
|
|
#[derive(Debug, PartialEq)]
|
|
|
|
enum SocketHealth {
|
|
|
|
Active,
|
|
|
|
Inactive,
|
|
|
|
}
|
|
|
|
|
2023-09-20 16:59:03 -05:00
|
|
|
type WebSocketTcpWrite = futures::stream::SplitSink<tokio_tungstenite::WebSocketStream<reqwest::Upgraded>, WsMsg>;
|
|
|
|
#[derive(Debug, Clone)]
|
2023-08-28 14:58:24 -07:00
|
|
|
pub struct EngineConnection {
|
2023-09-20 16:59:03 -05:00
|
|
|
engine_req_tx: mpsc::Sender<ToEngineReq>,
|
2023-09-15 20:45:28 -07:00
|
|
|
responses: Arc<DashMap<uuid::Uuid, WebSocketResponse>>,
|
2024-10-03 01:05:12 -04:00
|
|
|
pending_errors: Arc<Mutex<Vec<String>>>,
|
2024-08-23 17:40:30 -05:00
|
|
|
#[allow(dead_code)]
|
2023-09-20 18:27:08 -07:00
|
|
|
tcp_read_handle: Arc<TcpReadHandle>,
|
2024-03-01 14:43:11 -05:00
|
|
|
socket_health: Arc<Mutex<SocketHealth>>,
|
2024-03-23 15:45:55 -07:00
|
|
|
batch: Arc<Mutex<Vec<(WebSocketRequest, crate::executor::SourceRange)>>>,
|
2024-09-19 14:06:29 -07:00
|
|
|
batch_end: Arc<Mutex<IndexMap<uuid::Uuid, (WebSocketRequest, crate::executor::SourceRange)>>>,
|
2024-04-15 17:18:32 -07:00
|
|
|
|
|
|
|
/// The default planes for the scene.
|
|
|
|
default_planes: Arc<RwLock<Option<DefaultPlanes>>>,
|
2024-08-23 17:40:30 -05:00
|
|
|
/// If the server sends session data, it'll be copied to here.
|
|
|
|
session_data: Arc<Mutex<Option<ModelingSessionData>>>,
|
2023-08-28 14:58:24 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
pub struct TcpRead {
|
|
|
|
stream: futures::stream::SplitStream<tokio_tungstenite::WebSocketStream<reqwest::Upgraded>>,
|
|
|
|
}
|
|
|
|
|
2024-06-18 14:38:25 -05:00
|
|
|
/// Occurs when client couldn't read from the WebSocket to the engine.
|
|
|
|
// #[derive(Debug)]
|
|
|
|
pub enum WebSocketReadError {
|
|
|
|
/// Could not read a message due to WebSocket errors.
|
|
|
|
Read(tokio_tungstenite::tungstenite::Error),
|
|
|
|
/// WebSocket message didn't contain a valid message that the KCL Executor could parse.
|
|
|
|
Deser(anyhow::Error),
|
|
|
|
}
|
|
|
|
|
|
|
|
impl From<anyhow::Error> for WebSocketReadError {
|
|
|
|
fn from(e: anyhow::Error) -> Self {
|
|
|
|
Self::Deser(e)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-08-28 14:58:24 -07:00
|
|
|
impl TcpRead {
|
2024-06-18 14:38:25 -05:00
|
|
|
pub async fn read(&mut self) -> std::result::Result<WebSocketResponse, WebSocketReadError> {
|
2023-09-15 20:45:28 -07:00
|
|
|
let Some(msg) = self.stream.next().await else {
|
2024-06-18 14:38:25 -05:00
|
|
|
return Err(anyhow::anyhow!("Failed to read from WebSocket").into());
|
2023-09-15 20:45:28 -07:00
|
|
|
};
|
2024-06-18 14:38:25 -05:00
|
|
|
let msg = match msg {
|
|
|
|
Ok(msg) => msg,
|
|
|
|
Err(e) if matches!(e, tokio_tungstenite::tungstenite::Error::Protocol(_)) => {
|
|
|
|
return Err(WebSocketReadError::Read(e))
|
|
|
|
}
|
|
|
|
Err(e) => return Err(anyhow::anyhow!("Error reading from engine's WebSocket: {e}").into()),
|
|
|
|
};
|
|
|
|
let msg: WebSocketResponse = match msg {
|
|
|
|
WsMsg::Text(text) => serde_json::from_str(&text)
|
|
|
|
.map_err(anyhow::Error::from)
|
|
|
|
.map_err(WebSocketReadError::from)?,
|
|
|
|
WsMsg::Binary(bin) => bson::from_slice(&bin)
|
|
|
|
.map_err(anyhow::Error::from)
|
|
|
|
.map_err(WebSocketReadError::from)?,
|
|
|
|
other => return Err(anyhow::anyhow!("Unexpected WebSocket message from engine API: {other}").into()),
|
2023-08-28 14:58:24 -07:00
|
|
|
};
|
|
|
|
Ok(msg)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-09-20 18:27:08 -07:00
|
|
|
pub struct TcpReadHandle {
|
2024-06-18 14:38:25 -05:00
|
|
|
handle: Arc<tokio::task::JoinHandle<Result<(), WebSocketReadError>>>,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl std::fmt::Debug for TcpReadHandle {
|
|
|
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
|
|
write!(f, "TcpReadHandle")
|
|
|
|
}
|
2023-09-20 18:27:08 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
impl Drop for TcpReadHandle {
|
|
|
|
fn drop(&mut self) {
|
|
|
|
// Drop the read handle.
|
|
|
|
self.handle.abort();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-09-20 16:59:03 -05:00
|
|
|
/// Requests to send to the engine, and a way to await a response.
|
|
|
|
struct ToEngineReq {
|
|
|
|
/// The request to send
|
|
|
|
req: WebSocketRequest,
|
|
|
|
/// If this resolves to Ok, the request was sent.
|
|
|
|
/// If this resolves to Err, the request could not be sent.
|
|
|
|
/// If this has not yet resolved, the request has not been sent yet.
|
|
|
|
request_sent: oneshot::Sender<Result<()>>,
|
|
|
|
}
|
|
|
|
|
2023-08-28 14:58:24 -07:00
|
|
|
impl EngineConnection {
|
2023-09-20 16:59:03 -05:00
|
|
|
/// Start waiting for incoming engine requests, and send each one over the WebSocket to the engine.
|
|
|
|
async fn start_write_actor(mut tcp_write: WebSocketTcpWrite, mut engine_req_rx: mpsc::Receiver<ToEngineReq>) {
|
|
|
|
while let Some(req) = engine_req_rx.recv().await {
|
|
|
|
let ToEngineReq { req, request_sent } = req;
|
2024-09-18 17:04:04 -05:00
|
|
|
let res = if let WebSocketRequest::ModelingCmdReq(ModelingCmdReq {
|
|
|
|
cmd: ModelingCmd::ImportFiles { .. },
|
2024-02-11 15:08:54 -08:00
|
|
|
cmd_id: _,
|
2024-09-18 17:04:04 -05:00
|
|
|
}) = &req
|
2024-02-11 15:08:54 -08:00
|
|
|
{
|
|
|
|
// Send it as binary.
|
|
|
|
Self::inner_send_to_engine_binary(req, &mut tcp_write).await
|
2023-11-28 15:20:59 -08:00
|
|
|
} else {
|
|
|
|
Self::inner_send_to_engine(req, &mut tcp_write).await
|
|
|
|
};
|
2023-09-20 16:59:03 -05:00
|
|
|
let _ = request_sent.send(res);
|
|
|
|
}
|
2024-04-05 11:37:46 -04:00
|
|
|
let _ = Self::inner_close_engine(&mut tcp_write).await;
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Send the given `request` to the engine via the WebSocket connection `tcp_write`.
|
|
|
|
async fn inner_close_engine(tcp_write: &mut WebSocketTcpWrite) -> Result<()> {
|
|
|
|
tcp_write
|
|
|
|
.send(WsMsg::Close(None))
|
|
|
|
.await
|
|
|
|
.map_err(|e| anyhow!("could not send close over websocket: {e}"))?;
|
|
|
|
Ok(())
|
2023-09-20 16:59:03 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Send the given `request` to the engine via the WebSocket connection `tcp_write`.
|
|
|
|
async fn inner_send_to_engine(request: WebSocketRequest, tcp_write: &mut WebSocketTcpWrite) -> Result<()> {
|
|
|
|
let msg = serde_json::to_string(&request).map_err(|e| anyhow!("could not serialize json: {e}"))?;
|
|
|
|
tcp_write
|
|
|
|
.send(WsMsg::Text(msg))
|
|
|
|
.await
|
|
|
|
.map_err(|e| anyhow!("could not send json over websocket: {e}"))?;
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
2023-11-28 15:20:59 -08:00
|
|
|
/// Send the given `request` to the engine via the WebSocket connection `tcp_write` as binary.
|
|
|
|
async fn inner_send_to_engine_binary(request: WebSocketRequest, tcp_write: &mut WebSocketTcpWrite) -> Result<()> {
|
|
|
|
let msg = bson::to_vec(&request).map_err(|e| anyhow!("could not serialize bson: {e}"))?;
|
|
|
|
tcp_write
|
|
|
|
.send(WsMsg::Binary(msg))
|
|
|
|
.await
|
|
|
|
.map_err(|e| anyhow!("could not send json over websocket: {e}"))?;
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
2023-09-15 20:45:28 -07:00
|
|
|
pub async fn new(ws: reqwest::Upgraded) -> Result<EngineConnection> {
|
2024-07-18 15:20:50 -04:00
|
|
|
let wsconfig = tokio_tungstenite::tungstenite::protocol::WebSocketConfig {
|
|
|
|
// 4294967296 bytes, which is around 4.2 GB.
|
|
|
|
max_message_size: Some(0x100000000),
|
|
|
|
max_frame_size: Some(0x100000000),
|
|
|
|
..Default::default()
|
|
|
|
};
|
2024-07-17 15:32:57 -04:00
|
|
|
|
2023-08-28 14:58:24 -07:00
|
|
|
let ws_stream = tokio_tungstenite::WebSocketStream::from_raw_socket(
|
|
|
|
ws,
|
|
|
|
tokio_tungstenite::tungstenite::protocol::Role::Client,
|
2024-07-17 15:32:57 -04:00
|
|
|
Some(wsconfig),
|
2023-08-28 14:58:24 -07:00
|
|
|
)
|
|
|
|
.await;
|
|
|
|
|
|
|
|
let (tcp_write, tcp_read) = ws_stream.split();
|
2023-09-20 16:59:03 -05:00
|
|
|
let (engine_req_tx, engine_req_rx) = mpsc::channel(10);
|
|
|
|
tokio::task::spawn(Self::start_write_actor(tcp_write, engine_req_rx));
|
2023-08-28 14:58:24 -07:00
|
|
|
|
|
|
|
let mut tcp_read = TcpRead { stream: tcp_read };
|
|
|
|
|
2024-08-23 17:40:30 -05:00
|
|
|
let session_data: Arc<Mutex<Option<ModelingSessionData>>> = Arc::new(Mutex::new(None));
|
|
|
|
let session_data2 = session_data.clone();
|
2023-09-15 20:45:28 -07:00
|
|
|
let responses: Arc<DashMap<uuid::Uuid, WebSocketResponse>> = Arc::new(DashMap::new());
|
|
|
|
let responses_clone = responses.clone();
|
2024-03-01 14:43:11 -05:00
|
|
|
let socket_health = Arc::new(Mutex::new(SocketHealth::Active));
|
2024-10-03 01:05:12 -04:00
|
|
|
let pending_errors = Arc::new(Mutex::new(Vec::new()));
|
|
|
|
let pending_errors_clone = pending_errors.clone();
|
2023-08-29 19:13:30 -07:00
|
|
|
|
2024-03-01 14:43:11 -05:00
|
|
|
let socket_health_tcp_read = socket_health.clone();
|
2023-08-28 14:58:24 -07:00
|
|
|
let tcp_read_handle = tokio::spawn(async move {
|
|
|
|
// Get Websocket messages from API server
|
|
|
|
loop {
|
|
|
|
match tcp_read.read().await {
|
|
|
|
Ok(ws_resp) => {
|
2024-06-19 13:57:50 -07:00
|
|
|
// If we got a batch response, add all the inner responses.
|
2024-09-18 17:04:04 -05:00
|
|
|
let id = ws_resp.request_id();
|
|
|
|
match &ws_resp {
|
|
|
|
WebSocketResponse::Success(SuccessWebSocketResponse {
|
|
|
|
resp: OkWebSocketResponseData::ModelingBatch { responses },
|
|
|
|
..
|
|
|
|
}) => {
|
2024-08-23 17:40:30 -05:00
|
|
|
for (resp_id, batch_response) in responses {
|
2024-09-18 17:04:04 -05:00
|
|
|
let id: uuid::Uuid = (*resp_id).into();
|
|
|
|
match batch_response {
|
|
|
|
BatchResponse::Success { response } => {
|
|
|
|
responses_clone.insert(
|
|
|
|
id,
|
|
|
|
WebSocketResponse::Success(SuccessWebSocketResponse {
|
|
|
|
success: true,
|
|
|
|
request_id: Some(id),
|
|
|
|
resp: OkWebSocketResponseData::Modeling {
|
|
|
|
modeling_response: response.clone(),
|
|
|
|
},
|
|
|
|
}),
|
|
|
|
);
|
|
|
|
}
|
|
|
|
BatchResponse::Failure { errors } => {
|
|
|
|
responses_clone.insert(
|
|
|
|
id,
|
|
|
|
WebSocketResponse::Failure(FailureWebSocketResponse {
|
|
|
|
success: false,
|
|
|
|
request_id: Some(id),
|
|
|
|
errors: errors.clone(),
|
2024-08-23 17:40:30 -05:00
|
|
|
}),
|
2024-09-18 17:04:04 -05:00
|
|
|
);
|
|
|
|
}
|
2024-08-23 17:40:30 -05:00
|
|
|
}
|
2024-06-19 13:57:50 -07:00
|
|
|
}
|
|
|
|
}
|
2024-09-18 17:04:04 -05:00
|
|
|
WebSocketResponse::Success(SuccessWebSocketResponse {
|
|
|
|
resp: OkWebSocketResponseData::ModelingSessionData { session },
|
|
|
|
..
|
|
|
|
}) => {
|
2024-08-23 17:40:30 -05:00
|
|
|
let mut sd = session_data2.lock().unwrap();
|
|
|
|
sd.replace(session.clone());
|
|
|
|
}
|
2024-10-03 01:05:12 -04:00
|
|
|
WebSocketResponse::Failure(FailureWebSocketResponse {
|
|
|
|
success: _,
|
|
|
|
request_id,
|
|
|
|
errors,
|
|
|
|
}) => {
|
|
|
|
if let Some(id) = request_id {
|
|
|
|
responses_clone.insert(
|
|
|
|
*id,
|
|
|
|
WebSocketResponse::Failure(FailureWebSocketResponse {
|
|
|
|
success: false,
|
|
|
|
request_id: *request_id,
|
|
|
|
errors: errors.clone(),
|
|
|
|
}),
|
|
|
|
);
|
|
|
|
} else {
|
|
|
|
// Add it to our pending errors.
|
|
|
|
let mut pe = pending_errors_clone.lock().unwrap();
|
|
|
|
for error in errors {
|
|
|
|
if !pe.contains(&error.message) {
|
|
|
|
pe.push(error.message.clone());
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2024-08-23 17:40:30 -05:00
|
|
|
_ => {}
|
2024-06-19 13:57:50 -07:00
|
|
|
}
|
|
|
|
|
2024-09-18 17:04:04 -05:00
|
|
|
if let Some(id) = id {
|
2023-09-15 20:45:28 -07:00
|
|
|
responses_clone.insert(id, ws_resp.clone());
|
2023-08-28 14:58:24 -07:00
|
|
|
}
|
|
|
|
}
|
|
|
|
Err(e) => {
|
2024-06-18 14:38:25 -05:00
|
|
|
match &e {
|
|
|
|
WebSocketReadError::Read(e) => eprintln!("could not read from WS: {:?}", e),
|
|
|
|
WebSocketReadError::Deser(e) => eprintln!("could not deserialize msg from WS: {:?}", e),
|
|
|
|
}
|
2024-03-01 14:43:11 -05:00
|
|
|
*socket_health_tcp_read.lock().unwrap() = SocketHealth::Inactive;
|
2023-09-17 21:57:43 -07:00
|
|
|
return Err(e);
|
2023-08-28 14:58:24 -07:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
Ok(EngineConnection {
|
2023-09-20 16:59:03 -05:00
|
|
|
engine_req_tx,
|
2023-09-20 18:27:08 -07:00
|
|
|
tcp_read_handle: Arc::new(TcpReadHandle {
|
|
|
|
handle: Arc::new(tcp_read_handle),
|
|
|
|
}),
|
2023-09-15 20:45:28 -07:00
|
|
|
responses,
|
2024-10-03 01:05:12 -04:00
|
|
|
pending_errors,
|
2024-03-01 14:43:11 -05:00
|
|
|
socket_health,
|
2024-03-23 15:45:55 -07:00
|
|
|
batch: Arc::new(Mutex::new(Vec::new())),
|
2024-09-19 14:06:29 -07:00
|
|
|
batch_end: Arc::new(Mutex::new(IndexMap::new())),
|
2024-04-15 17:18:32 -07:00
|
|
|
default_planes: Default::default(),
|
2024-08-23 17:40:30 -05:00
|
|
|
session_data,
|
2023-08-28 14:58:24 -07:00
|
|
|
})
|
|
|
|
}
|
2023-09-17 21:57:43 -07:00
|
|
|
}
|
2023-08-28 14:58:24 -07:00
|
|
|
|
2024-03-12 13:37:47 -07:00
|
|
|
#[async_trait::async_trait]
|
2023-09-17 21:57:43 -07:00
|
|
|
impl EngineManager for EngineConnection {
|
2024-03-23 15:45:55 -07:00
|
|
|
fn batch(&self) -> Arc<Mutex<Vec<(WebSocketRequest, crate::executor::SourceRange)>>> {
|
|
|
|
self.batch.clone()
|
|
|
|
}
|
|
|
|
|
2024-09-19 14:06:29 -07:00
|
|
|
fn batch_end(&self) -> Arc<Mutex<IndexMap<uuid::Uuid, (WebSocketRequest, crate::executor::SourceRange)>>> {
|
2024-06-22 14:31:37 -07:00
|
|
|
self.batch_end.clone()
|
|
|
|
}
|
|
|
|
|
2024-10-09 19:38:40 -04:00
|
|
|
async fn default_planes(
|
|
|
|
&self,
|
|
|
|
id_generator: &mut IdGenerator,
|
|
|
|
source_range: crate::executor::SourceRange,
|
|
|
|
) -> Result<DefaultPlanes, KclError> {
|
2024-04-15 17:18:32 -07:00
|
|
|
{
|
|
|
|
let opt = self.default_planes.read().await.as_ref().cloned();
|
|
|
|
if let Some(planes) = opt {
|
|
|
|
return Ok(planes);
|
|
|
|
}
|
|
|
|
} // drop the read lock
|
|
|
|
|
2024-10-09 19:38:40 -04:00
|
|
|
let new_planes = self.new_default_planes(id_generator, source_range).await?;
|
2024-04-15 17:18:32 -07:00
|
|
|
*self.default_planes.write().await = Some(new_planes.clone());
|
|
|
|
|
|
|
|
Ok(new_planes)
|
|
|
|
}
|
|
|
|
|
2024-10-09 19:38:40 -04:00
|
|
|
async fn clear_scene_post_hook(
|
|
|
|
&self,
|
|
|
|
id_generator: &mut IdGenerator,
|
|
|
|
source_range: crate::executor::SourceRange,
|
|
|
|
) -> Result<(), KclError> {
|
2024-04-15 17:18:32 -07:00
|
|
|
// Remake the default planes, since they would have been removed after the scene was cleared.
|
2024-10-09 19:38:40 -04:00
|
|
|
let new_planes = self.new_default_planes(id_generator, source_range).await?;
|
2024-04-15 17:18:32 -07:00
|
|
|
*self.default_planes.write().await = Some(new_planes);
|
|
|
|
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
2024-03-23 15:45:55 -07:00
|
|
|
async fn inner_send_modeling_cmd(
|
2023-09-20 16:59:03 -05:00
|
|
|
&self,
|
2023-09-15 20:45:28 -07:00
|
|
|
id: uuid::Uuid,
|
|
|
|
source_range: crate::executor::SourceRange,
|
2024-09-18 17:04:04 -05:00
|
|
|
cmd: WebSocketRequest,
|
2024-03-23 15:45:55 -07:00
|
|
|
_id_to_source_range: std::collections::HashMap<uuid::Uuid, crate::executor::SourceRange>,
|
2024-06-19 13:57:50 -07:00
|
|
|
) -> Result<WebSocketResponse, KclError> {
|
2023-09-20 16:59:03 -05:00
|
|
|
let (tx, rx) = oneshot::channel();
|
|
|
|
|
|
|
|
// Send the request to the engine, via the actor.
|
|
|
|
self.engine_req_tx
|
|
|
|
.send(ToEngineReq {
|
2024-03-23 15:45:55 -07:00
|
|
|
req: cmd.clone(),
|
2023-09-20 16:59:03 -05:00
|
|
|
request_sent: tx,
|
|
|
|
})
|
2023-09-17 21:57:43 -07:00
|
|
|
.await
|
|
|
|
.map_err(|e| {
|
|
|
|
KclError::Engine(KclErrorDetails {
|
|
|
|
message: format!("Failed to send modeling command: {}", e),
|
|
|
|
source_ranges: vec![source_range],
|
|
|
|
})
|
|
|
|
})?;
|
2023-09-15 20:45:28 -07:00
|
|
|
|
2023-09-20 16:59:03 -05:00
|
|
|
// Wait for the request to be sent.
|
|
|
|
rx.await
|
|
|
|
.map_err(|e| {
|
|
|
|
KclError::Engine(KclErrorDetails {
|
|
|
|
message: format!("could not send request to the engine actor: {e}"),
|
|
|
|
source_ranges: vec![source_range],
|
|
|
|
})
|
|
|
|
})?
|
|
|
|
.map_err(|e| {
|
|
|
|
KclError::Engine(KclErrorDetails {
|
|
|
|
message: format!("could not send request to the engine: {e}"),
|
|
|
|
source_ranges: vec![source_range],
|
|
|
|
})
|
|
|
|
})?;
|
|
|
|
|
2023-09-15 20:45:28 -07:00
|
|
|
// Wait for the response.
|
2023-09-20 18:27:08 -07:00
|
|
|
let current_time = std::time::Instant::now();
|
|
|
|
while current_time.elapsed().as_secs() < 60 {
|
2024-03-01 14:43:11 -05:00
|
|
|
if let Ok(guard) = self.socket_health.lock() {
|
|
|
|
if *guard == SocketHealth::Inactive {
|
2024-10-03 01:05:12 -04:00
|
|
|
// Check if we have any pending errors.
|
|
|
|
let pe = self.pending_errors.lock().unwrap();
|
|
|
|
if !pe.is_empty() {
|
|
|
|
return Err(KclError::Engine(KclErrorDetails {
|
|
|
|
message: pe.join(", ").to_string(),
|
|
|
|
source_ranges: vec![source_range],
|
|
|
|
}));
|
|
|
|
} else {
|
|
|
|
return Err(KclError::Engine(KclErrorDetails {
|
|
|
|
message: "Modeling command failed: websocket closed early".to_string(),
|
|
|
|
source_ranges: vec![source_range],
|
|
|
|
}));
|
|
|
|
}
|
2024-03-01 14:43:11 -05:00
|
|
|
}
|
|
|
|
}
|
2023-09-20 18:27:08 -07:00
|
|
|
// We pop off the responses to cleanup our mappings.
|
|
|
|
if let Some((_, resp)) = self.responses.remove(&id) {
|
2024-06-19 13:57:50 -07:00
|
|
|
return Ok(resp);
|
2023-09-15 20:45:28 -07:00
|
|
|
}
|
|
|
|
}
|
2023-09-20 18:27:08 -07:00
|
|
|
|
|
|
|
Err(KclError::Engine(KclErrorDetails {
|
2023-11-27 15:43:26 -08:00
|
|
|
message: format!("Modeling command timed out `{}`", id),
|
2023-09-20 18:27:08 -07:00
|
|
|
source_ranges: vec![source_range],
|
|
|
|
}))
|
2023-09-15 20:45:28 -07:00
|
|
|
}
|
2024-08-23 17:40:30 -05:00
|
|
|
|
|
|
|
fn get_session_data(&self) -> Option<ModelingSessionData> {
|
|
|
|
self.session_data.lock().unwrap().clone()
|
|
|
|
}
|
2023-08-28 14:58:24 -07:00
|
|
|
}
|