glacier-web 0.4.0

A batteries-included web framework for Rust, inspired by Rails, Phoenix and Laravel.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
//! Background jobs, kept in the database as Rails' Solid Queue keeps them:
//! enqueued in the same transaction as the work that asks for them, run by
//! workers the app starts, retried with backoff, and left marked failed
//! after their last attempt.
//!
//! ```ignore
//! #[derive(Serialize, Deserialize)]
//! pub struct SendReport {
//!     pub report_id: i64,
//! }
//!
//! impl Job for SendReport {
//!     const NAME: &'static str = "send_report";
//!
//!     async fn perform(self) -> glacier::Result<()> {
//!         // …
//!         Ok(())
//!     }
//! }
//!
//! SendReport { report_id: report.id }.enqueue().await?;
//!
//! // The app runs them (two workers by default), and recurring ones:
//! App::new().database(repo).jobs(
//!     Jobs::new()
//!         .register::<SendReport>()
//!         .queue("mailers", 3)
//!         .cron("nightly_digest", "0 3 * * *", NightlyDigest),
//! )
//! ```
//!
//! On Postgres, workers wake as soon as a job is queued (`LISTEN/NOTIFY`)
//! rather than on their next look; on SQLite they look every second. A
//! running job's worker marks it alive every 15 seconds, so if the worker
//! dies the job is picked up again a minute later.
//!
//! The tables come from migrations, versioned as Oban's are so that an
//! app's old migrations keep making the same table: `create_table(s)`
//! makes it as 0.1 did, and `upgrade_table(s)` adds what 0.3 needs. A new
//! app's migration calls both; an older app adds one calling `upgrade_table`.

pub mod cron;
mod prune;

use std::collections::HashMap;
use std::future::Future;
use std::panic::AssertUnwindSafe;
use std::pin::Pin;
use std::sync::Arc;
use std::time::Duration;

use chrono::TimeDelta;
use futures_util::FutureExt;
use serde::Serialize;
use serde::de::DeserializeOwned;
use tokio::sync::Notify;

pub use self::cron::Cron;
pub use self::prune::{Prunable, prune};
use crate::db::migration::Schema;
use crate::db::{self, Repo, Sql, Timestamp, Value};
use crate::error::{Error, Result};

const TABLE: &str = "glacier_jobs";
const SCHEDULES: &str = "glacier_job_schedules";
/// The channel versions before 0.4 woke workers on, still listened to so
/// a deploy that mixes versions keeps waking them.
const OLD_CHANNEL: &str = "glacier_jobs";
/// How often a running job's worker says it's still alive.
const HEARTBEAT: Duration = Duration::from_secs(15);
/// A job whose worker hasn't been heard from for this long is taken again.
const STALE_AFTER: TimeDelta = TimeDelta::seconds(60);
/// How late a recurring job may still be queued, after every process was
/// down when it was due.
const SCHEDULE_GRACE: TimeDelta = TimeDelta::minutes(5);

/// The jobs table as 0.1 made it, for a migration's `up`. It never
/// changes, so migrations already run keep meaning the same thing; follow
/// it with [`upgrade_table`], as `glacier generate job` does:
/// `glacier::jobs::create_table(s); glacier::jobs::upgrade_table(s);`.
pub fn create_table(s: &mut Schema) {
    s.create_table(TABLE, |t| {
        t.string("name").not_null();
        t.string("queue").not_null();
        t.text("args").not_null();
        t.integer("attempts").not_null().default(0);
        t.integer("max_attempts").not_null().default(5);
        t.timestamp("run_at").not_null();
        t.timestamp("locked_at");
        t.timestamp("failed_at");
        t.text("last_error");
        t.timestamps();
    });
    s.add_index(TABLE, &["run_at"]);
}

/// What 0.3's jobs need on top of [`create_table`]: priorities, unique
/// and expiring jobs, an index for queues, and the table recurring jobs
/// keep their last run in. An app made before 0.3 adds a migration that
/// calls it.
pub fn upgrade_table(s: &mut Schema) {
    s.alter_table(TABLE, |t| {
        t.integer("priority").not_null().default(0);
        t.text("unique_key");
        t.timestamp("expires_at");
    });
    s.drop_index(TABLE, &["run_at"]);
    // What workers look for: due jobs by queue, in priority order.
    s.add_index(TABLE, &["queue", "priority", "run_at"]);
    // One waiting or running job per key; a failed one doesn't count.
    s.execute(&format!(
        "CREATE UNIQUE INDEX index_{TABLE}_on_unique_key ON {TABLE} (unique_key) WHERE failed_at IS NULL"
    ));
    s.create_table(SCHEDULES, |t| {
        t.string("name").not_null().unique();
        t.timestamp("last_run_at").not_null();
    });
}

/// How long before a job runs: a `chrono::TimeDelta` (`30.days()`) or a
/// `std::time::Duration`.
pub trait Delay {
    fn delay(self) -> TimeDelta;
}

impl Delay for TimeDelta {
    fn delay(self) -> TimeDelta {
        self
    }
}

