OXYGENHUB
◆ v0.9.11 oxygenhub / crates / hub / src / lib.rs
17.8 KiB · Rust · last changed Images that point at one of this hub's file pages render as the raw file (closes #346); a proposal's diffs over the API, GET …/proposals/N/diff (refs oxygenhub-android#4) 8 days ago source blame history raw
8d2caf12 Andy McCall ↶ 1
//! OxygenHub: a forge for Oxygen repositories (`docs/spec.md`).
d23464c0 Andy McCall ↶ 2
//!
e57765de Andy McCall ↶ 3
//! One process, or several sharing a database: an axum router serving
4
//! pages, the JSON API and the wire protocol (the web role); the background
5
//! tasks (the worker role, singletons under a leader lock: docs/roles.md);
6
//! SQLite or PostgreSQL for hub state; repositories as bare Oxygen stores.
d23464c0 Andy McCall ↶ 7
8
pub mod api;
ea85398a Andy McCall ↶ 9
pub mod apt;
e71846aa Andy McCall ↶ 10
pub mod assistants;
19bb31ff Andy McCall ↶ 11
pub mod auth;
86a69b53 Andy McCall ↶ 12
pub mod autoland;
d7d18246 Andy McCall ↶ 13
pub mod backups;
33d98147 Andy McCall 14
pub mod bus;
d23464c0 Andy McCall ↶ 15
pub mod config;
554ccacf Andy McCall ↶ 16
pub mod coverage;
d23464c0 Andy McCall ↶ 17
pub mod db;
f677d627 Andy McCall ↶ 18
pub mod diffusion;
166f6e9b Andy McCall 19
pub mod drops;
b64e2537 Andy McCall ↶ 20
pub mod events;
42fa9554 Andy McCall ↶ 21
pub mod flow;
d74ce22f Andy McCall ↶ 22
pub mod headers;
cb7b3cd4 Andy McCall ↶ 23
pub mod history_scan;
b64e2537 Andy McCall ↶ 24
pub mod hooks;
92a797b2 Andy McCall ↶ 25
pub mod images;
e97500b7 Andy McCall ↶ 26
pub mod insights;
0b203bbf Andy McCall ↶ 27
pub mod junit;
026a76d2 Andy McCall ↶ 28
pub mod keyless;
d23464c0 Andy McCall ↶ 29
pub mod keys;
e57765de Andy McCall ↶ 30
pub mod leader;
2a83f530 Andy McCall ↶ 31
pub mod levels;
5e6d6484 Andy McCall ↶ 32
pub mod live;
34beb1a7 Andy McCall ↶ 33
pub mod mail;
8a3334b7 Andy McCall ↶ 34
pub mod maintenance;
8a48dd83 Andy McCall ↶ 35
pub mod metrics;
3f4b0ea6 Andy McCall ↶ 36
pub mod mirror;
9a777fec Andy McCall ↶ 37
pub mod net;
18e381ea Andy McCall ↶ 38
pub mod notify;
d1727c57 Andy McCall ↶ 39
pub mod oidc;
d23464c0 Andy McCall ↶ 40
pub mod protocol;
076c7a7c Andy McCall ↶ 41
pub mod provenance;
aeed63c0 Andy McCall ↶ 42
pub mod push;
0ee5c3fb Andy McCall ↶ 43
pub mod push_protection;
dd327d76 Andy McCall ↶ 44
pub mod queue;
d23464c0 Andy McCall ↶ 45
pub mod render;
a36bab6b Andy McCall ↶ 46
pub mod reports;
d23464c0 Andy McCall ↶ 47
pub mod repos;
8501fd58 Andy McCall ↶ 48
pub mod runner_updates;
4ac01a73 Andy McCall ↶ 49
pub mod secrets;
c8684d44 Andy McCall 50
pub mod setup;
c92a9949 Andy McCall ↶ 51
pub mod shutdown;
83940d53 Andy McCall ↶ 52
pub mod signin;
89e89836 Andy McCall ↶ 53
pub mod social;
1f78655a Andy McCall ↶ 54
pub mod storage;
a46d15e7 Andy McCall ↶ 55
pub mod swarm;
ba0a55bb Andy McCall ↶ 56
pub mod tags;
8dcaeeb8 Andy McCall ↶ 57
pub mod terraform;
aa0bfbd1 Andy McCall ↶ 58
pub mod throttle;
965b950f Andy McCall ↶ 59
pub mod tlog;
2a83f530 Andy McCall ↶ 60
pub mod variables;
d23464c0 Andy McCall ↶ 61
pub mod web;
66fd9d6b Andy McCall ↶ 62
pub mod wiki;
d23464c0 Andy McCall ↶ 63
64
use crate::config::Config;
65
use crate::repos::Repos;
66
use std::sync::Arc;
67
68
/// Everything a request handler can reach.
69
pub struct App {
70
    pub config: Config,
71
    pub db: db::Pool,
72
    pub repos: Arc<Repos>,
66fd9d6b Andy McCall ↶ 73
    /// Wikis, one Oxygen repository per repository (hub spec §6.11).
74
    pub wikis: Arc<Repos>,
d23464c0 Andy McCall ↶ 75
    pub server: Arc<oxy_server::Server>,
76
    pub hub_key: keys::HubKey,
19bb31ff Andy McCall ↶ 77
    pub cookie_key: auth::CookieKey,
e71846aa Andy McCall ↶ 78
    /// Seals AI assistants' tokens at rest (hub spec §13.4).
79
    pub assistant_key: assistants::SecretKey,
4ac01a73 Andy McCall ↶ 80
    /// Seals Flow secrets at rest (hub spec §13.2, #107).
81
    pub secret_key: assistants::SecretKey,
d1727c57 Andy McCall ↶ 82
    /// The OIDC issuer for jobs (hub spec §13.5), made on first use.
83
    pub oidc: tokio::sync::OnceCell<oidc::Issuer>,
7d2eb590 Andy McCall ↶ 84
    /// Which assistants are answering which proposals, and recent calls
85
    /// per repository (hub spec §13.4).
86
    pub assistant_gate: std::sync::Mutex<assistants::Gate>,
aa0bfbd1 Andy McCall ↶ 87
    /// Failed sign-ins and the like, per account and address (oxygenhub#221).
88
    pub throttle: std::sync::Mutex<throttle::Throttle>,
33d98147 Andy McCall 89
    /// Events for live pages and workers, here and in the other processes
90
    /// sharing the database (docs/roles.md, #273).
91
    pub bus: bus::Bus,
5e6d6484 Andy McCall ↶ 92
    /// Who is resolving which conflict together (hub spec §6.10).
93
    pub rooms: Arc<live::Rooms>,
3556d08e Andy McCall ↶ 94
    /// Outgoing mail: hub.toml's `[email]`, overridden by what the admin
95
    /// page saved (#101).
96
    pub mail: std::sync::RwLock<config::Email>,
a46d15e7 Andy McCall ↶ 97
    /// The image swarm's tracker (oxygenhub#144).
98
    pub swarm: swarm::Tracker,
d23464c0 Andy McCall ↶ 99
    pub started: std::time::Instant,
965b950f Andy McCall ↶ 100
    /// The transparency log (#238).
101
    pub tlog: Arc<tlog::Log>,
e57765de Andy McCall ↶ 102
    /// What this process does: web, worker or both (docs/roles.md, #272).
103
    pub roles: config::Roles,
104
    /// The background tasks started here and the leader locks held (#272).
105
    pub leader: leader::Leader,
d23464c0 Andy McCall ↶ 106
}
107
d1727c57 Andy McCall ↶ 108
impl App {
92a797b2 Andy McCall ↶ 109
    /// The rootfs images this hub keeps for runners (oxygenflow#39).
110
    pub fn images(&self) -> images::Store {
111
        images::Store::new(&self.config.data)
112
    }
113
d1727c57 Andy McCall ↶ 114
    /// The OIDC issuer, its key loaded or made the first time it is asked for.
115
    pub async fn oidc(&self) -> anyhow::Result<&oidc::Issuer> {
116
        let keys = self.config.keys_dir();
117
        self.oidc.get_or_try_init(|| async move { tokio::task::spawn_blocking(move || oidc::Issuer::load_or_create(&keys)).await? }).await
118
    }
119
}
120
d23464c0 Andy McCall ↶ 121
pub type Shared = Arc<App>;
122
123
/// Open the data directory and build the application state. `init` must
124
/// have run once; `serve` and the tests call this.
125
pub async fn build(config: Config) -> anyhow::Result<Shared> {
e57765de Andy McCall ↶ 126
    let roles = config.roles()?;
70c3d029 Andy McCall ↶ 127
    // Images of this hub's file pages render as their raw files.
128
    render::markdown::set_origin(config.base_url());
d23464c0 Andy McCall ↶ 129
    std::fs::create_dir_all(config.repos_dir())?;
3b1bc27f Andy McCall 130
    let db = db::open(&config).await?;
d23464c0 Andy McCall ↶ 131
    let repos = Arc::new(Repos::new(config.repos_dir()));
66fd9d6b Andy McCall ↶ 132
    let wikis = Arc::new(Repos::new(config.data.join("wikis")));
d23464c0 Andy McCall ↶ 133
    let hub_key = keys::ensure_identity(&config.keys_dir(), &config.site.name, config.base_url())?;
19bb31ff Andy McCall ↶ 134
    let cookie_key = auth::CookieKey::load_or_create(&config.keys_dir())?;
e71846aa Andy McCall ↶ 135
    let assistant_key = assistants::SecretKey::load_or_create(&config.keys_dir())?;
4ac01a73 Andy McCall ↶ 136
    let secret_key = assistants::SecretKey::load_or_create_named(&config.keys_dir(), "secrets.key")?;
66fd9d6b Andy McCall ↶ 137
    let backend = protocol::HubBackend::new(
138
        repos.clone(),
139
        wikis.clone(),
140
        db.clone(),
141
        config.auth.push_tokens.clone(),
142
        tokio::runtime::Handle::current(),
3eb491e9 Andy McCall ↶ 143
    )
0ee5c3fb Andy McCall ↶ 144
    .with_acceptor(hub_key.identity.clone(), keys::load_secret(&config.keys_dir())?.1)
145
    .with_scan_budget(push_protection::Budget {
146
        bytes: config.limits.scan_limit.0,
147
        file: config.limits.scan_file_limit.0,
148
        time: std::time::Duration::from_millis(config.limits.scan_time_ms),
149
    });
18e381ea Andy McCall ↶ 150
    let slot = backend.app_slot();
d23464c0 Andy McCall ↶ 151
    let server = oxy_server::Server::new(backend);
3556d08e Andy McCall ↶ 152
    let mail = mail::load(&db, &config.email).await;
e57765de Andy McCall ↶ 153
    // The web role appends to the log; a worker alone only reads it (#272).
154
    let (tlog_dir, origin) = (config.data.join("tlog"), tlog::origin_of(config.base_url()));
155
    let tlog = Arc::new(if roles.web { tlog::Log::open(&tlog_dir, &origin)? } else { tlog::Log::open_reader(&tlog_dir, &origin)? });
4f40eed0 Andy McCall ↶ 156
    tlog.configure(&config.tlog)?;
b64e2537 Andy McCall ↶ 157
    let app = Arc::new(App {
3556d08e Andy McCall ↶ 158
        mail: std::sync::RwLock::new(mail),
b64e2537 Andy McCall ↶ 159
        config,
160
        db,
161
        repos,
66fd9d6b Andy McCall ↶ 162
        wikis,
b64e2537 Andy McCall ↶ 163
        server,
164
        hub_key,
165
        cookie_key,
e71846aa Andy McCall ↶ 166
        assistant_key,
4ac01a73 Andy McCall ↶ 167
        secret_key,
d1727c57 Andy McCall ↶ 168
        oidc: tokio::sync::OnceCell::new(),
7d2eb590 Andy McCall ↶ 169
        assistant_gate: std::sync::Mutex::new(assistants::Gate::default()),
aa0bfbd1 Andy McCall ↶ 170
        throttle: std::sync::Mutex::new(throttle::Throttle::default()),
33d98147 Andy McCall 171
        bus: bus::Bus::default(),
5e6d6484 Andy McCall ↶ 172
        rooms: Arc::new(live::Rooms::default()),
a46d15e7 Andy McCall ↶ 173
        swarm: Default::default(),
b64e2537 Andy McCall ↶ 174
        started: std::time::Instant::now(),
965b950f Andy McCall ↶ 175
        tlog,
e57765de Andy McCall ↶ 176
        roles,
177
        leader: leader::Leader::default(),
b64e2537 Andy McCall ↶ 178
    });
18e381ea Andy McCall ↶ 179
    *slot.lock().unwrap() = Some(Arc::downgrade(&app));
33d98147 Andy McCall 180
    bus::start(&app).await?;
1f78655a Andy McCall ↶ 181
    storage::load(&app).await?;
554ccacf Andy McCall ↶ 182
    coverage::load(&app).await?;
36e5a9c1 Andy McCall ↶ 183
    junit::load(&app).await?;
c8df33a6 Andy McCall ↶ 184
    reports::load(&app).await?;
e57765de Andy McCall ↶ 185
    start_background(&app);
186
    setup::ensure(&app).await?;
187
    Ok(app)
188
}
189
190
/// Start this process's background tasks (docs/roles.md, #272). The
191
/// worker role's are singletons across every process sharing the database,
192
/// each run under its leader lock; the transparency log's checkpointer goes
193
/// with the web role, which appends to the log, and is a singleton too.
194
fn start_background(app: &Shared) {
195
    if app.roles.web {
196
        // The checkpointer signs the log this process appends to (#238).
197
        leader::run(app, "tlog.checkpointer", tlog::checkpointer);
198
    }
199
    if !app.roles.worker {
200
        return;
201
    }
202
    leader::run(app, "hooks.worker", hooks::worker);
203
    leader::run(app, "flow.reaper", flow::reaper);
204
    leader::run(app, "flow.scheduler", flow::scheduler);
205
    leader::run(app, "flow.placement", flow::placement);
206
    leader::run(app, "maintenance.nightly", maintenance::nightly);
439ecd87 Andy McCall ↶ 207
    leader::run(app, "projects.archiver", maintenance::archiver);
e57765de Andy McCall ↶ 208
    leader::run(app, "backups.scheduler", backups::scheduler);
209
    // The reverse pin index for repositories pushed before it existed (#148):
210
    // once, by whichever worker leads it first (idempotent if run again).
211
    leader::run(app, "diffusion.backfill", |app| async move { diffusion::backfill(&app).await });
0e04dfc2 Andy McCall ↶ 212
    // Mend the pin index and the bumps it drives (oxygenhub#210).
e57765de Andy McCall ↶ 213
    leader::run(app, "diffusion.reconciler", diffusion::reconciler);
cb7b3cd4 Andy McCall ↶ 214
    // Each repository's history scanned for secrets (#277), a budget at a
215
    // time, at low priority.
216
    leader::run(app, "secrets.history_scan", history_scan::worker);
dd327d76 Andy McCall ↶ 217
    // The durable work queue (#276): every worker takes its due items.
218
    app.leader.note("queue.worker");
219
    tokio::spawn(queue::worker(app.clone()));
e57765de Andy McCall ↶ 220
    // What each image is for, read or learned once (oxygenhub#173): safe
221
    // in every worker, so it takes no lock.
222
    app.leader.note("images.learn_archs");
93501da2 Andy McCall ↶ 223
    tokio::spawn({
224
        let app = app.clone();
225
        async move {
226
            match images::learn_archs(&app).await {
227
                Ok(n) if n > 0 => tracing::info!(images = n, "read the architecture of kept images"),
228
                Ok(_) => {}
229
                Err(e) => tracing::warn!(error = %e, "learning image architectures"),
230
            }
231
        }
232
    });
e57765de Andy McCall ↶ 233
}
234
235
/// The router this process serves: everything for the web role; for a
236
/// worker alone, `/health` and `/metrics`, so it can be watched.
237
pub fn router(app: Shared) -> axum::Router {
238
    if !app.roles.web {
239
        return worker_router(app);
240
    }
241
    full_router(app)
242
}
243
244
/// What a worker-only process answers: its health and its metrics.
245
fn worker_router(app: Shared) -> axum::Router {
246
    use axum::routing::get;
247
    let hsts = headers::hsts(app.config.base_url(), app.config.server.hsts_max_age);
248
    axum::Router::new()
249
        .route("/health", get(web::home::health))
250
        .route("/metrics", get(metrics::metrics))
251
        .with_state(app)
252
        .layer(axum::middleware::from_fn_with_state(hsts, headers::security_headers))
d23464c0 Andy McCall ↶ 253
}
254
255
/// The full router: pages, API, protocol and static assets.
e57765de Andy McCall ↶ 256
fn full_router(app: Shared) -> axum::Router {
9a8e3b44 Andy McCall ↶ 257
    let https = app_https(&app);
2cbf6f34 Andy McCall ↶ 258
    let hsts = headers::hsts(app.config.base_url(), app.config.server.hsts_max_age);
bff9106e Andy McCall ↶ 259
    web::router(app.clone())
260
        .layer(axum::middleware::from_fn_with_state(app, agent_requests))
261
        .layer(axum::middleware::from_fn(private_pages))
262
        .layer(axum::middleware::from_fn(slow_requests))
9a8e3b44 Andy McCall ↶ 263
        .layer(axum::middleware::from_fn_with_state(https, https_only))
2cbf6f34 Andy McCall ↶ 264
        .layer(axum::middleware::from_fn_with_state(hsts, headers::security_headers))
d23464c0 Andy McCall ↶ 265
}
266
9a8e3b44 Andy McCall ↶ 267
/// The site's https address, when it has one: what [`https_only`] redirects to.
268
fn app_https(app: &Shared) -> Option<String> {
269
    let base = app.config.base_url();
270
    base.starts_with("https://").then(|| base.trim_end_matches('/').to_string())
271
}
272
273
/// The scheme a proxy in front of the hub says the visitor used
274
/// (`X-Forwarded-Proto`, else Cloudflare's `CF-Visitor`); `None` for a
275
/// request made to the hub directly (runners and tools on its host).
276
fn forwarded_scheme(headers: &axum::http::HeaderMap) -> Option<String> {
277
    if let Some(p) = headers.get("x-forwarded-proto").and_then(|v| v.to_str().ok()) {
278
        return p.split(',').next().map(|s| s.trim().to_ascii_lowercase());
279
    }
280
    let visitor = headers.get("cf-visitor").and_then(|v| v.to_str().ok())?;
281
    serde_json::from_str::<serde_json::Value>(visitor).ok()?["scheme"].as_str().map(str::to_ascii_lowercase)
282
}
283
284
/// HTTPS only (oxygenhub#218): on a site whose address is https, a request
285
/// a proxy reports as plain http is sent to the https address (GET and
286
/// HEAD) or refused (anything else, so a form or a password is never taken
287
/// over http). Requests made to the hub directly carry no such report and
288
/// are untouched.
289
async fn https_only(
290
    axum::extract::State(https): axum::extract::State<Option<String>>,
291
    req: axum::extract::Request,
292
    next: axum::middleware::Next,
293
) -> axum::response::Response {
294
    use axum::response::IntoResponse;
295
    let Some(base) = https else { return next.run(req).await };
296
    if forwarded_scheme(req.headers()).as_deref() != Some("http") {
297
        return next.run(req).await;
298
    }
299
    let to = format!("{base}{}", req.uri().path_and_query().map(|p| p.as_str()).unwrap_or("/"));
300
    if matches!(*req.method(), axum::http::Method::GET | axum::http::Method::HEAD) {
301
        return axum::response::Redirect::permanent(&to).into_response();
302
    }
303
    (axum::http::StatusCode::BAD_REQUEST, format!("This site takes requests over HTTPS only: send it to {to}\n")).into_response()
304
}
305
bff9106e Andy McCall ↶ 306
/// A request made with a token its owner marked as an agent's runs with
307
/// that token's name in [`notify::AGENT`], so what the agent does is told
308
/// to its owner (oxygenhub#183).
309
async fn agent_requests(
310
    axum::extract::State(app): axum::extract::State<Shared>,
311
    req: axum::extract::Request,
312
    next: axum::middleware::Next,
313
) -> axum::response::Response {
314
    let token = req
315
        .headers()
316
        .get(axum::http::header::AUTHORIZATION)
317
        .and_then(|v| v.to_str().ok())
318
        .and_then(|v| v.strip_prefix("Bearer "))
d4a0043f Andy McCall ↶ 319
        .map(|t| t.trim().to_string());
bff9106e Andy McCall ↶ 320
    let agent = match token {
d4a0043f Andy McCall ↶ 321
        // A keyless agent's grant token (#253) is always an agent's.
322
        Some(t) if t.starts_with(keyless::GRANT_TOKEN_PREFIX) => db::accounts::agent_grant_by_token(&app.db, &auth::token_hash(&t))
323
            .await
324
            .ok()
325
            .flatten()
326
            .filter(|g| g.live(db::now_ms()))
327
            .map(|g| g.agent),
328
        Some(t) => db::accounts::token_by_hash(&app.db, &auth::token_hash(&t)).await.ok().flatten().filter(|t| t.agent).map(|t| t.name),
bff9106e Andy McCall ↶ 329
        None => None,
330
    };
331
    notify::AGENT.scope(agent, next.run(req)).await
332
}
333
39442b00 Andy McCall ↶ 334
/// Requests slower than this are logged, with their path (#145).
335
const SLOW: std::time::Duration = std::time::Duration::from_secs(2);
336
337
/// Log a slow request's method, path and time, so a slow page can be
338
/// found afterwards. Never the query, which may hold a token.
339
async fn slow_requests(req: axum::extract::Request, next: axum::middleware::Next) -> axum::response::Response {
340
    let (method, path) = (req.method().clone(), req.uri().path().to_string());
341
    let start = std::time::Instant::now();
342
    let res = next.run(req).await;
343
    let took = start.elapsed();
b9b74d99 Andy McCall ↶ 344
    metrics::observe(method.as_str(), &path, res.status().as_u16(), took.as_secs_f64());
39442b00 Andy McCall ↶ 345
    if took >= SLOW {
346
        tracing::warn!("slow request: {method} {path} took {:.1} s ({})", took.as_secs_f64(), res.status().as_u16());
347
    }
348
    res
349
}
350
33bd0bd4 Andy McCall ↶ 351
/// A page for a signed-in viewer is theirs alone: it may list private
352
/// repositories, and the dashboard's sky carries their activity (#157). An
353
/// HTML response to a request with a session cookie, which has not said
354
/// how to cache itself, says `private, no-store`, so no shared cache (a
355
/// proxy or a CDN in front of the hub) ever serves it to anyone else.
356
async fn private_pages(req: axum::extract::Request, next: axum::middleware::Next) -> axum::response::Response {
357
    use axum::http::header;
358
    let signed_in = req
359
        .headers()
360
        .get_all(header::COOKIE)
361
        .iter()
362
        .filter_map(|v| v.to_str().ok())
363
        .any(|c| c.split(';').any(|kv| kv.trim_start().starts_with("oxyhub=")));
364
    let mut res = next.run(req).await;
365
    let html = res.headers().get(header::CONTENT_TYPE).and_then(|v| v.to_str().ok()).is_some_and(|t| t.starts_with("text/html"));
366
    if signed_in && html && !res.headers().contains_key(header::CACHE_CONTROL) {
367
        res.headers_mut().insert(header::CACHE_CONTROL, header::HeaderValue::from_static("private, no-store"));
368
    }
369
    res
370
}
371
d23464c0 Andy McCall ↶ 372
/// Serve on the configured addresses until the process is told to stop.
373
pub async fn serve(app: Shared) -> anyhow::Result<()> {
374
    let router = router(app.clone());
375
    let http = app.config.bind_addr()?;
376
    let https = app.config.tls_bind_addr()?;
e57765de Andy McCall ↶ 377
    if http.is_none() && https.is_none() && app.roles.web {
d23464c0 Andy McCall ↶ 378
        anyhow::bail!("nothing to bind: set server.bind or server.tls_bind");
379
    }
e57765de Andy McCall ↶ 380
    tracing::info!("roles: {}", app.roles.names().join(", "));
c92a9949 Andy McCall ↶ 381
    // Installed first: from here a SIGTERM drains rather than kills.
382
    let signal = shutdown::on_signal()?;
d23464c0 Andy McCall ↶ 383
    let mut tasks = tokio::task::JoinSet::new();
384
    if let Some(addr) = http {
c92a9949 Andy McCall ↶ 385
        let listener = match shutdown::systemd_listener() {
386
            Some(l) => {
387
                tracing::info!("http on the socket systemd holds ({})", l.local_addr().map(|a| a.to_string()).unwrap_or_default());
388
                tokio::net::TcpListener::from_std(l)?
389
            }
390
            None => {
391
                tracing::info!("http on {addr}");
392
                tokio::net::TcpListener::bind(addr).await?
393
            }
394
        };
d23464c0 Andy McCall ↶ 395
        let r = router.clone();
60f11b71 Andy McCall ↶ 396
        tasks.spawn(async move {
c92a9949 Andy McCall ↶ 397
            axum::serve(listener, r.into_make_service_with_connect_info::<std::net::SocketAddr>())
398
                .with_graceful_shutdown(shutdown::stopping())
399
                .await
400
                .map_err(anyhow::Error::from)
60f11b71 Andy McCall ↶ 401
        });
d23464c0 Andy McCall ↶ 402
    }
403
    if let Some(addr) = https {
404
        let _ = rustls::crypto::ring::default_provider().install_default();
405
        let tls = axum_server::tls_rustls::RustlsConfig::from_pem_file(app.config.tls_cert(), app.config.tls_key())
406
            .await
407
            .map_err(|e| anyhow::anyhow!("loading TLS files: {e}"))?;
408
        tracing::info!("https on {addr}");
409
        let r = router.clone();
c92a9949 Andy McCall ↶ 410
        let handle = axum_server::Handle::new();
411
        let draining = handle.clone();
412
        tokio::spawn(async move {
413
            shutdown::stopping().await;
414
            draining.graceful_shutdown(Some(shutdown::DRAIN));
415
        });
60f11b71 Andy McCall ↶ 416
        tasks.spawn(async move {
417
            axum_server::bind_rustls(addr, tls)
c92a9949 Andy McCall ↶ 418
                .handle(handle)
60f11b71 Andy McCall ↶ 419
                .serve(r.into_make_service_with_connect_info::<std::net::SocketAddr>())
420
                .await
421
                .map_err(anyhow::Error::from)
422
        });
d23464c0 Andy McCall ↶ 423
    }
424
    tokio::select! {
e57765de Andy McCall ↶ 425
        // A worker with no address to serve on runs until it is stopped.
426
        r = tasks.join_next(), if !tasks.is_empty() => { r.transpose()?.transpose()?; Ok(()) }
c92a9949 Andy McCall ↶ 427
        _ = signal => {
428
            // The servers stop taking connections and finish what they
429
            // have; whatever is still running after DRAIN is cut off.
430
            let drained = tokio::time::timeout(shutdown::DRAIN, async { while tasks.join_next().await.is_some() {} }).await;
431
            if drained.is_err() {
432
                tracing::warn!("requests still running after {} s: stopping anyway", shutdown::DRAIN.as_secs());
433
            }
434
            tracing::info!("stopped");
435
            Ok(())
436
        }
d23464c0 Andy McCall ↶ 437
    }
438
}