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}
211
212impl fmt::Display for Error {
213 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
214 match self {
215 Self::Database(error) => error.fmt(f),
216 Self::Encode(error) => error.fmt(f),
217 Self::Job(text) => write!(f, "worker error: {text}"),
218 Self::NotACode { what } => write!(
219 f,
220 "`{what}` must be 1 to {MAX_REASON_CHARS} characters with no line breaks"
221 ),
222 Self::NotATenant => f.write_str(
223 "a job's tenant must be 1 to 63 lower-case letters, digits, and hyphens, \
224 not starting or ending with a hyphen",
225 ),
226 }
227 }
228}
229
230impl std::error::Error for Error {
231 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
232 match self {
233 Self::Database(error) => Some(error),
234 Self::Encode(error) => Some(error),
235 Self::Job(_) | Self::NotACode { .. } | Self::NotATenant => None,
236 }
237 }
238}
239
240impl From<sqlx::Error> for Error {
241 fn from(error: sqlx::Error) -> Self {
242 Self::Database(error)
243 }
244}
245
246impl From<serde_json::Error> for Error {
247 fn from(error: serde_json::Error) -> Self {
248 Self::Encode(error)
249 }
250}
251
252type JobFuture = Pin<Box<dyn Future<Output = Result<(), Failure>> + Send>>;
253type Handler = Arc<dyn Fn(Option<String>, serde_json::Value) -> JobFuture + Send + Sync>;
254
255const SETUP: &str = "CREATE TABLE IF NOT EXISTS axa_queue (
256 id UUID PRIMARY KEY,
257 name TEXT NOT NULL,
258 args JSONB NOT NULL,
259 status TEXT NOT NULL DEFAULT 'queued',
260 error TEXT,
261 run_at TIMESTAMPTZ NOT NULL DEFAULT now(),
262 started_at TIMESTAMPTZ,
263 created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
264 updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
265)";
266const SETUP_INDEX: &str =
267 "CREATE INDEX IF NOT EXISTS axa_queue_ready ON axa_queue (run_at) WHERE status = 'queued'";
268const SETUP_ATTEMPTS: &str =
270 "ALTER TABLE axa_queue ADD COLUMN IF NOT EXISTS attempts INTEGER NOT NULL DEFAULT 0";
271const SETUP_MAX_ATTEMPTS: &str =
273 "ALTER TABLE axa_queue ADD COLUMN IF NOT EXISTS max_attempts INTEGER";
274const SETUP_PRIORITY: &str =
276 "ALTER TABLE axa_queue ADD COLUMN IF NOT EXISTS priority SMALLINT NOT NULL DEFAULT 0";
277const SETUP_TIMEOUT: &str = "ALTER TABLE axa_queue ADD COLUMN IF NOT EXISTS timeout_ms BIGINT";
279const SETUP_TENANT: &str = "ALTER TABLE axa_queue ADD COLUMN IF NOT EXISTS tenant TEXT
281 CONSTRAINT axa_queue_tenant_id CHECK (tenant ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$')";
282const SETUP_UNIQUE_KEY: &str = "ALTER TABLE axa_queue ADD COLUMN IF NOT EXISTS unique_key TEXT
284 CONSTRAINT axa_queue_unique_key_code
285 CHECK (length(unique_key) BETWEEN 1 AND 200 AND unique_key !~ '[[:cntrl:]]')";
286const SETUP_UNIQUE_INDEX: &str = "CREATE UNIQUE INDEX IF NOT EXISTS axa_queue_unique
288 ON axa_queue (name, (COALESCE(tenant, '')), unique_key)
289 WHERE unique_key IS NOT NULL AND status IN ('queued', 'running')";
290const SETUP_CLAIM_INDEX: &str = "CREATE INDEX IF NOT EXISTS axa_queue_claim
291 ON axa_queue (priority DESC, run_at) WHERE status = 'queued'";
292const SETUP_SCHEDULE: &str = "CREATE TABLE IF NOT EXISTS axa_schedule (
293 name TEXT PRIMARY KEY,
294 due_at TIMESTAMPTZ NOT NULL,
295 last_job UUID,
296 interval_ms BIGINT,
297 seen_at TIMESTAMPTZ NOT NULL DEFAULT now(),
298 archived_at TIMESTAMPTZ,
299 created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
300 updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
301)";
302const SETUP_SCHEDULE_CRON: &str = "ALTER TABLE axa_schedule ADD COLUMN IF NOT EXISTS cron TEXT";
308const SETUP_ACTS: &str = "CREATE TABLE IF NOT EXISTS axa_job_acts (
309 id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
310 job_id UUID NOT NULL,
311 job_name TEXT NOT NULL,
312 act TEXT NOT NULL CHECK (act IN ('cancelled', 'retried', 'released')),
313 attempts INTEGER NOT NULL,
314 by TEXT NOT NULL CHECK (length(by) BETWEEN 1 AND 200 AND by !~ '[[:cntrl:]]'),
315 reason TEXT NOT NULL CHECK (length(reason) BETWEEN 1 AND 200 AND reason !~ '[[:cntrl:]]'),
316 at TIMESTAMPTZ NOT NULL DEFAULT now()
317)";
318const SETUP_ACTS_INDEX: &str =
319 "CREATE INDEX IF NOT EXISTS axa_job_acts_job ON axa_job_acts (job_id, id)";
320const SETUP_ACTS_REFUSE: &str = "CREATE OR REPLACE FUNCTION axa_job_acts_refuse() RETURNS trigger
322LANGUAGE plpgsql AS $$
323BEGIN
324 RAISE EXCEPTION '% on % is refused: acts on jobs are only ever added to',
325 TG_OP, TG_TABLE_NAME;
326END
327$$";
328const SETUP_ACTS_ROWS: &str = "CREATE OR REPLACE TRIGGER axa_job_acts_refuse
329 BEFORE UPDATE OR DELETE ON axa_job_acts
330 FOR EACH ROW EXECUTE FUNCTION axa_job_acts_refuse()";
331const SETUP_ACTS_TRUNCATE: &str = "CREATE OR REPLACE TRIGGER axa_job_acts_refuse_truncate
332 BEFORE TRUNCATE ON axa_job_acts
333 FOR EACH STATEMENT EXECUTE FUNCTION axa_job_acts_refuse()";
334const SETUP_ACTS_ALWAYS: &str = "ALTER TABLE axa_job_acts
337 ENABLE ALWAYS TRIGGER axa_job_acts_refuse,
338 ENABLE ALWAYS TRIGGER axa_job_acts_refuse_truncate";
339pub const NOTIFY_CHANNEL: &str = "axa_queue";
341const SETUP_NOTIFY_FUNCTION: &str = "CREATE OR REPLACE FUNCTION axa_queue_notify() RETURNS trigger
343LANGUAGE plpgsql AS $$
344BEGIN
345 PERFORM pg_notify('axa_queue', '');
346 RETURN NULL;
347END
348$$";
349const SETUP_NOTIFY: &str = "CREATE OR REPLACE TRIGGER axa_queue_notify
350 AFTER INSERT ON axa_queue
351 FOR EACH STATEMENT EXECUTE FUNCTION axa_queue_notify()";
352const ACTS_TRIGGERS: [&str; 2] = ["axa_job_acts_refuse", "axa_job_acts_refuse_truncate"];
354const MISSING_TRIGGERS: &str = "SELECT want FROM unnest($1::text[]) AS want
355 WHERE NOT EXISTS (
356 SELECT 1 FROM pg_trigger t
357 WHERE t.tgrelid = to_regclass('axa_job_acts') AND t.tgname = want
358 AND t.tgenabled::text = 'A'
359 )";
360const NO_TENANT_HANDLER: &str =
362 "the job has a tenant, and its handler takes none: register it with handle_with_tenant";
363
364const SETUP_LOCK: i64 = 0x0061_7861_5F71;
366
367const ENQUEUE: &str = "INSERT INTO axa_queue
368 (id, name, args, max_attempts, priority, run_at, timeout_ms, tenant)
369 VALUES ($1, $2, $3, $4, $5, COALESCE($6, now() + make_interval(secs => $7)), $8, $9)";
370const ENQUEUE_UNIQUE: &str = "INSERT INTO axa_queue
375 (id, name, args, max_attempts, priority, run_at, timeout_ms, tenant, unique_key)
376 VALUES ($1, $2, $3, $4, $5, COALESCE($6, now() + make_interval(secs => $7)), $8, $9, $10)
377 ON CONFLICT (name, (COALESCE(tenant, '')), unique_key)
378 WHERE unique_key IS NOT NULL AND status IN ('queued', 'running')
379 DO UPDATE SET unique_key = EXCLUDED.unique_key
380 RETURNING id";
381const CLAIM: &str = "UPDATE axa_queue
382 SET status = 'running', started_at = now(), updated_at = now(), attempts = attempts + 1
383 WHERE id = (
384 SELECT id FROM axa_queue
385 WHERE status = 'queued' AND run_at <= now() AND name = ANY($1)
386 ORDER BY priority DESC, run_at
387 FOR UPDATE SKIP LOCKED
388 LIMIT 1
389 )
390 RETURNING id, name, args, attempts, max_attempts, timeout_ms, tenant";
391const HEARTBEAT: &str = "UPDATE axa_queue SET updated_at = now()
394 WHERE id = $1 AND attempts = $2 AND status = 'running'";
395const FINISH: &str = "UPDATE axa_queue SET status = $3, error = $4, updated_at = now()
396 WHERE id = $1 AND attempts = $2 AND status = 'running'";
397const RETRY: &str = "UPDATE axa_queue
398 SET status = 'queued', error = $3, started_at = NULL, updated_at = now(),
399 run_at = now() + make_interval(secs => $4)
400 WHERE id = $1 AND attempts = $2 AND status = 'running'";
401const REQUEUE_STALE: &str = "UPDATE axa_queue
402 SET status = 'queued', started_at = NULL, updated_at = now()
403 WHERE status = 'running' AND updated_at < now() - make_interval(mins => $1)
404 AND attempts < COALESCE(max_attempts, $2)";
405const FAIL_STALE: &str = "UPDATE axa_queue
406 SET status = 'failed', error = 'abandoned by its worker', updated_at = now()
407 WHERE status = 'running' AND updated_at < now() - make_interval(mins => $1)
408 AND attempts >= COALESCE(max_attempts, $2)";
409const PURGE: &str = "DELETE FROM axa_queue
410 WHERE status IN ('completed', 'failed', 'cancelled')
411 AND updated_at < now() - make_interval(days => $1)";
412const STATUS: &str = "SELECT id, name, status, attempts, max_attempts, priority, error,
413 timeout_ms, tenant, unique_key, run_at, started_at, created_at, updated_at FROM axa_queue WHERE id = $1";
414const MARK_LOST: &str =
418 "UPDATE axa_queue SET status = 'needs_review', error = $2, updated_at = now()
419 WHERE id = $1 AND status IN ('queued', 'running', 'failed')";
420const CANCEL: &str = "WITH changed AS (
423 UPDATE axa_queue SET status = 'cancelled', updated_at = now()
424 WHERE id = $1 AND status = 'queued'
425 RETURNING id, name, attempts
426 )
427 INSERT INTO axa_job_acts (job_id, job_name, act, attempts, by, reason)
428 SELECT id, name, 'cancelled', attempts, $2, $3 FROM changed";
429const RETRY_FAILED: &str = "WITH target AS (
434 SELECT id, status FROM axa_queue
435 WHERE id = $1 AND status IN ('failed', 'needs_review')
436 AND NOT EXISTS (
437 SELECT 1 FROM axa_queue other
438 WHERE other.unique_key = axa_queue.unique_key
439 AND other.name = axa_queue.name
440 AND COALESCE(other.tenant, '') = COALESCE(axa_queue.tenant, '')
441 AND other.status IN ('queued', 'running')
442 )
443 FOR UPDATE
444 ), changed AS (
445 UPDATE axa_queue q
446 SET status = 'queued', run_at = now(), started_at = NULL, updated_at = now(),
447 max_attempts = q.attempts + 1
448 FROM target WHERE q.id = target.id
449 RETURNING q.id, q.name, q.attempts, target.status AS was
450 )
451 INSERT INTO axa_job_acts (job_id, job_name, act, attempts, by, reason)
452 SELECT id, name, CASE was WHEN 'needs_review' THEN 'released' ELSE 'retried' END,
453 attempts, $2, $3
454 FROM changed";
455const ACTS: &str = "SELECT id, job_id, job_name, act, attempts, by, reason, at
456 FROM axa_job_acts WHERE job_id = $1 ORDER BY id";
457const COUNTS: &str = "SELECT
458 count(*) FILTER (WHERE status = 'queued' AND run_at <= now()) AS ready,
459 count(*) FILTER (WHERE status = 'queued' AND run_at > now()) AS waiting,
460 count(*) FILTER (WHERE status = 'running') AS running,
461 count(*) FILTER (WHERE status = 'completed') AS completed,
462 count(*) FILTER (WHERE status = 'failed') AS failed,
463 count(*) FILTER (WHERE status = 'cancelled') AS cancelled,
464 count(*) FILTER (WHERE status = 'needs_review') AS needs_review,
465 EXTRACT(EPOCH FROM now() - min(run_at) FILTER (WHERE status = 'queued' AND run_at <= now()))::float8 AS oldest
466 FROM axa_queue";
467const SCHEDULE_CREATE: &str = "INSERT INTO axa_schedule (name, due_at, interval_ms, cron)
472 VALUES ($1, COALESCE($2, now()), $3, $4)
473 ON CONFLICT (name) DO UPDATE
474 SET seen_at = now(), archived_at = NULL, interval_ms = EXCLUDED.interval_ms,
475 cron = EXCLUDED.cron,
476 due_at = CASE WHEN EXCLUDED.cron IS NOT NULL
477 AND axa_schedule.cron IS DISTINCT FROM EXCLUDED.cron
478 THEN EXCLUDED.due_at ELSE axa_schedule.due_at END
479 WHERE axa_schedule.archived_at IS NOT NULL
480 OR axa_schedule.interval_ms IS DISTINCT FROM EXCLUDED.interval_ms
481 OR axa_schedule.cron IS DISTINCT FROM EXCLUDED.cron
482 OR axa_schedule.seen_at < now() - interval '1 minute'";
483const SCHEDULE_LOCK: &str =
484 "SELECT last_job, due_at <= now() AS due, now() AS now FROM axa_schedule
485 WHERE name = $1 AND archived_at IS NULL FOR UPDATE SKIP LOCKED";
486const SCHEDULE_ARCHIVE: &str = "UPDATE axa_schedule SET archived_at = now(), updated_at = now()
490 WHERE archived_at IS NULL AND name <> ALL($1)
491 AND seen_at < now() - make_interval(mins => $2)";
492const SCHEDULES: &str = "SELECT s.name, s.interval_ms, s.cron, s.due_at, s.last_job, s.seen_at,
493 s.archived_at, s.created_at, q.status AS last_status, q.error AS last_error
494 FROM axa_schedule s LEFT JOIN axa_queue q ON q.id = s.last_job ORDER BY s.name";
495const SCHEDULE_BUSY: &str = "SELECT EXISTS (SELECT 1 FROM axa_queue
496 WHERE id = $1 AND status IN ('queued', 'running'))";
497const SCHEDULE_ADVANCE: &str = "UPDATE axa_schedule
500 SET due_at = due_at + make_interval(secs => $2)
501 * (floor(EXTRACT(EPOCH FROM now() - due_at)::float8 / $2) + 1),
502 last_job = COALESCE($3, last_job), updated_at = now()
503 WHERE name = $1";
504const SCHEDULE_ADVANCE_TO: &str = "UPDATE axa_schedule
506 SET due_at = $2, last_job = COALESCE($3, last_job), updated_at = now()
507 WHERE name = $1";
508
509pub const SETUP_STATEMENTS: [&str; 20] = [
513 SETUP,
514 SETUP_ATTEMPTS,
515 SETUP_MAX_ATTEMPTS,
516 SETUP_INDEX,
517 SETUP_PRIORITY,
518 SETUP_TIMEOUT,
519 SETUP_TENANT,
520 SETUP_UNIQUE_KEY,
521 SETUP_UNIQUE_INDEX,
522 SETUP_CLAIM_INDEX,
523 SETUP_SCHEDULE,
524 SETUP_SCHEDULE_CRON,
525 SETUP_ACTS,
526 SETUP_ACTS_INDEX,
527 SETUP_ACTS_REFUSE,
528 SETUP_ACTS_ROWS,
529 SETUP_ACTS_TRUNCATE,
530 SETUP_ACTS_ALWAYS,
531 SETUP_NOTIFY_FUNCTION,
532 SETUP_NOTIFY,
533];
534
535pub const MAX_REASON_CHARS: usize = 200;
537
538const MIN_HEARTBEAT: Duration = Duration::from_millis(20);
540
541const MAX_BACKOFF: Duration = Duration::from_hours(1);
543
544const MAX_ERROR: usize = 1024;
546
547#[must_use]
549pub fn backoff(base: Duration, attempts: i32) -> Duration {
550 let doublings = u32::try_from(attempts.saturating_sub(1))
551 .unwrap_or(0)
552 .min(16);
553 base.saturating_mul(1 << doublings).min(MAX_BACKOFF)
554}
555
556pub const MIN_RETRY_AFTER: Duration = Duration::from_secs(1);
558
559#[derive(Debug, Clone)]
564pub struct RetryAfter {
565 delay: Duration,
566 reason: String,
567}
568
569impl RetryAfter {
570 #[must_use]
572 pub fn new(delay: Duration, reason: impl Into<String>) -> Self {
573 Self {
574 delay,
575 reason: reason.into(),
576 }
577 }
578
579 #[must_use]
581 pub const fn delay(&self) -> Duration {
582 self.delay
583 }
584}
585
586impl fmt::Display for RetryAfter {
587 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
588 f.write_str(&self.reason)
589 }
590}
591
592impl std::error::Error for RetryAfter {}
593
594struct Failure {
596 text: String,
597 retry_in: Option<Duration>,
598}
599
600impl Failure {
601 fn from_error<E: fmt::Display + 'static>(error: E) -> Self {
602 let any = &error as &dyn std::any::Any;
603 let retry_in = any
605 .downcast_ref::<RetryAfter>()
606 .or_else(|| {
607 any.downcast_ref::<Box<dyn std::error::Error + Send + Sync>>()
608 .and_then(|boxed| boxed.downcast_ref::<RetryAfter>())
609 })
610 .map(RetryAfter::delay);
611 Self {
612 text: error.to_string(),
613 retry_in,
614 }
615 }
616}
617
618impl From<String> for Failure {
619 fn from(text: String) -> Self {
620 Self {
621 text,
622 retry_in: None,
623 }
624 }
625}
626
627impl fmt::Display for Failure {
628 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
629 f.write_str(&self.text)
630 }
631}
632
633#[must_use]
636pub fn jittered(wait: Duration) -> Duration {
637 let random = Uuid::new_v4().as_u128();
638 #[allow(clippy::cast_precision_loss)]
639 let fraction = (random % 1_000_000) as f64 / 1_000_000.0;
640 wait.mul_f64(0.5 + fraction / 2.0)
641}
642
643#[must_use]
647pub fn retry_wait(base: Duration, attempts: i32, chosen: Option<Duration>) -> Duration {
648 match chosen {
649 Some(delay) => delay.clamp(MIN_RETRY_AFTER, MAX_BACKOFF),
650 None => jittered(backoff(base, attempts)),
651 }
652}
653
654fn cut(mut text: String) -> String {
656 if text.len() > MAX_ERROR {
657 let mut end = MAX_ERROR;
658 while !text.is_char_boundary(end) {
659 end -= 1;
660 }
661 text.truncate(end);
662 }
663 text
664}
665
666fn millis(duration: Duration) -> i64 {
667 i64::try_from(duration.as_millis()).unwrap_or(i64::MAX)
668}
669
670fn from_millis(millis: i64) -> Duration {
671 Duration::from_millis(u64::try_from(millis).unwrap_or(0))
672}
673
674#[derive(Debug, Clone, Copy, PartialEq, Eq)]
676enum When {
677 Now,
678 At(Timestamp),
679 In(Duration),
680}
681
682#[derive(Clone)]
684pub struct NewJob {
685 name: String,
686 args: serde_json::Value,
687 max_attempts: Option<i32>,
688 priority: i16,
689 when: When,
690 timeout: Option<Duration>,
691 tenant: Option<String>,
692 unique_key: Option<String>,
693}
694
695impl fmt::Debug for NewJob {
696 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
697 f.debug_struct("NewJob")
698 .field("name", &self.name)
699 .field("max_attempts", &self.max_attempts)
700 .field("priority", &self.priority)
701 .field("when", &self.when)
702 .field("timeout", &self.timeout)
703 .field("tenant", &self.tenant)
704 .field("unique_key", &self.unique_key)
705 .finish_non_exhaustive()
706 }
707}
708
709impl NewJob {
710 pub fn new(name: impl Into<String>, args: serde_json::Value) -> Self {
713 Self {
714 name: name.into(),
715 args,
716 max_attempts: None,
717 priority: 0,
718 when: When::Now,
719 timeout: None,
720 tenant: None,
721 unique_key: None,
722 }
723 }
724
725 #[must_use]
732 pub fn unique(mut self, key: impl Into<String>) -> Self {
733 self.unique_key = Some(key.into());
734 self
735 }
736
737 #[must_use]
743 pub fn tenant(mut self, tenant: impl Into<String>) -> Self {
744 self.tenant = Some(tenant.into());
745 self
746 }
747
748 #[must_use]
751 pub const fn timeout(mut self, limit: Duration) -> Self {
752 self.timeout = Some(limit);
753 self
754 }
755
756 #[must_use]
758 pub const fn max_attempts(mut self, max_attempts: Option<i32>) -> Self {
759 self.max_attempts = max_attempts;
760 self
761 }
762
763 #[must_use]
766 pub const fn priority(mut self, priority: i16) -> Self {
767 self.priority = priority;
768 self
769 }
770
771 #[must_use]
773 pub const fn run_in(mut self, delay: Duration) -> Self {
774 self.when = When::In(delay);
775 self
776 }
777
778 #[must_use]
780 pub const fn run_at(mut self, at: Timestamp) -> Self {
781 self.when = When::At(at);
782 self
783 }
784
785 #[must_use]
787 pub fn name(&self) -> &str {
788 &self.name
789 }
790
791 #[must_use]
793 pub fn tenant_id(&self) -> Option<&str> {
794 self.tenant.as_deref()
795 }
796
797 #[must_use]
799 pub fn unique_key(&self) -> Option<&str> {
800 self.unique_key.as_deref()
801 }
802}
803
804pub const MAX_TENANT_ID_LEN: usize = 63;
806
807#[must_use]
811pub fn is_tenant_id(id: &str) -> bool {
812 (1..=MAX_TENANT_ID_LEN).contains(&id.len())
813 && !id.starts_with('-')
814 && !id.ends_with('-')
815 && id
816 .bytes()
817 .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'-')
818}
819
820pub async fn enqueue_on<'e, E: PgExecutor<'e>>(executor: E, job: &NewJob) -> Result<Uuid> {
831 if job
832 .tenant
833 .as_deref()
834 .is_some_and(|tenant| !is_tenant_id(tenant))
835 {
836 return Err(Error::NotATenant);
837 }
838 if let Some(key) = job.unique_key.as_deref() {
839 check_code(key, "unique key")?;
840 }
841 let id = Uuid::new_v4();
842 let (at, delay) = match job.when {
843 When::Now => (None, 0.0),
844 When::At(at) => (Some(at), 0.0),
845 When::In(delay) => (None, delay.as_secs_f64()),
846 };
847 let query = sqlx::query(if job.unique_key.is_some() {
848 ENQUEUE_UNIQUE
849 } else {
850 ENQUEUE
851 })
852 .bind(id)
853 .bind(&job.name)
854 .bind(&job.args)
855 .bind(job.max_attempts)
856 .bind(job.priority)
857 .bind(at.map(jiff_sqlx::Timestamp::from))
858 .bind(delay)
859 .bind(job.timeout.map(millis))
860 .bind(job.tenant.as_deref());
861 if let Some(key) = job.unique_key.as_deref() {
862 Ok(query.bind(key).fetch_one(executor).await?.try_get("id")?)
863 } else {
864 query.execute(executor).await?;
865 Ok(id)
866 }
867}
868
869pub async fn enqueue_all_on(connection: &mut PgConnection, jobs: &[NewJob]) -> Result<Vec<Uuid>> {
876 let mut ids = Vec::with_capacity(jobs.len());
877 for job in jobs {
878 ids.push(enqueue_on(&mut *connection, job).await?);
879 }
880 Ok(ids)
881}
882
883fn check_code(text: &str, what: &'static str) -> Result<()> {
885 if text.is_empty()
886 || text.chars().count() > MAX_REASON_CHARS
887 || text.chars().any(char::is_control)
888 {
889 Err(Error::NotACode { what })
890 } else {
891 Ok(())
892 }
893}
894
895pub async fn cancel(
909 transaction: &mut Transaction<'_, Postgres>,
910 id: Uuid,
911 by: &str,
912 reason: &str,
913) -> Result<bool> {
914 act(transaction, CANCEL, id, by, reason).await
915}
916
917pub async fn retry(
930 transaction: &mut Transaction<'_, Postgres>,
931 id: Uuid,
932 by: &str,
933 reason: &str,
934) -> Result<bool> {
935 act(transaction, RETRY_FAILED, id, by, reason).await
936}
937
938async fn act(
940 transaction: &mut Transaction<'_, Postgres>,
941 statement: &'static str,
942 id: Uuid,
943 by: &str,
944 reason: &str,
945) -> Result<bool> {
946 check_code(by, "by")?;
947 check_code(reason, "reason")?;
948 let kept = sqlx::query(statement)
949 .bind(id)
950 .bind(by)
951 .bind(reason)
952 .execute(&mut **transaction)
953 .await?
954 .rows_affected();
955 Ok(kept == 1)
956}
957
958#[derive(Debug, Clone, Copy, PartialEq, Eq)]
960#[non_exhaustive]
961pub enum ActKind {
962 Cancelled,
964 Retried,
966 Released,
968}
969
970impl ActKind {
971 fn parse(text: &str) -> Result<Self> {
972 match text {
973 "cancelled" => Ok(Self::Cancelled),
974 "retried" => Ok(Self::Retried),
975 "released" => Ok(Self::Released),
976 _ => Err(Error::Job("an act with an unknown kind".to_string())),
977 }
978 }
979}
980
981#[derive(Debug, Clone)]
984#[non_exhaustive]
985pub struct Act {
986 pub id: i64,
988 pub job_id: Uuid,
990 pub job_name: String,
992 pub kind: ActKind,
994 pub attempts: i32,
996 pub by: String,
998 pub reason: String,
1000 pub at: Timestamp,
1002}
1003
1004#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1006pub enum JobState {
1007 Queued,
1009 Running,
1011 Completed,
1013 Failed,
1015 Cancelled,
1017 NeedsReview,
1021}
1022
1023impl JobState {
1024 fn parse(text: &str) -> Result<Self> {
1025 match text {
1026 "queued" => Ok(Self::Queued),
1027 "running" => Ok(Self::Running),
1028 "completed" => Ok(Self::Completed),
1029 "failed" => Ok(Self::Failed),
1030 "cancelled" => Ok(Self::Cancelled),
1031 "needs_review" => Ok(Self::NeedsReview),
1032 _ => Err(Error::Job("a job row with an unknown status".to_string())),
1033 }
1034 }
1035}
1036
1037#[derive(Debug, Clone)]
1039#[non_exhaustive]
1040pub struct JobInfo {
1041 pub id: Uuid,
1043 pub name: String,
1045 pub state: JobState,
1047 pub attempts: i32,
1049 pub max_attempts: Option<i32>,
1051 pub priority: i16,
1053 pub timeout: Option<Duration>,
1055 pub tenant: Option<String>,
1057 pub unique_key: Option<String>,
1059 pub error: Option<String>,
1062 pub run_at: Timestamp,
1064 pub started_at: Option<Timestamp>,
1066 pub created_at: Timestamp,
1068 pub updated_at: Timestamp,
1070}
1071
1072#[derive(Debug, Clone, Copy, Default, PartialEq)]
1074#[non_exhaustive]
1075pub struct Counts {
1076 pub ready: i64,
1078 pub waiting: i64,
1080 pub running: i64,
1082 pub completed: i64,
1084 pub failed: i64,
1086 pub cancelled: i64,
1088 pub needs_review: i64,
1091 pub oldest_ready_seconds: f64,
1094}
1095
1096#[derive(Clone)]
1099pub struct Schedule {
1100 name: String,
1101 times: Times,
1102 first: Option<Timestamp>,
1103 job: NewJob,
1104}
1105
1106#[derive(Clone)]
1108enum Times {
1109 Every(Duration),
1110 Cron(Box<croner::Cron>, String),
1112}
1113
1114impl Times {
1115 fn interval(&self) -> Option<Duration> {
1116 match self {
1117 Self::Every(interval) => Some(*interval),
1118 Self::Cron(..) => None,
1119 }
1120 }
1121
1122 fn pattern(&self) -> Option<&str> {
1123 match self {
1124 Self::Every(_) => None,
1125 Self::Cron(_, pattern) => Some(pattern),
1126 }
1127 }
1128}
1129
1130fn next_after(cron: &croner::Cron, now: Timestamp) -> Result<Timestamp> {
1132 cron.find_next_occurrence(&InUtc(now), false)
1133 .map(|next| next.0)
1134 .map_err(|error| Error::Job(format!("the cron pattern has no next time: {error}")))
1135}
1136
1137#[derive(Clone, Copy)]
1141struct InUtc(Timestamp);
1142
1143impl croner::CronDateTime for InUtc {
1144 fn to_civil(&self) -> croner::CivilDateTime {
1145 let time = jiff::tz::TimeZone::UTC.to_datetime(self.0);
1146 croner::CivilDateTime::new(
1147 croner::CivilDate::from_parts_unchecked(
1148 i32::from(time.year()),
1149 time.month().unsigned_abs().into(),
1150 time.day().unsigned_abs().into(),
1151 ),
1152 croner::CivilTime::from_parts_unchecked(
1153 time.hour().unsigned_abs().into(),
1154 time.minute().unsigned_abs().into(),
1155 time.second().unsigned_abs().into(),
1156 ),
1157 )
1158 }
1159
1160 fn civil_weekday(&self) -> croner::Weekday {
1161 let day = jiff::tz::TimeZone::UTC
1162 .to_datetime(self.0)
1163 .weekday()
1164 .to_sunday_zero_offset();
1165 croner::Weekday::from_days_from_sunday(day.unsigned_abs().into())
1166 }
1167
1168 fn resolve_civil(
1169 &self,
1170 civil: croner::CivilDateTime,
1171 ) -> Result<croner::Resolution<Self>, croner::errors::CronError> {
1172 let part =
1173 |value: u32| i8::try_from(value).map_err(|_| croner::errors::CronError::InvalidDate);
1174 let year =
1175 i16::try_from(civil.year()).map_err(|_| croner::errors::CronError::InvalidDate)?;
1176 let time = jiff::civil::DateTime::new(
1177 year,
1178 part(civil.month())?,
1179 part(civil.day())?,
1180 part(civil.hour())?,
1181 part(civil.minute())?,
1182 part(civil.second())?,
1183 0,
1184 )
1185 .and_then(|time| jiff::tz::TimeZone::UTC.to_timestamp(time))
1186 .map_err(|_| croner::errors::CronError::InvalidDate)?;
1187 Ok(croner::Resolution::Single(Self(time)))
1188 }
1189
1190 fn checked_add_seconds(&self, seconds: i64) -> Option<Self> {
1191 self.0
1192 .checked_add(jiff::SignedDuration::from_secs(seconds))
1193 .ok()
1194 .map(Self)
1195 }
1196
1197 fn cmp_instant(&self, other: &Self) -> std::cmp::Ordering {
1198 self.0.cmp(&other.0)
1199 }
1200}
1201
1202fn time(row: &PgRow, column: &str) -> Result<Timestamp> {
1204 Ok(row.try_get::<jiff_sqlx::Timestamp, _>(column)?.to_jiff())
1205}
1206
1207fn time_or_none(row: &PgRow, column: &str) -> Result<Option<Timestamp>> {
1209 Ok(row
1210 .try_get::<Option<jiff_sqlx::Timestamp>, _>(column)?
1211 .map(jiff_sqlx::Timestamp::to_jiff))
1212}
1213
1214impl fmt::Debug for Schedule {
1215 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1216 f.debug_struct("Schedule")
1217 .field("name", &self.name)
1218 .field("interval", &self.times.interval())
1219 .field("cron", &self.times.pattern())
1220 .field("first", &self.first)
1221 .field("job", &self.job)
1222 .finish()
1223 }
1224}
1225
1226impl Schedule {
1227 pub fn every(name: impl Into<String>, interval: Duration, job: NewJob) -> Self {
1236 let name = checked_name(name.into());
1237 assert!(
1238 interval >= Duration::from_secs(1),
1239 "the schedule {name} needs an interval of at least a second"
1240 );
1241 Self {
1242 name,
1243 times: Times::Every(interval),
1244 first: None,
1245 job: NewJob {
1246 when: When::Now,
1247 ..job
1248 },
1249 }
1250 }
1251
1252 pub fn cron(name: impl Into<String>, pattern: &str, job: NewJob) -> Self {
1264 let name = checked_name(name.into());
1265 let cron: croner::Cron = pattern
1266 .parse()
1267 .unwrap_or_else(|error| panic!("the schedule {name} has a bad cron pattern: {error}"));
1268 assert!(
1269 next_after(&cron, Timestamp::now()).is_ok(),
1270 "the cron pattern of the schedule {name} names no time to come"
1271 );
1272 Self {
1273 name,
1274 times: Times::Cron(Box::new(cron), pattern.to_string()),
1275 first: None,
1276 job: NewJob {
1277 when: When::Now,
1278 ..job
1279 },
1280 }
1281 }
1282
1283 #[must_use]
1288 pub const fn first_at(mut self, first: Timestamp) -> Self {
1289 self.first = Some(first);
1290 self
1291 }
1292
1293 #[must_use]
1295 pub fn interval(&self) -> Option<Duration> {
1296 self.times.interval()
1297 }
1298
1299 #[must_use]
1301 pub fn cron_pattern(&self) -> Option<&str> {
1302 self.times.pattern()
1303 }
1304
1305 #[must_use]
1307 pub fn name(&self) -> &str {
1308 &self.name
1309 }
1310}
1311
1312fn checked_name(name: String) -> String {
1314 assert!(
1315 !name.is_empty() && name.len() <= 200,
1316 "a schedule name must be 1 to 200 characters"
1317 );
1318 name
1319}
1320
1321#[derive(Debug, Clone)]
1323#[non_exhaustive]
1324pub struct ScheduleInfo {
1325 pub name: String,
1327 pub interval: Option<Duration>,
1329 pub cron: Option<String>,
1331 pub due_at: Timestamp,
1333 pub last_job: Option<Uuid>,
1335 pub last_state: Option<JobState>,
1337 pub last_error: Option<String>,
1339 pub seen_at: Timestamp,
1341 pub archived_at: Option<Timestamp>,
1344 pub created_at: Timestamp,
1346}
1347
1348#[derive(Debug, Clone)]
1350pub struct QueueOptions {
1351 pub workers: usize,
1353 pub poll_interval: Duration,
1355 pub stale_minutes: i32,
1358 pub heartbeat_interval: Duration,
1360 pub max_attempts: i32,
1363 pub retry_backoff: Duration,
1365 pub retention_days: i32,
1367 pub maintenance_interval: Duration,
1369}
1370
1371impl Default for QueueOptions {
1372 fn default() -> Self {
1373 Self {
1374 workers: 2,
1375 poll_interval: Duration::from_secs(1),
1376 stale_minutes: 60,
1377 heartbeat_interval: Duration::from_mins(1),
1378 max_attempts: 1,
1379 retry_backoff: Duration::from_secs(30),
1380 retention_days: 7,
1381 maintenance_interval: Duration::from_mins(5),
1382 }
1383 }
1384}
1385
1386pub struct Queue {
1388 pool: PgPool,
1389 handlers: HashMap<String, Handler>,
1390 limits: HashMap<String, Arc<Semaphore>>,
1391 schedules: Vec<Schedule>,
1392 options: QueueOptions,
1393}
1394
1395impl fmt::Debug for Queue {
1396 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1397 f.debug_struct("Queue")
1398 .field("handlers", &self.handlers.len())
1399 .field("limits", &self.limits.len())
1400 .field("schedules", &self.schedules.len())
1401 .field("options", &self.options)
1402 .finish_non_exhaustive()
1403 }
1404}
1405
1406struct Claimed {
1408 id: Uuid,
1409 name: String,
1410 args: serde_json::Value,
1411 attempts: i32,
1412 limit: i32,
1413 timeout: Option<Duration>,
1414 tenant: Option<String>,
1415}
1416
1417enum Outcome {
1419 Done(Result<(), Failure>),
1421 Lost(String),
1423}
1424
1425impl Queue {
1426 #[must_use]
1429 pub fn from_pool(pool: PgPool, options: QueueOptions) -> Self {
1430 Self {
1431 pool,
1432 handlers: HashMap::new(),
1433 limits: HashMap::new(),
1434 schedules: Vec::new(),
1435 options,
1436 }
1437 }
1438
1439 async fn open(uri: &str, options: QueueOptions) -> Result<Self> {
1441 let loops = u32::try_from(options.workers).unwrap_or(u32::MAX);
1442 let pool = PgPoolOptions::new()
1443 .max_connections(loops.saturating_add(3))
1445 .connect(uri)
1446 .await?;
1447 Ok(Self::from_pool(pool, options))
1448 }
1449
1450 pub async fn connect_existing(uri: &str, options: QueueOptions) -> Result<Self> {
1460 let queue = Self::open(uri, options).await?;
1461 queue.check().await?;
1462 Ok(queue)
1463 }
1464
1465 pub async fn connect(uri: &str, options: QueueOptions) -> Result<Self> {
1472 let queue = Self::open(uri, options).await?;
1473 let mut setup = queue.pool.begin().await?;
1478 sqlx::query("SELECT pg_advisory_xact_lock($1)")
1479 .bind(SETUP_LOCK)
1480 .execute(&mut *setup)
1481 .await?;
1482 for statement in SETUP_STATEMENTS {
1483 sqlx::query(statement).execute(&mut *setup).await?;
1484 }
1485 setup.commit().await?;
1486 Ok(queue)
1487 }
1488
1489 pub async fn check(&self) -> Result<()> {
1497 sqlx::query(
1498 "SELECT attempts, max_attempts, priority, timeout_ms, tenant, unique_key FROM axa_queue LIMIT 0",
1499 )
1500 .execute(&self.pool)
1501 .await?;
1502 sqlx::query(
1503 "SELECT name, due_at, last_job, interval_ms, cron, seen_at, archived_at FROM axa_schedule LIMIT 0",
1504 )
1505 .execute(&self.pool)
1506 .await?;
1507 sqlx::query(
1508 "SELECT id, job_id, job_name, act, attempts, by, reason, at FROM axa_job_acts LIMIT 0",
1509 )
1510 .execute(&self.pool)
1511 .await?;
1512 let mut missing: Vec<String> = sqlx::query_scalar(MISSING_TRIGGERS)
1513 .bind(ACTS_TRIGGERS.to_vec())
1514 .fetch_all(&self.pool)
1515 .await?;
1516 let unique_index: bool =
1517 sqlx::query_scalar("SELECT to_regclass('axa_queue_unique') IS NOT NULL")
1518 .fetch_one(&self.pool)
1519 .await?;
1520 if !unique_index {
1521 missing.push("axa_queue_unique".to_string());
1522 }
1523 if missing.is_empty() {
1524 Ok(())
1525 } else {
1526 Err(Error::Database(sqlx::Error::Configuration(
1527 format!(
1528 "the job queue is missing, or has turned off, {}: run SETUP_STATEMENTS",
1529 missing.join(", ")
1530 )
1531 .into(),
1532 )))
1533 }
1534 }
1535
1536 #[must_use]
1539 pub const fn pool(&self) -> &PgPool {
1540 &self.pool
1541 }
1542
1543 #[must_use]
1545 pub const fn options(&self) -> &QueueOptions {
1546 &self.options
1547 }
1548
1549 pub fn handle<F, Fut, E>(&mut self, name: impl Into<String>, handler: F)
1556 where
1557 F: Fn(serde_json::Value) -> Fut + Send + Sync + 'static,
1558 Fut: Future<Output = std::result::Result<(), E>> + Send + 'static,
1559 E: fmt::Display + 'static,
1560 {
1561 let handler = Arc::new(handler);
1562 let run: Handler = Arc::new(move |tenant, args| {
1563 if tenant.is_some() {
1564 return Box::pin(std::future::ready(Err(NO_TENANT_HANDLER
1565 .to_string()
1566 .into())));
1567 }
1568 let job = handler(args);
1569 Box::pin(async move { job.await.map_err(Failure::from_error) })
1570 });
1571 self.handlers.insert(name.into(), run);
1572 }
1573
1574 pub fn handle_with_tenant<F, Fut, E>(&mut self, name: impl Into<String>, handler: F)
1579 where
1580 F: Fn(Option<String>, serde_json::Value) -> Fut + Send + Sync + 'static,
1581 Fut: Future<Output = std::result::Result<(), E>> + Send + 'static,
1582 E: fmt::Display + 'static,
1583 {
1584 let handler = Arc::new(handler);
1585 let run: Handler = Arc::new(move |tenant, args| {
1586 let job = handler(tenant, args);
1587 Box::pin(async move { job.await.map_err(Failure::from_error) })
1588 });
1589 self.handlers.insert(name.into(), run);
1590 }
1591
1592 pub fn limit(&mut self, name: impl Into<String>, jobs: usize) {
1595 self.limits
1596 .insert(name.into(), Arc::new(Semaphore::new(jobs.max(1))));
1597 }
1598
1599 pub fn schedule(&mut self, schedule: Schedule) {
1605 assert!(
1606 self.schedules.iter().all(|s| s.name != schedule.name),
1607 "the schedule {} was added twice",
1608 schedule.name
1609 );
1610 self.schedules.push(schedule);
1611 }
1612
1613 pub async fn enqueue(&self, name: &str, args: serde_json::Value) -> Result<Uuid> {
1619 enqueue_on(&self.pool, &NewJob::new(name, args)).await
1620 }
1621
1622 pub async fn enqueue_limited(
1628 &self,
1629 name: &str,
1630 args: serde_json::Value,
1631 max_attempts: Option<i32>,
1632 ) -> Result<Uuid> {
1633 enqueue_on(
1634 &self.pool,
1635 &NewJob::new(name, args).max_attempts(max_attempts),
1636 )
1637 .await
1638 }
1639
1640 pub async fn enqueue_job(&self, job: &NewJob) -> Result<Uuid> {
1646 enqueue_on(&self.pool, job).await
1647 }
1648
1649 pub async fn enqueue_all(&self, jobs: &[NewJob]) -> Result<Vec<Uuid>> {
1655 let mut transaction = self.pool.begin().await?;
1656 let ids = enqueue_all_on(&mut transaction, jobs).await?;
1657 transaction.commit().await?;
1658 Ok(ids)
1659 }
1660
1661 pub async fn job(&self, id: Uuid) -> Result<Option<JobInfo>> {
1668 let Some(row) = sqlx::query(STATUS)
1669 .bind(id)
1670 .fetch_optional(&self.pool)
1671 .await?
1672 else {
1673 return Ok(None);
1674 };
1675 Ok(Some(JobInfo {
1676 id: row.try_get("id")?,
1677 name: row.try_get("name")?,
1678 state: JobState::parse(row.try_get::<&str, _>("status")?)?,
1679 attempts: row.try_get("attempts")?,
1680 max_attempts: row.try_get("max_attempts")?,
1681 priority: row.try_get("priority")?,
1682 timeout: row
1683 .try_get::<Option<i64>, _>("timeout_ms")?
1684 .map(from_millis),
1685 tenant: row.try_get("tenant")?,
1686 unique_key: row.try_get("unique_key")?,
1687 error: row.try_get("error")?,
1688 run_at: time(&row, "run_at")?,
1689 started_at: time_or_none(&row, "started_at")?,
1690 created_at: time(&row, "created_at")?,
1691 updated_at: time(&row, "updated_at")?,
1692 }))
1693 }
1694
1695 pub async fn acts(&self, id: Uuid) -> Result<Vec<Act>> {
1703 let rows = sqlx::query(ACTS).bind(id).fetch_all(&self.pool).await?;
1704 rows.iter()
1705 .map(|row| {
1706 Ok(Act {
1707 id: row.try_get("id")?,
1708 job_id: row.try_get("job_id")?,
1709 job_name: row.try_get("job_name")?,
1710 kind: ActKind::parse(row.try_get::<&str, _>("act")?)?,
1711 attempts: row.try_get("attempts")?,
1712 by: row.try_get("by")?,
1713 reason: row.try_get("reason")?,
1714 at: time(row, "at")?,
1715 })
1716 })
1717 .collect()
1718 }
1719
1720 pub async fn counts(&self) -> Result<Counts> {
1726 let row = sqlx::query(COUNTS).fetch_one(&self.pool).await?;
1727 Ok(Counts {
1728 ready: row.try_get("ready")?,
1729 waiting: row.try_get("waiting")?,
1730 running: row.try_get("running")?,
1731 completed: row.try_get("completed")?,
1732 failed: row.try_get("failed")?,
1733 cancelled: row.try_get("cancelled")?,
1734 needs_review: row.try_get("needs_review")?,
1735 oldest_ready_seconds: row.try_get::<Option<f64>, _>("oldest")?.unwrap_or(0.0),
1736 })
1737 }
1738
1739 pub async fn ping(&self) -> Result<()> {
1745 sqlx::query("SELECT 1").execute(&self.pool).await?;
1746 Ok(())
1747 }
1748
1749 pub async fn requeue_stale(&self) -> Result<u64> {
1756 sqlx::query(FAIL_STALE)
1757 .bind(self.options.stale_minutes)
1758 .bind(self.options.max_attempts)
1759 .execute(&self.pool)
1760 .await?;
1761 let result = sqlx::query(REQUEUE_STALE)
1762 .bind(self.options.stale_minutes)
1763 .bind(self.options.max_attempts)
1764 .execute(&self.pool)
1765 .await?;
1766 Ok(result.rows_affected())
1767 }
1768
1769 pub async fn purge_finished(&self) -> Result<u64> {
1776 let result = sqlx::query(PURGE)
1777 .bind(self.options.retention_days)
1778 .execute(&self.pool)
1779 .await?;
1780 Ok(result.rows_affected())
1781 }
1782
1783 pub async fn tick_schedules(&self) -> Result<usize> {
1791 let mut queued = 0;
1792 for schedule in &self.schedules {
1793 if self.tick(schedule).await? {
1794 queued += 1;
1795 }
1796 }
1797 Ok(queued)
1798 }
1799
1800 async fn tick(&self, schedule: &Schedule) -> Result<bool> {
1802 let first = match &schedule.times {
1805 Times::Every(_) => schedule.first,
1806 Times::Cron(cron, _) => {
1807 let now: jiff_sqlx::Timestamp = sqlx::query_scalar("SELECT now()")
1808 .fetch_one(&self.pool)
1809 .await?;
1810 Some(next_after(cron, now.to_jiff())?)
1811 }
1812 };
1813 sqlx::query(SCHEDULE_CREATE)
1814 .bind(&schedule.name)
1815 .bind(first.map(jiff_sqlx::Timestamp::from))
1816 .bind(schedule.times.interval().map(millis))
1817 .bind(schedule.times.pattern())
1818 .execute(&self.pool)
1819 .await?;
1820 let mut transaction = self.pool.begin().await?;
1821 let Some(row) = sqlx::query(SCHEDULE_LOCK)
1823 .bind(&schedule.name)
1824 .fetch_optional(&mut *transaction)
1825 .await?
1826 else {
1827 return Ok(false);
1828 };
1829 if !row.try_get::<bool, _>("due")? {
1830 transaction.commit().await?;
1831 return Ok(false);
1832 }
1833 let busy = match row.try_get::<Option<Uuid>, _>("last_job")? {
1834 Some(last) => {
1835 sqlx::query_scalar::<_, bool>(SCHEDULE_BUSY)
1836 .bind(last)
1837 .fetch_one(&mut *transaction)
1838 .await?
1839 }
1840 None => false,
1841 };
1842 let job = if busy {
1843 tracing::info!(schedule = %schedule.name, "schedule skipped, its last job has not finished");
1844 None
1845 } else {
1846 Some(enqueue_on(&mut *transaction, &schedule.job).await?)
1847 };
1848 match &schedule.times {
1849 Times::Every(interval) => {
1850 sqlx::query(SCHEDULE_ADVANCE)
1851 .bind(&schedule.name)
1852 .bind(interval.as_secs_f64())
1853 .bind(job)
1854 .execute(&mut *transaction)
1855 .await?;
1856 }
1857 Times::Cron(cron, _) => {
1858 sqlx::query(SCHEDULE_ADVANCE_TO)
1859 .bind(&schedule.name)
1860 .bind(jiff_sqlx::Timestamp::from(next_after(
1861 cron,
1862 time(&row, "now")?,
1863 )?))
1864 .bind(job)
1865 .execute(&mut *transaction)
1866 .await?;
1867 }
1868 }
1869 transaction.commit().await?;
1870 if job.is_some() {
1871 tracing::debug!(schedule = %schedule.name, "schedule queued its job");
1872 }
1873 Ok(job.is_some())
1874 }
1875
1876 pub async fn archive_schedules(&self) -> Result<u64> {
1883 let names: Vec<&str> = self.schedules.iter().map(|s| s.name.as_str()).collect();
1884 let result = sqlx::query(SCHEDULE_ARCHIVE)
1885 .bind(&names)
1886 .bind(self.options.stale_minutes)
1887 .execute(&self.pool)
1888 .await?;
1889 Ok(result.rows_affected())
1890 }
1891
1892 pub async fn schedules(&self) -> Result<Vec<ScheduleInfo>> {
1898 let rows = sqlx::query(SCHEDULES).fetch_all(&self.pool).await?;
1899 rows.iter()
1900 .map(|row| {
1901 Ok(ScheduleInfo {
1902 name: row.try_get("name")?,
1903 interval: row
1904 .try_get::<Option<i64>, _>("interval_ms")?
1905 .map(from_millis),
1906 cron: row.try_get("cron")?,
1907 due_at: time(row, "due_at")?,
1908 last_job: row.try_get("last_job")?,
1909 last_state: row
1910 .try_get::<Option<&str>, _>("last_status")?
1911 .map(JobState::parse)
1912 .transpose()?,
1913 last_error: row.try_get("last_error")?,
1914 seen_at: time(row, "seen_at")?,
1915 archived_at: time_or_none(row, "archived_at")?,
1916 created_at: time(row, "created_at")?,
1917 })
1918 })
1919 .collect()
1920 }
1921
1922 async fn maintain(&self) {
1925 match self.archive_schedules().await {
1926 Ok(0) => {}
1927 Ok(archived) => tracing::info!(archived, "archived schedules no longer in code"),
1928 Err(error) => tracing::error!(%error, "could not archive schedules"),
1929 }
1930 if let Err(error) = self.requeue_stale().await {
1931 tracing::error!(%error, "could not recover stale jobs");
1932 }
1933 if let Err(error) = self.purge_finished().await {
1934 tracing::error!(%error, "could not delete old jobs");
1935 }
1936 }
1937
1938 async fn supervise(&self, job: JobFuture, claim: &Claimed) -> Outcome {
1942 let mut job = AbortOnDrop(tokio::spawn(job));
1943 let every = self.options.heartbeat_interval.max(MIN_HEARTBEAT);
1944 let stale =
1946 Duration::from_secs(u64::try_from(self.options.stale_minutes).unwrap_or(0) * 60);
1947 let give_up = stale.saturating_sub(every * 2).max(stale / 2);
1950 let mut last_heard = tokio::time::Instant::now();
1951 let beat = || {
1954 tokio::time::timeout(
1955 every,
1956 sqlx::query(HEARTBEAT)
1957 .bind(claim.id)
1958 .bind(claim.attempts)
1959 .execute(&self.pool),
1960 )
1961 };
1962 let mut beating = None;
1963 let mut next_beat = tokio::time::Instant::now() + every;
1964 let mut failing = false;
1965 let limit = claim
1966 .timeout
1967 .map(|timeout| tokio::time::Instant::now() + timeout);
1968 let deadline = async {
1969 match limit {
1970 Some(at) => tokio::time::sleep_until(at).await,
1971 None => std::future::pending().await,
1972 }
1973 };
1974 tokio::pin!(deadline);
1975 loop {
1976 tokio::select! {
1977 finished = &mut job.0 => {
1978 return Outcome::Done(finished.unwrap_or_else(|_| {
1979 Err(Error::Job("the job panicked".to_string()).to_string().into())
1980 }));
1981 }
1982 () = &mut deadline => {
1983 let limit = claim.timeout.unwrap_or_default();
1984 return Outcome::Done(Err(
1985 Error::Job(format!("timed out after {}s", limit.as_secs_f64())).to_string().into(),
1986 ));
1987 }
1988 () = tokio::time::sleep_until(last_heard + give_up), if failing => {
1989 return Outcome::Lost(format!(
1990 "it could not report in for {}s, near the {} minutes after which another worker may take it",
1991 give_up.as_secs(),
1992 self.options.stale_minutes
1993 ));
1994 }
1995 () = tokio::time::sleep_until(next_beat), if beating.is_none() => {
1996 beating = Some(Box::pin(beat()));
1997 }
1998 answer = async {
1999 match beating.as_mut() {
2000 Some(beat) => beat.await,
2001 None => std::future::pending().await,
2002 }
2003 }, if beating.is_some() => {
2004 beating = None;
2005 next_beat = tokio::time::Instant::now() + every;
2006 match answer {
2007 Ok(Ok(done)) if done.rows_affected() == 1 => {
2008 last_heard = tokio::time::Instant::now();
2009 failing = false;
2010 }
2011 Ok(Ok(_)) => return Outcome::Lost("another worker or recovery took its claim".to_string()),
2012 Ok(Err(error)) => {
2013 tracing::warn!(id = %claim.id, %error, "job heartbeat failed");
2014 failing = true;
2015 }
2016 Err(_) => {
2017 tracing::warn!(id = %claim.id, "job heartbeat did not answer in time");
2018 failing = true;
2019 }
2020 }
2021 }
2022 }
2023 }
2024 }
2025
2026 async fn mark_lost(&self, claim: &Claimed, reason: &str) {
2029 let text = Error::Job(format!("stopped: {reason}")).to_string();
2030 let every = self.options.heartbeat_interval.max(MIN_HEARTBEAT);
2031 loop {
2032 match sqlx::query(MARK_LOST)
2033 .bind(claim.id)
2034 .bind(&text)
2035 .execute(&self.pool)
2036 .await
2037 {
2038 Ok(_) => return,
2039 Err(error) => {
2040 tracing::error!(id = %claim.id, %error, "could not mark a lost job for review");
2041 tokio::time::sleep(every).await;
2042 }
2043 }
2044 }
2045 }
2046
2047 fn claimable(&self) -> (Vec<String>, HashMap<String, OwnedSemaphorePermit>) {
2050 let mut places = HashMap::new();
2051 let mut names = Vec::new();
2052 for name in self.handlers.keys() {
2053 match self.limits.get(name) {
2054 None => names.push(name.clone()),
2055 Some(limit) => {
2056 if let Ok(place) = limit.clone().try_acquire_owned() {
2057 places.insert(name.clone(), place);
2058 names.push(name.clone());
2059 }
2060 }
2061 }
2062 }
2063 (names, places)
2064 }
2065
2066 async fn claim(&self, names: &[String]) -> Result<Option<Claimed>> {
2067 let Some(row) = sqlx::query(CLAIM)
2068 .bind(names)
2069 .fetch_optional(&self.pool)
2070 .await?
2071 else {
2072 return Ok(None);
2073 };
2074 Ok(Some(Claimed {
2075 id: row.try_get("id")?,
2076 name: row.try_get("name")?,
2077 args: row.try_get("args")?,
2078 attempts: row.try_get("attempts")?,
2079 limit: row
2080 .try_get::<Option<i32>, _>("max_attempts")?
2081 .unwrap_or(self.options.max_attempts),
2082 timeout: row
2083 .try_get::<Option<i64>, _>("timeout_ms")?
2084 .map(from_millis),
2085 tenant: row.try_get("tenant")?,
2086 }))
2087 }
2088
2089 pub async fn run_one(&self) -> Result<bool> {
2096 let (names, mut places) = self.claimable();
2097 if names.is_empty() {
2098 return Ok(false);
2099 }
2100 let Some(job) = self.claim(&names).await? else {
2101 return Ok(false);
2102 };
2103 let _place = places.remove(&job.name);
2105 drop(places);
2106 let outcome = match self.handlers.get(&job.name) {
2107 Some(handler) => {
2108 let run = handler(job.tenant.clone(), job.args.clone());
2109 self.supervise(run, &job).await
2110 }
2111 None => Outcome::Done(Err(Error::Job(format!("no handler for job {}", job.name))
2112 .to_string()
2113 .into())),
2114 };
2115 let (id, name, attempts) = (job.id, job.name.as_str(), job.attempts);
2116 let finished = match outcome {
2117 Outcome::Lost(reason) => {
2118 tracing::error!(job = %name, %id, attempts, %reason, "job stopped, it lost its claim");
2119 self.mark_lost(&job, &reason).await;
2120 return Ok(true);
2121 }
2122 Outcome::Done(Ok(())) => {
2123 sqlx::query(FINISH)
2124 .bind(id)
2125 .bind(attempts)
2126 .bind("completed")
2127 .bind(None::<String>)
2128 .execute(&self.pool)
2129 .await?
2130 }
2131 Outcome::Done(Err(error)) if attempts < job.limit => {
2132 tracing::warn!(job = %name, %id, attempts, %error, "job failed, will retry");
2133 let wait = retry_wait(self.options.retry_backoff, attempts, error.retry_in);
2134 sqlx::query(RETRY)
2135 .bind(id)
2136 .bind(attempts)
2137 .bind(cut(error.text))
2138 .bind(wait.as_secs_f64())
2139 .execute(&self.pool)
2140 .await?
2141 }
2142 Outcome::Done(Err(error)) => {
2143 tracing::error!(job = %name, %id, attempts, %error, "job failed");
2144 sqlx::query(FINISH)
2145 .bind(id)
2146 .bind(attempts)
2147 .bind("failed")
2148 .bind(cut(error.text))
2149 .execute(&self.pool)
2150 .await?
2151 }
2152 };
2153 if finished.rows_affected() == 0 {
2154 tracing::error!(job = %name, %id, "job finished after losing its claim");
2157 self.mark_lost(
2158 &job,
2159 "it finished after another worker or recovery took its claim",
2160 )
2161 .await;
2162 }
2163 Ok(true)
2164 }
2165
2166 pub async fn run(self: Arc<Self>, shutdown: watch::Receiver<bool>) {
2172 let mut loops = Vec::new();
2173 loops.push(AbortOnDrop(tokio::spawn(every_until(
2174 shutdown.clone(),
2175 self.options.maintenance_interval,
2176 {
2177 let queue = self.clone();
2178 move || {
2179 let queue = queue.clone();
2180 async move { queue.maintain().await }
2181 }
2182 },
2183 ))));
2184 if !self.schedules.is_empty() {
2185 let queue = self.clone();
2186 loops.push(AbortOnDrop(tokio::spawn(every_until(
2187 shutdown.clone(),
2188 self.options.poll_interval,
2189 move || {
2190 let queue = queue.clone();
2191 async move {
2192 if let Err(error) = queue.tick_schedules().await {
2193 tracing::error!(%error, "could not queue scheduled jobs");
2194 }
2195 }
2196 },
2197 ))));
2198 }
2199 let wake = Arc::new(Notify::new());
2200 loops.push(AbortOnDrop(tokio::spawn(listen(
2201 self.pool.clone(),
2202 wake.clone(),
2203 self.options.poll_interval,
2204 shutdown.clone(),
2205 ))));
2206 for _ in 0..self.options.workers.max(1) {
2207 let queue = self.clone();
2208 let wake = wake.clone();
2209 let mut shutdown = shutdown.clone();
2210 loops.push(AbortOnDrop(tokio::spawn(async move {
2211 while !*shutdown.borrow() {
2212 let round = async {
2213 queue.run_one().await.unwrap_or_else(|error| {
2214 tracing::error!(%error, "job queue error");
2215 false
2216 })
2217 };
2218 work_or_wait(&wake, queue.options.poll_interval, &mut shutdown, round).await;
2219 }
2220 })));
2221 }
2222 for job_loop in &mut loops {
2223 let _ = (&mut job_loop.0).await;
2224 }
2225 }
2226
2227 #[must_use]
2229 pub fn handled(&self) -> HashSet<&str> {
2230 self.handlers.keys().map(String::as_str).collect()
2231 }
2232}
2233
2234async fn work_or_wait(
2238 wake: &Notify,
2239 poll: Duration,
2240 shutdown: &mut watch::Receiver<bool>,
2241 round: impl Future<Output = bool>,
2242) {
2243 let woken = wake.notified();
2244 tokio::pin!(woken);
2245 woken.as_mut().enable();
2246 if !round.await {
2247 tokio::select! {
2248 () = tokio::time::sleep(poll) => {},
2249 () = woken => {},
2250 _ = shutdown.changed() => {},
2251 }
2252 }
2253}
2254
2255async fn listen(
2258 pool: PgPool,
2259 wake: Arc<Notify>,
2260 gap: Duration,
2261 mut shutdown: watch::Receiver<bool>,
2262) {
2263 while !*shutdown.borrow() {
2264 match sqlx::postgres::PgListener::connect_with(&pool).await {
2265 Ok(mut listener) => match listener.listen(NOTIFY_CHANNEL).await {
2266 Ok(()) => loop {
2267 tokio::select! {
2268 notice = listener.try_recv() => match notice {
2269 Ok(_) => wake.notify_waiters(),
2272 Err(error) => {
2273 tracing::warn!(%error, "job queue listener failed, polling");
2274 break;
2275 }
2276 },
2277 _ = shutdown.changed() => return,
2278 }
2279 },
2280 Err(error) => tracing::warn!(%error, "job queue could not listen, polling"),
2281 },
2282 Err(error) => tracing::warn!(%error, "job queue could not listen, polling"),
2283 }
2284 tokio::select! {
2285 () = tokio::time::sleep(gap) => {},
2286 _ = shutdown.changed() => {},
2287 }
2288 }
2289}
2290
2291async fn every_until<F, Fut>(mut shutdown: watch::Receiver<bool>, gap: Duration, round: F)
2293where
2294 F: Fn() -> Fut,
2295 Fut: Future<Output = ()>,
2296{
2297 while !*shutdown.borrow() {
2298 round().await;
2299 tokio::select! {
2300 () = tokio::time::sleep(gap) => {},
2301 _ = shutdown.changed() => {},
2302 }
2303 }
2304}
2305
2306struct AbortOnDrop<T>(tokio::task::JoinHandle<T>);
2309
2310impl<T> Drop for AbortOnDrop<T> {
2311 fn drop(&mut self) {
2312 self.0.abort();
2313 }
2314}
2315
2316#[cfg(test)]
2317mod tests {
2318 use super::*;
2319
2320 #[tokio::test]
2321 async fn a_wake_during_a_round_that_found_nothing_is_not_lost() {
2322 let wake = Notify::new();
2323 let (_stop, mut shutdown) = watch::channel(false);
2324 let round = async {
2326 wake.notify_waiters();
2327 false
2328 };
2329 let waited = tokio::time::timeout(
2330 Duration::from_secs(5),
2331 work_or_wait(&wake, Duration::from_hours(1), &mut shutdown, round),
2332 )
2333 .await;
2334 assert!(
2335 waited.is_ok(),
2336 "the wake was lost and the loop waited for its poll"
2337 );
2338 }
2339
2340 #[test]
2341 fn each_retry_waits_twice_as_long_up_to_a_limit() {
2342 let base = Duration::from_secs(30);
2343 assert_eq!(backoff(base, 1), base);
2344 assert_eq!(backoff(base, 2), base * 2);
2345 assert_eq!(backoff(base, 3), base * 4);
2346 assert_eq!(backoff(base, 1_000), MAX_BACKOFF);
2347 }
2348
2349 #[test]
2350 fn a_retry_waits_a_jittered_backoff_or_the_delay_the_job_chose() {
2351 let base = Duration::from_secs(30);
2352 for _ in 0..200 {
2353 let wait = retry_wait(base, 2, None);
2354 assert!(wait >= base && wait <= base * 2, "{wait:?}");
2355 }
2356 let waits: HashSet<_> = (0..20).map(|_| retry_wait(base, 1, None)).collect();
2357 assert!(waits.len() > 1, "the waits are spread");
2358 assert_eq!(retry_wait(Duration::ZERO, 3, None), Duration::ZERO);
2359 let chosen = Some(Duration::from_secs(90));
2360 assert_eq!(retry_wait(base, 1, chosen), Duration::from_secs(90));
2361 assert_eq!(retry_wait(base, 1, Some(Duration::ZERO)), MIN_RETRY_AFTER);
2362 assert_eq!(
2363 retry_wait(base, 1, Some(Duration::from_hours(9))),
2364 MAX_BACKOFF
2365 );
2366 }
2367
2368 #[test]
2369 fn a_retry_after_error_carries_its_delay_and_others_none() {
2370 let chosen = Failure::from_error(RetryAfter::new(Duration::from_secs(7), "busy"));
2371 assert_eq!(
2372 (chosen.text.as_str(), chosen.retry_in),
2373 ("busy", Some(Duration::from_secs(7)))
2374 );
2375 let boxed: Box<dyn std::error::Error + Send + Sync> =
2376 Box::new(RetryAfter::new(Duration::from_secs(8), "boxed"));
2377 assert_eq!(
2378 Failure::from_error(boxed).retry_in,
2379 Some(Duration::from_secs(8))
2380 );
2381 let plain = Failure::from_error("broken".to_string());
2382 assert_eq!((plain.text.as_str(), plain.retry_in), ("broken", None));
2383 }
2384
2385 #[test]
2386 fn the_debug_text_leaves_out_arguments() {
2387 let job = NewJob::new("Report", serde_json::json!({ "nhs": "943 476 5919" }));
2388 let schedule = Schedule::every("nightly", Duration::from_hours(1), job.clone());
2389 let cron = Schedule::cron("at-two", "0 2 * * *", job.clone());
2390 for text in [
2391 format!("{job:?}"),
2392 format!("{schedule:?}"),
2393 format!("{cron:?}"),
2394 ] {
2395 assert!(text.contains("Report"), "{text}");
2396 assert!(!text.contains("943"), "{text}");
2397 }
2398 }
2399
2400 #[test]
2401 fn a_by_or_reason_that_is_not_a_code_is_refused() {
2402 assert!(check_code("ops:alice", "by").is_ok());
2403 assert!(check_code(&"é".repeat(MAX_REASON_CHARS), "reason").is_ok());
2404 for bad in [
2405 String::new(),
2406 "é".repeat(MAX_REASON_CHARS + 1),
2407 "two\nlines".to_string(),
2408 "a\ttab".to_string(),
2409 ] {
2410 let error = check_code(&bad, "reason").unwrap_err();
2411 assert!(matches!(error, Error::NotACode { what: "reason" }));
2412 assert!(!error.to_string().contains("lines"), "the text is left out");
2413 }
2414 }
2415
2416 #[test]
2417 fn a_long_error_is_cut_on_a_character_boundary() {
2418 let text = "é".repeat(MAX_ERROR);
2419 let kept = cut(text);
2420 assert!(kept.len() <= MAX_ERROR);
2421 assert!(kept.chars().all(|c| c == 'é'));
2422 assert_eq!(cut("short".to_string()), "short");
2423 }
2424
2425 #[test]
2426 #[should_panic(expected = "at least a second")]
2427 fn a_schedule_under_a_second_is_refused_at_boot() {
2428 let _ = Schedule::every(
2429 "fast",
2430 Duration::from_millis(10),
2431 NewJob::new("J", serde_json::Value::Null),
2432 );
2433 }
2434
2435 #[test]
2436 #[should_panic(expected = "bad cron pattern")]
2437 fn a_bad_cron_pattern_is_refused_at_boot() {
2438 let _ = Schedule::cron(
2439 "bad",
2440 "61 * * * *",
2441 NewJob::new("J", serde_json::Value::Null),
2442 );
2443 }
2444
2445 #[test]
2446 fn a_cron_schedule_names_its_next_times_in_utc() {
2447 let schedule = Schedule::cron(
2448 "weekdays",
2449 "0 9 * * MON-FRI",
2450 NewJob::new("J", serde_json::Value::Null),
2451 );
2452 assert_eq!(schedule.cron_pattern(), Some("0 9 * * MON-FRI"));
2453 assert_eq!(schedule.interval(), None);
2454 let Times::Cron(cron, _) = &schedule.times else {
2455 panic!("a cron schedule")
2456 };
2457 let friday: Timestamp = "2026-11-13T09:00:00Z".parse().unwrap();
2459 let monday: Timestamp = "2026-11-16T09:00:00Z".parse().unwrap();
2460 assert_eq!(next_after(cron, friday).unwrap(), monday);
2461 assert_eq!(
2462 Schedule::every(
2463 "e",
2464 Duration::from_secs(5),
2465 NewJob::new("J", serde_json::Value::Null)
2466 )
2467 .interval(),
2468 Some(Duration::from_secs(5))
2469 );
2470 }
2471
2472 #[test]
2473 fn a_cron_schedule_counts_in_utc_across_a_month_end_and_a_clock_change() {
2474 let next = |pattern: &str, after: &str| {
2475 let cron: croner::Cron = pattern.parse().unwrap();
2476 next_after(&cron, after.parse().unwrap())
2477 .unwrap()
2478 .to_string()
2479 };
2480 assert_eq!(
2482 next("0 0 31 * *", "2026-11-15T00:00:00Z"),
2483 "2026-12-31T00:00:00Z"
2484 );
2485 assert_eq!(
2486 next("30 23 * * *", "2026-12-31T23:30:00Z"),
2487 "2027-01-01T23:30:00Z"
2488 );
2489 assert_eq!(
2490 next("0 12 29 2 *", "2026-03-01T00:00:00Z"),
2491 "2028-02-29T12:00:00Z"
2492 );
2493 assert_eq!(
2497 next("30 1 * * *", "2026-03-28T01:30:00Z"),
2498 "2026-03-29T01:30:00Z"
2499 );
2500 assert_eq!(
2501 next("30 1 * * *", "2026-10-25T01:30:00Z"),
2502 "2026-10-26T01:30:00Z"
2503 );
2504 assert_eq!(
2505 next("0 6 * * *", "2026-11-01T06:00:00Z"),
2506 "2026-11-02T06:00:00Z"
2507 );
2508 assert_eq!(
2510 next("* * * * * *", "2026-11-15T00:00:00.5Z"),
2511 "2026-11-15T00:00:01Z"
2512 );
2513 }
2514
2515 #[test]
2516 #[should_panic(expected = "1 to 200 characters")]
2517 fn a_schedule_with_no_name_is_refused_at_boot() {
2518 let _ = Schedule::every(
2519 "",
2520 Duration::from_secs(1),
2521 NewJob::new("J", serde_json::Value::Null),
2522 );
2523 }
2524
2525 #[tokio::test]
2526 #[should_panic(expected = "added twice")]
2527 async fn a_schedule_added_twice_is_refused_at_boot() {
2528 let pool = PgPoolOptions::new()
2529 .connect_lazy("postgres://u@localhost/none")
2530 .unwrap();
2531 let mut queue = Queue::from_pool(pool, QueueOptions::default());
2532 let job = NewJob::new("J", serde_json::Value::Null);
2533 queue.schedule(Schedule::every("a", Duration::from_secs(5), job.clone()));
2534 queue.schedule(Schedule::every("a", Duration::from_secs(9), job));
2535 }
2536
2537 #[test]
2538 fn a_schedule_ignores_a_delay_on_its_job() {
2539 let job = NewJob::new("J", serde_json::Value::Null).run_in(Duration::from_hours(1));
2540 let schedule = Schedule::every("s", Duration::from_secs(5), job);
2541 assert_eq!(schedule.job.when, When::Now);
2542 }
2543}