aws-durable-execution-sdk 1.0.0

Rust SDK for AWS Lambda Durable Functions
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
//! The future combinators: [`TryJoinAllBuilder`], [`JoinAllBuilder`],
//! [`SelectOkBuilder`], and [`RaceBuilder`], returned by
//! [`DurableContext::try_join_all`](crate::DurableContext::try_join_all),
//! [`DurableContext::join_all`](crate::DurableContext::join_all),
//! [`DurableContext::select_ok`](crate::DurableContext::select_ok), and
//! [`DurableContext::race`](crate::DurableContext::race).
//!
//! A combinator claims its operation ID when it is first awaited or
//! polled, or when it is spawned, not when the context method is called.
//! A `with_retry` block claims its ID when its builder becomes its future.
//! Every other operation claims its ID when its builder is created. A
//! combinator builder or future that is dropped before that point claims no
//! ID and records nothing.
//!
//! The combinators are this SDK's composition surface over
//! [`DurableFuture`] values; the
//! [operations section of the SDK reference](https://docs.aws.amazon.com/durable-execution/sdk-reference/)
//! describes the underlying operations independently of any language SDK.

use std::future::IntoFuture;

use crate::context::DurableContext;
use crate::engine::OperationId;
use crate::error::OperationError;
use crate::future::{DurableFuture, PendingClaim};

/// The operation ID a combinator claimed on its first poll or at
/// `.spawn()`, with the context and name it was claimed with.
struct Claimed {
    ctx: DurableContext,
    op_id: OperationId,
    name: Option<String>,
}

/// Builder for [`DurableContext::try_join_all`]: fail-fast join.
///
/// Awaits all futures concurrently and returns `Vec<O>` on success,
/// or propagates the first [`OperationError`] encountered.
///
/// The returned value has passed through the combinator's JSON encoding,
/// so it equals the value replay returns.
///
/// When the combinator resolves, it stops every input that it started from
/// `.future()` and that is still running. A stopped input stops at its next
/// `.await`. An input started with `.spawn()` keeps running, and its result
/// is dropped.
///
/// # Examples
///
/// ```no_run
/// use aws_durable_execution_sdk as durable;
///
/// async fn handler(
///     _event: serde_json::Value,
///     ctx: durable::DurableContext,
/// ) -> Result<(), durable::BoxError> {
///     let a = ctx.step(|_| async { Ok(1) }).future();
///     let b = ctx.step(|_| async { Ok(2) }).future();
///     let results: Vec<i32> = ctx.try_join_all([a, b]).name("gather").await?;
///     assert_eq!(results.len(), 2);
///     Ok(())
/// }
/// ```
#[must_use = "builders do nothing unless awaited or spawned"]
#[non_exhaustive]
pub struct TryJoinAllBuilder<O> {
    ctx: DurableContext,
    name: Option<String>,
    futures: Vec<DurableFuture<O>>,
}

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

