Skip to main content

subc_daemon/config_gate/
snapshot.rs

1use std::collections::{BTreeMap, BTreeSet};
2
3use serde::{Deserialize, Serialize};
4use subc_config::{InputState, InputVector, RecordedValue};
5
6use super::{GateError, Result};
7use crate::config_store::Snapshot;
8
9/// Semantic roles are supplied by the daemon's file capturer, never by a client.
10/// Each module entry is also retained separately from the whole daemon document
11/// so launch-policy changes participate in that module's read set.
12#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
13pub enum InputKey {
14    Daemon,
15    Entry(String),
16    Layer {
17        module: String,
18        path: String,
19    },
20    /// A project's read witness, including absent locations. The capturer binds
21    /// the workspace/project locations, identities and byte digests (no raw bytes).
22    ProjectTuple {
23        module: String,
24        project: String,
25    },
26    Declaration(String),
27    Program {
28        module: String,
29        path: String,
30    },
31}
32
33impl InputKey {
34    pub fn module(&self) -> Option<&str> {
35        match self {
36            Self::Daemon => None,
37            Self::Entry(module) | Self::Declaration(module) => Some(module),
38            Self::Layer { module, .. }
39            | Self::ProjectTuple { module, .. }
40            | Self::Program { module, .. } => Some(module),
41        }
42    }
43    pub(super) fn is_program(&self) -> bool {
44        matches!(self, Self::Program { .. })
45    }
46}
47
48/// `state` binds raw bytes AND retained file identity, including an absent-file
49/// marker. `value` is the parsed, secret-redacted view used in plans and history.
50/// This diagnostic capture never contains a credential or vault reference in
51/// plaintext. Separate approved delivery bytes may contain reference strings;
52/// literal secret values are refused before a plan or generation is retained.
53#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
54pub struct CapturedInput {
55    pub state: InputState,
56    pub value: RecordedValue,
57}
58
59#[derive(Clone, Debug, Default, PartialEq)]
60pub struct GateSnapshot {
61    pub inputs: BTreeMap<InputKey, CapturedInput>,
62}
63
64impl GateSnapshot {
65    pub fn to_store(&self) -> Result<Snapshot> {
66        self.inputs
67            .iter()
68            .map(|(key, input)| {
69                Ok((
70                    serde_json::to_string(key).map_err(GateError::invalid)?,
71                    RecordedValue::new(serde_json::to_value(input).map_err(GateError::invalid)?),
72                ))
73            })
74            .collect()
75    }
76
77    pub fn from_store(snapshot: &Snapshot) -> Result<Self> {
78        let inputs = snapshot
79            .iter()
80            .map(|(key, value)| {
81                let RecordedValue::Value { value } = value else {
82                    return Err(GateError::invalid("invalid gate snapshot envelope"));
83                };
84                Ok((
85                    serde_json::from_str(key).map_err(GateError::invalid)?,
86                    serde_json::from_value(value.clone()).map_err(GateError::invalid)?,
87                ))
88            })
89            .collect::<Result<_>>()?;
90        Ok(Self { inputs })
91    }
92
93    pub(super) fn modules(&self) -> BTreeSet<String> {
94        self.inputs
95            .keys()
96            .filter_map(|key| key.module().map(str::to_owned))
97            .collect()
98    }
99
100    pub(super) fn changed_keys<'a>(&'a self, other: &'a Self) -> BTreeSet<&'a InputKey> {
101        self.inputs
102            .keys()
103            .chain(other.inputs.keys())
104            .filter(|key| self.inputs.get(key) != other.inputs.get(key))
105            .collect()
106    }
107
108    /// Aggregate the whole module inventory, not just paths that changed. This
109    /// detects newly seen project layers and replaced covered files as well as
110    /// edits to an unchanged project layer used by a bound check.
111    pub fn read_set(&self, modules: &BTreeSet<String>) -> Result<InputVector> {
112        let daemon = self
113            .inputs
114            .get(&InputKey::Daemon)
115            .ok_or_else(|| GateError::invalid("snapshot has no subc.jsonc input"))?;
116        let mut inputs = BTreeMap::from([("subc.jsonc".into(), daemon.state.clone())]);
117        for module in modules {
118            let inventory: BTreeMap<_, _> = self
119                .inputs
120                .iter()
121                .filter(|(key, _)| key.module() == Some(module))
122                .map(|(key, value)| (serde_json::to_string(key).expect("input key"), value))
123                .collect();
124            inputs.insert(
125                format!(
126                    "module:{}",
127                    serde_json::to_string(module).expect("module id")
128                ),
129                InputState::Present {
130                    digest: subc_config::raw_digest(
131                        &serde_json::to_vec(&inventory).map_err(GateError::invalid)?,
132                    ),
133                },
134            );
135        }
136        for (key, value) in &self.inputs {
137            if let InputKey::ProjectTuple { module, project } = key {
138                if modules.contains(module) {
139                    let key = super::targets::project_input_key(module, project);
140                    inputs.insert(
141                        key,
142                        InputState::Present {
143                            digest: subc_config::raw_digest(
144                                &serde_json::to_vec(value).map_err(GateError::invalid)?,
145                            ),
146                        },
147                    );
148                }
149            }
150        }
151        Ok(InputVector::new(inputs))
152    }
153
154    pub(super) fn restore_programs_from(&mut self, current: &Self) -> Result<()> {
155        for (key, identity) in self.inputs.iter_mut().filter(|(key, _)| key.is_program()) {
156            *identity = current.inputs.get(key).cloned().ok_or_else(|| {
157                GateError::new(
158                    "program_missing",
159                    "restored program path has no current captured identity",
160                )
161            })?;
162        }
163        Ok(())
164    }
165}