impl Delay for Duration {
    fn delay(self) -> TimeDelta {
        TimeDelta::from_std(self).unwrap_or(TimeDelta::MAX)
    }
}

/// Work to do later. Its fields are its arguments, stored as JSON.
pub trait Job: Serialize + DeserializeOwned + Send + Sync + 'static {
    /// The name it's stored and registered under: keep it when renaming
    /// the type, or queued jobs won't find it.
    const NAME: &'static str;
    const QUEUE: &'static str = "default";
    /// Attempts before the job is left failed.
    const MAX_ATTEMPTS: i32 = 5;
    /// Which due job runs first: lower first, as Active Job's priorities.
    const PRIORITY: i32 = 0;

    fn perform(self) -> impl Future<Output = Result<()>> + Send;

    /// Makes the job unique: while one with the same key waits or runs,
    /// queueing another returns the first one's id instead. The key is
    /// kept per job type: `Some(format!("{}", self.report_id))`.
    fn unique_key(&self) -> Option<String> {
        None
    }

    /// Drops the job, marked failed, if it hasn't started this long after
    /// it was due: a reminder that's pointless a day late.
    fn expires_in(&self) -> Option<TimeDelta> {
        None
    }

    /// When the job recurs, added to `jobs` as it's registered: a job
    /// with `cron "0 9 * * mon"` (or `every 1.hours()`) in `.glacier`
    /// returns `jobs.cron(Self::NAME, "0 9 * * mon", Self)`. None by
    /// default.
    fn schedule(jobs: Jobs) -> Jobs
    where
        Self: Sized,
    {
        jobs
    }

    /// Queues the job to run now, returning its id. Inside a transaction,
    /// it's only queued if the transaction commits.
    fn enqueue(&self) -> impl Future<Output = Result<i64>> + Send {
        self.enqueue_at(crate::time::now())
    }

    /// Queues the job to run after `delay`: `enqueue_in(30.days())`, or a
    /// `std::time::Duration`.
    fn enqueue_in(&self, delay: impl Delay) -> impl Future<Output = Result<i64>> + Send {
        self.enqueue_at(crate::time::now() + delay.delay())
    }

    /// Queues the job to run at `at`.
    fn enqueue_at(&self, at: Timestamp) -> impl Future<Output = Result<i64>> + Send {
        let reference = crate::access::current().and_then(|access| access.reference());
        queue_one(Queued::of_for(self, at, reference))
    }

    /// Queues the job to run now for `access` rather than the current one:
    /// an org a signed-in member works in, or another user the action
    /// acts for (`enqueue_for(UserAccess { user: author })`).
    fn enqueue_for(
        &self,
        access: &dyn crate::access::Access,
    ) -> impl Future<Output = Result<i64>> + Send {
        queue_one(Queued::of_for(self, crate::time::now(), access.reference()))
    }

    /// Queues the job to run now for no one, whoever queues it: `access`
    /// in its `perform` is then `401 Unauthorized`.
    fn enqueue_unscoped(&self) -> impl Future<Output = Result<i64>> + Send {
        queue_one(Queued::of_for(self, crate::time::now(), None))
    }

    /// Queues many jobs in one statement, to run now, returning how many
    /// were queued (unique ones already waiting aren't).
    fn enqueue_all(jobs: &[Self]) -> impl Future<Output = Result<usize>> + Send {
        let now = crate::time::now();
        let rows: Result<Vec<Queued>> = jobs.iter().map(|job| Queued::of(job, now)).collect();
        async move {
            let rows = rows?;
            if rows.is_empty() {
                return Ok(0);
            }
            Ok(insert(rows).await?.len())
        }
    }
}

/// Inserts one queued row, returning its id (or, for a unique job already
/// waiting, that one's).
async fn queue_one(row: Result<Queued>) -> Result<i64> {
    let row = row?;
    let key = row.unique_key.clone();
    match insert(vec![row]).await?.first() {
        Some(id) => Ok(*id),
        // Already queued: the one waiting is this job.
        None => existing(key.as_deref().unwrap_or_default()).await,
    }
}

/// Where a job's arguments keep the access it was queued for.
const ACCESS_KEY: &str = "__access";
/// Where they keep arguments that aren't an object, beside the access.
const ARGS_KEY: &str = "__args";

/// A row to insert into the jobs table.
struct Queued {
    name: &'static str,
    queue: &'static str,
    args: String,
    priority: i32,
    max_attempts: i32,
    run_at: Timestamp,
    unique_key: Option<String>,
    expires_at: Option<Timestamp>,
}

impl Queued {
    /// The row for `job`, for the current access (a request's, or a job's).
    fn of<J: Job>(job: &J, run_at: Timestamp) -> Result<Self> {
        let reference = crate::access::current().and_then(|access| access.reference());
        Self::of_for(job, run_at, reference)
    }

