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
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
use std::collections::{BTreeMap, HashMap, HashSet};
use std::fmt;
use std::future::{Future, IntoFuture};
use std::marker::PhantomData;
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
use std::time::Duration;

use futures_util::future::BoxFuture;
use jiff::{Timestamp, ZonedDateTimeArithmetic};
use serde::Serialize;
use serde::de::DeserializeOwned;
use tracing::Instrument;

use super::ErasedStore;
use super::advance::now;
use super::store::{Entry, EntryStatus, Kind, Lease, Waited};
use super::{RunId, Token};
use crate::errors::panic;
use crate::time::Moment;
use crate::{Error, Result};

/// How many times a step runs before it fails for good, unless it sets [`Step::tries`].
const TRIES: u32 = 3;

/// How long a step waits before each retry, unless it sets [`Step::backoff`]. The last repeats.
const BACKOFF: [Duration; 2] = [Duration::from_secs(10), Duration::from_secs(60)];

/// How many times a run may read one inbox. Every read replays on every advance.
const INBOX_READS: u32 = 1000;

/// One advance of a workflow run, which the workflow's `handle` method receives.
///
/// Every durable operation is a method on the run: [`step`](Self::step), [`sleep`](Self::sleep),
/// [`sleep_until`](Self::sleep_until), [`wait_for`](Self::wait_for), [`wait`](Self::wait),
/// [`inbox_for`](Self::inbox_for), and [`inbox`](Self::inbox).
///
/// Each advance calls `handle` from the top. An operation that the run already recorded returns
/// its recorded result at once, and the first operation that isn't recorded does its work. When
/// the run must wait for a sleep, a token, or a step's retry, it suspends. The current advance
/// ends, and a later advance continues from there.
pub struct Run {
    id: RunId,
    lease: Lease,
    started_at: Timestamp,
    store: Arc<dyn ErasedStore>,
    workflow: &'static str,
    replacements: HashMap<String, String>,
    state: Mutex<State>,
    attributes: Mutex<BTreeMap<String, String>>,
}

#[derive(Default)]
pub(super) struct State {
    journal: HashMap<(Kind, String), Entry>,
    /// The operations this advance has reached, to catch a name used twice.
    reached: HashSet<(Kind, String)>,
    /// How many unnamed sleeps this advance has reached, which numbers them.
    sleeps: u32,
    /// How many waits and inboxes without a token this advance has made, which numbers their
    /// tokens.
    waits: u32,
    /// How many operations are doing work or talking to the store.
    active: usize,
    /// How many unnamed sleeps are suspended, to catch one that overlaps another operation.
    unnamed_sleeping: usize,
    /// Whether an operation suspended the run.
    suspended: bool,
    /// The earliest time an operation that suspended the run has something to do.
    wake_at: Option<Timestamp>,
    /// The last operation that returned, which an error names.
    passed: Option<String>,
    pub(super) ending: Option<Ending>,
}

/// Why an advance must end however `handle` goes on.
#[derive(Debug)]
pub(super) enum Ending {
    /// The run broke a rule the runtime checks, or its journal doesn't decode: it fails.
    Broken(Error),
    /// The store couldn't be read or written: the advance fails, and the queue retries it.
    Store(Error),
    /// The advance lost its lease, because the run was cancelled or another worker claimed it.
    Lost,
}

impl Run {
    #[expect(clippy::too_many_arguments, reason = "internal constructor for one claimed advance")]
    pub(super) fn new(
        id: RunId,
        lease: Lease,
        workflow: &'static str,
        started_at: Timestamp,
        store: Arc<dyn ErasedStore>,
        entries: Vec<Entry>,
        attributes: BTreeMap<String, String>,
        replacements: HashMap<String, String>,
    ) -> Self {
        let journal = entries
            .into_iter()
            .map(|entry| ((entry.kind, entry.name.clone()), entry))
            .collect();

        Self {
            id,
            lease,
            started_at,
            store,
            workflow,
            replacements,
            state: Mutex::new(State {
                journal,
                ..State::default()
            }),
            attributes: Mutex::new(attributes),
        }
    }

    /// The run's labels, set with [`PendingStart::attribute`](super::PendingStart::attribute) and
    /// [`set_attribute`](Self::set_attribute).
    #[must_use]
    pub fn attributes(&self) -> BTreeMap<String, String> {
        self.attributes.lock().unwrap_or_else(PoisonError::into_inner).clone()
    }

    /// Label the run, such as with the phase it has reached.
    ///
    /// `workflow:list --attribute` finds runs by their labels, and `workflow:show` shows them. When
    /// you set the same name twice, the last value wins.
    ///
    /// The run saves its attributes when the advance ends, whether the run suspends, completes, or
    /// fails. A replay sets each attribute again in the same order, so it ends with the same values
    /// and writes nothing.
    ///
    /// ```no_run
    /// # use laravel::workflow::Run;
    /// # fn example(run: &Run) {
    /// run.set_attribute("phase", "shipping");
    /// # }
    /// ```
    pub fn set_attribute(&self, name: impl Into<String>, value: impl Into<String>) {
        self.attributes
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .insert(name.into(), value.into());
    }

    /// The run's ID, which [`start`](super::Workflow::start) returned.
    ///
    /// The ID is the same in every advance, so together with a step's name it makes a stable
    /// idempotency key.
    #[must_use]
    pub const fn id(&self) -> RunId {
        self.id
    }

