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