    /// The row for `job`, for the access `reference` names, or for no one.
    fn of_for<J: Job>(
        job: &J,
        run_at: Timestamp,
        reference: Option<serde_json::Value>,
    ) -> Result<Self> {
        let mut args = serde_json::to_value(job)
            .map_err(|e| Error::internal(format!("job arguments: {e}")))?;
        // It goes with the job, by reference, to be rebuilt when it runs.
        if let Some(reference) = reference {
            match args.as_object_mut() {
                Some(fields) => {
                    fields.insert(ACCESS_KEY.to_owned(), reference);
                }
                // Arguments that aren't an object (a unit struct's `null`)
                // go inside one.
                None => {
                    args = serde_json::json!({ ARGS_KEY: args, ACCESS_KEY: reference });
                }
            }
        }
        let args = args.to_string();
        Ok(Self {
            name: J::NAME,
            queue: J::QUEUE,
            args,
            priority: J::PRIORITY,
            max_attempts: J::MAX_ATTEMPTS,
            run_at,
            unique_key: job.unique_key().map(|key| format!("{}:{key}", J::NAME)),
            expires_at: job.expires_in().map(|within| run_at + within),
        })
    }
}

/// Inserts the rows, returning the ids of those queued (a unique job
/// already waiting isn't). On Postgres, the same statement tells workers.
async fn insert(rows: Vec<Queued>) -> Result<Vec<i64>> {
    let conn = db::current()?;
    let postgres = conn.dialect() == db::Dialect::Postgres;
    let now = crate::time::now();
    let unique = rows.iter().any(|row| row.unique_key.is_some());
    let mut sql = Sql::new();
    if postgres {
        sql.push("WITH queued AS (");
    }
    sql.push(&format!(
        "INSERT INTO {TABLE} (name, queue, args, priority, attempts, max_attempts, run_at, \
         unique_key, expires_at, inserted_at, updated_at) VALUES "
    ));
    for (i, row) in rows.into_iter().enumerate() {
        if i > 0 {
            sql.push(", ");
        }
        sql.push("(");
        let values = [
            Value::Text(row.name.to_owned()),
            Value::Text(row.queue.to_owned()),
            Value::Text(row.args),
            Value::Int(i64::from(row.priority)),
            Value::Int(0),
            Value::Int(i64::from(row.max_attempts)),
            Value::Timestamp(row.run_at),
            row.unique_key.map_or(Value::Null, Value::Text),
            row.expires_at.map_or(Value::Null, Value::Timestamp),
            Value::Timestamp(now),
            Value::Timestamp(now),
        ];
        for (j, value) in values.into_iter().enumerate() {
            if j > 0 {
                sql.push(", ");
            }
            sql.push_value(value);
        }
        sql.push(")");
    }
    if unique {
        sql.push(" ON CONFLICT (unique_key) WHERE failed_at IS NULL DO NOTHING");
    }
    sql.push(" RETURNING id, queue");
    if postgres {
        // Delivered when the transaction commits, so a worker never wakes
        // for a job it can't see yet.
        sql.push(&format!(
            ") SELECT id, {}::text AS notified FROM queued",
            crate::notify::pg_notify_sql("jobs", "queued", "id")
        ));
    }
    let rows = conn.fetch_all(&sql).await.map_err(upgrade_hint)?;
    rows.iter().map(id_of).collect()
}

/// A database error from a jobs table made before 0.3, with what to do.
fn upgrade_hint(err: sqlx::Error) -> Error {
    let message = err.to_string();
    let old_table = ["priority", "unique_key", "expires_at", SCHEDULES]
        .iter()
        .any(|name| message.contains(name));
    if old_table {
        Error::internal(format!(
            "{message}: the jobs table is from before Glacier 0.3; add a migration \
             whose `up` calls `glacier::jobs::upgrade_table(s)`"
        ))
    } else {
        err.into()
    }
}

/// The id of the unique job waiting with `key`.
async fn existing(key: &str) -> Result<i64> {
    let mut sql = Sql::new();
    sql.push(&format!(
        "SELECT id FROM {TABLE} WHERE failed_at IS NULL AND unique_key = "
    ));
    sql.push_value(Value::Text(key.to_owned()));
    let rows = db::current()?.fetch_all(&sql).await?;
    // Gone already: it finished between the insert and this look.
    rows.first().map_or(Ok(0), id_of)
}

fn id_of(row: &db::Row) -> Result<i64> {
    row.get::<i64>("id")
        .or_else(|_| row.get::<i32>("id").map(i64::from))
}

type Perform = Arc<dyn Fn(&str) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> + Send + Sync>;

/// A job queued again and again: on a cron schedule or at an interval.
#[derive(Clone)]
struct Recurring {
    name: String,
    when: When,
    job: &'static str,
    queue: &'static str,
    args: String,
    priority: i32,
    max_attempts: i32,
}

#[derive(Clone)]
enum When {
    Cron(Cron),
    /// At whole multiples of the interval since 1970, so every process
    /// agrees on when it's due.
    Every(TimeDelta),
}

impl When {
    /// The latest time it was due, if recently enough to still queue.
    fn latest_due(&self, now: Timestamp) -> Option<Timestamp> {
        match self {
            When::Cron(cron) => cron.latest_at_or_before(now, SCHEDULE_GRACE),
            When::Every(interval) => {
                let step = interval.num_milliseconds().max(1);
                let at = now.timestamp_millis().div_euclid(step) * step;
                let due = chrono::DateTime::from_timestamp_millis(at)?;
                (now - due <= SCHEDULE_GRACE).then_some(due)
            }
        }
    }
}