    /// When the run started, which is the same in every advance.
    #[must_use]
    pub const fn started_at(&self) -> Timestamp {
        self.started_at
    }

    /// Run `work` once and record its result under `name`.
    ///
    /// The work is any future that returns a `laravel::Result<T>`, where `T` serializes, such as
    /// an async method call or an async block. Pass the future without `.await`. The run awaits it
    /// only when the journal has no result for the step, and otherwise returns the recorded result.
    ///
    /// A step that fails runs again, for up to three tries. It waits 10 seconds before the second
    /// try and a minute before the third, unless the error sets another time with [`retry_after`].
    /// A step that returns [`fatal`] or runs out of tries fails with a [`StepFailed`] error. A
    /// panic in the step counts as a failed try.
    ///
    /// ```no_run
    /// # use laravel::workflow::Run;
    /// # async fn charge() -> laravel::Result<String> { Ok(String::new()) }
    /// use laravel::time::ToSpan;
    ///
    /// # async fn example(run: &Run) -> laravel::Result<()> {
    /// let receipt = run
    ///     .step("charge card", charge())
    ///     .tries(5)
    ///     .backoff([10.seconds(), 1.minutes()])
    ///     .timeout(30.seconds())
    ///     .await?;
    /// # Ok(()) }
    /// ```
    pub fn step<W>(&self, name: impl Into<String>, work: W) -> Step<'_, W> {
        Step {
            run: self,
            name: name.into(),
            work,
            tries: TRIES,
            backoff: BACKOFF.to_vec(),
            timeout: None,
        }
    }

    /// Suspend the run for `span`, such as `3.days()`.
    ///
    /// No worker holds the run while it sleeps. The run numbers its sleeps in the order it reaches
    /// them. A sleep that overlaps another operation, such as inside `task::try_join!`, needs a
    /// name, as in `run.sleep(1.hours()).named("cooling off")`.
    pub fn sleep(&self, span: impl Into<ZonedDateTimeArithmetic>) -> Sleep<'_> {
        Sleep {
            run: self,
            until: Until::After(crate::clock::exact_duration(span)),
            name: None,
        }
    }

    /// Suspend the run until `time`, which is a [`Timestamp`] or a
    /// [`ZonedDateTime`](crate::time::ZonedDateTime).
    pub fn sleep_until(&self, time: impl Into<Timestamp>) -> Sleep<'_> {
        Sleep {
            run: self,
            until: Until::At(time.into()),
            name: None,
        }
    }

    /// Suspend the run until [`workflow::resume`](super::resume) gives `token` a value, then
    /// return the value.
    ///
    /// The token identifies the wait, so a run waits for each token once. The token is a string,
    /// or a [`Token<T>`](super::Token) that names the value's type for the code that resumes it.
    ///
    /// Reaching the wait claims the token, so the run owns it until the run completes, fails, or
    /// is cancelled, and [`workflow::resume`](super::resume) gives its values only to this run.
    /// If another unfinished run owns the token, the run fails with an error that names the
    /// owner. To keep the values resumed before the run reaches the wait, claim the token when the
    /// run starts with [`PendingStart::claim`](super::PendingStart::claim).
    /// To stop waiting after a while, add [`Wait::timeout`], which returns `None` when the time
    /// passes.
    pub fn wait_for<T>(&self, token: impl Into<Token<T>>) -> Wait<'_, T> {
        let token = token.into();

        Wait {
            run: self,
            kind: Kind::Wait,
            name: token.as_str().to_owned(),
            token,
            number: 1,
            value: PhantomData,
        }
    }

    /// Wait for a token that the run generates, so a [resume URL](Wait::resume_url) needs no token
    /// of your own.
    ///
    /// Build the URL from the wait, send it in a step, and then await the wait:
    ///
    /// ```no_run
    /// # use laravel::workflow::Run;
    /// # #[derive(serde::Serialize, serde::Deserialize)] enum Decision { Approved, Rejected }
    /// # async fn email(approve: String, reject: String) -> laravel::Result<()> { Ok(()) }
    /// use laravel::time::ToSpan;
    ///
    /// # async fn example(run: &Run) -> laravel::Result<()> {
    /// let decision = run.wait::<Decision>();
    /// let approve = decision.resume_url(Decision::Approved)?.to_string();
    /// let reject = decision.resume_url(Decision::Rejected)?.to_string();
    ///
    /// run.step("email the manager", email(approve, reject)).await?;
    ///
    /// let decision = decision.timeout(3.days()).await?;
    /// # Ok(()) }
    /// ```
    ///
    /// The token is the run's ID and a number, such as `0193b1a2-….1`, so every advance generates
    /// the same token. The run numbers waits and [inboxes](Self::inbox) without a token together,
    /// in the order it makes them. If you add a new wait before an existing one, the existing wait's
    /// token changes, and a URL that a run in progress already sent no longer reaches it. When that
    /// matters, use [`wait_for`](Self::wait_for) with a token of your own. Making a wait while
    /// another operation is running, such as inside `task::try_join!`, fails the run, because the
    /// order could change on a replay.
    pub fn wait<T>(&self) -> Wait<'_, T> {
        self.wait_for(self.generate_token("a wait", "wait_for"))
    }

    /// Open an inbox for `token`, which is a wait that takes many values.
    ///
    /// Each call to [`next`](Inbox::next) suspends the run until a value arrives, and the inbox
    /// returns the values in the order they arrived. A run can loop over approvals, replies, or
    /// webhook deliveries this way:
    ///
    /// ```no_run
    /// # use std::collections::HashSet;
    /// # use laravel::workflow::Run;
    /// # #[derive(serde::Serialize, serde::Deserialize)] struct Vote { approver_id: i64, approve: bool }
    /// use laravel::time::ToSpan;
    ///
    /// # async fn example(run: &Run, expense_id: i64) -> laravel::Result<bool> {
    /// let mut votes = run.inbox_for::<Vote>(format!("expenses.{expense_id}.votes"));
    /// let mut approvers = HashSet::new();
    ///
    /// while let Some(vote) = votes.next().timeout(5.days()).await? {
    ///     if !vote.approve {
    ///         return Ok(false);
    ///     }
    ///
    ///     approvers.insert(vote.approver_id);
    ///
    ///     if approvers.len() == 2 {
    ///         return Ok(true);
    ///     }
    /// }
    ///
    /// Ok(false)
    /// # }
    /// ```
    ///
    /// [`workflow::resume`](super::resume) adds a value to the token's inbox. The first read
    /// claims the token for the run, as [`wait_for`](Self::wait_for) does, and the inbox returns
    /// every value that arrived after the run claimed it, including values that arrived while the
    /// run wasn't reading. A run may read one inbox at most 1,000 times.
    pub fn inbox_for<T>(&self, token: impl Into<Token<T>>) -> Inbox<'_, T> {
        Inbox {
            run: self,
            token: token.into(),
            reads: 0,
            received: 0,
            value: PhantomData,
        }
    }

    /// Open an inbox for a token that the run generates, as [`wait`](Self::wait) does for a single
    /// value.
    ///
    /// Build the inbox's [resume URLs](Inbox::resume_url) before its first read, and send them in
    /// a step.
    pub fn inbox<T>(&self) -> Inbox<'_, T> {
        self.inbox_for(self.generate_token("an inbox", "inbox_for"))
    }

    /// The next generated token. Fails the run when another operation is running, since the
    /// order could change on a replay.
    fn generate_token<T>(&self, what: &str, method: &str) -> Token<T> {
        let mut state = self.state();
        if state.active > 0 || state.suspended {
            let error = crate::error::fail(format!(
                "the workflow `{}` makes {what} without a token while another operation is running: \
                     give it a token, as in `run.{method}::<T>(\"..\")`",
                self.workflow
            ));
            state.ending.get_or_insert(Ending::Broken(error));
        }
        state.waits += 1;

        Token::new(format!("{}.{}", self.id, state.waits))
    }

    /// Resolve the workflow's services, which the generated `handle` awaits before the user's.
    #[doc(hidden)]
    pub async fn __prepare<T>(&self, resolve: impl Future<Output = Result<T>>) -> Result<T> {
        let _active = self.activate();

        resolve.await
    }

    pub(super) fn state(&self) -> MutexGuard<'_, State> {
        self.state.lock().unwrap_or_else(PoisonError::into_inner)
    }

    /// Mark an operation as busy until the guard drops, so the executor waits for it.
    fn activate(&self) -> Active<'_> {
        self.state().active += 1;

        Active(self)
    }

    /// Check the operation's name and return what the journal holds for it. Fails the run when
    /// the name was already used, or an unnamed sleep overlaps another operation.
    fn reach(&self, kind: Kind, name: &str, unnamed_sleep: bool) -> Result<Option<Entry>> {
        let mut state = self.state();
        if let Some(Ending::Broken(error)) = &state.ending {
            return Err(error.clone());
        }
        let overlaps = if unnamed_sleep {
            state.active > 0 || state.suspended
        } else {
            state.unnamed_sleeping > 0
        };
        if overlaps {
            let error = crate::error::fail(format!(
                "the workflow `{}` has a sleep that overlaps another operation: name it, as in \
                     `run.sleep(..).named(\"..\")`",
                self.workflow
            ));
            return Err(state.break_with(error));
        }
        if !state.reached.insert((kind, name.to_owned())) {
            let what = match kind {
                Kind::Step => format!("the step `{name}` runs twice: give each step its own name"),
                Kind::Sleep => format!("the sleep `{name}` is reached twice: give each sleep its own name"),
                Kind::Wait => format!("the token `{name}` is waited for twice: give each wait its own token"),
                Kind::Inbox => format!("the inbox read `{name}` is reached twice: read each token's inbox once"),
            };
            let error = crate::error::fail(format!("the workflow `{}` {what}", self.workflow));
            return Err(state.break_with(error));
        }

        Ok(state.journal.get(&(kind, name.to_owned())).cloned())
    }

    /// Save an entry. Ends the advance when the store fails or the advance lost its lease.
    async fn record(&self, entry: Entry) -> Result<()> {
        self.leased(self.store.record(self.id, &self.lease, entry.clone()).await)?;
        self.state().journal.insert((entry.kind, entry.name.clone()), entry);

        Ok(())
    }

    /// Check a write under the run's lease. Ends the advance when the store failed or the advance
    /// lost its lease.
    fn leased(&self, written: Result<bool>) -> Result<()> {
        match written {
            Ok(true) => Ok(()),
            Ok(false) => Err(self.end(Ending::Lost)),
            Err(error) => Err(self.end(Ending::Store(error))),
        }
    }

    /// Note that an operation returned, for errors that name the last one.
    fn pass(&self, kind: Kind, name: &str) {
        self.state().passed = Some(format!("{} `{name}`", kind.as_str()));
    }

    pub(super) fn passed(&self) -> Option<String> {
        self.state().passed.clone()
    }

    /// End the advance, and return an error for `handle` to see.
    fn end(&self, ending: Ending) -> Error {
        let error = match &ending {
            Ending::Broken(error) | Ending::Store(error) => error.clone(),
            Ending::Lost => crate::error::fail("the workflow advance lost its lease"),
        };
        self.state().ending.get_or_insert(ending);

        error
    }

    /// Suspend the run until `wake_at`, or until a resume when it's `None`, and never return.
    async fn suspend<T>(&self, wake_at: Option<Timestamp>, unnamed_sleep: bool) -> T {
        {
            let mut state = self.state();
            state.suspended = true;
            if unnamed_sleep {
                state.unnamed_sleeping += 1;
            }
            if let Some(wake_at) = wake_at {
                state.wake_at = Some(state.wake_at.map_or(wake_at, |earliest| earliest.min(wake_at)));
            }
        }

        std::future::pending().await
    }
}

