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;
pub(crate) const FIRST_POLL: Duration = Duration::from_millis(500);
pub(crate) const MAX_POLL: Duration = Duration::from_secs(5);
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
}
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
}
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 {
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 {
pub async fn wait(&self, run_id: &str) -> Result<WorkflowRun> {
wait_run(&self.client, &self.options, run_id).await
}
}