1use std::{
161 collections::{HashMap, HashSet},
162 fmt,
163 future::Future,
164 pin::Pin,
165 sync::Arc,
166 time::Duration,
167};
168
169use sqlx::{PgConnection, PgExecutor, PgPool, Postgres, Row, Transaction, postgres::PgPoolOptions};
170use tokio::sync::{OwnedSemaphorePermit, Semaphore, watch};
171use uuid::Uuid;
172
173pub use sqlx::types::chrono::{DateTime, Utc};
174
175pub type Result<T, E = Error> = std::result::Result<T, E>;
177
178#[derive(Debug)]
180#[non_exhaustive]
181pub enum Error {
182 Database(sqlx::Error),
184 Encode(serde_json::Error),
186 Job(String),
188 NotACode {
191 what: &'static str,
193 },
194 NotATenant,
196}
197
198impl fmt::Display for Error {
199 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
200 match self {
201 Self::Database(error) => error.fmt(f),
202 Self::Encode(error) => error.fmt(f),
203 Self::Job(text) => write!(f, "worker error: {text}"),
204 Self::NotACode { what } => write!(
205 f,
206 "`{what}` must be 1 to {MAX_REASON_CHARS} characters with no line breaks"
207 ),
208 Self::NotATenant => f.write_str(
209 "a job's tenant must be 1 to 63 lower-case letters, digits, and hyphens, \
210 not starting or ending with a hyphen",
211 ),
212 }
213 }
214}
215
216impl std::error::Error for Error {
217 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
218 match self {
219 Self::Database(error) => Some(error),
220 Self::Encode(error) => Some(error),
221 Self::Job(_) | Self::NotACode { .. } | Self::NotATenant => None,
222 }
223 }
224}
225
226impl From<sqlx::Error> for Error {
227 fn from(error: sqlx::Error) -> Self {
228 Self::Database(error)
229 }
230}
231
232impl From<serde_json::Error> for Error {
233 fn from(error: serde_json::Error) -> Self {
234 Self::Encode(error)
235 }
236}
237
238type JobFuture = Pin<Box<dyn Future<Output = Result<(), String>> + Send>>;
239type Handler = Arc<dyn Fn(Option<String>, serde_json::Value) -> JobFuture + Send + Sync>;
240
241const SETUP: &str = "CREATE TABLE IF NOT EXISTS axa_queue (
242 id UUID PRIMARY KEY,
243 name TEXT NOT NULL,
244 args JSONB NOT NULL,
245 status TEXT NOT NULL DEFAULT 'queued',
246 error TEXT,
247 run_at TIMESTAMPTZ NOT NULL DEFAULT now(),
248 started_at TIMESTAMPTZ,
249 created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
250 updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
251)";
252const SETUP_INDEX: &str =
253 "CREATE INDEX IF NOT EXISTS axa_queue_ready ON axa_queue (run_at) WHERE status = 'queued'";
254const SETUP_ATTEMPTS: &str =
256 "ALTER TABLE axa_queue ADD COLUMN IF NOT EXISTS attempts INTEGER NOT NULL DEFAULT 0";
257const SETUP_MAX_ATTEMPTS: &str =
259 "ALTER TABLE axa_queue ADD COLUMN IF NOT EXISTS max_attempts INTEGER";
260const SETUP_PRIORITY: &str =
262 "ALTER TABLE axa_queue ADD COLUMN IF NOT EXISTS priority SMALLINT NOT NULL DEFAULT 0";
263const SETUP_TIMEOUT: &str = "ALTER TABLE axa_queue ADD COLUMN IF NOT EXISTS timeout_ms BIGINT";
265const SETUP_TENANT: &str = "ALTER TABLE axa_queue ADD COLUMN IF NOT EXISTS tenant TEXT
267 CONSTRAINT axa_queue_tenant_id CHECK (tenant ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$')";
268const SETUP_UNIQUE_KEY: &str = "ALTER TABLE axa_queue ADD COLUMN IF NOT EXISTS unique_key TEXT
270 CONSTRAINT axa_queue_unique_key_code
271 CHECK (length(unique_key) BETWEEN 1 AND 200 AND unique_key !~ '[[:cntrl:]]')";
272const SETUP_UNIQUE_INDEX: &str = "CREATE UNIQUE INDEX IF NOT EXISTS axa_queue_unique
274 ON axa_queue (name, (COALESCE(tenant, '')), unique_key)
275 WHERE unique_key IS NOT NULL AND status IN ('queued', 'running')";
276const SETUP_CLAIM_INDEX: &str = "CREATE INDEX IF NOT EXISTS axa_queue_claim
277 ON axa_queue (priority DESC, run_at) WHERE status = 'queued'";
278const SETUP_SCHEDULE: &str = "CREATE TABLE IF NOT EXISTS axa_schedule (
279 name TEXT PRIMARY KEY,
280 due_at TIMESTAMPTZ NOT NULL,
281 last_job UUID,
282 interval_ms BIGINT,
283 seen_at TIMESTAMPTZ NOT NULL DEFAULT now(),
284 archived_at TIMESTAMPTZ,
285 created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
286 updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
287)";
288const SETUP_SCHEDULE_CRON: &str = "ALTER TABLE axa_schedule ADD COLUMN IF NOT EXISTS cron TEXT";
294const SETUP_ACTS: &str = "CREATE TABLE IF NOT EXISTS axa_job_acts (
295 id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
296 job_id UUID NOT NULL,
297 job_name TEXT NOT NULL,
298 act TEXT NOT NULL CHECK (act IN ('cancelled', 'retried', 'released')),
299 attempts INTEGER NOT NULL,
300 by TEXT NOT NULL CHECK (length(by) BETWEEN 1 AND 200 AND by !~ '[[:cntrl:]]'),
301 reason TEXT NOT NULL CHECK (length(reason) BETWEEN 1 AND 200 AND reason !~ '[[:cntrl:]]'),
302 at TIMESTAMPTZ NOT NULL DEFAULT now()
303)";
304const SETUP_ACTS_INDEX: &str =
305 "CREATE INDEX IF NOT EXISTS axa_job_acts_job ON axa_job_acts (job_id, id)";
306const SETUP_ACTS_REFUSE: &str = "CREATE OR REPLACE FUNCTION axa_job_acts_refuse() RETURNS trigger
308LANGUAGE plpgsql AS $$
309BEGIN
310 RAISE EXCEPTION '% on % is refused: acts on jobs are only ever added to',
311 TG_OP, TG_TABLE_NAME;
312END
313$$";
314const SETUP_ACTS_ROWS: &str = "CREATE OR REPLACE TRIGGER axa_job_acts_refuse
315 BEFORE UPDATE OR DELETE ON axa_job_acts
316 FOR EACH ROW EXECUTE FUNCTION axa_job_acts_refuse()";
317const SETUP_ACTS_TRUNCATE: &str = "CREATE OR REPLACE TRIGGER axa_job_acts_refuse_truncate
318 BEFORE TRUNCATE ON axa_job_acts
319 FOR EACH STATEMENT EXECUTE FUNCTION axa_job_acts_refuse()";
320const SETUP_ACTS_ALWAYS: &str = "ALTER TABLE axa_job_acts
323 ENABLE ALWAYS TRIGGER axa_job_acts_refuse,
324 ENABLE ALWAYS TRIGGER axa_job_acts_refuse_truncate";
325const ACTS_TRIGGERS: [&str; 2] = ["axa_job_acts_refuse", "axa_job_acts_refuse_truncate"];
327const MISSING_TRIGGERS: &str = "SELECT want FROM unnest($1::text[]) AS want
328 WHERE NOT EXISTS (
329 SELECT 1 FROM pg_trigger t
330 WHERE t.tgrelid = to_regclass('axa_job_acts') AND t.tgname = want
331 AND t.tgenabled::text = 'A'
332 )";
333const NO_TENANT_HANDLER: &str =
335 "the job has a tenant, and its handler takes none: register it with handle_with_tenant";
336
337const SETUP_LOCK: i64 = 0x0061_7861_5F71;
339
340const ENQUEUE: &str = "INSERT INTO axa_queue
341 (id, name, args, max_attempts, priority, run_at, timeout_ms, tenant)
342 VALUES ($1, $2, $3, $4, $5, COALESCE($6, now() + make_interval(secs => $7)), $8, $9)";
343const ENQUEUE_UNIQUE: &str = "INSERT INTO axa_queue
348 (id, name, args, max_attempts, priority, run_at, timeout_ms, tenant, unique_key)
349 VALUES ($1, $2, $3, $4, $5, COALESCE($6, now() + make_interval(secs => $7)), $8, $9, $10)
350 ON CONFLICT (name, (COALESCE(tenant, '')), unique_key)
351 WHERE unique_key IS NOT NULL AND status IN ('queued', 'running')
352 DO UPDATE SET unique_key = EXCLUDED.unique_key
353 RETURNING id";
354const CLAIM: &str = "UPDATE axa_queue
355 SET status = 'running', started_at = now(), updated_at = now(), attempts = attempts + 1
356 WHERE id = (
357 SELECT id FROM axa_queue
358 WHERE status = 'queued' AND run_at <= now() AND name = ANY($1)
359 ORDER BY priority DESC, run_at
360 FOR UPDATE SKIP LOCKED
361 LIMIT 1
362 )
363 RETURNING id, name, args, attempts, max_attempts, timeout_ms, tenant";
364const HEARTBEAT: &str = "UPDATE axa_queue SET updated_at = now()
367 WHERE id = $1 AND attempts = $2 AND status = 'running'";
368const FINISH: &str = "UPDATE axa_queue SET status = $3, error = $4, updated_at = now()
369 WHERE id = $1 AND attempts = $2 AND status = 'running'";
370const RETRY: &str = "UPDATE axa_queue
371 SET status = 'queued', error = $3, started_at = NULL, updated_at = now(),
372 run_at = now() + make_interval(secs => $4)
373 WHERE id = $1 AND attempts = $2 AND status = 'running'";
374const REQUEUE_STALE: &str = "UPDATE axa_queue
375 SET status = 'queued', started_at = NULL, updated_at = now()
376 WHERE status = 'running' AND updated_at < now() - make_interval(mins => $1)
377 AND attempts < COALESCE(max_attempts, $2)";
378const FAIL_STALE: &str = "UPDATE axa_queue
379 SET status = 'failed', error = 'abandoned by its worker', updated_at = now()
380 WHERE status = 'running' AND updated_at < now() - make_interval(mins => $1)
381 AND attempts >= COALESCE(max_attempts, $2)";
382const PURGE: &str = "DELETE FROM axa_queue
383 WHERE status IN ('completed', 'failed', 'cancelled')
384 AND updated_at < now() - make_interval(days => $1)";
385const STATUS: &str = "SELECT id, name, status, attempts, max_attempts, priority, error,
386 timeout_ms, tenant, unique_key, run_at, started_at, created_at, updated_at FROM axa_queue WHERE id = $1";
387const MARK_LOST: &str =
391 "UPDATE axa_queue SET status = 'needs_review', error = $2, updated_at = now()
392 WHERE id = $1 AND status IN ('queued', 'running', 'failed')";
393const CANCEL: &str = "WITH changed AS (
396 UPDATE axa_queue SET status = 'cancelled', updated_at = now()
397 WHERE id = $1 AND status = 'queued'
398 RETURNING id, name, attempts
399 )
400 INSERT INTO axa_job_acts (job_id, job_name, act, attempts, by, reason)
401 SELECT id, name, 'cancelled', attempts, $2, $3 FROM changed";
402const RETRY_FAILED: &str = "WITH target AS (
407 SELECT id, status FROM axa_queue
408 WHERE id = $1 AND status IN ('failed', 'needs_review')
409 AND NOT EXISTS (
410 SELECT 1 FROM axa_queue other
411 WHERE other.unique_key = axa_queue.unique_key
412 AND other.name = axa_queue.name
413 AND COALESCE(other.tenant, '') = COALESCE(axa_queue.tenant, '')
414 AND other.status IN ('queued', 'running')
415 )
416 FOR UPDATE
417 ), changed AS (
418 UPDATE axa_queue q
419 SET status = 'queued', run_at = now(), started_at = NULL, updated_at = now(),
420 max_attempts = q.attempts + 1
421 FROM target WHERE q.id = target.id
422 RETURNING q.id, q.name, q.attempts, target.status AS was
423 )
424 INSERT INTO axa_job_acts (job_id, job_name, act, attempts, by, reason)
425 SELECT id, name, CASE was WHEN 'needs_review' THEN 'released' ELSE 'retried' END,
426 attempts, $2, $3
427 FROM changed";
428const ACTS: &str = "SELECT id, job_id, job_name, act, attempts, by, reason, at
429 FROM axa_job_acts WHERE job_id = $1 ORDER BY id";
430const COUNTS: &str = "SELECT
431 count(*) FILTER (WHERE status = 'queued' AND run_at <= now()) AS ready,
432 count(*) FILTER (WHERE status = 'queued' AND run_at > now()) AS waiting,
433 count(*) FILTER (WHERE status = 'running') AS running,
434 count(*) FILTER (WHERE status = 'completed') AS completed,
435 count(*) FILTER (WHERE status = 'failed') AS failed,
436 count(*) FILTER (WHERE status = 'cancelled') AS cancelled,
437 count(*) FILTER (WHERE status = 'needs_review') AS needs_review,
438 EXTRACT(EPOCH FROM now() - min(run_at) FILTER (WHERE status = 'queued' AND run_at <= now()))::float8 AS oldest
439 FROM axa_queue";
440const SCHEDULE_CREATE: &str = "INSERT INTO axa_schedule (name, due_at, interval_ms, cron)
445 VALUES ($1, COALESCE($2, now()), $3, $4)
446 ON CONFLICT (name) DO UPDATE
447 SET seen_at = now(), archived_at = NULL, interval_ms = EXCLUDED.interval_ms,
448 cron = EXCLUDED.cron,
449 due_at = CASE WHEN EXCLUDED.cron IS NOT NULL
450 AND axa_schedule.cron IS DISTINCT FROM EXCLUDED.cron
451 THEN EXCLUDED.due_at ELSE axa_schedule.due_at END
452 WHERE axa_schedule.archived_at IS NOT NULL
453 OR axa_schedule.interval_ms IS DISTINCT FROM EXCLUDED.interval_ms
454 OR axa_schedule.cron IS DISTINCT FROM EXCLUDED.cron
455 OR axa_schedule.seen_at < now() - interval '1 minute'";
456const SCHEDULE_LOCK: &str =
457 "SELECT last_job, due_at <= now() AS due, now() AS now FROM axa_schedule
458 WHERE name = $1 AND archived_at IS NULL FOR UPDATE SKIP LOCKED";
459const SCHEDULE_ARCHIVE: &str = "UPDATE axa_schedule SET archived_at = now(), updated_at = now()
463 WHERE archived_at IS NULL AND name <> ALL($1)
464 AND seen_at < now() - make_interval(mins => $2)";
465const SCHEDULES: &str = "SELECT s.name, s.interval_ms, s.cron, s.due_at, s.last_job, s.seen_at,
466 s.archived_at, s.created_at, q.status AS last_status, q.error AS last_error
467 FROM axa_schedule s LEFT JOIN axa_queue q ON q.id = s.last_job ORDER BY s.name";
468const SCHEDULE_BUSY: &str = "SELECT EXISTS (SELECT 1 FROM axa_queue
469 WHERE id = $1 AND status IN ('queued', 'running'))";
470const SCHEDULE_ADVANCE: &str = "UPDATE axa_schedule
473 SET due_at = due_at + make_interval(secs => $2)
474 * (floor(EXTRACT(EPOCH FROM now() - due_at)::float8 / $2) + 1),
475 last_job = COALESCE($3, last_job), updated_at = now()
476 WHERE name = $1";
477const SCHEDULE_ADVANCE_TO: &str = "UPDATE axa_schedule
479 SET due_at = $2, last_job = COALESCE($3, last_job), updated_at = now()
480 WHERE name = $1";
481
482pub const SETUP_STATEMENTS: [&str; 18] = [
486 SETUP,
487 SETUP_ATTEMPTS,
488 SETUP_MAX_ATTEMPTS,
489 SETUP_INDEX,
490 SETUP_PRIORITY,
491 SETUP_TIMEOUT,
492 SETUP_TENANT,
493 SETUP_UNIQUE_KEY,
494 SETUP_UNIQUE_INDEX,
495 SETUP_CLAIM_INDEX,
496 SETUP_SCHEDULE,
497 SETUP_SCHEDULE_CRON,
498 SETUP_ACTS,
499 SETUP_ACTS_INDEX,
500 SETUP_ACTS_REFUSE,
501 SETUP_ACTS_ROWS,
502 SETUP_ACTS_TRUNCATE,
503 SETUP_ACTS_ALWAYS,
504];
505
506pub const MAX_REASON_CHARS: usize = 200;
508
509const MIN_HEARTBEAT: Duration = Duration::from_millis(20);
511
512const MAX_BACKOFF: Duration = Duration::from_hours(1);
514
515const MAX_ERROR: usize = 1024;
517
518#[must_use]
520pub fn backoff(base: Duration, attempts: i32) -> Duration {
521 let doublings = u32::try_from(attempts.saturating_sub(1))
522 .unwrap_or(0)
523 .min(16);
524 base.saturating_mul(1 << doublings).min(MAX_BACKOFF)
525}
526
527fn cut(mut text: String) -> String {
529 if text.len() > MAX_ERROR {
530 let mut end = MAX_ERROR;
531 while !text.is_char_boundary(end) {
532 end -= 1;
533 }
534 text.truncate(end);
535 }
536 text
537}
538
539fn millis(duration: Duration) -> i64 {
540 i64::try_from(duration.as_millis()).unwrap_or(i64::MAX)
541}
542
543fn from_millis(millis: i64) -> Duration {
544 Duration::from_millis(u64::try_from(millis).unwrap_or(0))
545}
546
547#[derive(Debug, Clone, Copy, PartialEq, Eq)]
549enum When {
550 Now,
551 At(DateTime<Utc>),
552 In(Duration),
553}
554
555#[derive(Clone)]
557pub struct NewJob {
558 name: String,
559 args: serde_json::Value,
560 max_attempts: Option<i32>,
561 priority: i16,
562 when: When,
563 timeout: Option<Duration>,
564 tenant: Option<String>,
565 unique_key: Option<String>,
566}
567
568impl fmt::Debug for NewJob {
569 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
570 f.debug_struct("NewJob")
571 .field("name", &self.name)
572 .field("max_attempts", &self.max_attempts)
573 .field("priority", &self.priority)
574 .field("when", &self.when)
575 .field("timeout", &self.timeout)
576 .field("tenant", &self.tenant)
577 .field("unique_key", &self.unique_key)
578 .finish_non_exhaustive()
579 }
580}
581
582impl NewJob {
583 pub fn new(name: impl Into<String>, args: serde_json::Value) -> Self {
586 Self {
587 name: name.into(),
588 args,
589 max_attempts: None,
590 priority: 0,
591 when: When::Now,
592 timeout: None,
593 tenant: None,
594 unique_key: None,
595 }
596 }
597
598 #[must_use]
605 pub fn unique(mut self, key: impl Into<String>) -> Self {
606 self.unique_key = Some(key.into());
607 self
608 }
609
610 #[must_use]
616 pub fn tenant(mut self, tenant: impl Into<String>) -> Self {
617 self.tenant = Some(tenant.into());
618 self
619 }
620
621 #[must_use]
624 pub const fn timeout(mut self, limit: Duration) -> Self {
625 self.timeout = Some(limit);
626 self
627 }
628
629 #[must_use]
631 pub const fn max_attempts(mut self, max_attempts: Option<i32>) -> Self {
632 self.max_attempts = max_attempts;
633 self
634 }
635
636 #[must_use]
639 pub const fn priority(mut self, priority: i16) -> Self {
640 self.priority = priority;
641 self
642 }
643
644 #[must_use]
646 pub const fn run_in(mut self, delay: Duration) -> Self {
647 self.when = When::In(delay);
648 self
649 }
650
651 #[must_use]
653 pub const fn run_at(mut self, at: DateTime<Utc>) -> Self {
654 self.when = When::At(at);
655 self
656 }
657
658 #[must_use]
660 pub fn name(&self) -> &str {
661 &self.name
662 }
663
664 #[must_use]
666 pub fn tenant_id(&self) -> Option<&str> {
667 self.tenant.as_deref()
668 }
669
670 #[must_use]
672 pub fn unique_key(&self) -> Option<&str> {
673 self.unique_key.as_deref()
674 }
675}
676
677pub const MAX_TENANT_ID_LEN: usize = 63;
679
680#[must_use]
684pub fn is_tenant_id(id: &str) -> bool {
685 (1..=MAX_TENANT_ID_LEN).contains(&id.len())
686 && !id.starts_with('-')
687 && !id.ends_with('-')
688 && id
689 .bytes()
690 .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'-')
691}
692
693pub async fn enqueue_on<'e, E: PgExecutor<'e>>(executor: E, job: &NewJob) -> Result<Uuid> {
704 if job
705 .tenant
706 .as_deref()
707 .is_some_and(|tenant| !is_tenant_id(tenant))
708 {
709 return Err(Error::NotATenant);
710 }
711 if let Some(key) = job.unique_key.as_deref() {
712 check_code(key, "unique key")?;
713 }
714 let id = Uuid::new_v4();
715 let (at, delay) = match job.when {
716 When::Now => (None, 0.0),
717 When::At(at) => (Some(at), 0.0),
718 When::In(delay) => (None, delay.as_secs_f64()),
719 };
720 let query = sqlx::query(if job.unique_key.is_some() {
721 ENQUEUE_UNIQUE
722 } else {
723 ENQUEUE
724 })
725 .bind(id)
726 .bind(&job.name)
727 .bind(&job.args)
728 .bind(job.max_attempts)
729 .bind(job.priority)
730 .bind(at)
731 .bind(delay)
732 .bind(job.timeout.map(millis))
733 .bind(job.tenant.as_deref());
734 if let Some(key) = job.unique_key.as_deref() {
735 Ok(query.bind(key).fetch_one(executor).await?.try_get("id")?)
736 } else {
737 query.execute(executor).await?;
738 Ok(id)
739 }
740}
741
742pub async fn enqueue_all_on(connection: &mut PgConnection, jobs: &[NewJob]) -> Result<Vec<Uuid>> {
749 let mut ids = Vec::with_capacity(jobs.len());
750 for job in jobs {
751 ids.push(enqueue_on(&mut *connection, job).await?);
752 }
753 Ok(ids)
754}
755
756fn check_code(text: &str, what: &'static str) -> Result<()> {
758 if text.is_empty()
759 || text.chars().count() > MAX_REASON_CHARS
760 || text.chars().any(char::is_control)
761 {
762 Err(Error::NotACode { what })
763 } else {
764 Ok(())
765 }
766}
767
768pub async fn cancel(
782 transaction: &mut Transaction<'_, Postgres>,
783 id: Uuid,
784 by: &str,
785 reason: &str,
786) -> Result<bool> {
787 act(transaction, CANCEL, id, by, reason).await
788}
789
790pub async fn retry(
803 transaction: &mut Transaction<'_, Postgres>,
804 id: Uuid,
805 by: &str,
806 reason: &str,
807) -> Result<bool> {
808 act(transaction, RETRY_FAILED, id, by, reason).await
809}
810
811async fn act(
813 transaction: &mut Transaction<'_, Postgres>,
814 statement: &'static str,
815 id: Uuid,
816 by: &str,
817 reason: &str,
818) -> Result<bool> {
819 check_code(by, "by")?;
820 check_code(reason, "reason")?;
821 let kept = sqlx::query(statement)
822 .bind(id)
823 .bind(by)
824 .bind(reason)
825 .execute(&mut **transaction)
826 .await?
827 .rows_affected();
828 Ok(kept == 1)
829}
830
831#[derive(Debug, Clone, Copy, PartialEq, Eq)]
833#[non_exhaustive]
834pub enum ActKind {
835 Cancelled,
837 Retried,
839 Released,
841}
842
843impl ActKind {
844 fn parse(text: &str) -> Result<Self> {
845 match text {
846 "cancelled" => Ok(Self::Cancelled),
847 "retried" => Ok(Self::Retried),
848 "released" => Ok(Self::Released),
849 _ => Err(Error::Job("an act with an unknown kind".to_string())),
850 }
851 }
852}
853
854#[derive(Debug, Clone)]
857#[non_exhaustive]
858pub struct Act {
859 pub id: i64,
861 pub job_id: Uuid,
863 pub job_name: String,
865 pub kind: ActKind,
867 pub attempts: i32,
869 pub by: String,
871 pub reason: String,
873 pub at: DateTime<Utc>,
875}
876
877#[derive(Debug, Clone, Copy, PartialEq, Eq)]
879pub enum JobState {
880 Queued,
882 Running,
884 Completed,
886 Failed,
888 Cancelled,
890 NeedsReview,
894}
895
896impl JobState {
897 fn parse(text: &str) -> Result<Self> {
898 match text {
899 "queued" => Ok(Self::Queued),
900 "running" => Ok(Self::Running),
901 "completed" => Ok(Self::Completed),
902 "failed" => Ok(Self::Failed),
903 "cancelled" => Ok(Self::Cancelled),
904 "needs_review" => Ok(Self::NeedsReview),
905 _ => Err(Error::Job("a job row with an unknown status".to_string())),
906 }
907 }
908}
909
910#[derive(Debug, Clone)]
912#[non_exhaustive]
913pub struct JobInfo {
914 pub id: Uuid,
916 pub name: String,
918 pub state: JobState,
920 pub attempts: i32,
922 pub max_attempts: Option<i32>,
924 pub priority: i16,
926 pub timeout: Option<Duration>,
928 pub tenant: Option<String>,
930 pub unique_key: Option<String>,
932 pub error: Option<String>,
935 pub run_at: DateTime<Utc>,
937 pub started_at: Option<DateTime<Utc>>,
939 pub created_at: DateTime<Utc>,
941 pub updated_at: DateTime<Utc>,
943}
944
945#[derive(Debug, Clone, Copy, Default, PartialEq)]
947#[non_exhaustive]
948pub struct Counts {
949 pub ready: i64,
951 pub waiting: i64,
953 pub running: i64,
955 pub completed: i64,
957 pub failed: i64,
959 pub cancelled: i64,
961 pub needs_review: i64,
964 pub oldest_ready_seconds: f64,
967}
968
969#[derive(Clone)]
972pub struct Schedule {
973 name: String,
974 times: Times,
975 first: Option<DateTime<Utc>>,
976 job: NewJob,
977}
978
979#[derive(Clone)]
981enum Times {
982 Every(Duration),
983 Cron(Box<croner::Cron>, String),
985}
986
987impl Times {
988 fn interval(&self) -> Option<Duration> {
989 match self {
990 Self::Every(interval) => Some(*interval),
991 Self::Cron(..) => None,
992 }
993 }
994
995 fn pattern(&self) -> Option<&str> {
996 match self {
997 Self::Every(_) => None,
998 Self::Cron(_, pattern) => Some(pattern),
999 }
1000 }
1001}
1002
1003fn next_after(cron: &croner::Cron, now: DateTime<Utc>) -> Result<DateTime<Utc>> {
1005 cron.find_next_occurrence(&now, false)
1006 .map_err(|error| Error::Job(format!("the cron pattern has no next time: {error}")))
1007}
1008
1009impl fmt::Debug for Schedule {
1010 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1011 f.debug_struct("Schedule")
1012 .field("name", &self.name)
1013 .field("interval", &self.times.interval())
1014 .field("cron", &self.times.pattern())
1015 .field("first", &self.first)
1016 .field("job", &self.job)
1017 .finish()
1018 }
1019}
1020
1021impl Schedule {
1022 pub fn every(name: impl Into<String>, interval: Duration, job: NewJob) -> Self {
1031 let name = checked_name(name.into());
1032 assert!(
1033 interval >= Duration::from_secs(1),
1034 "the schedule {name} needs an interval of at least a second"
1035 );
1036 Self {
1037 name,
1038 times: Times::Every(interval),
1039 first: None,
1040 job: NewJob {
1041 when: When::Now,
1042 ..job
1043 },
1044 }
1045 }
1046
1047 pub fn cron(name: impl Into<String>, pattern: &str, job: NewJob) -> Self {
1059 let name = checked_name(name.into());
1060 let cron: croner::Cron = pattern
1061 .parse()
1062 .unwrap_or_else(|error| panic!("the schedule {name} has a bad cron pattern: {error}"));
1063 assert!(
1064 next_after(&cron, Utc::now()).is_ok(),
1065 "the cron pattern of the schedule {name} names no time to come"
1066 );
1067 Self {
1068 name,
1069 times: Times::Cron(Box::new(cron), pattern.to_string()),
1070 first: None,
1071 job: NewJob {
1072 when: When::Now,
1073 ..job
1074 },
1075 }
1076 }
1077
1078 #[must_use]
1083 pub const fn first_at(mut self, first: DateTime<Utc>) -> Self {
1084 self.first = Some(first);
1085 self
1086 }
1087
1088 #[must_use]
1090 pub fn interval(&self) -> Option<Duration> {
1091 self.times.interval()
1092 }
1093
1094 #[must_use]
1096 pub fn cron_pattern(&self) -> Option<&str> {
1097 self.times.pattern()
1098 }
1099
1100 #[must_use]
1102 pub fn name(&self) -> &str {
1103 &self.name
1104 }
1105}
1106
1107fn checked_name(name: String) -> String {
1109 assert!(
1110 !name.is_empty() && name.len() <= 200,
1111 "a schedule name must be 1 to 200 characters"
1112 );
1113 name
1114}
1115
1116#[derive(Debug, Clone)]
1118#[non_exhaustive]
1119pub struct ScheduleInfo {
1120 pub name: String,
1122 pub interval: Option<Duration>,
1124 pub cron: Option<String>,
1126 pub due_at: DateTime<Utc>,
1128 pub last_job: Option<Uuid>,
1130 pub last_state: Option<JobState>,
1132 pub last_error: Option<String>,
1134 pub seen_at: DateTime<Utc>,
1136 pub archived_at: Option<DateTime<Utc>>,
1139 pub created_at: DateTime<Utc>,
1141}
1142
1143#[derive(Debug, Clone)]
1145pub struct QueueOptions {
1146 pub workers: usize,
1148 pub poll_interval: Duration,
1150 pub stale_minutes: i32,
1153 pub heartbeat_interval: Duration,
1155 pub max_attempts: i32,
1158 pub retry_backoff: Duration,
1160 pub retention_days: i32,
1162 pub maintenance_interval: Duration,
1164}
1165
1166impl Default for QueueOptions {
1167 fn default() -> Self {
1168 Self {
1169 workers: 2,
1170 poll_interval: Duration::from_secs(1),
1171 stale_minutes: 60,
1172 heartbeat_interval: Duration::from_mins(1),
1173 max_attempts: 1,
1174 retry_backoff: Duration::from_secs(30),
1175 retention_days: 7,
1176 maintenance_interval: Duration::from_mins(5),
1177 }
1178 }
1179}
1180
1181pub struct Queue {
1183 pool: PgPool,
1184 handlers: HashMap<String, Handler>,
1185 limits: HashMap<String, Arc<Semaphore>>,
1186 schedules: Vec<Schedule>,
1187 options: QueueOptions,
1188}
1189
1190impl fmt::Debug for Queue {
1191 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1192 f.debug_struct("Queue")
1193 .field("handlers", &self.handlers.len())
1194 .field("limits", &self.limits.len())
1195 .field("schedules", &self.schedules.len())
1196 .field("options", &self.options)
1197 .finish_non_exhaustive()
1198 }
1199}
1200
1201struct Claimed {
1203 id: Uuid,
1204 name: String,
1205 args: serde_json::Value,
1206 attempts: i32,
1207 limit: i32,
1208 timeout: Option<Duration>,
1209 tenant: Option<String>,
1210}
1211
1212enum Outcome {
1214 Done(Result<(), String>),
1216 Lost(String),
1218}
1219
1220impl Queue {
1221 #[must_use]
1224 pub fn from_pool(pool: PgPool, options: QueueOptions) -> Self {
1225 Self {
1226 pool,
1227 handlers: HashMap::new(),
1228 limits: HashMap::new(),
1229 schedules: Vec::new(),
1230 options,
1231 }
1232 }
1233
1234 async fn open(uri: &str, options: QueueOptions) -> Result<Self> {
1236 let loops = u32::try_from(options.workers).unwrap_or(u32::MAX);
1237 let pool = PgPoolOptions::new()
1238 .max_connections(loops.saturating_add(2))
1239 .connect(uri)
1240 .await?;
1241 Ok(Self::from_pool(pool, options))
1242 }
1243
1244 pub async fn connect_existing(uri: &str, options: QueueOptions) -> Result<Self> {
1254 let queue = Self::open(uri, options).await?;
1255 queue.check().await?;
1256 Ok(queue)
1257 }
1258
1259 pub async fn connect(uri: &str, options: QueueOptions) -> Result<Self> {
1266 let queue = Self::open(uri, options).await?;
1267 let mut setup = queue.pool.begin().await?;
1272 sqlx::query("SELECT pg_advisory_xact_lock($1)")
1273 .bind(SETUP_LOCK)
1274 .execute(&mut *setup)
1275 .await?;
1276 for statement in SETUP_STATEMENTS {
1277 sqlx::query(statement).execute(&mut *setup).await?;
1278 }
1279 setup.commit().await?;
1280 Ok(queue)
1281 }
1282
1283 pub async fn check(&self) -> Result<()> {
1291 sqlx::query(
1292 "SELECT attempts, max_attempts, priority, timeout_ms, tenant, unique_key FROM axa_queue LIMIT 0",
1293 )
1294 .execute(&self.pool)
1295 .await?;
1296 sqlx::query(
1297 "SELECT name, due_at, last_job, interval_ms, cron, seen_at, archived_at FROM axa_schedule LIMIT 0",
1298 )
1299 .execute(&self.pool)
1300 .await?;
1301 sqlx::query(
1302 "SELECT id, job_id, job_name, act, attempts, by, reason, at FROM axa_job_acts LIMIT 0",
1303 )
1304 .execute(&self.pool)
1305 .await?;
1306 let mut missing: Vec<String> = sqlx::query_scalar(MISSING_TRIGGERS)
1307 .bind(ACTS_TRIGGERS.to_vec())
1308 .fetch_all(&self.pool)
1309 .await?;
1310 let unique_index: bool =
1311 sqlx::query_scalar("SELECT to_regclass('axa_queue_unique') IS NOT NULL")
1312 .fetch_one(&self.pool)
1313 .await?;
1314 if !unique_index {
1315 missing.push("axa_queue_unique".to_string());
1316 }
1317 if missing.is_empty() {
1318 Ok(())
1319 } else {
1320 Err(Error::Database(sqlx::Error::Configuration(
1321 format!(
1322 "the job queue is missing, or has turned off, {}: run SETUP_STATEMENTS",
1323 missing.join(", ")
1324 )
1325 .into(),
1326 )))
1327 }
1328 }
1329
1330 #[must_use]
1333 pub const fn pool(&self) -> &PgPool {
1334 &self.pool
1335 }
1336
1337 #[must_use]
1339 pub const fn options(&self) -> &QueueOptions {
1340 &self.options
1341 }
1342
1343 pub fn handle<F, Fut, E>(&mut self, name: impl Into<String>, handler: F)
1350 where
1351 F: Fn(serde_json::Value) -> Fut + Send + Sync + 'static,
1352 Fut: Future<Output = std::result::Result<(), E>> + Send + 'static,
1353 E: fmt::Display + 'static,
1354 {
1355 let handler = Arc::new(handler);
1356 let run: Handler = Arc::new(move |tenant, args| {
1357 if tenant.is_some() {
1358 return Box::pin(std::future::ready(Err(NO_TENANT_HANDLER.to_string())));
1359 }
1360 let job = handler(args);
1361 Box::pin(async move { job.await.map_err(|error| error.to_string()) })
1362 });
1363 self.handlers.insert(name.into(), run);
1364 }
1365
1366 pub fn handle_with_tenant<F, Fut, E>(&mut self, name: impl Into<String>, handler: F)
1371 where
1372 F: Fn(Option<String>, serde_json::Value) -> Fut + Send + Sync + 'static,
1373 Fut: Future<Output = std::result::Result<(), E>> + Send + 'static,
1374 E: fmt::Display + 'static,
1375 {
1376 let handler = Arc::new(handler);
1377 let run: Handler = Arc::new(move |tenant, args| {
1378 let job = handler(tenant, args);
1379 Box::pin(async move { job.await.map_err(|error| error.to_string()) })
1380 });
1381 self.handlers.insert(name.into(), run);
1382 }
1383
1384 pub fn limit(&mut self, name: impl Into<String>, jobs: usize) {
1387 self.limits
1388 .insert(name.into(), Arc::new(Semaphore::new(jobs.max(1))));
1389 }
1390
1391 pub fn schedule(&mut self, schedule: Schedule) {
1397 assert!(
1398 self.schedules.iter().all(|s| s.name != schedule.name),
1399 "the schedule {} was added twice",
1400 schedule.name
1401 );
1402 self.schedules.push(schedule);
1403 }
1404
1405 pub async fn enqueue(&self, name: &str, args: serde_json::Value) -> Result<Uuid> {
1411 enqueue_on(&self.pool, &NewJob::new(name, args)).await
1412 }
1413
1414 pub async fn enqueue_limited(
1420 &self,
1421 name: &str,
1422 args: serde_json::Value,
1423 max_attempts: Option<i32>,
1424 ) -> Result<Uuid> {
1425 enqueue_on(
1426 &self.pool,
1427 &NewJob::new(name, args).max_attempts(max_attempts),
1428 )
1429 .await
1430 }
1431
1432 pub async fn enqueue_job(&self, job: &NewJob) -> Result<Uuid> {
1438 enqueue_on(&self.pool, job).await
1439 }
1440
1441 pub async fn enqueue_all(&self, jobs: &[NewJob]) -> Result<Vec<Uuid>> {
1447 let mut transaction = self.pool.begin().await?;
1448 let ids = enqueue_all_on(&mut transaction, jobs).await?;
1449 transaction.commit().await?;
1450 Ok(ids)
1451 }
1452
1453 pub async fn job(&self, id: Uuid) -> Result<Option<JobInfo>> {
1460 let Some(row) = sqlx::query(STATUS)
1461 .bind(id)
1462 .fetch_optional(&self.pool)
1463 .await?
1464 else {
1465 return Ok(None);
1466 };
1467 Ok(Some(JobInfo {
1468 id: row.try_get("id")?,
1469 name: row.try_get("name")?,
1470 state: JobState::parse(row.try_get::<&str, _>("status")?)?,
1471 attempts: row.try_get("attempts")?,
1472 max_attempts: row.try_get("max_attempts")?,
1473 priority: row.try_get("priority")?,
1474 timeout: row
1475 .try_get::<Option<i64>, _>("timeout_ms")?
1476 .map(from_millis),
1477 tenant: row.try_get("tenant")?,
1478 unique_key: row.try_get("unique_key")?,
1479 error: row.try_get("error")?,
1480 run_at: row.try_get("run_at")?,
1481 started_at: row.try_get("started_at")?,
1482 created_at: row.try_get("created_at")?,
1483 updated_at: row.try_get("updated_at")?,
1484 }))
1485 }
1486
1487 pub async fn acts(&self, id: Uuid) -> Result<Vec<Act>> {
1495 let rows = sqlx::query(ACTS).bind(id).fetch_all(&self.pool).await?;
1496 rows.iter()
1497 .map(|row| {
1498 Ok(Act {
1499 id: row.try_get("id")?,
1500 job_id: row.try_get("job_id")?,
1501 job_name: row.try_get("job_name")?,
1502 kind: ActKind::parse(row.try_get::<&str, _>("act")?)?,
1503 attempts: row.try_get("attempts")?,
1504 by: row.try_get("by")?,
1505 reason: row.try_get("reason")?,
1506 at: row.try_get("at")?,
1507 })
1508 })
1509 .collect()
1510 }
1511
1512 pub async fn counts(&self) -> Result<Counts> {
1518 let row = sqlx::query(COUNTS).fetch_one(&self.pool).await?;
1519 Ok(Counts {
1520 ready: row.try_get("ready")?,
1521 waiting: row.try_get("waiting")?,
1522 running: row.try_get("running")?,
1523 completed: row.try_get("completed")?,
1524 failed: row.try_get("failed")?,
1525 cancelled: row.try_get("cancelled")?,
1526 needs_review: row.try_get("needs_review")?,
1527 oldest_ready_seconds: row.try_get::<Option<f64>, _>("oldest")?.unwrap_or(0.0),
1528 })
1529 }
1530
1531 pub async fn ping(&self) -> Result<()> {
1537 sqlx::query("SELECT 1").execute(&self.pool).await?;
1538 Ok(())
1539 }
1540
1541 pub async fn requeue_stale(&self) -> Result<u64> {
1548 sqlx::query(FAIL_STALE)
1549 .bind(self.options.stale_minutes)
1550 .bind(self.options.max_attempts)
1551 .execute(&self.pool)
1552 .await?;
1553 let result = sqlx::query(REQUEUE_STALE)
1554 .bind(self.options.stale_minutes)
1555 .bind(self.options.max_attempts)
1556 .execute(&self.pool)
1557 .await?;
1558 Ok(result.rows_affected())
1559 }
1560
1561 pub async fn purge_finished(&self) -> Result<u64> {
1568 let result = sqlx::query(PURGE)
1569 .bind(self.options.retention_days)
1570 .execute(&self.pool)
1571 .await?;
1572 Ok(result.rows_affected())
1573 }
1574
1575 pub async fn tick_schedules(&self) -> Result<usize> {
1583 let mut queued = 0;
1584 for schedule in &self.schedules {
1585 if self.tick(schedule).await? {
1586 queued += 1;
1587 }
1588 }
1589 Ok(queued)
1590 }
1591
1592 async fn tick(&self, schedule: &Schedule) -> Result<bool> {
1594 let first = match &schedule.times {
1597 Times::Every(_) => schedule.first,
1598 Times::Cron(cron, _) => {
1599 let now: DateTime<Utc> = sqlx::query_scalar("SELECT now()")
1600 .fetch_one(&self.pool)
1601 .await?;
1602 Some(next_after(cron, now)?)
1603 }
1604 };
1605 sqlx::query(SCHEDULE_CREATE)
1606 .bind(&schedule.name)
1607 .bind(first)
1608 .bind(schedule.times.interval().map(millis))
1609 .bind(schedule.times.pattern())
1610 .execute(&self.pool)
1611 .await?;
1612 let mut transaction = self.pool.begin().await?;
1613 let Some(row) = sqlx::query(SCHEDULE_LOCK)
1615 .bind(&schedule.name)
1616 .fetch_optional(&mut *transaction)
1617 .await?
1618 else {
1619 return Ok(false);
1620 };
1621 if !row.try_get::<bool, _>("due")? {
1622 transaction.commit().await?;
1623 return Ok(false);
1624 }
1625 let busy = match row.try_get::<Option<Uuid>, _>("last_job")? {
1626 Some(last) => {
1627 sqlx::query_scalar::<_, bool>(SCHEDULE_BUSY)
1628 .bind(last)
1629 .fetch_one(&mut *transaction)
1630 .await?
1631 }
1632 None => false,
1633 };
1634 let job = if busy {
1635 tracing::info!(schedule = %schedule.name, "schedule skipped, its last job has not finished");
1636 None
1637 } else {
1638 Some(enqueue_on(&mut *transaction, &schedule.job).await?)
1639 };
1640 match &schedule.times {
1641 Times::Every(interval) => {
1642 sqlx::query(SCHEDULE_ADVANCE)
1643 .bind(&schedule.name)
1644 .bind(interval.as_secs_f64())
1645 .bind(job)
1646 .execute(&mut *transaction)
1647 .await?;
1648 }
1649 Times::Cron(cron, _) => {
1650 sqlx::query(SCHEDULE_ADVANCE_TO)
1651 .bind(&schedule.name)
1652 .bind(next_after(cron, row.try_get("now")?)?)
1653 .bind(job)
1654 .execute(&mut *transaction)
1655 .await?;
1656 }
1657 }
1658 transaction.commit().await?;
1659 if job.is_some() {
1660 tracing::debug!(schedule = %schedule.name, "schedule queued its job");
1661 }
1662 Ok(job.is_some())
1663 }
1664
1665 pub async fn archive_schedules(&self) -> Result<u64> {
1672 let names: Vec<&str> = self.schedules.iter().map(|s| s.name.as_str()).collect();
1673 let result = sqlx::query(SCHEDULE_ARCHIVE)
1674 .bind(&names)
1675 .bind(self.options.stale_minutes)
1676 .execute(&self.pool)
1677 .await?;
1678 Ok(result.rows_affected())
1679 }
1680
1681 pub async fn schedules(&self) -> Result<Vec<ScheduleInfo>> {
1687 let rows = sqlx::query(SCHEDULES).fetch_all(&self.pool).await?;
1688 rows.iter()
1689 .map(|row| {
1690 Ok(ScheduleInfo {
1691 name: row.try_get("name")?,
1692 interval: row
1693 .try_get::<Option<i64>, _>("interval_ms")?
1694 .map(from_millis),
1695 cron: row.try_get("cron")?,
1696 due_at: row.try_get("due_at")?,
1697 last_job: row.try_get("last_job")?,
1698 last_state: row
1699 .try_get::<Option<&str>, _>("last_status")?
1700 .map(JobState::parse)
1701 .transpose()?,
1702 last_error: row.try_get("last_error")?,
1703 seen_at: row.try_get("seen_at")?,
1704 archived_at: row.try_get("archived_at")?,
1705 created_at: row.try_get("created_at")?,
1706 })
1707 })
1708 .collect()
1709 }
1710
1711 async fn maintain(&self) {
1714 match self.archive_schedules().await {
1715 Ok(0) => {}
1716 Ok(archived) => tracing::info!(archived, "archived schedules no longer in code"),
1717 Err(error) => tracing::error!(%error, "could not archive schedules"),
1718 }
1719 if let Err(error) = self.requeue_stale().await {
1720 tracing::error!(%error, "could not recover stale jobs");
1721 }
1722 if let Err(error) = self.purge_finished().await {
1723 tracing::error!(%error, "could not delete old jobs");
1724 }
1725 }
1726
1727 async fn supervise(&self, job: JobFuture, claim: &Claimed) -> Outcome {
1731 let mut job = AbortOnDrop(tokio::spawn(job));
1732 let every = self.options.heartbeat_interval.max(MIN_HEARTBEAT);
1733 let stale =
1735 Duration::from_secs(u64::try_from(self.options.stale_minutes).unwrap_or(0) * 60);
1736 let mut last_heard = tokio::time::Instant::now();
1737 let limit = claim
1738 .timeout
1739 .map(|timeout| tokio::time::Instant::now() + timeout);
1740 let deadline = async {
1741 match limit {
1742 Some(at) => tokio::time::sleep_until(at).await,
1743 None => std::future::pending().await,
1744 }
1745 };
1746 tokio::pin!(deadline);
1747 loop {
1748 tokio::select! {
1749 finished = &mut job.0 => {
1750 return Outcome::Done(finished.unwrap_or_else(|_| {
1751 Err(Error::Job("the job panicked".to_string()).to_string())
1752 }));
1753 }
1754 () = &mut deadline => {
1755 let limit = claim.timeout.unwrap_or_default();
1756 return Outcome::Done(Err(
1757 Error::Job(format!("timed out after {}s", limit.as_secs_f64())).to_string(),
1758 ));
1759 }
1760 () = tokio::time::sleep(every) => {
1761 let beat = sqlx::query(HEARTBEAT)
1762 .bind(claim.id)
1763 .bind(claim.attempts)
1764 .execute(&self.pool)
1765 .await;
1766 match beat {
1767 Ok(done) if done.rows_affected() == 1 => last_heard = tokio::time::Instant::now(),
1768 Ok(_) => return Outcome::Lost("another worker or recovery took its claim".to_string()),
1769 Err(error) => {
1770 tracing::warn!(id = %claim.id, %error, "job heartbeat failed");
1771 if last_heard.elapsed() >= stale {
1772 return Outcome::Lost(format!(
1773 "it could not report in for {} minutes",
1774 self.options.stale_minutes
1775 ));
1776 }
1777 }
1778 }
1779 }
1780 }
1781 }
1782 }
1783
1784 async fn mark_lost(&self, claim: &Claimed, reason: &str) {
1787 let text = Error::Job(format!("stopped: {reason}")).to_string();
1788 let every = self.options.heartbeat_interval.max(MIN_HEARTBEAT);
1789 loop {
1790 match sqlx::query(MARK_LOST)
1791 .bind(claim.id)
1792 .bind(&text)
1793 .execute(&self.pool)
1794 .await
1795 {
1796 Ok(_) => return,
1797 Err(error) => {
1798 tracing::error!(id = %claim.id, %error, "could not mark a lost job for review");
1799 tokio::time::sleep(every).await;
1800 }
1801 }
1802 }
1803 }
1804
1805 fn claimable(&self) -> (Vec<String>, HashMap<String, OwnedSemaphorePermit>) {
1808 let mut places = HashMap::new();
1809 let mut names = Vec::new();
1810 for name in self.handlers.keys() {
1811 match self.limits.get(name) {
1812 None => names.push(name.clone()),
1813 Some(limit) => {
1814 if let Ok(place) = limit.clone().try_acquire_owned() {
1815 places.insert(name.clone(), place);
1816 names.push(name.clone());
1817 }
1818 }
1819 }
1820 }
1821 (names, places)
1822 }
1823
1824 async fn claim(&self, names: &[String]) -> Result<Option<Claimed>> {
1825 let Some(row) = sqlx::query(CLAIM)
1826 .bind(names)
1827 .fetch_optional(&self.pool)
1828 .await?
1829 else {
1830 return Ok(None);
1831 };
1832 Ok(Some(Claimed {
1833 id: row.try_get("id")?,
1834 name: row.try_get("name")?,
1835 args: row.try_get("args")?,
1836 attempts: row.try_get("attempts")?,
1837 limit: row
1838 .try_get::<Option<i32>, _>("max_attempts")?
1839 .unwrap_or(self.options.max_attempts),
1840 timeout: row
1841 .try_get::<Option<i64>, _>("timeout_ms")?
1842 .map(from_millis),
1843 tenant: row.try_get("tenant")?,
1844 }))
1845 }
1846
1847 pub async fn run_one(&self) -> Result<bool> {
1854 let (names, mut places) = self.claimable();
1855 if names.is_empty() {
1856 return Ok(false);
1857 }
1858 let Some(job) = self.claim(&names).await? else {
1859 return Ok(false);
1860 };
1861 let _place = places.remove(&job.name);
1863 drop(places);
1864 let outcome = match self.handlers.get(&job.name) {
1865 Some(handler) => {
1866 let run = handler(job.tenant.clone(), job.args.clone());
1867 self.supervise(run, &job).await
1868 }
1869 None => Outcome::Done(Err(
1870 Error::Job(format!("no handler for job {}", job.name)).to_string()
1871 )),
1872 };
1873 let (id, name, attempts) = (job.id, job.name.as_str(), job.attempts);
1874 let finished = match outcome {
1875 Outcome::Lost(reason) => {
1876 tracing::error!(job = %name, %id, attempts, %reason, "job stopped, it lost its claim");
1877 self.mark_lost(&job, &reason).await;
1878 return Ok(true);
1879 }
1880 Outcome::Done(Ok(())) => {
1881 sqlx::query(FINISH)
1882 .bind(id)
1883 .bind(attempts)
1884 .bind("completed")
1885 .bind(None::<String>)
1886 .execute(&self.pool)
1887 .await?
1888 }
1889 Outcome::Done(Err(error)) if attempts < job.limit => {
1890 tracing::warn!(job = %name, %id, attempts, %error, "job failed, will retry");
1891 let wait = backoff(self.options.retry_backoff, attempts);
1892 sqlx::query(RETRY)
1893 .bind(id)
1894 .bind(attempts)
1895 .bind(cut(error))
1896 .bind(wait.as_secs_f64())
1897 .execute(&self.pool)
1898 .await?
1899 }
1900 Outcome::Done(Err(error)) => {
1901 tracing::error!(job = %name, %id, attempts, %error, "job failed");
1902 sqlx::query(FINISH)
1903 .bind(id)
1904 .bind(attempts)
1905 .bind("failed")
1906 .bind(cut(error))
1907 .execute(&self.pool)
1908 .await?
1909 }
1910 };
1911 if finished.rows_affected() == 0 {
1912 tracing::error!(job = %name, %id, "job finished after losing its claim");
1915 self.mark_lost(
1916 &job,
1917 "it finished after another worker or recovery took its claim",
1918 )
1919 .await;
1920 }
1921 Ok(true)
1922 }
1923
1924 pub async fn run(self: Arc<Self>, shutdown: watch::Receiver<bool>) {
1930 let mut loops = Vec::new();
1931 loops.push(AbortOnDrop(tokio::spawn(every_until(
1932 shutdown.clone(),
1933 self.options.maintenance_interval,
1934 {
1935 let queue = self.clone();
1936 move || {
1937 let queue = queue.clone();
1938 async move { queue.maintain().await }
1939 }
1940 },
1941 ))));
1942 if !self.schedules.is_empty() {
1943 let queue = self.clone();
1944 loops.push(AbortOnDrop(tokio::spawn(every_until(
1945 shutdown.clone(),
1946 self.options.poll_interval,
1947 move || {
1948 let queue = queue.clone();
1949 async move {
1950 if let Err(error) = queue.tick_schedules().await {
1951 tracing::error!(%error, "could not queue scheduled jobs");
1952 }
1953 }
1954 },
1955 ))));
1956 }
1957 for _ in 0..self.options.workers.max(1) {
1958 let queue = self.clone();
1959 let mut shutdown = shutdown.clone();
1960 loops.push(AbortOnDrop(tokio::spawn(async move {
1961 while !*shutdown.borrow() {
1962 let worked = queue.run_one().await.unwrap_or_else(|error| {
1963 tracing::error!(%error, "job queue error");
1964 false
1965 });
1966 if !worked {
1967 tokio::select! {
1968 () = tokio::time::sleep(queue.options.poll_interval) => {},
1969 _ = shutdown.changed() => {},
1970 }
1971 }
1972 }
1973 })));
1974 }
1975 for job_loop in &mut loops {
1976 let _ = (&mut job_loop.0).await;
1977 }
1978 }
1979
1980 #[must_use]
1982 pub fn handled(&self) -> HashSet<&str> {
1983 self.handlers.keys().map(String::as_str).collect()
1984 }
1985}
1986
1987async fn every_until<F, Fut>(mut shutdown: watch::Receiver<bool>, gap: Duration, round: F)
1989where
1990 F: Fn() -> Fut,
1991 Fut: Future<Output = ()>,
1992{
1993 while !*shutdown.borrow() {
1994 round().await;
1995 tokio::select! {
1996 () = tokio::time::sleep(gap) => {},
1997 _ = shutdown.changed() => {},
1998 }
1999 }
2000}
2001
2002struct AbortOnDrop<T>(tokio::task::JoinHandle<T>);
2005
2006impl<T> Drop for AbortOnDrop<T> {
2007 fn drop(&mut self) {
2008 self.0.abort();
2009 }
2010}
2011
2012#[cfg(test)]
2013mod tests {
2014 use super::*;
2015
2016 #[test]
2017 fn each_retry_waits_twice_as_long_up_to_a_limit() {
2018 let base = Duration::from_secs(30);
2019 assert_eq!(backoff(base, 1), base);
2020 assert_eq!(backoff(base, 2), base * 2);
2021 assert_eq!(backoff(base, 3), base * 4);
2022 assert_eq!(backoff(base, 1_000), MAX_BACKOFF);
2023 }
2024
2025 #[test]
2026 fn the_debug_text_leaves_out_arguments() {
2027 let job = NewJob::new("Report", serde_json::json!({ "nhs": "943 476 5919" }));
2028 let schedule = Schedule::every("nightly", Duration::from_hours(1), job.clone());
2029 let cron = Schedule::cron("at-two", "0 2 * * *", job.clone());
2030 for text in [
2031 format!("{job:?}"),
2032 format!("{schedule:?}"),
2033 format!("{cron:?}"),
2034 ] {
2035 assert!(text.contains("Report"), "{text}");
2036 assert!(!text.contains("943"), "{text}");
2037 }
2038 }
2039
2040 #[test]
2041 fn a_by_or_reason_that_is_not_a_code_is_refused() {
2042 assert!(check_code("ops:alice", "by").is_ok());
2043 assert!(check_code(&"é".repeat(MAX_REASON_CHARS), "reason").is_ok());
2044 for bad in [
2045 String::new(),
2046 "é".repeat(MAX_REASON_CHARS + 1),
2047 "two\nlines".to_string(),
2048 "a\ttab".to_string(),
2049 ] {
2050 let error = check_code(&bad, "reason").unwrap_err();
2051 assert!(matches!(error, Error::NotACode { what: "reason" }));
2052 assert!(!error.to_string().contains("lines"), "the text is left out");
2053 }
2054 }
2055
2056 #[test]
2057 fn a_long_error_is_cut_on_a_character_boundary() {
2058 let text = "é".repeat(MAX_ERROR);
2059 let kept = cut(text);
2060 assert!(kept.len() <= MAX_ERROR);
2061 assert!(kept.chars().all(|c| c == 'é'));
2062 assert_eq!(cut("short".to_string()), "short");
2063 }
2064
2065 #[test]
2066 #[should_panic(expected = "at least a second")]
2067 fn a_schedule_under_a_second_is_refused_at_boot() {
2068 let _ = Schedule::every(
2069 "fast",
2070 Duration::from_millis(10),
2071 NewJob::new("J", serde_json::Value::Null),
2072 );
2073 }
2074
2075 #[test]
2076 #[should_panic(expected = "bad cron pattern")]
2077 fn a_bad_cron_pattern_is_refused_at_boot() {
2078 let _ = Schedule::cron(
2079 "bad",
2080 "61 * * * *",
2081 NewJob::new("J", serde_json::Value::Null),
2082 );
2083 }
2084
2085 #[test]
2086 fn a_cron_schedule_names_its_next_times_in_utc() {
2087 let schedule = Schedule::cron(
2088 "weekdays",
2089 "0 9 * * MON-FRI",
2090 NewJob::new("J", serde_json::Value::Null),
2091 );
2092 assert_eq!(schedule.cron_pattern(), Some("0 9 * * MON-FRI"));
2093 assert_eq!(schedule.interval(), None);
2094 let Times::Cron(cron, _) = &schedule.times else {
2095 panic!("a cron schedule")
2096 };
2097 let friday = DateTime::parse_from_rfc3339("2026-11-13T09:00:00Z")
2099 .unwrap()
2100 .with_timezone(&Utc);
2101 let monday = DateTime::parse_from_rfc3339("2026-11-16T09:00:00Z")
2102 .unwrap()
2103 .with_timezone(&Utc);
2104 assert_eq!(next_after(cron, friday).unwrap(), monday);
2105 assert_eq!(
2106 Schedule::every(
2107 "e",
2108 Duration::from_secs(5),
2109 NewJob::new("J", serde_json::Value::Null)
2110 )
2111 .interval(),
2112 Some(Duration::from_secs(5))
2113 );
2114 }
2115
2116 #[test]
2117 #[should_panic(expected = "1 to 200 characters")]
2118 fn a_schedule_with_no_name_is_refused_at_boot() {
2119 let _ = Schedule::every(
2120 "",
2121 Duration::from_secs(1),
2122 NewJob::new("J", serde_json::Value::Null),
2123 );
2124 }
2125
2126 #[tokio::test]
2127 #[should_panic(expected = "added twice")]
2128 async fn a_schedule_added_twice_is_refused_at_boot() {
2129 let pool = PgPoolOptions::new()
2130 .connect_lazy("postgres://u@localhost/none")
2131 .unwrap();
2132 let mut queue = Queue::from_pool(pool, QueueOptions::default());
2133 let job = NewJob::new("J", serde_json::Value::Null);
2134 queue.schedule(Schedule::every("a", Duration::from_secs(5), job.clone()));
2135 queue.schedule(Schedule::every("a", Duration::from_secs(9), job));
2136 }
2137
2138 #[test]
2139 fn a_schedule_ignores_a_delay_on_its_job() {
2140 let job = NewJob::new("J", serde_json::Value::Null).run_in(Duration::from_hours(1));
2141 let schedule = Schedule::every("s", Duration::from_secs(5), job);
2142 assert_eq!(schedule.job.when, When::Now);
2143 }
2144}