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; producer status failures leave the connection usable.
8//!
9//! The first request is `{"op":"describe"}`. Its successful response payload contains JSON
10//! matching [`StdioDescriptor`], checked against the verified artifact's manifest. Subsequent
11//! requests use `{"op":"call","contract":"name","method":"name","payload":[0,255]}`.
12//! Every response is `{"status":0,"payload":[0,255]}`. Status codes use `AlefStatus` semantics;
13//! a nonzero status carries error message bytes. Payloads are JSON byte arrays, not base64.
14//!
15//! This transport supports [`crate::LoadedComponent::invoke_bytes`]. Arbitrary generated C
16//! function tables cannot be represented across a process boundary: typed table access and
17//! typed instance creation return an explicit unsupported-transport error.
18
19mod process;
20
21pub(crate) use process::SidecarProcess;
22
23use crate::{ComponentError, ComponentProvidedContract};
24use serde::{Deserialize, Serialize};
25use std::io::{Read, Write};
26
27pub const STDIO_PROTOCOL_VERSION: u32 = 1;
28pub const MAX_FRAME_SIZE: usize = 16 * 1024 * 1024;
29
30/// Metadata returned as JSON inside the successful `describe` response payload.
31#[derive(Debug, Clone, Serialize, Deserialize)]
32#[serde(deny_unknown_fields)]
33pub struct StdioDescriptor {
34    pub protocol_version: u32,
35    pub abi_major: u32,
36    pub abi_minor: u32,
37    pub component_id: String,
38    pub component_version: String,
39    pub feature_set_hash: String,
40    pub provides: Vec<ComponentProvidedContract>,
41}
42
43/// A request envelope. A producer must answer exactly once for every request.
44#[derive(Debug, Serialize, Deserialize)]
45#[serde(tag = "op", rename_all = "snake_case", deny_unknown_fields)]
46pub enum StdioRequest {
47    Describe,
48    Call {
49        contract: String,
50        method: String,
51        payload: Vec<u8>,
52    },
53}
54
55/// A response envelope, using the component ABI's integer status codes.
56#[derive(Debug, Serialize, Deserialize)]
57#[serde(deny_unknown_fields)]
58pub struct StdioResponse {
59    pub status: i32,
60    pub payload: Vec<u8>,
61}
62
63/// Read one complete bounded frame. EOF, including between frames, is an error.
64pub fn read_frame(reader: &mut impl Read) -> Result<Vec<u8>, ComponentError> {
65    let mut header = [0_u8; 4];
66    reader.read_exact(&mut header).map_err(protocol_io)?;
67    let length = u32::from_le_bytes(header) as usize;
68    validate_length(length)?;
69    let mut payload = vec![0; length];
70    reader.read_exact(&mut payload).map_err(protocol_io)?;
71    Ok(payload)
72}
73
74/// Write and flush one bounded frame.
75pub fn write_frame(writer: &mut impl Write, payload: &[u8]) -> Result<(), ComponentError> {
76    validate_length(payload.len())?;
77    writer
78        .write_all(&(payload.len() as u32).to_le_bytes())
79        .map_err(protocol_io)?;
80    writer.write_all(payload).map_err(protocol_io)?;
81    writer.flush().map_err(protocol_io)
82}
83
84fn validate_length(length: usize) -> Result<(), ComponentError> {
85    if length == 0 || length > MAX_FRAME_SIZE {
86        return Err(ComponentError::SidecarProtocol(format!(
87            "frame length {length} is outside 1..={MAX_FRAME_SIZE}"
88        )));
89    }
90    Ok(())
91}
92
93fn protocol_io(error: std::io::Error) -> ComponentError {
94    ComponentError::SidecarProtocol(format!("frame I/O failed: {error}"))
95}