Skip to main content

adk_site/
updates.rs

1//! Constantly updated sites: the engine that sorts updates into lanes, bounds feeds, batches
2//! releases and holds only exceptions (spec 3.5 §7.8.3, A-I24–A-I27, §8.1 `site revert`,
3//! `site batches`, `site feeds`).
4//!
5//! ```text
6//! ContentSource ──records──▶ FeedMapping (no model) ──▶ bounds ──held whole──▶ P2 alarm, owner decides
7//!                                                          │
8//!                                   live values ◀──────────┤
9//!                                  (LiveStore, never released)
10//!                                                          ▼
11//! owner, editor, agents ──Update──▶ Batcher (window per kind, flush triggers)
12//!                                                          ▼
13//!                       exceptions held alone ◀── rules (price rule, new items)
14//!                                                          ▼
15//!                  PublishingPipeline::publish_batch: fast tier per item, A-I1 refuses whole,
16//!                  one release (delta or snapshot), one log entry, one checkpoint,
17//!                  one catalog.changed
18//! ```
19//!
20//! [`UpdateEngine::tick`] closes elapsed windows and runs the scheduled full checks every six
21//! hours or 500 releases. What the engine holds for the owner lives in a [`HeldStore`]
22//! ([`FileHeldStore`] keeps it across restarts). [`UpdateEngine::batches`] and [`UpdateEngine::feeds`] are the
23//! library side of `adk-rust site batches` and `site feeds`; [`UpdateEngine::revert`] of
24//! `site revert <item> [--to <seq>]`.
25
26use std::collections::{BTreeMap, BTreeSet, VecDeque};
27use std::sync::Arc;
28use std::time::Duration;
29
30use adk_core::audit_log::{AuditActor, AuditRecordDraft, AuditRecordKind, AuditRecorder};
31use adk_core::{ActingContext, Clock};
32use async_trait::async_trait;
33use awp_types::{ContentId, ContentItem, FeedBounds, PriceRule, ReleaseSource, Trigger, Urgency};
34use chrono::{DateTime, Utc};
35use serde::{Deserialize, Serialize};
36use serde_json::Value;
37use tokio::sync::Mutex;
38
39use crate::batch::{Batch, BatchPolicies, Batcher, FlushReason, Update, check_host};
40use crate::content::{ContentHistory, ContentStore, HistoryEntry};
41use crate::error::{Result, SiteError};
42use crate::feed::bounds::{self, BoundsReport, Delivery, price_within_rule};
43use crate::feed::{ContentSource, FeedChanges, FeedMapping, FeedRecord};
44use crate::gate::{Finding, GateReport};
45use crate::live::{LiveStore, LiveValue};
46use crate::pipeline::{EntryPoint, Published, PublishingPipeline};
47use crate::stream::{StreamLane, StreamStatus};
48
49mod held;
50
51pub use held::{FileHeldStore, HeldState, HeldStore, InMemoryHeldStore, held_store_conformance};
52
53/// Batch records kept for `site batches`.
54const RECORDS_KEPT: usize = 1_000;
55
56/// An alarm for the owner (spec 3.5 §7.21; `website.alarm.raised`).
57#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
58#[serde(rename_all = "camelCase")]
59pub struct SiteAlarm {
60    /// How urgent it is.
61    pub urgency: Urgency,
62    /// A stable code, such as `site.feed.held`.
63    pub code: String,
64    /// One line for the owner.
65    pub title: String,
66    /// What it is about, such as a held delivery's change summary.
67    pub detail: Value,
68    /// When it was raised.
69    pub at: DateTime<Utc>,
70}
71
72/// Where alarms go: the product's alarm routing (spec 3.5 §7.21).
73#[async_trait]
74pub trait AlarmSink: Send + Sync {
75    /// Raises an alarm.
76    ///
77    /// # Errors
78    ///
79    /// Returns an error when the alarm cannot be queued.
80    async fn raise(&self, alarm: &SiteAlarm) -> Result<()>;
81}
82
83/// Alarms kept in memory, for tests and for a product that polls them.
84#[derive(Debug, Default)]
85pub struct InMemoryAlarms(Mutex<Vec<SiteAlarm>>);
86
87impl InMemoryAlarms {
88    /// Every alarm raised so far.
89    pub async fn all(&self) -> Vec<SiteAlarm> {
90        self.0.lock().await.clone()
91    }
92}
93
94#[async_trait]
95impl AlarmSink for InMemoryAlarms {
96    async fn raise(&self, alarm: &SiteAlarm) -> Result<()> {
97        self.0.lock().await.push(alarm.clone());
98        Ok(())
99    }
100}
101
102/// When the launch gate's full tier runs again (spec 3.5 §7.8.3 "Tiered checks"): every
103/// six hours or every 500 releases by default, whichever comes first.
104///
105/// # Example
106///
107/// ```rust
108/// use adk_site::updates::FullCheckSchedule;
109/// use chrono::{Duration, Utc};
110///
111/// let start = Utc::now();
112/// let mut schedule = FullCheckSchedule::default();
113/// schedule.ran(start, 0);
114/// assert!(!schedule.due(start + Duration::hours(5), 499));
115/// assert!(schedule.due(start + Duration::hours(5), 500));
116/// assert!(schedule.due(start + Duration::hours(6), 1));
117/// ```
118#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
119#[serde(rename_all = "camelCase")]
120pub struct FullCheckSchedule {
121    /// The longest time between full checks.
122    #[serde(with = "secs")]
123    pub every: Duration,
124    /// The most releases between full checks.
125    pub every_releases: u64,
126    /// When they last ran.
127    #[serde(default, skip_serializing_if = "Option::is_none")]
128    pub last_at: Option<DateTime<Utc>>,
129    /// The release they last ran on.
130    #[serde(default)]
131    pub last_seq: u64,
132}
133
134mod secs {
135    use serde::{Deserialize, Deserializer, Serializer};
136    use std::time::Duration;
137
138    pub fn serialize<S: Serializer>(d: &Duration, s: S) -> Result<S::Ok, S::Error> {
139        s.serialize_u64(d.as_secs())
140    }
141
142    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Duration, D::Error> {
143        u64::deserialize(d).map(Duration::from_secs)
144    }
145}
146
147impl Default for FullCheckSchedule {
148    fn default() -> Self {
149        Self {
150            every: Duration::from_secs(6 * 3_600),
151            every_releases: 500,
152            last_at: None,
153            last_seq: 0,
154        }
155    }
156}
157
158impl FullCheckSchedule {
159    /// Whether the full checks are due at `now` with release `seq` live.
160    pub fn due(&self, now: DateTime<Utc>, seq: u64) -> bool {
161        let Some(last) = self.last_at else { return true };
162        now - last >= chrono::Duration::from_std(self.every).unwrap_or_default()
163            || seq.saturating_sub(self.last_seq) >= self.every_releases
164    }
165
166    /// Records that the full checks ran.
167    pub fn ran(&mut self, now: DateTime<Utc>, seq: u64) {
168        self.last_at = Some(now);
169        self.last_seq = seq;
170    }
171}
172
173/// What the weekly review reports on updates (spec 3.5 §7.8.3 "Model-free updates").
174#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
175#[serde(rename_all = "camelCase")]
176pub struct CostRates {
177    /// The cost of one model call, in millionths of the site's currency unit.
178    pub per_model_call_micros: u64,
179    /// The cost of one release on the host, in millionths of the site's currency unit.
180    pub per_release_micros: u64,
181}
182
183/// Update counts and costs for the weekly review (spec 3.5 §7.8.3, §7.21).
184#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
185#[serde(rename_all = "camelCase")]
186pub struct UpdateReview {
187    /// Item updates: live values set plus item versions batched.
188    pub updates: u64,
189    /// Live item updates.
190    pub live_updates: u64,
191    /// Item versions batched for release.
192    pub release_updates: u64,
193    /// Updates whose writing called a model.
194    pub updates_with_model: u64,
195    /// Model calls spent on updates.
196    pub model_calls: u64,
197    /// `updates_with_model / updates`.
198    pub model_share: f64,
199    /// Feed deliveries.
200    pub deliveries: u64,
201    /// Deliveries held whole by their bounds.
202    pub held_deliveries: u64,
203    /// Items held alone: exceptions and fast-tier failures.
204    pub held_items: u64,
205    /// Releases published.
206    pub releases: u64,
207    /// Scheduled full checks run.
208    pub full_checks: u64,
209    /// Cost of the model calls and releases, in millionths of the currency unit.
210    pub cost_micros: u64,
211    /// Cost per thousand updates, in millionths of the currency unit.
212    pub cost_per_thousand_updates_micros: f64,
213}
214
215/// Why an item waits on its own (spec 3.5 §7.8.3 "Approvals on exceptions only",
216/// "Tiered checks").
217#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
218#[serde(rename_all = "snake_case", tag = "reason", rename_all_fields = "camelCase")]
219#[non_exhaustive]
220pub enum HoldReason {
221    /// The price moves more than the price rule allows (A-I25).
222    PriceRule {
223        /// The largest change the rule allows, in percent.
224        allowed_pct: f32,
225    },
226    /// A new item waits for its approval chain.
227    NewItem,
228    /// The fast tier failed on it.
229    FastTier {
230        /// The blocking findings.
231        findings: Vec<Finding>,
232    },
233}
234
235/// An item held alone; the rest of its batch published.
236#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
237#[serde(rename_all = "camelCase")]
238pub struct HeldItem {
239    /// The version waiting.
240    pub update: Update,
241    /// Why it waits.
242    pub reason: HoldReason,
243    /// The batch it came in.
244    pub batch: u64,
245    /// When it was held.
246    pub held_at: DateTime<Utc>,
247}
248
249/// A delivery held whole by its bounds (spec 3.5 A-I27).
250#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
251#[serde(rename_all = "camelCase")]
252pub struct HeldDelivery {
253    /// The delivery number.
254    pub delivery: u64,
255    /// The feed.
256    pub feed: String,
257    /// When it arrived.
258    pub received_at: DateTime<Utc>,
259    /// The bounds it broke and what it would change.
260    pub report: BoundsReport,
261    /// What it would change, applied only if the owner releases it.
262    pub changes: FeedChanges,
263}
264
265/// The owner's decision on something held.
266#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
267#[serde(rename_all = "snake_case")]
268pub enum Decision {
269    /// Publish it.
270    Release,
271    /// Drop it.
272    Discard,
273}
274
275/// What one delivery did.
276#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
277#[serde(rename_all = "camelCase")]
278pub struct DeliveryOutcome {
279    /// The delivery number.
280    pub delivery: u64,
281    /// Whether its bounds held it whole.
282    pub held: bool,
283    /// Live item updates applied.
284    pub live: usize,
285    /// Item versions queued for release.
286    pub queued: usize,
287    /// Keys the site has no item for.
288    #[serde(default, skip_serializing_if = "Vec::is_empty")]
289    pub unknown: Vec<String>,
290    /// Batches it closed.
291    #[serde(default, skip_serializing_if = "Vec::is_empty")]
292    pub batches: Vec<BatchRecord>,
293}
294
295/// One batch for `site batches` (spec 3.5 §8.1).
296#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
297#[serde(rename_all = "camelCase")]
298pub struct BatchRecord {
299    /// The batch number.
300    pub batch: u64,
301    /// When its earliest change arrived.
302    pub opened_at: DateTime<Utc>,
303    /// When it closed.
304    pub closed_at: DateTime<Utc>,
305    /// Why it closed.
306    pub reason: FlushReason,
307    /// The release it published, if any.
308    #[serde(default, skip_serializing_if = "Option::is_none")]
309    pub release_seq: Option<u64>,
310    /// When the release went live.
311    #[serde(default, skip_serializing_if = "Option::is_none")]
312    pub live_at: Option<DateTime<Utc>>,
313    /// The items it published.
314    pub published: Vec<ContentId>,
315    /// Earlier versions replaced within the window.
316    pub superseded: usize,
317    /// The items it held alone, with why.
318    #[serde(default, skip_serializing_if = "Vec::is_empty")]
319    pub held: Vec<(ContentId, HoldReason)>,
320    /// Why the release was refused whole (A-I1), when it was.
321    #[serde(default, skip_serializing_if = "Option::is_none")]
322    pub refused: Option<String>,
323    /// Pages of changed ids after the first `catalog.changed` page.
324    pub catalog_pages: usize,
325    /// Approval-to-live of each published item, in milliseconds: from the change's arrival
326    /// (its approval, for a change within the rules) to its release going live.
327    #[serde(default, skip_serializing_if = "Vec::is_empty")]
328    pub latencies_ms: Vec<i64>,
329    /// Model calls spent on its updates.
330    pub model_calls: u64,
331}
332
333/// One feed for `site feeds` (spec 3.5 §8.1).
334#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
335#[serde(rename_all = "camelCase")]
336pub struct FeedStatus {
337    /// The mapping.
338    pub mapping: FeedMapping,
339    /// Its bounds.
340    pub bounds: FeedBounds,
341    /// Deliveries so far.
342    pub deliveries: u64,
343    /// Records so far.
344    pub records: u64,
345    /// Records in the last minute.
346    pub records_last_minute: u64,
347    /// When it last delivered.
348    #[serde(default, skip_serializing_if = "Option::is_none")]
349    pub last_delivery: Option<DateTime<Utc>>,
350    /// Deliveries held whole.
351    pub held: u64,
352    /// Model calls its mapping made: always zero.
353    pub model_calls: u64,
354}
355
356/// An item changed since a rollback point, which the Steward proposes replaying (spec 3.5
357/// §7.8.3 "Undo per item").
358#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
359#[serde(rename_all = "camelCase")]
360pub struct ReplayCandidate {
361    /// The item.
362    pub id: ContentId,
363    /// The release its latest version went live in.
364    pub release_seq: u64,
365    /// When that version was saved.
366    #[serde(default, skip_serializing_if = "Option::is_none")]
367    pub at: Option<DateTime<Utc>>,
368    /// Who saved it.
369    #[serde(default, skip_serializing_if = "Option::is_none")]
370    pub actor: Option<String>,
371    /// The version in the content history.
372    pub version: u64,
373}
374
375#[derive(Debug)]
376struct FeedState {
377    mapping: FeedMapping,
378    bounds: FeedBounds,
379    deliveries: u64,
380    records: u64,
381    recent: VecDeque<(DateTime<Utc>, u64)>,
382    last_delivery: Option<DateTime<Utc>>,
383    held: u64,
384}
385
386impl FeedState {
387    fn records_last_minute(&self, now: DateTime<Utc>) -> u64 {
388        let since = now - chrono::Duration::minutes(1);
389        self.recent.iter().filter(|(at, _)| *at > since).map(|(_, n)| n).sum()
390    }
391}
392
393#[derive(Debug)]
394struct Inner {
395    batcher: Batcher,
396    feeds: BTreeMap<String, FeedState>,
397    held_deliveries: BTreeMap<u64, HeldDelivery>,
398    held_items: BTreeMap<ContentId, HeldItem>,
399    records: VecDeque<BatchRecord>,
400    review: UpdateReview,
401    schedule: FullCheckSchedule,
402    next_delivery: u64,
403    /// Whether the held state was read from the store.
404    restored: bool,
405}
406
407impl Inner {
408    fn held_state(&self) -> HeldState {
409        HeldState {
410            items: self.held_items.values().cloned().collect(),
411            deliveries: self.held_deliveries.values().cloned().collect(),
412            next_delivery: self.next_delivery,
413        }
414    }
415}
416
417/// Builds an [`UpdateEngine`].
418pub struct UpdateEngineBuilder {
419    pipeline: Arc<PublishingPipeline>,
420    live: Arc<dyn LiveStore>,
421    policies: BatchPolicies,
422    price_rule: PriceRule,
423    approve_new_items: bool,
424    alarms: Option<Arc<dyn AlarmSink>>,
425    audit: Option<(Arc<dyn AuditRecorder>, ActingContext)>,
426    costs: CostRates,
427    schedule: FullCheckSchedule,
428    streams: Option<Arc<StreamLane>>,
429    held: Option<Arc<dyn HeldStore>>,
430}
431
432impl UpdateEngineBuilder {
433    /// Keeps held items and held deliveries in `store`, so they survive a restart; in memory
434    /// by default.
435    pub fn held_store(mut self, store: Arc<dyn HeldStore>) -> Self {
436        self.held = Some(store);
437        self
438    }
439
440    /// The stream lane: live blogs, tickers and emergency updates, folded into releases
441    /// (spec 3.5 §7.8.3).
442    pub fn streams(mut self, streams: Arc<StreamLane>) -> Self {
443        self.streams = Some(streams);
444        self
445    }
446
447    /// The batch policies; default 30 s, news 10 s, shops 60 s.
448    pub fn policies(mut self, policies: BatchPolicies) -> Self {
449        self.policies = policies;
450        self
451    }
452
453    /// The charter's price rule for changes that do not come from a feed (A-I25).
454    pub fn price_rule(mut self, rule: PriceRule) -> Self {
455        self.price_rule = rule;
456        self
457    }
458
459    /// Whether new items wait for their approval chain; default `true`.
460    pub fn approve_new_items(mut self, approve: bool) -> Self {
461        self.approve_new_items = approve;
462        self
463    }
464
465    /// Where alarms go.
466    pub fn alarms(mut self, alarms: Arc<dyn AlarmSink>) -> Self {
467        self.alarms = Some(alarms);
468        self
469    }
470
471    /// Records `site.batch.*`, `site.content.reverted` and `website.alarm.raised` as
472    /// `acting`.
473    pub fn audit(mut self, recorder: Arc<dyn AuditRecorder>, acting: ActingContext) -> Self {
474        self.audit = Some((recorder, acting));
475        self
476    }
477
478    /// The rates the weekly review prices updates with.
479    pub fn costs(mut self, costs: CostRates) -> Self {
480        self.costs = costs;
481        self
482    }
483
484    /// When the full checks run.
485    pub fn full_checks(mut self, schedule: FullCheckSchedule) -> Self {
486        self.schedule = schedule;
487        self
488    }
489
490    /// The engine.
491    ///
492    /// # Errors
493    ///
494    /// [`SiteError::InvalidConfig`] when a batch window is out of range or the pipeline's
495    /// host cannot serve the windows (spec 3.5 §7.8.3 "Hosts at speed").
496    pub fn build(self) -> Result<UpdateEngine> {
497        self.policies.validate()?;
498        check_host(&self.pipeline.site_host().limits(), &self.policies).require()?;
499        let clock = self.pipeline.clock();
500        let mut schedule = self.schedule;
501        if schedule.last_at.is_none() {
502            schedule.last_at = Some(clock.now());
503        }
504        Ok(UpdateEngine {
505            store: self.pipeline.content_store(),
506            history: self.pipeline.content_history(),
507            pipeline: self.pipeline,
508            live: self.live,
509            price_rule: self.price_rule,
510            approve_new_items: self.approve_new_items,
511            alarms: self.alarms,
512            audit: self.audit,
513            costs: self.costs,
514            streams: self.streams,
515            held: self.held.unwrap_or_else(|| Arc::new(InMemoryHeldStore::default())),
516            clock,
517            inner: Mutex::new(Inner {
518                batcher: Batcher::new(self.policies),
519                feeds: BTreeMap::new(),
520                held_deliveries: BTreeMap::new(),
521                held_items: BTreeMap::new(),
522                records: VecDeque::new(),
523                review: UpdateReview::default(),
524                schedule,
525                next_delivery: 1,
526                restored: false,
527            }),
528        })
529    }
530}
531
532/// The engine of a constantly updated site (spec 3.5 §7.8.3).
533///
534/// # Example
535///
536/// ```rust,no_run
537/// use std::sync::Arc;
538/// use adk_site::feed::{FeedMapping, FieldMapping, FieldType, FeedRecord};
539/// use adk_site::live::InMemoryLiveStore;
540/// use adk_site::updates::UpdateEngine;
541/// use awp_types::{ContentKind, FeedBounds, PriceRule, Rate};
542///
543/// # async fn demo(pipeline: Arc<adk_site::pipeline::PublishingPipeline>) -> adk_site::Result<()> {
544/// let engine = UpdateEngine::builder(pipeline, Arc::new(InMemoryLiveStore::default())).build()?;
545/// let mapping = FeedMapping::new("supplier", ContentKind::Product, "en".parse().unwrap(), "sku")
546///     .field("price", FieldMapping::new("price", FieldType::Number))
547///     .field("stock", FieldMapping::new("qty", FieldType::Integer));
548/// let bounds = FeedBounds {
549///     max_change_fraction: FeedBounds::DEFAULT_MAX_CHANGE_FRACTION,
550///     price_rule: PriceRule::default(),
551///     field_bounds: Default::default(),
552///     max_rate: Rate { per_minute: 10_000 },
553/// };
554/// engine.add_feed(mapping, bounds).await?;
555/// let outcome = engine.ingest("supplier", vec![FeedRecord::new([("sku", "A1".into()), ("qty", 3.into())])]).await?;
556/// assert_eq!(outcome.queued, 0, "a stock change never makes a release");
557/// engine.tick().await?;
558/// # Ok(())
559/// # }
560/// ```
561pub struct UpdateEngine {
562    pipeline: Arc<PublishingPipeline>,
563    store: Arc<dyn ContentStore>,
564    history: Option<Arc<dyn ContentHistory>>,
565    live: Arc<dyn LiveStore>,
566    price_rule: PriceRule,
567    approve_new_items: bool,
568    alarms: Option<Arc<dyn AlarmSink>>,
569    audit: Option<(Arc<dyn AuditRecorder>, ActingContext)>,
570    costs: CostRates,
571    streams: Option<Arc<StreamLane>>,
572    held: Arc<dyn HeldStore>,
573    clock: Arc<dyn Clock>,
574    inner: Mutex<Inner>,
575}
576
577impl std::fmt::Debug for UpdateEngine {
578    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
579        f.debug_struct("UpdateEngine").finish_non_exhaustive()
580    }
581}
582
583fn percentile(values: &mut [i64], p: f64) -> Option<i64> {
584    if values.is_empty() {
585        return None;
586    }
587    values.sort_unstable();
588    let rank = ((p / 100.0) * values.len() as f64).ceil() as usize;
589    Some(values[rank.clamp(1, values.len()) - 1])
590}
591
592impl UpdateEngine {
593    /// Starts an engine over `pipeline`, writing live values to `live`.
594    pub fn builder(
595        pipeline: Arc<PublishingPipeline>,
596        live: Arc<dyn LiveStore>,
597    ) -> UpdateEngineBuilder {
598        UpdateEngineBuilder {
599            pipeline,
600            live,
601            policies: BatchPolicies::default(),
602            price_rule: PriceRule::default(),
603            approve_new_items: true,
604            alarms: None,
605            audit: None,
606            costs: CostRates::default(),
607            schedule: FullCheckSchedule::default(),
608            streams: None,
609            held: None,
610        }
611    }
612
613    /// The engine's state, with what it holds read from its [`HeldStore`] on first use.
614    async fn lock_held(&self) -> Result<tokio::sync::MutexGuard<'_, Inner>> {
615        let mut inner = self.inner.lock().await;
616        if !inner.restored {
617            let state = self.held.load().await?;
618            let restored = (state.items.len(), state.deliveries.len());
619            for item in state.items {
620                inner.held_items.entry(item.update.id().clone()).or_insert(item);
621            }
622            let mut next = inner.next_delivery.max(state.next_delivery);
623            for delivery in state.deliveries {
624                next = next.max(delivery.delivery + 1);
625                inner.held_deliveries.entry(delivery.delivery).or_insert(delivery);
626            }
627            inner.next_delivery = next;
628            inner.restored = true;
629            if restored != (0, 0) {
630                tracing::info!(
631                    site.held.items = restored.0,
632                    site.held.deliveries = restored.1,
633                    "held updates restored"
634                );
635            }
636        }
637        Ok(inner)
638    }
639
640    /// Writes what the engine holds to its [`HeldStore`].
641    async fn save_held(&self, inner: &Inner) -> Result<()> {
642        self.held.save(&inner.held_state()).await
643    }
644
645    /// The pipeline releases go through.
646    pub fn pipeline(&self) -> &Arc<PublishingPipeline> {
647        &self.pipeline
648    }
649
650    /// Adds a feed the owner configured (A-I24).
651    ///
652    /// # Errors
653    ///
654    /// [`SiteError::InvalidConfig`] for a mapping that fills a stream field, maps nothing,
655    /// or reuses a feed name; or bounds with a change fraction outside (0, 1].
656    pub async fn add_feed(&self, mapping: FeedMapping, bounds: FeedBounds) -> Result<()> {
657        mapping.validate(self.pipeline.site_config())?;
658        if !(bounds.max_change_fraction > 0.0 && bounds.max_change_fraction <= 1.0) {
659            return Err(SiteError::InvalidConfig(format!(
660                "feed '{}' has a max change fraction of {}; use a share above 0 and at most 1",
661                mapping.feed, bounds.max_change_fraction
662            )));
663        }
664        let mut inner = self.inner.lock().await;
665        if inner.feeds.contains_key(&mapping.feed) {
666            return Err(SiteError::InvalidConfig(format!(
667                "a feed named '{}' is already configured",
668                mapping.feed
669            )));
670        }
671        inner.feeds.insert(
672            mapping.feed.clone(),
673            FeedState {
674                mapping,
675                bounds,
676                deliveries: 0,
677                records: 0,
678                recent: VecDeque::new(),
679                last_delivery: None,
680                held: 0,
681            },
682        );
683        Ok(())
684    }
685
686    /// Pulls one delivery from `source` and ingests it under the source's name.
687    ///
688    /// # Errors
689    ///
690    /// As [`ingest`](Self::ingest); errors from the source.
691    pub async fn pull(&self, source: &dyn ContentSource) -> Result<DeliveryOutcome> {
692        let records = source.pull().await?;
693        self.ingest(source.name(), records).await
694    }
695
696    /// Ingests one delivery of `feed`: maps it without a model, checks its bounds, writes its
697    /// live values and queues its item versions; a delivery that breaks its bounds is held
698    /// whole with a P2 alarm (A-I27).
699    ///
700    /// # Errors
701    ///
702    /// [`SiteError::NotFound`] for an unknown feed; store, alarm and publishing errors.
703    pub async fn ingest(&self, feed: &str, records: Vec<FeedRecord>) -> Result<DeliveryOutcome> {
704        let now = self.clock.now();
705        let (mapping, bounds_config, last_minute, delivery) = {
706            let mut inner = self.lock_held().await?;
707            let delivery = inner.next_delivery;
708            inner.next_delivery += 1;
709            let state = inner
710                .feeds
711                .get_mut(feed)
712                .ok_or_else(|| SiteError::NotFound(format!("feed '{feed}'")))?;
713            state.deliveries += 1;
714            state.records += records.len() as u64;
715            state.last_delivery = Some(now);
716            state.recent.push_back((now, records.len() as u64));
717            while state
718                .recent
719                .front()
720                .is_some_and(|(at, _)| now - *at > chrono::Duration::minutes(1))
721            {
722                state.recent.pop_front();
723            }
724            let last_minute = state.records_last_minute(now);
725            inner.review.deliveries += 1;
726            (
727                inner.feeds[feed].mapping.clone(),
728                inner.feeds[feed].bounds.clone(),
729                last_minute,
730                delivery,
731            )
732        };
733        let mut mapped = Vec::new();
734        let mut problems = Vec::new();
735        for record in &records {
736            match mapping.map(record, now) {
737                Ok(record) => mapped.push(record),
738                Err(problem) => problems.push(problem),
739            }
740        }
741        let current: BTreeMap<ContentId, ContentItem> =
742            self.store.list().await?.into_iter().map(|item| (item.id.clone(), item)).collect();
743        let collection = current.values().filter(|item| item.kind == mapping.kind).count();
744        let changes = mapping.changes(self.pipeline.site_config(), &mapped, &current, now);
745        let report = bounds::check(
746            &bounds_config,
747            &Delivery {
748                records: records.len(),
749                mapped: &mapped,
750                problems: &problems,
751                changes: &changes,
752                collection,
753                records_last_minute: last_minute,
754                now,
755            },
756        );
757        if report.held() {
758            let held = HeldDelivery {
759                delivery,
760                feed: feed.to_string(),
761                received_at: now,
762                report: report.clone(),
763                changes,
764            };
765            {
766                let mut inner = self.lock_held().await?;
767                inner.review.held_deliveries += 1;
768                if let Some(state) = inner.feeds.get_mut(feed) {
769                    state.held += 1;
770                }
771                inner.held_deliveries.insert(delivery, held);
772                self.save_held(&inner).await?;
773            }
774            tracing::warn!(
775                feed,
776                delivery,
777                breaks = report.breaks.len(),
778                "site.batch.held: feed bounds broken (A-I27)"
779            );
780            let detail = serde_json::json!({
781                "feed": feed,
782                "delivery": delivery,
783                "breaks": report.breaks,
784                "summary": report.summary,
785            });
786            self.record("site.batch.held", detail.clone()).await?;
787            self.alarm(
788                Urgency::P2,
789                "site.feed.held",
790                format!(
791                    "Feed '{feed}' delivery {delivery} broke its bounds and is held: it would change {} of {} items",
792                    report.summary.items_changed, report.summary.collection
793                ),
794                detail,
795            )
796            .await?;
797            return Ok(DeliveryOutcome { delivery, held: true, ..DeliveryOutcome::default() });
798        }
799        let unknown = changes.unknown.clone();
800        let mut outcome = self.apply(feed, changes, now).await?;
801        outcome.delivery = delivery;
802        outcome.unknown = unknown;
803        Ok(outcome)
804    }
805
806    /// Writes a delivery's live values and queues its item versions.
807    async fn apply(
808        &self,
809        feed: &str,
810        changes: FeedChanges,
811        now: DateTime<Utc>,
812    ) -> Result<DeliveryOutcome> {
813        for change in &changes.live {
814            let values = change
815                .fields
816                .iter()
817                .map(|(field, value)| {
818                    let live =
819                        LiveValue { value: value.clone(), at: now, feed: Some(feed.to_string()) };
820                    (field.clone(), live)
821                })
822                .collect();
823            self.live.set(&change.id, values).await?;
824        }
825        let queued = changes.release.len();
826        let updates: Vec<Update> = changes
827            .release
828            .into_iter()
829            .map(|change| Update {
830                item: change.after,
831                at: now,
832                entry: EntryPoint::Feed { feed: feed.to_string() },
833                proposer: format!("feed:{feed}"),
834                trigger: None,
835                model_calls: 0,
836            })
837            .collect();
838        {
839            let mut inner = self.inner.lock().await;
840            inner.review.live_updates += changes.live.len() as u64;
841            inner.review.updates += changes.live.len() as u64;
842        }
843        let batches = self.queue(updates).await?;
844        Ok(DeliveryOutcome {
845            delivery: 0,
846            held: false,
847            live: changes.live.len(),
848            queued,
849            unknown: Vec::new(),
850            batches,
851        })
852    }
853
854    /// Submits a change from an entry point that authors content (A-I24): an owner, an
855    /// editor, a committer, an agent, a schedule or a stream fold. A change whose trigger the
856    /// policy lists publishes at once with everything pending.
857    ///
858    /// # Errors
859    ///
860    /// Store, alarm and publishing errors.
861    pub async fn submit(&self, update: Update) -> Result<Vec<BatchRecord>> {
862        self.queue(vec![update]).await
863    }
864
865    async fn queue(&self, updates: Vec<Update>) -> Result<Vec<BatchRecord>> {
866        let closed = {
867            let mut inner = self.inner.lock().await;
868            let mut closed = Vec::new();
869            for update in updates {
870                inner.review.updates += 1;
871                inner.review.release_updates += 1;
872                inner.review.model_calls += u64::from(update.model_calls);
873                if update.model_calls > 0 {
874                    inner.review.updates_with_model += 1;
875                }
876                closed.extend(inner.batcher.push(update));
877            }
878            closed
879        };
880        self.publish_all(closed).await
881    }
882
883    /// Folds the streams that are due, closes the windows that have elapsed, publishes
884    /// them, and runs the full checks when they are due.
885    ///
886    /// # Errors
887    ///
888    /// Store, alarm, gate, signing and publishing errors.
889    pub async fn tick(&self) -> Result<Vec<BatchRecord>> {
890        let mut records = self.fold_streams().await?;
891        let now = self.clock.now();
892        let closed = self.inner.lock().await.batcher.poll(now);
893        records.extend(self.publish_all(closed).await?);
894        self.full_checks_if_due().await?;
895        Ok(records)
896    }
897
898    fn lane(&self) -> Result<&Arc<StreamLane>> {
899        self.streams
900            .as_ref()
901            .ok_or_else(|| SiteError::Pipeline("the engine has no stream lane".into()))
902    }
903
904    /// Opens a stream on a published story's stream field (spec 3.5 §7.8.3 "Stream").
905    ///
906    /// # Errors
907    ///
908    /// [`SiteError::NotFound`] for an unknown story; [`SiteError::InvalidConfig`] when
909    /// `field` is not a stream field of the story's kind; as [`StreamLane::open`].
910    pub async fn open_stream(&self, item: &ContentId, field: &str) -> Result<()> {
911        let story =
912            self.store.get(item).await?.ok_or_else(|| SiteError::NotFound(item.0.clone()))?;
913        let config = self.pipeline.site_config();
914        if !crate::lanes::stream_fields(config, story.kind).iter().any(|f| f == field) {
915            return Err(SiteError::InvalidConfig(format!(
916                "'{field}' is not a stream field of {} items; declare it under [lanes.{}] stream",
917                crate::content::kind_name(story.kind),
918                crate::content::kind_name(story.kind)
919            )));
920        }
921        self.lane()?.open(&story, field, self.clock.now()).await
922    }
923
924    /// Appends a reporter's entry to an open stream; the edge serves it at once.
925    ///
926    /// # Errors
927    ///
928    /// As [`StreamLane::append`].
929    pub async fn append_entry(
930        &self,
931        item: &ContentId,
932        markdown: &str,
933        corrects: Option<u64>,
934    ) -> Result<awp_types::StreamEntry> {
935        self.lane()?.append(item, markdown, corrects, self.clock.now()).await
936    }
937
938    /// The entries of a stream after number `after`: the edge feed the page polls.
939    ///
940    /// # Errors
941    ///
942    /// As [`StreamLane::since`].
943    pub async fn stream_since(
944        &self,
945        item: &ContentId,
946        after: u64,
947    ) -> Result<Vec<awp_types::StreamEntry>> {
948        self.lane()?.since(item, after).await
949    }
950
951    /// Closes a stream; its last entries fold at the next [`tick`](Self::tick).
952    ///
953    /// # Errors
954    ///
955    /// As [`StreamLane::close`].
956    pub async fn close_stream(&self, item: &ContentId) -> Result<()> {
957        self.lane()?.close(item, self.clock.now()).await
958    }
959
960    /// The streams and their folds.
961    pub async fn streams(&self) -> Vec<StreamStatus> {
962        match &self.streams {
963            Some(lane) => lane.status().await,
964            None => Vec::new(),
965        }
966    }
967
968    /// Folds every due stream into its story and queues the folded story for release.
969    async fn fold_streams(&self) -> Result<Vec<BatchRecord>> {
970        let Some(lane) = &self.streams else { return Ok(Vec::new()) };
971        let now = self.clock.now();
972        let mut updates = Vec::new();
973        for id in lane.due(now).await {
974            let Some(story) = self.store.get(&id).await? else { continue };
975            if let Some(folded) = lane.fold(&story, now).await? {
976                let entries =
977                    lane.status().await.into_iter().find(|s| s.item == id).map_or(0, |s| s.entries);
978                self.record(
979                    "site.stream.folded",
980                    serde_json::json!({ "item": id, "entries": entries }),
981                )
982                .await?;
983                updates.push(Update {
984                    item: folded,
985                    at: now,
986                    entry: EntryPoint::Schedule,
987                    proposer: format!("stream:{id}"),
988                    trigger: None,
989                    model_calls: 0,
990                });
991            }
992        }
993        if updates.is_empty() {
994            return Ok(Vec::new());
995        }
996        self.queue(updates).await
997    }
998
999    /// Publishes everything pending now, as at shutdown.
1000    ///
1001    /// # Errors
1002    ///
1003    /// As [`tick`](Self::tick).
1004    pub async fn drain(&self) -> Result<Vec<BatchRecord>> {
1005        let now = self.clock.now();
1006        let closed = self.inner.lock().await.batcher.drain(now);
1007        self.publish_all(closed.into_iter().collect()).await
1008    }
1009
1010    /// When the next window closes, for a scheduler's wake.
1011    pub async fn next_due(&self) -> Option<DateTime<Utc>> {
1012        self.inner.lock().await.batcher.next_due()
1013    }
1014
1015    async fn publish_all(&self, batches: Vec<Batch>) -> Result<Vec<BatchRecord>> {
1016        let mut records = Vec::new();
1017        for batch in batches {
1018            records.push(self.publish(batch).await?);
1019        }
1020        Ok(records)
1021    }
1022
1023    /// The exception an update raises, if any: a price outside the rule or a new item.
1024    fn exception(
1025        &self,
1026        update: &Update,
1027        before: Option<&ContentItem>,
1028        rules: &BTreeMap<String, PriceRule>,
1029    ) -> Option<HoldReason> {
1030        if update.trigger == Some(Trigger::OwnerRequest) {
1031            return None;
1032        }
1033        if before.is_none() && self.approve_new_items {
1034            return Some(HoldReason::NewItem);
1035        }
1036        let rule = match &update.entry {
1037            EntryPoint::Feed { feed } => rules.get(feed).copied().unwrap_or(self.price_rule),
1038            _ => self.price_rule,
1039        };
1040        (!price_within_rule(&rule, before, &update.item))
1041            .then_some(HoldReason::PriceRule { allowed_pct: rule.auto_within_pct })
1042    }
1043
1044    async fn publish(&self, batch: Batch) -> Result<BatchRecord> {
1045        let rules: BTreeMap<String, PriceRule> = {
1046            let inner = self.inner.lock().await;
1047            inner
1048                .feeds
1049                .iter()
1050                .map(|(name, state)| (name.clone(), state.bounds.price_rule))
1051                .collect()
1052        };
1053        let now = self.clock.now();
1054        let mut publish = Vec::new();
1055        let mut arrived: BTreeMap<ContentId, DateTime<Utc>> = BTreeMap::new();
1056        let mut held: Vec<(ContentId, HoldReason)> = Vec::new();
1057        let mut new_holds = Vec::new();
1058        for update in &batch.updates {
1059            let before = self.store.get(update.id()).await?;
1060            match self.exception(update, before.as_ref(), &rules) {
1061                Some(reason) => {
1062                    held.push((update.id().clone(), reason.clone()));
1063                    new_holds.push(HeldItem {
1064                        update: update.clone(),
1065                        reason,
1066                        batch: batch.id,
1067                        held_at: now,
1068                    });
1069                }
1070                None => {
1071                    arrived.insert(update.id().clone(), update.at);
1072                    publish.push(self.with_live_values(update.item.clone()).await?);
1073                }
1074            }
1075        }
1076        let feeds: BTreeSet<&str> = batch
1077            .updates
1078            .iter()
1079            .filter_map(|u| match &u.entry {
1080                EntryPoint::Feed { feed } => Some(feed.as_str()),
1081                _ => None,
1082            })
1083            .collect();
1084        let all_feed = batch.updates.iter().all(|u| matches!(u.entry, EntryPoint::Feed { .. }));
1085        let first = batch.updates.first().map(|u| u.proposer.clone()).unwrap_or_default();
1086        let (job, actor) = match feeds.iter().next() {
1087            Some(feed) if all_feed && feeds.len() == 1 => {
1088                (format!("feed:{feed}"), format!("feed:{feed}"))
1089            }
1090            _ if batch.updates.iter().all(|u| u.proposer == first) => ("batch".to_string(), first),
1091            _ => ("batch".to_string(), "batch".to_string()),
1092        };
1093        let superseded: Vec<ContentItem> =
1094            batch.superseded.iter().map(|u| u.item.clone()).collect();
1095        let source = ReleaseSource::Edit { job, decision: None };
1096        let mut record = BatchRecord {
1097            batch: batch.id,
1098            opened_at: batch.opened_at,
1099            closed_at: batch.closed_at,
1100            reason: batch.reason,
1101            release_seq: None,
1102            live_at: None,
1103            published: Vec::new(),
1104            superseded: batch.superseded.len(),
1105            held: Vec::new(),
1106            refused: None,
1107            catalog_pages: 0,
1108            latencies_ms: Vec::new(),
1109            model_calls: batch.model_calls(),
1110        };
1111        match self.pipeline.publish_batch(publish, superseded, source, &actor).await {
1112            Ok(release) => {
1113                for (id, findings) in &release.held {
1114                    let Some(update) = batch.updates.iter().find(|u| u.id() == id) else {
1115                        continue;
1116                    };
1117                    let reason = HoldReason::FastTier { findings: findings.clone() };
1118                    held.push((id.clone(), reason.clone()));
1119                    new_holds.push(HeldItem {
1120                        update: update.clone(),
1121                        reason,
1122                        batch: batch.id,
1123                        held_at: now,
1124                    });
1125                }
1126                if let Some(published) = &release.published {
1127                    let live_at = self.clock.now();
1128                    record.release_seq = Some(published.staged.manifest.seq);
1129                    record.live_at = Some(live_at);
1130                    record.published = published.tag.items.clone();
1131                    record.catalog_pages = published.announcement.catalog_pages.len();
1132                    record.latencies_ms = record
1133                        .published
1134                        .iter()
1135                        .filter_map(|id| arrived.get(id))
1136                        .map(|at| (live_at - *at).num_milliseconds())
1137                        .collect();
1138                }
1139            }
1140            Err(SiteError::GateFailed(summary)) => {
1141                record.refused = Some(summary.clone());
1142                let detail = serde_json::json!({ "batch": batch.id, "gate": summary });
1143                self.record("site.release.refused", detail.clone()).await?;
1144                self.alarm(
1145                    Urgency::P2,
1146                    "site.release.refused",
1147                    format!("Batch {} was refused whole: it holds server code (A-I1)", batch.id),
1148                    detail,
1149                )
1150                .await?;
1151            }
1152            Err(error) => return Err(error),
1153        }
1154        record.held = held;
1155        {
1156            let mut inner = self.lock_held().await?;
1157            inner.review.held_items += new_holds.len() as u64;
1158            if record.release_seq.is_some() {
1159                inner.review.releases += 1;
1160            }
1161            let holds = !new_holds.is_empty();
1162            for hold in new_holds {
1163                inner.held_items.insert(hold.update.id().clone(), hold);
1164            }
1165            if holds {
1166                self.save_held(&inner).await?;
1167            }
1168            inner.records.push_back(record.clone());
1169            while inner.records.len() > RECORDS_KEPT {
1170                inner.records.pop_front();
1171            }
1172        }
1173        if !record.held.is_empty() {
1174            let detail = serde_json::json!({ "batch": record.batch, "held": record.held });
1175            self.record("site.batch.held", detail).await?;
1176        }
1177        if let Some(seq) = record.release_seq {
1178            let detail = serde_json::json!({
1179                "batch": record.batch,
1180                "releaseSeq": seq,
1181                "items": record.published.len(),
1182                "superseded": record.superseded,
1183            });
1184            self.record("site.batch.published", detail).await?;
1185        }
1186        Ok(record)
1187    }
1188
1189    /// The item with its live fields set to the values the edge serves now, so the page
1190    /// shows the last released value with its time when script is off (spec 3.5 §7.8.3).
1191    async fn with_live_values(&self, mut item: ContentItem) -> Result<ContentItem> {
1192        let fields: Vec<String> = crate::lanes::live_fields(self.pipeline.site_config(), &item)
1193            .into_iter()
1194            .map(str::to_string)
1195            .collect();
1196        if fields.is_empty() {
1197            return Ok(item);
1198        }
1199        let live = self.live.get(&item.id).await?;
1200        for field in fields {
1201            if let Some(value) = live.get(&field) {
1202                item.fields.insert(field, value.value.clone());
1203            }
1204        }
1205        Ok(item)
1206    }
1207
1208    async fn full_checks_if_due(&self) -> Result<Option<GateReport>> {
1209        let now = self.clock.now();
1210        let seq = self.pipeline.previous().await.map_or(0, |p| p.manifest.seq);
1211        if !self.inner.lock().await.schedule.due(now, seq) {
1212            return Ok(None);
1213        }
1214        let report = self.pipeline.full_check().await?;
1215        {
1216            let mut inner = self.inner.lock().await;
1217            inner.schedule.ran(now, seq);
1218            inner.review.full_checks += 1;
1219        }
1220        if !report.passed() {
1221            let detail = serde_json::json!({ "releaseSeq": seq, "summary": report.summary() });
1222            self.alarm(
1223                Urgency::P2,
1224                "site.checks.failed",
1225                format!("The scheduled full checks failed on release {seq}: {}", report.summary()),
1226                detail,
1227            )
1228            .await?;
1229        }
1230        Ok(Some(report))
1231    }
1232
1233    /// Runs the scheduled full checks now.
1234    ///
1235    /// # Errors
1236    ///
1237    /// Build and gate errors.
1238    pub async fn run_full_checks(&self) -> Result<GateReport> {
1239        let now = self.clock.now();
1240        let seq = self.pipeline.previous().await.map_or(0, |p| p.manifest.seq);
1241        let report = self.pipeline.full_check().await?;
1242        let mut inner = self.inner.lock().await;
1243        inner.schedule.ran(now, seq);
1244        inner.review.full_checks += 1;
1245        Ok(report)
1246    }
1247
1248    /// The owner's decision on a held delivery: release applies it whole, discard drops it
1249    /// (spec 3.5 A-I27).
1250    ///
1251    /// # Errors
1252    ///
1253    /// [`SiteError::NotFound`] for a delivery that is not held; as [`ingest`](Self::ingest).
1254    pub async fn decide_delivery(
1255        &self,
1256        delivery: u64,
1257        decision: Decision,
1258        by: &str,
1259    ) -> Result<DeliveryOutcome> {
1260        let held = {
1261            let mut inner = self.lock_held().await?;
1262            let held = inner
1263                .held_deliveries
1264                .remove(&delivery)
1265                .ok_or_else(|| SiteError::NotFound(format!("held delivery {delivery}")))?;
1266            self.save_held(&inner).await?;
1267            held
1268        };
1269        let detail = serde_json::json!({ "delivery": delivery, "feed": held.feed, "decision": decision, "by": by });
1270        self.record("site.batch.decided", detail).await?;
1271        match decision {
1272            Decision::Discard => Ok(DeliveryOutcome { delivery, ..DeliveryOutcome::default() }),
1273            Decision::Release => {
1274                let kept = held.clone();
1275                match self.apply(&held.feed, held.changes, self.clock.now()).await {
1276                    Ok(mut outcome) => {
1277                        outcome.delivery = delivery;
1278                        Ok(outcome)
1279                    }
1280                    Err(error) => {
1281                        // Still held: the owner's decision did not take effect.
1282                        let mut inner = self.lock_held().await?;
1283                        inner.held_deliveries.insert(delivery, kept);
1284                        self.save_held(&inner).await?;
1285                        Err(error)
1286                    }
1287                }
1288            }
1289        }
1290    }
1291
1292    /// The owner's decision on a held item. Releasing it publishes it at once; the approver
1293    /// must not be the change's proposer (A-I23).
1294    ///
1295    /// # Errors
1296    ///
1297    /// [`SiteError::NotFound`] for an item that is not held; [`SiteError::Pipeline`] when
1298    /// the proposer approves their own change; publishing errors.
1299    pub async fn decide_item(
1300        &self,
1301        id: &ContentId,
1302        decision: Decision,
1303        by: &str,
1304    ) -> Result<Vec<BatchRecord>> {
1305        let held = {
1306            let mut inner = self.lock_held().await?;
1307            let held = inner.held_items.get(id).ok_or_else(|| SiteError::NotFound(id.0.clone()))?;
1308            if decision == Decision::Release && held.update.proposer == by {
1309                return Err(SiteError::Pipeline(format!(
1310                    "'{by}' proposed the change and cannot approve it (A-I23)"
1311                )));
1312            }
1313            let held =
1314                inner.held_items.remove(id).ok_or_else(|| SiteError::NotFound(id.0.clone()))?;
1315            self.save_held(&inner).await?;
1316            held
1317        };
1318        let detail = serde_json::json!({ "item": id, "decision": decision, "by": by });
1319        self.record("site.content.decided", detail).await?;
1320        match decision {
1321            Decision::Discard => Ok(Vec::new()),
1322            Decision::Release => {
1323                let mut update = held.update.clone();
1324                update.at = self.clock.now();
1325                update.trigger = Some(Trigger::OwnerRequest);
1326                match self.submit(update).await {
1327                    Ok(records) => Ok(records),
1328                    Err(error) => {
1329                        // Still held: the owner's decision did not take effect.
1330                        let mut inner = self.lock_held().await?;
1331                        inner.held_items.insert(id.clone(), held);
1332                        self.save_held(&inner).await?;
1333                        Err(error)
1334                    }
1335                }
1336            }
1337        }
1338    }
1339
1340    /// Publishes one item's earlier version as a new release and keeps every other change:
1341    /// the version release `to` served, or the one before its latest release (spec 3.5
1342    /// §7.8.3 "Undo per item", `site revert <item> [--to <seq>]`).
1343    ///
1344    /// # Errors
1345    ///
1346    /// [`SiteError::Pipeline`] without a content history or an earlier version; publishing
1347    /// errors.
1348    pub async fn revert(
1349        &self,
1350        id: &ContentId,
1351        to: Option<u64>,
1352        by: &str,
1353        entry: EntryPoint,
1354    ) -> Result<Vec<BatchRecord>> {
1355        let history = self
1356            .history
1357            .as_ref()
1358            .ok_or_else(|| SiteError::Pipeline("reverting needs a content history".into()))?;
1359        let version = match to {
1360            Some(seq) => history.at_release(id, seq).await?,
1361            None => history.previous_release(id).await?,
1362        }
1363        .ok_or_else(|| {
1364            SiteError::Pipeline(format!("item '{id}' has no earlier released version"))
1365        })?;
1366        let detail =
1367            serde_json::json!({ "item": id, "to": to, "version": version.version, "by": by });
1368        self.record("site.content.reverted", detail).await?;
1369        tracing::info!(item = %id, version = version.version, "site.content.reverted");
1370        self.submit(Update {
1371            item: version.item,
1372            at: self.clock.now(),
1373            entry,
1374            proposer: by.to_string(),
1375            trigger: Some(Trigger::OwnerRequest),
1376            model_calls: 0,
1377        })
1378        .await
1379    }
1380
1381    /// The items changed in releases after `since`, with their latest released versions,
1382    /// in release order: what the Steward proposes replaying after a rollback to `since`
1383    /// (spec 3.5 §7.8.3 "Undo per item").
1384    ///
1385    /// # Errors
1386    ///
1387    /// [`SiteError::Pipeline`] without a content history; store and history errors.
1388    pub async fn replay_list(&self, since: u64) -> Result<Vec<ReplayCandidate>> {
1389        let history = self
1390            .history
1391            .as_ref()
1392            .ok_or_else(|| SiteError::Pipeline("a replay list needs a content history".into()))?;
1393        let mut candidates = Vec::new();
1394        for item in self.store.list().await? {
1395            let latest = history
1396                .versions(&item.id)
1397                .await?
1398                .into_iter()
1399                .filter(|entry| entry.meta.release_seq.is_some_and(|seq| seq > since))
1400                .max_by_key(|entry| (entry.meta.release_seq, entry.version));
1401            if let Some(HistoryEntry { version, meta, .. }) = latest {
1402                candidates.push(ReplayCandidate {
1403                    id: item.id.clone(),
1404                    release_seq: meta.release_seq.unwrap_or_default(),
1405                    at: meta.at,
1406                    actor: meta.actor,
1407                    version,
1408                });
1409            }
1410        }
1411        candidates.sort_by(|a, b| (a.release_seq, &a.id).cmp(&(b.release_seq, &b.id)));
1412        Ok(candidates)
1413    }
1414
1415    /// Rolls the whole site back to release `to_seq` for an incident (A-I11), puts the
1416    /// working copy back to what that release served, and returns the changes made since,
1417    /// which the Steward proposes replaying one by one with [`replay`](Self::replay).
1418    ///
1419    /// # Errors
1420    ///
1421    /// As [`PublishingPipeline::rollback`] and [`replay_list`](Self::replay_list).
1422    pub async fn rollback(&self, to_seq: u64) -> Result<(Published, Vec<ReplayCandidate>)> {
1423        let candidates = self.replay_list(to_seq).await?;
1424        let published = self.pipeline.rollback(to_seq).await?;
1425        if let Some(history) = &self.history {
1426            for candidate in &candidates {
1427                match history.at_release(&candidate.id, to_seq).await? {
1428                    Some(entry) => self.store.put(&entry.item).await?,
1429                    None => {
1430                        self.store.remove(&candidate.id).await?;
1431                    }
1432                }
1433            }
1434        }
1435        Ok((published, candidates))
1436    }
1437
1438    /// Publishes a change listed by [`rollback`](Self::rollback) again, as the owner's
1439    /// request.
1440    ///
1441    /// # Errors
1442    ///
1443    /// [`SiteError::NotFound`] when the version is gone from the history; publishing errors.
1444    pub async fn replay(
1445        &self,
1446        candidate: &ReplayCandidate,
1447        by: &str,
1448        entry: EntryPoint,
1449    ) -> Result<Vec<BatchRecord>> {
1450        let history = self
1451            .history
1452            .as_ref()
1453            .ok_or_else(|| SiteError::Pipeline("replaying needs a content history".into()))?;
1454        let version = history
1455            .versions(&candidate.id)
1456            .await?
1457            .into_iter()
1458            .find(|entry| entry.version == candidate.version)
1459            .ok_or_else(|| {
1460                SiteError::NotFound(format!("{} version {}", candidate.id, candidate.version))
1461            })?;
1462        self.submit(Update {
1463            item: version.item,
1464            at: self.clock.now(),
1465            entry,
1466            proposer: by.to_string(),
1467            trigger: Some(Trigger::OwnerRequest),
1468            model_calls: 0,
1469        })
1470        .await
1471    }
1472
1473    /// Recent batches with their held items, newest last (`site batches`).
1474    pub async fn batches(&self) -> Vec<BatchRecord> {
1475        self.inner.lock().await.records.iter().cloned().collect()
1476    }
1477
1478    /// Items held alone, waiting for a decision, including those held before a restart.
1479    pub async fn held_items(&self) -> Vec<HeldItem> {
1480        match self.lock_held().await {
1481            Ok(inner) => inner.held_items.values().cloned().collect(),
1482            Err(error) => {
1483                tracing::warn!(error = %error, "held updates could not be read");
1484                self.inner.lock().await.held_items.values().cloned().collect()
1485            }
1486        }
1487    }
1488
1489    /// Deliveries held whole, waiting for the owner, including those held before a restart.
1490    pub async fn held_deliveries(&self) -> Vec<HeldDelivery> {
1491        match self.lock_held().await {
1492            Ok(inner) => inner.held_deliveries.values().cloned().collect(),
1493            Err(error) => {
1494                tracing::warn!(error = %error, "held updates could not be read");
1495                self.inner.lock().await.held_deliveries.values().cloned().collect()
1496            }
1497        }
1498    }
1499
1500    /// Feeds with their bounds and rates (`site feeds`).
1501    pub async fn feeds(&self) -> Vec<FeedStatus> {
1502        let now = self.clock.now();
1503        self.inner
1504            .lock()
1505            .await
1506            .feeds
1507            .values()
1508            .map(|state| FeedStatus {
1509                mapping: state.mapping.clone(),
1510                bounds: state.bounds.clone(),
1511                deliveries: state.deliveries,
1512                records: state.records,
1513                records_last_minute: state.records_last_minute(now),
1514                last_delivery: state.last_delivery,
1515                held: state.held,
1516                model_calls: 0,
1517            })
1518            .collect()
1519    }
1520
1521    /// Update counts and costs for the weekly review: cost per thousand updates and the
1522    /// share of updates that needed a model.
1523    pub async fn review(&self) -> UpdateReview {
1524        let mut review = self.inner.lock().await.review.clone();
1525        review.model_share = if review.updates == 0 {
1526            0.0
1527        } else {
1528            review.updates_with_model as f64 / review.updates as f64
1529        };
1530        review.cost_micros = review.model_calls * self.costs.per_model_call_micros
1531            + review.releases * self.costs.per_release_micros;
1532        review.cost_per_thousand_updates_micros = if review.updates == 0 {
1533            0.0
1534        } else {
1535            review.cost_micros as f64 * 1_000.0 / review.updates as f64
1536        };
1537        review
1538    }
1539
1540    /// The 50th and 95th percentile approval-to-live, in milliseconds, over the batches
1541    /// kept for `site batches`.
1542    pub async fn latency_percentiles(&self) -> Option<(i64, i64)> {
1543        let mut all: Vec<i64> =
1544            self.inner.lock().await.records.iter().flat_map(|r| r.latencies_ms.clone()).collect();
1545        let p50 = percentile(&mut all, 50.0)?;
1546        let p95 = percentile(&mut all, 95.0)?;
1547        Some((p50, p95))
1548    }
1549
1550    async fn alarm(
1551        &self,
1552        urgency: Urgency,
1553        code: &str,
1554        title: String,
1555        detail: Value,
1556    ) -> Result<()> {
1557        let alarm = SiteAlarm {
1558            urgency,
1559            code: code.into(),
1560            title,
1561            detail: detail.clone(),
1562            at: self.clock.now(),
1563        };
1564        if let Some(alarms) = &self.alarms {
1565            alarms.raise(&alarm).await?;
1566        }
1567        self.record(
1568            "website.alarm.raised",
1569            serde_json::json!({ "code": code, "urgency": urgency, "detail": detail }),
1570        )
1571        .await
1572    }
1573
1574    async fn record(&self, action: &str, value: Value) -> Result<()> {
1575        let Some((recorder, acting)) = &self.audit else { return Ok(()) };
1576        let draft = AuditRecordDraft::new(AuditRecordKind::Other("site".into()), action)
1577            .actor(AuditActor::new(acting, ""))
1578            .args_digest(recorder.digest(&value))
1579            .ext("site", value);
1580        recorder.record(draft).await.map_err(|e| SiteError::Pipeline(format!("audit: {e}")))
1581    }
1582}
1583
1584#[cfg(test)]
1585mod tests {
1586    use super::*;
1587
1588    #[test]
1589    fn percentiles_pick_ranks() {
1590        let mut values = vec![5, 1, 4, 2, 3, 6, 7, 8, 9, 10];
1591        assert_eq!(percentile(&mut values, 50.0), Some(5));
1592        assert_eq!(percentile(&mut values, 95.0), Some(10));
1593        assert_eq!(percentile(&mut [], 95.0), None);
1594    }
1595}