Skip to main content

kernel/graph/capture/
replay_outcome.rs

1// Copyright 2026 Mark Alan Boykin
2// This Source Code Form is subject to the terms of the Mozilla Public
3// License, v. 2.0. If a copy of the MPL was not distributed with this
4// file, You can obtain one at https://mozilla.org/MPL/2.0/.
5// SPDX-License-Identifier: MPL-2.0
6
7//! What a captured record replays as. [`CapturedDelta::replay`](super::CapturedDelta::replay)
8//! decides once; replay loops and writers only act on the answer.
9
10use super::{
11    GraphDelta, GraphDeltaResult, OnRefusal, ReplayRefused, apply_graph_delta, replay_quietly,
12};
13use crate::graph::Graph;
14use crate::graph::resource_content::ContentError;
15
16/// A captured record, turned into what a replay does with it.
17#[derive(Debug, Clone)]
18pub enum Replay {
19    /// A delta to apply.
20    Apply(GraphDelta),
21    /// Obsolete by design (pre-phase-2 inline imagery): never a refusal.
22    Skip,
23    /// Corrupt: checked replay stops here, tolerant replay drops it.
24    Malformed(Malformed),
25}
26
27/// A captured facet record whose value is not valid JSON.
28#[derive(Debug, Clone, PartialEq, Eq)]
29pub struct Malformed {
30    pub node_id: String,
31    pub facet: String,
32    pub error: String,
33}
34
35impl Malformed {
36    pub(super) fn new(node_id: &str, facet: &str, error: serde_json::Error) -> Self {
37        Self {
38            node_id: node_id.into(),
39            facet: facet.into(),
40            error: error.to_string(),
41        }
42    }
43
44    /// The refusal a checked replay reports for this record at `position`.
45    pub(crate) fn refused_at(self, position: usize) -> ReplayRefused {
46        ReplayRefused {
47            position,
48            reason: ContentError::InvalidFacet(self.to_string()),
49        }
50    }
51}
52
53impl std::fmt::Display for Malformed {
54    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
55        write!(
56            f,
57            "facet {} of node {} is not valid JSON: {}",
58            self.facet, self.node_id, self.error
59        )
60    }
61}
62
63/// Why a live write cannot carry out a captured record. Replay may skip or
64/// drop one; a write refuses it.
65#[derive(Debug, Clone, PartialEq, Eq)]
66pub enum Unwritable {
67    Skipped,
68    Malformed(Malformed),
69}
70
71impl std::fmt::Display for Unwritable {
72    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
73        match self {
74            Self::Skipped => f.write_str("obsolete record with no live form"),
75            Self::Malformed(malformed) => malformed.fmt(f),
76        }
77    }
78}
79
80impl std::error::Error for Unwritable {}
81
82impl Replay {
83    /// The delta a live write carries out; a skipped or malformed record is refused.
84    pub fn into_write(self) -> Result<GraphDelta, Unwritable> {
85        match self {
86            Self::Apply(delta) => Ok(delta),
87            Self::Skip => Err(Unwritable::Skipped),
88            Self::Malformed(malformed) => Err(Unwritable::Malformed(malformed)),
89        }
90    }
91}
92
93/// Replay a stream of outcomes quietly. `position` counts every outcome,
94/// skipped ones included. Under [`OnRefusal::Stop`] a malformed record or a
95/// refused delta ends the replay; under `Drop` either is passed over. A skip
96/// is passed over under both.
97pub(crate) fn replay_outcomes_onto<I>(
98    graph: &mut Graph,
99    outcomes: I,
100    on_refusal: OnRefusal,
101) -> Result<(), ReplayRefused>
102where
103    I: IntoIterator<Item = Replay>,
104{
105    replay_quietly(graph, |graph| {
106        for (position, outcome) in outcomes.into_iter().enumerate() {
107            let delta = match outcome {
108                Replay::Apply(delta) => delta,
109                Replay::Skip => continue,
110                Replay::Malformed(bad) if on_refusal == OnRefusal::Stop => {
111                    return Err(bad.refused_at(position));
112                },
113                Replay::Malformed(_) => continue,
114            };
115            if let GraphDeltaResult::Refused(reason) = apply_graph_delta(graph, delta)
116                && on_refusal == OnRefusal::Stop
117            {
118                return Err(ReplayRefused { position, reason });
119            }
120        }
121        Ok(())
122    })
123}