ulo 0.1.0-alpha.3

Fast and modular web framework for scalable applications
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
//! The application: the graph plus the singleton store, moving through typestates
//! `Wired` → `Connected` → `Bound` → serving → closed (§2, §9.4).
//!
//! From `Connected` on it hands out an [`AppHandle`], a `Clone + Send + Sync` view of the shared
//! state that outlives `serve`. The application value is `Send`.
//!
//! [`Bound`] here is the typestate after `listen()`; the timeout enum is [`crate::Bound`].

pub(crate) mod handle;
pub(crate) mod load;
pub(crate) mod shared;

use std::future::{Future, poll_fn};
use std::marker::PhantomData;
use std::panic::{AssertUnwindSafe, Location, catch_unwind};
use std::ops::Deref;
use std::pin::{Pin, pin};
use std::sync::{Arc, PoisonError};
use std::task::{Context, Poll};
use std::time::Duration;

use crate::app::shared::AppShared;
use crate::binding::Qualifier;
use crate::dependency::Dep;
use crate::dependency::FromContainer;
use crate::error::{
    Closed, ConfigureErrors, ConnectError, FailureReason, LookupError, PreparePanicked, RuntimeMissing, ServeEnd, Shutdown,
    ShutdownError, ShutdownFailure, StartupError,
};
use crate::execution::trace::{TraceMode, TraceSource};
use crate::execution::{ExecOptions, Execution};
use crate::key::{BindingKind, Key};
use crate::resolver::{Purpose, Resolver};
use crate::graph::{ModuleId, wire};
use crate::lifecycle::phase::Phase as Stage;
use crate::lifecycle::run::CatchUnwind;
use crate::lifecycle::{connect, shutdown};
use crate::module::Module;
use crate::module::handle::ModuleRef;
use crate::redact::{Redacted, Redactor, SecretRegistry, redact, redact_panic};
use crate::runtime::{Clocked, Runtime};
use crate::signal::Signal;
use crate::testing::TestPlan;
use crate::timer::{BoxError, BoxFuture, Defaults, Timer};
use crate::transport::server::{BoundAddr, ErasedServer, Server};
use crate::type_name::TypeName;

pub use handle::{AppHandle, Phase};

/// Wired: the graph is built and every wiring error has been reported. Nothing is built yet.
pub enum Wired {}

/// Connected: singletons built, readiness checks passed, init and bootstrap hooks run.
pub enum Connected {}

/// Bound: every transport holds its sockets. `serve` consumes this state.
pub enum Bound {}

/// An application in typestate `S`.
///
/// Keep the `App`, or the future serving it, alive for as long as the app serves: an
/// [`AppHandle`] is a view, not an owner. The `App` value's drop is the end of the app, whatever
/// handles are kept; what that drop does is below.
///
/// Dropping it lets go of the bound transports' servers, as the end of the shutdown's close step
/// does. For an app that never reaches that step the drop is where they are released: one bound
/// and dropped unserved, one whose `serve` future is dropped, and one whose shutdown was abandoned
/// mid-way. Each server then drops with its last other holder, and that drop is its only shutdown:
/// its `close` does not run, and what only `close` ends, such as a task the server spawned and
/// detached, keeps running.
///
/// A drop while a `close` on a handle holds its claim, taken at the call to `close`, leaves the
/// servers to it, whether its future was polled before the drop or is first polled after it: its
/// drain and close step run over every server, each server's `close` runs, and the close step's
/// end releases them. A `close` dropped before its close step, polled or not, releases them as it
/// drops, unclosed, as this drop would have; with several claims held, the last to drop does. A
/// `close` kept and neither polled to its end nor dropped holds the servers until it resumes or
/// drops. Its future holds a claim on the servers and the app's shared state, so it is awaited
/// where it is made: stored in state the app owns, a singleton among it, it holds the app from
/// inside the app, and no drop reaches either.
///
/// The release awaits nothing and does not panic on a lock: it takes two, each held only to read
/// or change a field and never across an await, and reads either through when poisoned. A
/// server's own drop runs on the thread dropping the app, or on the one dropping the last `close`
/// claim.
///
/// A release by this drop or by the last claim's, the close step not ended, moves the app to
/// [`Phase::Closed`] and resolves [`AppHandle::draining`], so a background loop holding a handle
/// is told to stop; its `execute` then answers `Closed` and a lookup `LookupError::Closed`, as
/// after a shutdown. No hook runs.
///
/// An [`AppHandle`] kept past the drop keeps the app's shared state, its singletons among it, and
/// no server once they are released: a `close` called on it after that, the close step not
/// ended, runs none of the shutdown's steps and answers `Err` carrying
/// [`ShutdownFailure::Dropped`]. Once a shutdown has run its close
/// step, a `close` after the drop answers that shutdown's outcome.
pub struct App<S = Wired> {
    pub(crate) shared: Owner,
    /// Queued by `bind` on `Connected`, bound by `listen`.
    pub(crate) servers: Vec<Box<dyn ErasedServer>>,
    _s: PhantomData<S>,
}

