ctb_workspace_ipc/workspace_runner/
workspace_runtime.rs1use crate::services::renderer::RendererClient;
23use crate::services::runtime::RuntimeClient;
24#[allow(
25 unused_imports,
26 clippy::wildcard_imports,
27 reason = "Standard workspace module prelude"
28)]
29use crate::utilities::*;
30use crate::workspace_runner::WorkspaceRunnerConfig;
31use crate::workspace_runner::process::{ChildCommand, ChildProcess};
32
33use async_trait::async_trait;
34use ctb_utilities::ipc::service_traits::RuntimeClientTrait;
35use ctb_utilities::ipc::service_traits::runtime::RuntimeSpawner;
36
37use std::collections::HashMap;
38use std::sync::Arc;
39
40use ctb_utilities::ipc::IPC_ARG;
41use uuid::Uuid;
42
43use crate::auth::capability::{
44 CapabilityBundle, CapabilitySet, CapabilityToken, InMemoryTokenValidator,
45};
46use crate::process_manager::{
47 ProcessManager, SpawnParams, TokioProcessManager,
48};
49use crate::services::network::NetworkClient;
50use crate::services::parent::api::DataPlaneRef;
51use crate::services::parent::api::{ParentMessageKind, ShutdownRequest};
52use crate::services::parent::channel::ParentMessageEvent;
53use crate::types::{ConnectionId, ProcessId};
54use ipc::ChildKind;
55
56use crate::peer::IpcPeer;
57
58#[derive(Debug, Clone, Default)]
59pub(crate) struct ShutdownState {
60 pub(crate) requested: bool,
61 pub(crate) reason: Option<String>,
62}
63
64#[derive(Debug, Clone)]
66pub struct WorkspaceRuntime {
67 pub(crate) socket_path: String,
68 pub(crate) validator: Arc<InMemoryTokenValidator>,
69 pub(crate) process_manager: Arc<TokioProcessManager>,
70 pub(crate) exe: Arc<std::path::PathBuf>,
71 pub(crate) config: WorkspaceRunnerConfig,
72 pub(crate) pending_processes:
73 Arc<tokio::sync::Mutex<HashMap<String, ProcessId>>>,
74 pub(crate) peers: Arc<tokio::sync::Mutex<HashMap<ProcessId, Arc<IpcPeer>>>>,
75 pub(crate) pid_by_conn:
76 Arc<tokio::sync::Mutex<HashMap<ConnectionId, ProcessId>>>,
77 pub(crate) root_pids: Arc<tokio::sync::Mutex<Vec<ProcessId>>>,
78 pub(crate) singleton_pids:
79 Arc<tokio::sync::Mutex<HashMap<ChildKind, ProcessId>>>,
80 pub(crate) shutdown_tx: tokio::sync::mpsc::Sender<Option<String>>,
81 pub(crate) shutdown_state: Arc<tokio::sync::Mutex<ShutdownState>>,
82 pub(crate) shutdown_notify: Arc<tokio::sync::Notify>,
83}
84
85impl WorkspaceRuntime {
86 pub fn socket_path(&self) -> &str {
88 &self.socket_path
89 }
90
91 pub async fn get_singleton_pid(
93 &self,
94 kind: ChildKind,
95 ) -> Option<ProcessId> {
96 let guard = self.singleton_pids.lock().await;
97 guard.get(&kind).copied()
98 }
99
100 pub async fn wait_for_shutdown(&self) -> Option<String> {
107 loop {
108 {
109 let guard = self.shutdown_state.lock().await;
110 if guard.requested {
111 return guard.reason.clone();
112 }
113 }
114 self.shutdown_notify.notified().await;
115 }
116 }
117
118 pub(crate) async fn notify_shutdown(&self, reason: Option<String>) {
119 let mut guard = self.shutdown_state.lock().await;
120 guard.requested = true;
121 guard.reason = reason;
122 drop(guard);
123 self.shutdown_notify.notify_waiters();
124 }
125
126 pub async fn start_singleton_service(
130 &self,
131 kind: ChildKind,
132 caps: CapabilitySet,
133 ) -> Result<ChildProcess> {
134 let mut guard = self.singleton_pids.lock().await;
135 if let Some(pid) = guard.get(&kind).copied() {
136 return Ok(ChildProcess {
137 pid,
138 rt: self.clone(),
139 });
140 }
141 let child = self.start_service(kind, caps, None).await?;
142 guard.insert(kind, child.pid);
143 Ok(child)
144 }
145
146 pub async fn start_service(
148 &self,
149 kind: ChildKind,
150 caps: CapabilitySet,
151 parent: Option<ProcessId>,
152 ) -> Result<ChildProcess> {
153 self.start_service_with_args(kind, caps, parent, vec![])
154 .await
155 }
156
157 pub async fn start_service_with_args(
159 &self,
160 kind: ChildKind,
161 caps: CapabilitySet,
162 parent: Option<ProcessId>,
163 extra_args: Vec<String>,
164 ) -> Result<ChildProcess> {
165 let mut args = invocation_settings::get_settings().command_line_args();
166 args.extend(extra_args);
167
168 let pid = self
169 .spawn_child_with_command(kind, parent, caps, args)
170 .await?;
171
172 Ok(ChildProcess {
173 pid,
174 rt: self.clone(),
175 })
176 }
177
178 pub async fn start_network_service(
180 &self,
181 caps: CapabilitySet,
182 parent: Option<ProcessId>,
183 ) -> Result<NetworkClient> {
184 let proc = self.start_service(ChildKind::Network, caps, parent).await?;
185 Ok(NetworkClient::from_child(proc))
186 }
187
188 pub async fn start_renderer_service(
190 &self,
191 caps: CapabilitySet,
192 parent: Option<ProcessId>,
193 ) -> Result<RendererClient> {
194 let proc = self
195 .start_service(ChildKind::Renderer, caps, parent)
196 .await?;
197 Ok(RendererClient::from_child(proc))
198 }
199
200 pub async fn start_runtime_service(
202 &self,
203 caps: CapabilitySet,
204 parent: Option<ProcessId>,
205 ) -> Result<RuntimeClient> {
206 let proc = self.start_service(ChildKind::Runtime, caps, parent).await?;
207 Ok(RuntimeClient::from_child(proc))
208 }
209
210 async fn spawn_child_with_command(
211 &self,
212 kind: ChildKind,
213 parent: Option<ProcessId>,
214 caps: CapabilitySet,
215 extra_args: Vec<String>,
216 ) -> Result<ProcessId> {
217 let token_for = ipc::format_child_kind(&kind);
218 let token = self.register_token(token_for, caps.clone());
219
220 let mut cmd = ChildCommand {
221 program: self.exe.to_path_buf(),
222 args: vec![],
223 env: vec![],
224 cwd: None,
225 };
226
227 cmd.args.insert(0, "--".into());
231 cmd.args.insert(0, self.socket_path.clone());
232 cmd.args.insert(0, "--socket".into());
233 cmd.args.insert(0, format!("--{token_for}"));
234 cmd.args.insert(0, IPC_ARG.into());
235
236 cmd.args.extend(extra_args);
238
239 let program = cmd.program.to_string_lossy().into_owned();
240
241 debug_fmt!("spawning child {:?} {:?}", cmd.program, cmd.args);
242
243 let handle = self
244 .process_manager
245 .spawn_child(SpawnParams {
246 kind,
247 parent,
248 program: Some(program),
249 args: cmd.args,
250 env: cmd.env,
251 cwd: cmd.cwd,
252 capabilities: CapabilityBundle {
253 token: CapabilityToken(token),
254 capabilities: caps,
255 },
256 })
257 .await
258 .map_err(|e| anyhow::anyhow!("spawn_child failed: {e:#}"))?;
259
260 self.pending_processes
261 .lock()
262 .await
263 .insert(token_for.to_string(), handle.pid);
264
265 if parent.is_none() {
266 self.root_pids.lock().await.push(handle.pid);
267 }
268
269 Ok(handle.pid)
270 }
271
272 pub async fn pid_for_connection(
274 &self,
275 conn: ConnectionId,
276 ) -> Option<ProcessId> {
277 self.pid_by_conn.lock().await.get(&conn).copied()
278 }
279
280 pub async fn peer_for_pid(&self, pid: ProcessId) -> Result<Arc<IpcPeer>> {
282 let peers = Arc::clone(&self.peers);
283 let timeout = self.config.connect_timeout;
284
285 tokio::time::timeout(timeout, async move {
286 loop {
287 if let Some(peer) = peers.lock().await.get(&pid).cloned() {
288 return Ok(peer);
289 }
290 tokio::time::sleep(std::time::Duration::from_millis(10)).await;
291 }
292 })
293 .await
294 .map_err(|_elapsed| {
295 anyhow::anyhow!("timed out waiting for child peer")
296 })?
297 }
298
299 pub async fn peer_for_connection(
301 &self,
302 conn: ConnectionId,
303 ) -> Result<Arc<IpcPeer>> {
304 let Some(pid) = self.pid_for_connection(conn).await else {
305 anyhow::bail!("no pid registered for connection {conn}");
306 };
307 self.peer_for_pid(pid).await
308 }
309
310 pub async fn read_data_plane_ref_bytes(
315 &self,
316 conn: ConnectionId,
317 data_ref: &DataPlaneRef,
318 ) -> Result<Vec<u8>> {
319 let mut descriptor = data_ref.descriptor.clone();
320
321 #[cfg(unix)]
322 {
323 if crate::data_plane::shared_memory::descriptor_requires_fd_transfer(
324 &descriptor,
325 ) {
326 let peer = self.peer_for_connection(conn).await?;
327 descriptor = crate::data_plane::recv_blob_fd(
328 peer.session(),
329 &descriptor,
330 )
331 .await
332 .map_err(|e| anyhow::anyhow!("recv_blob_fd failed: {e}"))?;
333 }
334 }
335
336 ctb_utilities::shared_memory::read_blob_contents(
337 &descriptor,
338 data_ref.token.size,
339 )
340 .context("read_blob_contents")
341 }
342
343 pub async fn resolve_parent_message(
349 &self,
350 event: &ParentMessageEvent,
351 ) -> Result<ResolvedParentMessage> {
352 match event.message.kind {
353 ParentMessageKind::DataPlane => {
354 let data_ref =
355 event.message.as_data_plane_ref().map_err(|e| {
356 anyhow::anyhow!("decode data plane ref failed: {e:#}")
357 })?;
358
359 match self
360 .read_data_plane_ref_bytes(
361 event.ctx.connection_id,
362 &data_ref,
363 )
364 .await
365 {
366 Ok(bytes) => Ok(ResolvedParentMessage::DataPlaneBytes {
367 bytes,
368 content_type: data_ref.content_type,
369 sequence: data_ref.sequence,
370 }),
371 Err(error) => {
372 Ok(ResolvedParentMessage::DataPlaneReadFailed {
373 error,
374 content_type: data_ref.content_type,
375 sequence: data_ref.sequence,
376 })
377 }
378 }
379 }
380 ParentMessageKind::Text => {
381 let text = event.message.as_text().map_err(|e| {
382 anyhow::anyhow!("decode text message failed: {e:#}")
383 })?;
384 Ok(ResolvedParentMessage::Text(text))
385 }
386 ParentMessageKind::ShutdownRequest => {
387 let ShutdownRequest { reason } =
388 event.message.as_shutdown_request().map_err(|e| {
389 anyhow::anyhow!("decode shutdown request failed: {e:#}")
390 })?;
391 Ok(ResolvedParentMessage::ShutdownRequest { reason })
392 }
393 other => Ok(ResolvedParentMessage::Other { kind: other }),
394 }
395 }
396
397 pub async fn request_shutdown(&self, reason: Option<String>) -> Result<()> {
399 self.shutdown_tx.send(reason).await.map_err(|e| {
400 anyhow::anyhow!("failed to send shutdown request: {e}")
401 })?;
402 Ok(())
403 }
404
405 pub fn register_token(
407 &self,
408 token_for: &str,
409 caps: CapabilitySet,
410 ) -> String {
411 let token = format!("{token_for}-{}", Uuid::new_v4());
412 self.validator.register_token(&token, caps);
413 token
414 }
415}
416
417#[derive(Debug)]
419pub enum ResolvedParentMessage {
420 DataPlaneBytes {
422 bytes: Vec<u8>,
423 content_type: String,
424 sequence: Option<u64>,
425 },
426 DataPlaneReadFailed {
429 error: anyhow::Error,
430 content_type: String,
431 sequence: Option<u64>,
432 },
433 Text(String),
435 ShutdownRequest { reason: Option<String> },
437 Other { kind: ParentMessageKind },
439}
440
441#[async_trait]
442impl RuntimeSpawner for WorkspaceRuntime {
443 async fn spawn_runtime(&self) -> Result<Box<dyn RuntimeClientTrait>> {
444 let caps = CapabilitySet::default();
448 let client = self.start_runtime_service(caps, None).await?;
449 Ok(Box::new(client))
450 }
451}