subc_daemon/config_gate/
snapshot.rs1use 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#[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 ProjectTuple {
23 module: String,
24 project: String,
25 },
26 ProjectFile {
28 module: String,
29 path: String,
30 },
31 Declaration(String),
32 Program {
33 module: String,
34 path: String,
35 },
36}
37
38impl InputKey {
39 pub fn module(&self) -> Option<&str> {
40 match self {
41 Self::Daemon => None,
42 Self::Entry(module) | Self::Declaration(module) => Some(module),
43 Self::Layer { module, .. }
44 | Self::ProjectTuple { module, .. }
45 | Self::ProjectFile { module, .. }
46 | Self::Program { module, .. } => Some(module),
47 }
48 }
49 pub(super) fn is_program(&self) -> bool {
50 matches!(self, Self::Program { .. })
51 }
52
53 pub(super) fn is_project(&self) -> bool {
54 matches!(self, Self::ProjectTuple { .. } | Self::ProjectFile { .. })
55 }
56}
57
58#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
64pub struct CapturedInput {
65 pub state: InputState,
66 pub value: RecordedValue,
67}
68
69#[derive(Clone, Debug, Default, PartialEq)]
70pub struct GateSnapshot {
71 pub inputs: BTreeMap<InputKey, CapturedInput>,
72}
73
74impl GateSnapshot {
75 pub fn to_store(&self) -> Result<Snapshot> {
76 self.inputs
77 .iter()
78 .map(|(key, input)| {
79 Ok((
80 serde_json::to_string(key).map_err(GateError::invalid)?,
81 RecordedValue::new(serde_json::to_value(input).map_err(GateError::invalid)?),
82 ))
83 })
84 .collect()
85 }
86
87 pub fn from_store(snapshot: &Snapshot) -> Result<Self> {
88 let inputs = snapshot
89 .iter()
90 .map(|(key, value)| {
91 let RecordedValue::Value { value } = value else {
92 return Err(GateError::invalid("invalid gate snapshot envelope"));
93 };
94 Ok((
95 serde_json::from_str(key).map_err(GateError::invalid)?,
96 serde_json::from_value(value.clone()).map_err(GateError::invalid)?,
97 ))
98 })
99 .collect::<Result<_>>()?;
100 Ok(Self { inputs })
101 }
102
103 pub(super) fn modules(&self) -> BTreeSet<String> {
104 self.inputs
105 .keys()
106 .filter_map(|key| key.module().map(str::to_owned))
107 .collect()
108 }
109
110 pub(super) fn changed_keys<'a>(&'a self, other: &'a Self) -> BTreeSet<&'a InputKey> {
111 self.inputs
112 .keys()
113 .chain(other.inputs.keys())
114 .filter(|key| self.inputs.get(key) != other.inputs.get(key))
115 .collect()
116 }
117
118 pub(super) fn carry_project_inputs(&mut self, previous: &Self) {
119 for (key, input) in &previous.inputs {
120 if key.is_project() {
121 self.inputs
122 .entry(key.clone())
123 .or_insert_with(|| input.clone());
124 }
125 }
126 }
127
128 pub fn read_set(&self, modules: &BTreeSet<String>) -> Result<InputVector> {
132 let daemon = self
133 .inputs
134 .get(&InputKey::Daemon)
135 .ok_or_else(|| GateError::invalid("snapshot has no subc.jsonc input"))?;
136 let mut inputs = BTreeMap::from([("subc.jsonc".into(), daemon.state.clone())]);
137 for module in modules {
138 let inventory: BTreeMap<_, _> = self
139 .inputs
140 .iter()
141 .filter(|(key, _)| key.module() == Some(module))
142 .map(|(key, value)| (serde_json::to_string(key).expect("input key"), value))
143 .collect();
144 inputs.insert(
145 format!(
146 "module:{}",
147 serde_json::to_string(module).expect("module id")
148 ),
149 InputState::Present {
150 digest: subc_config::raw_digest(
151 &serde_json::to_vec(&inventory).map_err(GateError::invalid)?,
152 ),
153 },
154 );
155 }
156 for (key, value) in &self.inputs {
157 if let InputKey::ProjectTuple { module, project } = key {
158 if modules.contains(module) {
159 let key = super::targets::project_input_key(module, project);
160 inputs.insert(
161 key,
162 InputState::Present {
163 digest: subc_config::raw_digest(
164 &serde_json::to_vec(value).map_err(GateError::invalid)?,
165 ),
166 },
167 );
168 }
169 }
170 }
171 Ok(InputVector::new(inputs))
172 }
173
174 pub(super) fn restore_programs_from(&mut self, current: &Self) -> Result<()> {
175 for (key, identity) in self.inputs.iter_mut().filter(|(key, _)| key.is_program()) {
176 *identity = current.inputs.get(key).cloned().ok_or_else(|| {
177 GateError::new(
178 "program_missing",
179 "restored program path has no current captured identity",
180 )
181 })?;
182 }
183 Ok(())
184 }
185}