2023-08-28 14:58:24 -07:00
|
|
|
|
//! Functions for setting up our WebSocket and WebRTC connections for communications with the
|
|
|
|
|
//! engine.
|
|
|
|
|
|
2025-02-18 13:50:13 -08:00
|
|
|
|
use std::{collections::HashMap, sync::Arc};
|
2023-08-28 14:58:24 -07:00
|
|
|
|
|
2023-09-20 16:59:03 -05:00
|
|
|
|
use anyhow::{anyhow, Result};
|
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
|
|
|
|
};
|
2025-02-19 00:11:11 -05:00
|
|
|
|
use kittycad_modeling_cmds::{self 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;
|
2025-01-08 20:02:30 -05:00
|
|
|
|
use uuid::Uuid;
|
2023-08-28 14:58:24 -07:00
|
|
|
|
|
2025-04-26 21:21:26 -07:00
|
|
|
|
#[cfg(feature = "artifact-graph")]
|
|
|
|
|
use crate::execution::ArtifactCommand;
|
2023-09-17 21:57:43 -07:00
|
|
|
|
use crate::{
|
2025-04-26 21:21:26 -07:00
|
|
|
|
engine::{AsyncTasks, EngineManager, EngineStats},
|
2023-09-17 21:57:43 -07:00
|
|
|
|
errors::{KclError, KclErrorDetails},
|
2025-04-26 21:21:26 -07:00
|
|
|
|
execution::{DefaultPlanes, IdGenerator},
|
2024-12-03 16:39:51 +13:00
|
|
|
|
SourceRange,
|
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>;
|
2025-01-10 20:05:27 -05:00
|
|
|
|
#[derive(Debug)]
|
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>,
|
2025-01-10 20:05:27 -05:00
|
|
|
|
shutdown_tx: mpsc::Sender<()>,
|
2025-04-26 21:21:26 -07:00
|
|
|
|
responses: ResponseInformation,
|
2025-02-18 13:50:13 -08:00
|
|
|
|
pending_errors: Arc<RwLock<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>,
|
2025-02-18 13:50:13 -08:00
|
|
|
|
socket_health: Arc<RwLock<SocketHealth>>,
|
|
|
|
|
batch: Arc<RwLock<Vec<(WebSocketRequest, SourceRange)>>>,
|
|
|
|
|
batch_end: Arc<RwLock<IndexMap<uuid::Uuid, (WebSocketRequest, SourceRange)>>>,
|
2025-04-26 21:21:26 -07:00
|
|
|
|
#[cfg(feature = "artifact-graph")]
|
2025-02-18 13:50:13 -08:00
|
|
|
|
artifact_commands: Arc<RwLock<Vec<ArtifactCommand>>>,
|
2025-04-17 17:22:19 -07:00
|
|
|
|
ids_of_async_commands: Arc<RwLock<IndexMap<Uuid, 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.
|
2025-02-18 13:50:13 -08:00
|
|
|
|
session_data: Arc<RwLock<Option<ModelingSessionData>>>,
|
2024-10-17 00:48:33 -04:00
|
|
|
|
|
2025-03-18 16:19:24 +13:00
|
|
|
|
stats: EngineStats,
|
2025-04-26 21:21:26 -07:00
|
|
|
|
|
|
|
|
|
async_tasks: AsyncTasks,
|
2025-05-07 12:10:40 -04:00
|
|
|
|
|
|
|
|
|
debug_info: Arc<RwLock<Option<OkWebSocketResponseData>>>,
|
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();
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2025-04-26 21:21:26 -07:00
|
|
|
|
/// Information about the responses from the engine.
|
|
|
|
|
#[derive(Clone, Debug)]
|
|
|
|
|
struct ResponseInformation {
|
2025-04-17 17:22:19 -07:00
|
|
|
|
/// The responses from the engine.
|
|
|
|
|
responses: Arc<RwLock<IndexMap<uuid::Uuid, WebSocketResponse>>>,
|
|
|
|
|
}
|
|
|
|
|
|
2025-04-26 21:21:26 -07:00
|
|
|
|
impl ResponseInformation {
|
2025-04-17 17:22:19 -07:00
|
|
|
|
pub async fn add(&self, id: Uuid, response: WebSocketResponse) {
|
|
|
|
|
self.responses.write().await.insert(id, response);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
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.
|
2025-01-10 20:05:27 -05:00
|
|
|
|
async fn start_write_actor(
|
|
|
|
|
mut tcp_write: WebSocketTcpWrite,
|
|
|
|
|
mut engine_req_rx: mpsc::Receiver<ToEngineReq>,
|
|
|
|
|
mut shutdown_rx: mpsc::Receiver<()>,
|
|
|
|
|
) {
|
|
|
|
|
loop {
|
|
|
|
|
tokio::select! {
|
|
|
|
|
maybe_req = engine_req_rx.recv() => {
|
|
|
|
|
match maybe_req {
|
|
|
|
|
Some(ToEngineReq { req, request_sent }) => {
|
|
|
|
|
// Decide whether to send as binary or text,
|
|
|
|
|
// then send to the engine.
|
|
|
|
|
let res = if let WebSocketRequest::ModelingCmdReq(ModelingCmdReq {
|
|
|
|
|
cmd: ModelingCmd::ImportFiles { .. },
|
|
|
|
|
cmd_id: _,
|
|
|
|
|
}) = &req
|
|
|
|
|
{
|
|
|
|
|
Self::inner_send_to_engine_binary(req, &mut tcp_write).await
|
|
|
|
|
} else {
|
|
|
|
|
Self::inner_send_to_engine(req, &mut tcp_write).await
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
// Let the caller know we’ve sent the request (ok or error).
|
|
|
|
|
let _ = request_sent.send(res);
|
|
|
|
|
}
|
|
|
|
|
None => {
|
|
|
|
|
// The engine_req_rx channel has closed, so no more requests.
|
|
|
|
|
// We'll gracefully exit the loop and close the engine.
|
|
|
|
|
break;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
},
|
|
|
|
|
|
|
|
|
|
// If we get a shutdown signal, close the engine immediately and return.
|
|
|
|
|
_ = shutdown_rx.recv() => {
|
|
|
|
|
let _ = Self::inner_close_engine(&mut tcp_write).await;
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
}
|
2023-09-20 16:59:03 -05:00
|
|
|
|
}
|
2025-01-10 20:05:27 -05:00
|
|
|
|
|
|
|
|
|
// If we exit the loop (e.g. engine_req_rx was closed),
|
|
|
|
|
// still gracefully close the engine before returning.
|
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.
|
2025-03-04 22:21:12 -08:00
|
|
|
|
max_message_size: Some(usize::MAX),
|
|
|
|
|
max_frame_size: Some(usize::MAX),
|
2024-07-18 15:20:50 -04:00
|
|
|
|
..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);
|
2025-01-10 20:05:27 -05:00
|
|
|
|
let (shutdown_tx, shutdown_rx) = mpsc::channel(1);
|
|
|
|
|
tokio::task::spawn(Self::start_write_actor(tcp_write, engine_req_rx, shutdown_rx));
|
2023-08-28 14:58:24 -07:00
|
|
|
|
|
|
|
|
|
let mut tcp_read = TcpRead { stream: tcp_read };
|
|
|
|
|
|
2025-02-18 13:50:13 -08:00
|
|
|
|
let session_data: Arc<RwLock<Option<ModelingSessionData>>> = Arc::new(RwLock::new(None));
|
2024-08-23 17:40:30 -05:00
|
|
|
|
let session_data2 = session_data.clone();
|
2025-04-17 17:22:19 -07:00
|
|
|
|
let ids_of_async_commands: Arc<RwLock<IndexMap<Uuid, SourceRange>>> = Arc::new(RwLock::new(IndexMap::new()));
|
2025-02-18 13:50:13 -08:00
|
|
|
|
let socket_health = Arc::new(RwLock::new(SocketHealth::Active));
|
|
|
|
|
let pending_errors = Arc::new(RwLock::new(Vec::new()));
|
2024-10-03 01:05:12 -04:00
|
|
|
|
let pending_errors_clone = pending_errors.clone();
|
2025-04-26 21:21:26 -07:00
|
|
|
|
let response_information = ResponseInformation {
|
|
|
|
|
responses: Arc::new(RwLock::new(IndexMap::new())),
|
2025-04-17 17:22:19 -07:00
|
|
|
|
};
|
2025-04-26 21:21:26 -07:00
|
|
|
|
let response_information_cloned = response_information.clone();
|
2025-05-07 12:10:40 -04:00
|
|
|
|
let debug_info = Arc::new(RwLock::new(None));
|
|
|
|
|
let debug_info_cloned = debug_info.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 },
|
|
|
|
|
..
|
2025-04-17 17:22:19 -07:00
|
|
|
|
}) => {
|
2024-12-05 12:09:35 -05:00
|
|
|
|
#[expect(
|
|
|
|
|
clippy::iter_over_hash_type,
|
|
|
|
|
reason = "modeling command uses a HashMap and keys are random, so we don't really have a choice"
|
|
|
|
|
)]
|
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 } => {
|
2025-04-17 17:22:19 -07:00
|
|
|
|
// If the id is in our ids of async commands, remove
|
|
|
|
|
// it.
|
2025-04-26 21:21:26 -07:00
|
|
|
|
response_information_cloned
|
2025-04-17 17:22:19 -07:00
|
|
|
|
.add(
|
|
|
|
|
id,
|
|
|
|
|
WebSocketResponse::Success(SuccessWebSocketResponse {
|
|
|
|
|
success: true,
|
|
|
|
|
request_id: Some(id),
|
|
|
|
|
resp: OkWebSocketResponseData::Modeling {
|
|
|
|
|
modeling_response: response.clone(),
|
|
|
|
|
},
|
|
|
|
|
}),
|
|
|
|
|
)
|
|
|
|
|
.await;
|
2024-09-18 17:04:04 -05:00
|
|
|
|
}
|
|
|
|
|
BatchResponse::Failure { errors } => {
|
2025-04-26 21:21:26 -07:00
|
|
|
|
response_information_cloned
|
2025-04-17 17:22:19 -07:00
|
|
|
|
.add(
|
|
|
|
|
id,
|
|
|
|
|
WebSocketResponse::Failure(FailureWebSocketResponse {
|
|
|
|
|
success: false,
|
|
|
|
|
request_id: Some(id),
|
|
|
|
|
errors: errors.clone(),
|
|
|
|
|
}),
|
|
|
|
|
)
|
|
|
|
|
.await;
|
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 },
|
|
|
|
|
..
|
|
|
|
|
}) => {
|
2025-02-18 13:50:13 -08:00
|
|
|
|
let mut sd = session_data2.write().await;
|
2024-08-23 17:40:30 -05:00
|
|
|
|
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 {
|
2025-04-26 21:21:26 -07:00
|
|
|
|
response_information_cloned
|
2025-04-17 17:22:19 -07:00
|
|
|
|
.add(
|
|
|
|
|
*id,
|
|
|
|
|
WebSocketResponse::Failure(FailureWebSocketResponse {
|
|
|
|
|
success: false,
|
|
|
|
|
request_id: *request_id,
|
|
|
|
|
errors: errors.clone(),
|
|
|
|
|
}),
|
|
|
|
|
)
|
|
|
|
|
.await;
|
2024-10-03 01:05:12 -04:00
|
|
|
|
} else {
|
|
|
|
|
// Add it to our pending errors.
|
2025-02-18 13:50:13 -08:00
|
|
|
|
let mut pe = pending_errors_clone.write().await;
|
2024-10-03 01:05:12 -04:00
|
|
|
|
for error in errors {
|
|
|
|
|
if !pe.contains(&error.message) {
|
|
|
|
|
pe.push(error.message.clone());
|
|
|
|
|
}
|
|
|
|
|
}
|
2025-02-18 13:50:13 -08:00
|
|
|
|
drop(pe);
|
2024-10-03 01:05:12 -04:00
|
|
|
|
}
|
|
|
|
|
}
|
2025-05-07 12:10:40 -04:00
|
|
|
|
WebSocketResponse::Success(SuccessWebSocketResponse {
|
|
|
|
|
resp: debug @ OkWebSocketResponseData::Debug { .. },
|
|
|
|
|
..
|
|
|
|
|
}) => {
|
|
|
|
|
let mut handle = debug_info_cloned.write().await;
|
|
|
|
|
*handle = Some(debug.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 {
|
2025-04-26 21:21:26 -07:00
|
|
|
|
response_information_cloned.add(id, ws_resp.clone()).await;
|
2023-08-28 14:58:24 -07:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
Err(e) => {
|
2024-06-18 14:38:25 -05:00
|
|
|
|
match &e {
|
2024-11-28 11:27:17 +13:00
|
|
|
|
WebSocketReadError::Read(e) => crate::logln!("could not read from WS: {:?}", e),
|
|
|
|
|
WebSocketReadError::Deser(e) => crate::logln!("could not deserialize msg from WS: {:?}", e),
|
2024-06-18 14:38:25 -05:00
|
|
|
|
}
|
2025-02-18 13:50:13 -08:00
|
|
|
|
*socket_health_tcp_read.write().await = 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,
|
2025-01-10 20:05:27 -05:00
|
|
|
|
shutdown_tx,
|
2023-09-20 18:27:08 -07:00
|
|
|
|
tcp_read_handle: Arc::new(TcpReadHandle {
|
|
|
|
|
handle: Arc::new(tcp_read_handle),
|
|
|
|
|
}),
|
2025-04-26 21:21:26 -07:00
|
|
|
|
responses: response_information,
|
2024-10-03 01:05:12 -04:00
|
|
|
|
pending_errors,
|
2024-03-01 14:43:11 -05:00
|
|
|
|
socket_health,
|
2025-02-18 13:50:13 -08:00
|
|
|
|
batch: Arc::new(RwLock::new(Vec::new())),
|
|
|
|
|
batch_end: Arc::new(RwLock::new(IndexMap::new())),
|
2025-04-26 21:21:26 -07:00
|
|
|
|
#[cfg(feature = "artifact-graph")]
|
2025-02-18 13:50:13 -08:00
|
|
|
|
artifact_commands: Arc::new(RwLock::new(Vec::new())),
|
2025-04-17 17:22:19 -07:00
|
|
|
|
ids_of_async_commands,
|
2024-04-15 17:18:32 -07:00
|
|
|
|
default_planes: Default::default(),
|
2024-08-23 17:40:30 -05:00
|
|
|
|
session_data,
|
2025-03-18 16:19:24 +13:00
|
|
|
|
stats: Default::default(),
|
2025-04-26 21:21:26 -07:00
|
|
|
|
async_tasks: AsyncTasks::new(),
|
2025-05-07 12:10:40 -04:00
|
|
|
|
debug_info,
|
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 {
|
2025-02-18 13:50:13 -08:00
|
|
|
|
fn batch(&self) -> Arc<RwLock<Vec<(WebSocketRequest, SourceRange)>>> {
|
2024-03-23 15:45:55 -07:00
|
|
|
|
self.batch.clone()
|
|
|
|
|
}
|
|
|
|
|
|
2025-02-18 13:50:13 -08:00
|
|
|
|
fn batch_end(&self) -> Arc<RwLock<IndexMap<uuid::Uuid, (WebSocketRequest, SourceRange)>>> {
|
2024-06-22 14:31:37 -07:00
|
|
|
|
self.batch_end.clone()
|
|
|
|
|
}
|
|
|
|
|
|
2025-02-18 13:50:13 -08:00
|
|
|
|
fn responses(&self) -> Arc<RwLock<IndexMap<Uuid, WebSocketResponse>>> {
|
2025-04-26 21:21:26 -07:00
|
|
|
|
self.responses.responses.clone()
|
2025-01-17 14:34:36 -05:00
|
|
|
|
}
|
|
|
|
|
|
2025-04-26 21:21:26 -07:00
|
|
|
|
#[cfg(feature = "artifact-graph")]
|
2025-02-18 13:50:13 -08:00
|
|
|
|
fn artifact_commands(&self) -> Arc<RwLock<Vec<ArtifactCommand>>> {
|
|
|
|
|
self.artifact_commands.clone()
|
2025-01-08 20:02:30 -05:00
|
|
|
|
}
|
|
|
|
|
|
2025-04-17 17:22:19 -07:00
|
|
|
|
fn ids_of_async_commands(&self) -> Arc<RwLock<IndexMap<Uuid, SourceRange>>> {
|
|
|
|
|
self.ids_of_async_commands.clone()
|
|
|
|
|
}
|
|
|
|
|
|
2025-04-26 21:21:26 -07:00
|
|
|
|
fn async_tasks(&self) -> AsyncTasks {
|
|
|
|
|
self.async_tasks.clone()
|
|
|
|
|
}
|
|
|
|
|
|
2025-03-18 16:19:24 +13:00
|
|
|
|
fn stats(&self) -> &EngineStats {
|
|
|
|
|
&self.stats
|
|
|
|
|
}
|
|
|
|
|
|
2025-03-15 10:08:39 -07:00
|
|
|
|
fn get_default_planes(&self) -> Arc<RwLock<Option<DefaultPlanes>>> {
|
|
|
|
|
self.default_planes.clone()
|
2024-04-15 17:18:32 -07:00
|
|
|
|
}
|
|
|
|
|
|
2025-05-07 12:10:40 -04:00
|
|
|
|
async fn get_debug(&self) -> Option<OkWebSocketResponseData> {
|
|
|
|
|
self.debug_info.read().await.clone()
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async fn fetch_debug(&self) -> Result<(), KclError> {
|
|
|
|
|
let (tx, rx) = oneshot::channel();
|
|
|
|
|
|
|
|
|
|
self.engine_req_tx
|
|
|
|
|
.send(ToEngineReq {
|
|
|
|
|
req: WebSocketRequest::Debug {},
|
|
|
|
|
request_sent: tx,
|
|
|
|
|
})
|
|
|
|
|
.await
|
2025-05-19 14:13:10 -04:00
|
|
|
|
.map_err(|e| KclError::Engine(KclErrorDetails::new(format!("Failed to send debug: {}", e), vec![])))?;
|
2025-05-07 12:10:40 -04:00
|
|
|
|
|
|
|
|
|
let _ = rx.await;
|
|
|
|
|
Ok(())
|
|
|
|
|
}
|
|
|
|
|
|
2024-10-09 19:38:40 -04:00
|
|
|
|
async fn clear_scene_post_hook(
|
|
|
|
|
&self,
|
|
|
|
|
id_generator: &mut IdGenerator,
|
2024-12-03 16:39:51 +13:00
|
|
|
|
source_range: SourceRange,
|
2024-10-09 19:38:40 -04:00
|
|
|
|
) -> 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(())
|
|
|
|
|
}
|
|
|
|
|
|
2025-04-17 17:22:19 -07:00
|
|
|
|
async fn inner_fire_modeling_cmd(
|
2023-09-20 16:59:03 -05:00
|
|
|
|
&self,
|
2025-04-17 17:22:19 -07:00
|
|
|
|
_id: uuid::Uuid,
|
2024-12-03 16:39:51 +13:00
|
|
|
|
source_range: SourceRange,
|
2024-09-18 17:04:04 -05:00
|
|
|
|
cmd: WebSocketRequest,
|
2025-02-18 13:50:13 -08:00
|
|
|
|
_id_to_source_range: HashMap<Uuid, SourceRange>,
|
2025-04-17 17:22:19 -07:00
|
|
|
|
) -> Result<(), 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| {
|
2025-05-19 14:13:10 -04:00
|
|
|
|
KclError::Engine(KclErrorDetails::new(
|
|
|
|
|
format!("Failed to send modeling command: {}", e),
|
|
|
|
|
vec![source_range],
|
|
|
|
|
))
|
2023-09-17 21:57:43 -07:00
|
|
|
|
})?;
|
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| {
|
2025-05-19 14:13:10 -04:00
|
|
|
|
KclError::Engine(KclErrorDetails::new(
|
|
|
|
|
format!("could not send request to the engine actor: {e}"),
|
|
|
|
|
vec![source_range],
|
|
|
|
|
))
|
2023-09-20 16:59:03 -05:00
|
|
|
|
})?
|
|
|
|
|
.map_err(|e| {
|
2025-05-19 14:13:10 -04:00
|
|
|
|
KclError::Engine(KclErrorDetails::new(
|
|
|
|
|
format!("could not send request to the engine: {e}"),
|
|
|
|
|
vec![source_range],
|
|
|
|
|
))
|
2023-09-20 16:59:03 -05:00
|
|
|
|
})?;
|
|
|
|
|
|
2025-04-17 17:22:19 -07:00
|
|
|
|
Ok(())
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async fn inner_send_modeling_cmd(
|
|
|
|
|
&self,
|
|
|
|
|
id: uuid::Uuid,
|
|
|
|
|
source_range: SourceRange,
|
|
|
|
|
cmd: WebSocketRequest,
|
|
|
|
|
id_to_source_range: HashMap<Uuid, SourceRange>,
|
|
|
|
|
) -> Result<WebSocketResponse, KclError> {
|
|
|
|
|
self.inner_fire_modeling_cmd(id, source_range, cmd, id_to_source_range)
|
|
|
|
|
.await?;
|
|
|
|
|
|
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 {
|
2025-02-18 13:50:13 -08:00
|
|
|
|
let guard = self.socket_health.read().await;
|
|
|
|
|
if *guard == SocketHealth::Inactive {
|
|
|
|
|
// Check if we have any pending errors.
|
|
|
|
|
let pe = self.pending_errors.read().await;
|
|
|
|
|
if !pe.is_empty() {
|
2025-05-19 14:13:10 -04:00
|
|
|
|
return Err(KclError::Engine(KclErrorDetails::new(
|
|
|
|
|
pe.join(", ").to_string(),
|
|
|
|
|
vec![source_range],
|
|
|
|
|
)));
|
2025-02-18 13:50:13 -08:00
|
|
|
|
} else {
|
2025-05-19 14:13:10 -04:00
|
|
|
|
return Err(KclError::Engine(KclErrorDetails::new(
|
|
|
|
|
"Modeling command failed: websocket closed early".to_string(),
|
|
|
|
|
vec![source_range],
|
|
|
|
|
)));
|
2024-03-01 14:43:11 -05:00
|
|
|
|
}
|
|
|
|
|
}
|
2025-04-26 21:21:26 -07:00
|
|
|
|
|
|
|
|
|
#[cfg(feature = "artifact-graph")]
|
|
|
|
|
{
|
|
|
|
|
// We cannot pop here or it will break the artifact graph.
|
|
|
|
|
if let Some(resp) = self.responses.responses.read().await.get(&id) {
|
|
|
|
|
return Ok(resp.clone());
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
#[cfg(not(feature = "artifact-graph"))]
|
|
|
|
|
{
|
|
|
|
|
if let Some(resp) = self.responses.responses.write().await.shift_remove(&id) {
|
|
|
|
|
return Ok(resp);
|
|
|
|
|
}
|
2023-09-15 20:45:28 -07:00
|
|
|
|
}
|
|
|
|
|
}
|
2023-09-20 18:27:08 -07:00
|
|
|
|
|
2025-05-19 14:13:10 -04:00
|
|
|
|
Err(KclError::Engine(KclErrorDetails::new(
|
|
|
|
|
format!("Modeling command timed out `{}`", id),
|
|
|
|
|
vec![source_range],
|
|
|
|
|
)))
|
2023-09-15 20:45:28 -07:00
|
|
|
|
}
|
2024-08-23 17:40:30 -05:00
|
|
|
|
|
2025-02-18 13:50:13 -08:00
|
|
|
|
async fn get_session_data(&self) -> Option<ModelingSessionData> {
|
|
|
|
|
self.session_data.read().await.clone()
|
2024-08-23 17:40:30 -05:00
|
|
|
|
}
|
2025-01-10 20:05:27 -05:00
|
|
|
|
|
|
|
|
|
async fn close(&self) {
|
|
|
|
|
let _ = self.shutdown_tx.send(()).await;
|
|
|
|
|
loop {
|
2025-02-18 13:50:13 -08:00
|
|
|
|
let guard = self.socket_health.read().await;
|
|
|
|
|
if *guard == SocketHealth::Inactive {
|
|
|
|
|
return;
|
2025-01-10 20:05:27 -05:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
2023-08-28 14:58:24 -07:00
|
|
|
|
}
|