hatchet-client 0.1.0

Rust SDK for Hatchet: run workers and trigger tasks
Documentation
//! Engine version check.

use crate::{Error, Result};

/// The oldest Hatchet engine this SDK works with.
pub const MIN_ENGINE_VERSION: &str = "v0.80.0";

/// The oldest engine that honours a workflow's `idempotency` config.
///
/// Measured, not guessed: on v0.80.0 the field is accepted at `PutWorkflow`
/// but idempotency does not apply — a duplicate trigger silently starts a
/// second run instead of being refused. On v0.107.0 it is enforced (a
/// colliding trigger is rejected with an `AlreadyExists`/collision error).
/// The exact version in between where enforcement was introduced was not
/// measured, so this gates at the newer, verified value.
pub const IDEMPOTENCY_MIN_ENGINE_VERSION: &str = "v0.107.0";

/// The oldest engine a durable handler may spawn a child run on with
/// [`DurableContext::spawn`](crate::DurableContext::spawn).
///
/// Measured, and the measurement is why this sits above
/// [`MIN_ENGINE_VERSION`] rather than at it — the official Go SDK gates durable
/// child spawns on v0.80.0 (`sdks/go/engine_version.go:17`). On v0.80.0 a
/// `trigger_runs` request is neither refused nor fatal: the engine consumes a
/// log node, really does start the child run, and acknowledges it — but with
/// **`workflow_run_external_id` left empty**, so the SDK cannot say which run
/// it started or hand a usable id back. Refusing the call is better than that
/// silent uselessness, so an engine below this answers
/// [`Error::UnsupportedFeature`](crate::Error::UnsupportedFeature) and nothing
/// is put on the durable stream.
///
/// v0.85.0 is the lowest version measured filling the id in (v0.90.0, v0.95.0
/// and v0.107.0 fill it too); v0.81.0 through v0.84.0 were not measured, so the
/// gate sits at the verified value, exactly as
/// [`IDEMPOTENCY_MIN_ENGINE_VERSION`] does.
pub const DURABLE_SPAWN_MIN_ENGINE_VERSION: &str = "v0.85.0";

/// The oldest engine that really batches a batch task's runs.
///
/// Measured across eleven tags, and the measurement is the whole point: every
/// version from v0.80.0 up **accepts** a `CreateTaskOpts.batch` at
/// `PutWorkflow` without a word, so acceptance says nothing. What splits them
/// is what the engine does next. On v0.80.0, v0.88.0, v0.88.1, v0.90.0,
/// v0.95.0, v0.96.0 and v0.97.0 the field is silently ignored: five concurrent
/// runs were assigned as five ordinary `START_STEP_RUN` actions and no
/// `START_BATCH` ever arrived. On v0.98.0, v0.101.0, v0.105.0 and v0.107.0 the
/// same five runs were buffered and assigned as **one** `START_BATCH`. The
/// boundary is monotone, so this gates at v0.98.0 — the lowest version
/// measured batching.
///
/// The official Python SDK writes down a different value
/// (`sdks/python/hatchet_sdk/engine_version.py:10`, `BATCHING = "v0.88.1"`),
/// but **no code in that SDK reads it** — a full grep finds no use — and the
/// measurement above contradicts it: v0.88.1 takes the registration and then
/// assigns plain step runs. The Go SDK has no batching constant at all.
///
/// A worker registering a batch task on an older engine is refused by
/// [`WorkerBuilder::build`](crate::WorkerBuilder::build) with
/// [`Error::UnsupportedFeature`](crate::Error::UnsupportedFeature). Refusing is
/// the point: an engine below this does not fail, it *succeeds differently* —
/// every run of the task is assigned singly to a worker whose only handler for
/// that action expects a whole batch, so the runs fail one by one with a
/// worker that looks perfectly healthy.
pub const BATCH_MIN_ENGINE_VERSION: &str = "v0.98.0";

/// The oldest engine that takes a worker-initiated eviction.
///
/// The same version the official Go and Python SDKs gate durable eviction on
/// (`sdks/go/engine_version.go:17`), and measured to be right: eviction works
/// end to end on v0.80.0 exactly as it does on v0.107.0, with the engine
/// assigning the task again 0.7 to 1.5 seconds after the wait it was parked
/// on completes on both.
///
/// It is deliberately **the same value** as [`MIN_ENGINE_VERSION`], which
/// [`WorkerBuilder::build`](crate::WorkerBuilder::build) already refuses to go
/// below — so no worker this SDK builds can ever fail this gate. The constant
/// and the check
/// ([`eviction::supported`](crate::durable::eviction::supported)) exist so
/// that the day the floor moves down, a policy meets a warning and is dropped
/// rather than being sent to an engine that cannot honour it. That is a
/// deliberate difference from the official SDKs, which *can* reach the warning.
pub(crate) const EVICTION_MIN_ENGINE_VERSION: &str = MIN_ENGINE_VERSION;