impl State {
    fn break_with(&mut self, error: Error) -> Error {
        self.ending.get_or_insert(Ending::Broken(error.clone()));

        error
    }

    /// Whether `handle` is waiting on an operation that is doing work.
    pub(super) const fn is_busy(&self) -> bool {
        self.active > 0
    }

    pub(super) const fn suspension(&self) -> Option<Option<Timestamp>> {
        if self.suspended { Some(self.wake_at) } else { None }
    }
}

impl fmt::Debug for Run {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Run")
            .field("id", &self.id)
            .field("workflow", &self.workflow)
            .finish_non_exhaustive()
    }
}

struct Active<'a>(&'a Run);

impl Drop for Active<'_> {
    fn drop(&mut self) {
        self.0.state().active -= 1;
    }
}

fn later(time: Timestamp, after: Duration) -> Timestamp {
    time.checked_add(after).unwrap_or(Timestamp::MAX)
}

fn entry(kind: Kind, name: &str, status: EntryStatus, started_at: Timestamp) -> Entry {
    Entry {
        kind,
        name: name.to_owned(),
        status,
        tries: 0,
        output: None,
        error: None,
        wake_at: None,
        started_at,
        finished_at: None,
    }
}

/// A step's work, name, and options, built by [`Run::step`].
///
/// Await the step to run the work, or to return the result that the run recorded for it.
#[must_use = "a step does nothing unless awaited"]
pub struct Step<'r, W> {
    run: &'r Run,
    name: String,
    work: W,
    tries: u32,
    backoff: Vec<Duration>,
    timeout: Option<Duration>,
}

