1use std::time::Duration;
11
12use jiff::Timestamp;
13use schedr_model::commands::{Command, CommandStatus};
14use sqlx::Connection as _;
15use sqlx::postgres::PgListener;
16use uuid::Uuid;
17
18use crate::database::{Database, DbError, Pool};
19use crate::query::{
20 Starting, db_time, from_json, from_name, in_tx, on_pool, parse_time, sql, to_json,
21};
22
23macro_rules! pending_from {
25 () => {
26 "FROM commands WHERE status = 'pending'"
27 };
28}
29pub(crate) use pending_from;
30
31#[cfg(test)]
32mod tests;
33
34const PROBE_ROUNDS: usize = 5;
36
37const PROBE_LIMITS: u32 = 4;
39
40pub async fn listening_is_safe(
52 y: &mut sqlx::PgConnection,
53 x: &mut sqlx::PgConnection,
54) -> Result<bool, sqlx::Error> {
55 const PROCESS: &str = "SELECT pg_backend_pid()";
56 for _ in 0..PROBE_ROUNDS {
57 let before: i32 = sqlx::query_scalar(PROCESS).fetch_one(&mut *y).await?;
58 let mut held = sqlx::Connection::begin(&mut *x).await?;
59 let other: i32 = sqlx::query_scalar(PROCESS).fetch_one(&mut *held).await?;
60 let after: i32 = sqlx::query_scalar(PROCESS).fetch_one(&mut *y).await?;
61 held.rollback().await?;
62 if other == before || after != before {
63 return Ok(false);
64 }
65 }
66 Ok(true)
67}
68
69pub const COMMANDS_CHANNEL: &str = "schedr_commands";
71
72pub const EVENTS_CHANNEL: &str = "schedr_events";
76
77#[derive(Debug)]
80pub struct CommandNotifications {
81 listener: PgListener,
82}
83
84#[derive(Debug, Clone, Copy, PartialEq, Eq)]
86pub enum Notified {
87 Command,
89 Event {
92 triggers: bool,
94 waiters: bool,
96 },
97}
98
99impl CommandNotifications {
100 pub async fn next(&mut self) -> Result<Notified, DbError> {
107 let notification = self.listener.recv().await?;
108 Ok(if notification.channel() == EVENTS_CHANNEL {
109 let payload = notification.payload();
110 Notified::Event {
111 triggers: payload.contains('t'),
112 waiters: payload.contains('w'),
113 }
114 } else {
115 Notified::Command
116 })
117 }
118
119 pub async fn skip_arrived(&mut self) -> bool {
123 let mut event = false;
124 while let Ok(Ok(notification)) =
125 tokio::time::timeout(Duration::ZERO, self.listener.recv()).await
126 {
127 event |= notification.channel() == EVENTS_CHANNEL;
128 }
129 event
130 }
131}
132
133#[derive(Debug)]
135pub(crate) enum Listening {
136 NotPostgres,
138 Off,
140 Unsafe {
142 through: &'static str,
144 },
145 Ready(PgListener),
147}
148
149#[derive(Debug, Clone, PartialEq, Eq)]
151pub struct PendingCommand {
152 pub id: String,
154 pub command: Result<Command, String>,
156 pub requested_by: String,
158 pub requested_at: Timestamp,
160 pub applying: bool,
162}
163
164#[derive(Debug, Clone, PartialEq, Eq)]
166pub struct CommandRecord {
167 pub id: String,
169 pub kind: String,
171 pub status: CommandStatus,
173 pub reason: Option<String>,
175 pub result: Option<serde_json::Value>,
177 pub requested_by: String,
179 pub requested_at: Timestamp,
181 pub decided_at: Option<Timestamp>,
183}
184
185#[derive(Debug, Clone, PartialEq, Eq)]
187pub enum Submitted {
188 New(String),
190 Again(String),
192 KeyTaken,
194}
195
196type RecordRow = (
197 String,
198 String,
199 String,
200 Option<String>,
201 Option<String>,
202 String,
203 String,
204 Option<String>,
205);
206
207impl Database {
208 pub async fn insert_command(
214 &self,
215 command: &Command,
216 requested_by: &str,
217 now: Timestamp,
218 ) -> Result<String, DbError> {
219 match self
220 .submit_command(command, requested_by, None, now)
221 .await?
222 {
223 Submitted::New(id) | Submitted::Again(id) => Ok(id),
224 Submitted::KeyTaken => unreachable!("a command without a key is always new"),
225 }
226 }
227
228 pub async fn submit_command(
236 &self,
237 command: &Command,
238 requested_by: &str,
239 key: Option<&str>,
240 now: Timestamp,
241 ) -> Result<Submitted, DbError> {
242 const INSERT: &str = "INSERT INTO commands \
243 (id, kind, payload, requested_by, requested_at, request_key) \
244 VALUES ($1{uuid}, $2, $3{json}, $4, $5{ts}, $6) \
245 ON CONFLICT (requested_by, request_key) WHERE request_key IS NOT NULL DO NOTHING";
246 const BY_KEY: &str = "SELECT id{text}, payload{text} FROM commands \
247 WHERE requested_by = $1 AND request_key = $2";
248 let id = Uuid::now_v7().to_string();
249 let payload = to_json(command);
250 let earlier: Option<(String, String)> = in_tx!(self, |tx, backend| {
251 let inserted = sqlx::query(sql(backend, INSERT))
252 .bind(&id)
253 .bind(command.kind())
254 .bind(&payload)
255 .bind(requested_by)
256 .bind(db_time(now))
257 .bind(key)
258 .execute(&mut *tx)
259 .await?
260 .rows_affected();
261 if inserted == 1 {
262 None
263 } else {
264 Some(
265 sqlx::query_as(sql(backend, BY_KEY))
266 .bind(requested_by)
267 .bind(key)
268 .fetch_one(&mut *tx)
269 .await?,
270 )
271 }
272 });
273 if let Some((earlier, stored)) = earlier {
274 let stored: serde_json::Value = from_json("commands.payload", &stored)?;
276 let sent: serde_json::Value = from_json("commands.payload", &payload)?;
277 return Ok(if stored == sent {
278 Submitted::Again(earlier)
279 } else {
280 Submitted::KeyTaken
281 });
282 }
283 self.notify(COMMANDS_CHANNEL, &id).await;
284 Ok(Submitted::New(id))
285 }
286
287 pub(crate) async fn notify(&self, channel: &str, id: &str) {
291 if let Pool::Postgres(pool) = self.pool()
292 && self.notifications().on
293 && let Err(error) = sqlx::query("SELECT pg_notify($1, $2)")
294 .bind(channel)
295 .bind(id)
296 .execute(pool)
297 .await
298 {
299 tracing::warn!(%error, channel, id, "stored, its notification failed");
300 }
301 }
302
303 pub async fn command_notifications(&self) -> Result<Option<CommandNotifications>, DbError> {
315 let mut listener = match self.checked_listener().await? {
316 Listening::NotPostgres => return Ok(None),
317 Listening::Off => {
318 tracing::info!(
319 "notifications off (`[database] notifications = false`): new commands are \
320 picked up by polling, every round"
321 );
322 return Ok(None);
323 }
324 Listening::Unsafe { through } => {
325 tracing::warn!(
326 through,
327 "the connection the master would listen through passes a connection pooler \
328 in transaction mode (PgBouncer or similar), where listening breaks other \
329 connections: notifications off, new commands are picked up by polling, \
330 every round. For immediate commands set `[database] notifications_url` to \
331 a connection straight to Postgres; `notifications = false` silences this"
332 );
333 return Ok(None);
334 }
335 Listening::Ready(listener) => listener,
336 };
337 listener
338 .listen_all([COMMANDS_CHANNEL, EVENTS_CHANNEL])
339 .await?;
340 Ok(Some(CommandNotifications { listener }))
341 }
342
343 pub(crate) async fn checked_listener(&self) -> Result<Listening, DbError> {
352 let Pool::Postgres(pool) = self.pool() else {
353 return Ok(Listening::NotPostgres);
354 };
355 let notifications = self.notifications();
356 if !notifications.on {
357 return Ok(Listening::Off);
358 }
359 let url = notifications.url.as_deref();
360 let checked = self
361 .limited(self.query_timeout() * PROBE_LIMITS, async {
362 Ok(if let Some(url) = url {
363 let mut y = sqlx::PgConnection::connect(url).await?;
364 let mut x = sqlx::PgConnection::connect(url).await?;
365 listening_is_safe(&mut y, &mut x).await?
366 } else {
367 let mut y = Starting::new(pool.acquire().await?);
370 let mut x = Starting::new(pool.acquire().await?);
371 let safe = listening_is_safe(y.conn(), x.conn()).await?;
372 y.completed();
373 x.completed();
374 safe
375 })
376 })
377 .await;
378 let safe = match checked {
382 Ok(safe) => safe,
383 Err(error @ DbError::QueryTimeout(_)) => {
384 tracing::warn!(
385 %error,
386 "couldn't check whether a listening connection passes a connection pooler \
387 in transaction mode (the database answered too slowly): polling for now"
388 );
389 return Err(error);
390 }
391 Err(error) => return Err(error),
392 };
393 if !safe {
394 return Ok(Listening::Unsafe {
395 through: if url.is_some() {
396 "notifications_url"
397 } else {
398 "url"
399 },
400 });
401 }
402 Ok(Listening::Ready(match url {
403 Some(url) => PgListener::connect(url).await?,
404 None => PgListener::connect_with(pool).await?,
405 }))
406 }
407
408 pub async fn pending_commands(&self, limit: u32) -> Result<Vec<PendingCommand>, DbError> {
415 const PENDING: &str = concat!(
416 "SELECT id{text}, payload{text}, requested_by, \
417 {ts<}requested_at{>ts}, {ts<}applying_at{>ts} ",
418 pending_from!(),
419 " ORDER BY requested_at, id LIMIT $1"
420 );
421 type Row = (String, String, String, String, Option<String>);
422 if self.skipped(crate::probe::Check::Commands).await? {
423 return Ok(Vec::new());
424 }
425 let rows: Vec<Row> = on_pool!(self, |pool, backend| {
426 sqlx::query_as(sql(backend, PENDING))
427 .bind(i64::from(limit))
428 .fetch_all(pool)
429 .await?
430 });
431 rows.into_iter()
432 .map(|(id, payload, requested_by, requested_at, applying_at)| {
433 Ok(PendingCommand {
434 id,
435 command: serde_json::from_str(&payload).map_err(|e| e.to_string()),
436 requested_by,
437 requested_at: parse_time("commands.requested_at", &requested_at)?,
438 applying: applying_at.is_some(),
439 })
440 })
441 .collect()
442 }
443
444 pub async fn mark_applying(&self, id: &str, now: Timestamp) -> Result<(), DbError> {
451 const MARK: &str = "UPDATE commands SET applying_at = $1{ts} \
452 WHERE id = $2{uuid} AND status = 'pending'";
453 in_tx!(self, |tx, backend| {
454 sqlx::query(sql(backend, MARK))
455 .bind(db_time(now))
456 .bind(id)
457 .execute(&mut *tx)
458 .await?
459 .rows_affected()
460 });
461 Ok(())
462 }
463
464 pub async fn decide_command(
471 &self,
472 id: &str,
473 status: CommandStatus,
474 reason: Option<&str>,
475 result: Option<&serde_json::Value>,
476 now: Timestamp,
477 ) -> Result<bool, DbError> {
478 const DECIDE: &str = "UPDATE commands SET status = $1, reason = $2, result = $3{json}, \
479 decided_at = $4{ts} WHERE id = $5{uuid} AND status = 'pending'";
480 let decided = in_tx!(self, |tx, backend| {
481 sqlx::query(sql(backend, DECIDE))
482 .bind(
483 serde_json::to_value(status)
484 .ok()
485 .and_then(|v| v.as_str().map(str::to_owned)),
486 )
487 .bind(reason)
488 .bind(result.map(to_json))
489 .bind(db_time(now))
490 .bind(id)
491 .execute(&mut *tx)
492 .await?
493 .rows_affected()
494 });
495 Ok(decided == 1)
496 }
497
498 pub async fn set_command_result(
505 &self,
506 id: &str,
507 result: &serde_json::Value,
508 ) -> Result<bool, DbError> {
509 const SET: &str =
510 "UPDATE commands SET result = $1{json} WHERE id = $2{uuid} AND status = 'applied'";
511 let set = in_tx!(self, |tx, backend| {
512 sqlx::query(sql(backend, SET))
513 .bind(to_json(result))
514 .bind(id)
515 .execute(&mut *tx)
516 .await?
517 .rows_affected()
518 });
519 Ok(set == 1)
520 }
521
522 pub async fn command(&self, id: &str) -> Result<Option<CommandRecord>, DbError> {
528 const ONE: &str = "SELECT id{text}, kind, status, reason, result{text}, requested_by, \
529 {ts<}requested_at{>ts}, {ts<}decided_at{>ts} FROM commands WHERE id = $1{uuid}";
530 let row: Option<RecordRow> = on_pool!(self, |pool, backend| {
531 sqlx::query_as(sql(backend, ONE))
532 .bind(id)
533 .fetch_optional(pool)
534 .await?
535 });
536 row.map(record).transpose()
537 }
538
539 pub async fn run_commands(&self, run_id: &str) -> Result<Vec<CommandRecord>, DbError> {
547 const OF_RUN: &str = "SELECT id{text}, kind, status, reason, result{text}, \
548 requested_by, {ts<}requested_at{>ts}, {ts<}decided_at{>ts} FROM commands \
549 WHERE payload ->> 'run_id' = $1 OR result ->> 'run_id' = $1 \
550 OR (kind = 'pause_dag' AND result{text} LIKE $2) \
551 ORDER BY requested_at, commands.id";
552 let rows: Vec<RecordRow> = on_pool!(self, |pool, backend| {
553 sqlx::query_as(sql(backend, OF_RUN))
554 .bind(run_id)
555 .bind(format!("%\"{run_id}\"%"))
557 .fetch_all(pool)
558 .await?
559 });
560 rows.into_iter().map(record).collect()
561 }
562
563 pub async fn connections_commands_lost(&self, why: &str) -> Result<usize, DbError> {
571 const RUNNING: &str = "SELECT id{text}, kind, status, reason, result{text}, \
572 requested_by, {ts<}requested_at{>ts}, {ts<}decided_at{>ts} FROM commands \
573 WHERE status = 'applied' AND kind IN ('check_connections', 'test_connection') \
574 AND result{text} LIKE '%\"running\"%'";
575 let rows: Vec<RecordRow> = on_pool!(self, |pool, backend| {
576 sqlx::query_as(sql(backend, RUNNING))
577 .fetch_all(pool)
578 .await?
579 });
580 let mut changed = 0;
581 for row in rows {
582 let command = record(row)?;
583 let Some(mut result) = command.result else {
584 continue;
585 };
586 let mut lost = false;
587 let jobs = result
588 .get_mut("jobs")
589 .and_then(serde_json::Value::as_array_mut);
590 for job in jobs.into_iter().flatten() {
591 if job.get("state").and_then(serde_json::Value::as_str) == Some("running") {
592 job["state"] = "lost".into();
593 job["reason"] = why.into();
594 lost = true;
595 }
596 }
597 if lost && self.set_command_result(&command.id, &result).await? {
598 changed += 1;
599 }
600 }
601 Ok(changed)
602 }
603}
604
605fn record(row: RecordRow) -> Result<CommandRecord, DbError> {
606 let (id, kind, status, reason, result, requested_by, requested_at, decided_at) = row;
607 Ok(CommandRecord {
608 id,
609 kind,
610 status: from_name("commands.status", status)?,
611 reason,
612 result: result
613 .map(|r| from_json("commands.result", &r))
614 .transpose()?,
615 requested_by,
616 requested_at: parse_time("commands.requested_at", &requested_at)?,
617 decided_at: decided_at
618 .map(|t| parse_time("commands.decided_at", &t))
619 .transpose()?,
620 })
621}