Skip to main content

saluki_core/topology/
condition.rs

1//! Conditional connections between components.
2//!
3//! A connection between two components can be made conditional on an [`EdgeCondition`]. Conditions are resolved in two
4//! stages, much like constant folding in a compiler:
5//!
6//! - fixed conditions are resolved when the topology is built: a connection whose condition is always false is removed
7//!   entirely, and any component left without inputs as a result is never built or spawned
8//! - dynamic conditions are resolved at runtime: the connection exists, but items are only sent over it while its
9//!   condition is true
10//!
11//! Dynamic conditions only control whether items are sent to the downstream component. The downstream component keeps
12//! running while its input is inactive, and simply receives nothing. When a condition becomes true, items dispatched
13//! from that point on are sent to the downstream component: items dispatched while the condition was false are never
14//! replayed.
15
16use std::sync::{
17    atomic::{AtomicBool, Ordering},
18    Arc,
19};
20
21use futures::{
22    stream::{self, BoxStream},
23    Stream, StreamExt as _,
24};
25use tokio::sync::watch;
26use tracing::debug;
27
28use super::{ComponentId, OutputName};
29
30/// A condition controlling whether a connection between two components is active.
31pub struct EdgeCondition(pub(crate) ConditionKind);
32
33pub(crate) enum ConditionKind {
34    Fixed(bool),
35    Dynamic {
36        initial: bool,
37        updates: BoxStream<'static, bool>,
38    },
39}
40
41impl EdgeCondition {
42    /// Creates a condition that never changes.
43    ///
44    /// A connection with a condition of `false` is removed when the topology is built.
45    pub fn fixed(active: bool) -> Self {
46        Self(ConditionKind::Fixed(active))
47    }
48
49    /// Creates a condition that starts as `initial` and changes to each value yielded by `updates`.
50    ///
51    /// If `updates` ends, the condition keeps its last value.
52    pub fn dynamic<S>(initial: bool, updates: S) -> Self
53    where
54        S: Stream<Item = bool> + Send + 'static,
55    {
56        Self(ConditionKind::Dynamic {
57            initial,
58            updates: updates.boxed(),
59        })
60    }
61
62    /// Creates a condition that follows the value of a watch channel.
63    ///
64    /// If the sender is dropped, the condition keeps its last value.
65    pub fn from_watch(mut rx: watch::Receiver<bool>) -> Self {
66        let initial = *rx.borrow_and_update();
67        let updates = stream::unfold(rx, |mut rx| async move {
68            rx.changed().await.ok()?;
69            let value = *rx.borrow_and_update();
70            Some((value, rx))
71        });
72        Self::dynamic(initial, updates)
73    }
74}
75
76/// Identifies a connection from a component output to a downstream component.
77#[derive(Clone, Debug, Eq, PartialEq)]
78pub(crate) struct EdgeKey {
79    pub upstream: ComponentId,
80    pub output: OutputName,
81    pub downstream: ComponentId,
82}
83
84impl EdgeKey {
85    fn involves(&self, id: &ComponentId) -> bool {
86        &self.upstream == id || &self.downstream == id
87    }
88}
89
90/// The runtime state of a connection with a dynamic condition.
91#[derive(Clone, Debug)]
92pub(crate) struct EdgeGate(Arc<AtomicBool>);
93
94impl EdgeGate {
95    pub(crate) fn new(active: bool) -> Self {
96        Self(Arc::new(AtomicBool::new(active)))
97    }
98
99    /// Returns `true` if items should be sent over the connection.
100    #[inline]
101    pub(crate) fn is_active(&self) -> bool {
102        // Pairs with the release store in `set`, so that an item dispatched after a condition becomes true is sent.
103        self.0.load(Ordering::Acquire)
104    }
105
106    pub(crate) fn set(&self, active: bool) {
107        self.0.store(active, Ordering::Release);
108    }
109}
110
111/// The connections in a topology whose conditions are resolved at runtime.
112#[derive(Default)]
113pub(crate) struct EdgeConditions {
114    conditions: Vec<(EdgeKey, EdgeGate, BoxStream<'static, bool>)>,
115}
116
117impl EdgeConditions {
118    /// Adds a connection with a dynamic condition.
119    pub fn insert(&mut self, key: EdgeKey, initial: bool, updates: BoxStream<'static, bool>) {
120        self.conditions.push((key, EdgeGate::new(initial), updates));
121    }
122
123    /// Removes any conditions on connections to or from the given component.
124    pub fn remove_component(&mut self, id: &ComponentId) {
125        self.conditions.retain(|(key, _, _)| !key.involves(id));
126    }
127
128    /// Returns the gate for the given connection, if its condition is dynamic.
129    pub fn gate(&self, key: &EdgeKey) -> Option<EdgeGate> {
130        self.conditions
131            .iter()
132            .find(|(k, _, _)| k == key)
133            .map(|(_, gate, _)| gate.clone())
134    }
135
136    pub fn is_empty(&self) -> bool {
137        self.conditions.is_empty()
138    }
139
140    /// Applies condition updates to their gates until every condition's updates have ended.
141    pub async fn run(self) {
142        let mut updates = stream::select_all(
143            self.conditions
144                .into_iter()
145                .map(|(key, gate, updates)| updates.map(move |active| (key.clone(), gate.clone(), active))),
146        );
147
148        while let Some((key, gate, active)) = updates.next().await {
149            debug!(
150                upstream = %key.upstream,
151                output = %key.output,
152                downstream = %key.downstream,
153                active,
154                "Updated connection condition."
155            );
156            gate.set(active);
157        }
158    }
159}
160
161#[cfg(test)]
162mod tests {
163    use super::*;
164
165    fn key(downstream: &str) -> EdgeKey {
166        EdgeKey {
167            upstream: ComponentId::try_from("up").unwrap(),
168            output: OutputName::Default,
169            downstream: ComponentId::try_from(downstream).unwrap(),
170        }
171    }
172
173    #[tokio::test]
174    async fn watch_condition_follows_sender() {
175        let (tx, rx) = watch::channel(false);
176        let ConditionKind::Dynamic { initial, updates } = EdgeCondition::from_watch(rx).0 else {
177            panic!("expected dynamic condition");
178        };
179
180        let mut conditions = EdgeConditions::default();
181        conditions.insert(key("down"), initial, updates);
182        let gate = conditions.gate(&key("down")).unwrap();
183        assert!(!gate.is_active());
184        let driver = tokio::spawn(conditions.run());
185
186        tx.send(true).unwrap();
187        crate::test_support::wait_until("gate becomes active", || gate.is_active()).await;
188
189        tx.send(false).unwrap();
190        crate::test_support::wait_until("gate becomes inactive", || !gate.is_active()).await;
191
192        // Dropping the sender ends the updates, and the gate keeps its last value.
193        drop(tx);
194        driver.await.unwrap();
195        assert!(!gate.is_active());
196    }
197
198    #[test]
199    fn removing_component_drops_its_conditions() {
200        let mut conditions = EdgeConditions::default();
201        conditions.insert(key("down"), true, stream::empty().boxed());
202        assert!(conditions.gate(&key("down")).is_some());
203
204        conditions.remove_component(&ComponentId::try_from("down").unwrap());
205        assert!(conditions.gate(&key("down")).is_none());
206        assert!(conditions.is_empty());
207    }
208}