Move the wasm lib, and cleanup rust directory and all references (#5585)
* git mv src/wasm-lib rust Signed-off-by: Jess Frazelle <github@jessfraz.com> * mv wasm-lib to workspace Signed-off-by: Jess Frazelle <github@jessfraz.com> * mv kcl-lib Signed-off-by: Jess Frazelle <github@jessfraz.com> * mv derive docs Signed-off-by: Jess Frazelle <github@jessfraz.com> * resolve file paths Signed-off-by: Jess Frazelle <github@jessfraz.com> * clippy Signed-off-by: Jess Frazelle <github@jessfraz.com> * move more shit Signed-off-by: Jess Frazelle <github@jessfraz.com> * fix more paths Signed-off-by: Jess Frazelle <github@jessfraz.com> * make yarn build:wasm work Signed-off-by: Jess Frazelle <github@jessfraz.com> * fix scripts Signed-off-by: Jess Frazelle <github@jessfraz.com> * fixups Signed-off-by: Jess Frazelle <github@jessfraz.com> * better references Signed-off-by: Jess Frazelle <github@jessfraz.com> * fix cargo ci Signed-off-by: Jess Frazelle <github@jessfraz.com> * fix reference Signed-off-by: Jess Frazelle <github@jessfraz.com> * fix more ci Signed-off-by: Jess Frazelle <github@jessfraz.com> * fix tests Signed-off-by: Jess Frazelle <github@jessfraz.com> * cargo sort Signed-off-by: Jess Frazelle <github@jessfraz.com> * fix script Signed-off-by: Jess Frazelle <github@jessfraz.com> * fix Signed-off-by: Jess Frazelle <github@jessfraz.com> * fmt Signed-off-by: Jess Frazelle <github@jessfraz.com> * fix a dep Signed-off-by: Jess Frazelle <github@jessfraz.com> * sort Signed-off-by: Jess Frazelle <github@jessfraz.com> * remove unused deps Signed-off-by: Jess Frazelle <github@jessfraz.com> * Revert "remove unused deps" This reverts commit fbabdb062e275fd5cbc1476f8480a1afee15d972. * updates Signed-off-by: Jess Frazelle <github@jessfraz.com> * deps; Signed-off-by: Jess Frazelle <github@jessfraz.com> * fixes Signed-off-by: Jess Frazelle <github@jessfraz.com> * updates Signed-off-by: Jess Frazelle <github@jessfraz.com> --------- Signed-off-by: Jess Frazelle <github@jessfraz.com>
This commit is contained in:
493
rust/kcl-lib/src/engine/conn.rs
Normal file
493
rust/kcl-lib/src/engine/conn.rs
Normal file
@ -0,0 +1,493 @@
|
||||
//! Functions for setting up our WebSocket and WebRTC connections for communications with the
|
||||
//! engine.
|
||||
|
||||
use std::{collections::HashMap, sync::Arc};
|
||||
|
||||
use anyhow::{anyhow, Result};
|
||||
use futures::{SinkExt, StreamExt};
|
||||
use indexmap::IndexMap;
|
||||
use kcmc::{
|
||||
websocket::{
|
||||
BatchResponse, FailureWebSocketResponse, ModelingCmdReq, ModelingSessionData, OkWebSocketResponseData,
|
||||
SuccessWebSocketResponse, WebSocketRequest, WebSocketResponse,
|
||||
},
|
||||
ModelingCmd,
|
||||
};
|
||||
use kittycad_modeling_cmds::{self as kcmc};
|
||||
use tokio::sync::{mpsc, oneshot, RwLock};
|
||||
use tokio_tungstenite::tungstenite::Message as WsMsg;
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::ExecutionKind;
|
||||
use crate::{
|
||||
engine::EngineManager,
|
||||
errors::{KclError, KclErrorDetails},
|
||||
execution::{ArtifactCommand, DefaultPlanes, IdGenerator},
|
||||
SourceRange,
|
||||
};
|
||||
|
||||
#[derive(Debug, PartialEq)]
|
||||
enum SocketHealth {
|
||||
Active,
|
||||
Inactive,
|
||||
}
|
||||
|
||||
type WebSocketTcpWrite = futures::stream::SplitSink<tokio_tungstenite::WebSocketStream<reqwest::Upgraded>, WsMsg>;
|
||||
#[derive(Debug)]
|
||||
pub struct EngineConnection {
|
||||
engine_req_tx: mpsc::Sender<ToEngineReq>,
|
||||
shutdown_tx: mpsc::Sender<()>,
|
||||
responses: Arc<RwLock<IndexMap<uuid::Uuid, WebSocketResponse>>>,
|
||||
pending_errors: Arc<RwLock<Vec<String>>>,
|
||||
#[allow(dead_code)]
|
||||
tcp_read_handle: Arc<TcpReadHandle>,
|
||||
socket_health: Arc<RwLock<SocketHealth>>,
|
||||
batch: Arc<RwLock<Vec<(WebSocketRequest, SourceRange)>>>,
|
||||
batch_end: Arc<RwLock<IndexMap<uuid::Uuid, (WebSocketRequest, SourceRange)>>>,
|
||||
artifact_commands: Arc<RwLock<Vec<ArtifactCommand>>>,
|
||||
|
||||
/// The default planes for the scene.
|
||||
default_planes: Arc<RwLock<Option<DefaultPlanes>>>,
|
||||
/// If the server sends session data, it'll be copied to here.
|
||||
session_data: Arc<RwLock<Option<ModelingSessionData>>>,
|
||||
|
||||
execution_kind: Arc<RwLock<ExecutionKind>>,
|
||||
}
|
||||
|
||||
pub struct TcpRead {
|
||||
stream: futures::stream::SplitStream<tokio_tungstenite::WebSocketStream<reqwest::Upgraded>>,
|
||||
}
|
||||
|
||||
/// 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)
|
||||
}
|
||||
}
|
||||
|
||||
impl TcpRead {
|
||||
pub async fn read(&mut self) -> std::result::Result<WebSocketResponse, WebSocketReadError> {
|
||||
let Some(msg) = self.stream.next().await else {
|
||||
return Err(anyhow::anyhow!("Failed to read from WebSocket").into());
|
||||
};
|
||||
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()),
|
||||
};
|
||||
Ok(msg)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct TcpReadHandle {
|
||||
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")
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TcpReadHandle {
|
||||
fn drop(&mut self) {
|
||||
// Drop the read handle.
|
||||
self.handle.abort();
|
||||
}
|
||||
}
|
||||
|
||||
/// 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<()>>,
|
||||
}
|
||||
|
||||
impl EngineConnection {
|
||||
/// 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>,
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// If we exit the loop (e.g. engine_req_rx was closed),
|
||||
// still gracefully close the engine before returning.
|
||||
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(())
|
||||
}
|
||||
|
||||
/// 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(())
|
||||
}
|
||||
|
||||
/// 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(())
|
||||
}
|
||||
|
||||
pub async fn new(ws: reqwest::Upgraded) -> Result<EngineConnection> {
|
||||
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()
|
||||
};
|
||||
|
||||
let ws_stream = tokio_tungstenite::WebSocketStream::from_raw_socket(
|
||||
ws,
|
||||
tokio_tungstenite::tungstenite::protocol::Role::Client,
|
||||
Some(wsconfig),
|
||||
)
|
||||
.await;
|
||||
|
||||
let (tcp_write, tcp_read) = ws_stream.split();
|
||||
let (engine_req_tx, engine_req_rx) = mpsc::channel(10);
|
||||
let (shutdown_tx, shutdown_rx) = mpsc::channel(1);
|
||||
tokio::task::spawn(Self::start_write_actor(tcp_write, engine_req_rx, shutdown_rx));
|
||||
|
||||
let mut tcp_read = TcpRead { stream: tcp_read };
|
||||
|
||||
let session_data: Arc<RwLock<Option<ModelingSessionData>>> = Arc::new(RwLock::new(None));
|
||||
let session_data2 = session_data.clone();
|
||||
let responses: Arc<RwLock<IndexMap<uuid::Uuid, WebSocketResponse>>> = Arc::new(RwLock::new(IndexMap::new()));
|
||||
let responses_clone = responses.clone();
|
||||
let socket_health = Arc::new(RwLock::new(SocketHealth::Active));
|
||||
let pending_errors = Arc::new(RwLock::new(Vec::new()));
|
||||
let pending_errors_clone = pending_errors.clone();
|
||||
|
||||
let socket_health_tcp_read = socket_health.clone();
|
||||
let tcp_read_handle = tokio::spawn(async move {
|
||||
// Get Websocket messages from API server
|
||||
loop {
|
||||
match tcp_read.read().await {
|
||||
Ok(ws_resp) => {
|
||||
// If we got a batch response, add all the inner responses.
|
||||
let id = ws_resp.request_id();
|
||||
match &ws_resp {
|
||||
WebSocketResponse::Success(SuccessWebSocketResponse {
|
||||
resp: OkWebSocketResponseData::ModelingBatch { responses },
|
||||
..
|
||||
}) =>
|
||||
{
|
||||
#[expect(
|
||||
clippy::iter_over_hash_type,
|
||||
reason = "modeling command uses a HashMap and keys are random, so we don't really have a choice"
|
||||
)]
|
||||
for (resp_id, batch_response) in responses {
|
||||
let id: uuid::Uuid = (*resp_id).into();
|
||||
match batch_response {
|
||||
BatchResponse::Success { response } => {
|
||||
responses_clone.write().await.insert(
|
||||
id,
|
||||
WebSocketResponse::Success(SuccessWebSocketResponse {
|
||||
success: true,
|
||||
request_id: Some(id),
|
||||
resp: OkWebSocketResponseData::Modeling {
|
||||
modeling_response: response.clone(),
|
||||
},
|
||||
}),
|
||||
);
|
||||
}
|
||||
BatchResponse::Failure { errors } => {
|
||||
responses_clone.write().await.insert(
|
||||
id,
|
||||
WebSocketResponse::Failure(FailureWebSocketResponse {
|
||||
success: false,
|
||||
request_id: Some(id),
|
||||
errors: errors.clone(),
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
WebSocketResponse::Success(SuccessWebSocketResponse {
|
||||
resp: OkWebSocketResponseData::ModelingSessionData { session },
|
||||
..
|
||||
}) => {
|
||||
let mut sd = session_data2.write().await;
|
||||
sd.replace(session.clone());
|
||||
}
|
||||
WebSocketResponse::Failure(FailureWebSocketResponse {
|
||||
success: _,
|
||||
request_id,
|
||||
errors,
|
||||
}) => {
|
||||
if let Some(id) = request_id {
|
||||
responses_clone.write().await.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.write().await;
|
||||
for error in errors {
|
||||
if !pe.contains(&error.message) {
|
||||
pe.push(error.message.clone());
|
||||
}
|
||||
}
|
||||
drop(pe);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
|
||||
if let Some(id) = id {
|
||||
responses_clone.write().await.insert(id, ws_resp.clone());
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
match &e {
|
||||
WebSocketReadError::Read(e) => crate::logln!("could not read from WS: {:?}", e),
|
||||
WebSocketReadError::Deser(e) => crate::logln!("could not deserialize msg from WS: {:?}", e),
|
||||
}
|
||||
*socket_health_tcp_read.write().await = SocketHealth::Inactive;
|
||||
return Err(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
Ok(EngineConnection {
|
||||
engine_req_tx,
|
||||
shutdown_tx,
|
||||
tcp_read_handle: Arc::new(TcpReadHandle {
|
||||
handle: Arc::new(tcp_read_handle),
|
||||
}),
|
||||
responses,
|
||||
pending_errors,
|
||||
socket_health,
|
||||
batch: Arc::new(RwLock::new(Vec::new())),
|
||||
batch_end: Arc::new(RwLock::new(IndexMap::new())),
|
||||
artifact_commands: Arc::new(RwLock::new(Vec::new())),
|
||||
default_planes: Default::default(),
|
||||
session_data,
|
||||
execution_kind: Default::default(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl EngineManager for EngineConnection {
|
||||
fn batch(&self) -> Arc<RwLock<Vec<(WebSocketRequest, SourceRange)>>> {
|
||||
self.batch.clone()
|
||||
}
|
||||
|
||||
fn batch_end(&self) -> Arc<RwLock<IndexMap<uuid::Uuid, (WebSocketRequest, SourceRange)>>> {
|
||||
self.batch_end.clone()
|
||||
}
|
||||
|
||||
fn responses(&self) -> Arc<RwLock<IndexMap<Uuid, WebSocketResponse>>> {
|
||||
self.responses.clone()
|
||||
}
|
||||
|
||||
fn artifact_commands(&self) -> Arc<RwLock<Vec<ArtifactCommand>>> {
|
||||
self.artifact_commands.clone()
|
||||
}
|
||||
|
||||
async fn execution_kind(&self) -> ExecutionKind {
|
||||
let guard = self.execution_kind.read().await;
|
||||
*guard
|
||||
}
|
||||
|
||||
async fn replace_execution_kind(&self, execution_kind: ExecutionKind) -> ExecutionKind {
|
||||
let mut guard = self.execution_kind.write().await;
|
||||
let original = *guard;
|
||||
*guard = execution_kind;
|
||||
original
|
||||
}
|
||||
|
||||
async fn default_planes(
|
||||
&self,
|
||||
id_generator: &mut IdGenerator,
|
||||
source_range: SourceRange,
|
||||
) -> Result<DefaultPlanes, KclError> {
|
||||
{
|
||||
let opt = self.default_planes.read().await.as_ref().cloned();
|
||||
if let Some(planes) = opt {
|
||||
return Ok(planes);
|
||||
}
|
||||
} // drop the read lock
|
||||
|
||||
let new_planes = self.new_default_planes(id_generator, source_range).await?;
|
||||
*self.default_planes.write().await = Some(new_planes.clone());
|
||||
|
||||
Ok(new_planes)
|
||||
}
|
||||
|
||||
async fn clear_scene_post_hook(
|
||||
&self,
|
||||
id_generator: &mut IdGenerator,
|
||||
source_range: SourceRange,
|
||||
) -> Result<(), KclError> {
|
||||
// Remake the default planes, since they would have been removed after the scene was cleared.
|
||||
let new_planes = self.new_default_planes(id_generator, source_range).await?;
|
||||
*self.default_planes.write().await = Some(new_planes);
|
||||
|
||||
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> {
|
||||
let (tx, rx) = oneshot::channel();
|
||||
|
||||
// Send the request to the engine, via the actor.
|
||||
self.engine_req_tx
|
||||
.send(ToEngineReq {
|
||||
req: cmd.clone(),
|
||||
request_sent: tx,
|
||||
})
|
||||
.await
|
||||
.map_err(|e| {
|
||||
KclError::Engine(KclErrorDetails {
|
||||
message: format!("Failed to send modeling command: {}", e),
|
||||
source_ranges: vec![source_range],
|
||||
})
|
||||
})?;
|
||||
|
||||
// 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],
|
||||
})
|
||||
})?;
|
||||
|
||||
// Wait for the response.
|
||||
let current_time = std::time::Instant::now();
|
||||
while current_time.elapsed().as_secs() < 60 {
|
||||
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() {
|
||||
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],
|
||||
}));
|
||||
}
|
||||
}
|
||||
// We pop off the responses to cleanup our mappings.
|
||||
if let Some(resp) = self.responses.write().await.shift_remove(&id) {
|
||||
return Ok(resp);
|
||||
}
|
||||
}
|
||||
|
||||
Err(KclError::Engine(KclErrorDetails {
|
||||
message: format!("Modeling command timed out `{}`", id),
|
||||
source_ranges: vec![source_range],
|
||||
}))
|
||||
}
|
||||
|
||||
async fn get_session_data(&self) -> Option<ModelingSessionData> {
|
||||
self.session_data.read().await.clone()
|
||||
}
|
||||
|
||||
async fn close(&self) {
|
||||
let _ = self.shutdown_tx.send(()).await;
|
||||
loop {
|
||||
let guard = self.socket_health.read().await;
|
||||
if *guard == SocketHealth::Inactive {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
139
rust/kcl-lib/src/engine/conn_mock.rs
Normal file
139
rust/kcl-lib/src/engine/conn_mock.rs
Normal file
@ -0,0 +1,139 @@
|
||||
//! Functions for setting up our WebSocket and WebRTC connections for communications with the
|
||||
//! engine.
|
||||
|
||||
use std::{collections::HashMap, sync::Arc};
|
||||
|
||||
use anyhow::Result;
|
||||
use indexmap::IndexMap;
|
||||
use kcmc::{
|
||||
ok_response::OkModelingCmdResponse,
|
||||
websocket::{
|
||||
BatchResponse, ModelingBatch, OkWebSocketResponseData, SuccessWebSocketResponse, WebSocketRequest,
|
||||
WebSocketResponse,
|
||||
},
|
||||
};
|
||||
use kittycad_modeling_cmds::{self as kcmc};
|
||||
use tokio::sync::RwLock;
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::ExecutionKind;
|
||||
use crate::{
|
||||
errors::KclError,
|
||||
exec::DefaultPlanes,
|
||||
execution::{ArtifactCommand, IdGenerator},
|
||||
SourceRange,
|
||||
};
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct EngineConnection {
|
||||
batch: Arc<RwLock<Vec<(WebSocketRequest, SourceRange)>>>,
|
||||
batch_end: Arc<RwLock<IndexMap<uuid::Uuid, (WebSocketRequest, SourceRange)>>>,
|
||||
artifact_commands: Arc<RwLock<Vec<ArtifactCommand>>>,
|
||||
execution_kind: Arc<RwLock<ExecutionKind>>,
|
||||
}
|
||||
|
||||
impl EngineConnection {
|
||||
pub async fn new() -> Result<EngineConnection> {
|
||||
Ok(EngineConnection {
|
||||
batch: Arc::new(RwLock::new(Vec::new())),
|
||||
batch_end: Arc::new(RwLock::new(IndexMap::new())),
|
||||
artifact_commands: Arc::new(RwLock::new(Vec::new())),
|
||||
execution_kind: Default::default(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl crate::engine::EngineManager for EngineConnection {
|
||||
fn batch(&self) -> Arc<RwLock<Vec<(WebSocketRequest, SourceRange)>>> {
|
||||
self.batch.clone()
|
||||
}
|
||||
|
||||
fn batch_end(&self) -> Arc<RwLock<IndexMap<uuid::Uuid, (WebSocketRequest, SourceRange)>>> {
|
||||
self.batch_end.clone()
|
||||
}
|
||||
|
||||
fn responses(&self) -> Arc<RwLock<IndexMap<Uuid, WebSocketResponse>>> {
|
||||
Arc::new(RwLock::new(IndexMap::new()))
|
||||
}
|
||||
|
||||
fn artifact_commands(&self) -> Arc<RwLock<Vec<ArtifactCommand>>> {
|
||||
self.artifact_commands.clone()
|
||||
}
|
||||
|
||||
async fn execution_kind(&self) -> ExecutionKind {
|
||||
let guard = self.execution_kind.read().await;
|
||||
*guard
|
||||
}
|
||||
|
||||
async fn replace_execution_kind(&self, execution_kind: ExecutionKind) -> ExecutionKind {
|
||||
let mut guard = self.execution_kind.write().await;
|
||||
let original = *guard;
|
||||
*guard = execution_kind;
|
||||
original
|
||||
}
|
||||
|
||||
async fn default_planes(
|
||||
&self,
|
||||
_id_generator: &mut IdGenerator,
|
||||
_source_range: SourceRange,
|
||||
) -> Result<DefaultPlanes, KclError> {
|
||||
Ok(DefaultPlanes::default())
|
||||
}
|
||||
|
||||
async fn clear_scene_post_hook(
|
||||
&self,
|
||||
_id_generator: &mut IdGenerator,
|
||||
_source_range: SourceRange,
|
||||
) -> Result<(), KclError> {
|
||||
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> {
|
||||
match cmd {
|
||||
WebSocketRequest::ModelingCmdBatchReq(ModelingBatch {
|
||||
ref requests,
|
||||
batch_id: _,
|
||||
responses: _,
|
||||
}) => {
|
||||
// Create the empty responses.
|
||||
let mut responses = HashMap::with_capacity(requests.len());
|
||||
for request in requests {
|
||||
responses.insert(
|
||||
request.cmd_id,
|
||||
BatchResponse::Success {
|
||||
response: OkModelingCmdResponse::Empty {},
|
||||
},
|
||||
);
|
||||
}
|
||||
Ok(WebSocketResponse::Success(SuccessWebSocketResponse {
|
||||
request_id: Some(id),
|
||||
resp: OkWebSocketResponseData::ModelingBatch { responses },
|
||||
success: true,
|
||||
}))
|
||||
}
|
||||
WebSocketRequest::ModelingCmdReq(_) => Ok(WebSocketResponse::Success(SuccessWebSocketResponse {
|
||||
request_id: Some(id),
|
||||
resp: OkWebSocketResponseData::Modeling {
|
||||
modeling_response: OkModelingCmdResponse::Empty {},
|
||||
},
|
||||
success: true,
|
||||
})),
|
||||
_ => Ok(WebSocketResponse::Success(SuccessWebSocketResponse {
|
||||
request_id: Some(id),
|
||||
resp: OkWebSocketResponseData::Modeling {
|
||||
modeling_response: OkModelingCmdResponse::Empty {},
|
||||
},
|
||||
success: true,
|
||||
})),
|
||||
}
|
||||
}
|
||||
|
||||
async fn close(&self) {}
|
||||
}
|
260
rust/kcl-lib/src/engine/conn_wasm.rs
Normal file
260
rust/kcl-lib/src/engine/conn_wasm.rs
Normal file
@ -0,0 +1,260 @@
|
||||
//! Functions for setting up our WebSocket and WebRTC connections for communications with the
|
||||
//! engine.
|
||||
use std::{collections::HashMap, sync::Arc};
|
||||
|
||||
use anyhow::Result;
|
||||
use indexmap::IndexMap;
|
||||
use kcmc::websocket::{WebSocketRequest, WebSocketResponse};
|
||||
use kittycad_modeling_cmds as kcmc;
|
||||
use tokio::sync::RwLock;
|
||||
use uuid::Uuid;
|
||||
use wasm_bindgen::prelude::*;
|
||||
|
||||
use crate::{
|
||||
engine::ExecutionKind,
|
||||
errors::{KclError, KclErrorDetails},
|
||||
execution::{ArtifactCommand, DefaultPlanes, IdGenerator},
|
||||
SourceRange,
|
||||
};
|
||||
|
||||
#[wasm_bindgen(module = "/../../src/lang/std/engineConnection.ts")]
|
||||
extern "C" {
|
||||
#[derive(Debug, Clone)]
|
||||
pub type EngineCommandManager;
|
||||
|
||||
#[wasm_bindgen(method, js_name = sendModelingCommandFromWasm, catch)]
|
||||
fn send_modeling_cmd_from_wasm(
|
||||
this: &EngineCommandManager,
|
||||
id: String,
|
||||
rangeStr: String,
|
||||
cmdStr: String,
|
||||
idToRangeStr: String,
|
||||
) -> Result<js_sys::Promise, js_sys::Error>;
|
||||
|
||||
#[wasm_bindgen(method, js_name = wasmGetDefaultPlanes, catch)]
|
||||
fn get_default_planes(this: &EngineCommandManager) -> Result<js_sys::Promise, js_sys::Error>;
|
||||
|
||||
#[wasm_bindgen(method, js_name = clearDefaultPlanes, catch)]
|
||||
fn clear_default_planes(this: &EngineCommandManager) -> Result<(), js_sys::Error>;
|
||||
|
||||
#[wasm_bindgen(method, js_name = startNewSession, catch)]
|
||||
fn start_new_session(this: &EngineCommandManager) -> Result<js_sys::Promise, js_sys::Error>;
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct EngineConnection {
|
||||
manager: Arc<EngineCommandManager>,
|
||||
batch: Arc<RwLock<Vec<(WebSocketRequest, SourceRange)>>>,
|
||||
batch_end: Arc<RwLock<IndexMap<uuid::Uuid, (WebSocketRequest, SourceRange)>>>,
|
||||
responses: Arc<RwLock<IndexMap<Uuid, WebSocketResponse>>>,
|
||||
artifact_commands: Arc<RwLock<Vec<ArtifactCommand>>>,
|
||||
execution_kind: Arc<RwLock<ExecutionKind>>,
|
||||
}
|
||||
|
||||
// Safety: WebAssembly will only ever run in a single-threaded context.
|
||||
unsafe impl Send for EngineConnection {}
|
||||
unsafe impl Sync for EngineConnection {}
|
||||
|
||||
impl EngineConnection {
|
||||
pub async fn new(manager: EngineCommandManager) -> Result<EngineConnection, JsValue> {
|
||||
#[allow(clippy::arc_with_non_send_sync)]
|
||||
Ok(EngineConnection {
|
||||
manager: Arc::new(manager),
|
||||
batch: Arc::new(RwLock::new(Vec::new())),
|
||||
batch_end: Arc::new(RwLock::new(IndexMap::new())),
|
||||
responses: Arc::new(RwLock::new(IndexMap::new())),
|
||||
artifact_commands: Arc::new(RwLock::new(Vec::new())),
|
||||
execution_kind: Default::default(),
|
||||
})
|
||||
}
|
||||
|
||||
async fn do_send_modeling_cmd(
|
||||
&self,
|
||||
id: uuid::Uuid,
|
||||
source_range: SourceRange,
|
||||
cmd: WebSocketRequest,
|
||||
id_to_source_range: HashMap<uuid::Uuid, SourceRange>,
|
||||
) -> Result<WebSocketResponse, KclError> {
|
||||
let source_range_str = serde_json::to_string(&source_range).map_err(|e| {
|
||||
KclError::Engine(KclErrorDetails {
|
||||
message: format!("Failed to serialize source range: {:?}", e),
|
||||
source_ranges: vec![source_range],
|
||||
})
|
||||
})?;
|
||||
let cmd_str = serde_json::to_string(&cmd).map_err(|e| {
|
||||
KclError::Engine(KclErrorDetails {
|
||||
message: format!("Failed to serialize modeling command: {:?}", e),
|
||||
source_ranges: vec![source_range],
|
||||
})
|
||||
})?;
|
||||
let id_to_source_range_str = serde_json::to_string(&id_to_source_range).map_err(|e| {
|
||||
KclError::Engine(KclErrorDetails {
|
||||
message: format!("Failed to serialize id to source range: {:?}", e),
|
||||
source_ranges: vec![source_range],
|
||||
})
|
||||
})?;
|
||||
|
||||
let promise = self
|
||||
.manager
|
||||
.send_modeling_cmd_from_wasm(id.to_string(), source_range_str, cmd_str, id_to_source_range_str)
|
||||
.map_err(|e| {
|
||||
KclError::Engine(KclErrorDetails {
|
||||
message: e.to_string().into(),
|
||||
source_ranges: vec![source_range],
|
||||
})
|
||||
})?;
|
||||
|
||||
let value = crate::wasm::JsFuture::from(promise).await.map_err(|e| {
|
||||
KclError::Engine(KclErrorDetails {
|
||||
message: format!("Failed to wait for promise from engine: {:?}", e),
|
||||
source_ranges: vec![source_range],
|
||||
})
|
||||
})?;
|
||||
|
||||
// Parse the value as a string.
|
||||
let s = value.as_string().ok_or_else(|| {
|
||||
KclError::Engine(KclErrorDetails {
|
||||
message: format!("Failed to get string from response from engine: `{:?}`", value),
|
||||
source_ranges: vec![source_range],
|
||||
})
|
||||
})?;
|
||||
|
||||
let ws_result: WebSocketResponse = serde_json::from_str(&s).map_err(|e| {
|
||||
KclError::Engine(KclErrorDetails {
|
||||
message: format!("Failed to deserialize response from engine: {:?}", e),
|
||||
source_ranges: vec![source_range],
|
||||
})
|
||||
})?;
|
||||
|
||||
Ok(ws_result)
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl crate::engine::EngineManager for EngineConnection {
|
||||
fn batch(&self) -> Arc<RwLock<Vec<(WebSocketRequest, SourceRange)>>> {
|
||||
self.batch.clone()
|
||||
}
|
||||
|
||||
fn batch_end(&self) -> Arc<RwLock<IndexMap<uuid::Uuid, (WebSocketRequest, SourceRange)>>> {
|
||||
self.batch_end.clone()
|
||||
}
|
||||
|
||||
fn responses(&self) -> Arc<RwLock<IndexMap<Uuid, WebSocketResponse>>> {
|
||||
self.responses.clone()
|
||||
}
|
||||
|
||||
fn artifact_commands(&self) -> Arc<RwLock<Vec<ArtifactCommand>>> {
|
||||
self.artifact_commands.clone()
|
||||
}
|
||||
|
||||
async fn execution_kind(&self) -> ExecutionKind {
|
||||
let guard = self.execution_kind.read().await;
|
||||
*guard
|
||||
}
|
||||
|
||||
async fn replace_execution_kind(&self, execution_kind: ExecutionKind) -> ExecutionKind {
|
||||
let mut guard = self.execution_kind.write().await;
|
||||
let original = *guard;
|
||||
*guard = execution_kind;
|
||||
original
|
||||
}
|
||||
|
||||
async fn default_planes(
|
||||
&self,
|
||||
_id_generator: &mut IdGenerator,
|
||||
source_range: SourceRange,
|
||||
) -> Result<DefaultPlanes, KclError> {
|
||||
// Get the default planes.
|
||||
let promise = self.manager.get_default_planes().map_err(|e| {
|
||||
KclError::Engine(KclErrorDetails {
|
||||
message: e.to_string().into(),
|
||||
source_ranges: vec![source_range],
|
||||
})
|
||||
})?;
|
||||
|
||||
let value = crate::wasm::JsFuture::from(promise).await.map_err(|e| {
|
||||
KclError::Engine(KclErrorDetails {
|
||||
message: format!("Failed to wait for promise from get default planes: {:?}", e),
|
||||
source_ranges: vec![source_range],
|
||||
})
|
||||
})?;
|
||||
|
||||
// Parse the value as a string.
|
||||
let s = value.as_string().ok_or_else(|| {
|
||||
KclError::Engine(KclErrorDetails {
|
||||
message: format!(
|
||||
"Failed to get string from response from get default planes: `{:?}`",
|
||||
value
|
||||
),
|
||||
source_ranges: vec![source_range],
|
||||
})
|
||||
})?;
|
||||
|
||||
// Deserialize the response.
|
||||
let default_planes: DefaultPlanes = serde_json::from_str(&s).map_err(|e| {
|
||||
KclError::Engine(KclErrorDetails {
|
||||
message: format!("Failed to deserialize default planes: {:?}", e),
|
||||
source_ranges: vec![source_range],
|
||||
})
|
||||
})?;
|
||||
|
||||
Ok(default_planes)
|
||||
}
|
||||
|
||||
async fn clear_scene_post_hook(
|
||||
&self,
|
||||
_id_generator: &mut IdGenerator,
|
||||
source_range: SourceRange,
|
||||
) -> Result<(), KclError> {
|
||||
self.manager.clear_default_planes().map_err(|e| {
|
||||
KclError::Engine(KclErrorDetails {
|
||||
message: e.to_string().into(),
|
||||
source_ranges: vec![source_range],
|
||||
})
|
||||
})?;
|
||||
|
||||
// Start a new session.
|
||||
let promise = self.manager.start_new_session().map_err(|e| {
|
||||
KclError::Engine(KclErrorDetails {
|
||||
message: e.to_string().into(),
|
||||
source_ranges: vec![source_range],
|
||||
})
|
||||
})?;
|
||||
|
||||
crate::wasm::JsFuture::from(promise).await.map_err(|e| {
|
||||
KclError::Engine(KclErrorDetails {
|
||||
message: format!("Failed to wait for promise from start new session: {:?}", e),
|
||||
source_ranges: vec![source_range],
|
||||
})
|
||||
})?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn inner_send_modeling_cmd(
|
||||
&self,
|
||||
id: uuid::Uuid,
|
||||
source_range: SourceRange,
|
||||
cmd: WebSocketRequest,
|
||||
id_to_source_range: HashMap<uuid::Uuid, SourceRange>,
|
||||
) -> Result<WebSocketResponse, KclError> {
|
||||
let ws_result = self
|
||||
.do_send_modeling_cmd(id, source_range, cmd, id_to_source_range)
|
||||
.await?;
|
||||
|
||||
// In isolated mode, we don't save the response.
|
||||
if self.execution_kind().await.is_isolated() {
|
||||
return Ok(ws_result);
|
||||
}
|
||||
|
||||
let mut responses = self.responses.write().await;
|
||||
responses.insert(id, ws_result.clone());
|
||||
drop(responses);
|
||||
|
||||
Ok(ws_result)
|
||||
}
|
||||
|
||||
// maybe we can actually impl this here? not sure how atm.
|
||||
async fn close(&self) {}
|
||||
}
|
745
rust/kcl-lib/src/engine/mod.rs
Normal file
745
rust/kcl-lib/src/engine/mod.rs
Normal file
@ -0,0 +1,745 @@
|
||||
//! Functions for managing engine communications.
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[cfg(feature = "engine")]
|
||||
pub mod conn;
|
||||
pub mod conn_mock;
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
#[cfg(feature = "engine")]
|
||||
pub mod conn_wasm;
|
||||
|
||||
use std::{collections::HashMap, sync::Arc};
|
||||
|
||||
use indexmap::IndexMap;
|
||||
use kcmc::{
|
||||
each_cmd as mcmd,
|
||||
id::ModelingCmdId,
|
||||
length_unit::LengthUnit,
|
||||
ok_response::OkModelingCmdResponse,
|
||||
shared::Color,
|
||||
websocket::{
|
||||
BatchResponse, ModelingBatch, ModelingCmdReq, ModelingSessionData, OkWebSocketResponseData, WebSocketRequest,
|
||||
WebSocketResponse,
|
||||
},
|
||||
ModelingCmd,
|
||||
};
|
||||
use kittycad_modeling_cmds as kcmc;
|
||||
use schemars::JsonSchema;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use tokio::sync::RwLock;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::{
|
||||
errors::{KclError, KclErrorDetails},
|
||||
execution::{ArtifactCommand, DefaultPlanes, IdGenerator, Point3d},
|
||||
SourceRange,
|
||||
};
|
||||
|
||||
lazy_static::lazy_static! {
|
||||
pub static ref GRID_OBJECT_ID: uuid::Uuid = uuid::Uuid::parse_str("cfa78409-653d-4c26-96f1-7c45fb784840").unwrap();
|
||||
|
||||
pub static ref GRID_SCALE_TEXT_OBJECT_ID: uuid::Uuid = uuid::Uuid::parse_str("10782f33-f588-4668-8bcd-040502d26590").unwrap();
|
||||
}
|
||||
|
||||
/// The mode of execution. When isolated, like during an import, attempting to
|
||||
/// send a command results in an error.
|
||||
#[derive(Debug, Default, Clone, Copy, Deserialize, Serialize, PartialEq, Eq, ts_rs::TS, JsonSchema)]
|
||||
#[ts(export)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum ExecutionKind {
|
||||
#[default]
|
||||
Normal,
|
||||
Isolated,
|
||||
}
|
||||
|
||||
impl ExecutionKind {
|
||||
pub fn is_isolated(&self) -> bool {
|
||||
matches!(self, ExecutionKind::Isolated)
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
pub trait EngineManager: std::fmt::Debug + Send + Sync + 'static {
|
||||
/// Get the batch of commands to be sent to the engine.
|
||||
fn batch(&self) -> Arc<RwLock<Vec<(WebSocketRequest, SourceRange)>>>;
|
||||
|
||||
/// Get the batch of end commands to be sent to the engine.
|
||||
fn batch_end(&self) -> Arc<RwLock<IndexMap<uuid::Uuid, (WebSocketRequest, SourceRange)>>>;
|
||||
|
||||
/// Get the command responses from the engine.
|
||||
fn responses(&self) -> Arc<RwLock<IndexMap<Uuid, WebSocketResponse>>>;
|
||||
|
||||
/// Get the artifact commands that have accumulated so far.
|
||||
fn artifact_commands(&self) -> Arc<RwLock<Vec<ArtifactCommand>>>;
|
||||
|
||||
/// Clear all artifact commands that have accumulated so far.
|
||||
async fn clear_artifact_commands(&self) {
|
||||
self.artifact_commands().write().await.clear();
|
||||
}
|
||||
|
||||
/// Take the artifact commands that have accumulated so far and clear them.
|
||||
async fn take_artifact_commands(&self) -> Vec<ArtifactCommand> {
|
||||
std::mem::take(&mut *self.artifact_commands().write().await)
|
||||
}
|
||||
|
||||
/// Take the responses that have accumulated so far and clear them.
|
||||
async fn take_responses(&self) -> IndexMap<Uuid, WebSocketResponse> {
|
||||
std::mem::take(&mut *self.responses().write().await)
|
||||
}
|
||||
|
||||
/// Get the current execution kind.
|
||||
async fn execution_kind(&self) -> ExecutionKind;
|
||||
|
||||
/// Replace the current execution kind with a new value and return the
|
||||
/// existing value.
|
||||
async fn replace_execution_kind(&self, execution_kind: ExecutionKind) -> ExecutionKind;
|
||||
|
||||
/// Get the default planes.
|
||||
async fn default_planes(
|
||||
&self,
|
||||
id_generator: &mut IdGenerator,
|
||||
_source_range: SourceRange,
|
||||
) -> Result<DefaultPlanes, crate::errors::KclError>;
|
||||
|
||||
/// Helpers to be called after clearing a scene.
|
||||
/// (These really only apply to wasm for now).
|
||||
async fn clear_scene_post_hook(
|
||||
&self,
|
||||
id_generator: &mut IdGenerator,
|
||||
source_range: SourceRange,
|
||||
) -> Result<(), crate::errors::KclError>;
|
||||
|
||||
/// Send a modeling command and wait for the response message.
|
||||
async fn inner_send_modeling_cmd(
|
||||
&self,
|
||||
id: uuid::Uuid,
|
||||
source_range: SourceRange,
|
||||
cmd: WebSocketRequest,
|
||||
id_to_source_range: HashMap<uuid::Uuid, SourceRange>,
|
||||
) -> Result<kcmc::websocket::WebSocketResponse, crate::errors::KclError>;
|
||||
|
||||
async fn clear_scene(
|
||||
&self,
|
||||
id_generator: &mut IdGenerator,
|
||||
source_range: SourceRange,
|
||||
) -> Result<(), crate::errors::KclError> {
|
||||
self.batch_modeling_cmd(
|
||||
uuid::Uuid::new_v4(),
|
||||
source_range,
|
||||
&ModelingCmd::SceneClearAll(mcmd::SceneClearAll::default()),
|
||||
)
|
||||
.await?;
|
||||
|
||||
// Flush the batch queue, so clear is run right away.
|
||||
// Otherwise the hooks below won't work.
|
||||
self.flush_batch(false, source_range).await?;
|
||||
|
||||
// Ensure artifact commands are cleared so that we don't accumulate them
|
||||
// across runs.
|
||||
self.clear_artifact_commands().await;
|
||||
|
||||
// Do the after clear scene hook.
|
||||
self.clear_scene_post_hook(id_generator, source_range).await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Set the visibility of edges.
|
||||
async fn set_edge_visibility(
|
||||
&self,
|
||||
visible: bool,
|
||||
source_range: SourceRange,
|
||||
) -> Result<(), crate::errors::KclError> {
|
||||
self.batch_modeling_cmd(
|
||||
uuid::Uuid::new_v4(),
|
||||
source_range,
|
||||
&ModelingCmd::from(mcmd::EdgeLinesVisible { hidden: !visible }),
|
||||
)
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn handle_artifact_command(
|
||||
&self,
|
||||
cmd: &ModelingCmd,
|
||||
cmd_id: ModelingCmdId,
|
||||
id_to_source_range: &HashMap<Uuid, SourceRange>,
|
||||
) -> Result<(), KclError> {
|
||||
let cmd_id = *cmd_id.as_ref();
|
||||
let range = id_to_source_range
|
||||
.get(&cmd_id)
|
||||
.copied()
|
||||
.ok_or_else(|| KclError::internal(format!("Failed to get source range for command ID: {:?}", cmd_id)))?;
|
||||
|
||||
// Add artifact command.
|
||||
self.artifact_commands().write().await.push(ArtifactCommand {
|
||||
cmd_id,
|
||||
range,
|
||||
command: cmd.clone(),
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn set_units(
|
||||
&self,
|
||||
units: crate::UnitLength,
|
||||
source_range: SourceRange,
|
||||
) -> Result<(), crate::errors::KclError> {
|
||||
// Before we even start executing the program, set the units.
|
||||
self.batch_modeling_cmd(
|
||||
uuid::Uuid::new_v4(),
|
||||
source_range,
|
||||
&ModelingCmd::from(mcmd::SetSceneUnits { unit: units.into() }),
|
||||
)
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Re-run the command to apply the settings.
|
||||
async fn reapply_settings(
|
||||
&self,
|
||||
settings: &crate::ExecutorSettings,
|
||||
source_range: SourceRange,
|
||||
) -> Result<(), crate::errors::KclError> {
|
||||
// Set the edge visibility.
|
||||
self.set_edge_visibility(settings.highlight_edges, source_range).await?;
|
||||
|
||||
// Change the units.
|
||||
self.set_units(settings.units, source_range).await?;
|
||||
|
||||
// Send the command to show the grid.
|
||||
self.modify_grid(!settings.show_grid, source_range).await?;
|
||||
|
||||
// We do not have commands for changing ssao on the fly.
|
||||
|
||||
// Flush the batch queue, so the settings are applied right away.
|
||||
self.flush_batch(false, source_range).await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// Add a modeling command to the batch but don't fire it right away.
|
||||
async fn batch_modeling_cmd(
|
||||
&self,
|
||||
id: uuid::Uuid,
|
||||
source_range: SourceRange,
|
||||
cmd: &ModelingCmd,
|
||||
) -> Result<(), crate::errors::KclError> {
|
||||
// In isolated mode, we don't send the command to the engine.
|
||||
if self.execution_kind().await.is_isolated() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let req = WebSocketRequest::ModelingCmdReq(ModelingCmdReq {
|
||||
cmd: cmd.clone(),
|
||||
cmd_id: id.into(),
|
||||
});
|
||||
|
||||
// Add cmd to the batch.
|
||||
self.batch().write().await.push((req, source_range));
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Add a command to the batch that needs to be executed at the very end.
|
||||
/// This for stuff like fillets or chamfers where if we execute too soon the
|
||||
/// engine will eat the ID and we can't reference it for other commands.
|
||||
async fn batch_end_cmd(
|
||||
&self,
|
||||
id: uuid::Uuid,
|
||||
source_range: SourceRange,
|
||||
cmd: &ModelingCmd,
|
||||
) -> Result<(), crate::errors::KclError> {
|
||||
// In isolated mode, we don't send the command to the engine.
|
||||
if self.execution_kind().await.is_isolated() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let req = WebSocketRequest::ModelingCmdReq(ModelingCmdReq {
|
||||
cmd: cmd.clone(),
|
||||
cmd_id: id.into(),
|
||||
});
|
||||
|
||||
// Add cmd to the batch end.
|
||||
self.batch_end().write().await.insert(id, (req, source_range));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Send the modeling cmd and wait for the response.
|
||||
async fn send_modeling_cmd(
|
||||
&self,
|
||||
id: uuid::Uuid,
|
||||
source_range: SourceRange,
|
||||
cmd: &ModelingCmd,
|
||||
) -> Result<OkWebSocketResponseData, crate::errors::KclError> {
|
||||
self.batch_modeling_cmd(id, source_range, cmd).await?;
|
||||
|
||||
// Flush the batch queue.
|
||||
self.flush_batch(false, source_range).await
|
||||
}
|
||||
|
||||
/// Force flush the batch queue.
|
||||
async fn flush_batch(
|
||||
&self,
|
||||
// Whether or not to flush the end commands as well.
|
||||
// We only do this at the very end of the file.
|
||||
batch_end: bool,
|
||||
source_range: SourceRange,
|
||||
) -> Result<OkWebSocketResponseData, crate::errors::KclError> {
|
||||
let all_requests = if batch_end {
|
||||
let mut requests = self.batch().read().await.clone();
|
||||
requests.extend(self.batch_end().read().await.values().cloned());
|
||||
requests
|
||||
} else {
|
||||
self.batch().read().await.clone()
|
||||
};
|
||||
|
||||
// Return early if we have no commands to send.
|
||||
if all_requests.is_empty() {
|
||||
return Ok(OkWebSocketResponseData::Modeling {
|
||||
modeling_response: OkModelingCmdResponse::Empty {},
|
||||
});
|
||||
}
|
||||
|
||||
let requests: Vec<ModelingCmdReq> = all_requests
|
||||
.iter()
|
||||
.filter_map(|(val, _)| match val {
|
||||
WebSocketRequest::ModelingCmdReq(ModelingCmdReq { cmd, cmd_id }) => Some(ModelingCmdReq {
|
||||
cmd: cmd.clone(),
|
||||
cmd_id: *cmd_id,
|
||||
}),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
|
||||
let batched_requests = WebSocketRequest::ModelingCmdBatchReq(ModelingBatch {
|
||||
requests,
|
||||
batch_id: uuid::Uuid::new_v4().into(),
|
||||
responses: true,
|
||||
});
|
||||
|
||||
let final_req = if all_requests.len() == 1 {
|
||||
// We can unwrap here because we know the batch has only one element.
|
||||
all_requests.first().unwrap().0.clone()
|
||||
} else {
|
||||
batched_requests
|
||||
};
|
||||
|
||||
// Create the map of original command IDs to source range.
|
||||
// This is for the wasm side, kurt needs it for selections.
|
||||
let mut id_to_source_range = HashMap::new();
|
||||
for (req, range) in all_requests.iter() {
|
||||
match req {
|
||||
WebSocketRequest::ModelingCmdReq(ModelingCmdReq { cmd: _, cmd_id }) => {
|
||||
id_to_source_range.insert(Uuid::from(*cmd_id), *range);
|
||||
}
|
||||
_ => {
|
||||
return Err(KclError::Engine(KclErrorDetails {
|
||||
message: format!("The request is not a modeling command: {:?}", req),
|
||||
source_ranges: vec![*range],
|
||||
}));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Do the artifact commands.
|
||||
for (req, _) in all_requests.iter() {
|
||||
match &req {
|
||||
WebSocketRequest::ModelingCmdBatchReq(ModelingBatch { requests, .. }) => {
|
||||
for request in requests {
|
||||
self.handle_artifact_command(&request.cmd, request.cmd_id, &id_to_source_range)
|
||||
.await?;
|
||||
}
|
||||
}
|
||||
WebSocketRequest::ModelingCmdReq(request) => {
|
||||
self.handle_artifact_command(&request.cmd, request.cmd_id, &id_to_source_range)
|
||||
.await?;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
// Throw away the old batch queue.
|
||||
self.batch().write().await.clear();
|
||||
if batch_end {
|
||||
self.batch_end().write().await.clear();
|
||||
}
|
||||
|
||||
// We pop off the responses to cleanup our mappings.
|
||||
match final_req {
|
||||
WebSocketRequest::ModelingCmdBatchReq(ModelingBatch {
|
||||
ref requests,
|
||||
batch_id,
|
||||
responses: _,
|
||||
}) => {
|
||||
// Get the last command ID.
|
||||
let last_id = requests.last().unwrap().cmd_id;
|
||||
let ws_resp = self
|
||||
.inner_send_modeling_cmd(batch_id.into(), source_range, final_req, id_to_source_range.clone())
|
||||
.await?;
|
||||
let response = self.parse_websocket_response(ws_resp, source_range)?;
|
||||
|
||||
// If we have a batch response, we want to return the specific id we care about.
|
||||
if let OkWebSocketResponseData::ModelingBatch { responses } = response {
|
||||
let responses = responses.into_iter().map(|(k, v)| (Uuid::from(k), v)).collect();
|
||||
self.parse_batch_responses(last_id.into(), id_to_source_range, responses)
|
||||
} else {
|
||||
// We should never get here.
|
||||
Err(KclError::Engine(KclErrorDetails {
|
||||
message: format!("Failed to get batch response: {:?}", response),
|
||||
source_ranges: vec![source_range],
|
||||
}))
|
||||
}
|
||||
}
|
||||
WebSocketRequest::ModelingCmdReq(ModelingCmdReq { cmd: _, cmd_id }) => {
|
||||
// You are probably wondering why we can't just return the source range we were
|
||||
// passed with the function. Well this is actually really important.
|
||||
// If this is the last command in the batch and there is only one and we've reached
|
||||
// the end of the file, this will trigger a flush batch function, but it will just
|
||||
// send default or the end of the file as it's source range not the origin of the
|
||||
// request so we need the original request source range in case the engine returns
|
||||
// an error.
|
||||
let source_range = id_to_source_range.get(cmd_id.as_ref()).cloned().ok_or_else(|| {
|
||||
KclError::Engine(KclErrorDetails {
|
||||
message: format!("Failed to get source range for command ID: {:?}", cmd_id),
|
||||
source_ranges: vec![],
|
||||
})
|
||||
})?;
|
||||
let ws_resp = self
|
||||
.inner_send_modeling_cmd(cmd_id.into(), source_range, final_req, id_to_source_range)
|
||||
.await?;
|
||||
self.parse_websocket_response(ws_resp, source_range)
|
||||
}
|
||||
_ => Err(KclError::Engine(KclErrorDetails {
|
||||
message: format!("The final request is not a modeling command: {:?}", final_req),
|
||||
source_ranges: vec![source_range],
|
||||
})),
|
||||
}
|
||||
}
|
||||
|
||||
async fn make_default_plane(
|
||||
&self,
|
||||
plane_id: uuid::Uuid,
|
||||
x_axis: Point3d,
|
||||
y_axis: Point3d,
|
||||
color: Option<Color>,
|
||||
source_range: SourceRange,
|
||||
) -> Result<uuid::Uuid, KclError> {
|
||||
// Create new default planes.
|
||||
let default_size = 100.0;
|
||||
let default_origin = Point3d { x: 0.0, y: 0.0, z: 0.0 }.into();
|
||||
|
||||
self.batch_modeling_cmd(
|
||||
plane_id,
|
||||
source_range,
|
||||
&ModelingCmd::from(mcmd::MakePlane {
|
||||
clobber: false,
|
||||
origin: default_origin,
|
||||
size: LengthUnit(default_size),
|
||||
x_axis: x_axis.into(),
|
||||
y_axis: y_axis.into(),
|
||||
hide: Some(true),
|
||||
}),
|
||||
)
|
||||
.await?;
|
||||
|
||||
if let Some(color) = color {
|
||||
// Set the color.
|
||||
self.batch_modeling_cmd(
|
||||
uuid::Uuid::new_v4(),
|
||||
source_range,
|
||||
&ModelingCmd::from(mcmd::PlaneSetColor { color, plane_id }),
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
|
||||
Ok(plane_id)
|
||||
}
|
||||
|
||||
async fn new_default_planes(
|
||||
&self,
|
||||
id_generator: &mut IdGenerator,
|
||||
source_range: SourceRange,
|
||||
) -> Result<DefaultPlanes, KclError> {
|
||||
let plane_settings: Vec<(PlaneName, Uuid, Point3d, Point3d, Option<Color>)> = vec![
|
||||
(
|
||||
PlaneName::Xy,
|
||||
id_generator.next_uuid(),
|
||||
Point3d { x: 1.0, y: 0.0, z: 0.0 },
|
||||
Point3d { x: 0.0, y: 1.0, z: 0.0 },
|
||||
Some(Color {
|
||||
r: 0.7,
|
||||
g: 0.28,
|
||||
b: 0.28,
|
||||
a: 0.4,
|
||||
}),
|
||||
),
|
||||
(
|
||||
PlaneName::Yz,
|
||||
id_generator.next_uuid(),
|
||||
Point3d { x: 0.0, y: 1.0, z: 0.0 },
|
||||
Point3d { x: 0.0, y: 0.0, z: 1.0 },
|
||||
Some(Color {
|
||||
r: 0.28,
|
||||
g: 0.7,
|
||||
b: 0.28,
|
||||
a: 0.4,
|
||||
}),
|
||||
),
|
||||
(
|
||||
PlaneName::Xz,
|
||||
id_generator.next_uuid(),
|
||||
Point3d { x: 1.0, y: 0.0, z: 0.0 },
|
||||
Point3d { x: 0.0, y: 0.0, z: 1.0 },
|
||||
Some(Color {
|
||||
r: 0.28,
|
||||
g: 0.28,
|
||||
b: 0.7,
|
||||
a: 0.4,
|
||||
}),
|
||||
),
|
||||
(
|
||||
PlaneName::NegXy,
|
||||
id_generator.next_uuid(),
|
||||
Point3d {
|
||||
x: -1.0,
|
||||
y: 0.0,
|
||||
z: 0.0,
|
||||
},
|
||||
Point3d { x: 0.0, y: 1.0, z: 0.0 },
|
||||
None,
|
||||
),
|
||||
(
|
||||
PlaneName::NegYz,
|
||||
id_generator.next_uuid(),
|
||||
Point3d {
|
||||
x: 0.0,
|
||||
y: -1.0,
|
||||
z: 0.0,
|
||||
},
|
||||
Point3d { x: 0.0, y: 0.0, z: 1.0 },
|
||||
None,
|
||||
),
|
||||
(
|
||||
PlaneName::NegXz,
|
||||
id_generator.next_uuid(),
|
||||
Point3d {
|
||||
x: -1.0,
|
||||
y: 0.0,
|
||||
z: 0.0,
|
||||
},
|
||||
Point3d { x: 0.0, y: 0.0, z: 1.0 },
|
||||
None,
|
||||
),
|
||||
];
|
||||
|
||||
let mut planes = HashMap::new();
|
||||
for (name, plane_id, x_axis, y_axis, color) in plane_settings {
|
||||
planes.insert(
|
||||
name,
|
||||
self.make_default_plane(plane_id, x_axis, y_axis, color, source_range)
|
||||
.await?,
|
||||
);
|
||||
}
|
||||
|
||||
// Flush the batch queue, so these planes are created right away.
|
||||
self.flush_batch(false, source_range).await?;
|
||||
|
||||
Ok(DefaultPlanes {
|
||||
xy: planes[&PlaneName::Xy],
|
||||
neg_xy: planes[&PlaneName::NegXy],
|
||||
xz: planes[&PlaneName::Xz],
|
||||
neg_xz: planes[&PlaneName::NegXz],
|
||||
yz: planes[&PlaneName::Yz],
|
||||
neg_yz: planes[&PlaneName::NegYz],
|
||||
})
|
||||
}
|
||||
|
||||
fn parse_websocket_response(
|
||||
&self,
|
||||
response: WebSocketResponse,
|
||||
source_range: SourceRange,
|
||||
) -> Result<OkWebSocketResponseData, crate::errors::KclError> {
|
||||
match response {
|
||||
WebSocketResponse::Success(success) => Ok(success.resp),
|
||||
WebSocketResponse::Failure(fail) => {
|
||||
let _request_id = fail.request_id;
|
||||
Err(KclError::Engine(KclErrorDetails {
|
||||
message: format!("Modeling command failed: {:?}", fail.errors),
|
||||
source_ranges: vec![source_range],
|
||||
}))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_batch_responses(
|
||||
&self,
|
||||
// The last response we are looking for.
|
||||
id: uuid::Uuid,
|
||||
// The mapping of source ranges to command IDs.
|
||||
id_to_source_range: HashMap<uuid::Uuid, SourceRange>,
|
||||
// The response from the engine.
|
||||
responses: HashMap<uuid::Uuid, BatchResponse>,
|
||||
) -> Result<OkWebSocketResponseData, crate::errors::KclError> {
|
||||
// Iterate over the responses and check for errors.
|
||||
#[expect(
|
||||
clippy::iter_over_hash_type,
|
||||
reason = "modeling command uses a HashMap and keys are random, so we don't really have a choice"
|
||||
)]
|
||||
for (cmd_id, resp) in responses.iter() {
|
||||
match resp {
|
||||
BatchResponse::Success { response } => {
|
||||
if cmd_id == &id {
|
||||
// This is the response we care about.
|
||||
return Ok(OkWebSocketResponseData::Modeling {
|
||||
modeling_response: response.clone(),
|
||||
});
|
||||
} else {
|
||||
// Continue the loop if this is not the response we care about.
|
||||
continue;
|
||||
}
|
||||
}
|
||||
BatchResponse::Failure { errors } => {
|
||||
// Get the source range for the command.
|
||||
let source_range = id_to_source_range.get(cmd_id).cloned().ok_or_else(|| {
|
||||
KclError::Engine(KclErrorDetails {
|
||||
message: format!("Failed to get source range for command ID: {:?}", cmd_id),
|
||||
source_ranges: vec![],
|
||||
})
|
||||
})?;
|
||||
return Err(KclError::Engine(KclErrorDetails {
|
||||
message: format!("Modeling command failed: {:?}", errors),
|
||||
source_ranges: vec![source_range],
|
||||
}));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Return an error that we did not get an error or the response we wanted.
|
||||
// This should never happen but who knows.
|
||||
Err(KclError::Engine(KclErrorDetails {
|
||||
message: format!("Failed to find response for command ID: {:?}", id),
|
||||
source_ranges: vec![],
|
||||
}))
|
||||
}
|
||||
|
||||
async fn modify_grid(&self, hidden: bool, source_range: SourceRange) -> Result<(), KclError> {
|
||||
// Hide/show the grid.
|
||||
self.batch_modeling_cmd(
|
||||
uuid::Uuid::new_v4(),
|
||||
source_range,
|
||||
&ModelingCmd::from(mcmd::ObjectVisible {
|
||||
hidden,
|
||||
object_id: *GRID_OBJECT_ID,
|
||||
}),
|
||||
)
|
||||
.await?;
|
||||
|
||||
// Hide/show the grid scale text.
|
||||
self.batch_modeling_cmd(
|
||||
uuid::Uuid::new_v4(),
|
||||
source_range,
|
||||
&ModelingCmd::from(mcmd::ObjectVisible {
|
||||
hidden,
|
||||
object_id: *GRID_SCALE_TEXT_OBJECT_ID,
|
||||
}),
|
||||
)
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Get session data, if it has been received.
|
||||
/// Returns None if the server never sent it.
|
||||
async fn get_session_data(&self) -> Option<ModelingSessionData> {
|
||||
None
|
||||
}
|
||||
|
||||
/// Close the engine connection and wait for it to finish.
|
||||
async fn close(&self);
|
||||
}
|
||||
|
||||
#[derive(Debug, Hash, Eq, Clone, Deserialize, Serialize, PartialEq, ts_rs::TS, JsonSchema)]
|
||||
#[ts(export)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum PlaneName {
|
||||
/// The XY plane.
|
||||
Xy,
|
||||
/// The opposite side of the XY plane.
|
||||
NegXy,
|
||||
/// The XZ plane.
|
||||
Xz,
|
||||
/// The opposite side of the XZ plane.
|
||||
NegXz,
|
||||
/// The YZ plane.
|
||||
Yz,
|
||||
/// The opposite side of the YZ plane.
|
||||
NegYz,
|
||||
}
|
||||
|
||||
/// Create a new zoo api client.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub fn new_zoo_client(token: Option<String>, engine_addr: Option<String>) -> anyhow::Result<kittycad::Client> {
|
||||
let user_agent = concat!(env!("CARGO_PKG_NAME"), ".rs/", env!("CARGO_PKG_VERSION"),);
|
||||
let http_client = reqwest::Client::builder()
|
||||
.user_agent(user_agent)
|
||||
// For file conversions we need this to be long.
|
||||
.timeout(std::time::Duration::from_secs(600))
|
||||
.connect_timeout(std::time::Duration::from_secs(60));
|
||||
let ws_client = reqwest::Client::builder()
|
||||
.user_agent(user_agent)
|
||||
// For file conversions we need this to be long.
|
||||
.timeout(std::time::Duration::from_secs(600))
|
||||
.connect_timeout(std::time::Duration::from_secs(60))
|
||||
.connection_verbose(true)
|
||||
.tcp_keepalive(std::time::Duration::from_secs(600))
|
||||
.http1_only();
|
||||
|
||||
let zoo_token_env = std::env::var("ZOO_API_TOKEN");
|
||||
|
||||
let token = if let Some(token) = token {
|
||||
token
|
||||
} else if let Ok(token) = std::env::var("KITTYCAD_API_TOKEN") {
|
||||
if let Ok(zoo_token) = zoo_token_env {
|
||||
if zoo_token != token {
|
||||
return Err(anyhow::anyhow!(
|
||||
"Both environment variables KITTYCAD_API_TOKEN=`{}` and ZOO_API_TOKEN=`{}` are set. Use only one.",
|
||||
token,
|
||||
zoo_token
|
||||
));
|
||||
}
|
||||
}
|
||||
token
|
||||
} else if let Ok(token) = zoo_token_env {
|
||||
token
|
||||
} else {
|
||||
return Err(anyhow::anyhow!(
|
||||
"No API token found in environment variables. Use KITTYCAD_API_TOKEN or ZOO_API_TOKEN"
|
||||
));
|
||||
};
|
||||
|
||||
// Create the client.
|
||||
let mut client = kittycad::Client::new_from_reqwest(token, http_client, ws_client);
|
||||
// Set an engine address if it's set.
|
||||
let kittycad_host_env = std::env::var("KITTYCAD_HOST");
|
||||
if let Some(addr) = engine_addr {
|
||||
client.set_base_url(addr);
|
||||
} else if let Ok(addr) = std::env::var("ZOO_HOST") {
|
||||
if let Ok(kittycad_host) = kittycad_host_env {
|
||||
if kittycad_host != addr {
|
||||
return Err(anyhow::anyhow!(
|
||||
"Both environment variables KITTYCAD_HOST=`{}` and ZOO_HOST=`{}` are set. Use only one.",
|
||||
kittycad_host,
|
||||
addr
|
||||
));
|
||||
}
|
||||
}
|
||||
client.set_base_url(addr);
|
||||
} else if let Ok(addr) = kittycad_host_env {
|
||||
client.set_base_url(addr);
|
||||
}
|
||||
|
||||
Ok(client)
|
||||
}
|
Reference in New Issue
Block a user