impl<O: serde::Serialize + serde::de::DeserializeOwned + Send + 'static> TryJoinAllBuilder<O> {
    /// Creates a new builder (internal).
    pub(crate) fn new_internal(ctx: DurableContext, futures: Vec<DurableFuture<O>>) -> Self {
        Self {
            ctx,
            name: None,
            futures,
        }
    }

    /// Sets a human-readable name for this operation.
    ///
    /// Names appear in logs, traces, and the execution history for
    /// debugging purposes.
    pub fn name(mut self, name: impl Into<String>) -> Self {
        self.name = Some(name.into());
        self
    }

    /// Converts this builder into a [`DurableFuture`] without starting it.
    ///
    /// [`DurableFuture`] is the one input type the combinators
    /// ([`DurableContext::try_join_all`], [`DurableContext::join_all`],
    /// [`DurableContext::select_ok`], and [`DurableContext::race`]) accept,
    /// so `.future()` is how operations of different kinds join or race
    /// together. It does not start the operation: whatever awaits the
    /// returned future drives it, and a combinator drops the losers.
    ///
    /// The returned future claims the combinator's operation ID on its
    /// first poll, not here. Dropped before its first poll, it claims no ID
    /// and records nothing. Do not pass it to another combinator: an outer
    /// combinator that would start a still-unclaimed combinator fails the
    /// execution with a context usage error. Pass the handle that
    /// [`.spawn()`](Self::spawn) returns instead.
    pub fn future(self) -> DurableFuture<Vec<O>> {
        self.into_future()
    }

    /// Eagerly spawns the operation on a tokio task.
    ///
    /// The returned [`DurableFuture`] is already running; this is the
    /// replay-safe alternative to bare `tokio::spawn` for durable
    /// operations.
    ///
    /// The combinator claims its operation ID at this call, and checks it
    /// against the recorded history before the task starts. The returned
    /// handle has claimed, so it is a valid input to another combinator. A
    /// `.spawn()` from a task or thread that does not own the context
    /// claims no ID, fails the execution with a context usage error,
    /// returns a handle that resolves to the task-ownership error, queues
    /// no `START` and runs no body.
    ///
    /// Dropping the returned future loses only the result: the operation
    /// runs until it settles. The SDK stops it earlier only when the scope
    /// it was started in closes, such as a child context whose body
    /// returned, or when the invocation ends. The SDK also stops the
    /// `.future()` inputs a combinator started. A stopped task stops at its
    /// next `.await`, and its record can stay `STARTED`. The SDK cannot stop
    /// code between two `.await`s, `spawn_blocking` work, tasks or threads
    /// the handler starts itself, or a request already sent to another
    /// service.
    ///
    /// # Errors
    ///
    /// When the invocation coordinator was created without a Tokio runtime,
    /// the returned future resolves to an error and the operation records
    /// nothing.
    pub fn spawn(self) -> DurableFuture<Vec<O>> {
        spawn_terminal!(self)
    }
}

impl<O: serde::Serialize + serde::de::DeserializeOwned + Send + 'static> IntoFuture
    for TryJoinAllBuilder<O>
{
    type Output = Result<Vec<O>, OperationError>;
    type IntoFuture = DurableFuture<Vec<O>>;

    fn into_future(self) -> Self::IntoFuture {
        use crate::combinator::TryJoinAllExecution;

        let Self { ctx, name, futures } = self;
        let context = crate::context::display_prefix(ctx.prefix()).to_owned();
        DurableFuture::deferred(PendingClaim::new("try_join_all", context, move || {
            let claimed = Claimed {
                op_id: ctx.claim_operation_id("try_join_all"),
                ctx,
                name,
            };
            preflight_identity!(claimed, "Context", crate::combinator::COMBINATOR_SUB_TYPE);
            let gate = claimed.ctx.clone();
            let execution = TryJoinAllExecution {
                ctx: claimed.ctx,
                op_id: claimed.op_id,
                name: claimed.name,
                futures,
            };
            DurableFuture::for_operation(&gate, execution.execute())
        }))
    }
}