/// Configures an app before `wire()`: the root module, the `Timer` or the `Runtime` that carries
/// one, and the four timing knobs. Every knob is timed by the `Timer`; set on a builder with none,
/// each is a wiring error.
pub struct AppBuilder {
    pub(crate) root: Box<dyn Module>,
    pub(crate) config: AppConfig,
    pub(crate) plan: Option<TestPlan>,
}

/// The app's timing configuration. `None` is unset.
#[derive(Clone, Default)]
pub(crate) struct AppConfig {
    /// The clock: the same object as `runtime`, unless `.timer(..)` came after `.runtime(..)`.
    pub(crate) timer: Option<Arc<dyn Timer>>,
    /// What `Dep<dyn Runtime>` resolves to: the app's wrapper around the runtime as given, timing
    /// with its clock or, once a later `.timer(..)` replaced it, with that timer's.
    pub(crate) runtime: Option<Arc<dyn Runtime>>,
    /// The runtime as given to `.runtime(..)`, which a later `.timer(..)` takes the spawning of.
    spawner: Option<Arc<dyn Runtime>>,
    /// The graph's secrets, which the app's runtime redacts a spawned task's panic with. The app
    /// sets them once a graph exists.
    pub(crate) redactor: Redactor,
    pub(crate) drain_timeout: Option<Duration>,
    pub(crate) shutdown_timeout: Option<Duration>,
    pub(crate) hook_timeout: Option<Duration>,
    pub(crate) construct_timeout: Option<Duration>,
    /// The calls that set `hook_timeout` and `construct_timeout`, for a zero `wire` refuses.
    hook_timeout_at: Option<&'static Location<'static>>,
    construct_timeout_at: Option<&'static Location<'static>>,
    pub(crate) trace: TraceMode,
}

impl AppConfig {
    pub(crate) const DEFAULT_DRAIN: Duration = Duration::from_secs(10);
    pub(crate) const DEFAULT_HOOK: Duration = Duration::from_secs(10);
    pub(crate) const DEFAULT_CONSTRUCT: Duration = Duration::from_secs(30);

    /// The defaults `Bound::Default` resolves against; `None` without a `Timer`, where an item
    /// left at `Default` runs unbounded.
    pub(crate) fn defaults(&self) -> Option<Defaults> {
        if self.timer.is_none() {
            return None;
        }
        Some(Defaults {
            hook_timeout: self.hook_timeout.unwrap_or(Self::DEFAULT_HOOK),
            construct_timeout: self.construct_timeout.unwrap_or(Self::DEFAULT_CONSTRUCT),
        })
    }

    /// The drain window: zero without a `Timer`, which abandons live executions at once.
    pub(crate) fn drain(&self) -> Duration {
        match self.timer {
            Some(_) => self.drain_timeout.unwrap_or(Self::DEFAULT_DRAIN),
            None => Duration::ZERO,
        }
    }