/// A cron expression for [`Jobs::cron`]: text (`"0 3 * * *"`), or a
/// [`Cron`] read in a time zone.
pub trait IntoCron {
    fn into_cron(self) -> Cron;
}

impl IntoCron for Cron {
    fn into_cron(self) -> Cron {
        self
    }
}

impl IntoCron for &str {
    /// # Panics
    ///
    /// When the expression isn't valid, as the app is set up.
    fn into_cron(self) -> Cron {
        Cron::parse(self).unwrap_or_else(|err| panic!("cron schedule: {}", err.message()))
    }
}

/// Which queues a group of workers takes jobs from.
#[derive(Clone)]
enum Queues {
    Only(String),
    /// Every queue without workers of its own.
    Except(Vec<String>),
}

/// The jobs an app can run, by name, and how many workers run them.
#[derive(Clone)]
pub struct Jobs {
    handlers: Arc<HashMap<&'static str, Perform>>,
    workers: usize,
    queues: Vec<(String, usize)>,
    poll: Option<Duration>,
    recurring: Vec<Recurring>,
    keep_failed: Option<TimeDelta>,
    pruners: Vec<(String, Pruner)>,
}

type Pruner = Arc<dyn Fn() -> Pin<Box<dyn Future<Output = Result<u64>> + Send>> + Send + Sync>;

impl Default for Jobs {
    fn default() -> Self {
        Self::new()
    }
}

impl Jobs {
    /// No jobs but Glacier's own: `deliver_later`'s mail delivery and
    /// webhook handling.
    pub fn new() -> Self {
        Self {
            handlers: Arc::new(HashMap::new()),
            workers: 2,
            queues: Vec::new(),
            poll: None,
            recurring: Vec::new(),
            keep_failed: None,
            pruners: Vec::new(),
        }
        .register::<crate::mail::DeliverMail>()
        .register::<crate::webhooks::HandleWebhook>()
    }

    /// Lets the workers run `J`.
    #[must_use]
    pub fn register<J: Job>(mut self) -> Self {
        let perform: Perform = Arc::new(|args: &str| {
            // The access it was queued for, if any, and its own arguments.
            let mut value = serde_json::from_str::<serde_json::Value>(args).unwrap_or_default();
            let reference = value.get_mut(ACCESS_KEY).map(serde_json::Value::take);
            let job = match value.get_mut(ARGS_KEY) {
                Some(inner) => serde_json::from_value::<J>(inner.take()),
                None => serde_json::from_str::<J>(args),
            };
            Box::pin(async move {
                let job = job.map_err(|e| Error::internal(format!("job arguments: {e}")))?;
                match reference {
                    Some(reference) => {
                        // Loaded and checked again: an access that's gone
                        // (a member removed) fails the job.
                        let access = crate::access::rebuild(reference)
                            .await
                            .map_err(|e| Error::internal(format!("rebuilding its access: {e}")))?;
                        tracing::Span::current().record("glacier.access", access.describe());
                        crate::access::with_shared(access, job.perform()).await
                    }
                    None => job.perform().await,
                }
            })
        });
        Arc::make_mut(&mut self.handlers).insert(J::NAME, perform);
        // Its schedule, if it recurs.
        J::schedule(self)
    }

    /// How many jobs run at once from queues without workers of their own
    /// (default 2).
    #[must_use]
    pub fn workers(mut self, workers: usize) -> Self {
        self.workers = workers.max(1);
        self
    }

    /// Gives `queue` workers of its own, so at most `workers` of its jobs
    /// run at once in each process, and they never wait behind other
    /// queues' jobs: `.queue("mailers", 3)`.
    #[must_use]
    pub fn queue(mut self, queue: &str, workers: usize) -> Self {
        self.queues.retain(|(name, _)| name != queue);
        self.queues.push((queue.to_owned(), workers.max(1)));
        self
    }

    /// How long an idle worker waits before looking again: 1 second by
    /// default, or 10 on Postgres, where queueing a job wakes workers.
    #[must_use]
    pub fn poll_every(mut self, interval: Duration) -> Self {
        self.poll = Some(interval);
        self
    }

    /// Queues `job` on a cron schedule, read in UTC:
    /// `.cron("nightly_digest", "0 3 * * *", NightlyDigest)`, or another
    /// zone with `Cron::parse("0 3 * * *")?.in_zone("Europe/London")?`.
    /// Each run is queued once, however many processes are running.
    ///
    /// # Panics
    ///
    /// When the expression isn't valid, or the job's arguments can't be
    /// stored.
    #[must_use]
    pub fn cron<J: Job>(self, name: &str, schedule: impl IntoCron, job: J) -> Self {
        self.recurring(name, When::Cron(schedule.into_cron()), &job)
    }

