wellfriend-document-sdk 1.0.0

Official async Rust SDK for the Wellfriend document API: typed document tools, pipelines, streaming uploads and downloads, retries and webhook verification.
Documentation
//! Waiting for operations and workflow runs.

use std::time::{Duration, Instant};

use reqwest::Method;

use crate::client::{Request, RequestOptions, Wellfriend};
use crate::error::{Error, OperationFailure, Result};
use crate::generated::resources::{DocumentOperations, WorkflowRuns};
use crate::models::{Operation, OperationState, RunState, WorkflowRun};
use crate::tools::ToolResult;

/// The first pause between two status reads.
pub(crate) const FIRST_POLL: Duration = Duration::from_millis(500);
/// The longest pause between two status reads.
pub(crate) const MAX_POLL: Duration = Duration::from_secs(5);

/// Polls with a growing pause (0.5 s, then ×1.5 up to 5 s) until `done` says the value is final.
pub(crate) async fn poll<T, F, Fut>(
    kind: &'static str,
    id: &str,
    limit: Duration,
    mut read: F,
    done: impl Fn(&T) -> bool,
) -> Result<T>
where
    F: FnMut() -> Fut,
    Fut: std::future::Future<Output = Result<T>>,
{
    let started = Instant::now();
    let mut pause = FIRST_POLL;
    loop {
        let value = read().await?;
        if done(&value) {
            return Ok(value);
        }
        let waited = started.elapsed();
        if waited >= limit {
            return Err(Error::WaitTimeout {
                kind,
                id: id.to_owned(),
                waited,
            });
        }
        tokio::time::sleep(pause.min(limit - waited)).await;
        pause = pause.mul_f64(1.5).min(MAX_POLL);
    }
}

pub(crate) async fn get_operation(
    client: &Wellfriend,
    options: &RequestOptions,
    id: &str,
) -> Result<Operation> {
    client
        .json_field(
            options,
            Request::new(Method::GET, ["document-operations", id]),
            "operation",
        )
        .await
}

/// Waits until the operation finishes and fails with [`Error::OperationFailed`] unless it
/// completed.
pub(crate) async fn wait_operation(
    client: &Wellfriend,
    options: &RequestOptions,
    id: &str,
) -> Result<Operation> {
    let reads = options.without_key();
    let limit = options.wait_limit(client);
    let operation = poll(
        "operation",
        id,
        limit,
        || get_operation(client, &reads, id),
        |operation: &Operation| operation.state.is_terminal(),
    )
    .await?;
    if operation.state == OperationState::Completed {
        Ok(operation)
    } else {
        Err(operation_failed(operation))
    }
}

pub(crate) fn operation_failed(operation: Operation) -> Error {
    let code = operation.error_code.clone().unwrap_or_else(|| {
        format!(
            "OPERATION_{}",
            operation.state.as_str().to_ascii_uppercase()
        )
    });
    let message = operation.error_message.clone().unwrap_or_default();
    Error::OperationFailed(Box::new(OperationFailure {
        code,
        message,
        id: operation.id.clone(),
        step: None,
        operation: Some(Box::new(operation)),
        run: None,
    }))
}

pub(crate) async fn get_run(
    client: &Wellfriend,
    options: &RequestOptions,
    id: &str,
) -> Result<WorkflowRun> {
    client
        .json_field(
            options,
            Request::new(Method::GET, ["workflow-runs", id]),
            "run",
        )
        .await
}

/// Waits until the run finishes and fails with [`Error::OperationFailed`] unless it succeeded.
pub(crate) async fn wait_run(
    client: &Wellfriend,
    options: &RequestOptions,
    id: &str,
) -> Result<WorkflowRun> {
    let reads = options.without_key();
    let limit = options.wait_limit(client);
    let run = poll(
        "workflow run",
        id,
        limit,
        || get_run(client, &reads, id),
        |run: &WorkflowRun| run.state.is_terminal(),
    )
    .await?;
    if run.state == RunState::Succeeded {
        Ok(run)
    } else {
        let code = run
            .error_code()
            .map(str::to_owned)
            .unwrap_or_else(|| format!("WORKFLOW_RUN_{}", run.state.as_str()));
        let message = run
            .steps
            .iter()
            .filter(|step| step.state == RunState::Failed)
            .find_map(|step| {
                step.output
                    .get("errorMessage")
                    .and_then(|value| value.as_str())
                    .map(str::to_owned)
            })
            .unwrap_or_default();
        Err(Error::OperationFailed(Box::new(OperationFailure {
            code,
            message,
            id: run.id.clone(),
            step: None,
            operation: None,
            run: Some(Box::new(run)),
        })))
    }
}

impl DocumentOperations {
    /// Waits for an operation started earlier (for example with
    /// [`Tools::start`](crate::Tools::start)) and returns its result.
    ///
    /// Fails with [`Error::OperationFailed`] when the operation fails or is cancelled, and with
    /// [`Error::WaitTimeout`] when it is still running at the wait limit.
    pub async fn wait(&self, operation_id: &str) -> Result<ToolResult> {
        let operation = wait_operation(&self.client, &self.options, operation_id).await?;
        ToolResult::from_operation(&self.client, &self.options, operation, None).await
    }
}

impl WorkflowRuns {
    /// Waits for a workflow run to finish and returns it.
    ///
    /// Fails with [`Error::OperationFailed`] when the run fails or is cancelled, and with
    /// [`Error::WaitTimeout`] when it is still running at the wait limit.
    pub async fn wait(&self, run_id: &str) -> Result<WorkflowRun> {
        wait_run(&self.client, &self.options, run_id).await
    }
}