1use std::{
170 collections::{HashMap, HashSet},
171 fmt,
172 future::Future,
173 pin::Pin,
174 sync::Arc,
175 time::Duration,
176};
177
178use sqlx::{
179 PgConnection, PgExecutor, PgPool, Postgres, Row, Transaction,
180 postgres::{PgPoolOptions, PgRow},
181};
182use tokio::sync::{Notify, OwnedSemaphorePermit, Semaphore, watch};
183use uuid::Uuid;
184
185pub use jiff::Timestamp;
188
189pub type Result<T, E = Error> = std::result::Result<T, E>;
191
192#[derive(Debug)]
194#[non_exhaustive]
195pub enum Error {
196 Database(sqlx::Error),
198 Encode(serde_json::Error),
200 Job(String),
202 NotACode {
205 what: &'static str,
207 },
208 NotATenant,
210 Schedule(String),
214 Overflow(&'static str),
216 OutOfRange(&'static str),
219}
220
221impl fmt::Display for Error {
222 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
223 match self {
224 Self::Database(error) => error.fmt(f),
225 Self::Encode(error) => error.fmt(f),
226 Self::Job(text) => write!(f, "worker error: {text}"),
227 Self::NotACode { what } => write!(
228 f,
229 "`{what}` must be 1 to {MAX_REASON_CHARS} characters with no line breaks"
230 ),
231 Self::Schedule(text) => write!(f, "schedule error: {text}"),
232 Self::Overflow(figure) => write!(f, "{figure}: the value is too large to compute"),
233 Self::OutOfRange(figure) => write!(f, "{figure}: the value is out of range"),
234 Self::NotATenant => f.write_str(
235 "a job's tenant must be 1 to 63 lower-case letters, digits, and hyphens, \
236 not starting or ending with a hyphen",
237 ),
238 }
239 }
240}
241
242impl std::error::Error for Error {
243 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
244 match self {
245 Self::Database(error) => Some(error),
246 Self::Encode(error) => Some(error),
247 Self::Job(_)
248 | Self::NotACode { .. }
249 | Self::NotATenant
250 | Self::Schedule(_)
251 | Self::Overflow(_)
252 | Self::OutOfRange(_) => None,
253 }
254 }
255}
256
257impl From<sqlx::Error> for Error {
258 fn from(error: sqlx::Error) -> Self {
259 Self::Database(error)
260 }
261}
262
263impl From<serde_json::Error> for Error {
264 fn from(error: serde_json::Error) -> Self {
265 Self::Encode(error)
266 }
267}
268
269type JobFuture = Pin<Box<dyn Future<Output = Result<(), Failure>> + Send>>;
270type Handler = Arc<dyn Fn(Option<String>, serde_json::Value) -> JobFuture + Send + Sync>;
271
272const SETUP: &str = "CREATE TABLE IF NOT EXISTS axa_queue (
273 id UUID PRIMARY KEY,
274 name TEXT NOT NULL,
275 args JSONB NOT NULL,
276 status TEXT NOT NULL DEFAULT 'queued',
277 error TEXT,
278 run_at TIMESTAMPTZ NOT NULL DEFAULT now(),
279 started_at TIMESTAMPTZ,
280 created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
281 updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
282)";
283const SETUP_INDEX: &str =
284 "CREATE INDEX IF NOT EXISTS axa_queue_ready ON axa_queue (run_at) WHERE status = 'queued'";
285const SETUP_ATTEMPTS: &str =
287 "ALTER TABLE axa_queue ADD COLUMN IF NOT EXISTS attempts INTEGER NOT NULL DEFAULT 0";
288const SETUP_MAX_ATTEMPTS: &str =
290 "ALTER TABLE axa_queue ADD COLUMN IF NOT EXISTS max_attempts INTEGER";
291const SETUP_PRIORITY: &str =
293 "ALTER TABLE axa_queue ADD COLUMN IF NOT EXISTS priority SMALLINT NOT NULL DEFAULT 0";
294const SETUP_TIMEOUT: &str = "ALTER TABLE axa_queue ADD COLUMN IF NOT EXISTS timeout_ms BIGINT";
296const SETUP_TENANT: &str = "ALTER TABLE axa_queue ADD COLUMN IF NOT EXISTS tenant TEXT
298 CONSTRAINT axa_queue_tenant_id CHECK (tenant ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$')";
299const SETUP_UNIQUE_KEY: &str = "ALTER TABLE axa_queue ADD COLUMN IF NOT EXISTS unique_key TEXT
301 CONSTRAINT axa_queue_unique_key_code
302 CHECK (length(unique_key) BETWEEN 1 AND 200 AND unique_key !~ '[[:cntrl:]]')";
303const SETUP_UNIQUE_INDEX: &str = "CREATE UNIQUE INDEX IF NOT EXISTS axa_queue_unique
305 ON axa_queue (name, (COALESCE(tenant, '')), unique_key)
306 WHERE unique_key IS NOT NULL AND status IN ('queued', 'running')";
307const SETUP_CLAIM_INDEX: &str = "CREATE INDEX IF NOT EXISTS axa_queue_claim
308 ON axa_queue (priority DESC, run_at) WHERE status = 'queued'";
309const SETUP_SCHEDULE: &str = "CREATE TABLE IF NOT EXISTS axa_schedule (
310 name TEXT PRIMARY KEY,
311 due_at TIMESTAMPTZ NOT NULL,
312 last_job UUID,
313 interval_ms BIGINT,
314 seen_at TIMESTAMPTZ NOT NULL DEFAULT now(),
315 archived_at TIMESTAMPTZ,
316 created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
317 updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
318)";
319const SETUP_SCHEDULE_CRON: &str = "ALTER TABLE axa_schedule ADD COLUMN IF NOT EXISTS cron TEXT";
325const SETUP_ACTS: &str = "CREATE TABLE IF NOT EXISTS axa_job_acts (
326 id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
327 job_id UUID NOT NULL,
328 job_name TEXT NOT NULL,
329 act TEXT NOT NULL CHECK (act IN ('cancelled', 'retried', 'released')),
330 attempts INTEGER NOT NULL,
331 by TEXT NOT NULL CHECK (length(by) BETWEEN 1 AND 200 AND by !~ '[[:cntrl:]]'),
332 reason TEXT NOT NULL CHECK (length(reason) BETWEEN 1 AND 200 AND reason !~ '[[:cntrl:]]'),
333 at TIMESTAMPTZ NOT NULL DEFAULT now()
334)";
335const SETUP_ACTS_INDEX: &str =
336 "CREATE INDEX IF NOT EXISTS axa_job_acts_job ON axa_job_acts (job_id, id)";
337const SETUP_ACTS_REFUSE: &str = "CREATE OR REPLACE FUNCTION axa_job_acts_refuse() RETURNS trigger
339LANGUAGE plpgsql AS $$
340BEGIN
341 RAISE EXCEPTION '% on % is refused: acts on jobs are only ever added to',
342 TG_OP, TG_TABLE_NAME;
343END
344$$";
345const SETUP_ACTS_ROWS: &str = "CREATE OR REPLACE TRIGGER axa_job_acts_refuse
346 BEFORE UPDATE OR DELETE ON axa_job_acts
347 FOR EACH ROW EXECUTE FUNCTION axa_job_acts_refuse()";
348const SETUP_ACTS_TRUNCATE: &str = "CREATE OR REPLACE TRIGGER axa_job_acts_refuse_truncate
349 BEFORE TRUNCATE ON axa_job_acts
350 FOR EACH STATEMENT EXECUTE FUNCTION axa_job_acts_refuse()";
351const SETUP_ACTS_ALWAYS: &str = "ALTER TABLE axa_job_acts
354 ENABLE ALWAYS TRIGGER axa_job_acts_refuse,
355 ENABLE ALWAYS TRIGGER axa_job_acts_refuse_truncate";
356pub const NOTIFY_CHANNEL: &str = "axa_queue";
358const SETUP_NOTIFY_FUNCTION: &str = "CREATE OR REPLACE FUNCTION axa_queue_notify() RETURNS trigger
360LANGUAGE plpgsql AS $$
361BEGIN
362 PERFORM pg_notify('axa_queue', '');
363 RETURN NULL;
364END
365$$";
366const SETUP_NOTIFY: &str = "CREATE OR REPLACE TRIGGER axa_queue_notify
367 AFTER INSERT ON axa_queue
368 FOR EACH STATEMENT EXECUTE FUNCTION axa_queue_notify()";
369const ACTS_TRIGGERS: [&str; 2] = ["axa_job_acts_refuse", "axa_job_acts_refuse_truncate"];
371const MISSING_TRIGGERS: &str = "SELECT want FROM unnest($1::text[]) AS want
372 WHERE NOT EXISTS (
373 SELECT 1 FROM pg_trigger t
374 WHERE t.tgrelid = to_regclass('axa_job_acts') AND t.tgname = want
375 AND t.tgenabled::text = 'A'
376 )";
377const NO_TENANT_HANDLER: &str =
379 "the job has a tenant, and its handler takes none: register it with handle_with_tenant";
380
381const SETUP_LOCK: i64 = 0x0061_7861_5F71;
383
384const ENQUEUE: &str = "INSERT INTO axa_queue
385 (id, name, args, max_attempts, priority, run_at, timeout_ms, tenant)
386 VALUES ($1, $2, $3, $4, $5, COALESCE($6, now() + make_interval(secs => $7)), $8, $9)";
387const ENQUEUE_UNIQUE: &str = "INSERT INTO axa_queue
392 (id, name, args, max_attempts, priority, run_at, timeout_ms, tenant, unique_key)
393 VALUES ($1, $2, $3, $4, $5, COALESCE($6, now() + make_interval(secs => $7)), $8, $9, $10)
394 ON CONFLICT (name, (COALESCE(tenant, '')), unique_key)
395 WHERE unique_key IS NOT NULL AND status IN ('queued', 'running')
396 DO UPDATE SET unique_key = EXCLUDED.unique_key
397 RETURNING id";
398const CLAIM: &str = "UPDATE axa_queue
399 SET status = 'running', started_at = now(), updated_at = now(), attempts = attempts + 1
400 WHERE id = (
401 SELECT id FROM axa_queue
402 WHERE status = 'queued' AND run_at <= now() AND name = ANY($1)
403 ORDER BY priority DESC, run_at
404 FOR UPDATE SKIP LOCKED
405 LIMIT 1
406 )
407 RETURNING id, name, args, attempts, max_attempts, timeout_ms, tenant";
408const HEARTBEAT: &str = "UPDATE axa_queue SET updated_at = now()
411 WHERE id = $1 AND attempts = $2 AND status = 'running'";
412const FINISH: &str = "UPDATE axa_queue SET status = $3, error = $4, updated_at = now()
413 WHERE id = $1 AND attempts = $2 AND status = 'running'";
414const RETRY: &str = "UPDATE axa_queue
415 SET status = 'queued', error = $3, started_at = NULL, updated_at = now(),
416 run_at = now() + make_interval(secs => $4)
417 WHERE id = $1 AND attempts = $2 AND status = 'running'";
418const REQUEUE_STALE: &str = "UPDATE axa_queue
419 SET status = 'queued', started_at = NULL, updated_at = now()
420 WHERE status = 'running' AND updated_at < now() - make_interval(mins => $1)
421 AND attempts < COALESCE(max_attempts, $2)";
422const FAIL_STALE: &str = "UPDATE axa_queue
423 SET status = 'failed', error = 'abandoned by its worker', updated_at = now()
424 WHERE status = 'running' AND updated_at < now() - make_interval(mins => $1)
425 AND attempts >= COALESCE(max_attempts, $2)";
426const PURGE: &str = "DELETE FROM axa_queue
427 WHERE status IN ('completed', 'failed', 'cancelled')
428 AND updated_at < now() - make_interval(days => $1)";
429const STATUS: &str = "SELECT id, name, status, attempts, max_attempts, priority, error,
430 timeout_ms, tenant, unique_key, run_at, started_at, created_at, updated_at FROM axa_queue WHERE id = $1";
431const MARK_LOST: &str =
435 "UPDATE axa_queue SET status = 'needs_review', error = $2, updated_at = now()
436 WHERE id = $1 AND status IN ('queued', 'running', 'failed')";
437const CANCEL: &str = "WITH changed AS (
440 UPDATE axa_queue SET status = 'cancelled', updated_at = now()
441 WHERE id = $1 AND status = 'queued'
442 RETURNING id, name, attempts
443 )
444 INSERT INTO axa_job_acts (job_id, job_name, act, attempts, by, reason)
445 SELECT id, name, 'cancelled', attempts, $2, $3 FROM changed";
446const RETRY_FAILED: &str = "WITH target AS (
451 SELECT id, status FROM axa_queue
452 WHERE id = $1 AND status IN ('failed', 'needs_review')
453 AND NOT EXISTS (
454 SELECT 1 FROM axa_queue other
455 WHERE other.unique_key = axa_queue.unique_key
456 AND other.name = axa_queue.name
457 AND COALESCE(other.tenant, '') = COALESCE(axa_queue.tenant, '')
458 AND other.status IN ('queued', 'running')
459 )
460 FOR UPDATE
461 ), changed AS (
462 UPDATE axa_queue q
463 SET status = 'queued', run_at = now(), started_at = NULL, updated_at = now(),
464 max_attempts = q.attempts + 1
465 FROM target WHERE q.id = target.id
466 RETURNING q.id, q.name, q.attempts, target.status AS was
467 )
468 INSERT INTO axa_job_acts (job_id, job_name, act, attempts, by, reason)
469 SELECT id, name, CASE was WHEN 'needs_review' THEN 'released' ELSE 'retried' END,
470 attempts, $2, $3
471 FROM changed";
472const ACTS: &str = "SELECT id, job_id, job_name, act, attempts, by, reason, at
473 FROM axa_job_acts WHERE job_id = $1 ORDER BY id";
474const COUNTS: &str = "SELECT
475 count(*) FILTER (WHERE status = 'queued' AND run_at <= now()) AS ready,
476 count(*) FILTER (WHERE status = 'queued' AND run_at > now()) AS waiting,
477 count(*) FILTER (WHERE status = 'running') AS running,
478 count(*) FILTER (WHERE status = 'completed') AS completed,
479 count(*) FILTER (WHERE status = 'failed') AS failed,
480 count(*) FILTER (WHERE status = 'cancelled') AS cancelled,
481 count(*) FILTER (WHERE status = 'needs_review') AS needs_review,
482 EXTRACT(EPOCH FROM now() - min(run_at) FILTER (WHERE status = 'queued' AND run_at <= now()))::float8 AS oldest
483 FROM axa_queue";
484const SCHEDULE_CREATE: &str = "INSERT INTO axa_schedule (name, due_at, interval_ms, cron)
489 VALUES ($1, COALESCE($2, now()), $3, $4)
490 ON CONFLICT (name) DO UPDATE
491 SET seen_at = now(), archived_at = NULL, interval_ms = EXCLUDED.interval_ms,
492 cron = EXCLUDED.cron,
493 due_at = CASE WHEN EXCLUDED.cron IS NOT NULL
494 AND axa_schedule.cron IS DISTINCT FROM EXCLUDED.cron
495 THEN EXCLUDED.due_at ELSE axa_schedule.due_at END
496 WHERE axa_schedule.archived_at IS NOT NULL
497 OR axa_schedule.interval_ms IS DISTINCT FROM EXCLUDED.interval_ms
498 OR axa_schedule.cron IS DISTINCT FROM EXCLUDED.cron
499 OR axa_schedule.seen_at < now() - interval '1 minute'";
500const SCHEDULE_LOCK: &str =
501 "SELECT last_job, due_at <= now() AS due, now() AS now FROM axa_schedule
502 WHERE name = $1 AND archived_at IS NULL FOR UPDATE SKIP LOCKED";
503const SCHEDULE_ARCHIVE: &str = "UPDATE axa_schedule SET archived_at = now(), updated_at = now()
507 WHERE archived_at IS NULL AND name <> ALL($1)
508 AND seen_at < now() - make_interval(mins => $2)";
509const SCHEDULES: &str = "SELECT s.name, s.interval_ms, s.cron, s.due_at, s.last_job, s.seen_at,
510 s.archived_at, s.created_at, q.status AS last_status, q.error AS last_error
511 FROM axa_schedule s LEFT JOIN axa_queue q ON q.id = s.last_job ORDER BY s.name";
512const SCHEDULE_BUSY: &str = "SELECT EXISTS (SELECT 1 FROM axa_queue
513 WHERE id = $1 AND status IN ('queued', 'running'))";
514const SCHEDULE_ADVANCE: &str = "UPDATE axa_schedule
517 SET due_at = due_at + make_interval(secs => $2)
518 * (floor(EXTRACT(EPOCH FROM now() - due_at)::float8 / $2) + 1),
519 last_job = COALESCE($3, last_job), updated_at = now()
520 WHERE name = $1";
521const SCHEDULE_ADVANCE_TO: &str = "UPDATE axa_schedule
523 SET due_at = $2, last_job = COALESCE($3, last_job), updated_at = now()
524 WHERE name = $1";
525
526pub const SETUP_STATEMENTS: [&str; 20] = [
530 SETUP,
531 SETUP_ATTEMPTS,
532 SETUP_MAX_ATTEMPTS,
533 SETUP_INDEX,
534 SETUP_PRIORITY,
535 SETUP_TIMEOUT,
536 SETUP_TENANT,
537 SETUP_UNIQUE_KEY,
538 SETUP_UNIQUE_INDEX,
539 SETUP_CLAIM_INDEX,
540 SETUP_SCHEDULE,
541 SETUP_SCHEDULE_CRON,
542 SETUP_ACTS,
543 SETUP_ACTS_INDEX,
544 SETUP_ACTS_REFUSE,
545 SETUP_ACTS_ROWS,
546 SETUP_ACTS_TRUNCATE,
547 SETUP_ACTS_ALWAYS,
548 SETUP_NOTIFY_FUNCTION,
549 SETUP_NOTIFY,
550];
551
552pub const MAX_REASON_CHARS: usize = 200;
554
555const MIN_HEARTBEAT: Duration = Duration::from_millis(20);
557
558const MAX_BACKOFF: Duration = Duration::from_hours(1);
560
561const MAX_ERROR: usize = 1024;
563
564const MAX_DOUBLING_FACTOR: u32 = 1 << 16;
566
567#[must_use]
569pub fn backoff(base: Duration, attempts: i32) -> Option<Duration> {
570 let doublings = u32::try_from(attempts.checked_sub(1)?).ok()?.min(16);
572 let factor = 1_u32.checked_shl(doublings).unwrap_or(MAX_DOUBLING_FACTOR);
573 Some(
575 base.checked_mul(factor)
576 .unwrap_or(MAX_BACKOFF)
577 .min(MAX_BACKOFF),
578 )
579}
580
581pub const MIN_RETRY_AFTER: Duration = Duration::from_secs(1);
583
584#[derive(Debug, Clone)]
589pub struct RetryAfter {
590 delay: Duration,
591 reason: String,
592}
593
594impl RetryAfter {
595 pub fn new(delay: Duration, reason: impl Into<String>) -> Result<Self> {
602 if !(MIN_RETRY_AFTER..=MAX_BACKOFF).contains(&delay) {
603 return Err(Error::OutOfRange("retry after"));
604 }
605 Ok(Self {
606 delay,
607 reason: reason.into(),
608 })
609 }
610
611 #[must_use]
613 pub const fn delay(&self) -> Duration {
614 self.delay
615 }
616}
617
618impl fmt::Display for RetryAfter {
619 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
620 f.write_str(&self.reason)
621 }
622}
623
624impl std::error::Error for RetryAfter {}
625
626struct Failure {
628 text: String,
629 retry_in: Option<Duration>,
630}
631
632impl Failure {
633 fn from_error<E: fmt::Display + 'static>(error: E) -> Self {
634 let any: &dyn std::any::Any = &error;
635 let retry_in = any
637 .downcast_ref::<RetryAfter>()
638 .or_else(|| {
639 any.downcast_ref::<Box<dyn std::error::Error + Send + Sync>>()
640 .and_then(|boxed| boxed.downcast_ref::<RetryAfter>())
641 })
642 .map(RetryAfter::delay);
643 Self {
644 text: error.to_string(),
645 retry_in,
646 }
647 }
648}
649
650impl From<String> for Failure {
651 fn from(text: String) -> Self {
652 Self {
653 text,
654 retry_in: None,
655 }
656 }
657}
658
659impl fmt::Display for Failure {
660 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
661 f.write_str(&self.text)
662 }
663}
664
665#[must_use]
668pub fn jittered(wait: Duration) -> Option<Duration> {
669 let random = u32::try_from(Uuid::new_v4().as_u128() % 1_000_000).ok()?;
671 wait.checked_mul(1_000_000_u32.checked_add(random)?)?
672 .checked_div(2_000_000)
673}
674
675#[must_use]
679pub fn retry_wait(base: Duration, attempts: i32, chosen: Option<Duration>) -> Option<Duration> {
680 match chosen {
681 Some(delay) => (MIN_RETRY_AFTER..=MAX_BACKOFF)
684 .contains(&delay)
685 .then_some(delay),
686 None => backoff(base, attempts).and_then(jittered),
687 }
688}
689
690fn cut(mut text: String) -> String {
692 if text.len() > MAX_ERROR {
693 let end = text.floor_char_boundary(MAX_ERROR);
694 text.truncate(end);
695 }
696 text
697}
698
699const TIMING: &str = "a time for the run is too large to compute";
701
702fn give_up_after(stale_minutes: i32, every: Duration) -> Option<Duration> {
706 let stale = Duration::from_secs(u64::try_from(stale_minutes).ok()?.checked_mul(60)?);
707 stale.checked_sub(every.checked_mul(2)?)
708}
709
710fn millis(duration: Duration) -> i64 {
711 i64::try_from(duration.as_millis()).unwrap_or(i64::MAX)
712}
713
714fn from_millis(millis: i64) -> Duration {
715 Duration::from_millis(u64::try_from(millis).unwrap_or(0))
716}
717
718#[derive(Debug, Clone, Copy, PartialEq, Eq)]
720enum When {
721 Now,
722 At(Timestamp),
723 In(Duration),
724}
725
726#[derive(Clone)]
728pub struct NewJob {
729 name: String,
730 args: serde_json::Value,
731 max_attempts: Option<i32>,
732 priority: i16,
733 when: When,
734 timeout: Option<Duration>,
735 tenant: Option<String>,
736 unique_key: Option<String>,
737}
738
739impl fmt::Debug for NewJob {
740 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
741 f.debug_struct("NewJob")
742 .field("name", &self.name)
743 .field("max_attempts", &self.max_attempts)
744 .field("priority", &self.priority)
745 .field("when", &self.when)
746 .field("timeout", &self.timeout)
747 .field("tenant", &self.tenant)
748 .field("unique_key", &self.unique_key)
749 .finish_non_exhaustive()
750 }
751}
752
753impl NewJob {
754 pub fn new(name: impl Into<String>, args: serde_json::Value) -> Self {
757 Self {
758 name: name.into(),
759 args,
760 max_attempts: None,
761 priority: 0,
762 when: When::Now,
763 timeout: None,
764 tenant: None,
765 unique_key: None,
766 }
767 }
768
769 #[must_use]
776 pub fn unique(mut self, key: impl Into<String>) -> Self {
777 self.unique_key = Some(key.into());
778 self
779 }
780
781 #[must_use]
787 pub fn tenant(mut self, tenant: impl Into<String>) -> Self {
788 self.tenant = Some(tenant.into());
789 self
790 }
791
792 #[must_use]
795 pub const fn timeout(mut self, limit: Duration) -> Self {
796 self.timeout = Some(limit);
797 self
798 }
799
800 #[must_use]
802 pub const fn max_attempts(mut self, max_attempts: Option<i32>) -> Self {
803 self.max_attempts = max_attempts;
804 self
805 }
806
807 #[must_use]
810 pub const fn priority(mut self, priority: i16) -> Self {
811 self.priority = priority;
812 self
813 }
814
815 #[must_use]
817 pub const fn run_in(mut self, delay: Duration) -> Self {
818 self.when = When::In(delay);
819 self
820 }
821
822 #[must_use]
824 pub const fn run_at(mut self, at: Timestamp) -> Self {
825 self.when = When::At(at);
826 self
827 }
828
829 #[must_use]
831 pub fn name(&self) -> &str {
832 &self.name
833 }
834
835 #[must_use]
837 pub fn tenant_id(&self) -> Option<&str> {
838 self.tenant.as_deref()
839 }
840
841 #[must_use]
843 pub fn unique_key(&self) -> Option<&str> {
844 self.unique_key.as_deref()
845 }
846}
847
848pub const MAX_TENANT_ID_LEN: usize = 63;
850
851#[must_use]
855pub fn is_tenant_id(id: &str) -> bool {
856 (1..=MAX_TENANT_ID_LEN).contains(&id.len())
857 && !id.starts_with('-')
858 && !id.ends_with('-')
859 && id
860 .bytes()
861 .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'-')
862}
863
864pub async fn enqueue_on<'e, E: PgExecutor<'e>>(executor: E, job: &NewJob) -> Result<Uuid> {
875 if job
876 .tenant
877 .as_deref()
878 .is_some_and(|tenant| !is_tenant_id(tenant))
879 {
880 return Err(Error::NotATenant);
881 }
882 if let Some(key) = job.unique_key.as_deref() {
883 check_code(key, "unique key")?;
884 }
885 let id = Uuid::new_v4();
886 let (at, delay) = match job.when {
887 When::Now => (None, 0.0_f64),
888 When::At(at) => (Some(at), 0.0_f64),
889 When::In(delay) => (None, delay.as_secs_f64()),
890 };
891 let query = sqlx::query(if job.unique_key.is_some() {
892 ENQUEUE_UNIQUE
893 } else {
894 ENQUEUE
895 })
896 .bind(id)
897 .bind(&job.name)
898 .bind(&job.args)
899 .bind(job.max_attempts)
900 .bind(job.priority)
901 .bind(at.map(jiff_sqlx::Timestamp::from))
902 .bind(delay)
903 .bind(job.timeout.map(millis))
904 .bind(job.tenant.as_deref());
905 if let Some(key) = job.unique_key.as_deref() {
906 Ok(query.bind(key).fetch_one(executor).await?.try_get("id")?)
907 } else {
908 query.execute(executor).await?;
909 Ok(id)
910 }
911}
912
913pub async fn enqueue_all_on(connection: &mut PgConnection, jobs: &[NewJob]) -> Result<Vec<Uuid>> {
920 let mut ids = Vec::with_capacity(jobs.len());
921 for job in jobs {
922 ids.push(enqueue_on(&mut *connection, job).await?);
923 }
924 Ok(ids)
925}
926
927fn check_code(text: &str, what: &'static str) -> Result<()> {
929 if text.is_empty()
930 || text.chars().count() > MAX_REASON_CHARS
931 || text.chars().any(char::is_control)
932 {
933 Err(Error::NotACode { what })
934 } else {
935 Ok(())
936 }
937}
938
939pub async fn cancel(
953 transaction: &mut Transaction<'_, Postgres>,
954 id: Uuid,
955 by: &str,
956 reason: &str,
957) -> Result<bool> {
958 act(transaction, CANCEL, id, by, reason).await
959}
960
961pub async fn retry(
974 transaction: &mut Transaction<'_, Postgres>,
975 id: Uuid,
976 by: &str,
977 reason: &str,
978) -> Result<bool> {
979 act(transaction, RETRY_FAILED, id, by, reason).await
980}
981
982async fn act(
984 transaction: &mut Transaction<'_, Postgres>,
985 statement: &'static str,
986 id: Uuid,
987 by: &str,
988 reason: &str,
989) -> Result<bool> {
990 check_code(by, "by")?;
991 check_code(reason, "reason")?;
992 let kept = sqlx::query(statement)
993 .bind(id)
994 .bind(by)
995 .bind(reason)
996 .execute(&mut **transaction)
997 .await?
998 .rows_affected();
999 Ok(kept == 1)
1000}
1001
1002#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1004#[non_exhaustive]
1005pub enum ActKind {
1006 Cancelled,
1008 Retried,
1010 Released,
1012}
1013
1014impl ActKind {
1015 fn parse(text: &str) -> Result<Self> {
1016 match text {
1017 "cancelled" => Ok(Self::Cancelled),
1018 "retried" => Ok(Self::Retried),
1019 "released" => Ok(Self::Released),
1020 _ => Err(Error::Job("an act with an unknown kind".to_string())),
1021 }
1022 }
1023}
1024
1025#[derive(Debug, Clone)]
1028#[non_exhaustive]
1029pub struct Act {
1030 pub id: i64,
1032 pub job_id: Uuid,
1034 pub job_name: String,
1036 pub kind: ActKind,
1038 pub attempts: i32,
1040 pub by: String,
1042 pub reason: String,
1044 pub at: Timestamp,
1046}
1047
1048#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1050pub enum JobState {
1051 Queued,
1053 Running,
1055 Completed,
1057 Failed,
1059 Cancelled,
1061 NeedsReview,
1065}
1066
1067impl JobState {
1068 fn parse(text: &str) -> Result<Self> {
1069 match text {
1070 "queued" => Ok(Self::Queued),
1071 "running" => Ok(Self::Running),
1072 "completed" => Ok(Self::Completed),
1073 "failed" => Ok(Self::Failed),
1074 "cancelled" => Ok(Self::Cancelled),
1075 "needs_review" => Ok(Self::NeedsReview),
1076 _ => Err(Error::Job("a job row with an unknown status".to_string())),
1077 }
1078 }
1079}
1080
1081#[derive(Debug, Clone)]
1083#[non_exhaustive]
1084pub struct JobInfo {
1085 pub id: Uuid,
1087 pub name: String,
1089 pub state: JobState,
1091 pub attempts: i32,
1093 pub max_attempts: Option<i32>,
1095 pub priority: i16,
1097 pub timeout: Option<Duration>,
1099 pub tenant: Option<String>,
1101 pub unique_key: Option<String>,
1103 pub error: Option<String>,
1106 pub run_at: Timestamp,
1108 pub started_at: Option<Timestamp>,
1110 pub created_at: Timestamp,
1112 pub updated_at: Timestamp,
1114}
1115
1116#[derive(Debug, Clone, Copy, Default, PartialEq)]
1118#[non_exhaustive]
1119pub struct Counts {
1120 pub ready: i64,
1122 pub waiting: i64,
1124 pub running: i64,
1126 pub completed: i64,
1128 pub failed: i64,
1130 pub cancelled: i64,
1132 pub needs_review: i64,
1135 pub oldest_ready_seconds: f64,
1138}
1139
1140#[derive(Clone)]
1143pub struct Schedule {
1144 name: String,
1145 times: Times,
1146 first: Option<Timestamp>,
1147 job: NewJob,
1148}
1149
1150#[derive(Clone)]
1152enum Times {
1153 Every(Duration),
1154 Cron(Box<croner::Cron>, String),
1156}
1157
1158impl Times {
1159 fn interval(&self) -> Option<Duration> {
1160 match self {
1161 Self::Every(interval) => Some(*interval),
1162 Self::Cron(..) => None,
1163 }
1164 }
1165
1166 fn pattern(&self) -> Option<&str> {
1167 match self {
1168 Self::Every(_) => None,
1169 Self::Cron(_, pattern) => Some(pattern),
1170 }
1171 }
1172}
1173
1174fn next_after(cron: &croner::Cron, now: Timestamp) -> Result<Timestamp> {
1176 cron.find_next_occurrence(&InUtc(now), false)
1177 .map(|next| next.0)
1178 .map_err(|error| Error::Job(format!("the cron pattern has no next time: {error}")))
1179}
1180
1181#[derive(Clone, Copy)]
1185struct InUtc(Timestamp);
1186
1187impl croner::CronDateTime for InUtc {
1188 fn to_civil(&self) -> croner::CivilDateTime {
1189 let time = jiff::tz::TimeZone::UTC.to_datetime(self.0);
1190 croner::CivilDateTime::new(
1191 croner::CivilDate::from_parts_unchecked(
1192 i32::from(time.year()),
1193 time.month().unsigned_abs().into(),
1194 time.day().unsigned_abs().into(),
1195 ),
1196 croner::CivilTime::from_parts_unchecked(
1197 time.hour().unsigned_abs().into(),
1198 time.minute().unsigned_abs().into(),
1199 time.second().unsigned_abs().into(),
1200 ),
1201 )
1202 }
1203
1204 fn civil_weekday(&self) -> croner::Weekday {
1205 let day = jiff::tz::TimeZone::UTC
1206 .to_datetime(self.0)
1207 .weekday()
1208 .to_sunday_zero_offset();
1209 croner::Weekday::from_days_from_sunday(day.unsigned_abs().into())
1210 }
1211
1212 fn resolve_civil(
1213 &self,
1214 civil: croner::CivilDateTime,
1215 ) -> Result<croner::Resolution<Self>, croner::errors::CronError> {
1216 let part =
1217 |value: u32| i8::try_from(value).map_err(|_| croner::errors::CronError::InvalidDate);
1218 let year =
1219 i16::try_from(civil.year()).map_err(|_| croner::errors::CronError::InvalidDate)?;
1220 let time = jiff::civil::DateTime::new(
1221 year,
1222 part(civil.month())?,
1223 part(civil.day())?,
1224 part(civil.hour())?,
1225 part(civil.minute())?,
1226 part(civil.second())?,
1227 0,
1228 )
1229 .and_then(|time| jiff::tz::TimeZone::UTC.to_timestamp(time))
1230 .map_err(|_| croner::errors::CronError::InvalidDate)?;
1231 Ok(croner::Resolution::Single(Self(time)))
1232 }
1233
1234 fn checked_add_seconds(&self, seconds: i64) -> Option<Self> {
1235 self.0
1236 .checked_add(jiff::SignedDuration::from_secs(seconds))
1237 .ok()
1238 .map(Self)
1239 }
1240
1241 fn cmp_instant(&self, other: &Self) -> std::cmp::Ordering {
1242 self.0.cmp(&other.0)
1243 }
1244}
1245
1246fn time(row: &PgRow, column: &str) -> Result<Timestamp> {
1248 Ok(row.try_get::<jiff_sqlx::Timestamp, _>(column)?.to_jiff())
1249}
1250
1251fn time_or_none(row: &PgRow, column: &str) -> Result<Option<Timestamp>> {
1253 Ok(row
1254 .try_get::<Option<jiff_sqlx::Timestamp>, _>(column)?
1255 .map(jiff_sqlx::Timestamp::to_jiff))
1256}
1257
1258impl fmt::Debug for Schedule {
1259 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1260 f.debug_struct("Schedule")
1261 .field("name", &self.name)
1262 .field("interval", &self.times.interval())
1263 .field("cron", &self.times.pattern())
1264 .field("first", &self.first)
1265 .field("job", &self.job)
1266 .finish()
1267 }
1268}
1269
1270impl Schedule {
1271 pub fn every(name: impl Into<String>, interval: Duration, job: NewJob) -> Result<Self> {
1279 let name = checked_name(name.into())?;
1280 if interval < Duration::from_secs(1) {
1281 return Err(Error::Schedule(format!(
1282 "the schedule {name} needs an interval of at least a second"
1283 )));
1284 }
1285 Ok(Self {
1286 name,
1287 times: Times::Every(interval),
1288 first: None,
1289 job: NewJob {
1290 when: When::Now,
1291 ..job
1292 },
1293 })
1294 }
1295
1296 pub fn cron(name: impl Into<String>, pattern: &str, job: NewJob) -> Result<Self> {
1308 let name = checked_name(name.into())?;
1309 let cron: croner::Cron = pattern.parse().map_err(|error| {
1310 Error::Schedule(format!(
1311 "the schedule {name} has a bad cron pattern: {error}"
1312 ))
1313 })?;
1314 if next_after(&cron, Timestamp::now()).is_err() {
1315 return Err(Error::Schedule(format!(
1316 "the cron pattern of the schedule {name} names no time to come"
1317 )));
1318 }
1319 Ok(Self {
1320 name,
1321 times: Times::Cron(Box::new(cron), pattern.to_string()),
1322 first: None,
1323 job: NewJob {
1324 when: When::Now,
1325 ..job
1326 },
1327 })
1328 }
1329
1330 #[must_use]
1335 pub const fn first_at(mut self, first: Timestamp) -> Self {
1336 self.first = Some(first);
1337 self
1338 }
1339
1340 #[must_use]
1342 pub fn interval(&self) -> Option<Duration> {
1343 self.times.interval()
1344 }
1345
1346 #[must_use]
1348 pub fn cron_pattern(&self) -> Option<&str> {
1349 self.times.pattern()
1350 }
1351
1352 #[must_use]
1354 pub fn name(&self) -> &str {
1355 &self.name
1356 }
1357}
1358
1359fn checked_name(name: String) -> Result<String> {
1361 if name.is_empty() || name.len() > 200 {
1362 return Err(Error::Schedule(
1363 "a schedule name must be 1 to 200 characters".to_string(),
1364 ));
1365 }
1366 Ok(name)
1367}
1368
1369#[derive(Debug, Clone)]
1371#[non_exhaustive]
1372pub struct ScheduleInfo {
1373 pub name: String,
1375 pub interval: Option<Duration>,
1377 pub cron: Option<String>,
1379 pub due_at: Timestamp,
1381 pub last_job: Option<Uuid>,
1383 pub last_state: Option<JobState>,
1385 pub last_error: Option<String>,
1387 pub seen_at: Timestamp,
1389 pub archived_at: Option<Timestamp>,
1392 pub created_at: Timestamp,
1394}
1395
1396#[derive(Debug, Clone)]
1398pub struct QueueOptions {
1399 pub workers: usize,
1401 pub poll_interval: Duration,
1403 pub stale_minutes: i32,
1406 pub heartbeat_interval: Duration,
1409 pub max_attempts: i32,
1412 pub retry_backoff: Duration,
1414 pub retention_days: i32,
1416 pub maintenance_interval: Duration,
1418}
1419
1420impl QueueOptions {
1421 pub fn check(&self) -> Result<()> {
1431 if u32::try_from(self.workers).is_err() {
1432 return Err(Error::OutOfRange("workers"));
1433 }
1434 let stale = u64::try_from(self.stale_minutes)
1435 .ok()
1436 .filter(|minutes| *minutes >= 1)
1437 .and_then(|minutes| minutes.checked_mul(60))
1438 .map(Duration::from_secs)
1439 .ok_or(Error::OutOfRange("stale_minutes"))?;
1440 let fits = self.heartbeat_interval >= MIN_HEARTBEAT
1441 && self
1442 .heartbeat_interval
1443 .checked_mul(4)
1444 .is_some_and(|four| four <= stale);
1445 if !fits {
1446 return Err(Error::OutOfRange("heartbeat_interval"));
1447 }
1448 Ok(())
1449 }
1450}
1451
1452impl Default for QueueOptions {
1453 fn default() -> Self {
1454 Self {
1455 workers: 2,
1456 poll_interval: Duration::from_secs(1),
1457 stale_minutes: 60,
1458 heartbeat_interval: Duration::from_mins(1),
1459 max_attempts: 1,
1460 retry_backoff: Duration::from_secs(30),
1461 retention_days: 7,
1462 maintenance_interval: Duration::from_mins(5),
1463 }
1464 }
1465}
1466
1467pub struct Queue {
1469 pool: PgPool,
1470 handlers: HashMap<String, Handler>,
1471 limits: HashMap<String, Arc<Semaphore>>,
1472 schedules: Vec<Schedule>,
1473 options: QueueOptions,
1474}
1475
1476impl fmt::Debug for Queue {
1477 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1478 f.debug_struct("Queue")
1479 .field("handlers", &self.handlers.len())
1480 .field("limits", &self.limits.len())
1481 .field("schedules", &self.schedules.len())
1482 .field("options", &self.options)
1483 .finish_non_exhaustive()
1484 }
1485}
1486
1487struct Claimed {
1489 id: Uuid,
1490 name: String,
1491 args: serde_json::Value,
1492 attempts: i32,
1493 limit: i32,
1494 timeout: Option<Duration>,
1495 tenant: Option<String>,
1496}
1497
1498enum Outcome {
1500 Done(Result<(), Failure>),
1502 Lost(String),
1504}
1505
1506impl Queue {
1507 pub fn from_pool(pool: PgPool, options: QueueOptions) -> Result<Self> {
1514 options.check()?;
1515 Ok(Self {
1516 pool,
1517 handlers: HashMap::new(),
1518 limits: HashMap::new(),
1519 schedules: Vec::new(),
1520 options,
1521 })
1522 }
1523
1524 async fn open(uri: &str, options: QueueOptions) -> Result<Self> {
1526 options.check()?;
1527 let loops = u32::try_from(options.workers).map_err(|_| Error::OutOfRange("workers"))?;
1528 let pool = PgPoolOptions::new()
1529 .max_connections(loops.checked_add(3).ok_or(Error::Overflow("connections"))?)
1531 .connect(uri)
1532 .await?;
1533 Self::from_pool(pool, options)
1534 }
1535
1536 pub async fn connect_existing(uri: &str, options: QueueOptions) -> Result<Self> {
1546 let queue = Self::open(uri, options).await?;
1547 queue.check().await?;
1548 Ok(queue)
1549 }
1550
1551 pub async fn connect(uri: &str, options: QueueOptions) -> Result<Self> {
1558 let queue = Self::open(uri, options).await?;
1559 let mut setup = queue.pool.begin().await?;
1564 sqlx::query("SELECT pg_advisory_xact_lock($1)")
1565 .bind(SETUP_LOCK)
1566 .execute(&mut *setup)
1567 .await?;
1568 for statement in SETUP_STATEMENTS {
1569 sqlx::query(statement).execute(&mut *setup).await?;
1570 }
1571 setup.commit().await?;
1572 Ok(queue)
1573 }
1574
1575 pub async fn check(&self) -> Result<()> {
1583 sqlx::query(
1584 "SELECT attempts, max_attempts, priority, timeout_ms, tenant, unique_key FROM axa_queue LIMIT 0",
1585 )
1586 .execute(&self.pool)
1587 .await?;
1588 sqlx::query(
1589 "SELECT name, due_at, last_job, interval_ms, cron, seen_at, archived_at FROM axa_schedule LIMIT 0",
1590 )
1591 .execute(&self.pool)
1592 .await?;
1593 sqlx::query(
1594 "SELECT id, job_id, job_name, act, attempts, by, reason, at FROM axa_job_acts LIMIT 0",
1595 )
1596 .execute(&self.pool)
1597 .await?;
1598 let mut missing: Vec<String> = sqlx::query_scalar(MISSING_TRIGGERS)
1599 .bind(ACTS_TRIGGERS.to_vec())
1600 .fetch_all(&self.pool)
1601 .await?;
1602 let unique_index: bool =
1603 sqlx::query_scalar("SELECT to_regclass('axa_queue_unique') IS NOT NULL")
1604 .fetch_one(&self.pool)
1605 .await?;
1606 if !unique_index {
1607 missing.push("axa_queue_unique".to_string());
1608 }
1609 if missing.is_empty() {
1610 Ok(())
1611 } else {
1612 Err(Error::Database(sqlx::Error::Configuration(
1613 format!(
1614 "the job queue is missing, or has turned off, {}: run SETUP_STATEMENTS",
1615 missing.join(", ")
1616 )
1617 .into(),
1618 )))
1619 }
1620 }
1621
1622 #[must_use]
1625 pub const fn pool(&self) -> &PgPool {
1626 &self.pool
1627 }
1628
1629 #[must_use]
1631 pub const fn options(&self) -> &QueueOptions {
1632 &self.options
1633 }
1634
1635 pub fn handle<F, Fut, E>(&mut self, name: impl Into<String>, handler: F)
1642 where
1643 F: Fn(serde_json::Value) -> Fut + Send + Sync + 'static,
1644 Fut: Future<Output = std::result::Result<(), E>> + Send + 'static,
1645 E: fmt::Display + 'static,
1646 {
1647 let handler = Arc::new(handler);
1648 let run: Handler = Arc::new(move |tenant, args| {
1649 if tenant.is_some() {
1650 return Box::pin(std::future::ready(Err(NO_TENANT_HANDLER
1651 .to_string()
1652 .into())));
1653 }
1654 let job = handler(args);
1655 Box::pin(async move { job.await.map_err(Failure::from_error) })
1656 });
1657 self.handlers.insert(name.into(), run);
1658 }
1659
1660 pub fn handle_with_tenant<F, Fut, E>(&mut self, name: impl Into<String>, handler: F)
1665 where
1666 F: Fn(Option<String>, serde_json::Value) -> Fut + Send + Sync + 'static,
1667 Fut: Future<Output = std::result::Result<(), E>> + Send + 'static,
1668 E: fmt::Display + 'static,
1669 {
1670 let handler = Arc::new(handler);
1671 let run: Handler = Arc::new(move |tenant, args| {
1672 let job = handler(tenant, args);
1673 Box::pin(async move { job.await.map_err(Failure::from_error) })
1674 });
1675 self.handlers.insert(name.into(), run);
1676 }
1677
1678 pub fn limit(&mut self, name: impl Into<String>, jobs: usize) {
1681 self.limits
1682 .insert(name.into(), Arc::new(Semaphore::new(jobs.max(1))));
1683 }
1684
1685 pub fn schedule(&mut self, schedule: Schedule) -> Result<()> {
1691 if self.schedules.iter().any(|s| s.name == schedule.name) {
1692 return Err(Error::Schedule(format!(
1693 "the schedule {} was added twice",
1694 schedule.name
1695 )));
1696 }
1697 self.schedules.push(schedule);
1698 Ok(())
1699 }
1700
1701 pub async fn enqueue(&self, name: &str, args: serde_json::Value) -> Result<Uuid> {
1707 enqueue_on(&self.pool, &NewJob::new(name, args)).await
1708 }
1709
1710 pub async fn enqueue_limited(
1716 &self,
1717 name: &str,
1718 args: serde_json::Value,
1719 max_attempts: Option<i32>,
1720 ) -> Result<Uuid> {
1721 enqueue_on(
1722 &self.pool,
1723 &NewJob::new(name, args).max_attempts(max_attempts),
1724 )
1725 .await
1726 }
1727
1728 pub async fn enqueue_job(&self, job: &NewJob) -> Result<Uuid> {
1734 enqueue_on(&self.pool, job).await
1735 }
1736
1737 pub async fn enqueue_all(&self, jobs: &[NewJob]) -> Result<Vec<Uuid>> {
1743 let mut transaction = self.pool.begin().await?;
1744 let ids = enqueue_all_on(&mut transaction, jobs).await?;
1745 transaction.commit().await?;
1746 Ok(ids)
1747 }
1748
1749 pub async fn job(&self, id: Uuid) -> Result<Option<JobInfo>> {
1756 let Some(row) = sqlx::query(STATUS)
1757 .bind(id)
1758 .fetch_optional(&self.pool)
1759 .await?
1760 else {
1761 return Ok(None);
1762 };
1763 Ok(Some(JobInfo {
1764 id: row.try_get("id")?,
1765 name: row.try_get("name")?,
1766 state: JobState::parse(row.try_get::<&str, _>("status")?)?,
1767 attempts: row.try_get("attempts")?,
1768 max_attempts: row.try_get("max_attempts")?,
1769 priority: row.try_get("priority")?,
1770 timeout: row
1771 .try_get::<Option<i64>, _>("timeout_ms")?
1772 .map(from_millis),
1773 tenant: row.try_get("tenant")?,
1774 unique_key: row.try_get("unique_key")?,
1775 error: row.try_get("error")?,
1776 run_at: time(&row, "run_at")?,
1777 started_at: time_or_none(&row, "started_at")?,
1778 created_at: time(&row, "created_at")?,
1779 updated_at: time(&row, "updated_at")?,
1780 }))
1781 }
1782
1783 pub async fn acts(&self, id: Uuid) -> Result<Vec<Act>> {
1791 let rows = sqlx::query(ACTS).bind(id).fetch_all(&self.pool).await?;
1792 rows.iter()
1793 .map(|row| {
1794 Ok(Act {
1795 id: row.try_get("id")?,
1796 job_id: row.try_get("job_id")?,
1797 job_name: row.try_get("job_name")?,
1798 kind: ActKind::parse(row.try_get::<&str, _>("act")?)?,
1799 attempts: row.try_get("attempts")?,
1800 by: row.try_get("by")?,
1801 reason: row.try_get("reason")?,
1802 at: time(row, "at")?,
1803 })
1804 })
1805 .collect()
1806 }
1807
1808 pub async fn counts(&self) -> Result<Counts> {
1814 let row = sqlx::query(COUNTS).fetch_one(&self.pool).await?;
1815 Ok(Counts {
1816 ready: row.try_get("ready")?,
1817 waiting: row.try_get("waiting")?,
1818 running: row.try_get("running")?,
1819 completed: row.try_get("completed")?,
1820 failed: row.try_get("failed")?,
1821 cancelled: row.try_get("cancelled")?,
1822 needs_review: row.try_get("needs_review")?,
1823 oldest_ready_seconds: row.try_get::<Option<f64>, _>("oldest")?.unwrap_or(0.0_f64),
1824 })
1825 }
1826
1827 pub async fn ping(&self) -> Result<()> {
1833 sqlx::query("SELECT 1").execute(&self.pool).await?;
1834 Ok(())
1835 }
1836
1837 pub async fn requeue_stale(&self) -> Result<u64> {
1844 sqlx::query(FAIL_STALE)
1845 .bind(self.options.stale_minutes)
1846 .bind(self.options.max_attempts)
1847 .execute(&self.pool)
1848 .await?;
1849 let result = sqlx::query(REQUEUE_STALE)
1850 .bind(self.options.stale_minutes)
1851 .bind(self.options.max_attempts)
1852 .execute(&self.pool)
1853 .await?;
1854 Ok(result.rows_affected())
1855 }
1856
1857 pub async fn purge_finished(&self) -> Result<u64> {
1864 let result = sqlx::query(PURGE)
1865 .bind(self.options.retention_days)
1866 .execute(&self.pool)
1867 .await?;
1868 Ok(result.rows_affected())
1869 }
1870
1871 pub async fn tick_schedules(&self) -> Result<usize> {
1879 let mut queued: usize = 0;
1880 for schedule in &self.schedules {
1881 if self.tick(schedule).await? {
1882 queued = queued
1883 .checked_add(1)
1884 .ok_or(Error::Overflow("schedules queued"))?;
1885 }
1886 }
1887 Ok(queued)
1888 }
1889
1890 async fn tick(&self, schedule: &Schedule) -> Result<bool> {
1892 let first = match &schedule.times {
1895 Times::Every(_) => schedule.first,
1896 Times::Cron(cron, _) => {
1897 let now: jiff_sqlx::Timestamp = sqlx::query_scalar("SELECT now()")
1898 .fetch_one(&self.pool)
1899 .await?;
1900 Some(next_after(cron, now.to_jiff())?)
1901 }
1902 };
1903 sqlx::query(SCHEDULE_CREATE)
1904 .bind(&schedule.name)
1905 .bind(first.map(jiff_sqlx::Timestamp::from))
1906 .bind(schedule.times.interval().map(millis))
1907 .bind(schedule.times.pattern())
1908 .execute(&self.pool)
1909 .await?;
1910 let mut transaction = self.pool.begin().await?;
1911 let Some(row) = sqlx::query(SCHEDULE_LOCK)
1913 .bind(&schedule.name)
1914 .fetch_optional(&mut *transaction)
1915 .await?
1916 else {
1917 return Ok(false);
1918 };
1919 if !row.try_get::<bool, _>("due")? {
1920 transaction.commit().await?;
1921 return Ok(false);
1922 }
1923 let busy = match row.try_get::<Option<Uuid>, _>("last_job")? {
1924 Some(last) => {
1925 sqlx::query_scalar::<_, bool>(SCHEDULE_BUSY)
1926 .bind(last)
1927 .fetch_one(&mut *transaction)
1928 .await?
1929 }
1930 None => false,
1931 };
1932 let job = if busy {
1933 tracing::info!(schedule = %schedule.name, "schedule skipped, its last job has not finished");
1934 None
1935 } else {
1936 Some(enqueue_on(&mut *transaction, &schedule.job).await?)
1937 };
1938 match &schedule.times {
1939 Times::Every(interval) => {
1940 sqlx::query(SCHEDULE_ADVANCE)
1941 .bind(&schedule.name)
1942 .bind(interval.as_secs_f64())
1943 .bind(job)
1944 .execute(&mut *transaction)
1945 .await?;
1946 }
1947 Times::Cron(cron, _) => {
1948 sqlx::query(SCHEDULE_ADVANCE_TO)
1949 .bind(&schedule.name)
1950 .bind(jiff_sqlx::Timestamp::from(next_after(
1951 cron,
1952 time(&row, "now")?,
1953 )?))
1954 .bind(job)
1955 .execute(&mut *transaction)
1956 .await?;
1957 }
1958 }
1959 transaction.commit().await?;
1960 if job.is_some() {
1961 tracing::debug!(schedule = %schedule.name, "schedule queued its job");
1962 }
1963 Ok(job.is_some())
1964 }
1965
1966 pub async fn archive_schedules(&self) -> Result<u64> {
1973 let names: Vec<&str> = self.schedules.iter().map(|s| s.name.as_str()).collect();
1974 let result = sqlx::query(SCHEDULE_ARCHIVE)
1975 .bind(&names)
1976 .bind(self.options.stale_minutes)
1977 .execute(&self.pool)
1978 .await?;
1979 Ok(result.rows_affected())
1980 }
1981
1982 pub async fn schedules(&self) -> Result<Vec<ScheduleInfo>> {
1988 let rows = sqlx::query(SCHEDULES).fetch_all(&self.pool).await?;
1989 rows.iter()
1990 .map(|row| {
1991 Ok(ScheduleInfo {
1992 name: row.try_get("name")?,
1993 interval: row
1994 .try_get::<Option<i64>, _>("interval_ms")?
1995 .map(from_millis),
1996 cron: row.try_get("cron")?,
1997 due_at: time(row, "due_at")?,
1998 last_job: row.try_get("last_job")?,
1999 last_state: row
2000 .try_get::<Option<&str>, _>("last_status")?
2001 .map(JobState::parse)
2002 .transpose()?,
2003 last_error: row.try_get("last_error")?,
2004 seen_at: time(row, "seen_at")?,
2005 archived_at: time_or_none(row, "archived_at")?,
2006 created_at: time(row, "created_at")?,
2007 })
2008 })
2009 .collect()
2010 }
2011
2012 async fn maintain(&self) {
2015 match self.archive_schedules().await {
2016 Ok(0) => {}
2017 Ok(archived) => tracing::info!(archived, "archived schedules no longer in code"),
2018 Err(error) => tracing::error!(%error, "could not archive schedules"),
2019 }
2020 if let Err(error) = self.requeue_stale().await {
2021 tracing::error!(%error, "could not recover stale jobs");
2022 }
2023 if let Err(error) = self.purge_finished().await {
2024 tracing::error!(%error, "could not delete old jobs");
2025 }
2026 }
2027
2028 async fn supervise(&self, job: JobFuture, claim: &Claimed) -> Outcome {
2032 let mut job = AbortOnDrop(tokio::spawn(job));
2033 let every = self.options.heartbeat_interval;
2034 let Some(give_up) = give_up_after(self.options.stale_minutes, every) else {
2035 return Outcome::Lost(TIMING.to_string());
2036 };
2037 let mut last_heard = tokio::time::Instant::now();
2038 let Some(mut give_up_at) = last_heard.checked_add(give_up) else {
2039 return Outcome::Lost(TIMING.to_string());
2040 };
2041 let beat = || {
2044 tokio::time::timeout(
2045 every,
2046 sqlx::query(HEARTBEAT)
2047 .bind(claim.id)
2048 .bind(claim.attempts)
2049 .execute(&self.pool),
2050 )
2051 };
2052 let mut beating = None;
2053 let Some(mut next_beat) = tokio::time::Instant::now().checked_add(every) else {
2054 return Outcome::Lost(TIMING.to_string());
2055 };
2056 let mut failing = false;
2057 let limit = match claim.timeout {
2058 Some(timeout) => match tokio::time::Instant::now().checked_add(timeout) {
2059 Some(at) => Some(at),
2060 None => return Outcome::Lost(TIMING.to_string()),
2061 },
2062 None => None,
2063 };
2064 let deadline = async {
2065 match limit {
2066 Some(at) => tokio::time::sleep_until(at).await,
2067 None => std::future::pending().await,
2068 }
2069 };
2070 tokio::pin!(deadline);
2071 loop {
2072 tokio::select! {
2073 finished = &mut job.0 => {
2074 return Outcome::Done(finished.unwrap_or_else(|_| {
2075 Err(Error::Job("the job panicked".to_string()).to_string().into())
2076 }));
2077 }
2078 () = &mut deadline => {
2079 let limit = claim.timeout.unwrap_or(Duration::ZERO);
2080 return Outcome::Done(Err(
2081 Error::Job(format!("timed out after {}s", limit.as_secs_f64())).to_string().into(),
2082 ));
2083 }
2084 () = tokio::time::sleep_until(give_up_at), if failing => {
2085 return Outcome::Lost(format!(
2086 "it could not report in for {}s, near the {} minutes after which another worker may take it",
2087 give_up.as_secs(),
2088 self.options.stale_minutes
2089 ));
2090 }
2091 () = tokio::time::sleep_until(next_beat), if beating.is_none() => {
2092 beating = Some(Box::pin(beat()));
2093 }
2094 answer = async {
2095 match beating.as_mut() {
2096 Some(beat) => beat.await,
2097 None => std::future::pending().await,
2098 }
2099 }, if beating.is_some() => {
2100 beating = None;
2101 let Some(next) = tokio::time::Instant::now().checked_add(every) else {
2102 return Outcome::Lost(TIMING.to_string());
2103 };
2104 next_beat = next;
2105 match answer {
2106 Ok(Ok(done)) if done.rows_affected() == 1 => {
2107 last_heard = tokio::time::Instant::now();
2108 let Some(at) = last_heard.checked_add(give_up) else {
2109 return Outcome::Lost(TIMING.to_string());
2110 };
2111 give_up_at = at;
2112 failing = false;
2113 }
2114 Ok(Ok(_)) => return Outcome::Lost("another worker or recovery took its claim".to_string()),
2115 Ok(Err(error)) => {
2116 tracing::warn!(id = %claim.id, %error, "job heartbeat failed");
2117 failing = true;
2118 }
2119 Err(_) => {
2120 tracing::warn!(id = %claim.id, "job heartbeat did not answer in time");
2121 failing = true;
2122 }
2123 }
2124 }
2125 }
2126 }
2127 }
2128
2129 async fn mark_lost(&self, claim: &Claimed, reason: &str) {
2132 let text = Error::Job(format!("stopped: {reason}")).to_string();
2133 let every = self.options.heartbeat_interval;
2134 loop {
2135 match sqlx::query(MARK_LOST)
2136 .bind(claim.id)
2137 .bind(&text)
2138 .execute(&self.pool)
2139 .await
2140 {
2141 Ok(_) => return,
2142 Err(error) => {
2143 tracing::error!(id = %claim.id, %error, "could not mark a lost job for review");
2144 tokio::time::sleep(every).await;
2145 }
2146 }
2147 }
2148 }
2149
2150 fn claimable(&self) -> (Vec<String>, HashMap<String, OwnedSemaphorePermit>) {
2153 let mut places = HashMap::new();
2154 let mut names = Vec::new();
2155 for name in self.handlers.keys() {
2156 match self.limits.get(name) {
2157 None => names.push(name.clone()),
2158 Some(limit) => {
2159 if let Ok(place) = limit.clone().try_acquire_owned() {
2160 places.insert(name.clone(), place);
2161 names.push(name.clone());
2162 }
2163 }
2164 }
2165 }
2166 (names, places)
2167 }
2168
2169 async fn claim(&self, names: &[String]) -> Result<Option<Claimed>> {
2170 let Some(row) = sqlx::query(CLAIM)
2171 .bind(names)
2172 .fetch_optional(&self.pool)
2173 .await?
2174 else {
2175 return Ok(None);
2176 };
2177 Ok(Some(Claimed {
2178 id: row.try_get("id")?,
2179 name: row.try_get("name")?,
2180 args: row.try_get("args")?,
2181 attempts: row.try_get("attempts")?,
2182 limit: row
2183 .try_get::<Option<i32>, _>("max_attempts")?
2184 .unwrap_or(self.options.max_attempts),
2185 timeout: row
2186 .try_get::<Option<i64>, _>("timeout_ms")?
2187 .map(from_millis),
2188 tenant: row.try_get("tenant")?,
2189 }))
2190 }
2191
2192 pub async fn run_one(&self) -> Result<bool> {
2199 let (names, mut places) = self.claimable();
2200 if names.is_empty() {
2201 return Ok(false);
2202 }
2203 let Some(job) = self.claim(&names).await? else {
2204 return Ok(false);
2205 };
2206 let _place = places.remove(&job.name);
2208 drop(places);
2209 let outcome = match self.handlers.get(&job.name) {
2210 Some(handler) => {
2211 let run = handler(job.tenant.clone(), job.args.clone());
2212 self.supervise(run, &job).await
2213 }
2214 None => Outcome::Done(Err(Error::Job(format!("no handler for job {}", job.name))
2215 .to_string()
2216 .into())),
2217 };
2218 let (id, name, attempts) = (job.id, job.name.as_str(), job.attempts);
2219 let finished = match outcome {
2220 Outcome::Lost(reason) => {
2221 tracing::error!(job = %name, %id, attempts, %reason, "job stopped, it lost its claim");
2222 self.mark_lost(&job, &reason).await;
2223 return Ok(true);
2224 }
2225 Outcome::Done(Ok(())) => {
2226 sqlx::query(FINISH)
2227 .bind(id)
2228 .bind(attempts)
2229 .bind("completed")
2230 .bind(None::<String>)
2231 .execute(&self.pool)
2232 .await?
2233 }
2234 Outcome::Done(Err(error)) if attempts < job.limit => {
2235 tracing::warn!(job = %name, %id, attempts, %error, "job failed, will retry");
2236 let wait = retry_wait(self.options.retry_backoff, attempts, error.retry_in)
2237 .ok_or(Error::Overflow("retry wait"))?;
2238 sqlx::query(RETRY)
2239 .bind(id)
2240 .bind(attempts)
2241 .bind(cut(error.text))
2242 .bind(wait.as_secs_f64())
2243 .execute(&self.pool)
2244 .await?
2245 }
2246 Outcome::Done(Err(error)) => {
2247 tracing::error!(job = %name, %id, attempts, %error, "job failed");
2248 sqlx::query(FINISH)
2249 .bind(id)
2250 .bind(attempts)
2251 .bind("failed")
2252 .bind(cut(error.text))
2253 .execute(&self.pool)
2254 .await?
2255 }
2256 };
2257 if finished.rows_affected() == 0 {
2258 tracing::error!(job = %name, %id, "job finished after losing its claim");
2261 self.mark_lost(
2262 &job,
2263 "it finished after another worker or recovery took its claim",
2264 )
2265 .await;
2266 }
2267 Ok(true)
2268 }
2269
2270 pub async fn run(self: Arc<Self>, shutdown: watch::Receiver<bool>) {
2276 let mut loops = Vec::new();
2277 loops.push(AbortOnDrop(tokio::spawn(every_until(
2278 shutdown.clone(),
2279 self.options.maintenance_interval,
2280 {
2281 let queue = self.clone();
2282 move || {
2283 let queue = queue.clone();
2284 async move { queue.maintain().await }
2285 }
2286 },
2287 ))));
2288 if !self.schedules.is_empty() {
2289 let queue = self.clone();
2290 loops.push(AbortOnDrop(tokio::spawn(every_until(
2291 shutdown.clone(),
2292 self.options.poll_interval,
2293 move || {
2294 let queue = queue.clone();
2295 async move {
2296 if let Err(error) = queue.tick_schedules().await {
2297 tracing::error!(%error, "could not queue scheduled jobs");
2298 }
2299 }
2300 },
2301 ))));
2302 }
2303 let wake = Arc::new(Notify::new());
2304 loops.push(AbortOnDrop(tokio::spawn(listen(
2305 self.pool.clone(),
2306 wake.clone(),
2307 self.options.poll_interval,
2308 shutdown.clone(),
2309 ))));
2310 for _ in 0..self.options.workers.max(1) {
2311 let queue = self.clone();
2312 let wake = wake.clone();
2313 let mut shutdown = shutdown.clone();
2314 loops.push(AbortOnDrop(tokio::spawn(async move {
2315 while !*shutdown.borrow() {
2316 let round = async {
2317 queue.run_one().await.unwrap_or_else(|error| {
2318 tracing::error!(%error, "job queue error");
2319 false
2320 })
2321 };
2322 work_or_wait(&wake, queue.options.poll_interval, &mut shutdown, round).await;
2323 }
2324 })));
2325 }
2326 for job_loop in &mut loops {
2327 let _ = (&mut job_loop.0).await;
2328 }
2329 }
2330
2331 #[must_use]
2333 pub fn handled(&self) -> HashSet<&str> {
2334 self.handlers.keys().map(String::as_str).collect()
2335 }
2336}
2337
2338async fn work_or_wait(
2342 wake: &Notify,
2343 poll: Duration,
2344 shutdown: &mut watch::Receiver<bool>,
2345 round: impl Future<Output = bool>,
2346) {
2347 let woken = wake.notified();
2348 tokio::pin!(woken);
2349 woken.as_mut().enable();
2350 if !round.await {
2351 tokio::select! {
2352 () = tokio::time::sleep(poll) => {},
2353 () = woken => {},
2354 _ = shutdown.changed() => {},
2355 }
2356 }
2357}
2358
2359async fn listen(
2362 pool: PgPool,
2363 wake: Arc<Notify>,
2364 gap: Duration,
2365 mut shutdown: watch::Receiver<bool>,
2366) {
2367 while !*shutdown.borrow() {
2368 match sqlx::postgres::PgListener::connect_with(&pool).await {
2369 Ok(mut listener) => match listener.listen(NOTIFY_CHANNEL).await {
2370 Ok(()) => loop {
2371 tokio::select! {
2372 notice = listener.try_recv() => match notice {
2373 Ok(_) => wake.notify_waiters(),
2376 Err(error) => {
2377 tracing::warn!(%error, "job queue listener failed, polling");
2378 break;
2379 }
2380 },
2381 _ = shutdown.changed() => return,
2382 }
2383 },
2384 Err(error) => tracing::warn!(%error, "job queue could not listen, polling"),
2385 },
2386 Err(error) => tracing::warn!(%error, "job queue could not listen, polling"),
2387 }
2388 tokio::select! {
2389 () = tokio::time::sleep(gap) => {},
2390 _ = shutdown.changed() => {},
2391 }
2392 }
2393}
2394
2395async fn every_until<F, Fut>(mut shutdown: watch::Receiver<bool>, gap: Duration, round: F)
2397where
2398 F: Fn() -> Fut,
2399 Fut: Future<Output = ()>,
2400{
2401 while !*shutdown.borrow() {
2402 round().await;
2403 tokio::select! {
2404 () = tokio::time::sleep(gap) => {},
2405 _ = shutdown.changed() => {},
2406 }
2407 }
2408}
2409
2410struct AbortOnDrop<T>(tokio::task::JoinHandle<T>);
2413
2414impl<T> Drop for AbortOnDrop<T> {
2415 fn drop(&mut self) {
2416 self.0.abort();
2417 }
2418}
2419
2420#[cfg(test)]
2421#[expect(clippy::string_slice, reason = "RCA-SCOPE-4: tests may slice strings")]
2422mod tests {
2423 use super::*;
2424
2425 #[test]
2426 fn the_time_to_give_up_is_two_heartbeats_before_the_stale_time() {
2427 let beat = Duration::from_secs(30);
2428 assert_eq!(give_up_after(60, beat), Some(Duration::from_mins(59)));
2429 assert_eq!(give_up_after(1, Duration::from_secs(40)), None);
2431 assert_eq!(give_up_after(60, Duration::MAX), None);
2432 assert_eq!(give_up_after(-1, beat), None);
2434 assert!(give_up_after(i32::MAX, Duration::ZERO).is_some());
2435 }
2436
2437 #[test]
2438 fn options_out_of_range_are_refused() {
2439 assert!(QueueOptions::default().check().is_ok());
2440 let refused = |change: fn(&mut QueueOptions)| {
2441 let mut options = QueueOptions::default();
2442 change(&mut options);
2443 options.check()
2444 };
2445 if let Ok(over) = usize::try_from(u64::from(u32::MAX) + 1) {
2447 let options = QueueOptions {
2448 workers: over,
2449 ..QueueOptions::default()
2450 };
2451 assert!(matches!(options.check(), Err(Error::OutOfRange("workers"))));
2452 }
2453 assert!(matches!(
2454 refused(|o| o.stale_minutes = 0_i32),
2455 Err(Error::OutOfRange("stale_minutes"))
2456 ));
2457 assert!(matches!(
2458 refused(|o| o.stale_minutes = -1_i32),
2459 Err(Error::OutOfRange("stale_minutes"))
2460 ));
2461 assert!(matches!(
2463 refused(|o| o.heartbeat_interval = Duration::from_mins(16)),
2464 Err(Error::OutOfRange("heartbeat_interval"))
2465 ));
2466 assert!(refused(|o| o.heartbeat_interval = Duration::from_mins(15)).is_ok());
2467 assert!(matches!(
2468 refused(|o| o.heartbeat_interval = Duration::ZERO),
2469 Err(Error::OutOfRange("heartbeat_interval"))
2470 ));
2471 assert!(matches!(
2472 refused(|o| o.heartbeat_interval = Duration::MAX),
2473 Err(Error::OutOfRange("heartbeat_interval"))
2474 ));
2475 }
2476
2477 #[test]
2478 fn a_delay_out_of_range_is_refused() {
2479 assert!(RetryAfter::new(MIN_RETRY_AFTER, "x").is_ok());
2480 assert!(RetryAfter::new(MAX_BACKOFF, "x").is_ok());
2481 for delay in [
2482 Duration::ZERO,
2483 Duration::from_millis(999),
2484 MAX_BACKOFF + Duration::from_secs(1),
2485 ] {
2486 assert!(
2487 matches!(
2488 RetryAfter::new(delay, "x"),
2489 Err(Error::OutOfRange("retry after"))
2490 ),
2491 "{delay:?}"
2492 );
2493 }
2494 assert_eq!(
2495 Error::OutOfRange("retry after").to_string(),
2496 "retry after: the value is out of range"
2497 );
2498 }
2499
2500 #[test]
2501 fn a_figure_too_large_to_compute_is_named_in_its_error() {
2502 let error = Error::Overflow("schedules queued");
2503 assert_eq!(
2504 error.to_string(),
2505 "schedules queued: the value is too large to compute"
2506 );
2507 assert!(std::error::Error::source(&error).is_none());
2508 }
2509
2510 #[test]
2511 fn a_stored_word_that_is_not_a_known_state_or_act_is_refused() {
2512 assert!(JobState::parse("cancelled").is_ok());
2513 assert!(ActKind::parse("released").is_ok());
2514 let error = JobState::parse("lost").unwrap_err().to_string();
2515 assert!(error.contains("unknown status"), "{error}");
2516 let error = ActKind::parse("lost").unwrap_err().to_string();
2517 assert!(error.contains("unknown kind"), "{error}");
2518 let error = Error::NotATenant.to_string();
2519 assert!(error.contains("lower-case letters"), "{error}");
2520 }
2521
2522 #[tokio::test]
2523 async fn a_wake_during_a_round_that_found_nothing_is_not_lost() {
2524 let wake = Notify::new();
2525 let (_stop, mut shutdown) = watch::channel(false);
2526 let round = async {
2528 wake.notify_waiters();
2529 false
2530 };
2531 let waited = tokio::time::timeout(
2532 Duration::from_secs(5),
2533 work_or_wait(&wake, Duration::from_hours(1), &mut shutdown, round),
2534 )
2535 .await;
2536 assert!(
2537 waited.is_ok(),
2538 "the wake was lost and the loop waited for its poll"
2539 );
2540 }
2541
2542 #[test]
2543 fn each_retry_waits_twice_as_long_up_to_a_limit() {
2544 let base = Duration::from_secs(30);
2545 assert_eq!(backoff(base, 1), Some(base));
2546 assert_eq!(backoff(base, 2), Some(base * 2));
2547 assert_eq!(backoff(base, 3), Some(base * 4));
2548 assert_eq!(backoff(base, 1_000), Some(MAX_BACKOFF));
2549 assert_eq!(backoff(base, 0), None);
2550 assert_eq!(backoff(base, i32::MIN), None);
2551 }
2552
2553 #[test]
2554 fn a_retry_waits_a_jittered_backoff_or_the_delay_the_job_chose() {
2555 let base = Duration::from_secs(30);
2556 for _ in 0_i32..200_i32 {
2557 let wait = retry_wait(base, 2, None).unwrap();
2558 assert!(wait >= base && wait <= base * 2, "{wait:?}");
2559 }
2560 let waits: HashSet<_> = (0_i32..20_i32)
2561 .map(|_| retry_wait(base, 1, None).unwrap())
2562 .collect();
2563 assert!(waits.len() > 1, "the waits are spread");
2564 assert_eq!(retry_wait(Duration::ZERO, 3, None), Some(Duration::ZERO));
2565 assert_eq!(retry_wait(base, 0, None), None);
2566 let chosen = Some(Duration::from_secs(90));
2567 assert_eq!(retry_wait(base, 1, chosen), Some(Duration::from_secs(90)));
2568 assert_eq!(retry_wait(base, 1, Some(Duration::ZERO)), None);
2570 assert_eq!(retry_wait(base, 1, Some(Duration::from_hours(9))), None);
2571 }
2572
2573 #[test]
2574 fn a_jittered_wait_is_between_half_and_the_whole_and_one_that_does_not_fit_has_none() {
2575 let wait = Duration::from_secs(40);
2576 for _ in 0_i32..200_i32 {
2577 let spread = jittered(wait).unwrap();
2578 assert!(spread >= wait / 2 && spread <= wait, "{spread:?}");
2579 }
2580 assert_eq!(jittered(Duration::ZERO), Some(Duration::ZERO));
2581 assert_eq!(jittered(Duration::MAX), None);
2582 }
2583
2584 #[test]
2585 fn a_retry_after_error_carries_its_delay_and_others_none() {
2586 let chosen = Failure::from_error(RetryAfter::new(Duration::from_secs(7), "busy").unwrap());
2587 assert_eq!(
2588 (chosen.text.as_str(), chosen.retry_in),
2589 ("busy", Some(Duration::from_secs(7)))
2590 );
2591 let boxed: Box<dyn std::error::Error + Send + Sync> =
2592 Box::new(RetryAfter::new(Duration::from_secs(8), "boxed").unwrap());
2593 assert_eq!(
2594 Failure::from_error(boxed).retry_in,
2595 Some(Duration::from_secs(8))
2596 );
2597 let plain = Failure::from_error("broken".to_string());
2598 assert_eq!((plain.text.as_str(), plain.retry_in), ("broken", None));
2599 }
2600
2601 #[test]
2602 fn the_debug_text_leaves_out_arguments() {
2603 let job = NewJob::new("Report", serde_json::json!({ "nhs": "943 476 5919" }));
2604 let schedule = Schedule::every("nightly", Duration::from_hours(1), job.clone()).unwrap();
2605 let cron = Schedule::cron("at-two", "0 2 * * *", job.clone()).unwrap();
2606 for text in [
2607 format!("{job:?}"),
2608 format!("{schedule:?}"),
2609 format!("{cron:?}"),
2610 ] {
2611 assert!(text.contains("Report"), "{text}");
2612 assert!(!text.contains("943"), "{text}");
2613 }
2614 }
2615
2616 #[test]
2617 fn a_by_or_reason_that_is_not_a_code_is_refused() {
2618 assert!(check_code("ops:alice", "by").is_ok());
2619 assert!(check_code(&"é".repeat(MAX_REASON_CHARS), "reason").is_ok());
2620 for bad in [
2621 String::new(),
2622 "é".repeat(MAX_REASON_CHARS + 1),
2623 "two\nlines".to_string(),
2624 "a\ttab".to_string(),
2625 ] {
2626 let error = check_code(&bad, "reason").unwrap_err();
2627 assert!(matches!(error, Error::NotACode { what: "reason" }));
2628 assert!(!error.to_string().contains("lines"), "the text is left out");
2629 }
2630 }
2631
2632 #[test]
2633 fn a_long_error_is_cut_on_a_character_boundary() {
2634 let text = format!("a{}", "é".repeat(MAX_ERROR));
2636 let kept = cut(text);
2637 assert_eq!(kept.len(), MAX_ERROR - 1);
2638 assert!(kept[1..].chars().all(|c| c == 'é'));
2639 assert_eq!(cut("short".to_string()), "short");
2640 }
2641
2642 #[test]
2643 fn a_schedule_under_a_second_is_refused_at_boot() {
2644 let error = Schedule::every(
2645 "fast",
2646 Duration::from_millis(10),
2647 NewJob::new("J", serde_json::Value::Null),
2648 )
2649 .unwrap_err();
2650 assert!(matches!(&error, Error::Schedule(_)), "{error:?}");
2651 assert!(error.to_string().contains("at least a second"), "{error}");
2652 }
2653
2654 #[test]
2655 fn a_bad_cron_pattern_is_refused_at_boot() {
2656 let error = Schedule::cron(
2657 "bad",
2658 "61 * * * *",
2659 NewJob::new("J", serde_json::Value::Null),
2660 )
2661 .unwrap_err();
2662 assert!(matches!(&error, Error::Schedule(_)), "{error:?}");
2663 assert!(error.to_string().contains("bad cron pattern"), "{error}");
2664 }
2665
2666 #[test]
2667 fn a_cron_schedule_names_its_next_times_in_utc() {
2668 let schedule = Schedule::cron(
2669 "weekdays",
2670 "0 9 * * MON-FRI",
2671 NewJob::new("J", serde_json::Value::Null),
2672 )
2673 .unwrap();
2674 assert_eq!(schedule.cron_pattern(), Some("0 9 * * MON-FRI"));
2675 assert_eq!(schedule.interval(), None);
2676 let Times::Cron(cron, _) = &schedule.times else {
2677 panic!("a cron schedule")
2678 };
2679 let friday: Timestamp = "2026-11-13T09:00:00Z".parse().unwrap();
2681 let monday: Timestamp = "2026-11-16T09:00:00Z".parse().unwrap();
2682 assert_eq!(next_after(cron, friday).unwrap(), monday);
2683 assert_eq!(
2684 Schedule::every(
2685 "e",
2686 Duration::from_secs(5),
2687 NewJob::new("J", serde_json::Value::Null)
2688 )
2689 .unwrap()
2690 .interval(),
2691 Some(Duration::from_secs(5))
2692 );
2693 }
2694
2695 #[test]
2696 fn a_cron_schedule_counts_in_utc_across_a_month_end_and_a_clock_change() {
2697 let next = |pattern: &str, after: &str| {
2698 let cron: croner::Cron = pattern.parse().unwrap();
2699 next_after(&cron, after.parse().unwrap())
2700 .unwrap()
2701 .to_string()
2702 };
2703 assert_eq!(
2705 next("0 0 31 * *", "2026-11-15T00:00:00Z"),
2706 "2026-12-31T00:00:00Z"
2707 );
2708 assert_eq!(
2709 next("30 23 * * *", "2026-12-31T23:30:00Z"),
2710 "2027-01-01T23:30:00Z"
2711 );
2712 assert_eq!(
2713 next("0 12 29 2 *", "2026-03-01T00:00:00Z"),
2714 "2028-02-29T12:00:00Z"
2715 );
2716 assert_eq!(
2720 next("30 1 * * *", "2026-03-28T01:30:00Z"),
2721 "2026-03-29T01:30:00Z"
2722 );
2723 assert_eq!(
2724 next("30 1 * * *", "2026-10-25T01:30:00Z"),
2725 "2026-10-26T01:30:00Z"
2726 );
2727 assert_eq!(
2728 next("0 6 * * *", "2026-11-01T06:00:00Z"),
2729 "2026-11-02T06:00:00Z"
2730 );
2731 assert_eq!(
2733 next("* * * * * *", "2026-11-15T00:00:00.5Z"),
2734 "2026-11-15T00:00:01Z"
2735 );
2736 }
2737
2738 #[test]
2739 fn a_schedule_with_no_name_is_refused_at_boot() {
2740 let error = Schedule::every(
2741 "",
2742 Duration::from_secs(1),
2743 NewJob::new("J", serde_json::Value::Null),
2744 )
2745 .unwrap_err();
2746 assert!(matches!(&error, Error::Schedule(_)), "{error:?}");
2747 assert!(error.to_string().contains("1 to 200 characters"), "{error}");
2748 }
2749
2750 #[tokio::test]
2751 async fn a_schedule_added_twice_is_refused_at_boot() {
2752 let pool = PgPoolOptions::new()
2753 .connect_lazy("postgres://u@localhost/none")
2754 .unwrap();
2755 let mut queue = Queue::from_pool(pool, QueueOptions::default()).unwrap();
2756 let job = NewJob::new("J", serde_json::Value::Null);
2757 queue
2758 .schedule(Schedule::every("a", Duration::from_secs(5), job.clone()).unwrap())
2759 .unwrap();
2760 let error = queue
2761 .schedule(Schedule::every("a", Duration::from_secs(9), job).unwrap())
2762 .unwrap_err();
2763 assert!(error.to_string().contains("added twice"), "{error}");
2764 }
2765
2766 #[test]
2767 fn a_schedule_ignores_a_delay_on_its_job() {
2768 let job = NewJob::new("J", serde_json::Value::Null).run_in(Duration::from_hours(1));
2769 let schedule = Schedule::every("s", Duration::from_secs(5), job).unwrap();
2770 assert_eq!(schedule.job.when, When::Now);
2771 }
2772
2773 #[test]
2774 fn an_error_keeps_what_caused_it_and_only_a_database_or_encoding_error_has_a_source() {
2775 use std::error::Error as _;
2776 let encoding = serde_json::from_str::<u8>("x").unwrap_err();
2777 let text = encoding.to_string();
2778 let error = Error::from(encoding);
2779 assert!(matches!(error, Error::Encode(_)));
2780 assert_eq!(error.to_string(), text);
2781 assert_eq!(error.source().map(ToString::to_string), Some(text));
2782 let database = Error::Database(sqlx::Error::RowNotFound);
2783 assert!(database.source().is_some());
2784 for none in [
2785 Error::Job("it broke".into()),
2786 Error::NotACode { what: "by" },
2787 Error::NotATenant,
2788 ] {
2789 assert!(none.source().is_none(), "{none}");
2790 }
2791 }
2792
2793 #[test]
2794 fn a_cron_pattern_that_names_no_time_to_come_is_refused_at_boot() {
2795 let error = Schedule::cron(
2797 "never",
2798 "0 0 30 2 *",
2799 NewJob::new("J", serde_json::Value::Null),
2800 )
2801 .unwrap_err();
2802 assert!(matches!(&error, Error::Schedule(_)), "{error:?}");
2803 assert!(
2804 error.to_string().contains("names no time to come"),
2805 "{error}"
2806 );
2807 }
2808
2809 #[test]
2810 fn a_job_and_a_schedule_say_their_names_and_a_failure_its_text() {
2811 let job = NewJob::new("SendMail", serde_json::Value::Null);
2812 assert_eq!(job.name(), "SendMail");
2813 let schedule = Schedule::every("hourly", Duration::from_hours(1), job).unwrap();
2814 assert_eq!(schedule.name(), "hourly");
2815 assert_eq!(
2816 Failure::from("the receiver is busy".to_string()).to_string(),
2817 "the receiver is busy"
2818 );
2819 }
2820
2821 #[tokio::test]
2822 async fn a_queue_shows_how_much_it_holds_and_its_options_and_never_its_pool() {
2823 let pool = sqlx::postgres::PgPoolOptions::new()
2824 .connect_lazy("postgres://axa:secret-password@127.0.0.1:1/axa")
2825 .unwrap();
2826 let options = QueueOptions {
2827 workers: 3,
2828 ..QueueOptions::default()
2829 };
2830 let mut queue = Queue::from_pool(pool, options).unwrap();
2831 queue.handle("A", |_: serde_json::Value| async { Ok::<(), String>(()) });
2832 queue.limit("A", 1);
2833 queue
2834 .schedule(
2835 Schedule::every(
2836 "hourly",
2837 Duration::from_hours(1),
2838 NewJob::new("A", serde_json::Value::Null),
2839 )
2840 .unwrap(),
2841 )
2842 .unwrap();
2843 assert_eq!(queue.options().workers, 3);
2844 let shown = format!("{queue:?}");
2845 assert!(
2846 shown.starts_with("Queue { handlers: 1, limits: 1, schedules: 1, options: "),
2847 "{shown}"
2848 );
2849 assert!(!shown.contains("secret-password"), "{shown}");
2850 }
2851}