impl<W> fmt::Debug for Step<'_, W> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Step")
            .field("name", &self.name)
            .field("tries", &self.tries)
            .finish_non_exhaustive()
    }
}

impl<W> Step<'_, W> {
    /// Set how many times the step may run, which is at least one and defaults to three.
    pub fn tries(mut self, tries: u32) -> Self {
        self.tries = tries.max(1);
        self
    }

    /// Set how long to wait before each retry, in order.
    ///
    /// The last delay repeats once the list runs out. The default is 10 seconds, then a minute.
    pub fn backoff(mut self, delays: impl IntoIterator<Item = impl Into<ZonedDateTimeArithmetic>>) -> Self {
        self.backoff = delays.into_iter().map(crate::clock::exact_duration).collect();
        self
    }

    /// Set how long one try may run. A try that runs longer fails.
    pub fn timeout(mut self, timeout: impl Into<ZonedDateTimeArithmetic>) -> Self {
        self.timeout = Some(crate::clock::exact_duration(timeout));
        self
    }
}

impl<'r, W, T> IntoFuture for Step<'r, W>
where
    W: IntoFuture<Output = Result<T>> + Send + 'r,
    W::IntoFuture: Send + 'r,
    T: Serialize + DeserializeOwned + Send + 'r,
{
    type Output = Result<T>;
    type IntoFuture = BoxFuture<'r, Result<T>>;

    fn into_future(self) -> Self::IntoFuture {
        Box::pin(self.run())
    }
}

