Skip to main content

adk_site/updates/
held.rs

1//! Where an [`UpdateEngine`](super::UpdateEngine) keeps what it holds for the owner, so held
2//! items and held deliveries survive a restart (spec 3.5 ยง7.8.3 "Approvals on exceptions
3//! only", A-I25, A-I27): the owner's decision on a card raised before a restart still finds
4//! the change it decides.
5
6use std::path::PathBuf;
7
8use async_trait::async_trait;
9use serde::{Deserialize, Serialize};
10use tokio::sync::Mutex;
11
12use super::{HeldDelivery, HeldItem};
13use crate::error::{Result, SiteError};
14
15/// Everything an engine holds: items held alone, deliveries held whole, and the next
16/// delivery number, so numbers are never reused across a restart.
17#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
18#[serde(rename_all = "camelCase")]
19pub struct HeldState {
20    /// Items held alone, waiting for a decision.
21    #[serde(default)]
22    pub items: Vec<HeldItem>,
23    /// Deliveries held whole by their bounds.
24    #[serde(default)]
25    pub deliveries: Vec<HeldDelivery>,
26    /// The number the next delivery gets.
27    #[serde(default)]
28    pub next_delivery: u64,
29}
30
31/// A durable home for an engine's [`HeldState`]. The engine reads it once, before its first
32/// use of held state, and writes the whole state after every change to it.
33///
34/// Implementations: [`InMemoryHeldStore`] (the default, lost on restart) and
35/// [`FileHeldStore`]; [`held_store_conformance`] checks any of them.
36#[async_trait]
37pub trait HeldStore: Send + Sync {
38    /// The state last saved, or the empty state.
39    ///
40    /// # Errors
41    ///
42    /// Returns an error when the state cannot be read.
43    async fn load(&self) -> Result<HeldState>;
44
45    /// Replaces the saved state with `state`.
46    ///
47    /// # Errors
48    ///
49    /// Returns an error when the state cannot be written.
50    async fn save(&self, state: &HeldState) -> Result<()>;
51}
52
53/// Held state in memory: the engine's default, lost on restart.
54#[derive(Debug, Default)]
55pub struct InMemoryHeldStore(Mutex<HeldState>);
56
57#[async_trait]
58impl HeldStore for InMemoryHeldStore {
59    async fn load(&self) -> Result<HeldState> {
60        Ok(self.0.lock().await.clone())
61    }
62
63    async fn save(&self, state: &HeldState) -> Result<()> {
64        *self.0.lock().await = state.clone();
65        Ok(())
66    }
67}
68
69/// Held state as one JSON file, replaced atomically on every save.
70///
71/// # Example
72///
73/// ```rust,no_run
74/// use std::sync::Arc;
75/// use adk_site::updates::{FileHeldStore, UpdateEngine};
76/// # fn demo(pipeline: Arc<adk_site::pipeline::PublishingPipeline>, live: Arc<dyn adk_site::live::LiveStore>) -> adk_site::Result<()> {
77/// let engine = UpdateEngine::builder(pipeline, live)
78///     .held_store(Arc::new(FileHeldStore::new("/var/lib/site/data/updates/held.json")))
79///     .build()?;
80/// # let _ = engine;
81/// # Ok(())
82/// # }
83/// ```
84#[derive(Debug)]
85pub struct FileHeldStore {
86    path: PathBuf,
87    lock: Mutex<()>,
88}
89
90impl FileHeldStore {
91    /// A store at `path`, created on the first save.
92    pub fn new(path: impl Into<PathBuf>) -> Self {
93        Self { path: path.into(), lock: Mutex::new(()) }
94    }
95}
96
97#[async_trait]
98impl HeldStore for FileHeldStore {
99    async fn load(&self) -> Result<HeldState> {
100        let _guard = self.lock.lock().await;
101        match tokio::fs::read(&self.path).await {
102            Ok(bytes) => serde_json::from_slice(&bytes)
103                .map_err(|e| SiteError::serde(self.path.display().to_string(), e)),
104            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(HeldState::default()),
105            Err(e) => Err(SiteError::io(&self.path, e)),
106        }
107    }
108
109    async fn save(&self, state: &HeldState) -> Result<()> {
110        let _guard = self.lock.lock().await;
111        if let Some(parent) = self.path.parent() {
112            tokio::fs::create_dir_all(parent).await.map_err(|e| SiteError::io(parent, e))?;
113        }
114        let bytes =
115            serde_json::to_vec_pretty(state).map_err(|e| SiteError::serde("held updates", e))?;
116        let tmp = self.path.with_extension("json.tmp");
117        tokio::fs::write(&tmp, bytes).await.map_err(|e| SiteError::io(&tmp, e))?;
118        tokio::fs::rename(&tmp, &self.path).await.map_err(|e| SiteError::io(&self.path, e))
119    }
120}
121
122/// Checks what every [`HeldStore`] promises: an empty store loads the empty state, a saved
123/// state loads back equal, and a save replaces the previous one whole. Panics on a violation;
124/// call it from a test with `sample`, a state holding at least one item and one delivery.
125pub async fn held_store_conformance(store: &dyn HeldStore, sample: &HeldState) {
126    assert_eq!(store.load().await.expect("load"), HeldState::default(), "a new store is empty");
127    store.save(sample).await.expect("save");
128    assert_eq!(&store.load().await.expect("load"), sample, "the saved state loads back");
129    let mut smaller = sample.clone();
130    smaller.items.clear();
131    smaller.next_delivery = sample.next_delivery + 1;
132    store.save(&smaller).await.expect("save");
133    assert_eq!(store.load().await.expect("load"), smaller, "a save replaces the state whole");
134}