hatchet-client 0.1.0

Rust SDK for Hatchet: run workers and trigger tasks
Documentation
//! What the engine remembers about a run.

use std::collections::BTreeMap;

use hatchet_proto::v1;
use serde::de::DeserializeOwned;

use crate::Task;
use crate::error::{Error, Result};
use crate::runs::filter::RunStatus;

/// Everything `GetRunDetails` knows about one run.
///
/// Get one from [`RunsClient::details`](crate::RunsClient::details). Unlike
/// a [`WorkflowResult`](crate::WorkflowResult), which only exists for a run
/// this process waited for, this can be asked for at any time — including
/// for a run started by another process, or one that is still going.
///
/// ```no_run
/// # use hatchet_client::{Client, Task};
/// # async fn example(client: &Client, publish: &Task<(), ()>) -> hatchet_client::Result<()> {
/// let details = client.runs().details("some-run-id").await?;
/// println!("{}: done={}", details.status(), details.is_done());
/// if let Some(task) = details.task(publish) {
///     println!("{}: {:?}", task.name(), task.error());
/// }
/// # Ok(())
/// # }
/// ```
#[derive(Clone, Debug)]
pub struct RunDetails {
    run_id: String,
    status: RunStatus,
    done: bool,
    is_evicted: bool,
    input: Vec<u8>,
    additional_metadata: Vec<u8>,
    /// Keyed by readable id (the task's declared name). The proto comment on
    /// `GetRunDetailsResponse.task_runs` calls the map key the task run's
    /// external id, but both the official Go and Python SDKs read it as the
    /// readable id (`pkg/client/admin.go:734-755`,
    /// `sdks/python/hatchet_sdk/clients/admin.py:716-730`) — so the map key
    /// on the wire is not trusted here either; this is keyed by each value's
    /// own `readable_id` field, which is right regardless of what the key
    /// turns out to mean.
    tasks: BTreeMap<String, TaskRunDetail>,
}

/// What the engine knows about one task of a run.
///
/// Get one from [`RunDetails::task`], [`RunDetails::task_by_name`] or
/// [`RunDetails::tasks`].
///
/// ```no_run
/// # use hatchet_client::RunDetails;
/// # fn example(details: &RunDetails) {
/// for (name, task) in details.tasks() {
///     println!("{name}: {} (evicted: {})", task.status(), task.is_evicted());
/// }
/// # }
/// ```
#[derive(Clone, Debug)]
pub struct TaskRunDetail {
    external_id: String,
    readable_id: String,
    status: RunStatus,
    error: Option<String>,
    output: Option<Vec<u8>>,
    is_evicted: bool,
}

impl RunDetails {
    pub(crate) fn from_proto(run_id: &str, response: v1::GetRunDetailsResponse) -> Result<Self> {
        let unknown = |status: i32| Error::UnknownRunStatus {
            run_id: run_id.to_string(),
            status,
        };
        let mut tasks = BTreeMap::new();
        for detail in response.task_runs.into_values() {
            let task = TaskRunDetail {
                readable_id: detail.readable_id.clone(),
                external_id: detail.external_id,
                status: RunStatus::from_proto(detail.status)
                    .ok_or_else(|| unknown(detail.status))?,
                // An empty error is reported even on success (measured
                // against both supported engines); an empty string is not
                // an error, so it is normalized away here.
                error: detail.error.filter(|error| !error.is_empty()),
                output: detail.output,
                is_evicted: detail.is_evicted,
            };
            tasks.insert(detail.readable_id, task);
        }
        Ok(Self {
            run_id: run_id.to_string(),
            status: RunStatus::from_proto(response.status)
                .ok_or_else(|| unknown(response.status))?,
            done: response.done,
            is_evicted: response.is_evicted,
            input: response.input,
            additional_metadata: response.additional_metadata,
            tasks,
        })
    }

    /// The engine's id for this run.
    pub fn run_id(&self) -> &str {
        &self.run_id
    }

    /// The run's state as a whole.
    pub fn status(&self) -> RunStatus {
        self.status
    }

    /// Whether the engine considers the run over.
    pub fn is_done(&self) -> bool {
        self.done
    }

    /// The engine's `is_evicted` flag for the run (what exactly it covers
    /// was not measured; it was `false` in every observed run).
    pub fn is_evicted(&self) -> bool {
        self.is_evicted
    }

