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
//! The child-context operation: [`ChildBuilder`], returned by
//! [`DurableContext::run_in_child_context`](crate::DurableContext::run_in_child_context).
//!
//! The [child context operation guide](https://docs.aws.amazon.com/durable-execution/sdk-reference/operations/child-context/)
//! describes this operation independently of any language SDK.

use std::future::{Future, IntoFuture};
use std::marker::PhantomData;

use crate::BoxError;
use crate::OperationSubType;
use crate::Serdes;
use crate::context::DurableContext;
use crate::engine::OperationId;
use crate::error::OperationError;
use crate::future::DurableFuture;
use crate::serdes::JsonSerdes;

/// Builder for a child context (sub-orchestration) operation.
///
/// Created by [`DurableContext::run_in_child_context`]. Use `.spawn()` for
/// eager fan-out execution.
///
/// The builder is generic over the body closure `F` and its future
/// `Fut`; both parameters are inferred at the call site and never written
/// by users.
///
/// # Examples
///
/// ```no_run
/// use aws_durable_execution_sdk as durable;
///
/// async fn handler(
///     _event: serde_json::Value,
///     ctx: durable::DurableContext,
/// ) -> Result<i32, durable::BoxError> {
///     let result = ctx.run_in_child_context(|child| async move {
///         Ok(42)
///     }).name("sub-orchestration")
///       .await?;
///     Ok(result)
/// }
/// ```
#[must_use = "builders do nothing unless awaited or spawned"]
#[non_exhaustive]
pub struct ChildBuilder<O, F, Fut, S = JsonSerdes> {
    ctx: DurableContext,
    op_id: OperationId,
    name: Option<String>,
    sub_type: Option<OperationSubType>,
    serdes: S,
    closure: F,
    /// Whether the body is a user function. Only `with_retry` clears it,
    /// for its attempt children.
    user_function: crate::child::UserFunctionPolicy,
    summary: Option<crate::child::ChildSummary<O>>,
    /// Whether the child is a virtual child context, which writes no
    /// record of its own.
    is_virtual: bool,
    _marker: PhantomData<fn() -> (O, Fut)>,
}

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

impl<O, F, Fut> ChildBuilder<O, F, Fut>
where
    O: Send + 'static,
    F: FnOnce(DurableContext) -> Fut + Send + 'static,
    Fut: Future<Output = Result<O, BoxError>> + Send + 'static,
{
    /// Creates a new builder (internal). Taking the closure here keeps the
    /// field non-optional: a builder without a body is unrepresentable.
    pub(crate) fn new_internal(ctx: DurableContext, op_id: OperationId, closure: F) -> Self {
        Self {
            ctx,
            op_id,
            name: None,
            sub_type: None,
            serdes: JsonSerdes,
            closure,
            user_function: crate::child::UserFunctionPolicy::Hooks,
            summary: None,
            is_virtual: false,
            _marker: PhantomData,
        }
    }
}

