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
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
//! Where workflow runs are kept: the [`Store`] trait, and the values a store saves and hands out.
//!
//! The framework replays a run, retries its steps, encodes its values, and dispatches its jobs. A
//! store only keeps runs. It saves inputs, outputs, and resume values as the JSON text it
//! receives.
//!
//! A token belongs to one unfinished run at a time. A run claims a token when it starts with
//! the token in [`NewRun::tokens`], or when it first [waits](Store::wait) for the token, and
//! gives up its tokens when it completes, fails, or is cancelled. A [`resume`](Store::resume)
//! adds its value to the list that the token's owner keeps for that token, numbered from 1 in
//! the order the values arrived. When no unfinished run owns the token, the store keeps nothing.
//! A wait reads value 1, and an inbox reads values 1, 2, 3, and so on. Reading doesn't remove a
//! value, so a run that crashed after reading a value reads it again.
//!
//! A store must make four operations atomic, and fence every in-advance write with the [`Lease`]
//! token that [`claim`](Store::claim) returned:
//!
//! - Of two [`claim`](Store::claim) calls for one run, only one gets the lease, with a distinct
//!   [`Lease`] token.
//! - Of two unfinished runs that claim one token, with [`create`](Store::create) or
//!   [`wait`](Store::wait), only one owns it. The other gets the owner's ID.
//! - Two [`resume`](Store::resume) calls for one token give their values different numbers.
//! - A [`wait`](Store::wait) and a [`resume`](Store::resume) for one token can't miss each
//!   other. Either the `resume` returns [`Delivery::Due`], or the `wait` returns the value.
//!
//! Register a store by name with [`Drivers::extend`](super::Drivers::extend).

use std::collections::BTreeMap;
use std::fmt;
use std::future::Future;
use std::time::Duration;

use jiff::Timestamp;

use super::{RunId, Status};
use crate::Result;

#[cfg(feature = "database")]
pub(super) mod database;
pub(super) mod lazy;
pub(super) mod memory;

/// A run to save, which [`Store::create`] receives.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct NewRun {
    /// The run's ID.
    pub id: RunId,
    /// The workflow's registered name.
    pub workflow: String,
    /// The workflow struct, as JSON.
    pub input: String,
    /// The context values the run started with, as JSON, which every advance restores.
    pub context: String,
    /// The queue connection the run's jobs use.
    pub connection: String,
    /// The queue the run's jobs join.
    pub queue: String,
    /// When the run started.
    pub created_at: Timestamp,
    /// When the run may first advance.
    pub wake_at: Timestamp,
    /// The labels the run started with, which [`Filter::attributes`] selects by.
    pub attributes: BTreeMap<String, String>,
    /// A key that no other unfinished run may hold, set with
    /// [`PendingStart::unique`](super::PendingStart::unique).
    pub unique: Option<String>,
    /// Whether the store deletes the run's data when it finishes, set with
    /// [`PendingStart::purge_when_finished`](super::PendingStart::purge_when_finished).
    pub purge: bool,
    /// The tokens the run owns from the start, set with
    /// [`PendingStart::claim`](super::PendingStart::claim), so the values resumed before the run
    /// waits for them are kept for it.
    pub tokens: Vec<String>,
}

impl NewRun {
    /// A run that starts now, with no attributes, as a test starts one.
    #[doc(hidden)]
    #[must_use]
    pub fn __starting(
        id: RunId,
        workflow: String,
        input: String,
        context: String,
        (connection, queue): (String, String),
        now: Timestamp,
    ) -> Self {
        Self {
            id,
            workflow,
            input,
            context,
            connection,
            queue,
            created_at: now,
            wake_at: now,
            attributes: BTreeMap::new(),
            unique: None,
            purge: false,
            tokens: Vec::new(),
        }
    }
}

/// What [`Store::create`] did.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Created {
    /// The store saved the run, which owns its tokens.
    Saved,
    /// An unfinished run holds the new run's [`unique`](NewRun::unique) key, so the store saved
    /// nothing. The ID is that run's.
    Existing(RunId),
    /// An unfinished run owns one of the new run's [`tokens`](NewRun::tokens), so the store saved
    /// nothing.
    Taken {
        /// The token that the other run owns.
        token: String,
        /// The run that owns the token.
        owner: RunId,
    },
}

