Skip to main content

adk_site/
stream.rs

1//! The stream lane: live blogs, tickers and emergency updates (spec 3.5 §7.8.3 "Three
2//! lanes", A-I26).
3//!
4//! A reporter's entry goes to the edge, which signs it with its delegated `receipt` key and
5//! serves it at once in a feed the page polls ([`StreamLane::since`]). Every
6//! `fold_interval` (default five minutes) and when the stream closes, the entries are folded
7//! into the story's stream field and released through the batcher, so every entry ends up
8//! in a signed release. Entries are [`StreamEntry`] documents with a detached JWS over their
9//! JCS form without `proof`, the same proof every AWP 2.0 document carries; a fold refuses
10//! an entry whose proof does not verify.
11//!
12//! A stream belongs to a story that is already published: the story passes its approval
13//! chain once, and its entries and folds run at the live job's level.
14
15use std::collections::BTreeMap;
16use std::time::Duration;
17
18use adk_auth::signed_audit::{
19    AuditSigner, Ed25519Signer, NoteVerifier, SignatureAlgorithm, canonicalize,
20};
21use async_trait::async_trait;
22use awp_types::{
23    ContentId, ContentItem, ContentState, Markdown, Proof, PublicKeyJwk, StreamEntry, without_proof,
24};
25use base64::Engine as _;
26use base64::engine::general_purpose::URL_SAFE_NO_PAD;
27use chrono::{DateTime, Utc};
28use serde::{Deserialize, Serialize};
29use serde_json::Value;
30use tokio::sync::Mutex;
31
32use crate::error::{Result, SiteError};
33
34/// The key that signs stream entries: the edge's delegated `receipt` key (spec 3.5 §7.3,
35/// §7.8.3). The edge implements it over its key store; [`Ed25519EntrySigner`] holds a seed.
36#[async_trait]
37pub trait EntrySigner: Send + Sync {
38    /// The key id in `keys.json`.
39    fn kid(&self) -> &str;
40
41    /// The public key.
42    fn public_key(&self) -> PublicKeyJwk;
43
44    /// Signs `message` with Ed25519.
45    ///
46    /// # Errors
47    ///
48    /// [`SiteError::Signing`] when the key cannot sign.
49    async fn sign(&self, message: &[u8]) -> Result<Vec<u8>>;
50}
51
52/// An Ed25519 [`EntrySigner`] holding its seed in memory; `Debug` shows the key id only.
53pub struct Ed25519EntrySigner {
54    kid: String,
55    inner: Ed25519Signer,
56}
57
58impl std::fmt::Debug for Ed25519EntrySigner {
59    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
60        f.debug_struct("Ed25519EntrySigner").field("kid", &self.kid).finish_non_exhaustive()
61    }
62}
63
64impl Ed25519EntrySigner {
65    /// A signer for key `kid` from a 32-byte seed.
66    ///
67    /// # Errors
68    ///
69    /// [`SiteError::Signing`] when `kid` is empty or holds whitespace or `+`.
70    pub fn from_seed(kid: impl Into<String>, seed: [u8; 32]) -> Result<Self> {
71        let kid = kid.into();
72        let inner = Ed25519Signer::from_seed(kid.clone(), seed)
73            .map_err(|e| SiteError::Signing(e.to_string()))?;
74        Ok(Self { kid, inner })
75    }
76
77    /// A signer for key `kid` with a fresh random seed.
78    ///
79    /// # Errors
80    ///
81    /// As [`from_seed`](Self::from_seed).
82    pub fn generate(kid: impl Into<String>) -> Result<Self> {
83        let kid = kid.into();
84        let inner =
85            Ed25519Signer::generate(kid.clone()).map_err(|e| SiteError::Signing(e.to_string()))?;
86        Ok(Self { kid, inner })
87    }
88}
89
90#[async_trait]
91impl EntrySigner for Ed25519EntrySigner {
92    fn kid(&self) -> &str {
93        &self.kid
94    }
95
96    fn public_key(&self) -> PublicKeyJwk {
97        PublicKeyJwk::ed25519(URL_SAFE_NO_PAD.encode(self.inner.public_key()))
98    }
99
100    async fn sign(&self, message: &[u8]) -> Result<Vec<u8>> {
101        self.inner.sign(message).await.map_err(|e| SiteError::Signing(e.to_string()))
102    }
103}
104
105/// The signing input of an entry: `base64url(header) . base64url(JCS(entry without proof))`.
106fn signing_input(entry: &StreamEntry, header: &str) -> Result<String> {
107    let value = without_proof(entry).map_err(|e| SiteError::serde("stream entry", e))?;
108    let payload = canonicalize(&value).map_err(|e| SiteError::serde("stream entry", e))?;
109    Ok(format!("{header}.{}", URL_SAFE_NO_PAD.encode(payload.as_bytes())))
110}
111
112/// Signs `entry` (its `proof` is ignored) and returns the detached JWS proof (AWP 2.0 §5.4).
113///
114/// # Errors
115///
116/// [`SiteError::Serde`] when the entry is not I-JSON; signing errors.
117pub async fn sign_entry(entry: &StreamEntry, signer: &dyn EntrySigner) -> Result<Proof> {
118    let header = format!(r#"{{"alg":"{}","kid":{}}}"#, Proof::EDDSA, Value::from(signer.kid()));
119    let header = URL_SAFE_NO_PAD.encode(header.as_bytes());
120    let signature = signer.sign(signing_input(entry, &header)?.as_bytes()).await?;
121    Ok(Proof::eddsa(signer.kid(), format!("{header}..{}", URL_SAFE_NO_PAD.encode(signature))))
122}
123
124/// Verifies an entry's proof with `key`.
125///
126/// # Errors
127///
128/// [`SiteError::Signing`] naming what failed.
129pub fn verify_entry(entry: &StreamEntry, key: &PublicKeyJwk) -> Result<()> {
130    let fail =
131        |m: &str| SiteError::Signing(format!("stream entry {} of {}: {m}", entry.n, entry.stream));
132    if entry.proof.alg != Proof::EDDSA {
133        return Err(fail("the proof is not EdDSA"));
134    }
135    let mut parts = entry.proof.jws.split('.');
136    let (Some(header), Some(""), Some(signature), None) =
137        (parts.next(), parts.next(), parts.next(), parts.next())
138    else {
139        return Err(fail("the proof is not a detached compact JWS"));
140    };
141    let decoded =
142        URL_SAFE_NO_PAD.decode(header).map_err(|_| fail("the header is not base64url"))?;
143    let header_json: Value =
144        serde_json::from_slice(&decoded).map_err(|_| fail("the header is not JSON"))?;
145    if header_json.get("alg").and_then(Value::as_str) != Some(Proof::EDDSA)
146        || header_json.get("kid").and_then(Value::as_str) != Some(entry.proof.kid.as_str())
147        || header_json.get("crit").is_some()
148        || header_json.get("b64").is_some()
149    {
150        return Err(fail("the protected header does not match the proof"));
151    }
152    let raw = URL_SAFE_NO_PAD.decode(&key.x).map_err(|_| fail("the key is not base64url"))?;
153    let verifier = NoteVerifier::from_public_key("awp", SignatureAlgorithm::Ed25519, &raw)
154        .map_err(|e| fail(&e.to_string()))?;
155    let signature =
156        URL_SAFE_NO_PAD.decode(signature).map_err(|_| fail("the signature is not base64url"))?;
157    if verifier.verify(signing_input(entry, header)?.as_bytes(), &signature) {
158        Ok(())
159    } else {
160        Err(fail("the signature does not match"))
161    }
162}
163
164/// Where a stream stands.
165#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
166#[serde(rename_all = "camelCase")]
167pub struct StreamStatus {
168    /// The story.
169    pub item: ContentId,
170    /// The story's stream field.
171    pub field: String,
172    /// Entries so far.
173    pub entries: u64,
174    /// Entries already in a release.
175    pub folded: u64,
176    /// When the last fold was taken.
177    pub last_fold: DateTime<Utc>,
178    /// Folds taken.
179    pub folds: u64,
180    /// When it opened.
181    pub opened_at: DateTime<Utc>,
182    /// When it closed.
183    #[serde(default, skip_serializing_if = "Option::is_none")]
184    pub closed_at: Option<DateTime<Utc>>,
185}
186
187#[derive(Debug)]
188struct Stream {
189    status: StreamStatus,
190    entries: Vec<StreamEntry>,
191}
192
193/// The open streams of a site and the key that signs their entries (spec 3.5 §7.8.3).
194///
195/// # Example
196///
197/// ```rust
198/// use std::sync::Arc;
199/// use adk_site::stream::{Ed25519EntrySigner, EntrySigner, StreamLane, verify_entry};
200/// use awp_types::{ContentItem, ContentKind, ContentState};
201/// use chrono::{Duration, Utc};
202///
203/// # #[tokio::main(flavor = "current_thread")]
204/// # async fn main() -> adk_site::Result<()> {
205/// let signer = Arc::new(Ed25519EntrySigner::from_seed("edge-receipt-2026", [3; 32])?);
206/// let lane = StreamLane::new(signer.clone());
207/// let story = ContentItem {
208///     id: "articles/count/en".into(), kind: ContentKind::Article, slug: "count".into(),
209///     language: "en".parse().unwrap(), fields: [("title".to_string(), "The count".into())].into(),
210///     volatile: vec![], body: None, media: vec![], sources: vec![], schedule: None,
211///     state: ContentState::Published,
212/// };
213/// let t0 = Utc::now();
214/// lane.open(&story, "entries", t0).await?;
215/// let entry = lane.append(&story.id, "Polls close.", None, t0).await?;
216/// verify_entry(&entry, &signer.public_key())?;
217/// assert_eq!(lane.since(&story.id, 0).await?.len(), 1, "the edge feed serves it at once");
218/// let folded = lane.fold(&story, t0 + Duration::minutes(5)).await?.unwrap();
219/// assert_eq!(folded.fields["entries"].as_array().unwrap().len(), 1);
220/// # Ok(())
221/// # }
222/// ```
223pub struct StreamLane {
224    signer: std::sync::Arc<dyn EntrySigner>,
225    fold_interval: Duration,
226    streams: Mutex<BTreeMap<ContentId, Stream>>,
227}
228
229impl std::fmt::Debug for StreamLane {
230    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
231        f.debug_struct("StreamLane").field("kid", &self.signer.kid()).finish_non_exhaustive()
232    }
233}
234
235impl StreamLane {
236    /// A lane signing with `signer`, folding every five minutes.
237    pub fn new(signer: std::sync::Arc<dyn EntrySigner>) -> Self {
238        Self {
239            signer,
240            fold_interval: StreamEntry::FOLD_INTERVAL,
241            streams: Mutex::new(BTreeMap::new()),
242        }
243    }
244
245    /// Folds every `interval` instead (at most five minutes).
246    #[must_use]
247    pub fn fold_interval(mut self, interval: Duration) -> Self {
248        self.fold_interval = interval.min(StreamEntry::FOLD_INTERVAL);
249        self
250    }
251
252    /// Opens a stream on a published story's stream field, continuing after the entries the
253    /// story already carries.
254    ///
255    /// # Errors
256    ///
257    /// [`SiteError::Pipeline`] when the story is not published or the stream is open.
258    pub async fn open(&self, story: &ContentItem, field: &str, at: DateTime<Utc>) -> Result<()> {
259        if !matches!(story.state, ContentState::Published | ContentState::Corrected) {
260            return Err(SiteError::Pipeline(format!(
261                "story '{}' is not published; a live story passes its approval chain before its stream opens",
262                story.id
263            )));
264        }
265        let mut streams = self.streams.lock().await;
266        if streams.get(&story.id).is_some_and(|s| s.status.closed_at.is_none()) {
267            return Err(SiteError::Pipeline(format!(
268                "the stream of '{}' is already open",
269                story.id
270            )));
271        }
272        let entries: Vec<StreamEntry> = story
273            .fields
274            .get(field)
275            .and_then(|v| serde_json::from_value(v.clone()).ok())
276            .unwrap_or_default();
277        let folded = entries.len() as u64;
278        streams.insert(
279            story.id.clone(),
280            Stream {
281                status: StreamStatus {
282                    item: story.id.clone(),
283                    field: field.to_string(),
284                    entries: folded,
285                    folded,
286                    last_fold: at,
287                    folds: 0,
288                    opened_at: at,
289                    closed_at: None,
290                },
291                entries,
292            },
293        );
294        Ok(())
295    }
296
297    /// Appends a reporter's entry, signed by the edge key, and returns it as the edge feed
298    /// serves it.
299    ///
300    /// # Errors
301    ///
302    /// [`SiteError::NotFound`] for no open stream; [`SiteError::Pipeline`] when `corrects`
303    /// names no earlier entry; signing errors.
304    pub async fn append(
305        &self,
306        item: &ContentId,
307        markdown: &str,
308        corrects: Option<u64>,
309        at: DateTime<Utc>,
310    ) -> Result<StreamEntry> {
311        let mut streams = self.streams.lock().await;
312        let stream = streams
313            .get_mut(item)
314            .filter(|s| s.status.closed_at.is_none())
315            .ok_or_else(|| SiteError::NotFound(format!("open stream of '{item}'")))?;
316        let n = stream.entries.len() as u64 + 1;
317        if corrects.is_some_and(|c| c == 0 || c >= n) {
318            return Err(SiteError::Pipeline(format!(
319                "entry {n} corrects an entry that does not exist"
320            )));
321        }
322        let mut entry = StreamEntry {
323            stream: item.clone(),
324            n,
325            published_at: at,
326            markdown: Markdown(markdown.to_string()),
327            corrects,
328            proof: Proof::eddsa(self.signer.kid(), ""),
329        };
330        entry.proof = sign_entry(&entry, self.signer.as_ref()).await?;
331        stream.entries.push(entry.clone());
332        stream.status.entries = n;
333        Ok(entry)
334    }
335
336    /// The entries after number `after`: the feed the page polls.
337    ///
338    /// # Errors
339    ///
340    /// [`SiteError::NotFound`] for an unknown stream.
341    pub async fn since(&self, item: &ContentId, after: u64) -> Result<Vec<StreamEntry>> {
342        let streams = self.streams.lock().await;
343        let stream =
344            streams.get(item).ok_or_else(|| SiteError::NotFound(format!("stream of '{item}'")))?;
345        Ok(stream.entries.iter().filter(|e| e.n > after).cloned().collect())
346    }
347
348    /// Closes a stream; its last entries fold at the next [`due`](Self::due).
349    ///
350    /// # Errors
351    ///
352    /// [`SiteError::NotFound`] for no open stream.
353    pub async fn close(&self, item: &ContentId, at: DateTime<Utc>) -> Result<()> {
354        let mut streams = self.streams.lock().await;
355        let stream = streams
356            .get_mut(item)
357            .filter(|s| s.status.closed_at.is_none())
358            .ok_or_else(|| SiteError::NotFound(format!("open stream of '{item}'")))?;
359        stream.status.closed_at = Some(at);
360        Ok(())
361    }
362
363    /// The streams whose fold is due at `now`: unfolded entries and a `fold_interval` boundary,
364    /// counted from the stream's opening, passed since the last fold; or a closed stream with
365    /// unfolded entries.
366    ///
367    /// Folds keep the stream's cadence: a fold taken late, after the boundary, does not push
368    /// the next boundary back, so a caller polling every few seconds or minutes still folds
369    /// every `fold_interval` (spec 3.5 §5 S19: "a signed fold lands every five minutes").
370    pub async fn due(&self, now: DateTime<Utc>) -> Vec<ContentId> {
371        let interval =
372            chrono::Duration::from_std(self.fold_interval).unwrap_or_default().num_milliseconds();
373        let slot = |status: &StreamStatus, at: DateTime<Utc>| {
374            (at - status.opened_at).num_milliseconds().div_euclid(interval)
375        };
376        self.streams
377            .lock()
378            .await
379            .values()
380            .filter(|s| s.status.entries > s.status.folded)
381            .filter(|s| {
382                s.status.closed_at.is_some()
383                    || interval <= 0
384                    || slot(&s.status, now) > slot(&s.status, s.status.last_fold)
385            })
386            .map(|s| s.status.item.clone())
387            .collect()
388    }
389
390    /// Folds a stream's entries into `story`: its stream field holds every entry so far,
391    /// each with its proof verified. `None` when nothing new arrived since the last fold.
392    ///
393    /// # Errors
394    ///
395    /// [`SiteError::NotFound`] for an unknown stream; [`SiteError::Signing`] when an entry's
396    /// proof does not verify.
397    pub async fn fold(
398        &self,
399        story: &ContentItem,
400        now: DateTime<Utc>,
401    ) -> Result<Option<ContentItem>> {
402        let key = self.signer.public_key();
403        let mut streams = self.streams.lock().await;
404        let stream = streams
405            .get_mut(&story.id)
406            .ok_or_else(|| SiteError::NotFound(format!("stream of '{}'", story.id)))?;
407        if stream.status.entries == stream.status.folded {
408            return Ok(None);
409        }
410        for entry in &stream.entries[stream.status.folded as usize..] {
411            verify_entry(entry, &key)?;
412        }
413        let mut folded = story.clone();
414        let entries =
415            serde_json::to_value(&stream.entries).map_err(|e| SiteError::serde("stream", e))?;
416        folded.fields.insert(stream.status.field.clone(), entries);
417        stream.status.folded = stream.status.entries;
418        stream.status.last_fold = now;
419        stream.status.folds += 1;
420        tracing::info!(stream = %story.id, entries = stream.status.entries, "site.stream.folded");
421        Ok(Some(folded))
422    }
423
424    /// Every stream's status.
425    pub async fn status(&self) -> Vec<StreamStatus> {
426        self.streams.lock().await.values().map(|s| s.status.clone()).collect()
427    }
428}
429
430#[cfg(test)]
431mod tests {
432    use super::*;
433
434    fn entry(n: u64) -> StreamEntry {
435        StreamEntry {
436            stream: "articles/count/en".into(),
437            n,
438            published_at: DateTime::parse_from_rfc3339("2026-10-25T20:00:00Z")
439                .unwrap()
440                .with_timezone(&Utc),
441            markdown: Markdown(format!("Update {n}.")),
442            corrects: None,
443            proof: Proof::eddsa("edge", ""),
444        }
445    }
446
447    /// S19's live blog as the soak drives it: an entry every 36 s for six hours, each followed
448    /// by a poll that arrives seconds late. Folds stay on the five-minute cadence from the
449    /// stream's opening (72: one per boundary and one at the close) instead of drifting by
450    /// each poll's lateness (spec 3.5 §5 S19).
451    #[tokio::test]
452    async fn late_polls_keep_the_five_minute_fold_cadence() {
453        let signer = std::sync::Arc::new(Ed25519EntrySigner::from_seed("edge", [9; 32]).unwrap());
454        let lane = StreamLane::new(signer);
455        let story = ContentItem {
456            id: "articles/count/en".into(),
457            kind: awp_types::ContentKind::Article,
458            slug: "count".into(),
459            language: "en".parse().unwrap(),
460            fields: BTreeMap::new(),
461            volatile: Vec::new(),
462            body: None,
463            media: Vec::new(),
464            sources: Vec::new(),
465            schedule: None,
466            state: ContentState::Published,
467        };
468        let t0 = DateTime::parse_from_rfc3339("2026-11-03T18:00:00Z").unwrap().with_timezone(&Utc);
469        lane.open(&story, "entries", t0).await.unwrap();
470        let mut fold_times = Vec::new();
471        for n in 0..600i64 {
472            let at = t0 + chrono::Duration::seconds(n * 36);
473            lane.append(&story.id, &format!("Update {n}."), None, at).await.unwrap();
474            if n == 599 {
475                lane.close(&story.id, at).await.unwrap();
476            }
477            // The poll after each entry runs late: ingesting a large delivery takes seconds.
478            let poll = at + chrono::Duration::seconds(4 + n % 17);
479            for id in lane.due(poll).await {
480                assert_eq!(id, story.id);
481                lane.fold(&story, poll).await.unwrap().unwrap();
482                fold_times.push(poll);
483            }
484        }
485        let status = lane.status().await.remove(0);
486        assert_eq!((status.folded, status.folds), (600, 72), "{fold_times:?}");
487        for (k, at) in fold_times.iter().take(71).enumerate() {
488            let boundary = t0 + chrono::Duration::minutes(5 * (k as i64 + 1));
489            assert!(
490                *at >= boundary && *at - boundary < chrono::Duration::seconds(60),
491                "fold {k} at {at}, boundary {boundary}"
492            );
493        }
494        assert!(lane.due(t0 + chrono::Duration::hours(7)).await.is_empty(), "nothing left");
495    }
496
497    #[tokio::test]
498    async fn entries_sign_and_tampering_is_caught() {
499        let signer = Ed25519EntrySigner::from_seed("edge", [9; 32]).unwrap();
500        let mut signed = entry(1);
501        signed.proof = sign_entry(&signed, &signer).await.unwrap();
502        assert!(signed.proof.jws.contains(".."));
503        verify_entry(&signed, &signer.public_key()).unwrap();
504        let mut altered = signed.clone();
505        altered.markdown = Markdown("Update 1, altered.".into());
506        assert!(verify_entry(&altered, &signer.public_key()).is_err());
507        let other = Ed25519EntrySigner::from_seed("edge", [8; 32]).unwrap();
508        assert!(verify_entry(&signed, &other.public_key()).is_err());
509        assert!(format!("{signer:?}").contains("edge"));
510    }
511}