Skip to main content

saluki_core/runtime/scope/
mod.rs

1//! Structured concurrency scopes.
2//!
3//! A supervisor runs a set of children and restarts them when they fail. A _scope_ is the same mechanism, but a single
4//! process owns it instead of a supervisor. The children that a worker spawns into its scope belong to that worker.
5//! Each child runs as a separate task, but the worker does not finish until all of its children finish.
6//!
7//! When the body of the worker finishes, the scope closes and tells its children to stop. The body finishes when it
8//! returns, panics, or is cut short because a child that it needs failed. If the worker is halted, the scope halts its
9//! children instead. A request for the worker to stop does not close the scope by itself.
10//!
11//! Every supervised worker has a scope. The runtime creates the scope at the first spawn into it, so a worker that
12//! never spawns a child uses no resources for a scope. The supervision tree shows the children of a worker below that
13//! worker.
14//!
15//! # How a scope closes
16//!
17//! A scope closes when the body of its owner finishes. It then stops each child according to the child's own shutdown
18//! strategy, the same as a supervisor does: a graceful child is told to stop and halted if it outlives its timeout, and
19//! a brutal child is halted at once. A closure-based child defaults to graceful, with a timeout of five seconds.
20//!
21//! The body can spawn children right before it returns, before they start. If the body returns normally, these
22//! children still start, and then they are told to stop. If the body fails, they never start.
23//!
24//! The scope does not close only because the owner was told to stop. The owner decides when its children stop, because
25//! its scope closes only when its body returns. Thus, the owner can stop its children in the order that it chooses. For
26//! example, it can refuse new connections first, and then close the connections that it has. The signal that the
27//! children get when the scope closes is the last step of that order. A child that already stopped, for example
28//! because its input closed, has nothing left to do then. The one exception is a nested supervisor that
29//! [stops with its owner](#nested-supervisors-that-stop-with-their-owner), which is told to stop together with the
30//! owner.
31//!
32//! The timeout of a child starts only when the child is told to stop, which is when the scope closes, after the body
33//! of the owner returns. Thus, the shutdown strategy of the owner must cover the time for its own body to stop and the
34//! time for its children to stop. If the owner's timeout expires, the owner and everything still running in its scope,
35//! nested scopes included, are halted, logged, and counted, whether or not they were already told to stop. A child
36//! timeout can't extend past its owner's.
37//!
38//! # Nested supervisors that stop with their owner
39//!
40//! Some owners consume what their children produce. For example, the body of a relay drains a channel that an HTTP
41//! server in its scope feeds, and dispatches each request downstream. The server is a nested supervisor. The body can
42//! finish its drain only once the server stops, but the server would stop only once the body returns.
43//!
44//! [`NestedSupervisorBuilder::stops_with_owner`][stops] resolves this. When the owner is told to stop, the scope tells
45//! the server to stop at once, while the body still runs. The server stops accepting connections and completes the
46//! requests that it accepted. When it exits, the scope drops its specification, and with it the handler that holds the
47//! last sender of the channel. The body sees the channel close, and returns once it dispatched what remains.
48//!
49//! - The setting takes effect only if the owner takes the shutdown signal (see
50//!   [`Supervisable::wants_shutdown_signal`]). Otherwise, the nested supervisor stops when the scope closes.
51//! - A nested supervisor with the setting that is spawned after its owner was told to stop is told to stop at once.
52//! - Its exit is a requested exit, because its owner was told to stop. Thus, the scope never restarts it, and it never
53//!   fails the owner, even if it is needed.
54//!
55//! The body of the owner **MUST NOT** hold a sender of a channel that it drains. Otherwise, the channel never closes,
56//! and the owner is halted when its timeout expires.
57//!
58//! Other kinds of ingress need no setting:
59//!
60//! - A closure child can stop on the owner's own shutdown handle, which the body moves into it.
61//! - The consumer can be a child too, which takes no signal and has no timeout of its own. The body then returns on
62//!   the signal. As the scope closes, the ingress stops, and the consumer drains its channel until it closes.
63//!
64//! [stops]: crate::runtime::NestedSupervisorBuilder::stops_with_owner
65//!
66//! # Requested exits and other exits
67//!
68//! If a child exits after its owner, or a process above its owner, was told to stop, the exit is a requested exit. This
69//! is true even if the scope is still open. The scope never restarts a child after a requested exit, and a requested
70//! exit never fails the owner. Thus, a child that exits while its owner drains cannot cut that drain short.
71//!
72//! The scope never restarts a child while the scope closes. If the child exits cleanly, the exit is also a requested
73//! exit, whatever the reason that the scope closes. But if the child fails and nothing told its owner to stop, the
74//! failure has the same effect as when the scope is open: a needed child fails the owner. This is necessary because a
75//! body often returns because a child failed. For example, the body sees the output channel of the child close. The
76//! body then returns before the scope sees the exit of the child, so the scope sees the failure only as it closes. If
77//! the body itself failed, its own error has priority.
78//!
79//! If a child exits while its scope is open and no stop was requested, the child stopped by itself. Two things then
80//! decide what occurs next:
81//!
82//! - Its restart policy decides if the scope restarts it, the same as under a supervisor.
83//! - Its _edge_ decides what occurs if the scope does not restart it. The default is a _hosted_ child: the scope reaps
84//!   it, and its owner continues. A _needed_ child is a child that its owner cannot work without, and it fails the
85//!   owner. To mark a child as needed, use [`ChildBuilder::needed`][crate::runtime::ChildBuilder::needed].
86//!
87//! A child can stop again and again. If one more restart exceeds the restart limit of the scope, the child fails the
88//! owner. The edge of the child has no effect on this, and under a supervisor, the same child stops the supervisor. A
89//! restart is a reset, unless the child keeps its state on purpose, as a
90//! [`ResumableWorker`][crate::runtime::ResumableWorker] does. If a child continues to fail, the failure goes to the
91//! next level of the supervision tree, and that level tries again.
92//!
93//! This also applies to the children of a [nested] scope: they fail the process that the scope belongs to.
94//!
95//! # How to spawn children
96//!
97//! [`spawn`][crate::runtime::spawn] and [`ChildBuilder::spawn`][crate::runtime::ChildBuilder::spawn] spawn into the
98//! scope of the current process. [`current`] returns a handle to that scope, and you can move that handle to other
99//! tasks. Some code can run fully outside supervision, for example a primitive that a test constructs. That code uses
100//! [`spawn_or_detached`][crate::runtime::ChildBuilder::spawn_or_detached] or [`nested_or_detached`]. If there is no
101//! scope, these functions run the work as a detached task, the same as without scopes.
102//!
103//! # Scopes owned by values
104//!
105//! [`nested`] creates a scope that a value owns instead of a process. Its children run under the current process, but
106//! the [`ScopeGuard`] that it returns stops them when the guard is dropped. For example, a cache can hold the guard for
107//! its background tasks. The tasks then stop when the last copy of the cache is dropped or when the process that owns
108//! the cache stops, whichever occurs first. In both cases, nothing restarts the tasks, because they were told to stop.
109//! If the process stops before the nested scope can start, the nested scope closes at once, and its tasks never run.
110//!
111//! A value can also own the scopes of the values that it builds. To do this, it builds them inside
112//! [`ScopeGuard::enter_sync`]. For example, a resolver that builds its own cache holds a guard, and builds the cache
113//! inside that guard. The scope of the cache is then nested in the scope of the resolver, and the tasks of the cache
114//! stop when the resolver stops. Only build a value inside the scope of another value if it never outlives that value.
115//!
116//! # Pre-created scopes
117//!
118//! [`UnadoptedScope::new`] creates a scope before the process that later owns it exists. The scope holds the children
119//! that are spawned into it until a worker adopts it. Then the children start as children of that worker. This is how
120//! the process that runs a component can own work that was spawned while the component was built. An example is the
121//! background tasks of a cache that is constructed together with the component.
122//!
123//! The [`UnadoptedScope`] holds the children that wait. Handles to the scope do not. Thus, if the `UnadoptedScope` is
124//! dropped before a worker adopts it, the children that wait are dropped too, even if one of them holds a handle to the
125//! scope.
126//!
127//! Only one worker can adopt a scope. If that worker starts again, for example because its supervisor restarts, the
128//! new instance gets a new scope of its own. The pre-created scope closed when the first instance stopped.
129
130mod drive;
131use std::{
132    fmt,
133    future::Future,
134    sync::{
135        atomic::{AtomicU64, Ordering},
136        Arc, Mutex, OnceLock,
137    },
138    time::Duration,
139};
140
141use async_trait::async_trait;
142use saluki_common::{
143    sync::shutdown::{ShutdownCoordinator, ShutdownHandle},
144    task::spawn_traced_named,
145};
146use snafu::Snafu;
147use tokio::{runtime::Handle, select, sync::mpsc};
148use tracing::{debug, warn};
149
150pub(super) use self::drive::{drive, DriveContext, StopLink};
151use super::{
152    supervisable::{InitializationError, ShutdownStrategy, Supervisable, SupervisorFuture},
153    supervisor::{ChildConfig, ChildId, ChildSpecification, ChildState, Registration, SupervisedChild, WorkerSpec},
154};
155
156/// How the termination of a child affects its owner, which is its supervisor or the process that owns its scope.
157///
158/// The owner uses the edge only if a child terminates without a request to stop and its restart policy does not restart
159/// it. If the restart policy requires a restart but the child reached the restart limit of its owner, the child fails
160/// the owner. The edge of the child has no effect on this.
161#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
162pub(crate) enum Edge {
163    /// The owner only runs the child: if the child terminates and is not restarted, it is reaped and the owner
164    /// continues.
165    #[default]
166    Hosted,
167
168    /// The owner cannot do its work without the child: if the child terminates and is not restarted, the owner fails.
169    Needed,
170}
171
172/// Errors that make a worker fail because of a child in its scope.
173#[derive(Debug, Snafu)]
174#[snafu(context(suffix(false)))]
175pub enum ScopeError {
176    /// A child terminated without a request to stop and was not restarted, and its owner cannot continue without it.
177    #[snafu(display("Child '{}' terminated: {}", child_name, reason))]
178    ChildTerminated {
179        /// The name of the child.
180        child_name: String,
181
182        /// How the child terminated.
183        reason: String,
184    },
185
186    /// A child terminated repeatedly without a request to stop and exceeded the restart limit of its scope.
187    #[snafu(display("Child '{}' exceeded its scope's restart limit.", child_name))]
188    ChildRestartLimit {
189        /// The name of the child.
190        child_name: String,
191    },
192}
193
194/// A child that is queued for a scope and waits for the owner of the scope to start it.
195struct PendingScopeChild {
196    id: u64,
197    spec: SupervisedChild,
198    config: ChildConfig,
199}
200
201/// The queue of children that wait for the owner of a scope to start them.
202type SpawnQueue = mpsc::UnboundedReceiver<PendingScopeChild>;
203
204/// A set of children owned by one process.
205///
206/// See the [module documentation][self] for a description of a scope. A `Scope` is a handle. A clone of it costs
207/// little, and any task can use it. A spawn through a `Scope` always succeeds. But, as with [`tokio::spawn`], a
208/// successful spawn does not guarantee that the child runs. If a child is spawned after its scope closed, the child is
209/// dropped.
210///
211/// A handle does not hold the children that wait to start. The owner of the scope holds them, or the
212/// [`UnadoptedScope`] before a worker adopts the scope. Thus, a child can hold a handle to its own scope without
213/// keeping the scope alive.
214#[derive(Clone)]
215pub struct Scope {
216    shared: Arc<ScopeShared>,
217}
218
219struct ScopeShared {
220    name: Arc<str>,
221    tx: mpsc::UnboundedSender<PendingScopeChild>,
222    next_id: AtomicU64,
223}
224
225impl Scope {
226    /// Creates a scope, and returns the handle to it together with its spawn queue.
227    fn with_queue(name: String) -> (Self, SpawnQueue) {
228        let (tx, rx) = mpsc::unbounded_channel();
229        let scope = Self {
230            shared: Arc::new(ScopeShared {
231                name: Arc::from(name),
232                tx,
233                next_id: AtomicU64::new(0),
234            }),
235        };
236        (scope, rx)
237    }
238
239    /// Returns the scope's name.
240    pub fn name(&self) -> &str {
241        &self.shared.name
242    }
243
244    /// Spawns a child into the scope.
245    ///
246    /// Accepts all values that [`SupervisorHandle::spawn`][crate::runtime::SupervisorHandle::spawn] accepts. This
247    /// includes a nested supervisor. By default, the child is hosted.
248    ///
249    /// The returned [`ChildId`] identifies the child in this scope.
250    pub fn spawn<S, T>(&self, child: T) -> ChildId
251    where
252        S: ChildState,
253        T: Into<ChildSpecification<S>>,
254    {
255        let (spec, config) = S::into_child_parts(child.into(), Registration::Spawned).into_parts();
256        self.enqueue(spec, config)
257    }
258
259    fn enqueue(&self, spec: SupervisedChild, config: ChildConfig) -> ChildId {
260        let id = self.shared.next_id.fetch_add(1, Ordering::Relaxed);
261        if let Err(e) = self.shared.tx.send(PendingScopeChild { id, spec, config }) {
262            // A race with the shutdown of the owner is normal and not an exception, so this message stays at debug
263            // level.
264            debug!(
265                scope = %self.shared.name,
266                child_name = e.0.spec.name(),
267                "Scope has closed; child will not be started."
268            );
269        }
270
271        ChildId::from_raw(id)
272    }
273
274    /// Runs `fut` with this scope as the current one.
275    ///
276    /// If `fut` spawns into the current scope, the spawn goes into this scope instead. This applies to spawns through
277    /// [`current`], [`spawn`][crate::runtime::spawn], or [`nested`]. While `fut` runs, this scope replaces the scope
278    /// that was current before.
279    pub fn enter<F: Future>(&self, fut: F) -> impl Future<Output = F::Output> {
280        CURRENT_SCOPE.scope(ScopeSlot::prefilled(self.clone()), fut)
281    }
282
283    /// Runs `f` with this scope as the current one.
284    ///
285    /// This is the synchronous version of [`enter`][Self::enter].
286    pub fn enter_sync<R>(&self, f: impl FnOnce() -> R) -> R {
287        CURRENT_SCOPE.sync_scope(ScopeSlot::prefilled(self.clone()), f)
288    }
289}
290
291impl fmt::Debug for Scope {
292    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
293        f.debug_struct("Scope")
294            .field("name", &self.shared.name)
295            .finish_non_exhaustive()
296    }
297}
298
299/// A scope that no process owns yet.
300///
301/// The scope holds the children that are spawned into it until a worker adopts it. Then the children start as
302/// children of that worker. If the `UnadoptedScope` is dropped before a worker adopts it, the scope closes, and it
303/// drops the children that wait and each child that is spawned into it later.
304///
305/// Most code does not use this type. Every supervised worker already has a scope, which is available through
306/// [`current`] or [`spawn`][crate::runtime::spawn].
307pub struct UnadoptedScope {
308    scope: Scope,
309
310    /// The children that wait for a worker to adopt the scope. Always present until the scope is adopted.
311    rx: Option<SpawnQueue>,
312}
313
314impl UnadoptedScope {
315    /// Creates a scope that no process owns yet.
316    pub fn new<N: Into<String>>(name: N) -> Self {
317        let (scope, rx) = Scope::with_queue(name.into());
318        Self { scope, rx: Some(rx) }
319    }
320
321    /// Returns a handle to the scope, through which children can be spawned into it before a worker adopts it.
322    pub fn scope(&self) -> &Scope {
323        &self.scope
324    }
325
326    /// Describes a worker that owns this scope, for a supervisor to add as a child.
327    ///
328    /// The worker only holds the children of the scope. It runs until it is told to stop, and then the scope closes.
329    /// Use this for work that is spawned outside supervised processes, such as work at startup before the supervision
330    /// tree runs. The worker makes that work part of the tree when the tree runs. The worker fails if one of the
331    /// children of the scope fails its owner. The worker passes that failure to the supervisor or scope that it is
332    /// added to.
333    ///
334    /// If the supervisor starts the worker again, for example because the supervisor restarts, the new worker holds
335    /// nothing. The scope closed when the first worker stopped, and the scope drops each child that is spawned into it
336    /// after that.
337    pub fn into_host(self) -> ChildSpecification<WorkerSpec> {
338        let name = self.scope.name().to_string();
339        ChildSpecification::worker(ScopeHost::new(name, None))
340            .forwarding_failures()
341            .adopting(self)
342    }
343
344    /// Splits the scope into its handle and its spawn queue, for the worker that adopts it.
345    fn into_parts(mut self) -> (Scope, SpawnQueue) {
346        let rx = self.rx.take().expect("an unadopted scope holds its spawn queue");
347        (self.scope.clone(), rx)
348    }
349}
350
351impl Drop for UnadoptedScope {
352    fn drop(&mut self) {
353        // If no worker adopted a scope, the scope drops all children that are in its queue. This is normal. For
354        // example, a component that fails before it runs never adopts the scope that it was built in. Thus, this
355        // message stays at debug level.
356        let Some(mut rx) = self.rx.take() else {
357            return;
358        };
359
360        rx.close();
361        let mut dropped = 0;
362        while rx.try_recv().is_ok() {
363            dropped += 1;
364        }
365        if dropped > 0 {
366            debug!(
367                scope = self.scope.name(),
368                dropped, "Scope was never adopted; dropping the children queued on it."
369            );
370        }
371    }
372}
373
374impl fmt::Debug for UnadoptedScope {
375    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
376        f.debug_struct("UnadoptedScope")
377            .field("name", &self.scope.name())
378            .finish_non_exhaustive()
379    }
380}
381
382/// A pre-created scope for a worker to adopt, shared by every copy of the configuration of that worker.
383///
384/// The first instance of the worker takes the scope. A later instance finds nothing, and gets a new scope instead. If
385/// the last copy of the configuration is dropped before any instance takes the scope, the scope closes and drops the
386/// children that wait in it.
387#[derive(Clone)]
388pub(crate) struct Adoption {
389    name: Arc<str>,
390    scope: Arc<Mutex<Option<UnadoptedScope>>>,
391}
392
393impl Adoption {
394    pub(crate) fn new(scope: UnadoptedScope) -> Self {
395        Self {
396            name: Arc::clone(&scope.scope.shared.name),
397            scope: Arc::new(Mutex::new(Some(scope))),
398        }
399    }
400
401    /// Returns the name of the scope.
402    fn name(&self) -> &str {
403        &self.name
404    }
405
406    /// Takes the scope, if no instance of the worker took it yet.
407    fn take(&self) -> Option<UnadoptedScope> {
408        self.scope.lock().expect("adoption lock poisoned").take()
409    }
410}
411
412impl fmt::Debug for Adoption {
413    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
414        f.debug_struct("Adoption")
415            .field("scope", &self.name)
416            .finish_non_exhaustive()
417    }
418}
419
420tokio::task_local! {
421    /// The scope of the current process.
422    static CURRENT_SCOPE: ScopeSlot;
423}
424
425/// Where the current process keeps its scope.
426///
427/// The runtime installs this slot around the body of each supervised worker. The runtime creates the scope of a worker
428/// only at the first spawn into it. Thus, a worker that never spawns a child never has a scope.
429#[derive(Clone)]
430struct ScopeSlot {
431    /// How the slot creates its scope on demand, or `None` if the slot received its scope at creation.
432    lazy: Option<Arc<LazyScope>>,
433
434    scope: Arc<OnceLock<Scope>>,
435}
436
437/// What a slot needs to create its scope on demand.
438struct LazyScope {
439    name: Arc<str>,
440
441    /// The spawn queue of the scope after the slot created it, until the worker that owns the slot takes it.
442    rx: Mutex<Option<SpawnQueue>>,
443}
444
445impl ScopeSlot {
446    /// Creates a slot that creates its scope, with the name `name`, at the first use.
447    fn lazy(name: Arc<str>) -> Self {
448        Self {
449            lazy: Some(Arc::new(LazyScope {
450                name,
451                rx: Mutex::new(None),
452            })),
453            scope: Arc::new(OnceLock::new()),
454        }
455    }
456
457    /// Creates a slot that holds `scope`.
458    fn prefilled(scope: Scope) -> Self {
459        Self {
460            lazy: None,
461            scope: Arc::new(OnceLock::from(scope)),
462        }
463    }
464
465    /// Returns the scope, if it exists.
466    fn get(&self) -> Option<&Scope> {
467        self.scope.get()
468    }
469
470    /// Returns the scope, and first creates it if this slot creates its scope on demand.
471    fn get_or_create(&self) -> Option<Scope> {
472        if let Some(scope) = self.scope.get() {
473            return Some(scope.clone());
474        }
475
476        let lazy = self.lazy.as_ref()?;
477        let scope = self.scope.get_or_init(|| {
478            let (scope, rx) = Scope::with_queue(lazy.name.to_string());
479            *lazy.rx.lock().expect("scope slot lock poisoned") = Some(rx);
480            scope
481        });
482        Some(scope.clone())
483    }
484
485    /// Takes the spawn queue of the scope that this slot created on demand, if the slot created one.
486    fn take_receiver(&self) -> Option<SpawnQueue> {
487        self.lazy.as_ref()?.rx.lock().expect("scope slot lock poisoned").take()
488    }
489}
490
491/// Returns the scope of the current process.
492///
493/// Returns `None` outside of a supervised process. You can move the returned handle to other tasks. Thus, code that
494/// does not run as the process that owns the scope can spawn into that scope. A callback-driven executor is an example
495/// of such code.
496pub fn current() -> Option<Scope> {
497    CURRENT_SCOPE.try_with(ScopeSlot::get_or_create).ok().flatten()
498}
499
500/// Creates a scope that a value owns instead of a process.
501///
502/// The children of the scope run under the current process. The supervision tree shows them below that process, under
503/// `name`. They stop when the returned guard is dropped or when the current process stops, whichever occurs first. In
504/// both cases, nothing restarts them. If the current process stops before the scope can start, the scope closes at
505/// once, and its children never run.
506///
507/// # Panics
508///
509/// Panics if there is no current scope. This means that the caller does not run in a supervised process. Use
510/// [`nested_or_detached`] for code that can run outside supervision.
511pub fn nested<N: Into<String>>(name: N) -> ScopeGuard {
512    let owner = current().unwrap_or_else(|| {
513        panic!(
514            "`scope::nested` called outside of a supervised process: there is no current scope to nest in. Use \
515             `scope::nested_or_detached` for code that may run outside supervision."
516        )
517    });
518
519    nested_under(&owner, name.into())
520}
521
522/// Creates a scope that a value owns, as [`nested`] does, or a detached guard that acts as a scope outside supervision.
523///
524/// Outside a supervised process, there is no scope to nest in. Thus, the returned guard runs its children as detached
525/// tasks instead. When the guard is dropped, it tells these tasks to stop. This is the behavior that this work has
526/// without scopes. For this reason, this function is the correct choice for primitives that code can construct
527/// anywhere.
528pub fn nested_or_detached<N: Into<String>>(name: N) -> ScopeGuard {
529    let name = name.into();
530    match current() {
531        Some(owner) => nested_under(&owner, name),
532        None => ScopeGuard {
533            inner: GuardInner::Detached {
534                name: Arc::from(name),
535                coordinator: ShutdownCoordinator::default(),
536            },
537        },
538    }
539}
540
541fn nested_under(owner: &Scope, name: String) -> ScopeGuard {
542    let unadopted = UnadoptedScope::new(name.clone());
543    let scope = unadopted.scope().clone();
544    let (close, close_signal) = ShutdownHandle::paired();
545
546    // The children of the nested scope must run under a process. Thus, a host worker adopts the scope and holds the
547    // children until the guard is dropped or the host is told to stop. The failures of the children belong to the
548    // owner, so the host passes its own failures to the owner.
549    //
550    // The specification of the host holds the scope until the host adopts it. If the host never starts, for example
551    // because the scope of the owner closed first, the specification is dropped. The nested scope then closes, and it
552    // drops the children that wait in it and each child that is spawned into it later.
553    let host = ChildSpecification::worker(ScopeHost::new(name, Some(close_signal)))
554        .forwarding_failures()
555        .adopting(unadopted);
556    owner.spawn(host);
557
558    ScopeGuard {
559        inner: GuardInner::Scoped { scope, _close: close },
560    }
561}
562
563/// A scope that a value owns, which closes when the guard is dropped.
564///
565/// [`nested`] and [`nested_or_detached`] return this guard. Keep the guard with the value that the scope's children
566/// serve, so that they stop when that value is dropped.
567#[must_use = "dropping the guard closes the scope, stopping everything spawned into it"]
568pub struct ScopeGuard {
569    inner: GuardInner,
570}
571
572enum GuardInner {
573    /// A nested scope, which closes when a drop of the coordinator fires the signal of its host worker.
574    Scoped { scope: Scope, _close: ShutdownCoordinator },
575
576    /// Detached tasks that act as a scope outside supervision, where each task holds a handle to this coordinator.
577    Detached {
578        name: Arc<str>,
579        coordinator: ShutdownCoordinator,
580    },
581}
582
583impl ScopeGuard {
584    /// Spawns a child into the scope.
585    ///
586    /// Returns the child's [`ChildId`], or `None` if the guard is detached and the child started as a detached task. A
587    /// detached child receives a shutdown signal that fires when the guard is dropped. It has no other supervision:
588    /// nothing restarts it, and nothing waits for it.
589    pub fn spawn<T>(&mut self, child: T) -> Option<ChildId>
590    where
591        T: Into<ChildSpecification<WorkerSpec>>,
592    {
593        match &mut self.inner {
594            GuardInner::Scoped { scope, .. } => Some(scope.spawn(child)),
595            GuardInner::Detached { coordinator, .. } => {
596                spawn_detached(child.into(), coordinator.register());
597                None
598            }
599        }
600    }
601
602    /// Runs `f` with the scope of this guard as the current scope.
603    ///
604    /// Each spawn into the current scope inside `f` goes into this scope instead. This includes each scope that `f`
605    /// creates with [`nested_or_detached`]. Thus, a value that builds other values can also own their background tasks.
606    /// For example, a resolver builds its caches inside its own scope. The tasks of the caches then appear below the
607    /// resolver, and they stop when the resolver is dropped.
608    ///
609    /// A detached guard has no scope, so it runs `f` with no change. The values that `f` builds then also run their
610    /// tasks detached.
611    pub fn enter_sync<R>(&self, f: impl FnOnce() -> R) -> R {
612        match &self.inner {
613            GuardInner::Scoped { scope, .. } => scope.enter_sync(f),
614            GuardInner::Detached { .. } => f(),
615        }
616    }
617
618    /// Returns `true` if the guard acts as a scope outside supervision and runs its children as detached tasks.
619    pub fn is_detached(&self) -> bool {
620        matches!(self.inner, GuardInner::Detached { .. })
621    }
622}
623
624impl fmt::Debug for ScopeGuard {
625    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
626        match &self.inner {
627            GuardInner::Scoped { scope, .. } => f.debug_struct("ScopeGuard").field("scope", scope).finish(),
628            GuardInner::Detached { name, .. } => f
629                .debug_struct("ScopeGuard")
630                .field("detached", name)
631                .finish_non_exhaustive(),
632        }
633    }
634}
635
636/// Runs a worker as a detached task, outside supervision.
637///
638/// This function initializes the worker with `shutdown` and runs it to completion. It logs failures, because there is
639/// no other place to report them. The worker runs on the runtime that it was placed on, if it was placed on one. No
640/// other setting of the worker applies, because nothing supervises the worker.
641pub(super) fn spawn_detached(child: ChildSpecification<WorkerSpec>, shutdown: ShutdownHandle) {
642    let (spec, config) = WorkerSpec::into_child_parts(child, Registration::Spawned).into_parts();
643    let SupervisedChild::Worker(worker) = spec else {
644        unreachable!("a worker specification always lowers to a worker");
645    };
646
647    let name = worker.name().to_string();
648    let _runtime = config.runtime().map(Handle::enter);
649    spawn_traced_named(name.clone(), async move {
650        let run = match worker.initialize(shutdown).await {
651            Ok(run) => run,
652            Err(e) => {
653                warn!(child_name = %name, error = %e, "Detached child failed to initialize.");
654                return;
655            }
656        };
657
658        if let Err(e) = run.await {
659            warn!(child_name = %name, error = %e, "Detached child exited with an error.");
660        }
661    });
662}
663
664/// The worker that a nested or pre-created scope runs under.
665///
666/// Its body only waits until it is told to stop. Its supervisor can tell it to stop. For a nested scope, a drop of the
667/// guard also tells it to stop. When the body returns, the scope that the host adopted closes. That scope contains the
668/// actual work.
669struct ScopeHost {
670    name: String,
671    close: Mutex<Option<ShutdownHandle>>,
672}
673
674impl ScopeHost {
675    fn new(name: String, close: Option<ShutdownHandle>) -> Self {
676        Self {
677            name,
678            close: Mutex::new(close),
679        }
680    }
681}
682
683#[async_trait]
684impl Supervisable for ScopeHost {
685    fn name(&self) -> &str {
686        &self.name
687    }
688
689    fn shutdown_strategy(&self) -> ShutdownStrategy {
690        // The host has no timeout of its own. Its body returns as soon as it is told to stop, and then its scope stops
691        // each child according to the child's own shutdown strategy. The host waits for that, however long it takes.
692        ShutdownStrategy::Graceful(Duration::MAX)
693    }
694
695    fn can_restart(&self) -> bool {
696        // The host adopts its scope when it starts. That scope closes when the host stops, so a restarted host would
697        // hold nothing.
698        false
699    }
700
701    async fn initialize(&self, process_shutdown: ShutdownHandle) -> Result<SupervisorFuture, InitializationError> {
702        let close = self.close.lock().expect("scope host lock poisoned").take();
703
704        Ok(Box::pin(async move {
705            match close {
706                Some(close) => {
707                    select! {
708                        _ = process_shutdown => {},
709                        _ = close => {},
710                    }
711                }
712                None => process_shutdown.await,
713            }
714
715            Ok(())
716        }))
717    }
718}
719
720#[cfg(test)]
721mod tests;