Skip to main content

saluki_core/topology/interconnect/
dispatcher.rs

1use std::{borrow::Cow, time::Instant};
2
3use saluki_common::collections::FastHashMap;
4use saluki_error::{generic_error, GenericError};
5use saluki_metrics::{static_metrics, Counter, Histogram};
6use tokio::sync::mpsc;
7
8use super::Dispatchable;
9use crate::{
10    components::ComponentContext,
11    topology::{condition::EdgeGate, OutputName},
12};
13
14// TODO: When we have support for additional static labels on a per-metric basis, add `discard_reason` to
15// `events_discarded_total` metric to indicate that it's due to the destination component being disconnected.
16#[static_metrics(prefix = component, labels(component_id, component_type, output))]
17#[derive(Clone)]
18struct DispatcherMetrics {
19    events_sent_total: Counter,
20    #[metric(level = trace)]
21    send_latency_seconds: Histogram,
22    events_discarded_total: Counter,
23    events_elided_total: Counter,
24}
25
26impl DispatcherMetrics {
27    fn default_output(context: ComponentContext) -> Self {
28        Self::with_output_name(context, "_default")
29    }
30
31    fn named_output(context: ComponentContext, output_name: &str) -> Self {
32        Self::with_output_name(context, output_name)
33    }
34
35    fn with_output_name(context: ComponentContext, output_name: &str) -> Self {
36        Self::new(context.component_id(), context.component_type().as_str(), output_name)
37    }
38}
39
40/// A type that can be used as a buffer for dispatching items.
41pub trait DispatchBuffer: Dispatchable + Default {
42    /// Type of item that can be pushed into the buffer.
43    type Item;
44
45    /// Returns the number of items currently in the buffer.
46    fn len(&self) -> usize;
47
48    /// Returns `true` if the buffer is full.
49    fn is_full(&self) -> bool;
50
51    /// Attempts to push an item into the buffer.
52    ///
53    /// Returns `Some(item)` if the buffer is full and the item couldn't be pushed.
54    fn try_push(&mut self, item: Self::Item) -> Option<Self::Item>;
55}
56
57/// A sender to a downstream component, optionally gated by a dynamic connection condition.
58struct GatedSender<T> {
59    sender: mpsc::Sender<T>,
60    gate: Option<EdgeGate>,
61}
62
63impl<T> GatedSender<T> {
64    #[inline]
65    fn is_active(&self) -> bool {
66        self.gate.as_ref().is_none_or(EdgeGate::is_active)
67    }
68}
69
70struct DispatchTarget<T> {
71    metrics: DispatcherMetrics,
72    senders: Vec<GatedSender<T>>,
73}
74
75impl<T> DispatchTarget<T>
76where
77    T: Dispatchable,
78{
79    fn default_output(context: ComponentContext) -> Self {
80        Self {
81            metrics: DispatcherMetrics::default_output(context),
82            senders: Vec::new(),
83        }
84    }
85
86    fn named_output(context: ComponentContext, output_name: &str) -> Self {
87        Self {
88            metrics: DispatcherMetrics::named_output(context, output_name),
89            senders: Vec::new(),
90        }
91    }
92
93    fn add_sender(&mut self, sender: mpsc::Sender<T>, gate: Option<EdgeGate>) {
94        self.senders.push(GatedSender { sender, gate });
95    }
96
97    /// Returns the index of the first active sender at or after `start`.
98    fn next_active_sender(&self, start: usize) -> Option<usize> {
99        self.senders[start..]
100            .iter()
101            .position(GatedSender::is_active)
102            .map(|offset| start + offset)
103    }
104
105    async fn send(&self, item: T) -> Result<(), GenericError> {
106        if self.senders.is_empty() {
107            // Track discarded events when no senders are attached to this output
108            let item_count = item.item_count() as u64;
109            self.metrics.events_discarded_total().increment(item_count);
110            // Anchor the legitimate zero-sender discard. A wired edge never reaches this branch, so this stays a
111            // disconnected-output signal — not a silent-loss-on-a-wired-edge violation.
112            saluki_antithesis::sometimes!(
113                true,
114                "events discarded on a zero-sender output",
115                { "items": item_count }
116            );
117            return Ok(());
118        }
119
120        let start = Instant::now();
121        let item_count = item.item_count();
122
123        // Senders whose connection condition is currently false are skipped entirely: the item is neither cloned nor
124        // sent to them. Only gated senders can be skipped, so every ungated connection still receives every item.
125        //
126        // The item is cloned for every active sender except the last one, which gets the original.
127        let mut item = Some(item);
128        let mut active_sends = 0;
129        let mut next_active = self.next_active_sender(0);
130        while let Some(index) = next_active {
131            next_active = self.next_active_sender(index + 1);
132            let item = if next_active.is_some() {
133                item.clone()
134            } else {
135                item.take()
136            };
137            self.senders[index]
138                .sender
139                .send(item.expect("item is only taken for the last active sender"))
140                .await
141                .map_err(|_| generic_error!("Failed to send to output."))?;
142            active_sends += 1;
143        }
144
145        let elided_sends = self.senders.len() - active_sends;
146        if elided_sends > 0 {
147            self.metrics
148                .events_elided_total()
149                .increment((elided_sends * item_count) as u64);
150            saluki_antithesis::sometimes!(
151                true,
152                "events elided on a connection whose condition is false",
153                { "items": item_count, "elided_sends": elided_sends }
154            );
155        }
156
157        if active_sends > 0 {
158            // TODO: We should consider splitting this out per-sender somehow. We would need to carry around the
159            // destination component's ID, though, to properly associate it.
160            self.metrics.send_latency_seconds().record(start.elapsed());
161            self.metrics
162                .events_sent_total()
163                .increment((active_sends * item_count) as u64);
164        }
165
166        Ok(())
167    }
168}
169
170/// A buffered dispatcher.
171///
172/// `BufferedDispatcher` provides an efficient and ergonomic interface to `Dispatcher` that allows for writing events
173/// one-by-one into batches, which are then dispatched to the configured output as needed. This allows callers to focus
174/// on the logic around what items to send, without needing to worry about the details of event buffer sizing or
175/// flushing.
176pub struct BufferedDispatcher<'a, T> {
177    metrics: &'a DispatcherMetrics,
178    flushed_len: usize,
179    buffer: Option<T>,
180    target: &'a DispatchTarget<T>,
181}
182
183impl<'a, T> BufferedDispatcher<'a, T> {
184    fn new(target: &'a DispatchTarget<T>) -> Self {
185        Self {
186            metrics: &target.metrics,
187            flushed_len: 0,
188            buffer: None,
189            target,
190        }
191    }
192}
193
194impl<T> BufferedDispatcher<'_, T>
195where
196    T: DispatchBuffer,
197{
198    async fn try_flush_buffer(&self, buffer: T) -> Result<(), GenericError> {
199        let buffer_len = buffer.len();
200        if buffer_len > 0 {
201            self.target.send(buffer).await
202        } else {
203            Ok(())
204        }
205    }
206
207    /// Pushes an item into the buffered dispatcher.
208    ///
209    /// # Errors
210    ///
211    /// If there is an error flushing items to the output, or if there is an error acquiring a new buffer, an error
212    /// is returned.
213    pub async fn push(&mut self, item: T::Item) -> Result<(), GenericError> {
214        // If our current buffer is full, flush it before acquiring a new one.
215        if let Some(old_buffer) = self.buffer.take_if(|b| b.is_full()) {
216            self.try_flush_buffer(old_buffer).await?;
217        }
218
219        // Add the item to our current buffer.
220        //
221        // If our current buffer is empty, create a new one first. If the current buffer is full, return an error
222        // because it should be impossible to get a new buffer that is full.
223        let buffer = self.buffer.get_or_insert_default();
224        if buffer.try_push(item).is_some() {
225            return Err(generic_error!("Dispatch buffer already full after acquisition."));
226        }
227
228        self.flushed_len += 1;
229
230        Ok(())
231    }
232
233    /// Consumes this buffered dispatcher and sends/flushes all input items to the underlying output.
234    ///
235    /// If flushing is successful, `Ok(flushed)` is returned, where `flushed` is the total number of items that
236    /// have been flushed through this buffered dispatcher.
237    ///
238    /// # Errors
239    ///
240    /// If there is an error sending items to the output, an error is returned.
241    pub async fn send_all<I>(mut self, items: I) -> Result<usize, GenericError>
242    where
243        I: IntoIterator<Item = T::Item>,
244    {
245        for item in items {
246            self.push(item).await?;
247        }
248
249        self.flush().await
250    }
251
252    /// Consumes this buffered dispatcher, flushing any buffered items to the underlying output.
253    ///
254    /// If flushing is successful, `Ok(flushed)` is returned, where `flushed` is the total number of items that have
255    /// been flushed through this buffered dispatcher.
256    ///
257    /// # Errors
258    ///
259    /// If there is an error sending items to the output, an error is returned.
260    pub async fn flush(mut self) -> Result<usize, GenericError> {
261        if let Some(old_buffer) = self.buffer.take() {
262            self.try_flush_buffer(old_buffer).await?;
263        }
264
265        // We increment the "events sent" metric here because we want to count the number of buffered items, vs doing it in
266        // `DispatchTarget::send` where all it knows is that it sent one item.
267        self.metrics.events_sent_total().increment(self.flushed_len as u64);
268
269        Ok(self.flushed_len)
270    }
271}
272
273/// Dispatches items from one component to another.
274///
275/// [`Dispatcher`] provides an ergonomic interface for sending items to a downstream component. It has support for
276/// multiple outputs (a default output, and additional "named" outputs) and provides telemetry around the number of
277/// dispatched items as well as the latency of sending them.
278pub struct Dispatcher<T>
279where
280    T: Dispatchable,
281{
282    context: ComponentContext,
283    default: Option<DispatchTarget<T>>,
284    targets: FastHashMap<Cow<'static, str>, DispatchTarget<T>>,
285}
286
287impl<T> Dispatcher<T>
288where
289    T: Dispatchable,
290{
291    /// Create a new `Dispatcher` for the given component context.
292    pub fn new(context: ComponentContext) -> Self {
293        Self {
294            context,
295            default: None,
296            targets: FastHashMap::default(),
297        }
298    }
299
300    /// Adds an output to the dispatcher.
301    ///
302    /// # Errors
303    ///
304    /// If the output already exists, an error is returned.
305    pub fn add_output(&mut self, output_name: OutputName) -> Result<(), GenericError> {
306        match output_name {
307            OutputName::Default => {
308                if self.default.is_some() {
309                    return Err(generic_error!("Default output already exists."));
310                }
311
312                self.default = Some(DispatchTarget::default_output(self.context.clone()));
313            }
314            OutputName::Given(name) => {
315                if self.targets.contains_key(&name) {
316                    return Err(generic_error!("Output '{}' already exists.", name));
317                }
318                let target = DispatchTarget::named_output(self.context.clone(), &name);
319                self.targets.insert(name, target);
320            }
321        }
322
323        Ok(())
324    }
325
326    /// Attaches a sender to the given output.
327    ///
328    /// # Errors
329    ///
330    /// If the output doesn't exist, an error is returned.
331    pub fn attach_sender_to_output(
332        &mut self, output_name: &OutputName, sender: mpsc::Sender<T>,
333    ) -> Result<(), GenericError> {
334        self.attach_gated_sender_to_output(output_name, sender, None)
335    }
336
337    /// Attaches a sender to the given output, only sending to it while `gate` is active.
338    ///
339    /// # Errors
340    ///
341    /// If the output doesn't exist, an error is returned.
342    pub(crate) fn attach_gated_sender_to_output(
343        &mut self, output_name: &OutputName, sender: mpsc::Sender<T>, gate: Option<EdgeGate>,
344    ) -> Result<(), GenericError> {
345        let target = match output_name {
346            OutputName::Default => self
347                .default
348                .as_mut()
349                .ok_or_else(|| generic_error!("No default output declared."))?,
350            OutputName::Given(name) => self
351                .targets
352                .get_mut(name)
353                .ok_or_else(|| generic_error!("Output '{}' does not exist.", name))?,
354        };
355        target.add_sender(sender, gate);
356
357        Ok(())
358    }
359
360    fn get_default_output(&self) -> Result<&DispatchTarget<T>, GenericError> {
361        self.default
362            .as_ref()
363            .ok_or_else(|| generic_error!("No default output declared."))
364    }
365
366    fn get_named_output(&self, name: &str) -> Result<&DispatchTarget<T>, GenericError> {
367        self.targets
368            .get(name)
369            .ok_or_else(|| generic_error!("No output named '{}' declared.", name))
370    }
371
372    /// Returns `true` if the default output is connected to downstream components.
373    pub fn is_default_output_connected(&self) -> bool {
374        self.default.as_ref().is_some_and(|target| !target.senders.is_empty())
375    }
376
377    /// Returns `true` if the named output is connected to downstream components.
378    pub fn is_named_output_connected(&self, name: &str) -> bool {
379        self.targets.get(name).is_some_and(|target| !target.senders.is_empty())
380    }
381
382    /// Dispatches the given item to the default output.
383    ///
384    /// # Errors
385    ///
386    /// If the default output isn't set, or there is an error sending to the default output, an error is returned.
387    pub async fn dispatch(&self, item: T) -> Result<(), GenericError> {
388        self.dispatch_inner(None, item).await
389    }
390
391    /// Dispatches the given items to the given named output.
392    ///
393    /// # Errors
394    ///
395    /// If a output of the given name isn't set, or there is an error sending to the output, an error is returned.
396    pub async fn dispatch_named<N>(&self, output_name: N, item: T) -> Result<(), GenericError>
397    where
398        N: AsRef<str>,
399    {
400        self.dispatch_inner(Some(output_name.as_ref()), item).await
401    }
402
403    async fn dispatch_inner(&self, output_name: Option<&str>, item: T) -> Result<(), GenericError> {
404        let target = match output_name {
405            None => self.get_default_output()?,
406            Some(name) => self.get_named_output(name)?,
407        };
408
409        target.send(item).await?;
410
411        Ok(())
412    }
413}
414
415impl<T> Dispatcher<T>
416where
417    T: DispatchBuffer,
418{
419    /// Creates a buffered dispatcher for the default output.
420    ///
421    /// This should generally be used if the items being dispatched aren't already collected in a container, or exposed
422    /// via an iterable type. It allows for efficiently buffering items one-by-one before dispatching them to the
423    /// underlying output.
424    ///
425    /// # Errors
426    ///
427    /// If the default output hasn't been configured, an error will be returned.
428    pub fn buffered(&self) -> Result<BufferedDispatcher<'_, T>, GenericError> {
429        self.get_default_output().map(BufferedDispatcher::new)
430    }
431
432    /// Creates a buffered dispatcher for the given named output.
433    ///
434    /// This should generally be used if the items being dispatched aren't already collected in a container, or exposed
435    /// via an iterable type. It allows for efficiently buffering items one-by-one before dispatching them to the
436    /// underlying output.
437    ///
438    /// # Errors
439    ///
440    /// If the given named output hasn't been configured, an error will be returned.
441    pub fn buffered_named<N>(&self, output_name: N) -> Result<BufferedDispatcher<'_, T>, GenericError>
442    where
443        N: AsRef<str>,
444    {
445        self.get_named_output(output_name.as_ref()).map(BufferedDispatcher::new)
446    }
447
448    /// Dispatches a single item to the default output.
449    ///
450    /// # Errors
451    ///
452    /// If the default output isn't set, or there is an error sending to the default output, an error is returned.
453    pub async fn dispatch_one(&self, item: T::Item) -> Result<(), GenericError> {
454        self.dispatch_one_inner(None, item).await
455    }
456
457    /// Dispatches a single item to the given named output.
458    ///
459    /// # Errors
460    ///
461    /// If an output of the given name isn't set, or there is an error sending to the output, an error is returned.
462    pub async fn dispatch_one_named<N>(&self, output_name: N, item: T::Item) -> Result<(), GenericError>
463    where
464        N: AsRef<str>,
465    {
466        self.dispatch_one_inner(Some(output_name.as_ref()), item).await
467    }
468
469    async fn dispatch_one_inner(&self, output_name: Option<&str>, item: T::Item) -> Result<(), GenericError> {
470        let target = match output_name {
471            None => self.get_default_output()?,
472            Some(name) => self.get_named_output(name)?,
473        };
474
475        let mut buffer = T::default();
476        if buffer.try_push(item).is_some() {
477            return Err(generic_error!("Default-constructed buffer rejected a single item."));
478        }
479        target.send(buffer).await
480    }
481}
482
483#[cfg(test)]
484mod tests {
485    // TODO: Tests asserting we emit metrics, and the right metrics.
486
487    use std::ops::Deref;
488
489    use metrics::{Key, Label};
490    use metrics_util::{
491        debugging::{DebugValue, DebuggingRecorder, Snapshotter},
492        CompositeKey, MetricKind,
493    };
494    use ordered_float::OrderedFloat;
495
496    use super::*;
497
498    #[derive(Clone, Copy, Debug, Eq, PartialEq)]
499    struct SingleEvent<T>(T);
500
501    impl<T: Clone + Copy> Dispatchable for SingleEvent<T> {
502        fn item_count(&self) -> usize {
503            1
504        }
505    }
506
507    impl<T: Clone + Copy> From<T> for SingleEvent<T> {
508        fn from(value: T) -> Self {
509            Self(value)
510        }
511    }
512
513    #[derive(Clone, Debug, Eq, PartialEq)]
514    struct FixedUsizeVec<const N: usize> {
515        data: [usize; N],
516        len: usize,
517    }
518
519    impl<const N: usize> Default for FixedUsizeVec<N> {
520        fn default() -> Self {
521            Self { data: [0; N], len: 0 }
522        }
523    }
524
525    impl<const N: usize> Deref for FixedUsizeVec<N> {
526        type Target = [usize];
527
528        fn deref(&self) -> &Self::Target {
529            &self.data
530        }
531    }
532
533    impl<const N: usize> Dispatchable for FixedUsizeVec<N> {
534        fn item_count(&self) -> usize {
535            self.len
536        }
537    }
538
539    impl<const N: usize> DispatchBuffer for FixedUsizeVec<N> {
540        type Item = usize;
541
542        fn len(&self) -> usize {
543            self.len
544        }
545
546        fn is_full(&self) -> bool {
547            self.len == N
548        }
549
550        fn try_push(&mut self, item: Self::Item) -> Option<Self::Item> {
551            if self.is_full() {
552                Some(item)
553            } else {
554                self.data[self.len] = item;
555                self.len += 1;
556                None
557            }
558        }
559    }
560
561    fn unbuffered_dispatcher<T: Dispatchable>() -> Dispatcher<T> {
562        let component_context = ComponentContext::test_source("dispatcher_test");
563        Dispatcher::new(component_context)
564    }
565
566    fn buffered_dispatcher<T: DispatchBuffer>() -> Dispatcher<T> {
567        unbuffered_dispatcher()
568    }
569
570    /// One output-kind case: the output to operate on, plus the `output` metric label it maps to.
571    ///
572    /// Every dispatcher operation must behave identically for the default output and for a named output, so the tests
573    /// below iterate over these two cases rather than duplicating a default-vs-named function pair for each scenario.
574    struct OutputCase {
575        output: OutputName,
576        metric_label: &'static str,
577    }
578
579    fn output_cases() -> [OutputCase; 2] {
580        [
581            OutputCase {
582                output: OutputName::Default,
583                metric_label: "_default",
584            },
585            OutputCase {
586                output: OutputName::Given("special".into()),
587                metric_label: "special",
588            },
589        ]
590    }
591
592    /// Declares `output` on the dispatcher and attaches the given senders to it.
593    fn add_output_with_senders<T: Dispatchable, const N: usize>(
594        dispatcher: &mut Dispatcher<T>, output: &OutputName, senders: [mpsc::Sender<T>; N],
595    ) {
596        dispatcher
597            .add_output(output.clone())
598            .expect("output should not be declared yet");
599        for sender in senders {
600            dispatcher
601                .attach_sender_to_output(output, sender)
602                .expect("output should exist after being declared");
603        }
604    }
605
606    /// Dispatches `item` to `output`, choosing the default or named entry point as appropriate.
607    async fn dispatch_to<T: Dispatchable>(
608        dispatcher: &Dispatcher<T>, output: &OutputName, item: T,
609    ) -> Result<(), GenericError> {
610        match output {
611            OutputName::Default => dispatcher.dispatch(item).await,
612            OutputName::Given(name) => dispatcher.dispatch_named(name.as_ref(), item).await,
613        }
614    }
615
616    /// Creates a buffered dispatcher for `output`, choosing the default or named entry point as appropriate.
617    fn buffered_for<'a, T: DispatchBuffer>(
618        dispatcher: &'a Dispatcher<T>, output: &OutputName,
619    ) -> Result<BufferedDispatcher<'a, T>, GenericError> {
620        match output {
621            OutputName::Default => dispatcher.buffered(),
622            OutputName::Given(name) => dispatcher.buffered_named(name.as_ref()),
623        }
624    }
625
626    /// Dispatches a single item to `output`, choosing the default or named entry point as appropriate.
627    async fn dispatch_one_to<T: DispatchBuffer>(
628        dispatcher: &Dispatcher<T>, output: &OutputName, item: T::Item,
629    ) -> Result<(), GenericError> {
630        match output {
631            OutputName::Default => dispatcher.dispatch_one(item).await,
632            OutputName::Given(name) => dispatcher.dispatch_one_named(name.as_ref(), item).await,
633        }
634    }
635
636    /// Returns whether `output` is connected, choosing the default or named query as appropriate.
637    fn is_output_connected<T: Dispatchable>(dispatcher: &Dispatcher<T>, output: &OutputName) -> bool {
638        match output {
639            OutputName::Default => dispatcher.is_default_output_connected(),
640            OutputName::Given(name) => dispatcher.is_named_output_connected(name.as_ref()),
641        }
642    }
643
644    fn get_dispatcher_metric_ckey(
645        kind: MetricKind, name: &'static str, output_name: &'static str, tags: &[(&'static str, &'static str)],
646    ) -> CompositeKey {
647        let mut labels = vec![
648            Label::from_static_parts("component_id", "dispatcher_test"),
649            Label::from_static_parts("component_type", "source"),
650            Label::from_static_parts("output", output_name),
651        ];
652
653        for tag in tags {
654            labels.push(Label::from_static_parts(tag.0, tag.1));
655        }
656
657        let key = Key::from_parts(name, labels);
658        CompositeKey::new(kind, key)
659    }
660
661    fn get_output_metrics(snapshotter: &Snapshotter, output_name: &'static str) -> (u64, u64, Vec<OrderedFloat<f64>>) {
662        let events_sent_key = get_dispatcher_metric_ckey(
663            MetricKind::Counter,
664            DispatcherMetrics::events_sent_total_name(),
665            output_name,
666            &[],
667        );
668        let events_discarded_key = get_dispatcher_metric_ckey(
669            MetricKind::Counter,
670            DispatcherMetrics::events_discarded_total_name(),
671            output_name,
672            &[],
673        );
674        let send_latency_key = get_dispatcher_metric_ckey(
675            MetricKind::Histogram,
676            DispatcherMetrics::send_latency_seconds_name(),
677            output_name,
678            &[],
679        );
680
681        // TODO: This API for querying the metrics really sucks... and we need something better.
682        let current_metrics = snapshotter.snapshot().into_hashmap();
683        let (_, _, events_sent) = current_metrics
684            .get(&events_sent_key)
685            .expect("should have events sent metric");
686        let (_, _, events_discarded) = current_metrics
687            .get(&events_discarded_key)
688            .expect("should have events discarded metric");
689        let (_, _, send_latency) = current_metrics
690            .get(&send_latency_key)
691            .expect("should have send latency metric");
692
693        let events_sent = match events_sent {
694            DebugValue::Counter(value) => *value,
695            _ => panic!("unexpected metric type for events sent"),
696        };
697
698        let events_discarded = match events_discarded {
699            DebugValue::Counter(value) => *value,
700            _ => panic!("unexpected metric type for events discarded"),
701        };
702
703        let send_latency = match send_latency {
704            DebugValue::Histogram(value) => value.clone(),
705            _ => panic!("unexpected metric type for send latency"),
706        };
707
708        (events_sent, events_discarded, send_latency)
709    }
710
711    #[tokio::test]
712    async fn dispatch_delivers_item_to_each_output_kind() {
713        // Dispatching a single item to a wired output delivers it unchanged, for both the default and a named output.
714        for case in output_cases() {
715            let mut dispatcher = unbuffered_dispatcher::<SingleEvent<usize>>();
716            let (tx, mut rx) = mpsc::channel(1);
717            add_output_with_senders(&mut dispatcher, &case.output, [tx]);
718
719            let input_item = 42.into();
720            dispatch_to(&dispatcher, &case.output, input_item).await.unwrap();
721
722            let output_item = rx.try_recv().expect("input item should have been dispatched");
723            assert_eq!(output_item, input_item);
724        }
725    }
726
727    #[tokio::test]
728    async fn dispatch_fans_out_to_all_senders_for_each_output_kind() {
729        // With multiple senders attached to an output, a dispatched item is delivered (cloned) to every sender.
730        for case in output_cases() {
731            let mut dispatcher = unbuffered_dispatcher::<SingleEvent<usize>>();
732            let (tx1, mut rx1) = mpsc::channel(1);
733            let (tx2, mut rx2) = mpsc::channel(1);
734            add_output_with_senders(&mut dispatcher, &case.output, [tx1, tx2]);
735
736            let input_item = 42.into();
737            dispatch_to(&dispatcher, &case.output, input_item).await.unwrap();
738
739            assert_eq!(rx1.try_recv().expect("first sender should receive"), input_item);
740            assert_eq!(rx2.try_recv().expect("second sender should receive"), input_item);
741        }
742    }
743
744    #[tokio::test]
745    async fn dispatch_to_unconfigured_output_errors() {
746        // Dispatching to an output that was never declared fails with the documented error for that output kind.
747        for case in output_cases() {
748            let dispatcher = unbuffered_dispatcher::<SingleEvent<()>>();
749            let err = dispatch_to(&dispatcher, &case.output, ().into())
750                .await
751                .expect_err("dispatch to an unconfigured output must fail");
752            let msg = err.to_string();
753            match &case.output {
754                OutputName::Default => assert_eq!(msg, "No default output declared."),
755                OutputName::Given(_) => assert!(msg.contains("No output named"), "got: {msg}"),
756            }
757        }
758    }
759
760    #[tokio::test]
761    async fn buffered_dispatch_flushes_partial_buffer() {
762        // A single buffered push, once flushed, arrives as a one-element buffer on the wired output.
763        for case in output_cases() {
764            let mut dispatcher = buffered_dispatcher::<FixedUsizeVec<4>>();
765            let (tx, mut rx) = mpsc::channel(1);
766            add_output_with_senders(&mut dispatcher, &case.output, [tx]);
767
768            let input_item = 42;
769            let mut buffered = buffered_for(&dispatcher, &case.output).unwrap();
770            buffered.push(input_item).await.unwrap();
771            let flushed_len = buffered.flush().await.unwrap();
772            assert_eq!(flushed_len, 1);
773
774            let output_item = rx.try_recv().expect("input item should have been dispatched");
775            assert_eq!(output_item.len(), 1);
776            assert_eq!(output_item[0], input_item);
777        }
778    }
779
780    #[tokio::test]
781    async fn buffered_dispatch_flushes_full_buffer_during_push() {
782        // Pushing more items than a single buffer can hold flushes the full buffer mid-push, so the items arrive as
783        // successive buffers (four, then the remaining two).
784        for case in output_cases() {
785            let mut dispatcher = buffered_dispatcher::<FixedUsizeVec<4>>();
786            let (tx, mut rx) = mpsc::channel(2);
787            add_output_with_senders(&mut dispatcher, &case.output, [tx]);
788
789            let input_items: Vec<usize> = vec![1, 2, 3, 4, 5, 6];
790            let mut buffered = buffered_for(&dispatcher, &case.output).unwrap();
791            for item in &input_items {
792                buffered.push(*item).await.unwrap();
793            }
794            let flushed_len = buffered.flush().await.unwrap();
795            assert_eq!(flushed_len, input_items.len());
796
797            let first = rx.try_recv().expect("first buffer should have been dispatched");
798            assert_eq!(first.len(), 4);
799            assert_eq!(first[0..4], input_items[0..4]);
800
801            let second = rx.try_recv().expect("second buffer should have been dispatched");
802            assert_eq!(second.len(), 2);
803            assert_eq!(second[0..2], input_items[4..6]);
804        }
805    }
806
807    #[tokio::test]
808    async fn buffered_dispatch_fans_out_partial_buffer() {
809        // A buffered push flushed to an output with multiple senders is delivered to every sender.
810        for case in output_cases() {
811            let mut dispatcher = buffered_dispatcher::<FixedUsizeVec<4>>();
812            let (tx1, mut rx1) = mpsc::channel(1);
813            let (tx2, mut rx2) = mpsc::channel(1);
814            add_output_with_senders(&mut dispatcher, &case.output, [tx1, tx2]);
815
816            let input_item = 42;
817            let mut buffered = buffered_for(&dispatcher, &case.output).unwrap();
818            buffered.push(input_item).await.unwrap();
819            let flushed_len = buffered.flush().await.unwrap();
820            assert_eq!(flushed_len, 1);
821
822            let out1 = rx1.try_recv().expect("first sender should receive");
823            assert_eq!(out1.len(), 1);
824            assert_eq!(out1[0], input_item);
825
826            let out2 = rx2.try_recv().expect("second sender should receive");
827            assert_eq!(out2.len(), 1);
828            assert_eq!(out2[0], input_item);
829        }
830    }
831
832    #[tokio::test]
833    async fn dispatch_to_output_without_senders_succeeds() {
834        // Dispatching to a declared output that has no senders attached succeeds (the item is discarded, not an error).
835        for case in output_cases() {
836            let mut dispatcher = unbuffered_dispatcher::<SingleEvent<u32>>();
837            dispatcher
838                .add_output(case.output.clone())
839                .expect("should be able to declare the output");
840
841            dispatch_to(&dispatcher, &case.output, 42.into())
842                .await
843                .expect("dispatch to a senderless output should succeed");
844        }
845    }
846
847    #[tokio::test]
848    async fn disconnected_output_records_discarded_events() {
849        // Dispatching to a declared-but-senderless output records the item count as discarded (and none as sent, with
850        // no send-latency samples), for both the default and a named output.
851        for case in output_cases() {
852            let recorder = DebuggingRecorder::new();
853            let snapshotter = recorder.snapshotter();
854            let output = case.output.clone();
855            let dispatcher = metrics::with_local_recorder(&recorder, || {
856                let mut dispatcher = buffered_dispatcher::<FixedUsizeVec<4>>();
857                dispatcher
858                    .add_output(output)
859                    .expect("should not fail to declare the output");
860                dispatcher
861            });
862
863            // Dispatch an item with a count of 1 to the senderless output; it is discarded rather than sent.
864            let mut single_item = FixedUsizeVec::<4>::default();
865            assert_eq!(None, single_item.try_push(42));
866            let single_item_count = single_item.item_count() as u64;
867            dispatch_to(&dispatcher, &case.output, single_item)
868                .await
869                .expect("should not fail to dispatch");
870
871            let (events_sent, events_discarded, send_latencies) = get_output_metrics(&snapshotter, case.metric_label);
872            assert_eq!(events_sent, 0);
873            assert_eq!(events_discarded, single_item_count);
874            assert!(send_latencies.is_empty());
875
876            // Dispatch a second item, this time with a count of 3.
877            let mut multiple_items = FixedUsizeVec::<4>::default();
878            assert_eq!(None, multiple_items.try_push(42));
879            assert_eq!(None, multiple_items.try_push(12345));
880            assert_eq!(None, multiple_items.try_push(1337));
881            let multiple_items_count = multiple_items.item_count() as u64;
882            dispatch_to(&dispatcher, &case.output, multiple_items)
883                .await
884                .expect("should not fail to dispatch");
885
886            let (events_sent, events_discarded, send_latencies) = get_output_metrics(&snapshotter, case.metric_label);
887            assert_eq!(events_sent, 0);
888            assert_eq!(events_discarded, multiple_items_count);
889            assert!(send_latencies.is_empty());
890        }
891    }
892
893    /// Returns the elided, sent, and discarded event counts recorded since the last snapshot.
894    ///
895    /// Taking a snapshot resets the counters, so each call returns the counts since the previous call.
896    fn take_send_counts(snapshotter: &Snapshotter, output_name: &'static str) -> (u64, u64, u64) {
897        let metrics = snapshotter.snapshot().into_hashmap();
898        let get = |name| {
899            let key = get_dispatcher_metric_ckey(MetricKind::Counter, name, output_name, &[]);
900            match metrics.get(&key) {
901                Some((_, _, DebugValue::Counter(value))) => *value,
902                Some(_) => panic!("unexpected metric type for {name}"),
903                None => 0,
904            }
905        };
906        (
907            get(DispatcherMetrics::events_elided_total_name()),
908            get(DispatcherMetrics::events_sent_total_name()),
909            get(DispatcherMetrics::events_discarded_total_name()),
910        )
911    }
912
913    #[tokio::test]
914    async fn gated_sender_only_receives_while_active() {
915        // A gated sender only receives items while its gate is active, and items skipped for it are counted as elided.
916        // Ungated senders on the same output receive every item regardless.
917        for case in output_cases() {
918            let recorder = DebuggingRecorder::new();
919            let snapshotter = recorder.snapshotter();
920            let gate = EdgeGate::new(false);
921            let (ungated_tx, mut ungated_rx) = mpsc::channel(4);
922            let (gated_tx, mut gated_rx) = mpsc::channel(4);
923            let output = case.output.clone();
924            let dispatcher = metrics::with_local_recorder(&recorder, || {
925                let mut dispatcher = buffered_dispatcher::<FixedUsizeVec<4>>();
926                dispatcher.add_output(output.clone()).unwrap();
927                dispatcher.attach_sender_to_output(&output, ungated_tx).unwrap();
928                dispatcher
929                    .attach_gated_sender_to_output(&output, gated_tx, Some(gate.clone()))
930                    .unwrap();
931                dispatcher
932            });
933
934            let mut item = FixedUsizeVec::<4>::default();
935            assert_eq!(None, item.try_push(1));
936            assert_eq!(None, item.try_push(2));
937            let item_count = item.item_count() as u64;
938
939            // Inactive gate: only the ungated sender receives the item.
940            dispatch_to(&dispatcher, &case.output, item.clone()).await.unwrap();
941            assert_eq!(ungated_rx.try_recv().unwrap(), item);
942            assert!(gated_rx.try_recv().is_err());
943            assert_eq!(
944                take_send_counts(&snapshotter, case.metric_label),
945                (item_count, item_count, 0)
946            );
947
948            // Active gate: both senders receive the item.
949            gate.set(true);
950            dispatch_to(&dispatcher, &case.output, item.clone()).await.unwrap();
951            assert_eq!(ungated_rx.try_recv().unwrap(), item);
952            assert_eq!(gated_rx.try_recv().unwrap(), item);
953            assert_eq!(
954                take_send_counts(&snapshotter, case.metric_label),
955                (0, 2 * item_count, 0)
956            );
957
958            // Inactive again: back to only the ungated sender.
959            gate.set(false);
960            dispatch_to(&dispatcher, &case.output, item.clone()).await.unwrap();
961            assert_eq!(ungated_rx.try_recv().unwrap(), item);
962            assert!(gated_rx.try_recv().is_err());
963            assert_eq!(
964                take_send_counts(&snapshotter, case.metric_label),
965                (item_count, item_count, 0)
966            );
967        }
968    }
969
970    #[tokio::test]
971    async fn output_with_only_inactive_senders_elides_items() {
972        // When every sender on an output is gated off, the item is elided rather than sent or discarded.
973        for case in output_cases() {
974            let recorder = DebuggingRecorder::new();
975            let snapshotter = recorder.snapshotter();
976            let (tx1, mut rx1) = mpsc::channel(1);
977            let (tx2, mut rx2) = mpsc::channel(1);
978            let output = case.output.clone();
979            let dispatcher = metrics::with_local_recorder(&recorder, || {
980                let mut dispatcher = buffered_dispatcher::<FixedUsizeVec<4>>();
981                dispatcher.add_output(output.clone()).unwrap();
982                for tx in [tx1, tx2] {
983                    dispatcher
984                        .attach_gated_sender_to_output(&output, tx, Some(EdgeGate::new(false)))
985                        .unwrap();
986                }
987                dispatcher
988            });
989
990            let mut item = FixedUsizeVec::<4>::default();
991            assert_eq!(None, item.try_push(7));
992            dispatch_to(&dispatcher, &case.output, item).await.unwrap();
993
994            assert!(rx1.try_recv().is_err());
995            assert!(rx2.try_recv().is_err());
996            assert!(is_output_connected(&dispatcher, &case.output));
997            assert_eq!(take_send_counts(&snapshotter, case.metric_label), (2, 0, 0));
998        }
999    }
1000
1001    #[tokio::test]
1002    async fn output_connected_reflects_sender_attachment() {
1003        // The connected-query reports false before an output exists, false once declared without senders, and true
1004        // only after a sender is attached -- for both the default and a named output.
1005        for case in output_cases() {
1006            let mut dispatcher = unbuffered_dispatcher::<SingleEvent<u32>>();
1007
1008            assert!(
1009                !is_output_connected(&dispatcher, &case.output),
1010                "an undeclared output must report as not connected"
1011            );
1012
1013            dispatcher
1014                .add_output(case.output.clone())
1015                .expect("should be able to declare the output");
1016            assert!(
1017                !is_output_connected(&dispatcher, &case.output),
1018                "a declared output with no senders must report as not connected"
1019            );
1020
1021            let (tx, _rx) = mpsc::channel(1);
1022            dispatcher
1023                .attach_sender_to_output(&case.output, tx)
1024                .expect("should be able to attach a sender");
1025            assert!(
1026                is_output_connected(&dispatcher, &case.output),
1027                "an output with a sender attached must report as connected"
1028            );
1029
1030            // A query for a different, undeclared named output is always false.
1031            assert!(
1032                !dispatcher.is_named_output_connected("nonexistent_output"),
1033                "an unknown named output must report as not connected"
1034            );
1035        }
1036    }
1037
1038    #[tokio::test]
1039    async fn dispatch_one_wraps_item_in_single_element_buffer() {
1040        // `dispatch_one`/`dispatch_one_named` wrap a single item into a one-element buffer on the wired output.
1041        for case in output_cases() {
1042            let mut dispatcher = buffered_dispatcher::<FixedUsizeVec<4>>();
1043            let (tx, mut rx) = mpsc::channel(1);
1044            add_output_with_senders(&mut dispatcher, &case.output, [tx]);
1045
1046            let input_item = 42;
1047            dispatch_one_to(&dispatcher, &case.output, input_item).await.unwrap();
1048
1049            let output_item = rx.try_recv().expect("input item should have been dispatched");
1050            assert_eq!(output_item.len(), 1);
1051            assert_eq!(output_item[0], input_item);
1052        }
1053    }
1054
1055    #[tokio::test]
1056    async fn dispatch_one_to_unconfigured_output_errors() {
1057        // `dispatch_one`/`dispatch_one_named` to an output that was never declared fails with the documented error for
1058        // that output kind.
1059        for case in output_cases() {
1060            let dispatcher = buffered_dispatcher::<FixedUsizeVec<4>>();
1061            let err = dispatch_one_to(&dispatcher, &case.output, 42)
1062                .await
1063                .expect_err("dispatch_one to an unconfigured output must fail");
1064            let msg = err.to_string();
1065            match &case.output {
1066                OutputName::Default => assert_eq!(msg, "No default output declared."),
1067                OutputName::Given(_) => assert!(msg.contains("No output named"), "got: {msg}"),
1068            }
1069        }
1070    }
1071
1072    #[tokio::test]
1073    async fn add_output_rejects_duplicate() {
1074        // `add_output`'s documented error: declaring the same output twice is rejected with an "already exists" error,
1075        // for both the default and a named output.
1076        for case in output_cases() {
1077            let mut dispatcher = unbuffered_dispatcher::<SingleEvent<u32>>();
1078            dispatcher
1079                .add_output(case.output.clone())
1080                .expect("first declaration should succeed");
1081
1082            let err = dispatcher
1083                .add_output(case.output.clone())
1084                .expect_err("declaring the same output twice must fail");
1085            assert!(err.to_string().contains("already exists"), "got: {err}");
1086        }
1087    }
1088
1089    #[tokio::test]
1090    async fn attach_sender_to_undeclared_output_errors() {
1091        // `attach_sender_to_output`'s documented error: attaching a sender to an output that hasn't been declared fails
1092        // with the documented error for that output kind.
1093        for case in output_cases() {
1094            let mut dispatcher = unbuffered_dispatcher::<SingleEvent<u32>>();
1095            let (tx, _rx) = mpsc::channel(1);
1096            let err = dispatcher
1097                .attach_sender_to_output(&case.output, tx)
1098                .expect_err("attaching to an undeclared output must fail");
1099            let msg = err.to_string();
1100            match &case.output {
1101                OutputName::Default => assert_eq!(msg, "No default output declared."),
1102                OutputName::Given(_) => assert!(msg.contains("does not exist"), "got: {msg}"),
1103            }
1104        }
1105    }
1106
1107    #[tokio::test]
1108    async fn dispatch_one_errors_when_buffer_cannot_hold_a_single_item() {
1109        // Defensive guard in `dispatch_one_inner`: if the default-constructed buffer can't accept even one item, it
1110        // returns a documented error rather than silently dropping the item. This branch is only reachable via a
1111        // degenerate zero-capacity buffer type; every real buffer (capacity >= 1) accepts the first item.
1112        let mut dispatcher = buffered_dispatcher::<FixedUsizeVec<0>>();
1113        let (tx, _rx) = mpsc::channel(1);
1114        add_output_with_senders(&mut dispatcher, &OutputName::Default, [tx]);
1115
1116        let err = dispatcher
1117            .dispatch_one(42)
1118            .await
1119            .expect_err("a zero-capacity buffer must be rejected, not silently drop the item");
1120        assert!(err.to_string().contains("rejected a single item"), "got: {err}");
1121    }
1122}