    /// The default knobs set to zero, which would end every item left at `Default` before it
    /// starts, each with the call that set it. `drain_timeout` and `shutdown_timeout` are windows
    /// where zero means none, and are not listed.
    pub(crate) fn zero_defaults(&self) -> Vec<(&'static str, &'static Location<'static>)> {
        let hook = self.hook_timeout.zip(self.hook_timeout_at);
        let construct = self.construct_timeout.zip(self.construct_timeout_at);
        [("hook_timeout", hook), ("construct_timeout", construct)]
            .into_iter()
            .filter_map(|(name, set)| set.filter(|(d, _)| d.is_zero()).map(|(_, at)| (name, at)))
            .collect()
    }

    /// The names of the knobs that were set, for the environment check.
    pub(crate) fn knobs_set(&self) -> Vec<&'static str> {
        [
            ("drain_timeout", self.drain_timeout),
            ("shutdown_timeout", self.shutdown_timeout),
            ("hook_timeout", self.hook_timeout),
            ("construct_timeout", self.construct_timeout),
        ]
        .into_iter()
        .filter_map(|(name, set)| set.map(|_| name))
        .collect()
    }
}

/// The `App` value's hold on the shared state. It moves from typestate to typestate and only
/// `wire` makes one, so an app has one however many `AppHandle`s it hands out, and its drop is the
/// app's. A drop after the close step finds the list of servers empty.
pub(crate) struct Owner(Arc<AppShared>);

impl Deref for Owner {
    type Target = Arc<AppShared>;

    fn deref(&self) -> &Arc<AppShared> {
        &self.0
    }
}

impl Drop for Owner {
    fn drop(&mut self) {
        shutdown::app_dropped(&self.0);
    }
}

impl App {
    pub fn builder(root: impl Module) -> AppBuilder {
        AppBuilder { root: Box::new(root), config: AppConfig::default(), plan: None }
    }
}

impl AppBuilder {
    /// The app's one clock; bound for services as `Dep<dyn Timer>` in the core's global module.
    ///
    /// It sets the clock and nothing else, so after [`runtime`](Self::runtime) it replaces only
    /// the runtime's clock: `.runtime(r).timer(t)` spawns on `r` and times with `t`, and
    /// `Dep<dyn Runtime>` then sleeps and reads the time on `t`, so the app has one clock whatever
    /// reads it.
    pub fn timer(mut self, timer: impl Timer) -> Self {
        let timer: Arc<dyn Timer> = Arc::new(timer);
        self.config.runtime = self.config.spawner.as_ref().map(|spawner| {
            Arc::new(Clocked::new(Arc::clone(spawner), Arc::clone(&timer), self.config.redactor.clone())) as Arc<dyn Runtime>
        });
        self.config.timer = Some(timer);
        self
    }

    /// The app's clock and executor; bound for services as `Dep<dyn Runtime>` in the core's global
    /// module, and as `Dep<dyn Timer>`, which resolves to the same object. Everything a `Timer`
    /// alone enables it enables as the clock.
    ///
    /// The object both resolve to is the app's wrapper around `runtime`: it spawns on `runtime`
    /// and times with its clock, and a task spawned through it that panics ends `Panicked` with
    /// every secret the app registered replaced in its message. The app's runtime is the core's
    /// wrapper around the one given, not that object, so code holding `Dep<dyn Runtime>` cannot
    /// reach `runtime`'s own type through it, a downcast included.
    ///
    /// It sets both the spawning and the clock, so it replaces a [`timer`](Self::timer) set
    /// before it: `.timer(t).runtime(r)` spawns and times on `r`.
    pub fn runtime(mut self, runtime: impl Runtime) -> Self {
        let runtime: Arc<dyn Runtime> = Arc::new(runtime);
        let clock = Arc::clone(&runtime) as Arc<dyn Timer>;
        let wrapped: Arc<dyn Runtime> = Arc::new(Clocked::new(Arc::clone(&runtime), clock, self.config.redactor.clone()));
        self.config.timer = Some(Arc::clone(&wrapped) as Arc<dyn Timer>);
        self.config.spawner = Some(runtime);
        self.config.runtime = Some(wrapped);
        self
    }

    /// In-flight executions at shutdown; ten seconds unset.
    pub fn drain_timeout(mut self, d: Duration) -> Self {
        self.config.drain_timeout = Some(d);
        self
    }