impl<'r, W, T> Step<'r, W>
where
    W: IntoFuture<Output = Result<T>> + Send + 'r,
    W::IntoFuture: Send + 'r,
    T: Serialize + DeserializeOwned + Send + 'r,
{
    async fn run(self) -> Result<T> {
        let Self {
            run,
            name,
            work,
            tries: max_tries,
            backoff,
            timeout,
        } = self;
        let recorded = run.reach(Kind::Step, &name, false)?;
        let mut tried = 0;
        if let Some(recorded) = &recorded {
            match recorded.status {
                EntryStatus::Completed => {
                    run.pass(Kind::Step, &name);
                    return decode(run, &name, recorded.output.as_deref().unwrap_or("null"));
                }
                EntryStatus::Failed => {
                    run.pass(Kind::Step, &name);
                    return Err(StepFailed::new(&name, recorded.error.clone().unwrap_or_default()).into());
                }
                EntryStatus::Pending => match recorded.wake_at {
                    Some(wake_at) if wake_at > now() => return run.suspend(Some(wake_at), false).await,
                    _ => tried = recorded.tries,
                },
            }
        }
        let started_at = recorded.as_ref().map_or_else(now, |recorded| recorded.started_at);

        let active = run.activate();
        let tries = tried + 1;
        let (output, tries) = match run.replacements.get(&name) {
            Some(replacement) => (decode(run, &name, replacement), tried),
            None => (attempt(run, &name, tries, timeout, work).await, tries),
        };
        let mut entry = entry(Kind::Step, &name, EntryStatus::Completed, started_at);
        entry.tries = tries;
        match output {
            Ok(value) => {
                entry.output = Some(serde_json::to_string(&value)?);
                entry.finished_at = Some(now());
                run.record(entry).await?;
                run.pass(Kind::Step, &name);

                Ok(value)
            }
            Err(error) => {
                let message = format!("{error:#}");
                entry.error = Some(message.clone());
                if error.is::<Fatal>() || tries >= max_tries {
                    entry.status = EntryStatus::Failed;
                    entry.finished_at = Some(now());
                    run.record(entry).await?;
                    run.pass(Kind::Step, &name);

                    return Err(StepFailed::new(&name, message).into());
                }

                let wake_at = match error.downcast_ref::<RetryAfter>() {
                    Some(RetryAfter { at, .. }) => Timestamp::try_from(at.time()).unwrap_or(Timestamp::MAX),
                    None => later(now(), backoff_after(&backoff, tries)),
                };
                crate::foundation::telemetry::logging(&error, || {
                    tracing::warn!(
                        target: crate::foundation::telemetry::WORKFLOW_TARGET,
                        run = %run.id,
                        workflow = run.workflow,
                        step = %name,
                        attempt = tries,
                        error = %message,
                        "A workflow step failed, and will be tried again",
                    )
                });
                entry.status = EntryStatus::Pending;
                entry.wake_at = Some(wake_at);
                run.record(entry).await?;
                drop(active);

                run.suspend(Some(wake_at), false).await
            }
        }
    }
}

/// The wait before the retry after `tries` tries: the last delay repeats once the list runs out.
fn backoff_after(backoff: &[Duration], tries: u32) -> Duration {
    let index = usize::try_from(tries.saturating_sub(1)).unwrap_or(usize::MAX);

    backoff
        .get(index)
        .or_else(|| backoff.last())
        .copied()
        .unwrap_or_default()
}

/// Try a step's work once, within its timeout, counting a panic as a failed try.
async fn attempt<W, T>(run: &Run, name: &str, tries: u32, timeout: Option<Duration>, work: W) -> Result<T>
where
    W: IntoFuture<Output = Result<T>>,
{
    let span = tracing::info_span!(
        target: crate::foundation::telemetry::WORKFLOW_TARGET,
        "step",
        workflow.run = %run.id,
        workflow.name = run.workflow,
        workflow.step = %name,
        workflow.attempt = i64::from(tries),
        otel.name = %format_args!("step {name}"),
        otel.status_code = tracing::field::Empty,
    );
    let current = CurrentStep {
        key: format!("{}:{name}", run.id),
        name: name.to_owned(),
        attempt: tries,
    };
    let work = CURRENT_STEP.scope(current, work.into_future());
    let limited = async move {
        match timeout {
            Some(limit) => tokio::time::timeout(limit, work).await.unwrap_or_else(|_| {
                Err(crate::error::fail(format!(
                    "the step ran longer than its timeout of {}",
                    crate::time::ExactDuration::from(limit)
                )))
            }),
            None => work.await,
        }
    };

    let output = panic::catch(limited).instrument(span.clone()).await;
    if let Err(error) = &output {
        crate::foundation::telemetry::fail(&span, error);
    }

    output
}

tokio::task_local! {
    static CURRENT_STEP: CurrentStep;
}

/// The step whose work is running, as [`current_step`] returns it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CurrentStep {
    key: String,
    name: String,
    attempt: u32,
}

impl CurrentStep {
    /// A key that is the same on every try of the step and differs between steps and runs.
    ///
    /// The key is the run's ID and the step's name, as in `0193b1a2-…:charge card`. Pass it as an
    /// API's idempotency key, so a try that runs again after a crash doesn't repeat the call.
    #[must_use]
    pub fn key(&self) -> &str {
        &self.key
    }

    /// The step's name.
    #[must_use]
    pub fn name(&self) -> &str {
        &self.name
    }

    /// The number of this try, counting from 1.
    #[must_use]
    pub const fn attempt(&self) -> u32 {
        self.attempt
    }
}

