1use std::{
4 collections::{BTreeMap, BTreeSet, HashMap, VecDeque},
5 sync::Mutex,
6 time::{Duration, Instant},
7};
8
9use subc_config::{Changeset, Digest};
10use subc_control::config::ConfigPlanView;
11use subc_protocol::config::{
12 ConfigDeclareRequest, ConfigLayer, ConfigLayerSnapshot, ConfigStatus, ConfigView,
13};
14
15use super::{
16 capture::{CapturedConfiguration, ConfigCapturer},
17 ApprovalChallenge, ApprovalFacts, ApprovalReply, ConfigGate, GateError, PlanKind, Result,
18};
19use crate::{
20 config_store::{ConfigStore, DeliverySnapshot, StoreActivity, StoreState},
21 ConnectionId,
22};
23
24#[path = "edits.rs"]
25pub(super) mod edits;
26
27#[cfg(test)]
28type UserFileTestIdle =
29 tokio::sync::mpsc::UnboundedSender<(ConnectionId, tokio::sync::oneshot::Sender<()>)>;
30
31#[cfg(test)]
32pub(crate) type SettingsProjectionHook = Box<dyn FnMut() -> Result<()> + Send>;
33
34pub struct RuntimeOwner {
35 #[cfg(test)]
36 pub(crate) user_file_test_idle: Mutex<Option<UserFileTestIdle>>,
37 #[cfg(test)]
38 config_park_hook: Mutex<Option<Box<dyn FnOnce() + Send>>>,
39 #[cfg(test)]
40 pub(crate) content_kill_hook: Mutex<Option<Box<dyn FnOnce() + Send>>>,
41 #[cfg(test)]
42 polled_capture_hook: Mutex<Option<Box<dyn FnOnce() + Send>>>,
43 #[cfg(test)]
44 pub(crate) settings_projection_hook: Mutex<Option<SettingsProjectionHook>>,
45 #[cfg(test)]
46 pub(crate) settings_status_hook: Mutex<Option<SettingsProjectionHook>>,
47 #[cfg(test)]
48 pub(crate) settings_observation_hook: Mutex<Option<Box<dyn FnMut() + Send>>>,
49 #[cfg(test)]
50 polled_capture_count: std::sync::atomic::AtomicUsize,
51 #[cfg(test)]
52 census_probe: Mutex<Option<std::sync::Arc<dyn Fn() + Send + Sync>>>,
53 #[cfg(test)]
54 agent_validation_window: Mutex<Option<Duration>>,
55 #[cfg(test)]
56 pub(crate) warm_restart_pause: Mutex<Option<WarmRestartPause>>,
57 #[cfg(test)]
58 pub(crate) warm_restart_busy: Mutex<Option<tokio::sync::oneshot::Sender<()>>>,
59 #[cfg(test)]
60 pub(crate) swap_preflight_attempts: std::sync::atomic::AtomicUsize,
61 #[cfg(feature = "test-support")]
62 test_hooks: Option<crate::config_store::testing::TestSupport>,
63 #[cfg(test)]
64 spawn_exec_hook: Mutex<Option<Box<dyn FnOnce() + Send>>>,
65 published: std::sync::RwLock<std::sync::Arc<Published>>,
66 projection_stale: std::sync::atomic::AtomicBool,
70 #[cfg(test)]
71 projection_builds: std::sync::atomic::AtomicUsize,
72 #[cfg(test)]
73 owner_guards: std::sync::atomic::AtomicUsize,
74 config_workers: Mutex<std::collections::HashSet<ConnectionId>>,
77 configured_modules: std::sync::RwLock<Option<admission::ConfiguredModuleSnapshot>>,
78 inner: Mutex<OwnerState>,
79 capturer: ConfigCapturer,
80 startup_overrides: Vec<String>,
81 module_gates: Mutex<HashMap<String, std::sync::Arc<tokio::sync::Mutex<()>>>>,
82 delivery_changed: std::sync::Arc<tokio::sync::Notify>,
83 settings_changed: tokio::sync::watch::Sender<u64>,
84 route_policy_authority: std::sync::OnceLock<std::sync::Arc<dyn RoutePolicyAuthority>>,
85 mark_publisher: std::sync::OnceLock<std::sync::Arc<dyn mark::MarkPublisher>>,
86 binding_retirements: Mutex<BTreeMap<usize, Box<dyn Fn() + Send + Sync>>>,
87 canceled_approvals: Mutex<Vec<u64>>,
88 approval_request_index: Mutex<HashMap<(ConnectionId, u64), std::sync::Arc<ApprovalRequest>>>,
91 disconnected_pending: Mutex<Vec<ConnectionId>>,
92 abandoned_spawns: Mutex<Vec<(DeliverySpawn, bool)>>,
93 phone_withdrawals: Mutex<phone::PhoneWithdrawals>,
94 #[cfg(any(test, feature = "test-support"))]
95 os_prompt_policy: std::sync::atomic::AtomicBool,
96 #[cfg(test)]
97 spawn_preflight_hook: Mutex<Option<Box<dyn FnOnce() + Send>>>,
98 #[cfg(test)]
99 exit_record_attempts: std::sync::atomic::AtomicUsize,
100 #[cfg(test)]
101 phone_bind_hook: Mutex<Option<Box<dyn FnOnce() + Send>>>,
102 #[cfg(test)]
103 begin_approval_hook: Mutex<Option<Box<dyn FnOnce() + Send>>>,
104 #[cfg(test)]
105 begin_approval_completions: std::sync::atomic::AtomicUsize,
106 #[cfg(test)]
107 desktop_receipt_hook: Mutex<Option<Box<dyn FnOnce() + Send>>>,
108 #[cfg(test)]
109 prepare_capture_hook: Mutex<Option<Box<dyn FnOnce() + Send>>>,
110 #[cfg(all(test, unix))]
111 approval_claim_pause: Mutex<Option<ApprovalClaimPause>>,
112}
113
114pub(crate) struct SwapConfiguration<'a> {
117 owner: &'a RuntimeOwner,
118 state: OwnerGuard<'a>,
119}
120
121#[cfg(test)]
122pub(crate) struct WarmRestartPause {
123 pub(crate) reached: tokio::sync::oneshot::Sender<()>,
124 pub(crate) resume: tokio::sync::oneshot::Receiver<()>,
125}
126
127impl SwapConfiguration<'_> {
128 pub(crate) fn before_cutover(
129 &mut self,
130 module: &str,
131 connection: ConnectionId,
132 spawn: Option<&DeliverySpawn>,
133 ) -> Result<Option<u64>> {
134 match self.state.store.loaded_admission_state().0 {
135 StoreState::Unstamped => return Ok(None),
136 StoreState::Stamped => {}
137 _ => {
138 return Err(GateError::new(
139 "config_gated",
140 "configuration store is in recovery",
141 ))
142 }
143 }
144 let newer = RuntimeOwner::requires_fresher_spawn_loaded(&self.state, module, spawn)?;
145 if newer.is_none() {
146 self.owner.module_get_locked(
147 &mut self.state,
148 connection,
149 module,
150 subc_protocol::config::ConfigGetRequest::new(),
151 false,
152 )?;
153 }
154 Ok(newer)
155 }
156 pub(crate) fn promoted(
157 &mut self,
158 module: &str,
159 connection: ConnectionId,
160 at: tokio::time::Instant,
161 ) -> Result<()> {
162 RuntimeOwner::promote_loaded(&mut self.state, connection, module, at).map(|_| ())
163 }
164}
165
166#[cfg(all(test, unix))]
167struct ApprovalClaimPause {
168 reached: tokio::sync::oneshot::Sender<()>,
169 release: tokio::sync::oneshot::Receiver<()>,
170}
171
172pub(crate) struct ApprovalCommitWindow {
175 pub deadline: tokio::time::Instant,
176 phase: std::sync::atomic::AtomicU8,
177}
178
179impl ApprovalCommitWindow {
180 pub(crate) fn new(deadline: tokio::time::Instant) -> Self {
181 Self {
182 deadline,
183 phase: std::sync::atomic::AtomicU8::new(0),
184 }
185 }
186
187 pub(crate) fn expire(&self) -> bool {
188 self.phase
189 .compare_exchange(
190 0,
191 2,
192 std::sync::atomic::Ordering::AcqRel,
193 std::sync::atomic::Ordering::Acquire,
194 )
195 .is_ok()
196 }
197
198 fn begin_publication(&self) -> Result<()> {
199 if tokio::time::Instant::now() >= self.deadline {
200 self.expire();
201 return Err(GateError::commit_timeout());
202 }
203 self.phase
204 .compare_exchange(
205 0,
206 1,
207 std::sync::atomic::Ordering::AcqRel,
208 std::sync::atomic::Ordering::Acquire,
209 )
210 .map(|_| ())
211 .map_err(|_| GateError::commit_timeout())
212 }
213}
214
215pub use route_policy::{
216 ApprovedRoutePolicy, RoutePolicyAuthority, RoutePolicyInstall, RoutePolicyInstallation,
217 RoutePolicyReceipt,
218};
219
220pub use delivery::{AppliedDisposition, DeliveryProbe, DeliverySpawn};
221
222pub trait DeliveryObserver: Send + Sync {
228 fn spawned(
229 &self,
230 module: &str,
231 spawned_at: tokio::time::Instant,
232 register_timeout: std::time::Duration,
233 first_health_budget: std::time::Duration,
234 ) -> Result<Option<DeliverySpawn>>;
235 fn registered(&self, connection: ConnectionId, spawn: &DeliverySpawn) -> Result<()>;
236 fn health_probe(&self, connection: ConnectionId, module: &str)
237 -> Result<Option<DeliveryProbe>>;
238 fn health_result(
239 &self,
240 probe: DeliveryProbe,
241 healthy: bool,
242 ) -> Result<Option<AppliedDisposition>>;
243 fn promoted(
244 &self,
245 connection: ConnectionId,
246 module: &str,
247 cutover_at: tokio::time::Instant,
248 ) -> Result<Option<(u64, u64)>>;
249 fn retry_anchor(&self) -> Result<Option<tokio::time::Instant>>;
252}
253
254impl DeliveryObserver for RuntimeOwner {
255 fn spawned(
256 &self,
257 module: &str,
258 spawned_at: tokio::time::Instant,
259 register_timeout: std::time::Duration,
260 first_health_budget: std::time::Duration,
261 ) -> Result<Option<DeliverySpawn>> {
262 self.delivery_spawned(module, spawned_at, register_timeout, first_health_budget)
263 }
264
265 fn registered(&self, connection: ConnectionId, spawn: &DeliverySpawn) -> Result<()> {
266 self.delivery_child_registered(connection, spawn)
267 }
268
269 fn health_probe(
272 &self,
273 connection: ConnectionId,
274 module: &str,
275 ) -> Result<Option<DeliveryProbe>> {
276 self.delivery_health_probe(connection, module)
277 }
278
279 fn health_result(
282 &self,
283 probe: DeliveryProbe,
284 healthy: bool,
285 ) -> Result<Option<AppliedDisposition>> {
286 self.delivery_health_result(probe, healthy)
287 }
288
289 fn promoted(
290 &self,
291 connection: ConnectionId,
292 module: &str,
293 cutover_at: tokio::time::Instant,
294 ) -> Result<Option<(u64, u64)>> {
295 self.delivery_promoted(connection, module, cutover_at)
296 }
297
298 fn retry_anchor(&self) -> Result<Option<tokio::time::Instant>> {
299 self.poll_anchor_retry()
300 }
301}
302
303const PLAN_IDLE_TIMEOUT: Duration = Duration::from_secs(60 * 60);
305pub(crate) const PLAN_SWEEP_INTERVAL: Duration = Duration::from_secs(60);
307const EXPIRED_PLAN_IDS: usize = 64;
309
310fn layer_file_rows(
311 changeset: &mut Changeset,
312 old: &super::GateSnapshot,
313 new: &super::GateSnapshot,
314 previous: Option<&DeliverySnapshot>,
315 candidate: &DeliverySnapshot,
316) -> Result<()> {
317 for key in old.changed_keys(new) {
318 let super::InputKey::Layer { module, path } = key else {
319 continue;
320 };
321 if changeset.fields.iter().any(|field| {
324 field.module_id == *module
325 && (field.old_source == subc_config::Layer::User
326 || field.new_source == subc_config::Layer::User)
327 }) {
328 continue;
329 }
330 let describe = |snapshot: Option<&DeliverySnapshot>,
331 input: Option<&super::CapturedInput>|
332 -> Result<serde_json::Value> {
333 if input.is_none()
334 || input.is_some_and(|input| input.state == subc_config::InputState::Absent)
335 {
336 return Ok(serde_json::json!({"absent":true}));
337 }
338 let bytes = snapshot
339 .and_then(|snapshot| snapshot.modules.get(module))
340 .and_then(|view| {
341 view.layers
342 .iter()
343 .find(|layer| layer.path.as_deref() == Some(path.as_str()))
344 })
345 .and_then(|layer| layer.bytes.as_deref())
346 .ok_or_else(|| GateError::new("config_gated", "retained layer bytes are absent"))?;
347 Ok(
348 serde_json::json!({"sha256":subc_config::raw_digest(bytes).as_str().trim_start_matches("sha256:"), "bytes":bytes.len()}),
349 )
350 };
351 changeset.policy_changes.push(serde_json::json!({
352 "kind":"layer_file", "module_id":module, "layer":"user",
353 "old":describe(previous, old.inputs.get(key))?,
354 "new":describe(Some(candidate), new.inputs.get(key))?,
355 }));
356 }
357 Ok(())
358}
359
360pub(crate) fn daemon_review(
361 old: &super::GateSnapshot,
362 new: &super::GateSnapshot,
363) -> Result<Changeset> {
364 let mut changeset = Changeset::new();
365 for key in old.changed_keys(new) {
366 match key {
367 super::InputKey::Entry(module) | super::InputKey::Program { module, .. } => {
368 let field = match key {
369 super::InputKey::Entry(_) => "entry".into(),
370 super::InputKey::Program { path, .. } => format!("program:{path}"),
371 _ => unreachable!(),
372 };
373 let manifest = changeset
374 .launch_manifests
375 .entry(module.clone())
376 .or_insert_with(|| serde_json::json!({"origin": "other"}));
377 manifest.as_object_mut().expect("launch manifest is an object").insert(field,serde_json::json!({"old":old.inputs.get(key).map(|v| &v.value),"new":new.inputs.get(key).map(|v| &v.value)}));
378 }
379 super::InputKey::Declaration(module) => {
380 changeset.policy_changes.push(serde_json::json!({"module_id":module,"path":"declaration","old":old.inputs.get(key).map(|v| &v.value),"new":new.inputs.get(key).map(|v| &v.value)}));
381 }
382 super::InputKey::Daemon => {
383 changeset.policy_changes.push(serde_json::json!({
384 "path":"subc.jsonc",
385 "old":old.inputs.get(key).map(|v| &v.value),
386 "new":new.inputs.get(key).map(|v| &v.value),
387 }));
388 changeset.apply_plan = serde_json::json!({"supervisor_reconcile":true});
389 }
390 _ => {}
391 }
392 }
393 Ok(changeset)
394}
395
396struct OwnerState {
397 authority_incarnation: std::sync::Arc<()>,
398 observed_snapshot: Option<super::GateSnapshot>,
399 stamp_channel_cutover: bool,
400 gate: ConfigGate,
401 store: ConfigStore,
402 _writer_lock: Option<crate::config_store::StoreWriterLock>,
403 plan_deadlines: BTreeMap<Digest, Instant>,
404 desktop_views: BTreeMap<u64, (Digest, u64)>,
407 phone_waiters: BTreeMap<u64, tokio::sync::oneshot::Sender<()>>,
408 approval_requests: HashMap<(ConnectionId, u64), u64>,
409 delivery: delivery::DeliveryState,
410 anchor_retry: super::anchor_retry::AnchorRetry,
411 retained_plan_files: BTreeMap<Digest, Vec<std::fs::File>>,
414 expired_plans: VecDeque<Digest>,
415 declarations: HashMap<ConnectionId, (String, ConfigDeclareRequest)>,
416 active_declarations: BTreeMap<String, ConnectionId>,
417 activity: Option<crate::activity::ActivityLedger>,
418 refused_generations: BTreeMap<String, Digest>,
419 admission_holds: Vec<String>,
420 admission_releases: Vec<String>,
421 authority_exit: Option<u64>,
422 reconciled_entries: BTreeMap<String, crate::daemon_config::ConfiguredModule>,
424 recovery_exit_hold: bool,
425 unstamp_hints: std::collections::HashSet<ConnectionId>,
426 anchor_waiters: std::collections::HashSet<ConnectionId>,
427 anchor_hints: std::collections::HashSet<ConnectionId>,
428 anchor_notify: std::sync::Arc<tokio::sync::Notify>,
429 installed_route_policies: BTreeMap<String, u64>,
430 route_policy_receipts: BTreeMap<(String, u64), route_policy::PendingRoutePolicy>,
431 #[cfg(test)]
432 publication_hook: Option<Box<dyn FnOnce() + Send>>,
433 #[cfg(test)]
434 prepublication_hook: Option<Box<dyn FnOnce() + Send>>,
435 #[cfg(test)]
436 after_approval_drain_hook: Option<Box<dyn FnOnce() + Send>>,
437}
438
439impl OwnerState {
440 fn retry_anchor(&mut self, operator_command: bool) -> Option<tokio::time::Instant> {
441 let pending = self.store.status().anchor_pending;
442 let events = self.anchor_retry.poll(
443 pending,
444 tokio::time::Instant::now(),
445 operator_command,
446 || {
447 let error = self
448 .store
449 .retry_anchor()
450 .err()
451 .map(|error| error.to_string());
452 (self.store.status().anchor_pending, error)
453 },
454 );
455 for event in events {
456 match event {
457 super::anchor_retry::Event::Pending => {
458 tracing::info!("configuration anchor became pending")
459 }
460 super::anchor_retry::Event::Failed(reason) => {
461 tracing::warn!(%reason, "configuration anchor retry failed")
462 }
463 super::anchor_retry::Event::Recovered => {
464 tracing::info!("configuration anchor recovered");
465 self.queue_anchor_hints();
466 }
467 }
468 }
469 self.commit_anchored_route_policies();
470 self.anchor_retry.next()
471 }
472 fn with_desktop_view(&self, digest: &Digest, facts: &ApprovalFacts) -> ApprovalFacts {
473 let mut checked = facts.clone();
474 let bound = self
475 .desktop_views
476 .get(&facts.connection)
477 .is_some_and(|(shown, revision)| {
478 shown == digest
479 && self
480 .gate
481 .plans
482 .get(digest)
483 .is_some_and(|plan| plan.view.base_revision == *revision)
484 });
485 if !bound {
486 checked.desktop_app = false;
487 checked.attested_operator_app = false;
488 }
489 checked
490 }
491 fn expire_idle(&mut self, now: Instant) -> bool {
493 let expired: Vec<_> = self
494 .plan_deadlines
495 .iter()
496 .filter(|(digest, deadline)| **deadline <= now && !self.gate.has_open_approval(digest))
497 .map(|(digest, _)| digest.clone())
498 .collect();
499 let any = !expired.is_empty();
500 for digest in expired {
501 self.plan_deadlines.remove(&digest);
502 self.retained_plan_files.remove(&digest);
503 self.desktop_views.retain(|_, (shown, _)| shown != &digest);
504 if self.gate.expire_plan(&digest) {
505 self.expired_plans.push_back(digest);
506 if self.expired_plans.len() > EXPIRED_PLAN_IDS {
507 self.expired_plans.pop_front();
508 }
509 }
510 }
511 any
512 }
513 fn reviewed(&mut self, digest: &Digest, now: Instant) {
514 self.plan_deadlines
515 .insert(digest.clone(), now + PLAN_IDLE_TIMEOUT);
516 self.expired_plans.retain(|expired| expired != digest);
517 }
518}
519
520struct OwnerGuard<'a> {
527 state: std::sync::MutexGuard<'a, OwnerState>,
528 owner: &'a RuntimeOwner,
529 changed: bool,
530}
531impl std::ops::Deref for OwnerGuard<'_> {
532 type Target = OwnerState;
533 fn deref(&self) -> &Self::Target {
534 &self.state
535 }
536}
537impl std::ops::DerefMut for OwnerGuard<'_> {
538 fn deref_mut(&mut self) -> &mut Self::Target {
539 self.changed = true;
543 &mut self.state
544 }
545}
546
547fn store_witness(store: &ConfigStore) -> (StoreState, u64, bool, u64) {
551 (
552 store.loaded_admission_state().0,
553 store.publication_sequence(),
554 store.loaded_anchor_pending(),
555 store.key_status_revision(),
556 )
557}
558
559impl<'a> OwnerGuard<'a> {
560 fn new(state: std::sync::MutexGuard<'a, OwnerState>, owner: &'a RuntimeOwner) -> Self {
561 #[cfg(test)]
562 owner
563 .owner_guards
564 .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
565 Self {
566 state,
567 owner,
568 changed: false,
569 }
570 }
571
572 fn store_read<T>(&mut self, read: impl FnOnce(&mut ConfigStore) -> T) -> T {
576 let before = store_witness(&self.state.store);
577 let result = read(&mut self.state.store);
578 if store_witness(&self.state.store) != before {
579 self.changed = true;
580 }
581 result
582 }
583
584 fn checked_body(
587 &mut self,
588 ) -> std::result::Result<&crate::config_store::StoreBody, crate::config_store::StoreError> {
589 self.store_read(ConfigStore::check)?;
590 Ok(self.state.store.loaded_admission_state().1)
591 }
592
593 fn check_authority_for_read(&mut self) -> Result<()> {
594 let before = store_witness(&self.state.store);
595 let retry = self.state.anchor_retry.next();
596 let result = RuntimeOwner::check_authority(&mut self.state, false);
597 let after = store_witness(&self.state.store);
598 self.changed |= after != before;
599 if before.2 != after.2 || retry != self.state.anchor_retry.next() {
602 self.owner.notify_delivery_changed();
603 }
604 result
605 }
606
607 fn publish(&mut self) {
608 #[cfg(test)]
609 self.owner
610 .projection_builds
611 .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
612 let previous = self
616 .owner
617 .published
618 .read()
619 .map(|view| view.approved_daemon.clone())
620 .unwrap_or(ApprovedDaemonView::Unavailable);
621 let approved_daemon = ApprovedDaemonView::from_store(
622 &self.state.store,
623 self.state.recovery_exit_hold,
624 &previous,
625 );
626 let (_, body) = self.state.store.loaded_admission_state();
630 let valid: std::collections::BTreeSet<_> = body
631 .program_refusals
632 .iter()
633 .map(|refusal| (refusal.module.clone(), refusal.approved_base.clone()))
634 .collect();
635 self.state
636 .refused_generations
637 .retain(|module, base| valid.contains(&(module.clone(), base.clone())));
638 let next = admission::AdmissionCache::from_state(&self.state);
639 mark::sweep(self.owner, &mut self.state, &next);
643 let observed = self.state.observed_snapshot.clone();
644 let projection = self
645 .owner
646 .status_projection(&mut self.state, observed, &next);
647 let settings = settings::SettingsVersion::from_state(&self.state);
648 if let Ok(mut cache) = self.owner.published.write() {
649 let (holds, releases) = next.transitions_from(&cache);
650 let changed = next.is_recovering() != cache.is_recovering()
651 || !holds.is_empty()
652 || !releases.is_empty();
653 let settings_changed = cache.settings.as_ref() != Some(&settings)
654 || projection.status.ungated_modules != cache.projection.status.ungated_modules;
655 self.state.admission_holds.extend(holds);
656 self.state.admission_releases.extend(releases);
657 *cache = std::sync::Arc::new(Published {
658 admission: next,
659 approved_daemon,
660 projection,
661 settings: Some(settings),
662 });
663 if settings_changed {
664 self.owner
665 .settings_changed
666 .send_modify(|revision| *revision = revision.wrapping_add(1));
667 }
668 if changed {
669 self.owner.delivery_changed.notify_one();
670 }
671 }
672 }
673}
674impl Drop for OwnerGuard<'_> {
675 fn drop(&mut self) {
676 let stale = self
678 .owner
679 .projection_stale
680 .swap(false, std::sync::atomic::Ordering::AcqRel);
681 let published = (!(self.changed || stale))
682 .then(|| {
683 self.owner
684 .published
685 .read()
686 .ok()
687 .map(|view| std::sync::Arc::clone(&view))
688 })
689 .flatten();
690 match published {
691 Some(published) => mark::sweep(self.owner, &mut self.state, &published.admission),
695 None => self.publish(),
696 }
697 let Some(ledger) = self.state.activity.clone() else {
698 return;
699 };
700 let Ok(gates) = self.owner.module_gates.try_lock() else {
701 return;
702 };
703 let held: Vec<_> = gates
704 .values()
705 .filter(|gate| gate.try_lock().is_err())
706 .cloned()
707 .collect();
708 drop(gates);
709 if held.is_empty() {
710 for activity in self.state.store.take_activities() {
711 ledger.config_store_activity(activity);
712 }
713 } else if let Ok(runtime) = tokio::runtime::Handle::try_current() {
714 let activities = self.state.store.take_activities();
715 if !activities.is_empty() {
716 runtime.spawn(async move {
717 for gate in held {
720 drop(gate.lock_owned().await);
721 }
722 for activity in activities {
723 ledger.config_store_activity(activity);
724 }
725 });
726 }
727 }
728 }
729}
730
731pub struct PreparedPlan {
732 edits: Option<edits::EditPlan>,
733 pub(crate) projects: Option<super::targets::ProjectReviews>,
736 pub candidate: CapturedConfiguration,
737 pub bases: BTreeMap<String, ConfigView>,
738 pub base_schemas: BTreeMap<String, subc_config::Schema>,
739 pub kind: PlanKind,
740 pub review_modules: std::collections::BTreeSet<String>,
741 pub rereview_modules: std::collections::BTreeSet<String>,
745 base_revision: u64,
746 active_generations: BTreeMap<crate::config_store::Tuple, Option<u64>>,
747 touched_modules: BTreeSet<String>,
748 read_set: subc_config::InputVector,
749 program_keys: Vec<super::InputKey>,
750 observed_handles: Vec<std::fs::File>,
751}
752
753pub struct ApprovedRollbackCommands {
755 pub generation: u64,
756 pub daemon: ConfigLayerSnapshot,
757 pub programs: BTreeMap<String, ApprovedRollbackProgram>,
758}
759
760#[derive(Clone, Debug)]
764pub(crate) struct ApprovedDaemonConfiguration {
765 generation: u64,
766 approval_digest: Digest,
767 authority_incarnation: std::sync::Arc<()>,
768 daemon: std::sync::Arc<ConfigLayerSnapshot>,
769 changed_entries: BTreeSet<String>,
770}
771
772#[derive(Clone, Debug)]
773pub(crate) struct ApprovalIdentity {
774 generation: u64,
775 approval_digest: Digest,
776 authority_incarnation: std::sync::Arc<()>,
780}
781
782impl PartialEq for ApprovalIdentity {
783 fn eq(&self, other: &Self) -> bool {
784 self.generation == other.generation
785 && self.approval_digest == other.approval_digest
786 && std::sync::Arc::ptr_eq(&self.authority_incarnation, &other.authority_incarnation)
787 }
788}
789
790impl Eq for ApprovalIdentity {}
791
792pub struct ApprovedRollbackProgram {
793 pub path: String,
794 pub identity: super::CapturedInput,
795}
796
797#[cfg(test)]
798#[path = "runtime_tests.rs"]
799mod tests;
800
801#[cfg(test)]
802#[path = "commit_pause.rs"]
803pub(crate) mod commit_pause;
804
805#[path = "delivery.rs"]
806pub(crate) mod delivery;
807
808#[path = "admission.rs"]
809mod admission;
810#[path = "mark.rs"]
811pub(crate) mod mark;
812#[path = "recovery.rs"]
813mod recovery;
814#[path = "route_policy.rs"]
815mod route_policy;
816pub(crate) use admission::SpawnAdmission;
817
818#[path = "approval_request.rs"]
819mod approval_request;
820#[path = "daemon_readers.rs"]
821mod daemon_readers;
822pub(crate) use daemon_readers::ApprovedDaemonView;
823#[path = "phone.rs"]
824mod phone;
825#[path = "placement.rs"]
826mod placement;
827#[path = "polled.rs"]
828mod polled;
829#[path = "published.rs"]
830mod published;
831#[path = "unstamped.rs"]
832pub(crate) mod unstamped;
833#[path = "widening.rs"]
834mod widening;
835pub(crate) use published::Published;
836#[path = "settings.rs"]
837pub(crate) mod settings;
838#[path = "status_inputs.rs"]
839mod status_inputs;
840pub(crate) use approval_request::{ApprovalRequest, ApprovalRequestGuard, CancelApprovalRequest};
841
842impl RuntimeOwner {
843 pub(crate) async fn on_blocking<T: Send + 'static>(
845 self: &std::sync::Arc<Self>,
846 work: impl FnOnce(std::sync::Arc<Self>) -> Result<T> + Send + 'static,
847 ) -> Result<T> {
848 let owner = self.clone();
849 tokio::task::spawn_blocking(move || work(owner))
850 .await
851 .map_err(|_| GateError::new("config_unavailable", "configuration worker stopped"))?
852 }
853
854 #[cfg(feature = "test-support")]
855 pub(crate) fn pause_spawn_before_exec(&self) -> Result<()> {
856 if let Some(hooks) = &self.test_hooks {
857 hooks
858 .pause_spawn_before_exec()
859 .map_err(|error| GateError::new("config_test_pause", error.to_string()))?;
860 }
861 Ok(())
862 }
863
864 #[cfg(feature = "test-support")]
865 pub(crate) fn pause_swap_before_promotion(&self) -> Result<()> {
866 if let Some(hooks) = &self.test_hooks {
867 hooks
868 .pause_swap_before_promotion()
869 .map_err(|error| GateError::new("config_test_pause", error.to_string()))?;
870 }
871 Ok(())
872 }
873 #[cfg(test)]
876 pub(crate) fn desktop_view_delivered(
877 &self,
878 connection: ConnectionId,
879 view: &subc_control::config::ConfigPlanView,
880 ) -> Result<()> {
881 self.desktop_view_delivered_when(connection, view, || true)
882 }
883
884 pub(crate) fn desktop_view_delivered_when(
885 &self,
886 connection: ConnectionId,
887 view: &subc_control::config::ConfigPlanView,
888 is_live: impl FnOnce() -> bool,
889 ) -> Result<()> {
890 #[cfg(test)]
891 if let Some(hook) = self.desktop_receipt_hook.lock().unwrap().take() {
892 hook();
893 }
894 let mut state = self.lock()?;
895 if !is_live() {
898 return Ok(());
899 }
900 let plan = state
901 .gate
902 .plans
903 .get(&view.digest)
904 .ok_or_else(|| GateError::new("plan_unknown", "plan is absent or expired"))?;
905 if plan.view != *view {
906 return Err(GateError::new(
907 "plan_stale",
908 "delivered view differs from the immutable plan",
909 ));
910 }
911 state
912 .desktop_views
913 .insert(connection.get(), (view.digest.clone(), view.base_revision));
914 Ok(())
915 }
916 pub fn new(incarnation: String, mut store: ConfigStore, capturer: ConfigCapturer) -> Self {
917 let initial_generation = match store.booted_generation() {
919 Some(booted) => booted,
920 None => store.body().map(|body| body.last_generation).unwrap_or(0),
921 };
922 let admission = admission::AdmissionCache::from_store(&store);
923 let approved_daemon =
924 ApprovedDaemonView::from_store(&store, false, &ApprovedDaemonView::Unavailable);
925 let reconciled_entries = match &approved_daemon {
926 ApprovedDaemonView::Approved { config, .. } => config
927 .modules
928 .iter()
929 .map(|module| (module.module_id.clone(), module.clone()))
930 .collect(),
931 _ => BTreeMap::new(),
932 };
933 let published = std::sync::RwLock::new(std::sync::Arc::new(Published {
934 admission,
935 approved_daemon,
936 projection: polled::Projection::default(),
937 settings: None,
938 }));
939 let delivery_changed = std::sync::Arc::new(tokio::sync::Notify::new());
940 let owner = Self {
941 #[cfg(test)]
942 user_file_test_idle: Mutex::new(None),
943 #[cfg(test)]
944 polled_capture_hook: Mutex::new(None),
945 #[cfg(test)]
946 settings_projection_hook: Mutex::new(None),
947 #[cfg(test)]
948 settings_status_hook: Mutex::new(None),
949 #[cfg(test)]
950 settings_observation_hook: Mutex::new(None),
951 #[cfg(test)]
952 config_park_hook: Mutex::new(None),
953 #[cfg(test)]
954 content_kill_hook: Mutex::new(None),
955 #[cfg(test)]
956 polled_capture_count: std::sync::atomic::AtomicUsize::new(0),
957 #[cfg(test)]
958 census_probe: Mutex::new(None),
959 #[cfg(test)]
960 agent_validation_window: Mutex::new(None),
961 #[cfg(test)]
962 warm_restart_pause: Mutex::new(None),
963 #[cfg(test)]
964 warm_restart_busy: Mutex::new(None),
965 #[cfg(test)]
966 swap_preflight_attempts: std::sync::atomic::AtomicUsize::new(0),
967 #[cfg(feature = "test-support")]
968 test_hooks: store.test_support().cloned(),
969 #[cfg(test)]
970 spawn_exec_hook: Mutex::new(None),
971 published,
972 projection_stale: std::sync::atomic::AtomicBool::new(true),
974 #[cfg(test)]
975 projection_builds: std::sync::atomic::AtomicUsize::new(0),
976 #[cfg(test)]
977 owner_guards: std::sync::atomic::AtomicUsize::new(0),
978 config_workers: Mutex::new(std::collections::HashSet::new()),
979 configured_modules: std::sync::RwLock::new(None),
980 inner: Mutex::new(OwnerState {
981 authority_incarnation: std::sync::Arc::new(()),
982 observed_snapshot: None,
983 stamp_channel_cutover: false,
984 gate: ConfigGate::new(incarnation),
985 store,
986 _writer_lock: None,
987 plan_deadlines: BTreeMap::new(),
988 desktop_views: BTreeMap::new(),
989 phone_waiters: BTreeMap::new(),
990 approval_requests: HashMap::new(),
991 delivery: delivery::DeliveryState::new(initial_generation),
992 anchor_retry: super::anchor_retry::AnchorRetry::default(),
993 retained_plan_files: BTreeMap::new(),
994 expired_plans: VecDeque::new(),
995 declarations: HashMap::new(),
996 active_declarations: BTreeMap::new(),
997 activity: None,
998 refused_generations: BTreeMap::new(),
999 admission_holds: Vec::new(),
1000 admission_releases: Vec::new(),
1001 authority_exit: None,
1002 reconciled_entries,
1003 recovery_exit_hold: false,
1004 unstamp_hints: std::collections::HashSet::new(),
1005 anchor_waiters: std::collections::HashSet::new(),
1006 anchor_hints: std::collections::HashSet::new(),
1007 anchor_notify: delivery_changed.clone(),
1008 installed_route_policies: BTreeMap::new(),
1009 route_policy_receipts: BTreeMap::new(),
1010 #[cfg(test)]
1011 publication_hook: None,
1012 #[cfg(test)]
1013 prepublication_hook: None,
1014 #[cfg(test)]
1015 after_approval_drain_hook: None,
1016 }),
1017 capturer,
1018 startup_overrides: status_inputs::present_overrides(|name| {
1019 std::env::var_os(name).is_some()
1020 }),
1021 module_gates: Mutex::new(HashMap::new()),
1022 delivery_changed,
1023 settings_changed: tokio::sync::watch::channel(0).0,
1024 route_policy_authority: std::sync::OnceLock::new(),
1025 mark_publisher: std::sync::OnceLock::new(),
1026 binding_retirements: Mutex::new(BTreeMap::new()),
1027 canceled_approvals: Mutex::new(Vec::new()),
1028 approval_request_index: Mutex::new(HashMap::new()),
1029 disconnected_pending: Mutex::new(Vec::new()),
1030 abandoned_spawns: Mutex::new(Vec::new()),
1031 phone_withdrawals: Mutex::new(phone::PhoneWithdrawals::default()),
1032 #[cfg(any(test, feature = "test-support"))]
1033 os_prompt_policy: std::sync::atomic::AtomicBool::new(false),
1034 #[cfg(test)]
1035 spawn_preflight_hook: Mutex::new(None),
1036 #[cfg(test)]
1037 exit_record_attempts: std::sync::atomic::AtomicUsize::new(0),
1038 #[cfg(test)]
1039 phone_bind_hook: Mutex::new(None),
1040 #[cfg(test)]
1041 begin_approval_hook: Mutex::new(None),
1042 #[cfg(test)]
1043 begin_approval_completions: std::sync::atomic::AtomicUsize::new(0),
1044 #[cfg(test)]
1045 desktop_receipt_hook: Mutex::new(None),
1046 #[cfg(test)]
1047 prepare_capture_hook: Mutex::new(None),
1048 #[cfg(all(test, unix))]
1049 approval_claim_pause: Mutex::new(None),
1050 };
1051 if let Ok(state) = owner.lock() {
1052 drop(state);
1053 }
1054 owner
1055 }
1056
1057 pub fn module_gate(&self, module: &str) -> Result<std::sync::Arc<tokio::sync::Mutex<()>>> {
1058 let mut gates = self
1059 .module_gates
1060 .lock()
1061 .map_err(|_| GateError::new("config_unavailable", "module gate lock is poisoned"))?;
1062 Ok(gates.entry(module.into()).or_default().clone())
1063 }
1064
1065 #[cfg(all(test, unix))]
1066 pub(crate) fn set_agent_validation_window_for_test(&self, window: Duration) {
1067 *self.agent_validation_window.lock().unwrap() = Some(window);
1068 }
1069
1070 #[cfg(test)]
1071 pub(crate) fn agent_validation_window_for_test(&self) -> Option<Duration> {
1072 *self.agent_validation_window.lock().unwrap()
1073 }
1074
1075 pub(crate) fn install_binding_retirement(
1076 &self,
1077 key: usize,
1078 retire: impl Fn() + Send + Sync + 'static,
1079 ) {
1080 self.binding_retirements
1081 .lock()
1082 .unwrap_or_else(|poisoned| poisoned.into_inner())
1083 .insert(key, Box::new(retire));
1084 }
1085
1086 pub(crate) fn delivery_notifications(&self) -> std::sync::Arc<tokio::sync::Notify> {
1087 self.delivery_changed.clone()
1088 }
1089
1090 pub(crate) fn notify_delivery_changed(&self) {
1091 self.delivery_changed.notify_one();
1092 }
1093
1094 pub(crate) fn retain_writer_lock(
1095 self,
1096 lock: crate::config_store::StoreWriterLock,
1097 ) -> Result<Self> {
1098 self.lock()?._writer_lock = Some(lock);
1099 Ok(self)
1100 }
1101
1102 fn lock(&self) -> Result<OwnerGuard<'_>> {
1103 crate::forwarding::assert_forwarding_unlocked("the configuration owner's state");
1106 let mut guard = self
1107 .inner
1108 .lock()
1109 .map(|state| OwnerGuard::new(state, self))
1110 .map_err(|_| {
1111 GateError::new("config_unavailable", "configuration owner lock is poisoned")
1112 })?;
1113 #[cfg(feature = "test-support")]
1115 guard.state.store.refresh_test_anchor_failure();
1116 let drained = self.drain_canceled_approvals(&mut guard.state)
1120 | self.drain_disconnections(&mut guard.state)
1121 | self.drain_abandoned_spawns(&mut guard.state)
1122 | guard.state.expire_idle(Instant::now());
1123 guard.changed |= drained;
1124 Ok(guard)
1125 }
1126
1127 pub(crate) fn try_swap_configuration(&self) -> Result<SwapConfiguration<'_>> {
1128 let state = self.inner.try_lock().map_err(|_| {
1129 GateError::new(
1130 "config_delivery_deferred",
1131 "configuration publication is busy or unavailable",
1132 )
1133 })?;
1134 Ok(SwapConfiguration {
1135 owner: self,
1136 state: OwnerGuard::new(state, self),
1137 })
1138 }
1139
1140 pub(crate) fn try_requires_fresher_spawn(
1141 &self,
1142 module: &str,
1143 spawn: Option<&DeliverySpawn>,
1144 ) -> Result<Option<u64>> {
1145 let state = self.inner.try_lock().map_err(|_| {
1146 GateError::new(
1147 "config_delivery_deferred",
1148 "configuration publication is busy or unavailable",
1149 )
1150 })?;
1151 Self::requires_fresher_spawn_loaded(&state, module, spawn)
1152 }
1153
1154 pub(crate) fn sweep_expired(&self) -> Result<()> {
1155 drop(self.lock()?);
1156 Ok(())
1157 }
1158
1159 pub(crate) fn poll_anchor_retry(&self) -> Result<Option<tokio::time::Instant>> {
1160 Ok(self.lock()?.retry_anchor(false))
1161 }
1162
1163 pub(crate) fn set_activity(
1164 &self,
1165 ledger: Option<crate::activity::ActivityLedger>,
1166 ) -> Result<()> {
1167 self.lock()?.activity = ledger;
1168 Ok(())
1169 }
1170
1171 pub fn take_activities(&self) -> Vec<StoreActivity> {
1172 self.inner
1173 .lock()
1174 .map(|mut state| state.store.take_activities())
1175 .unwrap_or_default()
1176 }
1177
1178 pub fn declare(
1181 &self,
1182 connection: ConnectionId,
1183 module: &str,
1184 declaration: ConfigDeclareRequest,
1185 active: bool,
1186 ) -> Result<()> {
1187 super::strict_json::check_canonical(&declaration.schema, "/schema")
1188 .map_err(|error| GateError::new(&error.code, format!("{module}: {}", error.detail)))?;
1189 subc_config::Schema::new(declaration.schema.clone())
1190 .map_err(|r| GateError::new("schema_invalid", format!("{module}: {}", r.path)))?;
1191 let mut state = self.lock()?;
1192 if state.store.status().state == StoreState::StoreMissing
1193 || state.store.status().state == StoreState::StoreUnverified
1194 {
1195 return Err(GateError::new(
1196 "config_gated",
1197 "configuration store is in recovery",
1198 ));
1199 }
1200 if state.declarations.contains_key(&connection) {
1201 return Err(GateError::new(
1202 "declaration_order",
1203 "configuration is declared once per connection",
1204 ));
1205 }
1206 state
1207 .declarations
1208 .insert(connection, (module.into(), declaration));
1209 state.delivery.declared(connection, module, active);
1210 if active {
1211 state.active_declarations.insert(module.into(), connection);
1212 }
1213 self.notify_delivery_changed();
1214 Ok(())
1215 }
1216
1217 pub fn disconnected(&self, connection: ConnectionId) {
1223 let mut held = false;
1224 if let Ok(mut index) = self.approval_request_index.lock() {
1225 index.retain(|(caller, _), request| {
1226 if *caller == connection {
1227 request.cancel();
1228 held = true;
1229 false
1230 } else {
1231 true
1232 }
1233 });
1234 }
1235 match self.inner.try_lock() {
1236 Ok(mut state) => {
1237 if state.disconnected(connection) {
1238 held = true;
1239 self.projection_stale
1242 .store(true, std::sync::atomic::Ordering::Release);
1243 }
1244 }
1245 Err(_) => {
1246 if let Ok(mut pending) = self.disconnected_pending.lock() {
1247 pending.push(connection);
1248 }
1249 held = true;
1252 }
1253 }
1254 if held || self.runs_config_worker(connection) {
1255 self.notify_delivery_changed();
1256 }
1257 }
1258
1259 pub(crate) fn config_worker_started(&self, connection: ConnectionId) {
1262 self.config_workers
1263 .lock()
1264 .unwrap_or_else(|poisoned| poisoned.into_inner())
1265 .insert(connection);
1266 }
1267
1268 pub(crate) fn config_worker_stopped(&self, connection: ConnectionId) {
1270 self.config_workers
1271 .lock()
1272 .unwrap_or_else(|poisoned| poisoned.into_inner())
1273 .remove(&connection);
1274 }
1275
1276 fn runs_config_worker(&self, connection: ConnectionId) -> bool {
1277 self.config_workers
1278 .lock()
1279 .map_or(true, |workers| workers.contains(&connection))
1280 }
1281
1282 pub fn module_get(
1283 &self,
1284 connection: ConnectionId,
1285 module: &str,
1286 request: subc_protocol::config::ConfigGetRequest,
1287 ) -> Result<subc_protocol::config::ConfigGetReply> {
1288 let mut state = self.lock()?;
1289 self.module_get_locked(&mut state, connection, module, request, true)
1290 }
1291
1292 fn module_get_locked(
1293 &self,
1294 state: &mut OwnerState,
1295 connection: ConnectionId,
1296 module: &str,
1297 request: subc_protocol::config::ConfigGetRequest,
1298 check_store: bool,
1299 ) -> Result<subc_protocol::config::ConfigGetReply> {
1300 let declaration = state
1301 .declarations
1302 .get(&connection)
1303 .filter(|(id, _)| id == module)
1304 .map(|(_, declaration)| declaration.clone())
1305 .ok_or_else(|| {
1306 GateError::new(
1307 "declaration_order",
1308 "config.declare must precede get or applied on this connection",
1309 )
1310 })?;
1311 if request.project_id.is_some() {
1312 return Err(GateError::new(
1313 "config_gated",
1314 format!("{module}: project-tuple delivery is not supported yet"),
1315 ));
1316 }
1317 if check_store {
1318 let checked = state.store.check();
1319 if matches!(
1320 state.store.loaded_admission_state().0,
1321 StoreState::StoreMissing | StoreState::StoreUnverified
1322 ) {
1323 return recovery::active_view(state, module, &declaration, &request);
1324 }
1325 checked?;
1326 }
1327 if state.store.loaded_admission_state().0 == StoreState::Unstamped {
1328 if request.generation.is_some() || request.attempt.is_some() {
1329 return Err(GateError::new(
1330 "config_gated",
1331 "unstamped reads have no assigned generation or delivery attempt",
1332 ));
1333 }
1334 let mut declarations = Self::declarations(state)?;
1335 declarations.insert(module.into(), declaration);
1336 let mut captured = self
1337 .capturer
1338 .capture_modules(&declarations, &BTreeSet::from([module.to_owned()]))?;
1339 let view = captured
1340 .modules
1341 .remove(module)
1342 .ok_or_else(|| GateError::new("config_gated", "module declaration is unavailable"))?
1343 .view;
1344 return Ok(subc_protocol::config::ConfigGetReply::new(Some(view), None));
1345 }
1346 if check_store {
1347 state.store.delivery_ready()?;
1348 }
1349 let body = if check_store {
1350 state.store.body()?
1351 } else {
1352 state.store.loaded_admission_state().1
1353 };
1354 let tuple = crate::config_store::Tuple {
1355 module: module.into(),
1356 project: None,
1357 };
1358 let versions = body
1359 .versions
1360 .iter()
1361 .find(|(entry, _)| entry == &tuple)
1362 .map(|(_, versions)| versions)
1363 .ok_or_else(|| {
1364 GateError::new("config_gated", "module is not in an approved generation")
1365 })?;
1366 let approved_declaration = [versions.pending, versions.active]
1367 .into_iter()
1368 .flatten()
1369 .any(|generation| {
1370 body.generations
1371 .get(&generation)
1372 .and_then(|entry| entry.delivery.as_ref())
1373 .and_then(|snapshot| snapshot.declarations.get(module))
1374 == Some(&declaration)
1375 });
1376 if !approved_declaration && versions.active.is_none() {
1377 return Err(GateError::new(
1378 "config_gated",
1379 "module has no approved active configuration",
1380 ));
1381 }
1382 let view = |generation: Option<u64>, status: ConfigStatus| -> Result<Option<ConfigView>> {
1383 let Some(generation) = generation else {
1384 return Ok(None);
1385 };
1386 let delivery = body
1387 .generations
1388 .get(&generation)
1389 .and_then(|entry| entry.delivery.as_ref())
1390 .ok_or_else(|| {
1391 GateError::new("config_gated", "approved delivery bytes are absent")
1392 })?;
1393 let mut view =
1394 delivery.modules.get(module).cloned().ok_or_else(|| {
1395 GateError::new("config_gated", "approved module view is absent")
1396 })?;
1397 view.generation = generation;
1398 view.status = status;
1399 Ok(Some(view))
1400 };
1401 let active = view(versions.active, ConfigStatus::Active)?;
1402 if !approved_declaration {
1403 let mut reply = subc_protocol::config::ConfigGetReply::new(active, None);
1404 reply.declaration_pending = Self::declaration_pending(state, module, &declaration);
1405 return if check_store {
1406 delivery::bind_declaration_fallback(state, connection, module, &request, reply)
1407 } else {
1408 Ok(reply)
1409 };
1410 }
1411 let pending = view(versions.pending, ConfigStatus::Pending)?;
1412 let transition = versions
1413 .pending
1414 .and_then(|id| body.generations.get(&id))
1415 .map(|entry| super::apply::Transition::for_module(&entry.generation.changeset, module))
1416 .transpose()?
1417 .unwrap_or(super::apply::Transition::Live);
1418 if active.is_none() && pending.is_none() {
1419 return Err(GateError::new(
1420 "config_gated",
1421 "module has no active or deliverable generation",
1422 ));
1423 }
1424 if !check_store {
1425 return delivery::visible_reply(
1426 state,
1427 connection,
1428 subc_protocol::config::ConfigGetReply::new(active, pending),
1429 transition,
1430 );
1431 }
1432 delivery::bind_get(
1433 state,
1434 connection,
1435 module,
1436 &request,
1437 subc_protocol::config::ConfigGetReply::new(active, pending),
1438 transition,
1439 )
1440 }
1441
1442 fn declaration_pending(
1443 state: &OwnerState,
1444 module: &str,
1445 declaration: &ConfigDeclareRequest,
1446 ) -> Option<subc_protocol::config::ConfigDeclarationPending> {
1447 let body = state.store.loaded_admission_state().1;
1448 if !body.stamped {
1449 return None;
1450 }
1451 let versions = body
1452 .versions
1453 .iter()
1454 .find(|(tuple, _)| tuple.module == module && tuple.project.is_none())?
1455 .1
1456 .clone();
1457 if versions.active.is_none()
1458 || [versions.active, versions.pending]
1459 .into_iter()
1460 .flatten()
1461 .any(|id| {
1462 body.generations
1463 .get(&id)
1464 .and_then(|entry| entry.delivery.as_ref())
1465 .and_then(|delivery| delivery.declarations.get(module))
1466 == Some(declaration)
1467 })
1468 {
1469 return None;
1470 }
1471 let mut marker = subc_protocol::config::ConfigDeclarationPending::default();
1472 marker.plan_digest = state
1473 .gate
1474 .plans
1475 .values()
1476 .filter(|plan| {
1477 plan.modules.contains(module)
1478 && plan
1479 .delivery
1480 .as_ref()
1481 .and_then(|delivery| delivery.declarations.get(module))
1482 == Some(declaration)
1483 })
1484 .max_by_key(|plan| plan.creation_sequence)
1485 .map(|plan| plan.view.digest.clone());
1486 Some(marker)
1487 }
1488
1489 fn declarations(state: &mut OwnerState) -> Result<BTreeMap<String, ConfigDeclareRequest>> {
1490 let mut declarations = if state.store.status().state == StoreState::Stamped {
1491 state
1492 .store
1493 .body()?
1494 .generations
1495 .values()
1496 .next_back()
1497 .and_then(|entry| entry.delivery.as_ref())
1498 .map(|snapshot| snapshot.declarations.clone())
1499 .unwrap_or_default()
1500 } else {
1501 BTreeMap::new()
1502 };
1503 for (module, connection) in &state.active_declarations {
1504 if let Some((_, declaration)) = state.declarations.get(connection) {
1505 declarations.insert(module.clone(), declaration.clone());
1506 }
1507 }
1508 Ok(declarations)
1509 }
1510
1511 fn capture(&self, state: &mut OwnerState) -> Result<CapturedConfiguration> {
1512 let declarations = Self::declarations(state)?;
1513 let captured = self.capturer.capture(&declarations)?;
1514 state.observed_snapshot = Some(captured.diagnostic.clone());
1515 Ok(captured)
1516 }
1517
1518 fn capture_modules(
1519 &self,
1520 state: &mut OwnerState,
1521 modules: &BTreeSet<String>,
1522 ) -> Result<CapturedConfiguration> {
1523 self.capturer
1524 .capture_modules(&Self::declarations(state)?, modules)
1525 }
1526
1527 fn check_authority(state: &mut OwnerState, recovery: bool) -> Result<()> {
1528 if let Err(error) = state.store.check() {
1529 return if recovery
1530 && matches!(
1531 state.store.loaded_admission_state().0,
1532 StoreState::StoreUnverified | StoreState::StoreMissing
1533 ) {
1534 Ok(())
1535 } else {
1536 Err(error.into())
1537 };
1538 }
1539 state.retry_anchor(true);
1540 match state.store.check() {
1541 Ok(()) => Ok(()),
1542 Err(_)
1543 if recovery
1544 && matches!(
1545 state.store.status().state,
1546 StoreState::StoreUnverified | StoreState::StoreMissing
1547 ) =>
1548 {
1549 Ok(())
1550 }
1551 Err(error) => Err(error.into()),
1552 }
1553 }
1554
1555 pub fn prepare(&self, kind: PlanKind) -> Result<PreparedPlan> {
1562 let mut state = self.lock()?;
1563 Self::check_authority(
1564 &mut state,
1565 matches!(kind, PlanKind::Stamp | PlanKind::Unstamp),
1566 )?;
1567 #[cfg(test)]
1568 if let Some(hook) = self.prepare_capture_hook.lock().unwrap().take() {
1569 hook();
1570 }
1571 let observed = self.capture(&mut state)?;
1572 if observed.daemon.bytes.is_none() {
1573 return Err(GateError::new(
1574 "invalid_daemon_config",
1575 "subc.jsonc is absent; refusing to rescan",
1576 ));
1577 }
1578 if !state.recovery_exit_hold && state.store.status().state == StoreState::Stamped {
1579 let approved = super::GateSnapshot::from_store(&state.store.body()?.approved)?;
1580 state
1581 .store
1582 .observe(observed.proposal_snapshot(&approved).to_store()?)?;
1583 }
1584 let rollback = if let PlanKind::Rollback(id) = kind {
1585 let target = super::GateSnapshot::from_store(&state.store.rollback_configuration(id)?)?;
1586 let delivery = state
1587 .store
1588 .body()?
1589 .generations
1590 .get(&id)
1591 .and_then(|entry| entry.delivery.as_ref())
1592 .ok_or_else(|| {
1593 GateError::new(
1594 "rollback_snapshot_unavailable",
1595 "retained raw configuration is absent",
1596 )
1597 })?;
1598 Some((self.capturer.capture_retained(&target, delivery)?, target))
1599 } else {
1600 None
1601 };
1602 let (candidate, mut observed, target) = if let Some((candidate, target)) = rollback {
1603 (candidate, Some(observed), Some(target))
1604 } else {
1605 (observed, None, None)
1606 };
1607 if kind == PlanKind::Stamp {
1608 super::registration::check_stamp(&candidate.diagnostic)?;
1609 }
1610 let base_revision = state.store.status().base_revision;
1611 let old = if state.store.status().state == StoreState::Stamped {
1612 super::GateSnapshot::from_store(&state.store.body()?.approved)?
1613 } else {
1614 super::GateSnapshot::default()
1615 };
1616 let mut touched_modules: BTreeSet<_> = candidate
1617 .diagnostic
1618 .changed_keys(&old)
1619 .iter()
1620 .filter_map(|key| key.module().map(str::to_owned))
1621 .collect();
1622 if matches!(kind, PlanKind::Stamp | PlanKind::Unstamp) {
1623 touched_modules.extend(candidate.diagnostic.modules());
1624 touched_modules.extend(old.modules());
1625 }
1626 if let Some(target) = target {
1627 touched_modules.extend(
1628 candidate
1629 .diagnostic
1630 .inputs
1631 .iter()
1632 .filter(|(key, value)| {
1633 key.is_program() && target.inputs.get(*key) != Some(*value)
1634 })
1635 .filter_map(|(key, _)| key.module().map(str::to_owned)),
1636 );
1637 }
1638 let mut review_modules: BTreeSet<String> = touched_modules
1639 .iter()
1640 .filter(|module| candidate.modules.contains_key(*module))
1641 .filter(|module|matches!(kind,PlanKind::Stamp|PlanKind::Unstamp) || candidate.diagnostic.changed_keys(&old).iter().any(|key|matches!(key,super::InputKey::Layer {module:owner,..}|super::InputKey::Declaration(owner) if owner==*module)))
1642 .cloned()
1643 .collect();
1644 let mut rereview_modules = BTreeSet::new();
1650 if matches!(kind, PlanKind::Change | PlanKind::Rollback(_))
1651 && state.store.status().state == StoreState::Stamped
1652 {
1653 for (module, rereview) in
1654 super::reviewed_build::pending(state.store.body()?, candidate.modules.keys())?
1655 {
1656 if rereview == super::reviewed_build::Rereview::Ready
1657 && !review_modules.contains(&module)
1658 {
1659 touched_modules.insert(module.clone());
1660 review_modules.insert(module.clone());
1661 rereview_modules.insert(module);
1662 }
1663 }
1664 }
1665 let program_keys: Vec<_> = candidate
1666 .diagnostic
1667 .inputs
1668 .keys()
1669 .filter(|key| {
1670 key.is_program()
1671 && key
1672 .module()
1673 .is_some_and(|module| touched_modules.contains(module))
1674 })
1675 .cloned()
1676 .collect();
1677 let read_set = if let Some(observed) = &mut observed {
1678 observed.capture_programs(&program_keys)?;
1679 if program_keys.iter().any(|key| {
1680 observed.diagnostic.inputs.get(key) != candidate.diagnostic.inputs.get(key)
1681 }) {
1682 return Err(GateError::stale());
1683 }
1684 observed.diagnostic.read_set(&touched_modules)?
1685 } else {
1686 candidate.diagnostic.read_set(&touched_modules)?
1687 };
1688 let observed_handles = observed
1689 .as_mut()
1690 .map(CapturedConfiguration::take_handles)
1691 .unwrap_or_default();
1692 let mut bases = BTreeMap::new();
1693 let mut base_schemas = BTreeMap::new();
1694 let mut active_generations = BTreeMap::new();
1695 if state.store.status().state == StoreState::Stamped {
1696 let body = state.store.body()?;
1697 let approved_id = placement::last_approved_generation(body);
1698 for (tuple, versions) in &body.versions {
1699 if touched_modules.contains(&tuple.module) {
1700 active_generations.insert(tuple.clone(), versions.active);
1701 }
1702 if tuple.project.is_some() || !review_modules.contains(&tuple.module) {
1703 continue;
1704 }
1705 if old
1710 .inputs
1711 .contains_key(&super::InputKey::Declaration(tuple.module.clone()))
1712 {
1713 let id = approved_id;
1714 let snapshot = body
1715 .generations
1716 .get(&id)
1717 .and_then(|entry| entry.delivery.as_ref())
1718 .ok_or_else(|| {
1719 GateError::new(
1720 "approved_schema_unavailable",
1721 format!(
1722 "{}: approved old schema is missing or damaged",
1723 tuple.module
1724 ),
1725 )
1726 })?;
1727 let schema = snapshot
1728 .declarations
1729 .get(&tuple.module)
1730 .and_then(|declaration| {
1731 subc_config::Schema::new(declaration.schema.clone()).ok()
1732 })
1733 .ok_or_else(|| {
1734 GateError::new(
1735 "approved_schema_unavailable",
1736 format!(
1737 "{}: approved old schema is missing or damaged",
1738 tuple.module
1739 ),
1740 )
1741 })?;
1742 base_schemas.insert(tuple.module.clone(), schema);
1743 let view = snapshot.modules.get(&tuple.module).ok_or_else(|| {
1744 GateError::new(
1745 "config_gated",
1746 format!("{}: approved view is absent", tuple.module),
1747 )
1748 })?;
1749 let mut view = view.clone();
1750 view.generation = id;
1751 view.status = if versions.active == Some(id) {
1752 ConfigStatus::Active
1753 } else {
1754 ConfigStatus::Pending
1755 };
1756 bases.insert(tuple.module.clone(), view);
1757 }
1758 }
1759 }
1760 Ok(PreparedPlan {
1761 edits: None,
1762 projects: None,
1763 candidate,
1764 bases,
1765 base_schemas,
1766 kind,
1767 review_modules,
1768 rereview_modules,
1769 base_revision,
1770 active_generations,
1771 touched_modules,
1772 read_set,
1773 program_keys,
1774 observed_handles,
1775 })
1776 }
1777
1778 pub fn finish_plan(
1779 &self,
1780 mut prepared: PreparedPlan,
1781 review: impl FnOnce(&super::GateSnapshot, &super::GateSnapshot) -> Result<Changeset>,
1782 ) -> Result<ConfigPlanView> {
1783 let mut state = self.lock()?;
1784 Self::check_authority(
1785 &mut state,
1786 matches!(prepared.kind, PlanKind::Stamp | PlanKind::Unstamp),
1787 )?;
1788 let active_generations = if state.store.status().state == StoreState::Stamped {
1789 state
1790 .store
1791 .body()?
1792 .versions
1793 .iter()
1794 .filter(|(tuple, _)| prepared.touched_modules.contains(&tuple.module))
1795 .map(|(tuple, versions)| (tuple.clone(), versions.active))
1796 .collect()
1797 } else {
1798 BTreeMap::new()
1799 };
1800 let mut current = if prepared.edits.is_some() {
1801 self.edit_baseline(&mut state, Some(&prepared.touched_modules))
1802 } else {
1803 self.capture_modules(&mut state, &prepared.touched_modules)
1804 }
1805 .map_err(|_| GateError::stale())?;
1806 current
1807 .capture_programs(&prepared.program_keys)
1808 .map_err(|_| GateError::stale())?;
1809 if (prepared.edits.is_none()
1810 && state.store.status().base_revision != prepared.base_revision)
1811 || active_generations != prepared.active_generations
1812 || !prepared
1813 .read_set
1814 .matches(¤t.diagnostic.read_set(&prepared.touched_modules)?)
1815 {
1816 return Err(if prepared.edits.is_some() {
1817 GateError::new(
1818 "config_changed_since_review",
1819 "a touched module changed while the edits were reviewed",
1820 )
1821 } else {
1822 GateError::stale()
1823 });
1824 }
1825 if prepared.edits.is_some() {
1826 let touched = &prepared.touched_modules;
1829 for (key, input) in ¤t.diagnostic.inputs {
1830 if key.module().is_none_or(|module| !touched.contains(module)) {
1831 prepared
1832 .candidate
1833 .diagnostic
1834 .inputs
1835 .insert(key.clone(), input.clone());
1836 }
1837 }
1838 prepared.candidate.diagnostic.inputs.retain(|key, _| {
1839 key.module().is_some_and(|module| touched.contains(module))
1840 || current.diagnostic.inputs.contains_key(key)
1841 });
1842 prepared
1843 .candidate
1844 .modules
1845 .retain(|module, _| touched.contains(module));
1846 for (module, captured) in std::mem::take(&mut current.modules) {
1847 if !touched.contains(&module) {
1848 prepared.candidate.modules.insert(module, captured);
1849 }
1850 }
1851 }
1852 let delivery = DeliverySnapshot {
1853 daemon: Some(ConfigLayerSnapshot::file(
1854 "subc",
1855 ConfigLayer::User,
1856 prepared.candidate.daemon.path.to_string_lossy(),
1857 prepared.candidate.daemon.bytes.clone(),
1858 )),
1859 modules: prepared
1860 .candidate
1861 .modules
1862 .iter()
1863 .map(|(module, captured)| (module.clone(), captured.view.clone()))
1864 .collect(),
1865 declarations: prepared
1866 .candidate
1867 .modules
1868 .iter()
1869 .map(|(module, captured)| (module.clone(), captured.declaration.clone()))
1870 .collect(),
1871 ..DeliverySnapshot::default()
1872 };
1873 let mut handles = prepared.candidate.take_handles();
1874 handles.append(&mut prepared.observed_handles);
1875 let previous_delivery = if state.store.status().state == StoreState::Stamped {
1876 let body = state.store.body()?;
1877 body.generations
1878 .get(&placement::last_approved_generation(body))
1879 .and_then(|entry| entry.delivery.clone())
1880 } else if prepared.edits.as_ref().is_some_and(|edit| edit.unstamped) {
1881 Some(DeliverySnapshot {
1882 daemon: delivery.daemon.clone(),
1883 modules: prepared.bases.clone(),
1884 declarations: delivery.declarations.clone(),
1885 ..DeliverySnapshot::default()
1886 })
1887 } else {
1888 None
1889 };
1890 let mut active_fields = Vec::new();
1893 for (module, captured) in prepared.candidate.modules.iter().filter(|(module, _)| {
1894 matches!(prepared.kind, PlanKind::Change | PlanKind::Rollback(_))
1897 && prepared.touched_modules.contains(*module)
1898 }) {
1899 let active = if state.store.status().state == StoreState::Stamped {
1900 let body = state.store.body()?;
1901 body.versions
1902 .iter()
1903 .find(|(tuple, _)| tuple.module == *module && tuple.project.is_none())
1904 .and_then(|(_, versions)| versions.active)
1905 .and_then(|id| body.generations.get(&id))
1906 .and_then(|entry| entry.delivery.as_ref())
1907 } else {
1908 None
1909 };
1910 let base = active.and_then(|snapshot| snapshot.modules.get(module));
1911 let schema = active
1912 .and_then(|snapshot| snapshot.declarations.get(module))
1913 .map(|declaration| subc_config::Schema::new(declaration.schema.clone()))
1914 .transpose()
1915 .map_err(GateError::invalid)?;
1916 active_fields.extend(
1917 super::review::expected_fields(
1918 module,
1919 &captured.schema,
1920 base,
1921 schema.as_ref(),
1922 &captured.view,
1923 )?
1924 .into_values(),
1925 );
1926 }
1927 let OwnerState { gate, store, .. } = &mut *state;
1928 let view = gate.plan_reviewed_inner(
1929 store,
1930 prepared.kind,
1931 prepared.candidate.diagnostic,
1932 ¤t.diagnostic,
1933 super::ReviewRecord::Reviewed(&prepared.review_modules),
1934 prepared.edits,
1935 prepared.projects,
1936 |old, new| {
1937 let mut changeset = review(old, new)?;
1938 layer_file_rows(
1939 &mut changeset,
1940 old,
1941 new,
1942 previous_delivery.as_ref(),
1943 &delivery,
1944 )?;
1945 let mut activation = changeset.clone();
1946 activation.fields = active_fields;
1947 super::apply::bind_plan(&mut activation)?;
1948 if !changeset.apply_plan.is_object() {
1949 changeset.apply_plan = if changeset.apply_plan.is_null() {
1950 serde_json::json!({})
1951 } else {
1952 serde_json::json!({"review": changeset.apply_plan})
1953 };
1954 }
1955 changeset.apply_plan["module_transitions"] =
1956 activation.apply_plan["module_transitions"].clone();
1957 Ok(changeset)
1958 },
1959 )?;
1960 if let Err(error) = self.check_route_policy_authority(&view.plan.changeset) {
1961 gate.expire_plan(&view.digest);
1962 return Err(error);
1963 }
1964 gate.bind_delivery(&view.digest, delivery)?;
1965 state.reviewed(&view.digest, Instant::now());
1966 state
1967 .retained_plan_files
1968 .insert(view.digest.clone(), handles);
1969 Ok(view)
1970 }
1971
1972 pub fn begin_approval(
1973 &self,
1974 digest: &Digest,
1975 facts: &ApprovalFacts,
1976 ) -> Result<ApprovalChallenge> {
1977 self.begin_approval_for_request(digest, facts, None)
1978 }
1979
1980 pub(crate) fn begin_approval_for_request(
1981 &self,
1982 digest: &Digest,
1983 facts: &ApprovalFacts,
1984 request: Option<&ApprovalRequest>,
1985 ) -> Result<ApprovalChallenge> {
1986 #[cfg(test)]
1987 struct Completion<'a>(&'a std::sync::atomic::AtomicUsize);
1988 #[cfg(test)]
1989 impl Drop for Completion<'_> {
1990 fn drop(&mut self) {
1991 self.0.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
1992 }
1993 }
1994 #[cfg(test)]
1995 let _completed = Completion(&self.begin_approval_completions);
1996 #[cfg(test)]
1997 if let Some(hook) = self.begin_approval_hook.lock().unwrap().take() {
1998 hook();
1999 }
2000 let mut state = self.lock()?;
2001 if let Some(request) = request {
2002 request.ensure_live()?;
2003 }
2004 if state.expired_plans.contains(digest) {
2005 return Err(GateError::new(
2006 "plan_expired",
2007 "configuration plan exceeded its one-hour idle lifetime",
2008 ));
2009 }
2010 Self::check_authority(&mut state, true)?;
2011 let modules = state.gate.plan_modules(digest)?;
2012 let program_keys = state.gate.plan_program_keys(digest)?;
2013 let mut current = if state
2014 .gate
2015 .plans
2016 .get(digest)
2017 .is_some_and(|plan| plan.edits.is_some())
2018 {
2019 self.edit_baseline(&mut state, Some(&modules))
2020 } else {
2021 self.capture_modules(&mut state, &modules)
2022 }
2023 .map_err(|_| GateError::stale())?;
2024 current
2025 .capture_programs(&program_keys)
2026 .map_err(|_| GateError::stale())?;
2027 let facts = state.with_desktop_view(digest, facts);
2028 let OwnerState { gate, store, .. } = &mut *state;
2029 if let Some(request) = request {
2030 request.ensure_live()?;
2031 }
2032 let challenge = gate.begin_approval(digest, store, ¤t.diagnostic, &facts)?;
2033 state.reviewed(digest, Instant::now());
2034 Ok(challenge)
2035 }
2036
2037 pub(crate) async fn approval_commit_gates(
2040 self: &std::sync::Arc<Self>,
2041 attempt: u64,
2042 ) -> Result<Vec<tokio::sync::OwnedMutexGuard<()>>> {
2043 let modules = self
2044 .on_blocking(move |owner| owner.lock()?.gate.approval_gate_modules(attempt))
2045 .await?;
2046 let mut guards = Vec::with_capacity(modules.len());
2047 for module in modules {
2048 guards.push(self.module_gate(&module)?.lock_owned().await);
2049 }
2050 Ok(guards)
2051 }
2052
2053 pub fn finish_approval(
2054 &self,
2055 attempt: u64,
2056 facts: &ApprovalFacts,
2057 reply: ApprovalReply,
2058 now_ms: u64,
2059 ) -> Result<u64> {
2060 self.finish_approval_with_commit_window(
2063 attempt,
2064 facts,
2065 reply,
2066 now_ms,
2067 None,
2068 ApprovalRequest::for_attempt(attempt),
2069 )
2070 }
2071
2072 pub(crate) fn finish_approval_with_commit_window(
2073 &self,
2074 attempt: u64,
2075 facts: &ApprovalFacts,
2076 reply: ApprovalReply,
2077 now_ms: u64,
2078 window: Option<std::sync::Arc<ApprovalCommitWindow>>,
2079 cancellation: std::sync::Arc<ApprovalRequest>,
2080 ) -> Result<u64> {
2081 if cancellation.attempt() != attempt {
2082 return Err(GateError::new(
2083 "config_unavailable",
2084 "approval request witness does not match its attempt",
2085 ));
2086 }
2087 let mut state = self.lock()?;
2088 let digest = state.gate.approval_digest(attempt)?;
2089 let declarations_only = state
2090 .gate
2091 .plans
2092 .get(&digest)
2093 .is_some_and(|plan| plan.development_approval.is_some());
2094 state.reviewed(&digest, Instant::now());
2095 let modules = state.gate.approval_modules(attempt)?;
2096 let user_modules = state.gate.plans[&digest]
2097 .targets()?
2098 .into_iter()
2099 .filter(|tuple| tuple.project.is_none())
2100 .map(|tuple| tuple.module)
2101 .collect();
2102 let program_keys = state.gate.plan_program_keys(&digest)?;
2103 let edit_plan = state
2106 .gate
2107 .plans
2108 .get(&digest)
2109 .and_then(|plan| plan.edits.clone());
2110 let current = match Self::check_authority(&mut state, true).and_then(|_| {
2111 let mut current = if edit_plan.is_some() {
2112 self.edit_baseline(&mut state, Some(&modules))
2113 } else {
2114 self.capture_modules(&mut state, &modules)
2115 }
2116 .map_err(|_| GateError::stale())?;
2117 current
2118 .capture_programs(&program_keys)
2119 .map_err(|_| GateError::stale())?;
2120 Ok(current)
2121 }) {
2122 Ok(current) => current,
2123 Err(error) => {
2124 state.gate.cancel_attempt(attempt);
2125 return Err(error);
2126 }
2127 };
2128 let facts = state.with_desktop_view(&digest, facts);
2129 self.drain_canceled_approvals(&mut state);
2130 self.drain_disconnections(&mut state);
2131 #[cfg(test)]
2132 if let Some(hook) = state.after_approval_drain_hook.take() {
2133 hook();
2134 }
2135 let was_unstamped = state.store.status().state == StoreState::Unstamped;
2136 let was_recovery = state.recovery_exit_hold
2137 || matches!(
2138 state.store.status().state,
2139 StoreState::StoreMissing | StoreState::StoreUnverified
2140 );
2141 let unstamp_hints = recovery::changed_file_views(self, &mut state, ¤t);
2142 #[cfg(test)]
2143 let publication_hook = state.publication_hook.take();
2144 #[cfg(test)]
2145 let prepublication_hook = state.prepublication_hook.take();
2146 let publication_before = state.store.publication_sequence();
2147 let OwnerState {
2148 gate,
2149 store,
2150 route_policy_receipts,
2151 installed_route_policies,
2152 delivery,
2153 ..
2154 } = &mut *state;
2155 let result = gate.finish_approval_with_precommit(
2156 attempt,
2157 reply,
2158 store,
2159 ¤t.diagnostic,
2160 &facts,
2161 now_ms,
2162 || {
2163 #[cfg(test)]
2164 if let Some(hook) = prepublication_hook {
2165 hook();
2166 }
2167 if let Some(window) = window {
2168 window.begin_publication()?;
2169 }
2170 {
2171 let _index = self.approval_request_index.lock().map_err(|_| {
2174 GateError::new(
2175 "config_unavailable",
2176 "approval cancellation index is poisoned",
2177 )
2178 })?;
2179 cancellation.claim_publication()?;
2180 }
2181 if !declarations_only {
2182 route_policy::restore_superseded(
2183 route_policy_receipts,
2184 installed_route_policies,
2185 &user_modules,
2186 delivery,
2187 );
2188 }
2189 #[cfg(test)]
2190 if let Some(hook) = publication_hook {
2191 hook();
2192 }
2193 Ok(())
2194 },
2195 );
2196 let committed_this_call = state.store.publication_sequence() != publication_before;
2197 if committed_this_call {
2198 if let Some(edit_plan) = edit_plan {
2199 for file in &edit_plan.files {
2200 let _ = file.write_back();
2201 }
2202 let _ = self.observe_proposal(&mut state);
2205 }
2206 }
2207 let stamped_files = committed_this_call
2208 && (was_unstamped || was_recovery)
2209 && state.store.body().is_ok_and(|body| {
2210 body.generations
2211 .get(&body.last_generation)
2212 .is_some_and(|entry| {
2213 entry.generation.plan_digest == digest
2214 && entry.kind == crate::config_store::CommitKind::Stamp
2215 })
2216 });
2217 if result.is_ok() {
2218 state.plan_deadlines.remove(&digest);
2219 state.retained_plan_files.remove(&digest);
2220 state.desktop_views.retain(|_, (shown, _)| shown != &digest);
2221 }
2222 let unstamped = result.is_ok() && state.store.status().state == StoreState::Unstamped;
2223 let committed_exit = state
2224 .store
2225 .loaded_admission_state()
2226 .1
2227 .generations
2228 .iter()
2229 .next_back()
2230 .filter(|(_, entry)| {
2231 committed_this_call
2232 && entry.generation.plan_digest == digest
2233 && entry.kind != crate::config_store::CommitKind::DeclarationApproval
2234 && (was_recovery
2235 || state.store.loaded_admission_state().1.stamped
2236 || entry.kind == crate::config_store::CommitKind::Unstamp)
2237 })
2238 .map(|(generation, entry)| {
2239 (
2240 *generation,
2241 entry.kind == crate::config_store::CommitKind::Unstamp,
2242 )
2243 });
2244 if committed_this_call && was_recovery {
2245 state.authority_incarnation = std::sync::Arc::new(());
2246 }
2247 if let Some((generation, unstamp)) = committed_exit {
2248 state.authority_exit = Some(generation);
2249 state.recovery_exit_hold = was_recovery;
2250 if was_recovery || unstamp {
2251 state
2252 .delivery
2253 .reset_for_authority_exit(if unstamp { generation } else { 0 });
2254 }
2255 if unstamp {
2256 state.stamp_channel_cutover = false;
2257 state.reconciled_entries.clear();
2258 state.unstamp_hints.extend(unstamp_hints);
2259 }
2260 } else if committed_this_call {
2261 state.authority_exit = None;
2262 }
2263 if stamped_files {
2264 state.stamp_channel_cutover = true;
2265 let connections: Vec<_> = state.active_declarations.values().copied().collect();
2266 state.delivery.remember_stamp_connections(connections);
2267 }
2268 drop(state);
2269 if unstamped {
2270 self.retire_unstamped_bindings();
2271 }
2272 result
2273 }
2274
2275 #[cfg(all(test, unix))]
2276 pub(crate) fn set_publication_hook(&self, hook: impl FnOnce() + Send + 'static) {
2277 self.inner.lock().unwrap().publication_hook = Some(Box::new(hook));
2278 }
2279
2280 #[cfg(all(test, unix))]
2281 pub(crate) fn set_prepublication_hook(&self, hook: impl FnOnce() + Send + 'static) {
2282 self.inner.lock().unwrap().prepublication_hook = Some(Box::new(hook));
2283 }
2284
2285 #[cfg(all(test, unix))]
2286 pub(crate) fn set_after_approval_drain_hook(&self, hook: impl FnOnce() + Send + 'static) {
2287 self.inner.lock().unwrap().after_approval_drain_hook = Some(Box::new(hook));
2288 }
2289
2290 #[cfg(all(test, unix))]
2291 pub(crate) fn approval_request_count_for_test(&self) -> usize {
2292 self.approval_request_index.lock().unwrap().len()
2293 }
2294
2295 #[cfg(all(test, unix))]
2296 pub(crate) fn poison_approval_request_index_for_test(&self) {
2297 let poisoned = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
2298 let _guard = self.approval_request_index.lock().unwrap();
2299 panic!("injected approval index poison");
2300 }));
2301 assert!(poisoned.is_err());
2302 }
2303
2304 #[cfg(all(test, unix))]
2305 pub(crate) fn pause_next_approval_claim_for_test(
2306 &self,
2307 ) -> (
2308 tokio::sync::oneshot::Receiver<()>,
2309 tokio::sync::oneshot::Sender<()>,
2310 ) {
2311 let (reached, observed) = tokio::sync::oneshot::channel();
2312 let (release, wait) = tokio::sync::oneshot::channel();
2313 *self.approval_claim_pause.lock().unwrap() = Some(ApprovalClaimPause {
2314 reached,
2315 release: wait,
2316 });
2317 (observed, release)
2318 }
2319
2320 #[cfg(all(test, unix))]
2321 pub(crate) async fn pause_approval_claim_for_test(&self) {
2322 let pause = self.approval_claim_pause.lock().unwrap().take();
2323 if let Some(pause) = pause {
2324 let _ = pause.reached.send(());
2325 pause.release.await.unwrap();
2326 }
2327 }
2328
2329 #[cfg(any(all(test, unix), feature = "test-support"))]
2332 pub(crate) fn set_os_prompt_policy_for_tests(&self) {
2333 self.os_prompt_policy
2334 .store(true, std::sync::atomic::Ordering::Relaxed);
2335 }
2336
2337 #[cfg(any(test, feature = "test-support"))]
2338 pub(crate) fn os_prompt_policy_for_tests(&self) -> bool {
2339 self.os_prompt_policy
2340 .load(std::sync::atomic::Ordering::Relaxed)
2341 }
2342
2343 pub fn status(&self) -> Result<subc_control::config::ConfigStatus> {
2344 let mut state = self.lock()?;
2345 let mut current_snapshot = None;
2346 let mut observation = None;
2347 state.retry_anchor(true);
2348 let verified = state.store.check().is_ok();
2349 if verified
2350 && !state.recovery_exit_hold
2351 && !state.store.status().anchor_pending
2352 && matches!(
2353 state.store.status().state,
2354 StoreState::Stamped | StoreState::Unstamped
2355 )
2356 {
2357 observation = Some(self.observe_proposal(&mut state)?);
2358 current_snapshot = state.observed_snapshot.clone();
2359 }
2360 let store_status = state.store.status();
2361 let mut status = subc_control::config::ConfigStatus::default();
2362 status.state = match store_status.state {
2363 StoreState::Stamped => "stamped",
2364 StoreState::Unstamped => "unstamped",
2365 StoreState::StoreMissing => "store_missing",
2366 StoreState::StoreUnverified => "store_unverified",
2367 }
2368 .into();
2369 if state.recovery_exit_hold {
2370 if store_status.state != StoreState::Stamped {
2371 status.state = "store_unverified".into();
2372 }
2373 status
2374 .warnings
2375 .push("approved recovery exit is waiting for reconciliation".into());
2376 }
2377 status.integrity = match store_status.integrity {
2378 crate::config_store::IntegrityMode::DigestOnly => "digest_only",
2379 crate::config_store::IntegrityMode::Sealed => "sealed",
2380 }
2381 .into();
2382 status.revision = store_status.revision;
2383 status.base_revision = store_status.base_revision;
2384 status.anchor_pending = store_status.anchor_pending;
2385 status.root_io = self.capturer.projects.root_io_health();
2386 status.ungated_inputs = self.startup_overrides.clone();
2387 #[cfg(feature = "test-support")]
2388 if state.store.uses_config_gate_test_seam() {
2389 status
2390 .development_switches
2391 .push("SUBC_TEST_CONFIG_GATE".into());
2392 }
2393 status.warnings.extend(store_status.warnings);
2394 if cfg!(feature = "dev-desktop-approval") {
2395 status
2396 .development_switches
2397 .push("dev-desktop-approval".into());
2398 }
2399 #[cfg(feature = "dev-desktop-approval")]
2400 if let Some(floor) = crate::operator_apps::development_floor_diagnostic() {
2401 status.development_switches.push(floor);
2402 }
2403 if cfg!(feature = "dev-placement") {
2404 status.development_switches.push("dev-placement".into());
2405 }
2406 let declared: Vec<String> = Self::declarations(&mut state)
2407 .map(|declarations| declarations.into_keys().collect())
2408 .unwrap_or_default();
2409 if let Ok(body) = state.store.body() {
2410 if body.stamped {
2411 for (module, rereview) in
2412 super::reviewed_build::pending(body, &declared).unwrap_or_default()
2413 {
2414 status.warnings.push(match rereview {
2415 super::reviewed_build::Rereview::WaitingForProgram => format!(
2416 "module {module}: needs configuration re-review: its approved program has not reviewed its approved layers; the re-review waits until that program is running and active"
2417 ),
2418 super::reviewed_build::Rereview::Ready => format!(
2419 "module {module}: needs configuration re-review: its approved program has not reviewed its approved layers; the next configuration plan re-reviews them with the running program"
2420 ),
2421 });
2422 }
2423 }
2424 if body.stamped {
2425 current_snapshot = super::GateSnapshot::from_store(&body.approved).ok();
2426 }
2427 for entry in body.generations.values().rev().take_while(|entry| {
2428 matches!(
2429 entry.kind,
2430 crate::config_store::CommitKind::Development
2431 | crate::config_store::CommitKind::DeclarationApproval
2432 )
2433 }) {
2434 if entry.kind != crate::config_store::CommitKind::Development {
2435 continue;
2436 }
2437 status.warnings.push(format!(
2438 "development generation {}: development placement (no approval)",
2439 entry.generation.id
2440 ));
2441 }
2442 status.approval_channels = body
2443 .generations
2444 .iter()
2445 .map(|(id, entry)| {
2446 subc_control::config::ConfigApprovalRecord::new(
2447 *id,
2448 entry.generation.approval_channel,
2449 )
2450 })
2451 .chain(body.pruned.iter().map(|(id, entry)| {
2452 subc_control::config::ConfigApprovalRecord::new(*id, entry.approval_channel)
2453 }))
2454 .collect();
2455 status
2456 .approval_channels
2457 .sort_by_key(|record| record.generation);
2458 status.pending_proposals = u64::from(body.proposal.is_some());
2459 for (tuple, versions) in &body.versions {
2460 if let Some(generation) = versions.pending {
2461 let entry = body.generations.get(&generation);
2462 let transition = entry.and_then(|entry| {
2463 super::apply::Transition::for_module(
2464 &entry.generation.changeset,
2465 &tuple.module,
2466 )
2467 .ok()
2468 });
2469 status.approved_but_inactive.push(serde_json::json!({
2470 "module_id":tuple.module,"project_id":tuple.project,"generation":generation,
2471 "digest":entry.map(|entry| &entry.generation.plan_digest),
2472 "waiting_for":match transition {
2473 Some(super::apply::Transition::DaemonRestart) => "daemon_restart",
2474 Some(super::apply::Transition::NextSupervision) => "next_supervision",
2475 _ => "delivery",
2476 },
2477 }));
2478 }
2479 }
2480 }
2481 if let Some(snapshot) = current_snapshot {
2482 status_inputs::report_snapshot(&snapshot, &mut status);
2483 }
2484 if let Some(captured) = observation {
2485 captured.report_errors(&mut status);
2486 }
2487 status.gated_modules = admission::AdmissionCache::from_state(&state).held_modules();
2488 if state.store.loaded_admission_state().0 == StoreState::Stamped {
2489 let declarations: Vec<_> = state
2490 .declarations
2491 .iter()
2492 .map(|(connection, (module, _))| (*connection, module.clone()))
2493 .collect();
2494 for (connection, module) in declarations {
2495 let reply = self.module_get_locked(
2498 &mut state,
2499 connection,
2500 &module,
2501 subc_protocol::config::ConfigGetRequest::new(),
2502 false,
2503 );
2504 if let Ok(reply) = &reply {
2505 Self::report_declaration_pending(
2506 &state,
2507 connection,
2508 &module,
2509 reply,
2510 &mut status,
2511 );
2512 }
2513 if reply.is_err_and(|error| error.code == "config_gated") {
2514 status.gated_modules.push(module);
2515 }
2516 }
2517 status.gated_modules.sort();
2518 status.gated_modules.dedup();
2519 }
2520 Ok(status)
2521 }
2522
2523 fn report_declaration_pending(
2524 state: &OwnerState,
2525 connection: ConnectionId,
2526 module: &str,
2527 reply: &subc_protocol::config::ConfigGetReply,
2528 status: &mut subc_control::config::ConfigStatus,
2529 ) {
2530 if state.active_declarations.get(module) != Some(&connection) {
2531 return;
2532 }
2533 if let Some(marker) = &reply.declaration_pending {
2534 status
2535 .declaration_pending
2536 .insert(module.into(), marker.clone());
2537 if let Some(generation) = state.delivery.fallback_applied.get(&connection) {
2538 if reply
2539 .active
2540 .as_ref()
2541 .is_some_and(|view| view.generation == *generation)
2542 {
2543 status.warnings.push(format!("module {module}: running last approved settings (generation {generation}); declaration awaits approval"));
2544 }
2545 }
2546 }
2547 }
2548
2549 pub fn history(&self) -> Result<(Vec<subc_config::Generation>, Vec<serde_json::Value>)> {
2550 let mut state = self.lock()?;
2551 state.retry_anchor(true);
2552 state.store.check()?;
2553 let body = state.store.body()?;
2554 Ok((
2555 body.generations
2556 .values()
2557 .map(|entry| entry.generation.clone())
2558 .collect(),
2559 body.pruned
2560 .values()
2561 .map(serde_json::to_value)
2562 .collect::<std::result::Result<_, _>>()
2563 .map_err(GateError::invalid)?,
2564 ))
2565 }
2566
2567 pub fn approved_snapshot(&self) -> Result<DeliverySnapshot> {
2570 let mut state = self.lock()?;
2571 state.store.delivery_ready()?;
2572 state
2573 .store
2574 .body()?
2575 .generations
2576 .values()
2577 .next_back()
2578 .and_then(|entry| entry.delivery.clone())
2579 .ok_or_else(|| GateError::new("config_gated", "approved delivery snapshot is absent"))
2580 }
2581
2582 pub fn approved_rollback_commands(&self, generation: u64) -> Result<ApprovedRollbackCommands> {
2590 let mut state = self.lock()?;
2591 state.store.delivery_ready()?;
2592 let configuration = state.store.rollback_configuration(generation)?;
2593 let entry = &state.store.body()?.generations[&generation];
2594 if entry.kind != crate::config_store::CommitKind::Rollback {
2595 return Err(GateError::new(
2596 "rollback_generation_required",
2597 "generation is not an approved rollback",
2598 ));
2599 }
2600 let daemon = entry
2601 .delivery
2602 .as_ref()
2603 .and_then(|snapshot| snapshot.daemon.clone())
2604 .ok_or_else(|| {
2605 GateError::new(
2606 "rollback_snapshot_unavailable",
2607 "approved rollback command input is absent",
2608 )
2609 })?;
2610 let snapshot = super::GateSnapshot::from_store(&configuration)?;
2611 let mut programs = BTreeMap::new();
2612 for (key, identity) in snapshot.inputs {
2613 if let super::InputKey::Program { module, path } = key {
2614 if programs
2615 .insert(module, ApprovedRollbackProgram { path, identity })
2616 .is_some()
2617 {
2618 return Err(GateError::new(
2619 "rollback_snapshot_unavailable",
2620 "rollback contains conflicting program identities",
2621 ));
2622 }
2623 }
2624 }
2625 Ok(ApprovedRollbackCommands {
2626 generation,
2627 daemon,
2628 programs,
2629 })
2630 }
2631}