Skip to main content

dynamo_runtime/
engine.rs

1// SPDX-FileCopyrightText: Copyright (c) 2024-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Asynchronous Engine System with Type Erasure Support
5//!
6//! This module provides the core asynchronous engine abstraction for Dynamo's runtime system.
7//! It defines the `AsyncEngine` trait for streaming engines and provides sophisticated
8//! type-erasure capabilities for managing heterogeneous engine collections.
9//!
10//! ## Type Erasure Overview
11//!
12//! Type erasure is a critical feature that allows storing different `AsyncEngine` implementations
13//! with varying generic type parameters in a single collection (e.g., `HashMap<String, Arc<dyn AnyAsyncEngine>>`).
14//! This is essential for:
15//!
16//! - **Dynamic Engine Management**: Registering and retrieving engines at runtime based on configuration
17//! - **Plugin Systems**: Loading different engine implementations without compile-time knowledge
18//! - **Service Discovery**: Managing multiple engine types in a unified registry
19//!
20//! ## Implementation Details
21//!
22//! The type-erasure system uses several advanced Rust features:
23//!
24//! - **Trait Objects (`dyn Trait`)**: For runtime polymorphism without compile-time type information
25//! - **`std::any::TypeId`**: For runtime type checking during downcasting
26//! - **`std::any::Any`**: For type-erased storage and safe downcasting
27//! - **`PhantomData`**: For maintaining type relationships in generic wrappers
28//! - **Extension Traits**: For ergonomic API design without modifying existing types
29//!
30//! ## Safety Considerations
31//!
32//! ⚠️ **IMPORTANT**: The type-erasure system relies on precise type matching at runtime.
33//! When modifying these traits or their implementations:
34//!
35//! - **Never change the type ID logic** in `AnyAsyncEngine` implementations
36//! - **Maintain the blanket `Data` implementation** for all `Send + Sync + 'static` types
37//! - **Test downcasting thoroughly** when adding new engine types
38//! - **Document any changes** that affect the type-erasure behavior
39//!
40//! ## Usage Example
41//!
42//! ```rust,ignore
43//! use std::collections::HashMap;
44//! use std::sync::Arc;
45//! use crate::engine::{AsyncEngine, AsAnyAsyncEngine, DowncastAnyAsyncEngine};
46//!
47//! // Create typed engines
48//! let string_engine: Arc<dyn AsyncEngine<String, String, ()>> = Arc::new(MyStringEngine::new());
49//! let int_engine: Arc<dyn AsyncEngine<i32, i32, ()>> = Arc::new(MyIntEngine::new());
50//!
51//! // Store in heterogeneous collection
52//! let mut engines: HashMap<String, Arc<dyn AnyAsyncEngine>> = HashMap::new();
53//! engines.insert("string".to_string(), string_engine.into_any_engine());
54//! engines.insert("int".to_string(), int_engine.into_any_engine());
55//!
56//! // Retrieve and downcast safely
57//! if let Some(typed_engine) = engines.get("string").unwrap().downcast::<String, String, ()>() {
58//!     let result = typed_engine.generate("hello".to_string()).await;
59//! }
60//! ```
61
62use std::{
63    any::{Any, TypeId},
64    fmt::Debug,
65    future::Future,
66    marker::PhantomData,
67    pin::Pin,
68    sync::Arc,
69};
70
71pub use async_trait::async_trait;
72use futures::stream::Stream;
73
74/// All [`Send`] + [`Sync`] + `'static` types can be used as [`AsyncEngine`] request and response types.
75///
76/// This is implemented as a blanket implementation for all types that meet the bounds.
77/// **Do not manually implement this trait** - the blanket implementation covers all valid types.
78pub trait Data: Send + Sync + 'static {}
79impl<T: Send + Sync + 'static> Data for T {}
80
81/// [`DataStream`] is a type alias for a stream of [`Data`] items. This can be adapted to a [`ResponseStream`]
82/// by associating it with a [`AsyncEngineContext`].
83pub type DataUnary<T> = Pin<Box<dyn Future<Output = T> + Send>>;
84pub type DataStream<T> = Pin<Box<dyn Stream<Item = T> + Send>>;
85
86pub type Engine<Req, Resp, E> = Arc<dyn AsyncEngine<Req, Resp, E>>;
87pub type EngineUnary<Resp> = Pin<Box<dyn AsyncEngineUnary<Resp>>>;
88/// Trait-object alias for an [`AsyncEngineStream`] — used on both sides of an
89/// engine: the input side via [`crate::pipeline::ManyIn`] and the output side via
90/// [`crate::pipeline::ManyOut`]. The directional names exist
91/// at the [`crate::pipeline`] alias layer for documentary clarity at use sites.
92pub type EngineStream<T> = Pin<Box<dyn AsyncEngineStream<T>>>;
93pub type Context = Arc<dyn AsyncEngineContext>;
94pub type EngineContextGuard = Arc<dyn Any + Send + Sync>;
95
96impl<T: Data> From<EngineStream<T>> for DataStream<T> {
97    fn from(stream: EngineStream<T>) -> Self {
98        Box::pin(stream)
99    }
100}
101
102// The Controller and the Context when https://github.com/rust-lang/rust/issues/65991 becomes stable
103pub trait AsyncEngineController: Send + Sync {}
104
105/// The [`AsyncEngineContext`] trait defines the interface to control the resulting stream
106/// produced by the engine.
107///
108/// This trait provides lifecycle management for async operations, including:
109/// - Stream identification via unique IDs
110/// - Graceful shutdown capabilities (`stop_generating`)
111/// - Immediate termination capabilities (`kill`)
112/// - Status checking for stopped/killed states
113///
114/// Implementations should ensure thread-safety and proper state management
115/// across concurrent access patterns.
116#[async_trait]
117pub trait AsyncEngineContext: Send + Sync + Debug {
118    /// Unique ID for the Stream
119    fn id(&self) -> &str;
120
121    /// Returns true if `stop_generating()` has been called; otherwise, false.
122    fn is_stopped(&self) -> bool;
123
124    /// Returns true if `kill()` has been called; otherwise, false.
125    /// This can be used with a `.take_while()` stream combinator to immediately terminate
126    /// the stream.
127    ///
128    /// An ideal location for a `[.take_while(!ctx.is_killed())]` stream combinator is on
129    /// the most downstream  return stream.
130    fn is_killed(&self) -> bool;
131
132    /// Calling this method when [`AsyncEngineContext::is_stopped`] is `true` will return
133    /// immediately; otherwise, it will [`AsyncEngineContext::is_stopped`] will return true.
134    async fn stopped(&self);
135
136    /// Calling this method when [`AsyncEngineContext::is_killed`] is `true` will return
137    /// immediately; otherwise, it will [`AsyncEngineContext::is_killed`] will return true.
138    async fn killed(&self);
139
140    // Controller
141
142    /// Informs the [`AsyncEngine`] to stop producing results for this particular stream.
143    /// This method is idempotent. This method does not invalidate results current in the
144    /// stream. It might take some time for the engine to stop producing results. The caller
145    /// can decided to drain the stream or drop the stream.
146    /// Implementations must preserve a killed state when `stop_generating()` or `stop()` is
147    /// called after `kill()`.
148    fn stop_generating(&self);
149
150    /// See [`AsyncEngineContext::stop_generating`].
151    fn stop(&self);
152
153    /// Extends the [`AsyncEngineContext::stop_generating`] also indicates a preference to
154    /// terminate without draining the remaining items in the stream. This is implementation
155    /// specific and may not be supported by all engines.
156    fn kill(&self);
157
158    /// Links child AsyncEngineContext to this AsyncEngineContext. If the `stop_generating`, `stop`
159    /// or `kill` on this AsyncEngineContext is called, the same method is called on all linked
160    /// child AsyncEngineContext, in the order they are linked, and then the method on this
161    /// AsyncEngineContext continues.
162    fn link_child(&self, child: Arc<dyn AsyncEngineContext>);
163
164    /// Retain request-scoped state until the engine context is dropped.
165    fn retain(&self, guard: EngineContextGuard) {
166        drop(guard);
167    }
168}
169
170/// Provides access to the [`AsyncEngineContext`] associated with an engine operation.
171///
172/// This trait is implemented by both unary and streaming engine results, allowing
173/// uniform access to context information regardless of the operation type.
174pub trait AsyncEngineContextProvider: Send + Debug {
175    fn context(&self) -> Arc<dyn AsyncEngineContext>;
176}
177
178/// A unary (single-response) asynchronous engine operation.
179///
180/// This trait combines `Future` semantics with context provider capabilities,
181/// representing a single async operation that produces one result.
182pub trait AsyncEngineUnary<Resp: Data>:
183    Future<Output = Resp> + AsyncEngineContextProvider + Send
184{
185}
186
187/// A streaming asynchronous engine operation.
188///
189/// This trait combines `Stream` semantics with context provider capabilities,
190/// representing a continuous async operation that produces multiple messages over time.
191/// The canonical boxed form is [`EngineStream<T>`] (= `crate::pipeline::ManyOut<T>`),
192/// the stream of response chunks an engine emits; [`ResponseStream`] is the
193/// canonical concrete implementor.
194pub trait AsyncEngineStream<T: Data>: Stream<Item = T> + AsyncEngineContextProvider + Send {}
195
196/// Engine is a trait that defines the interface for a streaming engine.
197/// The synchronous Engine version is does not need to be awaited.
198///
199/// This is the core trait for all async engine implementations. It provides:
200/// - Generic type parameters for request, response, and error types
201/// - Async generation capabilities with proper error handling
202/// - Thread-safe design with `Send + Sync` bounds
203///
204/// ## Type Parameters
205/// - `Req`: The request type — required to be `Send + 'static`. The `Sync`
206///   bound was removed from `Req` for convenience: forcing `Sync` on `Req`
207///   propagates a `+ Sync` constraint onto every type that flows in (in
208///   particular, every input-side trait-object alias), and no
209///   existing implementation of `AsyncEngine` relies on the `Sync` nature of
210///   the request. Revisit if a future implementation genuinely needs
211///   shared-reference access to a request value across threads.
212/// - `Resp`: The response type that implements `AsyncEngineContextProvider`
213/// - `E`: The error type that implements `Data`
214///
215/// ## Implementation Notes
216/// Implementations should ensure proper error handling and resource management.
217/// The `generate` method should be cancellable via the response's context provider.
218#[async_trait]
219pub trait AsyncEngine<Req: Send + 'static, Resp: AsyncEngineContextProvider, E: Data>:
220    Send + Sync
221{
222    /// Generate a stream of completion responses.
223    async fn generate(&self, request: Req) -> Result<Resp, E>;
224}
225
226/// Adapter for a [`DataStream`] to a [`ResponseStream`].
227///
228/// A common pattern is to consume the [`ResponseStream`] with standard stream combinators
229/// which produces a [`DataStream`] stream, then form a [`ResponseStream`] by propagating the
230/// original [`AsyncEngineContext`].
231pub struct ResponseStream<R: Data> {
232    stream: DataStream<R>,
233    ctx: Arc<dyn AsyncEngineContext>,
234}
235
236impl<R: Data> ResponseStream<R> {
237    pub fn new(stream: DataStream<R>, ctx: Arc<dyn AsyncEngineContext>) -> Pin<Box<Self>> {
238        Box::pin(Self { stream, ctx })
239    }
240}
241
242impl<R: Data> Stream for ResponseStream<R> {
243    type Item = R;
244
245    #[inline]
246    fn poll_next(
247        mut self: Pin<&mut Self>,
248        cx: &mut std::task::Context<'_>,
249    ) -> std::task::Poll<Option<Self::Item>> {
250        Pin::new(&mut self.stream).poll_next(cx)
251    }
252}
253
254impl<R: Data> AsyncEngineStream<R> for ResponseStream<R> {}
255
256impl<R: Data> AsyncEngineContextProvider for ResponseStream<R> {
257    fn context(&self) -> Arc<dyn AsyncEngineContext> {
258        self.ctx.clone()
259    }
260}
261
262impl<R: Data> Debug for ResponseStream<R> {
263    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
264        f.debug_struct("ResponseStream")
265            // todo: add debug for stream - possibly propagate some information about what
266            // engine created the stream
267            // .field("stream", &self.stream)
268            .field("ctx", &self.ctx)
269            .finish()
270    }
271}
272
273impl<T: Data> AsyncEngineContextProvider for Pin<Box<dyn AsyncEngineUnary<T>>> {
274    fn context(&self) -> Arc<dyn AsyncEngineContext> {
275        AsyncEngineContextProvider::context(&**self)
276    }
277}
278
279impl<T: Data> AsyncEngineContextProvider for Pin<Box<dyn AsyncEngineStream<T>>> {
280    fn context(&self) -> Arc<dyn AsyncEngineContext> {
281        AsyncEngineContextProvider::context(&**self)
282    }
283}
284
285/// A type-erased `AsyncEngine`.
286///
287/// This trait enables storing heterogeneous `AsyncEngine` implementations in collections
288/// by erasing their specific generic type parameters. It provides runtime type information
289/// and safe downcasting capabilities.
290///
291/// ## Type Erasure Mechanism
292/// The trait uses `std::any::TypeId` to preserve type information at runtime, allowing
293/// safe downcasting back to the original `AsyncEngine<Req, Resp, E>` types.
294///
295/// ## Safety Guarantees
296/// - Type IDs are preserved exactly as they were during type erasure
297/// - Downcasting is only possible to the original type combination
298/// - Incorrect downcasts return `None` rather than panicking
299///
300/// ## Implementation Notes
301/// This trait is implemented by the internal `AnyEngineWrapper` struct. Users should
302/// not implement this trait directly - use the `AsAnyAsyncEngine` extension trait instead.
303pub trait AnyAsyncEngine: Send + Sync {
304    /// Returns the `TypeId` of the request type used by this engine.
305    fn request_type_id(&self) -> TypeId;
306
307    /// Returns the `TypeId` of the response type used by this engine.
308    fn response_type_id(&self) -> TypeId;
309
310    /// Returns the `TypeId` of the error type used by this engine.
311    fn error_type_id(&self) -> TypeId;
312
313    /// Provides access to the underlying engine as a `dyn Any` for downcasting.
314    fn as_any(&self) -> &dyn Any;
315}
316
317/// An internal wrapper to hold a typed `AsyncEngine` behind the `AnyAsyncEngine` trait object.
318///
319/// This struct uses `PhantomData<fn(Req, Resp, E)>` to maintain the type relationship
320/// without storing the types directly, enabling the type-erasure mechanism.
321///
322/// ## PhantomData Usage
323/// The `PhantomData<fn(Req, Resp, E)>` ensures that the compiler knows about the
324/// generic type parameters without requiring them to be `'static`, which would
325/// prevent storing non-static types in the engine.
326struct AnyEngineWrapper<Req, Resp, E>
327where
328    Req: Data,
329    Resp: Data + AsyncEngineContextProvider,
330    E: Data,
331{
332    engine: Arc<dyn AsyncEngine<Req, Resp, E>>,
333    _phantom: PhantomData<fn(Req, Resp, E)>,
334}
335
336impl<Req, Resp, E> AnyAsyncEngine for AnyEngineWrapper<Req, Resp, E>
337where
338    Req: Data,
339    Resp: Data + AsyncEngineContextProvider,
340    E: Data,
341{
342    fn request_type_id(&self) -> TypeId {
343        TypeId::of::<Req>()
344    }
345
346    fn response_type_id(&self) -> TypeId {
347        TypeId::of::<Resp>()
348    }
349
350    fn error_type_id(&self) -> TypeId {
351        TypeId::of::<E>()
352    }
353
354    fn as_any(&self) -> &dyn Any {
355        &self.engine
356    }
357}
358
359/// An extension trait that provides a convenient way to type-erase an `AsyncEngine`.
360///
361/// This trait provides the `.into_any_engine()` method on any `Arc<dyn AsyncEngine<...>>`,
362/// enabling ergonomic type erasure without explicit wrapper construction.
363///
364/// ## Usage
365/// ```rust,ignore
366/// use crate::engine::AsAnyAsyncEngine;
367///
368/// let typed_engine: Arc<dyn AsyncEngine<String, String, ()>> = Arc::new(MyEngine::new());
369/// let any_engine = typed_engine.into_any_engine();
370/// ```
371pub trait AsAnyAsyncEngine {
372    /// Converts a typed `AsyncEngine` into a type-erased `AnyAsyncEngine`.
373    fn into_any_engine(self) -> Arc<dyn AnyAsyncEngine>;
374}
375
376impl<Req, Resp, E> AsAnyAsyncEngine for Arc<dyn AsyncEngine<Req, Resp, E>>
377where
378    Req: Data,
379    Resp: Data + AsyncEngineContextProvider,
380    E: Data,
381{
382    fn into_any_engine(self) -> Arc<dyn AnyAsyncEngine> {
383        Arc::new(AnyEngineWrapper {
384            engine: self,
385            _phantom: PhantomData,
386        })
387    }
388}
389
390/// An extension trait that provides a convenient method to downcast an `AnyAsyncEngine`.
391///
392/// This trait provides the `.downcast<Req, Resp, E>()` method on `Arc<dyn AnyAsyncEngine>`,
393/// enabling safe downcasting back to the original typed engine.
394///
395/// ## Safety
396/// The downcast method performs runtime type checking using `TypeId` comparison.
397/// It will only succeed if the type parameters exactly match the original engine's types.
398///
399/// ## Usage
400/// ```rust,ignore
401/// use crate::engine::DowncastAnyAsyncEngine;
402///
403/// let any_engine: Arc<dyn AnyAsyncEngine> = // ... from collection
404/// if let Some(typed_engine) = any_engine.downcast::<String, String, ()>() {
405///     // Use the typed engine
406///     let result = typed_engine.generate("hello".to_string()).await;
407/// }
408/// ```
409pub trait DowncastAnyAsyncEngine {
410    /// Attempts to downcast an `AnyAsyncEngine` to a specific `AsyncEngine` type.
411    ///
412    /// Returns `Some(engine)` if the type parameters match the original engine,
413    /// or `None` if the types don't match.
414    fn downcast<Req, Resp, E>(&self) -> Option<Arc<dyn AsyncEngine<Req, Resp, E>>>
415    where
416        Req: Data,
417        Resp: Data + AsyncEngineContextProvider,
418        E: Data;
419}
420
421impl DowncastAnyAsyncEngine for Arc<dyn AnyAsyncEngine> {
422    fn downcast<Req, Resp, E>(&self) -> Option<Arc<dyn AsyncEngine<Req, Resp, E>>>
423    where
424        Req: Data,
425        Resp: Data + AsyncEngineContextProvider,
426        E: Data,
427    {
428        if self.request_type_id() == TypeId::of::<Req>()
429            && self.response_type_id() == TypeId::of::<Resp>()
430            && self.error_type_id() == TypeId::of::<E>()
431        {
432            self.as_any()
433                .downcast_ref::<Arc<dyn AsyncEngine<Req, Resp, E>>>()
434                .cloned()
435        } else {
436            None
437        }
438    }
439}
440
441#[cfg(test)]
442mod tests {
443    use super::*;
444    use std::collections::HashMap;
445
446    // 1. Define mock data structures
447    #[derive(Debug, PartialEq)]
448    struct Req1(String);
449
450    #[derive(Debug, PartialEq)]
451    struct Resp1(String);
452
453    // Dummy context provider implementation for the response
454    impl AsyncEngineContextProvider for Resp1 {
455        fn context(&self) -> Arc<dyn AsyncEngineContext> {
456            // For this test, we don't need a real context.
457            unimplemented!()
458        }
459    }
460
461    #[derive(Debug)]
462    struct Err1;
463
464    // A different set of types for testing failure cases
465    #[derive(Debug)]
466    struct Req2;
467    #[derive(Debug)]
468    struct Resp2;
469    impl AsyncEngineContextProvider for Resp2 {
470        fn context(&self) -> Arc<dyn AsyncEngineContext> {
471            unimplemented!()
472        }
473    }
474
475    // 2. Define a mock engine
476    struct MockEngine;
477
478    #[async_trait]
479    impl AsyncEngine<Req1, Resp1, Err1> for MockEngine {
480        async fn generate(&self, request: Req1) -> Result<Resp1, Err1> {
481            Ok(Resp1(format!("response to {}", request.0)))
482        }
483    }
484
485    #[tokio::test]
486    async fn test_engine_type_erasure_and_downcast() {
487        // 3. Create a typed engine
488        let typed_engine: Arc<dyn AsyncEngine<Req1, Resp1, Err1>> = Arc::new(MockEngine);
489
490        // 4. Use the extension trait to erase the type
491        let any_engine = typed_engine.into_any_engine();
492
493        // Check type IDs are preserved
494        assert_eq!(any_engine.request_type_id(), TypeId::of::<Req1>());
495        assert_eq!(any_engine.response_type_id(), TypeId::of::<Resp1>());
496        assert_eq!(any_engine.error_type_id(), TypeId::of::<Err1>());
497
498        // 5. Use the new downcast method on the Arc
499        let downcasted_engine = any_engine.downcast::<Req1, Resp1, Err1>();
500
501        // 6. Assert success
502        assert!(downcasted_engine.is_some());
503
504        // We can even use the downcasted engine
505        let response = downcasted_engine
506            .unwrap()
507            .generate(Req1("hello".to_string()))
508            .await;
509        assert_eq!(response.unwrap(), Resp1("response to hello".to_string()));
510
511        // 7. Assert failure for wrong types
512        let failed_downcast = any_engine.downcast::<Req2, Resp2, Err1>();
513        assert!(failed_downcast.is_none());
514
515        // 8. HashMap usage test
516        let mut engine_map: HashMap<String, Arc<dyn AnyAsyncEngine>> = HashMap::new();
517        engine_map.insert("mock".to_string(), any_engine);
518
519        let retrieved_engine = engine_map.get("mock").unwrap();
520        let final_engine = retrieved_engine.downcast::<Req1, Resp1, Err1>().unwrap();
521        let final_response = final_engine.generate(Req1("world".to_string())).await;
522        assert_eq!(
523            final_response.unwrap(),
524            Resp1("response to world".to_string())
525        );
526    }
527}