Skip to main content

schedr_config/
config.rs

1//! The configuration sections and their defaults.
2//!
3//! Only the keys the first milestones need exist so far; sections grow additively. Unknown
4//! keys are an error, so a typo never passes silently.
5
6use std::collections::BTreeMap;
7use std::net::{IpAddr, Ipv4Addr};
8use std::path::PathBuf;
9use std::time::Duration;
10
11use schemars::JsonSchema;
12use serde::{Deserialize, Serialize};
13
14use crate::roots::{PathList, Root};
15use crate::units::{
16    DurationText, MemoryReserve, SizeText, deserialize_duration, deserialize_mode_text,
17    deserialize_optional_duration, deserialize_optional_size, deserialize_size, serialize_duration,
18    serialize_optional_duration, serialize_optional_size, serialize_size,
19};
20
21#[cfg(test)]
22mod tests;
23
24/// The interpreter name used for parsing DAGs and running Python tasks unless configured.
25pub const DEFAULT_DAG_INTERPRETER: &str = "python";
26
27/// The executable behind the built-in `python` interpreter when `[interpreters]` doesn't
28/// define one.
29pub const BUILTIN_PYTHON: &str = "python3";
30
31/// The start of the environment variables that set a timing of [`Timings`]:
32/// `SCHEDR_HIDDEN__MASTER__TICK_INTERVAL=100ms`. Not configuration, and unsupported: the tests
33/// need them, and anyone may experiment at their own risk. The name keeps them from being set by
34/// accident; a file can't set them, and each one set is warned about.
35pub const HIDDEN_PREFIX: &str = "SCHEDR_HIDDEN__";
36
37/// The timings that aren't a user's to choose, each tuned, tied to others, or what the cluster's
38/// correctness depends on (a wrong value can run tasks twice, or lose a healthy worker): fixed,
39/// not configuration. Only `SCHEDR_HIDDEN__*` changes them, which is what the tests do, to run
40/// in seconds; anyone else does so at their own risk.
41#[derive(Debug, Clone, PartialEq, Eq)]
42pub struct Timings {
43    /// How often the master's loop runs (scheduler, commands, dispatching).
44    pub tick_interval: Duration,
45    /// How often workers send `Heartbeat` (the master's setting, sent to every worker).
46    pub heartbeat_interval: Duration,
47    /// A worker silent for this long is lost.
48    pub lease_timeout: Duration,
49    /// How long no alive worker must report a script root before DAG roots using it are no
50    /// longer withdrawn for it (decision 303).
51    pub script_root_grace: Duration,
52    /// How far before the newest event an `EventNamed` trigger acted on it looks again, for one
53    /// stored late (decision 354: a post's time is taken before it commits, and webservers'
54    /// clocks differ); the keys its DAG has are skipped. Longer than a `query_timeout` and the
55    /// webservers' clock skew.
56    pub event_lookback: Duration,
57    /// How long the master's lease lasts (one master per database: a second one waits as a
58    /// standby, and takes over at most this long after the first dies); renewed every third
59    /// of it. At least three `query_timeout`s, shorter than `loop_stall_timeout`.
60    pub lease_period: Duration,
61    /// After a commit cut off by the time limit or a lost connection, how long the master reads
62    /// back whether it was stored (holding its lock: rounds and worker messages wait). Not seen
63    /// by then: taken as not stored.
64    pub read_back_window: Duration,
65    /// How often it reads back within `read_back_window`.
66    pub read_back_interval: Duration,
67    /// The longest a query (or waiting for a connection) may take; a write's transaction, a
68    /// few of these. Shorter than `loop_stall_timeout`, so one hung query doesn't look
69    /// like a stuck loop, and at most a third of `lease_period`.
70    pub query_timeout: Duration,
71    /// The master's liveness fails when its scheduling loop hasn't started an iteration for
72    /// this long.
73    pub loop_stall_timeout: Duration,
74    /// How long a task whose assignment fails on its own (its data won't read, the database
75    /// refuses it) is left out of the rounds, so the others go on, before it is tried again.
76    pub set_aside: Duration,
77    /// The least an `@sensor(wait_for=...)`'s call gets once it is handed its run, though its
78    /// `max_wait` is nearly or already out: the run ended within it (decision 353).
79    pub handed_call_min: Duration,
80    /// How long a lost worker's cleanup waits, on top of the cancel grace, before it moves: a
81    /// worker only cut off has stopped the task by then (decision 256).
82    pub cleanup_move_wait: Duration,
83    /// How often a master whose listening for commands failed to start (the database too slow
84    /// to check for a pooler, or unreachable) tries again; it polls meanwhile.
85    pub listen_retry: Duration,
86    /// How often the web UI's live pages are told to read themselves again when the
87    /// database's changes can't be followed (`[database] change_notifications = false`, or no
88    /// listening connection).
89    pub refresh_interval: Duration,
90    /// How long connecting to a worker may take, to fetch a task's log. Raise it on a slow
91    /// network between the webserver and the workers.
92    pub worker_connect_timeout: Duration,
93    /// From a drain's SIGKILL of the tasks still running to the end of
94    /// `termination_grace_period`: time to report them interrupted and deregister before the
95    /// pod is killed (with `0s`, their results may not reach the master, and they end `lost`).
96    pub drain_report_period: Duration,
97    /// How often the watchdog samples each task's memory.
98    pub memory_check_interval: Duration,
99    /// How long a peer has to complete the TLS handshake. Raise it for slow clients; lower it to
100    /// drop stalled connections sooner.
101    pub handshake_timeout: Duration,
102    /// How long a stopped process's output may take to reach its log (a process it started in a
103    /// session of its own can hold the pipes open).
104    pub output_drain_timeout: Duration,
105    /// How long a fork server may take to answer a request; then it is restarted, and the task
106    /// spawned.
107    pub fork_answer_timeout: Duration,
108    /// The first wait before a fork server is restarted; it doubles up to `fork_backoff_max`.
109    pub fork_backoff_first: Duration,
110    /// The longest wait before a fork server is restarted.
111    pub fork_backoff_max: Duration,
112    /// A fork server up for this long starts its restarts' waits over.
113    pub fork_backoff_reset_after: Duration,
114    /// How often old task logs are swept.
115    pub log_sweep_interval: Duration,
116    /// How often an orphan found at start is looked at while it stops.
117    pub orphan_poll: Duration,
118    /// How long an orphan may take to go after SIGKILL.
119    pub orphan_kill_wait: Duration,
120    /// How long an orphan found at start gets from SIGTERM to SIGKILL.
121    pub orphan_grace: Duration,
122    /// The first wait after the master connection drops; it doubles up to
123    /// `reconnect_backoff_max`, with jitter.
124    pub reconnect_backoff_first: Duration,
125    /// The longest wait between tries to reach the master.
126    pub reconnect_backoff_max: Duration,
127    /// How often the agent's loop turns at least, however quiet. Shorter than
128    /// `loop_stall_timeout`, or a quiet agent looks stuck.
129    pub worker_alive_interval: Duration,
130    /// How long a stopping worker waits for the master to take its deregistering, at most
131    /// (the drain's end bounds it; by default that end alone, B242).
132    pub deregister_wait: Duration,
133    /// How often a drain looks at what is left.
134    pub drain_tick: Duration,
135    /// How long a drained worker waits for the master to acknowledge its last results; never
136    /// past half the report period before the grace period ends, left to deregister and exit.
137    pub drain_ack_wait: Duration,
138    /// How often a stopped task's process group is looked at until it is gone.
139    pub stop_poll: Duration,
140    /// How long a connection test's process gets from SIGTERM to SIGKILL.
141    pub connection_job_cancel_grace: Duration,
142    /// A Vault token's renewal never comes sooner than this.
143    pub vault_min_renew_wait: Duration,
144    /// How far back a worker looks for its tightest master-time sample (decision 447).
145    pub master_sample_window: Duration,
146    /// How far apart the master's wall clock and a worker's may be, beyond the round trip, before
147    /// the worker warns (decision 449, B232).
148    pub clock_skew_warning: Duration,
149    /// How often a Vault session with nothing to renew is looked at again.
150    pub vault_renew_check: Duration,
151    /// How soon a failed Vault renewal is tried again, while the token lasts.
152    pub vault_renew_retry: Duration,
153    /// At most one extra round every this long, under a stream of finished tasks.
154    pub round_gap: Duration,
155    /// After notifications failed, how long until they are tried again; polling goes on
156    /// meanwhile.
157    pub notification_retry: Duration,
158    /// How often the master's loop turns at least while it waits. Shorter than
159    /// `loop_stall_timeout`, or a waiting master looks stuck.
160    pub master_alive_interval: Duration,
161    /// How often the master's gauges are read from the database.
162    pub gauge_refresh: Duration,
163    /// How often the master's sender looks for notifications to deliver.
164    pub outbox_poll: Duration,
165    /// The first wait before a notification that failed is tried again; it doubles up to
166    /// `outbox_retry_max`.
167    pub outbox_retry_first: Duration,
168    /// The longest wait before a notification that failed is tried again.
169    pub outbox_retry_max: Duration,
170    /// How often the master's retention job deletes what `[retention]` no longer keeps
171    /// (decision 432).
172    pub retention_interval: Duration,
173    /// How often the leading master samples each process, and a webserver itself (decision
174    /// 464).
175    pub sample_interval: Duration,
176    /// How long the minute samples are kept.
177    pub samples_kept: Duration,
178    /// How long the 15-minute rollups are kept.
179    pub rollups_kept: Duration,
180    /// The first wait before a failed parse job is tried again; it doubles up to
181    /// `parse_retry_max`.
182    pub parse_retry_first: Duration,
183    /// The longest wait before a failed parse job is tried again.
184    pub parse_retry_max: Duration,
185    /// How often a master writes its row of the deployment's nodes.
186    pub node_heartbeat: Duration,
187    /// How often changes are read where they aren't announced (`SQLite`).
188    pub changes_poll_interval: Duration,
189    /// How often the webserver looks at whether the database announces its changes.
190    pub events_recheck: Duration,
191    /// How often an event stream gets a comment, keeping idle connections open through proxies.
192    pub events_keep_alive: Duration,
193    /// How soon following the database's changes is tried again after a failure.
194    pub events_retry: Duration,
195    /// How often the users and token files are looked at for a change. A removed user or a
196    /// changed password keeps working this long: raising it delays revocation.
197    pub auth_recheck: Duration,
198    /// How long a password check that passed is remembered, instead of running bcrypt again. A
199    /// change of the users file forgets them all.
200    pub auth_remembered: Duration,
201    /// How long running requests get once the server stops; then they are cut.
202    pub requests_grace: Duration,
203    /// How often a webserver started before the migration looks again.
204    pub schema_retry: Duration,
205    /// How often a page's stream gets a `ping`, and the log tail a comment.
206    pub ui_keep_alive: Duration,
207    /// A page's stream sends at most one `change` this often, per deployment.
208    pub ui_coalesce: Duration,
209    /// How often the log tail reads the log.
210    pub ui_tail_interval: Duration,
211    /// How long the log tail keeps trying a log out of reach before it says so and stops.
212    pub ui_tail_give_up: Duration,
213    /// A Runs page read that took longer than this is slow (its deployments' answers).
214    pub ui_slow_read: Duration,
215    /// After a slow read, the page reads again on a change at most this often.
216    pub ui_slow_read_wait: Duration,
217    /// The first wait before a relay opens its stream again; it doubles up to `relay_retry_max`.
218    pub ui_relay_retry_first: Duration,
219    /// The longest wait between a relay's tries.
220    pub ui_relay_retry_max: Duration,
221    /// Once a standalone's master failed, how long its worker gets to stop.
222    pub worker_stop_after_failure: Duration,
223    /// How long a listener waits after a failed accept (too many open files), instead of
224    /// spinning.
225    pub accept_retry: Duration,
226    /// The wait before a failed trigger starts again; it doubles with each failure in a row.
227    pub trigger_restart_backoff: Duration,
228    /// The most it waits.
229    pub trigger_restart_backoff_max: Duration,
230    /// How long after its end a Metrics bucket is final, kept by the webserver between requests
231    /// (decision 492): longer than the rollup's grace, with room for the writers' clocks. (`WEBSERVER__METRICS_FINAL_AFTER`)
232    pub metrics_final_after: Duration,
233    /// How long after its end a samples window waits to be rolled up, so a sample stored late is
234    /// in it; shorter than `metrics_final_after`. (`MASTER__SAMPLE_ROLLUP_GRACE`)
235    pub sample_rollup_grace: Duration,
236    /// How far back the DAG page's memory p95s reach (decision 467). (`WEBSERVER__MEMORY_PEAKS_WINDOW`)
237    pub memory_peaks_window: Duration,
238    /// How far ahead of the clock a posted event's `at` may be, posted to a webserver or by a
239    /// task through its master (`EVENTS__FUTURE_TOLERANCE`).
240    pub event_future_tolerance: Duration,
241    /// How far ahead of the master's clock a run's `--for` may be. (`MASTER__FOR_FUTURE_TOLERANCE`)
242    pub for_future_tolerance: Duration,
243    /// When a task whose code wasn't on its worker yet is tried again: about a git-sync interval
244    /// and the settle time. (`MASTER__CODE_RETRY_DELAY`)
245    pub code_retry_delay: Duration,
246    /// How long a master's row stays after its last heartbeat before it is removed. (`MASTER__NODE_ROW_KEPT`)
247    pub node_row_kept: Duration,
248    /// How long the CLI and `schedr ui` wait to connect to a webserver. (`CLIENT__CONNECT_TIMEOUT`)
249    pub client_connect_timeout: Duration,
250    /// How long one request of the CLI or `schedr ui` to a webserver may take. (`CLIENT__REQUEST_TIMEOUT`)
251    pub client_request_timeout: Duration,
252    /// How long the CLI and `schedr ui` wait for the master's decision on a command. (`CLIENT__COMMAND_WAIT`)
253    pub client_command_wait: Duration,
254    /// How long `schedr dags test` waits for its run. (`DAGS__TEST_RUN_TIMEOUT`)
255    pub dags_test_run_timeout: Duration,
256    /// The `SCHEDR_HIDDEN__*` variables set, each warned about when starting.
257    pub overridden: Vec<String>,
258}
259
260impl Default for Timings {
261    /// The values every deployment runs with.
262    fn default() -> Self {
263        Self {
264            tick_interval: Duration::from_secs(1),
265            heartbeat_interval: Duration::from_secs(10),
266            lease_timeout: Duration::from_secs(60),
267            script_root_grace: Duration::from_mins(5),
268            event_lookback: Duration::from_mins(1),
269            lease_period: Duration::from_secs(30),
270            read_back_window: Duration::from_secs(3),
271            read_back_interval: Duration::from_millis(500),
272            query_timeout: Duration::from_secs(10),
273            loop_stall_timeout: Duration::from_secs(120),
274            set_aside: Duration::from_mins(1),
275            handed_call_min: Duration::from_mins(1),
276            cleanup_move_wait: Duration::from_secs(10),
277            listen_retry: Duration::from_mins(30),
278            refresh_interval: Duration::from_secs(15),
279            worker_connect_timeout: Duration::from_secs(5),
280            drain_report_period: Duration::from_secs(2),
281            memory_check_interval: Duration::from_secs(1),
282            handshake_timeout: Duration::from_secs(10),
283            output_drain_timeout: Duration::from_secs(5),
284            fork_answer_timeout: Duration::from_secs(30),
285            fork_backoff_first: Duration::from_secs(1),
286            fork_backoff_max: Duration::from_mins(5),
287            fork_backoff_reset_after: Duration::from_mins(10),
288            log_sweep_interval: Duration::from_hours(1),
289            orphan_poll: Duration::from_millis(50),
290            orphan_kill_wait: Duration::from_secs(5),
291            orphan_grace: Duration::from_secs(10),
292            reconnect_backoff_first: Duration::from_millis(200),
293            reconnect_backoff_max: Duration::from_secs(30),
294            worker_alive_interval: Duration::from_secs(5),
295            deregister_wait: Duration::from_hours(1),
296            drain_tick: Duration::from_millis(100),
297            drain_ack_wait: Duration::from_secs(5),
298            stop_poll: Duration::from_millis(100),
299            connection_job_cancel_grace: Duration::from_secs(5),
300            vault_min_renew_wait: Duration::from_secs(1),
301            master_sample_window: Duration::from_mins(10),
302            clock_skew_warning: Duration::from_secs(2),
303            vault_renew_check: Duration::from_mins(1),
304            vault_renew_retry: Duration::from_secs(10),
305            round_gap: Duration::from_millis(50),
306            notification_retry: Duration::from_secs(30),
307            master_alive_interval: Duration::from_secs(5),
308            gauge_refresh: Duration::from_secs(15),
309            outbox_poll: Duration::from_secs(5),
310            outbox_retry_first: Duration::from_secs(10),
311            outbox_retry_max: Duration::from_secs(3600),
312            retention_interval: Duration::from_hours(1),
313            sample_interval: Duration::from_mins(1),
314            samples_kept: Duration::from_hours(24),
315            rollups_kept: Duration::from_hours(24 * 30),
316            parse_retry_first: Duration::from_secs(30),
317            parse_retry_max: Duration::from_mins(10),
318            node_heartbeat: Duration::from_secs(10),
319            changes_poll_interval: Duration::from_secs(1),
320            events_recheck: Duration::from_mins(1),
321            events_keep_alive: Duration::from_secs(15),
322            events_retry: Duration::from_secs(1),
323            auth_recheck: Duration::from_secs(5),
324            auth_remembered: Duration::from_mins(5),
325            requests_grace: Duration::from_secs(3),
326            schema_retry: Duration::from_secs(5),
327            ui_keep_alive: Duration::from_secs(15),
328            ui_coalesce: Duration::from_secs(1),
329            ui_tail_interval: Duration::from_secs(1),
330            ui_tail_give_up: Duration::from_secs(30),
331            ui_slow_read: Duration::from_millis(50),
332            ui_slow_read_wait: Duration::from_secs(5),
333            ui_relay_retry_first: Duration::from_secs(1),
334            ui_relay_retry_max: Duration::from_secs(30),
335            worker_stop_after_failure: Duration::from_secs(10),
336            accept_retry: Duration::from_millis(100),
337            trigger_restart_backoff: Duration::from_secs(5),
338            trigger_restart_backoff_max: Duration::from_mins(5),
339            metrics_final_after: Duration::from_mins(15),
340            sample_rollup_grace: Duration::from_mins(2),
341            memory_peaks_window: Duration::from_hours(30 * 24),
342            event_future_tolerance: Duration::from_mins(1),
343            for_future_tolerance: Duration::from_mins(1),
344            code_retry_delay: Duration::from_secs(35),
345            node_row_kept: Duration::from_hours(1),
346            client_connect_timeout: Duration::from_secs(5),
347            client_request_timeout: Duration::from_secs(30),
348            client_command_wait: Duration::from_secs(30),
349            dags_test_run_timeout: Duration::from_hours(1),
350            overridden: Vec::new(),
351        }
352    }
353}
354
355/// `[watchers]`: the worker's watcher hosts, which run wait steps.
356#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
357#[serde(default, deny_unknown_fields)]
358pub struct WatchersSection {
359    /// How many wait steps a worker runs at once, apart from `[worker] slots`. 0: none.
360    pub slots: u32,
361    /// How long a wait step may hold its host's event loop before reaching an `await`. Past it
362    /// the host is killed: the wait step fails with `blocked_event_loop`, and the others on the
363    /// host start again without using a retry.
364    #[serde(
365        deserialize_with = "deserialize_duration",
366        serialize_with = "serialize_duration"
367    )]
368    #[schemars(with = "DurationText")]
369    pub block_limit: Duration,
370    /// The memory all of a worker's hosts may use together. Past it the largest is killed: its
371    /// wait steps end `lost`, each using a retry.
372    #[serde(
373        deserialize_with = "deserialize_size",
374        serialize_with = "serialize_size"
375    )]
376    #[schemars(with = "SizeText")]
377    pub memory_budget: u64,
378    /// After how many times in a row a wait step gets its host killed it is switched off: its
379    /// attempts then fail at once, until it succeeds on new code or `schedr sensors switch-on`.
380    /// 0: never.
381    pub switch_off_after: u32,
382    /// After how many calls in a row that each ran past its `every` a sensor's poke fails
383    /// (`PokeTooSlowError`). A call may run on past `every` to three times it, then it is
384    /// cancelled and fails at once. 1 (or 0): at the first.
385    pub poke_overruns: u32,
386}
387
388impl Default for WatchersSection {
389    fn default() -> Self {
390        Self {
391            slots: 500,
392            block_limit: Duration::from_secs(30),
393            memory_budget: 1024 * 1024 * 1024,
394            switch_off_after: 3,
395            poke_overruns: 3,
396        }
397    }
398}
399
400/// `[triggers]`: event triggers (`@trigger`, `@trigger.poke`).
401#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
402#[serde(default, deny_unknown_fields)]
403pub struct TriggersSection {
404    /// How many queued event runs a DAG may have before its trigger is stopped. It starts again
405    /// from its bookmark once they have all started: the events wait in the source, not in
406    /// schedr's database.
407    pub max_queued_events: u32,
408    /// How many errors in a row make a trigger `failing`.
409    pub failing_after: u32,
410}
411
412impl Default for TriggersSection {
413    fn default() -> Self {
414        Self {
415            max_queued_events: 1000,
416            failing_after: 5,
417        }
418    }
419}
420
421/// `[sensors]`: wait steps (`@sensor`, `@sensor.poke`).
422#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
423#[serde(default, deny_unknown_fields)]
424pub struct SensorsSection {
425    /// How long a wait step without a `max_wait` of its own waits, before it ends with the
426    /// `TimedOut` outcome.
427    #[serde(
428        deserialize_with = "deserialize_duration",
429        serialize_with = "serialize_duration"
430    )]
431    #[schemars(with = "DurationText")]
432    pub default_max_wait: Duration,
433}
434
435impl Default for SensorsSection {
436    fn default() -> Self {
437        Self {
438            default_max_wait: Duration::from_hours(24),
439        }
440    }
441}
442
443/// The whole configuration, after loading and validation.
444#[derive(Debug, Clone, PartialEq, Eq, Default, Deserialize, Serialize, JsonSchema)]
445#[serde(default, deny_unknown_fields)]
446pub struct Config {
447    /// `[dags]`: where DAG files are and how they are parsed.
448    pub dags: DagsSection,
449    /// `[scripts]`: where plain scripts are.
450    pub scripts: ScriptsSection,
451    /// `[interpreters]`: interpreter names and their executables.
452    #[schemars(with = "BTreeMap<String, InterpreterRepr>")]
453    pub interpreters: BTreeMap<String, Interpreter>,
454    /// `[log]`: schedr's own logs.
455    pub log: LogSection,
456    /// `[ops]`: the ops port (health and metrics).
457    pub ops: OpsSection,
458    /// `[database]`: the state database.
459    pub database: DatabaseSection,
460    /// `[master]`: the master's port and timing.
461    pub master: MasterSection,
462    /// `[mapping]`: mapped tasks (`.expand()`).
463    pub mapping: MappingSection,
464    /// `[backfill]`: backfills (`schedr runs backfill`).
465    pub backfill: BackfillSection,
466    /// `[webserver]`: the REST API (and later the UI).
467    pub webserver: WebserverSection,
468    /// `[ui]`: the web UI (`schedr ui`, and the one `schedr standalone` serves).
469    pub ui: UiSection,
470    /// `[worker]`: this worker's identity, capacity and data directory.
471    pub worker: WorkerSection,
472    /// `[sensors]`: wait steps (`@sensor`, `@sensor.poke`).
473    pub watchers: WatchersSection,
474    /// `[sensors]`.
475    pub sensors: SensorsSection,
476    /// Event triggers.
477    pub triggers: TriggersSection,
478    /// `[grpc]`: the link between the master and its workers, both ends.
479    pub grpc: GrpcSection,
480    /// `[events]`: events posted through the API (decision 354).
481    pub events: EventsSection,
482    /// `[notifications]`: what the master sends when runs and tasks end (decisions 408-429).
483    pub notifications: NotificationsSection,
484    /// `[retention]`: how long the database keeps runs, outputs, events and commands
485    /// (decisions 430-435).
486    pub retention: RetentionSection,
487    /// `[tls]`: mTLS on the internal links (master โ†” worker, webserver โ†’ worker logs).
488    pub tls: TlsSection,
489    /// `[secret_storage]`: where a worker's tasks get their secrets (workers only).
490    pub secret_storage: SecretStorageSection,
491    /// The DAG roots, resolved from `dags.path` and `dags.roots` when loading.
492    #[serde(skip)]
493    pub dag_roots: Vec<Root>,
494    /// The script roots, resolved from `scripts.path` and `scripts.roots` when loading.
495    #[serde(skip)]
496    pub script_roots: Vec<Root>,
497    /// How the `python` interpreter was chosen when `[interpreters]` doesn't define it: set to
498    /// [`BUILTIN_PYTHON_ORIGIN`] when loading, and by the binary when it looks for a better
499    /// one (e.g. `project venv`); `None` when `python` is configured.
500    #[serde(skip)]
501    pub builtin_python: Option<String>,
502    /// The fixed timings, as `SCHEDR_HIDDEN__*` left them.
503    #[serde(skip)]
504    pub timings: Timings,
505    /// The fixed limits, as `SCHEDR_HIDDEN__*` left them.
506    #[serde(skip)]
507    pub limits: HiddenLimits,
508}
509
510impl Config {
511    /// The longest a cleanup's try fits in a drain: the grace period less the drain's
512    /// terminate and report periods (25 s of the default 30 s).
513    #[must_use]
514    pub const fn cleanup_room(&self) -> Duration {
515        self.worker
516            .termination_grace_period
517            .saturating_sub(self.worker.drain_terminate_period)
518            .saturating_sub(self.timings.drain_report_period)
519    }
520
521    /// `[worker] cleanup_timeout`, or when not set the shorter of 5 minutes and
522    /// [`Self::cleanup_room`] (B252: the defaults agree with each other), at least 1 s: a
523    /// grace period the drain takes whole leaves none, and a zero would end every cleanup at
524    /// once.
525    #[must_use]
526    pub fn cleanup_timeout(&self) -> Duration {
527        self.worker.cleanup_timeout.unwrap_or_else(|| {
528            self.cleanup_room()
529                .min(Duration::from_mins(5))
530                .max(Duration::from_secs(1))
531        })
532    }
533}
534
535/// Fixed limits, like [`Timings`] not configuration: only `SCHEDR_HIDDEN__*` changes them.
536#[derive(Debug, Clone, PartialEq, Eq)]
537pub struct HiddenLimits {
538    /// The most records of one kind (wait step hosts, warnings) the master keeps of what a
539    /// worker reports (`MASTER__WORKER_REPORT_RECORDS`, B183): an honest agent sends a few.
540    pub worker_report_records: usize,
541    /// The most characters of each text in them the master keeps
542    /// (`MASTER__WORKER_REPORT_TEXT`).
543    pub worker_report_text: usize,
544    /// The most bytes a notification's body may take once filled
545    /// (`MASTER__NOTIFICATION_BODY`): a template using big values many times is refused.
546    pub notification_body: usize,
547    /// The most runs the retention job deletes in one transaction (`MASTER__RETENTION_BATCH`,
548    /// decision 432): one run can hold thousands of rows, and a transaction holds its locks.
549    pub retention_batch: usize,
550    /// The most messages of one worker the master handles in one turn of its lock
551    /// (`MASTER__MESSAGES_PER_TURN`, M4B.3): its `Started`s and `Finished`s stored together.
552    pub messages_per_turn: usize,
553    /// The Metrics cache's keys at most (each range, all processes or one; decision 492). (`WEBSERVER__METRICS_CACHE_KEYS`)
554    pub metrics_cache_keys: usize,
555    /// The buckets the Metrics cache keeps for one key at most; past them it reads each time. (`WEBSERVER__METRICS_CACHE_BUCKETS`)
556    pub metrics_cache_buckets: usize,
557    /// The runs, and one task's attempts, a memory p95 is taken from at most (decision 467). (`WEBSERVER__MEMORY_PEAKS_RUNS`)
558    pub memory_peaks_runs: usize,
559    /// The most assignments a round makes. (`MASTER__ASSIGNMENTS_PER_ROUND`)
560    pub assignments_per_round: usize,
561    /// The most assignments a round takes back as never started. (`MASTER__EXPIRIES_PER_ROUND`)
562    pub expiries_per_round: usize,
563    /// The most waiting reasons a round writes (a statement each). (`MASTER__WAITING_REASONS_PER_ROUND`)
564    pub waiting_reasons_per_round: usize,
565    /// The most pending reasons a round writes for the tasks past its cap (decision 481). (`MASTER__PENDING_REASONS_PER_ROUND`)
566    pub pending_reasons_per_round: usize,
567    /// The most commands a round applies. (`MASTER__COMMANDS_PER_ROUND`)
568    pub commands_per_round: usize,
569    /// The most scheduled runs a round creates for one DAG. (`MASTER__SCHEDULED_RUNS_PER_ROUND`)
570    pub scheduled_runs_per_round: usize,
571    /// The most task instances a round creates for runs that just started. (`MASTER__STARTED_INSTANCES_PER_ROUND`)
572    pub started_instances_per_round: usize,
573    /// The most failed tasks a round queues again. (`MASTER__RETRIES_PER_ROUND`)
574    pub retries_per_round: usize,
575    /// The most runs the scheduler creates for one DAG in one pass. (`MASTER__RUNS_PER_PLANNING_PASS`)
576    pub runs_per_planning_pass: usize,
577    /// The most runs one pass starts for a DAG started by `RunOf`. (`MASTER__RUN_OF_RUNS_PER_PASS`)
578    pub run_of_runs_per_pass: usize,
579    /// The most messages of a failed group handled one by one in a turn (M4B.3). (`MASTER__FAILED_GROUP_MESSAGES_PER_TURN`)
580    pub failed_group_messages_per_turn: usize,
581    /// The messages that wait for a worker before it is taken for one that stopped reading. (`MASTER__WORKER_STREAM_BUFFER`)
582    pub worker_stream_buffer: usize,
583    /// The most notifications one pass of the sender delivers. (`MASTER__NOTIFICATIONS_PER_PASS`)
584    pub notifications_per_pass: usize,
585    /// The most results a worker keeps in its journal as one group (M4B.5). (`WORKER__RESULTS_PER_JOURNAL_GROUP`)
586    pub results_per_journal_group: usize,
587    /// The most assignments whose journal records a worker writes as one group (M5.1b). (`WORKER__STARTS_PER_JOURNAL_GROUP`)
588    pub starts_per_journal_group: usize,
589    /// How many times a worker sends a result again over one session before it reconnects. (`WORKER__RESULT_RESENDS`)
590    pub result_resends: usize,
591    /// The most heartbeats between two sends of an unacknowledged result (B41). (`WORKER__RESULT_RESEND_GAP_MAX`)
592    pub result_resend_gap_max: usize,
593    /// The messages a worker keeps waiting to be heard of (B240), the oldest dropped first. (`WORKER__UNACKED_MESSAGES_KEPT`)
594    pub unacked_messages_kept: usize,
595    /// The connections jobs' answers a worker keeps while no master listens. (`WORKER__UNSENT_CONNECTION_ANSWERS`)
596    pub unsent_connection_answers: usize,
597    /// The most connections a task may have open to its agent at once. (`WORKER__TASK_CONNECTIONS_OPEN`)
598    pub task_connections_open: usize,
599    /// The messages of a wait step waiting for its attempt before its host waits too. (`WORKER__WATCHER_LOG_BACKLOG`)
600    pub watcher_log_backlog: usize,
601    /// The changes a slow event stream may fall behind by before it gets `refresh`. (`WEBSERVER__EVENTS_BACKLOG`)
602    pub webserver_events_backlog: usize,
603    /// The changes a slow browser may fall behind by before it gets `refresh`. (`UI__EVENTS_BACKLOG`)
604    pub ui_events_backlog: usize,
605    /// The password checks remembered at once, the oldest dropped first. (`WEBSERVER__AUTH_REMEMBERED_MAX`)
606    pub auth_remembered_max: usize,
607    /// The most rows of SQLite's `changes` one read takes. (`DATABASE__CHANGES_POLL_ROWS`)
608    pub changes_poll_rows: usize,
609    /// The DAG versions a process keeps parsed before clearing them. (`DATABASE__DAG_VERSIONS_CACHED`)
610    pub dag_versions_cached: usize,
611    /// How many TLS handshakes may run at once; beyond them accepting waits. (`TLS__HANDSHAKES_AT_ONCE`)
612    pub tls_handshakes_at_once: usize,
613    /// The `SCHEDR_HIDDEN__*` variables that changed one.
614    pub overridden: Vec<String>,
615}
616
617impl Default for HiddenLimits {
618    /// 256 records of each kind, 4096 characters of each text, 1 MiB a notification, 100 runs
619    /// a retention transaction, 80 messages a turn (decision 484); the rest as each says.
620    fn default() -> Self {
621        Self {
622            worker_report_records: 256,
623            worker_report_text: 4096,
624            notification_body: 1 << 20,
625            retention_batch: 100,
626            messages_per_turn: 80,
627            metrics_cache_keys: 64,
628            metrics_cache_buckets: 100_000,
629            memory_peaks_runs: 1000,
630            assignments_per_round: 50,
631            expiries_per_round: 50,
632            waiting_reasons_per_round: 100,
633            pending_reasons_per_round: 500,
634            commands_per_round: 50,
635            scheduled_runs_per_round: 10,
636            started_instances_per_round: 2000,
637            retries_per_round: 100,
638            runs_per_planning_pass: 100,
639            run_of_runs_per_pass: 50,
640            failed_group_messages_per_turn: 10,
641            worker_stream_buffer: 1024,
642            notifications_per_pass: 50,
643            results_per_journal_group: 32,
644            starts_per_journal_group: 32,
645            result_resends: 8,
646            result_resend_gap_max: 32,
647            unacked_messages_kept: 100_000,
648            unsent_connection_answers: 16,
649            task_connections_open: 64,
650            watcher_log_backlog: 16,
651            webserver_events_backlog: 1024,
652            ui_events_backlog: 1024,
653            auth_remembered_max: 1000,
654            changes_poll_rows: 1000,
655            dag_versions_cached: 4096,
656            tls_handshakes_at_once: 256,
657            overridden: Vec::new(),
658        }
659    }
660}
661
662/// The JSON Schema of the configuration file: every key with its doc comment, type and
663/// default (the configuration reference in the documentation is generated from it).
664#[must_use]
665pub fn config_schema() -> schemars::Schema {
666    schemars::schema_for!(Config)
667}
668
669/// How the built-in `python` interpreter was chosen when nothing looked further.
670pub const BUILTIN_PYTHON_ORIGIN: &str = "built-in default";
671
672/// `[dags]`.
673#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
674#[serde(default, deny_unknown_fields)]
675pub struct DagsSection {
676    /// The DAG directories (`SCHEDR_DAG_PATH`).
677    pub path: PathList,
678    /// Root renames: name โ†’ one of the `path` entries.
679    pub roots: BTreeMap<String, PathBuf>,
680    /// The `[interpreters]` entry used for parsing and for Python tasks.
681    pub interpreter: String,
682    /// How often the roots are scanned for changes.
683    #[serde(
684        deserialize_with = "deserialize_duration",
685        serialize_with = "serialize_duration"
686    )]
687    #[schemars(with = "DurationText")]
688    pub poll_interval: Duration,
689    /// How long a root must stay unchanged before its new content hash is computed.
690    #[serde(
691        deserialize_with = "deserialize_duration",
692        serialize_with = "serialize_duration"
693    )]
694    #[schemars(with = "DurationText")]
695    pub settle_time: Duration,
696    /// How long one DAG file may take to import before the agent stops its runner.
697    #[serde(
698        deserialize_with = "deserialize_duration",
699        serialize_with = "serialize_duration"
700    )]
701    #[schemars(with = "DurationText")]
702    pub parse_file_timeout: Duration,
703    /// How many DAG files are parsed at once, each in a process of its own. Capped at the cores
704    /// the agent may use; 1 parses them one at a time.
705    pub parse_concurrency: u32,
706}
707
708impl Default for DagsSection {
709    /// No DAG directories, the `python` interpreter, polling every 30 s with a 5 s settle time,
710    /// 60 s per file to import.
711    fn default() -> Self {
712        Self {
713            path: PathList::default(),
714            roots: BTreeMap::new(),
715            interpreter: DEFAULT_DAG_INTERPRETER.to_owned(),
716            poll_interval: Duration::from_secs(30),
717            settle_time: Duration::from_secs(5),
718            parse_file_timeout: Duration::from_secs(60),
719            parse_concurrency: 4,
720        }
721    }
722}
723
724/// `[scripts]`.
725#[derive(Debug, Clone, PartialEq, Eq, Default, Deserialize, Serialize, JsonSchema)]
726#[serde(default, deny_unknown_fields)]
727pub struct ScriptsSection {
728    /// The script directories (`SCHEDR_SCRIPT_PATH`).
729    pub path: PathList,
730    /// Root renames: name โ†’ one of the `path` entries.
731    pub roots: BTreeMap<String, PathBuf>,
732}
733
734/// An `[interpreters]` entry: a plain path, or a table with fork server settings.
735#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
736#[serde(from = "InterpreterRepr", into = "InterpreterRepr")]
737pub struct Interpreter {
738    /// The executable.
739    pub path: PathBuf,
740    /// Whether Python tasks start from a fork server (M2.5; off by default).
741    pub fork_server: bool,
742    /// The libraries the fork server preloads.
743    pub preload: Vec<String>,
744}
745
746impl Interpreter {
747    /// An interpreter given by its path only (spawn, no preloading).
748    #[must_use]
749    pub fn path(path: impl Into<PathBuf>) -> Self {
750        Self {
751            path: path.into(),
752            fork_server: false,
753            preload: Vec::new(),
754        }
755    }
756}
757
758/// How an interpreter is written in TOML.
759#[derive(Deserialize, Serialize, JsonSchema)]
760#[serde(untagged)]
761enum InterpreterRepr {
762    /// `python = "/usr/bin/python3"`.
763    Path(PathBuf),
764    /// `[interpreters.etl-venv]` with `path`, `fork_server`, `preload`.
765    Table(InterpreterTable),
766}
767
768/// The table form of an interpreter.
769#[derive(Deserialize, Serialize, JsonSchema)]
770#[serde(deny_unknown_fields)]
771struct InterpreterTable {
772    /// The executable.
773    path: PathBuf,
774    /// Whether Python tasks start from a fork server (M2.5; off by default).
775    #[serde(default)]
776    fork_server: bool,
777    /// The libraries the fork server preloads.
778    #[serde(default)]
779    preload: Vec<String>,
780}
781
782impl From<Interpreter> for InterpreterRepr {
783    /// The plain path when that says it all, else the table.
784    fn from(interpreter: Interpreter) -> Self {
785        if !interpreter.fork_server && interpreter.preload.is_empty() {
786            Self::Path(interpreter.path)
787        } else {
788            Self::Table(InterpreterTable {
789                path: interpreter.path,
790                fork_server: interpreter.fork_server,
791                preload: interpreter.preload,
792            })
793        }
794    }
795}
796
797impl From<InterpreterRepr> for Interpreter {
798    fn from(repr: InterpreterRepr) -> Self {
799        match repr {
800            InterpreterRepr::Path(path) => Self::path(path),
801            InterpreterRepr::Table(t) => Self {
802                path: t.path,
803                fork_server: t.fork_server,
804                preload: t.preload,
805            },
806        }
807    }
808}
809
810/// `[log] format`.
811#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize, Serialize, JsonSchema)]
812#[serde(rename_all = "lowercase")]
813pub enum LogFormat {
814    /// JSON when stdout isn't a terminal, readable text when it is.
815    #[default]
816    Auto,
817    /// Always JSON.
818    Json,
819    /// Always readable text.
820    Text,
821}
822
823/// `[log]`.
824#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
825#[serde(default, deny_unknown_fields)]
826pub struct LogSection {
827    /// The output format.
828    pub format: LogFormat,
829    /// The level, with per-module filters in the `RUST_LOG` style.
830    pub level: String,
831}
832
833impl Default for LogSection {
834    /// `auto` format at level `info`.
835    fn default() -> Self {
836        Self {
837            format: LogFormat::Auto,
838            level: "info".to_owned(),
839        }
840    }
841}
842
843/// `[database]`.
844#[derive(Clone, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
845#[serde(default, deny_unknown_fields)]
846pub struct DatabaseSection {
847    /// The connection URL (`sqlite:...` or `postgres://...`). A URL with a password must come
848    /// from `SCHEDR_CONFIG__DATABASE__URL`, never the file (see archive/PROJECT.md, Configuration:
849    /// secrets).
850    #[serde(skip_serializing_if = "Option::is_none")]
851    pub url: Option<String>,
852    /// Whether the master listens for new commands on Postgres (`LISTEN`), applying them at
853    /// once rather than at its next round. A connection pooler in transaction mode (`PgBouncer`
854    /// or similar) can't carry it: the master checks the connection it listens through, and
855    /// behind such a pooler it warns, turns notifications off and polls. Off: polling only;
856    /// the webserver doesn't notify either.
857    pub notifications: bool,
858    /// A connection for the master's listening only, straight to Postgres past a pooler, so
859    /// commands stay immediate behind one; the main URL when not set. With a password, it must
860    /// come from `SCHEDR_CONFIG__DATABASE__NOTIFICATIONS_URL`, never the file.
861    #[serde(skip_serializing_if = "Option::is_none")]
862    pub notifications_url: Option<String>,
863    /// Whether the writes announce what changed, for the web UI's live pages (triggers in the
864    /// database; about 2-3% of the master's throughput under heavy load, measured by stress
865    /// scenarios 15 and 15b). Applied by `schedr db migrate` and `--migrate`, not by a running
866    /// master. Off: the pages refresh every `refresh_interval` instead.
867    pub change_notifications: bool,
868}
869
870impl Default for DatabaseSection {
871    /// No URL, queries limited to 10 s, notifications on (through the main URL), changes
872    /// announced.
873    fn default() -> Self {
874        Self {
875            url: None,
876            notifications: true,
877            notifications_url: None,
878            change_notifications: true,
879        }
880    }
881}
882
883/// Whether a URL has a password: in its user-info part (`scheme://user:password@host`) or as
884/// a query parameter naming one (`?password=...`, any case, the name percent-decoded; B203).
885#[must_use]
886pub fn url_has_password(url: &str) -> bool {
887    // As its client reads it: `postgres:\n//u:p@db` is `postgres://u:p@db` (B216's review).
888    let url = crate::masked::url_as_read(url);
889    let Some((_, rest)) = url.split_once("://") else {
890        return false;
891    };
892    let (rest, query) = rest.split_once('?').unwrap_or((rest, ""));
893    let authority = rest.split('/').next().unwrap_or_default();
894    let in_user_info = authority
895        .rsplit_once('@')
896        .is_some_and(|(user_info, _)| user_info.contains(':'));
897    let query = query.split('#').next().unwrap_or_default();
898    in_user_info
899        || query.split('&').any(|pair| {
900            pair.split_once('=').is_some_and(|(name, _)| {
901                crate::masked::percent_decoded(name)
902                    .to_ascii_lowercase()
903                    .ends_with("password")
904            })
905        })
906}
907
908/// `[ops]`.
909#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
910#[serde(default, deny_unknown_fields)]
911pub struct OpsSection {
912    /// The address the ops port listens on (all interfaces by default; `schedr standalone`
913    /// uses its `--listen` address, else 127.0.0.1).
914    pub bind: IpAddr,
915    /// The plain-HTTP port for `/healthz`, `/readyz` and `/metrics`.
916    pub port: u16,
917}
918
919impl Default for OpsSection {
920    /// Port 8090 of every interface and a 2 minute loop stall timeout.
921    fn default() -> Self {
922        Self {
923            bind: IpAddr::V4(Ipv4Addr::UNSPECIFIED),
924            port: 8090,
925        }
926    }
927}
928
929/// `[mapping]`.
930#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
931#[serde(default, deny_unknown_fields)]
932pub struct MappingSection {
933    /// The most instances a mapped task may have in a run; more fail the task, saying so
934    /// (like Airflow's `max_map_length`). At least 1.
935    pub max_instances: u32,
936}
937
938impl Default for MappingSection {
939    /// 1024 instances.
940    fn default() -> Self {
941        Self {
942            max_instances: 1024,
943        }
944    }
945}
946
947/// `[backfill]`: backfills, a run per fire time of a range (`schedr runs backfill`, decisions
948/// 363, 400-404).
949#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
950#[serde(default, deny_unknown_fields)]
951pub struct BackfillSection {
952    /// The most fire times one backfill's range may have, those already run included (so
953    /// it is also the most runs it creates); a bigger range is refused, saying to split it.
954    /// At least 1.
955    pub max_runs: u32,
956}
957
958impl Default for BackfillSection {
959    /// 1000 runs: a year of a daily DAG, a month of an hourly one.
960    fn default() -> Self {
961        Self { max_runs: 1000 }
962    }
963}
964
965/// `[retention]`: how long the database keeps what runs left behind (decisions 430-435). The
966/// master deletes what is older every hour, in batches; never an unfinished run, nor a DAG's
967/// newest scheduled run, its newest run, or the last that ended `success` or `failed`.
968#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
969#[serde(default, deny_unknown_fields)]
970pub struct RetentionSection {
971    /// Finished runs older than this (by their end) are deleted with their tasks, attempts and
972    /// outputs; `"forever"` keeps them.
973    pub runs: Age,
974    /// A finished run's outputs older than this are deleted, its tasks and their outcomes
975    /// kept; the same as `runs` by default. Longer than `runs` changes nothing.
976    pub outputs: Option<Age>,
977    /// Events triggers found and events posted through the API older than this are deleted;
978    /// the same as `runs` by default.
979    pub events: Option<Age>,
980    /// Commands (the audit trail) decided longer ago than this are deleted, whatever their
981    /// runs' age.
982    pub commands: Age,
983}
984
985impl Default for RetentionSection {
986    /// 90 days of runs (their outputs and events the same), 365 days of commands.
987    fn default() -> Self {
988        Self {
989            runs: Age::For(Duration::from_hours(90 * 24)),
990            outputs: None,
991            events: None,
992            commands: Age::For(Duration::from_hours(365 * 24)),
993        }
994    }
995}
996
997impl RetentionSection {
998    /// How long outputs are kept: `outputs`, else `runs`.
999    #[must_use]
1000    pub fn outputs(&self) -> Age {
1001        self.outputs.unwrap_or(self.runs)
1002    }
1003
1004    /// How long events are kept: `events`, else `runs`.
1005    #[must_use]
1006    pub fn events(&self) -> Age {
1007        self.events.unwrap_or(self.runs)
1008    }
1009}
1010
1011/// How long something is kept: a duration (`"90d"`) or `"forever"`.
1012#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1013pub enum Age {
1014    /// Deleted once older than this.
1015    For(Duration),
1016    /// Never deleted.
1017    Forever,
1018}
1019
1020impl Serialize for Age {
1021    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
1022        match self {
1023            Self::For(duration) => serialize_duration(duration, s),
1024            Self::Forever => s.serialize_str("forever"),
1025        }
1026    }
1027}
1028
1029impl<'de> Deserialize<'de> for Age {
1030    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
1031        let text = String::deserialize(d)?;
1032        if text == "forever" {
1033            return Ok(Self::Forever);
1034        }
1035        let duration = crate::units::parse_duration(&text).map_err(serde::de::Error::custom)?;
1036        if duration.is_zero() {
1037            return Err(serde::de::Error::custom(
1038                "a zero age would delete everything; \"forever\" keeps it",
1039            ));
1040        }
1041        Ok(Self::For(duration))
1042    }
1043}
1044
1045impl JsonSchema for Age {
1046    fn schema_name() -> std::borrow::Cow<'static, str> {
1047        "Age".into()
1048    }
1049
1050    fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
1051        schemars::json_schema!({
1052            "type": "string",
1053            "description": "A duration such as `90d` or `12h`, or `forever`.",
1054            "examples": ["90d", "forever"]
1055        })
1056    }
1057}
1058
1059/// `[notifications]`: messages the master sends to channels when runs and tasks end, and
1060/// those tasks send themselves (decisions 408-429).
1061#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
1062#[serde(default, deny_unknown_fields)]
1063pub struct NotificationsSection {
1064    /// The UI's address (`https://schedr.example.com`), the base of the links in messages;
1065    /// none: messages carry no links.
1066    pub ui_url: Option<String>,
1067    /// The events a channel named without events is told of (`RUN_FAILED`, ...).
1068    pub default_events: Vec<String>,
1069    /// How long the master keeps retrying a notification it can't deliver; then it is logged
1070    /// as an error, counted and dropped.
1071    #[serde(
1072        deserialize_with = "deserialize_duration",
1073        serialize_with = "serialize_duration"
1074    )]
1075    #[schemars(with = "DurationText")]
1076    pub give_up_after: Duration,
1077    /// The limit for one delivery (a POST); past it, the delivery failed and is retried.
1078    #[serde(
1079        deserialize_with = "deserialize_duration",
1080        serialize_with = "serialize_duration"
1081    )]
1082    #[schemars(with = "DurationText")]
1083    pub timeout: Duration,
1084    /// The most notifications one task attempt may send itself (`send`); past it, `send`
1085    /// fails. At least 1.
1086    pub max_per_attempt: u32,
1087    /// The URLs a DAG's own webhook (`WebhookChannel`) may post to: its URL must start with
1088    /// one of them (`https://relay.example.com/`); empty: DAGs define none (decision 425).
1089    pub dag_urls: Vec<String>,
1090    /// A PEM file of CAs trusted for notifications besides the system's (a private CA, such
1091    /// as `OpenShift`'s service CA).
1092    pub ca_file: Option<PathBuf>,
1093    /// The server's channels, by name (`[notifications.channels.ops-slack]`): open to every
1094    /// DAG by its name.
1095    pub channels: BTreeMap<String, ChannelConfig>,
1096    /// `[notifications.smtp]`: the mail server every email channel sends through.
1097    pub smtp: SmtpSection,
1098}
1099
1100/// `[notifications.smtp]`: the mail server email channels send through (decisions 411, 426).
1101#[derive(Clone, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
1102#[serde(default, deny_unknown_fields)]
1103pub struct SmtpSection {
1104    /// The server's host; none: no email channel can be configured.
1105    pub host: Option<String>,
1106    /// Its port: 587 (submission, STARTTLS) by default; 465 for `tls = "tls"`.
1107    pub port: u16,
1108    /// How the connection is secured: `starttls` (upgrade, required), `tls` (TLS from the
1109    /// start) or `none` (plain text: a local relay only).
1110    pub tls: SmtpTls,
1111    /// The user to log in as; none: no login.
1112    pub username: Option<String>,
1113    /// Its password: only from `SCHEDR_CONFIG__NOTIFICATIONS__SMTP__PASSWORD`, never the
1114    /// file.
1115    #[serde(skip_serializing_if = "Option::is_none")]
1116    pub password: Option<String>,
1117    /// The sender (`schedr <schedr@example.com>`).
1118    pub from: Option<String>,
1119}
1120
1121impl std::fmt::Debug for DatabaseSection {
1122    /// The URLs with their passwords masked (B206).
1123    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1124        let masked = |url: &Option<String>| url.as_deref().map(crate::masked::mask_url);
1125        f.debug_struct("DatabaseSection")
1126            .field("url", &masked(&self.url))
1127            .field("notifications", &self.notifications)
1128            .field("notifications_url", &masked(&self.notifications_url))
1129            .field("change_notifications", &self.change_notifications)
1130            .finish()
1131    }
1132}
1133
1134impl std::fmt::Debug for ChannelConfig {
1135    /// Without its URL, which may be a capability (Slack's), or its body (B206).
1136    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1137        f.debug_struct("ChannelConfig")
1138            .field("kind", &self.kind)
1139            .field("url", &self.url.as_ref().map(|_| "****"))
1140            .field("headers_env", &self.headers_env)
1141            .field("body", &self.body.as_ref().map(|_| "****"))
1142            .field("to", &self.to)
1143            .finish()
1144    }
1145}
1146
1147impl std::fmt::Debug for SmtpSection {
1148    /// Without the password (Codex's review of M4.13b).
1149    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1150        f.debug_struct("SmtpSection")
1151            .field("host", &self.host)
1152            .field("port", &self.port)
1153            .field("tls", &self.tls)
1154            .field("username", &self.username)
1155            .field("password", &self.password.as_ref().map(|_| "****"))
1156            .field("from", &self.from)
1157            .finish()
1158    }
1159}
1160
1161impl Default for SmtpSection {
1162    /// No server; port 587 with STARTTLS.
1163    fn default() -> Self {
1164        Self {
1165            host: None,
1166            port: 587,
1167            tls: SmtpTls::Starttls,
1168            username: None,
1169            password: None,
1170            from: None,
1171        }
1172    }
1173}
1174
1175/// How an SMTP connection is secured.
1176#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
1177#[serde(rename_all = "snake_case")]
1178pub enum SmtpTls {
1179    /// A plain connection upgraded with STARTTLS, which the server must offer.
1180    Starttls,
1181    /// TLS from the start (port 465).
1182    Tls,
1183    /// No TLS: for a relay on the same host or network only.
1184    None,
1185}
1186
1187impl Default for NotificationsSection {
1188    /// No links, `RUN_FAILED`, giving up after 24 h, 10 s a delivery, 100 sends an attempt,
1189    /// no DAG webhooks, no channels.
1190    fn default() -> Self {
1191        Self {
1192            ui_url: None,
1193            default_events: vec!["RUN_FAILED".to_owned()],
1194            give_up_after: Duration::from_hours(24),
1195            timeout: Duration::from_secs(10),
1196            max_per_attempt: 100,
1197            dag_urls: Vec::new(),
1198            ca_file: None,
1199            channels: BTreeMap::new(),
1200            smtp: SmtpSection::default(),
1201        }
1202    }
1203}
1204
1205/// A server channel (`[notifications.channels.<name>]`, decision 424): its `type`, and the keys
1206/// that type takes (the master refuses another type's).
1207#[derive(Clone, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
1208#[serde(deny_unknown_fields)]
1209pub struct ChannelConfig {
1210    /// `webhook` (an HTTP POST of JSON) or `email`.
1211    #[serde(rename = "type")]
1212    pub kind: ChannelKind,
1213    /// A webhook's URL.
1214    #[serde(default, skip_serializing_if = "Option::is_none")]
1215    pub url: Option<String>,
1216    /// A webhook's headers whose values are read from environment variables, header to
1217    /// variable (`{ Authorization = "OPS_HOOK_TOKEN" }`); a secret is never written in the file.
1218    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
1219    pub headers_env: BTreeMap<String, String>,
1220    /// A webhook's JSON, with `{name}` placeholders in its strings (`{{` for a brace); none:
1221    /// schedr's fixed JSON.
1222    #[serde(default, skip_serializing_if = "Option::is_none")]
1223    #[schemars(with = "Option<serde_json::Map<String, serde_json::Value>>")]
1224    pub body: Option<serde_json::Value>,
1225    /// An email channel's recipients.
1226    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1227    pub to: Vec<String>,
1228}
1229
1230/// A server channel's type.
1231#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
1232#[serde(rename_all = "snake_case")]
1233pub enum ChannelKind {
1234    /// An HTTP POST of JSON (decisions 412, 417, 427).
1235    Webhook,
1236    /// An email, through `[notifications.smtp]` (decision 426).
1237    Email,
1238}
1239
1240/// `[master]`.
1241#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
1242#[serde(default, deny_unknown_fields)]
1243pub struct MasterSection {
1244    /// The address `schedr master` listens on (all interfaces by default; `schedr standalone`
1245    /// always listens on 127.0.0.1).
1246    pub bind: IpAddr,
1247    /// The gRPC port workers connect to.
1248    pub grpc_port: u16,
1249    /// The time between SIGTERM and SIGKILL when an attempt is cancelled.
1250    #[serde(
1251        deserialize_with = "deserialize_duration",
1252        serialize_with = "serialize_duration"
1253    )]
1254    #[schemars(with = "DurationText")]
1255    pub cancel_grace: Duration,
1256    /// How long a task's code may be missing on every eligible worker (git-sync not there
1257    /// yet) before the task is `unschedulable`.
1258    #[serde(
1259        deserialize_with = "deserialize_duration",
1260        serialize_with = "serialize_duration"
1261    )]
1262    #[schemars(with = "DurationText")]
1263    pub code_wait: Duration,
1264    /// How long a worker has for a parse job before it goes to another worker (or the same one
1265    /// again, if no other has that code). Raise it for DAG folders so large that parsing one
1266    /// takes longer; each file still has `[dags] parse_file_timeout`.
1267    #[serde(
1268        deserialize_with = "deserialize_duration",
1269        serialize_with = "serialize_duration"
1270    )]
1271    #[schemars(with = "DurationText")]
1272    pub parse_job_timeout: Duration,
1273    /// Whether rounds visit only busy DAGs and the quiet ones they wake (a run queued or
1274    /// ended, a command, a new version, a fire time coming up), instead of every DAG every
1275    /// round. `false` visits every DAG every round.
1276    pub quiet_dags: bool,
1277}
1278
1279impl Default for MasterSection {
1280    /// All interfaces, port 8070, messages up to 64 MiB, 30 s grace, 10 min for missing code,
1281    /// 10 min for a parse job; a
1282    /// task set aside for 60 s, listening tried again every 30 min; quiet DAGs on, quiet 60 s
1283    /// after a run, woken 60 s ahead, every DAG visited within 60 s.
1284    fn default() -> Self {
1285        Self {
1286            bind: IpAddr::V4(Ipv4Addr::UNSPECIFIED),
1287            grpc_port: 8070,
1288            cancel_grace: Duration::from_secs(30),
1289            parse_job_timeout: Duration::from_mins(10),
1290            code_wait: Duration::from_mins(10),
1291            quiet_dags: true,
1292        }
1293    }
1294}
1295
1296/// `[webserver]`.
1297#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
1298#[serde(default, deny_unknown_fields)]
1299pub struct WebserverSection {
1300    /// The address `schedr webserver` listens on (all interfaces by default; `schedr
1301    /// standalone` always listens on 127.0.0.1).
1302    pub bind: IpAddr,
1303    /// The HTTP port of the REST API (and later the UI).
1304    pub port: u16,
1305    /// The port serving the whole API to `schedr ui` alone, its calls there passing the user's
1306    /// name on (decision 36): in `[tls] mode = "app"` over mTLS (its certificate must name
1307    /// `[tls] ui_name`); in `mesh` mode only with `ui_port_in_mesh`. Elsewhere the UI proves
1308    /// itself by `ui_token_file`.
1309    pub ui_port: u16,
1310    /// In `[tls] mode = "mesh"`: serve `ui_port` in plain HTTP, trusting the mesh to let only
1311    /// `schedr ui` reach it (Istio's `AuthorizationPolicy` admitting only its account: decision
1312    /// 40A), as the mesh is trusted with the master's and workers' links. Nothing in schedr
1313    /// guards that port then: without such a policy, whoever reaches it could name any user.
1314    pub ui_port_in_mesh: bool,
1315    /// A file holding the token `schedr ui` presents (`X-Schedr-Ui-Token`) to prove its calls,
1316    /// where there is no mTLS: `mesh` mode, and standalone (decision 36); mounted from a
1317    /// Secret. None: no caller is trusted that way.
1318    #[serde(skip_serializing_if = "Option::is_none")]
1319    pub ui_token_file: Option<PathBuf>,
1320    /// How long a whole request to a worker may take, to fetch a task's log. Raise it when
1321    /// large logs come slowly; a user waits this long at most for a worker that hangs.
1322    #[serde(
1323        deserialize_with = "deserialize_duration",
1324        serialize_with = "serialize_duration"
1325    )]
1326    #[schemars(with = "DurationText")]
1327    pub worker_request_timeout: Duration,
1328    /// How long a connection test may take when the request doesn't say. Raise it for
1329    /// connections slow to open; `schedr connections test --timeout` sets it for one test.
1330    #[serde(
1331        deserialize_with = "deserialize_duration",
1332        serialize_with = "serialize_duration"
1333    )]
1334    #[schemars(with = "DurationText")]
1335    pub connection_test_timeout: Duration,
1336    /// `[webserver.auth]`: who the user is.
1337    pub auth: AuthSection,
1338}
1339
1340impl Default for WebserverSection {
1341    /// All interfaces, port 8080, live pages refreshed every 15 s when changes can't be
1342    /// followed.
1343    fn default() -> Self {
1344        Self {
1345            bind: IpAddr::V4(Ipv4Addr::UNSPECIFIED),
1346            port: 8080,
1347            worker_request_timeout: Duration::from_secs(30),
1348            connection_test_timeout: Duration::from_mins(1),
1349            ui_port: 8083,
1350            ui_port_in_mesh: false,
1351            ui_token_file: None,
1352            auth: AuthSection::default(),
1353        }
1354    }
1355}
1356
1357/// `[ui]`: the web UI. `schedr ui` is a role of its own that talks only to webservers' REST
1358/// APIs, one per deployment in `deployments` (one the common case); `schedr standalone` serves
1359/// the UI too, next to its API, over its own deployment (`deployments` is not used there).
1360#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
1361#[serde(default, deny_unknown_fields)]
1362pub struct UiSection {
1363    /// The address `schedr ui` listens on (all interfaces by default).
1364    pub bind: IpAddr,
1365    /// The HTTP port of `schedr ui`.
1366    pub port: u16,
1367    /// The deployments `schedr ui` shows, in this order: each a name (shown, and in the UI's
1368    /// URLs) and its webserver's URL.
1369    pub deployments: Vec<UiDeployment>,
1370    /// The documentation site served at `/docs` (the image's); served only when the directory
1371    /// exists, `""` for none.
1372    pub docs_dir: PathBuf,
1373    /// `[ui.auth]`: who the person using the UI is (as `[webserver.auth]`).
1374    pub auth: AuthSection,
1375}
1376
1377impl Default for UiSection {
1378    /// All interfaces, port 8082, no deployments, the image's documentation.
1379    fn default() -> Self {
1380        Self {
1381            bind: IpAddr::V4(Ipv4Addr::UNSPECIFIED),
1382            port: 8082,
1383            deployments: Vec::new(),
1384            docs_dir: PathBuf::from("/usr/share/schedr/docs"),
1385            auth: AuthSection::default(),
1386        }
1387    }
1388}
1389
1390/// A deployment `schedr ui` shows (`[[ui.deployments]]`).
1391#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
1392#[serde(deny_unknown_fields)]
1393pub struct UiDeployment {
1394    /// Its name: letters, digits, `-` and `_` (it is in the UI's URLs).
1395    pub name: String,
1396    /// Its webserver's URL, e.g. `http://schedr-webserver.etl.svc:8080`; with
1397    /// `https://`, its `[webserver] ui_port` over mTLS (this role's `[tls]` certificate).
1398    pub url: String,
1399    /// A file holding the token this UI presents to it (its `[webserver] ui_token_file`'s),
1400    /// where there is no mTLS: a webserver in `mesh` mode, a standalone.
1401    #[serde(default, skip_serializing_if = "Option::is_none")]
1402    pub token_file: Option<PathBuf>,
1403}
1404
1405/// `[webserver.auth]` and `[ui.auth]`: who the user is (see archive/PROJECT.md, Authentication: as
1406/// little as possible in schedr). The name is recorded on commands, never used to allow or
1407/// deny anything; there are no roles.
1408#[derive(Debug, Clone, PartialEq, Eq, Default, Deserialize, Serialize, JsonSchema)]
1409#[serde(default, deny_unknown_fields)]
1410pub struct AuthSection {
1411    /// How the user is known.
1412    pub mode: AuthMode,
1413    /// `none`: a header naming the user, recorded if present (e.g. `x-forwarded-user`, set
1414    /// by a mesh from its token); `proxy_header`: the header the SSO proxy sets, required
1415    /// (`x-forwarded-user` when not set).
1416    #[serde(skip_serializing_if = "Option::is_none")]
1417    pub identity_header: Option<String>,
1418    /// `basic`: a file of `name:bcrypt-hash` lines (mounted from a Secret; never in the
1419    /// configuration itself).
1420    #[serde(skip_serializing_if = "Option::is_none")]
1421    pub users_file: Option<PathBuf>,
1422    /// `basic` beyond a loopback address: TLS is ended by a proxy in front (passwords would
1423    /// otherwise cross the network in the clear: refused without it).
1424    pub behind_tls_proxy: bool,
1425    /// `proxy_header` beyond a loopback address: everything reaching it comes through the
1426    /// proxy (anything reaching it around the proxy could name any user: refused without it).
1427    pub allow_remote: bool,
1428}
1429
1430/// `[webserver.auth] mode`, `[ui.auth] mode`.
1431#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize, Serialize, JsonSchema)]
1432#[serde(rename_all = "snake_case")]
1433pub enum AuthMode {
1434    /// Whoever reaches it: access is decided in front (a mesh, the namespace).
1435    #[default]
1436    None,
1437    /// An SSO proxy in front logs users in and names them in a header.
1438    ProxyHeader,
1439    /// HTTP Basic against `users_file`.
1440    Basic,
1441}
1442
1443/// `[worker]`.
1444#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
1445#[serde(default, deny_unknown_fields)]
1446pub struct WorkerSection {
1447    /// The worker's ID, stable across restarts; the host name when not set.
1448    #[serde(skip_serializing_if = "Option::is_none")]
1449    pub id: Option<String>,
1450    /// Task slots.
1451    pub slots: u32,
1452    /// The queues served; none serves `default`.
1453    pub queues: Vec<String>,
1454    /// Where task logs, the journal (`journal/<id>`; keep it across restarts), the copies of
1455    /// the DAG roots' code that parse jobs and tasks import from (`code/<id>`, one or two per
1456    /// root, read-only) and (in standalone) the SQLite database go; `$XDG_DATA_HOME/schedr`
1457    /// (else `~/.local/share/schedr`) when not set.
1458    #[serde(skip_serializing_if = "Option::is_none")]
1459    pub data_dir: Option<PathBuf>,
1460    /// Where commands' connection files go while their attempts run (`.pgpass`, SSH keys:
1461    /// secrets as files their tools read), in a folder per worker; the worker's user's own,
1462    /// mode 0700, or the worker refuses to start. In memory when not set: under `/dev/shm`
1463    /// where it exists, else `connections/` in `data_dir`.
1464    #[serde(skip_serializing_if = "Option::is_none")]
1465    pub connection_dir: Option<PathBuf>,
1466    /// Agent environment variables passed to tasks besides the allow-list.
1467    pub pass_env: Vec<String>,
1468    /// The master's gRPC URL, e.g. `https://schedr-master:8070` (`http://` with `[tls] mode =
1469    /// "mesh"`); required by `schedr worker`
1470    /// (`schedr standalone` connects to its own master).
1471    #[serde(skip_serializing_if = "Option::is_none")]
1472    pub master_url: Option<String>,
1473    /// How long running tasks get when the worker is asked to stop (SIGTERM): match the
1474    /// pod's `terminationGracePeriodSeconds`.
1475    #[serde(
1476        deserialize_with = "deserialize_duration",
1477        serialize_with = "serialize_duration"
1478    )]
1479    #[schemars(with = "DurationText")]
1480    pub termination_grace_period: Duration,
1481    /// For a task still running when a drain's time is up: from its SIGTERM to its SIGKILL
1482    /// (the drain's own, instead of `[master] cancel_grace`). The running tasks get
1483    /// `termination_grace_period` minus this and `drain_report_period`, whose sum must not
1484    /// exceed it.
1485    #[serde(
1486        deserialize_with = "deserialize_duration",
1487        serialize_with = "serialize_duration"
1488    )]
1489    #[schemars(with = "DurationText")]
1490    pub drain_terminate_period: Duration,
1491    /// The address the log endpoint listens on (all interfaces by default; `schedr
1492    /// standalone` always listens on 127.0.0.1).
1493    pub log_bind: IpAddr,
1494    /// The log endpoint's port (0: a free one).
1495    pub log_port: u16,
1496    /// The host the webserver reaches the log endpoint at, sent to the master (e.g. the pod's
1497    /// DNS name through a headless Service); the host name when not set.
1498    #[serde(skip_serializing_if = "Option::is_none")]
1499    pub log_address: Option<String>,
1500    /// Task logs older than this are deleted.
1501    #[serde(
1502        deserialize_with = "deserialize_duration",
1503        serialize_with = "serialize_duration"
1504    )]
1505    #[schemars(with = "DurationText")]
1506    pub log_retention: Duration,
1507    /// Beyond this many bytes of logs the oldest are deleted; no limit when not set.
1508    #[serde(
1509        deserialize_with = "deserialize_optional_size",
1510        serialize_with = "serialize_optional_size",
1511        skip_serializing_if = "Option::is_none"
1512    )]
1513    #[schemars(with = "Option<SizeText>")]
1514    pub log_max_size: Option<u64>,
1515    /// The mode of the log files the worker creates (task, attempt, parse and watcher-host
1516    /// logs), in octal: owner-only `"0600"` by default, as the journal and connection files. A
1517    /// log shipper reading them under another uid needs them opened on purpose: `"0640"` for
1518    /// one in the worker's group. At most `"0644"`, and the owner always reads and writes.
1519    #[serde(deserialize_with = "deserialize_mode_text")]
1520    pub log_mode: String,
1521    /// Each task's memory budget; when not set, (the pod's limit โˆ’ 10 %) รท slots.
1522    #[serde(
1523        deserialize_with = "deserialize_optional_size",
1524        serialize_with = "serialize_optional_size",
1525        skip_serializing_if = "Option::is_none"
1526    )]
1527    #[schemars(with = "Option<SizeText>")]
1528    pub memory_budget: Option<u64>,
1529    /// The part of the pod's memory limit kept out of task budgets (for schedr's own process):
1530    /// a percentage (`25%`) or a size (`1GiB`); when not set, 10 % for `schedr worker` and 25 %
1531    /// for `schedr standalone` (whose process also runs the master and the API). Not used when
1532    /// `memory_budget` is set.
1533    #[serde(skip_serializing_if = "Option::is_none")]
1534    pub memory_reserve: Option<MemoryReserve>,
1535    /// How long a started Python runner has to say hello. Raise it where the interpreter is
1536    /// slow to start (cold storage, a loaded machine); a runner that can't start is noticed
1537    /// this much later.
1538    #[serde(
1539        deserialize_with = "deserialize_duration",
1540        serialize_with = "serialize_duration"
1541    )]
1542    #[schemars(with = "DurationText")]
1543    pub runner_start_timeout: Duration,
1544    /// How long a fork server may take to import its preloaded libraries. Raise it for large
1545    /// preload lists or slow storage; until it is up, tasks are spawned instead.
1546    #[serde(
1547        deserialize_with = "deserialize_duration",
1548        serialize_with = "serialize_duration"
1549    )]
1550    #[schemars(with = "DurationText")]
1551    pub fork_server_preload_timeout: Duration,
1552    /// How long one try of a cleanup may run, for a task that doesn't set `cleanup_timeout`.
1553    /// The attempt holds its slot meanwhile: raise it if your cleanups wait on slow systems,
1554    /// lower it to free slots sooner. When not set, 5 minutes or what a drain leaves of
1555    /// `termination_grace_period` for a cleanup, whichever is shorter (25 s with the defaults;
1556    /// B252: a longer one is lost when the pod is killed at the grace period's end), at least
1557    /// 1 s.
1558    #[serde(
1559        deserialize_with = "deserialize_optional_duration",
1560        serialize_with = "serialize_optional_duration",
1561        skip_serializing_if = "Option::is_none"
1562    )]
1563    #[schemars(with = "Option<DurationText>")]
1564    pub cleanup_timeout: Option<Duration>,
1565    /// How long one try of a resource's cleanup may run, for one that doesn't set `timeout`.
1566    /// It ends a cleanup hung on a system that never answers, which can't be cancelled with
1567    /// its run and holds the run (and its `max_active_runs` slot) until it ends. Raise it for
1568    /// teardowns that take longer (a cluster's deletion), lower it to notice a hang sooner.
1569    #[serde(
1570        deserialize_with = "deserialize_duration",
1571        serialize_with = "serialize_duration"
1572    )]
1573    #[schemars(with = "DurationText")]
1574    pub resource_cleanup_timeout: Duration,
1575    /// How long a fork server whose preloaded library fails to import is retried (with
1576    /// backoff, from the first failure), for what isn't ready when the pod starts (a
1577    /// sidecar's network, a mount); `0s`: not retried. Threads after preloading and a version
1578    /// mismatch are never retried (they don't change until the image does).
1579    #[serde(
1580        deserialize_with = "deserialize_duration",
1581        serialize_with = "serialize_duration"
1582    )]
1583    #[schemars(with = "DurationText")]
1584    pub fork_server_import_retry: Duration,
1585}
1586
1587impl Default for WorkerSection {
1588    /// The host name, 2 slots, the `default` queue, the default data directory, 30 s of grace
1589    /// (Kubernetes' default) of which the last 5 s stop and report what still runs (3 s to
1590    /// SIGKILL, 2 s to report), the log endpoint on port 8081 of every interface, logs kept for
1591    /// 30 days and mode 0600, the memory budget from the pod's limit, sampled every second, 30 s for a runner
1592    /// to start, 5 minutes for a fork server to preload and for a cleanup's try, 30 minutes for
1593    /// a resource cleanup's try, a fork server's failing import retried for 20 minutes.
1594    fn default() -> Self {
1595        Self {
1596            id: None,
1597            slots: 2,
1598            queues: Vec::new(),
1599            data_dir: None,
1600            connection_dir: None,
1601            pass_env: Vec::new(),
1602            termination_grace_period: Duration::from_secs(30),
1603            drain_terminate_period: Duration::from_secs(3),
1604            master_url: None,
1605            log_bind: IpAddr::V4(Ipv4Addr::UNSPECIFIED),
1606            log_port: 8081,
1607            log_address: None,
1608            log_retention: Duration::from_hours(24 * 30),
1609            log_max_size: None,
1610            log_mode: "0600".to_owned(),
1611            memory_budget: None,
1612            memory_reserve: None,
1613            runner_start_timeout: Duration::from_secs(30),
1614            fork_server_preload_timeout: Duration::from_mins(5),
1615            cleanup_timeout: None,
1616            resource_cleanup_timeout: Duration::from_mins(30),
1617            fork_server_import_retry: Duration::from_mins(20),
1618        }
1619    }
1620}
1621
1622/// `[tls] mode`.
1623#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize, Serialize, JsonSchema)]
1624#[serde(rename_all = "lowercase")]
1625pub enum TlsMode {
1626    /// schedr's own mTLS on every internal link.
1627    #[default]
1628    App,
1629    /// Plain traffic: a service mesh (e.g. Istio) provides mTLS between the pods.
1630    Mesh,
1631}
1632
1633/// `[events]`: events posted through the API (`POST /api/v1/events`, decision 354).
1634#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
1635#[serde(default, deny_unknown_fields)]
1636pub struct EventsSection {
1637    /// The largest event's data, as JSON; a bigger one is refused (`413`).
1638    #[serde(
1639        deserialize_with = "deserialize_size",
1640        serialize_with = "serialize_size"
1641    )]
1642    #[schemars(with = "SizeText")]
1643    pub max_size: u64,
1644}
1645
1646impl Default for EventsSection {
1647    fn default() -> Self {
1648        Self {
1649            max_size: 1024 * 1024,
1650        }
1651    }
1652}
1653
1654/// `[grpc]`: the link between the master and its workers. Set the same on both: each end reads
1655/// its own.
1656#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
1657#[serde(default, deny_unknown_fields)]
1658pub struct GrpcSection {
1659    /// The largest message either end takes from the other: a root's parse upload (every DAG it
1660    /// defines, in one message) or a `Finished` with its output, to the master; an assignment
1661    /// carrying another DAG's run result (`wait_for=`), to a worker. A larger upload is refused
1662    /// and the worker logs it; a larger message on the stream ends it; a run result too big for
1663    /// it fails the call that would carry it. From 4 MiB (gRPC's default) to 1 GiB.
1664    #[serde(
1665        deserialize_with = "deserialize_size",
1666        serialize_with = "serialize_size"
1667    )]
1668    #[schemars(with = "SizeText")]
1669    pub max_message_size: u64,
1670}
1671
1672impl Default for GrpcSection {
1673    fn default() -> Self {
1674        Self {
1675            max_message_size: 64 * 1024 * 1024,
1676        }
1677    }
1678}
1679
1680/// `[tls]`: certificates are PEM files (mounted from Kubernetes Secrets), read again when they
1681/// change.
1682#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
1683#[serde(default, deny_unknown_fields)]
1684pub struct TlsSection {
1685    /// Whether schedr does mTLS itself (`app`) or leaves it to a mesh (`mesh`).
1686    pub mode: TlsMode,
1687    /// The CA certificates peers' certificates must be signed by.
1688    #[serde(skip_serializing_if = "Option::is_none")]
1689    pub ca: Option<PathBuf>,
1690    /// This role's certificate (chain).
1691    #[serde(skip_serializing_if = "Option::is_none")]
1692    pub cert: Option<PathBuf>,
1693    /// This role's private key.
1694    #[serde(skip_serializing_if = "Option::is_none")]
1695    pub key: Option<PathBuf>,
1696    /// The name the webserver expects in workers' certificates, whatever address it reaches
1697    /// them at.
1698    pub worker_name: String,
1699    /// The name a webserver expects in `schedr ui`'s certificate on its `[webserver] ui_port`
1700    /// (decision 36: only a caller so proven may pass a user's name on).
1701    pub ui_name: String,
1702    /// How often the files are read again for a change.
1703    #[serde(
1704        deserialize_with = "deserialize_duration",
1705        serialize_with = "serialize_duration"
1706    )]
1707    #[schemars(with = "DurationText")]
1708    pub reload_interval: Duration,
1709}
1710
1711impl Default for TlsSection {
1712    /// `app` mode, no files yet, workers named `schedr-worker`, the UI `schedr-ui`, files read
1713    /// every 30 s, 10 s for a handshake.
1714    fn default() -> Self {
1715        Self {
1716            mode: TlsMode::App,
1717            ca: None,
1718            cert: None,
1719            key: None,
1720            worker_name: "schedr-worker".to_owned(),
1721            ui_name: "schedr-ui".to_owned(),
1722            reload_interval: Duration::from_secs(30),
1723        }
1724    }
1725}
1726
1727/// `[secret_storage]`: where a worker's tasks get their secrets (only workers fetch them; see
1728/// archive/PROJECT.md, Secret storage). Each storage is a table of its own, named by its key
1729/// (`[secret_storage.vault]`); standalone always has the `db` storage besides them.
1730#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
1731#[serde(default)]
1732pub struct SecretStorageSection {
1733    /// The storage `secrets['...']` means: one configured below, or `db` in standalone. Unset:
1734    /// the only storage configured, else `db` in standalone (none on a worker).
1735    #[serde(skip_serializing_if = "Option::is_none")]
1736    pub default: Option<String>,
1737    /// Values shorter than this many characters aren't masked in logs and outputs (masking
1738    /// `1` would mangle them); the task's log says which.
1739    pub min_mask_length: usize,
1740    /// The storages, by name.
1741    #[serde(flatten)]
1742    pub storages: BTreeMap<String, SecretStorageConfig>,
1743}
1744
1745impl Default for SecretStorageSection {
1746    /// No storages, values from 5 characters masked.
1747    fn default() -> Self {
1748        Self {
1749            default: None,
1750            min_mask_length: 5,
1751            storages: BTreeMap::new(),
1752        }
1753    }
1754}
1755
1756/// A secret storage's kind.
1757#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
1758#[serde(rename_all = "snake_case")]
1759pub enum SecretStorageType {
1760    /// The `secrets` table of schedr's database, encrypted under `SCHEDR_SECRET_KEY`
1761    /// (standalone only).
1762    Db,
1763    /// Vault's KV v2 (`HashiCorp` Vault).
1764    Vault,
1765}
1766
1767/// `[secret_storage.<name>]`: one secret storage. Its `Debug` hides the token.
1768#[derive(Clone, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
1769#[serde(deny_unknown_fields)]
1770pub struct SecretStorageConfig {
1771    /// Its kind: `db` or `vault`.
1772    #[serde(rename = "type")]
1773    pub kind: SecretStorageType,
1774    /// Vault's address, e.g. `https://vault.example.com:8200` (`vault`).
1775    #[serde(default, skip_serializing_if = "Option::is_none")]
1776    pub address: Option<String>,
1777    /// The KV v2 mount (`vault`; default `secret`).
1778    #[serde(default, skip_serializing_if = "Option::is_none")]
1779    pub mount: Option<String>,
1780    /// The Vault Enterprise namespace (`vault`).
1781    #[serde(default, skip_serializing_if = "Option::is_none")]
1782    pub namespace: Option<String>,
1783    /// A PEM file of the CA certificates Vault's certificate is checked against, instead of
1784    /// the system's (`vault`).
1785    #[serde(default, skip_serializing_if = "Option::is_none")]
1786    pub ca_cert: Option<PathBuf>,
1787    /// How the agent logs in to Vault (`vault`).
1788    #[serde(default, skip_serializing_if = "Option::is_none")]
1789    pub auth: Option<VaultAuthConfig>,
1790    /// The Vault token for `auth = { method = "token" }`: only from
1791    /// `SCHEDR_CONFIG__SECRET_STORAGE__<NAME>__TOKEN`, never the file.
1792    #[serde(default, skip_serializing_if = "Option::is_none")]
1793    pub token: Option<String>,
1794    /// How long one request to Vault may take (`vault`). Raise it for a slow or distant Vault;
1795    /// a task reading a secret waits this long at most for one that hangs.
1796    #[serde(
1797        default = "default_vault_request_timeout",
1798        deserialize_with = "deserialize_duration",
1799        serialize_with = "serialize_duration"
1800    )]
1801    #[schemars(with = "DurationText")]
1802    pub request_timeout: Duration,
1803    /// How long connecting to Vault may take (`vault`). Raise it on a slow network.
1804    #[serde(
1805        default = "default_vault_connect_timeout",
1806        deserialize_with = "deserialize_duration",
1807        serialize_with = "serialize_duration"
1808    )]
1809    #[schemars(with = "DurationText")]
1810    pub connect_timeout: Duration,
1811    /// How long a fetched value is kept in the agent's memory (never on disk); `0s` fetches
1812    /// every time.
1813    #[serde(
1814        default = "default_cache_ttl",
1815        deserialize_with = "deserialize_duration",
1816        serialize_with = "serialize_duration"
1817    )]
1818    #[schemars(with = "DurationText")]
1819    pub cache_ttl: Duration,
1820    /// Path prefixes whose values aren't masked (e.g. `["variables/"]`: settings, not
1821    /// credentials).
1822    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1823    pub unmasked_prefixes: Vec<String>,
1824}
1825
1826impl std::fmt::Debug for SecretStorageConfig {
1827    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1828        f.debug_struct("SecretStorageConfig")
1829            .field("kind", &self.kind)
1830            .field("address", &self.address)
1831            .field("mount", &self.mount)
1832            .field("namespace", &self.namespace)
1833            .field("ca_cert", &self.ca_cert)
1834            .field("auth", &self.auth)
1835            .field("token", &self.token.as_ref().map(|_| crate::masked::MASK))
1836            .field("request_timeout", &self.request_timeout)
1837            .field("connect_timeout", &self.connect_timeout)
1838            .field("cache_ttl", &self.cache_ttl)
1839            .field("unmasked_prefixes", &self.unmasked_prefixes)
1840            .finish()
1841    }
1842}
1843
1844/// How the agent logs in to Vault.
1845#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
1846#[serde(rename_all = "snake_case")]
1847pub enum VaultAuthMethod {
1848    /// A token from the environment (`SCHEDR_CONFIG__SECRET_STORAGE__<NAME>__TOKEN`): local
1849    /// development.
1850    Token,
1851    /// Vault's Kubernetes auth method, with the pod's service-account token.
1852    Kubernetes,
1853}
1854
1855/// `auth = { ... }` of a Vault storage.
1856#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
1857#[serde(deny_unknown_fields)]
1858pub struct VaultAuthConfig {
1859    /// `token` or `kubernetes`.
1860    pub method: VaultAuthMethod,
1861    /// The Vault role (`kubernetes`).
1862    #[serde(default, skip_serializing_if = "Option::is_none")]
1863    pub role: Option<String>,
1864    /// The auth method's mount (`kubernetes`; default `kubernetes`).
1865    #[serde(default, skip_serializing_if = "Option::is_none")]
1866    pub mount: Option<String>,
1867    /// The service-account token's file (`kubernetes`; default
1868    /// `/var/run/secrets/kubernetes.io/serviceaccount/token`).
1869    #[serde(default, skip_serializing_if = "Option::is_none")]
1870    pub token_file: Option<PathBuf>,
1871}
1872
1873const fn default_vault_request_timeout() -> Duration {
1874    Duration::from_secs(30)
1875}
1876
1877const fn default_vault_connect_timeout() -> Duration {
1878    Duration::from_secs(10)
1879}
1880
1881const fn default_cache_ttl() -> Duration {
1882    Duration::from_secs(60)
1883}
1884
1885/// `[worker] log_mode` as a mode: octal, within 0644, with the owner's read and write; `None`
1886/// for one that isn't.
1887#[must_use]
1888pub fn log_mode(text: &str) -> Option<u32> {
1889    let digits = text.strip_prefix("0o").unwrap_or(text);
1890    if digits.is_empty() || digits.len() > 4 {
1891        return None;
1892    }
1893    let mode = u32::from_str_radix(digits, 8).ok()?;
1894    (mode & !0o644 == 0 && mode & 0o600 == 0o600).then_some(mode)
1895}