Skip to main content

schedr_bin/
roles.rs

1//! The server roles as processes of their own (M2.1): `schedr master`, `schedr webserver` and
2//! `schedr worker`, and the pieces `schedr standalone` runs together in one process.
3//!
4//! - **master:** the gRPC service workers connect to and the master's loop, on the database
5//!   (Postgres, or SQLite on one host); it refuses an outdated schema (`schedr db migrate`
6//!   runs first) and picks commands up at once on Postgres (`LISTEN/NOTIFY`), else by polling.
7//! - **webserver:** the REST API on the same database.
8//! - **worker:** the agent, connected to `[worker] master_url`, and its log endpoint (the
9//!   webserver reads task logs from it), with log retention; no database.
10//!
11//! The internal links (worker โ†’ master, webserver โ†’ worker logs) use mTLS in `[tls] mode =
12//! "app"` (the default: each role needs `[tls] ca`, `cert` and `key`, read again when they
13//! change) and plain traffic in `mesh` mode, where a service mesh encrypts. SIGTERM and Ctrl-C
14//! stop a role (a worker drains first). See archive/PROJECT.md, Architecture: Components and roles.
15
16use std::collections::BTreeMap;
17use std::net::SocketAddr;
18use std::path::{Path, PathBuf};
19use std::time::Duration;
20
21use crate::ops::{Health, Ops, Starting, ops_line, serve_ops};
22use prometheus_client::registry::Registry;
23use schedr_agent::agent::{Agent, AgentSettings, NodeIdentity, ProcessExecutor};
24use schedr_agent::attempt::WorkerSetup;
25use schedr_agent::drain::DrainPeriods;
26use schedr_agent::fork::{ForkConfig, ForkServers};
27use schedr_agent::journal::Journal;
28use schedr_agent::logs::LogEndpoint;
29use schedr_agent::memory::{
30    MIN_BUDGET, MemoryWatch, Reserve, WORKER_RESERVE, budget, ceiling, cgroup_limit, show_size,
31};
32use schedr_agent::metrics::AgentMetrics;
33use schedr_agent::parse::ParseLimits;
34use schedr_agent::retention::{LogRetention, sweep_logs};
35use schedr_api::auth::Auth;
36use schedr_api::logs::HttpLogSource;
37use schedr_api::metrics::ApiMetrics;
38use schedr_api::{ApiState, router};
39use schedr_config::config::{HiddenLimits, Timings};
40use schedr_config::{AuthMode, AuthSection, Config, MemoryReserve, TlsMode};
41use schedr_db::{Backend, Database, SchemaStatus, redact_password};
42use schedr_master::core::{CoreError, MasterCore, Settings};
43use schedr_master::lease::{Leadership, Renewal};
44use schedr_master::metrics::MasterMetrics;
45use schedr_master::notifications::Notifications;
46use schedr_master::notifications::sender::{Backoff, Sender};
47use schedr_master::problems::{ProblemKind, Problems};
48use schedr_master::service::{Hub, LeaseLost};
49use schedr_proto::pb::master_client::MasterClient;
50use schedr_tls::{Protocol, Tls, TlsFiles, incoming};
51use tokio::net::TcpListener;
52use tokio::sync::watch;
53
54use crate::app::{AppError, describe_status, role_config};
55use crate::node::{MasterIdentity, heartbeat_master, new_master_id, webserver_node};
56use schedr_api::views::NodeView;
57use schedr_config::masked::masked;
58
59#[cfg(test)]
60mod tests;
61
62/// Completes once `stop` turns `true`: how every part of a role learns to stop.
63pub async fn until(mut stop: watch::Receiver<u32>) {
64    let _ = stop.wait_for(|requests| *requests > 0).await;
65}
66
67/// How long open requests get once a stop is asked for, before they are cut: an event stream
68/// never ends by itself, and a page reconnects to the next server (B26).
69pub const REQUESTS_GRACE: Duration = Duration::from_secs(3);
70
71/// `server` (shutting down gracefully on `stop`) until it ends; once `stop` asks, its open
72/// requests get `grace` and are then cut.
73///
74/// # Errors
75///
76/// As the server.
77pub async fn served(
78    server: impl std::future::IntoFuture<Output = std::io::Result<()>>,
79    stop: watch::Receiver<u32>,
80    grace: Duration,
81) -> std::io::Result<()> {
82    let server = server.into_future();
83    tokio::pin!(server);
84    tokio::select! {
85        done = &mut server => return done,
86        () = until(stop) => {}
87    }
88    if let Ok(done) = tokio::time::timeout(grace, server).await {
89        return done;
90    }
91    tracing::info!(
92        "open requests (the pages' event streams) cut {}s after the stop",
93        grace.as_secs()
94    );
95    Ok(())
96}
97
98/// How long what a worker starts may take, and how it is paced.
99#[must_use]
100pub fn worker_timeouts(config: &Config) -> schedr_agent::attempt::WorkerTimeouts {
101    schedr_agent::attempt::WorkerTimeouts {
102        runner_start: config.worker.runner_start_timeout,
103        fork_preload: config.worker.fork_server_preload_timeout,
104        cleanup: config.cleanup_timeout(),
105        resource_cleanup: config.worker.resource_cleanup_timeout,
106        sensor_max_wait: config.sensors.default_max_wait,
107        watcher_block_limit: config.watchers.block_limit,
108        watcher_import_limit: config.dags.parse_file_timeout,
109        watcher_memory_budget: config.watchers.memory_budget,
110        watcher_poke_overruns: config.watchers.poke_overruns,
111        output_drain: config.timings.output_drain_timeout,
112        fork_answer: config.timings.fork_answer_timeout,
113        fork_backoff: schedr_agent::fork::ForkBackoff {
114            first: config.timings.fork_backoff_first,
115            max: config.timings.fork_backoff_max,
116            reset_after: config.timings.fork_backoff_reset_after,
117        },
118        log_sweep: config.timings.log_sweep_interval,
119        orphan: schedr_agent::journal::OrphanWaits {
120            poll: config.timings.orphan_poll,
121            kill_wait: config.timings.orphan_kill_wait,
122        },
123        orphan_grace: config.timings.orphan_grace,
124        reconnect_first: config.timings.reconnect_backoff_first,
125        reconnect_max: config.timings.reconnect_backoff_max,
126        alive: config.timings.worker_alive_interval,
127        deregister: config.timings.deregister_wait,
128        drain_tick: config.timings.drain_tick,
129        stop_poll: config.timings.stop_poll,
130        connection_cancel_grace: config.timings.connection_job_cancel_grace,
131        accept_retry: config.timings.accept_retry,
132        master_sample_window: config.timings.master_sample_window,
133        clock_skew_warning: config.timings.clock_skew_warning,
134        results_per_journal_group: config.limits.results_per_journal_group,
135        starts_per_journal_group: config.limits.starts_per_journal_group,
136        result_resends: limit_u32(config.limits.result_resends),
137        result_resend_gap_max: limit_u32(config.limits.result_resend_gap_max),
138        unacked_messages_kept: config.limits.unacked_messages_kept,
139        unsent_connection_answers: config.limits.unsent_connection_answers,
140        task_connections_open: config.limits.task_connections_open,
141        watcher_log_backlog: config.limits.watcher_log_backlog,
142    }
143}
144
145/// A hidden limit as a `u32`, the largest when it doesn't fit.
146const fn limit_u32(limit: usize) -> u32 {
147    if limit > u32::MAX as usize {
148        u32::MAX
149    } else {
150        #[expect(clippy::cast_possible_truncation, reason = "checked just above")]
151        let limit = limit as u32;
152        limit
153    }
154}
155
156/// The master's notifications: `[notifications]` checked, with its sender's timings.
157#[derive(Debug, Clone)]
158pub struct MasterOutbox {
159    /// `[notifications]`, header values read from the environment.
160    pub settings: std::sync::Arc<Notifications>,
161    /// The waits between deliveries of a failing notification.
162    pub backoff: Backoff,
163    /// How often the sender looks for notifications to deliver.
164    pub poll: Duration,
165    /// Whether they are delivered: `dags test` keeps them, to list (its run notifies no one).
166    pub deliver: bool,
167    /// The most delivered in one pass (`SCHEDR_HIDDEN__MASTER__NOTIFICATIONS_PER_PASS`).
168    pub per_pass: u32,
169}
170
171/// `[notifications]` with the values its webhooks' headers read from `env`.
172///
173/// # Errors
174///
175/// [`AppError::BadArgument`] for a bad setting or a header's variable not set (the message
176/// names the key).
177pub fn master_outbox(
178    config: &Config,
179    env: &BTreeMap<String, String>,
180) -> Result<MasterOutbox, AppError> {
181    let mut settings =
182        Notifications::from_config(&config.notifications, env).map_err(AppError::BadArgument)?;
183    settings.max_body = config.limits.notification_body;
184    if let Some(path) = &config.notifications.ca_file {
185        let pem = std::fs::read(path).map_err(|e| {
186            AppError::BadArgument(format!(
187                "[notifications] ca_file: can't read `{}`: {e}",
188                path.display()
189            ))
190        })?;
191        // Checked here: the sender's client is built later, once the master serves.
192        match reqwest::Certificate::from_pem_bundle(&pem) {
193            Ok(certs) if !certs.is_empty() => {}
194            Ok(_) => {
195                return Err(AppError::BadArgument(format!(
196                    "[notifications] ca_file: `{}` holds no certificate",
197                    path.display()
198                )));
199            }
200            Err(e) => {
201                return Err(AppError::BadArgument(format!(
202                    "[notifications] ca_file: `{}` isn't PEM certificates: {e}",
203                    path.display()
204                )));
205            }
206        }
207        settings.extra_roots = Some(pem);
208    }
209    Ok(MasterOutbox {
210        settings: std::sync::Arc::new(settings),
211        backoff: Backoff {
212            first: config.timings.outbox_retry_first,
213            max: config.timings.outbox_retry_max,
214        },
215        poll: config.timings.outbox_poll,
216        deliver: true,
217        per_pass: u32::try_from(config.limits.notifications_per_pass).unwrap_or(u32::MAX),
218    })
219}
220
221/// The master's timing, from the configuration.
222#[must_use]
223pub fn master_settings(config: &Config) -> Settings {
224    Settings {
225        heartbeat_interval: config.timings.heartbeat_interval,
226        lease_timeout: config.timings.lease_timeout,
227        takeover_wait: config
228            .timings
229            .lease_period
230            .saturating_sub(config.timings.query_timeout),
231        cancel_grace: config.master.cancel_grace,
232        switch_off_after: config.watchers.switch_off_after,
233        max_queued_events: config.triggers.max_queued_events,
234        failing_after: config.triggers.failing_after,
235        sensor_max_wait: config.sensors.default_max_wait,
236        parse_job_timeout: config.master.parse_job_timeout,
237        code_wait: config.master.code_wait,
238        set_aside: config.timings.set_aside,
239        handed_call_min: config.timings.handed_call_min,
240        cleanup_move_wait: config.timings.cleanup_move_wait,
241        script_root_grace: config.timings.script_root_grace,
242        event_lookback: config.timings.event_lookback,
243        timings: schedr_master::core::MasterTimings {
244            round_gap: config.timings.round_gap,
245            notification_retry: config.timings.notification_retry,
246            alive: config.timings.master_alive_interval,
247            gauge_refresh: config.timings.gauge_refresh,
248            parse_retry_first: config.timings.parse_retry_first,
249            parse_retry_max: config.timings.parse_retry_max,
250            accept_retry: config.timings.accept_retry,
251            trigger_restart_backoff: config.timings.trigger_restart_backoff,
252            trigger_restart_backoff_max: config.timings.trigger_restart_backoff_max,
253        },
254        read_back: schedr_master::dispatch::ReadBack {
255            window: config.timings.read_back_window,
256            interval: config.timings.read_back_interval,
257        },
258        listen_retry: config.timings.listen_retry,
259        quiet: schedr_master::quiet::QuietSettings {
260            enabled: config.master.quiet_dags,
261        },
262        // At most 1 GiB (checked when the configuration is read).
263        max_message_size: usize::try_from(config.grpc.max_message_size).unwrap_or(usize::MAX),
264        max_instances: usize::try_from(config.mapping.max_instances).unwrap_or(usize::MAX),
265        messages_per_turn: config.limits.messages_per_turn,
266        backfill_max_runs: config.backfill.max_runs,
267        worker_report: schedr_master::core::ReportLimits {
268            records: config.limits.worker_report_records,
269            text: config.limits.worker_report_text,
270        },
271        retention: schedr_master::retention::RetentionSettings::from_config(
272            &config.retention,
273            config.timings.retention_interval,
274            config.limits.retention_batch,
275        ),
276        samples: schedr_master::samples::SampleSettings {
277            interval: config.timings.sample_interval,
278            minutes_kept: config.timings.samples_kept,
279            rollups_kept: config.timings.rollups_kept,
280            rollup_grace: config.timings.sample_rollup_grace,
281            node_heartbeat: config.timings.node_heartbeat,
282        },
283        // Standalone sets it: its webserver is this process.
284        with_webserver: false,
285        rounds: schedr_master::core::RoundLimits {
286            assignments: config.limits.assignments_per_round,
287            expiries: config.limits.expiries_per_round,
288            waiting_reasons: config.limits.waiting_reasons_per_round,
289            pending_reasons: config.limits.pending_reasons_per_round,
290            commands: u32::try_from(config.limits.commands_per_round).unwrap_or(u32::MAX),
291            scheduled_runs: config.limits.scheduled_runs_per_round,
292            started_instances: config.limits.started_instances_per_round,
293            retries: config.limits.retries_per_round,
294            planning_pass_runs: config.limits.runs_per_planning_pass,
295            run_of_runs: u32::try_from(config.limits.run_of_runs_per_pass).unwrap_or(u32::MAX),
296        },
297        for_future_tolerance: config.timings.for_future_tolerance,
298        code_retry_delay: config.timings.code_retry_delay,
299        failed_group_messages_per_turn: config.limits.failed_group_messages_per_turn,
300        worker_stream_buffer: config.limits.worker_stream_buffer,
301    }
302}
303
304/// Where task logs (and standalone's SQLite file) go: `[worker] data_dir`, else
305/// `$XDG_DATA_HOME/schedr`, else `~/.local/share/schedr`.
306///
307/// # Errors
308///
309/// [`AppError::BadArgument`] when none of them is set.
310pub fn data_dir(config: &Config, env: &BTreeMap<String, String>) -> Result<PathBuf, AppError> {
311    config
312        .worker
313        .data_dir
314        .clone()
315        .or_else(|| {
316            env.get("XDG_DATA_HOME")
317                .map(|d| PathBuf::from(d).join("schedr"))
318        })
319        .or_else(|| {
320            env.get("HOME")
321                .map(|h| PathBuf::from(h).join(".local/share/schedr"))
322        })
323        .ok_or_else(|| {
324            AppError::BadArgument("no data directory: set [worker] data_dir (or HOME)".to_owned())
325        })
326}
327
328/// The worker's memory watch, refused when it leaves a task less than [`MIN_BUDGET`].
329fn checked_memory(config: &Config, default_reserve: Reserve) -> Result<MemoryWatch, AppError> {
330    if let Some(budget) = config.worker.memory_budget
331        && budget < MIN_BUDGET
332    {
333        return Err(AppError::BadArgument(format!(
334            "[worker] memory_budget {} is too small for any task: give at least {}",
335            show_size(budget),
336            show_size(MIN_BUDGET)
337        )));
338    }
339    let limit = cgroup_limit(Path::new("/proc"), Path::new("/sys/fs/cgroup"))
340        .ok()
341        .flatten();
342    let memory = memory_watch(config, limit, default_reserve);
343    if config.worker.memory_budget.is_none()
344        && let Some(budget) = memory.budget
345        && budget < MIN_BUDGET
346    {
347        return Err(AppError::BadArgument(format!(
348            "[worker] memory_reserve leaves {} per task of the pod's {} limit: give at least {} \
349             (a smaller reserve, fewer slots, or more memory)",
350            show_size(budget),
351            show_size(limit.unwrap_or_default()),
352            show_size(MIN_BUDGET)
353        )));
354    }
355    Ok(memory)
356}
357
358/// Warns when a worker (or a standalone's) watches no directory (D476). Not an error: it starts
359/// and serves, but nothing is there to run, which a first start otherwise only shows as an empty
360/// UI. Only the roles that run a worker call it: `dags check` and `dags test` build agent
361/// settings too (a fork server's), for a path that isn't among the roots.
362/// A standalone's says `--dag-path` too (decision 488).
363pub(crate) fn warn_without_dag_roots(config: &Config, standalone: bool) -> bool {
364    let none = config.dag_roots.is_empty() && config.script_roots.is_empty();
365    if none {
366        let option = if standalone {
367            ", or start it with `--dag-path .` in their folder"
368        } else {
369            ""
370        };
371        tracing::warn!(
372            "no DAG directories: this worker watches none, so it has nothing to parse or run; \
373             set SCHEDR_DAG_PATH (or [dags] path) to the directories of your DAG files{option}"
374        );
375    }
376    none
377}
378
379/// The worker agent's settings, from the configuration; its journal is
380/// `<data_dir>/journal/<worker ID>` and its logs `<data_dir>/logs/<worker ID>` (other bytes
381/// than letters, digits, `-`, `_` and `.`, and a leading `.`, as `%XX`), so workers sharing a
382/// data directory never see each other's (retention, the log endpoint). Without `[worker]
383/// memory_reserve`, the task budgets leave `default_reserve` of the pod's limit out.
384///
385/// # Errors
386///
387/// [`AppError::BadArgument`] if the DAG interpreter isn't defined, the memory check interval
388/// is 0, or the memory budget (set, or what the reserve leaves) below [`MIN_BUDGET`].
389pub fn agent_settings(
390    config: &Config,
391    env: &BTreeMap<String, String>,
392    data_dir: &Path,
393    default_reserve: Reserve,
394) -> Result<AgentSettings, AppError> {
395    let python = config
396        .interpreters
397        .get(&config.dags.interpreter)
398        .map(|i| i.path.clone())
399        .ok_or_else(|| {
400            AppError::BadArgument(format!(
401                "the DAG interpreter `{}` isn't defined in [interpreters]",
402                config.dags.interpreter
403            ))
404        })?;
405    let worker_id = config
406        .worker
407        .id
408        .clone()
409        .or_else(|| env.get("HOSTNAME").cloned())
410        .unwrap_or_else(|| "localhost".to_owned());
411    let memory = checked_memory(config, default_reserve)?;
412    Ok(AgentSettings {
413        queues: config.worker.queues.clone(),
414        slots: config.worker.slots,
415        watcher_slots: config.watchers.slots,
416        setup: WorkerSetup {
417            timeouts: worker_timeouts(config),
418            roots: config
419                .dag_roots
420                .iter()
421                .map(|r| (r.name.clone(), r.path.clone()))
422                .collect(),
423            parse_only: config
424                .dag_roots
425                .iter()
426                .filter_map(|r| Some((r.name.clone(), r.only.clone()?)))
427                .collect(),
428            script_roots: config
429                .script_roots
430                .iter()
431                .map(|r| (r.name.clone(), r.path.clone()))
432                .collect(),
433            interpreters: config
434                .interpreters
435                .iter()
436                .map(|(name, interpreter)| (name.clone(), interpreter.path.clone()))
437                .collect(),
438            python,
439            agent_env: env.clone(),
440            pass_env: config.worker.pass_env.clone(),
441            log_dir: data_dir.join("logs").join(file_name(&worker_id)),
442            connection_dir: config
443                .worker
444                .connection_dir
445                .clone()
446                .unwrap_or_else(|| {
447                    schedr_agent::connection_env::default_dir(
448                        data_dir,
449                        Path::new("/dev/shm"),
450                        rustix::process::geteuid().as_raw(),
451                    )
452                })
453                .join(file_name(&worker_id)),
454            memory,
455            fork_server: fork_config(config),
456        },
457        poll_interval: config.dags.poll_interval,
458        settle_time: config.dags.settle_time,
459        journal_dir: data_dir.join("journal").join(file_name(&worker_id)),
460        code_dir: data_dir.join("code").join(file_name(&worker_id)),
461        drain: DrainPeriods {
462            grace: config.worker.termination_grace_period,
463            terminate_period: config.worker.drain_terminate_period,
464            report_period: config.timings.drain_report_period,
465            ack_wait: config.timings.drain_ack_wait,
466        },
467        // Known once the log endpoint listens (see [`log_endpoint`]).
468        log_endpoint: String::new(),
469        node: NodeIdentity {
470            process_id: crate::node::process_id().to_owned(),
471            config_json: masked(config).to_string(),
472        },
473        worker_id,
474        // Made by the role, which knows whether it has a database (`SecretPlan::stores`).
475        secrets: std::sync::Arc::new(schedr_agent::secrets::SecretStores::none()),
476    })
477}
478
479/// The DAG interpreter's fork server settings, when `fork_server = true`.
480pub(crate) fn fork_config(config: &Config) -> Option<ForkConfig> {
481    let interpreter = config.interpreters.get(&config.dags.interpreter)?;
482    interpreter.fork_server.then(|| ForkConfig {
483        interpreter: config.dags.interpreter.clone(),
484        preload: interpreter.preload.clone(),
485        import_retry: config.worker.fork_server_import_retry,
486    })
487}
488
489/// How the memory watchdog watches tasks: `[worker] memory_budget`, else (`limit` โˆ’ the
490/// reserve) รท slots, the reserve `[worker] memory_reserve` or `default_reserve`; without a
491/// budget or a limit it only measures.
492#[must_use]
493pub fn memory_watch(config: &Config, limit: Option<u64>, default_reserve: Reserve) -> MemoryWatch {
494    let reserve = config
495        .worker
496        .memory_reserve
497        .map_or(default_reserve, |reserve| match reserve {
498            MemoryReserve::Percent(percent) => Reserve::Percent(percent),
499            MemoryReserve::Size(bytes) => Reserve::Bytes(bytes),
500        });
501    MemoryWatch {
502        budget: budget(
503            config.worker.memory_budget,
504            limit,
505            config.worker.slots,
506            reserve,
507        ),
508        ceiling: limit.map(|limit| ceiling(limit, reserve)),
509        // The binary running the agent: `schedr task-exec` (decision 50).
510        task_exec: std::env::current_exe().ok(),
511        interval: config.timings.memory_check_interval,
512        ..MemoryWatch::default()
513    }
514}
515
516/// What the watchdog does, for the worker's startup line.
517#[must_use]
518pub fn memory_text(watch: &MemoryWatch) -> String {
519    match watch.budget {
520        Some(budget) => format!("memory budget {} per task", show_size(budget)),
521        None => "no memory limit found: task memory is measured, never limited".to_owned(),
522    }
523}
524
525/// `[worker] log_mode` as a mode (the loader checked it).
526#[must_use]
527pub fn log_mode(config: &Config) -> u32 {
528    schedr_config::config::log_mode(&config.worker.log_mode).unwrap_or(0o600)
529}
530
531/// Readies the worker's logs for `mode` (`[worker] log_mode`, B182), as it starts: the logs it creates
532/// get it, and its log directory and the logs already in it are given it.
533///
534/// # Errors
535///
536/// [`AppError::BadArgument`] when the directory or a log's mode can't be set.
537pub fn secure_logs(mode: u32, log_dir: &Path) -> Result<(), AppError> {
538    schedr_agent::process::set_log_mode(mode);
539    schedr_agent::process::secure_log_dir(log_dir, mode).map_err(|e| {
540        AppError::BadArgument(format!(
541            "can't set the mode of the logs in {}: {e}",
542            log_dir.display()
543        ))
544    })
545}
546
547/// The worker's log retention, from the configuration.
548#[must_use]
549pub const fn log_retention(config: &Config) -> LogRetention {
550    LogRetention {
551        max_age: config.worker.log_retention,
552        max_size: config.worker.log_max_size,
553    }
554}
555
556/// Where the webserver reaches this worker's log endpoint listening on `port`: `[worker]
557/// log_address` (else the host name), over https with TLS.
558#[must_use]
559pub fn log_endpoint(
560    config: &Config,
561    env: &BTreeMap<String, String>,
562    tls: bool,
563    port: u16,
564) -> String {
565    let host = config
566        .worker
567        .log_address
568        .clone()
569        .or_else(|| env.get("HOSTNAME").cloned())
570        .unwrap_or_else(|| "localhost".to_owned());
571    // An IPv6 address goes in brackets.
572    let host = if host.contains(':') && !host.starts_with('[') {
573        format!("[{host}]")
574    } else {
575        host
576    };
577    let scheme = if tls { "https" } else { "http" };
578    format!("{scheme}://{host}:{port}")
579}
580
581/// The role's TLS material by `[tls]`: none in `mesh` mode; in `app` mode the files, which
582/// must be configured and usable.
583///
584/// # Errors
585///
586/// [`AppError::BadArgument`] when a file isn't configured, or can't be read or used.
587pub fn role_tls(config: &Config) -> Result<Option<Tls>, AppError> {
588    if config.tls.mode == TlsMode::Mesh {
589        return Ok(None);
590    }
591    if config.tls.reload_interval.is_zero() {
592        return Err(AppError::BadArgument(
593            "[tls] reload_interval must be longer than 0s (e.g. \"30s\")".to_owned(),
594        ));
595    }
596    let file = |path: &Option<PathBuf>, key: &str| {
597        path.clone().ok_or_else(|| {
598            AppError::BadArgument(format!(
599                "[tls] mode is `app` (the default), which needs [tls] {key} \
600                 (SCHEDR_CONFIG__TLS__{}); or set [tls] mode = \"mesh\" behind a service mesh \
601                 that encrypts the traffic between pods",
602                key.to_uppercase()
603            ))
604        })
605    };
606    let files = TlsFiles {
607        ca: file(&config.tls.ca, "ca")?,
608        cert: file(&config.tls.cert, "cert")?,
609        key: file(&config.tls.key, "key")?,
610    };
611    Tls::load(files, &config.tls.worker_name, &config.tls.ui_name)
612        .map(|tls| {
613            tls.with_handshake_timeout(config.timings.handshake_timeout)
614                .with_handshakes_at_once(config.limits.tls_handshakes_at_once)
615        })
616        .map(Some)
617        .map_err(|e| AppError::BadArgument(e.to_string()))
618}
619
620/// Reads the role's certificates again every `[tls] reload_interval` until `stop`.
621fn watch_tls(tls: Option<&Tls>, config: &Config, stop: &watch::Receiver<u32>) {
622    if let Some(tls) = tls {
623        tokio::spawn(
624            tls.clone()
625                .watch(config.tls.reload_interval, until(stop.clone())),
626        );
627    }
628}
629
630/// `name` as one safe path component, different for different names: bytes other than
631/// letters, digits, `-`, `_` and `.` become `%XX`, and so does a leading `.`; an empty name is
632/// `%`.
633fn file_name(name: &str) -> String {
634    use std::fmt::Write as _;
635    if name.is_empty() {
636        return "%".to_owned();
637    }
638    let mut safe = String::new();
639    for (i, b) in name.bytes().enumerate() {
640        if b.is_ascii_alphanumeric() || b == b'-' || b == b'_' || (b == b'.' && i > 0) {
641            safe.push(char::from(b));
642        } else {
643            let _ = write!(safe, "%{b:02X}");
644        }
645    }
646    safe
647}
648
649/// Takes the worker's journal lock for as long as the returned file is open: one agent per
650/// worker ID and data directory.
651///
652/// # Errors
653///
654/// [`AppError::BadArgument`] if another agent holds it, or it can't be created.
655pub fn lock_journal(agent: &AgentSettings) -> Result<std::fs::File, AppError> {
656    let dir = &agent.journal_dir;
657    Journal::new(dir.clone()).lock().map_err(|e| {
658        if e.kind() == std::io::ErrorKind::WouldBlock {
659            AppError::BadArgument(format!(
660                "another schedr worker `{}` is using {}: give each worker on this host its own \
661                 [worker] id or data_dir",
662                agent.worker_id,
663                dir.display()
664            ))
665        } else {
666            AppError::BadArgument(format!(
667                "can't lock the journal in {}: {e} (the data directory must be writable)",
668                dir.display()
669            ))
670        }
671    })
672}
673
674/// Binds a TCP listener.
675///
676/// # Errors
677///
678/// [`AppError::BadArgument`] if the address can't be bound.
679pub async fn listen(address: SocketAddr) -> Result<TcpListener, AppError> {
680    TcpListener::bind(address)
681        .await
682        .map_err(|e| AppError::BadArgument(format!("can't listen on {address}: {e}")))
683}
684
685/// Starts the notification sender, unless `outbox` keeps them (`dags test`). Its HTTP client
686/// is built there, off the way to ready (loading TLS roots takes a while).
687fn spawn_sender(
688    hub: &Hub,
689    (db, metrics): (Database, MasterMetrics),
690    outbox: MasterOutbox,
691    stop: watch::Receiver<u32>,
692) {
693    if !outbox.deliver {
694        return;
695    }
696    let hub = hub.clone();
697    tokio::spawn(async move {
698        match Sender::new(db, outbox.settings, metrics, outbox.backoff) {
699            Ok(sender) => {
700                let sender = sender.with_per_pass(outbox.per_pass);
701                hub.run_sender(sender, outbox.poll, until(stop)).await;
702            }
703            Err(error) => tracing::error!(%error, "notifications can't be sent"),
704        }
705    });
706}
707
708/// Serves the master: its gRPC service on `listener` (over mTLS with `tls`) and its loop,
709/// until `stop`, once `leadership` has taken the lease (a standby waits there).
710///
711/// # Errors
712///
713/// [`AppError`] if the gRPC server fails, the lease can't be taken, or another master took it
714/// over.
715#[expect(clippy::too_many_arguments, reason = "the parts of one role, named")]
716pub async fn serve_master(
717    db: Database,
718    settings: Settings,
719    (tick, problems, (max_event_size, api_limits), outbox): (
720        Duration,
721        Problems,
722        (usize, schedr_api::state::ApiLimits),
723        MasterOutbox,
724    ),
725    listener: TcpListener,
726    tls: Option<Tls>,
727    leadership: impl Future<Output = Result<Leadership, AppError>>,
728    observed: Observed<'_, MasterMetrics>,
729    stop: watch::Receiver<u32>,
730) -> Result<(), AppError> {
731    // Nothing of the master's before the lease: a standby waits here, its readiness
732    // "starting".
733    let leadership = tokio::select! {
734        taken = leadership => taken?,
735        () = until(stop.clone()) => return Ok(()),
736    };
737    tracing::info!(
738        epoch = leadership.epoch(),
739        holder = leadership.holder(),
740        "schedr master: leading (the lease is this master's)"
741    );
742    let connections = incoming(listener, tls, Protocol::Grpc, settings.timings.accept_retry)
743        .map_err(|e| AppError::BadArgument(format!("gRPC server: {e}")))?;
744    let listen_retry = settings.listen_retry;
745    let retention = settings.retention;
746    let sampling = (settings.samples, settings.with_webserver);
747    let (notifications, retry) = match db.command_notifications().await {
748        Ok(notifications) => (notifications, false),
749        Err(error) => {
750            tracing::warn!(
751                %error,
752                "can't listen for commands; polling every tick, trying again in {} min",
753                listen_retry.as_secs() / 60
754            );
755            problems.set(
756                ProblemKind::Notifications,
757                false,
758                format!("it can't listen for commands ({error}): polling"),
759            );
760            (None, true)
761        }
762    };
763    // Tasks' requests to the API (M4.11h): answered in one message to their worker, with room
764    // for its envelope.
765    // Fenced as the master's writes: a call checked before another master took over writes
766    // nothing after (Codex's review).
767    let task_api = crate::task_api::RouterTaskApi::new(
768        leadership.fenced_db(),
769        (max_event_size, api_limits),
770        settings.max_message_size.saturating_sub(4096),
771    );
772    // Its writes through the lease: refused once another master took it over.
773    let sending = (leadership.fenced_db(), observed.metrics.clone());
774    let mut hub = Hub::new(
775        MasterCore::new(leadership.fenced_db(), settings)
776            .with_metrics(observed.metrics)
777            .with_task_api(std::sync::Arc::new(task_api))
778            .with_notifications(outbox.settings.clone()),
779    )
780    .with_refresh_limit(observed.health.stall() / 2)
781    .with_epoch(leadership.epoch())
782    .with_problems(problems);
783    if retry {
784        hub = hub.with_listen_retry(listen_retry);
785    }
786    observed.health.watch_loop("scheduling loop", hub.beat());
787    let restored = hub.restore().await.map_err(|e| match e {
788        CoreError::Db(db) => AppError::Db(db),
789        other => AppError::BadArgument(format!("can't read the worker registry: {other}")),
790    })?;
791    if restored > 0 {
792        tracing::info!(
793            restored,
794            "workers restored as disconnected; their leases start once a deposed master can no \
795             longer answer them"
796        );
797    }
798    observed.ready.ready();
799    // Ready only while leading (B165): a paused master, or one whose lease was taken over,
800    // gets no new workers from a Service, as a standby gets none.
801    tokio::spawn({
802        let (ready, mut leading) = (observed.ready.clone(), hub.leading());
803        async move {
804            loop {
805                ready.set(*leading.borrow_and_update());
806                if leading.changed().await.is_err() {
807                    break;
808                }
809            }
810        }
811    });
812    spawn_sender(&hub, sending, outbox, stop.clone());
813    tokio::spawn({
814        let (hub, stop) = (hub.clone(), stop.clone());
815        async move { hub.run_retention(retention, until(stop)).await }
816    });
817    tokio::spawn({
818        let (hub, stop) = (hub.clone(), stop.clone());
819        let own = (crate::node::process_id().to_owned(), sampling.1);
820        async move { hub.run_samples(sampling.0, own, until(stop)).await }
821    });
822    let grpc = tonic::transport::Server::builder()
823        .add_service(hub.service())
824        .serve_with_incoming_shutdown(connections, until(stop.clone()));
825    let master_loop = hub.run_leading(tick, notifications, leadership, until(stop));
826    tokio::pin!(grpc, master_loop);
827    // The server ends first only by failing (both end together on `stop`): the role must
828    // then end too, not go on with a loop no worker can reach.
829    tokio::select! {
830        result = &mut grpc => {
831            result.map_err(|e| AppError::BadArgument(format!("gRPC server: {e}")))?;
832            // Stopped (the server ends cleanly only on `stop`): the loop ends on the same stop
833            // and gives the lease up. Awaited, or the process could exit first and the next
834            // start wait the lease out as a standby.
835            master_loop.await.map_err(|lost| AppError::BadArgument(lost.to_string()))
836        }
837        ended = &mut master_loop => {
838            // The workers' streams ended, or the server's graceful shutdown waits for them
839            // forever (B200).
840            hub.close_streams().await;
841            ended.map_err(|lost| AppError::BadArgument(lost.to_string()))?;
842            grpc.await.map_err(|e| AppError::BadArgument(format!("gRPC server: {e}")))
843        }
844    }
845}
846
847/// The deployments `[ui] deployments` names, each with a client of its webserver's API.
848///
849/// # Errors
850///
851/// [`AppError::BadArgument`] for none, a name that isn't letters, digits, `-` and `_`, a name
852/// given twice, an unreadable token file, or an `https://` URL (a webserver's UI port, over
853/// mTLS) without `tls`.
854pub fn ui_deployments(
855    config: &Config,
856    tls: Option<&Tls>,
857) -> Result<Vec<schedr_ui::Deployment<schedr_client::HttpTransport>>, AppError> {
858    let listed = &config.ui.deployments;
859    if listed.is_empty() {
860        return Err(AppError::BadArgument(
861            "`schedr ui` shows deployments: list them in [ui] deployments \
862             ([[ui.deployments]] name = \"etl\", url = \"http://schedr-webserver.etl.svc:8080\")"
863                .to_owned(),
864        ));
865    }
866    let mut seen = std::collections::BTreeSet::new();
867    listed
868        .iter()
869        .map(|d| {
870            let plain = !d.name.is_empty()
871                && d.name
872                    .bytes()
873                    .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_');
874            if !plain {
875                return Err(AppError::BadArgument(format!(
876                    "[ui] deployments: `{}` must be letters, digits, `-` and `_` (it is in the \
877                     UI's URLs)",
878                    d.name
879                )));
880            }
881            if !seen.insert(d.name.as_str()) {
882                return Err(AppError::BadArgument(format!(
883                    "[ui] deployments: `{}` is listed twice",
884                    d.name
885                )));
886            }
887            let mut transport =
888                schedr_client::HttpTransport::new(&d.url, schedr_client::Auth::None)
889                    .with_timeouts(client_timeouts(config));
890            if let Some(path) = &d.token_file {
891                let token = schedr_api::auth::read_ui_token(path, config.timings.auth_recheck)
892                    .map_err(|e| {
893                        AppError::BadArgument(format!(
894                            "[ui] deployments: `{}`'s token_file: {e}",
895                            d.name
896                        ))
897                    })?;
898                transport = transport.with_ui_token(token);
899            }
900            if d.url.starts_with("https://") {
901                let tls = tls.ok_or_else(|| {
902                    AppError::BadArgument(format!(
903                        "[ui] deployments: `{}` is reached over mTLS (https://): set [tls] \
904                         mode = \"app\" with this UI's certificate ([tls] ca, cert, key), \
905                         named [tls] ui_name for the webserver",
906                        d.name
907                    ))
908                })?;
909                transport = transport.with_tls(tls.clone());
910            }
911            let proof = match (d.token_file.is_some(), d.url.starts_with("https://")) {
912                (false, false) => "none",
913                (true, false) => "token",
914                (false, true) => "mTLS",
915                (true, true) => "token and mTLS",
916            };
917            Ok(schedr_ui::Deployment {
918                name: d.name.clone(),
919                client: schedr_client::Client::new(
920                    transport,
921                    schedr_client::POLL_INTERVAL,
922                    config.timings.client_command_wait,
923                ),
924                proof,
925            })
926        })
927        .collect()
928}
929
930/// Runs `schedr ui`: the web UI over the webservers of `[ui] deployments`, until a signal.
931///
932/// # Errors
933///
934/// [`AppError::BadArgument`] for bad `[ui]` settings, a port that can't be bound, or the
935/// HTTP server failing.
936pub async fn ui(config: &Config) -> Result<(), AppError> {
937    // Certificates only where a deployment is reached over mTLS (`app` is the default mode).
938    let mtls = config
939        .ui
940        .deployments
941        .iter()
942        .any(|d| d.url.starts_with("https://"));
943    let tls = if mtls { role_tls(config)? } else { None };
944    let deployments = ui_deployments(config, tls.as_ref())?;
945    let stop = stop_on_signal();
946    watch_tls(tls.as_ref(), config, &stop);
947    let health = Health::new(config.timings.loop_stall_timeout);
948    let ready = health.starting("ui");
949    let ops = Ops::new(Registry::default(), health.clone());
950    start_ops(config, "ui", ops, &stop).await?;
951    let address = SocketAddr::new(config.ui.bind, config.ui.port);
952    let listener = listen(address).await?;
953    let bound = listener.local_addr().unwrap_or(address);
954    let auth = role_auth(
955        "ui",
956        &config.ui.auth,
957        bound,
958        None,
959        auth_timings(&config.timings, &config.limits),
960    )?;
961    if config.ui.auth.mode == AuthMode::None
962        && let Some(warning) =
963            no_auth_warning_for("the web UI", bound, "set [ui] bind = \"127.0.0.1\"")
964    {
965        tracing::warn!("{warning}");
966    }
967    let names: Vec<&str> = deployments.iter().map(|d| d.name.as_str()).collect();
968    tracing::info!(
969        "schedr ui: on http://{bound} (deployments: {})",
970        names.join(", ")
971    );
972    let app = schedr_ui::router(schedr_ui::Ui {
973        deployments,
974        docs_dir: docs_dir(config),
975        timings: ui_timings(&config.timings, &config.limits),
976        auth,
977        config: masked(config),
978        process_id: crate::node::process_id().to_owned(),
979        host: crate::node::host_name(),
980    });
981    ready.ready();
982    let server = axum::serve(listener, app).with_graceful_shutdown(until(stop.clone()));
983    served(server, stop, config.timings.requests_grace)
984        .await
985        .map_err(|e| AppError::BadArgument(format!("HTTP server: {e}")))
986}
987
988/// The web UI `schedr standalone` serves next to its API, over its own deployment.
989#[derive(Debug, Clone, PartialEq, Eq)]
990pub struct LocalUi {
991    /// The documentation site, when there is one (see [`docs_dir`]).
992    pub docs_dir: Option<PathBuf>,
993    /// How its live pages are paced.
994    pub timings: schedr_ui::live::UiTimings,
995}
996
997/// How long the UI waits for its webservers (`SCHEDR_HIDDEN__CLIENT__*`, decision 493).
998#[must_use]
999pub const fn client_timeouts(config: &Config) -> schedr_client::Timeouts {
1000    schedr_client::Timeouts {
1001        connect: config.timings.client_connect_timeout,
1002        request: config.timings.client_request_timeout,
1003        command_wait: config.timings.client_command_wait,
1004    }
1005}
1006
1007/// How a UI's live pages are paced, by `timings`, and how far a browser may fall behind.
1008#[must_use]
1009pub const fn ui_timings(timings: &Timings, limits: &HiddenLimits) -> schedr_ui::live::UiTimings {
1010    schedr_ui::live::UiTimings {
1011        keep_alive: timings.ui_keep_alive,
1012        coalesce: timings.ui_coalesce,
1013        tail_interval: timings.ui_tail_interval,
1014        tail_give_up: timings.ui_tail_give_up,
1015        slow_read: timings.ui_slow_read,
1016        slow_read_wait: timings.ui_slow_read_wait,
1017        retry_first: timings.ui_relay_retry_first,
1018        retry_max: timings.ui_relay_retry_max,
1019        backlog: limits.ui_events_backlog,
1020    }
1021}
1022
1023/// How the users and the UI's token are followed, by `timings`, and how much is remembered.
1024#[must_use]
1025pub const fn auth_timings(
1026    timings: &Timings,
1027    limits: &HiddenLimits,
1028) -> schedr_api::auth::AuthTimings {
1029    schedr_api::auth::AuthTimings {
1030        recheck: timings.auth_recheck,
1031        remembered: timings.auth_remembered,
1032        remembered_max: limits.auth_remembered_max,
1033    }
1034}
1035
1036/// The name of the deployment `schedr standalone`'s UI shows (in its URLs).
1037pub const LOCAL_DEPLOYMENT: &str = "default";
1038
1039/// `[ui] docs_dir` when it is a directory; `None` otherwise (`""`, or not there: no `/docs`).
1040#[must_use]
1041pub fn docs_dir(config: &Config) -> Option<PathBuf> {
1042    let dir = &config.ui.docs_dir;
1043    (!dir.as_os_str().is_empty() && dir.is_dir()).then(|| dir.clone())
1044}
1045
1046/// How long the webserver waits and refreshes.
1047#[derive(Debug, Clone, Copy)]
1048pub struct ApiTimings {
1049    /// How the database's changes are followed.
1050    pub events: schedr_api::events::EventTimings,
1051    /// How long open requests get once a stop is asked for (`requests_grace`).
1052    pub requests_grace: Duration,
1053    /// How long its listener waits after a failed accept (`accept_retry`).
1054    pub accept_retry: Duration,
1055    /// `refresh_interval`.
1056    pub refresh: Duration,
1057    /// `worker_connect_timeout`.
1058    pub worker_connect: Duration,
1059    /// `worker_request_timeout`.
1060    pub worker_request: Duration,
1061    /// `connection_test_timeout`.
1062    pub connection_test: Duration,
1063    /// The workers' heartbeat interval: the slack before a poke trigger counts as stuck.
1064    pub heartbeat: Duration,
1065    /// `[events] max_size`.
1066    pub max_event_size: usize,
1067    /// How far its reads reach and what they allow (decision 493).
1068    pub limits: schedr_api::state::ApiLimits,
1069    /// Its Metrics cache's (decision 493).
1070    pub cache: schedr_api::series::cache::CacheLimits,
1071    /// How long its own UI waits for a command's decision (`CLIENT__COMMAND_WAIT`).
1072    pub command_wait: Duration,
1073}
1074
1075impl ApiTimings {
1076    /// The ones `config` sets.
1077    #[must_use]
1078    pub fn of(config: &Config) -> Self {
1079        let signed = |duration: Duration| {
1080            jiff::SignedDuration::try_from(duration).unwrap_or(jiff::SignedDuration::MAX)
1081        };
1082        Self {
1083            requests_grace: config.timings.requests_grace,
1084            accept_retry: config.timings.accept_retry,
1085            events: schedr_api::events::EventTimings {
1086                recheck: config.timings.events_recheck,
1087                keep_alive: config.timings.events_keep_alive,
1088                retry: config.timings.events_retry,
1089                changes_poll: config.timings.changes_poll_interval,
1090                changes_rows: config.limits.changes_poll_rows,
1091                backlog: config.limits.webserver_events_backlog,
1092            },
1093            refresh: config.timings.refresh_interval,
1094            worker_connect: config.timings.worker_connect_timeout,
1095            worker_request: config.webserver.worker_request_timeout,
1096            connection_test: config.webserver.connection_test_timeout,
1097            heartbeat: config.timings.heartbeat_interval,
1098            #[expect(
1099                clippy::cast_possible_truncation,
1100                reason = "a size in bytes, a few MiB, on a 64-bit host"
1101            )]
1102            max_event_size: config.events.max_size as usize,
1103            limits: schedr_api::state::ApiLimits {
1104                memory_peaks_window: signed(config.timings.memory_peaks_window),
1105                memory_peaks_runs: u32::try_from(config.limits.memory_peaks_runs)
1106                    .unwrap_or(u32::MAX),
1107                event_future_tolerance: signed(config.timings.event_future_tolerance),
1108                masters_heard_within: signed(
1109                    config
1110                        .timings
1111                        .node_heartbeat
1112                        .saturating_mul(schedr_master::samples::MASTERS_HEARD_BEATS),
1113                ),
1114                sampled_within: signed(
1115                    config
1116                        .timings
1117                        .sample_interval
1118                        .saturating_mul(schedr_api::routes::SAMPLED_INTERVALS),
1119                ),
1120            },
1121            cache: schedr_api::series::cache::CacheLimits {
1122                final_after: signed(config.timings.metrics_final_after),
1123                keys: config.limits.metrics_cache_keys,
1124                buckets: config.limits.metrics_cache_buckets,
1125            },
1126            command_wait: config.timings.client_command_wait,
1127        }
1128    }
1129}
1130
1131/// Serves the REST API on `listener` until `stop`, reading task logs from workers (over mTLS
1132/// with `tls`), showing this webserver as `node` (`GET /api/v1/deployment`); with `ui`, the
1133/// web UI too, at `/`, calling this API in process.
1134///
1135/// # Errors
1136///
1137/// [`AppError::BadArgument`] if the HTTP server fails.
1138pub async fn serve_api(
1139    db: Database,
1140    (auth, timings, node): (Auth, ApiTimings, NodeView),
1141    (listener, ui_port): (TcpListener, Option<TcpListener>),
1142    tls: Option<Tls>,
1143    ui: Option<LocalUi>,
1144    observed: Observed<'_, ApiMetrics>,
1145    stop: watch::Receiver<u32>,
1146) -> Result<(), AppError> {
1147    // Its pages ask the person to sign in: the UI's token opens only the API.
1148    let ui_auth = auth.without_ui_token();
1149    let ui_config = node.config.clone();
1150    // Its UI runs in this process: drawn inside it.
1151    let (ui_process, ui_host) = (node.process_id.clone(), node.host.clone());
1152    let state = ApiState::new(db, None)
1153        .with_auth(auth)
1154        .with_event_timings(timings.events)
1155        .with_refresh(timings.refresh)
1156        .with_node(node)
1157        .with_usage(schedr_agent::memory::this_node)
1158        .with_logs(std::sync::Arc::new(
1159            HttpLogSource::new(tls.clone())
1160                .with_timeouts(timings.worker_connect, timings.worker_request),
1161        ))
1162        .with_connection_test_timeout(timings.connection_test)
1163        .with_heartbeat_interval(timings.heartbeat)
1164        .with_max_event_size(timings.max_event_size)
1165        .with_limits(timings.limits, timings.cache)
1166        .with_metrics(observed.metrics);
1167    observed.ready.ready();
1168    let api = router(state);
1169    let app = match ui {
1170        Some(local) => {
1171            let client = schedr_client::Client::new(
1172                schedr_client::RouterTransport::new(api.clone()),
1173                schedr_client::POLL_INTERVAL,
1174                timings.command_wait,
1175            );
1176            let deployments = vec![schedr_ui::Deployment {
1177                name: LOCAL_DEPLOYMENT.to_owned(),
1178                client,
1179                proof: "in process",
1180            }];
1181            // One port: its pages sign in as its API does (`[webserver.auth]`).
1182            api.clone().merge(schedr_ui::router(schedr_ui::Ui {
1183                deployments,
1184                docs_dir: local.docs_dir,
1185                timings: local.timings,
1186                auth: ui_auth,
1187                config: ui_config,
1188                process_id: ui_process,
1189                host: ui_host,
1190            }))
1191        }
1192        None => api.clone(),
1193    };
1194    let http = |e: std::io::Error| AppError::BadArgument(format!("HTTP server: {e}"));
1195    let public = served(
1196        axum::serve(listener, app).with_graceful_shutdown(until(stop.clone())),
1197        stop.clone(),
1198        timings.requests_grace,
1199    );
1200    // The UI port: the same API, its requests marked proven (decision 36): in `app` mode only
1201    // `schedr ui`'s certificate gets through the handshake; in `mesh` mode
1202    // (`ui_port_in_mesh`) the mesh's policy lets only `schedr ui` reach it (40A).
1203    let Some(ui_listener) = ui_port else {
1204        return public.await.map_err(http);
1205    };
1206    let proven = api.layer(axum::middleware::map_request(
1207        |mut request: axum::extract::Request| async move {
1208            request.extensions_mut().insert(schedr_api::auth::ProvenUi);
1209            request
1210        },
1211    ));
1212    let connections =
1213        incoming(ui_listener, tls, Protocol::Ui, timings.accept_retry).map_err(http)?;
1214    let ui_server = served(
1215        axum::serve(connections, proven).with_graceful_shutdown(until(stop.clone())),
1216        stop,
1217        timings.requests_grace,
1218    );
1219    tokio::try_join!(public, ui_server).map_err(http)?;
1220    Ok(())
1221}
1222
1223/// How a part of a role is observed: its metrics (registered by the caller), the health it
1224/// reports its loops to, and the readiness it sets once started.
1225#[derive(Debug)]
1226pub struct Observed<'a, M> {
1227    /// The part's metrics.
1228    pub metrics: M,
1229    /// The role's health.
1230    pub health: &'a Health,
1231    /// The part's readiness.
1232    pub ready: Starting,
1233}
1234
1235/// How a worker reaches the master and serves its logs.
1236#[derive(Debug)]
1237pub struct WorkerLinks {
1238    /// The master's gRPC URL.
1239    pub master_url: String,
1240    /// The TLS material (`app` mode), for both.
1241    pub tls: Option<Tls>,
1242    /// Where the log endpoint listens (`agent.log_endpoint` says how it is reached).
1243    pub log_listener: TcpListener,
1244    /// What logs to keep.
1245    pub retention: LogRetention,
1246    /// The largest message taken from the master (`[grpc] max_message_size`): an assignment
1247    /// carries another DAG's run result (Grok's review of M4.11d2).
1248    pub max_message_size: usize,
1249}
1250
1251/// Runs a worker agent connected to the master until it has drained after a stop request
1252/// (`stop` counts them; see [`schedr_agent::drain`]), with its log endpoint and log
1253/// retention beside it until then.
1254pub async fn run_worker(
1255    agent: AgentSettings,
1256    parse: ParseLimits,
1257    links: WorkerLinks,
1258    observed: Observed<'_, AgentMetrics>,
1259    stop: watch::Receiver<u32>,
1260) {
1261    let WorkerLinks {
1262        master_url,
1263        tls,
1264        log_listener,
1265        retention,
1266        max_message_size,
1267    } = links;
1268    let timeouts = agent.setup.timeouts;
1269    let endpoint = LogEndpoint {
1270        worker_id: agent.worker_id.clone(),
1271        log_dir: agent.setup.log_dir.clone(),
1272        journal: Journal::new(agent.journal_dir.clone()),
1273    };
1274    let (done, finished) = watch::channel(0);
1275    let logs = match incoming(
1276        log_listener,
1277        tls.clone(),
1278        Protocol::Http,
1279        timeouts.accept_retry,
1280    ) {
1281        Ok(connections) => Some(tokio::spawn(
1282            axum::serve(connections, schedr_agent::logs::router(endpoint.clone()))
1283                .with_graceful_shutdown(until(finished.clone()))
1284                .into_future(),
1285        )),
1286        Err(error) => {
1287            tracing::error!(%error, "can't serve task logs");
1288            None
1289        }
1290    };
1291    let sweeping = tokio::spawn(sweep_logs(
1292        endpoint.log_dir,
1293        endpoint.journal,
1294        retention,
1295        observed.metrics.clone(),
1296        timeouts.log_sweep,
1297        until(finished),
1298    ));
1299    if let Some(warning) = agent
1300        .drain
1301        .default_cleanup_warning(agent.setup.timeouts.cleanup)
1302    {
1303        tracing::warn!("{warning}");
1304    }
1305    let executor = ProcessExecutor {
1306        setup: agent.setup.clone(),
1307        parse,
1308        metrics: observed.metrics.clone(),
1309        drain_terminate_period: agent.drain.terminate_period,
1310        forks: ForkServers::for_worker(&agent.setup, &observed.metrics.fork),
1311        watchers: schedr_agent::watchers::WatcherHosts::with_metrics(
1312            observed.metrics.watchers.clone(),
1313        ),
1314        secrets: std::sync::Arc::clone(&agent.secrets),
1315        running_memory: schedr_agent::memory::RunningMemory::default(),
1316    };
1317    let mut agent = Agent::new(agent, executor, uuid::Uuid::now_v7().to_string())
1318        .with_metrics(observed.metrics);
1319    observed.health.watch_loop("worker agent", agent.beat());
1320    observed.ready.ready();
1321    agent
1322        .run(
1323            move || {
1324                let url = master_url.clone();
1325                let tls = tls.clone();
1326                async move {
1327                    schedr_tls::channel(&url, tls.as_ref())
1328                        .await
1329                        .map(|channel| {
1330                            MasterClient::new(channel).max_decoding_message_size(max_message_size)
1331                        })
1332                }
1333            },
1334            stop,
1335        )
1336        .await;
1337    let _ = done.send(1);
1338    let _ = sweeping.await;
1339    if let Some(Ok(Err(error))) = match logs {
1340        Some(logs) => Some(logs.await),
1341        None => None,
1342    } {
1343        tracing::warn!(%error, "the log endpoint failed");
1344    }
1345}
1346
1347/// Connects to the database of the master or the webserver, whatever its schema:
1348/// `[database] url` is required, SQLite is for one host (it warns).
1349///
1350/// # Errors
1351///
1352/// [`AppError::NoDatabase`] without a URL; [`AppError::Db`] if it can't be reached.
1353pub async fn connect_database(config: &Config, role: &str) -> Result<Database, AppError> {
1354    let url = config.database.url.as_deref().ok_or(AppError::NoDatabase)?;
1355    let db = Database::connect_with_timeout(url, config.timings.query_timeout)
1356        .await?
1357        .with_notifications(
1358            config.database.notifications,
1359            config.database.notifications_url.clone(),
1360        )
1361        .with_dag_versions_cached(config.limits.dag_versions_cached);
1362    if db.backend() == Backend::Sqlite {
1363        tracing::warn!(
1364            "schedr {role} on SQLite: every role must run on this host, on a local disk; \
1365             use Postgres for anything distributed"
1366        );
1367    }
1368    tracing::info!(database = %redact_password(url), "schedr {role}: database ready");
1369    Ok(db)
1370}
1371
1372/// How often a webserver checks again for a schema it can use.
1373pub const SCHEMA_RETRY: Duration = Duration::from_secs(5);
1374
1375/// Waits until `db`'s schema is usable by this binary, checking every `retry` and saying what
1376/// it waits for whenever that changes (the database unreachable, then a schema to migrate, โ€ฆ;
1377/// the master, or `schedr db migrate`, migrates it), so a webserver started before the
1378/// migration serves once it is done instead of failing.
1379///
1380/// # Errors
1381///
1382/// [`AppError::BadArgument`] for an earlier schedr's schema, which no migration makes usable.
1383pub async fn wait_for_schema(
1384    db: &Database,
1385    (role, place): (&str, &str),
1386    retry: Duration,
1387) -> Result<(), AppError> {
1388    const AGAIN: Duration = Duration::from_mins(1);
1389    let mut said: Option<(String, tokio::time::Instant)> = None;
1390    loop {
1391        let (waiting, error) = match db.schema_status().await {
1392            Ok(status) if status.is_usable() => return Ok(()),
1393            Ok(status @ SchemaStatus::Modified { .. }) => return Err(modified(&status)),
1394            Ok(status) => (describe_status(&status), false),
1395            // Codes only: the server's text may name the user (the review of M5.1q).
1396            Err(error) if error.is_transient() => {
1397                (format!("unreadable ({})", error.waiting_reason()), true)
1398            }
1399            // A setting that won't work (a password changed meanwhile) exits, as at connecting.
1400            Err(error) => return Err(AppError::Db(error)),
1401        };
1402        let now = tokio::time::Instant::now();
1403        // Said again when it changes, and an error every minute while it lasts.
1404        if said.as_ref().is_none_or(|(before, at)| {
1405            *before != waiting || (error && now.duration_since(*at) >= AGAIN)
1406        }) {
1407            let line = format!(
1408                "schedr {role}: the database schema at {place} is {waiting}; waiting for it \
1409                 (checked every {} s)",
1410                retry.as_secs()
1411            );
1412            if error {
1413                tracing::warn!("{line}");
1414            } else {
1415                tracing::info!("{line}");
1416            }
1417            said = Some((waiting, now));
1418        }
1419        tokio::time::sleep(retry).await;
1420    }
1421}
1422
1423/// `attempt`'s output once the database at `url` answers: while it fails because the database
1424/// can't be reached for now ([`schedr_db::DbError::is_transient`]: down, starting, busy, a time
1425/// limit), tried again every `retry`. A role starting before its database waits for it instead
1426/// of exiting (the user, 2026-11-15, after B247); a wrong host or port fails the same way, so the
1427/// warning names where it looks (the host and port, or the file: never the user or password)
1428/// and why (codes only), at once and again every minute while it waits. `None` once a shutdown
1429/// is asked for, before or during a try.
1430///
1431/// # Errors
1432///
1433/// `attempt`'s error when it isn't transient (a wrong URL, password or TLS setting).
1434pub async fn once_reached<T, F, Fut>(
1435    (role, url): (&str, &str),
1436    retry: Duration,
1437    mut stop: watch::Receiver<u32>,
1438    mut attempt: F,
1439) -> Result<Option<T>, AppError>
1440where
1441    F: FnMut() -> Fut,
1442    Fut: Future<Output = Result<T, AppError>>,
1443{
1444    const AGAIN: Duration = Duration::from_mins(1);
1445    let place = schedr_db::database_place(url);
1446    let mut said: Option<(String, tokio::time::Instant)> = None;
1447    loop {
1448        // A shutdown asked for before or during a try ends the wait: a try can stall (a
1449        // schema read on a connection that went quiet) as long as the database lets it.
1450        if *stop.borrow_and_update() > 0 {
1451            return Ok(None);
1452        }
1453        let tried = tokio::select! {
1454            tried = attempt() => tried,
1455            () = until(stop.clone()) => return Ok(None),
1456        };
1457        let error = match tried {
1458            Ok(done) => {
1459                if said.is_some() {
1460                    tracing::info!("schedr {role}: the database at {place} answers");
1461                }
1462                return Ok(Some(done));
1463            }
1464            Err(AppError::Db(error)) if error.is_transient() => error,
1465            Err(error) => return Err(error),
1466        };
1467        let why = error.waiting_reason();
1468        let now = tokio::time::Instant::now();
1469        if said
1470            .as_ref()
1471            .is_none_or(|(before, at)| *before != why || now.duration_since(*at) >= AGAIN)
1472        {
1473            tracing::warn!(
1474                "schedr {role}: can't reach the database at {place} ({why}); trying again every \
1475                 {} s. If the host or port is wrong, correct `[database] url`",
1476                retry.as_secs_f64()
1477            );
1478            said = Some((why, now));
1479        }
1480        tokio::select! {
1481            () = tokio::time::sleep(retry) => {}
1482            () = until(stop.clone()) => return Ok(None),
1483        }
1484    }
1485}
1486
1487/// The error for an earlier schedr's schema (B236), which no migration makes usable.
1488fn modified(status: &SchemaStatus) -> AppError {
1489    AppError::BadArgument(format!(
1490        "the database schema is {}",
1491        describe_status(status)
1492    ))
1493}
1494
1495/// The warning for the REST API listening on `address` beyond loopback: it has no
1496/// authentication of its own until the auth modes (M3.5). `alternative` says how to keep it
1497/// local.
1498#[must_use]
1499pub fn no_auth_warning(address: SocketAddr, alternative: &str) -> Option<String> {
1500    no_auth_warning_for("the REST API", address, alternative)
1501}
1502
1503/// As [`no_auth_warning`], for `what` (`the REST API`, `the web UI`).
1504#[must_use]
1505pub fn no_auth_warning_for(what: &str, address: SocketAddr, alternative: &str) -> Option<String> {
1506    (!address.ip().is_loopback()).then(|| {
1507        format!(
1508            "{what} signs no one in (auth mode `none`) and listens on {address}: keep it \
1509             behind an authenticating proxy or mesh, use the `proxy_header` or `basic` mode, \
1510             or {alternative}"
1511        )
1512    })
1513}
1514
1515/// Who the user is for the role `what` (`webserver`, `ui`) listening on `address`, by `section`; a
1516/// UI trusted by the token in `ui_token_file`. The safety rules (see archive/PROJECT.md,
1517/// Authentication): `proxy_header` beyond a loopback address only with `allow_remote` (anything
1518/// reaching it around the proxy could name any user), `basic` only with `behind_tls_proxy`
1519/// (passwords would cross the network in the clear).
1520///
1521/// # Errors
1522///
1523/// [`AppError::BadArgument`] when a rule refuses it, or the token or users can't be read.
1524pub fn role_auth(
1525    what: &str,
1526    section: &AuthSection,
1527    address: SocketAddr,
1528    ui_token_file: Option<&std::path::Path>,
1529    timings: schedr_api::auth::AuthTimings,
1530) -> Result<Auth, AppError> {
1531    let remote = !address.ip().is_loopback();
1532    match section.mode {
1533        AuthMode::ProxyHeader if remote && !section.allow_remote => {
1534            return Err(AppError::BadArgument(format!(
1535                "[{what}.auth] mode = \"proxy_header\" on {address}, beyond a loopback address: \
1536                 anything reaching it around the sign-in proxy could name any user. Listen on \
1537                 127.0.0.1 behind the proxy, or set [{what}.auth] allow_remote = true when only \
1538                 the proxy can reach it"
1539            )));
1540        }
1541        AuthMode::Basic if remote && !section.behind_tls_proxy => {
1542            return Err(AppError::BadArgument(format!(
1543                "[{what}.auth] mode = \"basic\" on {address}, beyond a loopback address, over \
1544                 plain HTTP: passwords would cross the network in the clear. End TLS in a proxy \
1545                 in front and set [{what}.auth] behind_tls_proxy = true, or listen on 127.0.0.1"
1546            )));
1547        }
1548        _ => {}
1549    }
1550    let token = ui_token_file
1551        .map(|path| {
1552            schedr_api::auth::read_ui_token(path, timings.recheck)
1553                .map_err(|e| AppError::BadArgument(format!("[webserver] ui_token_file: {e}")))
1554        })
1555        .transpose()?;
1556    Auth::from_config(section, token, timings)
1557        .map_err(|e| AppError::BadArgument(format!("[{what}.auth] {e}")))
1558}
1559
1560/// Checks `[worker] master_url` and returns its host: an `https://` URL with a host in `app`
1561/// mode (the master's certificate must name the host), an `http://` one in `mesh` mode.
1562///
1563/// # Errors
1564///
1565/// [`AppError::BadArgument`] for anything else, saying what is expected.
1566pub fn master_host(url: &str, mode: TlsMode) -> Result<String, AppError> {
1567    let (scheme, example, mode_name) = match mode {
1568        TlsMode::App => ("https", "https://schedr-master:8070", "app"),
1569        TlsMode::Mesh => ("http", "http://schedr-master:8070", "mesh"),
1570    };
1571    let bad = |why: &str| {
1572        AppError::BadArgument(format!(
1573            "[worker] master_url `{url}` {why}: give the master's gRPC URL, e.g. {example}"
1574        ))
1575    };
1576    let uri = url
1577        .parse::<tonic::transport::Uri>()
1578        .map_err(|_| bad("isn't a URL"))?;
1579    match uri.scheme_str() {
1580        Some(given) if given == scheme => {}
1581        Some("http" | "https") => {
1582            return Err(bad(&format!(
1583                "needs the {scheme}:// scheme with [tls] mode `{mode_name}`"
1584            )));
1585        }
1586        _ => return Err(bad(&format!("needs the {scheme}:// scheme"))),
1587    }
1588    uri.host()
1589        .map(str::to_owned)
1590        .ok_or_else(|| bad("has no host"))
1591}
1592
1593/// A count of stop requests (Ctrl-C or SIGTERM): the first stops a role (a worker drains), a
1594/// second makes a draining worker interrupt its tasks at once. The SIGTERM handler is
1595/// registered before this returns, so a SIGTERM right after start still stops the role
1596/// gracefully.
1597#[must_use]
1598pub fn stop_on_signal() -> watch::Receiver<u32> {
1599    let (stop, stopped) = watch::channel(0);
1600    let terminate = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate());
1601    tokio::spawn(async move {
1602        let mut terminate = terminate
1603            .map_err(|error| tracing::warn!(%error, "can't watch SIGTERM; Ctrl-C only"))
1604            .ok();
1605        let mut ctrl_c = true;
1606        loop {
1607            let sigterm = async {
1608                match &mut terminate {
1609                    Some(signal) => signal.recv().await,
1610                    None => std::future::pending().await,
1611                }
1612            };
1613            tokio::select! {
1614                watched = tokio::signal::ctrl_c(), if ctrl_c => {
1615                    if let Err(error) = watched {
1616                        tracing::warn!(%error, "can't watch Ctrl-C; SIGTERM only");
1617                        ctrl_c = false;
1618                        continue;
1619                    }
1620                }
1621                Some(()) = sigterm => {}
1622            }
1623            stop.send_modify(|requests| *requests += 1);
1624        }
1625    });
1626    stopped
1627}
1628
1629/// Waits for the master's lease (see [`Leadership::take`]) as `holder` (a new incarnation of
1630/// the master of `role`: [`crate::node::new_master_id`]), logging once that it waits as a
1631/// standby.
1632pub async fn take_lease(
1633    db: Database,
1634    period: Duration,
1635    role: &'static str,
1636    holder: String,
1637) -> Leadership {
1638    Leadership::take(db, holder, period, move || {
1639        tracing::info!("schedr {role}: another master holds the lease; waiting as a standby");
1640    })
1641    .await
1642}
1643
1644/// The master's lease, being taken (see [`take_lease`]).
1645pub type LeaseFuture = std::pin::Pin<Box<dyn Future<Output = Result<Leadership, AppError>> + Send>>;
1646
1647/// The master's lease for `role` (`master` or `standalone`), being taken while the role's
1648/// other parts start when the schema is usable; else, with `--migrate`, taken now (a standby
1649/// waits) and the schema migrated by its holder; taken as `holder` (the master's ID). `None`
1650/// when a shutdown is asked for while waiting. With `--migrate`, `[database] change_notifications` is applied by the holder.
1651///
1652/// # Errors
1653///
1654/// [`AppError::BadArgument`] for a schema to migrate without `--migrate`, as
1655/// [`migrate_holding`], or [`AppError::Db`] if the schema can't be read; the lease future
1656/// fails (the lease released) when the switch can't be applied to an up-to-date schema.
1657pub async fn lead(
1658    db: &Database,
1659    url: &str,
1660    (period, migrate, change_notifications): (Duration, bool, bool),
1661    (shutdown, retry): (watch::Receiver<u32>, Duration),
1662    (role, holder): (&'static str, String),
1663) -> Result<Option<LeaseFuture>, AppError> {
1664    // Read again while the database can't be reached (`retry` apart), as when connecting.
1665    let read = once_reached((role, url), retry, shutdown.clone(), || async {
1666        Ok(db.schema_status().await?)
1667    });
1668    let Some(status) = read.await? else {
1669        return Ok(None);
1670    };
1671    if status.is_usable() {
1672        let db = db.clone();
1673        return Ok(Some(Box::pin(async move {
1674            let mut lead = take_lease(db.clone(), period, role, holder).await;
1675            // `--migrate` on an up-to-date schema: the switch only, holding the lease; failing
1676            // as a migration does.
1677            if migrate
1678                && let Err(error) = while_holding(
1679                    &mut lead,
1680                    apply_change_notifications(&db, change_notifications),
1681                )
1682                .await
1683            {
1684                lead.release().await;
1685                return Err(error);
1686            }
1687            Ok(lead)
1688        })));
1689    }
1690    if let SchemaStatus::Modified { .. } = status {
1691        return Err(modified(&status));
1692    }
1693    if !migrate {
1694        return Err(AppError::BadArgument(format!(
1695            "the database schema is {}, or start {role} with `--migrate`",
1696            describe_status(&status)
1697        )));
1698    }
1699    let lease = take_lease(db.clone(), period, role, holder);
1700    let Some(lead) = until_stopped(lease, shutdown).await else {
1701        return Ok(None);
1702    };
1703    let lead = migrate_holding(lead, &unlimited(url, db).await?, change_notifications).await?;
1704    Ok(Some(Box::pin(std::future::ready(Ok(lead)))))
1705}
1706
1707/// `work`'s output, or `None` once a shutdown is asked for.
1708pub async fn until_stopped<T>(
1709    work: impl Future<Output = T>,
1710    stop: watch::Receiver<u32>,
1711) -> Option<T> {
1712    tokio::select! {
1713        done = work => Some(done),
1714        () = until(stop) => None,
1715    }
1716}
1717
1718/// `schedr db migrate`: migrates the database at `url` holding the master's lease, so no master
1719/// runs on the schema meanwhile and no other migration runs at once (sqlx's own lock is a
1720/// session lock, which a pooler in transaction mode doesn't keep). Refused while a master
1721/// holds it, unless `wait`.
1722///
1723/// # Errors
1724///
1725/// [`AppError::BadArgument`] when a master holds the lease (and not `wait`), else as
1726/// [`migrate_holding`].
1727pub async fn migrate_leased(
1728    url: &str,
1729    query_timeout: Duration,
1730    (period, wait): (Duration, bool),
1731    change_notifications: bool,
1732) -> Result<(), AppError> {
1733    let db = Database::connect_with_timeout(url, query_timeout).await?;
1734    let unlimited = unlimited(url, &db).await?;
1735    let holder = format!("migrate-{}", uuid::Uuid::now_v7());
1736    let lead = if wait {
1737        Leadership::take(db, holder, period, || {
1738            tracing::info!("a master holds the database's lease; waiting for it");
1739        })
1740        .await
1741    } else {
1742        Leadership::try_take(db, holder, period)
1743            .await?
1744            .ok_or_else(|| {
1745                AppError::BadArgument(
1746                    "a master holds the database's lease: stop it first, or wait for it with \
1747                 `schedr db migrate --wait`"
1748                        .to_owned(),
1749                )
1750            })?
1751    };
1752    let lead = migrate_holding(lead, &unlimited, change_notifications).await?;
1753    lead.release().await;
1754    Ok(())
1755}
1756
1757/// The database at `url` without a query limit, for a migration (a long one must finish);
1758/// `limited` itself in memory, where another connection would be another database.
1759///
1760/// # Errors
1761///
1762/// [`AppError::Db`] if it can't be connected to.
1763pub async fn unlimited(url: &str, limited: &Database) -> Result<Database, AppError> {
1764    if url.contains(":memory:") {
1765        Ok(limited.clone())
1766    } else {
1767        Ok(Database::connect(url).await?)
1768    }
1769}
1770
1771/// Migrates `db` (see [`unlimited`]) while holding `lead`, renewing it as the migration runs.
1772///
1773/// # Errors
1774///
1775/// [`AppError::Db`] if the migration fails (the lease given back), [`AppError::BadArgument`]
1776/// if another master took the lease over meanwhile.
1777pub async fn migrate_holding(
1778    mut lead: Leadership,
1779    db: &Database,
1780    change_notifications: bool,
1781) -> Result<Leadership, AppError> {
1782    // sqlx would refuse it too, without saying what to do (B236).
1783    if let Ok(status @ SchemaStatus::Modified { .. }) = db.schema_status().await {
1784        lead.release().await;
1785        return Err(modified(&status));
1786    }
1787    let applied = async {
1788        while_holding(&mut lead, async {
1789            db.migrate_as_lease_holder().await.map_err(AppError::from)
1790        })
1791        .await?;
1792        while_holding(
1793            &mut lead,
1794            apply_change_notifications(db, change_notifications),
1795        )
1796        .await
1797    }
1798    .await;
1799    // Failing, the lease given back at once: a retry, or a master, needn't wait for it to
1800    // expire.
1801    if let Err(error) = applied {
1802        lead.release().await;
1803        return Err(error);
1804    }
1805    Ok(lead)
1806}
1807
1808/// Runs `work` while renewing the lease, as a migration's holder must (B204: a switch of
1809/// `change_notifications` waiting on a lock let the lease lapse): [`LeaseLost`] when another
1810/// master took it over, or its time ran out with renewals failing (the database not
1811/// answering this master: another may take it), meanwhile or by the time `work` ended.
1812///
1813/// # Errors
1814///
1815/// What `work` returns, or [`AppError::BadArgument`] with [`LeaseLost`].
1816async fn while_holding<T>(
1817    lead: &mut Leadership,
1818    work: impl Future<Output = Result<T, AppError>>,
1819) -> Result<T, AppError> {
1820    tokio::pin!(work);
1821    loop {
1822        tokio::select! {
1823            done = &mut work => {
1824                let value = done?;
1825                return still_held(lead).await.map(|()| value);
1826            }
1827            () = tokio::time::sleep(lead.period() / 3) => still_held(lead).await?,
1828        }
1829    }
1830}
1831
1832/// Renews the lease: [`LeaseLost`] when it was taken over, or is no longer held in time (a
1833/// failed renewal past the last one's period: B204's review).
1834async fn still_held(lead: &mut Leadership) -> Result<(), AppError> {
1835    let held = match lead.renew(std::time::Instant::now()).await {
1836        Renewal::Held => true,
1837        Renewal::TakenOver => false,
1838        // Not renewed: held while the last renewal's time lasts, no longer.
1839        Renewal::Failed => lead.leads(std::time::Instant::now()),
1840    };
1841    if !held {
1842        return Err(AppError::BadArgument(LeaseLost.to_string()));
1843    }
1844    Ok(())
1845}
1846
1847/// Turns the database's change triggers on or off as `[database] change_notifications` says
1848/// (decision 38A'), logging a change; done where migrations are, holding the master's lease.
1849///
1850/// # Errors
1851///
1852/// [`AppError::Db`] if the statements fail.
1853pub async fn apply_change_notifications(db: &Database, on: bool) -> Result<(), AppError> {
1854    if db.set_change_notifications(on).await? {
1855        tracing::info!(
1856            "the database's change notifications turned {} (`[database] change_notifications`)",
1857            if on { "on" } else { "off" }
1858        );
1859    }
1860    Ok(())
1861}
1862
1863/// `schedr master`: the gRPC service and the loop, until Ctrl-C or SIGTERM.
1864///
1865/// # Errors
1866///
1867/// As [`connect_database`], [`lead`], [`listen`] and [`serve_master`].
1868pub async fn master(config: &Config, migrate: bool) -> Result<(), AppError> {
1869    let stop = stop_on_signal();
1870    let tls = role_tls(config)?;
1871    check_timeouts(config)?;
1872    let outbox = master_outbox(config, &std::env::vars().collect())?;
1873    let health = Health::new(config.timings.loop_stall_timeout);
1874    let ready = health.starting("master");
1875    let metrics = MasterMetrics::default();
1876    let mut registry = Registry::default();
1877    metrics.register(registry.sub_registry_with_prefix("schedr"));
1878    start_ops(config, "master", Ops::new(registry, health.clone()), &stop).await?;
1879    let retry = config.timings.schema_retry;
1880    let url = config.database.url.as_deref().unwrap_or_default();
1881    let connected = once_reached(("master", url), retry, stop.clone(), || {
1882        connect_database(config, "master")
1883    });
1884    let Some(db) = connected.await? else {
1885        return Ok(());
1886    };
1887    let period = (
1888        config.timings.lease_period,
1889        migrate,
1890        config.database.change_notifications,
1891    );
1892    // Its row on the Deployments page, from now on: a standby's too.
1893    let problems = Problems::default();
1894    let identity = MasterIdentity {
1895        master_id: new_master_id(),
1896        config: masked(config),
1897        problems: problems.clone(),
1898        heartbeat: config.timings.node_heartbeat,
1899        row_kept: config.timings.node_row_kept,
1900    };
1901    let master_id = identity.master_id.clone();
1902    tokio::spawn(heartbeat_master(db.clone(), identity, stop.clone()));
1903    let Some(leadership) = lead(
1904        &db,
1905        url,
1906        period,
1907        (stop.clone(), retry),
1908        ("master", master_id),
1909    )
1910    .await?
1911    else {
1912        return Ok(());
1913    };
1914    let address = SocketAddr::new(config.master.bind, config.master.grpc_port);
1915    let listener = listen(address).await?;
1916    let bound = listener.local_addr().unwrap_or(address);
1917    tracing::info!(
1918        "schedr master: gRPC on {bound} ({})",
1919        links_text(tls.as_ref())
1920    );
1921    watch_tls(tls.as_ref(), config, &stop);
1922    // Boxed: the role's future is large.
1923    Box::pin(serve_master(
1924        db,
1925        master_settings(config),
1926        (
1927            config.timings.tick_interval,
1928            problems,
1929            (
1930                usize::try_from(config.events.max_size).unwrap_or(usize::MAX),
1931                ApiTimings::of(config).limits,
1932            ),
1933            outbox,
1934        ),
1935        listener,
1936        tls,
1937        leadership,
1938        Observed {
1939            metrics,
1940            health: &health,
1941            ready,
1942        },
1943        stop,
1944    ))
1945    .await
1946}
1947
1948/// Checks that `query_timeout` and `lease_period` are shorter than
1949/// `loop_stall_timeout`, so one hung query doesn't look like a stuck loop, and a stuck master
1950/// doesn't lead past its restart.
1951///
1952/// # Errors
1953///
1954/// [`AppError::BadArgument`] when it isn't.
1955pub fn check_timeouts(config: &Config) -> Result<(), AppError> {
1956    // A test asked for without a timeout gets this one, and the API refuses what's outside this.
1957    let most = Duration::from_millis(schedr_model::commands::MAX_CONNECTION_TEST_MS);
1958    let test = config.webserver.connection_test_timeout;
1959    if test.as_millis() == 0 || test > most {
1960        return Err(AppError::BadArgument(format!(
1961            "[webserver] connection_test_timeout ({} s) must be at least 1 ms and at most {} s",
1962            test.as_secs_f64(),
1963            most.as_secs_f64()
1964        )));
1965    }
1966    // Below 1 ms every query would be cut off at once.
1967    if config.timings.query_timeout >= config.timings.loop_stall_timeout
1968        || config.timings.query_timeout.as_millis() == 0
1969    {
1970        return Err(AppError::BadArgument(format!(
1971            "query_timeout ({} s) must be at least 1 ms and shorter than loop_stall_timeout ({} s)",
1972            config.timings.query_timeout.as_secs_f64(),
1973            config.timings.loop_stall_timeout.as_secs_f64()
1974        )));
1975    }
1976    // A paused master keeps its loop beating, but a lease longer than the stall limit would
1977    // leave a stuck one leading past its restart. A renewal (limited by the query limit) must
1978    // fit a third of it, and leading stops a query limit before it ends.
1979    if config.timings.lease_period >= config.timings.loop_stall_timeout
1980        || config.timings.lease_period < config.timings.query_timeout * 3
1981    {
1982        return Err(AppError::BadArgument(format!(
1983            "the master's lease ({} s) must be at least three query_timeout ({} s) and shorter \
1984             than loop_stall_timeout ({} s)",
1985            config.timings.lease_period.as_secs_f64(),
1986            config.timings.query_timeout.as_secs_f64(),
1987            config.timings.loop_stall_timeout.as_secs_f64()
1988        )));
1989    }
1990    Ok(())
1991}
1992
1993/// Binds the ops port (`[ops] bind` : `port`) and serves `ops` there until `stop`, logging
1994/// the address as `schedr <role>: ops on http://<address>`.
1995///
1996/// # Errors
1997///
1998/// [`AppError::BadArgument`] if the address can't be bound.
1999pub async fn start_ops(
2000    config: &Config,
2001    role: &str,
2002    ops: Ops,
2003    stop: &watch::Receiver<u32>,
2004) -> Result<SocketAddr, AppError> {
2005    let address = SocketAddr::new(config.ops.bind, config.ops.port);
2006    let listener = listen(address).await?;
2007    let bound = listener.local_addr().unwrap_or(address);
2008    tracing::info!("schedr {role}: {}", ops_line(bound));
2009    let stop = stop.clone();
2010    tokio::spawn(async move {
2011        if let Err(error) = serve_ops(listener, ops, stop).await {
2012            tracing::error!(%error, "the ops port failed");
2013        }
2014    });
2015    Ok(bound)
2016}
2017
2018/// How a role's internal links are protected, for its startup line.
2019fn links_text(tls: Option<&Tls>) -> &'static str {
2020    if tls.is_some() {
2021        "mTLS"
2022    } else {
2023        "plain: tls mode `mesh`"
2024    }
2025}
2026
2027/// `schedr webserver`: the REST API, until Ctrl-C or SIGTERM.
2028///
2029/// # Errors
2030///
2031/// As [`connect_database`], [`listen`] and [`serve_api`]. A schema it can't use yet is waited
2032/// for (see [`wait_for_schema`]), not ready meanwhile.
2033pub async fn webserver(config: &Config) -> Result<(), AppError> {
2034    let stop = stop_on_signal();
2035    let tls = role_tls(config)?;
2036    check_timeouts(config)?;
2037    check_ui_port(config)?;
2038    let health = Health::new(config.timings.loop_stall_timeout);
2039    let ready = health.starting("webserver");
2040    let metrics = ApiMetrics::default();
2041    let mut registry = Registry::default();
2042    metrics.register(registry.sub_registry_with_prefix("schedr"));
2043    start_ops(
2044        config,
2045        "webserver",
2046        Ops::new(registry, health.clone()),
2047        &stop,
2048    )
2049    .await?;
2050    let retry = config.timings.schema_retry;
2051    let url = config.database.url.as_deref().unwrap_or_default();
2052    let connected = once_reached(("webserver", url), retry, stop.clone(), || {
2053        connect_database(config, "webserver")
2054    });
2055    let Some(db) = connected.await? else {
2056        return Ok(());
2057    };
2058    let place = schedr_db::database_place(url);
2059    let waiting = wait_for_schema(&db, ("webserver", &place), retry);
2060    match until_stopped(waiting, stop.clone()).await {
2061        None => return Ok(()),
2062        Some(waited) => waited?,
2063    }
2064    // Its own sample a minute (decision 464): in a process of its own, no master samples it.
2065    tokio::spawn(schedr_master::samples::sample_webserver(
2066        db.clone(),
2067        config.timings.sample_interval,
2068        crate::node::process_id().to_owned(),
2069        schedr_agent::memory::this_node,
2070        until(stop.clone()),
2071    ));
2072    let address = SocketAddr::new(config.webserver.bind, config.webserver.port);
2073    let listener = listen(address).await?;
2074    let bound = listener.local_addr().unwrap_or(address);
2075    let auth = role_auth(
2076        "webserver",
2077        &config.webserver.auth,
2078        bound,
2079        config.webserver.ui_token_file.as_deref(),
2080        auth_timings(&config.timings, &config.limits),
2081    )?;
2082    if config.webserver.auth.mode == AuthMode::None
2083        && let Some(warning) = no_auth_warning(bound, "set [webserver] bind = \"127.0.0.1\"")
2084    {
2085        tracing::warn!("{warning}");
2086    }
2087    tracing::info!(
2088        "schedr webserver: API on http://{bound} (worker logs: {})",
2089        links_text(tls.as_ref())
2090    );
2091    watch_tls(tls.as_ref(), config, &stop);
2092    let ui_port = match (&tls, config.webserver.ui_port_in_mesh) {
2093        (Some(_), _) => {
2094            let address = SocketAddr::new(config.webserver.bind, config.webserver.ui_port);
2095            let ui_listener = listen(address).await?;
2096            tracing::info!(
2097                "schedr webserver: the API for `schedr ui` on https://{} (mTLS, its \
2098                 certificate naming `{}`)",
2099                ui_listener.local_addr().unwrap_or(address),
2100                config.tls.ui_name
2101            );
2102            Some(ui_listener)
2103        }
2104        (None, true) => {
2105            let address = SocketAddr::new(config.webserver.bind, config.webserver.ui_port);
2106            let ui_listener = listen(address).await?;
2107            tracing::warn!(
2108                "schedr webserver: the API for `schedr ui` on http://{} trusting the mesh \
2109                 (`[webserver] ui_port_in_mesh`): only a mesh policy keeps others from naming \
2110                 any user there",
2111                ui_listener.local_addr().unwrap_or(address)
2112            );
2113            Some(ui_listener)
2114        }
2115        (None, false) => None,
2116    };
2117    serve_api(
2118        db,
2119        (auth, ApiTimings::of(config), webserver_node(masked(config))),
2120        (listener, ui_port),
2121        tls,
2122        None,
2123        Observed {
2124            metrics,
2125            health: &health,
2126            ready,
2127        },
2128        stop,
2129    )
2130    .await
2131}
2132
2133/// Checks that `[webserver] ui_port_in_mesh` is set only in `[tls] mode = "mesh"`.
2134///
2135/// # Errors
2136///
2137/// [`AppError::BadArgument`] in `app` mode, where the UI port proves `schedr ui` by its
2138/// certificate.
2139pub fn check_ui_port(config: &Config) -> Result<(), AppError> {
2140    if config.webserver.ui_port_in_mesh && config.tls.mode == TlsMode::App {
2141        return Err(AppError::BadArgument(
2142            "[webserver] ui_port_in_mesh is for [tls] mode = \"mesh\": in \"app\" mode the UI \
2143             port proves `schedr ui` by its certificate"
2144                .to_owned(),
2145        ));
2146    }
2147    Ok(())
2148}
2149
2150/// `schedr worker`: the agent connected to `[worker] master_url`, until Ctrl-C or SIGTERM.
2151///
2152/// # Errors
2153///
2154/// [`AppError::BadArgument`] without a master URL, a data directory or a usable DAG
2155/// interpreter.
2156pub async fn worker(config: &Config, env: &BTreeMap<String, String>) -> Result<(), AppError> {
2157    let stop = stop_on_signal();
2158    let master_url = config.worker.master_url.clone().ok_or_else(|| {
2159        AppError::BadArgument(
2160            "no master to connect to: set [worker] master_url \
2161             (SCHEDR_CONFIG__WORKER__MASTER_URL), e.g. https://schedr-master:8070"
2162                .to_owned(),
2163        )
2164    })?;
2165    master_host(&master_url, config.tls.mode)?;
2166    let tls = role_tls(config)?;
2167    let health = Health::new(config.timings.loop_stall_timeout);
2168    let ready = health.starting("worker");
2169    let metrics = AgentMetrics::default();
2170    let mut registry = Registry::default();
2171    metrics.register(registry.sub_registry_with_prefix("schedr"));
2172    start_ops(config, "worker", Ops::new(registry, health.clone()), &stop).await?;
2173    let config = role_config(config, env, false)?;
2174    let data_dir = data_dir(&config, env)?;
2175    tokio::fs::create_dir_all(&data_dir)
2176        .await
2177        .map_err(|e| AppError::BadArgument(format!("can't create {}: {e}", data_dir.display())))?;
2178    warn_without_dag_roots(&config, false);
2179    let mut agent = agent_settings(&config, env, &data_dir, WORKER_RESERVE)?;
2180    secure_logs(log_mode(&config), &agent.setup.log_dir)?;
2181    // Secrets go there as files: a folder another user made first is refused (decision 201).
2182    schedr_agent::connection_env::prepare(&agent.setup.connection_dir)
2183        .map_err(AppError::BadArgument)?;
2184    // No database here: never the `db` storage.
2185    agent.secrets = std::sync::Arc::new(
2186        crate::secret_storage::SecretPlan::new(&config.secret_storage, env)
2187            .renewing(&config.timings)
2188            .stores(None)?,
2189    );
2190    let _lock = lock_journal(&agent)?;
2191    let address = SocketAddr::new(config.worker.log_bind, config.worker.log_port);
2192    let log_listener = listen(address).await?;
2193    let port = log_listener
2194        .local_addr()
2195        .map_or(address.port(), |a| a.port());
2196    agent.log_endpoint = log_endpoint(&config, env, tls.is_some(), port);
2197    tracing::info!(
2198        "schedr worker {}: master {master_url} ({}), {}, data in {}, logs on {}",
2199        agent.worker_id,
2200        links_text(tls.as_ref()),
2201        memory_text(&agent.setup.memory),
2202        data_dir.display(),
2203        agent.log_endpoint
2204    );
2205    watch_tls(tls.as_ref(), &config, &stop);
2206    let links = WorkerLinks {
2207        master_url,
2208        tls,
2209        log_listener,
2210        retention: log_retention(&config),
2211        max_message_size: usize::try_from(config.grpc.max_message_size).unwrap_or(usize::MAX),
2212    };
2213    let observed = Observed {
2214        metrics,
2215        health: &health,
2216        ready,
2217    };
2218    Box::pin(run_worker(
2219        agent,
2220        ParseLimits::configured(
2221            config.dags.parse_file_timeout,
2222            config.dags.parse_concurrency,
2223        ),
2224        links,
2225        observed,
2226        stop,
2227    ))
2228    .await;
2229    Ok(())
2230}