Skip to main content

wellfriend/
operations.rs

1//! Waiting for operations and workflow runs.
2
3use std::time::{Duration, Instant};
4
5use reqwest::Method;
6
7use crate::client::{Request, RequestOptions, Wellfriend};
8use crate::error::{Error, OperationFailure, Result};
9use crate::generated::resources::{DocumentOperations, WorkflowRuns};
10use crate::models::{Operation, OperationState, RunState, WorkflowRun};
11use crate::tools::ToolResult;
12
13/// The first pause between two status reads.
14pub(crate) const FIRST_POLL: Duration = Duration::from_millis(500);
15/// The longest pause between two status reads.
16pub(crate) const MAX_POLL: Duration = Duration::from_secs(5);
17
18/// Polls with a growing pause (0.5 s, then ×1.5 up to 5 s) until `done` says the value is final.
19pub(crate) async fn poll<T, F, Fut>(
20    kind: &'static str,
21    id: &str,
22    limit: Duration,
23    mut read: F,
24    done: impl Fn(&T) -> bool,
25) -> Result<T>
26where
27    F: FnMut() -> Fut,
28    Fut: std::future::Future<Output = Result<T>>,
29{
30    let started = Instant::now();
31    let mut pause = FIRST_POLL;
32    loop {
33        let value = read().await?;
34        if done(&value) {
35            return Ok(value);
36        }
37        let waited = started.elapsed();
38        if waited >= limit {
39            return Err(Error::WaitTimeout {
40                kind,
41                id: id.to_owned(),
42                waited,
43            });
44        }
45        tokio::time::sleep(pause.min(limit - waited)).await;
46        pause = pause.mul_f64(1.5).min(MAX_POLL);
47    }
48}
49
50pub(crate) async fn get_operation(
51    client: &Wellfriend,
52    options: &RequestOptions,
53    id: &str,
54) -> Result<Operation> {
55    client
56        .json_field(
57            options,
58            Request::new(Method::GET, ["document-operations", id]),
59            "operation",
60        )
61        .await
62}
63
64/// Waits until the operation finishes and fails with [`Error::OperationFailed`] unless it
65/// completed.
66pub(crate) async fn wait_operation(
67    client: &Wellfriend,
68    options: &RequestOptions,
69    id: &str,
70) -> Result<Operation> {
71    let reads = options.without_key();
72    let limit = options.wait_limit(client);
73    let operation = poll(
74        "operation",
75        id,
76        limit,
77        || get_operation(client, &reads, id),
78        |operation: &Operation| operation.state.is_terminal(),
79    )
80    .await?;
81    if operation.state == OperationState::Completed {
82        Ok(operation)
83    } else {
84        Err(operation_failed(operation))
85    }
86}
87
88pub(crate) fn operation_failed(operation: Operation) -> Error {
89    let code = operation.error_code.clone().unwrap_or_else(|| {
90        format!(
91            "OPERATION_{}",
92            operation.state.as_str().to_ascii_uppercase()
93        )
94    });
95    let message = operation.error_message.clone().unwrap_or_default();
96    Error::OperationFailed(Box::new(OperationFailure {
97        code,
98        message,
99        id: operation.id.clone(),
100        step: None,
101        operation: Some(Box::new(operation)),
102        run: None,
103    }))
104}
105
106pub(crate) async fn get_run(
107    client: &Wellfriend,
108    options: &RequestOptions,
109    id: &str,
110) -> Result<WorkflowRun> {
111    client
112        .json_field(
113            options,
114            Request::new(Method::GET, ["workflow-runs", id]),
115            "run",
116        )
117        .await
118}
119
120/// Waits until the run finishes and fails with [`Error::OperationFailed`] unless it succeeded.
121pub(crate) async fn wait_run(
122    client: &Wellfriend,
123    options: &RequestOptions,
124    id: &str,
125) -> Result<WorkflowRun> {
126    let reads = options.without_key();
127    let limit = options.wait_limit(client);
128    let run = poll(
129        "workflow run",
130        id,
131        limit,
132        || get_run(client, &reads, id),
133        |run: &WorkflowRun| run.state.is_terminal(),
134    )
135    .await?;
136    if run.state == RunState::Succeeded {
137        Ok(run)
138    } else {
139        let code = run
140            .error_code()
141            .map(str::to_owned)
142            .unwrap_or_else(|| format!("WORKFLOW_RUN_{}", run.state.as_str()));
143        let message = run
144            .steps
145            .iter()
146            .filter(|step| step.state == RunState::Failed)
147            .find_map(|step| {
148                step.output
149                    .get("errorMessage")
150                    .and_then(|value| value.as_str())
151                    .map(str::to_owned)
152            })
153            .unwrap_or_default();
154        Err(Error::OperationFailed(Box::new(OperationFailure {
155            code,
156            message,
157            id: run.id.clone(),
158            step: None,
159            operation: None,
160            run: Some(Box::new(run)),
161        })))
162    }
163}
164
165impl DocumentOperations {
166    /// Waits for an operation started earlier (for example with
167    /// [`Tools::start`](crate::Tools::start)) and returns its result.
168    ///
169    /// Fails with [`Error::OperationFailed`] when the operation fails or is cancelled, and with
170    /// [`Error::WaitTimeout`] when it is still running at the wait limit.
171    pub async fn wait(&self, operation_id: &str) -> Result<ToolResult> {
172        let operation = wait_operation(&self.client, &self.options, operation_id).await?;
173        ToolResult::from_operation(&self.client, &self.options, operation, None).await
174    }
175}
176
177impl WorkflowRuns {
178    /// Waits for a workflow run to finish and returns it.
179    ///
180    /// Fails with [`Error::OperationFailed`] when the run fails or is cancelled, and with
181    /// [`Error::WaitTimeout`] when it is still running at the wait limit.
182    pub async fn wait(&self, run_id: &str) -> Result<WorkflowRun> {
183        wait_run(&self.client, &self.options, run_id).await
184    }
185}