hatchet-client 0.1.0

Rust SDK for Hatchet: run workers and trigger tasks
Documentation
//! Idempotency: letting the engine compute a key from a run's input and
//! refuse a second run that computes the same one.

use std::time::Duration;

use hatchet_proto::v1;

/// How long an idempotency key stays claimed.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum IdempotencyMethod {
    /// The key is released a fixed window after it was claimed.
    Ttl,
    /// The key is held until the run that claimed it reaches a terminal
    /// state, with the window as a cap on how long that can take.
    Status,
}

/// Makes the engine compute a key from each run's input and refuse a
/// second run that computes the same one.
///
/// The key is **not** something a caller passes per run — there is no
/// idempotency key field on the trigger request. It is declared here, as a
/// CEL expression the engine evaluates against the run's input, and a
/// trigger whose key is already claimed fails with
/// [`Error::IdempotencyCollision`](crate::Error::IdempotencyCollision)
/// naming the run that holds it. This is the shape the official Go and
/// Python SDKs have too.
///
/// Observed against `hatchet-lite`: enforced on v0.107.0 (the second
/// trigger with the same key fails, and the key is released once the
/// window elapses); **silently ignored on v0.80.0** (the second trigger
/// just starts a new run). The exact engine version where enforcement was
/// introduced, between v0.80.0 and v0.107.0, was not measured.
/// [`WorkerBuilder::build`](crate::WorkerBuilder::build) refuses to
/// register a declaration with idempotency against an engine reporting a
/// version below [`IDEMPOTENCY_MIN_ENGINE_VERSION`](crate::IDEMPOTENCY_MIN_ENGINE_VERSION)
/// (currently v0.107.0) with
/// [`Error::UnsupportedFeature`](crate::Error::UnsupportedFeature), rather
/// than registering it and letting the engine quietly ignore it.
///
/// ```
/// use std::time::Duration;
///
/// use hatchet_client::{Idempotency, TaskBuilder};
///
/// // One charge per order, however many times the caller retries.
/// let charge = TaskBuilder::<(), ()>::new("charge")
///     .idempotency(Idempotency::ttl("input.order_id", Duration::from_secs(600)))
///     .handler(|_ctx, _input| async { Ok(()) });
/// # let _ = charge;
/// ```
#[derive(Clone, Debug, PartialEq, Eq)]
#[must_use = "an idempotency config does nothing until it is given to a declaration"]
pub struct Idempotency {
    expression: String,
    window: Duration,
    method: IdempotencyMethod,
}

impl Idempotency {
    /// The key computed by `expression` is held for `window`, whatever
    /// happens to the run that claimed it.
    ///
    /// `expression` is CEL over the run's input, e.g. `"input.order_id"`.
    pub fn ttl(expression: impl Into<String>, window: Duration) -> Self {
        Self {
            expression: expression.into(),
            window,
            method: IdempotencyMethod::Ttl,
        }
    }

    /// The key computed by `expression` is held until the run that claimed
    /// it ends, and in no case longer than `fallback`.
    pub fn until_run_ends(expression: impl Into<String>, fallback: Duration) -> Self {
        Self {
            expression: expression.into(),
            window: fallback,
            method: IdempotencyMethod::Status,
        }
    }

    /// Checks that this configuration can be sent to the engine.
    pub(crate) fn validate(&self) -> Result<(), String> {
        if self.expression.trim().is_empty() {
            return Err(
                "an idempotency expression must not be empty; it is CEL over the \
                        run's input, such as `input.order_id`"
                    .to_string(),
            );
        }
        if self.window.as_millis() == 0 {
            return Err(
                "an idempotency window must not round down to a zero ttl in \
                        milliseconds; the engine rejects a zero ttl at registration on \
                        v0.107.0, and what it does with it on older engines is not \
                        documented, so the SDK refuses it rather than letting idempotency \
                        quietly not apply"
                    .to_string(),
            );
        }
        Ok(())
    }

    pub(crate) fn to_proto(&self) -> v1::IdempotencyConfig {
        let method = match self.method {
            IdempotencyMethod::Ttl => v1::IdempotencyMethod::Ttl,
            IdempotencyMethod::Status => v1::IdempotencyMethod::Status,
        };
        v1::IdempotencyConfig {
            expression: self.expression.clone(),
            ttl_ms: i64::try_from(self.window.as_millis()).unwrap_or(i64::MAX),
            // Always sent, as Go and Python both do, so the engine's own
            // default can never differ from what was declared.
            method: Some(method as i32),
        }
    }
}

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

    #[test]
    fn a_ttl_config_sends_the_expression_the_window_and_the_method() {
        assert_eq!(
            Idempotency::ttl("input.order_id", Duration::from_secs(600)).to_proto(),
            v1::IdempotencyConfig {
                expression: "input.order_id".to_string(),
                ttl_ms: 600_000,
                method: Some(v1::IdempotencyMethod::Ttl as i32),
            }
        );
    }

    #[test]
    fn a_status_config_sends_its_fallback_as_the_ttl() {
        assert_eq!(
            Idempotency::until_run_ends("input.order_id", Duration::from_secs(10)).to_proto(),
            v1::IdempotencyConfig {
                expression: "input.order_id".to_string(),
                ttl_ms: 10_000,
                method: Some(v1::IdempotencyMethod::Status as i32),
            }
        );
    }

    #[test]
    fn sub_millisecond_windows_are_truncated_to_whole_milliseconds() {
        let config = Idempotency::ttl("input.id", Duration::from_micros(1_500));
        assert_eq!(config.to_proto().ttl_ms, 1);
    }

    #[test]
    fn an_empty_expression_is_invalid() {
        let reason = Idempotency::ttl("   ", Duration::from_secs(60))
            .validate()
            .unwrap_err();
        assert!(reason.contains("expression"), "{reason}");
    }

    #[test]
    fn a_zero_window_is_invalid() {
        let reason = Idempotency::ttl("input.id", Duration::ZERO)
            .validate()
            .unwrap_err();
        assert!(reason.contains("zero"), "{reason}");
    }

    #[test]
    fn a_window_longer_than_i64_milliseconds_saturates_rather_than_panicking() {
        let config = Idempotency::ttl("input.id", Duration::MAX);
        assert_eq!(config.to_proto().ttl_ms, i64::MAX);
    }

    #[test]
    fn a_window_under_one_millisecond_is_invalid() {
        let reason = Idempotency::ttl("input.id", Duration::from_micros(500))
            .validate()
            .unwrap_err();
        assert!(reason.contains("zero"), "{reason}");
    }
}