1#[allow(
27 unused_imports,
28 clippy::wildcard_imports,
29 reason = "Standard workspace module prelude"
30)]
31use crate::utilities::*;
32
33use crate::auth::capability::{CapabilitySet, CapabilityToken};
34use crate::shared_memory::BlobToken;
35use crate::types::{RequestId, StreamId};
36use serde::{Deserialize, Serialize};
37
38#[derive(Debug, Clone, Serialize, Deserialize)]
40pub enum Message {
41 Hello(Hello),
43 HelloOk(HelloOk),
45 HelloErr(HelloErr),
46
47 Request(Request),
49 Response(Response),
51
52 Event(Event),
54
55 Stream(StreamControl),
57
58 Cancel(Cancel),
60}
61
62#[derive(Debug, Clone, Serialize, Deserialize)]
64pub struct Hello {
65 pub token: CapabilityToken,
66 pub client_info: Option<ClientInfo>,
68}
69
70#[derive(Debug, Clone, Serialize, Deserialize)]
71pub struct ClientInfo {
72 pub name: String,
73 pub version: String,
74 pub process_kind: String,
75}
76
77#[derive(Debug, Clone, Serialize, Deserialize)]
78pub struct HelloOk {
79 pub bound_capabilities: CapabilitySet,
80}
81
82#[derive(Debug, Clone, Serialize, Deserialize)]
83pub struct HelloErr {
84 pub message: String,
85}
86
87#[derive(Debug, Clone, Serialize, Deserialize)]
89pub struct Request {
90 pub id: RequestId,
91 pub method: MethodId,
92 pub args: Vec<u8>,
94}
95
96#[derive(Debug, Clone, Serialize, Deserialize)]
98pub struct Response {
99 pub id: RequestId,
100 pub ok: bool,
101 pub result: Option<Vec<u8>>,
103 pub error: Option<RpcError>,
105}
106
107#[derive(Debug, Clone, Serialize, Deserialize)]
108pub struct RpcError {
109 pub code: String,
110 pub message: String,
111}
112
113#[derive(Debug, Clone, Serialize, Deserialize)]
116pub struct Event {
117 pub topic: EventTopic,
118 pub payload: Vec<u8>,
120}
121
122impl Event {
123 pub fn heartbeat() -> Self {
125 Self {
126 topic: EventTopic::Heartbeat,
127 payload: Vec::new(),
128 }
129 }
130}
131
132#[derive(Debug, Clone, Serialize, Deserialize)]
133pub enum EventTopic {
134 Heartbeat,
135 ChildExited,
136 PermissionChanged,
137 StorageCompacted,
138 Custom(String),
139}
140
141#[derive(Debug, Clone, Serialize, Deserialize)]
143pub enum StreamControl {
144 Start {
145 id: StreamId,
146 blob: Option<BlobToken>,
148 },
149 Next {
150 id: StreamId,
151 chunk: Option<Vec<u8>>,
153 },
154 End {
155 id: StreamId,
156 ok: bool,
157 error: Option<String>,
158 },
159}
160
161#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
163pub struct MethodId {
164 pub service: String,
165 pub method: String,
166}
167
168#[derive(Debug, Clone, Serialize, Deserialize)]
170pub struct Cancel {
171 pub id: RequestId,
172}
173
174impl Hello {
175 pub fn new(
177 token: CapabilityToken,
178 client_info: Option<ClientInfo>,
179 ) -> Self {
180 Self { token, client_info }
181 }
182}
183
184impl HelloOk {
185 pub fn new(bound_capabilities: CapabilitySet) -> Self {
187 Self { bound_capabilities }
188 }
189}
190
191impl HelloErr {
192 pub fn new<S: Into<String>>(message: S) -> Self {
194 Self {
195 message: message.into(),
196 }
197 }
198}
199
200impl MethodId {
202 pub fn new<S1, S2>(service: S1, method: S2) -> Self
203 where
204 S1: Into<String>,
205 S2: Into<String>,
206 {
207 Self {
208 service: service.into(),
209 method: method.into(),
210 }
211 }
212}
213
214impl RpcError {
215 pub fn unauthorized<S: Into<String>>(message: S) -> Self {
217 Self {
218 code: RPC_ERROR_CODE_UNAUTHORIZED.into(),
219 message: message.into(),
220 }
221 }
222
223 pub fn capability_denied<S: Into<String>>(message: S) -> Self {
225 Self {
226 code: RPC_ERROR_CODE_CAPABILITY_DENIED.into(),
227 message: message.into(),
228 }
229 }
230
231 pub fn cancelled<S: Into<String>>(message: S) -> Self {
233 Self {
234 code: RPC_ERROR_CODE_CANCELLED.into(),
235 message: message.into(),
236 }
237 }
238
239 pub fn internal<S: Into<String>>(message: S) -> Self {
241 Self {
242 code: RPC_ERROR_CODE_INTERNAL.into(),
243 message: message.into(),
244 }
245 }
246}
247
248impl Cancel {
249 pub fn new(id: RequestId) -> Self {
251 Self { id }
252 }
253}
254
255pub const RPC_ERROR_CODE_UNAUTHORIZED: &str = "unauthorized";
257pub const RPC_ERROR_CODE_CAPABILITY_DENIED: &str = "capability_denied";
258pub const RPC_ERROR_CODE_RATE_LIMITED: &str = "rate_limited";
259pub const RPC_ERROR_CODE_CANCELLED: &str = "cancelled";
260pub const RPC_ERROR_CODE_INTERNAL: &str = "internal";
261pub const RPC_ERROR_CODE_NOT_IMPLEMENTED: &str = "not_implemented";
262
263pub const IO_NETWORK_BLOB_THRESHOLD_BYTES: u64 = 256 * 1024;
268
269pub const STREAM_CONTROL_PLANE_CHUNK_BYTES: usize = 16 * 1024;
271
272impl Request {
273 #[must_use]
278 pub fn span(&self) -> tracing::Span {
279 tracing::info_span!(
280 "ipc.request",
281 request_id = self.id,
282 service = %self.method.service,
283 method = %self.method.method
284 )
285 }
286}
287
288impl StreamControl {
289 #[must_use]
291 pub fn stream_id(&self) -> StreamId {
292 match self {
293 StreamControl::Start { id, .. } => *id,
294 StreamControl::Next { id, .. } => *id,
295 StreamControl::End { id, .. } => *id,
296 }
297 }
298
299 #[must_use]
304 pub fn span(&self) -> tracing::Span {
305 match self {
306 StreamControl::Start { id, blob } => tracing::info_span!(
307 "ipc.stream",
308 stream_id = *id,
309 variant = "start",
310 blob_id =
311 blob.as_ref().map(|b| b.id).map(tracing::field::display),
312 blob_size = blob.as_ref().map(|b| b.size),
313 blob_lease_ms = blob.as_ref().and_then(|b| b.lease_ms),
314 ),
315 StreamControl::Next { id, chunk } => tracing::info_span!(
316 "ipc.stream",
317 stream_id = *id,
318 variant = "next",
319 chunk_len = chunk.as_ref().map(std::vec::Vec::len),
320 ),
321 StreamControl::End { id, ok, error } => tracing::info_span!(
322 "ipc.stream",
323 stream_id = *id,
324 variant = "end",
325 ok = *ok,
326 error = error.as_deref(),
327 ),
328 }
329 }
330}
331
332#[cfg(test)]
333#[allow(
334 clippy::panic,
335 clippy::expect_used,
336 clippy::unwrap_used,
337 clippy::unwrap_in_result,
338 clippy::panic_in_result_fn,
339 clippy::indexing_slicing,
340 clippy::arithmetic_side_effects,
341 reason = "Standard repository test boilerplate"
342)]
343mod tests {
344 use super::*;
345 use anyhow::{Result, ensure};
346
347 use std::collections::HashMap;
348 use std::sync::Mutex;
349 use tracing::field::{Field, Visit};
350 use tracing_subscriber::layer::{Context as LayerContext, Layer};
351
352 use tracing_subscriber::registry::LookupSpan;
353
354 #[derive(Default)]
355 struct FieldCaptureVisitor {
356 fields: HashMap<String, String>,
357 }
358
359 impl Visit for FieldCaptureVisitor {
360 fn record_str(&mut self, field: &Field, value: &str) {
361 let _ = self
362 .fields
363 .insert(field.name().to_string(), value.to_string());
364 }
365
366 fn record_u64(&mut self, field: &Field, value: u64) {
367 let _ = self
368 .fields
369 .insert(field.name().to_string(), value.to_string());
370 }
371
372 fn record_i64(&mut self, field: &Field, value: i64) {
373 let _ = self
374 .fields
375 .insert(field.name().to_string(), value.to_string());
376 }
377
378 fn record_bool(&mut self, field: &Field, value: bool) {
379 let _ = self
380 .fields
381 .insert(field.name().to_string(), value.to_string());
382 }
383
384 fn record_debug(&mut self, field: &Field, value: &dyn std::fmt::Debug) {
385 let _ = self
386 .fields
387 .insert(field.name().to_string(), format!("{value:?}"));
388 }
389 }
390
391 #[derive(Default)]
392 struct CaptureLayer {
393 spans: Mutex<HashMap<tracing::span::Id, HashMap<String, String>>>,
394 events: Mutex<Vec<HashMap<String, String>>>,
395 }
396
397 impl CaptureLayer {
398 fn drain_events(&self) -> Vec<HashMap<String, String>> {
399 if let Ok(mut guard) = self.events.lock() {
400 std::mem::take(&mut *guard)
401 } else {
402 Vec::new()
403 }
404 }
405 }
406
407 impl<S> Layer<S> for CaptureLayer
408 where
409 S: tracing::Subscriber + for<'a> LookupSpan<'a>,
410 {
411 fn on_new_span(
412 &self,
413 attrs: &tracing::span::Attributes<'_>,
414 id: &tracing::span::Id,
415 _ctx: LayerContext<'_, S>,
416 ) {
417 let mut v = FieldCaptureVisitor::default();
418 attrs.record(&mut v);
419
420 if let Ok(mut spans) = self.spans.lock() {
421 let _ = spans.insert(id.clone(), v.fields);
422 }
423 }
424
425 fn on_event(
426 &self,
427 event: &tracing::Event<'_>,
428 ctx: LayerContext<'_, S>,
429 ) {
430 let mut merged: HashMap<String, String> = HashMap::new();
431
432 if let Some(scope) = ctx.event_scope(event)
433 && let Ok(spans) = self.spans.lock()
434 {
435 for span in scope.from_root() {
436 if let Some(fields) = spans.get(&span.id()) {
437 merged.extend(fields.clone());
438 }
439 }
440 }
441
442 let mut v = FieldCaptureVisitor::default();
443 event.record(&mut v);
444 merged.extend(v.fields);
445
446 if let Ok(mut events) = self.events.lock() {
447 events.push(merged);
448 }
449 }
450 }
451
452 #[crate::ctb_test]
453 fn spans_attach_request_and_stream_fields() -> Result<()> {
454 let req = Request {
458 id: 42,
459 method: MethodId::new("svc", "do_work"),
460 args: vec![],
461 };
462
463 let stream = StreamControl::Start {
464 id: 7,
465 blob: Some(BlobToken {
466 id: Default::default(),
467 size: 123,
468 lease_ms: Some(456),
469 }),
470 };
471
472 req.span().in_scope(|| {
473 tracing::info!("inside request span");
474 });
475
476 stream.span().in_scope(|| {
477 tracing::info!("inside stream span");
478 });
479
480 assert!(logs_contain("inside request span"));
482 assert!(logs_contain("inside stream span"));
483
484 Ok(())
485 }
486
487 fn roundtrip_bytes<T>(value: &T) -> Result<()>
489 where
490 T: serde::Serialize + for<'de> serde::de::Deserialize<'de>,
491 {
492 let bytes = postcard_helpers::encode(value, "test value")?;
493 let decoded: T = postcard_helpers::decode(&bytes, "test value")?;
494 let bytes2 = postcard_helpers::encode(&decoded, "test value")?;
495 ensure!(bytes == bytes2, "postcard roundtrip bytes mismatch");
496 Ok(())
497 }
498
499 #[crate::ctb_test]
501 fn message_hello_roundtrip() -> Result<()> {
502 let msg = Message::Hello(Hello {
503 token: Default::default(),
504 client_info: Some(ClientInfo {
505 name: "client".into(),
506 version: "1.0.0".into(),
507 process_kind: "test".into(),
508 }),
509 });
510 roundtrip_bytes(&msg)
511 }
512
513 #[crate::ctb_test]
515 fn message_hello_ok_roundtrip() -> Result<()> {
516 let msg = Message::HelloOk(HelloOk {
517 bound_capabilities: Default::default(),
518 });
519 roundtrip_bytes(&msg)
520 }
521
522 #[crate::ctb_test]
524 fn message_hello_err_roundtrip() -> Result<()> {
525 let msg = Message::HelloErr(HelloErr {
526 message: "handshake failed".into(),
527 });
528 roundtrip_bytes(&msg)
529 }
530
531 #[crate::ctb_test]
533 fn message_request_roundtrip() -> Result<()> {
534 let msg = Message::Request(Request {
535 id: Default::default(),
536 method: MethodId {
537 service: "svc".into(),
538 method: "do_work".into(),
539 },
540 args: vec![0x01, 0x02, 0x03],
541 });
542 roundtrip_bytes(&msg)
543 }
544
545 #[crate::ctb_test]
547 fn message_response_ok_roundtrip() -> Result<()> {
548 let msg = Message::Response(Response {
549 id: Default::default(),
550 ok: true,
551 result: Some(vec![0xAA, 0xBB]),
552 error: None,
553 });
554 roundtrip_bytes(&msg)
555 }
556
557 #[crate::ctb_test]
559 fn message_response_err_roundtrip() -> Result<()> {
560 let msg = Message::Response(Response {
561 id: Default::default(),
562 ok: false,
563 result: None,
564 error: Some(RpcError {
565 code: "bad_request".into(),
566 message: "invalid input".into(),
567 }),
568 });
569 roundtrip_bytes(&msg)
570 }
571
572 #[crate::ctb_test]
574 fn message_event_roundtrip() -> Result<()> {
575 let msg = Message::Event(Event {
576 topic: EventTopic::Custom("custom.topic".into()),
577 payload: vec![0x10, 0x20],
578 });
579 roundtrip_bytes(&msg)
580 }
581
582 #[crate::ctb_test]
584 fn message_event_heartbeat_roundtrip() -> Result<()> {
585 let msg = Message::Event(Event::heartbeat());
586 roundtrip_bytes(&msg)
587 }
588
589 #[crate::ctb_test]
591 fn message_stream_start_roundtrip() -> Result<()> {
592 let msg = Message::Stream(StreamControl::Start {
593 id: Default::default(),
594 blob: Some(Default::default()),
595 });
596 roundtrip_bytes(&msg)
597 }
598
599 #[crate::ctb_test]
601 fn message_stream_next_roundtrip() -> Result<()> {
602 let msg = Message::Stream(StreamControl::Next {
603 id: Default::default(),
604 chunk: Some(vec![1, 2, 3, 4]),
605 });
606 roundtrip_bytes(&msg)
607 }
608
609 #[crate::ctb_test]
611 fn message_stream_end_roundtrip() -> Result<()> {
612 let msg = Message::Stream(StreamControl::End {
613 id: Default::default(),
614 ok: false,
615 error: Some("stream error".into()),
616 });
617 roundtrip_bytes(&msg)
618 }
619
620 #[crate::ctb_test]
622 fn message_cancel_roundtrip() -> Result<()> {
623 let msg = Message::Cancel(Cancel {
624 id: Default::default(),
625 });
626 roundtrip_bytes(&msg)
627 }
628}