1use std::{
170 collections::{HashMap, HashSet},
171 fmt,
172 future::Future,
173 pin::Pin,
174 sync::Arc,
175 time::Duration,
176};
177
178use sqlx::{PgConnection, PgExecutor, PgPool, Postgres, Row, Transaction, postgres::PgPoolOptions};
179use tokio::sync::{Notify, OwnedSemaphorePermit, Semaphore, watch};
180use uuid::Uuid;
181
182pub use sqlx::types::chrono::{DateTime, Utc};
183
184pub type Result<T, E = Error> = std::result::Result<T, E>;
186
187#[derive(Debug)]
189#[non_exhaustive]
190pub enum Error {
191 Database(sqlx::Error),
193 Encode(serde_json::Error),
195 Job(String),
197 NotACode {
200 what: &'static str,
202 },
203 NotATenant,
205}
206
207impl fmt::Display for Error {
208 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
209 match self {
210 Self::Database(error) => error.fmt(f),
211 Self::Encode(error) => error.fmt(f),
212 Self::Job(text) => write!(f, "worker error: {text}"),
213 Self::NotACode { what } => write!(
214 f,
215 "`{what}` must be 1 to {MAX_REASON_CHARS} characters with no line breaks"
216 ),
217 Self::NotATenant => f.write_str(
218 "a job's tenant must be 1 to 63 lower-case letters, digits, and hyphens, \
219 not starting or ending with a hyphen",
220 ),
221 }
222 }
223}
224
225impl std::error::Error for Error {
226 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
227 match self {
228 Self::Database(error) => Some(error),
229 Self::Encode(error) => Some(error),
230 Self::Job(_) | Self::NotACode { .. } | Self::NotATenant => None,
231 }
232 }
233}
234
235impl From<sqlx::Error> for Error {
236 fn from(error: sqlx::Error) -> Self {
237 Self::Database(error)
238 }
239}
240
241impl From<serde_json::Error> for Error {
242 fn from(error: serde_json::Error) -> Self {
243 Self::Encode(error)
244 }
245}
246
247type JobFuture = Pin<Box<dyn Future<Output = Result<(), Failure>> + Send>>;
248type Handler = Arc<dyn Fn(Option<String>, serde_json::Value) -> JobFuture + Send + Sync>;
249
250const SETUP: &str = "CREATE TABLE IF NOT EXISTS axa_queue (
251 id UUID PRIMARY KEY,
252 name TEXT NOT NULL,
253 args JSONB NOT NULL,
254 status TEXT NOT NULL DEFAULT 'queued',
255 error TEXT,
256 run_at TIMESTAMPTZ NOT NULL DEFAULT now(),
257 started_at TIMESTAMPTZ,
258 created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
259 updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
260)";
261const SETUP_INDEX: &str =
262 "CREATE INDEX IF NOT EXISTS axa_queue_ready ON axa_queue (run_at) WHERE status = 'queued'";
263const SETUP_ATTEMPTS: &str =
265 "ALTER TABLE axa_queue ADD COLUMN IF NOT EXISTS attempts INTEGER NOT NULL DEFAULT 0";
266const SETUP_MAX_ATTEMPTS: &str =
268 "ALTER TABLE axa_queue ADD COLUMN IF NOT EXISTS max_attempts INTEGER";
269const SETUP_PRIORITY: &str =
271 "ALTER TABLE axa_queue ADD COLUMN IF NOT EXISTS priority SMALLINT NOT NULL DEFAULT 0";
272const SETUP_TIMEOUT: &str = "ALTER TABLE axa_queue ADD COLUMN IF NOT EXISTS timeout_ms BIGINT";
274const SETUP_TENANT: &str = "ALTER TABLE axa_queue ADD COLUMN IF NOT EXISTS tenant TEXT
276 CONSTRAINT axa_queue_tenant_id CHECK (tenant ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$')";
277const SETUP_UNIQUE_KEY: &str = "ALTER TABLE axa_queue ADD COLUMN IF NOT EXISTS unique_key TEXT
279 CONSTRAINT axa_queue_unique_key_code
280 CHECK (length(unique_key) BETWEEN 1 AND 200 AND unique_key !~ '[[:cntrl:]]')";
281const SETUP_UNIQUE_INDEX: &str = "CREATE UNIQUE INDEX IF NOT EXISTS axa_queue_unique
283 ON axa_queue (name, (COALESCE(tenant, '')), unique_key)
284 WHERE unique_key IS NOT NULL AND status IN ('queued', 'running')";
285const SETUP_CLAIM_INDEX: &str = "CREATE INDEX IF NOT EXISTS axa_queue_claim
286 ON axa_queue (priority DESC, run_at) WHERE status = 'queued'";
287const SETUP_SCHEDULE: &str = "CREATE TABLE IF NOT EXISTS axa_schedule (
288 name TEXT PRIMARY KEY,
289 due_at TIMESTAMPTZ NOT NULL,
290 last_job UUID,
291 interval_ms BIGINT,
292 seen_at TIMESTAMPTZ NOT NULL DEFAULT now(),
293 archived_at TIMESTAMPTZ,
294 created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
295 updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
296)";
297const SETUP_SCHEDULE_CRON: &str = "ALTER TABLE axa_schedule ADD COLUMN IF NOT EXISTS cron TEXT";
303const SETUP_ACTS: &str = "CREATE TABLE IF NOT EXISTS axa_job_acts (
304 id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
305 job_id UUID NOT NULL,
306 job_name TEXT NOT NULL,
307 act TEXT NOT NULL CHECK (act IN ('cancelled', 'retried', 'released')),
308 attempts INTEGER NOT NULL,
309 by TEXT NOT NULL CHECK (length(by) BETWEEN 1 AND 200 AND by !~ '[[:cntrl:]]'),
310 reason TEXT NOT NULL CHECK (length(reason) BETWEEN 1 AND 200 AND reason !~ '[[:cntrl:]]'),
311 at TIMESTAMPTZ NOT NULL DEFAULT now()
312)";
313const SETUP_ACTS_INDEX: &str =
314 "CREATE INDEX IF NOT EXISTS axa_job_acts_job ON axa_job_acts (job_id, id)";
315const SETUP_ACTS_REFUSE: &str = "CREATE OR REPLACE FUNCTION axa_job_acts_refuse() RETURNS trigger
317LANGUAGE plpgsql AS $$
318BEGIN
319 RAISE EXCEPTION '% on % is refused: acts on jobs are only ever added to',
320 TG_OP, TG_TABLE_NAME;
321END
322$$";
323const SETUP_ACTS_ROWS: &str = "CREATE OR REPLACE TRIGGER axa_job_acts_refuse
324 BEFORE UPDATE OR DELETE ON axa_job_acts
325 FOR EACH ROW EXECUTE FUNCTION axa_job_acts_refuse()";
326const SETUP_ACTS_TRUNCATE: &str = "CREATE OR REPLACE TRIGGER axa_job_acts_refuse_truncate
327 BEFORE TRUNCATE ON axa_job_acts
328 FOR EACH STATEMENT EXECUTE FUNCTION axa_job_acts_refuse()";
329const SETUP_ACTS_ALWAYS: &str = "ALTER TABLE axa_job_acts
332 ENABLE ALWAYS TRIGGER axa_job_acts_refuse,
333 ENABLE ALWAYS TRIGGER axa_job_acts_refuse_truncate";
334pub const NOTIFY_CHANNEL: &str = "axa_queue";
336const SETUP_NOTIFY_FUNCTION: &str = "CREATE OR REPLACE FUNCTION axa_queue_notify() RETURNS trigger
338LANGUAGE plpgsql AS $$
339BEGIN
340 PERFORM pg_notify('axa_queue', '');
341 RETURN NULL;
342END
343$$";
344const SETUP_NOTIFY: &str = "CREATE OR REPLACE TRIGGER axa_queue_notify
345 AFTER INSERT ON axa_queue
346 FOR EACH STATEMENT EXECUTE FUNCTION axa_queue_notify()";
347const ACTS_TRIGGERS: [&str; 2] = ["axa_job_acts_refuse", "axa_job_acts_refuse_truncate"];
349const MISSING_TRIGGERS: &str = "SELECT want FROM unnest($1::text[]) AS want
350 WHERE NOT EXISTS (
351 SELECT 1 FROM pg_trigger t
352 WHERE t.tgrelid = to_regclass('axa_job_acts') AND t.tgname = want
353 AND t.tgenabled::text = 'A'
354 )";
355const NO_TENANT_HANDLER: &str =
357 "the job has a tenant, and its handler takes none: register it with handle_with_tenant";
358
359const SETUP_LOCK: i64 = 0x0061_7861_5F71;
361
362const ENQUEUE: &str = "INSERT INTO axa_queue
363 (id, name, args, max_attempts, priority, run_at, timeout_ms, tenant)
364 VALUES ($1, $2, $3, $4, $5, COALESCE($6, now() + make_interval(secs => $7)), $8, $9)";
365const ENQUEUE_UNIQUE: &str = "INSERT INTO axa_queue
370 (id, name, args, max_attempts, priority, run_at, timeout_ms, tenant, unique_key)
371 VALUES ($1, $2, $3, $4, $5, COALESCE($6, now() + make_interval(secs => $7)), $8, $9, $10)
372 ON CONFLICT (name, (COALESCE(tenant, '')), unique_key)
373 WHERE unique_key IS NOT NULL AND status IN ('queued', 'running')
374 DO UPDATE SET unique_key = EXCLUDED.unique_key
375 RETURNING id";
376const CLAIM: &str = "UPDATE axa_queue
377 SET status = 'running', started_at = now(), updated_at = now(), attempts = attempts + 1
378 WHERE id = (
379 SELECT id FROM axa_queue
380 WHERE status = 'queued' AND run_at <= now() AND name = ANY($1)
381 ORDER BY priority DESC, run_at
382 FOR UPDATE SKIP LOCKED
383 LIMIT 1
384 )
385 RETURNING id, name, args, attempts, max_attempts, timeout_ms, tenant";
386const HEARTBEAT: &str = "UPDATE axa_queue SET updated_at = now()
389 WHERE id = $1 AND attempts = $2 AND status = 'running'";
390const FINISH: &str = "UPDATE axa_queue SET status = $3, error = $4, updated_at = now()
391 WHERE id = $1 AND attempts = $2 AND status = 'running'";
392const RETRY: &str = "UPDATE axa_queue
393 SET status = 'queued', error = $3, started_at = NULL, updated_at = now(),
394 run_at = now() + make_interval(secs => $4)
395 WHERE id = $1 AND attempts = $2 AND status = 'running'";
396const REQUEUE_STALE: &str = "UPDATE axa_queue
397 SET status = 'queued', started_at = NULL, updated_at = now()
398 WHERE status = 'running' AND updated_at < now() - make_interval(mins => $1)
399 AND attempts < COALESCE(max_attempts, $2)";
400const FAIL_STALE: &str = "UPDATE axa_queue
401 SET status = 'failed', error = 'abandoned by its worker', updated_at = now()
402 WHERE status = 'running' AND updated_at < now() - make_interval(mins => $1)
403 AND attempts >= COALESCE(max_attempts, $2)";
404const PURGE: &str = "DELETE FROM axa_queue
405 WHERE status IN ('completed', 'failed', 'cancelled')
406 AND updated_at < now() - make_interval(days => $1)";
407const STATUS: &str = "SELECT id, name, status, attempts, max_attempts, priority, error,
408 timeout_ms, tenant, unique_key, run_at, started_at, created_at, updated_at FROM axa_queue WHERE id = $1";
409const MARK_LOST: &str =
413 "UPDATE axa_queue SET status = 'needs_review', error = $2, updated_at = now()
414 WHERE id = $1 AND status IN ('queued', 'running', 'failed')";
415const CANCEL: &str = "WITH changed AS (
418 UPDATE axa_queue SET status = 'cancelled', updated_at = now()
419 WHERE id = $1 AND status = 'queued'
420 RETURNING id, name, attempts
421 )
422 INSERT INTO axa_job_acts (job_id, job_name, act, attempts, by, reason)
423 SELECT id, name, 'cancelled', attempts, $2, $3 FROM changed";
424const RETRY_FAILED: &str = "WITH target AS (
429 SELECT id, status FROM axa_queue
430 WHERE id = $1 AND status IN ('failed', 'needs_review')
431 AND NOT EXISTS (
432 SELECT 1 FROM axa_queue other
433 WHERE other.unique_key = axa_queue.unique_key
434 AND other.name = axa_queue.name
435 AND COALESCE(other.tenant, '') = COALESCE(axa_queue.tenant, '')
436 AND other.status IN ('queued', 'running')
437 )
438 FOR UPDATE
439 ), changed AS (
440 UPDATE axa_queue q
441 SET status = 'queued', run_at = now(), started_at = NULL, updated_at = now(),
442 max_attempts = q.attempts + 1
443 FROM target WHERE q.id = target.id
444 RETURNING q.id, q.name, q.attempts, target.status AS was
445 )
446 INSERT INTO axa_job_acts (job_id, job_name, act, attempts, by, reason)
447 SELECT id, name, CASE was WHEN 'needs_review' THEN 'released' ELSE 'retried' END,
448 attempts, $2, $3
449 FROM changed";
450const ACTS: &str = "SELECT id, job_id, job_name, act, attempts, by, reason, at
451 FROM axa_job_acts WHERE job_id = $1 ORDER BY id";
452const COUNTS: &str = "SELECT
453 count(*) FILTER (WHERE status = 'queued' AND run_at <= now()) AS ready,
454 count(*) FILTER (WHERE status = 'queued' AND run_at > now()) AS waiting,
455 count(*) FILTER (WHERE status = 'running') AS running,
456 count(*) FILTER (WHERE status = 'completed') AS completed,
457 count(*) FILTER (WHERE status = 'failed') AS failed,
458 count(*) FILTER (WHERE status = 'cancelled') AS cancelled,
459 count(*) FILTER (WHERE status = 'needs_review') AS needs_review,
460 EXTRACT(EPOCH FROM now() - min(run_at) FILTER (WHERE status = 'queued' AND run_at <= now()))::float8 AS oldest
461 FROM axa_queue";
462const SCHEDULE_CREATE: &str = "INSERT INTO axa_schedule (name, due_at, interval_ms, cron)
467 VALUES ($1, COALESCE($2, now()), $3, $4)
468 ON CONFLICT (name) DO UPDATE
469 SET seen_at = now(), archived_at = NULL, interval_ms = EXCLUDED.interval_ms,
470 cron = EXCLUDED.cron,
471 due_at = CASE WHEN EXCLUDED.cron IS NOT NULL
472 AND axa_schedule.cron IS DISTINCT FROM EXCLUDED.cron
473 THEN EXCLUDED.due_at ELSE axa_schedule.due_at END
474 WHERE axa_schedule.archived_at IS NOT NULL
475 OR axa_schedule.interval_ms IS DISTINCT FROM EXCLUDED.interval_ms
476 OR axa_schedule.cron IS DISTINCT FROM EXCLUDED.cron
477 OR axa_schedule.seen_at < now() - interval '1 minute'";
478const SCHEDULE_LOCK: &str =
479 "SELECT last_job, due_at <= now() AS due, now() AS now FROM axa_schedule
480 WHERE name = $1 AND archived_at IS NULL FOR UPDATE SKIP LOCKED";
481const SCHEDULE_ARCHIVE: &str = "UPDATE axa_schedule SET archived_at = now(), updated_at = now()
485 WHERE archived_at IS NULL AND name <> ALL($1)
486 AND seen_at < now() - make_interval(mins => $2)";
487const SCHEDULES: &str = "SELECT s.name, s.interval_ms, s.cron, s.due_at, s.last_job, s.seen_at,
488 s.archived_at, s.created_at, q.status AS last_status, q.error AS last_error
489 FROM axa_schedule s LEFT JOIN axa_queue q ON q.id = s.last_job ORDER BY s.name";
490const SCHEDULE_BUSY: &str = "SELECT EXISTS (SELECT 1 FROM axa_queue
491 WHERE id = $1 AND status IN ('queued', 'running'))";
492const SCHEDULE_ADVANCE: &str = "UPDATE axa_schedule
495 SET due_at = due_at + make_interval(secs => $2)
496 * (floor(EXTRACT(EPOCH FROM now() - due_at)::float8 / $2) + 1),
497 last_job = COALESCE($3, last_job), updated_at = now()
498 WHERE name = $1";
499const SCHEDULE_ADVANCE_TO: &str = "UPDATE axa_schedule
501 SET due_at = $2, last_job = COALESCE($3, last_job), updated_at = now()
502 WHERE name = $1";
503
504pub const SETUP_STATEMENTS: [&str; 20] = [
508 SETUP,
509 SETUP_ATTEMPTS,
510 SETUP_MAX_ATTEMPTS,
511 SETUP_INDEX,
512 SETUP_PRIORITY,
513 SETUP_TIMEOUT,
514 SETUP_TENANT,
515 SETUP_UNIQUE_KEY,
516 SETUP_UNIQUE_INDEX,
517 SETUP_CLAIM_INDEX,
518 SETUP_SCHEDULE,
519 SETUP_SCHEDULE_CRON,
520 SETUP_ACTS,
521 SETUP_ACTS_INDEX,
522 SETUP_ACTS_REFUSE,
523 SETUP_ACTS_ROWS,
524 SETUP_ACTS_TRUNCATE,
525 SETUP_ACTS_ALWAYS,
526 SETUP_NOTIFY_FUNCTION,
527 SETUP_NOTIFY,
528];
529
530pub const MAX_REASON_CHARS: usize = 200;
532
533const MIN_HEARTBEAT: Duration = Duration::from_millis(20);
535
536const MAX_BACKOFF: Duration = Duration::from_hours(1);
538
539const MAX_ERROR: usize = 1024;
541
542#[must_use]
544pub fn backoff(base: Duration, attempts: i32) -> Duration {
545 let doublings = u32::try_from(attempts.saturating_sub(1))
546 .unwrap_or(0)
547 .min(16);
548 base.saturating_mul(1 << doublings).min(MAX_BACKOFF)
549}
550
551pub const MIN_RETRY_AFTER: Duration = Duration::from_secs(1);
553
554#[derive(Debug, Clone)]
559pub struct RetryAfter {
560 delay: Duration,
561 reason: String,
562}
563
564impl RetryAfter {
565 #[must_use]
567 pub fn new(delay: Duration, reason: impl Into<String>) -> Self {
568 Self {
569 delay,
570 reason: reason.into(),
571 }
572 }
573
574 #[must_use]
576 pub const fn delay(&self) -> Duration {
577 self.delay
578 }
579}
580
581impl fmt::Display for RetryAfter {
582 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
583 f.write_str(&self.reason)
584 }
585}
586
587impl std::error::Error for RetryAfter {}
588
589struct Failure {
591 text: String,
592 retry_in: Option<Duration>,
593}
594
595impl Failure {
596 fn from_error<E: fmt::Display + 'static>(error: E) -> Self {
597 let any = &error as &dyn std::any::Any;
598 let retry_in = any
600 .downcast_ref::<RetryAfter>()
601 .or_else(|| {
602 any.downcast_ref::<Box<dyn std::error::Error + Send + Sync>>()
603 .and_then(|boxed| boxed.downcast_ref::<RetryAfter>())
604 })
605 .map(RetryAfter::delay);
606 Self {
607 text: error.to_string(),
608 retry_in,
609 }
610 }
611}
612
613impl From<String> for Failure {
614 fn from(text: String) -> Self {
615 Self {
616 text,
617 retry_in: None,
618 }
619 }
620}
621
622impl fmt::Display for Failure {
623 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
624 f.write_str(&self.text)
625 }
626}
627
628#[must_use]
631pub fn jittered(wait: Duration) -> Duration {
632 let random = Uuid::new_v4().as_u128();
633 #[allow(clippy::cast_precision_loss)]
634 let fraction = (random % 1_000_000) as f64 / 1_000_000.0;
635 wait.mul_f64(0.5 + fraction / 2.0)
636}
637
638#[must_use]
642pub fn retry_wait(base: Duration, attempts: i32, chosen: Option<Duration>) -> Duration {
643 match chosen {
644 Some(delay) => delay.clamp(MIN_RETRY_AFTER, MAX_BACKOFF),
645 None => jittered(backoff(base, attempts)),
646 }
647}
648
649fn cut(mut text: String) -> String {
651 if text.len() > MAX_ERROR {
652 let mut end = MAX_ERROR;
653 while !text.is_char_boundary(end) {
654 end -= 1;
655 }
656 text.truncate(end);
657 }
658 text
659}
660
661fn millis(duration: Duration) -> i64 {
662 i64::try_from(duration.as_millis()).unwrap_or(i64::MAX)
663}
664
665fn from_millis(millis: i64) -> Duration {
666 Duration::from_millis(u64::try_from(millis).unwrap_or(0))
667}
668
669#[derive(Debug, Clone, Copy, PartialEq, Eq)]
671enum When {
672 Now,
673 At(DateTime<Utc>),
674 In(Duration),
675}
676
677#[derive(Clone)]
679pub struct NewJob {
680 name: String,
681 args: serde_json::Value,
682 max_attempts: Option<i32>,
683 priority: i16,
684 when: When,
685 timeout: Option<Duration>,
686 tenant: Option<String>,
687 unique_key: Option<String>,
688}
689
690impl fmt::Debug for NewJob {
691 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
692 f.debug_struct("NewJob")
693 .field("name", &self.name)
694 .field("max_attempts", &self.max_attempts)
695 .field("priority", &self.priority)
696 .field("when", &self.when)
697 .field("timeout", &self.timeout)
698 .field("tenant", &self.tenant)
699 .field("unique_key", &self.unique_key)
700 .finish_non_exhaustive()
701 }
702}
703
704impl NewJob {
705 pub fn new(name: impl Into<String>, args: serde_json::Value) -> Self {
708 Self {
709 name: name.into(),
710 args,
711 max_attempts: None,
712 priority: 0,
713 when: When::Now,
714 timeout: None,
715 tenant: None,
716 unique_key: None,
717 }
718 }
719
720 #[must_use]
727 pub fn unique(mut self, key: impl Into<String>) -> Self {
728 self.unique_key = Some(key.into());
729 self
730 }
731
732 #[must_use]
738 pub fn tenant(mut self, tenant: impl Into<String>) -> Self {
739 self.tenant = Some(tenant.into());
740 self
741 }
742
743 #[must_use]
746 pub const fn timeout(mut self, limit: Duration) -> Self {
747 self.timeout = Some(limit);
748 self
749 }
750
751 #[must_use]
753 pub const fn max_attempts(mut self, max_attempts: Option<i32>) -> Self {
754 self.max_attempts = max_attempts;
755 self
756 }
757
758 #[must_use]
761 pub const fn priority(mut self, priority: i16) -> Self {
762 self.priority = priority;
763 self
764 }
765
766 #[must_use]
768 pub const fn run_in(mut self, delay: Duration) -> Self {
769 self.when = When::In(delay);
770 self
771 }
772
773 #[must_use]
775 pub const fn run_at(mut self, at: DateTime<Utc>) -> Self {
776 self.when = When::At(at);
777 self
778 }
779
780 #[must_use]
782 pub fn name(&self) -> &str {
783 &self.name
784 }
785
786 #[must_use]
788 pub fn tenant_id(&self) -> Option<&str> {
789 self.tenant.as_deref()
790 }
791
792 #[must_use]
794 pub fn unique_key(&self) -> Option<&str> {
795 self.unique_key.as_deref()
796 }
797}
798
799pub const MAX_TENANT_ID_LEN: usize = 63;
801
802#[must_use]
806pub fn is_tenant_id(id: &str) -> bool {
807 (1..=MAX_TENANT_ID_LEN).contains(&id.len())
808 && !id.starts_with('-')
809 && !id.ends_with('-')
810 && id
811 .bytes()
812 .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'-')
813}
814
815pub async fn enqueue_on<'e, E: PgExecutor<'e>>(executor: E, job: &NewJob) -> Result<Uuid> {
826 if job
827 .tenant
828 .as_deref()
829 .is_some_and(|tenant| !is_tenant_id(tenant))
830 {
831 return Err(Error::NotATenant);
832 }
833 if let Some(key) = job.unique_key.as_deref() {
834 check_code(key, "unique key")?;
835 }
836 let id = Uuid::new_v4();
837 let (at, delay) = match job.when {
838 When::Now => (None, 0.0),
839 When::At(at) => (Some(at), 0.0),
840 When::In(delay) => (None, delay.as_secs_f64()),
841 };
842 let query = sqlx::query(if job.unique_key.is_some() {
843 ENQUEUE_UNIQUE
844 } else {
845 ENQUEUE
846 })
847 .bind(id)
848 .bind(&job.name)
849 .bind(&job.args)
850 .bind(job.max_attempts)
851 .bind(job.priority)
852 .bind(at)
853 .bind(delay)
854 .bind(job.timeout.map(millis))
855 .bind(job.tenant.as_deref());
856 if let Some(key) = job.unique_key.as_deref() {
857 Ok(query.bind(key).fetch_one(executor).await?.try_get("id")?)
858 } else {
859 query.execute(executor).await?;
860 Ok(id)
861 }
862}
863
864pub async fn enqueue_all_on(connection: &mut PgConnection, jobs: &[NewJob]) -> Result<Vec<Uuid>> {
871 let mut ids = Vec::with_capacity(jobs.len());
872 for job in jobs {
873 ids.push(enqueue_on(&mut *connection, job).await?);
874 }
875 Ok(ids)
876}
877
878fn check_code(text: &str, what: &'static str) -> Result<()> {
880 if text.is_empty()
881 || text.chars().count() > MAX_REASON_CHARS
882 || text.chars().any(char::is_control)
883 {
884 Err(Error::NotACode { what })
885 } else {
886 Ok(())
887 }
888}
889
890pub async fn cancel(
904 transaction: &mut Transaction<'_, Postgres>,
905 id: Uuid,
906 by: &str,
907 reason: &str,
908) -> Result<bool> {
909 act(transaction, CANCEL, id, by, reason).await
910}
911
912pub async fn retry(
925 transaction: &mut Transaction<'_, Postgres>,
926 id: Uuid,
927 by: &str,
928 reason: &str,
929) -> Result<bool> {
930 act(transaction, RETRY_FAILED, id, by, reason).await
931}
932
933async fn act(
935 transaction: &mut Transaction<'_, Postgres>,
936 statement: &'static str,
937 id: Uuid,
938 by: &str,
939 reason: &str,
940) -> Result<bool> {
941 check_code(by, "by")?;
942 check_code(reason, "reason")?;
943 let kept = sqlx::query(statement)
944 .bind(id)
945 .bind(by)
946 .bind(reason)
947 .execute(&mut **transaction)
948 .await?
949 .rows_affected();
950 Ok(kept == 1)
951}
952
953#[derive(Debug, Clone, Copy, PartialEq, Eq)]
955#[non_exhaustive]
956pub enum ActKind {
957 Cancelled,
959 Retried,
961 Released,
963}
964
965impl ActKind {
966 fn parse(text: &str) -> Result<Self> {
967 match text {
968 "cancelled" => Ok(Self::Cancelled),
969 "retried" => Ok(Self::Retried),
970 "released" => Ok(Self::Released),
971 _ => Err(Error::Job("an act with an unknown kind".to_string())),
972 }
973 }
974}
975
976#[derive(Debug, Clone)]
979#[non_exhaustive]
980pub struct Act {
981 pub id: i64,
983 pub job_id: Uuid,
985 pub job_name: String,
987 pub kind: ActKind,
989 pub attempts: i32,
991 pub by: String,
993 pub reason: String,
995 pub at: DateTime<Utc>,
997}
998
999#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1001pub enum JobState {
1002 Queued,
1004 Running,
1006 Completed,
1008 Failed,
1010 Cancelled,
1012 NeedsReview,
1016}
1017
1018impl JobState {
1019 fn parse(text: &str) -> Result<Self> {
1020 match text {
1021 "queued" => Ok(Self::Queued),
1022 "running" => Ok(Self::Running),
1023 "completed" => Ok(Self::Completed),
1024 "failed" => Ok(Self::Failed),
1025 "cancelled" => Ok(Self::Cancelled),
1026 "needs_review" => Ok(Self::NeedsReview),
1027 _ => Err(Error::Job("a job row with an unknown status".to_string())),
1028 }
1029 }
1030}
1031
1032#[derive(Debug, Clone)]
1034#[non_exhaustive]
1035pub struct JobInfo {
1036 pub id: Uuid,
1038 pub name: String,
1040 pub state: JobState,
1042 pub attempts: i32,
1044 pub max_attempts: Option<i32>,
1046 pub priority: i16,
1048 pub timeout: Option<Duration>,
1050 pub tenant: Option<String>,
1052 pub unique_key: Option<String>,
1054 pub error: Option<String>,
1057 pub run_at: DateTime<Utc>,
1059 pub started_at: Option<DateTime<Utc>>,
1061 pub created_at: DateTime<Utc>,
1063 pub updated_at: DateTime<Utc>,
1065}
1066
1067#[derive(Debug, Clone, Copy, Default, PartialEq)]
1069#[non_exhaustive]
1070pub struct Counts {
1071 pub ready: i64,
1073 pub waiting: i64,
1075 pub running: i64,
1077 pub completed: i64,
1079 pub failed: i64,
1081 pub cancelled: i64,
1083 pub needs_review: i64,
1086 pub oldest_ready_seconds: f64,
1089}
1090
1091#[derive(Clone)]
1094pub struct Schedule {
1095 name: String,
1096 times: Times,
1097 first: Option<DateTime<Utc>>,
1098 job: NewJob,
1099}
1100
1101#[derive(Clone)]
1103enum Times {
1104 Every(Duration),
1105 Cron(Box<croner::Cron>, String),
1107}
1108
1109impl Times {
1110 fn interval(&self) -> Option<Duration> {
1111 match self {
1112 Self::Every(interval) => Some(*interval),
1113 Self::Cron(..) => None,
1114 }
1115 }
1116
1117 fn pattern(&self) -> Option<&str> {
1118 match self {
1119 Self::Every(_) => None,
1120 Self::Cron(_, pattern) => Some(pattern),
1121 }
1122 }
1123}
1124
1125fn next_after(cron: &croner::Cron, now: DateTime<Utc>) -> Result<DateTime<Utc>> {
1127 cron.find_next_occurrence(&now, false)
1128 .map_err(|error| Error::Job(format!("the cron pattern has no next time: {error}")))
1129}
1130
1131impl fmt::Debug for Schedule {
1132 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1133 f.debug_struct("Schedule")
1134 .field("name", &self.name)
1135 .field("interval", &self.times.interval())
1136 .field("cron", &self.times.pattern())
1137 .field("first", &self.first)
1138 .field("job", &self.job)
1139 .finish()
1140 }
1141}
1142
1143impl Schedule {
1144 pub fn every(name: impl Into<String>, interval: Duration, job: NewJob) -> Self {
1153 let name = checked_name(name.into());
1154 assert!(
1155 interval >= Duration::from_secs(1),
1156 "the schedule {name} needs an interval of at least a second"
1157 );
1158 Self {
1159 name,
1160 times: Times::Every(interval),
1161 first: None,
1162 job: NewJob {
1163 when: When::Now,
1164 ..job
1165 },
1166 }
1167 }
1168
1169 pub fn cron(name: impl Into<String>, pattern: &str, job: NewJob) -> Self {
1181 let name = checked_name(name.into());
1182 let cron: croner::Cron = pattern
1183 .parse()
1184 .unwrap_or_else(|error| panic!("the schedule {name} has a bad cron pattern: {error}"));
1185 assert!(
1186 next_after(&cron, Utc::now()).is_ok(),
1187 "the cron pattern of the schedule {name} names no time to come"
1188 );
1189 Self {
1190 name,
1191 times: Times::Cron(Box::new(cron), pattern.to_string()),
1192 first: None,
1193 job: NewJob {
1194 when: When::Now,
1195 ..job
1196 },
1197 }
1198 }
1199
1200 #[must_use]
1205 pub const fn first_at(mut self, first: DateTime<Utc>) -> Self {
1206 self.first = Some(first);
1207 self
1208 }
1209
1210 #[must_use]
1212 pub fn interval(&self) -> Option<Duration> {
1213 self.times.interval()
1214 }
1215
1216 #[must_use]
1218 pub fn cron_pattern(&self) -> Option<&str> {
1219 self.times.pattern()
1220 }
1221
1222 #[must_use]
1224 pub fn name(&self) -> &str {
1225 &self.name
1226 }
1227}
1228
1229fn checked_name(name: String) -> String {
1231 assert!(
1232 !name.is_empty() && name.len() <= 200,
1233 "a schedule name must be 1 to 200 characters"
1234 );
1235 name
1236}
1237
1238#[derive(Debug, Clone)]
1240#[non_exhaustive]
1241pub struct ScheduleInfo {
1242 pub name: String,
1244 pub interval: Option<Duration>,
1246 pub cron: Option<String>,
1248 pub due_at: DateTime<Utc>,
1250 pub last_job: Option<Uuid>,
1252 pub last_state: Option<JobState>,
1254 pub last_error: Option<String>,
1256 pub seen_at: DateTime<Utc>,
1258 pub archived_at: Option<DateTime<Utc>>,
1261 pub created_at: DateTime<Utc>,
1263}
1264
1265#[derive(Debug, Clone)]
1267pub struct QueueOptions {
1268 pub workers: usize,
1270 pub poll_interval: Duration,
1272 pub stale_minutes: i32,
1275 pub heartbeat_interval: Duration,
1277 pub max_attempts: i32,
1280 pub retry_backoff: Duration,
1282 pub retention_days: i32,
1284 pub maintenance_interval: Duration,
1286}
1287
1288impl Default for QueueOptions {
1289 fn default() -> Self {
1290 Self {
1291 workers: 2,
1292 poll_interval: Duration::from_secs(1),
1293 stale_minutes: 60,
1294 heartbeat_interval: Duration::from_mins(1),
1295 max_attempts: 1,
1296 retry_backoff: Duration::from_secs(30),
1297 retention_days: 7,
1298 maintenance_interval: Duration::from_mins(5),
1299 }
1300 }
1301}
1302
1303pub struct Queue {
1305 pool: PgPool,
1306 handlers: HashMap<String, Handler>,
1307 limits: HashMap<String, Arc<Semaphore>>,
1308 schedules: Vec<Schedule>,
1309 options: QueueOptions,
1310}
1311
1312impl fmt::Debug for Queue {
1313 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1314 f.debug_struct("Queue")
1315 .field("handlers", &self.handlers.len())
1316 .field("limits", &self.limits.len())
1317 .field("schedules", &self.schedules.len())
1318 .field("options", &self.options)
1319 .finish_non_exhaustive()
1320 }
1321}
1322
1323struct Claimed {
1325 id: Uuid,
1326 name: String,
1327 args: serde_json::Value,
1328 attempts: i32,
1329 limit: i32,
1330 timeout: Option<Duration>,
1331 tenant: Option<String>,
1332}
1333
1334enum Outcome {
1336 Done(Result<(), Failure>),
1338 Lost(String),
1340}
1341
1342impl Queue {
1343 #[must_use]
1346 pub fn from_pool(pool: PgPool, options: QueueOptions) -> Self {
1347 Self {
1348 pool,
1349 handlers: HashMap::new(),
1350 limits: HashMap::new(),
1351 schedules: Vec::new(),
1352 options,
1353 }
1354 }
1355
1356 async fn open(uri: &str, options: QueueOptions) -> Result<Self> {
1358 let loops = u32::try_from(options.workers).unwrap_or(u32::MAX);
1359 let pool = PgPoolOptions::new()
1360 .max_connections(loops.saturating_add(3))
1362 .connect(uri)
1363 .await?;
1364 Ok(Self::from_pool(pool, options))
1365 }
1366
1367 pub async fn connect_existing(uri: &str, options: QueueOptions) -> Result<Self> {
1377 let queue = Self::open(uri, options).await?;
1378 queue.check().await?;
1379 Ok(queue)
1380 }
1381
1382 pub async fn connect(uri: &str, options: QueueOptions) -> Result<Self> {
1389 let queue = Self::open(uri, options).await?;
1390 let mut setup = queue.pool.begin().await?;
1395 sqlx::query("SELECT pg_advisory_xact_lock($1)")
1396 .bind(SETUP_LOCK)
1397 .execute(&mut *setup)
1398 .await?;
1399 for statement in SETUP_STATEMENTS {
1400 sqlx::query(statement).execute(&mut *setup).await?;
1401 }
1402 setup.commit().await?;
1403 Ok(queue)
1404 }
1405
1406 pub async fn check(&self) -> Result<()> {
1414 sqlx::query(
1415 "SELECT attempts, max_attempts, priority, timeout_ms, tenant, unique_key FROM axa_queue LIMIT 0",
1416 )
1417 .execute(&self.pool)
1418 .await?;
1419 sqlx::query(
1420 "SELECT name, due_at, last_job, interval_ms, cron, seen_at, archived_at FROM axa_schedule LIMIT 0",
1421 )
1422 .execute(&self.pool)
1423 .await?;
1424 sqlx::query(
1425 "SELECT id, job_id, job_name, act, attempts, by, reason, at FROM axa_job_acts LIMIT 0",
1426 )
1427 .execute(&self.pool)
1428 .await?;
1429 let mut missing: Vec<String> = sqlx::query_scalar(MISSING_TRIGGERS)
1430 .bind(ACTS_TRIGGERS.to_vec())
1431 .fetch_all(&self.pool)
1432 .await?;
1433 let unique_index: bool =
1434 sqlx::query_scalar("SELECT to_regclass('axa_queue_unique') IS NOT NULL")
1435 .fetch_one(&self.pool)
1436 .await?;
1437 if !unique_index {
1438 missing.push("axa_queue_unique".to_string());
1439 }
1440 if missing.is_empty() {
1441 Ok(())
1442 } else {
1443 Err(Error::Database(sqlx::Error::Configuration(
1444 format!(
1445 "the job queue is missing, or has turned off, {}: run SETUP_STATEMENTS",
1446 missing.join(", ")
1447 )
1448 .into(),
1449 )))
1450 }
1451 }
1452
1453 #[must_use]
1456 pub const fn pool(&self) -> &PgPool {
1457 &self.pool
1458 }
1459
1460 #[must_use]
1462 pub const fn options(&self) -> &QueueOptions {
1463 &self.options
1464 }
1465
1466 pub fn handle<F, Fut, E>(&mut self, name: impl Into<String>, handler: F)
1473 where
1474 F: Fn(serde_json::Value) -> Fut + Send + Sync + 'static,
1475 Fut: Future<Output = std::result::Result<(), E>> + Send + 'static,
1476 E: fmt::Display + 'static,
1477 {
1478 let handler = Arc::new(handler);
1479 let run: Handler = Arc::new(move |tenant, args| {
1480 if tenant.is_some() {
1481 return Box::pin(std::future::ready(Err(NO_TENANT_HANDLER
1482 .to_string()
1483 .into())));
1484 }
1485 let job = handler(args);
1486 Box::pin(async move { job.await.map_err(Failure::from_error) })
1487 });
1488 self.handlers.insert(name.into(), run);
1489 }
1490
1491 pub fn handle_with_tenant<F, Fut, E>(&mut self, name: impl Into<String>, handler: F)
1496 where
1497 F: Fn(Option<String>, serde_json::Value) -> Fut + Send + Sync + 'static,
1498 Fut: Future<Output = std::result::Result<(), E>> + Send + 'static,
1499 E: fmt::Display + 'static,
1500 {
1501 let handler = Arc::new(handler);
1502 let run: Handler = Arc::new(move |tenant, args| {
1503 let job = handler(tenant, args);
1504 Box::pin(async move { job.await.map_err(Failure::from_error) })
1505 });
1506 self.handlers.insert(name.into(), run);
1507 }
1508
1509 pub fn limit(&mut self, name: impl Into<String>, jobs: usize) {
1512 self.limits
1513 .insert(name.into(), Arc::new(Semaphore::new(jobs.max(1))));
1514 }
1515
1516 pub fn schedule(&mut self, schedule: Schedule) {
1522 assert!(
1523 self.schedules.iter().all(|s| s.name != schedule.name),
1524 "the schedule {} was added twice",
1525 schedule.name
1526 );
1527 self.schedules.push(schedule);
1528 }
1529
1530 pub async fn enqueue(&self, name: &str, args: serde_json::Value) -> Result<Uuid> {
1536 enqueue_on(&self.pool, &NewJob::new(name, args)).await
1537 }
1538
1539 pub async fn enqueue_limited(
1545 &self,
1546 name: &str,
1547 args: serde_json::Value,
1548 max_attempts: Option<i32>,
1549 ) -> Result<Uuid> {
1550 enqueue_on(
1551 &self.pool,
1552 &NewJob::new(name, args).max_attempts(max_attempts),
1553 )
1554 .await
1555 }
1556
1557 pub async fn enqueue_job(&self, job: &NewJob) -> Result<Uuid> {
1563 enqueue_on(&self.pool, job).await
1564 }
1565
1566 pub async fn enqueue_all(&self, jobs: &[NewJob]) -> Result<Vec<Uuid>> {
1572 let mut transaction = self.pool.begin().await?;
1573 let ids = enqueue_all_on(&mut transaction, jobs).await?;
1574 transaction.commit().await?;
1575 Ok(ids)
1576 }
1577
1578 pub async fn job(&self, id: Uuid) -> Result<Option<JobInfo>> {
1585 let Some(row) = sqlx::query(STATUS)
1586 .bind(id)
1587 .fetch_optional(&self.pool)
1588 .await?
1589 else {
1590 return Ok(None);
1591 };
1592 Ok(Some(JobInfo {
1593 id: row.try_get("id")?,
1594 name: row.try_get("name")?,
1595 state: JobState::parse(row.try_get::<&str, _>("status")?)?,
1596 attempts: row.try_get("attempts")?,
1597 max_attempts: row.try_get("max_attempts")?,
1598 priority: row.try_get("priority")?,
1599 timeout: row
1600 .try_get::<Option<i64>, _>("timeout_ms")?
1601 .map(from_millis),
1602 tenant: row.try_get("tenant")?,
1603 unique_key: row.try_get("unique_key")?,
1604 error: row.try_get("error")?,
1605 run_at: row.try_get("run_at")?,
1606 started_at: row.try_get("started_at")?,
1607 created_at: row.try_get("created_at")?,
1608 updated_at: row.try_get("updated_at")?,
1609 }))
1610 }
1611
1612 pub async fn acts(&self, id: Uuid) -> Result<Vec<Act>> {
1620 let rows = sqlx::query(ACTS).bind(id).fetch_all(&self.pool).await?;
1621 rows.iter()
1622 .map(|row| {
1623 Ok(Act {
1624 id: row.try_get("id")?,
1625 job_id: row.try_get("job_id")?,
1626 job_name: row.try_get("job_name")?,
1627 kind: ActKind::parse(row.try_get::<&str, _>("act")?)?,
1628 attempts: row.try_get("attempts")?,
1629 by: row.try_get("by")?,
1630 reason: row.try_get("reason")?,
1631 at: row.try_get("at")?,
1632 })
1633 })
1634 .collect()
1635 }
1636
1637 pub async fn counts(&self) -> Result<Counts> {
1643 let row = sqlx::query(COUNTS).fetch_one(&self.pool).await?;
1644 Ok(Counts {
1645 ready: row.try_get("ready")?,
1646 waiting: row.try_get("waiting")?,
1647 running: row.try_get("running")?,
1648 completed: row.try_get("completed")?,
1649 failed: row.try_get("failed")?,
1650 cancelled: row.try_get("cancelled")?,
1651 needs_review: row.try_get("needs_review")?,
1652 oldest_ready_seconds: row.try_get::<Option<f64>, _>("oldest")?.unwrap_or(0.0),
1653 })
1654 }
1655
1656 pub async fn ping(&self) -> Result<()> {
1662 sqlx::query("SELECT 1").execute(&self.pool).await?;
1663 Ok(())
1664 }
1665
1666 pub async fn requeue_stale(&self) -> Result<u64> {
1673 sqlx::query(FAIL_STALE)
1674 .bind(self.options.stale_minutes)
1675 .bind(self.options.max_attempts)
1676 .execute(&self.pool)
1677 .await?;
1678 let result = sqlx::query(REQUEUE_STALE)
1679 .bind(self.options.stale_minutes)
1680 .bind(self.options.max_attempts)
1681 .execute(&self.pool)
1682 .await?;
1683 Ok(result.rows_affected())
1684 }
1685
1686 pub async fn purge_finished(&self) -> Result<u64> {
1693 let result = sqlx::query(PURGE)
1694 .bind(self.options.retention_days)
1695 .execute(&self.pool)
1696 .await?;
1697 Ok(result.rows_affected())
1698 }
1699
1700 pub async fn tick_schedules(&self) -> Result<usize> {
1708 let mut queued = 0;
1709 for schedule in &self.schedules {
1710 if self.tick(schedule).await? {
1711 queued += 1;
1712 }
1713 }
1714 Ok(queued)
1715 }
1716
1717 async fn tick(&self, schedule: &Schedule) -> Result<bool> {
1719 let first = match &schedule.times {
1722 Times::Every(_) => schedule.first,
1723 Times::Cron(cron, _) => {
1724 let now: DateTime<Utc> = sqlx::query_scalar("SELECT now()")
1725 .fetch_one(&self.pool)
1726 .await?;
1727 Some(next_after(cron, now)?)
1728 }
1729 };
1730 sqlx::query(SCHEDULE_CREATE)
1731 .bind(&schedule.name)
1732 .bind(first)
1733 .bind(schedule.times.interval().map(millis))
1734 .bind(schedule.times.pattern())
1735 .execute(&self.pool)
1736 .await?;
1737 let mut transaction = self.pool.begin().await?;
1738 let Some(row) = sqlx::query(SCHEDULE_LOCK)
1740 .bind(&schedule.name)
1741 .fetch_optional(&mut *transaction)
1742 .await?
1743 else {
1744 return Ok(false);
1745 };
1746 if !row.try_get::<bool, _>("due")? {
1747 transaction.commit().await?;
1748 return Ok(false);
1749 }
1750 let busy = match row.try_get::<Option<Uuid>, _>("last_job")? {
1751 Some(last) => {
1752 sqlx::query_scalar::<_, bool>(SCHEDULE_BUSY)
1753 .bind(last)
1754 .fetch_one(&mut *transaction)
1755 .await?
1756 }
1757 None => false,
1758 };
1759 let job = if busy {
1760 tracing::info!(schedule = %schedule.name, "schedule skipped, its last job has not finished");
1761 None
1762 } else {
1763 Some(enqueue_on(&mut *transaction, &schedule.job).await?)
1764 };
1765 match &schedule.times {
1766 Times::Every(interval) => {
1767 sqlx::query(SCHEDULE_ADVANCE)
1768 .bind(&schedule.name)
1769 .bind(interval.as_secs_f64())
1770 .bind(job)
1771 .execute(&mut *transaction)
1772 .await?;
1773 }
1774 Times::Cron(cron, _) => {
1775 sqlx::query(SCHEDULE_ADVANCE_TO)
1776 .bind(&schedule.name)
1777 .bind(next_after(cron, row.try_get("now")?)?)
1778 .bind(job)
1779 .execute(&mut *transaction)
1780 .await?;
1781 }
1782 }
1783 transaction.commit().await?;
1784 if job.is_some() {
1785 tracing::debug!(schedule = %schedule.name, "schedule queued its job");
1786 }
1787 Ok(job.is_some())
1788 }
1789
1790 pub async fn archive_schedules(&self) -> Result<u64> {
1797 let names: Vec<&str> = self.schedules.iter().map(|s| s.name.as_str()).collect();
1798 let result = sqlx::query(SCHEDULE_ARCHIVE)
1799 .bind(&names)
1800 .bind(self.options.stale_minutes)
1801 .execute(&self.pool)
1802 .await?;
1803 Ok(result.rows_affected())
1804 }
1805
1806 pub async fn schedules(&self) -> Result<Vec<ScheduleInfo>> {
1812 let rows = sqlx::query(SCHEDULES).fetch_all(&self.pool).await?;
1813 rows.iter()
1814 .map(|row| {
1815 Ok(ScheduleInfo {
1816 name: row.try_get("name")?,
1817 interval: row
1818 .try_get::<Option<i64>, _>("interval_ms")?
1819 .map(from_millis),
1820 cron: row.try_get("cron")?,
1821 due_at: row.try_get("due_at")?,
1822 last_job: row.try_get("last_job")?,
1823 last_state: row
1824 .try_get::<Option<&str>, _>("last_status")?
1825 .map(JobState::parse)
1826 .transpose()?,
1827 last_error: row.try_get("last_error")?,
1828 seen_at: row.try_get("seen_at")?,
1829 archived_at: row.try_get("archived_at")?,
1830 created_at: row.try_get("created_at")?,
1831 })
1832 })
1833 .collect()
1834 }
1835
1836 async fn maintain(&self) {
1839 match self.archive_schedules().await {
1840 Ok(0) => {}
1841 Ok(archived) => tracing::info!(archived, "archived schedules no longer in code"),
1842 Err(error) => tracing::error!(%error, "could not archive schedules"),
1843 }
1844 if let Err(error) = self.requeue_stale().await {
1845 tracing::error!(%error, "could not recover stale jobs");
1846 }
1847 if let Err(error) = self.purge_finished().await {
1848 tracing::error!(%error, "could not delete old jobs");
1849 }
1850 }
1851
1852 async fn supervise(&self, job: JobFuture, claim: &Claimed) -> Outcome {
1856 let mut job = AbortOnDrop(tokio::spawn(job));
1857 let every = self.options.heartbeat_interval.max(MIN_HEARTBEAT);
1858 let stale =
1860 Duration::from_secs(u64::try_from(self.options.stale_minutes).unwrap_or(0) * 60);
1861 let give_up = stale.saturating_sub(every * 2).max(stale / 2);
1864 let mut last_heard = tokio::time::Instant::now();
1865 let beat = || {
1868 tokio::time::timeout(
1869 every,
1870 sqlx::query(HEARTBEAT)
1871 .bind(claim.id)
1872 .bind(claim.attempts)
1873 .execute(&self.pool),
1874 )
1875 };
1876 let mut beating = None;
1877 let mut next_beat = tokio::time::Instant::now() + every;
1878 let mut failing = false;
1879 let limit = claim
1880 .timeout
1881 .map(|timeout| tokio::time::Instant::now() + timeout);
1882 let deadline = async {
1883 match limit {
1884 Some(at) => tokio::time::sleep_until(at).await,
1885 None => std::future::pending().await,
1886 }
1887 };
1888 tokio::pin!(deadline);
1889 loop {
1890 tokio::select! {
1891 finished = &mut job.0 => {
1892 return Outcome::Done(finished.unwrap_or_else(|_| {
1893 Err(Error::Job("the job panicked".to_string()).to_string().into())
1894 }));
1895 }
1896 () = &mut deadline => {
1897 let limit = claim.timeout.unwrap_or_default();
1898 return Outcome::Done(Err(
1899 Error::Job(format!("timed out after {}s", limit.as_secs_f64())).to_string().into(),
1900 ));
1901 }
1902 () = tokio::time::sleep_until(last_heard + give_up), if failing => {
1903 return Outcome::Lost(format!(
1904 "it could not report in for {}s, near the {} minutes after which another worker may take it",
1905 give_up.as_secs(),
1906 self.options.stale_minutes
1907 ));
1908 }
1909 () = tokio::time::sleep_until(next_beat), if beating.is_none() => {
1910 beating = Some(Box::pin(beat()));
1911 }
1912 answer = async {
1913 match beating.as_mut() {
1914 Some(beat) => beat.await,
1915 None => std::future::pending().await,
1916 }
1917 }, if beating.is_some() => {
1918 beating = None;
1919 next_beat = tokio::time::Instant::now() + every;
1920 match answer {
1921 Ok(Ok(done)) if done.rows_affected() == 1 => {
1922 last_heard = tokio::time::Instant::now();
1923 failing = false;
1924 }
1925 Ok(Ok(_)) => return Outcome::Lost("another worker or recovery took its claim".to_string()),
1926 Ok(Err(error)) => {
1927 tracing::warn!(id = %claim.id, %error, "job heartbeat failed");
1928 failing = true;
1929 }
1930 Err(_) => {
1931 tracing::warn!(id = %claim.id, "job heartbeat did not answer in time");
1932 failing = true;
1933 }
1934 }
1935 }
1936 }
1937 }
1938 }
1939
1940 async fn mark_lost(&self, claim: &Claimed, reason: &str) {
1943 let text = Error::Job(format!("stopped: {reason}")).to_string();
1944 let every = self.options.heartbeat_interval.max(MIN_HEARTBEAT);
1945 loop {
1946 match sqlx::query(MARK_LOST)
1947 .bind(claim.id)
1948 .bind(&text)
1949 .execute(&self.pool)
1950 .await
1951 {
1952 Ok(_) => return,
1953 Err(error) => {
1954 tracing::error!(id = %claim.id, %error, "could not mark a lost job for review");
1955 tokio::time::sleep(every).await;
1956 }
1957 }
1958 }
1959 }
1960
1961 fn claimable(&self) -> (Vec<String>, HashMap<String, OwnedSemaphorePermit>) {
1964 let mut places = HashMap::new();
1965 let mut names = Vec::new();
1966 for name in self.handlers.keys() {
1967 match self.limits.get(name) {
1968 None => names.push(name.clone()),
1969 Some(limit) => {
1970 if let Ok(place) = limit.clone().try_acquire_owned() {
1971 places.insert(name.clone(), place);
1972 names.push(name.clone());
1973 }
1974 }
1975 }
1976 }
1977 (names, places)
1978 }
1979
1980 async fn claim(&self, names: &[String]) -> Result<Option<Claimed>> {
1981 let Some(row) = sqlx::query(CLAIM)
1982 .bind(names)
1983 .fetch_optional(&self.pool)
1984 .await?
1985 else {
1986 return Ok(None);
1987 };
1988 Ok(Some(Claimed {
1989 id: row.try_get("id")?,
1990 name: row.try_get("name")?,
1991 args: row.try_get("args")?,
1992 attempts: row.try_get("attempts")?,
1993 limit: row
1994 .try_get::<Option<i32>, _>("max_attempts")?
1995 .unwrap_or(self.options.max_attempts),
1996 timeout: row
1997 .try_get::<Option<i64>, _>("timeout_ms")?
1998 .map(from_millis),
1999 tenant: row.try_get("tenant")?,
2000 }))
2001 }
2002
2003 pub async fn run_one(&self) -> Result<bool> {
2010 let (names, mut places) = self.claimable();
2011 if names.is_empty() {
2012 return Ok(false);
2013 }
2014 let Some(job) = self.claim(&names).await? else {
2015 return Ok(false);
2016 };
2017 let _place = places.remove(&job.name);
2019 drop(places);
2020 let outcome = match self.handlers.get(&job.name) {
2021 Some(handler) => {
2022 let run = handler(job.tenant.clone(), job.args.clone());
2023 self.supervise(run, &job).await
2024 }
2025 None => Outcome::Done(Err(Error::Job(format!("no handler for job {}", job.name))
2026 .to_string()
2027 .into())),
2028 };
2029 let (id, name, attempts) = (job.id, job.name.as_str(), job.attempts);
2030 let finished = match outcome {
2031 Outcome::Lost(reason) => {
2032 tracing::error!(job = %name, %id, attempts, %reason, "job stopped, it lost its claim");
2033 self.mark_lost(&job, &reason).await;
2034 return Ok(true);
2035 }
2036 Outcome::Done(Ok(())) => {
2037 sqlx::query(FINISH)
2038 .bind(id)
2039 .bind(attempts)
2040 .bind("completed")
2041 .bind(None::<String>)
2042 .execute(&self.pool)
2043 .await?
2044 }
2045 Outcome::Done(Err(error)) if attempts < job.limit => {
2046 tracing::warn!(job = %name, %id, attempts, %error, "job failed, will retry");
2047 let wait = retry_wait(self.options.retry_backoff, attempts, error.retry_in);
2048 sqlx::query(RETRY)
2049 .bind(id)
2050 .bind(attempts)
2051 .bind(cut(error.text))
2052 .bind(wait.as_secs_f64())
2053 .execute(&self.pool)
2054 .await?
2055 }
2056 Outcome::Done(Err(error)) => {
2057 tracing::error!(job = %name, %id, attempts, %error, "job failed");
2058 sqlx::query(FINISH)
2059 .bind(id)
2060 .bind(attempts)
2061 .bind("failed")
2062 .bind(cut(error.text))
2063 .execute(&self.pool)
2064 .await?
2065 }
2066 };
2067 if finished.rows_affected() == 0 {
2068 tracing::error!(job = %name, %id, "job finished after losing its claim");
2071 self.mark_lost(
2072 &job,
2073 "it finished after another worker or recovery took its claim",
2074 )
2075 .await;
2076 }
2077 Ok(true)
2078 }
2079
2080 pub async fn run(self: Arc<Self>, shutdown: watch::Receiver<bool>) {
2086 let mut loops = Vec::new();
2087 loops.push(AbortOnDrop(tokio::spawn(every_until(
2088 shutdown.clone(),
2089 self.options.maintenance_interval,
2090 {
2091 let queue = self.clone();
2092 move || {
2093 let queue = queue.clone();
2094 async move { queue.maintain().await }
2095 }
2096 },
2097 ))));
2098 if !self.schedules.is_empty() {
2099 let queue = self.clone();
2100 loops.push(AbortOnDrop(tokio::spawn(every_until(
2101 shutdown.clone(),
2102 self.options.poll_interval,
2103 move || {
2104 let queue = queue.clone();
2105 async move {
2106 if let Err(error) = queue.tick_schedules().await {
2107 tracing::error!(%error, "could not queue scheduled jobs");
2108 }
2109 }
2110 },
2111 ))));
2112 }
2113 let wake = Arc::new(Notify::new());
2114 loops.push(AbortOnDrop(tokio::spawn(listen(
2115 self.pool.clone(),
2116 wake.clone(),
2117 self.options.poll_interval,
2118 shutdown.clone(),
2119 ))));
2120 for _ in 0..self.options.workers.max(1) {
2121 let queue = self.clone();
2122 let wake = wake.clone();
2123 let mut shutdown = shutdown.clone();
2124 loops.push(AbortOnDrop(tokio::spawn(async move {
2125 while !*shutdown.borrow() {
2126 let round = async {
2127 queue.run_one().await.unwrap_or_else(|error| {
2128 tracing::error!(%error, "job queue error");
2129 false
2130 })
2131 };
2132 work_or_wait(&wake, queue.options.poll_interval, &mut shutdown, round).await;
2133 }
2134 })));
2135 }
2136 for job_loop in &mut loops {
2137 let _ = (&mut job_loop.0).await;
2138 }
2139 }
2140
2141 #[must_use]
2143 pub fn handled(&self) -> HashSet<&str> {
2144 self.handlers.keys().map(String::as_str).collect()
2145 }
2146}
2147
2148async fn work_or_wait(
2152 wake: &Notify,
2153 poll: Duration,
2154 shutdown: &mut watch::Receiver<bool>,
2155 round: impl Future<Output = bool>,
2156) {
2157 let woken = wake.notified();
2158 tokio::pin!(woken);
2159 woken.as_mut().enable();
2160 if !round.await {
2161 tokio::select! {
2162 () = tokio::time::sleep(poll) => {},
2163 () = woken => {},
2164 _ = shutdown.changed() => {},
2165 }
2166 }
2167}
2168
2169async fn listen(
2172 pool: PgPool,
2173 wake: Arc<Notify>,
2174 gap: Duration,
2175 mut shutdown: watch::Receiver<bool>,
2176) {
2177 while !*shutdown.borrow() {
2178 match sqlx::postgres::PgListener::connect_with(&pool).await {
2179 Ok(mut listener) => match listener.listen(NOTIFY_CHANNEL).await {
2180 Ok(()) => loop {
2181 tokio::select! {
2182 notice = listener.try_recv() => match notice {
2183 Ok(_) => wake.notify_waiters(),
2186 Err(error) => {
2187 tracing::warn!(%error, "job queue listener failed, polling");
2188 break;
2189 }
2190 },
2191 _ = shutdown.changed() => return,
2192 }
2193 },
2194 Err(error) => tracing::warn!(%error, "job queue could not listen, polling"),
2195 },
2196 Err(error) => tracing::warn!(%error, "job queue could not listen, polling"),
2197 }
2198 tokio::select! {
2199 () = tokio::time::sleep(gap) => {},
2200 _ = shutdown.changed() => {},
2201 }
2202 }
2203}
2204
2205async fn every_until<F, Fut>(mut shutdown: watch::Receiver<bool>, gap: Duration, round: F)
2207where
2208 F: Fn() -> Fut,
2209 Fut: Future<Output = ()>,
2210{
2211 while !*shutdown.borrow() {
2212 round().await;
2213 tokio::select! {
2214 () = tokio::time::sleep(gap) => {},
2215 _ = shutdown.changed() => {},
2216 }
2217 }
2218}
2219
2220struct AbortOnDrop<T>(tokio::task::JoinHandle<T>);
2223
2224impl<T> Drop for AbortOnDrop<T> {
2225 fn drop(&mut self) {
2226 self.0.abort();
2227 }
2228}
2229
2230#[cfg(test)]
2231mod tests {
2232 use super::*;
2233
2234 #[tokio::test]
2235 async fn a_wake_during_a_round_that_found_nothing_is_not_lost() {
2236 let wake = Notify::new();
2237 let (_stop, mut shutdown) = watch::channel(false);
2238 let round = async {
2240 wake.notify_waiters();
2241 false
2242 };
2243 let waited = tokio::time::timeout(
2244 Duration::from_secs(5),
2245 work_or_wait(&wake, Duration::from_hours(1), &mut shutdown, round),
2246 )
2247 .await;
2248 assert!(
2249 waited.is_ok(),
2250 "the wake was lost and the loop waited for its poll"
2251 );
2252 }
2253
2254 #[test]
2255 fn each_retry_waits_twice_as_long_up_to_a_limit() {
2256 let base = Duration::from_secs(30);
2257 assert_eq!(backoff(base, 1), base);
2258 assert_eq!(backoff(base, 2), base * 2);
2259 assert_eq!(backoff(base, 3), base * 4);
2260 assert_eq!(backoff(base, 1_000), MAX_BACKOFF);
2261 }
2262
2263 #[test]
2264 fn a_retry_waits_a_jittered_backoff_or_the_delay_the_job_chose() {
2265 let base = Duration::from_secs(30);
2266 for _ in 0..200 {
2267 let wait = retry_wait(base, 2, None);
2268 assert!(wait >= base && wait <= base * 2, "{wait:?}");
2269 }
2270 let waits: HashSet<_> = (0..20).map(|_| retry_wait(base, 1, None)).collect();
2271 assert!(waits.len() > 1, "the waits are spread");
2272 assert_eq!(retry_wait(Duration::ZERO, 3, None), Duration::ZERO);
2273 let chosen = Some(Duration::from_secs(90));
2274 assert_eq!(retry_wait(base, 1, chosen), Duration::from_secs(90));
2275 assert_eq!(retry_wait(base, 1, Some(Duration::ZERO)), MIN_RETRY_AFTER);
2276 assert_eq!(
2277 retry_wait(base, 1, Some(Duration::from_hours(9))),
2278 MAX_BACKOFF
2279 );
2280 }
2281
2282 #[test]
2283 fn a_retry_after_error_carries_its_delay_and_others_none() {
2284 let chosen = Failure::from_error(RetryAfter::new(Duration::from_secs(7), "busy"));
2285 assert_eq!(
2286 (chosen.text.as_str(), chosen.retry_in),
2287 ("busy", Some(Duration::from_secs(7)))
2288 );
2289 let boxed: Box<dyn std::error::Error + Send + Sync> =
2290 Box::new(RetryAfter::new(Duration::from_secs(8), "boxed"));
2291 assert_eq!(
2292 Failure::from_error(boxed).retry_in,
2293 Some(Duration::from_secs(8))
2294 );
2295 let plain = Failure::from_error("broken".to_string());
2296 assert_eq!((plain.text.as_str(), plain.retry_in), ("broken", None));
2297 }
2298
2299 #[test]
2300 fn the_debug_text_leaves_out_arguments() {
2301 let job = NewJob::new("Report", serde_json::json!({ "nhs": "943 476 5919" }));
2302 let schedule = Schedule::every("nightly", Duration::from_hours(1), job.clone());
2303 let cron = Schedule::cron("at-two", "0 2 * * *", job.clone());
2304 for text in [
2305 format!("{job:?}"),
2306 format!("{schedule:?}"),
2307 format!("{cron:?}"),
2308 ] {
2309 assert!(text.contains("Report"), "{text}");
2310 assert!(!text.contains("943"), "{text}");
2311 }
2312 }
2313
2314 #[test]
2315 fn a_by_or_reason_that_is_not_a_code_is_refused() {
2316 assert!(check_code("ops:alice", "by").is_ok());
2317 assert!(check_code(&"é".repeat(MAX_REASON_CHARS), "reason").is_ok());
2318 for bad in [
2319 String::new(),
2320 "é".repeat(MAX_REASON_CHARS + 1),
2321 "two\nlines".to_string(),
2322 "a\ttab".to_string(),
2323 ] {
2324 let error = check_code(&bad, "reason").unwrap_err();
2325 assert!(matches!(error, Error::NotACode { what: "reason" }));
2326 assert!(!error.to_string().contains("lines"), "the text is left out");
2327 }
2328 }
2329
2330 #[test]
2331 fn a_long_error_is_cut_on_a_character_boundary() {
2332 let text = "é".repeat(MAX_ERROR);
2333 let kept = cut(text);
2334 assert!(kept.len() <= MAX_ERROR);
2335 assert!(kept.chars().all(|c| c == 'é'));
2336 assert_eq!(cut("short".to_string()), "short");
2337 }
2338
2339 #[test]
2340 #[should_panic(expected = "at least a second")]
2341 fn a_schedule_under_a_second_is_refused_at_boot() {
2342 let _ = Schedule::every(
2343 "fast",
2344 Duration::from_millis(10),
2345 NewJob::new("J", serde_json::Value::Null),
2346 );
2347 }
2348
2349 #[test]
2350 #[should_panic(expected = "bad cron pattern")]
2351 fn a_bad_cron_pattern_is_refused_at_boot() {
2352 let _ = Schedule::cron(
2353 "bad",
2354 "61 * * * *",
2355 NewJob::new("J", serde_json::Value::Null),
2356 );
2357 }
2358
2359 #[test]
2360 fn a_cron_schedule_names_its_next_times_in_utc() {
2361 let schedule = Schedule::cron(
2362 "weekdays",
2363 "0 9 * * MON-FRI",
2364 NewJob::new("J", serde_json::Value::Null),
2365 );
2366 assert_eq!(schedule.cron_pattern(), Some("0 9 * * MON-FRI"));
2367 assert_eq!(schedule.interval(), None);
2368 let Times::Cron(cron, _) = &schedule.times else {
2369 panic!("a cron schedule")
2370 };
2371 let friday = DateTime::parse_from_rfc3339("2026-11-13T09:00:00Z")
2373 .unwrap()
2374 .with_timezone(&Utc);
2375 let monday = DateTime::parse_from_rfc3339("2026-11-16T09:00:00Z")
2376 .unwrap()
2377 .with_timezone(&Utc);
2378 assert_eq!(next_after(cron, friday).unwrap(), monday);
2379 assert_eq!(
2380 Schedule::every(
2381 "e",
2382 Duration::from_secs(5),
2383 NewJob::new("J", serde_json::Value::Null)
2384 )
2385 .interval(),
2386 Some(Duration::from_secs(5))
2387 );
2388 }
2389
2390 #[test]
2391 #[should_panic(expected = "1 to 200 characters")]
2392 fn a_schedule_with_no_name_is_refused_at_boot() {
2393 let _ = Schedule::every(
2394 "",
2395 Duration::from_secs(1),
2396 NewJob::new("J", serde_json::Value::Null),
2397 );
2398 }
2399
2400 #[tokio::test]
2401 #[should_panic(expected = "added twice")]
2402 async fn a_schedule_added_twice_is_refused_at_boot() {
2403 let pool = PgPoolOptions::new()
2404 .connect_lazy("postgres://u@localhost/none")
2405 .unwrap();
2406 let mut queue = Queue::from_pool(pool, QueueOptions::default());
2407 let job = NewJob::new("J", serde_json::Value::Null);
2408 queue.schedule(Schedule::every("a", Duration::from_secs(5), job.clone()));
2409 queue.schedule(Schedule::every("a", Duration::from_secs(9), job));
2410 }
2411
2412 #[test]
2413 fn a_schedule_ignores_a_delay_on_its_job() {
2414 let job = NewJob::new("J", serde_json::Value::Null).run_in(Duration::from_hours(1));
2415 let schedule = Schedule::every("s", Duration::from_secs(5), job);
2416 assert_eq!(schedule.job.when, When::Now);
2417 }
2418}