1use std::future::Future;
60use std::pin::Pin;
61use std::sync::Arc;
62use std::time::Duration;
63
64use a2a_protocol_types::error::A2aResult;
65
66use super::{CheckResult, Report};
67use crate::handler::HaltScope;
68use crate::store::{HaltSignal, HaltStore, StoredHalt};
69
70mod handlers;
71#[cfg(test)]
72mod tests;
73
74pub use handlers::check_handlers;
75
76const BOUND: Duration = Duration::from_secs(10);
78
79pub(super) struct Shared(pub(super) Arc<dyn HaltStore>);
81
82impl HaltStore for Shared {
83 fn load(&self) -> Pin<Box<dyn Future<Output = A2aResult<Vec<StoredHalt>>> + Send + '_>> {
84 self.0.load()
85 }
86 fn put<'a>(
87 &'a self,
88 halt: &'a StoredHalt,
89 ) -> Pin<Box<dyn Future<Output = A2aResult<()>> + Send + 'a>> {
90 self.0.put(halt)
91 }
92 fn remove<'a>(
93 &'a self,
94 scope: &'a HaltScope,
95 ) -> Pin<Box<dyn Future<Output = A2aResult<bool>> + Send + 'a>> {
96 self.0.remove(scope)
97 }
98 fn signals(&self) -> Option<tokio::sync::broadcast::Receiver<HaltSignal>> {
99 self.0.signals()
100 }
101 fn publish_cancel<'a>(
102 &'a self,
103 tenant: &'a str,
104 task: &'a str,
105 ) -> Pin<Box<dyn Future<Output = A2aResult<()>> + Send + 'a>> {
106 self.0.publish_cancel(tenant, task)
107 }
108}
109
110async fn loaded(store: &dyn HaltStore) -> Result<Vec<StoredHalt>, String> {
112 let mut halts = store
113 .load()
114 .await
115 .map_err(|e| format!("load failed: {e}"))?;
116 halts.sort_by_key(|h| format!("{:?}", h.scope));
117 Ok(halts)
118}
119
120fn sorted(mut halts: Vec<StoredHalt>) -> Vec<StoredHalt> {
121 halts.sort_by_key(|h| format!("{:?}", h.scope));
122 halts
123}
124
125pub async fn check_store<F, Fut>(open: &F) -> Report
129where
130 F: Fn() -> Fut + Sync,
131 Fut: Future<Output = Arc<dyn HaltStore>> + Send,
132{
133 let store = open().await;
134 let halts = Halts::new();
135 let mut results = vec![fresh(&*store).await];
136 let (written, expected) = writes(&*store, &halts).await;
137 results.extend(written);
138 let reopened = open().await;
139 results.push(reads_elsewhere(&*reopened, &expected).await);
140 results.extend(removals(&*store, &*reopened, &halts).await);
141 results.push(jobs(&*store, &*reopened).await);
142 results.extend(pushes(&*store, &*reopened).await);
143 Report {
144 subject: "halt store",
145 results,
146 }
147}
148
149struct Halts {
151 all: StoredHalt,
152 acme: StoredHalt,
153 named_all: StoredHalt,
156 replaced: StoredHalt,
157}
158
159impl Halts {
160 fn new() -> Self {
161 Self {
162 all: StoredHalt::new(HaltScope::All, "incident", "oncall"),
163 acme: StoredHalt::new(HaltScope::Tenant("acme".into()), "spend", "alice"),
164 named_all: StoredHalt::new(HaltScope::Tenant("all".into()), "odd name", "bob"),
165 replaced: StoredHalt::new(HaltScope::Tenant("acme".into()), "spend, again", "carol"),
166 }
167 }
168}
169
170async fn fresh(store: &dyn HaltStore) -> CheckResult {
171 const NAME: &str = "a_fresh_store_is_empty";
172 match loaded(store).await {
173 Ok(h) if h.is_empty() => CheckResult::pass(NAME, "no halts"),
174 Ok(h) => CheckResult::fail(
175 NAME,
176 format!("{} halt(s) already stored; grade an empty store", h.len()),
177 ),
178 Err(e) => CheckResult::fail(NAME, e),
179 }
180}
181
182async fn writes(store: &dyn HaltStore, h: &Halts) -> (Vec<CheckResult>, Vec<StoredHalt>) {
185 const REPLACES: &str = "a_put_replaces_the_halt_of_its_scope";
186 const COLLIDE: &str = "scopes_do_not_collide";
187 let mut wrote = Ok(());
188 for halt in [&h.all, &h.acme, &h.named_all, &h.replaced] {
189 if let Err(e) = store.put(halt).await {
190 wrote = Err(format!("put failed: {e}"));
191 }
192 }
193 let expected = sorted(vec![h.all.clone(), h.replaced.clone(), h.named_all.clone()]);
194 let after = match wrote {
195 Ok(()) => loaded(store).await,
196 Err(e) => Err(e),
197 };
198 let replaces = match &after {
199 Ok(got) if *got == expected => {
200 CheckResult::pass(REPLACES, "the second halt of a tenant replaced the first")
201 }
202 Ok(got) => CheckResult::fail(REPLACES, format!("expected {expected:?}, loaded {got:?}")),
203 Err(e) => CheckResult::fail(REPLACES, e.clone()),
204 };
205 let collide = match &after {
206 Ok(got)
207 if got.iter().any(|x| x.scope == HaltScope::All)
208 && got
209 .iter()
210 .any(|x| x.scope == HaltScope::Tenant("all".into())) =>
211 {
212 CheckResult::pass(
213 COLLIDE,
214 "the halt of everything and the halt of a tenant named `all` are two halts",
215 )
216 }
217 Ok(got) => CheckResult::fail(
218 COLLIDE,
219 format!("the halt of everything and of tenant `all` were merged: {got:?}"),
220 ),
221 Err(e) => CheckResult::fail(COLLIDE, e.clone()),
222 };
223 (vec![replaces, collide], expected)
224}
225
226async fn reads_elsewhere(reopened: &dyn HaltStore, expected: &[StoredHalt]) -> CheckResult {
227 const NAME: &str = "another_handle_reads_what_was_written";
228 match loaded(reopened).await {
229 Ok(h) if h == expected => {
230 CheckResult::pass(NAME, "a second handle on the store loaded the same halts")
231 }
232 Ok(h) => CheckResult::fail(
233 NAME,
234 format!("written {expected:?}, another handle loaded {h:?}"),
235 ),
236 Err(e) => CheckResult::fail(NAME, e),
237 }
238}
239
240async fn removals(store: &dyn HaltStore, reopened: &dyn HaltStore, h: &Halts) -> Vec<CheckResult> {
243 const EXACT: &str = "a_remove_removes_exactly_its_scope";
244 const SEEN: &str = "a_removal_is_seen_by_another_handle";
245 let tenant = HaltScope::Tenant("acme".into());
246 let removal = async {
247 let first = store.remove(&tenant).await.map_err(|e| e.to_string())?;
248 let second = store.remove(&tenant).await.map_err(|e| e.to_string())?;
249 let left = loaded(store).await?;
250 Ok::<_, String>((first, second, left))
251 }
252 .await;
253 let rest = sorted(vec![h.all.clone(), h.named_all.clone()]);
254 let exact = match removal {
255 Ok((true, false, left)) if left == rest => {
256 CheckResult::pass(EXACT, "true, then false, and the other halts stayed")
257 }
258 Ok((first, second, left)) => CheckResult::fail(
259 EXACT,
260 format!(
261 "remove answered {first} then {second} (want true then false); left {left:?}, want {rest:?}"
262 ),
263 ),
264 Err(e) => CheckResult::fail(EXACT, e),
265 };
266 let emptied = async {
267 for scope in [HaltScope::All, HaltScope::Tenant("all".into())] {
268 store.remove(&scope).await.map_err(|e| e.to_string())?;
269 }
270 loaded(reopened).await
271 }
272 .await;
273 let seen = match emptied {
274 Ok(left) if left.is_empty() => {
275 CheckResult::pass(SEEN, "the other handle loads no halts once all are removed")
276 }
277 Ok(left) => CheckResult::fail(
278 SEEN,
279 format!("all removed, another handle still loads {left:?}"),
280 ),
281 Err(e) => CheckResult::fail(SEEN, e),
282 };
283 vec![exact, seen]
284}
285
286async fn jobs(store: &dyn HaltStore, reopened: &dyn HaltStore) -> CheckResult {
289 const NAME: &str = "job_halts_are_kept_apart";
290 let a = StoredHalt::new(HaltScope::root("a:b", "c"), "job a", "dave");
291 let b = StoredHalt::new(HaltScope::root("a", "b:c"), "job b", "erin");
292 let run = async {
293 for halt in [&a, &b] {
294 store
295 .put(halt)
296 .await
297 .map_err(|e| format!("put failed: {e}"))?;
298 }
299 let both = loaded(reopened).await?;
300 let removed = store.remove(&a.scope).await.map_err(|e| e.to_string())?;
301 let left = loaded(reopened).await?;
302 store.remove(&b.scope).await.map_err(|e| e.to_string())?;
303 Ok::<_, String>((both, removed, left))
304 }
305 .await;
306 let want_both = sorted(vec![a, b.clone()]);
307 match run {
308 Ok((both, true, left)) if both == want_both && left == [b.clone()] => CheckResult::pass(
309 NAME,
310 "the jobs (\"a:b\", \"c\") and (\"a\", \"b:c\") are two halts, removed one at a time",
311 ),
312 Ok((both, removed, left)) => CheckResult::fail(
313 NAME,
314 format!(
315 "loaded {both:?} (want {want_both:?}); remove answered {removed}; then left {left:?} (want only {b:?})"
316 ),
317 ),
318 Err(e) => CheckResult::fail(NAME, e),
319 }
320}
321
322async fn pushes(writer: &dyn HaltStore, reader: &dyn HaltStore) -> Vec<CheckResult> {
324 let Some(mut rx) = reader.signals() else {
325 let why = "the store does not push: handlers sharing it learn of a halt by polling";
326 return vec![
327 CheckResult::skip("a_write_is_pushed_to_another_handle", why),
328 CheckResult::skip("a_cancel_is_pushed_to_another_handle", why),
329 ];
330 };
331 let _ = tokio::time::timeout(Duration::from_millis(500), async {
333 while rx.recv().await.is_ok() {}
334 })
335 .await;
336 while rx.try_recv().is_ok() {}
337
338 let scope = HaltScope::Tenant("conformance-push".into());
339 let mut out = Vec::new();
340 let write = async {
341 writer
342 .put(&StoredHalt::new(scope.clone(), "push", "conformance"))
343 .await
344 .map_err(|e| format!("put failed: {e}"))?;
345 next(&mut rx, |s| *s == HaltSignal::Changed)
346 .await
347 .ok_or("no signal within 10 s of a put")?;
348 writer
349 .remove(&scope)
350 .await
351 .map_err(|e| format!("remove failed: {e}"))?;
352 next(&mut rx, |s| *s == HaltSignal::Changed)
353 .await
354 .ok_or("no signal within 10 s of a remove")?;
355 Ok::<_, String>(())
356 }
357 .await;
358 out.push(match write {
359 Ok(()) => CheckResult::pass(
360 "a_write_is_pushed_to_another_handle",
361 "a put and a remove each signalled the other handle",
362 ),
363 Err(e) => CheckResult::fail("a_write_is_pushed_to_another_handle", e),
364 });
365
366 out.push(pushed_cancel(writer, &mut rx).await);
367 out
368}
369
370async fn pushed_cancel(
373 writer: &dyn HaltStore,
374 rx: &mut tokio::sync::broadcast::Receiver<HaltSignal>,
375) -> CheckResult {
376 let want = HaltSignal::Cancel {
377 tenant: "conformance".to_owned(),
378 task: "task-1".to_owned(),
379 };
380 let cancel = async {
381 writer
382 .publish_cancel("conformance", "task-1")
383 .await
384 .map_err(|e| format!("publish_cancel failed: {e}"))?;
385 next(rx, |s| *s == want)
386 .await
387 .ok_or_else(|| "the cancel did not reach the other handle within 10 s".to_owned())
388 }
389 .await;
390 match cancel {
391 Ok(_) => CheckResult::pass(
392 "a_cancel_is_pushed_to_another_handle",
393 "the other handle was told which task to stop",
394 ),
395 Err(e) => CheckResult::fail("a_cancel_is_pushed_to_another_handle", e),
396 }
397}
398
399async fn next(
401 rx: &mut tokio::sync::broadcast::Receiver<HaltSignal>,
402 want: impl Fn(&HaltSignal) -> bool + Send + Sync,
403) -> Option<HaltSignal> {
404 tokio::time::timeout(BOUND, async {
405 loop {
406 match rx.recv().await {
407 Ok(s) if want(&s) => return Some(s),
408 Ok(_) | Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => {}
409 Err(tokio::sync::broadcast::error::RecvError::Closed) => return None,
410 }
411 }
412 })
413 .await
414 .ok()
415 .flatten()
416}