2023-08-28 14:58:24 -07:00
|
|
|
//! Functions for setting up our WebSocket and WebRTC connections for communications with the
|
|
|
|
//! engine.
|
|
|
|
|
2024-03-01 14:43:11 -05: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};
|
|
|
|
use kittycad::types::{OkWebSocketResponseData, WebSocketRequest, WebSocketResponse};
|
2023-09-20 16:59:03 -05:00
|
|
|
use tokio::sync::{mpsc, oneshot};
|
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},
|
|
|
|
};
|
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-09-20 18:27:08 -07:00
|
|
|
#[allow(dead_code)] // for the TcpReadHandle
|
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>>,
|
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)>>>,
|
2023-08-28 14:58:24 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
pub struct TcpRead {
|
|
|
|
stream: futures::stream::SplitStream<tokio_tungstenite::WebSocketStream<reqwest::Upgraded>>,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl TcpRead {
|
|
|
|
pub async fn read(&mut self) -> Result<WebSocketResponse> {
|
2023-09-15 20:45:28 -07:00
|
|
|
let Some(msg) = self.stream.next().await else {
|
|
|
|
anyhow::bail!("Failed to read from websocket");
|
|
|
|
};
|
|
|
|
let msg: WebSocketResponse = match msg? {
|
2023-08-28 14:58:24 -07:00
|
|
|
WsMsg::Text(text) => serde_json::from_str(&text)?,
|
|
|
|
WsMsg::Binary(bin) => bson::from_slice(&bin)?,
|
|
|
|
other => anyhow::bail!("Unexpected websocket message from server: {}", other),
|
|
|
|
};
|
|
|
|
Ok(msg)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-09-20 18:27:08 -07:00
|
|
|
#[derive(Debug)]
|
|
|
|
pub struct TcpReadHandle {
|
|
|
|
handle: Arc<tokio::task::JoinHandle<Result<()>>>,
|
|
|
|
}
|
|
|
|
|
|
|
|
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-02-11 15:08:54 -08:00
|
|
|
let res = if let kittycad::types::WebSocketRequest::ModelingCmdReq {
|
|
|
|
cmd: kittycad::types::ModelingCmd::ImportFiles { .. },
|
|
|
|
cmd_id: _,
|
|
|
|
} = &req
|
|
|
|
{
|
|
|
|
// 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);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// 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> {
|
2023-08-28 14:58:24 -07:00
|
|
|
let ws_stream = tokio_tungstenite::WebSocketStream::from_raw_socket(
|
|
|
|
ws,
|
|
|
|
tokio_tungstenite::tungstenite::protocol::Role::Client,
|
2023-11-21 09:23:48 -08:00
|
|
|
Some(tokio_tungstenite::tungstenite::protocol::WebSocketConfig { ..Default::default() }),
|
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 };
|
|
|
|
|
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));
|
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-04-04 14:47:47 -04:00
|
|
|
for e in ws_resp.errors.iter().flatten() {
|
|
|
|
println!("got error message: {e}");
|
|
|
|
}
|
2023-09-15 20:45:28 -07:00
|
|
|
if let Some(id) = ws_resp.request_id {
|
|
|
|
responses_clone.insert(id, ws_resp.clone());
|
2023-08-28 14:58:24 -07:00
|
|
|
}
|
|
|
|
}
|
|
|
|
Err(e) => {
|
|
|
|
println!("got ws error: {:?}", 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-03-01 14:43:11 -05:00
|
|
|
socket_health,
|
2024-03-23 15:45:55 -07:00
|
|
|
batch: Arc::new(Mutex::new(Vec::new())),
|
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()
|
|
|
|
}
|
|
|
|
|
|
|
|
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-03-23 15:45:55 -07:00
|
|
|
cmd: kittycad::types::WebSocketRequest,
|
|
|
|
_id_to_source_range: std::collections::HashMap<uuid::Uuid, crate::executor::SourceRange>,
|
2023-09-15 20:45:28 -07:00
|
|
|
) -> Result<OkWebSocketResponseData, 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 {
|
|
|
|
return Err(KclError::Engine(KclErrorDetails {
|
|
|
|
message: "Modeling command failed: websocket closed early".to_string(),
|
|
|
|
source_ranges: vec![source_range],
|
|
|
|
}));
|
|
|
|
}
|
|
|
|
}
|
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) {
|
2023-09-20 16:59:03 -05:00
|
|
|
return if let Some(data) = &resp.resp {
|
|
|
|
Ok(data.clone())
|
2023-09-15 20:45:28 -07:00
|
|
|
} else {
|
2023-09-20 16:59:03 -05:00
|
|
|
Err(KclError::Engine(KclErrorDetails {
|
2023-09-15 20:45:28 -07:00
|
|
|
message: format!("Modeling command failed: {:?}", resp.errors),
|
|
|
|
source_ranges: vec![source_range],
|
2023-09-20 16:59:03 -05:00
|
|
|
}))
|
|
|
|
};
|
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
|
|
|
}
|
2023-08-28 14:58:24 -07:00
|
|
|
}
|