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