Skip to main content

dynamo_runtime/
pipeline.rs

1// SPDX-FileCopyrightText: Copyright (c) 2024-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2// SPDX-License-Identifier: Apache-2.0
3
4/// In a Pipeline, the [`AsyncEngine`] is constrained to take a [`Context`] as input and return
5/// a [`super::engine::ResponseStream`] as output.
6use serde::{Deserialize, Serialize};
7
8mod nodes;
9pub use nodes::{
10    Operator, PipelineNode, PipelineOperator, SegmentSink, SegmentSource, Service, ServiceBackend,
11    ServiceFrontend, Sink, Source,
12};
13
14pub mod context;
15pub mod error;
16pub mod network;
17pub use crate::routing_policy::{
18    InstanceSelector, ModeSelectors, OccupancyReservation, OccupancySelection, RouteTarget,
19    RoutingOccupancyState,
20};
21pub use network::egress::addressed_router::{
22    AddressedPushRouter, AddressedRequest, StreamingDispatch, attach_first_response_guard,
23    propagate_first_response_guard,
24};
25pub use network::egress::push_router::{
26    MultimodalCacheIndex, MultimodalCacheKeyExtractor, PushRouter, PushRouterOptions, RouterMode,
27    WorkerLoadMonitor,
28};
29pub mod registry;
30
31pub use crate::engine::{
32    self as engine, AsyncEngine, AsyncEngineContext, AsyncEngineContextProvider, AsyncEngineStream,
33    Data, DataStream, Engine, EngineStream, EngineUnary, ResponseStream, async_trait,
34};
35pub use anyhow::Error;
36pub use context::Context;
37pub use error::{PipelineError, PipelineErrorExt, TwoPartCodecError};
38
39/// Pipeline inputs carry a [`Context`] which can be used to carry metadata or additional information
40/// about the request. This information propagates through the stages, both local and distributed.
41pub type SingleIn<T> = Context<T>;
42
43/// `Sync` ownership cell for a non-`Sync` [`DataStream<T>`]. [`Self::take`]
44/// moves the inner stream out; the mutex serialises concurrent attempts so
45/// the first caller observes `Some(stream)` and all later callers see
46/// `None`. Iteration happens on the returned `DataStream<T>`.
47pub struct RequestStream<T: Data> {
48    inner: std::sync::Mutex<Option<DataStream<T>>>,
49}
50
51impl<T: Data> RequestStream<T> {
52    /// Wrap a [`DataStream<T>`] in a `Sync` ownership cell.
53    pub fn new(stream: DataStream<T>) -> Self {
54        Self {
55            inner: std::sync::Mutex::new(Some(stream)),
56        }
57    }
58
59    /// Atomically move the inner stream out. Returns `Some(stream)` exactly
60    /// once across all threads racing on the same `RequestStream`; every
61    /// subsequent call (on any thread) returns `None`. The returned stream
62    /// is the unique owner; the wrapper retains nothing.
63    pub fn take(&self) -> Option<DataStream<T>> {
64        self.inner.lock().unwrap().take()
65    }
66}
67
68impl<T: Data> std::fmt::Debug for RequestStream<T> {
69    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
70        let taken = self.inner.lock().map(|g| g.is_none()).unwrap_or(true);
71        f.debug_struct("RequestStream")
72            .field("taken", &taken)
73            .finish()
74    }
75}
76
77/// Pipeline input for streaming-request engines: a [`RequestStream<T>`]
78/// payload wrapped in a [`Context`], symmetric to [`SingleIn<T>`] for unary
79/// inputs.
80pub type ManyIn<T> = Context<RequestStream<T>>;
81
82/// Type alias for the output of pipeline that returns a single value
83pub type SingleOut<T> = EngineUnary<T>;
84
85/// Type alias for the output of pipeline that returns multiple values
86pub type ManyOut<T> = EngineStream<T>;
87
88pub type ServiceEngine<T, U> = Engine<T, U, Error>;
89
90/// Unary Engine is a pipeline that takes a single input and returns a single output
91pub type UnaryEngine<T, U> = ServiceEngine<SingleIn<T>, SingleOut<U>>;
92
93/// `ClientStreaming` Engine is a pipeline that takes multiple inputs and returns a single output
94/// Typically the engine will consume the entire input stream; however, it can also decided to exit
95/// early and emit a response without consuming the entire input stream.
96pub type ClientStreamingEngine<T, U> = ServiceEngine<ManyIn<T>, SingleOut<U>>;
97
98/// `ServerStreaming` takes a single input and returns multiple outputs.
99pub type ServerStreamingEngine<T, U> = ServiceEngine<SingleIn<T>, ManyOut<U>>;
100
101/// `BidirectionalStreaming` takes multiple inputs and returns multiple outputs. Input and output values
102/// are considered independent of each other; however, they could be constrained to be related.
103pub type BidirectionalStreamingEngine<T, U> = ServiceEngine<ManyIn<T>, ManyOut<U>>;
104
105pub trait AsyncTransportEngine<T: Data + PipelineIO, U: Data + PipelineIO>:
106    AsyncEngine<T, U, Error> + Send + Sync + 'static
107{
108}
109
110// pub type TransportEngine<T, U> = Arc<dyn AsyncTransportEngine<T, U>>;
111
112mod sealed {
113    use super::*;
114
115    #[allow(dead_code)]
116    pub struct Token;
117
118    pub trait Connectable {
119        type DataType: Data;
120    }
121
122    impl<T: Data> Connectable for Context<T> {
123        type DataType = T;
124    }
125    impl<T: Data> Connectable for EngineUnary<T> {
126        type DataType = T;
127    }
128    impl<T: Data> Connectable for EngineStream<T> {
129        type DataType = T;
130    }
131}
132
133pub trait PipelineIO: sealed::Connectable + AsyncEngineContextProvider + 'static {
134    fn id(&self) -> String;
135}
136
137impl<T: Data> PipelineIO for Context<T> {
138    fn id(&self) -> String {
139        self.id().to_string()
140    }
141}
142impl<T: Data> PipelineIO for EngineUnary<T> {
143    fn id(&self) -> String {
144        self.context().id().to_string()
145    }
146}
147impl<T: Data> PipelineIO for EngineStream<T> {
148    fn id(&self) -> String {
149        self.context().id().to_string()
150    }
151}
152
153#[derive(Serialize, Deserialize, Debug, Clone)]
154pub struct Event {
155    pub id: String,
156}