1#[allow(
26 unused_imports,
27 clippy::wildcard_imports,
28 reason = "Standard workspace module prelude"
29)]
30use crate::utilities::*;
31
32use std::sync::Arc;
33
34use crate::data_plane::send_blob_fd;
35use crate::data_plane::shared_memory::{
36 BlobAllocator, BlobBackend, SharedMemoryBlobs,
37 descriptor_requires_fd_transfer,
38};
39use crate::peer::IpcPeer;
40use crate::protocol::MethodId;
41use crate::services::parent::SERVICE_NAME as PARENT_SERVICE_NAME;
42use crate::services::parent::api::{
43 DataPlaneRef, METHOD_MESSAGE_PARENT, METHOD_PROXY_CALL,
44 METHOD_REQUEST_SPAWN_CHILD, MessageToParentRequest, ParentMessage,
45 ProxyCallRequest, ProxyCallResponse, SpawnChildRequest, SpawnChildResponse,
46};
47use crate::types::ProcessId;
48use ipc::ChildKind;
49
50#[cfg(unix)]
51use ctb_utilities::ipc::registry::IpcCallerWithFds;
52use ctb_utilities::ipc::registry::{IpcCallFuture, IpcCaller};
53
54pub(crate) async fn send_to_parent(
56 peer: &Arc<IpcPeer>,
57 message: &str,
58) -> Result<()> {
59 send_parent_message(peer, ParentMessage::text(message)).await
60}
61
62pub(crate) async fn send_data_plane_message(
67 peer: &Arc<IpcPeer>,
68 bytes: Vec<u8>,
69 content_type: &str,
70) -> Result<()> {
71 let blobs = SharedMemoryBlobs::new(BlobBackend::PlatformDefault);
72 let size = u64::try_from(bytes.len())
73 .map_err(|e| anyhow::anyhow!("blob too large: {e}"))?;
74
75 let blob = blobs
76 .create(size)
77 .await
78 .map_err(|e| anyhow::anyhow!("failed to allocate blob: {e}"))?;
79
80 blob.write_all(&bytes)
81 .map_err(|e| anyhow::anyhow!("failed to write blob: {e}"))?;
82
83 let data_ref = DataPlaneRef::new(
84 blob.token.clone(),
85 blob.descriptor.clone(),
86 content_type.to_string(),
87 );
88
89 let msg = ParentMessage::data_plane(&data_ref).map_err(|e| {
90 anyhow::anyhow!("failed to encode data plane message: {e}")
91 })?;
92
93 send_parent_message(peer, msg).await?;
94
95 if descriptor_requires_fd_transfer(&blob.descriptor) {
96 send_blob_fd(peer.session(), &blob.descriptor)
97 .await
98 .map_err(|e| anyhow::anyhow!("failed to send blob fd: {e}"))?;
99 }
100
101 Ok(())
102}
103
104pub(crate) async fn request_workspace_shutdown(
106 peer: &Arc<IpcPeer>,
107 reason: Option<String>,
108) -> Result<()> {
109 let msg = ParentMessage::shutdown_request(reason).map_err(|e| {
110 anyhow::anyhow!("failed to encode shutdown request: {e}")
111 })?;
112 send_parent_message(peer, msg).await
113}
114
115pub(crate) async fn request_spawn_child(
117 peer: &Arc<IpcPeer>,
118 kind: ChildKind,
119 init_data: Option<Vec<u8>>,
120) -> Result<ProcessId> {
121 let spawn_req = SpawnChildRequest { kind, init_data };
122 let args = postcard_helpers::encode(&spawn_req, "spawn request")?;
123
124 let resp = peer
125 .call(
126 MethodId {
127 service: PARENT_SERVICE_NAME.into(),
128 method: METHOD_REQUEST_SPAWN_CHILD.into(),
129 },
130 args,
131 )
132 .await
133 .map_err(|e| anyhow::anyhow!("spawn request IPC call failed: {e}"))?;
134
135 let bytes = crate::response_result_bytes(resp, "spawn request")?;
136 let result: SpawnChildResponse =
137 postcard_helpers::decode(&bytes, "spawn response")?;
138
139 if !result.accepted {
140 anyhow::bail!(
141 "spawn request rejected: {}",
142 result.error.unwrap_or_else(|| "no reason".into())
144 );
145 }
146
147 result
148 .child_pid
149 .ok_or_else(|| anyhow::anyhow!("spawn response missing child pid"))
150}
151
152async fn send_parent_message(
153 peer: &Arc<IpcPeer>,
154 message: ParentMessage,
155) -> Result<()> {
156 let req = MessageToParentRequest { message };
157 let args = postcard_helpers::encode(&req, "parent message")?;
158
159 let resp = peer
160 .call(
161 MethodId {
162 service: PARENT_SERVICE_NAME.into(),
163 method: METHOD_MESSAGE_PARENT.into(),
164 },
165 args,
166 )
167 .await
168 .map_err(|e| {
169 anyhow::anyhow!("send_parent_message IPC call failed: {e}")
170 })?;
171
172 crate::ensure_response_ok(&resp, "send_parent_message")?;
173
174 Ok(())
175}
176
177#[derive(Debug, Clone)]
179pub(crate) struct PeerProxiedClient {
180 peer: Arc<IpcPeer>,
181 target_pid: ProcessId,
182}
183
184impl PeerProxiedClient {
185 pub(crate) fn new(peer: Arc<IpcPeer>, target_pid: ProcessId) -> Self {
186 Self { peer, target_pid }
187 }
188
189 async fn proxy_call(
190 &self,
191 method: MethodId,
192 args: Vec<u8>,
193 ) -> Result<ProxyCallResponse> {
194 let req = ProxyCallRequest {
195 target_pid: self.target_pid,
196 method,
197 args,
198 fd_count: 0,
199 };
200 let payload = postcard_helpers::encode(&req, "proxy request")?;
201
202 let resp = self
203 .peer
204 .call(
205 MethodId {
206 service: PARENT_SERVICE_NAME.into(),
207 method: METHOD_PROXY_CALL.into(),
208 },
209 payload,
210 )
211 .await
212 .map_err(|e| anyhow::anyhow!("proxy_call IPC call failed: {e}"))?;
213
214 let bytes = crate::response_result_bytes(resp, "proxy_call")?;
215 let result: ProxyCallResponse =
216 postcard_helpers::decode(&bytes, "proxy_call response")?;
217 Ok(result)
218 }
219
220 #[cfg(unix)]
221 async fn proxy_call_with_fds(
222 &self,
223 method: MethodId,
224 args: Vec<u8>,
225 fds: Vec<std::os::unix::io::RawFd>,
226 ) -> Result<ProxyCallResponse> {
227 let fd_count = u32::try_from(fds.len())
228 .map_err(|e| anyhow::anyhow!("too many fds for proxy call: {e}"))?;
229
230 let req = ProxyCallRequest {
231 target_pid: self.target_pid,
232 method,
233 args,
234 fd_count,
235 };
236
237 let payload = postcard_helpers::encode(&req, "proxy request")?;
238
239 let resp = self
240 .peer
241 .call_raw_with_fds(
242 MethodId {
243 service: PARENT_SERVICE_NAME.into(),
244 method: METHOD_PROXY_CALL.into(),
245 },
246 payload,
247 fds,
248 )
249 .await
250 .map_err(|e| anyhow::anyhow!("proxy_call IPC call failed: {e}"))?;
251
252 let bytes = crate::response_result_bytes(resp, "proxy_call")?;
253 let result: ProxyCallResponse =
254 postcard_helpers::decode(&bytes, "proxy_call response")?;
255 Ok(result)
256 }
257
258 pub(crate) async fn call_postcard<Req, Resp>(
259 &self,
260 service: &str,
261 method: &str,
262 req: &Req,
263 ) -> Result<Resp>
264 where
265 Req: serde::Serialize + Send + Sync,
266 Resp: serde::de::DeserializeOwned,
267 {
268 let args = postcard_helpers::encode(req, "request")?;
269
270 let proxied = self
271 .proxy_call(
272 MethodId {
273 service: service.to_string(),
274 method: method.to_string(),
275 },
276 args,
277 )
278 .await?;
279
280 if !proxied.ok {
281 let msg = proxied
283 .error
284 .map_or_else(|| "unknown error".to_string(), |e| e.message);
285 anyhow::bail!("proxied call failed: {msg}");
286 }
287
288 let result = proxied
289 .result
290 .as_ref()
291 .ok_or_else(|| anyhow::anyhow!("response missing result"))
292 .and_then(|bytes| postcard_helpers::decode(bytes, "response"))?;
293
294 Ok(result)
295 }
296}
297
298impl IpcCaller for PeerProxiedClient {
299 fn call_raw(
300 &self,
301 service: &str,
302 method: &str,
303 args: Vec<u8>,
304 ) -> IpcCallFuture<'_> {
305 let service = service.to_string();
306 let method = method.to_string();
307
308 Box::pin(async move {
309 let proxied =
310 self.proxy_call(MethodId { service, method }, args).await?;
311
312 proxied_result_bytes(proxied, "proxied call")
313 })
314 }
315}
316
317#[cfg(unix)]
318impl IpcCallerWithFds for PeerProxiedClient {
319 fn call_raw_with_fds(
320 &self,
321 service: &str,
322 method: &str,
323 args: Vec<u8>,
324 fds: Vec<std::os::unix::io::RawFd>,
325 ) -> IpcCallFuture<'_> {
326 let service = service.to_string();
327 let method = method.to_string();
328
329 Box::pin(async move {
330 let proxied = self
331 .proxy_call_with_fds(MethodId { service, method }, args, fds)
332 .await?;
333
334 proxied_result_bytes(proxied, "proxied call")
335 })
336 }
337}
338
339fn proxied_result_bytes(
340 proxied: ProxyCallResponse,
341 context: &str,
342) -> Result<Vec<u8>> {
343 if !proxied.ok {
344 let msg = proxied
346 .error
347 .as_ref()
348 .map_or_else(|| "unknown error".to_string(), |e| e.message.clone());
349 anyhow::bail!("{context} failed: {msg}");
350 }
351
352 proxied
353 .result
354 .ok_or_else(|| anyhow::anyhow!("{context} missing result"))
355}