wabot-addon-async-sqlite 0.2.0

SQLite-backed JobRepository and CronJobRepository for Wabot's async feature — durable background work on a single node.
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
//! SQLite `JobRepository` + `CronJobRepository`.
//!
//! The durable counterpart to `wabot-addon-async-in-memory` for a
//! single node. Both are [`SqliteJsonbStore`] wrappers: the entity
//! lives in a `data` JSON column and the queries read it with
//! `data->>'$."field"'`, so the SQL reads side by side with the
//! Postgres addon's.
//!
//! ```ignore
//! let db = SqliteDatabase::open(SqliteConfig::at("/var/lib/app/app.db"))?;
//! register_job_repository(&c, Arc::new(SqliteJobRepository::new(db.clone())));
//! register_cron_job_repository(&c, Arc::new(SqliteCronJobRepository::new(db)));
//! register_async_runtime(&c);   // InProcessLocker is the right one on one node
//! ```
//!
//! ## Why this exists when there is an in-memory one
//!
//! Because jobs that vanish on restart are only acceptable for tests.
//! A deployment job — build this image, start this container, renew
//! this certificate — that disappears because the process was upgraded
//! leaves the system half-changed with nothing recording that it was.
//! In-memory is right for a unit test and wrong for anything that
//! survives a reboot.
//!
//! ## Field names are camelCase
//!
//! `scheduledAt`, not `scheduled_at`. That is the wabot-ts wire
//! format, and the document is the same shape in both stacks — a rule
//! worth keeping even where, as here, no TypeScript will ever read
//! these rows: it is what lets one entity definition serve both.

use std::sync::Arc;

use async_trait::async_trait;
use chrono::{DateTime, Utc};
use rusqlite::types::Value as SqlValue;

use wabot_feature_async::cron_job::{CronJob, CronJobData};
use wabot_feature_async::job::{Job, JobData};
use wabot_feature_async::repository::{CronJobRepository, JobRepository};
use wabot_feature_async::types::AsyncError;
use wabot_feature_sqlite::{SqliteDatabase, SqliteError, SqliteJsonbStore};

/// Default table names. Match the Postgres addon's, so an application
/// that moves between backends addresses the same tables.
pub const JOBS_TABLE: &str = "jobs";
pub const CRON_JOBS_TABLE: &str = "cron_jobs";

/// The JSON extraction for one document field.
///
/// A macro rather than a `format!` at each site because these strings
/// appear in both the queries *and* the index DDL, and an index built
/// on a subtly different expression is one SQLite will silently never
/// use.
macro_rules! field {
    ($name:literal) => {
        concat!("\"data\"->>'$.\"", $name, "\"'")
    };
}

// ---------- Job repository ----------------------------------------------

pub struct SqliteJobRepository {
    store: SqliteJsonbStore<JobData>,
}

impl SqliteJobRepository {
    pub fn new(database: SqliteDatabase) -> Self {
        Self::with_table(database, JOBS_TABLE)
    }

    pub fn with_table(database: SqliteDatabase, table: &str) -> Self {
        let store = SqliteJsonbStore::new(database, table)
            // The scheduler's every-tick query. Partial, so the index
            // stays small as completed jobs pile up — which they do,
            // and the pending set does not.
            .with_index(concat!(
                "CREATE INDEX IF NOT EXISTS jobs_pending_idx ON \"jobs\" (",
                field!("scheduledAt"),
                ") WHERE ",
                field!("startedAt"),
                " IS NULL AND ",
                field!("successAt"),
                " IS NULL AND ",
                field!("failedAt"),
                " IS NULL"
            ))
            .with_index(concat!(
                "CREATE INDEX IF NOT EXISTS jobs_dedup_idx ON \"jobs\" (",
                field!("commandName"),
                ", ",
                field!("dedupKey"),
                ")"
            ))
            .with_index(concat!(
                "CREATE INDEX IF NOT EXISTS jobs_running_idx ON \"jobs\" (",
                field!("commandName"),
                ") WHERE ",
                field!("startedAt"),
                " IS NOT NULL AND ",
                field!("successAt"),
                " IS NULL AND ",
                field!("failedAt"),
                " IS NULL"
            ));
        Self { store }
    }

