rust-job-queue-api-worker-system 0.1.0

A production-shaped Rust job queue: Axum API + async workers + Postgres SKIP LOCKED dequeue, retries with decorrelated jitter, idempotency, cooperative cancellation, OpenAPI, Prometheus metrics.
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
//! Integration tests for the `queue` module against a real Postgres
//! (Testcontainers). One container is shared by every test in this binary;
//! each test gets its own ephemeral database for isolation.

use std::time::Duration;

use rust_job_queue_api_worker_system::{
    queue::{self, CancelOutcome, ListFilter},
    JobKind, JobStatus, NewJob,
};
use serde_json::json;
use sqlx::query::query;
use testcontainers::{runners::AsyncRunner, ContainerAsync};
use testcontainers_modules::postgres::Postgres;
use tokio::sync::OnceCell;

struct Shared {
    port: u16,
    _container: ContainerAsync<Postgres>,
}

static SHARED: OnceCell<Shared> = OnceCell::const_new();

async fn shared() -> &'static Shared {
    SHARED
        .get_or_init(|| async {
            let container = Postgres::default()
                .start()
                .await
                .expect("start postgres container");
            let port = container
                .get_host_port_ipv4(5432)
                .await
                .expect("get host port");
            Shared {
                port,
                _container: container,
            }
        })
        .await
}

async fn fresh_pool() -> sqlx_postgres::PgPool {
    let s = shared().await;
    let port = s.port;

    let admin = sqlx_postgres::PgPool::connect(&format!(
        "postgres://postgres:postgres@127.0.0.1:{port}/postgres"
    ))
    .await
    .expect("admin connect");
    let db = format!("t{}", uuid::Uuid::now_v7().simple());
    query(&format!("CREATE DATABASE {db}"))
        .execute(&admin)
        .await
        .expect("create db");
    admin.close().await;

    let pool = sqlx_postgres::PgPool::connect(&format!(
        "postgres://postgres:postgres@127.0.0.1:{port}/{db}"
    ))
    .await
    .expect("pool connect");
    rust_job_queue_api_worker_system::migrate(&pool)
        .await
        .expect("run migrations");
    pool
}

fn email_payload() -> serde_json::Value {
    json!({ "to": "a@b.c", "subject": "hi", "body": "hello" })
}

// -------- enqueue --------

#[tokio::test]
async fn enqueue_creates_queued_row() {
    let pool = fresh_pool().await;
    let out = queue::enqueue(
        &pool,
        NewJob {
            kind: JobKind::SendEmail,
            payload: email_payload(),
            max_attempts: None,
            idempotency_key: None,
        },
    )
    .await
    .unwrap();

    assert!(out.is_new());
    let job = out.job();
    assert_eq!(job.status, JobStatus::Queued);
    assert_eq!(job.attempts, 0);
    assert_eq!(job.max_attempts, 3);
    assert_eq!(job.kind, JobKind::SendEmail);
    assert!(job.last_error.is_none());
    assert!(!job.cancel_requested);
}

#[tokio::test]
async fn enqueue_validates_payload() {
    let pool = fresh_pool().await;
    let err = queue::enqueue(
        &pool,
        NewJob {
            kind: JobKind::SendEmail,
            payload: json!({ "to": "a@b.c" }), // missing subject + body
            max_attempts: None,
            idempotency_key: None,
        },
    )
    .await
    .unwrap_err();
    assert_eq!(err.kind(), "payload_invalid");
}

#[tokio::test]
async fn enqueue_idempotent_on_same_key() {
    let pool = fresh_pool().await;
    let key = "user-42-welcome-email".to_string();

    let first = queue::enqueue(
        &pool,
        NewJob {
            kind: JobKind::SendEmail,
            payload: email_payload(),
            max_attempts: None,
            idempotency_key: Some(key.clone()),
        },
    )
    .await
    .unwrap();
    assert!(first.is_new());

    let second = queue::enqueue(
        &pool,
        NewJob {
            kind: JobKind::SendEmail,
            payload: email_payload(),
            max_attempts: None,
            idempotency_key: Some(key),
        },
    )
    .await
    .unwrap();
    assert!(!second.is_new());
    assert_eq!(first.job().id, second.job().id);
}