    /// Queues `job` every `interval`: `.every("sync_rates", 15.minutes(), SyncRates)`.
    /// Runs fall on whole multiples of the interval (on the hour, for an
    /// hourly job), the same for every process.
    ///
    /// # Panics
    ///
    /// When the job's arguments can't be stored.
    #[must_use]
    pub fn every<J: Job>(self, name: &str, interval: impl Delay, job: J) -> Self {
        self.recurring(name, When::Every(interval.delay()), &job)
    }

    fn recurring<J: Job>(mut self, name: &str, when: When, job: &J) -> Self {
        let args = serde_json::to_string(job)
            .unwrap_or_else(|e| panic!("recurring job `{name}`: arguments: {e}"));
        let register = !self.handlers.contains_key(J::NAME);
        self.recurring.retain(|r| r.name != name);
        self.recurring.push(Recurring {
            name: name.to_owned(),
            when,
            job: J::NAME,
            queue: J::QUEUE,
            args,
            priority: J::PRIORITY,
            max_attempts: J::MAX_ATTEMPTS,
        });
        if register { self.register::<J>() } else { self }
    }

    /// Deletes failed jobs this long after they failed (they're kept,
    /// for `glacier jobs`, until then; by default, until retried or
    /// deleted). Finished jobs are deleted as they finish.
    #[must_use]
    pub fn keep_failed_for(mut self, age: impl Delay) -> Self {
        self.keep_failed = Some(age.delay());
        self
    }

    /// Deletes `M`'s old records once an hour, as its [`Prunable`] says,
    /// a batch at a time.
    #[must_use]
    pub fn prune_records<M: Prunable>(self) -> Self {
        self.prune_with(M::TABLE, || prune::<M>())
    }

    /// Runs `prune` once an hour, for old rows without a model:
    /// `.prune_with("webhook_events", || glacier::webhooks::prune(30.days()))`.
    /// It returns how many rows it deleted.
    #[must_use]
    pub fn prune_with<F, Fut>(mut self, name: &str, prune: F) -> Self
    where
        F: Fn() -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<u64>> + Send + 'static,
    {
        let pruner: Pruner = Arc::new(move || Box::pin(prune()));
        self.pruners.retain(|(existing, _)| existing != name);
        self.pruners.push((name.to_owned(), pruner));
        self
    }

    /// Starts the workers on `repo`; they run until the process ends.
    /// `App::serve` does this; call it yourself to run jobs in a process
    /// of their own.
    pub fn start(&self, repo: Repo) {
        let wake = Arc::new(Notify::new());
        let listening = match repo.postgres_pool() {
            Some(pool) => {
                listen(pool.clone(), wake.clone());
                true
            }
            None => false,
        };
        let poll = self.poll.unwrap_or(if listening {
            Duration::from_secs(10)
        } else {
            Duration::from_secs(1)
        });
        let own: Vec<String> = self.queues.iter().map(|(name, _)| name.clone()).collect();
        let mut groups = vec![(Queues::Except(own), self.workers)];
        groups.extend(
            self.queues
                .iter()
                .map(|(name, n)| (Queues::Only(name.clone()), *n)),
        );
        for (queues, workers) in groups {
            for _ in 0..workers {
                let jobs = self.clone();
                let repo = repo.clone();
                let wake = wake.clone();
                let queues = queues.clone();
                tokio::spawn(async move {
                    loop {
                        // Ready before looking, so a job queued meanwhile wakes it.
                        let woken = wake.notified();
                        tokio::pin!(woken);
                        woken.as_mut().enable();
                        match db::with(&repo, jobs.run_next(&queues, Some(&repo))).await {
                            Ok(true) => {}
                            Ok(false) => {
                                tokio::select! {
                                    () = woken => {}
                                    () = tokio::time::sleep(poll) => {}
                                }
                            }
                            Err(err) => {
                                tracing::error!(target: "glacier::jobs", "job queue: {err}");
                                tokio::time::sleep(poll).await;
                            }
                        }
                    }
                });
            }
        }
        if !self.recurring.is_empty() || self.keep_failed.is_some() || !self.pruners.is_empty() {
            let jobs = self.clone();
            tokio::spawn(async move {
                let mut pruned_at: Option<std::time::Instant> = None;
                loop {
                    if let Err(err) = db::with(&repo, jobs.enqueue_recurring()).await {
                        tracing::error!(target: "glacier::jobs", "recurring jobs: {err}");
                    }
                    if pruned_at.is_none_or(|at| at.elapsed() > Duration::from_secs(3600)) {
                        if let Err(err) = db::with(&repo, jobs.prune()).await {
                            tracing::error!(target: "glacier::jobs", "pruning jobs: {err}");
                        }
                        pruned_at = Some(std::time::Instant::now());
                    }
                    tokio::time::sleep(jobs.until_next_recurring()).await;
                }
            });
        }
    }

    /// Runs every job that's due, one after another, on the current
    /// connection; returns how many ran. For tests, and for one-off
    /// processing without workers.
    pub async fn perform_due(&self) -> Result<usize> {
        let mut count = 0;
        while self.run_next(&Queues::Except(Vec::new()), None).await? {
            count += 1;
        }
        Ok(count)
    }

