1#[allow(
23 unused_imports,
24 clippy::wildcard_imports,
25 reason = "Standard workspace module prelude"
26)]
27use crate::utilities::*;
28
29use std::collections::HashMap;
30use std::sync::Arc;
31
32use async_trait::async_trait;
33use ctb_utilities::ipc::service_traits::{
34 ChildIpcContext, FormatsClientTrait, IoClientTrait, NetworkClientTrait,
35 RendererClientTrait, RuntimeClientTrait, StorageClientTrait,
36};
37use once_cell::sync::OnceCell;
38
39use crate::auth::capability::CapabilityToken;
40use crate::auth::capability::TokenValidator;
41use crate::auth::capability::trusted_workspace_capabilities;
42use crate::multiplex::session::{FramedSession, Session};
43use crate::peer::IpcPeer;
44use crate::process_manager::ProcessManager;
45use crate::protocol::{ClientInfo, Hello, MethodId};
46use crate::router::{ConnectionContext, IpcRouter};
47use crate::transport::{LocalSocketTransportFactory, TransportFactory};
48use crate::types::{ConnectionId, ProcessId};
49use ipc::ChildKind;
50
51pub async fn connect_to_workspace(
52 socket_path: &str,
53 token: &str,
54 client: ClientInfo,
55 router: IpcRouter,
56) -> Result<Arc<IpcPeer>> {
57 let factory = LocalSocketTransportFactory;
59 let conn = factory.connect(socket_path).await?;
60 let conn = Arc::new(conn);
61 let session = Arc::new(FramedSession::new(conn));
62
63 let hello =
65 Hello::new(CapabilityToken(token.to_string()), Some(client.clone()));
66 let caps = session.client_handshake(hello).await?;
67 let cap_keys = format!("{:?}", caps.allowed.keys());
68
69 let ctx = ConnectionContext {
74 id: ConnectionId::default(),
75 capabilities: trusted_workspace_capabilities(),
76 metadata: None,
77 };
78
79 let session: Arc<dyn Session> = session;
80 let peer = IpcPeer::new(session, Arc::new(router), ctx);
81
82 debug_fmt!(
83 "[{:?}] Connected with capabilities: {:?}",
84 client.process_kind,
85 cap_keys
86 );
87
88 Ok(peer)
89}
90
91#[derive(Debug, Clone)]
97pub struct WorkspaceConnectionHandler {
98 router: Arc<IpcRouter>,
99 validator: Arc<dyn TokenValidator>,
100}
101
102impl WorkspaceConnectionHandler {
103 pub fn new(
105 router: Arc<IpcRouter>,
106 validator: Arc<dyn TokenValidator>,
107 ) -> Self {
108 Self { router, validator }
109 }
110
111 pub async fn accept_peer<T>(
113 &self,
114 session: Arc<FramedSession<T>>,
115 conn_id: ConnectionId,
116 ) -> Result<Arc<IpcPeer>>
117 where
118 T: crate::transport::FramedConnection
119 + Clone
120 + std::fmt::Debug
121 + 'static,
122 {
123 let _caps = session
124 .server_handshake(
125 self.validator.as_ref(),
126 self.router.as_ref(),
127 conn_id,
128 )
129 .await
130 .context("server handshake")?;
131
132 let ctx = self.router.get(&conn_id).ok_or_else(|| {
133 anyhow::anyhow!("connection context missing for {conn_id}")
134 })?;
135
136 let session: Arc<dyn Session> = session;
137 Ok(IpcPeer::new(session, Arc::clone(&self.router), ctx))
138 }
139
140 pub async fn attach_peer_by_process_kind(
148 &self,
149 conn_id: ConnectionId,
150 peer: Arc<IpcPeer>,
151 process_manager: &dyn ProcessManager,
152 pending_processes: &tokio::sync::Mutex<HashMap<String, ProcessId>>,
153 peers: &tokio::sync::Mutex<HashMap<ProcessId, Arc<IpcPeer>>>,
154 ) -> Result<Option<ProcessId>> {
155 let Some(ctx) = self.router.get(&conn_id) else {
156 return Ok(None);
157 };
158
159 let kind = ctx
160 .metadata
161 .as_ref()
162 .and_then(|m| m.get("process_kind"))
163 .and_then(|v| v.as_str())
164 .map(ToString::to_string);
165
166 let Some(kind) = kind else {
167 return Ok(None);
168 };
169
170 let maybe_pid = pending_processes.lock().await.remove(&kind);
171 let Some(pid) = maybe_pid else {
172 return Ok(None);
173 };
174
175 if let Err(e) = process_manager.attach_connection(pid, conn_id).await {
176 tracing::warn!(
177 "attach_connection failed for pid={pid} conn_id={conn_id}: {e:#}"
178 );
179 }
180
181 peers.lock().await.insert(pid, peer);
182 Ok(Some(pid))
183 }
184
185 pub async fn handle_connection_with_pending_processes<T>(
187 &self,
188 session: Arc<FramedSession<T>>,
189 conn_id: ConnectionId,
190 process_manager: &dyn ProcessManager,
191 pending_processes: &tokio::sync::Mutex<HashMap<String, ProcessId>>,
192 peers: &tokio::sync::Mutex<HashMap<ProcessId, Arc<IpcPeer>>>,
193 ) -> Result<()>
194 where
195 T: crate::transport::FramedConnection
196 + Clone
197 + std::fmt::Debug
198 + 'static,
199 {
200 let peer = self.accept_peer(session, conn_id).await?;
201 let _ = self
202 .attach_peer_by_process_kind(
203 conn_id,
204 peer,
205 process_manager,
206 pending_processes,
207 peers,
208 )
209 .await?;
210 Ok(())
211 }
212}
213
214#[derive(Debug, Clone)]
220pub struct PeerChildIpcContext {
221 peer: Arc<IpcPeer>,
222}
223
224impl PeerChildIpcContext {
225 pub fn new(peer: Arc<IpcPeer>) -> Self {
227 Self { peer }
228 }
229
230 pub(crate) fn peer(&self) -> Arc<IpcPeer> {
231 Arc::clone(&self.peer)
232 }
233}
234
235#[derive(Debug, Default)]
244pub struct DeferredChildIpcContext {
245 inner: OnceCell<PeerChildIpcContext>,
246}
247
248impl DeferredChildIpcContext {
249 pub fn new() -> Self {
251 Self::default()
252 }
253
254 pub fn attach_peer(&self, peer: Arc<IpcPeer>) -> Result<()> {
258 if self.inner.set(PeerChildIpcContext::new(peer)).is_err() {
259 anyhow::bail!("IPC context already initialized");
260 }
261 Ok(())
262 }
263
264 fn ctx(&self) -> Result<&PeerChildIpcContext> {
265 self.inner
266 .get()
267 .ok_or_else(|| anyhow::anyhow!("IPC context not initialized yet"))
268 }
269
270 pub(crate) fn peer(&self) -> Result<Arc<IpcPeer>> {
271 Ok(self.ctx()?.peer())
272 }
273}
274
275#[async_trait]
276impl ChildIpcContext for DeferredChildIpcContext {
277 async fn request_spawn_formats(
278 &self,
279 init_data: Option<Vec<u8>>,
280 ) -> Result<Box<dyn FormatsClientTrait>> {
281 self.ctx()?.request_spawn_formats(init_data).await
282 }
283
284 async fn request_spawn_io(
285 &self,
286 init_data: Option<Vec<u8>>,
287 ) -> Result<Box<dyn IoClientTrait>> {
288 self.ctx()?.request_spawn_io(init_data).await
289 }
290
291 async fn request_spawn_network(
292 &self,
293 init_data: Option<Vec<u8>>,
294 ) -> Result<Box<dyn NetworkClientTrait>> {
295 self.ctx()?.request_spawn_network(init_data).await
296 }
297
298 async fn request_spawn_renderer(
299 &self,
300 init_data: Option<Vec<u8>>,
301 ) -> Result<Box<dyn RendererClientTrait>> {
302 self.ctx()?.request_spawn_renderer(init_data).await
303 }
304
305 async fn request_spawn_runtime(
306 &self,
307 init_data: Option<Vec<u8>>,
308 ) -> Result<Box<dyn RuntimeClientTrait>> {
309 self.ctx()?.request_spawn_runtime(init_data).await
310 }
311
312 async fn request_spawn_storage(
313 &self,
314 init_data: Option<Vec<u8>>,
315 ) -> Result<Box<dyn StorageClientTrait>> {
316 self.ctx()?.request_spawn_storage(init_data).await
317 }
318
319 async fn send_to_parent(&self, message: &str) -> Result<()> {
320 self.ctx()?.send_to_parent(message).await
321 }
322
323 async fn send_data_plane_message(
324 &self,
325 bytes: Vec<u8>,
326 content_type: &str,
327 ) -> Result<()> {
328 self.ctx()?
329 .send_data_plane_message(bytes, content_type)
330 .await
331 }
332
333 async fn request_workspace_shutdown(
334 &self,
335 reason: Option<String>,
336 ) -> Result<()> {
337 self.ctx()?.request_workspace_shutdown(reason).await
338 }
339
340 async fn call_raw(
341 &self,
342 service: &str,
343 method: &str,
344 args: Vec<u8>,
345 ) -> Result<Vec<u8>> {
346 self.ctx()?.call_raw(service, method, args).await
347 }
348}
349
350#[async_trait]
351impl ChildIpcContext for PeerChildIpcContext {
352 async fn request_spawn_formats(
353 &self,
354 init_data: Option<Vec<u8>>,
355 ) -> Result<Box<dyn FormatsClientTrait>> {
356 let pid = crate::peer_clients::request_spawn_child(
357 &self.peer,
358 ChildKind::Formats,
359 init_data,
360 )
361 .await?;
362 Ok(crate::services::formats::peer_formats_client(
363 Arc::clone(&self.peer),
364 pid,
365 ))
366 }
367
368 async fn request_spawn_io(
369 &self,
370 init_data: Option<Vec<u8>>,
371 ) -> Result<Box<dyn IoClientTrait>> {
372 let pid = crate::peer_clients::request_spawn_child(
373 &self.peer,
374 ChildKind::Io,
375 init_data,
376 )
377 .await?;
378 Ok(crate::services::io::peer_io_client(
379 Arc::clone(&self.peer),
380 pid,
381 ))
382 }
383
384 async fn request_spawn_network(
385 &self,
386 init_data: Option<Vec<u8>>,
387 ) -> Result<Box<dyn NetworkClientTrait>> {
388 let pid = crate::peer_clients::request_spawn_child(
389 &self.peer,
390 ChildKind::Network,
391 init_data,
392 )
393 .await?;
394 Ok(crate::services::network::peer_network_client(
395 Arc::clone(&self.peer),
396 pid,
397 ))
398 }
399
400 async fn request_spawn_runtime(
401 &self,
402 init_data: Option<Vec<u8>>,
403 ) -> Result<Box<dyn RuntimeClientTrait>> {
404 let pid = crate::peer_clients::request_spawn_child(
405 &self.peer,
406 ChildKind::Runtime,
407 init_data,
408 )
409 .await?;
410 Ok(crate::services::runtime::peer_runtime_client(
411 Arc::clone(&self.peer),
412 pid,
413 ))
414 }
415
416 async fn request_spawn_renderer(
417 &self,
418 init_data: Option<Vec<u8>>,
419 ) -> Result<Box<dyn RendererClientTrait>> {
420 let pid = crate::peer_clients::request_spawn_child(
421 &self.peer,
422 ChildKind::Renderer,
423 init_data,
424 )
425 .await?;
426 Ok(crate::services::renderer::peer_renderer_client(
427 Arc::clone(&self.peer),
428 pid,
429 ))
430 }
431
432 async fn request_spawn_storage(
433 &self,
434 init_data: Option<Vec<u8>>,
435 ) -> Result<Box<dyn StorageClientTrait>> {
436 let pid = crate::peer_clients::request_spawn_child(
437 &self.peer,
438 ChildKind::Storage,
439 init_data,
440 )
441 .await?;
442 Ok(crate::services::storage::peer_storage_client(
443 Arc::clone(&self.peer),
444 pid,
445 ))
446 }
447
448 async fn send_to_parent(&self, message: &str) -> Result<()> {
449 crate::peer_clients::send_to_parent(&self.peer, message).await
450 }
451
452 async fn send_data_plane_message(
453 &self,
454 bytes: Vec<u8>,
455 content_type: &str,
456 ) -> Result<()> {
457 crate::peer_clients::send_data_plane_message(
458 &self.peer,
459 bytes,
460 content_type,
461 )
462 .await
463 }
464
465 async fn request_workspace_shutdown(
466 &self,
467 reason: Option<String>,
468 ) -> Result<()> {
469 crate::peer_clients::request_workspace_shutdown(&self.peer, reason)
470 .await
471 }
472
473 async fn call_raw(
474 &self,
475 service: &str,
476 method: &str,
477 args: Vec<u8>,
478 ) -> Result<Vec<u8>> {
479 let resp = self
480 .peer
481 .call(
482 MethodId {
483 service: service.to_string(),
484 method: method.to_string(),
485 },
486 args,
487 )
488 .await
489 .map_err(|e| anyhow::anyhow!("IPC call_raw failed: {e}"))?;
490
491 crate::ensure_response_ok(&resp, "IPC call_raw")?;
492 Ok(resp.result.unwrap_or_default())
494 }
495}