    /// Escape hatch for callers that need a custom query against the
    /// same table.
    pub fn store(&self) -> &SqliteJsonbStore<JobData> {
        &self.store
    }

    /// Create the table + indexes now instead of on first query.
    pub async fn ensure_ready(&self) -> Result<(), AsyncError> {
        self.store.ensure_ready().await.map_err(to_async_error)
    }
}

#[async_trait]
impl JobRepository for SqliteJobRepository {
    async fn find(&self, id: &str) -> Result<Option<Job>, AsyncError> {
        self.store.find_by_id(id).await.map_err(to_async_error)
    }

    async fn create(&self, job: &Job) -> Result<(), AsyncError> {
        // Upsert rather than plain insert: the runner re-saves a job it
        // already created, and a retry after a partial failure should
        // not trip a primary-key violation.
        self.store.save(job).await.map_err(to_async_error)
    }

    async fn update(&self, job: &Job) -> Result<(), AsyncError> {
        self.store.save(job).await.map_err(to_async_error)
    }

    async fn delete(&self, job: &Job) -> Result<(), AsyncError> {
        self.store.delete(job.id()).await.map_err(to_async_error)
    }

    async fn find_pending_for_run_from(
        &self,
        as_of: DateTime<Utc>,
        limit: usize,
    ) -> Result<Vec<Job>, AsyncError> {
        // No cast on `scheduledAt`: SQLite's `->>` returns the stored
        // JSON number as an INTEGER, so this comparison is numeric.
        // The Postgres version needs `::bigint` because its `->>`
        // always yields text.
        let sql = format!(
            "SELECT \"data\" FROM {t} \
              WHERE {scheduled} IS NOT NULL \
                AND {scheduled} <= ?1 \
                AND {started} IS NULL \
                AND {success} IS NULL \
                AND {failed} IS NULL \
              ORDER BY {scheduled} ASC \
              LIMIT ?2",
            t = self.store.table(),
            scheduled = field!("scheduledAt"),
            started = field!("startedAt"),
            success = field!("successAt"),
            failed = field!("failedAt"),
        );
        self.store
            .query(
                &sql,
                vec![
                    SqlValue::Integer(as_of.timestamp_millis()),
                    SqlValue::Integer(limit as i64),
                ],
            )
            .await
            .map_err(to_async_error)
    }

    async fn find_running(&self) -> Result<Vec<Job>, AsyncError> {
        let sql = format!(
            "SELECT \"data\" FROM {t} \
              WHERE {started} IS NOT NULL \
                AND {success} IS NULL \
                AND {failed} IS NULL",
            t = self.store.table(),
            started = field!("startedAt"),
            success = field!("successAt"),
            failed = field!("failedAt"),
        );
        self.store
            .query(&sql, Vec::new())
            .await
            .map_err(to_async_error)
    }

    async fn count_running_by_command(&self, command_name: &str) -> Result<usize, AsyncError> {
        let sql = format!(
            "SELECT COUNT(*) FROM {t} \
              WHERE {started} IS NOT NULL \
                AND {success} IS NULL \
                AND {failed} IS NULL \
                AND {command} = ?1",
            t = self.store.table(),
            started = field!("startedAt"),
            success = field!("successAt"),
            failed = field!("failedAt"),
            command = field!("commandName"),
        );
        let count = self
            .store
            .count(&sql, vec![SqlValue::Text(command_name.to_string())])
            .await
            .map_err(to_async_error)?;
        Ok(count.max(0) as usize)
    }

    async fn find_active_by_dedup_key(
        &self,
        command_name: &str,
        dedup_key: &str,
        succeeded_since_ms: i64,
    ) -> Result<Option<Job>, AsyncError> {
        let sql = format!(
            "SELECT \"data\" FROM {t} \
              WHERE {command} = ?1 \
                AND {dedup} = ?2 \
                AND {failed} IS NULL \
                AND ({success} IS NULL OR {success} >= ?3) \
              ORDER BY \"created_at\" DESC \
              LIMIT 1",
            t = self.store.table(),
            command = field!("commandName"),
            dedup = field!("dedupKey"),
            failed = field!("failedAt"),
            success = field!("successAt"),
        );
        self.store
            .query_opt(
                &sql,
                vec![
                    SqlValue::Text(command_name.to_string()),
                    SqlValue::Text(dedup_key.to_string()),
                    SqlValue::Integer(succeeded_since_ms),
                ],
            )
            .await
            .map_err(to_async_error)
    }
}