/// Builder for [`DurableContext::join_all`]: collect all outcomes.
///
/// Awaits all futures concurrently and returns one
/// `Result<O, OperationError>` per input, in input order. Never
/// short-circuits: every future runs to completion regardless of
/// individual failures.
///
/// Awaiting the builder returns
/// `Result<Vec<Result<O, OperationError>>, OperationError>`. The two
/// levels report different failures:
///
/// - The outer `Err` means the combinator itself failed, for example
///   replay nondeterminism. A failed checkpoint write never reaches it:
///   the write fails the invocation, and the combinator does not resolve.
/// - An input that returns `Err` appears only as that input's inner `Err`,
///   and the outer result is `Ok`.
/// - A panicking input ends the invocation, as a panic does everywhere else
///   in the SDK. The SDK resumes the original panic payload, and the
///   combinator writes no record and returns no result.
/// - Nothing cancels an input that `join_all` awaits: `join_all` drops no
///   input before it settles.
///
/// An inner `Err` is a `ChildContext` error of kind `ChildFailed` whose
/// `wire()` carries the input's recorded failure, on the first run and on
/// replay. Match on the `err.wire()` fields, not on the kind of the input
/// that failed.
///
/// # Examples
///
/// ```no_run
/// use aws_durable_execution_sdk as durable;
///
/// async fn handler(
///     _event: serde_json::Value,
///     ctx: durable::DurableContext,
/// ) -> Result<(), durable::BoxError> {
///     let a = ctx.step(|_| async { Ok(1) }).future();
///     let b = ctx.step(|_| async { Ok(2) }).future();
///     let outcomes: Vec<Result<i32, durable::OperationError>> =
///         ctx.join_all([a, b]).await?;
///     let rendered: Vec<String> = outcomes
///         .iter()
///         .map(|outcome| match outcome {
///             Ok(value) => format!("ok:{value}"),
///             Err(err) => format!("err:{err}"),
///         })
///         .collect();
///     assert_eq!(rendered.len(), 2);
///     Ok(())
/// }
/// ```
#[must_use = "builders do nothing unless awaited or spawned"]
#[non_exhaustive]
pub struct JoinAllBuilder<O> {
    ctx: DurableContext,
    name: Option<String>,
    futures: Vec<DurableFuture<O>>,
}

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

impl<O: serde::Serialize + serde::de::DeserializeOwned + Send + 'static> JoinAllBuilder<O> {
    /// Creates a new builder (internal).
    pub(crate) fn new_internal(ctx: DurableContext, futures: Vec<DurableFuture<O>>) -> Self {
        Self {
            ctx,
            name: None,
            futures,
        }
    }

    /// Sets a human-readable name for this operation.
    ///
    /// Names appear in logs, traces, and the execution history for
    /// debugging purposes.
    pub fn name(mut self, name: impl Into<String>) -> Self {
        self.name = Some(name.into());
        self
    }

    /// Converts this builder into a [`DurableFuture`] without starting it.
    ///
    /// [`DurableFuture`] is the one input type the combinators
    /// ([`DurableContext::try_join_all`], [`DurableContext::join_all`],
    /// [`DurableContext::select_ok`], and [`DurableContext::race`]) accept,
    /// so `.future()` is how operations of different kinds join or race
    /// together. It does not start the operation: whatever awaits the
    /// returned future drives it, and a combinator drops the losers.
    ///
    /// The returned future claims the combinator's operation ID on its
    /// first poll, not here. Dropped before its first poll, it claims no ID
    /// and records nothing. Do not pass it to another combinator: an outer
    /// combinator that would start a still-unclaimed combinator fails the
    /// execution with a context usage error. Pass the handle that
    /// [`.spawn()`](Self::spawn) returns instead.
    pub fn future(self) -> DurableFuture<Vec<Result<O, OperationError>>> {
        self.into_future()
    }

    /// Eagerly spawns the operation on a tokio task.
    ///
    /// The returned [`DurableFuture`] is already running; this is the
    /// replay-safe alternative to bare `tokio::spawn` for durable
    /// operations.
    ///
    /// The combinator claims its operation ID at this call, and checks it
    /// against the recorded history before the task starts. The returned
    /// handle has claimed, so it is a valid input to another combinator. A
    /// `.spawn()` from a task or thread that does not own the context
    /// claims no ID, fails the execution with a context usage error,
    /// returns a handle that resolves to the task-ownership error, queues
    /// no `START` and runs no body.
    ///
    /// Dropping the returned future loses only the result: the operation
    /// runs until it settles. The SDK stops it earlier only when the scope
    /// it was started in closes, such as a child context whose body
    /// returned, or when the invocation ends. The SDK also stops the
    /// `.future()` inputs a combinator started. A stopped task stops at its
    /// next `.await`, and its record can stay `STARTED`. The SDK cannot stop
    /// code between two `.await`s, `spawn_blocking` work, tasks or threads
    /// the handler starts itself, or a request already sent to another
    /// service.
    ///
    /// # Errors
    ///
    /// When the invocation coordinator was created without a Tokio runtime,
    /// the returned future resolves to an error and the operation records
    /// nothing.
    pub fn spawn(self) -> DurableFuture<Vec<Result<O, OperationError>>> {
        spawn_terminal!(self)
    }
}

