1use jiff::Timestamp;
9use schedr_model::WorkerState;
10
11use crate::database::{Database, DbError};
12use crate::query::{
13 db_time, from_json, from_name, in_tx, on_pool, optional_time, parse_time, sql, to_json,
14};
15
16#[cfg(test)]
17mod tests;
18
19#[derive(Debug, Clone, PartialEq, Eq)]
21pub struct WorkerRegistration<'a> {
22 pub id: &'a str,
24 pub incarnation: &'a str,
26 pub protocol_version: &'a str,
28 pub schedr_version: &'a str,
30 pub queues: &'a [String],
32 pub slots: u32,
34 pub watcher_slots: u32,
36 pub log_endpoint: &'a str,
38}
39
40#[derive(Debug, Clone, PartialEq, Eq)]
42pub struct WorkerRecord {
43 pub id: String,
45 pub incarnation: String,
47 pub state: WorkerState,
49 pub protocol_version: String,
51 pub schedr_version: String,
53 pub queues: Vec<String>,
55 pub slots: u32,
57 pub log_endpoint: String,
59 pub registered_at: Timestamp,
61 pub last_heartbeat_at: Timestamp,
63 pub offline_at: Option<Timestamp>,
65 pub running: u32,
67 pub drained: bool,
69 pub warnings: Vec<WorkerWarning>,
71 pub watcher_slots: u32,
73 pub watcher_hosts: Vec<WatcherHostRecord>,
75}
76
77#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
79pub struct WatcherHostRecord {
80 pub code: String,
82 pub wait_steps: u32,
84 pub threads: u32,
86 pub tied_threads: u32,
88 pub memory_bytes: u64,
90 pub hosts_lost: u64,
92}
93
94#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
96pub struct WorkerWarning {
97 pub kind: String,
99 pub interpreter: String,
101 pub message: String,
103}
104
105type WorkerRow = (
106 String,
107 String,
108 String,
109 String,
110 String,
111 String,
112 i32,
113 String,
114 String,
115 String,
116 Option<String>,
117 i64,
118 bool,
119 String,
120 i32,
121 String,
122);
123
124impl Database {
125 pub async fn register_worker(
131 &self,
132 worker: &WorkerRegistration<'_>,
133 now: Timestamp,
134 ) -> Result<(), DbError> {
135 const UPSERT: &str = "INSERT INTO workers (worker_id, incarnation_id, state, \
136 protocol_version, schedr_version, queues, slots, log_endpoint, registered_at, \
137 last_heartbeat_at, offline_at, watcher_slots, watcher_hosts) \
138 VALUES ($1, $2{uuid}, 'active', $3, $4, $5{json}, $6, $7, $8{ts}, $8{ts}, NULL, $9, \
139 $10{json}) \
140 ON CONFLICT (worker_id) DO UPDATE SET incarnation_id = excluded.incarnation_id, \
141 state = 'active', protocol_version = excluded.protocol_version, \
142 schedr_version = excluded.schedr_version, queues = excluded.queues, \
143 slots = excluded.slots, log_endpoint = excluded.log_endpoint, \
144 registered_at = excluded.registered_at, \
145 last_heartbeat_at = excluded.last_heartbeat_at, offline_at = NULL, \
146 watcher_slots = excluded.watcher_slots, watcher_hosts = excluded.watcher_hosts";
147 in_tx!(self, |tx, backend| {
148 sqlx::query(sql(backend, UPSERT))
149 .bind(worker.id)
150 .bind(worker.incarnation)
151 .bind(worker.protocol_version)
152 .bind(worker.schedr_version)
153 .bind(to_json(&worker.queues))
154 .bind(i32::try_from(worker.slots).unwrap_or(i32::MAX))
155 .bind(worker.log_endpoint)
156 .bind(db_time(now))
157 .bind(i32::try_from(worker.watcher_slots).unwrap_or(i32::MAX))
158 .bind("[]")
159 .execute(&mut *tx)
160 .await?;
161 });
162 Ok(())
163 }
164
165 pub async fn worker_seen(&self, worker_id: &str, now: Timestamp) -> Result<(), DbError> {
171 const SEEN: &str = "UPDATE workers SET last_heartbeat_at = $1{ts} WHERE worker_id = $2";
172 in_tx!(self, |tx, backend| {
173 sqlx::query(sql(backend, SEEN))
174 .bind(db_time(now))
175 .bind(worker_id)
176 .execute(&mut *tx)
177 .await?;
178 });
179 Ok(())
180 }
181
182 pub async fn set_worker_warnings(
188 &self,
189 worker_id: &str,
190 warnings: &[WorkerWarning],
191 ) -> Result<(), DbError> {
192 const SET: &str = "UPDATE workers SET warnings = $1{json} WHERE worker_id = $2";
193 in_tx!(self, |tx, backend| {
194 sqlx::query(sql(backend, SET))
195 .bind(to_json(&warnings))
196 .bind(worker_id)
197 .execute(&mut *tx)
198 .await?;
199 });
200 Ok(())
201 }
202
203 pub async fn set_worker_hosts(
209 &self,
210 worker_id: &str,
211 hosts: &[WatcherHostRecord],
212 ) -> Result<(), DbError> {
213 const SET: &str = "UPDATE workers SET watcher_hosts = $1{json} WHERE worker_id = $2";
214 in_tx!(self, |tx, backend| {
215 sqlx::query(sql(backend, SET))
216 .bind(to_json(&hosts))
217 .bind(worker_id)
218 .execute(&mut *tx)
219 .await?;
220 });
221 Ok(())
222 }
223
224 pub async fn set_worker_state(
230 &self,
231 worker_id: &str,
232 state: WorkerState,
233 now: Timestamp,
234 ) -> Result<(), DbError> {
235 const STATE: &str = "UPDATE workers SET state = $1, \
236 offline_at = CASE WHEN $2 THEN $3{ts} ELSE offline_at END WHERE worker_id = $4";
237 in_tx!(self, |tx, backend| {
238 sqlx::query(sql(backend, STATE))
239 .bind(state.to_string())
240 .bind(state.is_gone())
241 .bind(db_time(now))
242 .bind(worker_id)
243 .execute(&mut *tx)
244 .await?;
245 });
246 Ok(())
247 }
248
249 pub async fn set_worker_drained(
255 &self,
256 worker_id: &str,
257 drained: bool,
258 ) -> Result<bool, DbError> {
259 const DRAINED: &str = "UPDATE workers SET drained = $1 WHERE worker_id = $2";
260 let updated = in_tx!(self, |tx, backend| {
261 sqlx::query(sql(backend, DRAINED))
262 .bind(drained)
263 .bind(worker_id)
264 .execute(&mut *tx)
265 .await?
266 .rows_affected()
267 });
268 Ok(updated > 0)
269 }
270
271 pub async fn resume_worker(&self, worker_id: &str) -> Result<Option<bool>, DbError> {
278 const RESUME: &str = "UPDATE workers SET drained = $1 WHERE worker_id = $2 AND drained";
279 const KNOWN: &str = "SELECT 1 FROM workers WHERE worker_id = $1";
280 let (resumed, known) = in_tx!(self, |tx, backend| {
281 let resumed = sqlx::query(sql(backend, RESUME))
282 .bind(false)
283 .bind(worker_id)
284 .execute(&mut *tx)
285 .await?
286 .rows_affected();
287 let known: Option<i32> = sqlx::query_scalar(sql(backend, KNOWN))
288 .bind(worker_id)
289 .fetch_optional(&mut *tx)
290 .await?;
291 (resumed, known)
292 });
293 Ok(known.map(|_| resumed > 0))
294 }
295
296 pub async fn worker_drained(&self, worker_id: &str) -> Result<bool, DbError> {
302 const DRAINED: &str = "SELECT drained FROM workers WHERE worker_id = $1";
303 let drained: Option<bool> = on_pool!(self, |pool, backend| {
304 sqlx::query_scalar(sql(backend, DRAINED))
305 .bind(worker_id)
306 .fetch_optional(pool)
307 .await?
308 });
309 Ok(drained.unwrap_or(false))
310 }
311
312 pub async fn worker_log_endpoint(
319 &self,
320 worker_id: &str,
321 ) -> Result<Option<(WorkerState, String)>, DbError> {
322 const ENDPOINT: &str = "SELECT state, log_endpoint FROM workers WHERE worker_id = $1";
323 let row: Option<(String, String)> = on_pool!(self, |pool, backend| {
324 sqlx::query_as(sql(backend, ENDPOINT))
325 .bind(worker_id)
326 .fetch_optional(pool)
327 .await?
328 });
329 row.map(|(state, endpoint)| Ok((from_name("workers.state", state)?, endpoint)))
330 .transpose()
331 }
332
333 pub async fn workers(&self) -> Result<Vec<WorkerRecord>, DbError> {
339 const WORKERS: &str = "SELECT w.worker_id, w.incarnation_id{text}, w.state, \
340 w.protocol_version, w.schedr_version, w.queues{text}, w.slots, w.log_endpoint, \
341 {ts<}w.registered_at{>ts}, {ts<}w.last_heartbeat_at{>ts}, {ts<}w.offline_at{>ts}, \
342 (SELECT COUNT(*) FROM attempts a WHERE a.worker_id = w.worker_id \
343 AND a.status IS NULL), w.drained, w.warnings{text}, w.watcher_slots, \
344 w.watcher_hosts{text} \
345 FROM workers w ORDER BY w.worker_id";
346 let rows: Vec<WorkerRow> = on_pool!(self, |pool, backend| {
347 sqlx::query_as(sql(backend, WORKERS))
348 .fetch_all(pool)
349 .await?
350 });
351 rows.into_iter().map(worker_record).collect()
352 }
353}
354
355fn worker_record(row: WorkerRow) -> Result<WorkerRecord, DbError> {
356 let (
357 id,
358 incarnation,
359 state,
360 protocol_version,
361 schedr_version,
362 queues,
363 slots,
364 log_endpoint,
365 registered,
366 heartbeat,
367 offline,
368 running,
369 drained,
370 warnings,
371 watcher_slots,
372 watcher_hosts,
373 ) = row;
374 Ok(WorkerRecord {
375 id,
376 incarnation,
377 state: from_name("workers.state", state)?,
378 protocol_version,
379 schedr_version,
380 queues: from_json("workers.queues", &queues)?,
381 slots: u32::try_from(slots).unwrap_or(0),
382 log_endpoint,
383 registered_at: parse_time("workers.registered_at", ®istered)?,
384 last_heartbeat_at: parse_time("workers.last_heartbeat_at", &heartbeat)?,
385 offline_at: optional_time("workers.offline_at", offline)?,
386 running: u32::try_from(running).unwrap_or(0),
387 drained,
388 warnings: from_json("workers.warnings", &warnings)?,
389 watcher_slots: u32::try_from(watcher_slots).unwrap_or(0),
390 watcher_hosts: from_json("workers.watcher_hosts", &watcher_hosts)?,
391 })
392}