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//! a four-byte little-endian unsigned JSON byte length, followed by that JSON. Stderr is
5//! inherited for diagnostics. Frames are bounded by [`MAX_FRAME_SIZE`]. Calls are serialized
6//! across all contracts sharing the executable. A timeout or protocol failure terminates and
7//! reaps the child; the connection is then respawned from the verified executable on a later
8//! call, up to the manager's restart budget, re-running the describe validation and the host's
9//! session setup ([`SidecarSessionSetup`]) each time. Producer status failures leave the
10//! connection usable.
11//!
12//! The first request is `{"op":"describe"}`. Its successful response payload contains JSON
13//! matching [`StdioDescriptor`], checked against the verified artifact's manifest. Subsequent
14//! requests use `{"op":"call","contract":"name","method":"name","payload":[0,255]}`.
15//! Every response is `{"status":0,"payload":[0,255]}`. Status codes use `AlefStatus` semantics;
16//! a nonzero status carries error message bytes. Payloads are JSON byte arrays, not base64.
17//!
18//! This transport supports [`crate::LoadedComponent::invoke_bytes`]. Arbitrary generated C
19//! function tables cannot be represented across a process boundary: typed table access and
20//! typed instance creation return an explicit unsupported-transport error.
21
22mod process;
23
24pub(crate) use process::{SidecarPolicy, SidecarProcess};
25
26use crate::{ComponentError, ComponentProvidedContract};
27use serde::{Deserialize, Serialize};
28use std::io::{Read, Write};
29use std::sync::Arc;
30
31pub const STDIO_PROTOCOL_VERSION: u32 = 1;
32pub const MAX_FRAME_SIZE: usize = 16 * 1024 * 1024;
33
34/// Metadata returned as JSON inside the successful `describe` response payload.
35#[derive(Debug, Clone, Serialize, Deserialize)]
36#[serde(deny_unknown_fields)]
37pub struct StdioDescriptor {
38    pub protocol_version: u32,
39    pub abi_major: u32,
40    pub abi_minor: u32,
41    pub component_id: String,
42    pub component_version: String,
43    pub feature_set_hash: String,
44    pub provides: Vec<ComponentProvidedContract>,
45}
46
47/// A request envelope. A producer must answer exactly once for every request.
48#[derive(Debug, Serialize, Deserialize)]
49#[serde(tag = "op", rename_all = "snake_case", deny_unknown_fields)]
50pub enum StdioRequest {
51    Describe,
52    Call {
53        contract: String,
54        method: String,
55        payload: Vec<u8>,
56    },
57}
58
59/// A response envelope, using the component ABI's integer status codes.
60#[derive(Debug, Serialize, Deserialize)]
61#[serde(deny_unknown_fields)]
62pub struct StdioResponse {
63    pub status: i32,
64    pub payload: Vec<u8>,
65}
66
67/// Read one complete bounded frame. EOF, including between frames, is an error.
68pub fn read_frame(reader: &mut impl Read) -> Result<Vec<u8>, ComponentError> {
69    let mut header = [0_u8; 4];
70    reader.read_exact(&mut header).map_err(protocol_io)?;
71    let length = u32::from_le_bytes(header) as usize;
72    validate_length(length)?;
73    let mut payload = vec![0; length];
74    reader.read_exact(&mut payload).map_err(protocol_io)?;
75    Ok(payload)
76}
77
78/// Write and flush one bounded frame.
79pub fn write_frame(writer: &mut impl Write, payload: &[u8]) -> Result<(), ComponentError> {
80    validate_length(payload.len())?;
81    writer
82        .write_all(&(payload.len() as u32).to_le_bytes())
83        .map_err(protocol_io)?;
84    writer.write_all(payload).map_err(protocol_io)?;
85    writer.flush().map_err(protocol_io)
86}
87
88fn validate_length(length: usize) -> Result<(), ComponentError> {
89    if length == 0 || length > MAX_FRAME_SIZE {
90        return Err(ComponentError::SidecarProtocol(format!(
91            "frame length {length} is outside 1..={MAX_FRAME_SIZE}"
92        )));
93    }
94    Ok(())
95}
96
97/// One stdio connection as seen by a host's session setup: a [`SidecarSessionSetup`] receives it
98/// once a sidecar child has started and passed describe validation, and calls
99/// [`SidecarSession::invoke`] to re-establish whatever session the host had built on the previous
100/// connection.
101pub struct SidecarSession<'a> {
102    pub(crate) process: &'a SidecarProcess,
103}
104
105impl SidecarSession<'_> {
106    /// Invoke a bytes-only method on the connection's component, as
107    /// [`crate::LoadedComponent::invoke_bytes`] does.
108    pub fn invoke(&self, contract: &str, method: &str, payload: &[u8]) -> Result<Vec<u8>, ComponentError> {
109        self.process.invoke_for_session(contract, method, payload)
110    }
111}
112
113/// Host-provided setup for a stdio sidecar connection, replayed after the first spawn and after
114/// every respawn of the connection (see [`crate::ComponentManager::with_sidecar_session`]).
115pub type SidecarSessionSetup = Arc<dyn Fn(&SidecarSession) -> Result<(), ComponentError> + Send + Sync>;
116
117/// Handler called with the component id and the new restart count after each successful stdio
118/// respawn (see [`crate::ComponentManager::with_sidecar_restart_event`]).
119pub type SidecarRestartEvent = Arc<dyn Fn(&str, u32) + Send + Sync>;
120
121fn protocol_io(error: std::io::Error) -> ComponentError {
122    ComponentError::SidecarProtocol(format!("frame I/O failed: {error}"))
123}