impl<O: serde::Serialize + serde::de::DeserializeOwned + Send + 'static> IntoFuture
    for JoinAllBuilder<O>
{
    type Output = Result<Vec<Result<O, OperationError>>, OperationError>;
    type IntoFuture = DurableFuture<Vec<Result<O, OperationError>>>;

    fn into_future(self) -> Self::IntoFuture {
        use crate::combinator::JoinAllExecution;

        let Self { ctx, name, futures } = self;
        let context = crate::context::display_prefix(ctx.prefix()).to_owned();
        DurableFuture::deferred(PendingClaim::new("join_all", context, move || {
            let claimed = Claimed {
                op_id: ctx.claim_operation_id("join_all"),
                ctx,
                name,
            };
            preflight_identity!(claimed, "Context", crate::combinator::COMBINATOR_SUB_TYPE);
            let gate = claimed.ctx.clone();
            let execution = JoinAllExecution {
                ctx: claimed.ctx,
                op_id: claimed.op_id,
                name: claimed.name,
                futures,
            };
            DurableFuture::for_operation(&gate, execution.execute())
        }))
    }
}

/// Builder for [`DurableContext::select_ok`]: first success wins.
///
/// Returns the first successful `O`.
///
/// The returned value has passed through the combinator's JSON encoding,
/// so it equals the value replay returns.
///
/// When the combinator resolves, it stops every input that it started from
/// `.future()` and that is still running. A stopped input stops at its next
/// `.await`. An input started with `.spawn()` keeps running, and its result
/// is dropped.
///
/// # Examples
///
/// ```no_run
/// use aws_durable_execution_sdk as durable;
///
/// async fn handler(
///     _event: serde_json::Value,
///     ctx: durable::DurableContext,
/// ) -> Result<(), durable::BoxError> {
///     let a = ctx.step(|_| async { Ok("a".to_owned()) }).future();
///     let b = ctx.step(|_| async { Ok("b".to_owned()) }).future();
///     let _winner: String = ctx.select_ok([a, b]).await?;
///     Ok(())
/// }
/// ```
#[must_use = "builders do nothing unless awaited or spawned"]
#[non_exhaustive]
pub struct SelectOkBuilder<O> {
    ctx: DurableContext,
    name: Option<String>,
    futures: Vec<DurableFuture<O>>,
}

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