impl wabot_core::injection::IsSingleton for SqliteJobRepository {
    fn register_in(c: &wabot_core::injection::Container) {
        c.register_singleton_factory::<SqliteJobRepository, _>(|c2| {
            let database: Arc<SqliteDatabase> = c2.resolve();
            Arc::new(SqliteJobRepository::new(database.as_ref().clone()))
        });
    }
}

// ---------- CronJob repository ------------------------------------------

pub struct SqliteCronJobRepository {
    store: SqliteJsonbStore<CronJobData>,
}

impl SqliteCronJobRepository {
    pub fn new(database: SqliteDatabase) -> Self {
        Self::with_table(database, CRON_JOBS_TABLE)
    }

    pub fn with_table(database: SqliteDatabase, table: &str) -> Self {
        let store = SqliteJsonbStore::new(database, table)
            .with_index(concat!(
                "CREATE INDEX IF NOT EXISTS cron_jobs_next_run_idx ON \"cron_jobs\" (",
                field!("nextRunAt"),
                ")"
            ))
            // Unique, not merely indexed: reconcile looks a cron up by
            // name and creates it when missing. One node cannot race
            // itself, but a restart mid-reconcile can, and two rows for
            // one schedule means it fires twice.
            .with_index(concat!(
                "CREATE UNIQUE INDEX IF NOT EXISTS cron_jobs_name_idx ON \"cron_jobs\" (",
                field!("name"),
                ")"
            ));
        Self { store }
    }

    pub fn store(&self) -> &SqliteJsonbStore<CronJobData> {
        &self.store
    }

    pub async fn ensure_ready(&self) -> Result<(), AsyncError> {
        self.store.ensure_ready().await.map_err(to_async_error)
    }
}

#[async_trait]
impl CronJobRepository for SqliteCronJobRepository {
    async fn find(&self, id: &str) -> Result<Option<CronJob>, AsyncError> {
        self.store.find_by_id(id).await.map_err(to_async_error)
    }

    async fn find_by_name(&self, name: &str) -> Result<Option<CronJob>, AsyncError> {
        let sql = format!(
            "SELECT \"data\" FROM {t} WHERE {name} = ?1 LIMIT 1",
            t = self.store.table(),
            name = field!("name"),
        );
        self.store
            .query_opt(&sql, vec![SqlValue::Text(name.to_string())])
            .await
            .map_err(to_async_error)
    }

    async fn create(&self, cron: &CronJob) -> Result<(), AsyncError> {
        self.store.save(cron).await.map_err(to_async_error)
    }

    async fn update(&self, cron: &CronJob) -> Result<(), AsyncError> {
        self.store.save(cron).await.map_err(to_async_error)
    }

    async fn find_due(&self, now: DateTime<Utc>) -> Result<Vec<CronJob>, AsyncError> {
        // A JSON `true` comes back from `->>` as the integer 1, which
        // is why this compares against 1 rather than casting to a
        // boolean type SQLite does not have.
        let sql = format!(
            "SELECT \"data\" FROM {t} \
              WHERE {next} IS NOT NULL \
                AND {next} <= ?1 \
                AND {enabled} = 1 \
              ORDER BY {next} ASC",
            t = self.store.table(),
            next = field!("nextRunAt"),
            enabled = field!("enabled"),
        );
        self.store
            .query(&sql, vec![SqlValue::Integer(now.timestamp_millis())])
            .await
            .map_err(to_async_error)
    }
}

impl wabot_core::injection::IsSingleton for SqliteCronJobRepository {
    fn register_in(c: &wabot_core::injection::Container) {
        c.register_singleton_factory::<SqliteCronJobRepository, _>(|c2| {
            let database: Arc<SqliteDatabase> = c2.resolve();
            Arc::new(SqliteCronJobRepository::new(database.as_ref().clone()))
        });
    }
}