/// Return the step whose work is running.
///
/// The step has a stable [`key`](CurrentStep::key) to use as an API's idempotency key, and the
/// try's [`attempt`](CurrentStep::attempt) number.
///
/// ```no_run
/// # struct Stripe;
/// # impl Stripe { async fn charge(&self, cents: i64, key: &str) -> laravel::Result<String> { Ok(String::new()) } }
/// use laravel::workflow;
///
/// async fn charge(stripe: &Stripe, cents: i64) -> laravel::Result<String> {
///     let step = workflow::current_step();
///
///     stripe.charge(cents, step.key()).await
/// }
/// ```
///
/// # Panics
///
/// Panics if called outside a step's work, such as in `handle` itself.
#[must_use]
#[track_caller]
pub fn current_step() -> CurrentStep {
    CURRENT_STEP
        .try_with(Clone::clone)
        .unwrap_or_else(|_| panic!("laravel::workflow::current_step() is called outside a workflow step's work"))
}

fn decode<T: DeserializeOwned>(run: &Run, name: &str, output: &str) -> Result<T> {
    serde_json::from_str(output).map_err(|error| {
        run.end(Ending::Broken(crate::error::fail(format!(
            "the step `{name}` of the workflow `{}` recorded a value that doesn't decode as `{}`: {error}",
            run.workflow,
            std::any::type_name::<T>()
        ))))
    })
}

#[derive(Debug, Clone, Copy)]
enum Until {
    After(Duration),
    At(Timestamp),
}

/// A sleep, built by [`Run::sleep`] or [`Run::sleep_until`].
///
/// Await the sleep to suspend the run until the time comes.
#[derive(Debug)]
#[must_use = "a sleep does nothing unless awaited"]
pub struct Sleep<'r> {
    run: &'r Run,
    until: Until,
    name: Option<String>,
}

impl Sleep<'_> {
    /// Name the sleep, so `workflow:show` lists it by name.
    ///
    /// A sleep that overlaps another operation needs a name.
    pub fn named(mut self, name: impl Into<String>) -> Self {
        self.name = Some(name.into());
        self
    }

    async fn run(self) -> Result<()> {
        let run = self.run;
        let unnamed = self.name.is_none();
        let name = self.name.unwrap_or_else(|| {
            let mut state = run.state();
            state.sleeps += 1;
            format!("sleep {}", state.sleeps)
        });
        let recorded = run.reach(Kind::Sleep, &name, unnamed)?;

        let active = run.activate();
        let wake_at = match &recorded {
            Some(recorded) if recorded.status == EntryStatus::Completed => {
                run.pass(Kind::Sleep, &name);
                return Ok(());
            }
            Some(recorded) => recorded.wake_at.unwrap_or_else(now),
            None => {
                let started_at = now();
                let wake_at = match self.until {
                    Until::After(duration) => later(started_at, duration),
                    Until::At(time) => time,
                };
                let mut entry = entry(Kind::Sleep, &name, EntryStatus::Pending, started_at);
                entry.wake_at = Some(wake_at);
                run.record(entry).await?;
                wake_at
            }
        };
        if wake_at > now() {
            drop(active);
            return run.suspend(Some(wake_at), unnamed).await;
        }

        let started_at = recorded.map_or(wake_at, |recorded| recorded.started_at);
        let mut entry = entry(Kind::Sleep, &name, EntryStatus::Completed, started_at);
        entry.wake_at = Some(wake_at);
        entry.finished_at = Some(now());
        run.record(entry).await?;
        run.pass(Kind::Sleep, &name);

        Ok(())
    }
}

impl<'r> IntoFuture for Sleep<'r> {
    type Output = Result<()>;
    type IntoFuture = BoxFuture<'r, Result<()>>;

    fn into_future(self) -> Self::IntoFuture {
        Box::pin(self.run())
    }
}

/// A wait for a token's value, built by [`Run::wait_for`], [`Run::wait`], or [`Inbox::next`].
///
/// Await the wait to suspend the run until [`workflow::resume`](super::resume) gives the token a
/// value.
#[derive(Debug)]
#[must_use = "a wait does nothing unless awaited"]
pub struct Wait<'r, T> {
    run: &'r Run,
    token: Token<T>,
    /// The journal entry: a wait's token, or an inbox's token and the read's number.
    kind: Kind,
    name: String,
    /// Which of the token's values the wait reads, counting from 1.
    number: u32,
    value: PhantomData<fn() -> T>,
}

impl<'r, T> Wait<'r, T> {
    /// The token that the wait is for, which [`workflow::resume`](super::resume) resumes with a
    /// `T`.
    #[must_use]
    pub const fn token(&self) -> &Token<T> {
        &self.token
    }

    /// Build a [resume URL](super::resume_url) that resumes this wait with `value`.
    ///
    /// # Errors
    ///
    /// Returns the same errors as [`workflow::resume_url`](super::resume_url).
    #[track_caller]
    pub fn resume_url(&self, value: impl Into<T>) -> Result<super::ResumeUrl>
    where
        T: Serialize,
    {
        super::resume_url(&self.token, value.into())
    }

    /// Build a [webhook URL](super::webhook_url) that resumes this wait with a request's JSON
    /// body.
    ///
    /// # Errors
    ///
    /// Returns the same errors as [`workflow::webhook_url`](super::webhook_url).
    #[track_caller]
    pub fn webhook_url(&self) -> Result<super::ResumeUrl> {
        super::webhook_url(&self.token)
    }

    /// Stop waiting after `span`, such as `11.days()`.
    ///
    /// The wait returns `Some(value)` if a resume comes first, and `None` if the time passes
    /// first.
    pub fn timeout(self, span: impl Into<ZonedDateTimeArithmetic>) -> TimedWait<'r, T> {
        TimedWait {
            wait: self,
            timeout: crate::clock::exact_duration(span),
        }
    }
}