impl<O: serde::Serialize + serde::de::DeserializeOwned + Send + 'static> SelectOkBuilder<O> {
    /// Creates a new builder (internal).
    pub(crate) fn new_internal(ctx: DurableContext, futures: Vec<DurableFuture<O>>) -> Self {
        Self {
            ctx,
            name: None,
            futures,
        }
    }

    /// Sets a human-readable name for this operation.
    ///
    /// Names appear in logs, traces, and the execution history for
    /// debugging purposes.
    pub fn name(mut self, name: impl Into<String>) -> Self {
        self.name = Some(name.into());
        self
    }

    /// Converts this builder into a [`DurableFuture`] without starting it.
    ///
    /// [`DurableFuture`] is the one input type the combinators
    /// ([`DurableContext::try_join_all`], [`DurableContext::join_all`],
    /// [`DurableContext::select_ok`], and [`DurableContext::race`]) accept,
    /// so `.future()` is how operations of different kinds join or race
    /// together. It does not start the operation: whatever awaits the
    /// returned future drives it, and a combinator drops the losers.
    ///
    /// The returned future claims the combinator's operation ID on its
    /// first poll, not here. Dropped before its first poll, it claims no ID
    /// and records nothing. Do not pass it to another combinator: an outer
    /// combinator that would start a still-unclaimed combinator fails the
    /// execution with a context usage error. Pass the handle that
    /// [`.spawn()`](Self::spawn) returns instead.
    pub fn future(self) -> DurableFuture<O> {
        self.into_future()
    }

    /// Eagerly spawns the operation on a tokio task.
    ///
    /// The returned [`DurableFuture`] is already running; this is the
    /// replay-safe alternative to bare `tokio::spawn` for durable
    /// operations.
    ///
    /// The combinator claims its operation ID at this call, and checks it
    /// against the recorded history before the task starts. The returned
    /// handle has claimed, so it is a valid input to another combinator. A
    /// `.spawn()` from a task or thread that does not own the context
    /// claims no ID, fails the execution with a context usage error,
    /// returns a handle that resolves to the task-ownership error, queues
    /// no `START` and runs no body.
    ///
    /// Dropping the returned future loses only the result: the operation
    /// runs until it settles. The SDK stops it earlier only when the scope
    /// it was started in closes, such as a child context whose body
    /// returned, or when the invocation ends. The SDK also stops the
    /// `.future()` inputs a combinator started. A stopped task stops at its
    /// next `.await`, and its record can stay `STARTED`. The SDK cannot stop
    /// code between two `.await`s, `spawn_blocking` work, tasks or threads
    /// the handler starts itself, or a request already sent to another
    /// service.
    ///
    /// # Errors
    ///
    /// When the invocation coordinator was created without a Tokio runtime,
    /// the returned future resolves to an error and the operation records
    /// nothing.
    pub fn spawn(self) -> DurableFuture<O> {
        spawn_terminal!(self)
    }
}

impl<O: serde::Serialize + serde::de::DeserializeOwned + Send + 'static> IntoFuture
    for SelectOkBuilder<O>
{
    type Output = Result<O, OperationError>;
    type IntoFuture = DurableFuture<O>;

    fn into_future(self) -> Self::IntoFuture {
        use crate::combinator::SelectOkExecution;

        let Self { ctx, name, futures } = self;
        let context = crate::context::display_prefix(ctx.prefix()).to_owned();
        DurableFuture::deferred(PendingClaim::new("select_ok", context, move || {
            let claimed = Claimed {
                op_id: ctx.claim_operation_id("select_ok"),
                ctx,
                name,
            };
            preflight_identity!(claimed, "Context", crate::combinator::COMBINATOR_SUB_TYPE);
            let gate = claimed.ctx.clone();
            let execution = SelectOkExecution {
                ctx: claimed.ctx,
                op_id: claimed.op_id,
                name: claimed.name,
                futures,
            };
            DurableFuture::for_operation(&gate, execution.execute())
        }))
    }
}

/// Builder for [`DurableContext::race`]: first settled wins.
///
/// Returns the first result (success or failure).
///
/// The returned value has passed through the combinator's JSON encoding,
/// so it equals the value replay returns.
///
/// When the combinator resolves, it stops every input that it started from
/// `.future()` and that is still running. A stopped input stops at its next
/// `.await`. An input started with `.spawn()` keeps running, and its result
/// is dropped.
///
/// # Examples
///
/// ```no_run
/// use aws_durable_execution_sdk as durable;
///
/// async fn handler(
///     _event: serde_json::Value,
///     ctx: durable::DurableContext,
/// ) -> Result<(), durable::BoxError> {
///     let a = ctx.step(|_| async { Ok("fast".to_owned()) }).future();
///     let b = ctx.step(|_| async { Ok("slow".to_owned()) }).future();
///     let _winner: String = ctx.race([a, b]).await?;
///     Ok(())
/// }
/// ```
#[must_use = "builders do nothing unless awaited or spawned"]
#[non_exhaustive]
pub struct RaceBuilder<O> {
    ctx: DurableContext,
    name: Option<String>,
    futures: Vec<DurableFuture<O>>,
}

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

