aws-durable-execution-sdk 1.0.0

Rust SDK for AWS Lambda Durable Functions
Documentation
//! The wait (durable timer) operation: [`WaitBuilder`], returned by
//! [`DurableContext::wait`](crate::DurableContext::wait).
//!
//! The [wait operation guide](https://docs.aws.amazon.com/durable-execution/sdk-reference/operations/wait/)
//! describes this operation 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;

/// Builder for a durable wait (timer) operation.
///
/// Created by [`DurableContext::wait`]. The wait duration is set at
/// creation; chain `.name()` for identification.
///
/// The duration is rounded up to whole seconds, and a duration under one
/// second waits one second.
///
/// # Examples
///
/// ```no_run
/// use aws_durable_execution_sdk as durable;
/// use std::time::Duration;
///
/// async fn handler(
///     _event: serde_json::Value,
///     ctx: durable::DurableContext,
/// ) -> Result<(), durable::BoxError> {
///     ctx.wait(Duration::from_secs(30))
///         .name("pause")
///         .await?;
///     Ok(())
/// }
/// ```
#[must_use = "builders do nothing unless awaited or spawned"]
#[non_exhaustive]
pub struct WaitBuilder {
    ctx: DurableContext,
    op_id: OperationId,
    name: Option<String>,
    duration_secs: i32,
}

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

impl WaitBuilder {
    /// Creates a new wait builder (internal).
    pub(crate) fn new_internal(
        ctx: DurableContext,
        op_id: OperationId,
        duration_secs: i32,
    ) -> Self {
        Self {
            ctx,
            op_id,
            name: None,
            duration_secs,
        }
    }

    /// Sets a human-readable name for this wait.
    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.
    ///
    /// 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<()> {
        self.into_future()
    }

    /// Eagerly spawns the wait 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;
    /// use std::time::Duration;
    ///
    /// async fn handler(
    ///     _event: serde_json::Value,
    ///     ctx: durable::DurableContext,
    /// ) -> Result<(), durable::BoxError> {
    ///     let handle = ctx.wait(Duration::from_secs(10)).spawn();
    ///     // do other work while timer runs
    ///     handle.await?;
    ///     Ok(())
    /// }
    /// ```
    pub fn spawn(self) -> DurableFuture<()> {
        spawn_terminal!(self, started_awaited)
    }

    /// The wait's future, with its start step run now on the caller's
    /// task (see [`crate::start`]).
    fn started_future(self) -> DurableFuture<()> {
        match self.execution() {
            Ok(execution) => DurableFuture::for_started_operation(
                &execution.ctx.clone(),
                execution.execute_started(),
            ),
            Err(future) => *future,
        }
    }

    /// The wait's execution, or the error future of a failed identity
    /// preflight.
    fn execution(self) -> Result<crate::wait::WaitExecution, Box<DurableFuture<()>>> {
        if let Err(err) = self.ctx.preflight_replay_identity(
            &self.op_id,
            "Wait",
            Some(crate::wait::WAIT_SUB_TYPE),
            self.name.as_deref(),
        ) {
            return Err(Box::new(DurableFuture::from_async(async move { Err(err) })));
        }
        Ok(crate::wait::WaitExecution {
            ctx: self.ctx,
            op_id: self.op_id,
            name: self.name,
            duration_secs: self.duration_secs,
        })
    }
}

impl IntoFuture for WaitBuilder {
    type Output = Result<(), OperationError>;
    type IntoFuture = DurableFuture<()>;

    fn into_future(self) -> Self::IntoFuture {
        match self.execution() {
            Ok(execution) => DurableFuture::for_start_step(&execution.ctx.clone(), move || {
                execution.execute_started()
            }),
            Err(future) => *future,
        }
    }
}