saluki_core/topology/
condition.rs1use 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
30pub 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 pub fn fixed(active: bool) -> Self {
46 Self(ConditionKind::Fixed(active))
47 }
48
49 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 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#[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#[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 #[inline]
101 pub(crate) fn is_active(&self) -> bool {
102 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#[derive(Default)]
113pub(crate) struct EdgeConditions {
114 conditions: Vec<(EdgeKey, EdgeGate, BoxStream<'static, bool>)>,
115}
116
117impl EdgeConditions {
118 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 pub fn remove_component(&mut self, id: &ComponentId) {
125 self.conditions.retain(|(key, _, _)| !key.involves(id));
126 }
127
128 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 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 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}