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