// -------- fetch_next --------

#[tokio::test]
async fn fetch_next_claims_queued_job() {
    let pool = fresh_pool().await;
    let enqueued = queue::enqueue(
        &pool,
        NewJob {
            kind: JobKind::SendEmail,
            payload: email_payload(),
            max_attempts: None,
            idempotency_key: None,
        },
    )
    .await
    .unwrap();

    let claimed = queue::fetch_next(&pool, "worker-A")
        .await
        .unwrap()
        .expect("a job is available");

    assert_eq!(claimed.id, enqueued.job().id);
    assert_eq!(claimed.status, JobStatus::Running);
    assert_eq!(claimed.attempts, 1);
    assert_eq!(claimed.locked_by.as_deref(), Some("worker-A"));
    assert!(claimed.locked_at.is_some());
}

#[tokio::test]
async fn fetch_next_returns_none_when_empty() {
    let pool = fresh_pool().await;
    let result = queue::fetch_next(&pool, "worker-A").await.unwrap();
    assert!(result.is_none());
}

#[tokio::test]
async fn fetch_next_skips_future_run_at() {
    let pool = fresh_pool().await;
    let job = queue::enqueue(
        &pool,
        NewJob {
            kind: JobKind::SendEmail,
            payload: email_payload(),
            max_attempts: None,
            idempotency_key: None,
        },
    )
    .await
    .unwrap();

    // Push run_at into the future.
    query("UPDATE jobs SET run_at = now() + interval '1 hour' WHERE id = $1")
        .bind(job.job().id.as_uuid())
        .execute(&pool)
        .await
        .unwrap();

    let claimed = queue::fetch_next(&pool, "worker-A").await.unwrap();
    assert!(claimed.is_none());
}

#[tokio::test]
async fn two_concurrent_workers_each_get_a_distinct_job() {
    let pool = fresh_pool().await;
    for _ in 0..2 {
        queue::enqueue(
            &pool,
            NewJob {
                kind: JobKind::SendEmail,
                payload: email_payload(),
                max_attempts: None,
                idempotency_key: None,
            },
        )
        .await
        .unwrap();
    }

    let p1 = pool.clone();
    let p2 = pool.clone();
    let (a, b) = tokio::join!(
        async move { queue::fetch_next(&p1, "w1").await.unwrap().unwrap() },
        async move { queue::fetch_next(&p2, "w2").await.unwrap().unwrap() },
    );

    assert_ne!(
        a.id, b.id,
        "two workers must claim distinct jobs under SKIP LOCKED"
    );
}

// -------- mark_succeeded --------

#[tokio::test]
async fn mark_succeeded_transitions_running_to_succeeded() {
    let pool = fresh_pool().await;
    let job = queue::enqueue(
        &pool,
        NewJob {
            kind: JobKind::SendEmail,
            payload: email_payload(),
            max_attempts: None,
            idempotency_key: None,
        },
    )
    .await
    .unwrap();
    let id = job.job().id;

    queue::fetch_next(&pool, "w").await.unwrap();
    queue::mark_succeeded(&pool, id).await.unwrap();

    let after = queue::get(&pool, id).await.unwrap().unwrap();
    assert_eq!(after.status, JobStatus::Succeeded);
    assert!(after.locked_by.is_none());
    assert!(after.locked_at.is_none());
}

#[tokio::test]
async fn mark_succeeded_errors_when_not_running() {
    let pool = fresh_pool().await;
    let job = queue::enqueue(
        &pool,
        NewJob {
            kind: JobKind::SendEmail,
            payload: email_payload(),
            max_attempts: None,
            idempotency_key: None,
        },
    )
    .await
    .unwrap();
    // Not yet claimed; still 'queued'.
    let err = queue::mark_succeeded(&pool, job.job().id)
        .await
        .unwrap_err();
    assert_eq!(err.kind(), "invalid_transition");
}