impl<O: serde::Serialize + serde::de::DeserializeOwned + Send + 'static> RaceBuilder<O> {
    /// Creates a new builder (internal).
    pub(crate) fn new_internal(ctx: DurableContext, futures: Vec<DurableFuture<O>>) -> Self {
        Self {
            ctx,
            name: None,
            futures,
        }
    }

    /// Sets a human-readable name for this operation.
    ///
    /// Names appear in logs, traces, and the execution history for
    /// debugging purposes.
    pub fn name(mut self, name: impl Into<String>) -> Self {
        self.name = Some(name.into());
        self
    }

    /// Converts this builder into a [`DurableFuture`] without starting it.
    ///
    /// [`DurableFuture`] is the one input type the combinators
    /// ([`DurableContext::try_join_all`], [`DurableContext::join_all`],
    /// [`DurableContext::select_ok`], and [`DurableContext::race`]) accept,
    /// so `.future()` is how operations of different kinds join or race
    /// together. It does not start the operation: whatever awaits the
    /// returned future drives it, and a combinator drops the losers.
    ///
    /// The returned future claims the combinator's operation ID on its
    /// first poll, not here. Dropped before its first poll, it claims no ID
    /// and records nothing. Do not pass it to another combinator: an outer
    /// combinator that would start a still-unclaimed combinator fails the
    /// execution with a context usage error. Pass the handle that
    /// [`.spawn()`](Self::spawn) returns instead.
    pub fn future(self) -> DurableFuture<O> {
        self.into_future()
    }

    /// Eagerly spawns the operation on a tokio task.
    ///
    /// The returned [`DurableFuture`] is already running; this is the
    /// replay-safe alternative to bare `tokio::spawn` for durable
    /// operations.
    ///
    /// The combinator claims its operation ID at this call, and checks it
    /// against the recorded history before the task starts. The returned
    /// handle has claimed, so it is a valid input to another combinator. A
    /// `.spawn()` from a task or thread that does not own the context
    /// claims no ID, fails the execution with a context usage error,
    /// returns a handle that resolves to the task-ownership error, queues
    /// no `START` and runs no body.
    ///
    /// Dropping the returned future loses only the result: the operation
    /// runs until it settles. The SDK stops it earlier only when the scope
    /// it was started in closes, such as a child context whose body
    /// returned, or when the invocation ends. The SDK also stops the
    /// `.future()` inputs a combinator started. A stopped task stops at its
    /// next `.await`, and its record can stay `STARTED`. The SDK cannot stop
    /// code between two `.await`s, `spawn_blocking` work, tasks or threads
    /// the handler starts itself, or a request already sent to another
    /// service.
    ///
    /// # Errors
    ///
    /// When the invocation coordinator was created without a Tokio runtime,
    /// the returned future resolves to an error and the operation records
    /// nothing.
    pub fn spawn(self) -> DurableFuture<O> {
        spawn_terminal!(self)
    }
}

impl<O: serde::Serialize + serde::de::DeserializeOwned + Send + 'static> IntoFuture
    for RaceBuilder<O>
{
    type Output = Result<O, OperationError>;
    type IntoFuture = DurableFuture<O>;

    fn into_future(self) -> Self::IntoFuture {
        use crate::combinator::RaceExecution;

        let Self { ctx, name, futures } = self;
        let context = crate::context::display_prefix(ctx.prefix()).to_owned();
        DurableFuture::deferred(PendingClaim::new("race", context, move || {
            let claimed = Claimed {
                op_id: ctx.claim_operation_id("race"),
                ctx,
                name,
            };
            preflight_identity!(claimed, "Context", crate::combinator::COMBINATOR_SUB_TYPE);
            let gate = claimed.ctx.clone();
            let execution = RaceExecution {
                ctx: claimed.ctx,
                op_id: claimed.op_id,
                name: claimed.name,
                futures,
            };
            DurableFuture::for_operation(&gate, execution.execute())
        }))
    }
}

