Skip to main content

dynamo_runtime/pipeline/
network.rs

1// SPDX-FileCopyrightText: Copyright (c) 2024-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Network layer for distributed communication
5//!
6//! Provides request distribution across multiple transport protocols:
7//! - HTTP/2 for standard deployments
8//! - TCP with length-prefixed protocol for high-performance scenarios
9//! - NATS for legacy/messaging-based deployments
10
11pub mod codec;
12pub mod egress;
13pub mod ingress;
14pub mod manager;
15pub mod quic_response;
16pub mod tcp;
17mod tombstones;
18pub mod velo_response;
19
20use crate::SystemHealth;
21use crate::error::{DynamoError, ErrorType};
22use crate::traits::DistributedRuntimeProvider;
23use std::sync::{Arc, OnceLock};
24
25use anyhow::Result;
26use async_trait::async_trait;
27use bytes::Bytes;
28use codec::{TwoPartCodec, TwoPartMessage, TwoPartMessageType};
29use derive_builder::Builder;
30use futures::StreamExt;
31// io::Cursor, TryStreamExt
32use super::{AsyncEngine, AsyncEngineContext, AsyncEngineContextProvider, ResponseStream};
33use serde::{Deserialize, Serialize, de::DeserializeOwned};
34
35use super::{
36    AsyncTransportEngine, Context, Data, Error, ManyIn, ManyOut, PipelineError, PipelineIO,
37    SegmentSource, ServiceBackend, ServiceEngine, SingleIn, Source, context,
38};
39use crate::metrics::MetricsHierarchy;
40use crate::metrics::prometheus_names::work_handler;
41use crate::protocols::maybe_error::MaybeError;
42use crate::telemetry::LifecycleOperationRole;
43use ingress::push_handler::WorkHandlerMetrics;
44use prometheus::{CounterVec, Histogram, IntCounter, IntCounterVec, IntGauge};
45
46/// Shared default maximum TCP message size across request-plane components.
47pub(crate) const DEFAULT_TCP_MAX_MESSAGE_SIZE: usize = 32 * 1024 * 1024;
48
49/// Prefix a request-plane server writes on the request connection to reject a request it cannot
50/// serve. The client matches on it to classify the reply as a rejection rather than the success
51/// ACK; anything it does not recognise is read as the ACK and it waits for a response stream.
52/// Both ends must use this constant.
53pub(crate) const ACK_UNAVAILABLE_PREFIX: &str = "Server unavailable:";
54
55static REQUEST_PLANE_PAYLOAD_CODEC: OnceLock<RequestPlanePayloadCodec> = OnceLock::new();
56static RESPONSE_PLANE_MODE: OnceLock<ResponsePlaneMode> = OnceLock::new();
57
58/// Process-wide response transport. Frontends and workers must use the same mode.
59#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
60pub enum ResponsePlaneMode {
61    #[default]
62    Tcp,
63    Quic,
64    Velo,
65}
66
67impl ResponsePlaneMode {
68    pub fn configured() -> Result<Self> {
69        if let Some(mode) = RESPONSE_PLANE_MODE.get() {
70            return Ok(*mode);
71        }
72        let value =
73            std::env::var(crate::config::environment_names::response_plane::DYN_RESPONSE_PLANE)
74                .ok();
75        let mode = Self::from_config_value(value.as_deref())?;
76        Ok(*RESPONSE_PLANE_MODE.get_or_init(|| mode))
77    }
78
79    fn from_config_value(value: Option<&str>) -> Result<Self> {
80        match value {
81            None | Some("tcp") => Ok(Self::Tcp),
82            Some("quic") => Ok(Self::Quic),
83            Some("velo") => Ok(Self::Velo),
84            Some(other) => anyhow::bail!(
85                "invalid {} value '{other}'; expected 'tcp', 'quic', or 'velo'",
86                crate::config::environment_names::response_plane::DYN_RESPONSE_PLANE
87            ),
88        }
89    }
90
91    pub fn from_transport_name(transport: &str) -> Result<Self> {
92        match transport {
93            "tcp_server" => Ok(Self::Tcp),
94            quic_response::TRANSPORT_NAME => Ok(Self::Quic),
95            velo_response::TRANSPORT_NAME => Ok(Self::Velo),
96            other => anyhow::bail!("unsupported response transport '{other}'"),
97        }
98    }
99
100    pub const fn name(self) -> &'static str {
101        match self {
102            Self::Tcp => "tcp",
103            Self::Quic => "quic",
104            Self::Velo => "velo",
105        }
106    }
107}
108
109crate::env_config! {
110    /// Read the configured TCP max message size once and share it across client,
111    /// server, and zero-copy decoder code paths.
112    pub(crate) fn get_tcp_max_message_size() -> usize =
113        crate::config::environment_names::request_plane::DYN_TCP_MAX_MESSAGE_SIZE,
114        default = DEFAULT_TCP_MAX_MESSAGE_SIZE;
115}
116
117#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
118#[serde(rename_all = "snake_case")]
119pub enum RequestPlanePayloadCodec {
120    /// The serde default deliberately remains JSON for wire compatibility with
121    /// control messages produced before the payload codec field existed.
122    #[default]
123    Json,
124    Msgpack,
125}
126
127impl RequestPlanePayloadCodec {
128    pub fn configured() -> Self {
129        *REQUEST_PLANE_PAYLOAD_CODEC.get_or_init(Self::from_env)
130    }
131
132    fn from_env() -> Self {
133        let value =
134            std::env::var(crate::config::environment_names::request_plane::DYN_REQUEST_PLANE_CODEC)
135                .ok();
136        Self::from_config_value(value.as_deref())
137    }
138
139    fn from_config_value(value: Option<&str>) -> Self {
140        match value {
141            None | Some("") | Some("msgpack") => Self::Msgpack,
142            Some("json") => Self::Json,
143            Some(other) => {
144                tracing::warn!(
145                    env_var =
146                        crate::config::environment_names::request_plane::DYN_REQUEST_PLANE_CODEC,
147                    value = other,
148                    "invalid request plane payload codec, defaulting to msgpack"
149                );
150                Self::Msgpack
151            }
152        }
153    }
154
155    pub fn name(&self) -> &'static str {
156        match self {
157            Self::Json => "json",
158            Self::Msgpack => "msgpack",
159        }
160    }
161
162    pub fn encode<T: Serialize>(&self, value: &T) -> Result<Vec<u8>> {
163        match self {
164            Self::Json => Ok(serde_json::to_vec(value)?),
165            Self::Msgpack => Ok(rmp_serde::to_vec_named(value)?),
166        }
167    }
168
169    /// Encode into a caller-owned writer, so a hot path can reuse one buffer
170    /// across frames instead of allocating per frame.
171    ///
172    /// Emits the same bytes as [`Self::encode`], which
173    /// `encode_into_matches_encode_byte_for_byte` pins for both codecs.
174    pub fn encode_into<T, W>(&self, value: &T, writer: &mut W) -> Result<()>
175    where
176        T: Serialize + ?Sized,
177        W: std::io::Write,
178    {
179        match self {
180            Self::Json => Ok(serde_json::to_writer(writer, value)?),
181            Self::Msgpack => Ok(rmp_serde::encode::write_named(writer, value)?),
182        }
183    }
184
185    pub fn decode<T: DeserializeOwned>(&self, bytes: &[u8]) -> Result<T> {
186        match self {
187            Self::Json => Ok(serde_json::from_slice(bytes)?),
188            Self::Msgpack => Ok(rmp_serde::from_slice(bytes)?),
189        }
190    }
191}
192
193/// Starting capacity for a buffer that one response frame is encoded into.
194///
195/// Matches `serde_json::to_vec`'s own default so msgpack — which otherwise
196/// starts at zero — stops regrowing its buffer on every streamed frame.
197pub const RESPONSE_ENCODE_CAPACITY_HINT: usize = 128;
198
199pub trait Codable: PipelineIO + Serialize + for<'de> Deserialize<'de> {}
200impl<T: PipelineIO + Serialize + for<'de> Deserialize<'de>> Codable for T {}
201
202/// `WorkQueueConsumer` is a generic interface for a work queue that can be used to send and receive
203#[async_trait]
204pub trait WorkQueueConsumer {
205    async fn dequeue(&self) -> Result<Bytes, String>;
206}
207
208#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
209#[serde(rename_all = "snake_case")]
210pub enum StreamType {
211    Request,
212    Response,
213}
214
215#[derive(Debug, Clone, Serialize, Deserialize)]
216#[serde(rename_all = "snake_case")]
217pub(crate) enum RequestType {
218    SingleIn,
219    ManyIn,
220}
221
222#[derive(Debug, Clone, Serialize, Deserialize)]
223#[serde(rename_all = "snake_case")]
224pub(crate) enum ResponseType {
225    SingleOut,
226    ManyOut,
227}
228
229#[derive(Debug, Clone, Serialize, Deserialize)]
230pub(crate) struct RequestControlMessage {
231    pub(crate) id: String,
232    pub(crate) request_type: RequestType,
233    pub(crate) response_type: ResponseType,
234    #[serde(default)]
235    pub(crate) payload_codec: RequestPlanePayloadCodec,
236    pub(crate) connection_info: ConnectionInfo,
237    #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
238    pub(crate) metadata: std::collections::BTreeMap<String, String>,
239    /// Wall-clock send timestamp (nanos since UNIX epoch) for transport latency breakdown.
240    /// Uses `SystemTime` so accuracy depends on NTP sync between frontend and backend hosts.
241    /// Reliable for single-machine profiling; treat cross-host values as approximate.
242    #[serde(default, skip_serializing_if = "Option::is_none")]
243    pub(crate) frontend_send_ts_ns: Option<u64>,
244    /// For bidirectional dispatch (`request_type == ManyIn`): connection info the
245    /// worker dials back to in order to receive subsequent request frames. `None`
246    /// for the unary path, which is the wire-compatible default.
247    #[serde(default, skip_serializing_if = "Option::is_none")]
248    pub(crate) request_stream_connection_info: Option<ConnectionInfo>,
249}
250
251#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
252#[serde(rename_all = "snake_case")]
253pub enum ControlMessage {
254    Stop,
255    Kill,
256    Sentinel,
257}
258
259/// This is the first message in a `ResponseStream`. This is not a message that gets process
260/// by the general pipeline, but is a control message that is awaited before the
261/// [`AsyncEngine::generate`] method is allowed to return.
262///
263/// If an error is present, the [`AsyncEngine::generate`] method will return the error instead
264/// of returning the `ResponseStream`.
265#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
266pub struct ResponseStreamPrologue {
267    error: Option<String>,
268
269    /// The same failure as `error`, but keeping the worker's
270    /// [`crate::error::ErrorType`] instead of only its display text, so the
271    /// frontend can classify a
272    /// pre-stream failure (for example, a backend refusing a request it can
273    /// never serve) rather than guessing from a message.
274    ///
275    /// `Option` plus `#[serde(default)]` is a compatibility requirement, not a
276    /// convenience: worker and frontend are deployed independently, so during a
277    /// rolling upgrade an old worker sends a prologue without this field and a
278    /// new worker sends one an old frontend does not know. A required field
279    /// would break the handshake in both directions; an absent field or unrecognized legacy
280    /// `error_type` decodes to `None` and the frontend falls back to the untyped behavior.
281    /// A payload with the semantic `class` field uses `DynamoError`'s fail-closed policy.
282    #[serde(
283        default,
284        deserialize_with = "deserialize_typed_error",
285        skip_serializing_if = "Option::is_none"
286    )]
287    typed_error: Option<DynamoError>,
288}
289
290fn deserialize_typed_error<'de, D>(deserializer: D) -> Result<Option<DynamoError>, D::Error>
291where
292    D: serde::Deserializer<'de>,
293{
294    let typed_error = Option::<serde_json::Value>::deserialize(deserializer)?;
295    Ok(typed_error.and_then(|typed_error| {
296        // The legacy enum decoder rejected future variants. ErrorClass is tolerant, so
297        // compare the raw value with its canonical round trip to preserve that fallback.
298        if typed_error.get("class").is_none()
299            && let Some(wire_error_type) = typed_error.get("error_type")
300        {
301            let round_trip = serde_json::from_value::<ErrorType>(wire_error_type.clone())
302                .ok()
303                .and_then(|error_type| serde_json::to_value(error_type).ok());
304            if round_trip.as_ref() != Some(wire_error_type) {
305                return None;
306            }
307        }
308        serde_json::from_value(typed_error).ok()
309    }))
310}
311
312/// A pre-stream failure as it reaches the requesting side of the transport.
313///
314/// `message` is the display text the prologue has always carried.
315/// `typed_error` is the worker's own [`DynamoError`] when the worker was new
316/// enough to send one.
317#[derive(Debug, Clone, PartialEq, Eq)]
318pub struct StreamPrologueError {
319    pub message: String,
320    pub typed_error: Option<DynamoError>,
321}
322
323impl StreamPrologueError {
324    /// A failure detected by the transport itself, with no worker error behind it.
325    pub fn from_message(message: impl Into<String>) -> Self {
326        Self {
327            message: message.into(),
328            typed_error: None,
329        }
330    }
331
332    /// A worker failure, keeping the display text the prologue has always
333    /// carried alongside the worker's typed error.
334    pub fn new(message: impl Into<String>, typed_error: DynamoError) -> Self {
335        Self {
336            message: message.into(),
337            typed_error: Some(typed_error),
338        }
339    }
340}
341
342impl std::fmt::Display for StreamPrologueError {
343    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
344        f.write_str(&self.message)
345    }
346}
347
348/// Derefs to the message so code written against the previous `String` error
349/// keeps working: `err.contains(..)`, `err.len()`, `&err[..]` all still resolve.
350/// Only an explicit `String` type annotation or signature needs updating.
351impl std::ops::Deref for StreamPrologueError {
352    type Target = str;
353
354    fn deref(&self) -> &Self::Target {
355        &self.message
356    }
357}
358
359impl AsRef<str> for StreamPrologueError {
360    fn as_ref(&self) -> &str {
361        &self.message
362    }
363}
364
365impl From<String> for StreamPrologueError {
366    fn from(message: String) -> Self {
367        Self::from_message(message)
368    }
369}
370
371impl From<&str> for StreamPrologueError {
372    fn from(message: &str) -> Self {
373        Self::from_message(message)
374    }
375}
376
377/// Resolves once the worker's response stream is established, or with a
378/// [`StreamPrologueError`] carrying both the failure's display text and, when
379/// the worker sent one, its [`crate::error::ErrorType`], so the requesting side
380/// can classify a pre-stream failure without parsing the message.
381pub type StreamProvider<T> = tokio::sync::oneshot::Receiver<Result<T, StreamPrologueError>>;
382
383/// Owning `Drop` here (rather than on `RegisteredStream`) lets `into_parts()`
384/// move the public fields out by plain destructure.
385struct Cleanup(Option<Box<dyn FnOnce() + Send + 'static>>);
386
387impl Drop for Cleanup {
388    fn drop(&mut self) {
389        if let Some(f) = self.0.take() {
390            f();
391        }
392    }
393}
394
395/// Awaitable handle for a stream sender or receiver. Dropping the handle without
396/// a successful `wait()` or a call to `into_parts()` runs the optional cleanup
397/// closure, removing the registration from the stream server's maps.
398pub struct RegisteredStream<T> {
399    pub connection_info: ConnectionInfo,
400    pub stream_provider: StreamProvider<T>,
401    registration_id: Option<uuid::Uuid>,
402    cleanup: Cleanup,
403}
404
405impl<T> std::fmt::Debug for RegisteredStream<T> {
406    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
407        f.debug_struct("RegisteredStream")
408            .field("connection_info", &self.connection_info)
409            .finish_non_exhaustive()
410    }
411}
412
413impl<T> RegisteredStream<T> {
414    pub(crate) fn new(connection_info: ConnectionInfo, stream_provider: StreamProvider<T>) -> Self {
415        Self {
416            connection_info,
417            stream_provider,
418            registration_id: None,
419            cleanup: Cleanup(None),
420        }
421    }
422
423    pub(crate) fn with_registration_id(mut self, registration_id: uuid::Uuid) -> Self {
424        self.registration_id = Some(registration_id);
425        self
426    }
427
428    pub(crate) fn registration_id(&self) -> Option<uuid::Uuid> {
429        self.registration_id
430    }
431
432    pub(crate) fn with_cleanup<F>(mut self, cleanup: F) -> Self
433    where
434        F: FnOnce() + Send + 'static,
435    {
436        self.cleanup.0 = Some(Box::new(cleanup));
437        self
438    }
439
440    /// Consume the registration, disarming the RAII cleanup. Caller takes
441    /// responsibility for cleanup if the stream provider is never awaited.
442    pub fn into_parts(self) -> (ConnectionInfo, StreamProvider<T>) {
443        let Self {
444            connection_info,
445            stream_provider,
446            registration_id: _,
447            mut cleanup,
448        } = self;
449        cleanup.0.take();
450        (connection_info, stream_provider)
451    }
452
453    /// Await the stream provider, keeping registration cleanup armed until success.
454    ///
455    /// An error or a dropped future removes the registration from the transport.
456    /// Once the stream is established, cleanup is disarmed and the transport owns
457    /// the stream's remaining lifecycle.
458    pub async fn wait(
459        mut self,
460    ) -> Result<Result<T, StreamPrologueError>, tokio::sync::oneshot::error::RecvError> {
461        let result = (&mut self.stream_provider).await;
462        if matches!(result, Ok(Ok(_))) {
463            self.cleanup.0.take();
464        }
465        result
466    }
467}
468
469/// After registering a stream, the [`PendingConnections`] object is returned to the caller. This
470/// object can be used to await the connection to be established.
471pub struct PendingConnections {
472    pub send_stream: Option<RegisteredStream<StreamSender>>,
473    pub recv_stream: Option<RegisteredStream<StreamReceiver>>,
474}
475
476impl PendingConnections {
477    pub fn into_parts(
478        self,
479    ) -> (
480        Option<RegisteredStream<StreamSender>>,
481        Option<RegisteredStream<StreamReceiver>>,
482    ) {
483        (self.send_stream, self.recv_stream)
484    }
485}
486
487/// A [`ResponseService`] implements a services in which a context a specific subject with will
488/// be associated with a stream of responses.
489#[async_trait::async_trait]
490pub trait ResponseService {
491    async fn register(&self, options: StreamOptions) -> PendingConnections;
492}
493
494/// A response plane that registers each response stream by id and leaves any
495/// request stream to the TCP callback server. QUIC and Velo work this way.
496#[async_trait]
497pub(crate) trait RegisteredResponsePlane: Send + Sync {
498    /// QUIC ignores `defer_cancellation_until_prologue`.
499    fn register_stream(
500        self: Arc<Self>,
501        context: Arc<dyn AsyncEngineContext>,
502        defer_cancellation_until_prologue: bool,
503    ) -> Result<RegisteredStream<StreamReceiver>>;
504
505    /// Link a registration to its worker. Returns `false` and cancels the
506    /// registration when discovery has just removed that worker.
507    async fn associate_instance(
508        &self,
509        registration_id: uuid::Uuid,
510        instance: &crate::discovery::EndpointInstanceId,
511    ) -> bool;
512
513    async fn cancel_response(&self, registration_id: uuid::Uuid);
514
515    /// Cancel every registration linked to `instance` and tombstone it.
516    async fn cancel_instance_streams(
517        &self,
518        instance: &crate::discovery::EndpointInstanceId,
519    ) -> usize;
520
521    async fn clear_instance_tombstone(&self, instance: &crate::discovery::EndpointInstanceId);
522}
523
524#[cfg(test)]
525mod registered_stream_tests {
526    use super::*;
527    use std::sync::atomic::{AtomicBool, Ordering};
528
529    fn dummy_conn_info() -> ConnectionInfo {
530        ConnectionInfo {
531            transport: "test".to_string(),
532            info: "{}".to_string(),
533        }
534    }
535
536    /// Drop without `into_parts()` must run the cleanup closure.
537    #[test]
538    fn drop_runs_cleanup() {
539        let flag = Arc::new(AtomicBool::new(false));
540        let flag_clone = flag.clone();
541
542        let (_tx, rx) = tokio::sync::oneshot::channel::<Result<(), StreamPrologueError>>();
543        let stream = RegisteredStream::new(dummy_conn_info(), rx).with_cleanup(move || {
544            flag_clone.store(true, Ordering::SeqCst);
545        });
546
547        drop(stream);
548        assert!(
549            flag.load(Ordering::SeqCst),
550            "cleanup must fire when RegisteredStream is dropped"
551        );
552    }
553
554    /// `into_parts()` must disarm the cleanup. After the call, dropping the
555    /// returned halves must NOT trigger the closure -- the caller has taken
556    /// ownership of cleanup responsibility.
557    #[test]
558    fn into_parts_disarms_cleanup() {
559        let flag = Arc::new(AtomicBool::new(false));
560        let flag_clone = flag.clone();
561
562        let (_tx, rx) = tokio::sync::oneshot::channel::<Result<(), StreamPrologueError>>();
563        let stream = RegisteredStream::new(dummy_conn_info(), rx).with_cleanup(move || {
564            flag_clone.store(true, Ordering::SeqCst);
565        });
566
567        let (conn, provider) = stream.into_parts();
568        drop(conn);
569        drop(provider);
570
571        assert!(
572            !flag.load(Ordering::SeqCst),
573            "into_parts() must disarm the cleanup closure"
574        );
575    }
576
577    #[tokio::test]
578    async fn successful_wait_disarms_cleanup() {
579        let flag = Arc::new(AtomicBool::new(false));
580        let flag_clone = flag.clone();
581        let (tx, rx) = tokio::sync::oneshot::channel();
582        let stream = RegisteredStream::new(dummy_conn_info(), rx).with_cleanup(move || {
583            flag_clone.store(true, Ordering::SeqCst);
584        });
585
586        tx.send(Ok(42)).unwrap();
587        assert_eq!(stream.wait().await.unwrap().unwrap(), 42);
588        assert!(
589            !flag.load(Ordering::SeqCst),
590            "successful wait must disarm cleanup"
591        );
592    }
593
594    #[tokio::test]
595    async fn failed_prologue_wait_runs_cleanup() {
596        let flag = Arc::new(AtomicBool::new(false));
597        let flag_clone = flag.clone();
598        let (tx, rx) = tokio::sync::oneshot::channel::<Result<(), StreamPrologueError>>();
599        let stream = RegisteredStream::new(dummy_conn_info(), rx).with_cleanup(move || {
600            flag_clone.store(true, Ordering::SeqCst);
601        });
602        let error = StreamPrologueError::from_message("worker rejected request");
603
604        tx.send(Err(error.clone())).unwrap();
605        assert_eq!(stream.wait().await.unwrap().unwrap_err(), error);
606        assert!(
607            flag.load(Ordering::SeqCst),
608            "failed prologue must run cleanup"
609        );
610    }
611
612    #[tokio::test]
613    async fn closed_provider_wait_runs_cleanup() {
614        let flag = Arc::new(AtomicBool::new(false));
615        let flag_clone = flag.clone();
616        let (tx, rx) = tokio::sync::oneshot::channel::<Result<(), StreamPrologueError>>();
617        let stream = RegisteredStream::new(dummy_conn_info(), rx).with_cleanup(move || {
618            flag_clone.store(true, Ordering::SeqCst);
619        });
620
621        drop(tx);
622        assert!(stream.wait().await.is_err());
623        assert!(
624            flag.load(Ordering::SeqCst),
625            "closed provider must run cleanup"
626        );
627    }
628
629    /// `RegisteredStream` with no cleanup configured must drop cleanly.
630    #[test]
631    fn drop_without_cleanup_is_a_noop() {
632        let (_tx, rx) = tokio::sync::oneshot::channel::<Result<(), StreamPrologueError>>();
633        let stream: RegisteredStream<()> = RegisteredStream::new(dummy_conn_info(), rx);
634        drop(stream); // must not panic; nothing observable to assert beyond that
635    }
636}
637
638// #[derive(Debug, Clone, Serialize, Deserialize)]
639// struct Handshake {
640//     request_id: String,
641//     worker_id: Option<String>,
642//     error: Option<String>,
643// }
644
645// impl Handshake {
646//     pub fn validate(&self) -> Result<(), String> {
647//         if let Some(e) = &self.error {
648//             return Err(e.clone());
649//         }
650//         Ok(())
651//     }
652// }
653
654// this probably needs to be come a ResponseStreamSender
655// since the prologue in this scenario sender telling the receiver
656// that all is good and it's ready to send
657//
658// in the RequestStreamSender, the prologue would be coming from the
659// receiver, so the sender would have to await the prologue which if
660// was not an error, would indicate the RequestStreamReceiver is read
661// to receive data.
662pub struct StreamSender {
663    tx: tokio::sync::mpsc::Sender<TwoPartMessage>,
664    prologue: Option<ResponseStreamPrologue>,
665}
666
667impl StreamSender {
668    pub async fn send(&self, data: Bytes) -> Result<()> {
669        Ok(self.tx.send(TwoPartMessage::from_data(data)).await?)
670    }
671
672    pub async fn send_control(&self, control: ControlMessage) -> Result<()> {
673        let bytes = serde_json::to_vec(&control)?;
674        Ok(self
675            .tx
676            .send(TwoPartMessage::from_header(bytes.into()))
677            .await?)
678    }
679
680    /// Send the prologue, reporting an untyped failure.
681    ///
682    /// A caller holding the worker's typed error uses
683    /// [`Self::send_prologue_typed`] instead, which keeps that type on the wire.
684    pub async fn send_prologue(&mut self, error: Option<String>) -> Result<(), String> {
685        self.send_prologue_typed(error.map(StreamPrologueError::from_message))
686            .await
687    }
688
689    pub async fn send_prologue_typed(
690        &mut self,
691        error: Option<StreamPrologueError>,
692    ) -> Result<(), String> {
693        // leaving the original logic in place for now
694        if let Some(_prologue) = self.prologue.take() {
695            let (error, typed_error) = match error {
696                Some(StreamPrologueError {
697                    message,
698                    typed_error,
699                }) => (Some(message), typed_error),
700                None => (None, None),
701            };
702            let prologue = ResponseStreamPrologue { error, typed_error };
703            let header_bytes: Bytes = match serde_json::to_vec(&prologue) {
704                Ok(b) => b.into(),
705                Err(err) => {
706                    tracing::error!(%err, "send_prologue: ResponseStreamPrologue did not serialize to a JSON array");
707                    return Err("Invalid prologue".to_string());
708                }
709            };
710            self.tx
711                .send(TwoPartMessage::from_header(header_bytes))
712                .await
713                .map_err(|e| e.to_string())?;
714        } else {
715            panic!("Prologue already sent; or not set; logic error");
716        }
717        Ok(())
718    }
719}
720
721pub struct StreamReceiver {
722    rx: ByteReceiver,
723}
724
725/// Existing socket queues and Velo anchors share the response decoder.
726/// Velo is polled directly; it needs no second data queue.
727enum ByteReceiver {
728    Channel(tokio::sync::mpsc::Receiver<Bytes>),
729    Velo(Box<velo_response::VeloResponseReceiver>),
730}
731
732impl From<tokio::sync::mpsc::Receiver<Bytes>> for ByteReceiver {
733    fn from(rx: tokio::sync::mpsc::Receiver<Bytes>) -> Self {
734        Self::Channel(rx)
735    }
736}
737
738impl ByteReceiver {
739    // TCP request streams and existing socket tests use the byte-only API.
740    async fn recv(&mut self) -> Option<Bytes> {
741        self.next().await.and_then(|result| result.ok())
742    }
743}
744
745impl futures::Stream for ByteReceiver {
746    type Item = Result<Bytes, DynamoError>;
747    fn poll_next(
748        self: std::pin::Pin<&mut Self>,
749        cx: &mut std::task::Context<'_>,
750    ) -> std::task::Poll<Option<Self::Item>> {
751        match self.get_mut() {
752            Self::Channel(rx) => rx.poll_recv(cx).map(|item| item.map(Ok)),
753            Self::Velo(rx) => std::pin::Pin::new(rx.as_mut()).poll_next(cx),
754        }
755    }
756}
757
758/// Connection Info is encoded as JSON and then again serialized has part of the Transport
759/// Layer. The double serialization is not performance critical as it is only done once per
760/// connection. The primary reason storing the ConnecitonInfo has a JSON string is for type
761/// erasure. The Transport Layer will check the [`ConnectionInfo::transport`] type and then
762/// route it to the appropriate instance of the Transport, which will then deserialize the
763/// [`ConnectionInfo::info`] field to its internal connection info object.
764///
765/// Optionally, this object could become strongly typed for which all possible combinations
766/// of transport and connection info would need to be enumerated.
767#[derive(Debug, Clone, Serialize, Deserialize)]
768pub struct ConnectionInfo {
769    pub transport: String,
770    pub info: String,
771}
772
773/// Default number of frames buffered between the data-plane socket task and the
774/// engine consumer/producer for a single stream. Preserves the historically
775/// hard-coded mpsc channel capacity used by the TCP transport.
776pub const DEFAULT_SEND_BUFFER_COUNT: usize = 64;
777
778/// When registering a new TransportStream on the server, the caller specifies if the
779/// stream is a sender, receiver or both.
780///
781/// Senders and Receivers are with share a Context, but result in separate tcp socket
782/// connections to the server. Internally, we may use bcast channels to coordinate the
783/// internal control messages between the sender and receiver socket connections.
784#[derive(Clone, Builder)]
785pub struct StreamOptions {
786    /// Context
787    pub context: Arc<dyn AsyncEngineContext>,
788
789    /// Register with the server that this connection will have a server-side Sender
790    /// that can be picked up by the Request/Forward pipeline. The downstream side
791    /// dials in via [`crate::pipeline::network::tcp::client::TcpClient::create_request_stream`]
792    /// to receive the frames the server pushes.
793    pub enable_request_stream: bool,
794
795    /// Register with the server that this connection will have a server-side Receiver
796    /// that can be picked up by the Response/Reverse pipeline
797    pub enable_response_stream: bool,
798
799    /// Preserve guarded dispatch setup until the worker sends its prologue.
800    #[builder(default)]
801    pub defer_cancellation_until_prologue: bool,
802
803    /// The number of frames buffered between the data-plane socket task and the
804    /// engine consumer/producer before backpressure kicks in. Drives the mpsc
805    /// channel capacity for the per-stream buffer in the TCP transport.
806    #[builder(default = "DEFAULT_SEND_BUFFER_COUNT")]
807    pub send_buffer_count: usize,
808
809    /// The number of messages to buffer before blocking
810    #[builder(default = "8")]
811    pub recv_buffer_count: usize,
812}
813
814impl StreamOptions {
815    pub fn builder() -> StreamOptionsBuilder {
816        StreamOptionsBuilder::default()
817    }
818}
819
820pub struct Egress<Req: PipelineIO, Resp: PipelineIO> {
821    transport_engine: Arc<dyn AsyncTransportEngine<Req, Resp>>,
822}
823
824#[cfg(test)]
825mod tests {
826    use super::{
827        DEFAULT_SEND_BUFFER_COUNT, Ingress, IngressResponseEncoder, ManyOut, NetworkStreamWrapper,
828        RequestControlMessage, RequestPlanePayloadCodec, RequestType, ResponsePlaneMode,
829        ResponseStreamPrologue, ResponseType, SerdeIngressPayloadAdapter, SingleIn, StreamOptions,
830        StreamPrologueError,
831    };
832    use crate::engine::AsyncEngineContextProvider;
833    use crate::error::{BackendError, DynamoError, ErrorType};
834    use crate::pipeline::Context;
835    use crate::protocols::annotated::Annotated;
836    use crate::telemetry::LifecycleOperationRole;
837    use serde::{Deserialize, Serialize};
838    use std::sync::{Arc, OnceLock};
839
840    #[derive(Debug, Serialize, Deserialize, PartialEq, Eq)]
841    struct TestPayload {
842        id: u64,
843        text: String,
844        tokens: Vec<u32>,
845    }
846
847    #[test]
848    fn prologue_without_typed_error_field_still_decodes() {
849        let legacy = br#"{"error":"Generate Error: something went wrong"}"#;
850        let prologue: ResponseStreamPrologue =
851            serde_json::from_slice(legacy).expect("a prologue without the typed field must decode");
852
853        assert_eq!(
854            prologue.error.as_deref(),
855            Some("Generate Error: something went wrong")
856        );
857        assert!(
858            prologue.typed_error.is_none(),
859            "an absent typed error must decode to None, not fail"
860        );
861    }
862
863    /// Pins the `String` compat shim on the widened `StreamProvider` error:
864    /// `str` methods and `String` conversion must keep resolving without a
865    /// field access, or the source break gets wider than intended.
866    #[test]
867    fn stream_prologue_error_substitutes_for_the_previous_string() {
868        let err = StreamPrologueError::from_message("malformed prologue: bad header");
869
870        assert!(err.contains("malformed prologue"));
871        assert!(err.starts_with("malformed"));
872        assert_eq!(err.len(), "malformed prologue: bad header".len());
873        assert_eq!(&err[..9], "malformed");
874        assert_eq!(err.as_ref() as &str, "malformed prologue: bad header");
875
876        let converted: StreamPrologueError = "from a &str".into();
877        assert_eq!(converted.message, "from a &str");
878        assert!(converted.typed_error.is_none());
879
880        let converted: StreamPrologueError = String::from("from a String").into();
881        assert_eq!(converted.message, "from a String");
882    }
883
884    #[test]
885    fn prologue_round_trips_the_typed_error() {
886        let prologue = ResponseStreamPrologue {
887            error: Some("Generate Error: unsupported input".to_string()),
888            typed_error: Some(
889                DynamoError::builder()
890                    .error_type(ErrorType::Backend(BackendError::InvalidArgument))
891                    .message("unsupported input")
892                    .build(),
893            ),
894        };
895
896        let encoded = serde_json::to_vec(&prologue).expect("prologue should serialize");
897        let decoded: ResponseStreamPrologue =
898            serde_json::from_slice(&encoded).expect("prologue should deserialize");
899
900        assert_eq!(decoded, prologue);
901        assert_eq!(
902            decoded.typed_error.map(|e| e.error_type()),
903            Some(ErrorType::Backend(BackendError::InvalidArgument))
904        );
905    }
906
907    #[test]
908    fn prologue_accepts_a_known_legacy_typed_error() {
909        let legacy = br#"{
910            "error":"Generate Error: unsupported input",
911            "typed_error":{"error_type":"InvalidArgument","message":"unsupported input"}
912        }"#;
913        let prologue: ResponseStreamPrologue =
914            serde_json::from_slice(legacy).expect("a known legacy typed error must decode");
915        let error = prologue
916            .typed_error
917            .expect("a known legacy typed error must remain typed");
918
919        assert_eq!(error.error_type(), ErrorType::InvalidArgument);
920        assert_eq!(error.class(), ErrorType::InvalidRequest);
921        assert_eq!(error.reason().as_str(), "request.invalid_argument");
922    }
923
924    #[test]
925    fn prologue_ignores_a_future_legacy_typed_error() {
926        let future = br#"{
927            "error":"Generate Error: future failure",
928            "typed_error":{"error_type":"VariantFromTheFuture","message":"future failure"}
929        }"#;
930        let prologue: ResponseStreamPrologue = serde_json::from_slice(future)
931            .expect("a future legacy typed error must not reject the prologue");
932
933        assert!(prologue.typed_error.is_none());
934    }
935
936    #[test]
937    fn prologue_fails_closed_for_a_future_semantic_class() {
938        let future = br#"{
939            "error":"Generate Error: future failure",
940            "typed_error":{
941                "class":"FutureErrorClass",
942                "reason":"runtime.internal",
943                "public":{"type":"message","message":"must not escape"}
944            }
945        }"#;
946        let prologue: ResponseStreamPrologue = serde_json::from_slice(future)
947            .expect("a future semantic class must not reject the prologue");
948        let error = prologue
949            .typed_error
950            .expect("semantic errors use the DynamoError fail-closed identity");
951
952        assert_eq!(error.class(), ErrorType::Internal);
953        assert_eq!(error.reason().as_str(), "runtime.invalid_error");
954        assert!(error.public_details().is_none());
955    }
956
957    #[test]
958    fn response_plane_mode_parses_supported_values() {
959        assert_eq!(
960            ResponsePlaneMode::from_config_value(None).unwrap(),
961            ResponsePlaneMode::Tcp
962        );
963        assert_eq!(
964            ResponsePlaneMode::from_config_value(Some("tcp")).unwrap(),
965            ResponsePlaneMode::Tcp
966        );
967        assert_eq!(
968            ResponsePlaneMode::from_config_value(Some("quic")).unwrap(),
969            ResponsePlaneMode::Quic
970        );
971        assert_eq!(
972            ResponsePlaneMode::from_config_value(Some("velo")).unwrap(),
973            ResponsePlaneMode::Velo
974        );
975        assert!(ResponsePlaneMode::from_config_value(Some("")).is_err());
976        assert!(ResponsePlaneMode::from_config_value(Some("invalid")).is_err());
977    }
978
979    #[test]
980    fn encode_into_matches_encode_byte_for_byte() {
981        let payload = NetworkStreamWrapper {
982            data: Some(TestPayload {
983                id: 7,
984                text: "hello".to_string(),
985                tokens: vec![1, 200, 70_000],
986            }),
987            complete_final: false,
988        };
989
990        for codec in [
991            RequestPlanePayloadCodec::Json,
992            RequestPlanePayloadCodec::Msgpack,
993        ] {
994            let expected = codec.encode(&payload).expect("encode");
995            let mut actual = Vec::new();
996            codec
997                .encode_into(&payload, &mut actual)
998                .expect("encode_into");
999            assert_eq!(expected, actual, "codec={}", codec.name());
1000        }
1001    }
1002
1003    #[test]
1004    fn stream_options_send_buffer_count_defaults_to_64() {
1005        let context = Context::new(());
1006        let options = StreamOptions::builder()
1007            .context(context.context())
1008            .enable_request_stream(true)
1009            .enable_response_stream(true)
1010            .build()
1011            .expect("stream options should build");
1012
1013        assert_eq!(DEFAULT_SEND_BUFFER_COUNT, 64);
1014        assert_eq!(options.send_buffer_count, DEFAULT_SEND_BUFFER_COUNT);
1015    }
1016
1017    #[test]
1018    fn stream_options_send_buffer_count_overrides_default() {
1019        let context = Context::new(());
1020        let options = StreamOptions::builder()
1021            .context(context.context())
1022            .enable_request_stream(true)
1023            .enable_response_stream(true)
1024            .send_buffer_count(128)
1025            .build()
1026            .expect("stream options should build");
1027
1028        assert_eq!(options.send_buffer_count, 128);
1029    }
1030
1031    #[test]
1032    fn ingress_observes_lifecycle_role_set_after_binding() {
1033        let ingress = Ingress::<SingleIn<String>, ManyOut<String>>::new();
1034        let endpoint_role = Arc::new(OnceLock::new());
1035
1036        ingress
1037            .lifecycle_operation_role
1038            .set(endpoint_role.clone())
1039            .expect("new ingress lifecycle role source must be empty");
1040        assert_eq!(ingress.registered_lifecycle_role(), None);
1041
1042        endpoint_role
1043            .set(LifecycleOperationRole::Prefill)
1044            .expect("new endpoint lifecycle role cell must be empty");
1045        assert_eq!(
1046            ingress.registered_lifecycle_role(),
1047            Some(LifecycleOperationRole::Prefill)
1048        );
1049    }
1050
1051    #[test]
1052    fn legacy_frontend_control_message_defaults_payload_codec_to_json() {
1053        let json = r#"{
1054            "id": "request-123",
1055            "request_type": "single_in",
1056            "response_type": "many_out",
1057            "connection_info": {
1058                "transport": "tcp",
1059                "info": "{}"
1060            }
1061        }"#;
1062
1063        let message: RequestControlMessage =
1064            serde_json::from_str(json).expect("control message should deserialize");
1065
1066        assert_eq!(message.id, "request-123");
1067        assert!(matches!(message.request_type, RequestType::SingleIn));
1068        assert!(matches!(message.response_type, ResponseType::ManyOut));
1069        assert_eq!(message.payload_codec, RequestPlanePayloadCodec::Json);
1070        assert_eq!(message.connection_info.transport, "tcp");
1071        assert_eq!(message.connection_info.info, "{}");
1072        assert!(message.metadata.is_empty());
1073        assert!(message.frontend_send_ts_ns.is_none());
1074
1075        let payload = br#"{"id":7,"text":"legacy","tokens":[1,2]}"#;
1076        let decoded: TestPayload = message
1077            .payload_codec
1078            .decode(payload)
1079            .expect("worker should decode the legacy frontend's JSON payload");
1080        assert_eq!(
1081            decoded,
1082            TestPayload {
1083                id: 7,
1084                text: "legacy".to_string(),
1085                tokens: vec![1, 2],
1086            }
1087        );
1088    }
1089
1090    #[test]
1091    fn request_control_message_decodes_msgpack_payload_codec() {
1092        let json = r#"{
1093            "id": "request-123",
1094            "request_type": "single_in",
1095            "response_type": "many_out",
1096            "payload_codec": "msgpack",
1097            "connection_info": {
1098                "transport": "tcp",
1099                "info": "{}"
1100            }
1101        }"#;
1102
1103        let message: RequestControlMessage =
1104            serde_json::from_str(json).expect("control message should deserialize");
1105
1106        assert_eq!(message.payload_codec, RequestPlanePayloadCodec::Msgpack);
1107    }
1108
1109    #[test]
1110    fn request_plane_payload_codec_configuration_defaults_to_msgpack() {
1111        assert_eq!(
1112            RequestPlanePayloadCodec::from_config_value(None),
1113            RequestPlanePayloadCodec::Msgpack
1114        );
1115        assert_eq!(
1116            RequestPlanePayloadCodec::from_config_value(Some("")),
1117            RequestPlanePayloadCodec::Msgpack
1118        );
1119        assert_eq!(
1120            RequestPlanePayloadCodec::from_config_value(Some("invalid")),
1121            RequestPlanePayloadCodec::Msgpack
1122        );
1123    }
1124
1125    #[test]
1126    fn request_plane_payload_codec_configuration_honors_explicit_overrides() {
1127        assert_eq!(
1128            RequestPlanePayloadCodec::from_config_value(Some("json")),
1129            RequestPlanePayloadCodec::Json
1130        );
1131        assert_eq!(
1132            RequestPlanePayloadCodec::from_config_value(Some("msgpack")),
1133            RequestPlanePayloadCodec::Msgpack
1134        );
1135    }
1136
1137    #[test]
1138    fn request_plane_payload_codec_round_trips_response_wrapper_json_and_msgpack() {
1139        let wrapper = NetworkStreamWrapper {
1140            data: Some(TestPayload {
1141                id: 42,
1142                text: "line\nquote\"slash\\unicode 中".to_string(),
1143                tokens: vec![1, 2, 3, 65535],
1144            }),
1145            complete_final: false,
1146        };
1147
1148        for codec in [
1149            RequestPlanePayloadCodec::Json,
1150            RequestPlanePayloadCodec::Msgpack,
1151        ] {
1152            let encoded = codec.encode(&wrapper).expect("wrapper should encode");
1153            let decoded: NetworkStreamWrapper<TestPayload> =
1154                codec.decode(&encoded).expect("wrapper should decode");
1155            assert_eq!(decoded, wrapper);
1156        }
1157    }
1158
1159    /// `encode_into` must stay byte-compatible with `encode` for both codecs.
1160    #[tokio::test]
1161    async fn serde_ingress_encoder_matches_encode_byte_for_byte() {
1162        let data = Annotated::from_data(serde_json::json!({
1163            "token_ids": [128, 9001],
1164            "index": 3,
1165        }));
1166        let error = Annotated::<serde_json::Value>::from_error("engine failed");
1167
1168        for codec in [
1169            RequestPlanePayloadCodec::Json,
1170            RequestPlanePayloadCodec::Msgpack,
1171        ] {
1172            for (case, response, complete_final, expect_error) in [
1173                ("data frame", Some(data.clone()), false, false),
1174                ("error frame", Some(error.clone()), false, true),
1175                ("complete final", None, true, false),
1176            ] {
1177                let expected = codec
1178                    .encode(&NetworkStreamWrapper {
1179                        data: response.clone(),
1180                        complete_final,
1181                    })
1182                    .expect("reference encode");
1183
1184                let frame = SerdeIngressPayloadAdapter
1185                    .encode_response(codec, response, complete_final)
1186                    .await
1187                    .expect("adapter encode");
1188
1189                assert_eq!(
1190                    frame.bytes.as_ref(),
1191                    expected.as_slice(),
1192                    "codec={} case={case}",
1193                    codec.name()
1194                );
1195                assert_eq!(
1196                    frame.is_error,
1197                    expect_error,
1198                    "codec={} case={case}",
1199                    codec.name()
1200                );
1201                assert!(!frame.stop_stream, "codec={} case={case}", codec.name());
1202            }
1203        }
1204    }
1205}
1206
1207#[async_trait]
1208impl<T: Data, U: Data> AsyncEngine<SingleIn<T>, ManyOut<U>, Error>
1209    for Egress<SingleIn<T>, ManyOut<U>>
1210where
1211    T: Data + Serialize,
1212    U: for<'de> Deserialize<'de> + Data,
1213{
1214    async fn generate(&self, request: SingleIn<T>) -> Result<ManyOut<U>, Error> {
1215        self.transport_engine.generate(request).await
1216    }
1217}
1218
1219/// Result of encoding one response item for the request plane.
1220pub struct EncodedResponseFrame {
1221    pub bytes: Bytes,
1222    pub is_error: bool,
1223    /// Stop consuming the engine stream after publishing this frame. The
1224    /// normal complete-final frame is still sent.
1225    pub stop_stream: bool,
1226}
1227
1228/// Converts request-plane bytes into the item consumed by an ingress engine.
1229pub trait IngressRequestDecoder<T>: Send + Sync + 'static
1230where
1231    T: Data,
1232{
1233    fn decode_request(
1234        &self,
1235        payload_codec: RequestPlanePayloadCodec,
1236        bytes: Bytes,
1237    ) -> impl std::future::Future<Output = std::result::Result<T, PipelineError>> + Send;
1238}
1239
1240/// Converts an ingress engine response into its complete on-wire frame.
1241pub trait IngressResponseEncoder<U>: Send + Sync + 'static
1242where
1243    U: Data,
1244{
1245    fn encode_response(
1246        &self,
1247        payload_codec: RequestPlanePayloadCodec,
1248        response: Option<U>,
1249        complete_final: bool,
1250    ) -> impl std::future::Future<Output = std::result::Result<EncodedResponseFrame, PipelineError>> + Send;
1251}
1252
1253/// Complete request/response payload adapter for an ingress engine.
1254pub trait IngressPayloadAdapter<T, U>:
1255    IngressRequestDecoder<T> + IngressResponseEncoder<U>
1256where
1257    T: Data,
1258    U: Data,
1259{
1260}
1261
1262impl<T, U, Adapter> IngressPayloadAdapter<T, U> for Adapter
1263where
1264    T: Data,
1265    U: Data,
1266    Adapter: IngressRequestDecoder<T> + IngressResponseEncoder<U>,
1267{
1268}
1269
1270/// Default adapter for ordinary Rust request and response types.
1271#[derive(Debug, Default)]
1272pub struct SerdeIngressPayloadAdapter;
1273
1274impl<T> IngressRequestDecoder<T> for SerdeIngressPayloadAdapter
1275where
1276    T: Data + DeserializeOwned,
1277{
1278    #[inline]
1279    fn decode_request(
1280        &self,
1281        payload_codec: RequestPlanePayloadCodec,
1282        bytes: Bytes,
1283    ) -> impl std::future::Future<Output = std::result::Result<T, PipelineError>> + Send {
1284        let decoded = payload_codec.decode(&bytes).map_err(|err| {
1285            PipelineError::DeserializationError(format!(
1286                "Failed deserializing {} request payload: {}",
1287                payload_codec.name(),
1288                err
1289            ))
1290        });
1291        std::future::ready(decoded)
1292    }
1293}
1294
1295impl<U> IngressResponseEncoder<U> for SerdeIngressPayloadAdapter
1296where
1297    U: Data + Serialize + MaybeError,
1298{
1299    #[inline]
1300    fn encode_response(
1301        &self,
1302        payload_codec: RequestPlanePayloadCodec,
1303        response: Option<U>,
1304        complete_final: bool,
1305    ) -> impl std::future::Future<Output = std::result::Result<EncodedResponseFrame, PipelineError>> + Send
1306    {
1307        let is_error = response
1308            .as_ref()
1309            .is_some_and(|response| response.err().is_some());
1310        let wrapper = NetworkStreamWrapper {
1311            data: response,
1312            complete_final,
1313        };
1314        let mut bytes = Vec::with_capacity(RESPONSE_ENCODE_CAPACITY_HINT);
1315        let encoded = payload_codec
1316            .encode_into(&wrapper, &mut bytes)
1317            .map(|()| bytes)
1318            .map_err(|err| {
1319                PipelineError::SerializationError(format!(
1320                    "Failed serializing {} request-plane response: {}",
1321                    payload_codec.name(),
1322                    err
1323                ))
1324            });
1325        std::future::ready(encoded.map(|bytes| EncodedResponseFrame {
1326            bytes: bytes.into(),
1327            is_error,
1328            stop_stream: false,
1329        }))
1330    }
1331}
1332
1333pub struct Ingress<Req: PipelineIO, Resp: PipelineIO, Adapter = SerdeIngressPayloadAdapter> {
1334    segment: OnceLock<Arc<SegmentSource<Req, Resp>>>,
1335    metrics: OnceLock<Arc<WorkHandlerMetrics>>,
1336    /// Endpoint-specific notifier for health check timer resets
1337    endpoint_health_check_notifier: OnceLock<Arc<tokio::sync::Notify>>,
1338    /// Resolved response transport of the bound endpoint's runtime.
1339    response_plane: OnceLock<ResponsePlaneMode>,
1340    quic_response_client_pool: OnceLock<Arc<quic_response::QuicResponseClientPool>>,
1341    velo_response_service: tokio::sync::OnceCell<Arc<velo_response::VeloResponseService>>,
1342    velo_response_owner: OnceLock<std::sync::Weak<velo_response::RuntimeService>>,
1343    payload_adapter: Arc<Adapter>,
1344    lifecycle_operation_role: OnceLock<Arc<OnceLock<LifecycleOperationRole>>>,
1345}
1346
1347impl<Req: PipelineIO + Sync, Resp: PipelineIO> Ingress<Req, Resp> {
1348    pub fn new() -> Arc<Self> {
1349        Ingress::new_with_adapter(SerdeIngressPayloadAdapter)
1350    }
1351
1352    pub fn link(segment: Arc<SegmentSource<Req, Resp>>) -> Result<Arc<Self>> {
1353        let ingress = Ingress::new();
1354        ingress.attach(segment)?;
1355        Ok(ingress)
1356    }
1357
1358    pub fn for_pipeline(segment: Arc<SegmentSource<Req, Resp>>) -> Result<Arc<Self>> {
1359        let ingress = Ingress::new();
1360        ingress.attach(segment)?;
1361        Ok(ingress)
1362    }
1363
1364    pub fn for_engine(engine: ServiceEngine<Req, Resp>) -> Result<Arc<Self>> {
1365        Self::for_engine_with_adapter(engine, SerdeIngressPayloadAdapter)
1366    }
1367
1368    /// Build a worker ingress with the role fixed by its startup configuration.
1369    pub fn for_engine_with_lifecycle_role(
1370        engine: ServiceEngine<Req, Resp>,
1371        role: LifecycleOperationRole,
1372    ) -> Result<Arc<Self>> {
1373        Self::for_engine_with_adapter_and_lifecycle_role(engine, SerdeIngressPayloadAdapter, role)
1374    }
1375}
1376
1377impl<Req, Resp, Adapter> Ingress<Req, Resp, Adapter>
1378where
1379    Req: PipelineIO + Sync,
1380    Resp: PipelineIO,
1381    Adapter: Send + Sync + 'static,
1382{
1383    pub fn new_with_adapter(payload_adapter: Adapter) -> Arc<Self> {
1384        Arc::new(Self {
1385            segment: OnceLock::new(),
1386            metrics: OnceLock::new(),
1387            endpoint_health_check_notifier: OnceLock::new(),
1388            response_plane: OnceLock::new(),
1389            quic_response_client_pool: OnceLock::new(),
1390            velo_response_service: tokio::sync::OnceCell::new(),
1391            velo_response_owner: OnceLock::new(),
1392            payload_adapter: Arc::new(payload_adapter),
1393            lifecycle_operation_role: OnceLock::new(),
1394        })
1395    }
1396
1397    fn new_with_adapter_and_lifecycle_role(
1398        payload_adapter: Adapter,
1399        lifecycle_operation_role: LifecycleOperationRole,
1400    ) -> Arc<Self> {
1401        let ingress = Self::new_with_adapter(payload_adapter);
1402        let role = Arc::new(OnceLock::new());
1403        role.set(lifecycle_operation_role)
1404            .expect("new lifecycle role cell must be empty");
1405        ingress
1406            .lifecycle_operation_role
1407            .set(role)
1408            .expect("new ingress lifecycle role source must be empty");
1409        ingress
1410    }
1411
1412    pub fn attach(&self, segment: Arc<SegmentSource<Req, Resp>>) -> Result<()> {
1413        self.segment
1414            .set(segment)
1415            .map_err(|_| anyhow::anyhow!("Segment already set"))
1416    }
1417
1418    pub(crate) fn set_quic_response_client_pool(
1419        &self,
1420        pool: Arc<quic_response::QuicResponseClientPool>,
1421    ) -> Result<()> {
1422        self.quic_response_client_pool
1423            .set(pool)
1424            .map_err(|_| anyhow::anyhow!("QUIC response client pool already set"))
1425    }
1426
1427    pub(crate) fn quic_response_client_pool(
1428        &self,
1429    ) -> Result<Arc<quic_response::QuicResponseClientPool>, PipelineError> {
1430        if let Some(pool) = self.quic_response_client_pool.get() {
1431            return Ok(pool.clone());
1432        }
1433        let pool = quic_response::process_client_pool_from_env()?;
1434        Ok(self.quic_response_client_pool.get_or_init(|| pool).clone())
1435    }
1436
1437    async fn velo_response_service(
1438        &self,
1439    ) -> Result<&Arc<velo_response::VeloResponseService>, PipelineError> {
1440        let owner = self
1441            .velo_response_owner
1442            .get()
1443            .and_then(std::sync::Weak::upgrade)
1444            .ok_or_else(|| {
1445                PipelineError::Generic(
1446                    "Velo ingress must be bound to a live runtime endpoint".into(),
1447                )
1448            })?;
1449        if owner.is_closed() {
1450            return Err(PipelineError::Generic(
1451                "Velo response runtime is shut down".into(),
1452            ));
1453        }
1454        self.velo_response_service
1455            .get_or_try_init(|| owner.service())
1456            .await
1457            .map_err(|error| PipelineError::Generic(error.to_string()))
1458    }
1459
1460    pub fn add_metrics(
1461        &self,
1462        endpoint: &crate::component::Endpoint,
1463        metrics_labels: Option<&[(&str, &str)]>,
1464    ) -> Result<()> {
1465        let metrics = WorkHandlerMetrics::from_endpoint(endpoint, metrics_labels)
1466            .map_err(|e| anyhow::anyhow!("Failed to create work handler metrics: {}", e))?;
1467
1468        // Register global transport breakdown metrics (idempotent)
1469        crate::metrics::work_handler_perf::ensure_work_handler_perf_metrics_registered(
1470            endpoint.get_metrics_registry(),
1471        );
1472
1473        // Register worker-pool saturation metrics (idempotent). These are
1474        // process-global and shared across all endpoints attached to the
1475        // same shared TCP server.
1476        crate::metrics::work_handler_pool::ensure_work_handler_pool_metrics_registered(
1477            endpoint.get_metrics_registry(),
1478        );
1479
1480        self.metrics
1481            .set(Arc::new(metrics))
1482            .map_err(|_| anyhow::anyhow!("Metrics already set"))
1483    }
1484
1485    pub fn for_engine_with_adapter(
1486        engine: ServiceEngine<Req, Resp>,
1487        payload_adapter: Adapter,
1488    ) -> Result<Arc<Self>> {
1489        let frontend = SegmentSource::<Req, Resp>::new();
1490        let backend = ServiceBackend::from_engine(engine);
1491        let pipeline = frontend.link(backend)?.link_terminal(frontend)?;
1492        let ingress = Ingress::new_with_adapter(payload_adapter);
1493        ingress.attach(pipeline)?;
1494        Ok(ingress)
1495    }
1496
1497    pub fn for_engine_with_adapter_and_lifecycle_role(
1498        engine: ServiceEngine<Req, Resp>,
1499        payload_adapter: Adapter,
1500        role: LifecycleOperationRole,
1501    ) -> Result<Arc<Self>> {
1502        let frontend = SegmentSource::<Req, Resp>::new();
1503        let backend = ServiceBackend::from_engine(engine);
1504
1505        let pipeline = frontend.link(backend)?.link_terminal(frontend)?;
1506
1507        let ingress = Ingress::new_with_adapter_and_lifecycle_role(payload_adapter, role);
1508        ingress.attach(pipeline)?;
1509
1510        Ok(ingress)
1511    }
1512
1513    /// Helper method to access metrics if available
1514    fn metrics(&self) -> Option<&Arc<WorkHandlerMetrics>> {
1515        self.metrics.get()
1516    }
1517
1518    fn registered_lifecycle_role(&self) -> Option<LifecycleOperationRole> {
1519        self.lifecycle_operation_role
1520            .get()
1521            .and_then(|role| role.get())
1522            .copied()
1523    }
1524
1525    fn bind_endpoint_config(&self, endpoint: &crate::component::Endpoint) {
1526        let _ = self.response_plane.set(endpoint.drt().response_plane());
1527        // Endpoint tasks retain this ingress. Keep a weak back-reference so
1528        // those tasks cannot keep their own Tokio runtime alive.
1529        let _ = self.velo_response_owner.set(Arc::downgrade(
1530            &endpoint.drt().runtime().velo_response_service(),
1531        ));
1532        // Keep an explicitly constructed ingress role; otherwise observe model
1533        // registration even when it happens after the endpoint starts serving.
1534        let _ = self
1535            .lifecycle_operation_role
1536            .set(endpoint.lifecycle_operation_role());
1537    }
1538}
1539
1540#[async_trait]
1541pub trait PushWorkHandler: Send + Sync {
1542    /// Bind endpoint identity independently of metrics registration.
1543    fn bind_endpoint(&self, _endpoint: &crate::component::Endpoint) {}
1544
1545    async fn handle_payload(
1546        &self,
1547        payload: Bytes,
1548        request_id: Option<String>,
1549    ) -> Result<(), PipelineError>;
1550
1551    /// Add metrics to the handler
1552    fn add_metrics(
1553        &self,
1554        endpoint: &crate::component::Endpoint,
1555        metrics_labels: Option<&[(&str, &str)]>,
1556    ) -> Result<()>;
1557
1558    /// Set the endpoint-specific notifier for health check timer resets
1559    fn set_endpoint_health_check_notifier(
1560        &self,
1561        _notifier: Arc<tokio::sync::Notify>,
1562    ) -> Result<()> {
1563        // Default implementation for backwards compatibility
1564        Ok(())
1565    }
1566}
1567
1568/*
1569/// `NetworkStreamWrapper` is a simple wrapper used to detect proper stream termination
1570/// in network communication between ingress and egress components.
1571///
1572/// **Purpose**: This wrapper solves the problem of detecting whether a stream ended
1573/// gracefully or was cut off prematurely (e.g., due to network issues).
1574///
1575/// **Design Rationale**:
1576/// - Cannot use `Annotated` directly because the generic type `U` varies:
1577///   - Sometimes `U = Annotated<...>`
1578///   - Sometimes `U = LLMEngineOutput<...>`
1579/// - Using `Annotated` would require double-wrapping like `Annotated<Annotated<...>>`
1580/// - A simple wrapper is cleaner and more straightforward
1581///
1582/// **Stream Flow**:
1583/// ```
1584/// At AsyncEngine:
1585///   response 1 -> response 2 -> response 3 -> <end>
1586///
1587/// Between ingress/egress:
1588///   response 1 <end=false> -> response 2 <end=false> -> response 3 <end=false> -> (null) <end=true>
1589///
1590/// At client:
1591///   response 1 -> response 2 -> response 3 -> <end>
1592/// ```
1593///
1594/// **Error Handling**:
1595/// If the stream is cut off before proper termination, the egress is responsible for
1596/// injecting an error response to communicate the incomplete stream to the client:
1597/// ```
1598/// At AsyncEngine:
1599///   response 1 -> ... <without end flag>
1600///
1601/// At egress:
1602///   response 1 <end=false> -> <stream ended without end flag -> convert to error>
1603///
1604/// At client:
1605///   response 1 -> error response
1606/// ```
1607///
1608/// The detection must be done at egress level because premature stream termination
1609/// can be due to network issues that only the egress component can detect.
1610*/
1611/// TODO: Detect end-of-stream using Server-Sent Events (SSE). This will be removed.
1612#[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
1613pub struct NetworkStreamWrapper<U> {
1614    #[serde(skip_serializing_if = "Option::is_none")]
1615    pub data: Option<U>,
1616    pub complete_final: bool,
1617}