use std::{fmt, sync::atomic::Ordering, time::Duration};
use serde_json::Value;
use crate::{
path_segment, AvroValue, Boundary, Client, Error, RequestProtocol, Result, WorkflowHandle,
};
pub(crate) const UPDATE_OUTCOME_READS_CAPABILITY: &str = "update_outcome_reads";
const WAIT_TRANSPORT_MARGIN: Duration = Duration::from_secs(30);
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum UpdateWaitStage {
#[default]
Accepted,
Completed,
}
impl UpdateWaitStage {
pub fn as_str(self) -> &'static str {
match self {
Self::Accepted => "accepted",
Self::Completed => "completed",
}
}
}
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub struct UpdatePending {
pub workflow_id: String,
pub run_id: Option<String>,
pub update_name: Option<String>,
pub update_id: Option<String>,
pub request_id: Option<String>,
pub update_status: Option<String>,
pub wait_timed_out: bool,
pub receipt: Value,
from_outcome_read: bool,
}
impl UpdatePending {
fn from_receipt(workflow_id: &str, receipt: Value, from_outcome_read: bool) -> Self {
let string = |name: &str| {
receipt
.get(name)
.and_then(Value::as_str)
.filter(|value| !value.is_empty())
.map(str::to_string)
};
Self {
workflow_id: string("workflow_id").unwrap_or_else(|| workflow_id.to_string()),
run_id: string("run_id"),
update_name: string("update_name"),
update_id: string("update_id"),
request_id: string("request_id"),
update_status: string("update_status"),
wait_timed_out: receipt.get("wait_timed_out") == Some(&Value::Bool(true)),
receipt,
from_outcome_read,
}
}
}
impl fmt::Display for UpdatePending {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let status = self.update_status.as_deref().unwrap_or("pending");
let update = match (&self.update_name, &self.update_id) {
(Some(name), Some(id)) => format!("{name} ({id})"),
(Some(name), None) => name.clone(),
(None, Some(id)) => id.clone(),
(None, None) => "update".to_string(),
};
write!(
f,
"update_still_pending: update {update} on workflow {} is still {status}; it has no result yet.",
self.workflow_id
)?;
match (&self.update_id, &self.request_id) {
(Some(id), _) if self.from_outcome_read => write!(
f,
" Call update_outcome() again with update id {id:?} to keep waiting. Reading never admits another update."
),
(Some(id), Some(key)) => write!(
f,
" Read it again with update_outcome() and update id {id:?} on a Server that advertises update_outcome_reads, or call update_workflow() again with request_id {key:?}: the Server returns the retained update instead of admitting a second one."
),
(Some(id), None) => write!(
f,
" Read it again with update_outcome() and update id {id:?} on a Server that advertises update_outcome_reads."
),
(None, Some(key)) => write!(
f,
" Call update_workflow() again with request_id {key:?}: the Server returns the retained update instead of admitting a second one."
),
(None, None) => Ok(()),
}
}
}
impl std::error::Error for UpdatePending {}
pub(crate) fn update_receipt_is_pending(receipt: &Value) -> bool {
if receipt.get("result_envelope").is_some_and(Value::is_object) {
return false;
}
receipt.get("wait_timed_out") == Some(&Value::Bool(true))
|| receipt
.get("update_status")
.and_then(Value::as_str)
.is_some_and(|status| !matches!(status, "completed" | "failed" | "rejected"))
}
pub(crate) fn reject_pending_update(
workflow_id: &str,
receipt: Value,
from_outcome_read: bool,
) -> Result<Value> {
if update_receipt_is_pending(&receipt) {
return Err(Error::UpdateStillPending(UpdatePending::from_receipt(
workflow_id,
receipt,
from_outcome_read,
)));
}
Ok(receipt)
}
fn is_receipt_for(receipt: &Value, workflow_id: &str, update_id: &str) -> bool {
receipt.get("update_id").and_then(Value::as_str) == Some(update_id)
&& receipt.get("update_status").is_some_and(Value::is_string)
&& receipt
.get("workflow_id")
.and_then(Value::as_str)
.is_none_or(|echoed| echoed == workflow_id)
}
fn unrecognized(workflow_id: &str, update_id: &str, receipt: Value) -> Error {
Error::UnrecognizedUpdateOutcome {
workflow_id: workflow_id.to_string(),
update_id: update_id.to_string(),
receipt,
}
}
fn completed_update_avro_value(client: &Client, receipt: &Value) -> Result<AvroValue> {
client.assert_protected_result_receipt(receipt, true)?;
let envelope = receipt
.get("result_envelope")
.filter(|envelope| !envelope.is_null())
.ok_or_else(|| {
Error::Codec(
"missing_payload_envelope: typed update result requires result_envelope"
.to_string(),
)
})?;
client.decode_client_payload(envelope, Boundary::UpdateResult)
}
impl Client {
pub async fn update_outcome(
&self,
workflow_id: &str,
update_id: &str,
wait_timeout_seconds: Option<u64>,
) -> Result<Value> {
let receipt = self
.completed_update_outcome(workflow_id, update_id, wait_timeout_seconds)
.await?;
match receipt
.get("result_envelope")
.filter(|envelope| !envelope.is_null())
{
Some(envelope) => self.decode_client_json(envelope, Boundary::UpdateResult),
None => Ok(receipt.get("result").cloned().unwrap_or(Value::Null)),
}
}
pub async fn update_outcome_avro_value(
&self,
workflow_id: &str,
update_id: &str,
wait_timeout_seconds: Option<u64>,
) -> Result<AvroValue> {
let receipt = self
.completed_update_outcome(workflow_id, update_id, wait_timeout_seconds)
.await?;
completed_update_avro_value(self, &receipt)
}
pub async fn update_outcome_receipt(
&self,
workflow_id: &str,
update_id: &str,
wait_for: UpdateWaitStage,
wait_timeout_seconds: Option<u64>,
) -> Result<Value> {
let mut path = format!(
"/workflows/{}/updates/{}",
path_segment("workflow_id", workflow_id)?,
path_segment("update_id", update_id)?,
);
if update_id.trim().is_empty() {
return Err(Error::Codec(
"an update outcome read needs the update id".to_string(),
));
}
self.require_update_outcome_reads().await?;
let mut query = Vec::new();
if wait_for == UpdateWaitStage::Completed {
query.push(format!("wait_for={}", wait_for.as_str()));
}
if let Some(seconds) = wait_timeout_seconds {
query.push(format!("wait_timeout_seconds={seconds}"));
}
if !query.is_empty() {
path.push('?');
path.push_str(&query.join("&"));
}
let timeout = wait_timeout_seconds
.map(|seconds| Duration::from_secs(seconds).saturating_add(WAIT_TRANSPORT_MARGIN))
.unwrap_or(Duration::ZERO)
.max(Duration::from_secs(60));
let receipt: Value = self
.request_json_with_timeout(
reqwest::Method::GET,
&path,
RequestProtocol::ControlPlane,
Option::<&Value>::None,
timeout,
)
.await?;
self.assert_protected_result_receipt(
&receipt,
receipt.get("update_status").and_then(Value::as_str) == Some("completed"),
)?;
if !is_receipt_for(&receipt, workflow_id, update_id) {
return Err(unrecognized(workflow_id, update_id, receipt));
}
Ok(receipt)
}
async fn completed_update_outcome(
&self,
workflow_id: &str,
update_id: &str,
wait_timeout_seconds: Option<u64>,
) -> Result<Value> {
let receipt = self
.update_outcome_receipt(
workflow_id,
update_id,
UpdateWaitStage::Completed,
wait_timeout_seconds,
)
.await?;
let receipt = reject_pending_update(workflow_id, receipt, true)?;
let completed = receipt.get("result_envelope").is_some_and(Value::is_object)
|| receipt.get("update_status").and_then(Value::as_str) == Some("completed");
if !completed {
return Err(unrecognized(workflow_id, update_id, receipt));
}
Ok(receipt)
}
async fn require_update_outcome_reads(&self) -> Result<()> {
if self.update_outcome_reads_supported.load(Ordering::SeqCst) {
return Ok(());
}
let discovery = self.cluster_info().await?;
if discovery["capabilities"][UPDATE_OUTCOME_READS_CAPABILITY] != Value::Bool(true) {
return Err(Error::UpdateOutcomeReadsUnavailable);
}
self.update_outcome_reads_supported
.store(true, Ordering::SeqCst);
Ok(())
}
}
impl WorkflowHandle {
pub async fn update_outcome(
&self,
update_id: &str,
wait_timeout_seconds: Option<u64>,
) -> Result<Value> {
self.client
.update_outcome(&self.workflow_id, update_id, wait_timeout_seconds)
.await
}
pub async fn update_outcome_avro_value(
&self,
update_id: &str,
wait_timeout_seconds: Option<u64>,
) -> Result<AvroValue> {
self.client
.update_outcome_avro_value(&self.workflow_id, update_id, wait_timeout_seconds)
.await
}
}
impl Client {
pub(crate) fn submitted_update_value(
&self,
workflow_id: &str,
receipt: Value,
) -> Result<Value> {
let receipt = reject_pending_update(workflow_id, receipt, false)?;
self.assert_protected_result_receipt(&receipt, true)?;
if let Some(envelope) = receipt
.get("result_envelope")
.filter(|envelope| !envelope.is_null())
{
return self.decode_client_json(envelope, Boundary::UpdateResult);
}
Ok(receipt.get("result").cloned().unwrap_or(receipt))
}
pub(crate) fn submitted_update_avro_value(
&self,
workflow_id: &str,
receipt: Value,
) -> Result<AvroValue> {
let receipt = reject_pending_update(workflow_id, receipt, false)?;
completed_update_avro_value(self, &receipt)
}
}
#[cfg(test)]
pub(crate) mod tests;