    /// Queues each recurring job that's due and not yet queued by any
    /// process, returning how many it queued. The workers' scheduler
    /// calls it; tests can too, after `travel`ling to when one is due.
    pub async fn enqueue_recurring(&self) -> Result<usize> {
        let now = crate::time::now();
        let mut queued = 0;
        for recurring in &self.recurring {
            let Some(due) = recurring.when.latest_due(now) else {
                continue;
            };
            let claimed = db::transaction(async {
                // Only one process moves `last_run_at` on to this run.
                let mut sql = Sql::new();
                sql.push(&format!(
                    "INSERT INTO {SCHEDULES} (name, last_run_at) VALUES ("
                ));
                sql.push_value(Value::Text(recurring.name.clone()));
                sql.push(", ");
                sql.push_value(Value::Timestamp(due));
                sql.push(&format!(
                    ") ON CONFLICT (name) DO UPDATE SET last_run_at = excluded.last_run_at \
                     WHERE {SCHEDULES}.last_run_at < excluded.last_run_at RETURNING name"
                ));
                if db::current()?
                    .fetch_all(&sql)
                    .await
                    .map_err(upgrade_hint)?
                    .is_empty()
                {
                    return Ok(false);
                }
                insert(vec![Queued {
                    name: recurring.job,
                    queue: recurring.queue,
                    args: recurring.args.clone(),
                    priority: recurring.priority,
                    max_attempts: recurring.max_attempts,
                    run_at: now,
                    unique_key: None,
                    expires_at: None,
                }])
                .await?;
                Ok(true)
            })
            .await?;
            queued += usize::from(claimed);
        }
        Ok(queued)
    }

    /// How long the scheduler sleeps: until the next recurring job is due,
    /// but at most a minute.
    fn until_next_recurring(&self) -> Duration {
        let now = chrono::Utc::now();
        self.recurring
            .iter()
            .filter_map(|r| match &r.when {
                When::Cron(cron) => cron.next_after(now),
                When::Every(interval) => {
                    let step = interval.num_milliseconds().max(1);
                    let next = (now.timestamp_millis().div_euclid(step) + 1) * step;
                    chrono::DateTime::from_timestamp_millis(next)
                }
            })
            .map(|next| (next - now).to_std().unwrap_or_default())
            .min()
            .unwrap_or(Duration::MAX)
            .min(Duration::from_secs(60))
            + Duration::from_millis(50)
    }

    /// Deletes what's old: failed jobs past `keep_failed_for`, and each
    /// model's and table's prunable rows; how many it deleted in all. The
    /// scheduler calls it once an hour; tests can call it themselves.
    pub async fn prune(&self) -> Result<u64> {
        let mut deleted = 0;
        if let Some(age) = self.keep_failed {
            let mut sql = Sql::new();
            sql.push(&format!("DELETE FROM {TABLE} WHERE failed_at < "));
            sql.push_value(Value::Timestamp(crate::time::now() - age));
            deleted += db::current()?.execute(&sql).await?;
        }
        for (name, prune) in &self.pruners {
            let pruned = crate::access::unscoped("pruning", prune()).await?;
            if pruned > 0 {
                tracing::info!(target: "glacier::jobs", "pruned {pruned} from {name}");
            }
            deleted += pruned;
        }
        Ok(deleted)
    }

    /// The failed jobs, most recent first: what `glacier jobs` lists.
    pub async fn failed() -> Result<Vec<FailedJob>> {
        let rows = db::sql(&format!(
            "SELECT id, name, queue, args, attempts, last_error, failed_at FROM {TABLE} \
             WHERE failed_at IS NOT NULL ORDER BY failed_at DESC, id DESC"
        ))
        .fetch_all()
        .await?;
        rows.iter()
            .map(|row| {
                Ok(FailedJob {
                    id: id_of(row)?,
                    name: row.get("name")?,
                    queue: row.get("queue")?,
                    args: row.get("args")?,
                    attempts: row.get("attempts")?,
                    last_error: row.get::<Option<String>>("last_error")?.unwrap_or_default(),
                    failed_at: row.get("failed_at")?,
                })
            })
            .collect()
    }

    /// Queues a failed job to run again now, with its attempts reset and
    /// no expiry (retrying is a decision to run it); `false` if there's no
    /// failed job `id`, or it's a unique job and another with its key is
    /// already waiting.
    pub async fn retry(id: i64) -> Result<bool> {
        let now = crate::time::now();
        let mut sql = Sql::new();
        sql.push(&format!(
            "UPDATE {TABLE} SET failed_at = NULL, locked_at = NULL, expires_at = NULL, \
             attempts = 0, run_at = "
        ));
        sql.push_value(Value::Timestamp(now));
        sql.push(", updated_at = ");
        sql.push_value(Value::Timestamp(now));
        sql.push(" WHERE failed_at IS NOT NULL AND id = ");
        sql.push_value(Value::Int(id));
        sql.push(&format!(
            " AND (unique_key IS NULL OR NOT EXISTS (SELECT 1 FROM {TABLE} waiting \
             WHERE waiting.unique_key = {TABLE}.unique_key AND waiting.failed_at IS NULL))"
        ));
        Ok(db::current()?.execute(&sql).await? > 0)
    }

