1use std::{
141 collections::{HashMap, HashSet},
142 fmt,
143 future::Future,
144 pin::Pin,
145 sync::Arc,
146 time::Duration,
147};
148
149use sqlx::{PgConnection, PgExecutor, PgPool, Postgres, Row, Transaction, postgres::PgPoolOptions};
150use tokio::sync::{OwnedSemaphorePermit, Semaphore, watch};
151use uuid::Uuid;
152
153pub use sqlx::types::chrono::{DateTime, Utc};
154
155pub type Result<T, E = Error> = std::result::Result<T, E>;
157
158#[derive(Debug)]
160#[non_exhaustive]
161pub enum Error {
162 Database(sqlx::Error),
164 Encode(serde_json::Error),
166 Job(String),
168 NotACode {
171 what: &'static str,
173 },
174 NotATenant,
176}
177
178impl fmt::Display for Error {
179 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
180 match self {
181 Self::Database(error) => error.fmt(f),
182 Self::Encode(error) => error.fmt(f),
183 Self::Job(text) => write!(f, "worker error: {text}"),
184 Self::NotACode { what } => write!(
185 f,
186 "`{what}` must be 1 to {MAX_REASON_CHARS} characters with no line breaks"
187 ),
188 Self::NotATenant => f.write_str(
189 "a job's tenant must be 1 to 63 lower-case letters, digits, and hyphens, \
190 not starting or ending with a hyphen",
191 ),
192 }
193 }
194}
195
196impl std::error::Error for Error {
197 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
198 match self {
199 Self::Database(error) => Some(error),
200 Self::Encode(error) => Some(error),
201 Self::Job(_) | Self::NotACode { .. } | Self::NotATenant => None,
202 }
203 }
204}
205
206impl From<sqlx::Error> for Error {
207 fn from(error: sqlx::Error) -> Self {
208 Self::Database(error)
209 }
210}
211
212impl From<serde_json::Error> for Error {
213 fn from(error: serde_json::Error) -> Self {
214 Self::Encode(error)
215 }
216}
217
218type JobFuture = Pin<Box<dyn Future<Output = Result<(), String>> + Send>>;
219type Handler = Arc<dyn Fn(Option<String>, serde_json::Value) -> JobFuture + Send + Sync>;
220
221const SETUP: &str = "CREATE TABLE IF NOT EXISTS axa_queue (
222 id UUID PRIMARY KEY,
223 name TEXT NOT NULL,
224 args JSONB NOT NULL,
225 status TEXT NOT NULL DEFAULT 'queued',
226 error TEXT,
227 run_at TIMESTAMPTZ NOT NULL DEFAULT now(),
228 started_at TIMESTAMPTZ,
229 created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
230 updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
231)";
232const SETUP_INDEX: &str =
233 "CREATE INDEX IF NOT EXISTS axa_queue_ready ON axa_queue (run_at) WHERE status = 'queued'";
234const SETUP_ATTEMPTS: &str =
236 "ALTER TABLE axa_queue ADD COLUMN IF NOT EXISTS attempts INTEGER NOT NULL DEFAULT 0";
237const SETUP_MAX_ATTEMPTS: &str =
239 "ALTER TABLE axa_queue ADD COLUMN IF NOT EXISTS max_attempts INTEGER";
240const SETUP_PRIORITY: &str =
242 "ALTER TABLE axa_queue ADD COLUMN IF NOT EXISTS priority SMALLINT NOT NULL DEFAULT 0";
243const SETUP_TIMEOUT: &str = "ALTER TABLE axa_queue ADD COLUMN IF NOT EXISTS timeout_ms BIGINT";
245const SETUP_TENANT: &str = "ALTER TABLE axa_queue ADD COLUMN IF NOT EXISTS tenant TEXT
247 CONSTRAINT axa_queue_tenant_id CHECK (tenant ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$')";
248const SETUP_CLAIM_INDEX: &str = "CREATE INDEX IF NOT EXISTS axa_queue_claim
249 ON axa_queue (priority DESC, run_at) WHERE status = 'queued'";
250const SETUP_SCHEDULE: &str = "CREATE TABLE IF NOT EXISTS axa_schedule (
251 name TEXT PRIMARY KEY,
252 due_at TIMESTAMPTZ NOT NULL,
253 last_job UUID,
254 interval_ms BIGINT,
255 seen_at TIMESTAMPTZ NOT NULL DEFAULT now(),
256 archived_at TIMESTAMPTZ,
257 created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
258 updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
259)";
260const SETUP_ACTS: &str = "CREATE TABLE IF NOT EXISTS axa_job_acts (
265 id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
266 job_id UUID NOT NULL,
267 job_name TEXT NOT NULL,
268 act TEXT NOT NULL CHECK (act IN ('cancelled', 'retried', 'released')),
269 attempts INTEGER NOT NULL,
270 by TEXT NOT NULL CHECK (length(by) BETWEEN 1 AND 200 AND by !~ '[[:cntrl:]]'),
271 reason TEXT NOT NULL CHECK (length(reason) BETWEEN 1 AND 200 AND reason !~ '[[:cntrl:]]'),
272 at TIMESTAMPTZ NOT NULL DEFAULT now()
273)";
274const SETUP_ACTS_INDEX: &str =
275 "CREATE INDEX IF NOT EXISTS axa_job_acts_job ON axa_job_acts (job_id, id)";
276const SETUP_ACTS_REFUSE: &str = "CREATE OR REPLACE FUNCTION axa_job_acts_refuse() RETURNS trigger
278LANGUAGE plpgsql AS $$
279BEGIN
280 RAISE EXCEPTION '% on % is refused: acts on jobs are only ever added to',
281 TG_OP, TG_TABLE_NAME;
282END
283$$";
284const SETUP_ACTS_ROWS: &str = "CREATE OR REPLACE TRIGGER axa_job_acts_refuse
285 BEFORE UPDATE OR DELETE ON axa_job_acts
286 FOR EACH ROW EXECUTE FUNCTION axa_job_acts_refuse()";
287const SETUP_ACTS_TRUNCATE: &str = "CREATE OR REPLACE TRIGGER axa_job_acts_refuse_truncate
288 BEFORE TRUNCATE ON axa_job_acts
289 FOR EACH STATEMENT EXECUTE FUNCTION axa_job_acts_refuse()";
290const SETUP_ACTS_ALWAYS: &str = "ALTER TABLE axa_job_acts
293 ENABLE ALWAYS TRIGGER axa_job_acts_refuse,
294 ENABLE ALWAYS TRIGGER axa_job_acts_refuse_truncate";
295const ACTS_TRIGGERS: [&str; 2] = ["axa_job_acts_refuse", "axa_job_acts_refuse_truncate"];
297const MISSING_TRIGGERS: &str = "SELECT want FROM unnest($1::text[]) AS want
298 WHERE NOT EXISTS (
299 SELECT 1 FROM pg_trigger t
300 WHERE t.tgrelid = to_regclass('axa_job_acts') AND t.tgname = want
301 AND t.tgenabled::text = 'A'
302 )";
303const NO_TENANT_HANDLER: &str =
305 "the job has a tenant, and its handler takes none: register it with handle_with_tenant";
306
307const SETUP_LOCK: i64 = 0x0061_7861_5F71;
309
310const ENQUEUE: &str = "INSERT INTO axa_queue
311 (id, name, args, max_attempts, priority, run_at, timeout_ms, tenant)
312 VALUES ($1, $2, $3, $4, $5, COALESCE($6, now() + make_interval(secs => $7)), $8, $9)";
313const CLAIM: &str = "UPDATE axa_queue
314 SET status = 'running', started_at = now(), updated_at = now(), attempts = attempts + 1
315 WHERE id = (
316 SELECT id FROM axa_queue
317 WHERE status = 'queued' AND run_at <= now() AND name = ANY($1)
318 ORDER BY priority DESC, run_at
319 FOR UPDATE SKIP LOCKED
320 LIMIT 1
321 )
322 RETURNING id, name, args, attempts, max_attempts, timeout_ms, tenant";
323const HEARTBEAT: &str = "UPDATE axa_queue SET updated_at = now()
326 WHERE id = $1 AND attempts = $2 AND status = 'running'";
327const FINISH: &str = "UPDATE axa_queue SET status = $3, error = $4, updated_at = now()
328 WHERE id = $1 AND attempts = $2 AND status = 'running'";
329const RETRY: &str = "UPDATE axa_queue
330 SET status = 'queued', error = $3, started_at = NULL, updated_at = now(),
331 run_at = now() + make_interval(secs => $4)
332 WHERE id = $1 AND attempts = $2 AND status = 'running'";
333const REQUEUE_STALE: &str = "UPDATE axa_queue
334 SET status = 'queued', started_at = NULL, updated_at = now()
335 WHERE status = 'running' AND updated_at < now() - make_interval(mins => $1)
336 AND attempts < COALESCE(max_attempts, $2)";
337const FAIL_STALE: &str = "UPDATE axa_queue
338 SET status = 'failed', error = 'abandoned by its worker', updated_at = now()
339 WHERE status = 'running' AND updated_at < now() - make_interval(mins => $1)
340 AND attempts >= COALESCE(max_attempts, $2)";
341const PURGE: &str = "DELETE FROM axa_queue
342 WHERE status IN ('completed', 'failed', 'cancelled')
343 AND updated_at < now() - make_interval(days => $1)";
344const STATUS: &str = "SELECT id, name, status, attempts, max_attempts, priority, error,
345 timeout_ms, tenant, run_at, started_at, created_at, updated_at FROM axa_queue WHERE id = $1";
346const MARK_LOST: &str =
350 "UPDATE axa_queue SET status = 'needs_review', error = $2, updated_at = now()
351 WHERE id = $1 AND status IN ('queued', 'running', 'failed')";
352const CANCEL: &str = "WITH changed AS (
355 UPDATE axa_queue SET status = 'cancelled', updated_at = now()
356 WHERE id = $1 AND status = 'queued'
357 RETURNING id, name, attempts
358 )
359 INSERT INTO axa_job_acts (job_id, job_name, act, attempts, by, reason)
360 SELECT id, name, 'cancelled', attempts, $2, $3 FROM changed";
361const RETRY_FAILED: &str = "WITH target AS (
366 SELECT id, status FROM axa_queue
367 WHERE id = $1 AND status IN ('failed', 'needs_review')
368 FOR UPDATE
369 ), changed AS (
370 UPDATE axa_queue q
371 SET status = 'queued', run_at = now(), started_at = NULL, updated_at = now(),
372 max_attempts = q.attempts + 1
373 FROM target WHERE q.id = target.id
374 RETURNING q.id, q.name, q.attempts, target.status AS was
375 )
376 INSERT INTO axa_job_acts (job_id, job_name, act, attempts, by, reason)
377 SELECT id, name, CASE was WHEN 'needs_review' THEN 'released' ELSE 'retried' END,
378 attempts, $2, $3
379 FROM changed";
380const ACTS: &str = "SELECT id, job_id, job_name, act, attempts, by, reason, at
381 FROM axa_job_acts WHERE job_id = $1 ORDER BY id";
382const COUNTS: &str = "SELECT
383 count(*) FILTER (WHERE status = 'queued' AND run_at <= now()) AS ready,
384 count(*) FILTER (WHERE status = 'queued' AND run_at > now()) AS waiting,
385 count(*) FILTER (WHERE status = 'running') AS running,
386 count(*) FILTER (WHERE status = 'completed') AS completed,
387 count(*) FILTER (WHERE status = 'failed') AS failed,
388 count(*) FILTER (WHERE status = 'cancelled') AS cancelled,
389 count(*) FILTER (WHERE status = 'needs_review') AS needs_review,
390 EXTRACT(EPOCH FROM now() - min(run_at) FILTER (WHERE status = 'queued' AND run_at <= now()))::float8 AS oldest
391 FROM axa_queue";
392const SCHEDULE_CREATE: &str = "INSERT INTO axa_schedule (name, due_at, interval_ms)
396 VALUES ($1, COALESCE($2, now()), $3)
397 ON CONFLICT (name) DO UPDATE
398 SET seen_at = now(), archived_at = NULL, interval_ms = EXCLUDED.interval_ms
399 WHERE axa_schedule.archived_at IS NOT NULL
400 OR axa_schedule.interval_ms IS DISTINCT FROM EXCLUDED.interval_ms
401 OR axa_schedule.seen_at < now() - interval '1 minute'";
402const SCHEDULE_LOCK: &str = "SELECT last_job, due_at <= now() AS due FROM axa_schedule
403 WHERE name = $1 AND archived_at IS NULL FOR UPDATE SKIP LOCKED";
404const SCHEDULE_ARCHIVE: &str = "UPDATE axa_schedule SET archived_at = now(), updated_at = now()
408 WHERE archived_at IS NULL AND name <> ALL($1)
409 AND seen_at < now() - make_interval(mins => $2)";
410const SCHEDULES: &str = "SELECT s.name, s.interval_ms, s.due_at, s.last_job, s.seen_at,
411 s.archived_at, s.created_at, q.status AS last_status, q.error AS last_error
412 FROM axa_schedule s LEFT JOIN axa_queue q ON q.id = s.last_job ORDER BY s.name";
413const SCHEDULE_BUSY: &str = "SELECT EXISTS (SELECT 1 FROM axa_queue
414 WHERE id = $1 AND status IN ('queued', 'running'))";
415const SCHEDULE_ADVANCE: &str = "UPDATE axa_schedule
418 SET due_at = due_at + make_interval(secs => $2)
419 * (floor(EXTRACT(EPOCH FROM now() - due_at)::float8 / $2) + 1),
420 last_job = COALESCE($3, last_job), updated_at = now()
421 WHERE name = $1";
422
423pub const SETUP_STATEMENTS: [&str; 15] = [
427 SETUP,
428 SETUP_ATTEMPTS,
429 SETUP_MAX_ATTEMPTS,
430 SETUP_INDEX,
431 SETUP_PRIORITY,
432 SETUP_TIMEOUT,
433 SETUP_TENANT,
434 SETUP_CLAIM_INDEX,
435 SETUP_SCHEDULE,
436 SETUP_ACTS,
437 SETUP_ACTS_INDEX,
438 SETUP_ACTS_REFUSE,
439 SETUP_ACTS_ROWS,
440 SETUP_ACTS_TRUNCATE,
441 SETUP_ACTS_ALWAYS,
442];
443
444pub const MAX_REASON_CHARS: usize = 200;
446
447const MIN_HEARTBEAT: Duration = Duration::from_millis(20);
449
450const MAX_BACKOFF: Duration = Duration::from_hours(1);
452
453const MAX_ERROR: usize = 1024;
455
456#[must_use]
458pub fn backoff(base: Duration, attempts: i32) -> Duration {
459 let doublings = u32::try_from(attempts.saturating_sub(1))
460 .unwrap_or(0)
461 .min(16);
462 base.saturating_mul(1 << doublings).min(MAX_BACKOFF)
463}
464
465fn cut(mut text: String) -> String {
467 if text.len() > MAX_ERROR {
468 let mut end = MAX_ERROR;
469 while !text.is_char_boundary(end) {
470 end -= 1;
471 }
472 text.truncate(end);
473 }
474 text
475}
476
477fn millis(duration: Duration) -> i64 {
478 i64::try_from(duration.as_millis()).unwrap_or(i64::MAX)
479}
480
481fn from_millis(millis: i64) -> Duration {
482 Duration::from_millis(u64::try_from(millis).unwrap_or(0))
483}
484
485#[derive(Debug, Clone, Copy, PartialEq, Eq)]
487enum When {
488 Now,
489 At(DateTime<Utc>),
490 In(Duration),
491}
492
493#[derive(Clone)]
495pub struct NewJob {
496 name: String,
497 args: serde_json::Value,
498 max_attempts: Option<i32>,
499 priority: i16,
500 when: When,
501 timeout: Option<Duration>,
502 tenant: Option<String>,
503}
504
505impl fmt::Debug for NewJob {
506 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
507 f.debug_struct("NewJob")
508 .field("name", &self.name)
509 .field("max_attempts", &self.max_attempts)
510 .field("priority", &self.priority)
511 .field("when", &self.when)
512 .field("timeout", &self.timeout)
513 .field("tenant", &self.tenant)
514 .finish_non_exhaustive()
515 }
516}
517
518impl NewJob {
519 pub fn new(name: impl Into<String>, args: serde_json::Value) -> Self {
522 Self {
523 name: name.into(),
524 args,
525 max_attempts: None,
526 priority: 0,
527 when: When::Now,
528 timeout: None,
529 tenant: None,
530 }
531 }
532
533 #[must_use]
539 pub fn tenant(mut self, tenant: impl Into<String>) -> Self {
540 self.tenant = Some(tenant.into());
541 self
542 }
543
544 #[must_use]
547 pub const fn timeout(mut self, limit: Duration) -> Self {
548 self.timeout = Some(limit);
549 self
550 }
551
552 #[must_use]
554 pub const fn max_attempts(mut self, max_attempts: Option<i32>) -> Self {
555 self.max_attempts = max_attempts;
556 self
557 }
558
559 #[must_use]
562 pub const fn priority(mut self, priority: i16) -> Self {
563 self.priority = priority;
564 self
565 }
566
567 #[must_use]
569 pub const fn run_in(mut self, delay: Duration) -> Self {
570 self.when = When::In(delay);
571 self
572 }
573
574 #[must_use]
576 pub const fn run_at(mut self, at: DateTime<Utc>) -> Self {
577 self.when = When::At(at);
578 self
579 }
580
581 #[must_use]
583 pub fn name(&self) -> &str {
584 &self.name
585 }
586
587 #[must_use]
589 pub fn tenant_id(&self) -> Option<&str> {
590 self.tenant.as_deref()
591 }
592}
593
594pub const MAX_TENANT_ID_LEN: usize = 63;
596
597#[must_use]
601pub fn is_tenant_id(id: &str) -> bool {
602 (1..=MAX_TENANT_ID_LEN).contains(&id.len())
603 && !id.starts_with('-')
604 && !id.ends_with('-')
605 && id
606 .bytes()
607 .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'-')
608}
609
610pub async fn enqueue_on<'e, E: PgExecutor<'e>>(executor: E, job: &NewJob) -> Result<Uuid> {
618 if job
619 .tenant
620 .as_deref()
621 .is_some_and(|tenant| !is_tenant_id(tenant))
622 {
623 return Err(Error::NotATenant);
624 }
625 let id = Uuid::new_v4();
626 let (at, delay) = match job.when {
627 When::Now => (None, 0.0),
628 When::At(at) => (Some(at), 0.0),
629 When::In(delay) => (None, delay.as_secs_f64()),
630 };
631 sqlx::query(ENQUEUE)
632 .bind(id)
633 .bind(&job.name)
634 .bind(&job.args)
635 .bind(job.max_attempts)
636 .bind(job.priority)
637 .bind(at)
638 .bind(delay)
639 .bind(job.timeout.map(millis))
640 .bind(job.tenant.as_deref())
641 .execute(executor)
642 .await?;
643 Ok(id)
644}
645
646pub async fn enqueue_all_on(connection: &mut PgConnection, jobs: &[NewJob]) -> Result<Vec<Uuid>> {
653 let mut ids = Vec::with_capacity(jobs.len());
654 for job in jobs {
655 ids.push(enqueue_on(&mut *connection, job).await?);
656 }
657 Ok(ids)
658}
659
660fn check_code(text: &str, what: &'static str) -> Result<()> {
662 if text.is_empty()
663 || text.chars().count() > MAX_REASON_CHARS
664 || text.chars().any(char::is_control)
665 {
666 Err(Error::NotACode { what })
667 } else {
668 Ok(())
669 }
670}
671
672pub async fn cancel(
686 transaction: &mut Transaction<'_, Postgres>,
687 id: Uuid,
688 by: &str,
689 reason: &str,
690) -> Result<bool> {
691 act(transaction, CANCEL, id, by, reason).await
692}
693
694pub async fn retry(
707 transaction: &mut Transaction<'_, Postgres>,
708 id: Uuid,
709 by: &str,
710 reason: &str,
711) -> Result<bool> {
712 act(transaction, RETRY_FAILED, id, by, reason).await
713}
714
715async fn act(
717 transaction: &mut Transaction<'_, Postgres>,
718 statement: &'static str,
719 id: Uuid,
720 by: &str,
721 reason: &str,
722) -> Result<bool> {
723 check_code(by, "by")?;
724 check_code(reason, "reason")?;
725 let kept = sqlx::query(statement)
726 .bind(id)
727 .bind(by)
728 .bind(reason)
729 .execute(&mut **transaction)
730 .await?
731 .rows_affected();
732 Ok(kept == 1)
733}
734
735#[derive(Debug, Clone, Copy, PartialEq, Eq)]
737#[non_exhaustive]
738pub enum ActKind {
739 Cancelled,
741 Retried,
743 Released,
745}
746
747impl ActKind {
748 fn parse(text: &str) -> Result<Self> {
749 match text {
750 "cancelled" => Ok(Self::Cancelled),
751 "retried" => Ok(Self::Retried),
752 "released" => Ok(Self::Released),
753 _ => Err(Error::Job("an act with an unknown kind".to_string())),
754 }
755 }
756}
757
758#[derive(Debug, Clone)]
761#[non_exhaustive]
762pub struct Act {
763 pub id: i64,
765 pub job_id: Uuid,
767 pub job_name: String,
769 pub kind: ActKind,
771 pub attempts: i32,
773 pub by: String,
775 pub reason: String,
777 pub at: DateTime<Utc>,
779}
780
781#[derive(Debug, Clone, Copy, PartialEq, Eq)]
783pub enum JobState {
784 Queued,
786 Running,
788 Completed,
790 Failed,
792 Cancelled,
794 NeedsReview,
798}
799
800impl JobState {
801 fn parse(text: &str) -> Result<Self> {
802 match text {
803 "queued" => Ok(Self::Queued),
804 "running" => Ok(Self::Running),
805 "completed" => Ok(Self::Completed),
806 "failed" => Ok(Self::Failed),
807 "cancelled" => Ok(Self::Cancelled),
808 "needs_review" => Ok(Self::NeedsReview),
809 _ => Err(Error::Job("a job row with an unknown status".to_string())),
810 }
811 }
812}
813
814#[derive(Debug, Clone)]
816#[non_exhaustive]
817pub struct JobInfo {
818 pub id: Uuid,
820 pub name: String,
822 pub state: JobState,
824 pub attempts: i32,
826 pub max_attempts: Option<i32>,
828 pub priority: i16,
830 pub timeout: Option<Duration>,
832 pub tenant: Option<String>,
834 pub error: Option<String>,
837 pub run_at: DateTime<Utc>,
839 pub started_at: Option<DateTime<Utc>>,
841 pub created_at: DateTime<Utc>,
843 pub updated_at: DateTime<Utc>,
845}
846
847#[derive(Debug, Clone, Copy, Default, PartialEq)]
849#[non_exhaustive]
850pub struct Counts {
851 pub ready: i64,
853 pub waiting: i64,
855 pub running: i64,
857 pub completed: i64,
859 pub failed: i64,
861 pub cancelled: i64,
863 pub needs_review: i64,
866 pub oldest_ready_seconds: f64,
869}
870
871#[derive(Clone)]
873pub struct Schedule {
874 name: String,
875 interval: Duration,
876 first: Option<DateTime<Utc>>,
877 job: NewJob,
878}
879
880impl fmt::Debug for Schedule {
881 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
882 f.debug_struct("Schedule")
883 .field("name", &self.name)
884 .field("interval", &self.interval)
885 .field("first", &self.first)
886 .field("job", &self.job)
887 .finish()
888 }
889}
890
891impl Schedule {
892 pub fn every(name: impl Into<String>, interval: Duration, job: NewJob) -> Self {
901 let name = name.into();
902 assert!(
903 !name.is_empty() && name.len() <= 200,
904 "a schedule name must be 1 to 200 characters"
905 );
906 assert!(
907 interval >= Duration::from_secs(1),
908 "the schedule {name} needs an interval of at least a second"
909 );
910 Self {
911 name,
912 interval,
913 first: None,
914 job: NewJob {
915 when: When::Now,
916 ..job
917 },
918 }
919 }
920
921 #[must_use]
925 pub const fn first_at(mut self, first: DateTime<Utc>) -> Self {
926 self.first = Some(first);
927 self
928 }
929
930 #[must_use]
932 pub fn name(&self) -> &str {
933 &self.name
934 }
935}
936
937#[derive(Debug, Clone)]
939#[non_exhaustive]
940pub struct ScheduleInfo {
941 pub name: String,
943 pub interval: Option<Duration>,
945 pub due_at: DateTime<Utc>,
947 pub last_job: Option<Uuid>,
949 pub last_state: Option<JobState>,
951 pub last_error: Option<String>,
953 pub seen_at: DateTime<Utc>,
955 pub archived_at: Option<DateTime<Utc>>,
958 pub created_at: DateTime<Utc>,
960}
961
962#[derive(Debug, Clone)]
964pub struct QueueOptions {
965 pub workers: usize,
967 pub poll_interval: Duration,
969 pub stale_minutes: i32,
972 pub heartbeat_interval: Duration,
974 pub max_attempts: i32,
977 pub retry_backoff: Duration,
979 pub retention_days: i32,
981 pub maintenance_interval: Duration,
983}
984
985impl Default for QueueOptions {
986 fn default() -> Self {
987 Self {
988 workers: 2,
989 poll_interval: Duration::from_secs(1),
990 stale_minutes: 60,
991 heartbeat_interval: Duration::from_mins(1),
992 max_attempts: 1,
993 retry_backoff: Duration::from_secs(30),
994 retention_days: 7,
995 maintenance_interval: Duration::from_mins(5),
996 }
997 }
998}
999
1000pub struct Queue {
1002 pool: PgPool,
1003 handlers: HashMap<String, Handler>,
1004 limits: HashMap<String, Arc<Semaphore>>,
1005 schedules: Vec<Schedule>,
1006 options: QueueOptions,
1007}
1008
1009impl fmt::Debug for Queue {
1010 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1011 f.debug_struct("Queue")
1012 .field("handlers", &self.handlers.len())
1013 .field("limits", &self.limits.len())
1014 .field("schedules", &self.schedules.len())
1015 .field("options", &self.options)
1016 .finish_non_exhaustive()
1017 }
1018}
1019
1020struct Claimed {
1022 id: Uuid,
1023 name: String,
1024 args: serde_json::Value,
1025 attempts: i32,
1026 limit: i32,
1027 timeout: Option<Duration>,
1028 tenant: Option<String>,
1029}
1030
1031enum Outcome {
1033 Done(Result<(), String>),
1035 Lost(String),
1037}
1038
1039impl Queue {
1040 #[must_use]
1043 pub fn from_pool(pool: PgPool, options: QueueOptions) -> Self {
1044 Self {
1045 pool,
1046 handlers: HashMap::new(),
1047 limits: HashMap::new(),
1048 schedules: Vec::new(),
1049 options,
1050 }
1051 }
1052
1053 async fn open(uri: &str, options: QueueOptions) -> Result<Self> {
1055 let loops = u32::try_from(options.workers).unwrap_or(u32::MAX);
1056 let pool = PgPoolOptions::new()
1057 .max_connections(loops.saturating_add(2))
1058 .connect(uri)
1059 .await?;
1060 Ok(Self::from_pool(pool, options))
1061 }
1062
1063 pub async fn connect_existing(uri: &str, options: QueueOptions) -> Result<Self> {
1073 let queue = Self::open(uri, options).await?;
1074 queue.check().await?;
1075 Ok(queue)
1076 }
1077
1078 pub async fn connect(uri: &str, options: QueueOptions) -> Result<Self> {
1085 let queue = Self::open(uri, options).await?;
1086 let mut setup = queue.pool.begin().await?;
1091 sqlx::query("SELECT pg_advisory_xact_lock($1)")
1092 .bind(SETUP_LOCK)
1093 .execute(&mut *setup)
1094 .await?;
1095 for statement in SETUP_STATEMENTS {
1096 sqlx::query(statement).execute(&mut *setup).await?;
1097 }
1098 setup.commit().await?;
1099 Ok(queue)
1100 }
1101
1102 pub async fn check(&self) -> Result<()> {
1110 sqlx::query(
1111 "SELECT attempts, max_attempts, priority, timeout_ms, tenant FROM axa_queue LIMIT 0",
1112 )
1113 .execute(&self.pool)
1114 .await?;
1115 sqlx::query(
1116 "SELECT name, due_at, last_job, interval_ms, seen_at, archived_at FROM axa_schedule LIMIT 0",
1117 )
1118 .execute(&self.pool)
1119 .await?;
1120 sqlx::query(
1121 "SELECT id, job_id, job_name, act, attempts, by, reason, at FROM axa_job_acts LIMIT 0",
1122 )
1123 .execute(&self.pool)
1124 .await?;
1125 let missing: Vec<String> = sqlx::query_scalar(MISSING_TRIGGERS)
1126 .bind(ACTS_TRIGGERS.to_vec())
1127 .fetch_all(&self.pool)
1128 .await?;
1129 if missing.is_empty() {
1130 Ok(())
1131 } else {
1132 Err(Error::Database(sqlx::Error::Configuration(
1133 format!(
1134 "the job queue is missing, or has turned off, {}: run SETUP_STATEMENTS",
1135 missing.join(", ")
1136 )
1137 .into(),
1138 )))
1139 }
1140 }
1141
1142 #[must_use]
1145 pub const fn pool(&self) -> &PgPool {
1146 &self.pool
1147 }
1148
1149 #[must_use]
1151 pub const fn options(&self) -> &QueueOptions {
1152 &self.options
1153 }
1154
1155 pub fn handle<F, Fut, E>(&mut self, name: impl Into<String>, handler: F)
1162 where
1163 F: Fn(serde_json::Value) -> Fut + Send + Sync + 'static,
1164 Fut: Future<Output = std::result::Result<(), E>> + Send + 'static,
1165 E: fmt::Display + 'static,
1166 {
1167 let handler = Arc::new(handler);
1168 let run: Handler = Arc::new(move |tenant, args| {
1169 if tenant.is_some() {
1170 return Box::pin(std::future::ready(Err(NO_TENANT_HANDLER.to_string())));
1171 }
1172 let job = handler(args);
1173 Box::pin(async move { job.await.map_err(|error| error.to_string()) })
1174 });
1175 self.handlers.insert(name.into(), run);
1176 }
1177
1178 pub fn handle_with_tenant<F, Fut, E>(&mut self, name: impl Into<String>, handler: F)
1183 where
1184 F: Fn(Option<String>, serde_json::Value) -> Fut + Send + Sync + 'static,
1185 Fut: Future<Output = std::result::Result<(), E>> + Send + 'static,
1186 E: fmt::Display + 'static,
1187 {
1188 let handler = Arc::new(handler);
1189 let run: Handler = Arc::new(move |tenant, args| {
1190 let job = handler(tenant, args);
1191 Box::pin(async move { job.await.map_err(|error| error.to_string()) })
1192 });
1193 self.handlers.insert(name.into(), run);
1194 }
1195
1196 pub fn limit(&mut self, name: impl Into<String>, jobs: usize) {
1199 self.limits
1200 .insert(name.into(), Arc::new(Semaphore::new(jobs.max(1))));
1201 }
1202
1203 pub fn schedule(&mut self, schedule: Schedule) {
1209 assert!(
1210 self.schedules.iter().all(|s| s.name != schedule.name),
1211 "the schedule {} was added twice",
1212 schedule.name
1213 );
1214 self.schedules.push(schedule);
1215 }
1216
1217 pub async fn enqueue(&self, name: &str, args: serde_json::Value) -> Result<Uuid> {
1223 enqueue_on(&self.pool, &NewJob::new(name, args)).await
1224 }
1225
1226 pub async fn enqueue_limited(
1232 &self,
1233 name: &str,
1234 args: serde_json::Value,
1235 max_attempts: Option<i32>,
1236 ) -> Result<Uuid> {
1237 enqueue_on(
1238 &self.pool,
1239 &NewJob::new(name, args).max_attempts(max_attempts),
1240 )
1241 .await
1242 }
1243
1244 pub async fn enqueue_job(&self, job: &NewJob) -> Result<Uuid> {
1250 enqueue_on(&self.pool, job).await
1251 }
1252
1253 pub async fn enqueue_all(&self, jobs: &[NewJob]) -> Result<Vec<Uuid>> {
1259 let mut transaction = self.pool.begin().await?;
1260 let ids = enqueue_all_on(&mut transaction, jobs).await?;
1261 transaction.commit().await?;
1262 Ok(ids)
1263 }
1264
1265 pub async fn job(&self, id: Uuid) -> Result<Option<JobInfo>> {
1272 let Some(row) = sqlx::query(STATUS)
1273 .bind(id)
1274 .fetch_optional(&self.pool)
1275 .await?
1276 else {
1277 return Ok(None);
1278 };
1279 Ok(Some(JobInfo {
1280 id: row.try_get("id")?,
1281 name: row.try_get("name")?,
1282 state: JobState::parse(row.try_get::<&str, _>("status")?)?,
1283 attempts: row.try_get("attempts")?,
1284 max_attempts: row.try_get("max_attempts")?,
1285 priority: row.try_get("priority")?,
1286 timeout: row
1287 .try_get::<Option<i64>, _>("timeout_ms")?
1288 .map(from_millis),
1289 tenant: row.try_get("tenant")?,
1290 error: row.try_get("error")?,
1291 run_at: row.try_get("run_at")?,
1292 started_at: row.try_get("started_at")?,
1293 created_at: row.try_get("created_at")?,
1294 updated_at: row.try_get("updated_at")?,
1295 }))
1296 }
1297
1298 pub async fn acts(&self, id: Uuid) -> Result<Vec<Act>> {
1306 let rows = sqlx::query(ACTS).bind(id).fetch_all(&self.pool).await?;
1307 rows.iter()
1308 .map(|row| {
1309 Ok(Act {
1310 id: row.try_get("id")?,
1311 job_id: row.try_get("job_id")?,
1312 job_name: row.try_get("job_name")?,
1313 kind: ActKind::parse(row.try_get::<&str, _>("act")?)?,
1314 attempts: row.try_get("attempts")?,
1315 by: row.try_get("by")?,
1316 reason: row.try_get("reason")?,
1317 at: row.try_get("at")?,
1318 })
1319 })
1320 .collect()
1321 }
1322
1323 pub async fn counts(&self) -> Result<Counts> {
1329 let row = sqlx::query(COUNTS).fetch_one(&self.pool).await?;
1330 Ok(Counts {
1331 ready: row.try_get("ready")?,
1332 waiting: row.try_get("waiting")?,
1333 running: row.try_get("running")?,
1334 completed: row.try_get("completed")?,
1335 failed: row.try_get("failed")?,
1336 cancelled: row.try_get("cancelled")?,
1337 needs_review: row.try_get("needs_review")?,
1338 oldest_ready_seconds: row.try_get::<Option<f64>, _>("oldest")?.unwrap_or(0.0),
1339 })
1340 }
1341
1342 pub async fn ping(&self) -> Result<()> {
1348 sqlx::query("SELECT 1").execute(&self.pool).await?;
1349 Ok(())
1350 }
1351
1352 pub async fn requeue_stale(&self) -> Result<u64> {
1359 sqlx::query(FAIL_STALE)
1360 .bind(self.options.stale_minutes)
1361 .bind(self.options.max_attempts)
1362 .execute(&self.pool)
1363 .await?;
1364 let result = sqlx::query(REQUEUE_STALE)
1365 .bind(self.options.stale_minutes)
1366 .bind(self.options.max_attempts)
1367 .execute(&self.pool)
1368 .await?;
1369 Ok(result.rows_affected())
1370 }
1371
1372 pub async fn purge_finished(&self) -> Result<u64> {
1379 let result = sqlx::query(PURGE)
1380 .bind(self.options.retention_days)
1381 .execute(&self.pool)
1382 .await?;
1383 Ok(result.rows_affected())
1384 }
1385
1386 pub async fn tick_schedules(&self) -> Result<usize> {
1394 let mut queued = 0;
1395 for schedule in &self.schedules {
1396 if self.tick(schedule).await? {
1397 queued += 1;
1398 }
1399 }
1400 Ok(queued)
1401 }
1402
1403 async fn tick(&self, schedule: &Schedule) -> Result<bool> {
1405 sqlx::query(SCHEDULE_CREATE)
1408 .bind(&schedule.name)
1409 .bind(schedule.first)
1410 .bind(millis(schedule.interval))
1411 .execute(&self.pool)
1412 .await?;
1413 let mut transaction = self.pool.begin().await?;
1414 let Some(row) = sqlx::query(SCHEDULE_LOCK)
1416 .bind(&schedule.name)
1417 .fetch_optional(&mut *transaction)
1418 .await?
1419 else {
1420 return Ok(false);
1421 };
1422 if !row.try_get::<bool, _>("due")? {
1423 transaction.commit().await?;
1424 return Ok(false);
1425 }
1426 let busy = match row.try_get::<Option<Uuid>, _>("last_job")? {
1427 Some(last) => {
1428 sqlx::query_scalar::<_, bool>(SCHEDULE_BUSY)
1429 .bind(last)
1430 .fetch_one(&mut *transaction)
1431 .await?
1432 }
1433 None => false,
1434 };
1435 let job = if busy {
1436 tracing::info!(schedule = %schedule.name, "schedule skipped, its last job has not finished");
1437 None
1438 } else {
1439 Some(enqueue_on(&mut *transaction, &schedule.job).await?)
1440 };
1441 sqlx::query(SCHEDULE_ADVANCE)
1442 .bind(&schedule.name)
1443 .bind(schedule.interval.as_secs_f64())
1444 .bind(job)
1445 .execute(&mut *transaction)
1446 .await?;
1447 transaction.commit().await?;
1448 if job.is_some() {
1449 tracing::debug!(schedule = %schedule.name, "schedule queued its job");
1450 }
1451 Ok(job.is_some())
1452 }
1453
1454 pub async fn archive_schedules(&self) -> Result<u64> {
1461 let names: Vec<&str> = self.schedules.iter().map(|s| s.name.as_str()).collect();
1462 let result = sqlx::query(SCHEDULE_ARCHIVE)
1463 .bind(&names)
1464 .bind(self.options.stale_minutes)
1465 .execute(&self.pool)
1466 .await?;
1467 Ok(result.rows_affected())
1468 }
1469
1470 pub async fn schedules(&self) -> Result<Vec<ScheduleInfo>> {
1476 let rows = sqlx::query(SCHEDULES).fetch_all(&self.pool).await?;
1477 rows.iter()
1478 .map(|row| {
1479 Ok(ScheduleInfo {
1480 name: row.try_get("name")?,
1481 interval: row
1482 .try_get::<Option<i64>, _>("interval_ms")?
1483 .map(from_millis),
1484 due_at: row.try_get("due_at")?,
1485 last_job: row.try_get("last_job")?,
1486 last_state: row
1487 .try_get::<Option<&str>, _>("last_status")?
1488 .map(JobState::parse)
1489 .transpose()?,
1490 last_error: row.try_get("last_error")?,
1491 seen_at: row.try_get("seen_at")?,
1492 archived_at: row.try_get("archived_at")?,
1493 created_at: row.try_get("created_at")?,
1494 })
1495 })
1496 .collect()
1497 }
1498
1499 async fn maintain(&self) {
1502 match self.archive_schedules().await {
1503 Ok(0) => {}
1504 Ok(archived) => tracing::info!(archived, "archived schedules no longer in code"),
1505 Err(error) => tracing::error!(%error, "could not archive schedules"),
1506 }
1507 if let Err(error) = self.requeue_stale().await {
1508 tracing::error!(%error, "could not recover stale jobs");
1509 }
1510 if let Err(error) = self.purge_finished().await {
1511 tracing::error!(%error, "could not delete old jobs");
1512 }
1513 }
1514
1515 async fn supervise(&self, job: JobFuture, claim: &Claimed) -> Outcome {
1519 let mut job = AbortOnDrop(tokio::spawn(job));
1520 let every = self.options.heartbeat_interval.max(MIN_HEARTBEAT);
1521 let stale =
1523 Duration::from_secs(u64::try_from(self.options.stale_minutes).unwrap_or(0) * 60);
1524 let mut last_heard = tokio::time::Instant::now();
1525 let limit = claim
1526 .timeout
1527 .map(|timeout| tokio::time::Instant::now() + timeout);
1528 let deadline = async {
1529 match limit {
1530 Some(at) => tokio::time::sleep_until(at).await,
1531 None => std::future::pending().await,
1532 }
1533 };
1534 tokio::pin!(deadline);
1535 loop {
1536 tokio::select! {
1537 finished = &mut job.0 => {
1538 return Outcome::Done(finished.unwrap_or_else(|_| {
1539 Err(Error::Job("the job panicked".to_string()).to_string())
1540 }));
1541 }
1542 () = &mut deadline => {
1543 let limit = claim.timeout.unwrap_or_default();
1544 return Outcome::Done(Err(
1545 Error::Job(format!("timed out after {}s", limit.as_secs_f64())).to_string(),
1546 ));
1547 }
1548 () = tokio::time::sleep(every) => {
1549 let beat = sqlx::query(HEARTBEAT)
1550 .bind(claim.id)
1551 .bind(claim.attempts)
1552 .execute(&self.pool)
1553 .await;
1554 match beat {
1555 Ok(done) if done.rows_affected() == 1 => last_heard = tokio::time::Instant::now(),
1556 Ok(_) => return Outcome::Lost("another worker or recovery took its claim".to_string()),
1557 Err(error) => {
1558 tracing::warn!(id = %claim.id, %error, "job heartbeat failed");
1559 if last_heard.elapsed() >= stale {
1560 return Outcome::Lost(format!(
1561 "it could not report in for {} minutes",
1562 self.options.stale_minutes
1563 ));
1564 }
1565 }
1566 }
1567 }
1568 }
1569 }
1570 }
1571
1572 async fn mark_lost(&self, claim: &Claimed, reason: &str) {
1575 let text = Error::Job(format!("stopped: {reason}")).to_string();
1576 let every = self.options.heartbeat_interval.max(MIN_HEARTBEAT);
1577 loop {
1578 match sqlx::query(MARK_LOST)
1579 .bind(claim.id)
1580 .bind(&text)
1581 .execute(&self.pool)
1582 .await
1583 {
1584 Ok(_) => return,
1585 Err(error) => {
1586 tracing::error!(id = %claim.id, %error, "could not mark a lost job for review");
1587 tokio::time::sleep(every).await;
1588 }
1589 }
1590 }
1591 }
1592
1593 fn claimable(&self) -> (Vec<String>, HashMap<String, OwnedSemaphorePermit>) {
1596 let mut places = HashMap::new();
1597 let mut names = Vec::new();
1598 for name in self.handlers.keys() {
1599 match self.limits.get(name) {
1600 None => names.push(name.clone()),
1601 Some(limit) => {
1602 if let Ok(place) = limit.clone().try_acquire_owned() {
1603 places.insert(name.clone(), place);
1604 names.push(name.clone());
1605 }
1606 }
1607 }
1608 }
1609 (names, places)
1610 }
1611
1612 async fn claim(&self, names: &[String]) -> Result<Option<Claimed>> {
1613 let Some(row) = sqlx::query(CLAIM)
1614 .bind(names)
1615 .fetch_optional(&self.pool)
1616 .await?
1617 else {
1618 return Ok(None);
1619 };
1620 Ok(Some(Claimed {
1621 id: row.try_get("id")?,
1622 name: row.try_get("name")?,
1623 args: row.try_get("args")?,
1624 attempts: row.try_get("attempts")?,
1625 limit: row
1626 .try_get::<Option<i32>, _>("max_attempts")?
1627 .unwrap_or(self.options.max_attempts),
1628 timeout: row
1629 .try_get::<Option<i64>, _>("timeout_ms")?
1630 .map(from_millis),
1631 tenant: row.try_get("tenant")?,
1632 }))
1633 }
1634
1635 pub async fn run_one(&self) -> Result<bool> {
1642 let (names, mut places) = self.claimable();
1643 if names.is_empty() {
1644 return Ok(false);
1645 }
1646 let Some(job) = self.claim(&names).await? else {
1647 return Ok(false);
1648 };
1649 let _place = places.remove(&job.name);
1651 drop(places);
1652 let outcome = match self.handlers.get(&job.name) {
1653 Some(handler) => {
1654 let run = handler(job.tenant.clone(), job.args.clone());
1655 self.supervise(run, &job).await
1656 }
1657 None => Outcome::Done(Err(
1658 Error::Job(format!("no handler for job {}", job.name)).to_string()
1659 )),
1660 };
1661 let (id, name, attempts) = (job.id, job.name.as_str(), job.attempts);
1662 let finished = match outcome {
1663 Outcome::Lost(reason) => {
1664 tracing::error!(job = %name, %id, attempts, %reason, "job stopped, it lost its claim");
1665 self.mark_lost(&job, &reason).await;
1666 return Ok(true);
1667 }
1668 Outcome::Done(Ok(())) => {
1669 sqlx::query(FINISH)
1670 .bind(id)
1671 .bind(attempts)
1672 .bind("completed")
1673 .bind(None::<String>)
1674 .execute(&self.pool)
1675 .await?
1676 }
1677 Outcome::Done(Err(error)) if attempts < job.limit => {
1678 tracing::warn!(job = %name, %id, attempts, %error, "job failed, will retry");
1679 let wait = backoff(self.options.retry_backoff, attempts);
1680 sqlx::query(RETRY)
1681 .bind(id)
1682 .bind(attempts)
1683 .bind(cut(error))
1684 .bind(wait.as_secs_f64())
1685 .execute(&self.pool)
1686 .await?
1687 }
1688 Outcome::Done(Err(error)) => {
1689 tracing::error!(job = %name, %id, attempts, %error, "job failed");
1690 sqlx::query(FINISH)
1691 .bind(id)
1692 .bind(attempts)
1693 .bind("failed")
1694 .bind(cut(error))
1695 .execute(&self.pool)
1696 .await?
1697 }
1698 };
1699 if finished.rows_affected() == 0 {
1700 tracing::error!(job = %name, %id, "job finished after losing its claim");
1703 self.mark_lost(
1704 &job,
1705 "it finished after another worker or recovery took its claim",
1706 )
1707 .await;
1708 }
1709 Ok(true)
1710 }
1711
1712 pub async fn run(self: Arc<Self>, shutdown: watch::Receiver<bool>) {
1718 let mut loops = Vec::new();
1719 loops.push(AbortOnDrop(tokio::spawn(every_until(
1720 shutdown.clone(),
1721 self.options.maintenance_interval,
1722 {
1723 let queue = self.clone();
1724 move || {
1725 let queue = queue.clone();
1726 async move { queue.maintain().await }
1727 }
1728 },
1729 ))));
1730 if !self.schedules.is_empty() {
1731 let queue = self.clone();
1732 loops.push(AbortOnDrop(tokio::spawn(every_until(
1733 shutdown.clone(),
1734 self.options.poll_interval,
1735 move || {
1736 let queue = queue.clone();
1737 async move {
1738 if let Err(error) = queue.tick_schedules().await {
1739 tracing::error!(%error, "could not queue scheduled jobs");
1740 }
1741 }
1742 },
1743 ))));
1744 }
1745 for _ in 0..self.options.workers.max(1) {
1746 let queue = self.clone();
1747 let mut shutdown = shutdown.clone();
1748 loops.push(AbortOnDrop(tokio::spawn(async move {
1749 while !*shutdown.borrow() {
1750 let worked = queue.run_one().await.unwrap_or_else(|error| {
1751 tracing::error!(%error, "job queue error");
1752 false
1753 });
1754 if !worked {
1755 tokio::select! {
1756 () = tokio::time::sleep(queue.options.poll_interval) => {},
1757 _ = shutdown.changed() => {},
1758 }
1759 }
1760 }
1761 })));
1762 }
1763 for job_loop in &mut loops {
1764 let _ = (&mut job_loop.0).await;
1765 }
1766 }
1767
1768 #[must_use]
1770 pub fn handled(&self) -> HashSet<&str> {
1771 self.handlers.keys().map(String::as_str).collect()
1772 }
1773}
1774
1775async fn every_until<F, Fut>(mut shutdown: watch::Receiver<bool>, gap: Duration, round: F)
1777where
1778 F: Fn() -> Fut,
1779 Fut: Future<Output = ()>,
1780{
1781 while !*shutdown.borrow() {
1782 round().await;
1783 tokio::select! {
1784 () = tokio::time::sleep(gap) => {},
1785 _ = shutdown.changed() => {},
1786 }
1787 }
1788}
1789
1790struct AbortOnDrop<T>(tokio::task::JoinHandle<T>);
1793
1794impl<T> Drop for AbortOnDrop<T> {
1795 fn drop(&mut self) {
1796 self.0.abort();
1797 }
1798}
1799
1800#[cfg(test)]
1801mod tests {
1802 use super::*;
1803
1804 #[test]
1805 fn each_retry_waits_twice_as_long_up_to_a_limit() {
1806 let base = Duration::from_secs(30);
1807 assert_eq!(backoff(base, 1), base);
1808 assert_eq!(backoff(base, 2), base * 2);
1809 assert_eq!(backoff(base, 3), base * 4);
1810 assert_eq!(backoff(base, 1_000), MAX_BACKOFF);
1811 }
1812
1813 #[test]
1814 fn the_debug_text_leaves_out_arguments() {
1815 let job = NewJob::new("Report", serde_json::json!({ "nhs": "943 476 5919" }));
1816 let schedule = Schedule::every("nightly", Duration::from_hours(1), job.clone());
1817 for text in [format!("{job:?}"), format!("{schedule:?}")] {
1818 assert!(text.contains("Report"), "{text}");
1819 assert!(!text.contains("943"), "{text}");
1820 }
1821 }
1822
1823 #[test]
1824 fn a_by_or_reason_that_is_not_a_code_is_refused() {
1825 assert!(check_code("ops:alice", "by").is_ok());
1826 assert!(check_code(&"é".repeat(MAX_REASON_CHARS), "reason").is_ok());
1827 for bad in [
1828 String::new(),
1829 "é".repeat(MAX_REASON_CHARS + 1),
1830 "two\nlines".to_string(),
1831 "a\ttab".to_string(),
1832 ] {
1833 let error = check_code(&bad, "reason").unwrap_err();
1834 assert!(matches!(error, Error::NotACode { what: "reason" }));
1835 assert!(!error.to_string().contains("lines"), "the text is left out");
1836 }
1837 }
1838
1839 #[test]
1840 fn a_long_error_is_cut_on_a_character_boundary() {
1841 let text = "é".repeat(MAX_ERROR);
1842 let kept = cut(text);
1843 assert!(kept.len() <= MAX_ERROR);
1844 assert!(kept.chars().all(|c| c == 'é'));
1845 assert_eq!(cut("short".to_string()), "short");
1846 }
1847
1848 #[test]
1849 #[should_panic(expected = "at least a second")]
1850 fn a_schedule_under_a_second_is_refused_at_boot() {
1851 let _ = Schedule::every(
1852 "fast",
1853 Duration::from_millis(10),
1854 NewJob::new("J", serde_json::Value::Null),
1855 );
1856 }
1857
1858 #[test]
1859 #[should_panic(expected = "1 to 200 characters")]
1860 fn a_schedule_with_no_name_is_refused_at_boot() {
1861 let _ = Schedule::every(
1862 "",
1863 Duration::from_secs(1),
1864 NewJob::new("J", serde_json::Value::Null),
1865 );
1866 }
1867
1868 #[tokio::test]
1869 #[should_panic(expected = "added twice")]
1870 async fn a_schedule_added_twice_is_refused_at_boot() {
1871 let pool = PgPoolOptions::new()
1872 .connect_lazy("postgres://u@localhost/none")
1873 .unwrap();
1874 let mut queue = Queue::from_pool(pool, QueueOptions::default());
1875 let job = NewJob::new("J", serde_json::Value::Null);
1876 queue.schedule(Schedule::every("a", Duration::from_secs(5), job.clone()));
1877 queue.schedule(Schedule::every("a", Duration::from_secs(9), job));
1878 }
1879
1880 #[test]
1881 fn a_schedule_ignores_a_delay_on_its_job() {
1882 let job = NewJob::new("J", serde_json::Value::Null).run_in(Duration::from_hours(1));
1883 let schedule = Schedule::every("s", Duration::from_secs(5), job);
1884 assert_eq!(schedule.job.when, When::Now);
1885 }
1886}