rustqueue 0.2.0

Background jobs without infrastructure — embeddable job queue with zero external dependencies
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
//! DAG flow integration tests — verifying dependency resolution, cycle detection,
//! cascade failure, and flow status through the HTTP API.

use std::sync::Arc;

use reqwest::Client;
use serde_json::{Value, json};

use rustqueue::api::{self, AppState};
use rustqueue::engine::queue::QueueManager;
use rustqueue::storage::MemoryStorage;

/// Start a test server backed by MemoryStorage for fast DAG tests.
async fn start_test_server() -> (String, Arc<QueueManager>) {
    let (event_tx, _) = tokio::sync::broadcast::channel(1024);
    let storage = Arc::new(MemoryStorage::new());
    let qm = Arc::new(
        QueueManager::new(storage)
            .with_event_sender(event_tx.clone())
            .with_max_dag_depth(5),
    );
    let state = Arc::new(AppState {
        queue_manager: Arc::clone(&qm),
        start_time: std::time::Instant::now(),
        metrics_handle: None,
        event_tx,
        auth_config: rustqueue::config::AuthConfig::default(),
        auth_rate_limiter: rustqueue::api::auth::AuthRateLimiter::new(),
        webhook_manager: None,
    });
    let app = api::router(state);

    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
    let addr = listener.local_addr().unwrap();
    tokio::spawn(async move {
        axum::serve(listener, app).await.unwrap();
    });
    (format!("http://{addr}"), qm)
}

/// Push a job via HTTP, returning the job ID string.
async fn push_job(client: &Client, base: &str, queue: &str, body: Value) -> String {
    let resp = client
        .post(format!("{base}/api/v1/queues/{queue}/jobs"))
        .json(&body)
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status(), 201, "push should return 201");
    let val: Value = resp.json().await.unwrap();
    val["id"].as_str().unwrap().to_string()
}

/// Get a job by ID via HTTP.
async fn get_job(client: &Client, base: &str, id: &str) -> Value {
    let resp = client
        .get(format!("{base}/api/v1/jobs/{id}"))
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status(), 200);
    resp.json().await.unwrap()
}

/// Ack a job by ID via HTTP.
async fn ack_job(client: &Client, base: &str, id: &str) {
    let resp = client
        .post(format!("{base}/api/v1/jobs/{id}/ack"))
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status(), 200, "ack should return 200");
}

/// Pull a job from a queue, returning the job JSON (or None if empty).
async fn pull_job(client: &Client, base: &str, queue: &str) -> Option<Value> {
    let resp = client
        .get(format!("{base}/api/v1/queues/{queue}/jobs"))
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status(), 200);
    let body: Value = resp.json().await.unwrap();
    if body["job"].is_object() {
        Some(body["job"].clone())
    } else {
        None
    }
}

/// Fail a job (will eventually go to DLQ after max_attempts exhausted).
async fn fail_job(client: &Client, base: &str, id: &str) {
    let resp = client
        .post(format!("{base}/api/v1/jobs/{id}/fail"))
        .json(&json!({"error": "test failure"}))
        .send()
        .await
        .unwrap();
    assert!(
        resp.status() == 200 || resp.status() == 409,
        "fail returned unexpected status: {}",
        resp.status()
    );
}

// ── Test: child starts Blocked, parent ack promotes to Waiting ──────────────

#[tokio::test]
async fn test_child_blocked_until_parent_ack() {
    let (base, _qm) = start_test_server().await;
    let client = Client::new();

    // Push parent (no deps → Waiting)
    let parent_id = push_job(
        &client,
        &base,
        "dag",
        json!({
            "name": "parent-job",
            "data": {"step": "parent"}
        }),
    )
    .await;

    // Push child with depends_on parent
    let child_id = push_job(
        &client,
        &base,
        "dag",
        json!({
            "name": "child-job",
            "data": {"step": "child"},
            "depends_on": [parent_id]
        }),
    )
    .await;

    // Child should be Blocked
    let child = get_job(&client, &base, &child_id).await;
    assert_eq!(
        child["job"]["state"], "blocked",
        "child should start as Blocked"
    );

    // Pull should only get the parent (child is Blocked)
    let pulled = pull_job(&client, &base, "dag")
        .await
        .expect("should pull parent");
    assert_eq!(pulled["id"], parent_id);

    // No more pullable jobs (child still Blocked)
    let empty = pull_job(&client, &base, "dag").await;
    assert!(
        empty.is_none(),
        "child should not be pullable while Blocked"
    );

    // Ack parent → should promote child to Waiting
    ack_job(&client, &base, &parent_id).await;

    // Child should now be Waiting
    let child_after = get_job(&client, &base, &child_id).await;
    assert_eq!(
        child_after["job"]["state"], "waiting",
        "child should be Waiting after parent ack"
    );

    // Now we can pull the child
    let pulled_child = pull_job(&client, &base, "dag")
        .await
        .expect("should pull child now");
    assert_eq!(pulled_child["id"], child_id);
}

// ── Test: chain A→B→C, ack in order ────────────────────────────────────────