    /// Claims the next due job and runs it: `false` when none is due.
    /// With `heartbeat`, the job is marked alive on that repo while it runs.
    async fn run_next(&self, queues: &Queues, heartbeat: Option<&Repo>) -> Result<bool> {
        let conn = db::current()?;
        let now = crate::time::now();
        let skip_locked = match conn.dialect() {
            db::Dialect::Postgres => " FOR UPDATE SKIP LOCKED",
            db::Dialect::Sqlite => "",
        };
        let mut sql = Sql::new();
        sql.push(&format!("UPDATE {TABLE} SET locked_at = "));
        sql.push_value(Value::Timestamp(now));
        sql.push(", attempts = attempts + 1 WHERE id = (SELECT id FROM ");
        sql.push(TABLE);
        sql.push(" WHERE failed_at IS NULL AND run_at <= ");
        sql.push_value(Value::Timestamp(now));
        // Not running, or its worker has stopped saying it's alive.
        sql.push(" AND (locked_at IS NULL OR locked_at < ");
        sql.push_value(Value::Timestamp(now - STALE_AFTER));
        sql.push(")");
        match queues {
            Queues::Only(queue) => {
                sql.push(" AND queue = ");
                sql.push_value(Value::Text(queue.clone()));
            }
            Queues::Except(others) if !others.is_empty() => {
                sql.push(" AND queue NOT IN (");
                for (i, queue) in others.iter().enumerate() {
                    if i > 0 {
                        sql.push(", ");
                    }
                    sql.push_value(Value::Text(queue.clone()));
                }
                sql.push(")");
            }
            Queues::Except(_) => {}
        }
        sql.push(&format!(
            " ORDER BY priority, run_at, id LIMIT 1{skip_locked}) \
             RETURNING id, name, args, attempts, max_attempts, expires_at"
        ));
        let rows = conn.fetch_all(&sql).await.map_err(upgrade_hint)?;
        let Some(row) = rows.first() else {
            return Ok(false);
        };
        let id = id_of(row)?;
        let name: String = row.get("name")?;
        let args: String = row.get("args")?;
        let attempts: i32 = row.get("attempts")?;
        let max_attempts: i32 = row.get("max_attempts")?;
        let expires_at: Option<Timestamp> = row.get("expires_at")?;

        if expires_at.is_some_and(|at| at < now) {
            give_up(id, "expired before it could run").await?;
            return Ok(true);
        }
        // Only reached by taking over from workers that died mid-run.
        if attempts > max_attempts {
            give_up(id, "its worker stopped while running it, too many times").await?;
            return Ok(true);
        }

        let outcome = match self.handlers.get(name.as_str()) {
            Some(perform) => {
                let span = tracing::info_span!(
                    target: "glacier::jobs",
                    "glacier.job",
                    otel.name = %name,
                    otel.kind = "consumer",
                    job.name = %name,
                    job.id = id,
                    job.attempt = attempts,
                    glacier.access = tracing::field::Empty,
                );
                // A panic is a failure like any other, not the end of the worker.
                let run = async {
                    match AssertUnwindSafe(perform(&args)).catch_unwind().await {
                        Ok(outcome) => outcome,
                        Err(panic) => Err(Error::internal(format!(
                            "panicked: {}",
                            panic_text(&*panic)
                        ))),
                    }
                };
                let run = tracing::Instrument::instrument(run, span);
                // Stops marking the job alive however this ends.
                let _alive = heartbeat.map(|repo| AbortOnDrop(keep_alive(repo.clone(), id)));
                // In a transaction (tests), a failing job's writes are undone
                // without spoiling the rest of it.
                if conn.in_transaction() {
                    db::savepoint(run).await
                } else {
                    run.await
                }
            }
            None => Err(Error::internal(format!("no job is registered as `{name}`"))),
        };
        let mut sql = Sql::new();
        match outcome {
            Ok(()) => {
                sql.push(&format!("DELETE FROM {TABLE} WHERE id = "));
                sql.push_value(Value::Int(id));
            }
            Err(err) => {
                let message = err.to_string();
                tracing::warn!(target: "glacier::jobs", "job {name} #{id} failed (attempt {attempts}): {message}");
                let now = crate::time::now();
                sql.push(&format!(
                    "UPDATE {TABLE} SET locked_at = NULL, last_error = "
                ));
                sql.push_value(Value::Text(message));
                sql.push(", updated_at = ");
                sql.push_value(Value::Timestamp(now));
                if attempts >= max_attempts {
                    sql.push(", failed_at = ");
                    sql.push_value(Value::Timestamp(now));
                } else {
                    sql.push(", run_at = ");
                    sql.push_value(Value::Timestamp(now + backoff(attempts)));
                }
                sql.push(" WHERE id = ");
                sql.push_value(Value::Int(id));
            }
        }
        conn.execute(&sql).await?;
        Ok(true)
    }
}