/// What [`Store::wait`] found.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Waited {
    /// The value has arrived, as JSON.
    Value(String),
    /// The run owns the token and waits for the value.
    Waiting,
    /// Another unfinished run owns the token. The ID is that run's.
    Taken(RunId),
    /// The caller no longer holds the run's lease, so the store changed nothing.
    Lost,
}

/// What [`Store::resume`] did with a value.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Delivery {
    /// No unfinished run owns the token, so the store kept nothing.
    NotFound,
    /// The run that owns the token keeps the value for a later wait.
    Queued(RunId),
    /// The run that owns the token waits for the value, so it should advance.
    Due(RunId),
}

/// A run as a store keeps it, without its [entries](Entry).
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct RunRecord {
    /// The run's ID.
    pub id: RunId,
    /// The workflow's registered name.
    pub workflow: String,
    /// The workflow struct, as JSON.
    pub input: String,
    /// The context values the run started with, as JSON.
    pub context: String,
    /// The queue connection the run's jobs use.
    pub connection: String,
    /// The queue the run's jobs join.
    pub queue: String,
    /// How far the run has come.
    pub status: Status,
    /// What the workflow returned, as JSON, once the run has completed.
    pub output: Option<String>,
    /// The error the run failed with, or the reason it was cancelled.
    pub error: Option<String>,
    /// When the run next has something to do, or `None` when only a
    /// [`resume`](Store::resume) moves it on.
    pub wake_at: Option<Timestamp>,
    /// When the run started.
    pub created_at: Timestamp,
    /// When the run completed, failed, or was cancelled.
    pub finished_at: Option<Timestamp>,
    /// The run's labels.
    pub attributes: BTreeMap<String, String>,
    /// Whether the store deletes the run's data when it finishes.
    ///
    /// Once the run has finished, its input, context, output, and error are gone, and so are its
    /// entries' outputs and errors.
    pub purge: bool,
}

impl RunRecord {
    /// A pending run, as [`Store::create`] first saves it.
    #[must_use]
    pub fn new(run: NewRun) -> Self {
        Self {
            id: run.id,
            workflow: run.workflow,
            input: run.input,
            context: run.context,
            connection: run.connection,
            queue: run.queue,
            status: Status::Pending,
            output: None,
            error: None,
            wake_at: Some(run.wake_at),
            created_at: run.created_at,
            finished_at: None,
            attributes: run.attributes,
            purge: run.purge,
        }
    }

    /// Apply how an advance ended, as [`Store::release`] saves it.
    ///
    /// A run that finishes with [`purge`](Self::purge) set loses its data.
    pub fn end(&mut self, outcome: Outcome, now: Timestamp) {
        match outcome {
            Outcome::Waiting { wake_at } => {
                self.status = Status::Waiting;
                self.wake_at = wake_at;
            }
            Outcome::Completed { output } => {
                self.status = Status::Completed;
                self.output = Some(output);
                self.wake_at = None;
                self.finished_at = Some(now);
            }
            Outcome::Failed { error } => {
                self.status = Status::Failed;
                self.error = Some(error);
                self.wake_at = None;
                self.finished_at = Some(now);
            }
        }
        if self.purge && self.status.has_ended() {
            self.forget_data();
        }
    }

    /// Mark the run [`Status::Cancelled`] at `now`, with the reason, as [`Store::cancel`] saves it.
    ///
    /// A run with [`purge`](Self::purge) set loses its data but keeps the reason.
    pub fn cancel(&mut self, reason: Option<String>, now: Timestamp) {
        self.status = Status::Cancelled;
        self.wake_at = None;
        self.finished_at = Some(now);
        if self.purge {
            self.forget_data();
        }
        self.error = reason;
    }

    /// Deletes the run's input, context, output and error.
    fn forget_data(&mut self) {
        self.input = PURGED_INPUT.to_owned();
        self.context = PURGED_CONTEXT.to_owned();
        self.output = None;
        self.error = None;
    }
}

/// What a purged run's input reads as.
pub(super) const PURGED_INPUT: &str = "null";

/// What a purged run's context reads as.
const PURGED_CONTEXT: &str = "{}";

/// What a journal entry records.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum Kind {
    /// A step: `run.step(..)`.
    Step,
    /// A sleep: `run.sleep(..)` or `run.sleep_until(..)`.
    Sleep,
    /// A wait for a token: `run.wait_for(..)` or `run.wait()`.
    Wait,
    /// One value of an inbox: `inbox.next()`. The entry's name is the token and the value's
    /// number, as in `expenses.7.votes #2`.
    Inbox,
}

