Skip to main content

rpi_cli/host/
daemon_administration.rs

1//! Daemon-owned administrative authority. Only private Host configuration or a
2//! trusted Rust owner constructs these inputs; never deserialize a peer grant.
3use super::{
4    administration::{
5        AdministrativeCoordinator, AdministrativeError, AdministrativeGrant,
6        AdministrativePermissions, MAX_ADMINISTRATIVE_JOBS,
7    },
8    daemon::DaemonError,
9    lifecycle::{LifecycleReceipt, LifecycleRequest},
10    recovery::Bindings,
11    service::HostService,
12    AgentId, ControlScopeId, HostStartupAgent, ProfileRef, TrustedProfileSet, MAX_TRUSTED_PROFILES,
13};
14use std::{
15    collections::{BTreeMap, BTreeSet},
16    num::NonZeroUsize,
17    sync::Arc,
18};
19
20/// Trusted native assembly input, not a wire DTO. Startup profiles are added to
21/// the same frozen set; do not duplicate them here to grant restore authority.
22pub struct DaemonAdministrationConfig {
23    pub scope: ControlScopeId,
24    pub allowed_agents: BTreeSet<AgentId>,
25    pub permissions: AdministrativePermissions,
26    pub max_jobs: NonZeroUsize,
27    /// Configured for dynamic use, never automatically started or registered.
28    pub profiles: Vec<HostStartupAgent>,
29}
30
31/// Cloneable native handle with fixed authority. No caller can supply a grant,
32/// credentials, tool policy, alternate scope or mutable profile configuration.
33/// This is not yet an IPC handler and grants no listener/daemon exit proof.
34#[derive(Clone)]
35pub struct DaemonAdministration {
36    coordinator: AdministrativeCoordinator,
37    grant: Arc<AdministrativeGrant>,
38    references: Arc<[ProfileRef]>,
39}
40impl DaemonAdministration {
41    pub fn scope(&self) -> ControlScopeId {
42        self.grant.scope()
43    }
44    pub fn profile_references(&self) -> impl ExactSizeIterator<Item = ProfileRef> + '_ {
45        self.references.iter().copied()
46    }
47    pub(super) async fn prepare_attach(
48        &self,
49        id: AgentId,
50    ) -> Result<super::PreparedProfile, super::ordinary::BackendError> {
51        let reference = self
52            .profile_references()
53            .find(|reference| reference.agent_id == id && self.grant.can_restore(id))
54            .ok_or(super::ordinary::BackendError::Binding(
55                "Session attach Restore is not authorized",
56            ))?;
57        self.coordinator.prepare_attach(reference).await
58    }
59    pub fn active_jobs(&self) -> usize {
60        self.coordinator.active_jobs()
61    }
62    pub(crate) fn stop_completed(&self) -> tokio_util::sync::CancellationToken {
63        self.coordinator.stop_completed()
64    }
65    pub async fn execute(
66        &self,
67        request: LifecycleRequest,
68    ) -> Result<LifecycleReceipt, AdministrativeError> {
69        self.coordinator.execute(&self.grant, request).await
70    }
71    pub async fn receipt(
72        &self,
73        request: &LifecycleRequest,
74    ) -> Result<Option<LifecycleReceipt>, AdministrativeError> {
75        self.coordinator.receipt(&self.grant, request).await
76    }
77}
78
79pub(crate) struct PreparedDaemonAdministration {
80    profiles: TrustedProfileSet,
81    startup: Vec<ProfileRef>,
82    grant: AdministrativeGrant,
83    visible: Vec<ProfileRef>,
84    restorable: BTreeSet<AgentId>,
85    max_jobs: NonZeroUsize,
86}
87impl DaemonAdministrationConfig {
88    /// All configuration and cross-set aliases are checked before catalog open,
89    /// Session creation, writer acquisition, Agent registration or server bind.
90    pub(crate) async fn prepare(
91        self,
92        mut startup: Vec<HostStartupAgent>,
93    ) -> Result<PreparedDaemonAdministration, DaemonError> {
94        if self.max_jobs.get() > MAX_ADMINISTRATIVE_JOBS
95            || startup.len().saturating_add(self.profiles.len()) > MAX_TRUSTED_PROFILES
96        {
97            return Err(DaemonError::Administration);
98        }
99        let grant =
100            AdministrativeGrant::new(self.scope, self.allowed_agents.clone(), self.permissions)
101                .map_err(|_| DaemonError::Administration)?;
102        let startup_ids: Vec<_> = startup.iter().map(|agent| agent.spec.id).collect();
103        startup.extend(self.profiles);
104        let profiles = TrustedProfileSet::freeze(startup)
105            .await
106            .map_err(|_| DaemonError::Administration)?;
107        let references: BTreeMap<_, _> = profiles
108            .references()
109            .map(|reference| (reference.agent_id, reference))
110            .collect();
111        if !self
112            .allowed_agents
113            .iter()
114            .all(|id| references.contains_key(id))
115        {
116            return Err(DaemonError::Administration);
117        }
118        let visible = references
119            .values()
120            .filter(|reference| self.allowed_agents.contains(&reference.agent_id))
121            .copied()
122            .collect();
123        let startup = startup_ids
124            .into_iter()
125            .map(|id| {
126                references
127                    .get(&id)
128                    .copied()
129                    .ok_or(DaemonError::Administration)
130            })
131            .collect::<Result<_, _>>()?;
132        let restorable = if self.permissions.restore {
133            self.allowed_agents
134        } else {
135            BTreeSet::new()
136        };
137        Ok(PreparedDaemonAdministration {
138            profiles,
139            startup,
140            grant,
141            visible,
142            restorable,
143            max_jobs: self.max_jobs,
144        })
145    }
146}
147impl PreparedDaemonAdministration {
148    pub(crate) async fn start(&self, service: &HostService) -> Result<(), DaemonError> {
149        super::daemon::start_frozen_agents(service, &self.profiles, &self.startup).await
150    }
151    pub(super) async fn start_recovery(
152        &self,
153        service: &HostService,
154        bindings: &Bindings,
155        mini_count: usize,
156    ) -> Result<Vec<AgentId>, DaemonError> {
157        super::daemon::start_recovery(
158            service,
159            &self.profiles,
160            &self.startup,
161            &self.restorable,
162            bindings,
163            mini_count,
164        )
165        .await
166    }
167    pub(crate) fn assemble(
168        self,
169        service: HostService,
170    ) -> Result<DaemonAdministration, DaemonError> {
171        Ok(DaemonAdministration {
172            coordinator: AdministrativeCoordinator::new(service, self.profiles, self.max_jobs)
173                .map_err(|_| DaemonError::Administration)?,
174            grant: Arc::new(self.grant),
175            references: self.visible.into(),
176        })
177    }
178}
179
180#[cfg(test)]
181#[path = "daemon_administration_tests.rs"]
182mod tests;