/// A job that ran out of attempts (or expired), kept for inspection.
#[derive(Debug, Clone)]
pub struct FailedJob {
    pub id: i64,
    pub name: String,
    pub queue: String,
    /// Its arguments, as stored (JSON).
    pub args: String,
    pub attempts: i32,
    pub last_error: String,
    pub failed_at: Timestamp,
}

/// Marks a job failed without running it.
async fn give_up(id: i64, why: &str) -> Result<()> {
    let now = crate::time::now();
    let mut sql = Sql::new();
    sql.push(&format!(
        "UPDATE {TABLE} SET locked_at = NULL, failed_at = "
    ));
    sql.push_value(Value::Timestamp(now));
    sql.push(", updated_at = ");
    sql.push_value(Value::Timestamp(now));
    sql.push(", last_error = ");
    sql.push_value(Value::Text(why.to_owned()));
    sql.push(" WHERE id = ");
    sql.push_value(Value::Int(id));
    db::current()?.execute(&sql).await?;
    tracing::warn!(target: "glacier::jobs", "job #{id} {why}");
    Ok(())
}

/// Aborts a task when dropped.
struct AbortOnDrop(tokio::task::JoinHandle<()>);

impl Drop for AbortOnDrop {
    fn drop(&mut self) {
        self.0.abort();
    }
}

fn panic_text(panic: &(dyn std::any::Any + Send)) -> String {
    panic
        .downcast_ref::<&str>()
        .map(|s| (*s).to_owned())
        .or_else(|| panic.downcast_ref::<String>().cloned())
        .unwrap_or_else(|| "a panic".to_owned())
}

/// Marks job `id` alive every few seconds, on a connection of its own,
/// until aborted.
fn keep_alive(repo: Repo, id: i64) -> tokio::task::JoinHandle<()> {
    tokio::spawn(async move {
        loop {
            tokio::time::sleep(HEARTBEAT).await;
            let mut sql = Sql::new();
            sql.push(&format!("UPDATE {TABLE} SET locked_at = "));
            sql.push_value(Value::Timestamp(chrono::Utc::now()));
            sql.push(" WHERE id = ");
            sql.push_value(Value::Int(id));
            let beat: Result<u64> =
                db::with(&repo, async { Ok(db::current()?.execute(&sql).await?) }).await;
            if let Err(err) = beat {
                tracing::warn!(target: "glacier::jobs", "job #{id} heartbeat: {err}");
            }
        }
    })
}

/// Wakes idle workers whenever a job is queued, from any process.
fn listen(pool: sqlx::PgPool, wake: Arc<Notify>) {
    tokio::spawn(async move {
        loop {
            let mut listener = match sqlx::postgres::PgListener::connect_with(&pool).await {
                Ok(listener) => listener,
                Err(err) => {
                    tracing::warn!(target: "glacier::jobs", "listening for jobs: {err}");
                    tokio::time::sleep(Duration::from_secs(5)).await;
                    continue;
                }
            };
            if let Err(err) = listener
                .listen_all([crate::notify::CHANNEL, OLD_CHANNEL])
                .await
            {
                tracing::warn!(target: "glacier::jobs", "listening for jobs: {err}");
                tokio::time::sleep(Duration::from_secs(5)).await;
                continue;
            }
            // `recv` reconnects by itself; an error means it couldn't.
            while let Ok(notification) = listener.recv().await {
                let for_jobs = notification.channel() == OLD_CHANNEL
                    || crate::notify::Envelope::parse(notification.payload())
                        .is_some_and(|envelope| envelope.topic == "jobs");
                if for_jobs {
                    wake.notify_waiters();
                }
            }
            // Jobs queued while reconnecting are found by polling.
            wake.notify_waiters();
        }
    });
}

/// Active Job's polynomial backoff: attempts⁴ + 2 seconds (3s, 18s, 83s…).
fn backoff(attempts: i32) -> TimeDelta {
    let n = i64::from(attempts.max(1));
    TimeDelta::seconds(n.pow(4) + 2)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn backs_off_polynomially() {
        let seconds: Vec<i64> = (1..=4).map(|n| backoff(n).num_seconds()).collect();
        assert_eq!(seconds, [3, 18, 83, 258]);
    }

    #[test]
    fn intervals_fall_on_whole_multiples() {
        let at = |s: &str| chrono::DateTime::parse_from_rfc3339(s).unwrap().to_utc();
        let hourly = When::Every(TimeDelta::hours(1));
        assert_eq!(
            hourly.latest_due(at("2026-10-04T10:03:00Z")),
            Some(at("2026-10-04T10:00:00Z"))
        );
        // Twenty minutes late is a missed run, as for cron: starting the
        // app doesn't queue it.
        assert_eq!(hourly.latest_due(at("2026-10-04T10:20:00Z")), None);
        let quarter = When::Every(TimeDelta::minutes(15));
        assert_eq!(
            quarter.latest_due(at("2026-10-04T10:20:00Z")),
            Some(at("2026-10-04T10:15:00Z"))
        );
    }
}