    /// The input the run was triggered with, as a `T`.
    ///
    /// # Errors
    ///
    /// [`Error::RunOutput`] when the engine recorded no input, or it is not
    /// a `T`.
    pub fn input<T: DeserializeOwned>(&self) -> Result<T> {
        self.decode(&self.input, "input")
    }

    /// The metadata the run was triggered with
    /// ([`RunOpts::metadata`](crate::RunOpts::metadata)), as a `T` —
    /// `serde_json::Value` for a plain map.
    ///
    /// # Errors
    ///
    /// [`Error::RunOutput`] when there was none, or it is not a `T`.
    pub fn additional_metadata<T: DeserializeOwned>(&self) -> Result<T> {
        self.decode(&self.additional_metadata, "additional metadata")
    }

    /// What the engine knows about `task`, by the name it was declared with.
    pub fn task<I, O>(&self, task: &Task<I, O>) -> Option<&TaskRunDetail> {
        self.task_by_name(task.name())
    }

    /// [`task`](RunDetails::task), by name — matched as declared first and
    /// then without regard to case, because the engine knows a task by the
    /// lowercased name it was registered under.
    pub fn task_by_name(&self, name: &str) -> Option<&TaskRunDetail> {
        self.tasks.get(name).or_else(|| {
            self.tasks
                .values()
                .find(|task| task.readable_id.eq_ignore_ascii_case(name))
        })
    }

    /// Every task of the run, by name, in name order.
    pub fn tasks(&self) -> impl Iterator<Item = (&str, &TaskRunDetail)> {
        self.tasks.iter().map(|(name, task)| (name.as_str(), task))
    }

    /// The output `task` produced, deserialized into the type it was
    /// declared with.
    ///
    /// # Errors
    ///
    /// [`Error::RunOutput`] when the run has no such task, the task recorded
    /// no output, or the output is not an `O`.
    pub fn output_of<I, O: DeserializeOwned>(&self, task: &Task<I, O>) -> Result<O> {
        let detail = self.task(task).ok_or_else(|| Error::RunOutput {
            run_id: self.run_id.clone(),
            reason: format!("the run has no task {:?}", task.name()),
        })?;
        let output = detail.output.as_deref().ok_or_else(|| Error::RunOutput {
            run_id: self.run_id.clone(),
            reason: format!("task {:?} recorded no output", detail.readable_id),
        })?;
        self.decode(
            output,
            &format!("the output of task {:?}", detail.readable_id),
        )
    }

    fn decode<T: DeserializeOwned>(&self, bytes: &[u8], what: &str) -> Result<T> {
        if bytes.is_empty() {
            return Err(Error::RunOutput {
                run_id: self.run_id.clone(),
                reason: format!("the engine recorded no {what} for this run"),
            });
        }
        serde_json::from_slice(bytes).map_err(|error| Error::RunOutput {
            run_id: self.run_id.clone(),
            reason: format!("{what}: {error}"),
        })
    }
}

impl TaskRunDetail {
    /// The engine's id for this task run — what
    /// [`RunsClient::cancel`](crate::RunsClient::cancel) takes.
    pub fn id(&self) -> &str {
        &self.external_id
    }

    /// The task's declared name.
    pub fn name(&self) -> &str {
        &self.readable_id
    }

    /// This task's state.
    pub fn status(&self) -> RunStatus {
        self.status
    }

    /// What went wrong, if anything. `None` both when nothing was recorded
    /// and when the engine recorded an empty error string — an empty string
    /// was observed even on tasks that succeeded, so it does not mean "an
    /// error happened".
    pub fn error(&self) -> Option<&str> {
        self.error.as_deref()
    }

    /// Whether this task was taken off its worker.
    pub fn is_evicted(&self) -> bool {
        self.is_evicted
    }

    /// This task's output, as a `T`.
    ///
    /// # Errors
    ///
    /// [`Error::RunOutput`] when the task recorded no output or it is not a
    /// `T`.
    pub fn output<T: DeserializeOwned>(&self) -> Result<T> {
        let output = self.output.as_deref().ok_or_else(|| Error::RunOutput {
            run_id: self.external_id.clone(),
            reason: format!("task {:?} recorded no output", self.readable_id),
        })?;
        serde_json::from_slice(output).map_err(|error| Error::RunOutput {
            run_id: self.external_id.clone(),
            reason: format!("task {:?}: {error}", self.readable_id),
        })
    }
}