impl<O, F, Fut, S> ChildBuilder<O, F, Fut, S>
where
    O: Send + 'static,
    F: FnOnce(DurableContext) -> Fut + Send + 'static,
    Fut: Future<Output = Result<O, BoxError>> + Send + 'static,
{
    /// Marks the body as no user function: no frame and no user-function
    /// hooks. `with_retry` sets it for its attempt children in both modes.
    /// The block itself, with its own record or virtual, is the user
    /// function, as JS wraps only that block.
    pub(crate) fn without_user_function(mut self) -> Self {
        self.user_function = crate::child::UserFunctionPolicy::None;
        self
    }

    /// 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
    }

    /// Records `sub_type` instead of the default subtype.
    ///
    /// The subtype labels this child context in its checkpoint, in place
    /// of `RunInChildContext`. So the child contexts of an operation
    /// composed from several durable operations can be told apart.
    /// Execution history and plugins read it. Without this call the child
    /// context records [`OperationSubType::RUN_IN_CHILD_CONTEXT`]. A second
    /// call replaces the first.
    ///
    /// Replay compares the recorded subtype with this one, as it compares
    /// the name. So changing the subtype of an existing child context
    /// breaks the executions in flight: their replay fails with
    /// `NonDeterministicExecutionError`.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use aws_durable_execution_sdk as durable;
    /// use aws_durable_execution_sdk::OperationSubType;
    ///
    /// async fn handler(
    ///     _event: serde_json::Value,
    ///     ctx: durable::DurableContext,
    /// ) -> Result<String, durable::BoxError> {
    ///     let order = ctx
    ///         .run_in_child_context(|child| async move {
    ///             let id = child
    ///                 .step(|_| async { Ok("order-1".to_owned()) })
    ///                 .name("reserve")
    ///                 .await?;
    ///             Ok(id)
    ///         })
    ///         .name("checkout")
    ///         .sub_type(OperationSubType::new("Checkout")?)
    ///         .await?;
    ///     Ok(order)
    /// }
    /// ```
    pub fn sub_type(mut self, sub_type: OperationSubType) -> Self {
        self.sub_type = Some(sub_type);
        self
    }

    /// Overrides the serialization strategy for the child result.
    ///
    /// Replaces the builder's serdes type parameter with `S2`, which must
    /// implement [`Serdes<O>`](crate::Serdes) for this child's output type:
    /// attaching a serdes for a different type fails at compile time. To
    /// share one instance across operations, wrap it in an
    /// [`Arc`](std::sync::Arc) and clone the `Arc` handle into each builder.
    pub fn serdes<S2>(self, serdes: S2) -> ChildBuilder<O, F, Fut, S2>
    where
        S2: Serdes<O>,
    {
        ChildBuilder {
            ctx: self.ctx,
            op_id: self.op_id,
            name: self.name,
            sub_type: self.sub_type,
            serdes,
            closure: self.closure,
            user_function: self.user_function,
            summary: self.summary,
            is_virtual: self.is_virtual,
            _marker: PhantomData,
        }
    }

    /// Sets the payload recorded when the child's result is too large to
    /// checkpoint.
    ///
    /// Called only when the serialized result is over 256 KiB. The child
    /// then records its result with `ReplayChildren` and no value, so a
    /// replay runs the body again to rebuild the result. The summary
    /// receives the value the child returns, after the serdes round trip,
    /// and its output becomes the record's payload. Without a summary the
    /// payload is `""`. A result that fits is recorded as usual, and the
    /// summary is not called.
    ///
    /// The output is observability only: replay never reads it. A replay
    /// that rebuilds the result of a completed `ReplayChildren` record does
    /// not call the summary; a child that is still running when an
    /// invocation resumes it calls the summary when it completes with an
    /// oversized result. Keep it under 256 KiB, because the service rejects
    /// a larger payload. A second call replaces the first.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use aws_durable_execution_sdk as durable;
    ///
    /// async fn handler(
    ///     _event: serde_json::Value,
    ///     ctx: durable::DurableContext,
    /// ) -> Result<usize, durable::BoxError> {
    ///     let report = ctx
    ///         .run_in_child_context(|child| async move {
    ///             let report = child
    ///                 .step(|_| async { Ok("x".repeat(300 * 1024)) })
    ///                 .name("render")
    ///                 .await?;
    ///             Ok(report)
    ///         })
    ///         .name("report")
    ///         .summary(|report: &String| format!("len={}", report.len()))
    ///         .await?;
    ///     Ok(report.len())
    /// }
    /// ```
    pub fn summary(mut self, summary: impl Fn(&O) -> String + Send + Sync + 'static) -> Self {
        self.summary = Some(Box::new(summary));
        self
    }

    /// Runs the body without recording this child context itself.
    ///
    /// The body still runs in a context with its own operation namespace,
    /// so the operations it creates keep IDs independent of the caller's.
    /// No record is written for the child: its operations name the
    /// caller's parent as their parent, and the child adds no level to
    /// [`plugin_child_operations_depth`](crate::OptionsBuilder::plugin_child_operations_depth).
    /// Because nothing records the child's result, the body runs inline on
    /// the awaiting task in every invocation, and its operations replay
    /// their recorded results.
    ///
    /// A body that returns `Err` fails the child with a
    /// [`ChildContextError`](crate::ChildContextError) of kind
    /// `ChildFailed` whose source is the body's error. A result that the
    /// serdes cannot serialize or deserialize returns the serdes error, or
    /// ends the invocation when the serdes marks the error with
    /// [`RetryableSerdesError`](crate::serdes::RetryableSerdesError).
    ///
    /// The child is stopped with its caller's scope, not when its own body
    /// returns: an operation the body started with `.spawn()` and did not
    /// await keeps running and checkpointing after the body returns.
    ///
    /// Replay fails with `NonDeterministicExecutionError` when the log
    /// holds a record at the child's ID. So switching an existing child to
    /// virtual fails the replay of the executions in flight. A summary set
    /// with [`summary`](Self::summary) is never called, because no record
    /// exists to hold it, and a subtype set with
    /// [`sub_type`](Self::sub_type) appears only in errors and plugin hook
    /// infos.
    ///
    /// Plugins see the child: `on_operation_start` fires before the body
    /// and `on_operation_end` after it, with `Succeeded` and no result, or
    /// `Failed` and the error, both with
    /// [`is_virtual`](crate::plugin::OperationInfo::is_virtual) true and
    /// [`is_replay`](crate::plugin::OperationInfo::is_replay) the
    /// invocation's replay state when each fires. The body is a user
    /// function: its user-function hooks and `wrap_user_function` run in
    /// every invocation, because the body runs in every invocation.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use aws_durable_execution_sdk as durable;
    ///
    /// async fn handler(
    ///     _event: serde_json::Value,
    ///     ctx: durable::DurableContext,
    /// ) -> Result<u32, durable::BoxError> {
    ///     let value = ctx
    ///         .run_in_child_context(|child| async move {
    ///             Ok(child.step(|_| async { Ok(7_u32) }).name("work").await?)
    ///         })
    ///         .name("group")
    ///         .virtual_context()
    ///         .await?;
    ///     Ok(value)
    /// }
    /// ```
    pub fn virtual_context(mut self) -> Self {
        self.is_virtual = true;
        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.
    ///
    /// A combinator begins its `.future()` inputs' start phases, in input
    /// order, before its own start step. So this operation's `START` is
    /// queued before the combinator's, and a start hook it fires when it
    /// queues `START` runs before the combinator's; a start hook that waits
    /// for the `START` response keeps that timing. A replay of the
    /// combinator's final record starts no `.future()` input.
    ///
    /// A handle that [`.spawn()`](Self::spawn) returned already runs on its
    /// own task. A combinator that receives it never starts it again, and
    /// it keeps running independently: when the combinator resolves first,
    /// it does not cancel the handle, and the handle's result is dropped.
    pub fn future(self) -> DurableFuture<O>
    where
        S: Serdes<O>,
    {
        <Self as IntoFuture>::into_future(self)
    }

    /// Eagerly spawns the child context on a tokio task.
    ///
    /// The returned [`DurableFuture`] is already running; this is the
    /// replay-safe alternative to bare `tokio::spawn` for durable
    /// operations.
    ///
    /// 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.
    ///
    /// `.spawn()` runs the operation's start step on the caller's task
    /// before it returns, as JS starts the operation inside the call. When
    /// the operation's current state requires a `START` (it has no record,
    /// or its record begins a new attempt), that `START` is admitted to the
    /// write order before `.spawn()` returns, so it reaches the service
    /// before every update the caller sends afterwards, on any runtime
    /// flavor. The task-ownership check runs on the caller too: a
    /// `.spawn()` from a task or thread that does not own the context
    /// 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. A start hook that JS fires when it queues the `START`, and the
    /// replay start hook of a record that resumes work, fire before
    /// `.spawn()` returns. The rest of the operation, including
    /// `on_attempt_start` and the body, runs on the spawned task. The
    /// exceptions are `invoke`, `wait_for_condition` and the combinators,
    /// whose `.spawn()` starts the whole operation on the spawned task.
    ///
    /// # Errors
    ///
    /// When the invocation coordinator was created without a Tokio runtime,
    /// the returned future resolves to an error and the operation records
    /// nothing.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use aws_durable_execution_sdk as durable;
    ///
    /// async fn handler(
    ///     _event: serde_json::Value,
    ///     ctx: durable::DurableContext,
    /// ) -> Result<(), durable::BoxError> {
    ///     let handle = ctx.run_in_child_context(|child| async move {
    ///         Ok(1)
    ///     }).name("bg").spawn();
    ///     let _result = handle.await?;
    ///     Ok(())
    /// }
    /// ```
    pub fn spawn(self) -> DurableFuture<O>
    where
        S: Serdes<O>,
    {
        spawn_terminal!(self, started)
    }
}

