hatchet-client 0.1.0

Rust SDK for Hatchet: run workers and trigger tasks
Documentation
//! Reading an idempotency collision out of a failed trigger.
//!
//! The engine reports one as gRPC `AlreadyExists` with a `google.rpc.Status`
//! in the `grpc-status-details-bin` trailer, carrying a
//! `v1.IdempotencyCollisionError` (or, for a bulk trigger, a
//! `v1.BulkTriggerIdempotencyCollisionError`) as a `google.protobuf.Any`.
//! Hatchet's `api-contracts/` do not vendor `google/rpc/status.proto`, and
//! the only field that matters here is the repeated `Any`, so the wrapper is
//! declared rather than generated.
//!
//! Observed against `hatchet-lite` v0.107.0: only
//! `existing_run_external_id` is ever populated on
//! `v1.IdempotencyCollisionError` — `colliding_run_external_id` arrives
//! empty on every collision seen. So only the existing run's id is exposed
//! here; an always-empty field would just be noise.

use hatchet_proto::prost::Message;
use hatchet_proto::prost_types::Any;
use hatchet_proto::v1;
use tonic::Code;

use crate::error::{Error, IdempotencyCollision};

const IDEMPOTENCY_TYPE_URL: &str = "type.googleapis.com/v1.IdempotencyCollisionError";
const BULK_IDEMPOTENCY_TYPE_URL: &str =
    "type.googleapis.com/v1.BulkTriggerIdempotencyCollisionError";

/// The part of `google.rpc.Status` this needs. Unknown fields are skipped by
/// prost, so a status carrying more than this decodes fine.
///
/// `#[prost(prost_path = "::hatchet_proto::prost")]` points the generated
/// code at the `prost` already re-exported from `hatchet-proto`, so this
/// crate needs no direct `prost` dependency of its own for the derive to
/// compile.
#[derive(Clone, PartialEq, ::hatchet_proto::prost::Message)]
#[prost(prost_path = "::hatchet_proto::prost")]
struct RpcStatus {
    #[prost(int32, tag = "1")]
    code: i32,
    #[prost(string, tag = "2")]
    message: ::hatchet_proto::prost::alloc::string::String,
    #[prost(message, repeated, tag = "3")]
    details: ::hatchet_proto::prost::alloc::vec::Vec<Any>,
}

/// Turns the error of a trigger call into a collision error when the engine
/// said `AlreadyExists` and named the run that already holds the key.
///
/// Anything else is handed straight back: a plain `AlreadyExists` is the
/// engine's *deduplication* answer (a child key that was already used), not
/// an idempotency collision, and must keep its own shape.
pub(crate) fn from_trigger(error: Error) -> Error {
    let Error::Grpc(status) = &error else {
        return error;
    };
    if status.code() != Code::AlreadyExists {
        return error;
    }
    let Ok(rpc) = RpcStatus::decode(status.details()) else {
        return error;
    };
    for detail in &rpc.details {
        match detail.type_url.as_str() {
            IDEMPOTENCY_TYPE_URL => {
                if let Ok(one) = v1::IdempotencyCollisionError::decode(&detail.value[..]) {
                    return Error::IdempotencyCollision(collision(&one));
                }
            }
            BULK_IDEMPOTENCY_TYPE_URL => {
                if let Ok(bulk) =
                    v1::BulkTriggerIdempotencyCollisionError::decode(&detail.value[..])
                {
                    return Error::BulkIdempotencyCollision {
                        started: bulk.successful_workflow_run_external_ids,
                        collisions: bulk.collisions.iter().map(collision).collect(),
                    };
                }
            }
            _ => {}
        }
    }
    error
}

fn collision(one: &v1::IdempotencyCollisionError) -> IdempotencyCollision {
    IdempotencyCollision {
        existing_run_id: one.existing_run_external_id.clone(),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use tonic::{Code, Status, codegen::Bytes};

    fn status_with(type_url: &str, value: Vec<u8>) -> Status {
        let details = RpcStatus {
            code: Code::AlreadyExists as i32,
            message: "already exists".to_string(),
            details: vec![hatchet_proto::prost_types::Any {
                type_url: type_url.to_string(),
                value,
            }],
        };
        Status::with_details(
            Code::AlreadyExists,
            "already exists",
            Bytes::from(details.encode_to_vec()),
        )
    }

    #[test]
    fn a_single_collision_becomes_its_own_error() {
        let detail = v1::IdempotencyCollisionError {
            existing_run_external_id: "run-1".to_string(),
            colliding_run_external_id: String::new(),
        };
        let error = from_trigger(Error::Grpc(Box::new(status_with(
            IDEMPOTENCY_TYPE_URL,
            detail.encode_to_vec(),
        ))));
        let Error::IdempotencyCollision(collision) = error else {
            panic!("{error:?}")
        };
        assert_eq!(collision.existing_run_id, "run-1");
    }

    #[test]
    fn a_bulk_collision_keeps_the_runs_that_did_start() {
        let detail = v1::BulkTriggerIdempotencyCollisionError {
            successful_workflow_run_external_ids: vec!["run-1".to_string()],
            collisions: vec![v1::IdempotencyCollisionError {
                existing_run_external_id: "run-0".to_string(),
                colliding_run_external_id: String::new(),
            }],
        };
        let error = from_trigger(Error::Grpc(Box::new(status_with(
            BULK_IDEMPOTENCY_TYPE_URL,
            detail.encode_to_vec(),
        ))));
        let Error::BulkIdempotencyCollision {
            started,
            collisions,
        } = error
        else {
            panic!("{error:?}")
        };
        assert_eq!(started, vec!["run-1".to_string()]);
        assert_eq!(collisions.len(), 1);
        assert_eq!(collisions[0].existing_run_id, "run-0");
    }

    #[test]
    fn already_exists_without_details_stays_a_plain_grpc_error() {
        let error = from_trigger(Error::Grpc(Box::new(Status::already_exists("dedupe"))));
        assert!(matches!(error, Error::Grpc(_)), "{error:?}");
    }

    #[test]
    fn already_exists_with_details_of_another_type_stays_a_plain_grpc_error() {
        let error = from_trigger(Error::Grpc(Box::new(status_with(
            "type.googleapis.com/google.rpc.BadRequest",
            Vec::new(),
        ))));
        assert!(matches!(error, Error::Grpc(_)), "{error:?}");
    }

    #[test]
    fn another_code_is_never_touched_however_its_details_look() {
        let error = from_trigger(Error::Grpc(Box::new(Status::internal("boom"))));
        assert!(matches!(error, Error::Grpc(_)), "{error:?}");
    }

    #[test]
    fn details_that_do_not_decode_are_left_alone() {
        let error = from_trigger(Error::Grpc(Box::new(Status::with_details(
            Code::AlreadyExists,
            "already exists",
            Bytes::from_static(&[0xff, 0xff, 0xff, 0xff]),
        ))));
        assert!(matches!(error, Error::Grpc(_)), "{error:?}");
    }

    #[test]
    fn errors_that_are_not_grpc_pass_through() {
        let error = from_trigger(Error::Json("nope".to_string()));
        assert!(matches!(error, Error::Json(_)), "{error:?}");
    }

    #[test]
    fn the_message_names_the_existing_run() {
        let error = Error::IdempotencyCollision(IdempotencyCollision {
            existing_run_id: "run-1".to_string(),
        });
        let message = error.to_string();
        assert!(message.contains("run-1"), "{message}");
    }
}