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 mut last_heard = tokio::time::Instant::now();
1862 let limit = claim
1863 .timeout
1864 .map(|timeout| tokio::time::Instant::now() + timeout);
1865 let deadline = async {
1866 match limit {
1867 Some(at) => tokio::time::sleep_until(at).await,
1868 None => std::future::pending().await,
1869 }
1870 };
1871 tokio::pin!(deadline);
1872 loop {
1873 tokio::select! {
1874 finished = &mut job.0 => {
1875 return Outcome::Done(finished.unwrap_or_else(|_| {
1876 Err(Error::Job("the job panicked".to_string()).to_string().into())
1877 }));
1878 }
1879 () = &mut deadline => {
1880 let limit = claim.timeout.unwrap_or_default();
1881 return Outcome::Done(Err(
1882 Error::Job(format!("timed out after {}s", limit.as_secs_f64())).to_string().into(),
1883 ));
1884 }
1885 () = tokio::time::sleep(every) => {
1886 let beat = sqlx::query(HEARTBEAT)
1887 .bind(claim.id)
1888 .bind(claim.attempts)
1889 .execute(&self.pool)
1890 .await;
1891 match beat {
1892 Ok(done) if done.rows_affected() == 1 => last_heard = tokio::time::Instant::now(),
1893 Ok(_) => return Outcome::Lost("another worker or recovery took its claim".to_string()),
1894 Err(error) => {
1895 tracing::warn!(id = %claim.id, %error, "job heartbeat failed");
1896 if last_heard.elapsed() >= stale {
1897 return Outcome::Lost(format!(
1898 "it could not report in for {} minutes",
1899 self.options.stale_minutes
1900 ));
1901 }
1902 }
1903 }
1904 }
1905 }
1906 }
1907 }
1908
1909 async fn mark_lost(&self, claim: &Claimed, reason: &str) {
1912 let text = Error::Job(format!("stopped: {reason}")).to_string();
1913 let every = self.options.heartbeat_interval.max(MIN_HEARTBEAT);
1914 loop {
1915 match sqlx::query(MARK_LOST)
1916 .bind(claim.id)
1917 .bind(&text)
1918 .execute(&self.pool)
1919 .await
1920 {
1921 Ok(_) => return,
1922 Err(error) => {
1923 tracing::error!(id = %claim.id, %error, "could not mark a lost job for review");
1924 tokio::time::sleep(every).await;
1925 }
1926 }
1927 }
1928 }
1929
1930 fn claimable(&self) -> (Vec<String>, HashMap<String, OwnedSemaphorePermit>) {
1933 let mut places = HashMap::new();
1934 let mut names = Vec::new();
1935 for name in self.handlers.keys() {
1936 match self.limits.get(name) {
1937 None => names.push(name.clone()),
1938 Some(limit) => {
1939 if let Ok(place) = limit.clone().try_acquire_owned() {
1940 places.insert(name.clone(), place);
1941 names.push(name.clone());
1942 }
1943 }
1944 }
1945 }
1946 (names, places)
1947 }
1948
1949 async fn claim(&self, names: &[String]) -> Result<Option<Claimed>> {
1950 let Some(row) = sqlx::query(CLAIM)
1951 .bind(names)
1952 .fetch_optional(&self.pool)
1953 .await?
1954 else {
1955 return Ok(None);
1956 };
1957 Ok(Some(Claimed {
1958 id: row.try_get("id")?,
1959 name: row.try_get("name")?,
1960 args: row.try_get("args")?,
1961 attempts: row.try_get("attempts")?,
1962 limit: row
1963 .try_get::<Option<i32>, _>("max_attempts")?
1964 .unwrap_or(self.options.max_attempts),
1965 timeout: row
1966 .try_get::<Option<i64>, _>("timeout_ms")?
1967 .map(from_millis),
1968 tenant: row.try_get("tenant")?,
1969 }))
1970 }
1971
1972 pub async fn run_one(&self) -> Result<bool> {
1979 let (names, mut places) = self.claimable();
1980 if names.is_empty() {
1981 return Ok(false);
1982 }
1983 let Some(job) = self.claim(&names).await? else {
1984 return Ok(false);
1985 };
1986 let _place = places.remove(&job.name);
1988 drop(places);
1989 let outcome = match self.handlers.get(&job.name) {
1990 Some(handler) => {
1991 let run = handler(job.tenant.clone(), job.args.clone());
1992 self.supervise(run, &job).await
1993 }
1994 None => Outcome::Done(Err(Error::Job(format!("no handler for job {}", job.name))
1995 .to_string()
1996 .into())),
1997 };
1998 let (id, name, attempts) = (job.id, job.name.as_str(), job.attempts);
1999 let finished = match outcome {
2000 Outcome::Lost(reason) => {
2001 tracing::error!(job = %name, %id, attempts, %reason, "job stopped, it lost its claim");
2002 self.mark_lost(&job, &reason).await;
2003 return Ok(true);
2004 }
2005 Outcome::Done(Ok(())) => {
2006 sqlx::query(FINISH)
2007 .bind(id)
2008 .bind(attempts)
2009 .bind("completed")
2010 .bind(None::<String>)
2011 .execute(&self.pool)
2012 .await?
2013 }
2014 Outcome::Done(Err(error)) if attempts < job.limit => {
2015 tracing::warn!(job = %name, %id, attempts, %error, "job failed, will retry");
2016 let wait = retry_wait(self.options.retry_backoff, attempts, error.retry_in);
2017 sqlx::query(RETRY)
2018 .bind(id)
2019 .bind(attempts)
2020 .bind(cut(error.text))
2021 .bind(wait.as_secs_f64())
2022 .execute(&self.pool)
2023 .await?
2024 }
2025 Outcome::Done(Err(error)) => {
2026 tracing::error!(job = %name, %id, attempts, %error, "job failed");
2027 sqlx::query(FINISH)
2028 .bind(id)
2029 .bind(attempts)
2030 .bind("failed")
2031 .bind(cut(error.text))
2032 .execute(&self.pool)
2033 .await?
2034 }
2035 };
2036 if finished.rows_affected() == 0 {
2037 tracing::error!(job = %name, %id, "job finished after losing its claim");
2040 self.mark_lost(
2041 &job,
2042 "it finished after another worker or recovery took its claim",
2043 )
2044 .await;
2045 }
2046 Ok(true)
2047 }
2048
2049 pub async fn run(self: Arc<Self>, shutdown: watch::Receiver<bool>) {
2055 let mut loops = Vec::new();
2056 loops.push(AbortOnDrop(tokio::spawn(every_until(
2057 shutdown.clone(),
2058 self.options.maintenance_interval,
2059 {
2060 let queue = self.clone();
2061 move || {
2062 let queue = queue.clone();
2063 async move { queue.maintain().await }
2064 }
2065 },
2066 ))));
2067 if !self.schedules.is_empty() {
2068 let queue = self.clone();
2069 loops.push(AbortOnDrop(tokio::spawn(every_until(
2070 shutdown.clone(),
2071 self.options.poll_interval,
2072 move || {
2073 let queue = queue.clone();
2074 async move {
2075 if let Err(error) = queue.tick_schedules().await {
2076 tracing::error!(%error, "could not queue scheduled jobs");
2077 }
2078 }
2079 },
2080 ))));
2081 }
2082 let wake = Arc::new(Notify::new());
2083 loops.push(AbortOnDrop(tokio::spawn(listen(
2084 self.pool.clone(),
2085 wake.clone(),
2086 self.options.poll_interval,
2087 shutdown.clone(),
2088 ))));
2089 for _ in 0..self.options.workers.max(1) {
2090 let queue = self.clone();
2091 let wake = wake.clone();
2092 let mut shutdown = shutdown.clone();
2093 loops.push(AbortOnDrop(tokio::spawn(async move {
2094 while !*shutdown.borrow() {
2095 let worked = queue.run_one().await.unwrap_or_else(|error| {
2096 tracing::error!(%error, "job queue error");
2097 false
2098 });
2099 if !worked {
2100 tokio::select! {
2101 () = tokio::time::sleep(queue.options.poll_interval) => {},
2102 () = wake.notified() => {},
2103 _ = shutdown.changed() => {},
2104 }
2105 }
2106 }
2107 })));
2108 }
2109 for job_loop in &mut loops {
2110 let _ = (&mut job_loop.0).await;
2111 }
2112 }
2113
2114 #[must_use]
2116 pub fn handled(&self) -> HashSet<&str> {
2117 self.handlers.keys().map(String::as_str).collect()
2118 }
2119}
2120
2121async fn listen(
2124 pool: PgPool,
2125 wake: Arc<Notify>,
2126 gap: Duration,
2127 mut shutdown: watch::Receiver<bool>,
2128) {
2129 while !*shutdown.borrow() {
2130 match sqlx::postgres::PgListener::connect_with(&pool).await {
2131 Ok(mut listener) => match listener.listen(NOTIFY_CHANNEL).await {
2132 Ok(()) => loop {
2133 tokio::select! {
2134 notice = listener.try_recv() => match notice {
2135 Ok(_) => wake.notify_waiters(),
2138 Err(error) => {
2139 tracing::warn!(%error, "job queue listener failed, polling");
2140 break;
2141 }
2142 },
2143 _ = shutdown.changed() => return,
2144 }
2145 },
2146 Err(error) => tracing::warn!(%error, "job queue could not listen, polling"),
2147 },
2148 Err(error) => tracing::warn!(%error, "job queue could not listen, polling"),
2149 }
2150 tokio::select! {
2151 () = tokio::time::sleep(gap) => {},
2152 _ = shutdown.changed() => {},
2153 }
2154 }
2155}
2156
2157async fn every_until<F, Fut>(mut shutdown: watch::Receiver<bool>, gap: Duration, round: F)
2159where
2160 F: Fn() -> Fut,
2161 Fut: Future<Output = ()>,
2162{
2163 while !*shutdown.borrow() {
2164 round().await;
2165 tokio::select! {
2166 () = tokio::time::sleep(gap) => {},
2167 _ = shutdown.changed() => {},
2168 }
2169 }
2170}
2171
2172struct AbortOnDrop<T>(tokio::task::JoinHandle<T>);
2175
2176impl<T> Drop for AbortOnDrop<T> {
2177 fn drop(&mut self) {
2178 self.0.abort();
2179 }
2180}
2181
2182#[cfg(test)]
2183mod tests {
2184 use super::*;
2185
2186 #[test]
2187 fn each_retry_waits_twice_as_long_up_to_a_limit() {
2188 let base = Duration::from_secs(30);
2189 assert_eq!(backoff(base, 1), base);
2190 assert_eq!(backoff(base, 2), base * 2);
2191 assert_eq!(backoff(base, 3), base * 4);
2192 assert_eq!(backoff(base, 1_000), MAX_BACKOFF);
2193 }
2194
2195 #[test]
2196 fn a_retry_waits_a_jittered_backoff_or_the_delay_the_job_chose() {
2197 let base = Duration::from_secs(30);
2198 for _ in 0..200 {
2199 let wait = retry_wait(base, 2, None);
2200 assert!(wait >= base && wait <= base * 2, "{wait:?}");
2201 }
2202 let waits: HashSet<_> = (0..20).map(|_| retry_wait(base, 1, None)).collect();
2203 assert!(waits.len() > 1, "the waits are spread");
2204 assert_eq!(retry_wait(Duration::ZERO, 3, None), Duration::ZERO);
2205 let chosen = Some(Duration::from_secs(90));
2206 assert_eq!(retry_wait(base, 1, chosen), Duration::from_secs(90));
2207 assert_eq!(retry_wait(base, 1, Some(Duration::ZERO)), MIN_RETRY_AFTER);
2208 assert_eq!(
2209 retry_wait(base, 1, Some(Duration::from_hours(9))),
2210 MAX_BACKOFF
2211 );
2212 }
2213
2214 #[test]
2215 fn a_retry_after_error_carries_its_delay_and_others_none() {
2216 let chosen = Failure::from_error(RetryAfter::new(Duration::from_secs(7), "busy"));
2217 assert_eq!(
2218 (chosen.text.as_str(), chosen.retry_in),
2219 ("busy", Some(Duration::from_secs(7)))
2220 );
2221 let boxed: Box<dyn std::error::Error + Send + Sync> =
2222 Box::new(RetryAfter::new(Duration::from_secs(8), "boxed"));
2223 assert_eq!(
2224 Failure::from_error(boxed).retry_in,
2225 Some(Duration::from_secs(8))
2226 );
2227 let plain = Failure::from_error("broken".to_string());
2228 assert_eq!((plain.text.as_str(), plain.retry_in), ("broken", None));
2229 }
2230
2231 #[test]
2232 fn the_debug_text_leaves_out_arguments() {
2233 let job = NewJob::new("Report", serde_json::json!({ "nhs": "943 476 5919" }));
2234 let schedule = Schedule::every("nightly", Duration::from_hours(1), job.clone());
2235 let cron = Schedule::cron("at-two", "0 2 * * *", job.clone());
2236 for text in [
2237 format!("{job:?}"),
2238 format!("{schedule:?}"),
2239 format!("{cron:?}"),
2240 ] {
2241 assert!(text.contains("Report"), "{text}");
2242 assert!(!text.contains("943"), "{text}");
2243 }
2244 }
2245
2246 #[test]
2247 fn a_by_or_reason_that_is_not_a_code_is_refused() {
2248 assert!(check_code("ops:alice", "by").is_ok());
2249 assert!(check_code(&"é".repeat(MAX_REASON_CHARS), "reason").is_ok());
2250 for bad in [
2251 String::new(),
2252 "é".repeat(MAX_REASON_CHARS + 1),
2253 "two\nlines".to_string(),
2254 "a\ttab".to_string(),
2255 ] {
2256 let error = check_code(&bad, "reason").unwrap_err();
2257 assert!(matches!(error, Error::NotACode { what: "reason" }));
2258 assert!(!error.to_string().contains("lines"), "the text is left out");
2259 }
2260 }
2261
2262 #[test]
2263 fn a_long_error_is_cut_on_a_character_boundary() {
2264 let text = "é".repeat(MAX_ERROR);
2265 let kept = cut(text);
2266 assert!(kept.len() <= MAX_ERROR);
2267 assert!(kept.chars().all(|c| c == 'é'));
2268 assert_eq!(cut("short".to_string()), "short");
2269 }
2270
2271 #[test]
2272 #[should_panic(expected = "at least a second")]
2273 fn a_schedule_under_a_second_is_refused_at_boot() {
2274 let _ = Schedule::every(
2275 "fast",
2276 Duration::from_millis(10),
2277 NewJob::new("J", serde_json::Value::Null),
2278 );
2279 }
2280
2281 #[test]
2282 #[should_panic(expected = "bad cron pattern")]
2283 fn a_bad_cron_pattern_is_refused_at_boot() {
2284 let _ = Schedule::cron(
2285 "bad",
2286 "61 * * * *",
2287 NewJob::new("J", serde_json::Value::Null),
2288 );
2289 }
2290
2291 #[test]
2292 fn a_cron_schedule_names_its_next_times_in_utc() {
2293 let schedule = Schedule::cron(
2294 "weekdays",
2295 "0 9 * * MON-FRI",
2296 NewJob::new("J", serde_json::Value::Null),
2297 );
2298 assert_eq!(schedule.cron_pattern(), Some("0 9 * * MON-FRI"));
2299 assert_eq!(schedule.interval(), None);
2300 let Times::Cron(cron, _) = &schedule.times else {
2301 panic!("a cron schedule")
2302 };
2303 let friday = DateTime::parse_from_rfc3339("2026-11-13T09:00:00Z")
2305 .unwrap()
2306 .with_timezone(&Utc);
2307 let monday = DateTime::parse_from_rfc3339("2026-11-16T09:00:00Z")
2308 .unwrap()
2309 .with_timezone(&Utc);
2310 assert_eq!(next_after(cron, friday).unwrap(), monday);
2311 assert_eq!(
2312 Schedule::every(
2313 "e",
2314 Duration::from_secs(5),
2315 NewJob::new("J", serde_json::Value::Null)
2316 )
2317 .interval(),
2318 Some(Duration::from_secs(5))
2319 );
2320 }
2321
2322 #[test]
2323 #[should_panic(expected = "1 to 200 characters")]
2324 fn a_schedule_with_no_name_is_refused_at_boot() {
2325 let _ = Schedule::every(
2326 "",
2327 Duration::from_secs(1),
2328 NewJob::new("J", serde_json::Value::Null),
2329 );
2330 }
2331
2332 #[tokio::test]
2333 #[should_panic(expected = "added twice")]
2334 async fn a_schedule_added_twice_is_refused_at_boot() {
2335 let pool = PgPoolOptions::new()
2336 .connect_lazy("postgres://u@localhost/none")
2337 .unwrap();
2338 let mut queue = Queue::from_pool(pool, QueueOptions::default());
2339 let job = NewJob::new("J", serde_json::Value::Null);
2340 queue.schedule(Schedule::every("a", Duration::from_secs(5), job.clone()));
2341 queue.schedule(Schedule::every("a", Duration::from_secs(9), job));
2342 }
2343
2344 #[test]
2345 fn a_schedule_ignores_a_delay_on_its_job() {
2346 let job = NewJob::new("J", serde_json::Value::Null).run_in(Duration::from_hours(1));
2347 let schedule = Schedule::every("s", Duration::from_secs(5), job);
2348 assert_eq!(schedule.job.when, When::Now);
2349 }
2350}