impl<O, F, Fut, S> ChildBuilder<O, F, Fut, S>
where
    O: Send + 'static,
    F: FnOnce(DurableContext) -> Fut + Send + 'static,
    Fut: Future<Output = Result<O, BoxError>> + Send + 'static,
    S: Serdes<O>,
{
    /// The operation's future. With `started`, its start step runs now, on
    /// the caller's task (see [`crate::start`]); `.spawn()` uses that.
    fn build(self, started: bool) -> DurableFuture<O> {
        use crate::child::ChildExecution;

        if self.is_virtual {
            return self.build_virtual();
        }

        preflight_identity!(
            self,
            "Context",
            self.sub_type
                .as_ref()
                .map_or(crate::child::CHILD_SUB_TYPE, OperationSubType::as_str)
        );

        let execution = ChildExecution {
            ctx: self.ctx,
            op_id: self.op_id,
            name: self.name,
            sub_type: self
                .sub_type
                .unwrap_or(OperationSubType::RUN_IN_CHILD_CONTEXT),
            serdes: self.serdes,
            closure: self.closure,
            user_function: self.user_function,
            summary: self.summary,
            _marker: PhantomData,
        };

        if started {
            DurableFuture::for_started_operation(
                &execution.ctx.clone(),
                execution.execute_started(),
            )
        } else {
            DurableFuture::for_start_step(&execution.ctx.clone(), move || {
                execution.execute_started()
            })
        }
    }

    /// The future of a virtual child context. It has no start step: it
    /// rejects a record at its ID now, and runs the body when it is polled.
    fn build_virtual(self) -> DurableFuture<O> {
        use crate::child::ChildExecution;

        let sub_type = self
            .sub_type
            .unwrap_or(OperationSubType::RUN_IN_CHILD_CONTEXT);
        if let Err(err) = self.ctx.reject_record_at_virtual_child(
            &self.op_id,
            sub_type.as_str(),
            self.name.as_deref(),
        ) {
            return DurableFuture::from_async(async move { Err(err) });
        }
        let execution = ChildExecution {
            ctx: self.ctx,
            op_id: self.op_id,
            name: self.name,
            sub_type,
            serdes: self.serdes,
            closure: self.closure,
            user_function: self.user_function,
            summary: None,
            _marker: PhantomData,
        };
        DurableFuture::for_operation(&execution.ctx.clone(), execution.execute_virtual())
    }

    /// The operation's future, with its start step run now.
    fn started_future(self) -> DurableFuture<O> {
        self.build(true)
    }
}

