ctb_workspace_ipc/
services.rs1#[allow(
23 unused_imports,
24 clippy::wildcard_imports,
25 reason = "Standard workspace module prelude"
26)]
27use crate::utilities::*;
28
29use std::sync::Arc;
30
31use crate::connection::DeferredChildIpcContext;
32use crate::connection::connect_to_workspace;
33use anyhow::{Result, anyhow};
34use ipc::{ChildKind, child_kind_from_string, format_child_kind};
35use tokio::sync::oneshot;
36
37use crate::protocol::ClientInfo;
38use crate::router::IpcRouter;
39use crate::services::process::OneshotShutdownProcessService;
40
41use serde::{Deserialize, Serialize};
42
43use crate::types::ProcessId;
44use crate::workspace_runner::process::ChildProcess;
45
46pub mod formats;
47pub mod io;
48pub mod network;
49pub mod parent;
50pub mod process;
51pub mod renderer;
52pub mod runtime;
53pub mod storage;
54
55pub mod macros;
56
57#[derive(Debug, Clone, Serialize, Deserialize)]
59pub struct EmptyResponse {}
60
61#[derive(Debug, Clone, Serialize, Deserialize)]
62pub struct StringResponse {
63 pub value: String,
64}
65
66#[derive(Debug, Clone, Serialize, Deserialize)]
67pub struct BytesResponse {
68 pub bytes: Vec<u8>,
70}
71
72#[derive(Debug, Clone, Serialize, Deserialize)]
73pub struct ExitCodeResponse {
74 pub code: i32,
75}
76
77pub trait IpcServiceClient {
78 fn proc(&self) -> &ChildProcess;
80}
81
82pub trait IpcServiceClientExt: IpcServiceClient {
87 fn pid(&self) -> ProcessId {
88 self.proc().pid
89 }
90}
91
92impl<C: IpcServiceClient> IpcServiceClientExt for C {}
93
94pub async fn run_as_subprocess(
96 mode: &str,
97 socket_path: &str,
98 token: &str,
99) -> Result<()> {
100 crate::services::run_service(
101 child_kind_from_string(mode)?,
102 socket_path,
103 token,
104 )
105 .await
106}
107
108pub async fn run_service(
115 service: ChildKind,
116 socket_path: &str,
117 token: &str,
118) -> Result<()> {
119 let process_kind: &'static str = format_child_kind(&service);
120 debug_fmt!("[{process_kind}] Starting...");
121
122 let (shutdown_tx, shutdown_rx) = oneshot::channel::<Option<String>>();
123
124 let router = IpcRouter::new();
125 let mut deferred_ipc: Option<Arc<DeferredChildIpcContext>> = None;
126 let router = match service {
127 ChildKind::Network => {
128 let ipc = Arc::new(DeferredChildIpcContext::new());
129 deferred_ipc = Some(Arc::clone(&ipc));
130 let ipc_ctx: Arc<
131 dyn ctb_utilities::ipc::service_traits::ChildIpcContext,
132 > = ipc.clone();
133 ctb_network::init_ipc_context(&ipc_ctx, Some(ChildKind::Network))?;
134
135 let backend: Arc<dyn ctb_network::NetworkBackend> =
136 Arc::new(ctb_network::DefaultNetworkBackend);
137 ctb_network::init_backend(&backend)?;
138
139 Ok(router)
140 }
141 ChildKind::Io => {
142 let ipc = Arc::new(DeferredChildIpcContext::new());
143 deferred_ipc = Some(Arc::clone(&ipc));
144 let ipc_ctx: Arc<
145 dyn ctb_utilities::ipc::service_traits::ChildIpcContext,
146 > = ipc.clone();
147 ctb_io::init_ipc_context(&ipc_ctx, Some(ChildKind::Io))?;
148 Ok(router)
149 }
150 ChildKind::Renderer => {
151 let ipc = Arc::new(DeferredChildIpcContext::new());
152 deferred_ipc = Some(Arc::clone(&ipc));
153 let ipc_ctx: Arc<
154 dyn ctb_utilities::ipc::service_traits::ChildIpcContext,
155 > = ipc.clone();
156 ctb_renderer::init_ipc_context(
157 &ipc_ctx,
158 Some(ChildKind::Renderer),
159 )?;
160 Ok(router)
161 }
162 ChildKind::Runtime => {
163 let ipc = Arc::new(DeferredChildIpcContext::new());
164 deferred_ipc = Some(Arc::clone(&ipc));
165 let ipc_ctx: Arc<
166 dyn ctb_utilities::ipc::service_traits::ChildIpcContext,
167 > = ipc.clone();
168 ctb_runtime::init_ipc_context(&ipc_ctx, Some(ChildKind::Runtime))?;
169 Ok(router)
170 }
171 ChildKind::Storage => {
172 let ipc = Arc::new(DeferredChildIpcContext::new());
173 deferred_ipc = Some(Arc::clone(&ipc));
174 let ipc_ctx: Arc<
175 dyn ctb_utilities::ipc::service_traits::ChildIpcContext,
176 > = ipc.clone();
177 ctb_storage::init_ipc_context(&ipc_ctx, Some(ChildKind::Storage))?;
178 Ok(router)
179 }
180 _ => Err(anyhow!(
181 "unsupported or unimplemented service kind for runtime"
182 )),
183 }?;
184 let router = router.with_process_service(Arc::new(
185 OneshotShutdownProcessService::new(shutdown_tx),
186 ));
187
188 let client_info = ClientInfo {
189 name: format!("example-{process_kind}"),
190 version: "0.1.0".into(),
191 process_kind: process_kind.into(),
192 };
193
194 let peer =
195 connect_to_workspace(socket_path, token, client_info, router).await?;
196
197 if let Some(ipc) = deferred_ipc.as_ref() {
198 ipc.attach_peer(Arc::clone(&peer)).map_err(|e| {
199 anyhow!("failed to attach IPC peer to context: {e}")
200 })?;
201 }
202
203 debug_fmt!("[{process_kind}] Listening for requests...");
204
205 tokio::select! {
206 reason = shutdown_rx => {
207 let reason = match reason {
208 Ok(reason) => reason,
209 Err(_canceled) => Some("shutdown channel closed".into()),
210 };
211 debug_fmt!(
212 "[{process_kind}] Shutdown acknowledged; exiting: {}",
213 reason.unwrap_or_else(|| "no reason".into())
215 );
216 }
217 () = peer.wait_closed() => {
218 debug_fmt!("[{process_kind}] Connection closed; exiting.");
219 }
220 }
221
222 debug_fmt!("[{process_kind}] Done.");
223 Ok(())
224}