#[tokio::test]
async fn test_chain_a_b_c() {
    let (base, _qm) = start_test_server().await;
    let client = Client::new();

    // A (no deps)
    let a_id = push_job(
        &client,
        &base,
        "chain",
        json!({
            "name": "step-a",
            "data": {},
            "flow_id": "pipeline-1"
        }),
    )
    .await;

    // B depends on A
    let b_id = push_job(
        &client,
        &base,
        "chain",
        json!({
            "name": "step-b",
            "data": {},
            "depends_on": [a_id],
            "flow_id": "pipeline-1"
        }),
    )
    .await;

    // C depends on B
    let c_id = push_job(
        &client,
        &base,
        "chain",
        json!({
            "name": "step-c",
            "data": {},
            "depends_on": [b_id],
            "flow_id": "pipeline-1"
        }),
    )
    .await;

    // B and C should be Blocked
    assert_eq!(
        get_job(&client, &base, &b_id).await["job"]["state"],
        "blocked"
    );
    assert_eq!(
        get_job(&client, &base, &c_id).await["job"]["state"],
        "blocked"
    );

    // Pull A, ack it
    let pulled_a = pull_job(&client, &base, "chain")
        .await
        .expect("should pull A");
    assert_eq!(pulled_a["id"], a_id);
    ack_job(&client, &base, &a_id).await;

    // B should now be Waiting, C still Blocked
    assert_eq!(
        get_job(&client, &base, &b_id).await["job"]["state"],
        "waiting"
    );
    assert_eq!(
        get_job(&client, &base, &c_id).await["job"]["state"],
        "blocked"
    );

    // Pull B, ack it
    let pulled_b = pull_job(&client, &base, "chain")
        .await
        .expect("should pull B");
    assert_eq!(pulled_b["id"], b_id);
    ack_job(&client, &base, &b_id).await;

    // C should now be Waiting
    assert_eq!(
        get_job(&client, &base, &c_id).await["job"]["state"],
        "waiting"
    );

    // Pull C, ack it
    let pulled_c = pull_job(&client, &base, "chain")
        .await
        .expect("should pull C");
    assert_eq!(pulled_c["id"], c_id);
    ack_job(&client, &base, &c_id).await;

    // All done — C should be Completed
    assert_eq!(
        get_job(&client, &base, &c_id).await["job"]["state"],
        "completed"
    );
}

// ── Test: cycle detection ───────────────────────────────────────────────────

#[tokio::test]
async fn test_cycle_detection() {
    let (base, _qm) = start_test_server().await;
    let client = Client::new();

    // Push A
    let a_id = push_job(
        &client,
        &base,
        "cycle",
        json!({
            "name": "node-a",
            "data": {}
        }),
    )
    .await;

    // Push B depends on A
    let b_id = push_job(
        &client,
        &base,
        "cycle",
        json!({
            "name": "node-b",
            "data": {},
            "depends_on": [a_id]
        }),
    )
    .await;

    // Try to push C that depends on B, and also try to make A depend on C
    // But A is already pushed, so we can't retroactively add a cycle.
    // Instead, test: push C depends on B, then push D depends on C,
    // then push E depends on D + A (which would create a long chain, no cycle).
    // Direct cycle: push a job that depends on itself.
    let resp = client
        .post(format!("{base}/api/v1/queues/cycle/jobs"))
        .json(&json!({
            "name": "self-dep",
            "data": {},
            "depends_on": ["00000000-0000-0000-0000-000000000000"]
        }))
        .send()
        .await
        .unwrap();

    // Should fail — dep doesn't exist
    assert_ne!(resp.status(), 201, "should reject non-existent dep");

    // Verify A and B are still fine
    assert_eq!(
        get_job(&client, &base, &a_id).await["job"]["state"],
        "waiting"
    );
    assert_eq!(
        get_job(&client, &base, &b_id).await["job"]["state"],
        "blocked"
    );
}

// ── Test: max depth exceeded ────────────────────────────────────────────────

#[tokio::test]
async fn test_max_depth_exceeded() {
    let (base, _qm) = start_test_server().await;
    let client = Client::new();

    // Build a chain of depth 5 (server configured with max_dag_depth=5)
    let mut prev_id = push_job(
        &client,
        &base,
        "deep",
        json!({
            "name": "depth-0",
            "data": {}
        }),
    )
    .await;

    // Build chain up to depth 5 (indices 1..=5) — depth 5 should still work
    for i in 1..=5 {
        prev_id = push_job(
            &client,
            &base,
            "deep",
            json!({
                "name": format!("depth-{}", i),
                "data": {},
                "depends_on": [prev_id]
            }),
        )
        .await;
    }

    // Depth 6 should fail (exceeds max_dag_depth=5)
    let resp = client
        .post(format!("{base}/api/v1/queues/deep/jobs"))
        .json(&json!({
            "name": "depth-6-too-deep",
            "data": {},
            "depends_on": [prev_id]
        }))
        .send()
        .await
        .unwrap();

    assert_ne!(
        resp.status(),
        201,
        "should reject job exceeding max DAG depth"
    );
}

