1use jiff::{SignedDuration, Timestamp};
8
9use crate::database::{Database, DbError};
10use crate::query::{db_time, from_json, in_tx, on_pool, parse_time, sql, storable_json, to_json};
11
12#[cfg(test)]
13mod tests;
14
15pub const MASTER_ROW_KEPT: SignedDuration = SignedDuration::from_hours(1);
18
19#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
21pub struct NodeProblem {
22 pub error: bool,
24 pub message: String,
26}
27
28#[derive(Debug, Clone, PartialEq)]
30pub struct MasterNode<'a> {
31 pub master_id: &'a str,
33 pub process_id: &'a str,
35 pub host: &'a str,
37 pub schedr_version: &'a str,
39 pub config: &'a serde_json::Value,
41 pub started_at: Timestamp,
43 pub problems: &'a [NodeProblem],
45 pub usage: Option<&'a schedr_model::usage::NodeUsage>,
47}
48
49#[derive(Debug, Clone, PartialEq)]
51pub struct MasterRecord {
52 pub master_id: String,
54 pub process_id: String,
56 pub host: String,
58 pub schedr_version: String,
60 pub config: serde_json::Value,
62 pub started_at: Timestamp,
64 pub heard_at: Timestamp,
66 pub leading: bool,
68 pub problems: Vec<NodeProblem>,
70 pub usage: Option<schedr_model::usage::NodeUsage>,
72}
73
74#[derive(Debug, Clone, PartialEq)]
76pub struct WorkerNode {
77 pub worker_id: String,
79 pub master_id: Option<String>,
81 pub process_id: Option<String>,
83 pub config: Option<serde_json::Value>,
85 pub usage: Option<schedr_model::usage::WorkerUsage>,
87}
88
89impl Database {
90 pub async fn heartbeat_master(
96 &self,
97 master: &MasterNode<'_>,
98 now: Timestamp,
99 ) -> Result<(), DbError> {
100 self.heartbeat_master_keeping(master, now, MASTER_ROW_KEPT)
101 .await
102 }
103
104 pub async fn heartbeat_master_keeping(
112 &self,
113 master: &MasterNode<'_>,
114 now: Timestamp,
115 kept: SignedDuration,
116 ) -> Result<(), DbError> {
117 const UPSERT: &str = "INSERT INTO masters (master_id, process_id, host, schedr_version, \
118 config, started_at, heard_at, problems, usage) \
119 VALUES ($1, $2, $3, $4, $5{json}, $6{ts}, $7{ts}, $8{json}, $9{json}) \
120 ON CONFLICT (master_id) DO UPDATE SET process_id = excluded.process_id, \
121 host = excluded.host, schedr_version = excluded.schedr_version, \
122 config = excluded.config, heard_at = excluded.heard_at, \
123 problems = excluded.problems, usage = excluded.usage";
124 const PRUNE: &str = "DELETE FROM masters WHERE heard_at < $1{ts}";
125 let config = storable_json(master.config.to_string());
126 let problems = storable_json(
127 serde_json::to_string(master.problems).unwrap_or_else(|_| "[]".to_owned()),
128 );
129 let usage = master.usage.map(to_json);
130 let gone = now.checked_sub(kept).unwrap_or(Timestamp::UNIX_EPOCH);
131 in_tx!(self, |tx, backend| {
132 sqlx::query(sql(backend, UPSERT))
133 .bind(master.master_id)
134 .bind(master.process_id)
135 .bind(master.host)
136 .bind(master.schedr_version)
137 .bind(&config)
138 .bind(db_time(master.started_at))
139 .bind(db_time(now))
140 .bind(&problems)
141 .bind(&usage)
142 .execute(&mut *tx)
143 .await?;
144 sqlx::query(sql(backend, PRUNE))
145 .bind(db_time(gone))
146 .execute(&mut *tx)
147 .await?;
148 });
149 Ok(())
150 }
151
152 pub async fn masters(&self, since: Timestamp) -> Result<Vec<MasterRecord>, DbError> {
159 const MASTERS: &str = "SELECT m.master_id, m.process_id, m.host, m.schedr_version, \
160 m.config{text}, {ts<}m.started_at{>ts}, {ts<}m.heard_at{>ts}, m.problems{text}, \
161 m.usage{text} FROM masters m WHERE m.heard_at >= $1{ts} ORDER BY m.master_id";
162 type Row = (
163 String,
164 String,
165 String,
166 String,
167 String,
168 String,
169 String,
170 String,
171 Option<String>,
172 );
173 let rows: Vec<Row> = on_pool!(self, |pool, backend| {
174 sqlx::query_as(sql(backend, MASTERS))
175 .bind(db_time(since))
176 .fetch_all(pool)
177 .await?
178 });
179 let holder = self.lease_holder().await?;
180 let mut masters = rows
181 .into_iter()
182 .map(
183 |(
184 master_id,
185 process_id,
186 host,
187 version,
188 config,
189 started,
190 heard,
191 problems,
192 usage,
193 )| {
194 Ok(MasterRecord {
195 leading: holder.as_deref() == Some(master_id.as_str()),
196 master_id,
197 process_id,
198 host,
199 schedr_version: version,
200 config: from_json("masters.config", &config)?,
201 started_at: parse_time("masters.started_at", &started)?,
202 heard_at: parse_time("masters.heard_at", &heard)?,
203 problems: from_json("masters.problems", &problems)?,
204 usage: usage.map(|u| from_json("masters.usage", &u)).transpose()?,
205 })
206 },
207 )
208 .collect::<Result<Vec<_>, DbError>>()?;
209 masters.sort_by_key(|m| !m.leading);
210 Ok(masters)
211 }
212
213 pub async fn set_worker_node(
220 &self,
221 worker_id: &str,
222 master_id: Option<&str>,
223 process_id: Option<&str>,
224 config: Option<&serde_json::Value>,
225 ) -> Result<(), DbError> {
226 const SET: &str = "UPDATE workers SET master_id = $1, process_id = $2, config = $3{json} \
227 WHERE worker_id = $4";
228 let config = config.map(|c| storable_json(c.to_string()));
229 in_tx!(self, |tx, backend| {
230 sqlx::query(sql(backend, SET))
231 .bind(master_id)
232 .bind(process_id)
233 .bind(config)
234 .bind(worker_id)
235 .execute(&mut *tx)
236 .await?;
237 });
238 Ok(())
239 }
240
241 pub async fn worker_nodes(&self) -> Result<Vec<WorkerNode>, DbError> {
247 const NODES: &str = "SELECT worker_id, master_id, process_id, config{text}, usage{text} \
248 FROM workers ORDER BY worker_id";
249 type Row = (
250 String,
251 Option<String>,
252 Option<String>,
253 Option<String>,
254 Option<String>,
255 );
256 let rows: Vec<Row> = on_pool!(self, |pool, backend| {
257 sqlx::query_as(sql(backend, NODES)).fetch_all(pool).await?
258 });
259 rows.into_iter()
260 .map(|(worker_id, master_id, process_id, config, usage)| {
261 Ok(WorkerNode {
262 worker_id,
263 master_id,
264 process_id,
265 config: config
266 .map(|c| from_json("workers.config", &c))
267 .transpose()?,
268 usage: usage.map(|u| from_json("workers.usage", &u)).transpose()?,
269 })
270 })
271 .collect()
272 }
273
274 pub async fn set_worker_usage(
280 &self,
281 worker_id: &str,
282 usage: &schedr_model::usage::WorkerUsage,
283 now: Timestamp,
284 ) -> Result<(), DbError> {
285 const SET: &str =
286 "UPDATE workers SET usage = $1{json}, usage_at = $3{ts} WHERE worker_id = $2";
287 in_tx!(self, |tx, backend| {
288 sqlx::query(sql(backend, SET))
289 .bind(to_json(usage))
290 .bind(worker_id)
291 .bind(db_time(now))
292 .execute(&mut *tx)
293 .await?;
294 });
295 Ok(())
296 }
297}