#[cfg(test)]
mod tests {
    use std::sync::Arc;

    use crate::DurableFuture;
    use crate::context::DurableContext;
    use crate::engine::{CheckpointLog, CheckpointRecord, CheckpointStatus};

    /// Test 18: a builder and a `.future()` dropped before their first poll
    /// claim no ID.
    #[test]
    fn dropped_combinator_builder_claims_nothing() {
        let ctx = DurableContext::new_root(
            "arn:aws:lambda:us-east-1:1:function:test".to_owned(),
            lambda_runtime::Context::default(),
            Arc::new(CheckpointLog::empty()),
        );
        drop(ctx.try_join_all(Vec::<DurableFuture<i32>>::new()));
        drop(ctx.join_all(Vec::<DurableFuture<i32>>::new()).future());
        drop(
            ctx.select_ok(Vec::<DurableFuture<i32>>::new())
                .name("s")
                .future(),
        );
        drop(ctx.race(Vec::<DurableFuture<i32>>::new()));
        assert_eq!(ctx.mint_id().positional(), "1", "the counter is unchanged");
    }

    /// A context whose log records a succeeded step at positional ID "1".
    fn ctx_with_step_at_1() -> DurableContext {
        let wire_id = crate::engine::compute_wire_id_public("1");
        let record = CheckpointRecord {
            id: wire_id.clone(),
            status: CheckpointStatus::Succeeded,
            result: Some("1".to_owned()),
            error_type: None,
            error_message: None,
            error_data: None,
            stack_trace: None,
            attempt: 0,
            invoke_result: None,
            invoke_error_type: None,
            invoke_error_message: None,
            invoke_error_data: None,
            invoke_stack_trace: None,
            replay_children: false,
            callback_id: None,
            op_type: Some("Step".to_owned()),
            sub_type: Some("Step".to_owned()),
            due_at: None,
            op_name: None,
            parent_id: None,
            start_timestamp: None,
            end_timestamp: None,
        };
        DurableContext::new_root(
            "arn:aws:lambda:us-east-1:1:function:test".to_owned(),
            lambda_runtime::Context::default(),
            Arc::new(CheckpointLog::from_records(vec![(wire_id, record)])),
        )
    }

    /// Asserts that `claim` recorded a replay identity mismatch on `ctx`.
    fn assert_mismatch_recorded(method: &str, ctx: &DurableContext) {
        assert!(
            ctx.coordinator().fatal_error().is_some(),
            "{method}: the claim records the mismatch before any poll"
        );
    }

    /// The claim of each combinator checks its ID against the recorded
    /// history at once, before the future is polled. A step recorded at
    /// the claimed ID is a replay identity mismatch.
    #[test]
    fn claim_checks_identity_before_poll() {
        let empty = Vec::<DurableFuture<i32>>::new;

        let ctx = ctx_with_step_at_1();
        ctx.try_join_all(empty()).future().claim_now();
        assert_mismatch_recorded("try_join_all", &ctx);

        let ctx = ctx_with_step_at_1();
        ctx.join_all(empty()).future().claim_now();
        assert_mismatch_recorded("join_all", &ctx);

        let ctx = ctx_with_step_at_1();
        ctx.select_ok(empty()).future().claim_now();
        assert_mismatch_recorded("select_ok", &ctx);

        let ctx = ctx_with_step_at_1();
        ctx.race(empty()).future().claim_now();
        assert_mismatch_recorded("race", &ctx);
    }
}