1use std::collections::{BTreeMap, BTreeSet};
2
3use serde::{Deserialize, Serialize};
4use subc_config::{Digest, Generation, GenerationState, RecordedValue};
5use subc_protocol::config::ConfigView;
6
7mod project_files;
8pub use project_files::*;
9
10pub const RECENT_HISTORY_LIMIT: usize = 20;
12pub type Snapshot = BTreeMap<String, RecordedValue>;
13
14#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
15#[serde(rename_all = "snake_case")]
16pub enum IntegrityMode {
17 Sealed,
18 DigestOnly,
19}
20
21#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
22pub struct Tuple {
23 pub module: String,
24 pub project: Option<String>,
25}
26
27#[derive(Clone, Debug, Default, Serialize, Deserialize)]
28pub struct Versions {
29 pub active: Option<u64>,
30 pub recovery: Option<u64>,
31 pub pending: Option<u64>,
32}
33
34#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
35#[serde(rename_all = "snake_case")]
36pub enum CommitKind {
37 Stamp,
38 Unstamp,
39 Approved,
40 Rollback,
41 Development,
42 DeclarationApproval,
43}
44
45type ByProject<T> = BTreeMap<String, BTreeMap<String, T>>;
46
47#[derive(Clone, Debug, Default, Serialize, Deserialize)]
48pub struct DeliverySnapshot {
49 pub daemon: Option<subc_protocol::config::ConfigLayerSnapshot>,
50 pub modules: BTreeMap<String, subc_protocol::config::ConfigView>,
51 pub declarations: BTreeMap<String, subc_protocol::config::ConfigDeclareRequest>,
52 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
53 pub project_views: ByProject<ConfigView>,
54 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
55 pub project_cutoffs: ByProject<ProjectCutoffs>,
56 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
57 pub project_approval_digests: ByProject<Digest>,
58}
59
60#[derive(Clone, Debug, Serialize, Deserialize)]
61pub struct ProjectCutoffs {
62 pub user: ConfigView,
63 pub workspace: ConfigView,
64}
65
66#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
67#[serde(rename_all = "snake_case")]
68pub enum ProjectDeliveryState {
69 Pending,
70 Resumed,
71 Active,
72 Failed,
73}
74
75#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
76pub struct ProjectOutcome {
77 pub state: ProjectDeliveryState,
78 pub never_redeliver: bool,
79}
80
81#[derive(Clone, Debug, Serialize, Deserialize)]
82pub struct HistoryEntry {
83 pub generation: Generation,
84 pub kind: CommitKind,
85 pub approval_id: String,
86 pub outcome: String,
87 pub tuples: BTreeSet<Tuple>,
88 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
89 pub project_outcomes: ByProject<ProjectOutcome>,
90 pub configuration: Snapshot,
92 #[serde(default, skip_serializing_if = "Option::is_none")]
95 pub delivery: Option<DeliverySnapshot>,
96}
97
98impl HistoryEntry {
99 pub(super) fn initialize_project_outcomes(&mut self) {
100 for tuple in &self.tuples {
101 if let Some(project) = &tuple.project {
102 self.project_outcomes
103 .entry(tuple.module.clone())
104 .or_default()
105 .insert(
106 project.clone(),
107 ProjectOutcome {
108 state: ProjectDeliveryState::Pending,
109 never_redeliver: false,
110 },
111 );
112 }
113 }
114 }
115
116 pub fn redelivery_suppressed(&self, tuple: &Tuple) -> bool {
117 match &tuple.project {
118 Some(project) => self
119 .project_outcomes
120 .get(&tuple.module)
121 .and_then(|projects| projects.get(project))
122 .is_some_and(|outcome| outcome.never_redeliver),
123 None => self.generation.never_redeliver.contains(&tuple.module),
124 }
125 }
126
127 pub(super) fn record_tuple_delivery(&mut self, tuple: &Tuple, ack: bool, anchoring: bool) {
128 if let Some(project) = &tuple.project {
129 self.set_project_outcome(
130 &tuple.module,
131 project,
132 if ack {
133 ProjectDeliveryState::Active
134 } else {
135 ProjectDeliveryState::Failed
136 },
137 );
138 return;
139 }
140 self.generation.module_states.insert(
141 tuple.module.clone(),
142 if ack {
143 GenerationState::Active
144 } else {
145 GenerationState::Failed
146 },
147 );
148 if !ack && !self.redelivery_suppressed(tuple) {
149 self.generation.never_redeliver.push(tuple.module.clone());
150 }
151 if !anchoring
154 || !self
155 .generation
156 .module_states
157 .values()
158 .any(|state| *state == GenerationState::Failed)
159 {
160 self.outcome = if ack { "active" } else { "failed" }.into();
161 }
162 }
163
164 pub(super) fn resume_tuple_delivery(&mut self, tuple: &Tuple) {
165 if let Some(project) = &tuple.project {
166 self.set_project_outcome(&tuple.module, project, ProjectDeliveryState::Resumed);
167 } else {
168 self.outcome = "resumed".into();
169 }
170 }
171
172 fn set_project_outcome(&mut self, module: &str, project: &str, state: ProjectDeliveryState) {
173 self.project_outcomes
174 .entry(module.into())
175 .or_default()
176 .insert(
177 project.into(),
178 ProjectOutcome {
179 state,
180 never_redeliver: state == ProjectDeliveryState::Failed,
181 },
182 );
183 }
184}
185
186#[derive(Clone, Debug, Serialize, Deserialize)]
187pub struct PrunedGeneration {
188 pub generation: u64,
189 pub approval_channel: subc_config::ApprovalChannel,
190 pub plan_digest: Digest,
191 pub approval_id: String,
192 pub outcome: String,
193 pub pruned_at_ms: u64,
194}
195
196#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
197pub struct Proposal {
198 pub base_revision: u64,
199 pub snapshot_digest: Digest,
200 pub diff: BTreeMap<String, Option<RecordedValue>>,
201}
202
203#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
205pub struct ProgramRefusal {
206 pub module: String,
207 pub approved_base: Digest,
208 pub refused_identity: Digest,
209}
210
211pub const PROGRAM_REFUSAL_LIMIT: usize = 256;
212
213pub const DAEMON_MODULE: &str = "subc";
216
217#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
220pub struct RestartIntent {
221 pub generation: u64,
222 pub attempted: bool,
225}
226
227#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
230pub struct DaemonPointers {
231 pub active: u64,
236 pub awaiting_restart: Option<u64>,
240 pub restart: Option<RestartIntent>,
241}
242
243#[derive(Clone, Debug, Default, Serialize, Deserialize)]
246pub struct StoreBody {
247 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
249 pub approved_declarations: BTreeMap<String, BTreeMap<String, String>>,
250 #[serde(default, skip_serializing_if = "Vec::is_empty")]
251 pub program_refusals: Vec<ProgramRefusal>,
252 pub stamped: bool,
253 pub base_revision: u64,
254 pub last_generation: u64,
255 pub approved: Snapshot,
256 pub generations: BTreeMap<u64, HistoryEntry>,
257 pub versions: Vec<(Tuple, Versions)>,
258 pub pruned: BTreeMap<u64, PrunedGeneration>,
259 pub proposal: Option<Proposal>,
260 pub observed: Option<Snapshot>,
262 pub daemon: DaemonPointers,
263 #[serde(default, skip_serializing_if = "Option::is_none")]
264 pub registry_membership: Option<RegistryMembership>,
265 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
266 pub project_write_back: BTreeMap<std::path::PathBuf, ProjectWriteBackIntent>,
267}
268
269fn requires_daemon_restart(base: Option<&HistoryEntry>, entry: &HistoryEntry) -> bool {
273 if entry.generation.changeset.fields.iter().any(|field| {
274 field.project_id.is_none() && field.apply == subc_config::ApplyKind::DaemonRestart
275 }) {
276 return true;
277 }
278 if entry
279 .delivery
280 .as_ref()
281 .is_none_or(|delivery| delivery.daemon.is_none())
282 {
283 return false;
285 }
286 let (Some(base), Some(next)) = (base.and_then(daemon_config), daemon_config(entry)) else {
287 return true;
289 };
290 base.port != next.port
291 || base.storage != next.storage
292 || base.admission_facts_carrier_module_id != next.admission_facts_carrier_module_id
293 || base.admission_facts_targets != next.admission_facts_targets
294 || base.scope_authority_owners != next.scope_authority_owners
295 || base.privileged_operator_prompt != next.privileged_operator_prompt
296}
297
298fn daemon_config(entry: &HistoryEntry) -> Option<crate::daemon_config::DaemonConfig> {
299 let layer = entry.delivery.as_ref()?.daemon.as_ref()?;
300 let doc = std::str::from_utf8(layer.bytes.as_deref()?).ok()?;
301 let path = std::path::Path::new(layer.path.as_deref()?);
302 crate::daemon_config::parse_with_activity(doc, path)
303 .ok()
304 .map(|(config, _)| config)
305}
306
307pub(crate) fn generation_failed(entry: &HistoryEntry) -> bool {
309 entry.outcome == "failed"
310 || !entry.generation.never_redeliver.is_empty()
311 || entry
312 .generation
313 .module_states
314 .values()
315 .any(|state| *state == subc_config::GenerationState::Failed)
316}
317
318fn bootable(entry: &HistoryEntry) -> bool {
319 !matches!(entry.kind, CommitKind::Development | CommitKind::Unstamp)
320 && !entry.generation.development
321 && entry
322 .delivery
323 .as_ref()
324 .is_some_and(|delivery| delivery.daemon.is_some())
325 && !generation_failed(entry)
326}
327
328impl StoreBody {
329 pub(super) fn awaits_restart(&self, entry: &HistoryEntry) -> bool {
332 let base = self
333 .active_daemon_generation()
334 .and_then(|id| self.generations.get(&id));
335 self.daemon.awaiting_restart.is_none() && requires_daemon_restart(base, entry)
336 }
337
338 pub(super) fn first_awaiting_restart_after(&self, active: u64) -> Option<u64> {
341 let base = self.generations.get(&active);
342 self.generations
343 .range(active.saturating_add(1)..)
344 .find(|(_, entry)| {
345 !matches!(entry.kind, CommitKind::Development | CommitKind::Unstamp)
346 && !entry.generation.development
347 && requires_daemon_restart(base, entry)
348 })
349 .map(|(&id, _)| id)
350 }
351
352 pub(crate) fn active_daemon_generation(&self) -> Option<u64> {
356 let limit = self.daemon.awaiting_restart.unwrap_or(u64::MAX);
357 self.generations
358 .range(..limit)
359 .rev()
360 .find(|(_, entry)| bootable(entry))
361 .map(|(&id, _)| id)
362 }
363
364 pub(crate) fn restart_candidate(&self) -> Option<u64> {
367 let candidate = self
368 .generations
369 .iter()
370 .rev()
371 .find(|(_, entry)| bootable(entry))
372 .map(|(&id, _)| id)?;
373 (Some(candidate) > self.active_daemon_generation()).then_some(candidate)
374 }
375
376 pub(crate) fn bootable_generation(&self, id: u64) -> bool {
377 self.generations.get(&id).is_some_and(bootable)
378 }
379
380 pub(super) fn protected_generations(&self) -> BTreeSet<u64> {
383 let mut keep = BTreeSet::new();
384 let mut placed_modules = BTreeSet::new();
388 for (&id, entry) in self.generations.iter().rev().take_while(|(_, entry)| {
389 matches!(
390 entry.kind,
391 CommitKind::Development | CommitKind::DeclarationApproval
392 )
393 }) {
394 if entry.kind != CommitKind::Development {
395 continue;
396 }
397 for module in entry.generation.changeset.launch_manifests.keys() {
398 if placed_modules.insert(module) {
399 keep.insert(id);
400 }
401 }
402 }
403 for (_, versions) in &self.versions {
404 keep.extend(
405 [versions.active, versions.recovery, versions.pending]
406 .into_iter()
407 .flatten(),
408 );
409 }
410 keep.extend(
414 [
415 self.daemon.restart.map(|intent| intent.generation),
416 self.active_daemon_generation(),
417 self.daemon.awaiting_restart,
418 ]
419 .into_iter()
420 .flatten()
421 .filter(|id| self.generations.contains_key(id)),
422 );
423 let mut daemon_versions = Vec::new();
424 for (&id, entry) in self.generations.iter().rev() {
425 if daemon_versions.len() == 2 {
426 break;
427 }
428 if matches!(
429 entry.kind,
430 CommitKind::Development | CommitKind::DeclarationApproval
431 ) || entry.generation.development
432 {
433 continue;
434 }
435 let Some(daemon) = entry
436 .delivery
437 .as_ref()
438 .and_then(|delivery| delivery.daemon.as_ref())
439 else {
440 continue;
441 };
442 let Some(input) = entry.generation.input_vector.inputs.get("subc.jsonc") else {
443 keep.insert(id);
446 continue;
447 };
448 let version = (input, &daemon.digest);
449 if !daemon_versions.contains(&version) {
450 daemon_versions.push(version);
451 keep.insert(id);
452 }
453 }
454 keep
455 }
456
457 pub(super) fn prune(&mut self, now_ms: u64) {
460 let protected = self.protected_generations();
461 let mut keep = protected.clone();
462 let tuples: BTreeSet<_> = self
463 .generations
464 .values()
465 .flat_map(|e| e.tuples.iter().cloned())
466 .collect();
467 for tuple in tuples.into_iter().map(Some).chain(std::iter::once(None)) {
468 let mut recent = 0;
469 for (&id, entry) in self.generations.iter().rev() {
470 let belongs = match &tuple {
471 Some(tuple) => entry.tuples.contains(tuple),
472 None => entry.tuples.is_empty(),
473 };
474 if !belongs || protected.contains(&id) {
475 continue;
476 }
477 if recent < RECENT_HISTORY_LIMIT {
478 keep.insert(id);
479 }
480 recent += 1;
481 }
482 }
483 let removed: Vec<_> = self
484 .generations
485 .keys()
486 .copied()
487 .filter(|id| !keep.contains(id))
488 .collect();
489 for id in removed {
490 self.prune_generation(id, now_ms);
491 }
492 }
493
494 pub(super) fn prune_oldest(&mut self, now_ms: u64) -> bool {
495 let protected = self.protected_generations();
496 let Some(id) = self
497 .generations
498 .keys()
499 .copied()
500 .find(|id| !protected.contains(id))
501 else {
502 return false;
503 };
504 self.prune_generation(id, now_ms);
505 true
506 }
507
508 fn prune_generation(&mut self, id: u64, now_ms: u64) {
509 if let Some(entry) = self.generations.remove(&id) {
510 self.pruned.insert(
511 id,
512 PrunedGeneration {
513 generation: id,
514 approval_channel: entry.generation.approval_channel,
515 plan_digest: entry.generation.plan_digest,
516 approval_id: entry.approval_id,
517 outcome: entry.outcome,
518 pruned_at_ms: now_ms,
519 },
520 );
521 }
522 }
523
524 pub(super) fn rebase_proposal(&mut self) -> Result<bool, super::StoreError> {
525 let old_diff = self
526 .proposal
527 .as_ref()
528 .map(|p| &p.diff)
529 .cloned()
530 .unwrap_or_default();
531 let Some(snapshot) = &self.observed else {
532 self.proposal = None;
533 return Ok(!old_diff.is_empty());
534 };
535 let keys: BTreeSet<_> = self.approved.keys().chain(snapshot.keys()).collect();
536 let diff: BTreeMap<_, _> = keys
537 .into_iter()
538 .filter(|key| self.approved.get(*key) != snapshot.get(*key))
539 .map(|key| (key.clone(), snapshot.get(key).cloned()))
540 .collect();
541 let changed = old_diff != diff;
542 self.proposal = if diff.is_empty() {
543 None
544 } else {
545 Some(Proposal {
546 base_revision: self.base_revision,
547 snapshot_digest: subc_config::digest(
548 subc_config::PURPOSE_SNAPSHOT,
549 &serde_json::to_value(snapshot).map_err(super::StoreError::serialization)?,
550 )
551 .map_err(super::StoreError::serialization)?,
552 diff,
553 })
554 };
555 Ok(changed)
556 }
557}