impl<'r, T: DeserializeOwned + Send + 'r> IntoFuture for Wait<'r, T> {
    type Output = Result<T>;
    type IntoFuture = BoxFuture<'r, Result<T>>;

    fn into_future(self) -> Self::IntoFuture {
        Box::pin(async move {
            let value = wait(&self, None).await?;
            let value = value.ok_or_else(|| crate::error::fail("the wait has no timeout, but timed out"))?;

            decode_value(self.run, &self.name, &value)
        })
    }
}

/// A wait with a timeout, built by [`Wait::timeout`].
///
/// Awaiting it returns `Some(value)` if a resume comes first, or `None` if the time passes
/// first.
#[derive(Debug)]
#[must_use = "a wait does nothing unless awaited"]
pub struct TimedWait<'r, T> {
    wait: Wait<'r, T>,
    timeout: Duration,
}

impl<'r, T: DeserializeOwned + Send + 'r> IntoFuture for TimedWait<'r, T> {
    type Output = Result<Option<T>>;
    type IntoFuture = BoxFuture<'r, Result<Option<T>>>;

    fn into_future(self) -> Self::IntoFuture {
        Box::pin(async move {
            match wait(&self.wait, Some(self.timeout)).await? {
                Some(value) => decode_value(self.wait.run, &self.wait.name, &value).map(Some),
                None => Ok(None),
            }
        })
    }
}

/// Wait for the token's value, as JSON, or `None` once the timeout has passed.
async fn wait<T>(wait: &Wait<'_, T>, timeout: Option<Duration>) -> Result<Option<String>> {
    let Wait {
        run,
        token,
        kind,
        name,
        number,
        ..
    } = wait;
    let (run, kind) = (*run, *kind);
    let recorded = run.reach(kind, name, false)?;
    if let Some(recorded) = recorded
        .as_ref()
        .filter(|recorded| recorded.status == EntryStatus::Completed)
    {
        run.pass(kind, name);
        return Ok(recorded.output.clone());
    }

    let active = run.activate();
    let (started_at, wake_at) = match &recorded {
        Some(recorded) => (recorded.started_at, recorded.wake_at),
        None => {
            let started_at = now();
            let mut entry = entry(kind, name, EntryStatus::Pending, started_at);
            entry.wake_at = timeout.map(|timeout| later(started_at, timeout));
            run.record(entry.clone()).await?;
            (started_at, entry.wake_at)
        }
    };
    let token = token.as_str();
    let value = match run.store.wait(run.id, &run.lease, token, *number).await {
        Ok(Waited::Value(value)) => Some(value),
        Ok(Waited::Waiting) => None,
        Ok(Waited::Lost) => return Err(run.end(Ending::Lost)),
        Ok(Waited::Taken(owner)) => {
            let error = crate::error::fail(format!(
                "the workflow `{}` waits for the token `{token}`, which the unfinished run `{owner}` owns: \
                     give each run its own token, such as one with the record's ID",
                run.workflow
            ));
            return Err(run.end(Ending::Broken(error)));
        }
        Err(error) => return Err(run.end(Ending::Store(error))),
    };
    if value.is_none() {
        if wake_at.is_none_or(|wake_at| wake_at > now()) {
            drop(active);
            return run.suspend(wake_at, false).await;
        }
        run.leased(run.store.stop_waiting(run.id, &run.lease, token).await)?;
    }

    let mut entry = entry(kind, name, EntryStatus::Completed, started_at);
    entry.output = value.clone();
    entry.wake_at = wake_at;
    entry.finished_at = Some(now());
    run.record(entry).await?;
    run.pass(kind, name);

    Ok(value)
}

/// A token that takes many values, built by [`Run::inbox_for`] or [`Run::inbox`].
///
/// Read the values in the order they arrived with [`next`](Self::next).
#[derive(Debug)]
pub struct Inbox<'r, T> {
    run: &'r Run,
    token: Token<T>,
    /// How many times the run has read the inbox.
    reads: u32,
    /// How many of those reads returned a value, rather than timing out.
    received: u32,
    value: PhantomData<fn() -> T>,
}

impl<'r, T> Inbox<'r, T> {
    /// The inbox's token, which [`workflow::resume`](super::resume) resumes with a `T`.
    #[must_use]
    pub const fn token(&self) -> &Token<T> {
        &self.token
    }

    /// Build a [resume URL](super::resume_url) that adds `value` to the inbox on each request.
    ///
    /// # Errors
    ///
    /// Returns the same errors as [`workflow::resume_url`](super::resume_url).
    #[track_caller]
    pub fn resume_url(&self, value: impl Into<T>) -> Result<super::ResumeUrl>
    where
        T: Serialize,
    {
        super::resume_url(&self.token, value.into())
    }

    /// Build a [webhook URL](super::webhook_url) that adds each request's JSON body to the inbox.
    ///
    /// # Errors
    ///
    /// Returns the same errors as [`workflow::webhook_url`](super::webhook_url).
    #[track_caller]
    pub fn webhook_url(&self) -> Result<super::ResumeUrl> {
        super::webhook_url(&self.token)
    }

