Files
leleka/control-plane/src/responses/stream.rs
T
Pavlo Ratushnyi 35bf3a03d3 STRA-338 S16: gateway ports (EngineClient, ResponseStore, Clock, ToolHub, VisionEncoder) with adapters and fakes
AppState now holds ports instead of concrete types: `engine: Option<SharedEngine>` replaces the
mpsc::Sender<GenerationCommand>, `responses: SharedResponseStore` replaces Arc<RwLock<ResponseHistory>>,
`clock: SharedClock` serves queue deadlines, uptime and response timestamps, `mcp` is a ToolHub and `vision` a
VisionEncoder. The channel (adapters::ChannelEngine), the history with its disk snapshot
(responses::HistoryResponseStore), the system clock, mcp::Hub and vision::Vision are the adapters; main.rs serve()
composes them. No behaviour change: the HTTP handlers make the same calls in the same order, the queue claim race is
unchanged, only the deadline now reads the injected clock.

Ports are called per request, never per token or stream event (docs/architecture/gateway-ports.md).
ports/fakes has an in-memory adapter per port; control-plane/tests/ports_fakes.rs (12 tests), queue.rs and
adapters/channel_engine.rs add tests that drive the real handlers through them.

Architecture gate: dyn-trait:strata-control fell 35 -> 21 (a BoxError alias replaces 20 `Box<dyn Error>` spellings,
which pays for the 6 new port aliases); main.rs 1156 -> 1155 lines. Also adds scripts/dev/test-outcomes.py (per-test
outcome comparison of two cargo test logs) and scripts/dev/wsl-cargo.sh.
2026-11-05 20:06:28 +01:00

99 lines
3.0 KiB
Rust

//! Server-sent-event streaming of a Responses API generation: plain text, buffered and tool calls.
//! Moved out of responses.rs (STRA-338 S6); everything here is private to the `responses` module tree.
use super::*;
mod buffered;
mod text;
mod tools;
pub(super) use buffered::stream_live_buffered;
pub(super) use text::stream_live_text;
pub(super) use tools::stream_live_tools;
/// What a stream needs from outside once per response: where to store the finished response (`None`: nowhere) and
/// the clock its timestamps and id come from. Both are called at the start and the end of a stream, never per event.
#[derive(Clone)]
pub(crate) struct StreamEnv {
pub store: Option<SharedResponseStore>,
pub clock: SharedClock,
}
impl StreamEnv {
/// No store, system clock.
#[cfg(test)]
pub(crate) fn none() -> Self {
Self {
store: None,
clock: crate::adapters::SystemClock::shared(),
}
}
/// Seconds since the epoch and the same moment with nanoseconds, the form response ids use.
fn now(&self) -> std::time::Duration {
self.clock.unix_time()
}
}
pub(super) struct ResponseEventStream {
receiver: mpsc::Receiver<Value>,
}
impl Stream for ResponseEventStream {
type Item = Result<SseEvent, Infallible>;
fn poll_next(mut self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll<Option<Self::Item>> {
Pin::new(&mut self.receiver).poll_recv(context).map(|item| {
item.map(|value| {
let kind = value["type"].as_str().unwrap_or("error").to_owned();
Ok(SseEvent::default().event(kind).data(value.to_string()))
})
})
}
}
pub(super) fn drain_utf8(pending: &mut Vec<u8>, finish: bool) -> String {
let mut output = String::new();
while !pending.is_empty() {
match std::str::from_utf8(pending) {
Ok(text) => {
output.push_str(text);
pending.clear();
}
Err(error) => {
let valid = error.valid_up_to();
if valid > 0 {
output.push_str(std::str::from_utf8(&pending[..valid]).expect("UTF-8 prefix"));
pending.drain(..valid);
}
if let Some(invalid) = error.error_len() {
output.push('\u{fffd}');
pending.drain(..invalid);
} else if finish {
output.push('\u{fffd}');
pending.clear();
} else {
break;
}
}
}
}
output
}
pub(super) async fn send_stream_event(
sender: &mpsc::Sender<Value>,
sequence: &mut usize,
kind: &'static str,
fields: Value,
) -> bool {
let mut value = fields
.as_object()
.cloned()
.expect("event fields are an object");
value.insert("type".to_owned(), json!(kind));
value.insert("sequence_number".to_owned(), json!(*sequence));
*sequence += 1;
sender.send(Value::Object(value)).await.is_ok()
}