Skip to main content

weirdnet_service/
feed.rs

1//! Live topic feeds: snapshot, then deltas, with resume and backpressure.
2//!
3//! A [`Hub`] holds the current [`State`] of each topic and numbers every delta published to
4//! it. A subscriber first gets a [`Event::Snapshot`] at a [`Position`] (the hub's epoch and the
5//! topic's sequence number), then [`Event::Deltas`] in order. Applying the deltas to the
6//! snapshot always gives the topic's state at the last sequence number received.
7//!
8//! - **Resume.** A subscriber that reconnects passes its last position. If the hub still holds
9//!   every delta after it (the last [`HubOptions::retain`] per topic) and the epoch matches
10//!   (the hub was not restarted), it gets [`Event::Resumed`] and the missed deltas; otherwise a
11//!   fresh snapshot.
12//! - **Backpressure.** Each subscriber has its own queue of at most [`HubOptions::queue`]
13//!   deltas. Publishing never waits for subscribers. Deltas with the same
14//!   [`State::coalesce_key`] replace each other in a queue (the latest price of a product, the
15//!   latest state of an order). A queue that still overflows is cleared and the subscriber
16//!   gets a fresh snapshot ([`Overflow::Resnapshot`], the default) or is ended with reason
17//!   `lagged` so it resumes ([`Overflow::Disconnect`]).
18//! - **Throttling.** [`FeedOptions::min_interval`] spaces out what a network subscriber is sent;
19//!   deltas published in between are coalesced in its queue.
20//!
21//! [`serve_feed`] serves one subscription on a [`Channel`]; [`Subscription`] is the client
22//! side and [`Live`] keeps a local copy of the state that reconnects and resumes on its own.
23
24use std::collections::{HashMap, VecDeque};
25use std::fmt::Debug;
26use std::hash::Hash;
27use std::marker::PhantomData;
28use std::sync::{Arc, Mutex, Weak};
29use std::time::Duration;
30
31use serde::de::DeserializeOwned;
32use serde::{Deserialize, Serialize};
33use tokio::sync::Notify;
34
35use crate::service::first;
36use crate::{Access, Authorize, Caller, Channel, Client, Credentials, ProtocolId, ServiceError, WIRE};
37
38/// A topic's state. Deltas change it; the hub and [`Live`] apply them the same way.
39pub trait State: Clone + Debug + Serialize + DeserializeOwned + Send + Sync + 'static {
40    type Delta: Clone + Debug + Serialize + DeserializeOwned + Send + Sync + 'static;
41
42    /// Applies one delta.
43    fn apply(&mut self, delta: &Self::Delta);
44
45    /// Deltas with the same key supersede each other: applying only the latest of them gives
46    /// the same state as applying them all. `None` (the default) never coalesces.
47    fn coalesce_key(_delta: &Self::Delta) -> Option<String> {
48        None
49    }
50}
51
52/// A topic key, such as `Ticker { account, product }`.
53pub trait Topic: Clone + Eq + Hash + Debug + Serialize + DeserializeOwned + Send + Sync + 'static {}
54
55impl<T: Clone + Eq + Hash + Debug + Serialize + DeserializeOwned + Send + Sync + 'static> Topic for T {}
56
57/// Where a subscriber is: the hub's epoch (new on every hub, so a restarted server is
58/// noticed) and the topic's sequence number.
59#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
60pub struct Position {
61    pub epoch: u64,
62    pub seq: u64,
63}
64
65/// What happens to a subscriber whose queue overflows.
66#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
67pub enum Overflow {
68    /// Clear the queue and send a fresh snapshot.
69    #[default]
70    Resnapshot,
71    /// Clear the queue and end the subscription with reason `lagged`; the client resumes.
72    Disconnect,
73}
74
75/// How a hub keeps history and queues.
76#[derive(Debug, Clone)]
77#[non_exhaustive]
78pub struct HubOptions {
79    /// Deltas kept per topic for resuming (default 1024).
80    pub retain: usize,
81    /// Deltas queued per subscriber before [`Overflow`] applies (default 1024).
82    pub queue: usize,
83    pub overflow: Overflow,
84}
85
86impl Default for HubOptions {
87    fn default() -> Self {
88        Self { retain: 1024, queue: 1024, overflow: Overflow::Resnapshot }
89    }
90}
91
92impl HubOptions {
93    pub fn with_retain(mut self, n: usize) -> Self {
94        self.retain = n;
95        self
96    }
97
98    pub fn with_queue(mut self, n: usize) -> Self {
99        self.queue = n.max(1);
100        self
101    }
102
103    pub fn with_overflow(mut self, o: Overflow) -> Self {
104        self.overflow = o;
105        self
106    }
107}
108
109/// What a subscriber receives.
110#[derive(Debug, Clone)]
111pub enum Event<S: State> {
112    /// The whole state at `at`. Replace any local copy.
113    Snapshot { at: Position, state: S },
114    /// Resumed at `at`: the local copy is current as of `at`, missed deltas follow.
115    Resumed { at: Position },
116    /// Deltas in order, each with its sequence number. Sequence numbers increase but may skip
117    /// (coalesced deltas).
118    Deltas { epoch: u64, items: Vec<(u64, S::Delta)> },
119    /// The topic is gone (`removed`) or the subscriber fell behind (`lagged`).
120    Ended { reason: String },
121}
122
123struct Queue<S: State> {
124    items: VecDeque<(u64, Option<String>, S::Delta)>,
125    resnapshot: bool,
126    ended: Option<String>,
127}
128
129struct Sub<S: State> {
130    q: Mutex<Queue<S>>,
131    notify: Notify,
132}
133
134impl<S: State> Sub<S> {
135    fn new() -> Self {
136        Self { q: Mutex::new(Queue { items: VecDeque::new(), resnapshot: false, ended: None }), notify: Notify::new() }
137    }
138
139    fn push(&self, seq: u64, delta: &S::Delta, options: &HubOptions) {
140        let mut q = lock(&self.q);
141        if q.resnapshot || q.ended.is_some() {
142            return;
143        }
144        let key = S::coalesce_key(delta);
145        if let Some(k) = &key
146            && let Some(i) = q.items.iter().position(|(_, kk, _)| kk.as_ref() == Some(k))
147        {
148            q.items.remove(i);
149        }
150        q.items.push_back((seq, key, delta.clone()));
151        if q.items.len() > options.queue {
152            q.items.clear();
153            match options.overflow {
154                Overflow::Resnapshot => q.resnapshot = true,
155                Overflow::Disconnect => q.ended = Some("lagged".into()),
156            }
157        }
158        drop(q);
159        self.notify.notify_one();
160    }
161
162    fn resnapshot(&self) {
163        let mut q = lock(&self.q);
164        if q.ended.is_none() {
165            q.items.clear();
166            q.resnapshot = true;
167        }
168        drop(q);
169        self.notify.notify_one();
170    }
171
172    fn end(&self, reason: &str) {
173        let mut q = lock(&self.q);
174        q.items.clear();
175        q.ended.get_or_insert_with(|| reason.to_string());
176        drop(q);
177        self.notify.notify_one();
178    }
179}
180
181struct Entry<S: State> {
182    state: S,
183    seq: u64,
184    ring: VecDeque<(u64, S::Delta)>,
185    subs: Vec<Weak<Sub<S>>>,
186}
187
188impl<S: State> Entry<S> {
189    fn live_subs(&mut self) -> Vec<Arc<Sub<S>>> {
190        let live: Vec<Arc<Sub<S>>> = self.subs.iter().filter_map(Weak::upgrade).collect();
191        self.subs = live.iter().map(Arc::downgrade).collect();
192        live
193    }
194}
195
196fn lock<T>(m: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
197    m.lock().unwrap_or_else(|e| e.into_inner())
198}
199
200fn new_epoch() -> u64 {
201    use std::hash::{BuildHasher, Hasher};
202    let mut h = std::collections::hash_map::RandomState::new().build_hasher();
203    h.write_u128(std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or_default());
204    h.finish().max(1)
205}
206
207/// Topics, their current state and their subscribers. Share it in an `Arc` between the code
208/// that publishes and the [`Server`](crate::net::Server) that serves it.
209pub struct Hub<T: Topic, S: State> {
210    epoch: u64,
211    options: HubOptions,
212    topics: Mutex<HashMap<T, Entry<S>>>,
213}
214
215impl<T: Topic, S: State> Hub<T, S> {
216    /// A hub with a new random epoch.
217    pub fn new(options: HubOptions) -> Self {
218        Self::with_epoch(new_epoch(), options)
219    }
220
221    /// A hub with a chosen epoch: only if sequence numbers are restored with it (for example
222    /// from an event log), so positions from before a restart stay valid.
223    pub fn with_epoch(epoch: u64, options: HubOptions) -> Self {
224        Self { epoch, options, topics: Mutex::new(HashMap::new()) }
225    }
226
227    pub fn epoch(&self) -> u64 {
228        self.epoch
229    }
230
231    /// Creates `topic` with `state`, or replaces its state: the sequence number moves on, the
232    /// history is dropped and every subscriber gets a fresh snapshot.
233    pub fn insert(&self, topic: T, state: S) -> Position {
234        let mut topics = lock(&self.topics);
235        match topics.get_mut(&topic) {
236            Some(e) => {
237                e.state = state;
238                e.seq += 1;
239                e.ring.clear();
240                for s in e.live_subs() {
241                    s.resnapshot();
242                }
243                Position { epoch: self.epoch, seq: e.seq }
244            }
245            None => {
246                topics.insert(topic, Entry { state, seq: 1, ring: VecDeque::new(), subs: Vec::new() });
247                Position { epoch: self.epoch, seq: 1 }
248            }
249        }
250    }
251
252    /// Applies `delta` to the topic and sends it to its subscribers. Never waits for them.
253    pub fn publish(&self, topic: &T, delta: S::Delta) -> Result<Position, ServiceError> {
254        self.publish_all(topic, [delta])
255    }
256
257    /// Publishes several deltas at once (one lock, consecutive sequence numbers).
258    pub fn publish_all(&self, topic: &T, deltas: impl IntoIterator<Item = S::Delta>) -> Result<Position, ServiceError> {
259        let mut topics = lock(&self.topics);
260        let e = topics.get_mut(topic).ok_or_else(|| ServiceError::not_found(format!("topic {topic:?}")))?;
261        let subs = e.live_subs();
262        for delta in deltas {
263            e.state.apply(&delta);
264            e.seq += 1;
265            for s in &subs {
266                s.push(e.seq, &delta, &self.options);
267            }
268            if self.options.retain > 0 {
269                if e.ring.len() == self.options.retain {
270                    e.ring.pop_front();
271                }
272                e.ring.push_back((e.seq, delta));
273            }
274        }
275        Ok(Position { epoch: self.epoch, seq: e.seq })
276    }
277
278    /// Removes the topic; its subscribers get [`Event::Ended`] with reason `removed`.
279    pub fn remove(&self, topic: &T) -> bool {
280        let Some(mut e) = lock(&self.topics).remove(topic) else { return false };
281        for s in e.live_subs() {
282            s.end("removed");
283        }
284        true
285    }
286
287    /// The topic's state and position.
288    pub fn snapshot(&self, topic: &T) -> Option<(Position, S)> {
289        lock(&self.topics).get(topic).map(|e| (Position { epoch: self.epoch, seq: e.seq }, e.state.clone()))
290    }
291
292    pub fn position(&self, topic: &T) -> Option<Position> {
293        lock(&self.topics).get(topic).map(|e| Position { epoch: self.epoch, seq: e.seq })
294    }
295
296    pub fn contains(&self, topic: &T) -> bool {
297        lock(&self.topics).contains_key(topic)
298    }
299
300    pub fn topics(&self) -> Vec<T> {
301        lock(&self.topics).keys().cloned().collect()
302    }
303
304    /// Subscribers currently attached to the topic.
305    pub fn subscribers(&self, topic: &T) -> usize {
306        lock(&self.topics).get_mut(topic).map(|e| e.live_subs().len()).unwrap_or(0)
307    }
308
309    /// Subscribes in process (the network side uses this too). With `resume`, continues from
310    /// that position when the history allows, else starts with a snapshot.
311    pub fn subscribe(self: &Arc<Self>, topic: &T, resume: Option<Position>) -> Result<Watcher<T, S>, ServiceError> {
312        let mut topics = lock(&self.topics);
313        let e = topics.get_mut(topic).ok_or_else(|| ServiceError::not_found(format!("topic {topic:?}")))?;
314        let sub = Arc::new(Sub::<S>::new());
315        let at = Position { epoch: self.epoch, seq: e.seq };
316        let resumable = resume
317            .filter(|p| p.epoch == self.epoch && p.seq <= e.seq && (p.seq == e.seq || e.ring.front().is_some_and(|(first, _)| *first <= p.seq + 1)));
318        let first = match resumable {
319            Some(p) => {
320                for (seq, d) in e.ring.iter().filter(|(s, _)| *s > p.seq) {
321                    sub.push(*seq, d, &self.options);
322                }
323                Event::Resumed { at: p }
324            }
325            None => Event::Snapshot { at, state: e.state.clone() },
326        };
327        e.live_subs();
328        e.subs.push(Arc::downgrade(&sub));
329        drop(topics);
330        Ok(Watcher { hub: self.clone(), topic: topic.clone(), sub, first: Some(first), done: false })
331    }
332}
333
334/// One subscriber's view of a topic on the hub.
335pub struct Watcher<T: Topic, S: State> {
336    hub: Arc<Hub<T, S>>,
337    topic: T,
338    sub: Arc<Sub<S>>,
339    first: Option<Event<S>>,
340    done: bool,
341}
342
343impl<T: Topic, S: State> Watcher<T, S> {
344    /// The next event; `None` after [`Event::Ended`]. Cancel-safe.
345    pub async fn next(&mut self) -> Option<Event<S>> {
346        if let Some(f) = self.first.take() {
347            return Some(f);
348        }
349        if self.done {
350            return None;
351        }
352        loop {
353            let sub = self.sub.clone();
354            let notified = sub.notify.notified();
355            {
356                let mut q = lock(&sub.q);
357                if let Some(reason) = q.ended.take() {
358                    self.done = true;
359                    return Some(Event::Ended { reason });
360                }
361                if q.resnapshot {
362                    drop(q);
363                    return Some(self.resnapshot());
364                }
365                if !q.items.is_empty() {
366                    let items = q.items.drain(..).map(|(s, _, d)| (s, d)).collect();
367                    return Some(Event::Deltas { epoch: self.hub.epoch, items });
368                }
369            }
370            notified.await;
371        }
372    }
373
374    fn resnapshot(&mut self) -> Event<S> {
375        let topics = lock(&self.hub.topics);
376        let Some(e) = topics.get(&self.topic) else {
377            self.done = true;
378            return Event::Ended { reason: "removed".into() };
379        };
380        let mut q = lock(&self.sub.q);
381        q.resnapshot = false;
382        let seq = e.seq;
383        q.items.retain(|(s, _, _)| *s > seq);
384        Event::Snapshot { at: Position { epoch: self.hub.epoch, seq }, state: e.state.clone() }
385    }
386
387    pub fn topic(&self) -> &T {
388        &self.topic
389    }
390}
391
392/// How [`serve_feed`] runs a subscription.
393#[derive(Debug, Clone)]
394#[non_exhaustive]
395pub struct FeedOptions {
396    /// A heartbeat when nothing else was sent for this long (default 15 s), so clients notice
397    /// a dead stream.
398    pub heartbeat: Duration,
399    /// At most one message per this interval (default none). Deltas in between coalesce.
400    pub min_interval: Option<Duration>,
401    /// Ask the [`Authorize`] hook again this often (default 30 s), so a revoked device or
402    /// membership loses its live stream. `None` checks only at the start.
403    pub recheck: Option<Duration>,
404    /// How long a new stream may take to send `Subscribe` (default 10 s).
405    pub hello_timeout: Duration,
406}
407
408impl Default for FeedOptions {
409    fn default() -> Self {
410        Self {
411            heartbeat: Duration::from_secs(15),
412            min_interval: None,
413            recheck: Some(Duration::from_secs(30)),
414            hello_timeout: Duration::from_secs(10),
415        }
416    }
417}
418
419impl FeedOptions {
420    pub fn with_heartbeat(mut self, d: Duration) -> Self {
421        self.heartbeat = d;
422        self
423    }
424
425    pub fn with_min_interval(mut self, d: Option<Duration>) -> Self {
426        self.min_interval = d;
427        self
428    }
429
430    pub fn with_recheck(mut self, d: Option<Duration>) -> Self {
431        self.recheck = d;
432        self
433    }
434
435    pub fn with_hello_timeout(mut self, d: Duration) -> Self {
436        self.hello_timeout = d;
437        self
438    }
439}
440
441#[derive(Debug, Serialize, Deserialize)]
442#[serde(rename_all = "snake_case")]
443pub(crate) struct SubscribeFrame<T> {
444    wire: u8,
445    credentials: Credentials,
446    topic: T,
447    #[serde(default, skip_serializing_if = "Option::is_none")]
448    resume: Option<Position>,
449}
450
451#[derive(Debug, Serialize, Deserialize)]
452#[serde(rename_all = "snake_case")]
453pub(crate) enum FeedFrame<S, D> {
454    Snapshot { at: Position, state: S },
455    Resumed { at: Position },
456    Deltas { epoch: u64, items: Vec<(u64, D)> },
457    Heartbeat { at: Position },
458    Ended { reason: String },
459    Failed(ServiceError),
460}
461
462/// What a feed needs for a topic (usually a read permission on the topic's account).
463pub type AccessFn<T> = Arc<dyn Fn(&T) -> Access + Send + Sync>;
464
465/// Serves one subscription on `ch`. `peer` must be the transport-authenticated peer id.
466pub async fn serve_feed<T: Topic, S: State>(
467    hub: Arc<Hub<T, S>>,
468    access: AccessFn<T>,
469    auth: Arc<dyn Authorize>,
470    mut ch: Channel,
471    peer: String,
472    options: &FeedOptions,
473) -> Result<(), ServiceError> {
474    type Frame<S> = FeedFrame<S, <S as State>::Delta>;
475    let hello = match first::<SubscribeFrame<T>>(&mut ch, options.hello_timeout).await {
476        Ok(Some(h)) => h,
477        Ok(None) => return Ok(()),
478        Err(e) => {
479            let _ = ch.send_cbor(&Frame::<S>::Failed(e.clone())).await;
480            return Err(e);
481        }
482    };
483    if hello.wire != WIRE {
484        return ch.send_cbor(&Frame::<S>::Failed(ServiceError::unsupported(format!("wire version {}", hello.wire)))).await;
485    }
486    let caller = Caller::new(peer, hello.credentials);
487    let need = access(&hello.topic);
488    if let Err(e) = auth.authorize(&caller, &need) {
489        return ch.send_cbor(&Frame::<S>::Failed(e)).await;
490    }
491    let mut watcher = match hub.subscribe(&hello.topic, hello.resume) {
492        Ok(w) => w,
493        Err(e) => return ch.send_cbor(&Frame::<S>::Failed(e)).await,
494    };
495    let mut at = Position { epoch: hub.epoch(), seq: 0 };
496    let mut beat = tokio::time::interval(options.heartbeat.max(Duration::from_millis(10)));
497    beat.reset();
498    let mut recheck = tokio::time::interval(options.recheck.unwrap_or(Duration::from_secs(3600)).max(Duration::from_millis(10)));
499    recheck.reset();
500    loop {
501        tokio::select! {
502            ev = watcher.next() => {
503                let Some(ev) = ev else { return Ok(()) };
504                let (frame, end) = match ev {
505                    Event::Snapshot { at: p, state } => { at = p; (Frame::<S>::Snapshot { at: p, state }, false) }
506                    Event::Resumed { at: p } => { at = p; (Frame::<S>::Resumed { at: p }, false) }
507                    Event::Deltas { epoch, items } => {
508                        if let Some((s, _)) = items.last() { at.seq = *s; }
509                        (Frame::<S>::Deltas { epoch, items }, false)
510                    }
511                    Event::Ended { reason } => (Frame::<S>::Ended { reason }, true),
512                };
513                ch.send_cbor(&frame).await?;
514                if end {
515                    return Ok(());
516                }
517                beat.reset();
518                if let Some(d) = options.min_interval {
519                    tokio::time::sleep(d).await;
520                }
521            }
522            _ = beat.tick() => ch.send_cbor(&Frame::<S>::Heartbeat { at }).await?,
523            _ = recheck.tick(), if options.recheck.is_some() => {
524                if let Err(e) = auth.authorize(&caller, &need) {
525                    return ch.send_cbor(&Frame::<S>::Failed(e)).await;
526                }
527            }
528            r = ch.rx.recv() => match r {
529                Ok(None) | Err(_) => return Ok(()),
530                Ok(Some(_)) => return ch.send_cbor(&Frame::<S>::Failed(ServiceError::protocol("unexpected message on a subscription"))).await,
531            },
532        }
533    }
534}
535
536/// A client's subscription to one topic. Checks that positions only move forward.
537pub struct Subscription<T, S: State> {
538    ch: Channel,
539    at: Option<Position>,
540    stall: Option<Duration>,
541    pending: Option<FeedFrame<S, S::Delta>>,
542    done: bool,
543    _topic: PhantomData<fn() -> T>,
544}
545
546impl<T: Topic, S: State> Subscription<T, S> {
547    /// Sends `Subscribe` on `ch` and waits for the first answer, so a refusal comes back here.
548    pub async fn start(mut ch: Channel, credentials: Credentials, topic: T, resume: Option<Position>) -> Result<Self, ServiceError> {
549        ch.send_cbor(&SubscribeFrame { wire: WIRE, credentials, topic, resume }).await?;
550        let first = match ch.recv_cbor::<FeedFrame<S, S::Delta>>().await? {
551            None => return Err(ServiceError::Closed),
552            Some(FeedFrame::Failed(e)) => return Err(e),
553            Some(FeedFrame::Resumed { at }) if Some(at) != resume => return Err(ServiceError::protocol("resumed at another position")),
554            Some(f) => f,
555        };
556        Ok(Self { ch, at: None, stall: Some(Duration::from_secs(45)), pending: Some(first), done: false, _topic: PhantomData })
557    }
558
559    /// Fail with [`ServiceError::Timeout`] when nothing (not even a heartbeat) arrives for this
560    /// long (default 45 s, three server heartbeats). `None` waits forever.
561    pub fn with_stall(mut self, d: Option<Duration>) -> Self {
562        self.stall = d;
563        self
564    }
565
566    /// The position of the last event received.
567    pub fn position(&self) -> Option<Position> {
568        self.at
569    }
570
571    async fn recv(&mut self) -> Result<Option<FeedFrame<S, S::Delta>>, ServiceError> {
572        if let Some(f) = self.pending.take() {
573            return Ok(Some(f));
574        }
575        match self.stall {
576            None => self.ch.recv_cbor().await,
577            Some(d) => tokio::time::timeout(d, self.ch.recv_cbor()).await.unwrap_or(Err(ServiceError::Timeout)),
578        }
579    }
580
581    /// The next event; `None` once the stream ended. Cancel-safe only between events (don't
582    /// race it against something that may drop it mid-frame on a slow link).
583    pub async fn next(&mut self) -> Option<Result<Event<S>, ServiceError>> {
584        loop {
585            if self.done {
586                return None;
587            }
588            let frame = match self.recv().await {
589                Ok(Some(f)) => f,
590                Ok(None) => {
591                    self.done = true;
592                    return None;
593                }
594                Err(e) => {
595                    self.done = true;
596                    return Some(Err(e));
597                }
598            };
599            let out = match frame {
600                FeedFrame::Snapshot { at, state } => {
601                    self.at = Some(at);
602                    Ok(Event::Snapshot { at, state })
603                }
604                FeedFrame::Resumed { at } => {
605                    self.at = Some(at);
606                    Ok(Event::Resumed { at })
607                }
608                FeedFrame::Deltas { epoch, items } => match self.at {
609                    Some(mut p) if p.epoch == epoch => {
610                        let mut ok = true;
611                        for (s, _) in &items {
612                            ok &= *s > p.seq;
613                            p.seq = *s;
614                        }
615                        if ok {
616                            self.at = Some(p);
617                            Ok(Event::Deltas { epoch, items })
618                        } else {
619                            Err(ServiceError::protocol("feed: sequence went backwards"))
620                        }
621                    }
622                    _ => Err(ServiceError::protocol("feed: deltas before a snapshot, or from another epoch")),
623                },
624                FeedFrame::Heartbeat { at } => {
625                    if self.at.is_some_and(|p| p.epoch != at.epoch) {
626                        Err(ServiceError::protocol("feed: heartbeat from another epoch"))
627                    } else {
628                        continue;
629                    }
630                }
631                FeedFrame::Ended { reason } => {
632                    self.done = true;
633                    Ok(Event::Ended { reason })
634                }
635                FeedFrame::Failed(e) => Err(e),
636            };
637            if out.is_err() {
638                self.done = true;
639            }
640            return Some(out);
641        }
642    }
643}
644
645/// What changed in a [`Live`] state.
646#[derive(Debug, Clone)]
647pub enum Change<S: State> {
648    /// A new snapshot replaced the state.
649    Snapshot,
650    /// Reconnected without losing anything.
651    Resumed,
652    /// These deltas were applied.
653    Deltas(Vec<S::Delta>),
654    /// The stream dropped; the next call reconnects (after a backoff) and resumes.
655    Disconnected(ServiceError),
656    /// The topic ended for good (`removed`).
657    Ended(String),
658}
659
660/// A local copy of a topic's state that follows the server, reconnecting and resuming on its
661/// own. Drive it with [`next`](Self::next) from a background task and push each change into
662/// the UI.
663pub struct Live<T: Topic, S: State> {
664    client: Client,
665    node: String,
666    protocol: ProtocolId,
667    topic: T,
668    state: Option<S>,
669    at: Option<Position>,
670    sub: Option<Subscription<T, S>>,
671    backoff: Duration,
672    wait: Option<Duration>,
673    max_backoff: Duration,
674    ended: bool,
675}
676
677impl<T: Topic, S: State> Live<T, S> {
678    pub fn new(client: Client, node: impl Into<String>, protocol: ProtocolId, topic: T) -> Self {
679        Self {
680            client,
681            node: node.into(),
682            protocol,
683            topic,
684            state: None,
685            at: None,
686            sub: None,
687            backoff: Duration::from_millis(250),
688            wait: None,
689            max_backoff: Duration::from_secs(30),
690            ended: false,
691        }
692    }
693
694    /// Reconnect backoff: starts at `first`, doubles up to `max`.
695    pub fn with_backoff(mut self, first: Duration, max: Duration) -> Self {
696        self.backoff = first;
697        self.max_backoff = max.max(first);
698        self
699    }
700
701    /// The state, once the first snapshot arrived.
702    pub fn state(&self) -> Option<&S> {
703        self.state.as_ref()
704    }
705
706    pub fn position(&self) -> Option<Position> {
707        self.at
708    }
709
710    pub fn is_connected(&self) -> bool {
711        self.sub.is_some()
712    }
713
714    fn dropped(&mut self, e: ServiceError) -> Result<Change<S>, ServiceError> {
715        self.sub = None;
716        let next = self.wait.map(|w| (w * 2).min(self.max_backoff)).unwrap_or(self.backoff);
717        self.wait = Some(next);
718        Ok(Change::Disconnected(e))
719    }
720
721    /// The next change. Errors are permanent (refused, not found, unsupported); transient
722    /// failures come back as [`Change::Disconnected`] and the next call retries.
723    pub async fn next(&mut self) -> Result<Change<S>, ServiceError> {
724        if self.ended {
725            return Err(ServiceError::not_found("the topic ended"));
726        }
727        if self.sub.is_none() {
728            if let Some(w) = self.wait {
729                tokio::time::sleep(w).await;
730            }
731            match self.client.subscribe::<T, S>(&self.node, &self.protocol, self.topic.clone(), self.at).await {
732                Ok(s) => self.sub = Some(s),
733                Err(e) if e.is_permanent() => return Err(e),
734                Err(e) => return self.dropped(e),
735            }
736        }
737        let Some(sub) = self.sub.as_mut() else { return self.dropped(ServiceError::Closed) };
738        match sub.next().await {
739            Some(Ok(Event::Snapshot { at, state })) => {
740                self.wait = None;
741                self.state = Some(state);
742                self.at = Some(at);
743                Ok(Change::Snapshot)
744            }
745            Some(Ok(Event::Resumed { at })) => {
746                self.wait = None;
747                self.at = Some(at);
748                Ok(Change::Resumed)
749            }
750            Some(Ok(Event::Deltas { items, .. })) => {
751                let mut applied = Vec::with_capacity(items.len());
752                if let Some(state) = self.state.as_mut() {
753                    for (seq, d) in items {
754                        state.apply(&d);
755                        if let Some(p) = self.at.as_mut() {
756                            p.seq = seq;
757                        }
758                        applied.push(d);
759                    }
760                }
761                Ok(Change::Deltas(applied))
762            }
763            Some(Ok(Event::Ended { reason })) if reason == "lagged" => self.dropped(ServiceError::unavailable("lagged")),
764            Some(Ok(Event::Ended { reason })) => {
765                self.sub = None;
766                self.ended = true;
767                Ok(Change::Ended(reason))
768            }
769            Some(Err(e)) if e.is_permanent() => {
770                self.sub = None;
771                Err(e)
772            }
773            Some(Err(e)) => self.dropped(e),
774            None => self.dropped(ServiceError::Closed),
775        }
776    }
777}
778
779#[cfg(test)]
780mod tests {
781    use super::*;
782    use crate::{AllowAll, memory_pair};
783
784    #[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
785    struct Prices(std::collections::BTreeMap<String, i64>);
786
787    #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
788    enum P {
789        Set(String, i64),
790        Clear,
791    }
792
793    impl State for Prices {
794        type Delta = P;
795        fn apply(&mut self, d: &P) {
796            match d {
797                P::Set(k, v) => {
798                    self.0.insert(k.clone(), *v);
799                }
800                P::Clear => self.0.clear(),
801            }
802        }
803        fn coalesce_key(d: &P) -> Option<String> {
804            match d {
805                P::Set(k, _) => Some(k.clone()),
806                P::Clear => None,
807            }
808        }
809    }
810
811    fn set(k: &str, v: i64) -> P {
812        P::Set(k.into(), v)
813    }
814
815    fn hub(options: HubOptions) -> Arc<Hub<String, Prices>> {
816        let h = Arc::new(Hub::new(options));
817        h.insert("t".into(), Prices::default());
818        h
819    }
820
821    async fn next(w: &mut Watcher<String, Prices>) -> Event<Prices> {
822        tokio::time::timeout(Duration::from_secs(2), w.next()).await.unwrap().unwrap()
823    }
824
825    #[tokio::test]
826    async fn snapshot_then_deltas_and_resume() {
827        let h = hub(HubOptions::default().with_retain(3));
828        h.publish(&"t".into(), set("btc", 1)).unwrap();
829        let mut w = h.subscribe(&"t".into(), None).unwrap();
830        let Event::Snapshot { at, state } = next(&mut w).await else { panic!() };
831        assert_eq!((at.seq, state.0.get("btc")), (2, Some(&1)));
832        h.publish(&"t".into(), set("eth", 2)).unwrap();
833        let Event::Deltas { items, .. } = next(&mut w).await else { panic!() };
834        assert_eq!(items, [(3, set("eth", 2))]);
835        drop(w);
836        assert_eq!(h.subscribers(&"t".into()), 0);
837
838        // Resume from seq 3 after two more deltas: both arrive, no snapshot.
839        h.publish_all(&"t".into(), [set("sol", 3), set("ada", 4)]).unwrap();
840        let mut w = h.subscribe(&"t".into(), Some(Position { epoch: h.epoch(), seq: 3 })).unwrap();
841        assert!(matches!(next(&mut w).await, Event::Resumed { at } if at.seq == 3));
842        let Event::Deltas { items, .. } = next(&mut w).await else { panic!() };
843        assert_eq!(items.iter().map(|(s, _)| *s).collect::<Vec<_>>(), [4, 5]);
844
845        // Too old for the history (3 kept), another epoch, or ahead of the hub: a snapshot.
846        h.publish_all(&"t".into(), [set("a", 1), set("b", 1), set("c", 1)]).unwrap();
847        for p in [Position { epoch: h.epoch(), seq: 3 }, Position { epoch: h.epoch() ^ 1, seq: 8 }, Position { epoch: h.epoch(), seq: 99 }] {
848            let mut w = h.subscribe(&"t".into(), Some(p)).unwrap();
849            assert!(matches!(next(&mut w).await, Event::Snapshot { at, .. } if at.seq == 8), "{p:?}");
850        }
851        let mut w = h.subscribe(&"t".into(), Some(Position { epoch: h.epoch(), seq: 8 })).unwrap();
852        assert!(matches!(next(&mut w).await, Event::Resumed { .. }), "up to date");
853        assert!(h.subscribe(&"nope".into(), None).is_err());
854    }
855
856    #[tokio::test]
857    async fn slow_subscribers_coalesce_then_resnapshot_or_disconnect() {
858        let h = hub(HubOptions::default().with_queue(3));
859        let mut w = h.subscribe(&"t".into(), None).unwrap();
860        next(&mut w).await;
861        for i in 0..100 {
862            h.publish(&"t".into(), set("btc", i)).unwrap();
863        }
864        h.publish(&"t".into(), set("eth", 7)).unwrap();
865        let Event::Deltas { items, .. } = next(&mut w).await else { panic!() };
866        assert_eq!(items, [(101, set("btc", 99)), (102, set("eth", 7))], "latest per key");
867
868        for _ in 0..4 {
869            h.publish(&"t".into(), P::Clear).unwrap();
870        }
871        let Event::Snapshot { at, state } = next(&mut w).await else { panic!("overflow re-snapshots") };
872        assert_eq!((at.seq, state), (106, Prices::default()));
873
874        let h = hub(HubOptions::default().with_queue(1).with_overflow(Overflow::Disconnect));
875        let mut w = h.subscribe(&"t".into(), None).unwrap();
876        next(&mut w).await;
877        h.publish_all(&"t".into(), [P::Clear, P::Clear]).unwrap();
878        assert!(matches!(next(&mut w).await, Event::Ended { reason } if reason == "lagged"));
879        assert!(w.next().await.is_none());
880    }
881
882    #[tokio::test]
883    async fn replacing_and_removing_topics() {
884        let h = hub(HubOptions::default());
885        let mut w = h.subscribe(&"t".into(), None).unwrap();
886        next(&mut w).await;
887        h.publish(&"t".into(), set("x", 1)).unwrap();
888        let mut fresh = Prices::default();
889        fresh.apply(&set("y", 2));
890        h.insert("t".into(), fresh.clone());
891        assert!(matches!(next(&mut w).await, Event::Snapshot { state, .. } if state == fresh));
892        assert!(h.remove(&"t".into()));
893        assert!(matches!(next(&mut w).await, Event::Ended { reason } if reason == "removed"));
894        assert!(!h.contains(&"t".into()) && h.topics().is_empty());
895    }
896
897    #[tokio::test]
898    async fn served_over_a_channel_with_heartbeats_and_rechecks() {
899        let h = hub(HubOptions::default());
900        let allowed = Arc::new(std::sync::atomic::AtomicBool::new(true));
901        let a = allowed.clone();
902        let auth: Arc<dyn Authorize> =
903            Arc::new(
904                move |c: &Caller, x: &Access| {
905                    if a.load(std::sync::atomic::Ordering::SeqCst) { AllowAll.authorize(c, x) } else { Err(ServiceError::refused("revoked")) }
906                },
907            );
908        let access: AccessFn<String> = Arc::new(|t: &String| Access::new("read").on(t.clone()));
909        let (client, server) = memory_pair(8);
910        let opts = FeedOptions::default().with_heartbeat(Duration::from_millis(30)).with_recheck(Some(Duration::from_millis(100)));
911        let (h2, auth2, access2) = (h.clone(), auth.clone(), access.clone());
912        tokio::spawn(async move { serve_feed(h2, access2, auth2, server, "p".into(), &opts).await });
913        let mut sub = Subscription::<String, Prices>::start(client, Credentials::new(), "t".into(), None)
914            .await
915            .unwrap()
916            .with_stall(Some(Duration::from_millis(500)));
917        assert!(matches!(sub.next().await, Some(Ok(Event::Snapshot { .. }))));
918        tokio::time::sleep(Duration::from_millis(80)).await; // heartbeats are swallowed
919        h.publish(&"t".into(), set("btc", 5)).unwrap();
920        assert!(matches!(sub.next().await, Some(Ok(Event::Deltas { items, .. })) if items == [(2, set("btc", 5))]));
921        allowed.store(false, std::sync::atomic::Ordering::SeqCst);
922        assert_eq!(sub.next().await.unwrap().unwrap_err(), ServiceError::refused("revoked"));
923        assert!(sub.next().await.is_none());
924
925        let (client, server) = memory_pair(8);
926        let opts = FeedOptions::default();
927        tokio::spawn(async move { serve_feed(h, access, auth, server, "p".into(), &opts).await });
928        let refused = Subscription::<String, Prices>::start(client, Credentials::new(), "t".into(), None).await;
929        assert_eq!(refused.err(), Some(ServiceError::refused("revoked")));
930    }
931}