impl<O, F, Fut, S> IntoFuture for ChildBuilder<O, F, Fut, S>
where
    O: Send + 'static,
    F: FnOnce(DurableContext) -> Fut + Send + 'static,
    Fut: Future<Output = Result<O, BoxError>> + Send + 'static,
    S: Serdes<O>,
{
    type Output = Result<O, OperationError>;
    type IntoFuture = DurableFuture<O>;

    fn into_future(self) -> Self::IntoFuture {
        self.build(false)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// A second `sub_type` call replaces the first, and `serdes` keeps
    /// the subtype.
    #[test]
    fn sub_type_setter_replaces_and_survives_serdes() {
        let ctx = DurableContext::test_context();
        let builder = ctx
            .run_in_child_context(|_child| async { Ok(1_u32) })
            .sub_type(OperationSubType::new("First").unwrap())
            .sub_type(OperationSubType::new("Second").unwrap())
            .serdes(std::sync::Arc::new(JsonSerdes));
        assert_eq!(
            builder.sub_type.as_ref().map(OperationSubType::as_str),
            Some("Second")
        );
    }

    /// `virtual_context` sets the flag, which defaults to false, and
    /// `serdes` keeps it.
    #[test]
    fn virtual_context_setter_survives_serdes() {
        let ctx = DurableContext::test_context();
        let plain = ctx.run_in_child_context(|_child| async { Ok(1_u32) });
        assert!(!plain.is_virtual);
        let builder = ctx
            .run_in_child_context(|_child| async { Ok(1_u32) })
            .virtual_context()
            .serdes(std::sync::Arc::new(JsonSerdes));
        assert!(builder.is_virtual);
    }

    /// A second `summary` call replaces the first, and `serdes` keeps the
    /// summary.
    #[test]
    fn summary_setter_replaces_and_survives_serdes() {
        let ctx = DurableContext::test_context();
        let builder = ctx
            .run_in_child_context(|_child| async { Ok(1_u32) })
            .summary(|v: &u32| format!("first {v}"))
            .summary(|v: &u32| format!("second {v}"))
            .serdes(std::sync::Arc::new(JsonSerdes));
        let summary = builder.summary.as_ref().expect("the summary is kept");
        assert_eq!(summary(&7), "second 7");
    }
}