/home/runner/work/lyquor/lyquor/platform/api/src/subsys.rs
Line | Count | Source |
1 | | //! Ownership-based lifecycle supervision for long-lived node subsystems. |
2 | | //! |
3 | | //! Reusable components expose a dormant configuration whose `spawn` method constructs a |
4 | | //! [`TaskGroup`](crate::subsys::TaskGroup) and returns a |
5 | | //! [`SpawnResult`](crate::subsys::SpawnResult) containing the capability handle. After spawning |
6 | | //! succeeds, the composition root moves the task group into |
7 | | //! [`Supervisor::register`](crate::subsys::Supervisor::register). |
8 | | //! [`Supervisor::stop_before`](crate::subsys::Supervisor::stop_before) records lifecycle ordering. |
9 | | //! Capability flow stays in normal Rust fields and is not coupled to the supervisor graph. |
10 | | //! |
11 | | //! Startup remains ordinary imperative code. Register each successfully spawned component |
12 | | //! immediately, and call [`Supervisor::shutdown`](crate::subsys::Supervisor::shutdown) on a later |
13 | | //! startup error to unwind everything already registered. Independent startup branches may still |
14 | | //! be joined explicitly at the composition root, without making subsystem types carry readiness |
15 | | //! promises. |
16 | | //! |
17 | | //! Every graph entry owns one [`TaskGroup`](crate::subsys::TaskGroup), and related workers share |
18 | | //! clones of it. A task group may create child groups for nested work: |
19 | | //! parent cancellation propagates to children, while a child may stop independently. At that |
20 | | //! graph node's turn, its token is cancelled and its whole task-group tree is drained. |
21 | | //! |
22 | | //! Shutdown walks the dependency graph in reverse: each node stops after all nodes depending on it |
23 | | //! have stopped, while independent branches stop concurrently. |
24 | | |
25 | | use std::{ |
26 | | future::Future, |
27 | | sync::Arc, |
28 | | time::{Duration, Instant}, |
29 | | }; |
30 | | |
31 | | use tokio::sync::SetOnce; |
32 | | use tokio_util::{ |
33 | | sync::{CancellationToken, DropGuard}, |
34 | | task::TaskTracker, |
35 | | }; |
36 | | |
37 | | use crate::log::LogClass; |
38 | | |
39 | | /// Interval at which the supervisor warns about a subsystem that is slow to stop. The supervisor |
40 | | /// keeps waiting: this is observability, not a deadline. |
41 | | const SLOW_WARN_INTERVAL: Duration = Duration::from_secs(10); |
42 | | |
43 | | /// Cancellation-and-drain scope for a related task group. |
44 | | /// |
45 | | /// Clone and share a task group among related workers. Use [`Self::child`] only when a nested group |
46 | | /// needs an independent shutdown boundary. Use [`Self::spawn_cancellable`] when a leaf worker needs |
47 | | /// the group's shutdown token, and [`Self::spawn_child`] when one worker needs narrower cancellation |
48 | | /// while remaining tracked by this group. Runtime state that owns a task group should derive group |
49 | | /// shutdown from it rather than carrying a parallel group-level cancellation token. |
50 | | /// |
51 | | /// Dropping the last clone cancels the scope without draining it. |
52 | | #[derive(Clone)] |
53 | | pub struct TaskGroup { |
54 | | shutdown: CancellationToken, |
55 | | tasks: TaskTracker, |
56 | | _drop_guard: Arc<DropGuard>, |
57 | | } |
58 | | |
59 | | lyquor_primitives::debug_struct_name!(TaskGroup); |
60 | | |
61 | | impl TaskGroup { |
62 | 594 | fn new(shutdown: CancellationToken) -> Self { |
63 | 594 | let tasks = TaskTracker::new(); |
64 | 594 | tasks.spawn(shutdown.clone().cancelled_owned()); |
65 | 594 | tasks.close(); |
66 | 594 | let drop_guard = Arc::new(shutdown.clone().drop_guard()); |
67 | 594 | Self { |
68 | 594 | shutdown, |
69 | 594 | tasks, |
70 | 594 | _drop_guard: drop_guard, |
71 | 594 | } |
72 | 594 | } |
73 | | |
74 | | /// Create a nested task-group scope. |
75 | | /// |
76 | | /// Parent cancellation reaches the child; child cancellation is local. Parent shutdown waits |
77 | | /// for the child to drain. |
78 | 260 | pub fn child(&self) -> Self { |
79 | 260 | let child = Self::new(self.shutdown.child_token()); |
80 | 260 | let child_tasks = child.tasks.clone(); |
81 | 260 | self.tasks.spawn(async move { |
82 | 260 | child_tasks.wait().await; |
83 | 119 | }); |
84 | 260 | child |
85 | 260 | } |
86 | | |
87 | | /// Token cancelled when this task group must stop. |
88 | | /// |
89 | | /// A child token changes signalling, not task ownership. |
90 | 659 | pub fn shutdown_token(&self) -> &CancellationToken { |
91 | 659 | &self.shutdown |
92 | 659 | } |
93 | | |
94 | | /// Track one task as part of this group. |
95 | | /// |
96 | | /// Shutdown waits for all tracked tasks to finish. Worker-owned cleanup should complete inside |
97 | | /// the tracked future before it returns. |
98 | | /// |
99 | | /// Like [`TaskTracker::spawn`], this does not reject inserts after the tracker has been closed. |
100 | | /// Runtime request paths that keep a cloned task group should check |
101 | | /// [`CancellationToken::is_cancelled`] before spawning new work. |
102 | | #[track_caller] |
103 | 51.0k | pub fn spawn<F>(&self, task: F) |
104 | 51.0k | where |
105 | 51.0k | F: Future + Send + 'static, |
106 | 51.0k | F::Output: Send + 'static, |
107 | | { |
108 | 51.0k | self.tasks.spawn(task); |
109 | 51.0k | } |
110 | | |
111 | | /// Spawn one task that is cancelled with this task group. |
112 | | /// |
113 | | /// The task receives a clone of this group's shutdown token. Cancelling that token cancels the |
114 | | /// entire task group; use [`Self::spawn_child`] when only the spawned task should be cancelled. |
115 | | /// The task remains tracked and drained by this group. |
116 | | #[track_caller] |
117 | 50.5k | pub fn spawn_cancellable<F, Fut>(&self, run: F) |
118 | 50.5k | where |
119 | 50.5k | F: FnOnce(CancellationToken) -> Fut, |
120 | 50.5k | Fut: Future + Send + 'static, |
121 | 50.5k | Fut::Output: Send + 'static, |
122 | | { |
123 | 50.5k | self.spawn(run(self.shutdown.clone())); |
124 | 50.5k | } |
125 | | |
126 | | /// Spawn one independently cancellable task owned by this task group. |
127 | | /// |
128 | | /// The task receives a child token, and the same token is returned to its controller. Cancelling |
129 | | /// the child token signals only this task; cancelling the task group also cancels the child token. |
130 | | /// The task remains tracked and drained by this group. |
131 | | #[must_use = "retain the token to cancel this task independently; use spawn_cancellable otherwise"] |
132 | | #[track_caller] |
133 | 97 | pub fn spawn_child<F, Fut>(&self, run: F) -> CancellationToken |
134 | 97 | where |
135 | 97 | F: FnOnce(CancellationToken) -> Fut, |
136 | 97 | Fut: Future + Send + 'static, |
137 | 97 | Fut::Output: Send + 'static, |
138 | | { |
139 | 97 | let shutdown = self.shutdown.child_token(); |
140 | 97 | self.spawn(run(shutdown.clone())); |
141 | 97 | shutdown |
142 | 97 | } |
143 | | |
144 | | /// Wait until this task group has been cancelled and all tracked work and children have |
145 | | /// drained. This does not request cancellation. |
146 | 300 | pub async fn finished(&self) { |
147 | 300 | self.tasks.wait().await; |
148 | 300 | } |
149 | | |
150 | | /// Cancel this task group and wait for all work spawned through it and its children to finish. |
151 | 297 | pub async fn shutdown(self) { |
152 | 297 | self.shutdown.cancel(); |
153 | 297 | self.finished().await; |
154 | 297 | } |
155 | | } |
156 | | |
157 | | impl Default for TaskGroup { |
158 | 334 | fn default() -> Self { |
159 | 334 | Self::new(Default::default()) |
160 | 334 | } |
161 | | } |
162 | | |
163 | | /// Standard result of spawning a reusable component. |
164 | | /// |
165 | | /// `T` is the component's runtime capability. Components without one use `()`. The default error |
166 | | /// type is [`anyhow::Error`], while components with a typed error can override `E`. A `spawn` |
167 | | /// implementation must unwind partial work before returning `Err` because task-group ownership has |
168 | | /// not yet transferred to [`Supervisor::register`]. |
169 | | pub type SpawnResult<T, E = anyhow::Error> = Result<(T, TaskGroup), E>; |
170 | | |
171 | | /// Identifier of a subsystem or direct task group in one [`Supervisor`]'s lifecycle graph. |
172 | | /// |
173 | | /// Ids are plain graph indices scoped to the supervisor that issued them. Mixing ids from separate |
174 | | /// supervisors is unsupported wiring. |
175 | | #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] |
176 | | pub struct SubsysId(usize); |
177 | | |
178 | | struct Entry { |
179 | | name: &'static str, |
180 | | /// Nodes this entry must stop before. |
181 | | deps: Vec<usize>, |
182 | | task_group: TaskGroup, |
183 | | } |
184 | | |
185 | | /// Owner of the node lifecycle graph. |
186 | | /// |
187 | | /// Registration retains ownership of each task group until ordered shutdown completes or the |
188 | | /// supervisor is dropped. [`Self::finished`] observes task-group completion without initiating it. |
189 | | #[derive(Default)] |
190 | | pub struct Supervisor { |
191 | | entries: Vec<Entry>, |
192 | | } |
193 | | |
194 | | lyquor_primitives::debug_struct_name!(Supervisor); |
195 | | |
196 | | impl Supervisor { |
197 | | /// Register one task group in the shutdown graph. |
198 | | /// |
199 | | /// The component creates the task group and spawns its workers through it. After spawning |
200 | | /// succeeds, move the returned task group here. It and all its clones must belong to only one |
201 | | /// graph entry. |
202 | 17 | pub fn register(&mut self, name: &'static str, task_group: TaskGroup) -> SubsysId { |
203 | 17 | let id = SubsysId(self.entries.len()); |
204 | 17 | self.entries.push(Entry { |
205 | 17 | name, |
206 | 17 | deps: Vec::new(), |
207 | 17 | task_group, |
208 | 17 | }); |
209 | 17 | id |
210 | 17 | } |
211 | | |
212 | | /// Start and register a composition-local task group. |
213 | | /// |
214 | | /// `run` is called immediately with the new task group. Its returned future is tracked, receives |
215 | | /// the shutdown signal through that group, and is drained during ordered shutdown. |
216 | | /// Reusable components should expose a dormant configuration whose `spawn` method returns a |
217 | | /// [`SpawnResult`], then use [`Self::register`]. This helper is for composition-local task |
218 | | /// groups without a separate capability type. |
219 | 2 | pub fn spawn<Fut>(&mut self, name: &'static str, run: impl FnOnce(TaskGroup) -> Fut) -> SubsysId |
220 | 2 | where |
221 | 2 | Fut: Future<Output = ()> + Send + 'static, |
222 | | { |
223 | 2 | let task_group = TaskGroup::default(); |
224 | 2 | task_group.spawn(run(task_group.clone())); |
225 | 2 | self.register(name, task_group) |
226 | 2 | } |
227 | | |
228 | | /// Require `first` to stop and drain before `later` begins stopping. |
229 | | /// |
230 | | /// Use the same primitive for capability dependencies and ordering-only flow constraints. The |
231 | | /// graph describes shutdown order only; business handles remain ordinary fields in the |
232 | | /// composition root and dormant component configurations. |
233 | | /// |
234 | | /// # Panics |
235 | | /// Panics if either id is out of range for this supervisor or the edge would create a cycle. |
236 | 6 | pub fn stop_before(&mut self, first: SubsysId, later: SubsysId) { |
237 | 6 | assert!( |
238 | 6 | first.0 < self.entries.len() && later.0 < self.entries.len(), |
239 | | "stop_before: SubsysId is out of range for this supervisor graph" |
240 | | ); |
241 | 5 | assert_ne!(first, later, "stop_before: a subsystem cannot stop before itself"); |
242 | 5 | assert!( |
243 | 5 | !stops_before(&self.entries, later.0, first.0), |
244 | | "stop_before({} before {}) contradicts the existing stop order", |
245 | 1 | self.entries[first.0].name, |
246 | 1 | self.entries[later.0].name, |
247 | | ); |
248 | 4 | if !self.entries[first.0].deps.contains(&later.0) { |
249 | 4 | self.entries[first.0].deps.push(later.0); |
250 | 4 | }0 |
251 | 4 | } |
252 | | |
253 | | /// Wait until every registered task group has been cancelled and drained. |
254 | | /// |
255 | | /// This only observes completion; it does not request cancellation or alter shutdown order. |
256 | 1 | pub async fn finished(&self) { |
257 | 2 | futures::future::join_all1 (self.entries.iter()1 .map1 (|entry| entry.task_group.finished())).await1 ; |
258 | 1 | } |
259 | | |
260 | | /// Stop all entries in reverse dependency layers. Independent branches stop concurrently. |
261 | | /// |
262 | | /// This consumes the supervisor and is intended to be awaited to completion. It is not a |
263 | | /// cancel-safe operation to race in `tokio::select!` and then drop; enforce any process-level |
264 | | /// shutdown deadline outside the lifecycle registry. |
265 | 6 | pub async fn shutdown(mut self) { |
266 | 6 | let started = Instant::now(); |
267 | | // Empty the supervisor so its Drop safety net does not run after orderly shutdown. |
268 | 6 | let entries = std::mem::take(&mut self.entries); |
269 | | |
270 | 6 | let mut dependents = vec![Vec::new(); entries.len()]; |
271 | 11 | for (index, entry) in entries.iter()6 .enumerate6 () { |
272 | 11 | for &dependency3 in &entry.deps { |
273 | 3 | dependents[dependency].push(index); |
274 | 3 | } |
275 | | } |
276 | | |
277 | 11 | let stopped6 = Arc::new6 (entries.iter()6 .map6 (|_| SetOnce::new()).collect6 ::<Vec<_>>()); |
278 | 11 | let waits6 = entries6 .into_iter6 ().enumerate6 ().map6 (|(index, entry)| { |
279 | 11 | let blockers = dependents[index].clone(); |
280 | 11 | let stopped = stopped.clone(); |
281 | 11 | async move { |
282 | 11 | for blocker3 in blockers { |
283 | 3 | stopped[blocker].wait().await; |
284 | | } |
285 | 11 | stop_entry(entry.name, entry.task_group).await; |
286 | 11 | let _ = stopped[index].set(()); |
287 | 11 | } |
288 | 11 | }); |
289 | 6 | futures::future::join_all(waits).await; |
290 | | |
291 | 6 | tracing::info!( |
292 | 0 | elapsed_ms = started.elapsed().as_millis() as u64, |
293 | | "all subsystems stopped" |
294 | | ); |
295 | 6 | } |
296 | | } |
297 | | |
298 | | /// Safety net for a supervisor dropped without ordered shutdown. Every entry is signalled but not |
299 | | /// drained; tracked subsystem tasks may continue in the background. |
300 | | impl Drop for Supervisor { |
301 | 11 | fn drop(&mut self) { |
302 | 11 | if self.entries.is_empty() { |
303 | 6 | return; |
304 | 5 | } |
305 | 5 | tracing::warn!( |
306 | | class = %LogClass::CoreRuntime, |
307 | | "supervisor dropped before shutdown completed" |
308 | | ); |
309 | 6 | for entry in &self.entries5 { |
310 | 6 | entry.task_group.shutdown.cancel(); |
311 | 6 | } |
312 | 11 | } |
313 | | } |
314 | | |
315 | 11 | async fn stop_entry(name: &'static str, task_group: TaskGroup) { |
316 | 11 | let started = Instant::now(); |
317 | 11 | tracing::debug!(subsystem = name, "stopping subsystem"); |
318 | 11 | warn_if_slow(name, task_group.shutdown()).await; |
319 | | |
320 | 11 | tracing::debug!( |
321 | | subsystem = name, |
322 | 0 | elapsed_ms = started.elapsed().as_millis() as u64, |
323 | | "subsystem stopped" |
324 | | ); |
325 | 11 | } |
326 | | |
327 | 11 | async fn warn_if_slow<T>(name: &'static str, operation: impl Future<Output = T>) -> T { |
328 | 11 | let started = Instant::now(); |
329 | 11 | tokio::pin!(operation); |
330 | | loop { |
331 | 11 | match tokio::time::timeout(SLOW_WARN_INTERVAL, &mut operation).await { |
332 | 11 | Ok(output) => break output, |
333 | 0 | Err(_) => tracing::warn!( |
334 | | subsystem = name, |
335 | 0 | elapsed_ms = started.elapsed().as_millis() as u64, |
336 | | class = %LogClass::CoreRuntime, |
337 | | "subsystem is taking a long time to stop" |
338 | | ), |
339 | | } |
340 | | } |
341 | 11 | } |
342 | | |
343 | 5 | fn stops_before(entries: &[Entry], from: usize, to: usize) -> bool { |
344 | 5 | let mut seen = vec![false; entries.len()]; |
345 | 5 | let mut stack = vec![from]; |
346 | 10 | while let Some(current6 ) = stack.pop() { |
347 | 6 | if current == to { |
348 | 1 | return true; |
349 | 5 | } |
350 | 5 | if std::mem::replace(&mut seen[current], true) { |
351 | 0 | continue; |
352 | 5 | } |
353 | 5 | stack.extend(entries[current].deps.iter().copied()); |
354 | | } |
355 | 4 | false |
356 | 5 | } |
357 | | |
358 | | #[cfg(test)] |
359 | | mod tests { |
360 | | use lyquor_test::test; |
361 | | use tokio::sync::{mpsc, oneshot}; |
362 | | |
363 | | use super::*; |
364 | | |
365 | | struct TestSubsystem { |
366 | | name: &'static str, |
367 | | task_group: TaskGroup, |
368 | | } |
369 | | |
370 | | impl TestSubsystem { |
371 | 10 | fn new( |
372 | 10 | name: &'static str, events: &mpsc::UnboundedSender<&'static str>, gate: Option<oneshot::Receiver<()>>, |
373 | 10 | ) -> (Self, TaskGroup) { |
374 | 10 | let task_group = TaskGroup::default(); |
375 | 10 | let registration_task_group = task_group.clone(); |
376 | 10 | let worker_task_group = task_group.clone(); |
377 | 10 | let events = events.clone(); |
378 | 10 | task_group.spawn(async move { |
379 | 10 | worker_task_group.shutdown_token().cancelled().await; |
380 | 10 | events.send(name).unwrap(); |
381 | 10 | if let Some(gate6 ) = gate { |
382 | 6 | let _ = gate.await; |
383 | 4 | } |
384 | 10 | }); |
385 | 10 | (Self { name, task_group }, registration_task_group) |
386 | 10 | } |
387 | | |
388 | 1 | fn handle(&self) -> &'static str { |
389 | 1 | self.name |
390 | 1 | } |
391 | | |
392 | 2 | fn is_shutdown(&self) -> bool { |
393 | 2 | self.task_group.shutdown_token().is_cancelled() |
394 | 2 | } |
395 | | } |
396 | | |
397 | 9 | fn start_test_subsystem( |
398 | 9 | sup: &mut Supervisor, name: &'static str, events: &mpsc::UnboundedSender<&'static str>, |
399 | 9 | gate: Option<oneshot::Receiver<()>>, |
400 | 9 | ) -> (TestSubsystem, SubsysId) { |
401 | 9 | let (subsystem, task_group) = TestSubsystem::new(name, events, gate); |
402 | 9 | let id = sup.register(name, task_group); |
403 | 9 | (subsystem, id) |
404 | 9 | } |
405 | | |
406 | | #[test(tokio::test)] |
407 | | async fn subsystem_handles_remain_ordinary_values() { |
408 | | let (events_tx, mut events_rx) = mpsc::unbounded_channel(); |
409 | | let mut sup = Supervisor::default(); |
410 | | let (subsystem, _) = start_test_subsystem(&mut sup, "subsystem", &events_tx, None); |
411 | | let handle = subsystem.handle(); |
412 | | |
413 | | assert_eq!(handle, "subsystem"); |
414 | | assert!(!subsystem.is_shutdown()); |
415 | | assert!(events_rx.try_recv().is_err()); |
416 | | sup.shutdown().await; |
417 | | assert!(subsystem.is_shutdown()); |
418 | | assert_eq!(events_rx.recv().await, Some("subsystem")); |
419 | | } |
420 | | |
421 | | #[test(tokio::test)] |
422 | | async fn stop_before_orders_entries() { |
423 | | let (events_tx, mut events_rx) = mpsc::unbounded_channel(); |
424 | | let (release_dependent, dependent_gate) = oneshot::channel(); |
425 | | let mut sup = Supervisor::default(); |
426 | | let (_dependency_subsystem, dependency) = start_test_subsystem(&mut sup, "dependency", &events_tx, None); |
427 | | let (_dependent_subsystem, dependent) = |
428 | | start_test_subsystem(&mut sup, "dependent", &events_tx, Some(dependent_gate)); |
429 | | sup.stop_before(dependent, dependency); |
430 | | |
431 | | let shutdown = tokio::spawn(sup.shutdown()); |
432 | | assert_eq!(events_rx.recv().await, Some("dependent")); |
433 | | assert!(events_rx.try_recv().is_err()); |
434 | | release_dependent.send(()).unwrap(); |
435 | | assert_eq!(events_rx.recv().await, Some("dependency")); |
436 | | shutdown.await.unwrap(); |
437 | | } |
438 | | |
439 | | #[test(tokio::test)] |
440 | | async fn independent_subsystems_stop_concurrently() { |
441 | | let (events_tx, mut events_rx) = mpsc::unbounded_channel(); |
442 | | let (release_x, gate_x) = oneshot::channel(); |
443 | | let (release_y, gate_y) = oneshot::channel(); |
444 | | let mut sup = Supervisor::default(); |
445 | | let (_x, _) = start_test_subsystem(&mut sup, "x", &events_tx, Some(gate_x)); |
446 | | let (_y, _) = start_test_subsystem(&mut sup, "y", &events_tx, Some(gate_y)); |
447 | | |
448 | | let shutdown = tokio::spawn(sup.shutdown()); |
449 | | let first = events_rx.recv().await.unwrap(); |
450 | | let second = events_rx.recv().await.unwrap(); |
451 | | assert_ne!(first, second); |
452 | | release_x.send(()).unwrap(); |
453 | | release_y.send(()).unwrap(); |
454 | | shutdown.await.unwrap(); |
455 | | } |
456 | | |
457 | | #[test(tokio::test)] |
458 | | async fn all_dependents_drain_before_dependency() { |
459 | | let (events_tx, mut events_rx) = mpsc::unbounded_channel(); |
460 | | let (release_y, gate_y) = oneshot::channel(); |
461 | | let (release_z, gate_z) = oneshot::channel(); |
462 | | let mut sup = Supervisor::default(); |
463 | | let (_x_subsystem, x) = start_test_subsystem(&mut sup, "x", &events_tx, None); |
464 | | let (_y_subsystem, y) = start_test_subsystem(&mut sup, "y", &events_tx, Some(gate_y)); |
465 | | let (_z_subsystem, z) = start_test_subsystem(&mut sup, "z", &events_tx, Some(gate_z)); |
466 | | sup.stop_before(y, x); |
467 | | sup.stop_before(z, x); |
468 | | |
469 | | let shutdown = tokio::spawn(sup.shutdown()); |
470 | | let first = events_rx.recv().await.unwrap(); |
471 | | let second = events_rx.recv().await.unwrap(); |
472 | | assert!(matches!((first, second), ("y", "z") | ("z", "y"))); |
473 | | assert!(events_rx.try_recv().is_err()); |
474 | | release_y.send(()).unwrap(); |
475 | | assert!(events_rx.try_recv().is_err()); |
476 | | release_z.send(()).unwrap(); |
477 | | assert_eq!(events_rx.recv().await, Some("x")); |
478 | | shutdown.await.unwrap(); |
479 | | } |
480 | | |
481 | | #[test(tokio::test)] |
482 | | async fn stop_edges_reject_cycles() { |
483 | | let mut sup = Supervisor::default(); |
484 | | let a = sup.register("a", TaskGroup::default()); |
485 | | let b = sup.register("b", TaskGroup::default()); |
486 | | sup.stop_before(b, a); |
487 | 1 | let cycle = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| sup.stop_before(a, b))); |
488 | | assert!(cycle.is_err()); |
489 | | } |
490 | | |
491 | | #[test(tokio::test)] |
492 | | async fn stop_edges_reject_out_of_range_ids() { |
493 | | let mut first = Supervisor::default(); |
494 | | let foreign = first.register("foreign", TaskGroup::default()); |
495 | | let mut second = Supervisor::default(); |
496 | | let local = second.register("local", TaskGroup::default()); |
497 | | let invalid = SubsysId(foreign.0 + 1); |
498 | 1 | let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| second.stop_before(local, invalid))); |
499 | | assert!(result.is_err()); |
500 | | } |
501 | | |
502 | | #[test(tokio::test)] |
503 | | async fn supervisor_spawn_tasks_are_cancelled_and_drained() { |
504 | | let (events_tx, mut events_rx) = mpsc::unbounded_channel(); |
505 | | let mut sup = Supervisor::default(); |
506 | 1 | sup.spawn("worker", |task_group| async move { |
507 | 1 | task_group.shutdown_token().cancelled().await; |
508 | 1 | events_tx.send("stopped").unwrap(); |
509 | 2 | }); |
510 | | |
511 | | sup.shutdown().await; |
512 | | assert_eq!(events_rx.recv().await, Some("stopped")); |
513 | | } |
514 | | |
515 | | #[test(tokio::test)] |
516 | | async fn direct_task_group_shutdown_awaits_cleanup() { |
517 | | let (events_tx, mut events_rx) = mpsc::unbounded_channel(); |
518 | | let (release_tx, gate) = oneshot::channel(); |
519 | | let (_subsystem, task_group) = TestSubsystem::new("subsystem", &events_tx, Some(gate)); |
520 | | |
521 | | let shutdown = tokio::spawn(task_group.shutdown()); |
522 | | assert_eq!(events_rx.recv().await, Some("subsystem")); |
523 | | assert!(!shutdown.is_finished()); |
524 | | release_tx.send(()).unwrap(); |
525 | | shutdown.await.unwrap(); |
526 | | } |
527 | | |
528 | | #[test(tokio::test)] |
529 | | async fn child_shutdown_does_not_cancel_parent() { |
530 | | let parent = TaskGroup::default(); |
531 | | let child = parent.child(); |
532 | | let worker_task_group = child.clone(); |
533 | | let (stopped_tx, stopped_rx) = oneshot::channel(); |
534 | 1 | child.spawn(async move { |
535 | 1 | worker_task_group.shutdown_token().cancelled().await; |
536 | 1 | stopped_tx.send(()).unwrap(); |
537 | 1 | }); |
538 | | |
539 | | child.shutdown().await; |
540 | | stopped_rx.await.unwrap(); |
541 | | assert!(!parent.shutdown_token().is_cancelled()); |
542 | | parent.shutdown().await; |
543 | | } |
544 | | |
545 | | #[test(tokio::test)] |
546 | | async fn spawned_child_is_independently_cancellable_and_group_tracked() { |
547 | | let task_group = TaskGroup::default(); |
548 | | let (child_stopped_tx, child_stopped_rx) = oneshot::channel(); |
549 | | let (release_child_tx, release_child_rx) = oneshot::channel(); |
550 | 1 | let child_shutdown = task_group.spawn_child(|shutdown| async move { |
551 | 1 | shutdown.cancelled().await; |
552 | 1 | child_stopped_tx.send(()).unwrap(); |
553 | 1 | let _ = release_child_rx.await; |
554 | 2 | }); |
555 | | |
556 | | child_shutdown.cancel(); |
557 | | child_stopped_rx.await.unwrap(); |
558 | | assert!(!task_group.shutdown_token().is_cancelled()); |
559 | | |
560 | | let (parent_stopped_tx, parent_stopped_rx) = oneshot::channel(); |
561 | 1 | let parent_child_shutdown = task_group.spawn_child(|shutdown| async move { |
562 | 1 | shutdown.cancelled().await; |
563 | 1 | parent_stopped_tx.send(()).unwrap(); |
564 | 2 | }); |
565 | | let shutdown = tokio::spawn(task_group.shutdown()); |
566 | | parent_stopped_rx.await.unwrap(); |
567 | | assert!(parent_child_shutdown.is_cancelled()); |
568 | | assert!(!shutdown.is_finished()); |
569 | | |
570 | | release_child_tx.send(()).unwrap(); |
571 | | shutdown.await.unwrap(); |
572 | | } |
573 | | |
574 | | #[test(tokio::test)] |
575 | | async fn spawned_cancellable_uses_task_group_token_and_is_tracked() { |
576 | | let task_group = TaskGroup::default(); |
577 | | let (cancelled_tx, cancelled_rx) = oneshot::channel(); |
578 | | let (release_tx, release_rx) = oneshot::channel(); |
579 | 1 | task_group.spawn_cancellable(|shutdown| async move { |
580 | 1 | shutdown.cancel(); |
581 | 1 | cancelled_tx.send(()).unwrap(); |
582 | 1 | let _ = release_rx.await; |
583 | 2 | }); |
584 | | |
585 | | cancelled_rx.await.unwrap(); |
586 | | assert!(task_group.shutdown_token().is_cancelled()); |
587 | | |
588 | | let shutdown = tokio::spawn(task_group.shutdown()); |
589 | | assert!(!shutdown.is_finished()); |
590 | | release_tx.send(()).unwrap(); |
591 | | shutdown.await.unwrap(); |
592 | | } |
593 | | |
594 | | #[test(tokio::test)] |
595 | | async fn dropping_last_clone_cancels_task_group() { |
596 | | let task_group = TaskGroup::default(); |
597 | | let clone = task_group.clone(); |
598 | | let shutdown = task_group.shutdown_token().clone(); |
599 | | |
600 | | drop(task_group); |
601 | | assert!(!shutdown.is_cancelled()); |
602 | | drop(clone); |
603 | | shutdown.cancelled().await; |
604 | | } |
605 | | |
606 | | #[test(tokio::test)] |
607 | | async fn dropping_child_cancels_only_child() { |
608 | | let parent = TaskGroup::default(); |
609 | | let child = parent.child(); |
610 | | let child_shutdown = child.shutdown_token().clone(); |
611 | | |
612 | | drop(child); |
613 | | child_shutdown.cancelled().await; |
614 | | assert!(!parent.shutdown_token().is_cancelled()); |
615 | | parent.shutdown().await; |
616 | | } |
617 | | |
618 | | #[test(tokio::test)] |
619 | | async fn parent_shutdown_cancels_and_drains_child() { |
620 | | let parent = TaskGroup::default(); |
621 | | let child = parent.child(); |
622 | | let worker_task_group = child.clone(); |
623 | | let (stopped_tx, stopped_rx) = oneshot::channel(); |
624 | | let (release_tx, release_rx) = oneshot::channel(); |
625 | 1 | child.spawn(async move { |
626 | 1 | worker_task_group.shutdown_token().cancelled().await; |
627 | 1 | stopped_tx.send(()).unwrap(); |
628 | 1 | let _ = release_rx.await; |
629 | 1 | }); |
630 | | |
631 | | let shutdown = tokio::spawn(parent.shutdown()); |
632 | | stopped_rx.await.unwrap(); |
633 | | assert!(!shutdown.is_finished()); |
634 | | release_tx.send(()).unwrap(); |
635 | | shutdown.await.unwrap(); |
636 | | } |
637 | | |
638 | | #[test(tokio::test)] |
639 | | async fn finished_waits_for_all_registered_task_groups_without_cancelling_them() { |
640 | | let mut sup = Supervisor::default(); |
641 | | let first = TaskGroup::default(); |
642 | | let first_shutdown = first.shutdown_token().clone(); |
643 | | let (release_first_tx, release_first_rx) = oneshot::channel(); |
644 | | let (first_drained_tx, first_drained_rx) = oneshot::channel(); |
645 | 1 | first.spawn(async move { |
646 | 1 | first_shutdown.cancelled().await; |
647 | 1 | let _ = release_first_rx.await; |
648 | 1 | first_drained_tx.send(()).unwrap(); |
649 | 1 | }); |
650 | | let first_shutdown = first.shutdown_token().clone(); |
651 | | sup.register("first", first); |
652 | | |
653 | | let second = TaskGroup::default(); |
654 | | let second_shutdown = second.shutdown_token().clone(); |
655 | | sup.register("second", second); |
656 | | |
657 | 1 | let finished = tokio::spawn(async move { |
658 | 1 | sup.finished().await; |
659 | 1 | sup |
660 | 1 | }); |
661 | | tokio::task::yield_now().await; |
662 | | assert!(!first_shutdown.is_cancelled()); |
663 | | assert!(!second_shutdown.is_cancelled()); |
664 | | assert!(!finished.is_finished()); |
665 | | |
666 | | first_shutdown.cancel(); |
667 | | release_first_tx.send(()).unwrap(); |
668 | | first_drained_rx.await.unwrap(); |
669 | | assert!(!finished.is_finished()); |
670 | | |
671 | | second_shutdown.cancel(); |
672 | | finished.await.unwrap().shutdown().await; |
673 | | } |
674 | | |
675 | | #[test(tokio::test)] |
676 | | async fn dropping_supervisor_signals_subsystem_tasks() { |
677 | | let (events_tx, mut events_rx) = mpsc::unbounded_channel(); |
678 | | let mut sup = Supervisor::default(); |
679 | | let (_subsystem, _) = start_test_subsystem(&mut sup, "subsystem", &events_tx, None); |
680 | | |
681 | | drop(sup); |
682 | | assert_eq!(events_rx.recv().await, Some("subsystem")); |
683 | | } |
684 | | |
685 | | #[test(tokio::test)] |
686 | | async fn dropping_supervisor_signals_spawned_tasks() { |
687 | | let (stopped_tx, stopped_rx) = oneshot::channel(); |
688 | | let mut sup = Supervisor::default(); |
689 | 1 | sup.spawn("worker", |task_group| async move { |
690 | 1 | task_group.shutdown_token().cancelled().await; |
691 | 1 | stopped_tx.send(()).unwrap(); |
692 | 2 | }); |
693 | | |
694 | | drop(sup); |
695 | | stopped_rx.await.unwrap(); |
696 | | } |
697 | | } |