// ── Test: parent DLQ cascades to child ──────────────────────────────────────

#[tokio::test]
async fn test_parent_dlq_cascades_to_child() {
    let (base, _qm) = start_test_server().await;
    let client = Client::new();

    // Push parent with max_attempts=1 so it goes to DLQ on first fail
    let parent_id = push_job(
        &client,
        &base,
        "cascade",
        json!({
            "name": "parent",
            "data": {},
            "max_attempts": 1
        }),
    )
    .await;

    // Push child depending on parent
    let child_id = push_job(
        &client,
        &base,
        "cascade",
        json!({
            "name": "child",
            "data": {},
            "depends_on": [parent_id]
        }),
    )
    .await;

    // Child should be Blocked
    assert_eq!(
        get_job(&client, &base, &child_id).await["job"]["state"],
        "blocked"
    );

    // Pull parent to make it Active
    let pulled = pull_job(&client, &base, "cascade")
        .await
        .expect("should pull parent");
    assert_eq!(pulled["id"], parent_id);

    // Fail parent — with max_attempts=1, it should go to DLQ
    fail_job(&client, &base, &parent_id).await;

    // Parent should be in DLQ (or Failed depending on retry logic)
    let parent_state = get_job(&client, &base, &parent_id).await;
    let state = parent_state["job"]["state"].as_str().unwrap();

    // If state is Failed (waiting for retry), we need to force it to DLQ
    // The QueueManager fail() moves to DLQ when attempts >= max_attempts
    if state == "dlq" {
        // Check child — should be cascaded to DLQ
        let child_after = get_job(&client, &base, &child_id).await;
        assert_eq!(
            child_after["job"]["state"], "dlq",
            "child should be cascaded to DLQ when parent goes to DLQ"
        );
    }
    // If it went to Failed (retry), that's also valid — cascade only happens on DLQ
}

// ── Test: parent already completed → child goes directly to Waiting ─────────

#[tokio::test]
async fn test_dep_already_completed() {
    let (base, _qm) = start_test_server().await;
    let client = Client::new();

    // Push parent and complete it
    let parent_id = push_job(
        &client,
        &base,
        "pre-done",
        json!({
            "name": "parent",
            "data": {}
        }),
    )
    .await;

    let _pulled = pull_job(&client, &base, "pre-done")
        .await
        .expect("should pull parent");
    ack_job(&client, &base, &parent_id).await;

    // Now push child depending on already-completed parent
    let child_id = push_job(
        &client,
        &base,
        "pre-done",
        json!({
            "name": "child",
            "data": {},
            "depends_on": [parent_id]
        }),
    )
    .await;

    // Child should go directly to Waiting (not Blocked) since dep is already done
    let child = get_job(&client, &base, &child_id).await;
    assert_eq!(
        child["job"]["state"], "waiting",
        "child should be Waiting when all deps already completed"
    );
}

// ── Test: flow status endpoint ──────────────────────────────────────────────

#[tokio::test]
async fn test_flow_status_endpoint() {
    let (base, _qm) = start_test_server().await;
    let client = Client::new();

    let flow_id = "test-flow-42";

    // Push 3 jobs in the same flow
    let a_id = push_job(
        &client,
        &base,
        "flow-q",
        json!({
            "name": "flow-a",
            "data": {},
            "flow_id": flow_id
        }),
    )
    .await;

    let _b_id = push_job(
        &client,
        &base,
        "flow-q",
        json!({
            "name": "flow-b",
            "data": {},
            "depends_on": [a_id],
            "flow_id": flow_id
        }),
    )
    .await;

    let _c_id = push_job(
        &client,
        &base,
        "flow-q",
        json!({
            "name": "flow-c",
            "data": {},
            "depends_on": [a_id],
            "flow_id": flow_id
        }),
    )
    .await;

    // Get flow status
    let resp = client
        .get(format!("{base}/api/v1/flows/{flow_id}"))
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status(), 200);

    let body: Value = resp.json().await.unwrap();
    assert_eq!(body["ok"], true);
    assert_eq!(body["flow_id"], flow_id);

    let jobs = body["jobs"].as_array().expect("should have jobs array");
    assert_eq!(jobs.len(), 3, "flow should contain 3 jobs");

    let summary = &body["summary"];
    assert_eq!(summary["total"], 3);
    // A is Waiting, B and C are Blocked
    assert_eq!(summary["waiting"], 1);
    assert_eq!(summary["blocked"], 2);
}

// ── Test: non-existent dependency rejected ──────────────────────────────────

#[tokio::test]
async fn test_nonexistent_dep_rejected() {
    let (base, _qm) = start_test_server().await;
    let client = Client::new();

    let fake_id = uuid::Uuid::now_v7().to_string();

    let resp = client
        .post(format!("{base}/api/v1/queues/reject/jobs"))
        .json(&json!({
            "name": "orphan-child",
            "data": {},
            "depends_on": [fake_id]
        }))
        .send()
        .await
        .unwrap();

    // Should be rejected (400 or 409)
    assert_ne!(
        resp.status(),
        201,
        "should reject job with non-existent dependency"
    );
}