ctb_workspace_ipc/services/parent/
api.rs1#[allow(
28 unused_imports,
29 clippy::wildcard_imports,
30 reason = "Standard workspace module prelude"
31)]
32use crate::utilities::*;
33
34use anyhow::Result;
35use async_trait::async_trait;
36use ctb_utilities::shared_memory::BlobToken;
37use serde::{Deserialize, Serialize};
38
39use crate::data_plane::shared_memory::SharedBlobDescriptor;
40use crate::error::Error;
41use crate::types::{ConnectionId, ProcessId};
42use ipc::ChildKind;
43
44pub const METHOD_MESSAGE_PARENT: &str = "message_parent";
46
47pub const METHOD_REQUEST_SPAWN_CHILD: &str = "request_spawn_child";
49
50pub const METHOD_PROXY_CALL: &str = "proxy_call";
53
54#[derive(Debug, Clone, Serialize, Deserialize)]
56pub struct ParentMessage {
57 pub kind: ParentMessageKind,
59 pub payload: Vec<u8>,
61}
62
63impl ParentMessage {
64 pub fn data_plane(data_ref: &DataPlaneRef) -> Result<Self, Error> {
66 let payload = postcard_helpers::encode(data_ref, "data plane ref")
67 .map_err(|e| Error::Serialization(e.to_string()))?;
68 Ok(Self {
69 kind: ParentMessageKind::DataPlane,
70 payload,
71 })
72 }
73
74 pub fn text<S: Into<String>>(text: S) -> Self {
76 Self {
77 kind: ParentMessageKind::Text,
78 payload: text.into().into_bytes(),
79 }
80 }
81
82 pub fn shutdown_request(reason: Option<String>) -> Result<Self, Error> {
84 let payload = postcard_helpers::encode(
85 &ShutdownRequest { reason },
86 "shutdown request",
87 )
88 .map_err(|e| Error::Serialization(e.to_string()))?;
89 Ok(Self {
90 kind: ParentMessageKind::ShutdownRequest,
91 payload,
92 })
93 }
94
95 pub fn as_data_plane_ref(&self) -> Result<DataPlaneRef, Error> {
97 if self.kind != ParentMessageKind::DataPlane {
98 return Err(Error::Internal("not a data plane message".into()));
99 }
100 postcard_helpers::decode(&self.payload, "data plane ref")
101 .map_err(|e| Error::Serialization(e.to_string()))
102 }
103
104 pub fn as_text(&self) -> Result<String, Error> {
106 if self.kind != ParentMessageKind::Text {
107 return Err(Error::Internal("not a text message".into()));
108 }
109 String::from_utf8(self.payload.clone())
110 .map_err(|e| Error::Serialization(e.to_string()))
111 }
112
113 pub fn as_shutdown_request(&self) -> Result<ShutdownRequest, Error> {
115 if self.kind != ParentMessageKind::ShutdownRequest {
116 return Err(Error::Internal("not a shutdown request".into()));
117 }
118 postcard_helpers::decode(&self.payload, "shutdown request")
119 .map_err(|e| Error::Serialization(e.to_string()))
120 }
121}
122
123#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
125pub enum ParentMessageKind {
126 DataPlane,
128 Text,
130 ShutdownRequest,
132 Status,
134 Error,
136}
137
138#[derive(Debug, Clone, Serialize, Deserialize)]
143pub struct DataPlaneRef {
144 pub sequence: Option<u64>,
146 pub content_type: String,
148 pub token: BlobToken,
150 pub descriptor: SharedBlobDescriptor,
152}
153
154impl DataPlaneRef {
155 pub fn new(
157 token: BlobToken,
158 descriptor: SharedBlobDescriptor,
159 content_type: impl Into<String>,
160 ) -> Self {
161 Self {
162 sequence: None,
163 content_type: content_type.into(),
164 token,
165 descriptor,
166 }
167 }
168
169 #[must_use]
171 pub fn with_sequence(mut self, seq: u64) -> Self {
172 self.sequence = Some(seq);
173 self
174 }
175}
176
177#[derive(Debug, Clone, Serialize, Deserialize)]
179pub struct ShutdownRequest {
180 pub reason: Option<String>,
182}
183
184#[derive(Debug, Clone, Serialize, Deserialize)]
186pub struct MessageToParentRequest {
187 pub message: ParentMessage,
189}
190
191#[derive(Debug, Clone, Serialize, Deserialize)]
193pub struct MessageToParentResponse {
194 pub accepted: bool,
196 pub response: Option<Vec<u8>>,
198}
199
200#[derive(Debug, Clone, Serialize, Deserialize)]
202pub struct SpawnChildRequest {
203 pub kind: ChildKind,
205 pub init_data: Option<Vec<u8>>,
207}
208
209#[derive(Debug, Clone, Serialize, Deserialize)]
211pub struct SpawnChildResponse {
212 pub accepted: bool,
214 pub child_pid: Option<ProcessId>,
216 pub error: Option<String>,
218}
219
220#[derive(Debug, Clone, Serialize, Deserialize)]
225pub struct ProxyCallRequest {
226 pub target_pid: ProcessId,
227 pub method: crate::protocol::MethodId,
228 pub args: Vec<u8>,
229 #[serde(default)]
237 pub fd_count: u32,
238}
239
240#[derive(Debug, Clone, Serialize, Deserialize)]
242pub struct ProxyCallResponse {
243 pub ok: bool,
244 pub result: Option<Vec<u8>>,
245 pub error: Option<crate::protocol::RpcError>,
246}
247
248#[derive(Debug, Clone)]
253pub struct ParentRequestContext {
254 pub connection_id: ConnectionId,
256 pub process_kind: Option<String>,
258}
259
260#[async_trait]
265pub trait ParentMessenger: Send + Sync + std::fmt::Debug {
266 async fn send_message(
268 &self,
269 ctx: ParentRequestContext,
270 message: ParentMessage,
271 ) -> Result<MessageToParentResponse, Error>;
272
273 async fn request_spawn_child(
275 &self,
276 ctx: ParentRequestContext,
277 request: SpawnChildRequest,
278 ) -> Result<SpawnChildResponse, Error>;
279
280 async fn proxy_call(
282 &self,
283 ctx: ParentRequestContext,
284 request: ProxyCallRequest,
285 ) -> Result<ProxyCallResponse, Error>;
286}
287
288#[derive(Debug, Default)]
290pub struct MockParentMessenger {
291 messages: std::sync::Mutex<Vec<ParentMessage>>,
292 spawn_requests: std::sync::Mutex<Vec<SpawnChildRequest>>,
293}
294
295impl MockParentMessenger {
296 pub fn new() -> Self {
298 Self::default()
299 }
300
301 pub fn messages(&self) -> Vec<ParentMessage> {
303 self.messages.lock().map(|g| g.clone()).unwrap_or_default()
305 }
306
307 pub fn spawn_requests(&self) -> Vec<SpawnChildRequest> {
309 self.spawn_requests
311 .lock()
312 .map(|g| g.clone())
313 .unwrap_or_default()
314 }
315}
316#[async_trait]
317impl ParentMessenger for MockParentMessenger {
318 async fn send_message(
319 &self,
320 _ctx: ParentRequestContext,
321 message: ParentMessage,
322 ) -> Result<MessageToParentResponse, Error> {
323 if let Ok(mut guard) = self.messages.lock() {
324 guard.push(message);
325 }
326 Ok(MessageToParentResponse {
327 accepted: true,
328 response: None,
329 })
330 }
331
332 async fn request_spawn_child(
333 &self,
334 _ctx: ParentRequestContext,
335 request: SpawnChildRequest,
336 ) -> Result<SpawnChildResponse, Error> {
337 if let Ok(mut guard) = self.spawn_requests.lock() {
338 guard.push(request);
339 }
340 Ok(SpawnChildResponse {
341 accepted: true,
342 child_pid: Some(ProcessId::new()),
343 error: None,
344 })
345 }
346
347 async fn proxy_call(
348 &self,
349 _ctx: ParentRequestContext,
350 _request: ProxyCallRequest,
351 ) -> Result<ProxyCallResponse, Error> {
352 Ok(ProxyCallResponse {
353 ok: false,
354 result: None,
355 error: Some(crate::protocol::RpcError {
356 code: "not_implemented".into(),
357 message: "mock does not proxy calls".into(),
358 }),
359 })
360 }
361}
362
363#[cfg(test)]
364#[allow(
365 clippy::panic,
366 clippy::expect_used,
367 clippy::unwrap_used,
368 clippy::unwrap_in_result,
369 clippy::panic_in_result_fn,
370 clippy::indexing_slicing,
371 clippy::arithmetic_side_effects,
372 reason = "Standard repository test boilerplate"
373)]
374mod tests {
375 use super::*;
376
377 #[crate::ctb_test("tokio")]
378 async fn mock_messenger_records_messages() -> Result<()> {
379 let messenger = MockParentMessenger::new();
380
381 let ctx = ParentRequestContext {
382 connection_id: ConnectionId::default(),
383 process_kind: Some("test".into()),
384 };
385
386 messenger
387 .send_message(ctx.clone(), ParentMessage::text("hello"))
388 .await?;
389 messenger
390 .send_message(ctx.clone(), ParentMessage::text("world"))
391 .await?;
392
393 let messages = messenger.messages();
394 assert_eq!(messages.len(), 2);
395 assert_eq!(messages[0].as_text()?, "hello");
396 assert_eq!(messages[1].as_text()?, "world");
397 Ok(())
398 }
399
400 #[crate::ctb_test("tokio")]
401 async fn mock_messenger_records_spawn_requests() -> Result<()> {
402 let messenger = MockParentMessenger::new();
403
404 let ctx = ParentRequestContext {
405 connection_id: ConnectionId::default(),
406 process_kind: Some("test".into()),
407 };
408
409 let resp = messenger
410 .request_spawn_child(
411 ctx,
412 SpawnChildRequest {
413 kind: ChildKind::Renderer,
414 init_data: None,
415 },
416 )
417 .await?;
418
419 assert!(resp.accepted);
420 assert!(resp.child_pid.is_some());
421
422 let requests = messenger.spawn_requests();
423 assert_eq!(requests.len(), 1);
424 assert_eq!(requests[0].kind, ChildKind::Renderer);
425 Ok(())
426 }
427
428 #[crate::ctb_test]
429 fn data_plane_ref_roundtrip() -> Result<()> {
430 use crate::data_plane::shared_memory::SharedBlobDescriptor;
431 use shared_memory::BlobId;
432 use uuid::Uuid;
433
434 let token = BlobToken {
435 id: BlobId(Uuid::new_v4()),
436 size: 128,
437 lease_ms: None,
438 };
439 let descriptor = SharedBlobDescriptor::Named("test-blob".into());
440 let data_ref =
441 DataPlaneRef::new(token.clone(), descriptor, "text/plain");
442 let msg = ParentMessage::data_plane(&data_ref)?;
443 let decoded = msg.as_data_plane_ref()?;
444 anyhow::ensure!(decoded.token == token, "tokens should match");
445 anyhow::ensure!(
446 decoded.content_type == "text/plain",
447 "content types should match"
448 );
449 Ok(())
450 }
451}