impl Kind {
    /// The kind's name, as a store may save it: `step`, `sleep`, `wait`, or `inbox`.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Step => "step",
            Self::Sleep => "sleep",
            Self::Wait => "wait",
            Self::Inbox => "inbox",
        }
    }

    /// Parse a kind from the name that [`as_str`](Self::as_str) returns, or return `None` for an
    /// unknown name.
    #[must_use]
    pub fn from_name(name: &str) -> Option<Self> {
        match name {
            "step" => Some(Self::Step),
            "sleep" => Some(Self::Sleep),
            "wait" => Some(Self::Wait),
            "inbox" => Some(Self::Inbox),
            _ => None,
        }
    }
}

/// How far a journal entry has come.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum EntryStatus {
    /// A step that is running or will be tried again, a sleep that hasn't ended, or a wait that
    /// nothing has resumed.
    Pending,
    /// A step that returned, a sleep that ended, or a wait that was resumed or timed out.
    Completed,
    /// A step that is out of tries.
    Failed,
}

impl EntryStatus {
    /// The status's name, as a store may save it: `pending`, `completed`, or `failed`.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Pending => "pending",
            Self::Completed => "completed",
            Self::Failed => "failed",
        }
    }

    /// Parse a status from the name that [`as_str`](Self::as_str) returns, or return `None` for an
    /// unknown name.
    #[must_use]
    pub fn from_name(name: &str) -> Option<Self> {
        match name {
            "pending" => Some(Self::Pending),
            "completed" => Some(Self::Completed),
            "failed" => Some(Self::Failed),
            _ => None,
        }
    }
}

/// One line of a run's journal: a step, a sleep, a wait, or an inbox value, and how far it has
/// come.
///
/// A run's entries differ by their kind and name.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Entry {
    /// Whether the entry is a step, a sleep, a wait, or an inbox value.
    pub kind: Kind,
    /// The step's or sleep's name, the wait's token, or the inbox's token and the value's number.
    pub name: String,
    /// How far the entry has come.
    pub status: EntryStatus,
    /// How many times the step has been tried.
    pub tries: u32,
    /// What the step returned or the value that resumed the wait, as JSON.
    ///
    /// A wait that timed out has no output.
    pub output: Option<String>,
    /// The error from the step's last failed try.
    pub error: Option<String>,
    /// When the sleep ends, the wait times out, or the step is tried again.
    pub wake_at: Option<Timestamp>,
    /// When the run first reached the entry.
    pub started_at: Timestamp,
    /// When the entry completed or failed.
    pub finished_at: Option<Timestamp>,
}

/// Identifies one advance's lease on a workflow run.
///
/// [`Store::claim`] returns a `Lease` when a caller claims a run, and the store's in-advance write
/// methods ([`record`](Store::record), [`wait`](Store::wait), [`stop_waiting`](Store::stop_waiting),
/// [`set_attributes`](Store::set_attributes), [`renew`](Store::renew), and
/// [`release`](Store::release)) carry it back so a stalled advance whose lease expired can't
/// overwrite a newer advance's work.
///
/// Each [`claim`](Store::claim) must return a distinct token, such as a generated UUID via
/// [`Lease::generate`] or an incrementing counter wrapped with [`Lease::new`].
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Lease(String);

impl Lease {
    /// Wrap a store-defined fencing token, such as a version counter or random ID.
    #[must_use]
    pub fn new(token: impl Into<String>) -> Self {
        Self(token.into())
    }

    /// Generate a unique time-ordered UUID token for a new lease.
    #[must_use]
    pub fn generate() -> Self {
        Self(crate::str::uuid7().to_string())
    }

    /// The token's text, as a store saves and compares it.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl fmt::Display for Lease {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

impl AsRef<str> for Lease {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

/// What [`Store::claim`] found.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Claim {
    /// The caller holds the run's lease. The run's status is now [`Status::Running`].
    Claimed {
        /// The claimed run record.
        run: Box<RunRecord>,
        /// The run's journal entries, in the order the run first reached them.
        entries: Vec<Entry>,
        /// The fencing token identifying this lease.
        lease: Lease,
    },
    /// Another caller holds the run's lease.
    Held,
    /// The run doesn't exist or has completed, failed, or been cancelled.
    Ended,
}

/// How an advance of a run ended, which [`Store::release`] saves.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Outcome {
    /// The run sleeps, waits for a token, or waits to try a step again.
    Waiting {
        /// When the run next has something to do, or `None` when only a
        /// [`resume`](Store::resume) moves it on.
        wake_at: Option<Timestamp>,
    },
    /// The workflow returned.
    Completed {
        /// What the workflow returned, as JSON.
        output: String,
    },
    /// The workflow failed.
    Failed {
        /// The error the workflow failed with.
        error: String,
    },
}

