1mod anchor_retry;
9mod apply;
10mod approval;
11pub mod capture;
12pub(crate) mod program;
13pub mod project_registry;
14pub(crate) mod review;
15mod reviewed_build;
16pub mod runtime;
17mod snapshot;
18mod strict_json;
19
20pub use approval::*;
21pub use snapshot::{CapturedInput, GateSnapshot, InputKey};
22
23pub(crate) fn module_base_generation(body: &crate::config_store::StoreBody, module: &str) -> u64 {
25 if !body.stamped {
26 return 0;
27 }
28 body.generations
29 .values()
30 .rev()
31 .find(|entry| entry.tuples.iter().any(|tuple| tuple.module == module))
32 .map_or(0, |entry| entry.generation.id)
33}
34
35use std::collections::{BTreeMap, BTreeSet};
36
37use subc_config::{Changeset, Digest, Generation, Plan};
38use subc_control::config::ConfigPlanView;
39
40use crate::config_store::{CommitKind, ConfigStore, HistoryEntry, StoreError, StoreState, Tuple};
41
42#[derive(Clone, Debug, PartialEq, Eq)]
43pub struct GateError {
44 pub code: String,
45 pub detail: String,
46 capture_race: bool,
47}
48type Result<T> = std::result::Result<T, GateError>;
49
50impl GateError {
51 pub fn new(code: &str, detail: impl ToString) -> Self {
52 Self {
53 code: code.into(),
54 detail: detail.to_string(),
55 capture_race: false,
56 }
57 }
58 fn invalid(detail: impl ToString) -> Self {
59 Self::new("value_invalid", detail)
60 }
61 fn stale() -> Self {
62 Self::new(
63 "plan_stale",
64 "reviewed inputs or generation changed; plan again",
65 )
66 }
67
68 pub(crate) fn capture_race() -> Self {
71 Self {
72 capture_race: true,
73 ..Self::stale()
74 }
75 }
76
77 pub(crate) fn is_capture_race(&self) -> bool {
78 self.capture_race
79 }
80
81 pub(crate) fn commit_timeout() -> Self {
82 Self::new("config_commit_timeout", "the post-answer commit window expired before durable publication; plan remains unapproved")
83 }
84}
85impl std::fmt::Display for GateError {
86 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
87 write!(f, "{}: {}", self.code, self.detail)
88 }
89}
90impl std::error::Error for GateError {}
91impl From<StoreError> for GateError {
92 fn from(error: StoreError) -> Self {
93 use crate::config_store::StoreErrorCode as Code;
94 let code = match error.code {
95 Code::StoreUnverified => "store_unverified",
96 Code::StoreMissing => "store_missing",
97 Code::StoreTampered => "store_tampered",
98 Code::StoreTooLarge => "store_too_large",
99 Code::AnchorPending => "anchor_pending",
100 Code::GenerationPruned => "generation_pruned",
101 Code::GenerationMissing => "generation_missing",
102 Code::RevisionExhausted => "revision_exhausted",
103 Code::InvalidState => "config_gated",
104 Code::Io => "config_store_io",
105 };
106 Self::new(code, error.detail)
107 }
108}
109
110pub trait ReviewAdmission: Send + Sync {
113 fn check(&self, registration: &crate::registry::ModuleRegistration) -> Result<()>;
114}
115
116pub(crate) struct MissingReviewAdmission;
117impl ReviewAdmission for MissingReviewAdmission {
118 fn check(&self, registration: &crate::registry::ModuleRegistration) -> Result<()> {
119 Err(GateError::new(
120 "program_admission_unavailable",
121 format!(
122 "{}: running program review admission is not connected",
123 registration.manifest.module_id
124 ),
125 ))
126 }
127}
128
129pub(crate) enum ReviewRecord<'a> {
132 Absent,
135 Reviewed(&'a BTreeSet<String>),
139 Copied(Option<serde_json::Value>),
142}
143
144#[derive(Clone, Copy, Debug, PartialEq, Eq)]
145pub enum PlanKind {
146 Change,
147 Stamp,
148 Unstamp,
149 Rollback(u64),
150}
151impl PlanKind {
152 fn commit_kind(self) -> CommitKind {
153 match self {
154 Self::Change => CommitKind::Approved,
155 Self::Stamp => CommitKind::Stamp,
156 Self::Unstamp => CommitKind::Unstamp,
157 Self::Rollback(_) => CommitKind::Rollback,
158 }
159 }
160}
161
162struct PendingPlan {
163 creation_sequence: u64,
164 edits: Option<runtime::edits::EditPlan>,
165 development_approval: Option<crate::program_origin::DevelopmentApproval>,
166 view: ConfigPlanView,
167 kind: PlanKind,
168 snapshot: GateSnapshot,
169 modules: BTreeSet<String>,
170 changed: BTreeSet<InputKey>,
171 callosum_entry_changed: bool,
172 recovery: bool,
173 delivery: Option<crate::config_store::DeliverySnapshot>,
174}
175
176pub struct ConfigGate {
179 incarnation: String,
180 plans: BTreeMap<Digest, PendingPlan>,
181 attempts: BTreeMap<u64, approval::Attempt>,
182 next_attempt: u64,
183 next_plan_sequence: u64,
184}
185
186impl ConfigGate {
187 fn pending_file_plan(&self, module: &str) -> Option<Digest> {
188 self.plans
189 .values()
190 .filter(|plan| plan.edits.is_none() && plan.modules.contains(module))
191 .max_by_key(|plan| plan.creation_sequence)
192 .map(|plan| plan.view.digest.clone())
193 }
194
195 pub(crate) fn plan_modules(&self, digest: &Digest) -> Result<BTreeSet<String>> {
196 self.plans
197 .get(digest)
198 .map(|plan| plan.modules.clone())
199 .ok_or_else(|| GateError::new("plan_unknown", "plan is absent or already applied"))
200 }
201
202 pub(crate) fn cancel_attempt(&mut self, attempt: u64) {
203 self.attempts.remove(&attempt);
204 }
205
206 pub(crate) fn expire_plan(&mut self, digest: &Digest) -> bool {
207 self.plans.remove(digest).is_some()
208 }
209 pub fn new(incarnation: String) -> Self {
210 Self {
211 incarnation,
212 plans: BTreeMap::new(),
213 attempts: BTreeMap::new(),
214 next_attempt: 0,
215 next_plan_sequence: 0,
216 }
217 }
218
219 pub fn plan(
222 &mut self,
223 store: &mut ConfigStore,
224 kind: PlanKind,
225 candidate: GateSnapshot,
226 observed: &GateSnapshot,
227 review: impl FnOnce(&GateSnapshot, &GateSnapshot) -> Result<Changeset>,
228 ) -> Result<ConfigPlanView> {
229 self.plan_reviewed(
230 store,
231 kind,
232 candidate,
233 observed,
234 ReviewRecord::Absent,
235 review,
236 )
237 }
238
239 pub(crate) fn plan_reviewed(
244 &mut self,
245 store: &mut ConfigStore,
246 kind: PlanKind,
247 candidate: GateSnapshot,
248 observed: &GateSnapshot,
249 record: ReviewRecord<'_>,
250 review: impl FnOnce(&GateSnapshot, &GateSnapshot) -> Result<Changeset>,
251 ) -> Result<ConfigPlanView> {
252 self.plan_reviewed_inner(store, kind, candidate, observed, record, None, review)
253 }
254
255 #[allow(clippy::too_many_arguments)]
256 fn plan_reviewed_inner(
257 &mut self,
258 store: &mut ConfigStore,
259 kind: PlanKind,
260 candidate: GateSnapshot,
261 observed: &GateSnapshot,
262 record: ReviewRecord<'_>,
263 edits: Option<runtime::edits::EditPlan>,
264 review: impl FnOnce(&GateSnapshot, &GateSnapshot) -> Result<Changeset>,
265 ) -> Result<ConfigPlanView> {
266 let status = store.status();
267 let recovery = matches!(
268 status.state,
269 StoreState::StoreUnverified | StoreState::StoreMissing
270 );
271 if (recovery && !matches!(kind, PlanKind::Stamp | PlanKind::Unstamp))
272 || (status.state == StoreState::Unstamped && kind != PlanKind::Stamp && edits.is_none())
273 {
274 return Err(GateError::new(
275 "config_gated",
276 "stamp is required before planning changes",
277 ));
278 }
279 if self.plans.len() >= 64 {
280 return Err(GateError::new("config_busy", "too many pending plans"));
281 }
282 let mut rollback_programs = Vec::new();
283 if let PlanKind::Rollback(id) = kind {
284 let target = GateSnapshot::from_store(&store.rollback_configuration(id)?)?;
285 if target
286 .inputs
287 .iter()
288 .filter(|(key, _)| !key.is_program())
289 .ne(candidate.inputs.iter().filter(|(key, _)| !key.is_program()))
290 {
291 return Err(GateError::invalid(
292 "rollback must reverse the target configuration",
293 ));
294 }
295 for (key, now) in candidate.inputs.iter().filter(|(key, _)| key.is_program()) {
296 if target.inputs.get(key) != Some(now) {
297 rollback_programs.push(serde_json::json!({
298 "module_id":key.module(),
299 "input":key,
300 "reason":"program changed since that version",
301 "approved_then":target.inputs.get(key),
302 "on_disk_now":now,
303 }));
304 }
305 }
306 }
307 let (base_revision, base_generation, approved, active) =
308 if let Some(edit) = edits.as_ref().filter(|edit| edit.unstamped) {
309 (
310 status.base_revision,
311 0,
312 edit.baseline.clone(),
313 BTreeMap::new(),
314 )
315 } else if recovery {
316 (0, 0, GateSnapshot::default(), BTreeMap::new())
317 } else {
318 store.delivery_ready()?;
319 let body = store.body()?;
320 let active = body
321 .versions
322 .iter()
323 .filter_map(|(tuple, versions)| {
324 versions
325 .active
326 .map(|id| (serde_json::to_string(tuple).expect("tuple"), id))
327 })
328 .collect();
329 (
330 body.base_revision,
331 body.last_generation,
332 GateSnapshot::from_store(&body.approved)?,
333 active,
334 )
335 };
336 let changed: BTreeSet<InputKey> = approved
337 .changed_keys(&candidate)
338 .into_iter()
339 .cloned()
340 .collect();
341 let callosum_entry_changed = if changed.contains(&InputKey::Daemon) {
342 match (
343 approved.inputs.get(&InputKey::Daemon),
344 candidate.inputs.get(&InputKey::Daemon),
345 ) {
346 (
347 Some(CapturedInput {
348 value: subc_config::RecordedValue::Value { value: old },
349 ..
350 }),
351 Some(CapturedInput {
352 value: subc_config::RecordedValue::Value { value: new },
353 ..
354 }),
355 ) => old.pointer("/modules/callosum") != new.pointer("/modules/callosum"),
356 _ => true,
357 }
358 } else {
359 false
360 };
361 let mut modules: BTreeSet<String> = changed
362 .iter()
363 .filter_map(|key| key.module().map(str::to_owned))
364 .collect();
365 let mut changeset = review(&approved, &candidate)?;
366 for difference in &rollback_programs {
367 if let Some(module) = difference["module_id"].as_str() {
368 modules.insert(module.to_owned());
369 changeset
370 .launch_manifests
371 .entry(module.to_owned())
372 .or_insert_with(|| serde_json::json!({}))
373 .as_object_mut()
374 .ok_or_else(|| GateError::invalid("launch manifest must be an object"))?
375 .insert(
376 "program_changed_since_target".into(),
377 serde_json::Value::Bool(true),
378 );
379 }
380 }
381 modules.extend(changeset.fields.iter().map(|field| field.module_id.clone()));
382 modules.extend(changeset.launch_manifests.keys().cloned());
383 if matches!(kind, PlanKind::Stamp | PlanKind::Unstamp) {
384 modules.extend(observed.modules());
385 modules.extend(approved.modules());
386 }
387 let transitions = changeset
394 .apply_plan
395 .as_object_mut()
396 .and_then(|review| review.remove("module_transitions"));
397 if transitions.is_some()
398 && changeset
399 .apply_plan
400 .as_object()
401 .is_some_and(|review| review.is_empty())
402 {
403 changeset.apply_plan = serde_json::Value::Null;
404 }
405 changeset.apply_plan = serde_json::json!({
406 "operation": match kind { PlanKind::Change => "change", PlanKind::Stamp => "stamp", PlanKind::Unstamp => "unstamp", PlanKind::Rollback(_) => "rollback" },
407 "rollback_to": if let PlanKind::Rollback(id) = kind { Some(id) } else { None },
408 "review": changeset.apply_plan,
409 "previous": approved.to_store()?,
410 "snapshot": candidate.to_store()?,
411 });
412 if let Some(transitions) = transitions {
413 if let Some(table) = transitions.as_object() {
414 modules.extend(table.keys().cloned());
415 }
416 changeset.apply_plan["module_transitions"] = transitions;
417 }
418 if matches!(kind, PlanKind::Rollback(_)) {
419 changeset.apply_plan["rollback_programs"] = serde_json::Value::Array(rollback_programs);
420 }
421 let replaces_programs =
422 !recovery && matches!(kind, PlanKind::Change | PlanKind::Rollback(_));
423 if replaces_programs {
424 let body = store.body()?;
430 for module in &modules {
431 if reviewed_build::active(body, module)?
432 .is_some_and(|active| active != reviewed_build::identity(&candidate, module))
433 {
434 changeset
435 .launch_manifests
436 .entry(module.clone())
437 .or_insert_with(|| serde_json::json!({}))
438 .as_object_mut()
439 .ok_or_else(|| GateError::invalid("launch manifest must be an object"))?
440 .insert(
441 "program_changed_since_active".into(),
442 serde_json::Value::Bool(true),
443 );
444 }
445 }
446 }
447 let reviewed = match record {
448 ReviewRecord::Absent | ReviewRecord::Copied(None) => None,
449 ReviewRecord::Copied(Some(copied)) => {
450 changeset.apply_plan[reviewed_build::REVIEWED_PROGRAMS] = copied;
451 None
452 }
453 ReviewRecord::Reviewed(reviewed) => Some(reviewed),
454 };
455 if let Some(reviewed) = reviewed {
456 let mut record = if replaces_programs {
457 reviewed_build::recorded(store.body()?)?
458 } else {
459 BTreeMap::new()
460 };
461 let present = candidate.modules();
462 record.retain(|module, _| present.contains(module));
463 for module in reviewed {
464 let program = if replaces_programs {
469 match reviewed_build::active(store.body()?, module)? {
470 Some(active) => active,
471 None => reviewed_build::identity(&approved, module),
472 }
473 } else {
474 reviewed_build::identity(&candidate, module)
475 };
476 if let Some(previous) = record.get(module).filter(|previous| **previous != program)
477 {
478 changeset.policy_changes.push(serde_json::json!({
479 "module_id": module,
480 "path": "reviewed_program",
481 "old": previous,
482 "new": program,
483 "reason": "approved configuration re-reviewed by the module's newly approved program",
484 }));
485 }
486 record.insert(module.clone(), program);
487 }
488 changeset.apply_plan[reviewed_build::REVIEWED_PROGRAMS] = serde_json::json!(record);
489 }
490 apply::bind_plan(&mut changeset)?;
491 if let Some(edit) = &edits {
492 changeset.apply_plan["edit_plan"] = serde_json::json!({
493 "unstamped": edit.unstamped,
494 "write_back": edit.files.iter().map(runtime::edits::WriteBack::intent).collect::<Vec<_>>(),
495 });
496 if !edit.refusals.is_empty() {
497 changeset.apply_plan["edit_refusals"] = serde_json::json!(edit.refusals);
500 }
501 }
502 let mut plan = Plan::new(
503 base_revision,
504 base_generation,
505 &self.incarnation,
506 observed.read_set(&modules)?,
507 changeset,
508 );
509 plan.active_generations = active;
510 let mut view = ConfigPlanView::new(plan).map_err(GateError::invalid)?;
511 if let Some(edit) = &edits {
512 view.refusals = edit.refusals.clone();
513 }
514 self.next_plan_sequence = self
515 .next_plan_sequence
516 .checked_add(1)
517 .ok_or_else(|| GateError::new("config_busy", "plan creation sequence exhausted"))?;
518 self.plans.insert(
519 view.digest.clone(),
520 PendingPlan {
521 creation_sequence: self.next_plan_sequence,
522 edits,
523 development_approval: None,
524 view: view.clone(),
525 kind,
526 snapshot: candidate,
527 modules,
528 changed,
529 callosum_entry_changed,
530 recovery,
531 delivery: None,
532 },
533 );
534 Ok(view)
535 }
536
537 fn plan_program_keys(&self, digest: &Digest) -> Result<Vec<InputKey>> {
538 let plan = self
539 .plans
540 .get(digest)
541 .ok_or_else(|| GateError::new("plan_unknown", "plan is absent or already applied"))?;
542 Ok(plan
543 .snapshot
544 .inputs
545 .keys()
546 .filter(|key| {
547 key.is_program()
548 && key
549 .module()
550 .is_some_and(|module| plan.modules.contains(module))
551 })
552 .cloned()
553 .collect())
554 }
555
556 pub(crate) fn bind_delivery(
560 &mut self,
561 digest: &Digest,
562 delivery: crate::config_store::DeliverySnapshot,
563 ) -> Result<()> {
564 self.plans
565 .get_mut(digest)
566 .ok_or_else(|| GateError::new("plan_unknown", "plan is absent or already applied"))?
567 .delivery = Some(delivery);
568 Ok(())
569 }
570
571 pub fn rollback(
577 &mut self,
578 store: &mut ConfigStore,
579 generation: u64,
580 observed: &GateSnapshot,
581 current_programs: &GateSnapshot,
582 review: impl FnOnce(&GateSnapshot, &GateSnapshot) -> Result<Changeset>,
583 ) -> Result<ConfigPlanView> {
584 let mut target = GateSnapshot::from_store(&store.rollback_configuration(generation)?)?;
585 target.restore_programs_from(current_programs)?;
586 let copied = store
587 .body()?
588 .generations
589 .get(&generation)
590 .and_then(|entry| {
591 entry
592 .generation
593 .changeset
594 .apply_plan
595 .get(reviewed_build::REVIEWED_PROGRAMS)
596 })
597 .cloned();
598 self.plan_reviewed(
599 store,
600 PlanKind::Rollback(generation),
601 target,
602 observed,
603 ReviewRecord::Copied(copied),
604 review,
605 )
606 }
607
608 fn fresh(plan: &PendingPlan, store: &mut ConfigStore, current: &GateSnapshot) -> Result<()> {
609 let status = store.status();
610 let recovery = matches!(
611 status.state,
612 StoreState::StoreUnverified | StoreState::StoreMissing
613 );
614 if recovery != plan.recovery {
615 return Err(GateError::stale());
616 }
617 let base = if recovery {
618 0
619 } else {
620 store.delivery_ready()?;
621 store.body()?.base_revision
622 };
623 plan.view
624 .plan
625 .check_fresh(base, ¤t.read_set(&plan.modules)?)
626 .map_err(|_| GateError::stale())
627 }
628
629 #[allow(clippy::too_many_arguments)]
630 fn commit(
631 &mut self,
632 digest: &Digest,
633 approval_channel: subc_config::ApprovalChannel,
634 store: &mut ConfigStore,
635 current: &GateSnapshot,
636 now_ms: u64,
637 before_publication: impl FnOnce() -> Result<()>,
638 ) -> Result<u64> {
639 let plan = self
640 .plans
641 .get(digest)
642 .ok_or_else(|| GateError::new("plan_unknown", "plan is absent or already applied"))?;
643 Self::fresh(plan, store, current)?;
644 let mut generation = Generation::new(
645 0,
646 approval_channel,
647 digest.clone(),
648 plan.view.plan.input_vector.clone(),
649 plan.view.plan.changeset.clone(),
650 );
651 let declarations_only = plan.development_approval.is_some();
652 generation.active_generations = plan.view.plan.active_generations.clone();
653 for module in plan.modules.iter().filter(|_| !declarations_only) {
654 generation
655 .module_states
656 .insert(module.clone(), subc_config::GenerationState::Pending);
657 if let Some(CapturedInput {
658 state: subc_config::InputState::Present { digest },
659 ..
660 }) = plan
661 .snapshot
662 .inputs
663 .get(&InputKey::Declaration(module.clone()))
664 {
665 generation
666 .declaration_digests
667 .insert(module.clone(), digest.clone());
668 }
669 }
670 let mut tuples: BTreeSet<Tuple> = plan
671 .modules
672 .iter()
673 .map(|module| Tuple {
674 module: module.clone(),
675 project: None,
676 })
677 .chain(plan.view.plan.changeset.fields.iter().map(|field| Tuple {
678 module: field.module_id.clone(),
679 project: field.project_id.clone(),
680 }))
681 .chain(plan.modules.iter().flat_map(|module| {
682 plan.view
683 .plan
684 .changeset
685 .affected_projects
686 .iter()
687 .map(move |project| Tuple {
688 module: module.clone(),
689 project: Some(project.clone()),
690 })
691 }))
692 .collect();
693 if declarations_only {
694 tuples.clear();
695 }
696 let snapshot = plan.snapshot.to_store()?;
697 let entry = HistoryEntry {
698 generation,
699 kind: if declarations_only {
700 CommitKind::DeclarationApproval
701 } else {
702 plan.kind.commit_kind()
703 },
704 approval_id: digest.to_string(),
705 outcome: "approved".into(),
706 tuples,
707 configuration: snapshot.clone(),
708 delivery: plan.delivery.clone(),
709 };
710 let base_before = store.status().base_revision;
711 let observed = current.to_store()?;
712 before_publication()?;
713 let result = if plan.recovery {
714 store.recovery_exit(entry, snapshot, now_ms)
715 } else {
716 store.commit_generation(entry, snapshot, observed, now_ms)
717 };
718 if result.is_ok() || store.status().base_revision != base_before {
722 self.plans.remove(digest);
723 }
724 let id = result?;
725 store.delivery_ready()?;
726 Ok(id)
727 }
728}
729
730mod registration;
731#[cfg(test)]
732mod tests;