aimdb_core/transform/join.rs
1use crate::transform::events::{report, TransformEvent};
2
3use core::any::{type_name, Any, TypeId};
4use core::fmt::Debug;
5use core::marker::PhantomData;
6
7use alloc::{
8 boxed::Box,
9 string::{String, ToString},
10 sync::Arc,
11 vec::Vec,
12};
13
14use crate::executor::{ExecutorError, ExecutorResult};
15
16use crate::transform::{CollectedTransform, TransformDescriptor};
17use crate::typed_record::BoxFuture;
18
19// ============================================================================
20// Fan-in queue
21// ============================================================================
22
23/// Capacity of the bounded fan-in channel between input forwarders and the
24/// trigger loop. Sized per target to match the per-adapter GAT queue family
25/// this replaces: 64 on std and wasm32 (tokio/WASM used 64 — a blocked
26/// forwarder stops draining its input buffer, so burst headroom matters
27/// there; the WASM adapter builds core without `std`, hence the target cfg).
28#[cfg(any(feature = "std", target_arch = "wasm32"))]
29const JOIN_QUEUE_CAPACITY: usize = 64;
30/// Embedded no_std: the Embassy queue this replaces used 8; 16 adds burst
31/// headroom at a few words of RAM per slot.
32#[cfg(not(any(feature = "std", target_arch = "wasm32")))]
33const JOIN_QUEUE_CAPACITY: usize = 16;
34
35/// One bounded queue for all runtimes — the same `async-channel` primitive the
36/// session engine already uses on tokio, Embassy, and WASM.
37fn join_channel() -> (
38 async_channel::Sender<JoinTrigger>,
39 async_channel::Receiver<JoinTrigger>,
40) {
41 async_channel::bounded(JOIN_QUEUE_CAPACITY)
42}
43
44// ============================================================================
45// JoinTrigger
46// ============================================================================
47
48/// Identifies which input produced a value in a multi-input join transform.
49///
50/// Passed to the event loop inside the closure registered with [`JoinBuilder::on_triggers`].
51/// Use [`JoinTrigger::index`] to branch on the source input and
52/// [`JoinTrigger::as_input`] to downcast the value to the concrete type.
53///
54/// # Why this carries `Box<dyn Any>`
55///
56/// This is the one deliberate exception to the data-plane de-erasure
57/// A join fans N *differently-typed* inputs into a single
58/// trigger channel, and the user's `on_triggers` closure branches on them
59/// via [`JoinTrigger::as_input`] — the erasure *is* the public API here, not
60/// an implementation accident. Removing it would mean N channels or a
61/// generated input enum, i.e. a different feature. The cost (one box +
62/// downcast per join input value) is confined to this module and applies
63/// only to explicit user-built joins, never to the connector spine.
64pub enum JoinTrigger {
65 /// A value written to input `index`. `metadata` is the write metadata of
66 /// that input value; match with `..`, more fields may follow.
67 #[non_exhaustive]
68 Input {
69 index: usize,
70 value: Box<dyn Any + Send>,
71 metadata: crate::WriteMetadata,
72 },
73}
74
75impl JoinTrigger {
76 pub fn as_input<T: 'static>(&self) -> Option<&T> {
77 match self {
78 JoinTrigger::Input { value, .. } => value.downcast_ref::<T>(),
79 }
80 }
81
82 pub fn index(&self) -> usize {
83 match self {
84 JoinTrigger::Input { index, .. } => *index,
85 }
86 }
87
88 /// The write metadata of the input value. The join's output is a new
89 /// write with its own; pairing inputs on write time is an application
90 /// choice (design 058 §1).
91 pub fn metadata(&self) -> &crate::WriteMetadata {
92 match self {
93 JoinTrigger::Input { metadata, .. } => metadata,
94 }
95 }
96
97 /// When the input value was written, on the instance clock.
98 pub fn stamp(&self) -> crate::Stamp {
99 self.metadata().stamp()
100 }
101}
102
103// ============================================================================
104// JoinEventRx — trigger receiver
105// ============================================================================
106
107/// Receiver for join trigger events.
108///
109/// Obtained as the first argument to the [`JoinBuilder::on_triggers`] closure.
110/// Call `.recv().await` in a loop to consume trigger events from all input forwarders.
111/// Returns `Err` when all input forwarders have exited and the channel is closed.
112pub struct JoinEventRx {
113 inner: async_channel::Receiver<JoinTrigger>,
114}
115
116impl JoinEventRx {
117 fn new(inner: async_channel::Receiver<JoinTrigger>) -> Self {
118 Self { inner }
119 }
120
121 /// Receive the next trigger event.
122 ///
123 /// Returns `Ok(JoinTrigger)` when an input fires, or `Err` when all input
124 /// forwarders have dropped their senders — on every runtime, ending any
125 /// `while let Ok(_) = rx.recv().await` loop.
126 pub async fn recv(&mut self) -> ExecutorResult<JoinTrigger> {
127 self.inner
128 .recv()
129 .await
130 .map_err(|_| ExecutorError::QueueClosed)
131 }
132}
133
134// ============================================================================
135// JoinBuilder → JoinPipeline
136// ============================================================================
137
138/// Type-erased factory for creating a forwarder task for one join input.
139type JoinInputFactory = Box<
140 dyn FnOnce(
141 Arc<crate::AimDb>,
142 usize,
143 async_channel::Sender<JoinTrigger>,
144 ) -> BoxFuture<'static, ()>
145 + Send
146 + Sync,
147>;
148
149/// Configures a multi-input join transform.
150///
151/// Available on every runtime. The fan-in queue (bounded channel between input
152/// forwarders and the trigger loop) lives in core, with capacity 64 on std and
153/// wasm32 and 16 on embedded `no_std`.
154///
155/// Obtain via [`RecordRegistrar::transform_join`](crate::RecordRegistrar::transform_join).
156pub struct JoinBuilder<O> {
157 inputs: Vec<(String, JoinInputFactory)>,
158 /// Type each input is read as, parallel to `inputs`.
159 input_types: Vec<(TypeId, &'static str)>,
160 _phantom: PhantomData<O>,
161}
162
163impl<O> JoinBuilder<O>
164where
165 O: Send + Sync + Clone + Debug + 'static,
166{
167 pub(crate) fn new() -> Self {
168 Self {
169 inputs: Vec::new(),
170 input_types: Vec::new(),
171 _phantom: PhantomData,
172 }
173 }
174
175 /// Add a typed input to the join.
176 pub fn input<I>(mut self, key: impl crate::RecordKey) -> Self
177 where
178 I: Send + Sync + Clone + Debug + 'static,
179 {
180 let key_str = key.as_str().to_string();
181 let key_for_factory = key_str.clone();
182
183 let factory: JoinInputFactory = Box::new(
184 move |db: Arc<crate::AimDb>, index: usize, tx: async_channel::Sender<JoinTrigger>| {
185 Box::pin(async move {
186 let consumer = match db.consumer::<I>(&key_for_factory) {
187 Ok(c) => c,
188 Err(_e) => {
189 report(TransformEvent::JoinConsumerResolutionFailed {
190 input: &key_for_factory,
191 index,
192 error: &_e,
193 });
194 return;
195 }
196 };
197 let mut reader = consumer.subscribe();
198
199 loop {
200 let sample = match reader.recv().await {
201 Ok(sample) => sample,
202 // SPMC-ring overflow: the reader recovers (cursor
203 // resets to the oldest live value), so a transient
204 // lag must not permanently silence this input —
205 // same policy as every other recv loop in core.
206 Err(crate::DbError::BufferLagged { .. }) => {
207 report(TransformEvent::JoinLagged {
208 input: &key_for_factory,
209 index,
210 });
211 continue;
212 }
213 // Buffer closed / fatal — the input record is gone.
214 Err(_) => break,
215 };
216 // Box the value, not the `Stamped<I>`: `as_input::<I>()`
217 // downcasts to `I` and would never match the envelope.
218 let trigger = JoinTrigger::Input {
219 index,
220 metadata: *sample.metadata(),
221 value: Box::new(sample.value),
222 };
223 if tx.send(trigger).await.is_err() {
224 break;
225 }
226 }
227 }) as BoxFuture<'static, ()>
228 },
229 );
230
231 self.inputs.push((key_str, factory));
232 self.input_types.push((TypeId::of::<I>(), type_name::<I>()));
233 self
234 }
235
236 /// Complete the pipeline by providing an async task that owns the event loop and state.
237 ///
238 /// The closure receives a [`JoinEventRx`] to read trigger events and a `Producer<O>`
239 /// to emit output values. Both are owned — moved into the `async move` block — so the
240 /// closure can freely hold borrows across `.await` points and maintain any state it needs.
241 ///
242 /// The task runs until all input forwarders close (i.e., all upstream records stop producing).
243 ///
244 /// Illustrative (not compiled: fragment of a `transform_join` pipeline with
245 /// user-defined input types):
246 ///
247 /// ```rust,ignore
248 /// .on_triggers(|mut rx, producer| async move {
249 /// let mut last_a: Option<f32> = None;
250 /// let mut last_b: Option<f32> = None;
251 /// while let Ok(trigger) = rx.recv().await {
252 /// match trigger.index() {
253 /// 0 => last_a = trigger.as_input::<InputA>().copied(),
254 /// 1 => last_b = trigger.as_input::<InputB>().copied(),
255 /// _ => {}
256 /// }
257 /// if let (Some(a), Some(b)) = (last_a, last_b) {
258 /// producer.produce(compute(a, b));
259 /// }
260 /// }
261 /// })
262 /// ```
263 ///
264 /// # Pairing values that belong together
265 ///
266 /// The handler above pairs each new value with the other input's latest.
267 /// When both inputs change at about the same time, the first output pairs
268 /// a new value with an old one. If the inputs carry a field that says
269 /// which values belong together, emit only when it matches and consume
270 /// both values:
271 ///
272 /// ```rust,ignore
273 /// .on_triggers(|mut rx, producer| async move {
274 /// let mut flow: Option<Flow> = None;
275 /// let mut ret: Option<Return> = None;
276 /// while let Ok(trigger) = rx.recv().await {
277 /// match trigger.index() {
278 /// 0 => flow = trigger.as_input::<Flow>().cloned(),
279 /// 1 => ret = trigger.as_input::<Return>().cloned(),
280 /// _ => {}
281 /// }
282 /// if let (Some(f), Some(r)) = (&flow, &ret) {
283 /// // Or a tolerance on an application timestamp. `trigger.stamp()`
284 /// // is the write time: "written within", not "measured within".
285 /// if f.sample_id == r.sample_id {
286 /// producer.produce(Difference::of(f, r));
287 /// flow = None;
288 /// ret = None;
289 /// }
290 /// }
291 /// }
292 /// })
293 /// ```
294 ///
295 /// - One value is retained per input, so an input running ahead skips
296 /// cycles: Flow 2, Flow 3, Return 3 emits only cycle 3.
297 /// - Which cycles are skipped depends on the arrival order between inputs.
298 /// - Values produced together by one source are better published as one
299 /// compound record, which needs no join.
300 ///
301 /// `transform_join_pairs_values_by_timestamp` in the Tokio adapter's
302 /// integration tests runs this handler, matching on timestamps.
303 pub fn on_triggers<F, Fut>(self, handler: F) -> JoinPipeline<O>
304 where
305 F: FnOnce(JoinEventRx, crate::Producer<O>) -> Fut + Send + 'static,
306 Fut: core::future::Future<Output = ()> + Send + 'static,
307 {
308 let inputs = self.inputs;
309 let input_types = self.input_types;
310 let input_keys_for_descriptor: Vec<String> =
311 inputs.iter().map(|(k, _)| k.clone()).collect();
312
313 JoinPipeline {
314 spawn_factory: Box::new(move |_| TransformDescriptor {
315 input_keys: input_keys_for_descriptor,
316 input_types,
317 build_fn: Box::new(move |producer, db, output_key, _profiling| {
318 build_join_collected(db, inputs, producer, handler, output_key)
319 }),
320 }),
321 }
322 }
323}
324
325/// Completed multi-input join pipeline, ready to be registered on a record.
326///
327/// Produced by [`JoinBuilder::on_triggers`] and consumed by
328/// [`RecordRegistrar::transform_join`](crate::RecordRegistrar::transform_join). Not normally constructed directly.
329pub struct JoinPipeline<O: Send + Sync + Clone + Debug + 'static> {
330 pub(crate) spawn_factory: Box<dyn FnOnce(()) -> TransformDescriptor<O> + Send>,
331}
332
333impl<O> JoinPipeline<O>
334where
335 O: Send + Sync + Clone + Debug + 'static,
336{
337 pub(crate) fn into_descriptor(self) -> TransformDescriptor<O> {
338 (self.spawn_factory)(())
339 }
340}
341
342// ============================================================================
343// Join Transform Build (forwarders + handler future, both collected at build time)
344// ============================================================================
345
346fn build_join_collected<O, F, Fut>(
347 db: Arc<crate::AimDb>,
348 inputs: Vec<(String, JoinInputFactory)>,
349 producer: crate::Producer<O>,
350 handler: F,
351 output_key: &str,
352) -> CollectedTransform
353where
354 O: Send + Sync + Clone + Debug + 'static,
355 F: FnOnce(JoinEventRx, crate::Producer<O>) -> Fut + Send + 'static,
356 Fut: core::future::Future<Output = ()> + Send + 'static,
357{
358 // Output key is threaded in from the descriptor so diagnostics stay
359 // unambiguous when multiple records share output type `O`.
360 // Owned copies are build-time, one-shot allocations.
361 let output_key = output_key.to_string();
362 let input_keys: Vec<String> = inputs.iter().map(|(k, _)| k.clone()).collect();
363 log_info!(
364 "🔄 Join transform building: {:?} → '{}'",
365 input_keys,
366 output_key
367 );
368
369 let (tx, rx) = join_channel();
370
371 // Build all forwarder futures eagerly; they will be driven by AimDbRunner.
372 let fanin_futures: Vec<BoxFuture<'static, ()>> = inputs
373 .into_iter()
374 .enumerate()
375 .map(|(index, (_key, factory))| {
376 let sender = tx.clone();
377 factory(db.clone(), index, sender)
378 })
379 .collect();
380
381 // Drop our local sender so the receiver closes once all forwarders exit.
382 drop(tx);
383
384 let task_future: BoxFuture<'static, ()> = Box::pin(async move {
385 log_debug!(
386 "✅ Join transform '{}' handing receiver to user task",
387 output_key
388 );
389
390 handler(JoinEventRx::new(rx), producer).await;
391
392 report(TransformEvent::JoinTaskExited {
393 output: &output_key,
394 });
395 });
396
397 CollectedTransform {
398 task_future,
399 fanin_futures,
400 }
401}