/// Which runs [`Store::list`] returns.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Filter {
    /// Only runs with this status.
    pub status: Option<Status>,
    /// Only runs of the workflow with this registered name.
    pub workflow: Option<String>,
    /// Only runs with every one of these attributes.
    pub attributes: BTreeMap<String, String>,
    /// At most this many runs.
    pub limit: usize,
}

impl Filter {
    /// Whether a run matches the filter's status, workflow, and attributes.
    #[must_use]
    pub fn matches(&self, run: &RunRecord) -> bool {
        self.status.is_none_or(|status| run.status == status)
            && self.workflow.as_ref().is_none_or(|workflow| run.workflow == *workflow)
            && self
                .attributes
                .iter()
                .all(|(name, value)| run.attributes.get(name) == Some(value))
    }
}

/// Keeps workflow runs: their input, their journal, and the values they wait for.
///
/// The [module](self) describes what a store must guarantee. A store reads the time for its
/// leases from its own clock, so a test that moves the application's clock doesn't end a lease.
///
/// ```
/// use std::collections::BTreeMap;
/// use std::time::Duration;
///
/// use laravel::time::Timestamp;
/// use laravel::workflow::RunId;
/// use laravel::workflow::store::{
///     Claim, Created, Delivery, Entry, Filter, Lease, NewRun, Outcome, RunRecord, Store, Waited,
/// };
///
/// pub struct DynamoStore {
///     pub table: String,
/// }
///
/// impl Store for DynamoStore {
///     async fn create(&self, run: NewRun) -> laravel::Result<Created> {
///         // Save `RunRecord::new(run)` owning `run.tokens`, unless an unfinished run holds
///         // `run.unique` or owns one of the tokens...
///         # let _ = run;
///         Ok(Created::Saved)
///     }
///
///     async fn claim(&self, id: RunId, lease: Duration) -> laravel::Result<Claim> {
///         // Take the run's lease with a fresh `Lease` token if no one holds it, and return the
///         // run with its entries...
///         # let _ = (id, lease);
///         Ok(Claim::Ended)
///     }
///
///     async fn record(&self, id: RunId, lease: &Lease, entry: Entry) -> laravel::Result<bool> {
///         // Save the entry, in place of the run's entry of the same kind and name, while `lease`
///         // is still held...
///         # let _ = (id, lease, entry);
///         Ok(true)
///     }
///
///     async fn wait(&self, id: RunId, lease: &Lease, token: &str, number: u32) -> laravel::Result<Waited> {
///         // Claim the token while `lease` is held unless another unfinished run owns it, note
///         // that the run waits for its value with this number, and return the value if it has
///         // arrived...
///         # let _ = (id, lease, token, number);
///         Ok(Waited::Waiting)
///     }
///
///     async fn stop_waiting(&self, id: RunId, lease: &Lease, token: &str) -> laravel::Result<bool> {
///         # let _ = (id, lease, token);
///         Ok(true)
///     }
///
///     async fn resume(&self, token: &str, value: String) -> laravel::Result<Delivery> {
///         // Add the value to the list the token's owner keeps, and say whether the owner waits for it...
///         # let _ = (token, value);
///         Ok(Delivery::NotFound)
///     }
///
///     async fn waiting(&self, token: &str) -> laravel::Result<Option<RunId>> {
///         # let _ = token;
///         Ok(None)
///     }
///
///     async fn set_attributes(
///         &self,
///         id: RunId,
///         lease: &Lease,
///         attributes: BTreeMap<String, String>,
///     ) -> laravel::Result<bool> {
///         # let _ = (id, lease, attributes);
///         Ok(true)
///     }
///
///     async fn renew(&self, id: RunId, lease: &Lease, duration: Duration) -> laravel::Result<bool> {
///         // Extend the lease while `lease` is still held...
///         # let _ = (id, lease, duration);
///         Ok(true)
///     }
///
///     async fn release(
///         &self,
///         id: RunId,
///         lease: &Lease,
///         outcome: Outcome,
///         now: Timestamp,
///     ) -> laravel::Result<bool> {
///         // Save how the advance ended and give up the lease while `lease` is still held...
///         # let _ = (id, lease, outcome, now);
///         Ok(true)
///     }
///
///     async fn find(&self, id: RunId) -> laravel::Result<Option<RunRecord>> {
///         # let _ = id;
///         Ok(None)
///     }
///
///     async fn entries(&self, id: RunId) -> laravel::Result<Vec<Entry>> {
///         # let _ = id;
///         Ok(Vec::new())
///     }
///
///     async fn list(&self, filter: Filter) -> laravel::Result<Vec<RunRecord>> {
///         # let _ = filter;
///         Ok(Vec::new())
///     }
///
///     async fn cancel(&self, id: RunId, reason: Option<String>, now: Timestamp) -> laravel::Result<bool> {
///         # let _ = (id, reason, now);
///         Ok(false)
///     }
///
///     async fn retry(&self, id: RunId, now: Timestamp) -> laravel::Result<bool> {
///         # let _ = (id, now);
///         Ok(false)
///     }
///
///     async fn overdue(&self, now: Timestamp) -> laravel::Result<Vec<RunRecord>> {
///         # let _ = now;
///         Ok(Vec::new())
///     }
///
///     async fn prune(&self, before: Timestamp) -> laravel::Result<u64> {
///         # let _ = before;
///         Ok(0)
///     }
/// }
/// ```
pub trait Store: Send + Sync + 'static {
    /// Save a new run as [`Status::Pending`], owning its [`tokens`](NewRun::tokens).
    /// [`RunRecord::new`] builds the record to save.
    ///
    /// When [`unique`](NewRun::unique) is set and an unfinished run already holds that key, the
    /// store saves nothing and returns [`Created::Existing`]. Of two calls with one key, only one
    /// may save its run. A run holds its key until it completes, fails, or is cancelled. When an
    /// unfinished run owns one of the tokens, the store saves nothing and returns
    /// [`Created::Taken`].
    fn create(&self, run: NewRun) -> impl Future<Output = Result<Created>> + Send;

    /// Take the run's lease for `lease`, mark the run [`Status::Running`], mint a distinct
    /// [`Lease`] fencing token, and return the run with its entries and lease.
    ///
    /// A lease that has run out counts as given up.
    ///
    /// Of two calls for one run, only one may get [`Claim::Claimed`].
    fn claim(&self, id: RunId, lease: Duration) -> impl Future<Output = Result<Claim>> + Send;

    /// Save an entry, in place of the run's entry of the same kind and name.
    ///
    /// Returns `false`, and saves nothing, if the run isn't [`Status::Running`] or `lease` is no
    /// longer the run's current lease, such as after a [`cancel`](Self::cancel) or another worker
    /// claiming the run after the lease ran out. The advance then stops before its next step.
    fn record(&self, id: RunId, lease: &Lease, entry: Entry) -> impl Future<Output = Result<bool>> + Send;

    /// Claim the token for the run, note that the run waits for its value numbered `number`, and
    /// return that value if it has arrived.
    ///
    /// Returns [`Waited::Lost`], and changes nothing, if the run isn't [`Status::Running`] or
    /// `lease` is no longer the run's current lease. When another unfinished run owns the token,
    /// the store changes nothing and returns [`Waited::Taken`]. Values are numbered from 1 in the
    /// order they arrived. A run that gets its value no longer waits for the token, but still owns
    /// it. A run waits for one value of a token at a time, so a later `wait` for the same token
    /// replaces the number it waits for.
    fn wait(&self, id: RunId, lease: &Lease, token: &str, number: u32) -> impl Future<Output = Result<Waited>> + Send;

    /// Note that the run no longer waits for `token`, because its wait timed out. The run still
    /// owns the token.
    ///
    /// Returns `false`, and changes nothing, if the run isn't [`Status::Running`] or `lease` is no
    /// longer the run's current lease.
    fn stop_waiting(&self, id: RunId, lease: &Lease, token: &str) -> impl Future<Output = Result<bool>> + Send;

    /// Add `value` to the end of the list that the token's owner keeps for the token, numbered
    /// one past the last.
    ///
    /// Returns [`Delivery::Due`] when the owner waits for a number up to the value's,
    /// [`Delivery::Queued`] when it doesn't, and [`Delivery::NotFound`], without keeping the value,
    /// when no unfinished run owns the token.
    ///
    /// A `resume` and a [`wait`](Self::wait) for one token can't miss each other.
    fn resume(&self, token: &str, value: String) -> impl Future<Output = Result<Delivery>> + Send;

    /// Return the run that owns `token` and waits for a value of it now.
    fn waiting(&self, token: &str) -> impl Future<Output = Result<Option<RunId>>> + Send;

    /// Replace the run's attributes.
    ///
    /// Returns `false`, and saves nothing, if the run isn't [`Status::Running`] or `lease` is no
    /// longer the run's current lease.
    fn set_attributes(
        &self,
        id: RunId,
        lease: &Lease,
        attributes: BTreeMap<String, String>,
    ) -> impl Future<Output = Result<bool>> + Send;

    /// Extend the run's lease to `duration` from now, while an advance is still running.
    ///
    /// Returns `false`, and changes nothing, if the run isn't [`Status::Running`] or `lease` is no
    /// longer the run's current lease.
    fn renew(&self, id: RunId, lease: &Lease, duration: Duration) -> impl Future<Output = Result<bool>> + Send;

    /// Save how an advance ended at `now` and give up the lease. [`RunRecord::end`] applies the
    /// outcome.
    ///
    /// A run that ends no longer waits, and gives up its [`unique`](NewRun::unique) key and its
    /// tokens. A completed run loses its values. A failed run keeps them, so a
    /// [`retry`](Self::retry) continues reading where it stopped once it claims each token again.
    ///
    /// When a run with [`purge`](RunRecord::purge) set completes or fails, it loses its data as
    /// [`RunRecord::end`] applies it, and its entries lose their outputs and errors. The run
    /// loses its values even when it failed, because it can't be retried.
    ///
    /// Returns `false`, and saves nothing, if the run isn't [`Status::Running`] or `lease` is no
    /// longer the run's current lease.
    fn release(
        &self,
        id: RunId,
        lease: &Lease,
        outcome: Outcome,
        now: Timestamp,
    ) -> impl Future<Output = Result<bool>> + Send;

    /// Return the run with this ID, or `None` if no run has it.
    fn find(&self, id: RunId) -> impl Future<Output = Result<Option<RunRecord>>> + Send;

    /// Return the run's entries, in the order the run first reached them.
    fn entries(&self, id: RunId) -> impl Future<Output = Result<Vec<Entry>>> + Send;

    /// Return the runs that a filter selects, newest first.
    fn list(&self, filter: Filter) -> impl Future<Output = Result<Vec<RunRecord>>> + Send;

    /// Mark a run [`Status::Cancelled`] with the reason, finished at `now`, as
    /// [`RunRecord::cancel`] applies it, and give up its [`unique`](NewRun::unique) key.
    ///
    /// The run gives up its tokens and loses its values, and loses its data if
    /// [`purge`](RunRecord::purge) is set, as [`release`](Self::release) does for a completed run. Returns `false` if the run
    /// doesn't exist or has already completed, failed, or been cancelled.
    fn cancel(&self, id: RunId, reason: Option<String>, now: Timestamp) -> impl Future<Output = Result<bool>> + Send;

    /// Mark a failed run [`Status::Pending`] again, due at `now`, without its error and without
    /// its failed entries.
    ///
    /// Returns `false` if the run hasn't failed or has lost its data.
    fn retry(&self, id: RunId, now: Timestamp) -> impl Future<Output = Result<bool>> + Send;

    /// Return the runs that should have advanced by `now` and haven't.
    ///
    /// These are pending and waiting runs whose `wake_at` has passed, waiting runs whose
    /// [`wait`](Self::wait) a [`resume`](Self::resume) has answered, and running runs whose lease
    /// has run out.
    fn overdue(&self, now: Timestamp) -> impl Future<Output = Result<Vec<RunRecord>>> + Send;

    /// Delete the runs that finished before `before`, with their entries and values.
    ///
    /// Returns how many runs the store deleted.
    fn prune(&self, before: Timestamp) -> impl Future<Output = Result<u64>> + Send;
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::workflow::store_contract::contract;

    #[tokio::test]
    async fn the_memory_store_keeps_the_contract() {
        contract(&memory::MemoryStore::default()).await;
    }
}