Skip to main content

adk_server/awp/
control.rs

1//! The edge's modes, the kill switch and the signed site status (spec 3.5 §7.5, §7.9, A-I12).
2//!
3//! | Mode | Capabilities | Status published |
4//! |---|---|---|
5//! | [`EdgeMode::Serving`] | Every visible capability | `operational` |
6//! | [`EdgeMode::ReadOnly`] | `read_only` capabilities; the rest answer `503 read_only` with the status | `read_only` with the reason |
7//! | [`EdgeMode::Off`] | None: every edge route answers `404`, leaving only the static content | — |
8//!
9//! The owner's kill switch ([`GovernanceControl`]) puts a serving edge in read-only mode with
10//! reason `kill_switch` for as long as it is frozen (A-I12).
11
12use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
13use std::sync::{Arc, OnceLock, RwLock};
14
15use adk_awp::signing::jws::{DocumentSigner, sign};
16use adk_awp::v2::store::{StatusStore, StoreError};
17use adk_core::GovernanceControl;
18use awp_types::{Proof, ReasonCode, SiteState, SiteStatus};
19use chrono::Utc;
20
21/// The reason code of the status the kill switch publishes (AWP 2.0 §10.3).
22pub const KILL_SWITCH_REASON: &str = "kill_switch";
23
24/// How the edge answers (spec 3.5 §7.9).
25#[derive(Debug, Clone, PartialEq, Eq)]
26#[non_exhaustive]
27pub enum EdgeMode {
28    /// Every visible capability answers.
29    Serving,
30    /// Only `read_only` capabilities answer; the rest answer `503 read_only` with the signed
31    /// status document.
32    ReadOnly {
33        /// The status `reasonCode`, a snake_case code such as `drift_detected`.
34        reason: String,
35    },
36    /// The edge is off: its routes answer `404` and only the static content remains.
37    Off,
38}
39
40impl EdgeMode {
41    /// Read-only mode for `reason`.
42    pub fn read_only(reason: impl Into<String>) -> Self {
43        Self::ReadOnly { reason: reason.into() }
44    }
45}
46
47/// Why the edge could not publish a status (spec 3.5 §7.5).
48#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
49#[non_exhaustive]
50pub enum StatusError {
51    /// The receipt key could not sign the document.
52    #[error("the edge's receipt key could not sign the status: {0}")]
53    Signing(String),
54    /// The status store failed.
55    #[error(transparent)]
56    Store(#[from] StoreError),
57}
58
59/// Shared state behind the edge's mode, kill switch and status.
60pub(crate) struct EdgeControl {
61    mode: RwLock<EdgeMode>,
62    governance: OnceLock<GovernanceControl>,
63    status: Arc<dyn StatusStore>,
64    receipt: Arc<dyn DocumentSigner>,
65    release_seq: AtomicU64,
66    frozen_seen: AtomicBool,
67    events: OnceLock<super::events::EdgeEvents>,
68}
69
70impl std::fmt::Debug for EdgeControl {
71    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
72        f.debug_struct("EdgeControl").field("mode", &self.mode()).finish_non_exhaustive()
73    }
74}
75
76impl EdgeControl {
77    pub(crate) fn new(status: Arc<dyn StatusStore>, receipt: Arc<dyn DocumentSigner>) -> Self {
78        Self {
79            mode: RwLock::new(EdgeMode::Serving),
80            governance: OnceLock::new(),
81            status,
82            receipt,
83            release_seq: AtomicU64::new(0),
84            frozen_seen: AtomicBool::new(false),
85            events: OnceLock::new(),
86        }
87    }
88
89    /// Attaches the owner's kill switch unless one is attached; returns whether it was.
90    pub(crate) fn attach_governance(&self, control: GovernanceControl) -> bool {
91        self.governance.set(control).is_ok()
92    }
93
94    /// Publishes `site.status.changed` on every transition through `events`.
95    pub(crate) fn attach_events(&self, events: super::events::EdgeEvents) {
96        let _ = self.events.set(events);
97    }
98
99    pub(crate) fn governance(&self) -> Option<&GovernanceControl> {
100        self.governance.get()
101    }
102
103    pub(crate) fn mode(&self) -> EdgeMode {
104        self.mode.read().unwrap_or_else(std::sync::PoisonError::into_inner).clone()
105    }
106
107    pub(crate) fn set_release_seq(&self, seq: u64) {
108        self.release_seq.store(seq, Ordering::SeqCst);
109    }
110
111    /// Whether the owner's kill switch is engaged.
112    pub(crate) fn frozen(&self) -> bool {
113        self.governance.get().is_some_and(GovernanceControl::is_frozen)
114    }
115
116    pub(crate) fn is_off(&self) -> bool {
117        matches!(self.mode(), EdgeMode::Off)
118    }
119
120    /// Whether non-`read_only` capabilities are refused: the kill switch or read-only mode.
121    pub(crate) fn is_read_only(&self) -> bool {
122        self.frozen() || matches!(self.mode(), EdgeMode::ReadOnly { .. })
123    }
124
125    /// Signs and stores a status in `state` for `reason` (spec 3.5 §7.5).
126    pub(crate) async fn publish(
127        &self,
128        state: SiteState,
129        reason: Option<&str>,
130    ) -> Result<SiteStatus, StatusError> {
131        let mut status = SiteStatus::new(state, Utc::now(), Proof::eddsa(self.receipt.kid(), ""));
132        status.reason_code = reason.map(|reason| ReasonCode(reason.to_owned()));
133        let seq = self.release_seq.load(Ordering::SeqCst);
134        status.release_seq = (seq > 0).then_some(seq);
135        status.proof = sign(&status, self.receipt.as_ref())
136            .await
137            .map_err(|error| StatusError::Signing(error.to_string()))?;
138        let previous = self.status.set(status.clone()).await?;
139        let changed = previous.as_ref().is_none_or(|previous| {
140            previous.state != status.state || previous.reason_code != status.reason_code
141        });
142        if changed && let Some(events) = self.events.get() {
143            let change = awp_types::StatusChanged {
144                previous: previous.map(|previous| previous.state),
145                status: status.clone(),
146            };
147            if let Err(error) = events.status_changed(change).await {
148                tracing::warn!(error = %error, "awp site.status.changed not published");
149            }
150        }
151        tracing::info!(
152            awp.status = ?status.state,
153            awp.reason = reason.unwrap_or(""),
154            "awp edge status published"
155        );
156        Ok(status)
157    }
158
159    /// Switches the mode and publishes the status it implies; `Off` publishes nothing.
160    pub(crate) async fn set_mode(&self, mode: EdgeMode) -> Result<Option<SiteStatus>, StatusError> {
161        *self.mode.write().unwrap_or_else(std::sync::PoisonError::into_inner) = mode.clone();
162        if self.frozen() {
163            return Ok(None);
164        }
165        match mode {
166            EdgeMode::Serving => self.publish(SiteState::Operational, None).await.map(Some),
167            EdgeMode::ReadOnly { reason } => {
168                self.publish(SiteState::ReadOnly, Some(&reason)).await.map(Some)
169            }
170            EdgeMode::Off => Ok(None),
171        }
172    }
173
174    /// Publishes the kill switch's status when it engages, and the mode's status when it
175    /// lifts (A-I12). Cheap when nothing changed.
176    pub(crate) async fn sync_kill_switch(&self) {
177        let frozen = self.frozen();
178        if self.frozen_seen.swap(frozen, Ordering::SeqCst) == frozen {
179            return;
180        }
181        let published = if frozen {
182            tracing::warn!("awp edge is read-only: the owner's kill switch is engaged");
183            self.publish(SiteState::ReadOnly, Some(KILL_SWITCH_REASON)).await
184        } else {
185            match self.mode() {
186                EdgeMode::ReadOnly { reason } => {
187                    self.publish(SiteState::ReadOnly, Some(&reason)).await
188                }
189                EdgeMode::Serving | EdgeMode::Off => {
190                    self.publish(SiteState::Operational, None).await
191                }
192            }
193        };
194        if let Err(error) = published {
195            tracing::error!(error = %error, "awp edge could not publish its status");
196        }
197    }
198
199    /// The current status, if one was published.
200    pub(crate) async fn current_status(&self) -> Option<SiteStatus> {
201        match self.status.current().await {
202            Ok(status) => status,
203            Err(error) => {
204                tracing::error!(error = %error, "awp status store failed");
205                None
206            }
207        }
208    }
209}