Skip to main content

aimdb_core/transform/
single.rs

1use crate::transform::events::{report, TransformEvent};
2
3use core::any::{type_name, TypeId};
4use core::fmt::Debug;
5use core::marker::PhantomData;
6
7use alloc::{
8    boxed::Box,
9    string::{String, ToString},
10    sync::Arc,
11    vec,
12};
13
14use crate::transform::{CollectedTransform, TransformDescriptor, TransformProfiling};
15
16// ============================================================================
17// TransformBuilder โ†’ TransformPipeline
18// ============================================================================
19
20/// Configures a single-input transform pipeline.
21///
22/// Created by `RecordRegistrar::transform()`. Use `.map()` for stateless
23/// transforms or `.with_state()` for stateful transforms.
24pub struct TransformBuilder<I, O> {
25    input_key: String,
26    _phantom: PhantomData<(I, O)>,
27}
28
29impl<I, O> TransformBuilder<I, O>
30where
31    I: Send + Sync + Clone + Debug + 'static,
32    O: Send + Sync + Clone + Debug + 'static,
33{
34    pub(crate) fn new(input_key: String) -> Self {
35        Self {
36            input_key,
37            _phantom: PhantomData,
38        }
39    }
40
41    /// Stateless 1:1 map. Returning `None` skips output for this input value.
42    pub fn map<F>(self, f: F) -> TransformPipeline<I, O>
43    where
44        F: Fn(&I) -> Option<O> + Send + Sync + 'static,
45    {
46        TransformPipeline {
47            input_key: self.input_key,
48            spawn_factory: Box::new(move |input_key| {
49                let transform_fn = move |val: &I, _state: &mut ()| f(val);
50                create_single_transform_descriptor::<I, O, ()>(input_key, (), transform_fn)
51            }),
52            _phantom_i: PhantomData,
53        }
54    }
55
56    /// Begin configuring a stateful transform. `S` is the user-defined state type.
57    pub fn with_state<S: Send + Sync + 'static>(
58        self,
59        initial: S,
60    ) -> StatefulTransformBuilder<I, O, S> {
61        StatefulTransformBuilder {
62            input_key: self.input_key,
63            initial_state: initial,
64            _phantom: PhantomData,
65        }
66    }
67}
68
69/// Intermediate builder for stateful single-input transforms.
70pub struct StatefulTransformBuilder<I, O, S> {
71    input_key: String,
72    initial_state: S,
73    _phantom: PhantomData<(I, O)>,
74}
75
76impl<I, O, S> StatefulTransformBuilder<I, O, S>
77where
78    I: Send + Sync + Clone + Debug + 'static,
79    O: Send + Sync + Clone + Debug + 'static,
80    S: Send + Sync + 'static,
81{
82    /// Called for each input value. Receives mutable state, returns optional output.
83    pub fn on_value<F>(self, f: F) -> TransformPipeline<I, O>
84    where
85        F: Fn(&I, &mut S) -> Option<O> + Send + Sync + 'static,
86    {
87        let initial = self.initial_state;
88        TransformPipeline {
89            input_key: self.input_key,
90            spawn_factory: Box::new(move |input_key| {
91                create_single_transform_descriptor::<I, O, S>(input_key, initial, f)
92            }),
93            _phantom_i: PhantomData,
94        }
95    }
96}
97
98/// Completed single-input transform pipeline, ready to be stored in `TypedRecord`.
99pub struct TransformPipeline<I, O: Send + Sync + Clone + Debug + 'static> {
100    pub(crate) input_key: String,
101    pub(crate) spawn_factory: Box<dyn FnOnce(String) -> TransformDescriptor<O> + Send + Sync>,
102    pub(crate) _phantom_i: PhantomData<I>,
103}
104
105impl<I, O> TransformPipeline<I, O>
106where
107    I: Send + Sync + Clone + Debug + 'static,
108    O: Send + Sync + Clone + Debug + 'static,
109{
110    pub(crate) fn into_descriptor(self) -> TransformDescriptor<O> {
111        (self.spawn_factory)(self.input_key)
112    }
113}
114
115fn create_single_transform_descriptor<I, O, S>(
116    input_key: String,
117    initial_state: S,
118    transform_fn: impl Fn(&I, &mut S) -> Option<O> + Send + Sync + 'static,
119) -> TransformDescriptor<O>
120where
121    I: Send + Sync + Clone + Debug + 'static,
122    O: Send + Sync + Clone + Debug + 'static,
123    S: Send + Sync + 'static,
124{
125    let input_key_clone = input_key.clone();
126    let input_keys = vec![input_key];
127
128    TransformDescriptor {
129        input_keys,
130        input_types: vec![(TypeId::of::<I>(), type_name::<I>())],
131        build_fn: Box::new(
132            move |producer, db, output_key, profiling| CollectedTransform {
133                task_future: Box::pin(run_single_transform::<I, O, S>(
134                    db,
135                    input_key_clone,
136                    output_key.to_string(),
137                    producer,
138                    initial_state,
139                    transform_fn,
140                    profiling,
141                )),
142                fanin_futures: alloc::vec::Vec::new(),
143            },
144        ),
145    }
146}
147
148// ============================================================================
149// Transform Task Runner
150// ============================================================================
151
152#[allow(unused_variables)]
153pub(crate) async fn run_single_transform<I, O, S>(
154    db: Arc<crate::AimDb>,
155    input_key: String,
156    output_key: String,
157    producer: crate::Producer<O>,
158    mut state: S,
159    transform_fn: impl Fn(&I, &mut S) -> Option<O> + Send + Sync + 'static,
160    profiling: TransformProfiling,
161) where
162    I: Send + Sync + Clone + Debug + 'static,
163    O: Send + Sync + Clone + Debug + 'static,
164    S: Send + 'static,
165{
166    // `Producer<O>` no longer exposes a `.key()` accessor โ€” the
167    // output key is threaded in by the transform descriptor so diagnostics
168    // remain unambiguous when multiple records share type `O`.
169    log_info!("๐Ÿ”„ Transform started: '{}' โ†’ '{}'", input_key, output_key);
170
171    let consumer = match db.consumer::<I>(&input_key) {
172        Ok(c) => c,
173        Err(_e) => {
174            report(TransformEvent::ConsumerResolutionFailed {
175                input: &input_key,
176                output: &output_key,
177                error: &_e,
178            });
179            return;
180        }
181    };
182    let mut reader = consumer.subscribe();
183
184    log_debug!(
185        "โœ… Transform '{}' โ†’ '{}' subscribed, entering event loop",
186        input_key,
187        output_key
188    );
189
190    loop {
191        // The input's write metadata stays here: the output is a new write
192        // and gets its own (design 058 ยง4.4).
193        match reader.recv().await.map(crate::Stamped::into_value) {
194            Ok(input_value) => {
195                #[cfg(feature = "observability")]
196                {
197                    let started_ns = profiling.as_ref().map(|(_, clock)| clock());
198                    let output_value = transform_fn(&input_value, &mut state);
199                    if let (Some((metrics, clock)), Some(started_ns)) = (&profiling, started_ns) {
200                        metrics.record(clock().saturating_sub(started_ns));
201                    }
202                    if let Some(output_value) = output_value {
203                        producer.produce(output_value);
204                    }
205                }
206                #[cfg(not(feature = "observability"))]
207                {
208                    if let Some(output_value) = transform_fn(&input_value, &mut state) {
209                        producer.produce(output_value);
210                    }
211                }
212            }
213            Err(crate::DbError::BufferLagged { .. }) => {
214                report(TransformEvent::Lagged {
215                    input: &input_key,
216                    output: &output_key,
217                });
218                continue;
219            }
220            Err(_) => {
221                report(TransformEvent::InputClosed {
222                    input: &input_key,
223                    output: &output_key,
224                });
225                break;
226            }
227        }
228    }
229}
230
231#[cfg(all(test, feature = "std"))]
232mod event_tests {
233    use super::*;
234    #[tokio::test]
235    async fn missing_input_reports_a_typed_fatal_event() {
236        let mut builder = crate::AimDbBuilder::new()
237            .runtime(Arc::new(crate::executor::test_support::NoopRuntimeOps));
238        builder.configure::<u32>("output", |_| {});
239        let (db, _runner) = builder.build().await.unwrap();
240        let producer = db.producer::<u32>("output").unwrap();
241        let seen = Arc::new(core::sync::atomic::AtomicBool::new(false));
242        let observer = {
243            let seen = seen.clone();
244            Arc::new(move |event: &TransformEvent<'_>| match event {
245                TransformEvent::ConsumerResolutionFailed {
246                    input,
247                    output,
248                    error,
249                } => {
250                    assert_eq!((*input, *output), ("missing", "output"));
251                    assert!(matches!(error, crate::DbError::RecordKeyNotFound { .. }));
252                    seen.store(true, core::sync::atomic::Ordering::Relaxed);
253                }
254                other => panic!("unexpected {other:?}"),
255            })
256        };
257        super::super::events::capture::future(
258            observer,
259            run_single_transform::<u32, u32, ()>(
260                Arc::new(db),
261                "missing".into(),
262                "output".into(),
263                producer,
264                (),
265                |_, _| None,
266                #[cfg(feature = "observability")]
267                None,
268                #[cfg(not(feature = "observability"))]
269                (),
270            ),
271        )
272        .await;
273        assert!(seen.load(core::sync::atomic::Ordering::Relaxed));
274    }
275}