Skip to main content

artifactize_core/
changes.rs

1//! Best-effort, state-scoped invalidation hints. SQLite and session files remain authoritative.
2//! The first subscriber temporarily hosts a hub; there is no daemon and writers never elect one.
3mod probe;
4#[cfg(test)]
5pub(crate) mod test_support;
6#[cfg(test)]
7mod tests;
8mod transport;
9
10use crate::types::{RunId, SessionId};
11use serde::{Deserialize, Serialize};
12use std::{
13    collections::{BTreeMap, BTreeSet},
14    path::Path,
15    sync::{Arc, Mutex, OnceLock, Weak},
16    time::Duration,
17};
18use tokio::{
19    io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt},
20    sync::{Notify, broadcast, oneshot},
21    task::JoinSet,
22};
23use tokio_util::sync::CancellationToken;
24use transport::Endpoint;
25
26/// Reconcile missed commits and database replacement without reloading idle snapshots.
27pub const RECONCILE: Duration = Duration::from_secs(5);
28/// A dead hub is replaced promptly, without a spin loop or a permanent process.
29const RECONNECT: Duration = Duration::from_millis(500);
30/// Bound startup and short-command shutdown; notification availability cannot block correctness.
31const DELIVERY_TIMEOUT: Duration = Duration::from_millis(300);
32/// Bound hostile frames before allocation (IDs are at most 200 bytes).
33const MAX_FRAME_BYTES: usize = 1024;
34/// Share a small number of long-lived per-state publisher tasks; a writer can always
35/// commit without notifications when those are full.
36const MAX_STATES: usize = 32;
37/// Cap per-hub handles and tasks so abandoned or idle clients cannot exhaust them.
38const MAX_CLIENTS: usize = 64;
39/// Absorb a burst of commits without unbounded buffering for a stalled subscriber.
40const MAX_BACKLOG: usize = 64;
41/// Above this many dirty transcripts, one resync is cheaper than tracking every hint.
42const MAX_DIRTY_SESSIONS: usize = 64;
43/// Above this many dirty Runs, reread the state rather than holding an unbounded set.
44const MAX_DIRTY_RUNS: usize = 64;
45/// Version 2 names the Run a write changed ([`Change::RunInvalidated`]). The wire format is
46/// independent of the state database schema and durable session-event format. The Hello
47/// handshake rejects any unsupported version instead of interpreting incompatible hints; a
48/// reader that cannot connect reconciles every [`RECONCILE`] instead.
49const VERSION: u32 = 2;
50
51/// Hints carry no records, credentials, scheduler decisions or remote-store events.
52#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
53pub enum Change {
54    /// The list of Runs changed: a Run was created or removed, or a write could not be tied to
55    /// a Run. Any Run may have changed with it.
56    StateInvalidated,
57    /// That Run's records changed: its state, a request, or an execution one of its requests
58    /// holds.
59    RunInvalidated(RunId),
60    SessionInvalidated(SessionId),
61    /// Initial registration, reconnect, gap, overflow or database replacement: read afresh.
62    Resync,
63}
64
65/// What the hints since a reader's last read say it must read again: nothing, these Runs, or
66/// everything. Session hints are not about the state database and change nothing here.
67#[derive(Debug, Clone, Default, PartialEq, Eq)]
68pub enum Changed {
69    #[default]
70    Nothing,
71    Runs(BTreeSet<RunId>),
72    Everything,
73}
74impl Changed {
75    pub fn add(&mut self, change: &Change) {
76        match change {
77            Change::StateInvalidated | Change::Resync => *self = Self::Everything,
78            Change::RunInvalidated(id) if !matches!(self, Self::Everything) => {
79                self.add_run(id.clone());
80            }
81            Change::RunInvalidated(_) => {}
82            Change::SessionInvalidated(_) => {}
83        }
84    }
85    fn add_run(&mut self, id: RunId) {
86        match self {
87            Self::Nothing => *self = Self::Runs(BTreeSet::from([id])),
88            Self::Runs(ids) => {
89                ids.insert(id);
90                if ids.len() > MAX_DIRTY_RUNS {
91                    *self = Self::Everything;
92                }
93            }
94            Self::Everything => {}
95        }
96    }
97    fn pop(&mut self) -> Option<Change> {
98        match self {
99            Self::Nothing => None,
100            Self::Runs(ids) => {
101                let change = ids.pop_first().map(Change::RunInvalidated);
102                if ids.is_empty() {
103                    *self = Self::Nothing;
104                }
105                change
106            }
107            Self::Everything => {
108                *self = Self::Nothing;
109                Some(Change::StateInvalidated)
110            }
111        }
112    }
113    /// Keep what `other` says changed as well, as when a read that took it was not used.
114    pub fn merge(&mut self, other: Self) {
115        match other {
116            Self::Nothing => {}
117            Self::Everything => *self = Self::Everything,
118            Self::Runs(ids) => {
119                for id in ids {
120                    self.add_run(id);
121                }
122            }
123        }
124    }
125    /// What a read reads again: what the hints named or, when the database was `written` and
126    /// no hint named the change yet (a writer that could not reach the hub), everything.
127    pub fn or_written(&self, written: bool) -> Self {
128        match self {
129            Self::Nothing if written => Self::Everything,
130            changed => changed.clone(),
131        }
132    }
133    /// Whether Run `id` may have changed.
134    pub fn run(&self, id: &RunId) -> bool {
135        match self {
136            Self::Nothing => false,
137            Self::Runs(ids) => ids.contains(id),
138            Self::Everything => true,
139        }
140    }
141}
142
143/// Changes not yet delivered: a resync replaces everything else pending, and a state change
144/// replaces pending Run changes.
145enum Dirty {
146    Pending {
147        state: Changed,
148        sessions: BTreeSet<SessionId>,
149    },
150    Resync,
151}
152impl Default for Dirty {
153    fn default() -> Self {
154        Self::Pending {
155            state: Changed::Nothing,
156            sessions: BTreeSet::new(),
157        }
158    }
159}
160impl Dirty {
161    fn add(&mut self, change: Change) {
162        let Self::Pending { state, sessions } = self else {
163            return;
164        };
165        match change {
166            Change::Resync => *self = Self::Resync,
167            Change::StateInvalidated => *state = Changed::Everything,
168            Change::RunInvalidated(id) => state.add_run(id),
169            Change::SessionInvalidated(id) => {
170                sessions.insert(id);
171                if sessions.len() > MAX_DIRTY_SESSIONS {
172                    *self = Self::Resync;
173                }
174            }
175        }
176    }
177    fn pop(&mut self) -> Option<Change> {
178        match self {
179            Self::Resync => {
180                *self = Self::default();
181                Some(Change::Resync)
182            }
183            Self::Pending { state, sessions } => state
184                .pop()
185                .or_else(|| sessions.pop_first().map(Change::SessionInvalidated)),
186        }
187    }
188    fn is_empty(&self) -> bool {
189        matches!(self, Self::Pending { state: Changed::Nothing, sessions } if sessions.is_empty())
190    }
191}
192struct Inbox {
193    #[cfg(test)]
194    registration: tokio::sync::watch::Sender<Option<crate::config::HubEpoch>>,
195    // A test can wait for received hints rather than confusing the hub's ACK with delivery.
196    #[cfg(test)]
197    received: tokio::sync::watch::Sender<Option<u64>>,
198    dirty: Mutex<Dirty>,
199    wake: Notify,
200}
201impl Default for Inbox {
202    fn default() -> Self {
203        Self {
204            #[cfg(test)]
205            registration: tokio::sync::watch::channel(None).0,
206            #[cfg(test)]
207            received: tokio::sync::watch::channel(None).0,
208            dirty: Mutex::default(),
209            wake: Notify::new(),
210        }
211    }
212}
213impl Inbox {
214    fn add(&self, change: Change) {
215        self.dirty.lock().unwrap().add(change);
216        self.wake.notify_one();
217    }
218    async fn next(&self) -> Change {
219        loop {
220            // Register before checking: a hint arriving between check and await is retained.
221            let wake = self.wake.notified();
222            if let Some(change) = self.dirty.lock().unwrap().pop() {
223                return change;
224            }
225            wake.await;
226        }
227    }
228}
229
230/// The OS directory outside `state` where its subscriptions meet. Every process using that
231/// state shares it, so only the owner of a temporary state removes it with the state.
232pub fn namespace(state: &Path) -> std::io::Result<std::path::PathBuf> {
233    Endpoint::new(state).map(|endpoint| endpoint.directory().to_owned())
234}
235
236/// Register before reading the baseline. Dirties arriving during that read stay queued.
237/// Drop requests cancellation; await [`Self::close`] before removing the subscribed state.
238pub struct Subscription {
239    inbox: Arc<Inbox>,
240    cancel: CancellationToken,
241    task: tokio::task::JoinHandle<Result<(), String>>,
242}
243impl Subscription {
244    pub async fn new(state: &Path) -> Self {
245        let mut interval =
246            tokio::time::interval_at(tokio::time::Instant::now() + RECONCILE, RECONCILE);
247        interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
248        Self::with_reconciliation(state, Reconciliation::Interval(interval)).await
249    }
250
251    async fn with_reconciliation(state: &Path, reconciliation: Reconciliation) -> Self {
252        let inbox = Arc::new(Inbox::default());
253        let cancel = CancellationToken::new();
254        let (ready, registered) = oneshot::channel();
255        let state = state.to_path_buf();
256        let task = tokio::spawn(watch(
257            state,
258            inbox.clone(),
259            cancel.clone(),
260            ready,
261            reconciliation,
262        ));
263        // Keep cancellation ownership even if the caller abandons registration midway.
264        let subscription = Self {
265            inbox,
266            cancel,
267            task,
268        };
269        // An unavailable or unsafe endpoint degrades, never prevents a baseline read.
270        let _ = registered.await;
271        subscription
272    }
273    /// Stop this subscription and wait for its connection, hub and probe database to close.
274    /// Other subscriptions remain independent. Dropping this future still requests cancellation.
275    pub async fn close(mut self) -> Result<(), String> {
276        self.cancel.cancel();
277        crate::task::joined((&mut self.task).await).map_err(|error| error.to_string())?
278    }
279    /// Process-owner death has no database writer; reuse the subscription's reconciliation
280    /// cadence when an observer also owns liveness reconciliation.
281    pub async fn next_reconciled(&mut self) -> Change {
282        tokio::time::timeout(RECONCILE, self.next_state())
283            .await
284            .unwrap_or(Change::Resync)
285    }
286    pub async fn next(&mut self) -> Change {
287        self.inbox.next().await
288    }
289    /// Schedulers and non-session UIs can ignore session-only hints without reloading state.
290    /// A Run's hint is returned: the caller reads that Run again, or the state.
291    pub async fn next_state(&mut self) -> Change {
292        loop {
293            let change = self.next().await;
294            if !matches!(change, Change::SessionInvalidated(_)) {
295                return change;
296            }
297        }
298    }
299}
300impl Drop for Subscription {
301    fn drop(&mut self) {
302        self.cancel.cancel();
303    }
304}
305
306#[derive(Default)]
307struct Outbox {
308    dirty: Dirty,
309    submitted: u64,
310    delivered: u64,
311}
312struct Publishing {
313    endpoint: Endpoint,
314    pending: Mutex<Outbox>,
315    wake: Notify,
316    drained: Notify,
317    // Fixture barriers must distinguish an actual hub ACK from best-effort timeout.
318    #[cfg(test)]
319    delivery_error: Mutex<Option<String>>,
320}
321/// Cloneable synchronous producer, also safe to invoke on the SQLite worker thread.
322#[derive(Clone, Default)]
323pub(crate) struct Publisher(Option<Arc<Publishing>>);
324static PUBLISHERS: OnceLock<Mutex<BTreeMap<crate::config::EndpointId, Weak<Publishing>>>> =
325    OnceLock::new();
326impl Publisher {
327    pub(crate) fn new(state: &Path) -> Self {
328        let Ok(runtime) = tokio::runtime::Handle::try_current() else {
329            return Self::default();
330        };
331        let Ok(endpoint) = Endpoint::new(state) else {
332            return Self::default();
333        };
334        let mut publishers = PUBLISHERS.get_or_init(Default::default).lock().unwrap();
335        publishers.retain(|_, publisher| publisher.strong_count() != 0);
336        if let Some(publisher) = publishers.get(&endpoint.identity).and_then(Weak::upgrade) {
337            return Self(Some(publisher));
338        }
339        if publishers.len() >= MAX_STATES {
340            return Self::default();
341        }
342        let publisher = Arc::new(Publishing {
343            endpoint,
344            pending: Mutex::new(Outbox::default()),
345            wake: Notify::new(),
346            drained: Notify::new(),
347            #[cfg(test)]
348            delivery_error: Mutex::default(),
349        });
350        publishers.insert(
351            publisher.endpoint.identity.clone(),
352            Arc::downgrade(&publisher),
353        );
354        runtime.spawn(publish(publisher.clone()));
355        Self(Some(publisher))
356    }
357    pub(crate) fn notify(&self, change: Change) {
358        if let Some(publisher) = &self.0 {
359            let mut pending = publisher.pending.lock().unwrap();
360            pending.dirty.add(change);
361            pending.submitted = pending.submitted.wrapping_add(1);
362            drop(pending);
363            publisher.wake.notify_one();
364        }
365    }
366}
367
368/// Drain short-lived commands centrally. Only bounded hints are sent; a failed delivery is safe.
369pub async fn drain() {
370    let publishers: Vec<_> = PUBLISHERS
371        .get()
372        .map(|publishers| {
373            publishers
374                .lock()
375                .unwrap()
376                .values()
377                .filter_map(Weak::upgrade)
378                .collect()
379        })
380        .unwrap_or_default();
381    let wait = async {
382        for publisher in publishers {
383            let target = publisher.pending.lock().unwrap().submitted;
384            loop {
385                let drained = publisher.drained.notified();
386                if publisher.pending.lock().unwrap().delivered >= target {
387                    break;
388                }
389                drained.await;
390            }
391        }
392    };
393    let _ = tokio::time::timeout(DELIVERY_TIMEOUT, wait).await;
394}
395
396#[derive(Serialize, Deserialize)]
397enum Frame {
398    Hello {
399        version: u32,
400        identity: crate::config::EndpointId,
401        subscriber: bool,
402    },
403    Registered {
404        epoch: crate::config::HubEpoch,
405    },
406    Publish(Change),
407    Delivered,
408    Hint {
409        epoch: crate::config::HubEpoch,
410        sequence: u64,
411        change: Change,
412    },
413}
414async fn read_frame<R: AsyncRead + Unpin>(reader: &mut R) -> std::io::Result<Frame> {
415    let bytes = reader.read_u32().await? as usize;
416    if bytes == 0 || bytes > MAX_FRAME_BYTES {
417        return Err(std::io::ErrorKind::InvalidData.into());
418    }
419    let mut data = vec![0; bytes];
420    reader.read_exact(&mut data).await?;
421    serde_json::from_slice(&data).map_err(std::io::Error::other)
422}
423async fn write_frame<W: AsyncWrite + Unpin>(writer: &mut W, frame: &Frame) -> std::io::Result<()> {
424    let data = serde_json::to_vec(frame).map_err(std::io::Error::other)?;
425    if data.len() > MAX_FRAME_BYTES {
426        return Err(std::io::ErrorKind::InvalidData.into());
427    }
428    writer.write_u32(data.len() as u32).await?;
429    writer.write_all(&data).await?;
430    writer.flush().await
431}
432async fn connect(
433    endpoint: &Endpoint,
434    subscriber: bool,
435) -> std::io::Result<(transport::Stream, crate::config::HubEpoch)> {
436    let mut stream = endpoint.connect().await?;
437    write_frame(
438        &mut stream,
439        &Frame::Hello {
440            version: VERSION,
441            identity: endpoint.identity.clone(),
442            subscriber,
443        },
444    )
445    .await?;
446    match read_frame(&mut stream).await? {
447        Frame::Registered { epoch } if epoch.len() <= crate::types::MAX_ID_BYTES => {
448            Ok((stream, epoch))
449        }
450        _ => Err(std::io::ErrorKind::InvalidData.into()),
451    }
452}
453async fn publish(publisher: Arc<Publishing>) {
454    loop {
455        let wake = publisher.wake.notified();
456        if publisher.pending.lock().unwrap().dirty.is_empty() {
457            tokio::select! {
458                _ = wake => {},
459                _ = tokio::time::sleep(RECONNECT) => {
460                    // The task must not retain a publisher forever after its writers disappear.
461                    if Arc::strong_count(&publisher) == 1 {
462                        break;
463                    }
464                    continue;
465                }
466            }
467        }
468        let (mut dirty, target) = {
469            let mut pending = publisher.pending.lock().unwrap();
470            (std::mem::take(&mut pending.dirty), pending.submitted)
471        };
472        // No retries when no reader exists: future registration and the probe recover all state.
473        let delivery = async {
474            let (mut stream, _) = connect(&publisher.endpoint, false).await?;
475            while let Some(change) = dirty.pop() {
476                write_frame(&mut stream, &Frame::Publish(change)).await?;
477                if !matches!(read_frame(&mut stream).await?, Frame::Delivered) {
478                    return Err(std::io::ErrorKind::InvalidData.into());
479                }
480            }
481            Ok::<_, std::io::Error>(())
482        };
483        let _delivery = tokio::time::timeout(DELIVERY_TIMEOUT, delivery).await;
484        #[cfg(test)]
485        if !matches!(&_delivery, Ok(Ok(()))) {
486            *publisher.delivery_error.lock().unwrap() = Some(format!("{_delivery:?}"));
487        }
488        publisher.pending.lock().unwrap().delivered = target;
489        publisher.drained.notify_one();
490    }
491}
492
493enum Reconciliation {
494    Interval(tokio::time::Interval),
495    #[cfg(test)]
496    Controlled(tokio::sync::mpsc::UnboundedReceiver<()>),
497}
498
499impl Reconciliation {
500    async fn tick(&mut self) {
501        match self {
502            Self::Interval(interval) => {
503                interval.tick().await;
504            }
505            #[cfg(test)]
506            Self::Controlled(ticks) => {
507                if ticks.recv().await.is_none() {
508                    std::future::pending::<()>().await;
509                }
510            }
511        }
512    }
513}
514
515async fn watch(
516    state: std::path::PathBuf,
517    inbox: Arc<Inbox>,
518    cancel: CancellationToken,
519    ready: oneshot::Sender<()>,
520    mut reconcile: Reconciliation,
521) -> Result<(), String> {
522    let mut ready = Some(ready);
523    let endpoint = Endpoint::new(&state).ok();
524    let mut hub = None;
525    let mut probe = probe::Probe::new(state);
526    // Establish the cheap persistent baseline before the caller reads its snapshot.
527    let _ = probe.changed().await;
528    loop {
529        if cancel.is_cancelled() {
530            break;
531        }
532        if let Some(endpoint) = &endpoint {
533            if hub
534                .as_ref()
535                .is_some_and(|task: &tokio::task::JoinHandle<()>| task.is_finished())
536            {
537                hub = None;
538            }
539            if hub.is_none()
540                && let Ok(Some(owner)) = endpoint.elect()
541                && let Ok(listener) = endpoint.listen()
542            {
543                let endpoint = endpoint.clone();
544                let token = cancel.child_token();
545                hub = Some(tokio::spawn(async move {
546                    let _ = serve(endpoint, listener, owner, token).await;
547                }));
548            }
549            let connection = tokio::time::timeout(DELIVERY_TIMEOUT, connect(endpoint, true));
550            tokio::select! {
551                _ = cancel.cancelled() => break,
552                result = connection => {
553                    if let Ok(Ok((stream, epoch))) = result {
554                        inbox.add(Change::Resync);
555                        #[cfg(test)]
556                        inbox.registration.send_replace(Some(epoch.clone()));
557                        if let Some(ready) = ready.take() {
558                            let _ = ready.send(());
559                        }
560                        let receive = receive(stream, epoch, inbox.clone());
561                        tokio::pin!(receive);
562                        loop {
563                            tokio::select! {
564                                _ = cancel.cancelled() => break,
565                                _ = &mut receive => {
566                                    #[cfg(test)]
567                                    inbox.registration.send_replace(None);
568                                    inbox.add(Change::Resync);
569                                    break;
570                                }
571                                // A commit no hint reported is read like one; only a
572                                // replaced database is read afresh.
573                                _ = reconcile.tick() => match probe.changed().await {
574                                    probe::Probed::Same => {}
575                                    probe::Probed::Written => inbox.add(Change::StateInvalidated),
576                                    probe::Probed::Replaced => inbox.add(Change::Resync),
577                                }
578                            }
579                        }
580                    }
581                }
582            }
583        }
584        if let Some(ready) = ready.take() {
585            inbox.add(Change::Resync);
586            let _ = ready.send(());
587        }
588        tokio::select! {
589            _ = cancel.cancelled() => break,
590            _ = reconcile.tick() => {
591                let _ = probe.changed().await;
592                // No secure transport: low-frequency authoritative reconciliation also
593                // recovers session-only writes, which SQLite data_version cannot observe.
594                inbox.add(Change::Resync);
595            },
596            _ = tokio::time::sleep(RECONNECT) => {},
597        }
598    }
599    if let Some(task) = hub {
600        // Its child token is cancelled too; let serve join every client before releasing IPC.
601        let _ = crate::task::joined(task.await);
602    }
603    probe.close().await
604}
605async fn receive(
606    mut stream: transport::Stream,
607    epoch: crate::config::HubEpoch,
608    inbox: Arc<Inbox>,
609) -> std::io::Result<()> {
610    let mut previous = None;
611    loop {
612        match read_frame(&mut stream).await? {
613            Frame::Hint {
614                epoch: incoming,
615                sequence,
616                change,
617            } if incoming == epoch => {
618                if previous.is_some_and(|previous: u64| sequence != previous.wrapping_add(1)) {
619                    inbox.add(Change::Resync);
620                }
621                previous = Some(sequence);
622                inbox.add(change);
623                #[cfg(test)]
624                inbox.received.send_replace(Some(sequence));
625            }
626            _ => return Err(std::io::ErrorKind::InvalidData.into()),
627        }
628    }
629}
630
631#[derive(Clone)]
632struct Hint {
633    sequence: u64,
634    change: Change,
635}
636async fn serve(
637    endpoint: Endpoint,
638    mut listener: transport::Listener,
639    _owner: std::fs::File,
640    cancel: CancellationToken,
641) -> std::io::Result<()> {
642    let epoch: crate::config::HubEpoch = crate::agent::uuid()
643        .map_err(std::io::Error::other)?
644        .parse()
645        .expect("UUID hub epoch");
646    let (sender, _) = broadcast::channel(MAX_BACKLOG);
647    let sequence = Arc::new(Mutex::new(0_u64));
648    let mut clients = JoinSet::new();
649    loop {
650        tokio::select! {
651            _ = cancel.cancelled() => break,
652            Some(result) = clients.join_next(), if !clients.is_empty() => {
653                let _ = crate::task::joined(result);
654            },
655            result = listener.accept(), if clients.len() < MAX_CLIENTS => {
656                let stream = result?;
657                let (identity, epoch, sender, sequence) = (
658                    endpoint.identity.clone(),
659                    epoch.clone(),
660                    sender.clone(),
661                    sequence.clone(),
662                );
663                clients.spawn(async move {
664                    let _ = client(stream, identity, epoch, sender, sequence).await;
665                });
666            }
667        }
668    }
669    clients.abort_all();
670    while let Some(result) = clients.join_next().await {
671        let _ = crate::task::joined(result);
672    }
673    Ok(())
674}
675async fn client(
676    mut stream: transport::Stream,
677    identity: crate::config::EndpointId,
678    epoch: crate::config::HubEpoch,
679    sender: broadcast::Sender<Hint>,
680    sequence: Arc<Mutex<u64>>,
681) -> std::io::Result<()> {
682    // Peer lookup can fail after a short-lived connection closes (Darwin ENOTCONN).
683    // Reject only that client, never tear down the listener or other subscribers.
684    transport::validate_peer(&stream)?;
685    let hello = tokio::time::timeout(DELIVERY_TIMEOUT, read_frame(&mut stream)).await??;
686    let Frame::Hello {
687        version: VERSION,
688        identity: incoming,
689        subscriber,
690    } = hello
691    else {
692        return Err(std::io::ErrorKind::InvalidData.into());
693    };
694    if incoming != identity {
695        return Err(std::io::ErrorKind::PermissionDenied.into());
696    }
697    // Register before acknowledging. Broadcast retains any hint that races the baseline read.
698    let mut receiver = sender.subscribe();
699    tokio::time::timeout(
700        DELIVERY_TIMEOUT,
701        write_frame(
702            &mut stream,
703            &Frame::Registered {
704                epoch: epoch.clone(),
705            },
706        ),
707    )
708    .await??;
709    if subscriber {
710        let (mut reader, mut writer) = tokio::io::split(stream);
711        let outgoing = async {
712            loop {
713                let hint = match receiver.recv().await {
714                    Ok(hint) => hint,
715                    Err(broadcast::error::RecvError::Lagged(_)) => Hint {
716                        sequence: *sequence.lock().unwrap(),
717                        change: Change::Resync,
718                    },
719                    Err(_) => return Ok::<_, std::io::Error>(()),
720                };
721                // A slow client loses only hints, not memory or the hub's other clients.
722                tokio::time::timeout(
723                    DELIVERY_TIMEOUT,
724                    write_frame(
725                        &mut writer,
726                        &Frame::Hint {
727                            epoch: epoch.clone(),
728                            sequence: hint.sequence,
729                            change: hint.change,
730                        },
731                    ),
732                )
733                .await??;
734            }
735        };
736        tokio::select! { result = outgoing => result, _ = reader.read_u8() => Ok(()) }
737    } else {
738        loop {
739            let frame = tokio::time::timeout(DELIVERY_TIMEOUT, read_frame(&mut stream)).await??;
740            let Frame::Publish(change) = frame else {
741                return Err(std::io::ErrorKind::InvalidData.into());
742            };
743            {
744                // Serialize sequence assignment and broadcast, including concurrent writers.
745                let mut sequence = sequence.lock().unwrap();
746                *sequence = sequence.wrapping_add(1);
747                let _ = sender.send(Hint {
748                    sequence: *sequence,
749                    change,
750                });
751            }
752            tokio::time::timeout(
753                DELIVERY_TIMEOUT,
754                write_frame(&mut stream, &Frame::Delivered),
755            )
756            .await??;
757        }
758    }
759}