/// Fails unless `reported` (as returned by `Dispatcher/GetVersion`, e.g.
/// `"v0.107.0"`) is at least [`MIN_ENGINE_VERSION`].
pub(crate) fn ensure_supported(reported: &str) -> Result<()> {
    let found = parse(reported)?;
    let minimum = parse(MIN_ENGINE_VERSION).expect("MIN_ENGINE_VERSION is valid");
    if found < minimum {
        return Err(Error::UnsupportedEngine {
            found: reported.to_string(),
            minimum: MIN_ENGINE_VERSION.to_string(),
        });
    }
    Ok(())
}

/// Fails unless `reported` is at least `minimum`, naming `feature`.
pub(crate) fn ensure_feature(feature: &str, minimum: &str, reported: &str) -> Result<()> {
    let found = parse(reported)?;
    let wanted = parse(minimum).expect("a feature minimum is valid");
    if found < wanted {
        return Err(Error::UnsupportedFeature {
            feature: feature.to_string(),
            found: reported.to_string(),
            minimum: minimum.to_string(),
        });
    }
    Ok(())
}

/// `"v0.80.0-alpha.1"` → `(0, 80, 0)`. Pre-release tags are ignored.
fn parse(version: &str) -> Result<(u64, u64, u64)> {
    let invalid = || Error::InvalidEngineVersion(version.to_string());
    let core = version.strip_prefix('v').unwrap_or(version);
    let core = core.split_once('-').map_or(core, |(core, _)| core);
    let mut parts = core.split('.').map(|part| part.parse::<u64>().ok());
    match (parts.next(), parts.next(), parts.next(), parts.next()) {
        (Some(Some(major)), Some(Some(minor)), Some(Some(patch)), None) => {
            Ok((major, minor, patch))
        }
        _ => Err(invalid()),
    }
}

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

    #[test]
    fn versions_at_or_above_the_minimum_are_accepted() {
        for version in [
            "v0.80.0",
            "v0.80.1",
            "v0.107.0",
            "v1.0.0",
            "0.80.0",
            "v0.80.0-alpha.1",
        ] {
            ensure_supported(version).unwrap_or_else(|e| panic!("{version}: {e}"));
        }
    }

    #[test]
    fn versions_below_the_minimum_are_rejected_with_both_versions_named() {
        for version in ["v0.79.9", "v0.78.23", "v0.9.200"] {
            let err = ensure_supported(version).unwrap_err();
            assert!(
                matches!(err, Error::UnsupportedEngine { .. }),
                "{version}: {err:?}"
            );
            assert!(err.to_string().contains(version), "{err}");
            assert!(err.to_string().contains("v0.80.0"), "{err}");
        }
    }

    #[test]
    fn unparseable_versions_are_errors() {
        for version in ["", "latest", "v0.80", "v0.x.1", "v1.2.3.4", "v-1.0.0"] {
            let err = ensure_supported(version).unwrap_err();
            assert!(
                matches!(err, Error::InvalidEngineVersion(_)),
                "{version:?}: {err:?}"
            );
        }
    }

    #[test]
    fn a_feature_gate_names_the_feature_the_engine_and_the_minimum() {
        let err =
            ensure_feature("idempotency", IDEMPOTENCY_MIN_ENGINE_VERSION, "v0.80.0").unwrap_err();
        assert!(matches!(err, Error::UnsupportedFeature { .. }), "{err:?}");
        let message = err.to_string();
        assert!(message.contains("idempotency"), "{message}");
        assert!(message.contains("v0.80.0"), "{message}");
        assert!(
            message.contains(IDEMPOTENCY_MIN_ENGINE_VERSION),
            "{message}"
        );
    }

    #[test]
    fn a_new_enough_engine_passes_the_gate() {
        ensure_feature("idempotency", IDEMPOTENCY_MIN_ENGINE_VERSION, "v0.107.0").unwrap();
    }

    #[test]
    fn the_batch_gate_names_the_feature_and_both_versions() {
        // v0.97.0 is the highest version measured *not* batching, so it is the
        // one the gate has to keep out.
        let err = ensure_feature("batch tasks", BATCH_MIN_ENGINE_VERSION, "v0.97.0").unwrap_err();
        assert!(matches!(err, Error::UnsupportedFeature { .. }), "{err:?}");
        let message = err.to_string();
        assert!(message.contains("batch"), "{message}");
        assert!(message.contains("v0.97.0"), "{message}");
        assert!(message.contains(BATCH_MIN_ENGINE_VERSION), "{message}");

        // The Python SDK's documented value is below the measured boundary, so
        // it must not pass: an engine there accepts the registration and then
        // assigns ordinary step runs.
        assert!(ensure_feature("batch tasks", BATCH_MIN_ENGINE_VERSION, "v0.88.1").is_err());

        ensure_feature("batch tasks", BATCH_MIN_ENGINE_VERSION, "v0.98.0").unwrap();
        ensure_feature("batch tasks", BATCH_MIN_ENGINE_VERSION, "v0.107.0").unwrap();
    }

    #[test]
    fn an_unparseable_engine_version_is_its_own_error_at_the_gate_too() {
        let err =
            ensure_feature("idempotency", IDEMPOTENCY_MIN_ENGINE_VERSION, "latest").unwrap_err();
        assert!(matches!(err, Error::InvalidEngineVersion(_)), "{err:?}");
    }
}