// -------- retry / permanent failure --------

#[tokio::test]
async fn mark_failed_returns_to_retrying_with_future_run_at() {
    let pool = fresh_pool().await;
    let job = queue::enqueue(
        &pool,
        NewJob {
            kind: JobKind::SendEmail,
            payload: email_payload(),
            max_attempts: Some(3),
            idempotency_key: None,
        },
    )
    .await
    .unwrap();
    let id = job.job().id;

    let before = chrono::Utc::now();
    queue::fetch_next(&pool, "w").await.unwrap(); // attempts=1
    let updated = queue::mark_failed_or_retry(&pool, id, "boom")
        .await
        .unwrap();

    assert_eq!(updated.status, JobStatus::Retrying);
    assert_eq!(updated.attempts, 1);
    assert_eq!(updated.last_error.as_deref(), Some("boom"));
    assert!(updated.run_at > before, "run_at should be in the future");
}

#[tokio::test]
async fn mark_failed_lands_in_failed_permanent_at_max_attempts() {
    let pool = fresh_pool().await;
    let job = queue::enqueue(
        &pool,
        NewJob {
            kind: JobKind::SendEmail,
            payload: email_payload(),
            max_attempts: Some(1),
            idempotency_key: None,
        },
    )
    .await
    .unwrap();
    let id = job.job().id;

    queue::fetch_next(&pool, "w").await.unwrap(); // attempts becomes 1; equal to max
    let updated = queue::mark_failed_or_retry(&pool, id, "fatal")
        .await
        .unwrap();

    assert_eq!(updated.status, JobStatus::FailedPermanent);
    assert_eq!(updated.last_error.as_deref(), Some("fatal"));
}

// -------- cancellation --------

#[tokio::test]
async fn request_cancel_on_queued_cancels_immediately() {
    let pool = fresh_pool().await;
    let job = queue::enqueue(
        &pool,
        NewJob {
            kind: JobKind::SendEmail,
            payload: email_payload(),
            max_attempts: None,
            idempotency_key: None,
        },
    )
    .await
    .unwrap();

    let outcome = queue::request_cancel(&pool, job.job().id).await.unwrap();
    assert_eq!(outcome, CancelOutcome::CancelledNow);

    let after = queue::get(&pool, job.job().id).await.unwrap().unwrap();
    assert_eq!(after.status, JobStatus::Cancelled);
}

#[tokio::test]
async fn request_cancel_on_running_sets_pending_flag() {
    let pool = fresh_pool().await;
    let job = queue::enqueue(
        &pool,
        NewJob {
            kind: JobKind::SendEmail,
            payload: email_payload(),
            max_attempts: None,
            idempotency_key: None,
        },
    )
    .await
    .unwrap();

    queue::fetch_next(&pool, "w").await.unwrap();
    let outcome = queue::request_cancel(&pool, job.job().id).await.unwrap();
    assert_eq!(outcome, CancelOutcome::PendingOnWorker);

    let after = queue::get(&pool, job.job().id).await.unwrap().unwrap();
    assert!(after.cancel_requested);
    assert_eq!(after.status, JobStatus::Running);

    // Worker observes and finalises.
    queue::finalize_cancelled(&pool, job.job().id)
        .await
        .unwrap();
    let after = queue::get(&pool, job.job().id).await.unwrap().unwrap();
    assert_eq!(after.status, JobStatus::Cancelled);
}

#[tokio::test]
async fn request_cancel_on_terminal_is_noop() {
    let pool = fresh_pool().await;
    let job = queue::enqueue(
        &pool,
        NewJob {
            kind: JobKind::SendEmail,
            payload: email_payload(),
            max_attempts: None,
            idempotency_key: None,
        },
    )
    .await
    .unwrap();
    queue::fetch_next(&pool, "w").await.unwrap();
    queue::mark_succeeded(&pool, job.job().id).await.unwrap();

    let outcome = queue::request_cancel(&pool, job.job().id).await.unwrap();
    assert_eq!(
        outcome,
        CancelOutcome::AlreadyTerminal(JobStatus::Succeeded)
    );
}

