iroh_live_node/value.rs
1//! A reader of a latest-value JSON track that follows its subscription to a new publisher.
2
3use std::{fmt, time::Duration};
4
5use moq_ext_json::ValueError;
6use moq_net::broadcast;
7use serde::de::DeserializeOwned;
8use tokio::sync::watch;
9use tracing::debug;
10
11use crate::{Subscription, json};
12
13/// How long a track that failed waits for its broadcast to end before the error counts.
14///
15/// A track fails as its broadcast ends, a moment before the broadcast reports
16/// that it closed.
17const END_GRACE: Duration = Duration::from_millis(500);
18
19/// A reader of a latest-value JSON track that follows its [`Subscription`].
20///
21/// Returned by [`Subscription::value_track`]. When the publisher restarts and
22/// a new broadcast takes over the path, the reader opens the track on the new
23/// broadcast and reads on, the same as media follows the subscription. The
24/// first read after the move returns the new publisher's current value. The
25/// reader ends only once the subscription closes.
26///
27/// The reader holds the subscription, so the subscription stays open while
28/// the reader lives.
29///
30/// A value's `at` orders it among the others but is not the writer's time:
31/// moq-lite 06, which sessions speak, drops frame timestamps, so a track
32/// arrives untimed and `at` holds the group's sequence with no timescale. Put
33/// a time in the value itself when the reader needs it.
34pub struct ValueReader<T> {
35 subscription: Subscription,
36 name: String,
37 /// The broadcast that serves the path, as the subscription follows it.
38 current: watch::Receiver<broadcast::Consumer>,
39 /// The broadcast the track was opened on.
40 broadcast: broadcast::Consumer,
41 /// The track on [`broadcast`](Self::broadcast), or `None` once it ended
42 /// or when that broadcast has no such track.
43 track: Option<json::snapshot::Consumer<T>>,
44}
45
46impl<T> fmt::Debug for ValueReader<T> {
47 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
48 f.debug_struct("ValueReader")
49 .field("path", self.subscription.path())
50 .field("name", &self.name)
51 .field("open", &self.track.is_some())
52 .finish()
53 }
54}
55
56impl<T: DeserializeOwned> ValueReader<T> {
57 /// Creates a reader of track `name` that follows `subscription`.
58 ///
59 /// Opens the track on the broadcast that serves the path now.
60 pub(crate) fn new(
61 subscription: Subscription,
62 current: watch::Receiver<broadcast::Consumer>,
63 name: &str,
64 ) -> Result<Self, moq_net::Error> {
65 let mut current = current;
66 let broadcast = current.borrow_and_update().clone();
67 let track = open(&broadcast, name)?;
68 Ok(Self {
69 subscription,
70 name: name.to_string(),
71 current,
72 broadcast,
73 track: Some(track),
74 })
75 }
76
77 /// Returns the name of the track.
78 #[must_use]
79 pub fn name(&self) -> &str {
80 &self.name
81 }
82
83 /// Waits for the newest value, skipping older ones.
84 ///
85 /// Returns `None` once the subscription closes. Cancellation safe.
86 ///
87 /// # Errors
88 ///
89 /// Fails when a value does not decode, or when the publisher refuses the
90 /// track, such as a track it does not publish. A track that ends with its
91 /// broadcast is no error: the reader waits for the next broadcast.
92 pub async fn latest(&mut self) -> Result<Option<json::Timed<T>>, ValueError> {
93 Ok(self.read(Read::Latest).await?)
94 }
95
96 /// Waits for the next value, in order within the newest group.
97 ///
98 /// Returns `None` once the subscription closes. Cancellation safe.
99 ///
100 /// # Errors
101 ///
102 /// As [`latest`](Self::latest).
103 pub async fn next(&mut self) -> Result<Option<json::Timed<T>>, ValueError> {
104 Ok(self.read(Read::Next).await?)
105 }
106
107 /// Reads a value from the track, and moves to the next broadcast when it ends.
108 async fn read(&mut self, how: Read) -> json::Result<Option<json::Timed<T>>> {
109 loop {
110 let Some(track) = self.track.as_mut() else {
111 if !self.next_broadcast().await {
112 return Ok(None);
113 }
114 continue;
115 };
116 let read = async {
117 match how {
118 Read::Latest => track.latest().await,
119 Read::Next => track.next().await,
120 }
121 };
122 // The reader holds the subscription, and so the sender, so the
123 // watch never closes under it.
124 let result = tokio::select! {
125 result = read => Some(result),
126 _ = self.current.changed() => None,
127 };
128 // The subscription moved to another broadcast before a value came.
129 let Some(result) = result else {
130 self.reopen();
131 continue;
132 };
133 match result {
134 Ok(Some(value)) => return Ok(Some(value)),
135 Ok(None) => {
136 debug!(path = %self.subscription.path(), track = self.name, "value track finished, waiting for the next broadcast");
137 self.track = None;
138 }
139 Err(json::Error::Net(err)) => {
140 if !ended_with_broadcast(&self.broadcast, &self.subscription).await {
141 return Err(json::Error::Net(err));
142 }
143 debug!(path = %self.subscription.path(), track = self.name, error = %err, "value track ended with its broadcast");
144 self.track = None;
145 }
146 Err(err) => return Err(err),
147 }
148 }
149 }
150
151 /// Waits for another broadcast to serve the path, and opens the track on it.
152 ///
153 /// Returns `false` once the subscription closed instead.
154 async fn next_broadcast(&mut self) -> bool {
155 let moved = tokio::select! {
156 changed = self.current.changed() => changed.is_ok(),
157 () = self.subscription.closed() => false,
158 };
159 if moved {
160 self.reopen();
161 }
162 moved
163 }
164
165 /// Opens the track on the broadcast that serves the path now.
166 fn reopen(&mut self) {
167 self.broadcast = self.current.borrow_and_update().clone();
168 self.track = match open(&self.broadcast, &self.name) {
169 Ok(track) => {
170 debug!(path = %self.subscription.path(), track = self.name, "reading the value track of a new broadcast");
171 Some(track)
172 }
173 Err(err) => {
174 debug!(path = %self.subscription.path(), track = self.name, error = %err, "the new broadcast has no such value track");
175 None
176 }
177 };
178 }
179}
180
181/// Reports whether `broadcast` or `subscription` ended, within [`END_GRACE`].
182///
183/// Takes the two rather than the reader, whose track is not `Sync`, so the
184/// read futures stay `Send`.
185async fn ended_with_broadcast(
186 broadcast: &broadcast::Consumer,
187 subscription: &Subscription,
188) -> bool {
189 let ended = async {
190 tokio::select! {
191 () = broadcast.closed() => {}
192 () = subscription.closed() => {}
193 }
194 };
195 tokio::time::timeout(END_GRACE, ended).await.is_ok()
196}
197
198/// Fails to compile if a read future is not `Send`, which a spawned task needs.
199#[cfg(test)]
200#[expect(dead_code, reason = "a compile-time check, never called")]
201fn reads_are_send(reader: &mut ValueReader<u32>) {
202 fn send<F: Send>(_: F) {}
203 send(reader.latest());
204 send(reader.next());
205}
206
207/// Which value a read returns.
208#[derive(Debug, Clone, Copy)]
209enum Read {
210 /// The newest, skipping older ones.
211 Latest,
212 /// The next, in order.
213 Next,
214}
215
216/// Opens the latest-value track `name` of `broadcast`.
217fn open<T: DeserializeOwned>(
218 broadcast: &broadcast::Consumer,
219 name: &str,
220) -> Result<json::snapshot::Consumer<T>, moq_net::Error> {
221 let track = broadcast.track(name)?;
222 Ok(json::snapshot::Consumer::new(track, Default::default()))
223}