Skip to main content

riffdb_client_rust/
saga.rs

1//! Typed client operations for compiled multi-step durable sagas (`ADR-0334`).
2
3use std::collections::BTreeMap;
4use std::time::Duration;
5
6use crate::{
7    ApplicationClientError, ApplicationCommand, ApplicationCommandResult, ApplicationValue,
8    AttemptBudget, CallMetadata, RiffDbClient, StableApplicationClient,
9    application::raise_application_command_result,
10};
11
12/// Durable lifecycle status of a compiled saga instance (`ADR-0334`).
13#[derive(Clone, Copy, Debug, Eq, PartialEq)]
14pub enum ClientSagaStatus {
15    /// Forward execution is in progress or ready to advance.
16    RunningForward,
17    /// Reverse compensation is in progress in strict LIFO order.
18    Compensating,
19    /// Forward execution reached a terminal success branch.
20    Completed,
21    /// Forward execution aborted before any effectful step committed.
22    AbortedClean,
23    /// Forward execution explicitly transitioned to `abort_uncompensated`.
24    AbortedUncompensated,
25    /// All prior effectful forward steps have been compensated in reverse order.
26    Compensated,
27    /// Step execution encountered transient contention and is waiting for backoff or manual resume.
28    BlockedRetryable,
29    /// Step execution failed live capability/policy authorization and requires `resume_saga`.
30    BlockedAuthority,
31    /// A compensating command returned a non-success outcome and requires operator intervention.
32    CompensationFailed,
33}
34
35impl ClientSagaStatus {
36    /// Parses a canonical status string returned by the service.
37    #[must_use]
38    pub fn parse(value: &str) -> Option<Self> {
39        match value {
40            "running_forward" => Some(Self::RunningForward),
41            "compensating" => Some(Self::Compensating),
42            "completed" => Some(Self::Completed),
43            "aborted_clean" => Some(Self::AbortedClean),
44            "aborted_uncompensated" => Some(Self::AbortedUncompensated),
45            "compensated" => Some(Self::Compensated),
46            "blocked_retryable" => Some(Self::BlockedRetryable),
47            "blocked_authority" => Some(Self::BlockedAuthority),
48            "compensation_failed" => Some(Self::CompensationFailed),
49            _ => None,
50        }
51    }
52
53    /// Stable wire string representation.
54    #[must_use]
55    pub const fn as_str(self) -> &'static str {
56        match self {
57            Self::RunningForward => "running_forward",
58            Self::Compensating => "compensating",
59            Self::Completed => "completed",
60            Self::AbortedClean => "aborted_clean",
61            Self::AbortedUncompensated => "aborted_uncompensated",
62            Self::Compensated => "compensated",
63            Self::BlockedRetryable => "blocked_retryable",
64            Self::BlockedAuthority => "blocked_authority",
65            Self::CompensationFailed => "compensation_failed",
66        }
67    }
68
69    /// Whether this status is an immutable terminal state.
70    #[must_use]
71    pub const fn is_terminal(self) -> bool {
72        matches!(
73            self,
74            Self::Completed | Self::AbortedClean | Self::AbortedUncompensated | Self::Compensated
75        )
76    }
77
78    /// Whether this status is paused in a blocked or failed state.
79    #[must_use]
80    pub const fn is_blocked(self) -> bool {
81        matches!(
82            self,
83            Self::BlockedRetryable | Self::BlockedAuthority | Self::CompensationFailed
84        )
85    }
86}
87
88/// Admission or observation disposition of a saga operation.
89#[derive(Clone, Copy, Debug, Eq, PartialEq)]
90pub enum ClientSagaDisposition {
91    /// A new saga instance was durably admitted.
92    Admitted,
93    /// An existing saga instance matched the caller's idempotency key and input.
94    Replayed,
95    /// An existing saga instance was read, awaited, cancelled, or resumed.
96    Observed,
97    /// No visible saga instance exists for the requested ID.
98    NotFound,
99}
100
101impl ClientSagaDisposition {
102    /// Parses a canonical disposition string.
103    #[must_use]
104    pub fn parse(value: &str) -> Option<Self> {
105        match value {
106            "admitted" => Some(Self::Admitted),
107            "replayed" => Some(Self::Replayed),
108            "observed" => Some(Self::Observed),
109            "not_found" => Some(Self::NotFound),
110            _ => None,
111        }
112    }
113
114    /// Stable wire string representation.
115    #[must_use]
116    pub const fn as_str(self) -> &'static str {
117        match self {
118            Self::Admitted => "admitted",
119            Self::Replayed => "replayed",
120            Self::Observed => "observed",
121            Self::NotFound => "not_found",
122        }
123    }
124}
125
126/// One committed forward or compensating step in a saga's durable step ledger.
127#[derive(Clone, Debug, Eq, PartialEq)]
128pub struct ClientCommittedSagaStep {
129    /// Zero-based topological step index.
130    pub step_index: u16,
131    /// Declared step symbol.
132    pub step_name: String,
133    /// `"forward"` or `"compensate"`.
134    pub direction: String,
135    /// Compiled command name executed by the step.
136    pub command_name: String,
137    /// Numeric outcome variant ID.
138    pub outcome_id: u32,
139    /// Declared outcome variant name.
140    pub outcome_name: String,
141    /// `"effectful"` or `"no_op"`.
142    pub effect_disposition: String,
143    /// Deterministic UUIDv5 step idempotency key.
144    pub step_idempotency_key: String,
145}
146
147/// Public client view of one durable saga instance (`ADR-0334`).
148#[derive(Clone, Debug, Eq, PartialEq)]
149pub struct ClientSagaInstanceView {
150    /// Durable UUIDv7 saga identifier.
151    pub saga_id: String,
152    /// Compiled saga symbol.
153    pub saga_name: String,
154    /// Declared execution role.
155    pub execution_role: String,
156    /// Current durable lifecycle status.
157    pub status: ClientSagaStatus,
158    /// Admission or observation disposition.
159    pub disposition: ClientSagaDisposition,
160    /// Monotonic saga state revision.
161    pub revision: u64,
162    /// Monotonic worker fencing token.
163    pub fencing_token: u64,
164    /// Current step index in the compiled saga plan.
165    pub current_step_index: u16,
166    /// Whether explicit cancellation has been requested.
167    pub cancel_requested: bool,
168    /// Current step retry count.
169    pub retry_count: u8,
170    /// Total committed step count in the durable ledger.
171    pub step_count: u64,
172    /// Terminal outcome variant name when completed, aborted, or compensated.
173    pub terminal_outcome_name: Option<String>,
174    /// Diagnostic reason when blocked or failed.
175    pub diagnostic_reason: Option<String>,
176    /// Committed forward and compensating steps in execution order.
177    pub step_ledger: Vec<ClientCommittedSagaStep>,
178    /// Raw JSON array of committed step ledger entries.
179    pub step_ledger_json: String,
180    /// Raw JSON object of terminal outcome fields when present.
181    pub terminal_outcome_json: String,
182}
183
184/// Result of starting or replaying a compiled saga.
185#[derive(Clone, Debug, Eq, PartialEq)]
186pub struct ClientStartSagaResult {
187    /// Whether the saga was newly admitted or replayed.
188    pub disposition: ClientSagaDisposition,
189    /// Current durable saga instance view.
190    pub instance: ClientSagaInstanceView,
191}
192
193/// Decodes a [`ClientSagaInstanceView`] from an [`ApplicationCommandResult`] returned by saga dispatch.
194pub fn decode_saga_command_result(
195    result: &ApplicationCommandResult,
196) -> Result<Option<ClientSagaInstanceView>, ApplicationClientError> {
197    let Some(ApplicationValue::Record(fields)) = result.outcome_value.as_ref() else {
198        return Err(ApplicationClientError::InvalidResponse);
199    };
200    let get_str = |key: &str| match fields.get(key) {
201        Some(ApplicationValue::String(s)) => Ok(s.clone()),
202        _ => Err(ApplicationClientError::InvalidResponse),
203    };
204    let get_opt_str = |key: &str| match fields.get(key) {
205        Some(ApplicationValue::String(s)) => Ok(Some(s.clone())),
206        Some(ApplicationValue::Null) | None => Ok(None),
207        _ => Err(ApplicationClientError::InvalidResponse),
208    };
209    let get_u64 = |key: &str| match fields.get(key) {
210        Some(ApplicationValue::U64(v)) => Ok(*v),
211        Some(ApplicationValue::I64(v)) if *v >= 0 => Ok(*v as u64),
212        _ => Err(ApplicationClientError::InvalidResponse),
213    };
214    let get_bool = |key: &str| match fields.get(key) {
215        Some(ApplicationValue::Bool(v)) => Ok(*v),
216        _ => Err(ApplicationClientError::InvalidResponse),
217    };
218
219    let disposition_str = get_str("disposition")?;
220    let disposition = ClientSagaDisposition::parse(&disposition_str)
221        .ok_or(ApplicationClientError::InvalidResponse)?;
222    let status_str = get_str("status")?;
223    if disposition == ClientSagaDisposition::NotFound || status_str == "not_found" {
224        return Ok(None);
225    }
226    let status =
227        ClientSagaStatus::parse(&status_str).ok_or(ApplicationClientError::InvalidResponse)?;
228    let saga_id = get_str("saga_id")?;
229    let saga_name = get_str("saga_name")?;
230    let execution_role = get_str("execution_role")?;
231    let revision = get_u64("revision")?;
232    let fencing_token = get_u64("fencing_token")?;
233    let current_step_index = u16::try_from(get_u64("current_step_index")?)
234        .map_err(|_| ApplicationClientError::InvalidResponse)?;
235    let cancel_requested = get_bool("cancel_requested")?;
236    let retry_count = u8::try_from(get_u64("retry_count")?)
237        .map_err(|_| ApplicationClientError::InvalidResponse)?;
238    let step_count = get_u64("step_count")?;
239    let terminal_outcome_name = get_opt_str("terminal_outcome_name")?;
240    let diagnostic_reason = get_opt_str("diagnostic_reason")?;
241    let step_ledger_json = get_str("step_ledger_json")?;
242    let terminal_outcome_json = get_str("terminal_outcome_json")?;
243    let step_ledger = parse_step_ledger_json(&step_ledger_json);
244
245    Ok(Some(ClientSagaInstanceView {
246        saga_id,
247        saga_name,
248        execution_role,
249        status,
250        disposition,
251        revision,
252        fencing_token,
253        current_step_index,
254        cancel_requested,
255        retry_count,
256        step_count,
257        terminal_outcome_name,
258        diagnostic_reason,
259        step_ledger,
260        step_ledger_json,
261        terminal_outcome_json,
262    }))
263}
264
265fn parse_step_ledger_json(json_str: &str) -> Vec<ClientCommittedSagaStep> {
266    let trimmed = json_str.trim();
267    if !trimmed.starts_with('[') || !trimmed.ends_with(']') || trimmed.len() <= 2 {
268        return Vec::new();
269    }
270    let inner = &trimmed[1..trimmed.len() - 1];
271    let mut entries = Vec::new();
272    let mut depth = 0_usize;
273    let mut in_quotes = false;
274    let mut escaped = false;
275    let mut obj_start: Option<usize> = None;
276    for (idx, ch) in inner.char_indices() {
277        if in_quotes {
278            if escaped {
279                escaped = false;
280            } else if ch == '\\' {
281                escaped = true;
282            } else if ch == '"' {
283                in_quotes = false;
284            }
285            continue;
286        }
287        match ch {
288            '"' => in_quotes = true,
289            '{' => {
290                if depth == 0 {
291                    obj_start = Some(idx);
292                }
293                depth += 1;
294            }
295            '}' => {
296                depth = depth.saturating_sub(1);
297                if depth == 0
298                    && let Some(start) = obj_start.take()
299                    && let Some(step) = parse_single_step_object(&inner[start..=idx])
300                {
301                    entries.push(step);
302                }
303            }
304            _ => {}
305        }
306    }
307    entries
308}
309
310fn parse_single_step_object(obj_str: &str) -> Option<ClientCommittedSagaStep> {
311    let extract_str = |key: &str| -> Option<String> {
312        let pattern = format!("\"{key}\":\"");
313        let start = obj_str.find(&pattern)? + pattern.len();
314        let rest = &obj_str[start..];
315        let mut out = String::new();
316        let mut escaped = false;
317        for ch in rest.chars() {
318            if escaped {
319                out.push(ch);
320                escaped = false;
321            } else if ch == '\\' {
322                escaped = true;
323            } else if ch == '"' {
324                return Some(out);
325            } else {
326                out.push(ch);
327            }
328        }
329        None
330    };
331    let extract_u64 = |key: &str| -> Option<u64> {
332        let pattern = format!("\"{key}\":");
333        let start = obj_str.find(&pattern)? + pattern.len();
334        let rest = obj_str[start..].trim_start();
335        let digits: String = rest.chars().take_while(char::is_ascii_digit).collect();
336        digits.parse().ok()
337    };
338
339    Some(ClientCommittedSagaStep {
340        step_index: u16::try_from(extract_u64("step_index")?).ok()?,
341        step_name: extract_str("step_name")?,
342        direction: extract_str("direction")?,
343        command_name: extract_str("command_name")?,
344        outcome_id: u32::try_from(extract_u64("outcome_id")?).ok()?,
345        outcome_name: extract_str("outcome_name")?,
346        effect_disposition: extract_str("effect_disposition")?,
347        step_idempotency_key: extract_str("step_idempotency_key")?,
348    })
349}
350
351impl StableApplicationClient {
352    /// Starts or idempotently replays a compiled saga instance (`ADR-0334`).
353    pub async fn start_saga(
354        &mut self,
355        saga_name: &str,
356        saga_id: Option<&str>,
357        mut input: BTreeMap<String, ApplicationValue>,
358        await_window: Option<Duration>,
359        attempts: AttemptBudget,
360        metadata: &CallMetadata,
361    ) -> Result<ClientStartSagaResult, ApplicationClientError> {
362        input.insert(
363            "__saga_op".to_owned(),
364            ApplicationValue::String("start".to_owned()),
365        );
366        if let Some(id) = saga_id {
367            input.insert(
368                "saga_id".to_owned(),
369                ApplicationValue::String(id.to_owned()),
370            );
371        }
372        if let Some(window) = await_window {
373            let millis = u64::try_from(window.as_millis())
374                .map_err(|_| ApplicationClientError::InvalidInput)?;
375            input.insert("__await_millis".to_owned(), ApplicationValue::U64(millis));
376        }
377        let cmd = ApplicationCommand::new(saga_name, None, input)?;
378        let res = self.execute_command(cmd, attempts, metadata).await?;
379        let view =
380            decode_saga_command_result(&res)?.ok_or(ApplicationClientError::InvalidResponse)?;
381        Ok(ClientStartSagaResult {
382            disposition: view.disposition,
383            instance: view,
384        })
385    }
386
387    /// Reads the current durable status and step ledger of a saga instance.
388    pub async fn get_saga(
389        &mut self,
390        saga_name: Option<&str>,
391        saga_id: &str,
392        attempts: AttemptBudget,
393        metadata: &CallMetadata,
394    ) -> Result<Option<ClientSagaInstanceView>, ApplicationClientError> {
395        let mut input = BTreeMap::new();
396        input.insert(
397            "__saga_op".to_owned(),
398            ApplicationValue::String("get".to_owned()),
399        );
400        input.insert(
401            "saga_id".to_owned(),
402            ApplicationValue::String(saga_id.to_owned()),
403        );
404        let cmd_name = saga_name.map_or_else(|| "__saga_get__".to_owned(), str::to_owned);
405        let cmd = ApplicationCommand::new(cmd_name, None, input)?;
406        let res = self.execute_command(cmd, attempts, metadata).await?;
407        decode_saga_command_result(&res)
408    }
409
410    /// Awaits a saga instance for a bounded duration (`<= 30s`).
411    pub async fn await_saga(
412        &mut self,
413        saga_name: Option<&str>,
414        saga_id: &str,
415        max_wait: Duration,
416        attempts: AttemptBudget,
417        metadata: &CallMetadata,
418    ) -> Result<Option<ClientSagaInstanceView>, ApplicationClientError> {
419        let millis = u64::try_from(max_wait.as_millis())
420            .map_err(|_| ApplicationClientError::InvalidInput)?;
421        let mut input = BTreeMap::new();
422        input.insert(
423            "__saga_op".to_owned(),
424            ApplicationValue::String("await".to_owned()),
425        );
426        input.insert(
427            "saga_id".to_owned(),
428            ApplicationValue::String(saga_id.to_owned()),
429        );
430        input.insert("__await_millis".to_owned(), ApplicationValue::U64(millis));
431        let cmd_name = saga_name.map_or_else(|| "__saga_await__".to_owned(), str::to_owned);
432        let cmd = ApplicationCommand::new(cmd_name, None, input)?;
433        let res = self.execute_command(cmd, attempts, metadata).await?;
434        decode_saga_command_result(&res)
435    }
436
437    /// Requests explicit cancellation and reverse LIFO compensation of a saga instance.
438    pub async fn cancel_saga(
439        &mut self,
440        saga_name: Option<&str>,
441        saga_id: &str,
442        attempts: AttemptBudget,
443        metadata: &CallMetadata,
444    ) -> Result<Option<ClientSagaInstanceView>, ApplicationClientError> {
445        let mut input = BTreeMap::new();
446        input.insert(
447            "__saga_op".to_owned(),
448            ApplicationValue::String("cancel".to_owned()),
449        );
450        input.insert(
451            "saga_id".to_owned(),
452            ApplicationValue::String(saga_id.to_owned()),
453        );
454        let cmd_name = saga_name.map_or_else(|| "__saga_cancel__".to_owned(), str::to_owned);
455        let cmd = ApplicationCommand::new(cmd_name, None, input)?;
456        let res = self.execute_command(cmd, attempts, metadata).await?;
457        decode_saga_command_result(&res)
458    }
459
460    /// Resumes a blocked or failed saga instance with fresh capability authority.
461    pub async fn resume_saga(
462        &mut self,
463        saga_name: Option<&str>,
464        saga_id: &str,
465        attempts: AttemptBudget,
466        metadata: &CallMetadata,
467    ) -> Result<Option<ClientSagaInstanceView>, ApplicationClientError> {
468        let mut input = BTreeMap::new();
469        input.insert(
470            "__saga_op".to_owned(),
471            ApplicationValue::String("resume".to_owned()),
472        );
473        input.insert(
474            "saga_id".to_owned(),
475            ApplicationValue::String(saga_id.to_owned()),
476        );
477        let cmd_name = saga_name.map_or_else(|| "__saga_resume__".to_owned(), str::to_owned);
478        let cmd = ApplicationCommand::new(cmd_name, None, input)?;
479        let res = self.execute_command(cmd, attempts, metadata).await?;
480        decode_saga_command_result(&res)
481    }
482}
483
484impl RiffDbClient {
485    /// Starts or idempotently replays a compiled saga instance (`ADR-0334`).
486    pub async fn start_saga(
487        &mut self,
488        saga_name: &str,
489        saga_id: Option<&str>,
490        mut input: BTreeMap<String, ApplicationValue>,
491        await_window: Option<Duration>,
492        attempts: AttemptBudget,
493        metadata: &CallMetadata,
494    ) -> Result<ClientStartSagaResult, ApplicationClientError> {
495        if let Some(id) = saga_id {
496            input.insert(
497                "saga_id".to_owned(),
498                ApplicationValue::String(id.to_owned()),
499            );
500        }
501        if let Some(window) = await_window {
502            let millis = u64::try_from(window.as_millis())
503                .map_err(|_| ApplicationClientError::InvalidInput)?;
504            input.insert("__await_millis".to_owned(), ApplicationValue::U64(millis));
505        }
506        let cmd = ApplicationCommand::new(format!("__saga_start__{saga_name}"), None, input)?;
507        let idempotent = cmd.into_idempotent_command()?;
508        let response = self
509            .execute_with_retry(&idempotent, attempts, metadata)
510            .await
511            .map_err(ApplicationClientError::Client)?;
512        let raised = raise_application_command_result(response)?;
513        let view =
514            decode_saga_command_result(&raised)?.ok_or(ApplicationClientError::InvalidResponse)?;
515        Ok(ClientStartSagaResult {
516            disposition: view.disposition,
517            instance: view,
518        })
519    }
520
521    /// Reads the current durable status and step ledger of a saga instance.
522    pub async fn get_saga(
523        &mut self,
524        saga_id: &str,
525        attempts: AttemptBudget,
526        metadata: &CallMetadata,
527    ) -> Result<Option<ClientSagaInstanceView>, ApplicationClientError> {
528        let mut input = BTreeMap::new();
529        input.insert(
530            "saga_id".to_owned(),
531            ApplicationValue::String(saga_id.to_owned()),
532        );
533        let cmd = ApplicationCommand::new("__saga_get__", None, input)?;
534        let idempotent = cmd.into_idempotent_command()?;
535        let response = self
536            .execute_with_retry(&idempotent, attempts, metadata)
537            .await
538            .map_err(ApplicationClientError::Client)?;
539        let raised = raise_application_command_result(response)?;
540        decode_saga_command_result(&raised)
541    }
542
543    /// Awaits a saga instance for a bounded duration (`<= 30s`).
544    pub async fn await_saga(
545        &mut self,
546        saga_id: &str,
547        max_wait: Duration,
548        attempts: AttemptBudget,
549        metadata: &CallMetadata,
550    ) -> Result<Option<ClientSagaInstanceView>, ApplicationClientError> {
551        let millis = u64::try_from(max_wait.as_millis())
552            .map_err(|_| ApplicationClientError::InvalidInput)?;
553        let mut input = BTreeMap::new();
554        input.insert(
555            "saga_id".to_owned(),
556            ApplicationValue::String(saga_id.to_owned()),
557        );
558        input.insert("__await_millis".to_owned(), ApplicationValue::U64(millis));
559        let cmd = ApplicationCommand::new("__saga_await__", None, input)?;
560        let idempotent = cmd.into_idempotent_command()?;
561        let response = self
562            .execute_with_retry(&idempotent, attempts, metadata)
563            .await
564            .map_err(ApplicationClientError::Client)?;
565        let raised = raise_application_command_result(response)?;
566        decode_saga_command_result(&raised)
567    }
568
569    /// Requests explicit cancellation and reverse LIFO compensation of a saga instance.
570    pub async fn cancel_saga(
571        &mut self,
572        saga_id: &str,
573        attempts: AttemptBudget,
574        metadata: &CallMetadata,
575    ) -> Result<Option<ClientSagaInstanceView>, ApplicationClientError> {
576        let mut input = BTreeMap::new();
577        input.insert(
578            "saga_id".to_owned(),
579            ApplicationValue::String(saga_id.to_owned()),
580        );
581        let cmd = ApplicationCommand::new("__saga_cancel__", None, input)?;
582        let idempotent = cmd.into_idempotent_command()?;
583        let response = self
584            .execute_with_retry(&idempotent, attempts, metadata)
585            .await
586            .map_err(ApplicationClientError::Client)?;
587        let raised = raise_application_command_result(response)?;
588        decode_saga_command_result(&raised)
589    }
590
591    /// Resumes a blocked or failed saga instance with fresh capability authority.
592    pub async fn resume_saga(
593        &mut self,
594        saga_id: &str,
595        attempts: AttemptBudget,
596        metadata: &CallMetadata,
597    ) -> Result<Option<ClientSagaInstanceView>, ApplicationClientError> {
598        let mut input = BTreeMap::new();
599        input.insert(
600            "saga_id".to_owned(),
601            ApplicationValue::String(saga_id.to_owned()),
602        );
603        let cmd = ApplicationCommand::new("__saga_resume__", None, input)?;
604        let idempotent = cmd.into_idempotent_command()?;
605        let response = self
606            .execute_with_retry(&idempotent, attempts, metadata)
607            .await
608            .map_err(ApplicationClientError::Client)?;
609        let raised = raise_application_command_result(response)?;
610        decode_saga_command_result(&raised)
611    }
612}
613
614#[cfg(test)]
615mod tests {
616    use super::*;
617
618    // req: WF-002, WF-005, WF-011, WF-012, WF-013, ID-001, ID-002, TXN-001
619    #[test]
620    fn decode_saga_command_result_parses_completed_and_compensated_views_and_step_ledger() {
621        let mut fields = BTreeMap::new();
622        fields.insert(
623            "saga_id".to_owned(),
624            ApplicationValue::String("018f0000-0000-7000-8000-010203040506".to_owned()),
625        );
626        fields.insert(
627            "saga_name".to_owned(),
628            ApplicationValue::String("CheckoutOrder".to_owned()),
629        );
630        fields.insert(
631            "execution_role".to_owned(),
632            ApplicationValue::String("OrchestratorRole".to_owned()),
633        );
634        fields.insert(
635            "status".to_owned(),
636            ApplicationValue::String("compensated".to_owned()),
637        );
638        fields.insert(
639            "disposition".to_owned(),
640            ApplicationValue::String("admitted".to_owned()),
641        );
642        fields.insert("revision".to_owned(), ApplicationValue::U64(4));
643        fields.insert("fencing_token".to_owned(), ApplicationValue::U64(1));
644        fields.insert("current_step_index".to_owned(), ApplicationValue::U64(1));
645        fields.insert("cancel_requested".to_owned(), ApplicationValue::Bool(false));
646        fields.insert("retry_count".to_owned(), ApplicationValue::U64(0));
647        fields.insert("step_count".to_owned(), ApplicationValue::U64(2));
648        fields.insert(
649            "terminal_outcome_name".to_owned(),
650            ApplicationValue::String("Compensated".to_owned()),
651        );
652        fields.insert("diagnostic_reason".to_owned(), ApplicationValue::Null);
653        fields.insert(
654            "step_ledger_json".to_owned(),
655            ApplicationValue::String(
656                "[{\"step_index\":0,\"step_name\":\"reserve\",\"direction\":\"forward\",\"command_name\":\"ReserveInventory\",\"outcome_id\":1,\"outcome_name\":\"Reserved\",\"effect_disposition\":\"effectful\",\"step_idempotency_key\":\"saga:018f:f:0:ReserveInventory\"},{\"step_index\":0,\"step_name\":\"reserve\",\"direction\":\"compensating\",\"command_name\":\"ReleaseInventory\",\"outcome_id\":2,\"outcome_name\":\"Released\",\"effect_disposition\":\"effectful\",\"step_idempotency_key\":\"saga:018f:c:0:ReleaseInventory\"}]"
657                    .to_owned(),
658            ),
659        );
660        fields.insert(
661            "terminal_outcome_json".to_owned(),
662            ApplicationValue::String("{}".to_owned()),
663        );
664
665        let result = ApplicationCommandResult {
666            outcome: Some("SagaStatus".to_owned()),
667            outcome_value: Some(ApplicationValue::Record(fields)),
668            commit_sequence: None,
669            contract_version: 1,
670            plan_hash: [0u8; 32],
671            replayed: false,
672            outcome_uri: None,
673        };
674        let view = decode_saga_command_result(&result)
675            .expect("decode ok")
676            .expect("some view");
677        assert_eq!(view.saga_name, "CheckoutOrder");
678        assert_eq!(view.status, ClientSagaStatus::Compensated);
679        assert_eq!(view.disposition, ClientSagaDisposition::Admitted);
680        assert!(view.status.is_terminal());
681        assert_eq!(view.revision, 4);
682        assert_eq!(view.step_count, 2);
683        assert_eq!(view.step_ledger.len(), 2);
684        assert_eq!(view.step_ledger[0].direction, "forward");
685        assert_eq!(view.step_ledger[1].direction, "compensating");
686    }
687}