/// Storage failures surface as `AsyncError::Storage`, which the
/// scheduler loops already log-and-continue on — a database blip
/// should not kill the worker.
fn to_async_error(error: SqliteError) -> AsyncError {
    AsyncError::Storage(error.to_string())
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;
    use wabot_core::entity::EntityData;
    use wabot_feature_async::cron_job::{self, CronJobData};
    use wabot_feature_async::job::new_job;
    use wabot_feature_async::types::MisfirePolicy;

    fn ts(ms: i64) -> DateTime<Utc> {
        DateTime::<Utc>::from_timestamp_millis(ms).unwrap()
    }

    fn job(command: &str, scheduled_at: Option<i64>, dedup_key: Option<&str>) -> Job {
        new_job(JobData {
            base: EntityData::default(),
            command_name: command.into(),
            command_data: json!({}),
            scheduled_at,
            started_at: None,
            success_at: None,
            failed_at: None,
            retry_delays_seconds: None,
            intent_number: None,
            error: None,
            acceptable_running_time_seconds: None,
            stuck_retry_attempts: None,
            dedup_key: dedup_key.map(str::to_string),
            actor: None,
            request_id: None,
        })
    }

    async fn jobs() -> SqliteJobRepository {
        let repository = SqliteJobRepository::new(SqliteDatabase::in_memory().expect("open"));
        repository.ensure_ready().await.expect("ready");
        repository
    }

    #[tokio::test]
    async fn a_job_round_trips() {
        let repository = jobs().await;
        let job = job("ping", Some(1_000), None);
        repository.create(&job).await.expect("create");

        let found = repository
            .find(job.id())
            .await
            .expect("find")
            .expect("present");
        assert_eq!(found.data().command_name, "ping");

        repository.delete(&job).await.expect("delete");
        assert!(repository.find(job.id()).await.expect("find").is_none());
    }

    /// `create` upserts, because the runner re-saves a job it already
    /// created and a retry must not trip the primary key.
    #[tokio::test]
    async fn creating_the_same_job_twice_is_not_an_error() {
        let repository = jobs().await;
        let job = job("ping", Some(1), None);
        repository.create(&job).await.expect("create");
        repository.create(&job).await.expect("create again");
    }

    /// The scheduler's every-tick query, including the parts that keep
    /// finished work out of it.
    #[tokio::test]
    async fn pending_finds_only_unstarted_jobs_that_are_due() {
        let repository = jobs().await;

        repository
            .create(&job("due", Some(1_000), None))
            .await
            .unwrap();
        repository
            .create(&job("later", Some(9_000), None))
            .await
            .unwrap();
        repository
            .create(&job("unscheduled", None, None))
            .await
            .unwrap();

        let mut started = job("started", Some(1_000), None);
        started.update(|data| data.started_at = Some(1_500));
        repository.create(&started).await.unwrap();

        let mut done = job("done", Some(1_000), None);
        done.update(|data| data.success_at = Some(1_500));
        repository.create(&done).await.unwrap();

        let pending = repository
            .find_pending_for_run_from(ts(2_000), 10)
            .await
            .expect("pending");
        assert_eq!(
            pending
                .iter()
                .map(|j| j.data().command_name.as_str())
                .collect::<Vec<_>>(),
            vec!["due"]
        );
    }

    /// The claim `find_pending_for_run_from` rests on: `scheduledAt`
    /// compares as a number. Bound as text, 9000 would sort before
    /// 10000 and the limit would return the wrong jobs.
    #[tokio::test]
    async fn pending_orders_numerically_not_lexicographically() {
        let repository = jobs().await;
        for at in [9_000, 10_000, 800] {
            repository
                .create(&job(&format!("j{at}"), Some(at), None))
                .await
                .unwrap();
        }

        let pending = repository
            .find_pending_for_run_from(ts(20_000), 2)
            .await
            .expect("pending");
        assert_eq!(
            pending
                .iter()
                .map(|j| j.data().scheduled_at.unwrap())
                .collect::<Vec<_>>(),
            vec![800, 9_000],
            "lexicographic ordering would have put 10000 before 800 and 9000"
        );
    }

    #[tokio::test]
    async fn running_jobs_are_counted_per_command() {
        let repository = jobs().await;

        for command in ["build", "build", "deploy"] {
            let mut running = job(command, Some(1), None);
            running.update(|data| data.started_at = Some(2));
            repository.create(&running).await.unwrap();
        }
        // Started but finished: not running.
        let mut finished = job("build", Some(1), None);
        finished.update(|data| {
            data.started_at = Some(2);
            data.success_at = Some(3);
        });
        repository.create(&finished).await.unwrap();

        assert_eq!(repository.find_running().await.unwrap().len(), 3);
        assert_eq!(
            repository.count_running_by_command("build").await.unwrap(),
            2
        );
        assert_eq!(
            repository.count_running_by_command("absent").await.unwrap(),
            0
        );
    }

    #[tokio::test]
    async fn dedup_finds_an_active_job_and_respects_the_success_window() {
        let repository = jobs().await;

        repository
            .create(&job("send", Some(1), Some("key-1")))
            .await
            .unwrap();
        assert!(repository
            .find_active_by_dedup_key("send", "key-1", 0)
            .await
            .unwrap()
            .is_some());
        assert!(
            repository
                .find_active_by_dedup_key("send", "other", 0)
                .await
                .unwrap()
                .is_none(),
            "a different key is a different job"
        );

        // A job that succeeded long ago is outside the window.
        let mut old = job("send", Some(1), Some("key-2"));
        old.update(|data| data.success_at = Some(1_000));
        repository.create(&old).await.unwrap();
        assert!(repository
            .find_active_by_dedup_key("send", "key-2", 5_000)
            .await
            .unwrap()
            .is_none());
        assert!(repository
            .find_active_by_dedup_key("send", "key-2", 500)
            .await
            .unwrap()
            .is_some());

        // A failed job never dedups against a new one.
        let mut failed = job("send", Some(1), Some("key-3"));
        failed.update(|data| data.failed_at = Some(1_000));
        repository.create(&failed).await.unwrap();
        assert!(repository
            .find_active_by_dedup_key("send", "key-3", 0)
            .await
            .unwrap()
            .is_none());
    }

    fn cron(name: &str, next_run_at: Option<i64>, enabled: bool) -> CronJob {
        cron_job::new_cron_job(CronJobData {
            base: EntityData::default(),
            name: name.into(),
            command_name: "ping".into(),
            command_data: None,
            cron: "0 0 * * * *".into(),
            enabled,
            last_run_at: None,
            next_run_at,
            max_running_jobs: Some(1),
            misfire_policy: Some(MisfirePolicy::RunOnce),
            retry_delays_seconds: None,
            acceptable_running_time_seconds: None,
            stuck_retry_attempts: None,
        })
        .unwrap()
    }

    async fn crons() -> SqliteCronJobRepository {
        let repository = SqliteCronJobRepository::new(SqliteDatabase::in_memory().expect("open"));
        repository.ensure_ready().await.expect("ready");
        repository
    }

    #[tokio::test]
    async fn a_cron_round_trips_and_is_findable_by_name() {
        let repository = crons().await;
        let cron = cron("nightly", Some(1_000), true);
        repository.create(&cron).await.expect("create");

        assert_eq!(
            repository
                .find_by_name("nightly")
                .await
                .expect("find")
                .expect("present")
                .id(),
            cron.id()
        );
        assert!(repository.find_by_name("absent").await.unwrap().is_none());
    }

    #[tokio::test]
    async fn due_crons_exclude_disabled_and_future_ones() {
        let repository = crons().await;
        repository
            .create(&cron("due", Some(1_000), true))
            .await
            .unwrap();
        repository
            .create(&cron("later", Some(9_000), true))
            .await
            .unwrap();
        repository
            .create(&cron("off", Some(1_000), false))
            .await
            .unwrap();
        repository.create(&cron("never", None, true)).await.unwrap();

        let due = repository.find_due(ts(2_000)).await.expect("due");
        assert_eq!(
            due.iter()
                .map(|c| c.data().name.as_str())
                .collect::<Vec<_>>(),
            vec!["due"],
            "a JSON `true` reads back as 1, and a disabled cron must not fire"
        );
    }

    /// Two rows for one schedule means it fires twice, so the name
    /// index is unique rather than merely present.
    #[tokio::test]
    async fn two_crons_cannot_share_a_name() {
        let repository = crons().await;
        repository
            .create(&cron("nightly", Some(1), true))
            .await
            .unwrap();
        assert!(
            repository
                .create(&cron("nightly", Some(1), true))
                .await
                .is_err(),
            "the unique index refused the duplicate"
        );
    }
}