laravel-rust-workflow 0.2.0

Internal crate of Laravel for Rust: durable workflows. Depend on `laravel-rust` instead
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
//! The contract every workflow store keeps, which the stores' tests run. The database store's test
//! needs an application, so it lives in the `laravel-rust` package and reaches the contract
//! through the `testing` feature.

use std::collections::BTreeMap;
use std::time::Duration;

use jiff::Timestamp;

use super::store::{PURGED_INPUT, *};
use super::{ErasedStore, RunId, Status};

fn new_run(id: RunId, now: Timestamp) -> NewRun {
    NewRun {
        id,
        workflow: "orders.checkout".into(),
        input: "{\"order_id\":1}".into(),
        context: "{}".into(),
        connection: "sync".into(),
        queue: "default".into(),
        created_at: now,
        wake_at: now,
        attributes: BTreeMap::from([("tenant".into(), "acme".into())]),
        unique: None,
        purge: false,
        tokens: Vec::new(),
    }
}

/// What every store must do: hand a run's lease to one claimer at a time, let one unfinished run
/// own a token, give a resume to the token's owner and nothing to a token without one, and number
/// a run's values in order.
pub async fn contract(store: &dyn ErasedStore) {
    let now = Timestamp::from_second(1_800_000_000).unwrap();
    let id = RunId::generate();
    assert_eq!(store.create(new_run(id, now)).await.unwrap(), Created::Saved);

    let Claim::Claimed { run, entries, lease } = store.claim(id, Duration::from_secs(60)).await.unwrap() else {
        panic!("the first claim takes the lease");
    };
    assert_eq!(
        (run.status, run.input.as_str(), entries.len()),
        (Status::Running, "{\"order_id\":1}", 0)
    );
    assert_eq!(store.claim(id, Duration::from_secs(60)).await.unwrap(), Claim::Held);
    assert_eq!(run.attributes["tenant"], "acme");

    let entry = Entry {
        kind: Kind::Step,
        name: "charge card".into(),
        status: EntryStatus::Pending,
        tries: 1,
        output: None,
        error: Some("declined".into()),
        wake_at: Some(now),
        started_at: now,
        finished_at: None,
    };
    assert!(store.record(id, &lease, entry.clone()).await.unwrap());
    let completed = Entry {
        status: EntryStatus::Completed,
        tries: 2,
        output: Some("\"re_1\"".into()),
        error: None,
        finished_at: Some(now),
        ..entry
    };
    assert!(store.record(id, &lease, completed.clone()).await.unwrap());
    assert_eq!(
        store.entries(id).await.unwrap(),
        [completed],
        "an entry replaces its namesake"
    );

    // A resume for a token that no run owns keeps nothing, and a wait claims the token...
    assert_eq!(store.resume("late", "1".into()).await.unwrap(), Delivery::NotFound);
    assert_eq!(store.wait(id, &lease, "late", 1).await.unwrap(), Waited::Waiting);
    assert_eq!(store.waiting("late").await.unwrap(), Some(id));
    assert_eq!(store.resume("late", "2".into()).await.unwrap(), Delivery::Due(id));
    assert_eq!(
        store.wait(id, &lease, "late", 1).await.unwrap(),
        Waited::Value("2".into())
    );
    assert_eq!(
        store.waiting("late").await.unwrap(),
        None,
        "a run that took its value doesn't wait"
    );

    // The run still owns the token, so a value that arrives while it doesn't wait queues on it...
    assert_eq!(store.resume("late", "3".into()).await.unwrap(), Delivery::Queued(id));
    assert_eq!(
        store.wait(id, &lease, "late", 2).await.unwrap(),
        Waited::Value("3".into())
    );
    assert_eq!(store.wait(id, &lease, "late", 3).await.unwrap(), Waited::Waiting);
    assert_eq!(store.resume("late", "4".into()).await.unwrap(), Delivery::Due(id));
    assert_eq!(store.wait(id, &lease, "timeout", 1).await.unwrap(), Waited::Waiting);
    assert!(store.stop_waiting(id, &lease, "timeout").await.unwrap());
    assert_eq!(store.resume("timeout", "5".into()).await.unwrap(), Delivery::Queued(id));

    assert!(
        store
            .release(id, &lease, Outcome::Waiting { wake_at: None }, now)
            .await
            .unwrap()
    );
    assert!(
        !store
            .release(id, &lease, Outcome::Waiting { wake_at: None }, now)
            .await
            .unwrap()
    );
    let overdue: Vec<RunId> = store.overdue(now).await.unwrap().iter().map(|run| run.id).collect();
    assert_eq!(overdue, [id], "a value the run waits for and hasn't read is due");

    // Reading the value ends the wait, so the run is no longer due...
    let Claim::Claimed { lease, .. } = store.claim(id, Duration::ZERO).await.unwrap() else {
        panic!("the second claim takes the lease");
    };
    assert_eq!(
        store.wait(id, &lease, "late", 3).await.unwrap(),
        Waited::Value("4".into())
    );
    assert!(
        store
            .release(id, &lease, Outcome::Waiting { wake_at: None }, now)
            .await
            .unwrap()
    );
    assert!(store.overdue(now).await.unwrap().is_empty(), "taken values aren't due");
    let Claim::Claimed { lease, .. } = store.claim(id, Duration::ZERO).await.unwrap() else {
        panic!("the third claim takes the lease");
    };
    let labels = BTreeMap::from([("tenant".into(), "acme".into()), ("phase".into(), "billing".into())]);
    assert!(store.set_attributes(id, &lease, labels).await.unwrap());
    let failed = Outcome::Failed {
        error: "the step `charge card` failed".into(),
    };
    assert!(store.release(id, &lease, failed, now).await.unwrap());
    assert_eq!(store.claim(id, Duration::from_secs(60)).await.unwrap(), Claim::Ended);
    assert_eq!(
        store.resume("late", "6".into()).await.unwrap(),
        Delivery::NotFound,
        "a failed run gives up its tokens"
    );

    let mut filter = Filter {
        status: Some(Status::Failed),
        workflow: None,
        attributes: BTreeMap::from([("phase".into(), "billing".into())]),
        limit: 10,
    };
    let listed = store.list(filter.clone()).await.unwrap();
    assert_eq!(listed.iter().map(|run| run.id).collect::<Vec<_>>(), [id]);
    assert_eq!(listed[0].attributes.len(), 2);
    filter.attributes.insert("tenant".into(), "other".into());
    assert!(
        store.list(filter).await.unwrap().is_empty(),
        "every attribute must match"
    );
    assert!(store.retry(id, now).await.unwrap());
    assert_eq!(store.find(id).await.unwrap().unwrap().status, Status::Pending);
    assert_eq!(store.overdue(now).await.unwrap().len(), 1);
    let Claim::Claimed { lease, .. } = store.claim(id, Duration::from_secs(60)).await.unwrap() else {
        panic!("a retried run can be claimed again");
    };
    assert_eq!(
        store.wait(id, &lease, "late", 1).await.unwrap(),
        Waited::Value("2".into()),
        "a retried run claims its token again and reads its values again"
    );
    assert!(store.cancel(id, Some("closed".into()), now).await.unwrap());
    assert!(!store.cancel(id, None, now).await.unwrap());
    assert!(
        !store.renew(id, &lease, Duration::from_secs(60)).await.unwrap(),
        "cancelling revokes the held lease"
    );
    let cancelled = store.find(id).await.unwrap().unwrap();
    assert_eq!(
        (cancelled.status, cancelled.error.as_deref()),
        (Status::Cancelled, Some("closed"))
    );
    assert_eq!(
        store.resume("late", "7".into()).await.unwrap(),
        Delivery::NotFound,
        "a cancelled run gives up its tokens"
    );
    assert_eq!(
        store.prune(now).await.unwrap(),
        0,
        "a run that finished at `now` isn't before it"
    );
    assert_eq!(store.prune(now + jiff::SignedDuration::from_secs(1)).await.unwrap(), 1);
    assert_eq!(store.find(id).await.unwrap(), None);

    // One unfinished run owns a token at a time, from its start when it claims the token there...
    let token = "expenses.5.decision";
    let (owner, rival, later) = (RunId::generate(), RunId::generate(), RunId::generate());
    let claiming = |id| NewRun {
        tokens: vec![token.into()],
        ..new_run(id, now)
    };
    assert_eq!(store.create(claiming(owner)).await.unwrap(), Created::Saved);
    assert_eq!(
        store.resume(token, "\"early\"".into()).await.unwrap(),
        Delivery::Queued(owner),
        "a run that claims a token at its start keeps the values sent before it waits"
    );
    assert_eq!(
        store.create(claiming(rival)).await.unwrap(),
        Created::Taken {
            token: token.into(),
            owner
        }
    );
    assert_eq!(store.find(rival).await.unwrap(), None);
    assert_eq!(store.create(new_run(later, now)).await.unwrap(), Created::Saved);
    let Claim::Claimed { lease: later_lease, .. } = store.claim(later, Duration::from_secs(60)).await.unwrap() else {
        panic!("the later run takes its lease");
    };
    assert_eq!(
        store.wait(later, &later_lease, token, 1).await.unwrap(),
        Waited::Taken(owner)
    );
    let Claim::Claimed { lease: owner_lease, .. } = store.claim(owner, Duration::ZERO).await.unwrap() else {
        panic!("the owner takes its lease");
    };
    assert_eq!(
        store.wait(owner, &owner_lease, token, 1).await.unwrap(),
        Waited::Value("\"early\"".into())
    );
    let completed = Outcome::Completed { output: "null".into() };
    assert!(store.release(owner, &owner_lease, completed, now).await.unwrap());

    // ...and a finished run gives the token up, so a stale value reaches no later run...
    assert_eq!(
        store.resume(token, "\"stale\"".into()).await.unwrap(),
        Delivery::NotFound
    );
    assert_eq!(
        store.wait(later, &later_lease, token, 1).await.unwrap(),
        Waited::Waiting,
        "a later run claims the token and reads none of the old values"
    );
    assert_eq!(store.waiting(token).await.unwrap(), Some(later));
    assert!(store.cancel(later, None, now).await.unwrap());

    // An unfinished run holds its unique key, and a finished one gives it up...
    let (first, second, third) = (RunId::generate(), RunId::generate(), RunId::generate());
    let unique = |id| NewRun {
        unique: Some("orders.42".into()),
        ..new_run(id, now)
    };
    assert_eq!(store.create(unique(first)).await.unwrap(), Created::Saved);
    assert_eq!(store.create(unique(second)).await.unwrap(), Created::Existing(first));
    assert_eq!(store.find(second).await.unwrap(), None);
    assert!(store.cancel(first, None, now).await.unwrap());
    assert_eq!(store.create(unique(third)).await.unwrap(), Created::Saved);

    // A purged run loses its data when it finishes, and can't be retried...
    let purged = RunId::generate();
    let run = NewRun {
        purge: true,
        ..new_run(purged, now)
    };
    store.create(run).await.unwrap();
    let Claim::Claimed {
        lease: purged_lease, ..
    } = store.claim(purged, Duration::ZERO).await.unwrap()
    else {
        panic!("the purged run takes its lease");
    };
    let step = Entry {
        kind: Kind::Step,
        name: "read bank details".into(),
        status: EntryStatus::Completed,
        tries: 1,
        output: Some("\"DE89\"".into()),
        error: None,
        wake_at: None,
        started_at: now,
        finished_at: Some(now),
    };
    assert!(store.record(purged, &purged_lease, step).await.unwrap());
    let failed = Outcome::Failed { error: "secret".into() };
    assert!(store.release(purged, &purged_lease, failed, now).await.unwrap());
    let record = store.find(purged).await.unwrap().unwrap();
    assert_eq!(
        (
            record.status,
            record.input.as_str(),
            record.error,
            record.attributes.len()
        ),
        (Status::Failed, PURGED_INPUT, None, 1)
    );
    let entries = store.entries(purged).await.unwrap();
    assert_eq!(
        (entries[0].name.as_str(), entries[0].output.as_deref()),
        ("read bank details", None)
    );
    assert!(!store.retry(purged, now).await.unwrap());

    // A stale lease whose claim expired and was taken over can't write, renew, or release...
    let fenced = RunId::generate();
    assert_eq!(store.create(new_run(fenced, now)).await.unwrap(), Created::Saved);
    let Claim::Claimed { lease: stale, .. } = store.claim(fenced, Duration::ZERO).await.unwrap() else {
        panic!("the first worker takes the lease");
    };
    let Claim::Claimed { lease: current, .. } = store.claim(fenced, Duration::from_secs(60)).await.unwrap() else {
        panic!("a second worker reclaims an expired lease");
    };
    assert_ne!(stale, current, "each claim must issue a distinct lease token");

    let current_step = Entry {
        kind: Kind::Step,
        name: "charge".into(),
        status: EntryStatus::Completed,
        tries: 1,
        output: Some("\"current\"".into()),
        error: None,
        wake_at: None,
        started_at: now,
        finished_at: Some(now),
    };
    let stale_step = Entry {
        output: Some("\"stale\"".into()),
        ..current_step.clone()
    };
    assert!(store.record(fenced, &current, current_step.clone()).await.unwrap());
    assert!(
        store
            .set_attributes(fenced, &current, BTreeMap::from([("owner".into(), "current".into())]))
            .await
            .unwrap()
    );
    assert_eq!(
        store.wait(fenced, &current, "fenced.active", 1).await.unwrap(),
        Waited::Waiting
    );

    assert!(!store.record(fenced, &stale, stale_step).await.unwrap());
    assert_eq!(store.entries(fenced).await.unwrap(), [current_step]);
    assert_eq!(
        store.wait(fenced, &stale, "fenced.stale", 1).await.unwrap(),
        Waited::Lost
    );
    assert_eq!(store.waiting("fenced.stale").await.unwrap(), None);
    assert!(!store.stop_waiting(fenced, &stale, "fenced.active").await.unwrap());
    assert_eq!(store.waiting("fenced.active").await.unwrap(), Some(fenced));
    assert!(
        !store
            .set_attributes(fenced, &stale, BTreeMap::from([("owner".into(), "stale".into())]))
            .await
            .unwrap()
    );
    assert_eq!(
        store.find(fenced).await.unwrap().unwrap().attributes["owner"],
        "current"
    );
    assert!(!store.renew(fenced, &stale, Duration::from_secs(60)).await.unwrap());
    assert!(
        !store
            .release(
                fenced,
                &stale,
                Outcome::Completed {
                    output: "\"stale\"".into()
                },
                now,
            )
            .await
            .unwrap()
    );
    assert!(
        !store
            .release(fenced, &stale, Outcome::Waiting { wake_at: None }, now)
            .await
            .unwrap()
    );
    assert_eq!(store.find(fenced).await.unwrap().unwrap().status, Status::Running);

    assert!(store.renew(fenced, &current, Duration::from_secs(60)).await.unwrap());
    assert!(
        store
            .release(
                fenced,
                &current,
                Outcome::Completed {
                    output: "\"current\"".into()
                },
                now,
            )
            .await
            .unwrap()
    );
    let finished = store.find(fenced).await.unwrap().unwrap();
    assert_eq!(
        (finished.status, finished.output.as_deref()),
        (Status::Completed, Some("\"current\""))
    );
    assert!(!store.renew(fenced, &current, Duration::from_secs(60)).await.unwrap());
    assert!(!store.stop_waiting(fenced, &current, "fenced.active").await.unwrap());
    assert_eq!(
        store.wait(fenced, &current, "fenced.after", 1).await.unwrap(),
        Waited::Lost
    );
    assert!(!store.set_attributes(fenced, &current, BTreeMap::new()).await.unwrap());
}