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