use std::fmt;
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};
pub const MAX_TIME: u64 = (1 << 53) - 1;
pub const DEFAULT_MAX_TIMERS: usize = 1000;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Outcome {
Resolved,
Rejected,
Done,
}
#[derive(Debug, Clone, PartialEq)]
pub enum Input {
Event(Value),
Time { now: i64 },
Work { id: String, outcome: Outcome, data: Option<Value> },
}
impl Input {
pub fn from_json(input: &Value) -> Result<Self, ApplyError> {
let Some(object) = input.as_object() else {
return Err(ApplyError::invalid_input("Each input is an object, an event or a control input."));
};
match object.get("kind").and_then(Value::as_str) {
Some(kind @ ("time" | "work")) => {
if object.contains_key("type") {
return Err(ApplyError::invalid_input("A control input has no type."));
}
if kind == "time" {
let now = object
.get("now")
.and_then(safe_integer)
.ok_or_else(|| ApplyError::invalid_input("A time input has a now of whole milliseconds."))?;
return Ok(Self::Time { now });
}
let id = object
.get("id")
.and_then(Value::as_str)
.ok_or_else(|| ApplyError::invalid_input("A work result has a string id."))?;
let outcome =
object.get("outcome").cloned().and_then(|o| serde_json::from_value(o).ok()).ok_or_else(|| {
ApplyError::invalid_input("A work result has an outcome, resolved, rejected or done.")
})?;
if outcome == Outcome::Done && object.contains_key("data") {
return Err(ApplyError::invalid_input("A work result of done has no data."));
}
Ok(Self::Work { id: id.to_owned(), outcome, data: object.get("data").cloned() })
}
_ if object.get("type").is_some_and(Value::is_string) => Ok(Self::Event(input.clone())),
_ if object.contains_key("kind") => {
Err(ApplyError::invalid_input("A control input is of kind time or work."))
}
_ => Err(ApplyError::invalid_input("An event has a string type.")),
}
}
pub fn to_json(&self) -> Value {
match self {
Self::Event(event) => event.clone(),
Self::Time { now } => serde_json::json!({ "kind": "time", "now": now }),
Self::Work { id, outcome, data } => {
let mut m = Map::new();
m.insert("kind".into(), "work".into());
m.insert("id".into(), Value::String(id.clone()));
m.insert("outcome".into(), serde_json::to_value(outcome).unwrap_or_default());
if let Some(data) = data {
m.insert("data".into(), data.clone());
}
Value::Object(m)
}
}
}
}
fn safe_integer(now: &Value) -> Option<i64> {
let max = MAX_TIME as i64;
let whole = now.as_i64().or_else(|| {
let f = now.as_f64()?;
(f.fract() == 0.0 && f.abs() <= MAX_TIME as f64).then_some(f as i64)
})?;
(-max..=max).contains(&whole).then_some(whole)
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "lowercase")]
pub enum Work {
Invoke {
id: String,
actor: String,
src: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
input: Option<Value>,
},
Action {
id: String,
actor: String,
#[serde(rename = "type")]
ty: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
params: Option<Value>,
},
}
impl Work {
pub fn id(&self) -> &str {
match self {
Self::Invoke { id, .. } | Self::Action { id, .. } => id,
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Root {
pub status: String,
pub value: Value,
pub context: Value,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub output: Option<Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub error: Option<Value>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Step {
pub emitted: Vec<Value>,
pub root: Root,
pub time: u64,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub deadline: Option<u64>,
pub work: Vec<Work>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Failure {
pub message: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub data: Option<Value>,
}
impl Failure {
pub fn new(message: impl Into<String>) -> Self {
Self { message: message.into(), data: None }
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum ApplyError {
Rejected { rejected: Failure },
Fault { code: String, message: String },
}
impl ApplyError {
pub fn fault(code: impl Into<String>, message: impl Into<String>) -> Self {
Self::Fault { code: code.into(), message: message.into() }
}
pub fn invalid_input(message: impl Into<String>) -> Self {
Self::fault("WORKFLOW_INVALID_INPUT", message)
}
pub fn invalid_work_result(message: impl Into<String>) -> Self {
Self::fault("WORKFLOW_INVALID_WORK_RESULT", message)
}
pub fn rejected(message: impl Into<String>) -> Self {
Self::Rejected { rejected: Failure::new(message) }
}
pub fn rejected_with(failure: Failure) -> Self {
Self::Rejected { rejected: failure }
}
pub fn start_failed(message: impl Into<String>) -> Self {
Self::fault("WORKFLOW_MACHINE_FAILED", message)
}
pub fn invalid_snapshot(message: impl Into<String>) -> Self {
Self::fault("WORKFLOW_INVALID_SNAPSHOT", message)
}
pub fn invalid_machine(message: impl Into<String>) -> Self {
Self::fault("WORKFLOW_INVALID_MACHINE", message)
}
pub fn engine_failed(message: impl Into<String>) -> Self {
Self::fault("WORKFLOW_ENGINE_FAILED", message)
}
pub fn code(&self) -> Option<&str> {
match self {
Self::Rejected { .. } => None,
Self::Fault { code, .. } => Some(code),
}
}
pub fn message(&self) -> &str {
match self {
Self::Rejected { rejected } => &rejected.message,
Self::Fault { message, .. } => message,
}
}
pub fn rejection(&self) -> Option<&Failure> {
match self {
Self::Rejected { rejected } => Some(rejected),
Self::Fault { .. } => None,
}
}
}
impl fmt::Display for ApplyError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Rejected { rejected } => write!(f, "rejected: {}", rejected.message),
Self::Fault { code, message } => write!(f, "{code}: {message}"),
}
}
}
impl std::error::Error for ApplyError {}
pub(crate) fn decode_address_segment(segment: &str) -> String {
if segment.contains('%') {
segment.replace("%2F", "/").replace("%25", "%")
} else {
segment.to_owned()
}
}