Skip to main content

schedr_api/
state.rs

1//! What every request handler shares.
2
3use std::sync::Arc;
4
5use jiff::Timestamp;
6use schedr_db::Database;
7use schedr_model::SchedrVersion;
8
9use crate::auth::Auth;
10use crate::events::Feed;
11use crate::logs::{HttpLogSource, LogSource};
12use crate::metrics::ApiMetrics;
13
14#[cfg(test)]
15mod tests;
16
17pub use crate::auth::ANONYMOUS;
18
19/// The webserver's shared state.
20#[derive(Debug, Clone)]
21pub struct ApiState {
22    /// The database (read directly; actions are command rows).
23    pub db: Database,
24    /// The server's version, for the version check.
25    pub version: SchedrVersion,
26    /// The server's full version, sent in `Schedr-Server-Version`.
27    pub version_text: &'static str,
28    /// Who the user is (`[webserver.auth]`, and the UI's proof: see [`crate::auth`]).
29    pub auth: Auth,
30    /// The clock (replaced in tests).
31    pub clock: fn() -> Timestamp,
32    /// Where task logs come from (the workers).
33    pub logs: Arc<dyn LogSource>,
34    /// The webserver's metrics.
35    pub metrics: ApiMetrics,
36    /// How long a connection test may take when its request doesn't say.
37    pub connection_test_timeout: std::time::Duration,
38    /// The workers' heartbeat interval: a poke trigger whose last call ended longer ago than
39    /// three times its `every` plus this is stuck.
40    pub heartbeat_interval: std::time::Duration,
41    /// What changed, for `GET /api/v1/changes`.
42    pub feed: Feed,
43    /// The largest posted event's data (`[events] max_size`).
44    pub max_event_size: usize,
45    /// This webserver as a node of its deployment (`GET /api/v1/deployment`), its
46    /// configuration masked.
47    pub node: Arc<crate::views::NodeView>,
48    /// What this process uses now (decision 463); none by default (the binary reads `/proc`).
49    pub usage: fn() -> Option<schedr_model::usage::NodeUsage>,
50    /// The Metrics endpoints' final buckets, kept between requests.
51    pub series: Arc<crate::series::cache::SeriesCache>,
52    /// The Metrics page's throughput and start latency's final buckets, kept the same way.
53    pub flow: Arc<crate::task_flow::FlowCache>,
54    /// How far its reads reach and what they allow (decision 493).
55    pub limits: ApiLimits,
56}
57
58impl ApiState {
59    /// State over `db` for this build of schedr, with the system clock, reading logs from
60    /// workers over plain HTTP (see [`Self::with_logs`]).
61    #[must_use]
62    pub fn new(db: Database, identity_header: Option<String>) -> Self {
63        let feed = Feed::new(db.clone());
64        Self {
65            db,
66            version: SchedrVersion::current(),
67            version_text: env!("CARGO_PKG_VERSION"),
68            auth: Auth::identity(identity_header),
69            clock: Timestamp::now,
70            logs: Arc::new(HttpLogSource::new(None)),
71            metrics: ApiMetrics::default(),
72            connection_test_timeout: crate::routes::CONNECTION_TEST_TIMEOUT,
73            // The configuration's default; the webserver passes its own.
74            heartbeat_interval: std::time::Duration::from_secs(10),
75            feed,
76            max_event_size: crate::named_events::DEFAULT_MAX_EVENT_SIZE,
77            node: Arc::new(crate::views::NodeView {
78                process_id: String::new(),
79                host: String::new(),
80                schedr_version: env!("CARGO_PKG_VERSION").to_owned(),
81                config: serde_json::json!({}),
82                usage: None,
83            }),
84            usage: || None,
85            series: Arc::default(),
86            flow: Arc::default(),
87            limits: ApiLimits::default(),
88        }
89    }
90
91    /// This state with the webserver's limits, its Metrics cache's included (decision 493).
92    #[must_use]
93    pub fn with_limits(self, limits: ApiLimits, cache: crate::series::cache::CacheLimits) -> Self {
94        Self {
95            limits,
96            series: Arc::new(crate::series::cache::SeriesCache::new(cache)),
97            ..self
98        }
99    }
100
101    /// This state, giving a connection test `timeout` when its request doesn't say.
102    #[must_use]
103    pub fn with_connection_test_timeout(self, timeout: std::time::Duration) -> Self {
104        Self {
105            connection_test_timeout: timeout,
106            ..self
107        }
108    }
109
110    /// This state, judging a poke trigger stuck with `interval`, the workers' heartbeat.
111    #[must_use]
112    pub fn with_heartbeat_interval(self, interval: std::time::Duration) -> Self {
113        Self {
114            heartbeat_interval: interval,
115            ..self
116        }
117    }
118
119    /// This state, refusing posted events whose data is over `bytes` (`[events] max_size`).
120    #[must_use]
121    pub fn with_max_event_size(self, bytes: usize) -> Self {
122        Self {
123            max_event_size: bytes,
124            ..self
125        }
126    }
127
128    /// This state reading what its process uses with `usage` (decision 463).
129    #[must_use]
130    pub fn with_usage(self, usage: fn() -> Option<schedr_model::usage::NodeUsage>) -> Self {
131        Self { usage, ..self }
132    }
133
134    /// This state's webserver shown as `node` (its configuration masked by the caller).
135    #[must_use]
136    pub fn with_node(self, node: crate::views::NodeView) -> Self {
137        Self {
138            node: Arc::new(node),
139            ..self
140        }
141    }
142
143    /// This state recording its metrics in `metrics` (registered by the caller).
144    #[must_use]
145    pub fn with_metrics(self, metrics: ApiMetrics) -> Self {
146        Self { metrics, ..self }
147    }
148
149    /// This state's live pages refreshed every `interval` when the database's changes can't be
150    /// followed (`refresh_interval`).
151    #[must_use]
152    pub fn with_refresh(self, interval: std::time::Duration) -> Self {
153        Self {
154            feed: self.feed.clone().with_refresh(interval),
155            ..self
156        }
157    }
158
159    /// This state following the database's changes as `timings` say.
160    #[must_use]
161    pub fn with_event_timings(self, timings: crate::events::EventTimings) -> Self {
162        Self {
163            feed: self.feed.clone().with_timings(timings),
164            ..self
165        }
166    }
167
168    /// This state telling who the user is by `auth`.
169    #[must_use]
170    pub fn with_auth(self, auth: Auth) -> Self {
171        Self { auth, ..self }
172    }
173
174    /// This state reading logs from `logs` (over TLS in `app` mode).
175    #[must_use]
176    pub fn with_logs(self, logs: Arc<dyn LogSource>) -> Self {
177        Self { logs, ..self }
178    }
179}
180
181/// How far the webserver's reads reach and what its writes allow, each a
182/// `SCHEDR_HIDDEN__WEBSERVER__*` value (decision 493).
183#[derive(Debug, Clone, Copy, PartialEq, Eq)]
184pub struct ApiLimits {
185    /// How far back the DAG page's memory p95s reach (`MEMORY_PEAKS_WINDOW`).
186    pub memory_peaks_window: jiff::SignedDuration,
187    /// The runs, and one task's attempts, a p95 is taken from at most (`MEMORY_PEAKS_RUNS`).
188    pub memory_peaks_runs: u32,
189    /// How far ahead of now a posted event's `at` may be (`SCHEDR_HIDDEN__EVENTS__FUTURE_TOLERANCE`).
190    pub event_future_tolerance: jiff::SignedDuration,
191    /// A master heard from within this long is on the Deployments page: three of its node
192    /// heartbeats (`SCHEDR_HIDDEN__MASTER__NODE_HEARTBEAT`).
193    pub masters_heard_within: jiff::SignedDuration,
194    /// A process with no sample within this long has ended (the Metrics page folds it): three
195    /// of the master's sample intervals (`SCHEDR_HIDDEN__MASTER__SAMPLE_INTERVAL`).
196    pub sampled_within: jiff::SignedDuration,
197}
198
199impl Default for ApiLimits {
200    fn default() -> Self {
201        Self {
202            memory_peaks_window: crate::attempt_memory::PEAKS_OVER,
203            memory_peaks_runs: schedr_db::task_memory::PEAKS_PER_TASK,
204            event_future_tolerance: crate::named_events::AT_TOLERANCE,
205            masters_heard_within: crate::routes::MASTERS_HEARD_WITHIN,
206            sampled_within: crate::routes::SAMPLED_WITHIN,
207        }
208    }
209}