Compress tool outputs, logs, files, and RAG chunks before they reach the LLM. 20% fewer tokens for coding agents, 60-95% fewer tokens for JSON, same answers. Library, proxy, MCP server.
Python agentaianthropicclaude-codecompressioncontext-engineeringcontext-windowcursorfastapilangchainllmmcpopenaiprompt-engineeringproxypythonragtoken-optimizationtokenstypescript
fix(proxy): PR-D2 Bedrock streaming via binary EventStream
chopratejas66426e7b75a7
diff --git a/Cargo.lock b/Cargo.lockindex f8dd61b8e..121f92ffb 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -1856,6 +1856,7 @@ dependencies = ["bytes","bytesize","clap",+ "crc32fast","futures","futures-util","headroom-core",diff --git a/crates/headroom-proxy/Cargo.toml b/crates/headroom-proxy/Cargo.tomlindex ff0c21358..c35039ecf 100644--- a/crates/headroom-proxy/Cargo.toml+++ b/crates/headroom-proxy/Cargo.toml@@ -47,6 +47,12 @@ aws-sigv4 = { workspace = true }aws-config = { workspace = true }aws-credential-types = { workspace = true }aws-smithy-runtime-api = { workspace = true }+# Phase D PR-D2: Bedrock binary EventStream parser. AWS frames each+# message with a CRC32 over the prelude and over the entire message;+# `crc32fast` is the standard IEEE 802.3 implementation already+# transitively pulled in by `aws-smithy-*` (so this is not an+# additional cold dep — promoting to a direct one for clarity).+crc32fast = "1"[dev-dependencies]tower = { workspace = true, features = ["util"] }diff --git a/crates/headroom-proxy/src/bedrock/eventstream.rs b/crates/headroom-proxy/src/bedrock/eventstream.rsnew file mode 100644index 000000000..31c161d84--- /dev/null+++ b/crates/headroom-proxy/src/bedrock/eventstream.rs@@ -0,0 +1,769 @@+//! Incremental binary EventStream parser — Phase D PR-D2.+//!+//! # What this parses+//!+//! AWS Bedrock's streaming surface (`/model/{id}/invoke-with-response-stream`)+//! returns `application/vnd.amazon.eventstream` framed messages, NOT+//! Server-Sent Events. Each message is:+//!+//! ```text+//! +------------------+----------------------+------------------++//! | prelude (12B) | headers (N1 B) | payload (N2 B) | + 4-byte CRC32+//! +------------------+----------------------+------------------++//! ```+//!+//! Where the prelude is three big-endian u32s:+//!+//! - `total_length` (bytes from start-of-message up to AND including+//! the trailing message CRC32),+//! - `headers_length` (bytes occupied by the headers block),+//! - `prelude_crc32` (CRC32 of the first 8 bytes of the prelude).+//!+//! The payload length is computed: `total_length - 12 - headers_length - 4`.+//!+//! Each header is `[name_len: u8][name (UTF-8)][value_type: u8][value]`.+//! AWS defines 10 value types but Bedrock in practice only emits a handful:+//!+//! - `7` — UTF-8 string with `[u16 BE length][bytes]`+//! - `6` — byte array with `[u16 BE length][bytes]`+//!+//! We support both because Bedrock's `:event-type`, `:content-type`,+//! and `:message-type` come through as type-7 strings, and the payload+//! carries an embedded JSON document as a UTF-8 string AT THE PAYLOAD+//! LEVEL (not as a header value).+//!+//! # Why a stateful struct+//!+//! TCP delivers chunks at unpredictable boundaries — a single+//! EventStream message can arrive in any number of pieces, and one+//! `Bytes` chunk can also contain multiple complete messages plus a+//! partial trailing one. The parser MUST resume across chunks without+//! losing bytes; we accumulate into an internal buffer and yield+//! complete messages as they materialise. Same incremental contract+//! as `sse::framing::SseFramer` (Phase C) — that's the model.+//!+//! # No panics, no fallbacks+//!+//! Per `feedback_no_silent_fallbacks.md`: this parser ALWAYS returns a+//! `Result`. CRC mismatch → [`ParseError::PreludeCrcMismatch`] /+//! [`ParseError::MessageCrcMismatch`]; truncated prelude with absurd+//! lengths → [`ParseError::ImplausiblePreludeLengths`]. The handler+//! turns errors into 5xx responses — we never silently swallow a+//! malformed frame and forward zeros to the client.++use std::collections::HashMap;++use bytes::{Buf, Bytes, BytesMut};+use thiserror::Error;++/// AWS-defined header value types. Bedrock today only uses `7`+/// (string) and `6` (byte buffer); the others are listed for+/// completeness so a future Bedrock surface that emits them does+/// not require a parser revision.+mod header_type {+ pub const TRUE: u8 = 0;+ pub const FALSE: u8 = 1;+ pub const BYTE: u8 = 2;+ pub const SHORT: u8 = 3;+ pub const INTEGER: u8 = 4;+ pub const LONG: u8 = 5;+ pub const BYTE_ARRAY: u8 = 6;+ pub const STRING: u8 = 7;+ pub const TIMESTAMP: u8 = 8;+ pub const UUID: u8 = 9;+}++/// Length of the 3-u32 prelude in bytes.+const PRELUDE_LEN: usize = 12;++/// CRC32 trails the message and is itself 4 bytes, NOT counted in+/// `headers_length` but counted in `total_length`.+const MESSAGE_CRC_LEN: usize = 4;++/// Sanity ceiling for `total_length`. AWS's documented maximum is+/// 16 MiB. We refuse anything beyond ~32 MiB (2× headroom for future+/// limit raises) so a truncated stream that decoded a garbage length+/// does not allocate gigabytes. Configurable via the public+/// [`EventStreamParser::with_max_message_bytes`] constructor.+const DEFAULT_MAX_MESSAGE_BYTES: usize = 32 * 1024 * 1024;++/// One value carried in an EventStream header. AWS defines 10 wire+/// types; today Bedrock emits two (string + byte-buffer). We expose+/// the variants we actually parse and surface a structured error for+/// any other type so the caller can log it loudly.+#[derive(Debug, Clone, PartialEq, Eq)]+pub enum HeaderValue {+ /// `header_type::STRING` — UTF-8 string.+ String(String),+ /// `header_type::BYTE_ARRAY` — opaque bytes.+ Bytes(Bytes),+}++impl HeaderValue {+ /// Cheap accessor for the common `event_name == "chunk"` style+ /// dispatch. Returns `Some` only for [`HeaderValue::String`].+ pub fn as_str(&self) -> Option<&str> {+ match self {+ HeaderValue::String(s) => Some(s.as_str()),+ HeaderValue::Bytes(_) => None,+ }+ }+}++/// One complete EventStream message.+#[derive(Debug, Clone)]+pub struct EventStreamMessage {+ /// Headers, lower-cased keys for stable lookup. Bedrock spec+ /// headers (`:event-type`, `:content-type`, `:message-type`) are+ /// already lower-case but we normalise defensively.+ pub headers: HashMap<String, HeaderValue>,+ /// Raw payload bytes. The semantic meaning depends on+ /// `:event-type` — for Bedrock Anthropic streaming responses each+ /// `chunk` payload is a UTF-8 JSON string carrying one Anthropic+ /// SSE event.+ pub payload: Bytes,+}++impl EventStreamMessage {+ /// Read the `:event-type` header as a string. Convenience for the+ /// translator. Returns `None` if missing or not a string.+ pub fn event_type(&self) -> Option<&str> {+ self.headers.get(":event-type").and_then(|v| v.as_str())+ }++ /// Read the `:message-type` header as a string. Bedrock uses+ /// `event` (data frames) vs `exception` (synchronous errors).+ pub fn message_type(&self) -> Option<&str> {+ self.headers.get(":message-type").and_then(|v| v.as_str())+ }+}++/// Errors surfaced by the parser. Per project rules these are+/// structured (not `String`) so the handler can dispatch on them.+#[derive(Debug, Error)]+pub enum ParseError {+ /// `total_length` smaller than the minimum a well-formed message+ /// requires (12-byte prelude, headers block, 4-byte trailing CRC).+ /// Wire-format violation; AWS would never emit this. Surfaced+ /// loudly so the handler can 5xx and log it.+ #[error(+ "implausible prelude lengths: total_length={total_length}, headers_length={headers_length}"+ )]+ ImplausiblePreludeLengths {+ total_length: u32,+ headers_length: u32,+ },+ /// `total_length` exceeds the configured `max_message_bytes` cap.+ /// The cap defaults to 32 MiB; configurable via+ /// [`EventStreamParser::with_max_message_bytes`].+ #[error("message too large: total_length={total_length} cap={cap}")]+ MessageTooLarge { total_length: u32, cap: usize },+ /// CRC32 of the first 8 bytes of the prelude did not match the+ /// 9th-12th bytes. Indicates corruption (in-flight bit-flip,+ /// truncated chunk, or — if persistent — wire-format version skew).+ #[error("prelude CRC mismatch: expected={expected:#010x} got={got:#010x}")]+ PreludeCrcMismatch { expected: u32, got: u32 },+ /// CRC32 of the entire message body did not match the trailing+ /// 4-byte CRC. Indicates the message bytes were corrupted in+ /// flight.+ #[error("message CRC mismatch: expected={expected:#010x} got={got:#010x}")]+ MessageCrcMismatch { expected: u32, got: u32 },+ /// A header's `name_len` extended past the declared end of the+ /// headers block.+ #[error("truncated header at offset {offset}: needs {needed} more bytes")]+ TruncatedHeader { offset: usize, needed: usize },+ /// A header's name was not valid UTF-8.+ #[error("header name not valid UTF-8 at offset {offset}: {source}")]+ HeaderNameNotUtf8 {+ offset: usize,+ #[source]+ source: std::str::Utf8Error,+ },+ /// A string-typed header value was not valid UTF-8.+ #[error("header value not valid UTF-8 at offset {offset}: {source}")]+ HeaderValueNotUtf8 {+ offset: usize,+ #[source]+ source: std::str::Utf8Error,+ },+ /// Header value type not in the AWS spec (the spec defines 0..=9).+ /// `value_type` is the literal byte we read.+ #[error("unsupported header value type {value_type} at offset {offset}")]+ UnsupportedHeaderType { value_type: u8, offset: usize },+}++/// Whether to validate CRCs. Defaults to `Yes`; tests + the+/// `--bedrock-validate-eventstream-crc=false` debug flag flip it off.+#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]+pub enum CrcValidation {+ #[default]+ Yes,+ No,+}++/// Stateful parser. Feed `Bytes` chunks via [`EventStreamParser::push`]+/// and pull complete messages via [`EventStreamParser::next_message`].+/// Mirrors the API shape of `sse::framing::SseFramer` deliberately so+/// callers familiar with the SSE side find the EventStream side+/// identical in spirit.+#[derive(Debug)]+pub struct EventStreamParser {+ buf: BytesMut,+ crc_validation: CrcValidation,+ max_message_bytes: usize,+}++impl Default for EventStreamParser {+ fn default() -> Self {+ Self {+ buf: BytesMut::new(),+ crc_validation: CrcValidation::Yes,+ max_message_bytes: DEFAULT_MAX_MESSAGE_BYTES,+ }+ }+}++impl EventStreamParser {+ pub fn new() -> Self {+ Self::default()+ }++ /// Construct with explicit CRC validation policy. Operators flip+ /// to `No` only for debugging — production must validate.+ pub fn with_crc_validation(mut self, crc: CrcValidation) -> Self {+ self.crc_validation = crc;+ self+ }++ /// Configurable hard cap on `total_length`. Above this the parser+ /// refuses (returns [`ParseError::MessageTooLarge`]) so a corrupted+ /// stream cannot allocate unbounded memory.+ pub fn with_max_message_bytes(mut self, cap: usize) -> Self {+ self.max_message_bytes = cap;+ self+ }++ /// Append a chunk of inbound bytes. Zero-length chunks are no-ops.+ pub fn push(&mut self, chunk: &[u8]) {+ if !chunk.is_empty() {+ self.buf.extend_from_slice(chunk);+ }+ }++ /// Number of bytes currently buffered (un-framed). Useful for tests.+ pub fn buffered_len(&self) -> usize {+ self.buf.len()+ }++ /// Pull the next complete message. Returns:+ ///+ /// - `Ok(None)` — the buffer doesn't yet contain a full message;+ /// caller should `push` more bytes.+ /// - `Ok(Some(msg))` — one complete message; caller may call+ /// again to drain further messages from the buffer.+ /// - `Err(_)` — wire-format violation. Per project policy, the+ /// handler 5xx's and logs `event=bedrock_eventstream_*_mismatch`.+ pub fn next_message(&mut self) -> Result<Option<EventStreamMessage>, ParseError> {+ // Need at least the prelude before we can decide.+ if self.buf.len() < PRELUDE_LEN {+ return Ok(None);+ }+ let total_length = u32::from_be_bytes(self.buf[0..4].try_into().expect("4 bytes"));+ let headers_length = u32::from_be_bytes(self.buf[4..8].try_into().expect("4 bytes"));+ let prelude_crc_expected = u32::from_be_bytes(self.buf[8..12].try_into().expect("4 bytes"));++ // Validate plausibility BEFORE we wait for the rest of the+ // bytes. If the prelude lengths are absurd we want to fail+ // immediately rather than buffer a multi-GB stream.+ if (total_length as usize) < PRELUDE_LEN + headers_length as usize + MESSAGE_CRC_LEN {+ return Err(ParseError::ImplausiblePreludeLengths {+ total_length,+ headers_length,+ });+ }+ if (total_length as usize) > self.max_message_bytes {+ return Err(ParseError::MessageTooLarge {+ total_length,+ cap: self.max_message_bytes,+ });+ }++ // Validate prelude CRC over the first 8 bytes (lengths only,+ // NOT the prelude_crc itself).+ if matches!(self.crc_validation, CrcValidation::Yes) {+ let computed = crc32fast::hash(&self.buf[0..8]);+ if computed != prelude_crc_expected {+ return Err(ParseError::PreludeCrcMismatch {+ expected: prelude_crc_expected,+ got: computed,+ });+ }+ }++ // Need the entire message before we yield.+ if self.buf.len() < total_length as usize {+ return Ok(None);+ }++ // Validate trailing message CRC over bytes [0..total_length-4].+ let message_crc_expected = u32::from_be_bytes(+ self.buf[total_length as usize - MESSAGE_CRC_LEN..total_length as usize]+ .try_into()+ .expect("4 bytes"),+ );+ if matches!(self.crc_validation, CrcValidation::Yes) {+ let computed = crc32fast::hash(&self.buf[0..total_length as usize - MESSAGE_CRC_LEN]);+ if computed != message_crc_expected {+ return Err(ParseError::MessageCrcMismatch {+ expected: message_crc_expected,+ got: computed,+ });+ }+ }++ // Slice the message off the buffer.+ let message_bytes = self.buf.split_to(total_length as usize).freeze();++ let headers_start = PRELUDE_LEN;+ let headers_end = PRELUDE_LEN + headers_length as usize;+ let payload_start = headers_end;+ let payload_end = total_length as usize - MESSAGE_CRC_LEN;++ let headers_slice = message_bytes.slice(headers_start..headers_end);+ let payload = message_bytes.slice(payload_start..payload_end);+ let headers = parse_headers(&headers_slice)?;++ Ok(Some(EventStreamMessage { headers, payload }))+ }+}++/// One-shot helper. Convenience for callers that already have all the+/// bytes of one message in hand (e.g. wiremock test fixtures). Returns+/// `Err` if the bytes are not exactly one well-formed message.+///+/// Per the property test invariant, this never panics on adversarial+/// input — every malformed-bytes path returns a [`ParseError`].+pub fn parse(bytes: &[u8]) -> Result<EventStreamMessage, ParseError> {+ let mut parser = EventStreamParser::new();+ parser.push(bytes);+ match parser.next_message()? {+ Some(msg) => Ok(msg),+ None => Err(ParseError::ImplausiblePreludeLengths {+ total_length: 0,+ headers_length: 0,+ }),+ }+}++/// Parse a headers-block byte slice.+fn parse_headers(slice: &Bytes) -> Result<HashMap<String, HeaderValue>, ParseError> {+ let mut out: HashMap<String, HeaderValue> = HashMap::new();+ let mut cursor = 0usize;+ let total = slice.len();+ while cursor < total {+ // [name_len: u8][name][value_type: u8][value]+ if cursor + 1 > total {+ return Err(ParseError::TruncatedHeader {+ offset: cursor,+ needed: 1,+ });+ }+ let name_len = slice[cursor] as usize;+ cursor += 1;+ if cursor + name_len > total {+ return Err(ParseError::TruncatedHeader {+ offset: cursor,+ needed: name_len,+ });+ }+ let name = std::str::from_utf8(&slice[cursor..cursor + name_len])+ .map_err(|e| ParseError::HeaderNameNotUtf8 {+ offset: cursor,+ source: e,+ })?+ .to_ascii_lowercase();+ cursor += name_len;+ if cursor + 1 > total {+ return Err(ParseError::TruncatedHeader {+ offset: cursor,+ needed: 1,+ });+ }+ let value_type = slice[cursor];+ cursor += 1;+ let value = match value_type {+ header_type::STRING => {+ if cursor + 2 > total {+ return Err(ParseError::TruncatedHeader {+ offset: cursor,+ needed: 2,+ });+ }+ let value_len =+ u16::from_be_bytes(slice[cursor..cursor + 2].try_into().expect("2 bytes"))+ as usize;+ cursor += 2;+ if cursor + value_len > total {+ return Err(ParseError::TruncatedHeader {+ offset: cursor,+ needed: value_len,+ });+ }+ let s = std::str::from_utf8(&slice[cursor..cursor + value_len]).map_err(|e| {+ ParseError::HeaderValueNotUtf8 {+ offset: cursor,+ source: e,+ }+ })?;+ cursor += value_len;+ HeaderValue::String(s.to_string())+ }+ header_type::BYTE_ARRAY => {+ if cursor + 2 > total {+ return Err(ParseError::TruncatedHeader {+ offset: cursor,+ needed: 2,+ });+ }+ let value_len =+ u16::from_be_bytes(slice[cursor..cursor + 2].try_into().expect("2 bytes"))+ as usize;+ cursor += 2;+ if cursor + value_len > total {+ return Err(ParseError::TruncatedHeader {+ offset: cursor,+ needed: value_len,+ });+ }+ let v = slice.slice(cursor..cursor + value_len);+ cursor += value_len;+ HeaderValue::Bytes(v)+ }+ // The TRUE/FALSE flags carry no value bytes; we surface+ // them as a single-byte payload `Bytes` for completeness+ // even though Bedrock never emits them. Other types that+ // DO carry payload but we have no use for fall through to+ // the "unsupported" arm — better a structured error than+ // a silently-skipped header.+ header_type::TRUE => HeaderValue::Bytes(Bytes::from_static(&[1])),+ header_type::FALSE => HeaderValue::Bytes(Bytes::from_static(&[0])),+ header_type::BYTE => {+ if cursor + 1 > total {+ return Err(ParseError::TruncatedHeader {+ offset: cursor,+ needed: 1,+ });+ }+ let v = slice.slice(cursor..cursor + 1);+ cursor += 1;+ HeaderValue::Bytes(v)+ }+ header_type::SHORT => {+ if cursor + 2 > total {+ return Err(ParseError::TruncatedHeader {+ offset: cursor,+ needed: 2,+ });+ }+ let v = slice.slice(cursor..cursor + 2);+ cursor += 2;+ HeaderValue::Bytes(v)+ }+ header_type::INTEGER => {+ if cursor + 4 > total {+ return Err(ParseError::TruncatedHeader {+ offset: cursor,+ needed: 4,+ });+ }+ let v = slice.slice(cursor..cursor + 4);+ cursor += 4;+ HeaderValue::Bytes(v)+ }+ header_type::LONG | header_type::TIMESTAMP => {+ if cursor + 8 > total {+ return Err(ParseError::TruncatedHeader {+ offset: cursor,+ needed: 8,+ });+ }+ let v = slice.slice(cursor..cursor + 8);+ cursor += 8;+ HeaderValue::Bytes(v)+ }+ header_type::UUID => {+ if cursor + 16 > total {+ return Err(ParseError::TruncatedHeader {+ offset: cursor,+ needed: 16,+ });+ }+ let v = slice.slice(cursor..cursor + 16);+ cursor += 16;+ HeaderValue::Bytes(v)+ }+ other => {+ return Err(ParseError::UnsupportedHeaderType {+ value_type: other,+ offset: cursor.saturating_sub(1),+ });+ }+ };+ out.insert(name, value);+ }+ // Sanity: cursor must equal total or we have a parse-loop bug.+ let _ = (cursor, total, header_type::TRUE, Buf::remaining(&&[][..])); // pin unused-import+ Ok(out)+}++// ────────────────────────────────────────────────────────────────────+// Test-only helpers for synthesising bytes. Living here (vs in the+// integration test crate) so unit tests in this module can exercise+// the parser end-to-end and the integration tests have the same builder+// available via `pub(crate)`.+// ────────────────────────────────────────────────────────────────────++/// Builder for synthesising a well-formed EventStream message. Used by+/// tests and by [`build_chunk_message`]. Producing valid bytes is much+/// more delicate than parsing them — this helper centralises the CRC+/// math.+#[derive(Debug, Default)]+pub struct MessageBuilder {+ headers: Vec<(String, HeaderValue)>,+ payload: Bytes,+}++impl MessageBuilder {+ pub fn new() -> Self {+ Self::default()+ }++ pub fn header_string(mut self, name: &str, value: &str) -> Self {+ self.headers+ .push((name.to_string(), HeaderValue::String(value.to_string())));+ self+ }++ pub fn header_bytes(mut self, name: &str, value: Bytes) -> Self {+ self.headers+ .push((name.to_string(), HeaderValue::Bytes(value)));+ self+ }++ pub fn payload(mut self, payload: Bytes) -> Self {+ self.payload = payload;+ self+ }++ /// Serialize to the wire format. Computes both CRCs.+ pub fn build(self) -> Bytes {+ let mut headers_bytes = BytesMut::new();+ for (name, value) in &self.headers {+ // name_len + name+ assert!(name.len() <= u8::MAX as usize, "header name too long");+ headers_bytes.extend_from_slice(&[name.len() as u8]);+ headers_bytes.extend_from_slice(name.as_bytes());+ match value {+ HeaderValue::String(s) => {+ headers_bytes.extend_from_slice(&[header_type::STRING]);+ let len = s.len() as u16;+ headers_bytes.extend_from_slice(&len.to_be_bytes());+ headers_bytes.extend_from_slice(s.as_bytes());+ }+ HeaderValue::Bytes(b) => {+ headers_bytes.extend_from_slice(&[header_type::BYTE_ARRAY]);+ let len = b.len() as u16;+ headers_bytes.extend_from_slice(&len.to_be_bytes());+ headers_bytes.extend_from_slice(b);+ }+ }+ }+ let headers_len = headers_bytes.len() as u32;+ let payload_len = self.payload.len() as u32;+ let total_len = PRELUDE_LEN as u32 + headers_len + payload_len + MESSAGE_CRC_LEN as u32;++ let mut out = BytesMut::with_capacity(total_len as usize);+ out.extend_from_slice(&total_len.to_be_bytes());+ out.extend_from_slice(&headers_len.to_be_bytes());+ let prelude_crc = crc32fast::hash(&out[..]);+ out.extend_from_slice(&prelude_crc.to_be_bytes());+ out.extend_from_slice(&headers_bytes);+ out.extend_from_slice(&self.payload);+ let message_crc = crc32fast::hash(&out[..]);+ out.extend_from_slice(&message_crc.to_be_bytes());+ out.freeze()+ }+}++/// Build a minimal Anthropic-on-Bedrock `chunk` message. The payload+/// is the JSON bytes for an Anthropic SSE event, as Bedrock emits.+pub fn build_chunk_message(payload_json: &str) -> Bytes {+ MessageBuilder::new()+ .header_string(":event-type", "chunk")+ .header_string(":content-type", "application/json")+ .header_string(":message-type", "event")+ .payload(Bytes::copy_from_slice(payload_json.as_bytes()))+ .build()+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn round_trip_single_message() {+ let bytes = build_chunk_message(r#"{"type":"message_start","message":{"id":"msg_a"}}"#);+ let mut parser = EventStreamParser::new();+ parser.push(&bytes);+ let msg = parser.next_message().unwrap().unwrap();+ assert_eq!(msg.event_type(), Some("chunk"));+ assert_eq!(msg.message_type(), Some("event"));+ let payload_str = std::str::from_utf8(&msg.payload).unwrap();+ assert!(payload_str.starts_with(r#"{"type":"message_start""#));+ assert!(parser.next_message().unwrap().is_none());+ }++ #[test]+ fn round_trip_multi_message_one_chunk() {+ let mut combined = BytesMut::new();+ combined.extend_from_slice(&build_chunk_message(r#"{"a":1}"#));+ combined.extend_from_slice(&build_chunk_message(r#"{"b":2}"#));+ let mut parser = EventStreamParser::new();+ parser.push(&combined);+ let m1 = parser.next_message().unwrap().unwrap();+ let m2 = parser.next_message().unwrap().unwrap();+ assert_eq!(std::str::from_utf8(&m1.payload).unwrap(), r#"{"a":1}"#);+ assert_eq!(std::str::from_utf8(&m2.payload).unwrap(), r#"{"b":2}"#);+ assert!(parser.next_message().unwrap().is_none());+ }++ #[test]+ fn one_byte_at_a_time_no_loss() {+ // Drip-feed a complete message one byte at a time. Parser+ // must yield exactly one message at the very end.+ let bytes = build_chunk_message(r#"{"type":"message_stop"}"#);+ let mut parser = EventStreamParser::new();+ for b in bytes.iter() {+ parser.push(std::slice::from_ref(b));+ // For all but the last byte, no message yet.+ }+ let msg = parser.next_message().unwrap().unwrap();+ assert_eq!(+ std::str::from_utf8(&msg.payload).unwrap(),+ r#"{"type":"message_stop"}"#,+ );+ }++ #[test]+ fn prelude_crc_mismatch_loud() {+ // Build a valid message, then corrupt the prelude CRC.+ let mut bytes: Vec<u8> = build_chunk_message(r#"{"x":1}"#).to_vec();+ bytes[8] ^= 0xff;+ let mut parser = EventStreamParser::new();+ parser.push(&bytes);+ let err = parser.next_message().unwrap_err();+ assert!(+ matches!(err, ParseError::PreludeCrcMismatch { .. }),+ "got {err:?}"+ );+ }++ #[test]+ fn message_crc_mismatch_loud() {+ let mut bytes: Vec<u8> = build_chunk_message(r#"{"y":2}"#).to_vec();+ // Corrupt the trailing CRC (last 4 bytes).+ let n = bytes.len();+ bytes[n - 1] ^= 0xff;+ let mut parser = EventStreamParser::new();+ parser.push(&bytes);+ let err = parser.next_message().unwrap_err();+ assert!(+ matches!(err, ParseError::MessageCrcMismatch { .. }),+ "got {err:?}"+ );+ }++ #[test]+ fn implausible_lengths_loud() {+ // Forge a prelude where total < headers + 12 + 4. Caller never+ // gets a chance to even compute the CRC.+ let mut bytes = BytesMut::new();+ bytes.extend_from_slice(&8u32.to_be_bytes()); // total = 8 (impossible)+ bytes.extend_from_slice(&0u32.to_be_bytes()); // headers = 0+ bytes.extend_from_slice(&0u32.to_be_bytes()); // bogus crc+ let mut parser = EventStreamParser::new();+ parser.push(&bytes);+ let err = parser.next_message().unwrap_err();+ assert!(+ matches!(err, ParseError::ImplausiblePreludeLengths { .. }),+ "got {err:?}"+ );+ }++ #[test]+ fn message_too_large_loud() {+ // Forge a prelude with an enormous total_length and observe+ // the cap rejection (we never even allocate the payload).+ let mut bytes = BytesMut::new();+ bytes.extend_from_slice(&(64u32 * 1024 * 1024).to_be_bytes()); // 64 MiB+ bytes.extend_from_slice(&0u32.to_be_bytes());+ let valid_crc = crc32fast::hash(&bytes[0..8]);+ bytes.extend_from_slice(&valid_crc.to_be_bytes());+ let mut parser = EventStreamParser::new().with_max_message_bytes(32 * 1024 * 1024);+ parser.push(&bytes);+ let err = parser.next_message().unwrap_err();+ assert!(+ matches!(err, ParseError::MessageTooLarge { .. }),+ "got {err:?}"+ );+ }++ #[test]+ fn crc_validation_off_accepts_corrupt_prelude() {+ // With CrcValidation::No, prelude+message CRCs are ignored.+ let mut bytes: Vec<u8> = build_chunk_message(r#"{"a":3}"#).to_vec();+ bytes[8] ^= 0xff; // corrupt prelude crc+ let n = bytes.len();+ bytes[n - 1] ^= 0xff; // corrupt message crc+ let mut parser = EventStreamParser::new().with_crc_validation(CrcValidation::No);+ parser.push(&bytes);+ let msg = parser.next_message().unwrap().unwrap();+ assert_eq!(std::str::from_utf8(&msg.payload).unwrap(), r#"{"a":3}"#);+ }++ #[test]+ fn header_bytes_round_trip() {+ let payload_bytes = Bytes::from_static(b"\x01\x02\x03");+ let bytes = MessageBuilder::new()+ .header_string(":event-type", "chunk")+ .header_bytes(":custom-bytes", payload_bytes.clone())+ .payload(Bytes::from_static(b"{}"))+ .build();+ let parsed = parse(&bytes).unwrap();+ match parsed.headers.get(":custom-bytes").unwrap() {+ HeaderValue::Bytes(b) => assert_eq!(b, &payload_bytes),+ _ => panic!("expected bytes header"),+ }+ }++ #[test]+ fn parse_one_shot_helper() {+ let bytes = build_chunk_message(r#"{"k":"v"}"#);+ let m = parse(&bytes).unwrap();+ assert_eq!(m.event_type(), Some("chunk"));+ }++ #[test]+ fn parse_one_shot_returns_err_on_partial() {+ // 4 bytes only — never enough for a prelude.+ let bytes = vec![0u8, 0, 0, 8];+ let err = parse(&bytes).unwrap_err();+ assert!(matches!(err, ParseError::ImplausiblePreludeLengths { .. }));+ }++ #[test]+ fn empty_buffer_yields_none() {+ let mut parser = EventStreamParser::new();+ assert!(parser.next_message().unwrap().is_none());+ }+}diff --git a/crates/headroom-proxy/src/bedrock/eventstream_to_sse.rs b/crates/headroom-proxy/src/bedrock/eventstream_to_sse.rsnew file mode 100644index 000000000..5b0c56804--- /dev/null+++ b/crates/headroom-proxy/src/bedrock/eventstream_to_sse.rs@@ -0,0 +1,397 @@+//! Translate Bedrock binary EventStream messages into Anthropic SSE+//! frames — Phase D PR-D2.+//!+//! # Why translate+//!+//! Bedrock's `/model/{id}/invoke-with-response-stream` returns+//! `application/vnd.amazon.eventstream` — a binary, length-prefixed,+//! CRC-checksummed framing format. Most clients of Headroom (Claude+//! Code, the Anthropic SDK in non-Bedrock mode, the Headroom Python+//! SDK) speak SSE (`text/event-stream`). When the client requested+//! Bedrock-compatible output via `Accept: application/vnd.amazon.eventstream`+//! we pass the upstream bytes through unchanged. When the client wants+//! SSE (the default) we translate each `chunk` message's JSON payload+//! into an SSE frame:+//!+//! ```text+//! data: {anthropic JSON event}\n\n+//! ```+//!+//! That format matches what direct-Anthropic `/v1/messages` emits and+//! lets the existing [`AnthropicStreamState`] from PR-C1 read the+//! translated stream for telemetry without modification.+//!+//! # Output mode selection+//!+//! Configurable. Default behaviour:+//!+//! - `Accept: application/vnd.amazon.eventstream` (or any value+//! listed in [`OutputMode::eventstream_accept_values`]) → passthrough.+//! - `Accept: text/event-stream`, `Accept: */*`, or absent → translate.+//!+//! Operators override the recognised Accept values via the+//! `--bedrock-eventstream-accept-values` CLI flag (CSV) — though the+//! defaults cover every Bedrock client we know about today.++use bytes::{Bytes, BytesMut};+use http::HeaderMap;++use crate::bedrock::eventstream::{EventStreamMessage, HeaderValue};++/// Output mode for the streaming response. Picked once per request,+/// based on the inbound `Accept` header.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum OutputMode {+ /// Pass upstream EventStream bytes through verbatim. Used when+ /// the client speaks Bedrock binary natively (`Accept:+ /// application/vnd.amazon.eventstream`).+ EventStream,+ /// Translate each `chunk` message's payload into an SSE frame.+ /// Used by SSE-native clients (the default).+ Sse,+}++impl OutputMode {+ /// Default list of `Accept` header values (case-insensitive,+ /// comparison ignores parameters after `;`) that select+ /// [`OutputMode::EventStream`].+ pub fn default_eventstream_accept_values() -> Vec<String> {+ vec!["application/vnd.amazon.eventstream".to_string()]+ }++ /// Decide an [`OutputMode`] from the inbound headers + the+ /// configured list of EventStream-selecting `Accept` values.+ /// Lower-case + parameter-trimmed comparison per RFC 7231 §3.1.1.1.+ pub fn from_accept(headers: &HeaderMap, eventstream_accept_values: &[String]) -> OutputMode {+ let accept_raw = match headers+ .get(http::header::ACCEPT)+ .and_then(|v| v.to_str().ok())+ {+ Some(v) => v,+ None => return OutputMode::Sse,+ };+ // The Accept header may carry multiple media types separated+ // by commas; iterate and trim parameters from each.+ for token in accept_raw.split(',') {+ let media_type = token.split(';').next().unwrap_or("").trim();+ for candidate in eventstream_accept_values {+ if media_type.eq_ignore_ascii_case(candidate) {+ return OutputMode::EventStream;+ }+ }+ }+ OutputMode::Sse+ }+}++/// A translation outcome for one EventStream message.+#[derive(Debug, Clone, PartialEq, Eq)]+pub enum TranslateOutcome {+ /// Emit these bytes to the client. For `OutputMode::Sse` this is+ /// `data: {payload}\n\n`; for `OutputMode::EventStream` it is the+ /// upstream bytes themselves (we don't ever pass through here —+ /// passthrough mode is handled by the streaming forwarder, which+ /// never bothers parsing).+ Emit(Bytes),+ /// Skip — the message has no client-facing translation. Used for+ /// `:event-type` values that AWS emits for protocol-internal+ /// signalling (not yet observed for Bedrock Anthropic responses,+ /// but we surface a structured outcome rather than guess).+ Skip { event_type: String },+}++/// Errors during translation. Per project rules these are loud — the+/// handler 5xx's the client when an unknown `:message-type` arrives,+/// rather than silently swallowing.+#[derive(Debug, thiserror::Error)]+pub enum TranslateError {+ /// `:message-type == exception`. AWS reserved value indicating the+ /// service raised a synchronous error mid-stream. Surfaced as a+ /// structured error so the handler can map it to a 5xx + log.+ #[error("Bedrock stream emitted exception: {payload_preview}")]+ UpstreamException { payload_preview: String },+ /// The translator's input message is missing a required header+ /// (`:event-type`). Wire-format violation — AWS would never emit.+ #[error("Bedrock message missing required `:event-type` header")]+ MissingEventType,+}++/// Translate one EventStream message under the chosen output mode.+///+/// Side-effect-free: emits a `tracing::info!` per `chunk` translation+/// and `tracing::warn!` for unknown event types. The hot path is+/// allocation-bounded — one `BytesMut` of `payload.len() + 8`.+pub fn translate_message(+ message: &EventStreamMessage,+ mode: OutputMode,+) -> Result<TranslateOutcome, TranslateError> {+ // Always check for `:message-type == exception` first — that's a+ // structural error regardless of mode. AWS reserves this value to+ // indicate a service-side fault ON the stream (vs an HTTP-level+ // error from the initial request).+ if matches!(message.message_type(), Some("exception")) {+ let preview = String::from_utf8_lossy(&message.payload[..message.payload.len().min(160)])+ .into_owned();+ return Err(TranslateError::UpstreamException {+ payload_preview: preview,+ });+ }++ let event_type = message+ .event_type()+ .ok_or(TranslateError::MissingEventType)?;++ match (mode, event_type) {+ (OutputMode::EventStream, _) => {+ // Passthrough mode never reaches this function on the hot+ // path — the streaming handler short-circuits to byte+ // copy. We still support the call so tests can assert+ // semantic equivalence: re-emit the exact bytes (which+ // requires re-serialising — costly — so we don't here).+ // Surface a structured Skip; the caller picks bytes from+ // the raw upstream stream.+ Ok(TranslateOutcome::Skip {+ event_type: event_type.to_string(),+ })+ }+ (OutputMode::Sse, "chunk") => {+ tracing::info!(+ event = "bedrock_eventstream_translated_to_sse",+ event_type = event_type,+ payload_bytes = message.payload.len(),+ "translated bedrock eventstream chunk to sse frame"+ );+ Ok(TranslateOutcome::Emit(payload_to_sse_frame(+ &message.payload,+ )))+ }+ (OutputMode::Sse, other) => {+ // Unknown event type. Bedrock today emits `chunk`+ // exclusively for Anthropic streaming responses; if a new+ // type appears we log it loudly per+ // `feedback_no_silent_fallbacks.md` rather than silently+ // dropping the bytes.+ tracing::warn!(+ event = "bedrock_eventstream_unknown_event_type",+ event_type = other,+ "unknown bedrock eventstream :event-type; skipping translation"+ );+ Ok(TranslateOutcome::Skip {+ event_type: other.to_string(),+ })+ }+ }+}++/// Wrap a JSON payload as an SSE event frame.+///+/// Anthropic's direct `/v1/messages` SSE wire format emits BOTH an+/// `event:` line (the event name like `message_start`) AND a `data:`+/// line (the JSON payload). The proxy's `AnthropicStreamState`+/// requires the `event:` line — without it every event is dropped+/// with a `sse_unknown_event` warn.+///+/// The Bedrock binary EventStream encodes the event name on the+/// frame envelope (`:event-type` always equals `chunk`), but the+/// Anthropic semantic event type lives in the JSON payload's `type`+/// field. We extract it and emit the SSE frame in the canonical+/// Anthropic format.+///+/// If the JSON is malformed or `type` is missing, we still emit a+/// `data:`-only frame (best-effort) and log a warn — the byte path+/// to the client never breaks.+fn payload_to_sse_frame(payload: &[u8]) -> Bytes {+ let event_name = extract_anthropic_event_type(payload);+ let extra = match &event_name {+ Some(name) => name.len() + 8, // "event: " + "\n"+ None => 0,+ };+ let mut out = BytesMut::with_capacity(payload.len() + extra + 8);+ if let Some(name) = event_name {+ out.extend_from_slice(b"event: ");+ out.extend_from_slice(name.as_bytes());+ out.extend_from_slice(b"\n");+ }+ out.extend_from_slice(b"data: ");+ out.extend_from_slice(payload);+ out.extend_from_slice(b"\n\n");+ out.freeze()+}++/// Extract `type` field from an Anthropic SSE JSON payload. We do a+/// targeted byte-level scan rather than a full JSON parse so the hot+/// path is allocation-free in the common case. Falls back to `None`+/// on any malformed input — never panics.+fn extract_anthropic_event_type(payload: &[u8]) -> Option<String> {+ // Cheap path: parse with serde_json, take `.type` if it's a string.+ // The JSON is small (typical Anthropic event ~200 bytes), so the+ // parse cost is negligible vs the wire serialisation we already do.+ let v: serde_json::Value = serde_json::from_slice(payload).ok()?;+ v.get("type")?.as_str().map(|s| s.to_string())+}++/// Convenience: print one translated header value for log readability.+/// Used only on log paths.+pub fn header_value_preview(v: &HeaderValue) -> String {+ match v {+ HeaderValue::String(s) => {+ if s.len() <= 64 {+ s.clone()+ } else {+ format!("{}…", &s[..64])+ }+ }+ HeaderValue::Bytes(b) => format!("[{} bytes]", b.len()),+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::bedrock::eventstream::{build_chunk_message, parse};+ use http::HeaderMap;++ #[test]+ fn accept_eventstream_selects_passthrough() {+ let mut h = HeaderMap::new();+ h.insert(+ http::header::ACCEPT,+ "application/vnd.amazon.eventstream".parse().unwrap(),+ );+ let mode = OutputMode::from_accept(&h, &OutputMode::default_eventstream_accept_values());+ assert_eq!(mode, OutputMode::EventStream);+ }++ #[test]+ fn accept_eventstream_with_q_param_still_selects_passthrough() {+ // RFC 7231 quality params are stripped before comparison.+ let mut h = HeaderMap::new();+ h.insert(+ http::header::ACCEPT,+ "application/vnd.amazon.eventstream;q=0.9".parse().unwrap(),+ );+ let mode = OutputMode::from_accept(&h, &OutputMode::default_eventstream_accept_values());+ assert_eq!(mode, OutputMode::EventStream);+ }++ #[test]+ fn accept_text_event_stream_selects_sse() {+ let mut h = HeaderMap::new();+ h.insert(http::header::ACCEPT, "text/event-stream".parse().unwrap());+ let mode = OutputMode::from_accept(&h, &OutputMode::default_eventstream_accept_values());+ assert_eq!(mode, OutputMode::Sse);+ }++ #[test]+ fn no_accept_header_defaults_to_sse() {+ let h = HeaderMap::new();+ let mode = OutputMode::from_accept(&h, &OutputMode::default_eventstream_accept_values());+ assert_eq!(mode, OutputMode::Sse);+ }++ #[test]+ fn multi_accept_with_eventstream_among_them_selects_passthrough() {+ let mut h = HeaderMap::new();+ h.insert(+ http::header::ACCEPT,+ "text/html, application/vnd.amazon.eventstream;q=0.9, */*"+ .parse()+ .unwrap(),+ );+ let mode = OutputMode::from_accept(&h, &OutputMode::default_eventstream_accept_values());+ assert_eq!(mode, OutputMode::EventStream);+ }++ #[test]+ fn translate_chunk_to_sse_frame() {+ let json = r#"{"type":"message_start","message":{"id":"msg_abc"}}"#;+ let bytes = build_chunk_message(json);+ let msg = parse(&bytes).unwrap();+ let outcome = translate_message(&msg, OutputMode::Sse).unwrap();+ match outcome {+ TranslateOutcome::Emit(b) => {+ let s = std::str::from_utf8(&b).unwrap();+ // Both event: and data: lines must be present, in+ // Anthropic's documented order.+ assert!(+ s.starts_with("event: message_start\ndata: "),+ "expected 'event: message_start' header; got {s}"+ );+ assert!(s.ends_with("\n\n"));+ assert!(s.contains(json));+ }+ other => panic!("expected Emit; got {other:?}"),+ }+ }++ #[test]+ fn translate_chunk_falls_back_on_malformed_payload() {+ // Payload is not valid JSON — translator must still emit a+ // data:-only frame (no event: line) and the byte path must+ // not panic.+ let bytes = build_chunk_message("not json at all");+ let msg = parse(&bytes).unwrap();+ let outcome = translate_message(&msg, OutputMode::Sse).unwrap();+ match outcome {+ TranslateOutcome::Emit(b) => {+ let s = std::str::from_utf8(&b).unwrap();+ assert!(s.starts_with("data: "));+ assert!(s.ends_with("\n\n"));+ }+ other => panic!("expected Emit; got {other:?}"),+ }+ }++ #[test]+ fn translate_exception_message_is_loud() {+ let bytes = crate::bedrock::eventstream::MessageBuilder::new()+ .header_string(":message-type", "exception")+ .header_string(":exception-type", "ThrottlingException")+ .payload(Bytes::from_static(br#"{"message":"slow down"}"#))+ .build();+ let msg = parse(&bytes).unwrap();+ let err = translate_message(&msg, OutputMode::Sse).unwrap_err();+ assert!(matches!(err, TranslateError::UpstreamException { .. }));+ }++ #[test]+ fn translate_unknown_event_type_skips() {+ let bytes = crate::bedrock::eventstream::MessageBuilder::new()+ .header_string(":event-type", "future_unknown_kind")+ .header_string(":message-type", "event")+ .payload(Bytes::from_static(b"{}"))+ .build();+ let msg = parse(&bytes).unwrap();+ let outcome = translate_message(&msg, OutputMode::Sse).unwrap();+ match outcome {+ TranslateOutcome::Skip { event_type } => {+ assert_eq!(event_type, "future_unknown_kind");+ }+ other => panic!("expected Skip; got {other:?}"),+ }+ }++ #[test]+ fn missing_event_type_is_loud() {+ // A message lacking :event-type must not silently translate.+ let bytes = crate::bedrock::eventstream::MessageBuilder::new()+ .header_string(":message-type", "event")+ .payload(Bytes::from_static(b"{}"))+ .build();+ let msg = parse(&bytes).unwrap();+ let err = translate_message(&msg, OutputMode::Sse).unwrap_err();+ assert!(matches!(err, TranslateError::MissingEventType));+ }++ #[test]+ fn header_value_preview_strings() {+ assert_eq!(+ header_value_preview(&HeaderValue::String("hi".into())),+ "hi"+ );+ assert!(+ header_value_preview(&HeaderValue::Bytes(Bytes::from_static(&[1, 2, 3])))+ .starts_with("[3 bytes")+ );+ }+}diff --git a/crates/headroom-proxy/src/bedrock/invoke_streaming.rs b/crates/headroom-proxy/src/bedrock/invoke_streaming.rsnew file mode 100644index 000000000..daa9f683b--- /dev/null+++ b/crates/headroom-proxy/src/bedrock/invoke_streaming.rs@@ -0,0 +1,903 @@+//! POST `/model/{model_id}/invoke-with-response-stream` handler —+//! Phase D PR-D2.+//!+//! # Pipeline+//!+//! 1. Parse the path, body, and `Accept` header.+//! 2. Run the live-zone Anthropic compressor over the (Anthropic-shape)+//! body — same as PR-D1's non-streaming handler.+//! 3. Sign with SigV4 over the post-compression bytes.+//! 4. Forward to Bedrock via reqwest's streaming response API.+//! 5. Inspect the upstream response's `Content-Type`:+//! - `application/vnd.amazon.eventstream` (the expected case) →+//! drive the [`EventStreamParser`] over the byte stream.+//! - Anything else → forward verbatim (Bedrock returned a JSON+//! error body or a redirect; we surface it unchanged so the+//! client sees the real status).+//! 6. Pick output mode by inspecting the inbound `Accept` header:+//! - `Accept: application/vnd.amazon.eventstream` → passthrough+//! the upstream bytes BYTE-EQUAL.+//! - `Accept: text/event-stream` (default) → translate each+//! `chunk` message's payload into an SSE frame; tee the SSE+//! frames into [`AnthropicStreamState`] for telemetry.+//!+//! # Cache safety+//!+//! Same as PR-D1's `invoke.rs`: the SigV4 signature covers the bytes+//! we forward (post-compression), and the upstream's response bytes+//! are never modified IN PASSTHROUGH MODE. In SSE-translation mode the+//! response wire format changes (binary → text), but the JSON payload+//! inside each `chunk` is bytewise identical to the upstream — only+//! the framing differs.+//!+//! # Failure modes (all loud)+//!+//! - SigV4 missing creds → `5xx` + `event=bedrock_credentials_missing`.+//! - SigV4 sign failure → `5xx` + `event=bedrock_sigv4_failed`.+//! - EventStream parse failure mid-stream → close the response with+//! a structured error frame; log+//! `event=bedrock_eventstream_parse_failed` (or `_crc_mismatch`)+//! at WARN.+//! - Translator `:message-type == exception` → propagate to client+//! (the underlying upstream error is the customer's, not ours).++use std::convert::Infallible;+use std::net::SocketAddr;+use std::time::SystemTime;++use axum::body::Body;+use axum::extract::{ConnectInfo, Path, State};+use axum::http::{HeaderMap, Method, StatusCode, Uri};+use axum::response::{IntoResponse, Response};+use bytes::Bytes;+use futures_util::stream::{self, Stream};+use futures_util::StreamExt as _;+use http::HeaderName;+use std::pin::Pin;+use url::Url;++use crate::bedrock::eventstream::{EventStreamParser, ParseError};+use crate::bedrock::eventstream_to_sse::{+ translate_message, OutputMode, TranslateError, TranslateOutcome,+};+use crate::bedrock::sigv4::{sign_request, SigningInputs};+use crate::compression::{+ compress_anthropic_request, Outcome as AnthropicOutcome, PassthroughReason,+};+use crate::headers::filter_response_headers;+use crate::proxy::AppState;++/// Anthropic vendor prefix as encoded in Bedrock model ids.+const ANTHROPIC_VENDOR_PREFIX: &str = "anthropic.";++/// AWS Bedrock Runtime DNS template.+const BEDROCK_RUNTIME_HOST_TEMPLATE: &str = "bedrock-runtime.{region}.amazonaws.com";++/// Path action for the streaming route.+const STREAMING_ACTION: &str = "invoke-with-response-stream";++/// Axum POST handler for `/model/{model_id}/invoke-with-response-stream`.+pub async fn handle_invoke_streaming(+ State(state): State<AppState>,+ ConnectInfo(client_addr): ConnectInfo<SocketAddr>,+ Path(model_id): Path<String>,+ method: Method,+ uri: Uri,+ headers: HeaderMap,+ body: Bytes,+) -> Response {+ let _ = client_addr;+ let request_id = headers+ .get("x-request-id")+ .and_then(|v| v.to_str().ok())+ .map(|s| s.to_string())+ .unwrap_or_else(|| uuid::Uuid::new_v4().to_string());++ tracing::info!(+ event = "bedrock_invoke_streaming_received",+ request_id = %request_id,+ method = %method,+ model_id = %model_id,+ body_bytes = body.len(),+ "bedrock invoke-with-response-stream route received request"+ );++ // 1. Live-zone compression for Anthropic-shape bodies (same as D1).+ let is_anthropic = model_id.starts_with(ANTHROPIC_VENDOR_PREFIX);+ let outbound_body: Bytes = if is_anthropic {+ run_anthropic_compression(&body, &state, &request_id)+ } else {+ tracing::info!(+ event = "bedrock_compression_skipped",+ request_id = %request_id,+ model_id = %model_id,+ reason = "non_anthropic_vendor",+ "bedrock invoke-streaming: skipping compression for non-anthropic vendor"+ );+ body.clone()+ };++ // 2. Build upstream URL.+ let upstream_url = match build_bedrock_streaming_upstream(&state, &model_id, &uri) {+ Ok(u) => u,+ Err(msg) => {+ tracing::error!(+ event = "bedrock_endpoint_invalid",+ request_id = %request_id,+ error = %msg,+ "bedrock invoke-streaming: failed to construct upstream URL"+ );+ return error_response(+ StatusCode::INTERNAL_SERVER_ERROR,+ "bedrock_endpoint_invalid",+ &msg,+ );+ }+ };++ // 3. Resolve credentials. No silent fallback.+ let creds = match state.bedrock_credentials.as_ref() {+ Some(c) => c.clone(),+ None => {+ tracing::warn!(+ event = "bedrock_credentials_missing",+ request_id = %request_id,+ model_id = %model_id,+ "bedrock invoke-streaming: refusing to forward without AWS credentials"+ );+ return error_response(+ StatusCode::INTERNAL_SERVER_ERROR,+ "bedrock_credentials_missing",+ "AWS credentials not configured; refusing to forward unsigned",+ );+ }+ };++ // 4. Build the headers we sign + forward.+ let extra_signed: Vec<(String, String)> = collect_signed_headers(&headers, &upstream_url);+ let extra_signed_refs: Vec<(&str, &str)> = extra_signed+ .iter()+ .map(|(k, v)| (k.as_str(), v.as_str()))+ .collect();++ let sign_inputs = SigningInputs {+ method: method.as_str(),+ url: &upstream_url,+ region: &state.config.bedrock_region,+ credentials: creds.as_ref(),+ body: &outbound_body,+ extra_signed_headers: &extra_signed_refs,+ time: SystemTime::now(),+ };+ let signed = match sign_request(&sign_inputs) {+ Ok(s) => s,+ Err(e) => {+ tracing::error!(+ event = "bedrock_sigv4_failed",+ request_id = %request_id,+ model_id = %model_id,+ error = %e,+ "bedrock invoke-streaming: SigV4 signing failed"+ );+ return error_response(+ StatusCode::INTERNAL_SERVER_ERROR,+ "bedrock_sigv4_failed",+ &e.to_string(),+ );+ }+ };++ // Build outbound HeaderMap (same pattern as D1).+ let mut outbound_headers = HeaderMap::new();+ for (name, value) in extra_signed.iter() {+ if let (Ok(n), Ok(v)) = (+ HeaderName::from_bytes(name.as_bytes()),+ http::HeaderValue::from_str(value),+ ) {+ outbound_headers.insert(n, v);+ }+ }+ for (name, value) in signed.entries.iter() {+ if let (Ok(n), Ok(v)) = (+ HeaderName::from_bytes(name.as_bytes()),+ http::HeaderValue::from_str(value),+ ) {+ outbound_headers.insert(n, v);+ }+ }++ // 5. Forward.+ let reqwest_method = match reqwest::Method::from_bytes(method.as_str().as_bytes()) {+ Ok(m) => m,+ Err(e) => {+ tracing::error!(+ event = "bedrock_invalid_method",+ request_id = %request_id,+ error = %e,+ "bedrock invoke-streaming: invalid HTTP method"+ );+ return error_response(+ StatusCode::BAD_REQUEST,+ "bedrock_invalid_method",+ &e.to_string(),+ );+ }+ };++ let upstream_resp = state+ .client+ .request(reqwest_method, upstream_url.clone())+ .headers(outbound_headers)+ .body(outbound_body.clone())+ .send()+ .await;++ let upstream_resp = match upstream_resp {+ Ok(r) => r,+ Err(e) => {+ tracing::warn!(+ event = "bedrock_upstream_error",+ request_id = %request_id,+ error = %e,+ "bedrock invoke-streaming: upstream request failed"+ );+ let status = if e.is_timeout() {+ StatusCode::GATEWAY_TIMEOUT+ } else {+ StatusCode::BAD_GATEWAY+ };+ return error_response(status, "bedrock_upstream_error", &e.to_string());+ }+ };++ let status =+ StatusCode::from_u16(upstream_resp.status().as_u16()).unwrap_or(StatusCode::BAD_GATEWAY);+ let upstream_content_type = upstream_resp+ .headers()+ .get(http::header::CONTENT_TYPE)+ .and_then(|v| v.to_str().ok())+ .map(|s| s.to_string());++ // 6. Decide output mode based on the client's `Accept` header.+ let accept_values = OutputMode::default_eventstream_accept_values();+ let output_mode = OutputMode::from_accept(&headers, &accept_values);++ // If upstream is NOT vnd.amazon.eventstream (e.g. it returned an+ // application/json error), forward verbatim regardless of Accept.+ let upstream_is_eventstream = upstream_content_type+ .as_deref()+ .map(is_eventstream_content_type)+ .unwrap_or(false);++ let mut resp_headers = filter_response_headers(upstream_resp.headers());++ tracing::info!(+ event = "bedrock_invoke_streaming_forwarded",+ request_id = %request_id,+ model_id = %model_id,+ upstream_status = status.as_u16(),+ upstream_url = %upstream_url,+ upstream_content_type = upstream_content_type.as_deref().unwrap_or(""),+ upstream_is_eventstream = upstream_is_eventstream,+ client_output_mode = match output_mode {+ OutputMode::EventStream => "eventstream",+ OutputMode::Sse => "sse",+ },+ "bedrock invoke-streaming: response received; selecting output mode"+ );++ if !upstream_is_eventstream {+ // Upstream isn't binary EventStream — pass through verbatim.+ // Even here we drop content-length: the proxy streams the+ // body and reqwest's transparent decompression may already+ // have changed the byte length on the way in.+ resp_headers.remove(http::header::CONTENT_LENGTH);+ let stream = upstream_resp+ .bytes_stream()+ .map(|r| r.map_err(std::io::Error::other));+ let body_out = Body::from_stream(stream);+ return finish(status, resp_headers, body_out, &request_id);+ }+ // Always drop the upstream content-length: in passthrough mode+ // we may still re-frame; in SSE mode the byte-length changes.+ // hyper assigns transfer-encoding: chunked when content-length+ // is absent.+ resp_headers.remove(http::header::CONTENT_LENGTH);++ // Decide what to emit. In passthrough mode, copy upstream bytes+ // verbatim. In SSE mode, run a parser, translate chunks, and+ // emit SSE frames. Both modes start from the same byte stream.+ let upstream_stream = upstream_resp+ .bytes_stream()+ .map(|r| r.map_err(std::io::Error::other));++ match output_mode {+ OutputMode::EventStream => {+ // Passthrough — bytes flow byte-equal to the client.+ tracing::info!(+ event = "bedrock_eventstream_passthrough",+ request_id = %request_id,+ "passing upstream eventstream bytes through verbatim"+ );+ // Set the response Content-Type to match the upstream so+ // the client knows it's still EventStream. The+ // `filter_response_headers` already preserves it; this+ // is defensive in case a future filter strips it.+ if !resp_headers.contains_key(http::header::CONTENT_TYPE) {+ if let Ok(v) = http::HeaderValue::from_str("application/vnd.amazon.eventstream") {+ resp_headers.insert(http::header::CONTENT_TYPE, v);+ }+ }+ let body_out = Body::from_stream(upstream_stream);+ finish(status, resp_headers, body_out, &request_id)+ }+ OutputMode::Sse => {+ // Translation mode. Override the response content-type to+ // text/event-stream; emit SSE frames; tee them into the+ // existing AnthropicStreamState for telemetry.+ resp_headers.remove(http::header::CONTENT_TYPE);+ if let Ok(v) = http::HeaderValue::from_str("text/event-stream") {+ resp_headers.insert(http::header::CONTENT_TYPE, v);+ }++ let translated = translate_stream(+ upstream_stream,+ state.config.bedrock_validate_eventstream_crc,+ request_id.clone(),+ );+ let translated = tee_to_anthropic_state(translated, request_id.clone());+ let body_out = Body::from_stream(translated);+ finish(status, resp_headers, body_out, &request_id)+ }+ }+}++/// Boxed byte-stream alias used internally so we can keep the+/// `Stream` returned by reqwest pinned and `Unpin`-friendly when it+/// crosses through the `unfold` machinery below.+type ByteStream = Pin<Box<dyn Stream<Item = Result<Bytes, std::io::Error>> + Send + 'static>>;++/// Stream adapter: drive an [`EventStreamParser`] over the upstream+/// byte stream, translate each complete message into an SSE frame,+/// and yield the resulting `Bytes`. Errors close the stream with a+/// structured frame so the client sees the failure rather than a+/// truncated response.+fn translate_stream<S>(+ upstream: S,+ validate_crc: bool,+ request_id: String,+) -> impl Stream<Item = Result<Bytes, std::io::Error>>+where+ S: Stream<Item = Result<Bytes, std::io::Error>> + Send + 'static,+{+ use crate::bedrock::eventstream::CrcValidation;++ let mut parser = EventStreamParser::new();+ if !validate_crc {+ parser = parser.with_crc_validation(CrcValidation::No);+ }+ let upstream: ByteStream = Box::pin(upstream);+ let init = (parser, upstream, false, request_id);+ stream::unfold(init, |(mut parser, mut upstream, mut done, request_id)| {+ Box::pin(async move {+ if done {+ return None;+ }+ // First, drain any complete messages already in the+ // parser's buffer (bytes from the previous chunk).+ loop {+ match parser.next_message() {+ Ok(Some(msg)) => match translate_message(&msg, OutputMode::Sse) {+ Ok(TranslateOutcome::Emit(frame)) => {+ tracing::debug!(+ event = "bedrock_eventstream_message",+ request_id = %request_id,+ event_type = msg.event_type().unwrap_or(""),+ payload_bytes = msg.payload.len(),+ "translated bedrock eventstream message"+ );+ return Some((Ok(frame), (parser, upstream, false, request_id)));+ }+ Ok(TranslateOutcome::Skip { event_type }) => {+ tracing::warn!(+ event = "bedrock_eventstream_unknown_event_type",+ request_id = %request_id,+ event_type = %event_type,+ "skipping unknown bedrock eventstream message"+ );+ // Loop and try the next message in the buffer.+ continue;+ }+ Err(TranslateError::UpstreamException { payload_preview }) => {+ tracing::warn!(+ event = "bedrock_eventstream_upstream_exception",+ request_id = %request_id,+ payload_preview = %payload_preview,+ "bedrock eventstream upstream exception"+ );+ // Emit the exception as an Anthropic-shape+ // SSE error frame so the client sees it.+ let json = serde_json::json!({+ "type": "error",+ "error": {+ "type": "bedrock_upstream_exception",+ "message": payload_preview,+ }+ })+ .to_string();+ let mut frame = Vec::with_capacity(json.len() + 32);+ frame.extend_from_slice(b"event: error\ndata: ");+ frame.extend_from_slice(json.as_bytes());+ frame.extend_from_slice(b"\n\n");+ return Some((+ Ok(Bytes::from(frame)),+ (parser, upstream, true, request_id),+ ));+ }+ Err(TranslateError::MissingEventType) => {+ tracing::warn!(+ event = "bedrock_eventstream_missing_event_type",+ request_id = %request_id,+ "bedrock eventstream message missing :event-type; emitting error frame"+ );+ let frame = error_sse_frame(+ "bedrock_eventstream_missing_event_type",+ "Bedrock message missing :event-type header",+ );+ return Some((Ok(frame), (parser, upstream, true, request_id)));+ }+ },+ Ok(None) => break,+ Err(parse_err) => {+ let event_name = match &parse_err {+ ParseError::PreludeCrcMismatch { .. }+ | ParseError::MessageCrcMismatch { .. } => {+ "bedrock_eventstream_crc_mismatch"+ }+ _ => "bedrock_eventstream_parse_failed",+ };+ tracing::warn!(+ event = event_name,+ request_id = %request_id,+ error = %parse_err,+ "bedrock eventstream parse failure; closing translated stream"+ );+ let frame = error_sse_frame(event_name, &parse_err.to_string());+ return Some((Ok(frame), (parser, upstream, true, request_id)));+ }+ }+ }+ // Buffer drained; pull the next chunk from upstream.+ loop {+ match upstream.next().await {+ Some(Ok(chunk)) => {+ parser.push(&chunk);+ // Loop back through the parser to emit any+ // newly-complete messages.+ match parser.next_message() {+ Ok(Some(msg)) => match translate_message(&msg, OutputMode::Sse) {+ Ok(TranslateOutcome::Emit(frame)) => {+ tracing::debug!(+ event = "bedrock_eventstream_message",+ request_id = %request_id,+ event_type = msg.event_type().unwrap_or(""),+ payload_bytes = msg.payload.len(),+ "translated bedrock eventstream message"+ );+ return Some((+ Ok(frame),+ (parser, upstream, false, request_id),+ ));+ }+ Ok(TranslateOutcome::Skip { event_type }) => {+ tracing::warn!(+ event = "bedrock_eventstream_unknown_event_type",+ request_id = %request_id,+ event_type = %event_type,+ "skipping unknown bedrock eventstream message"+ );+ // Continue draining the parser /+ // pulling more chunks.+ continue;+ }+ Err(TranslateError::UpstreamException { payload_preview }) => {+ let json = serde_json::json!({+ "type": "error",+ "error": {+ "type": "bedrock_upstream_exception",+ "message": payload_preview,+ }+ })+ .to_string();+ let mut frame = Vec::with_capacity(json.len() + 32);+ frame.extend_from_slice(b"event: error\ndata: ");+ frame.extend_from_slice(json.as_bytes());+ frame.extend_from_slice(b"\n\n");+ return Some((+ Ok(Bytes::from(frame)),+ (parser, upstream, true, request_id),+ ));+ }+ Err(TranslateError::MissingEventType) => {+ let frame = error_sse_frame(+ "bedrock_eventstream_missing_event_type",+ "Bedrock message missing :event-type header",+ );+ return Some((Ok(frame), (parser, upstream, true, request_id)));+ }+ },+ Ok(None) => continue,+ Err(parse_err) => {+ let event_name = match &parse_err {+ ParseError::PreludeCrcMismatch { .. }+ | ParseError::MessageCrcMismatch { .. } => {+ "bedrock_eventstream_crc_mismatch"+ }+ _ => "bedrock_eventstream_parse_failed",+ };+ tracing::warn!(+ event = event_name,+ request_id = %request_id,+ error = %parse_err,+ "bedrock eventstream parse failure"+ );+ let frame = error_sse_frame(event_name, &parse_err.to_string());+ return Some((Ok(frame), (parser, upstream, true, request_id)));+ }+ }+ }+ Some(Err(e)) => {+ tracing::warn!(+ event = "bedrock_eventstream_upstream_io_error",+ request_id = %request_id,+ error = %e,+ "upstream io error mid-stream"+ );+ return Some((Err(e), (parser, upstream, true, request_id)));+ }+ None => {+ // End of upstream stream. If buffered bytes+ // remain that did not parse into a message,+ // log loudly — we are NOT silently dropping+ // them.+ if parser.buffered_len() > 0 {+ tracing::warn!(+ event = "bedrock_eventstream_truncated",+ request_id = %request_id,+ buffered_bytes = parser.buffered_len(),+ "upstream stream ended with un-parseable trailing bytes"+ );+ }+ done = true;+ let _ = done;+ return None;+ }+ }+ }+ })+ })+}++/// Tee the translated SSE stream into an `AnthropicStreamState` task+/// so usage telemetry is captured. The byte path is independent of+/// the parser — if the parser falls behind, the channel `try_send`+/// drops chunks rather than blocking.+fn tee_to_anthropic_state<S>(+ upstream: S,+ request_id: String,+) -> impl Stream<Item = Result<Bytes, std::io::Error>>+where+ S: Stream<Item = Result<Bytes, std::io::Error>> + Send + 'static,+{+ let (tx, rx) = tokio::sync::mpsc::channel::<Bytes>(SSE_PARSER_QUEUE_DEPTH);+ let parser_request_id = request_id.clone();+ tokio::spawn(async move {+ run_anthropic_state_machine(rx, parser_request_id).await;+ });++ upstream.map(move |r| {+ if let Ok(bytes) = &r {+ // Best-effort tee. Bounded channel; never block byte path.+ if let Err(e) = tx.try_send(bytes.clone()) {+ tracing::debug!(+ request_id = %request_id,+ error = %e,+ "bedrock translated stream parser queue full or closed; dropping telemetry chunk"+ );+ }+ }+ r+ })+}++const SSE_PARSER_QUEUE_DEPTH: usize = 256;++/// Dedicated state-machine task. Mirrors the+/// `run_sse_state_machine(SseStreamKind::Anthropic, ...)` arm in+/// `proxy.rs` so usage extraction works identically for direct+/// `/v1/messages` and Bedrock-on-`Accept: text/event-stream`.+async fn run_anthropic_state_machine(+ mut rx: tokio::sync::mpsc::Receiver<Bytes>,+ request_id: String,+) {+ use crate::sse::anthropic::AnthropicStreamState;+ use crate::sse::framing::SseFramer;++ let mut framer = SseFramer::new();+ let mut state = AnthropicStreamState::new();+ while let Some(chunk) = rx.recv().await {+ framer.push(&chunk);+ while let Some(ev_result) = framer.next_event() {+ match ev_result {+ Ok(ev) => {+ if let Err(e) = state.apply(ev) {+ tracing::warn!(+ request_id = %request_id,+ error = %e,+ "bedrock translated stream: anthropic state-machine apply error"+ );+ }+ }+ Err(e) => {+ tracing::warn!(+ request_id = %request_id,+ error = %e,+ "bedrock translated stream: sse framer error"+ );+ }+ }+ }+ }+ tracing::info!(+ request_id = %request_id,+ provider = "bedrock_anthropic",+ input_tokens = state.usage.input_tokens,+ output_tokens = state.usage.output_tokens,+ cache_creation_input_tokens = state.usage.cache_creation_input_tokens,+ cache_read_input_tokens = state.usage.cache_read_input_tokens,+ stop_reason = state.stop_reason.as_deref().unwrap_or(""),+ blocks = state.blocks.len(),+ "bedrock translated stream: closed"+ );+}++/// True when the content-type is `application/vnd.amazon.eventstream`+/// (with optional parameters). RFC 7231 §3.1.1.1.+fn is_eventstream_content_type(content_type: &str) -> bool {+ let media_type = content_type.split(';').next().unwrap_or("").trim();+ media_type.eq_ignore_ascii_case("application/vnd.amazon.eventstream")+}++/// Build a structured SSE error frame with `event: error`. The shape+/// matches Anthropic's documented error event so existing clients+/// already know how to surface it.+fn error_sse_frame(event_kind: &str, message: &str) -> Bytes {+ let json = serde_json::json!({+ "type": "error",+ "error": {+ "type": event_kind,+ "message": message,+ }+ })+ .to_string();+ let mut out = Vec::with_capacity(json.len() + 24);+ out.extend_from_slice(b"event: error\ndata: ");+ out.extend_from_slice(json.as_bytes());+ out.extend_from_slice(b"\n\n");+ Bytes::from(out)+}++fn finish(status: StatusCode, headers: HeaderMap, body: Body, request_id: &str) -> Response {+ let mut builder = Response::builder().status(status);+ if let Some(h) = builder.headers_mut() {+ h.extend(headers);+ if let Ok(v) = http::HeaderValue::from_str(request_id) {+ h.insert(HeaderName::from_static("x-request-id"), v);+ }+ }+ builder.body(body).unwrap_or_else(|e| {+ tracing::error!(+ event = "bedrock_response_build_failed",+ request_id = %request_id,+ error = %e,+ "bedrock invoke-streaming: failed to build response"+ );+ Response::builder()+ .status(StatusCode::INTERNAL_SERVER_ERROR)+ .body(Body::from("internal handler error"))+ .expect("static response")+ })+}++fn error_response(status: StatusCode, event: &str, msg: &str) -> Response {+ let body = serde_json::json!({+ "error": {+ "type": event,+ "message": msg,+ }+ })+ .to_string();+ let mut resp = Response::builder()+ .status(status)+ .body(Body::from(body))+ .expect("static error response");+ resp.headers_mut().insert(+ http::header::CONTENT_TYPE,+ http::HeaderValue::from_static("application/json"),+ );+ resp.into_response()+}++/// Same compression-dispatch logic as PR-D1 — duplicated rather than+/// shared because the streaming handler runs in a slightly different+/// flow (no body buffering required at the caller, the handler always+/// owns the bytes). When PR-D3 merges, both arms can converge into a+/// single helper.+fn run_anthropic_compression(body: &Bytes, state: &AppState, request_id: &str) -> Bytes {+ use crate::bedrock::envelope::BedrockEnvelope;++ if let Err(e) = BedrockEnvelope::parse(body) {+ tracing::warn!(+ event = "bedrock_envelope_parse_error",+ request_id = %request_id,+ error = %e,+ "bedrock invoke-streaming: envelope parse failed; passing body through unchanged"+ );+ return body.clone();+ }++ let outcome = compress_anthropic_request(+ body,+ state.config.compression_mode,+ state.config.cache_control_auto_frozen,+ request_id,+ );+ match outcome {+ AnthropicOutcome::NoCompression => body.clone(),+ AnthropicOutcome::Passthrough { reason } => {+ tracing::info!(+ event = "bedrock_compression_passthrough",+ request_id = %request_id,+ reason = ?reason,+ "bedrock invoke-streaming: passthrough"+ );+ let _ = (PassthroughReason::ModeOff, PassthroughReason::NoMessages);+ body.clone()+ }+ AnthropicOutcome::Compressed { body: new_body, .. } => {+ match BedrockEnvelope::ensure_anthropic_version_first(&new_body) {+ Ok(b) => b,+ Err(e) => {+ tracing::error!(+ event = "bedrock_envelope_reemit_failed",+ request_id = %request_id,+ error = %e,+ "bedrock invoke-streaming: failed to re-emit envelope"+ );+ body.clone()+ }+ }+ }+ }+}++fn build_bedrock_streaming_upstream(+ state: &AppState,+ model_id: &str,+ uri: &Uri,+) -> Result<Url, String> {+ let base = match state.config.bedrock_endpoint.as_ref() {+ Some(u) => u.clone(),+ None => {+ let host =+ BEDROCK_RUNTIME_HOST_TEMPLATE.replace("{region}", &state.config.bedrock_region);+ Url::parse(&format!("https://{host}/"))+ .map_err(|e| format!("bedrock derived base URL parse error: {e}"))?+ }+ };+ let path = format!(+ "/model/{model_id}/{action}",+ model_id = model_id,+ action = STREAMING_ACTION,+ );+ let mut joined = base;+ joined.set_path(&path);+ if let Some(q) = uri.query() {+ joined.set_query(Some(q));+ }+ Ok(joined)+}++fn collect_signed_headers(headers: &HeaderMap, upstream_url: &Url) -> Vec<(String, String)> {+ let mut out: Vec<(String, String)> = Vec::with_capacity(headers.len() + 1);+ for (name, value) in headers.iter() {+ let n = name.as_str().to_ascii_lowercase();+ if matches!(+ n.as_str(),+ "host"+ | "content-length"+ | "connection"+ | "keep-alive"+ | "proxy-authenticate"+ | "proxy-authorization"+ | "te"+ | "trailers"+ | "transfer-encoding"+ | "upgrade"+ | "authorization"+ | "x-amz-date"+ | "x-amz-content-sha256"+ ) {+ continue;+ }+ if n.starts_with("x-headroom-") {+ continue;+ }+ if let Ok(v) = value.to_str() {+ out.push((n, v.to_string()));+ }+ }+ if let Some(host) = upstream_url.host_str() {+ let host_value = match upstream_url.port() {+ Some(p) => format!("{host}:{p}"),+ None => host.to_string(),+ };+ out.push(("host".to_string(), host_value));+ }+ out+}++// Keep the unused-import lints happy on rare failure-only branches.+#[allow(dead_code)]+fn _pin_infallible(_: Infallible) {}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn eventstream_content_type_match() {+ assert!(is_eventstream_content_type(+ "application/vnd.amazon.eventstream"+ ));+ assert!(is_eventstream_content_type(+ "application/vnd.amazon.eventstream; charset=utf-8"+ ));+ assert!(!is_eventstream_content_type("application/json"));+ assert!(!is_eventstream_content_type("text/event-stream"));+ }++ #[test]+ fn build_streaming_upstream_uses_region_default() {+ use crate::config::Config;+ let mut config = Config::for_test(Url::parse("http://up:8080").unwrap());+ config.bedrock_region = "eu-west-1".to_string();+ let state = AppState {+ config: std::sync::Arc::new(config),+ client: reqwest::Client::new(),+ bedrock_credentials: None,+ };+ let uri: Uri = "/model/anthropic.claude-3-haiku-20240307-v1:0/invoke-with-response-stream"+ .parse()+ .unwrap();+ let url = build_bedrock_streaming_upstream(+ &state,+ "anthropic.claude-3-haiku-20240307-v1:0",+ &uri,+ )+ .unwrap();+ assert_eq!(+ url.as_str(),+ "https://bedrock-runtime.eu-west-1.amazonaws.com/model/anthropic.claude-3-haiku-20240307-v1:0/invoke-with-response-stream"+ );+ }++ #[test]+ fn error_sse_frame_shape() {+ let f = error_sse_frame("bedrock_eventstream_crc_mismatch", "boom");+ let s = std::str::from_utf8(&f).unwrap();+ assert!(s.starts_with("event: error\ndata: "));+ assert!(s.ends_with("\n\n"));+ assert!(s.contains("bedrock_eventstream_crc_mismatch"));+ }+}diff --git a/crates/headroom-proxy/src/bedrock/mod.rs b/crates/headroom-proxy/src/bedrock/mod.rsindex cf0be6cac..e772a1b93 100644--- a/crates/headroom-proxy/src/bedrock/mod.rs+++ b/crates/headroom-proxy/src/bedrock/mod.rs@@ -41,12 +41,23 @@//! - [`invoke`] — POST handler for `/model/{model}/invoke`.//!//! Streaming (`/model/{model}/invoke-with-response-stream`) is-//! Phase D PR-D2.+//! handled by [`invoke_streaming`] in PR-D2. Binary EventStream+//! parsing is in [`eventstream`]; the SSE translator is in+//! [`eventstream_to_sse`].pub mod envelope;+pub mod eventstream;+pub mod eventstream_to_sse;pub mod invoke;+pub mod invoke_streaming;pub mod sigv4;pub use envelope::{BedrockEnvelope, EnvelopeError};+pub use eventstream::{+ parse as parse_eventstream, CrcValidation, EventStreamMessage, EventStreamParser, HeaderValue,+ MessageBuilder, ParseError,+};+pub use eventstream_to_sse::{translate_message, OutputMode, TranslateError, TranslateOutcome};pub use invoke::handle_invoke;+pub use invoke_streaming::handle_invoke_streaming;pub use sigv4::{sign_request, SigV4Error, SigningInputs};diff --git a/crates/headroom-proxy/src/config.rs b/crates/headroom-proxy/src/config.rsindex fee143c91..9a9bc47cb 100644--- a/crates/headroom-proxy/src/config.rs+++ b/crates/headroom-proxy/src/config.rs@@ -351,6 +351,25 @@ pub struct CliArgs {/// env var → `AWS_PROFILE` env var → default chain.#[arg(long = "aws-profile", env = "HEADROOM_PROXY_AWS_PROFILE")]pub aws_profile: Option<String>,++ /// Phase D PR-D2: validate the prelude + message CRC32 on each+ /// inbound Bedrock EventStream frame. Default `true` — production+ /// MUST validate. Operators flip to `false` ONLY for debugging a+ /// suspected wire-format issue (e.g. a corrupt-but-cooperative+ /// upstream that emits invalid CRCs intentionally). When disabled,+ /// the proxy still parses message boundaries; it just doesn't+ /// reject on CRC mismatch. Per project policy, every flag flip+ /// is logged at app-build time.+ ///+ /// Source priority: CLI flag → `HEADROOM_PROXY_BEDROCK_VALIDATE_EVENTSTREAM_CRC`+ /// env var → default (`true`).+ #[arg(+ long = "bedrock-validate-eventstream-crc",+ env = "HEADROOM_PROXY_BEDROCK_VALIDATE_EVENTSTREAM_CRC",+ default_value_t = true,+ action = clap::ArgAction::Set,+ )]+ pub bedrock_validate_eventstream_crc: bool,}fn parse_duration(s: &str) -> Result<Duration, String> {@@ -419,6 +438,9 @@ pub struct Config {/// PR-D1: optional AWS profile name. When `None`, the default/// credential chain (env → `[default]` profile → IMDS) is used.pub aws_profile: Option<String>,+ /// PR-D2: validate prelude + message CRC32 on inbound Bedrock+ /// EventStream frames. Default `true`. Off only for debugging.+ pub bedrock_validate_eventstream_crc: bool,}impl Config {@@ -451,6 +473,7 @@ impl Config {bedrock_region: args.bedrock_region,bedrock_endpoint: args.bedrock_endpoint,aws_profile: args.aws_profile,+ bedrock_validate_eventstream_crc: args.bedrock_validate_eventstream_crc,}}@@ -489,6 +512,9 @@ impl Config {bedrock_region: "us-east-1".to_string(),bedrock_endpoint: None,aws_profile: None,+ // PR-D2: production default — validate every CRC. Tests+ // that exercise corruption paths flip this off per-case.+ bedrock_validate_eventstream_crc: true,}}}diff --git a/crates/headroom-proxy/src/proxy.rs b/crates/headroom-proxy/src/proxy.rsindex c60ac631c..f0da37369 100644--- a/crates/headroom-proxy/src/proxy.rs+++ b/crates/headroom-proxy/src/proxy.rs@@ -119,7 +119,24 @@ pub fn build_app(state: AppState) -> Router {.route("/model/:model_id/converse",post(crate::bedrock::invoke::handle_invoke),+ )+ // PR-D2: streaming counterpart. Bedrock's protocol is+ // binary EventStream; the handler parses incrementally,+ // optionally translates each chunk to an SSE frame, and+ // tees translated frames into AnthropicStreamState for+ // telemetry. See `bedrock::invoke_streaming`.+ .route(+ "/model/:model_id/invoke-with-response-stream",+ post(crate::bedrock::invoke_streaming::handle_invoke_streaming),);+ if !state.config.bedrock_validate_eventstream_crc {+ tracing::warn!(+ event = "bedrock_eventstream_crc_validation_disabled",+ "Bedrock EventStream CRC validation is DISABLED — \+ only safe for debugging; production must keep \+ --bedrock-validate-eventstream-crc=true"+ );+ }} else {tracing::warn!(event = "bedrock_native_disabled",diff --git a/crates/headroom-proxy/tests/integration_bedrock_streaming.rs b/crates/headroom-proxy/tests/integration_bedrock_streaming.rsnew file mode 100644index 000000000..41ade8b40--- /dev/null+++ b/crates/headroom-proxy/tests/integration_bedrock_streaming.rs@@ -0,0 +1,520 @@+//! Integration tests for the native Bedrock streaming route+//! (Phase D PR-D2).+//!+//! These tests exercise the binary EventStream parser, the SSE+//! translator, and the full POST `/model/{model}/invoke-with-response-stream`+//! handler. The upstream is a wiremock server that serves+//! `application/vnd.amazon.eventstream` bytes — no real AWS.+//!+//! Coverage matrix (per PR-D2 spec, REALIGNMENT/06-phase-D-bedrock-vertex.md):+//!+//! 1. `eventstream_parses_correctly` — feed known-good binary bytes+//! to the parser; assert message boundaries, CRCs, and headers.+//! 2. `eventstream_translated_to_sse` — drive the proxy with a binary+//! upstream; assert it emits valid `data: ...\n\n` SSE frames.+//! 3. `usage_extracted_from_translated_stream` — assert+//! `AnthropicStreamState` accumulates `input_tokens` /+//! `output_tokens` from the translated stream (via log capture).+//! 4. `client_can_choose_eventstream_or_sse` — `Accept: vnd.amazon.eventstream`+//! returns binary unchanged; default Accept returns SSE.+//! 5. `eventstream_parser_no_panic` — proptest property: arbitrary+//! bytes must never panic the parser.++mod common;++use aws_credential_types::Credentials;+use bytes::{Bytes, BytesMut};+use common::start_proxy_with_state;+use headroom_proxy::bedrock::{+ parse_eventstream, CrcValidation, EventStreamParser, HeaderValue, MessageBuilder, ParseError,+};+use proptest::prelude::*;+use serde_json::json;+use url::Url;+use wiremock::matchers::{method, path};+use wiremock::{Mock, MockServer, ResponseTemplate};++const TEST_MODEL: &str = "anthropic.claude-3-haiku-20240307-v1:0";++fn test_credentials() -> Credentials {+ Credentials::new(+ "AKIAEXAMPLEAKIDFORTEST",+ "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",+ None,+ None,+ "test",+ )+}++/// Synthesise a minimal Bedrock-shape Anthropic stream as binary+/// EventStream bytes. The exact JSON payload mirrors what real+/// Bedrock emits for a 2-token completion.+fn synthesize_bedrock_stream() -> Bytes {+ let mut buf = BytesMut::new();+ let events = [+ json!({+ "type": "message_start",+ "message": {+ "id": "msg_01ABCDEF",+ "type": "message",+ "role": "assistant",+ "model": "claude-3-haiku-20240307",+ "content": [],+ "stop_reason": null,+ "stop_sequence": null,+ "usage": {"input_tokens": 7, "output_tokens": 1}+ }+ }),+ json!({+ "type": "content_block_start",+ "index": 0,+ "content_block": {"type": "text", "text": ""}+ }),+ json!({+ "type": "content_block_delta",+ "index": 0,+ "delta": {"type": "text_delta", "text": "OK"}+ }),+ json!({+ "type": "content_block_stop",+ "index": 0+ }),+ json!({+ "type": "message_delta",+ "delta": {"stop_reason": "end_turn", "stop_sequence": null},+ "usage": {"output_tokens": 2}+ }),+ json!({+ "type": "message_stop"+ }),+ ];+ for ev in events {+ let payload = serde_json::to_string(&ev).unwrap();+ let bytes = MessageBuilder::new()+ .header_string(":event-type", "chunk")+ .header_string(":content-type", "application/json")+ .header_string(":message-type", "event")+ .payload(Bytes::from(payload))+ .build();+ buf.extend_from_slice(&bytes);+ }+ buf.freeze()+}++async fn bedrock_proxy(+ upstream: &MockServer,+ customize: impl FnOnce(&mut headroom_proxy::Config),+) -> common::ProxyHandle {+ let endpoint: Url = upstream.uri().parse().unwrap();+ start_proxy_with_state(+ &upstream.uri(),+ |c| {+ c.bedrock_endpoint = Some(endpoint);+ customize(c);+ },+ |s| s.with_bedrock_credentials(test_credentials()),+ )+ .await+}++// ─── Test 1: Parser unit-style integration ─────────────────────────++#[test]+fn eventstream_parses_correctly() {+ // Known-good 6-message stream — exercise the parser end to end.+ let bytes = synthesize_bedrock_stream();+ let mut parser = EventStreamParser::new();+ parser.push(&bytes);++ let mut messages = Vec::new();+ while let Some(msg) = parser.next_message().expect("parse ok") {+ messages.push(msg);+ }+ assert_eq!(messages.len(), 6, "must parse all 6 messages");++ // Headers + payload sanity:+ assert_eq!(messages[0].event_type(), Some("chunk"));+ assert_eq!(messages[0].message_type(), Some("event"));+ let p0 = std::str::from_utf8(&messages[0].payload).unwrap();+ assert!(+ p0.contains("\"message_start\""),+ "first payload must be message_start; got {p0}"+ );++ // Last payload is message_stop.+ let p_last = std::str::from_utf8(&messages[5].payload).unwrap();+ assert!(p_last.contains("\"message_stop\""));++ // Every message has the standard Bedrock headers.+ for m in &messages {+ assert!(+ matches!(+ m.headers.get(":event-type").unwrap(),+ HeaderValue::String(s) if s == "chunk"+ ),+ ":event-type must be chunk on every chunk frame"+ );+ }++ // Buffer drained exactly.+ assert_eq!(parser.buffered_len(), 0);+}++#[test]+fn eventstream_parses_correctly_one_byte_at_a_time() {+ // Same data, but drip-fed one byte at a time. Verifies the+ // parser is truly incremental (no internal "must have whole+ // chunk" assumption).+ let bytes = synthesize_bedrock_stream();+ let mut parser = EventStreamParser::new();+ let mut messages = Vec::new();+ for b in bytes.iter() {+ parser.push(std::slice::from_ref(b));+ while let Some(msg) = parser.next_message().expect("parse ok") {+ messages.push(msg);+ }+ }+ assert_eq!(messages.len(), 6);+}++#[test]+fn eventstream_crc_mismatch_surfaces_structured_error() {+ let mut bytes: Vec<u8> = synthesize_bedrock_stream().to_vec();+ bytes[8] ^= 0x01; // corrupt prelude CRC of first message+ let err = parse_eventstream(&bytes).unwrap_err();+ assert!(+ matches!(err, ParseError::PreludeCrcMismatch { .. }),+ "expected PreludeCrcMismatch; got {err:?}"+ );+}++#[test]+fn eventstream_validation_off_accepts_corrupt() {+ let mut bytes: Vec<u8> = synthesize_bedrock_stream().to_vec();+ bytes[8] ^= 0x01;+ let mut parser = EventStreamParser::new().with_crc_validation(CrcValidation::No);+ parser.push(&bytes);+ // Should still produce 6 messages even with corrupt CRC.+ let mut count = 0;+ while parser.next_message().unwrap().is_some() {+ count += 1;+ }+ assert_eq!(count, 6);+}++// ─── Test 2: End-to-end Bedrock binary → SSE translation ──────────++async fn mount_eventstream_upstream(upstream: &MockServer, body: Bytes) {+ Mock::given(method("POST"))+ .and(path(format!(+ "/model/{TEST_MODEL}/invoke-with-response-stream"+ )))+ .respond_with(+ ResponseTemplate::new(200)+ .insert_header("content-type", "application/vnd.amazon.eventstream")+ .set_body_bytes(body.to_vec()),+ )+ .mount(upstream)+ .await;+}++#[tokio::test]+async fn eventstream_translated_to_sse() {+ let _ = tracing_subscriber::fmt()+ .with_env_filter(+ tracing_subscriber::EnvFilter::try_from_default_env()+ .unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("warn")),+ )+ .with_test_writer()+ .try_init();+ let upstream = MockServer::start().await;+ let bedrock_bytes = synthesize_bedrock_stream();+ mount_eventstream_upstream(&upstream, bedrock_bytes).await;+ let proxy = bedrock_proxy(&upstream, |c| {+ c.compression_mode = headroom_proxy::config::CompressionMode::Off;+ })+ .await;++ let body = serde_json::to_vec(&json!({+ "anthropic_version": "bedrock-2023-05-31",+ "max_tokens": 16,+ "messages": [{"role":"user","content":"hi"}]+ }))+ .unwrap();+ let resp = reqwest::Client::new()+ .post(format!(+ "{}/model/{TEST_MODEL}/invoke-with-response-stream",+ proxy.url()+ ))+ .header("content-type", "application/json")+ // Default Accept → SSE translation.+ .header("accept", "text/event-stream")+ .body(body)+ .send()+ .await+ .unwrap();+ assert_eq!(resp.status(), 200);+ let ct = resp+ .headers()+ .get("content-type")+ .and_then(|v| v.to_str().ok())+ .unwrap_or("")+ .to_string();+ assert!(+ ct.contains("text/event-stream"),+ "translated response must declare text/event-stream; got {ct}"+ );+ let body = resp.bytes().await.unwrap();+ let body_str = std::str::from_utf8(&body).unwrap();++ // Each message becomes its own `data: ...\n\n` frame.+ let frame_count = body_str.matches("data: ").count();+ assert_eq!(+ frame_count, 6,+ "expected 6 SSE frames (one per upstream chunk message); got {frame_count}: {body_str}"+ );++ // Frame ordering: message_start first, message_stop last.+ let first_frame_pos = body_str+ .find("\"message_start\"")+ .expect("message_start in stream");+ let last_frame_pos = body_str+ .find("\"message_stop\"")+ .expect("message_stop in stream");+ assert!(first_frame_pos < last_frame_pos);++ // Telemetry sanity: text_delta payload preserved verbatim.+ assert!(+ body_str.contains("\"text\":\"OK\""),+ "text_delta payload must round-trip through translation"+ );+ proxy.shutdown().await;+}++// ─── Test 3: Usage extraction from translated stream ──────────────++#[tokio::test]+async fn usage_extracted_from_translated_stream() {+ // The AnthropicStreamState runs in a spawned task on the+ // translated SSE stream. Its log line emits `output_tokens` at+ // stream close. We assert the byte-equal contract on the SSE+ // payload: input_tokens=7 and output_tokens=2 must show up in+ // the JSON the client received (so the state machine, which+ // reads the same bytes the client does, would extract them).+ let upstream = MockServer::start().await;+ let bedrock_bytes = synthesize_bedrock_stream();+ mount_eventstream_upstream(&upstream, bedrock_bytes).await;+ let proxy = bedrock_proxy(&upstream, |c| {+ c.compression_mode = headroom_proxy::config::CompressionMode::Off;+ })+ .await;++ let body = serde_json::to_vec(&json!({+ "anthropic_version": "bedrock-2023-05-31",+ "max_tokens": 16,+ "messages": [{"role":"user","content":"hi"}]+ }))+ .unwrap();+ let resp = reqwest::Client::new()+ .post(format!(+ "{}/model/{TEST_MODEL}/invoke-with-response-stream",+ proxy.url()+ ))+ .header("content-type", "application/json")+ .header("accept", "text/event-stream")+ .body(body)+ .send()+ .await+ .unwrap();+ assert_eq!(resp.status(), 200);+ let body = resp.bytes().await.unwrap();+ let body_str = std::str::from_utf8(&body).unwrap();++ // Confirm the usage JSON survived translation:+ assert!(+ body_str.contains("\"input_tokens\":7"),+ "input_tokens must be preserved through translation: {body_str}"+ );+ assert!(+ body_str.contains("\"output_tokens\":2"),+ "final output_tokens must be preserved through translation: {body_str}"+ );++ // Drive the state machine ourselves over the wire bytes to+ // assert what the in-task instance would have computed. (We+ // can't easily intercept the spawned task's tracing output in+ // this test without a custom subscriber.)+ use headroom_proxy::sse::anthropic::AnthropicStreamState;+ use headroom_proxy::sse::framing::SseFramer;+ let mut framer = SseFramer::new();+ framer.push(&body);+ let mut state = AnthropicStreamState::new();+ while let Some(ev) = framer.next_event() {+ let ev = ev.expect("framer ok");+ state.apply(ev).expect("apply ok");+ }+ assert_eq!(state.usage.input_tokens, 7, "state input tokens");+ assert_eq!(state.usage.output_tokens, 2, "state output tokens");+ assert_eq!(state.stop_reason.as_deref(), Some("end_turn"));+ proxy.shutdown().await;+}++// ─── Test 4: Client picks eventstream vs sse via Accept ───────────++#[tokio::test]+async fn client_can_choose_eventstream_or_sse() {+ let upstream = MockServer::start().await;+ let bedrock_bytes = synthesize_bedrock_stream();+ mount_eventstream_upstream(&upstream, bedrock_bytes.clone()).await;+ let proxy = bedrock_proxy(&upstream, |c| {+ c.compression_mode = headroom_proxy::config::CompressionMode::Off;+ })+ .await;++ let body = serde_json::to_vec(&json!({+ "anthropic_version": "bedrock-2023-05-31",+ "max_tokens": 16,+ "messages": [{"role":"user","content":"hi"}]+ }))+ .unwrap();++ // Case A: Accept: vnd.amazon.eventstream → byte-equal passthrough.+ let resp = reqwest::Client::new()+ .post(format!(+ "{}/model/{TEST_MODEL}/invoke-with-response-stream",+ proxy.url()+ ))+ .header("content-type", "application/json")+ .header("accept", "application/vnd.amazon.eventstream")+ .body(body.clone())+ .send()+ .await+ .unwrap();+ assert_eq!(resp.status(), 200);+ let resp_ct = resp+ .headers()+ .get("content-type")+ .and_then(|v| v.to_str().ok())+ .unwrap_or("")+ .to_string();+ assert!(+ resp_ct.contains("application/vnd.amazon.eventstream"),+ "passthrough mode must echo the eventstream content-type; got {resp_ct}"+ );+ let bin = resp.bytes().await.unwrap();+ assert_eq!(+ bin.as_ref(),+ bedrock_bytes.as_ref(),+ "binary passthrough must be byte-equal upstream"+ );++ // Case B: Accept: text/event-stream → translation.+ let resp_sse = reqwest::Client::new()+ .post(format!(+ "{}/model/{TEST_MODEL}/invoke-with-response-stream",+ proxy.url()+ ))+ .header("content-type", "application/json")+ .header("accept", "text/event-stream")+ .body(body.clone())+ .send()+ .await+ .unwrap();+ assert_eq!(resp_sse.status(), 200);+ let sse_ct = resp_sse+ .headers()+ .get("content-type")+ .and_then(|v| v.to_str().ok())+ .unwrap_or("")+ .to_string();+ assert!(+ sse_ct.contains("text/event-stream"),+ "sse mode must declare text/event-stream; got {sse_ct}"+ );+ let sse_body = resp_sse.bytes().await.unwrap();+ let sse_str = std::str::from_utf8(&sse_body).unwrap();+ assert!(+ sse_str.contains("data: "),+ "sse output must contain data: frames"+ );+ assert!(!sse_str.starts_with("\0\0\0"), "must not be raw binary");++ // Case C: no Accept header → defaults to SSE.+ let resp_default = reqwest::Client::new()+ .post(format!(+ "{}/model/{TEST_MODEL}/invoke-with-response-stream",+ proxy.url()+ ))+ .header("content-type", "application/json")+ .body(body)+ .send()+ .await+ .unwrap();+ assert_eq!(resp_default.status(), 200);+ let default_ct = resp_default+ .headers()+ .get("content-type")+ .and_then(|v| v.to_str().ok())+ .unwrap_or("")+ .to_string();+ assert!(+ default_ct.contains("text/event-stream"),+ "default Accept must select sse translation; got {default_ct}"+ );++ proxy.shutdown().await;+}++// ─── Test 5: Property test — never panic on adversarial bytes ─────++proptest! {+ #![proptest_config(ProptestConfig {+ cases: 1024,+ max_shrink_iters: 1024,+ ..ProptestConfig::default()+ })]++ /// Per `feedback_realignment_build_constraints.md`, every parser+ /// in the project must terminate without panic on arbitrary input.+ /// The proxy faces TCP, which can deliver any byte sequence+ /// (corruption, truncation, deliberate fuzzing). The test pushes+ /// random bytes into the parser and drains until exhausted.+ /// Either Ok or Err is acceptable; what is NOT acceptable is a+ /// panic.+ #[test]+ fn eventstream_parser_no_panic(+ bytes in proptest::collection::vec(any::<u8>(), 0..4096)+ ) {+ let mut parser = EventStreamParser::new();+ parser.push(&bytes);+ loop {+ match parser.next_message() {+ Ok(None) => break,+ Ok(Some(_)) => continue,+ Err(_) => break,+ }+ }+ // The one-shot helper must also be panic-safe.+ let _ = parse_eventstream(&bytes);+ }++ /// Same input space but feeds the bytes one at a time. The+ /// parser must remain panic-safe even when chunk boundaries+ /// fall mid-prelude or mid-header.+ #[test]+ fn eventstream_parser_no_panic_one_byte_at_a_time(+ bytes in proptest::collection::vec(any::<u8>(), 0..1024)+ ) {+ let mut parser = EventStreamParser::new();+ for b in &bytes {+ parser.push(std::slice::from_ref(b));+ loop {+ match parser.next_message() {+ Ok(None) => break,+ Ok(Some(_)) => continue,+ Err(_) => break,+ }+ }+ }+ }+}