hatchet-client 0.1.0

Rust SDK for Hatchet: run workers and trigger tasks
Documentation
//! Pure functions that turn context values into the wire representations the
//! engine expects. No I/O here, so these are exercised directly rather than
//! through a `MockEngine`.

use std::time::Duration;

use serde_json::{Map, Value};

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

/// `PutLog` truncates its message at this many *characters* (not bytes).
pub(crate) const MAX_LOG_CHARS: usize = 10_000;

/// The engine's `RefreshTimeout` only accepts an increment expressed in
/// whole hours, minutes, or seconds (`"90m"`, `"2h"`, `"45s"`) — never a
/// mix, and never fractional. Sub-second durations round up to the next
/// whole second so a caller's intent to extend the deadline is never
/// silently dropped.
pub(crate) fn timeout_increment(duration: Duration) -> Result<String> {
    if duration.is_zero() {
        return Err(Error::InvalidArgument(
            "timeout increment must be greater than zero".to_string(),
        ));
    }
    let mut seconds = duration.as_secs();
    if duration.subsec_nanos() > 0 {
        seconds += 1;
    }
    if seconds.is_multiple_of(3600) {
        Ok(format!("{}h", seconds / 3600))
    } else if seconds.is_multiple_of(60) {
        Ok(format!("{}m", seconds / 60))
    } else {
        Ok(format!("{seconds}s"))
    }
}

/// Truncates a log message to [`MAX_LOG_CHARS`] *characters*, always at a
/// character boundary so a multi-byte string is never split mid-character.
pub(crate) fn truncate_log(message: &str) -> &str {
    match message.char_indices().nth(MAX_LOG_CHARS) {
        Some((byte_index, _)) => &message[..byte_index],
        None => message,
    }
}

/// The engine sends `additional_metadata` as an optional JSON-object string.
/// Anything else — absent, empty, or not a JSON object — is treated as no
/// metadata rather than an error, since a handler reading metadata should
/// never panic over what the engine happened to send.
pub(crate) fn parse_metadata(raw: Option<&str>) -> Map<String, Value> {
    let Some(raw) = raw.filter(|raw| !raw.is_empty()) else {
        return Map::new();
    };
    match serde_json::from_str::<Value>(raw) {
        Ok(Value::Object(map)) => map,
        _ => Map::new(),
    }
}

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

    #[test]
    fn timeout_increment_prefers_the_largest_whole_unit() {
        assert_eq!(
            timeout_increment(Duration::from_secs(90 * 60)).unwrap(),
            "90m"
        );
        assert_eq!(
            timeout_increment(Duration::from_secs(2 * 3600)).unwrap(),
            "2h"
        );
        assert_eq!(timeout_increment(Duration::from_secs(45)).unwrap(), "45s");
        assert_eq!(
            timeout_increment(Duration::from_secs(3661)).unwrap(),
            "3661s"
        );
    }

    #[test]
    fn timeout_increment_rounds_sub_second_durations_up() {
        assert_eq!(
            timeout_increment(Duration::from_millis(1500)).unwrap(),
            "2s"
        );
        assert_eq!(timeout_increment(Duration::from_millis(999)).unwrap(), "1s");
    }

    #[test]
    fn timeout_increment_rejects_zero() {
        let error = timeout_increment(Duration::ZERO).unwrap_err();
        assert!(matches!(error, Error::InvalidArgument(_)), "{error:?}");
    }

    #[test]
    fn truncate_log_leaves_short_messages_alone() {
        let message = "a".repeat(MAX_LOG_CHARS);
        assert_eq!(truncate_log(&message), message);
    }

    #[test]
    fn truncate_log_cuts_long_messages_to_exactly_the_limit() {
        let message = "a".repeat(2 * MAX_LOG_CHARS);
        let truncated = truncate_log(&message);
        assert_eq!(truncated.chars().count(), MAX_LOG_CHARS);
        assert_eq!(truncated, "a".repeat(MAX_LOG_CHARS));
    }

    #[test]
    fn truncate_log_cuts_multibyte_messages_at_a_character_boundary() {
        let message = "가".repeat(15_000);
        let truncated = truncate_log(&message);
        assert_eq!(truncated.chars().count(), MAX_LOG_CHARS);
        assert_eq!(truncated, "가".repeat(MAX_LOG_CHARS));
    }

    #[test]
    fn metadata_parses_a_json_object() {
        let map = parse_metadata(Some(r#"{"a":"b","n":1}"#));
        assert_eq!(map.len(), 2);
        assert_eq!(map.get("a"), Some(&Value::String("b".to_string())));
        assert_eq!(map.get("n"), Some(&Value::from(1)));
    }

    #[test]
    fn metadata_is_empty_for_absent_empty_or_non_object_json() {
        assert!(parse_metadata(None).is_empty());
        assert!(parse_metadata(Some("")).is_empty());
        assert!(parse_metadata(Some("[1,2,3]")).is_empty());
    }
}