Skip to main content

alef_component_runtime/stdio/
mod.rs

1//! Framed stdio transport for bytes-only named component contracts.
2//!
3//! An executable stays alive for its component's lifetime. Stdin and stdout carry only frames;
4//! stderr is inherited for diagnostics. A timeout or protocol failure that leaves the connection
5//! unusable terminates and reaps the child; the connection is then respawned from the verified
6//! executable on a later call, up to the manager's restart budget, re-running the describe
7//! validation and the host's session setup ([`SidecarSessionSetup`]) each time. Producer status
8//! failures leave the connection usable.
9//!
10//! The host starts the child with [`STDIO_PROTOCOLS_ENV`] listing the protocol versions it speaks
11//! (`1,2`). The first request is always a protocol-1 JSON frame: a four-byte little-endian
12//! unsigned JSON byte length, followed by `{"op":"describe"}`. Its successful response payload
13//! contains JSON matching [`StdioDescriptor`], checked against the verified artifact's manifest.
14//! The descriptor's `protocol_version` selects the framing of every later frame:
15//!
16//! * Protocol 1 ([`STDIO_PROTOCOL_VERSION`]): JSON envelopes,
17//!   `{"op":"call","contract":"name","method":"name","payload":[0,255]}` answered by
18//!   `{"status":0,"payload":[0,255]}`, with payloads as JSON byte arrays. Calls are serialized
19//!   across all contracts sharing the executable, and a timeout is fatal.
20//! * Protocol 2 ([`STDIO_BINARY_PROTOCOL_VERSION`]): binary frames ([`frame`]) carrying raw payload
21//!   bytes and a request id. A protocol-2 descriptor may add `max_in_flight` (default 1): the host
22//!   pipelines up to that many unanswered requests and the sidecar may answer them in any order.
23//!   A timeout abandons only its own request (a late response is dropped) unless the sidecar
24//!   answered nothing during the whole deadline, which is fatal.
25//!
26//! Status codes use `AlefStatus` semantics; a nonzero status carries error message bytes. The wire
27//! format is specified in `docs/design/component-stdio-binary-protocol.md`.
28//!
29//! This transport supports [`crate::LoadedComponent::invoke_bytes`]. Arbitrary generated C
30//! function tables cannot be represented across a process boundary: typed table access and
31//! typed instance creation return an explicit unsupported-transport error.
32
33mod binary;
34pub mod frame;
35mod handshake;
36mod process;
37
38pub(crate) use process::{SidecarPolicy, SidecarProcess, SidecarVerifier};
39
40use crate::{ComponentError, ComponentProvidedContract};
41use serde::{Deserialize, Serialize};
42use std::io::{Read, Write};
43use std::sync::Arc;
44
45pub use frame::{
46    BINARY_FRAME_MAGIC, BINARY_FRAME_PREFIX_LEN, BinaryFrame, BinaryFrameKind, MAX_BINARY_HEADER_SIZE,
47    RESPONSE_HEADER_LEN, decode_call_header, decode_response_header, encode_binary_frame, encode_call_header,
48    encode_response_header, read_binary_frame, write_binary_frame,
49};
50
51/// The JSON-envelope protocol every sidecar speaks for `describe`, and for every later frame when
52/// its descriptor declares this version.
53pub const STDIO_PROTOCOL_VERSION: u32 = 1;
54/// The binary-frame protocol: raw payload bytes, request ids, optional pipelining.
55pub const STDIO_BINARY_PROTOCOL_VERSION: u32 = 2;
56/// Environment variable the host sets on the child: the comma-separated protocol versions it
57/// speaks. A sidecar declares protocol 2 only when this lists `2`, so it still serves older hosts.
58pub const STDIO_PROTOCOLS_ENV: &str = "ALEF_STDIO_PROTOCOLS";
59/// Largest JSON body of a protocol-1 frame, and largest payload of a protocol-2 frame.
60pub const MAX_FRAME_SIZE: usize = 16 * 1024 * 1024;
61
62/// Metadata returned as JSON inside the successful `describe` response payload. A protocol-2
63/// descriptor may also carry `max_in_flight`, which the runtime reads separately so this type stays
64/// exactly the protocol-1 shape.
65#[derive(Debug, Clone, Serialize, Deserialize)]
66#[serde(deny_unknown_fields)]
67pub struct StdioDescriptor {
68    pub protocol_version: u32,
69    pub abi_major: u32,
70    pub abi_minor: u32,
71    pub component_id: String,
72    pub component_version: String,
73    pub feature_set_hash: String,
74    pub provides: Vec<ComponentProvidedContract>,
75}
76
77/// A request envelope. A producer must answer exactly once for every request.
78#[derive(Debug, Serialize, Deserialize)]
79#[serde(tag = "op", rename_all = "snake_case", deny_unknown_fields)]
80pub enum StdioRequest {
81    Describe,
82    Call {
83        contract: String,
84        method: String,
85        payload: Vec<u8>,
86    },
87}
88
89/// A response envelope, using the component ABI's integer status codes.
90#[derive(Debug, Serialize, Deserialize)]
91#[serde(deny_unknown_fields)]
92pub struct StdioResponse {
93    pub status: i32,
94    pub payload: Vec<u8>,
95}
96
97/// Read one complete bounded frame. EOF, including between frames, is an error.
98pub fn read_frame(reader: &mut impl Read) -> Result<Vec<u8>, ComponentError> {
99    let mut header = [0_u8; 4];
100    reader.read_exact(&mut header).map_err(protocol_io)?;
101    let length = u32::from_le_bytes(header) as usize;
102    validate_length(length)?;
103    let mut payload = vec![0; length];
104    reader.read_exact(&mut payload).map_err(protocol_io)?;
105    Ok(payload)
106}
107
108/// Write and flush one bounded frame.
109pub fn write_frame(writer: &mut impl Write, payload: &[u8]) -> Result<(), ComponentError> {
110    validate_length(payload.len())?;
111    writer
112        .write_all(&(payload.len() as u32).to_le_bytes())
113        .map_err(protocol_io)?;
114    writer.write_all(payload).map_err(protocol_io)?;
115    writer.flush().map_err(protocol_io)
116}
117
118fn validate_length(length: usize) -> Result<(), ComponentError> {
119    if length == 0 || length > MAX_FRAME_SIZE {
120        return Err(ComponentError::SidecarProtocol(format!(
121            "frame length {length} is outside 1..={MAX_FRAME_SIZE}"
122        )));
123    }
124    Ok(())
125}
126
127/// One stdio connection as seen by a host's session setup: a [`SidecarSessionSetup`] receives it
128/// once a sidecar child has started and passed describe validation, and calls
129/// [`SidecarSession::invoke`] to re-establish whatever session the host had built on the previous
130/// connection.
131pub struct SidecarSession<'a> {
132    pub(crate) process: &'a SidecarProcess,
133}
134
135impl SidecarSession<'_> {
136    /// Invoke a bytes-only method on the connection's component, as
137    /// [`crate::LoadedComponent::invoke_bytes`] does.
138    pub fn invoke(&self, contract: &str, method: &str, payload: &[u8]) -> Result<Vec<u8>, ComponentError> {
139        self.process.invoke_for_session(contract, method, payload)
140    }
141}
142
143/// Host-provided setup for a stdio sidecar connection, replayed after the first spawn and after
144/// every respawn of the connection (see [`crate::ComponentManager::with_sidecar_session`]).
145pub type SidecarSessionSetup = Arc<dyn Fn(&SidecarSession) -> Result<(), ComponentError> + Send + Sync>;
146
147/// Handler called with the component id and the new restart count after each successful stdio
148/// respawn (see [`crate::ComponentManager::with_sidecar_restart_event`]).
149pub type SidecarRestartEvent = Arc<dyn Fn(&str, u32) + Send + Sync>;
150
151fn protocol_io(error: std::io::Error) -> ComponentError {
152    ComponentError::SidecarProtocol(format!("frame I/O failed: {error}"))
153}