    /// Wait for the inbox's next value.
    ///
    /// Await the wait for the value, or add [`timeout`](Wait::timeout) to get `None` when no value
    /// arrives in time. A value that arrives after a read timed out goes to the next read.
    ///
    /// The run records each read as the token and the read's number, as in `expenses.7.votes #2`.
    /// Reading an inbox more than 1,000 times fails the run, so hand a long conversation to a new
    /// run instead.
    #[expect(
        clippy::should_implement_trait,
        reason = "a read is a durable wait to await, which may time out, not an iterator's item"
    )]
    pub fn next(&mut self) -> Wait<'r, T> {
        if self.reads > 0 {
            let previous = (Kind::Inbox, read_name(self.token.as_str(), self.reads));
            let state = self.run.state();
            if state
                .journal
                .get(&previous)
                .is_some_and(|read| read.status == EntryStatus::Completed && read.output.is_some())
            {
                self.received += 1;
            }
        }
        self.reads += 1;
        if self.reads > INBOX_READS {
            let error = crate::error::fail(format!(
                "the workflow `{}` reads the inbox `{}` more than {INBOX_READS} times",
                self.run.workflow, self.token
            ));
            self.run.state().ending.get_or_insert(Ending::Broken(error));
        }

        Wait {
            run: self.run,
            token: self.token.clone(),
            kind: Kind::Inbox,
            name: read_name(self.token.as_str(), self.reads),
            number: self.received + 1,
            value: PhantomData,
        }
    }
}

/// The journal name of an inbox's `read`th read.
fn read_name(token: &str, read: u32) -> String {
    format!("{token} #{read}")
}

fn decode_value<T: DeserializeOwned>(run: &Run, token: &str, value: &str) -> Result<T> {
    serde_json::from_str(value).map_err(|error| {
        crate::error::fail(format!(
            "the value resumed for the token `{token}` of the workflow `{}` doesn't decode as `{}`: {error}",
            run.workflow,
            std::any::type_name::<T>()
        ))
    })
}

/// Mark a step's error as final, so the step fails without another try.
///
/// Use it for errors that a retry can't fix, such as a card the bank declined.
///
/// ```no_run
/// # #[derive(Debug, thiserror::Error)] #[error("the card was declined")] struct Declined;
/// # async fn charge() -> Result<String, Declined> { Ok(String::new()) }
/// use laravel::workflow;
///
/// async fn charge_card() -> laravel::Result<String> {
///     charge().await.map_err(workflow::fatal)
/// }
/// ```
pub fn fatal(error: impl Into<Error>) -> Error {
    let error = error.into();
    let status = error.status();

    Error::new(status, Fatal(format!("{error:#}")))
}

/// A step's error that [`fatal`] marked, so the step fails without another try.
#[derive(Debug, Clone, thiserror::Error)]
#[error("{0}")]
struct Fatal(String);

/// Mark a step's error with the time to try the step again, in place of its backoff.
///
/// Use it when an API's rate limit says when to come back. `when` is a span from now, such as
/// `30.seconds()`, or a [`Timestamp`]. The failed try still counts against the step's
/// [`tries`](Step::tries).
///
/// ```no_run
/// # #[derive(Debug, thiserror::Error)] #[error("rate limited")] struct RateLimited { retry_after: u32 }
/// # async fn sync() -> Result<(), RateLimited> { Ok(()) }
/// use laravel::time::ToSpan;
/// use laravel::workflow;
///
/// async fn sync_contacts() -> laravel::Result<()> {
///     sync().await.map_err(|error| {
///         let wait = i64::from(error.retry_after).seconds();
///
///         workflow::retry_after(wait, error)
///     })
/// }
/// ```
pub fn retry_after(when: impl Into<Moment>, error: impl Into<Error>) -> Error {
    let error = error.into();
    let status = error.status();

    Error::new(
        status,
        RetryAfter {
            at: when.into(),
            message: format!("{error:#}"),
        },
    )
}

/// A step's error that [`retry_after`] marked with when to try again.
#[derive(Debug, Clone, thiserror::Error)]
#[error("{message}")]
struct RetryAfter {
    at: Moment,
    message: String,
}

/// The error when a step fails for good, because it ran out of tries or returned [`fatal`].
///
/// `run.step(..).await` returns this error on the advance where the step fails and on every later
/// advance, so code that branches on it takes the same branch in each replay.
///
/// ```no_run
/// # use laravel::workflow::{Run, StepFailed};
/// # async fn book_hotel() -> laravel::Result<()> { Ok(()) }
/// # async fn example(run: &Run) -> laravel::Result<()> {
/// if let Err(error) = run.step("book hotel", book_hotel()).await
///     && let Some(failed) = error.downcast_ref::<StepFailed>()
/// {
///     tracing::warn!(step = failed.step(), error = failed.error(), "the hotel couldn't be booked");
/// }
/// # Ok(()) }
/// ```
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error("the step `{step}` failed: {error}")]
pub struct StepFailed {
    step: String,
    error: String,
}

impl StepFailed {
    fn new(step: &str, error: String) -> Self {
        Self {
            step: step.to_owned(),
            error,
        }
    }

    /// The step's name.
    #[must_use]
    pub fn step(&self) -> &str {
        &self.step
    }

    /// The error message from the step's last try.
    #[must_use]
    pub fn error(&self) -> &str {
        &self.error
    }
}