    /// The whole close sequence, from the trigger; unset by default. Set it a few seconds under
    /// the orchestrator's grace period.
    pub fn shutdown_timeout(mut self, d: Duration) -> Self {
        self.config.shutdown_timeout = Some(d);
        self
    }

    /// The `Default` every hook starts with; ten seconds unset. Zero is refused by `wire()` as
    /// `WiringError::ZeroDefault`.
    #[track_caller]
    pub fn hook_timeout(mut self, d: Duration) -> Self {
        self.config.hook_timeout = Some(d);
        self.config.hook_timeout_at = Some(Location::caller());
        self
    }

    /// The `Default` every construction and one attempt of every readiness check starts with;
    /// thirty seconds unset. Zero is refused by `wire()` as `WiringError::ZeroDefault`.
    #[track_caller]
    pub fn construct_timeout(mut self, d: Duration) -> Self {
        self.config.construct_timeout = Some(d);
        self.config.construct_timeout_at = Some(Location::caller());
        self
    }

    /// Whether the app reads and writes W3C trace headers; `TraceMode::On` unset (integrations
    /// §6.1). Under `Off` no transport's context reaches an execution, no `TraceSource` is resolved
    /// or called, and `traceparent` and `tracestate` are ordinary headers to every client.
    pub fn trace(mut self, mode: TraceMode) -> Self {
        self.config.trace = mode;
        self
    }

    /// Builds the graph and validates everything, collecting every error in one pass. No
    /// instances, no I/O.
    pub fn wire(self) -> Result<App<Wired>, StartupError> {
        let env = wire::WireEnv {
            timer: self.config.timer.clone(),
            runtime: self.config.runtime.clone(),
            knobs_set: self.config.knobs_set(),
            zero_defaults: self.config.zero_defaults(),
        };
        let graph = wire::wire(self.root, &env, self.plan)?;
        Ok(App::from_shared(Owner(AppShared::new(graph, self.config)), Vec::new()))
    }
}

impl<S> App<S> {
    pub(crate) fn from_shared(shared: Owner, servers: Vec<Box<dyn ErasedServer>>) -> Self {
        App { shared, servers, _s: PhantomData }
    }
}

impl App<Wired> {
    /// Builds the singletons in dependency order, running each one's readiness check right after
    /// it, then every `OnModuleInit` hook, then every `OnApplicationBootstrap` hook (§9.2).
    ///
    /// Then, under `TraceMode::On`, resolves the `dyn TraceSource` the root module sees, if one is
    /// bound, for `AppHandle::trace_source()` to answer (I15). A source that cannot be read, one
    /// two exports answer or one bound per execution, fails the connect as
    /// `ConnectError::Construct` naming it.
    pub async fn connect(self) -> Result<App<Connected>, StartupError> {
        let shared = self.shared;
        shared.phase.advance(Stage::Connecting);
        let graph = shared.graph();
        // `ModuleId`s are positions in collection order, the order the hooks take.
        let modules: Vec<ModuleId> = graph.modules.iter().map(|module| module.id).collect();
        connect::connect(&shared, &graph.connect_order, &modules).await?;
        if shared.config.trace == TraceMode::On {
            let resolver = Resolver::new(&shared, graph.root, None, Purpose::Lookup);
            match <Option<Dep<dyn TraceSource>> as FromContainer>::from_container(&resolver).await {
                Ok(Some(source)) => {
                    let _ = shared.trace_source.set(source.into_arc());
                }
                Ok(None) => {}
                Err(error) => return Err(StartupError::Connect(trace_source_failure(&graph, error))),
            }
        }
        shared.phase.advance(Stage::Running);
        Ok(App::from_shared(shared, Vec::new()))
    }
}

/// A `dyn TraceSource` lookup at `connect` that answered neither a source nor `NotFound`.
fn trace_source_failure(graph: &crate::graph::Graph, error: LookupError) -> ConnectError {
    let key = Key::of::<dyn TraceSource, ()>().name(BindingKind::Single);
    let module = graph.module(graph.root).name.clone();
    let reason = match error {
        LookupError::Construct { reason, .. } => reason,
        other => {
            let text = other.to_string();
            FailureReason::Errored(Redacted::from_parts(Box::new(other), text))
        }
    };
    ConnectError::Construct { key, module, reason }
}

