Skip to main content

adk_website/deploy/
updates.rs

1//! The running site's constant updates (spec 3.5 §7.8.3, A-I23, A-I24, A-I27): the
2//! `UpdateEngine` driven on its own schedule, its journal for `adk-rust site batches` and
3//! `site feeds`, held deliveries and items as the owner's decision cards, and its alarms on
4//! the owner's channels.
5//!
6//! | Part | Does |
7//! |---|---|
8//! | [`UpdateDriver`] | Ticks the engine when [`UpdateEngine::next_due`] says, journals each closed batch and the feed counters, and keeps the cards in step |
9//! | [`UpdateJournal`] | `data/updates/batches.jsonl` (one `BatchRecord` per line) and `data/updates/feeds.json` |
10//! | [`UpdateCards`] | Each held delivery and held item becomes an approval request in the kernel's inbox, which the owner's channels show as a decision card; the owner's answer releases or discards it, and the change's proposer cannot approve it (A-I23) |
11//! | [`SiteAlarms`] | The engine's alarms on the product's P1/P2/P3 routing: a delivery held by its bounds is P2 |
12
13use std::collections::BTreeMap;
14use std::io::Write as _;
15use std::path::PathBuf;
16use std::sync::Arc;
17use std::time::Duration;
18
19use adk_core::{
20    AdkError, ApprovalPolicy, ApprovalRequest, ApprovalRisk, ApprovalScope, ApprovalService,
21    ApprovalState, ApproverSelector, Result, ToolConfirmationRequest,
22};
23use adk_site::updates::{
24    AlarmSink, BatchRecord, Decision, FeedStatus, HoldReason, SiteAlarm, UpdateEngine,
25};
26use async_trait::async_trait;
27use awp_types::ContentId;
28use serde_json::json;
29use tokio::sync::Mutex;
30use tokio::task::JoinHandle;
31use uuid::Uuid;
32
33use crate::alarms::{Alarm, AlarmRouter};
34
35/// The tool a held delivery's card names (spec 3.5 A-I27).
36pub const RELEASE_DELIVERY: &str = "site_update_release_delivery";
37/// The tool a held item's card names (spec 3.5 §7.8.3 "Approvals on exceptions only").
38pub const RELEASE_ITEM: &str = "site_update_release_item";
39
40fn site_error(error: impl std::fmt::Display) -> AdkError {
41    AdkError::config(error.to_string())
42}
43
44/// The engine's journal beside the content repository, read by `adk-rust site batches` and
45/// `site feeds`.
46#[derive(Debug, Clone, PartialEq, Eq)]
47pub struct UpdateJournal {
48    dir: PathBuf,
49}
50
51impl UpdateJournal {
52    /// The journal in `dir`, `data/updates/` of the project.
53    pub fn new(dir: impl Into<PathBuf>) -> Self {
54        Self { dir: dir.into() }
55    }
56
57    /// Appends `records` to `batches.jsonl`.
58    ///
59    /// # Errors
60    ///
61    /// The file system's error.
62    pub fn append(&self, records: &[BatchRecord]) -> Result<()> {
63        if records.is_empty() {
64            return Ok(());
65        }
66        std::fs::create_dir_all(&self.dir).map_err(site_error)?;
67        let mut file = std::fs::OpenOptions::new()
68            .create(true)
69            .append(true)
70            .open(self.dir.join("batches.jsonl"))
71            .map_err(site_error)?;
72        for record in records {
73            let line = serde_json::to_string(record).map_err(site_error)?;
74            writeln!(file, "{line}").map_err(site_error)?;
75        }
76        Ok(())
77    }
78
79    /// Replaces `feeds.json` with `feeds`.
80    ///
81    /// # Errors
82    ///
83    /// The file system's error.
84    pub fn write_feeds(&self, feeds: &[FeedStatus]) -> Result<()> {
85        std::fs::create_dir_all(&self.dir).map_err(site_error)?;
86        let text = serde_json::to_vec_pretty(feeds).map_err(site_error)?;
87        let temporary = self.dir.join("feeds.json.tmp");
88        std::fs::write(&temporary, text).map_err(site_error)?;
89        std::fs::rename(&temporary, self.dir.join("feeds.json")).map_err(site_error)
90    }
91
92    /// The batches journaled so far.
93    ///
94    /// # Errors
95    ///
96    /// A line that is not a batch record.
97    pub fn batches(&self) -> Result<Vec<BatchRecord>> {
98        match std::fs::read_to_string(self.dir.join("batches.jsonl")) {
99            Ok(text) => text
100                .lines()
101                .filter(|line| !line.trim().is_empty())
102                .map(|line| serde_json::from_str(line).map_err(site_error))
103                .collect(),
104            Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(Vec::new()),
105            Err(error) => Err(site_error(error)),
106        }
107    }
108}
109
110/// Something the engine holds for the owner.
111#[derive(Debug, Clone, PartialEq, Eq)]
112enum Held {
113    Delivery(u64),
114    Item(ContentId),
115}
116
117/// What the owner decided on a card, once applied.
118#[derive(Debug, Clone, PartialEq)]
119pub struct CardOutcome {
120    /// The card's approval request.
121    pub request: String,
122    /// Released or discarded.
123    pub decision: Decision,
124    /// Who decided.
125    pub by: String,
126    /// Batches the release closed.
127    pub batches: Vec<BatchRecord>,
128}
129
130/// Held deliveries and items as the owner's decision cards (spec 3.5 §7.8.3, A-I23, A-I27):
131/// approval requests in the kernel's inbox, which the owner's channels show as cards.
132pub struct UpdateCards {
133    engine: Arc<UpdateEngine>,
134    approvals: Arc<dyn ApprovalService>,
135    site: Uuid,
136    app: String,
137    owner: String,
138    carded: Mutex<BTreeMap<String, Held>>,
139}
140
141impl UpdateCards {
142    /// Cards for `engine`'s holds in `approvals`, for site `site` of app `app`, decided by
143    /// `owner`.
144    pub fn new(
145        engine: Arc<UpdateEngine>,
146        approvals: Arc<dyn ApprovalService>,
147        site: Uuid,
148        app: impl Into<String>,
149        owner: impl Into<String>,
150    ) -> Self {
151        Self {
152            engine,
153            approvals,
154            site,
155            app: app.into(),
156            owner: owner.into(),
157            carded: Mutex::new(BTreeMap::new()),
158        }
159    }
160
161    fn request(
162        &self,
163        id: String,
164        tool: &str,
165        args: serde_json::Value,
166        summary: String,
167    ) -> ApprovalRequest {
168        let call = ToolConfirmationRequest::new(tool, args);
169        let scope = ApprovalScope::new(self.app.clone(), self.owner.clone(), "site-updates");
170        let policy = ApprovalPolicy::new([ApproverSelector::human(self.owner.clone())]);
171        ApprovalRequest::new(id, scope, &call, policy)
172            .with_summary(summary)
173            .with_risk(ApprovalRisk::Medium)
174    }
175
176    /// Submits a card for every hold that has none; returns the new cards.
177    ///
178    /// # Errors
179    ///
180    /// The approval service's error.
181    pub async fn sync(&self) -> Result<Vec<ApprovalRequest>> {
182        let mut carded = self.carded.lock().await;
183        let mut submitted = Vec::new();
184        for held in self.engine.held_deliveries().await {
185            let id = format!("site-update-{}-delivery-{}", self.site, held.delivery);
186            if carded.contains_key(&id) {
187                continue;
188            }
189            let summary = format!(
190                "Feed {} sent a delivery its bounds held: release it or discard it",
191                held.feed
192            );
193            let args =
194                json!({ "delivery": held.delivery, "feed": held.feed, "report": held.report });
195            let request = self
196                .approvals
197                .submit(self.request(id.clone(), RELEASE_DELIVERY, args, summary))
198                .await?;
199            carded.insert(id, Held::Delivery(held.delivery));
200            submitted.push(request);
201        }
202        for held in self.engine.held_items().await {
203            let item = held.update.item.id.clone();
204            let id = format!(
205                "site-update-{}-item-{}-{}",
206                self.site,
207                item.0.replace('/', "~"),
208                held.batch
209            );
210            if carded.contains_key(&id) {
211                continue;
212            }
213            let why = match &held.reason {
214                HoldReason::PriceRule { allowed_pct } => {
215                    format!("its price moves more than {allowed_pct}%")
216                }
217                HoldReason::NewItem => "it is new".to_string(),
218                HoldReason::FastTier { .. } => "it failed the fast checks".to_string(),
219                _ => "it is an exception".to_string(),
220            };
221            let summary = format!("{} waits because {why}: publish it or discard it", item.0);
222            let args =
223                json!({ "item": item, "reason": held.reason, "proposer": held.update.proposer });
224            let request = self
225                .approvals
226                .submit(self.request(id.clone(), RELEASE_ITEM, args, summary))
227                .await?;
228            carded.insert(id, Held::Item(item));
229            submitted.push(request);
230        }
231        Ok(submitted)
232    }
233
234    /// Applies every decided card: an approval releases, a rejection discards; a release by
235    /// the change's own proposer is refused and the card stays decided (A-I23).
236    ///
237    /// # Errors
238    ///
239    /// The approval service's error; a refused decision is logged and skipped.
240    pub async fn apply(&self) -> Result<Vec<CardOutcome>> {
241        let mut carded = self.carded.lock().await;
242        let mut outcomes = Vec::new();
243        let ids: Vec<String> = carded.keys().cloned().collect();
244        for id in ids {
245            let Some(request) = self.approvals.get(&id).await? else { continue };
246            let decision = match request.state {
247                ApprovalState::Approved => Decision::Release,
248                ApprovalState::Rejected | ApprovalState::Expired | ApprovalState::Cancelled => {
249                    Decision::Discard
250                }
251                ApprovalState::Pending | ApprovalState::Responded => continue,
252            };
253            let by = request
254                .decisions
255                .last()
256                .map_or_else(|| self.owner.clone(), |decision| decision.approver.id.clone());
257            let Some(held) = carded.remove(&id) else { continue };
258            let batches = match &held {
259                Held::Delivery(delivery) => {
260                    self.engine.decide_delivery(*delivery, decision, &by).await.map(|o| o.batches)
261                }
262                Held::Item(item) => self.engine.decide_item(item, decision, &by).await,
263            };
264            match batches {
265                Ok(batches) => outcomes.push(CardOutcome { request: id, decision, by, batches }),
266                Err(error) => {
267                    tracing::warn!(card = %id, error = %error, "the owner's decision was not applied");
268                }
269            }
270        }
271        Ok(outcomes)
272    }
273}
274
275/// The engine's alarms on the product's routing (spec 3.5 §7.21): a delivery its bounds held
276/// whole is P2 with its summary.
277pub struct SiteAlarms {
278    router: Arc<AlarmRouter>,
279    site: Uuid,
280}
281
282impl SiteAlarms {
283    /// Alarms of `site` through `router`.
284    pub fn new(router: Arc<AlarmRouter>, site: Uuid) -> Self {
285        Self { router, site }
286    }
287}
288
289#[async_trait]
290impl AlarmSink for SiteAlarms {
291    async fn raise(&self, alarm: &SiteAlarm) -> adk_site::Result<()> {
292        let summary = match alarm.detail.get("summary").and_then(serde_json::Value::as_str) {
293            Some(summary) => format!("{}: {summary}", alarm.title),
294            None => alarm.title.clone(),
295        };
296        self.router
297            .raise(Alarm::new(self.site, alarm.urgency, alarm.code.clone(), summary, alarm.at))
298            .await;
299        Ok(())
300    }
301}
302
303/// Drives the engine (spec 3.5 §7.8.3): ticks it when it is due, journals closed batches and
304/// the feed counters, and keeps the cards in step.
305pub struct UpdateDriver {
306    engine: Arc<UpdateEngine>,
307    journal: UpdateJournal,
308    cards: Option<Arc<UpdateCards>>,
309    journaled: Mutex<u64>,
310}
311
312impl UpdateDriver {
313    /// A driver of `engine` journaling to `journal`, with `cards` for the holds.
314    pub fn new(
315        engine: Arc<UpdateEngine>,
316        journal: UpdateJournal,
317        cards: Option<Arc<UpdateCards>>,
318    ) -> Self {
319        Self { engine, journal, cards, journaled: Mutex::new(0) }
320    }
321
322    /// One step: applies decided cards, ticks the engine, journals every batch closed since
323    /// the last step and the feed counters, and cards new holds. Returns the batches
324    /// journaled.
325    ///
326    /// # Errors
327    ///
328    /// The engine's, the journal's or the approval service's error.
329    pub async fn step(&self) -> Result<Vec<BatchRecord>> {
330        if let Some(cards) = &self.cards {
331            cards.apply().await?;
332        }
333        self.engine.tick().await.map_err(site_error)?;
334        let mut journaled = self.journaled.lock().await;
335        let fresh: Vec<BatchRecord> =
336            self.engine.batches().await.into_iter().filter(|r| r.batch > *journaled).collect();
337        self.journal.append(&fresh)?;
338        if let Some(last) = fresh.iter().map(|r| r.batch).max() {
339            *journaled = last;
340        }
341        self.journal.write_feeds(&self.engine.feeds().await)?;
342        if let Some(cards) = &self.cards {
343            cards.sync().await?;
344        }
345        Ok(fresh)
346    }
347
348    /// Steps until aborted: at the engine's next due time, and at least every `idle`.
349    pub fn spawn(self: Arc<Self>, idle: Duration) -> JoinHandle<()> {
350        tokio::spawn(async move {
351            loop {
352                if let Err(error) = self.step().await {
353                    tracing::warn!(error = %error, "the update engine's step failed");
354                }
355                let wait = match self.engine.next_due().await {
356                    Some(due) => (due - chrono::Utc::now()).to_std().unwrap_or_default().min(idle),
357                    None => idle,
358                };
359                tokio::time::sleep(wait.max(Duration::from_millis(50))).await;
360            }
361        })
362    }
363}