#[tokio::test]
async fn request_cancel_on_missing_id_returns_not_found() {
    let pool = fresh_pool().await;
    let err = queue::request_cancel(&pool, rust_job_queue_api_worker_system::JobId::new())
        .await
        .unwrap_err();
    assert_eq!(err.kind(), "not_found");
}

// -------- recovery sweep --------

#[tokio::test]
async fn recover_stale_resets_old_running_rows() {
    let pool = fresh_pool().await;
    let job = queue::enqueue(
        &pool,
        NewJob {
            kind: JobKind::SendEmail,
            payload: email_payload(),
            max_attempts: None,
            idempotency_key: None,
        },
    )
    .await
    .unwrap();

    queue::fetch_next(&pool, "doomed-worker").await.unwrap();

    // Backdate the lock so it looks stale.
    query("UPDATE jobs SET locked_at = now() - interval '1 hour' WHERE id = $1")
        .bind(job.job().id.as_uuid())
        .execute(&pool)
        .await
        .unwrap();

    let recovered = queue::recover_stale(&pool, 60).await.unwrap();
    assert_eq!(recovered, 1);

    let after = queue::get(&pool, job.job().id).await.unwrap().unwrap();
    assert_eq!(after.status, JobStatus::Retrying);
    assert!(after.locked_by.is_none());
}

// -------- list / get --------

#[tokio::test]
async fn list_filters_by_status_and_kind() {
    let pool = fresh_pool().await;

    let a = queue::enqueue(
        &pool,
        NewJob {
            kind: JobKind::SendEmail,
            payload: email_payload(),
            max_attempts: None,
            idempotency_key: None,
        },
    )
    .await
    .unwrap();
    let _b = queue::enqueue(
        &pool,
        NewJob {
            kind: JobKind::SummarizeText,
            payload: json!({ "text": "lorem ipsum" }),
            max_attempts: None,
            idempotency_key: None,
        },
    )
    .await
    .unwrap();
    queue::fetch_next(&pool, "w").await.unwrap();
    queue::mark_succeeded(&pool, a.job().id).await.unwrap();

    let succeeded = queue::list(
        &pool,
        ListFilter {
            status: Some(JobStatus::Succeeded),
            ..Default::default()
        },
    )
    .await
    .unwrap();
    assert_eq!(succeeded.len(), 1);
    assert_eq!(succeeded[0].id, a.job().id);

    let summarize = queue::list(
        &pool,
        ListFilter {
            kind: Some(JobKind::SummarizeText),
            ..Default::default()
        },
    )
    .await
    .unwrap();
    assert_eq!(summarize.len(), 1);
}

#[tokio::test]
async fn get_returns_none_for_unknown_id() {
    let pool = fresh_pool().await;
    let res = queue::get(&pool, rust_job_queue_api_worker_system::JobId::new())
        .await
        .unwrap();
    assert!(res.is_none());
}

// -------- jitter sanity at the integration layer --------

#[tokio::test]
async fn retry_run_at_advances_by_at_least_base_backoff() {
    let pool = fresh_pool().await;
    let job = queue::enqueue(
        &pool,
        NewJob {
            kind: JobKind::SendEmail,
            payload: email_payload(),
            max_attempts: Some(3),
            idempotency_key: None,
        },
    )
    .await
    .unwrap();
    let id = job.job().id;
    let before = chrono::Utc::now();

    queue::fetch_next(&pool, "w").await.unwrap();
    let updated = queue::mark_failed_or_retry(&pool, id, "err").await.unwrap();

    let delta = (updated.run_at - before).to_std().unwrap_or(Duration::ZERO);
    assert!(
        delta >= Duration::from_millis(900), // BASE_MS minus small slack
        "expected at least ~1s backoff, got {delta:?}"
    );
}