impl App<Connected> {
    /// Queues a transport; `listen` binds every queued transport.
    pub fn bind(mut self, server: impl Server) -> App<Connected> {
        self.servers.push(Box::new(server));
        self
    }

    /// Prepares every queued transport, then binds them in the order they were queued
    /// (transports DESIGN §2.7, X6).
    ///
    /// 1. `prepare` on every server: route tables, duplicate checks, TLS loading, CORS
    ///    validation, endpoint parsing, inherited sockets. Every failure is collected and
    ///    reported together as `StartupError::Configure`; nothing has bound yet, so a
    ///    configuration error is always reported before a port conflict. A `prepare` that panics
    ///    is caught and reported as that server's entry, its `source` holding a
    ///    [`PreparePanicked`], and the other servers still prepare.
    /// 2. `bind` on each server in order. When one fails, those already bound are closed before
    ///    the error returns, so a refused app holds no sockets.
    ///
    /// Refuses an app that binds a transport with no `Runtime` before either step, one given
    /// `.timer(..)` alone included: `StartupError::Bind` carrying `RuntimeMissing` in its `source`.
    pub async fn listen(mut self) -> Result<App<Bound>, StartupError> {
        let mut queued = std::mem::take(&mut self.servers);
        if self.shared.config.runtime.is_none()
            && let Some(server) = queued.first()
        {
            let transport = server.transport_name();
            let refusal = RuntimeMissing { transport };
            let text = refusal.to_string();
            return Err(StartupError::Bind { transport, source: Redacted::from_parts(Box::new(refusal), text) });
        }
        let handle = self.handle();

        // A panic in one server's `prepare` is that server's failure: the others still prepare,
        // and the panicked server drops with the rest when `listen` returns, which is where a
        // transport lets go of what its `prepare` took.
        let mut refused: Vec<(TypeName, BoxError)> = Vec::new();
        for server in &mut queued {
            let transport = server.transport_name();
            match CatchUnwind::new(async { server.prepare(&handle).await }).await {
                Ok(Ok(())) => {}
                Ok(Err(error)) => refused.push((transport, error)),
                Err(payload) => {
                    let message = redact_panic(&self.shared.graph().secrets, payload);
                    refused.push((transport, Box::new(PreparePanicked { message })));
                }
            }
        }
        if !refused.is_empty() {
            return Err(StartupError::Configure(ConfigureErrors::collect(refused, &self.shared.graph().secrets)));
        }

        let mut bound: Vec<Arc<dyn ErasedServer>> = Vec::with_capacity(queued.len());
        for mut server in queued {
            let transport = server.transport_name();
            if let Err(error) = server.bind(&handle).await {
                let source = redact(&self.shared.graph().secrets, error);
                for done in &bound {
                    let _ = done.close().await;
                }
                return Err(StartupError::Bind { transport, source });
            }
            bound.push(Arc::from(server));
        }
        *self.shared.servers.lock().unwrap_or_else(PoisonError::into_inner) = bound;
        Ok(App::from_shared(self.shared, Vec::new()))
    }

    pub fn handle(&self) -> AppHandle {
        AppHandle { shared: Arc::clone(&self.shared) }
    }

    /// `T` with the root module's visibility.
    pub async fn get<T: ?Sized + Send + Sync + 'static>(&self) -> Result<Dep<T>, LookupError> {
        self.shared.get_root::<T>().await
    }

    /// The one module of type `M`: `LookupError::AmbiguousModule` if several configurations of
    /// it are registered. `M` is the type a module's identity names, the owner type for a
    /// `DynamicModule`.
    pub fn module<M: 'static>(&self) -> Result<ModuleRef, LookupError> {
        self.shared.find_module::<M>(None)
    }

    /// The keyed instance `Q` of `M`.
    pub fn module_keyed<M: 'static, Q: 'static>(&self) -> Result<ModuleRef, LookupError> {
        self.shared.find_module::<M>(Some(Qualifier::of::<Q>()))
    }

    /// The module whose identity is `config`'s: one configuration of a module type registered
    /// with several, `app.module_of(&DbModule::for_root(url))`, a keyed one written
    /// `.keyed::<Q>()` as it was imported. Nothing is loaded or built: a module the graph does not
    /// hold is `LookupError::NotFound` with `LookupKind::Module`.
    pub fn module_of<M: Module>(&self, config: &M) -> Result<ModuleRef, LookupError> {
        self.shared.module_of(config)
    }

    /// A standalone execution with the root module's visibility (§6.3). Refused from Draining on
    /// with `Closed`. `execute` drops the execution when the closure's future completes, which
    /// fires no cancellation; a subtask that outlives it takes `exec.handle()`.
    ///
    /// A stream built from the execution is consumed inside the closure: it ends when `execute`
    /// returns, and a read it makes afterwards answers `LookupError::ExecutionEnded`.
    ///
    /// ```
    /// # use ulo::{App, Connected, Dep, ExecOptions, ExecutionRef, LookupError};
    /// # struct Clock;
    /// /// A reply source reading through its execution on every item.
    /// struct Ticks(ExecutionRef);
    ///
    /// impl Ticks {
    ///     async fn next(&self) -> Result<Dep<Clock>, LookupError> {
    ///         self.0.get::<Clock>().await
    ///     }
    /// }
    /// # async fn f(app: App<Connected>) -> Result<(), Box<dyn std::error::Error>> {
    /// // Consumed inside the closure: the execution is alive for every read.
    /// app.execute(ExecOptions::new(), async |exec| {
    ///     let ticks = Ticks(exec.handle());
    ///     ticks.next().await.map(|_| ())
    /// })
    /// .await??;
    ///
    /// // Returned out of it: the execution has ended, and the next read is `ExecutionEnded`.
    /// let ticks = app.execute(ExecOptions::new(), async |exec| Ticks(exec.handle())).await?;
    /// assert!(matches!(ticks.next().await, Err(LookupError::ExecutionEnded { .. })));
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// An inherent `async fn`, so its future is `Send` whenever the closure's future is.
    pub async fn execute<F, R>(&self, opts: ExecOptions, f: F) -> Result<R, Closed>
    where
        F: AsyncFnOnce(&Execution) -> R,
    {
        let root = self.shared.graph().root;
        self.shared.execute(root, opts, f).await
    }

    /// Runs the shutdown sequence with no sockets to close: for a job, a CLI command or a test
    /// that stops after `connect()`.
    pub async fn close(self, signal: Signal) -> Result<Shutdown, ShutdownError> {
        shutdown::close(&self.shared, signal).await
    }
}

impl App<Bound> {
    pub fn handle(&self) -> AppHandle {
        AppHandle { shared: Arc::clone(&self.shared) }
    }

    /// Every address the bound transports listen on, in bind order: port 0 reports the port the
    /// OS chose (transports DESIGN §2.7, X6). Empty once the shutdown's close step has run, whatever
    /// each server's `close` returned: a close that timed out, errored or panicked releases its
    /// server too.
    pub fn addresses(&self) -> Vec<BoundAddr> {
        let servers = self.shared.servers.lock().unwrap_or_else(PoisonError::into_inner);
        servers.iter().flat_map(|server| server.bound()).collect()
    }

    /// Serves until `signal` resolves, a `close` on any handle, or a transport's `serve` ends,
    /// whichever comes first, then runs the shutdown sequence and returns its outcome (§9.5).
    ///
    /// Dropping the returned future releases the servers without running their `close`; see
    /// [`App`].
    ///
    /// Each transport's `Server::serve` is polled from here until the shutdown's outcome, so a
    /// transport keeps serving through the before-shutdown stage and the drain. One whose `serve`
    /// ends before any other trigger, returning `Err` or returning `Ok` while the app is running,
    /// starts the same shutdown under a signal naming the transport: every server is drained and
    /// closed and every hook runs, and the outcome is `Err` with
    /// [`ShutdownFailure::Serve`] naming that transport listed
    /// first, its error redacted, which every `close` caller receives too. A `serve` that panics
    /// is caught on each poll and ends the same way, as [`ServeEnd::Panicked`] holding the
    /// redacted message; the other servers drain and close as for an `Err`. A `serve` that ends once
    /// the shutdown has begun is not a failure.
    pub async fn serve(self, signal: impl Future<Output = Signal> + Send) -> Result<Shutdown, ShutdownError> {
        let shared = self.shared;
        let servers: Vec<Arc<dyn ErasedServer>> = shared.servers.lock().unwrap_or_else(PoisonError::into_inner).clone();
        let mut serving: Vec<Option<BoxFuture<'_, Result<(), BoxError>>>> =
            servers.iter().map(|server| Some(server.serve())).collect();

        let trigger = {
            let mut signal = pin!(signal);
            let mut triggered = shared.shutdown.triggered();
            poll_fn(|cx| {
                if let Poll::Ready(own) = signal.as_mut().poll(cx) {
                    return Poll::Ready(own);
                }
                // A `close` won; its sequence is already running, and `close` below joins it
                // whatever signal it is handed.
                if Pin::new(&mut triggered).poll(cx).is_ready() {
                    return Poll::Ready(shared.shutdown.winning_signal().unwrap_or_else(|| Signal::new("close")));
                }
                for (server, slot) in servers.iter().zip(serving.iter_mut()) {
                    let Some(fut) = slot else { continue };
                    let Poll::Ready(result) = poll_serve(fut, cx, &shared.graph().secrets) else { continue };
                    *slot = None;
                    let transport = server.transport_name();
                    let (signal, end, failed) = match result {
                        Err(panic) => {
                            let failed = format!("panicked: {panic}");
                            (Signal::new(format!("transport `{transport}` failed: {failed}")), ServeEnd::Panicked(panic), Some(failed))
                        }
                        Ok(Err(error)) => {
                            let reason = redact(&shared.graph().secrets, error);
                            let failed = reason.to_string();
                            (Signal::new(format!("transport `{transport}` failed: {failed}")), ServeEnd::Errored(reason), Some(failed))
                        }
                        Ok(Ok(())) => (Signal::new(format!("transport `{transport}` stopped serving")), ServeEnd::Returned, None),
                    };
                    // A trigger that arrived since `triggered` was polled wins, and this end is
                    // then part of that shutdown rather than its cause.
                    let won = shared.shutdown.trigger_with(signal.clone(), Some(ShutdownFailure::Serve { transport, end }));
                    if !won && let Some(failed) = failed {
                        discarded(transport, &failed);
                    }
                    return Poll::Ready(signal);
                }
                Poll::Pending
            })
            .await
        };

        let mut closing = pin!(shutdown::close(&shared, trigger));
        poll_fn(|cx| {
            for (server, slot) in servers.iter().zip(serving.iter_mut()) {
                if let Some(fut) = slot
                    && let Poll::Ready(result) = poll_serve(fut, cx, &shared.graph().secrets)
                {
                    *slot = None;
                    match result {
                        Ok(Ok(())) => {}
                        Ok(Err(error)) => discarded(server.transport_name(), &redact(&shared.graph().secrets, error).to_string()),
                        Err(panic) => discarded(server.transport_name(), &format!("panicked: {panic}")),
                    }
                }
            }
            closing.as_mut().poll(cx)
        })
        .await
    }
}

/// Polls one transport's `serve` inside `catch_unwind`: a panic is that transport's failure, an
/// `Err` holding the redacted payload. The future is dropped by the caller and never polled again.
fn poll_serve(
    fut: &mut BoxFuture<'_, Result<(), BoxError>>,
    cx: &mut Context<'_>,
    secrets: &SecretRegistry,
) -> Poll<Result<Result<(), BoxError>, Redacted>> {
    match catch_unwind(AssertUnwindSafe(|| fut.as_mut().poll(cx))) {
        Ok(poll) => poll.map(Ok),
        Err(payload) => Poll::Ready(Err(redact_panic(secrets, payload))),
    }
}

/// A `serve` that failed once another trigger had arrived: the outcome reports that trigger
/// alone, so the failure reaches the log and nothing else.
fn discarded(transport: TypeName, error: &str) {
    tracing::warn!(
        transport = %transport,
        error,
        "a transport's `serve` failed after the shutdown was triggered; the outcome reports the trigger alone"
    );
}