weida/cursor.rs
1//! Cursors: what a peer reports about one transfer, and how it gets here.
2//!
3//! A completion is a **cursor** — a level plus an absolute byte offset — not a
4//! verdict
5//! ([decisions/0023](https://github.com/tuco86/weida/blob/main/docs/decisions/0023-completion-is-a-cursor.md)).
6//! Three properties follow, and all three are structural here rather than
7//! promised:
8//!
9//! * **Coalescing is free.** [`CursorSet`] keeps the maximum offset per level,
10//! so a repeated or reordered record changes nothing and a `watch` channel —
11//! which keeps only the latest value — is the right carrier by construction.
12//! * **Nothing waits on a cursor.** A report rides a unidirectional stream of
13//! its own, and every write on it is best effort: a peer that never reads its
14//! [`Cursors`] blocks no transfer, and a peer that never takes its
15//! [`Reporter`] fails none.
16//! * **A set costs no allocation.** The entries array is fixed at
17//! `MAX_REPORT_LEVELS`, which is also the cap the decoder enforces, so a
18//! snapshot is a `Copy` value a reader can hold without touching the
19//! connection.
20//!
21//! There is no error variant on the reading side. `Cursors::changed` yields
22//! `None` when the reporter FINed, when the stream was reset and when the
23//! connection died, and the three are deliberately indistinguishable: a cursor
24//! is never load-bearing, so "no more cursors" is the only fact a reader can
25//! act on.
26
27use std::collections::HashMap;
28use std::sync::Arc;
29use std::sync::atomic::{AtomicU64, Ordering};
30use std::time::{Duration, Instant};
31
32use tokio::sync::watch;
33use weida_core::Error;
34use weida_protocol::header::MAX_CURSOR_RECORD_LEN;
35use weida_protocol::header::limits::MAX_REPORT_LEVELS;
36use weida_protocol::{
37 CursorHeader, CursorLevel, FrameKind, ReportMode, codes, encode_cursor_record, encode_preamble,
38};
39
40use crate::conn::ConnHandle;
41use crate::transport::SendHalf;
42
43/// The report table of one connection: the ids **this** side handed out.
44///
45/// A peer reports only on transfers it received, so each direction allocates
46/// from its own space and the two cannot collide — which is why there is no
47/// shared numbering rule and no direction field on the wire
48/// (`docs/PROTOCOL.md` §6.2).
49pub(crate) struct ReportTable {
50 /// Next id. Starts at 1: `0` is never allocated, so an id nobody handed
51 /// out cannot masquerade as one.
52 next: AtomicU64,
53 live: std::sync::Mutex<HashMap<u64, Arc<watch::Sender<CursorSet>>>>,
54}
55
56impl ReportTable {
57 pub(crate) fn new() -> ReportTable {
58 ReportTable {
59 next: AtomicU64::new(1),
60 live: std::sync::Mutex::new(HashMap::new()),
61 }
62 }
63
64 /// Hands out the sender for `id`, or `None` if no transfer of ours ordered
65 /// it.
66 ///
67 /// The clone is taken once per cursor stream rather than once per record:
68 /// a reader holds it for the stream's life and pays no lock per record.
69 pub(crate) fn claim(&self, id: u64) -> Option<Arc<watch::Sender<CursorSet>>> {
70 self.live
71 .lock()
72 .unwrap_or_else(|e| e.into_inner())
73 .get(&id)
74 .map(Arc::clone)
75 }
76
77 /// Drops the report's entry, which is what turns a reader's
78 /// [`Cursors::changed`] into `None`.
79 ///
80 /// A poisoned lock is taken rather than propagated: this runs inside
81 /// `Drop for ReportGuard`, and a panic in a destructor during an unwind
82 /// aborts the process. A map of senders has no invariant a panic could
83 /// have broken.
84 pub(crate) fn release(&self, id: u64) {
85 self.live
86 .lock()
87 .unwrap_or_else(|e| e.into_inner())
88 .remove(&id);
89 }
90}
91
92/// Allocates a report id and the channel its cursors will arrive on.
93///
94/// The [`Cursors`] handle owns the table entry: dropping it releases the id,
95/// which is what keeps the table bounded by handles the application holds
96/// rather than by transfers it has ever sent.
97pub(crate) fn order_report(conn: &ConnHandle) -> (u64, Cursors) {
98 let id = conn.reports.next.fetch_add(1, Ordering::Relaxed);
99 let (tx, rx) = watch::channel(CursorSet::default());
100 conn.reports
101 .live
102 .lock()
103 .unwrap_or_else(|e| e.into_inner())
104 .insert(id, Arc::new(tx));
105 (
106 id,
107 Cursors {
108 rx,
109 guard: ReportGuard {
110 id,
111 conn: ConnHandle::clone(conn),
112 },
113 },
114 )
115}
116
117/// Releases a report id when the last reader of its cursors goes away.
118struct ReportGuard {
119 id: u64,
120 conn: ConnHandle,
121}
122
123impl Drop for ReportGuard {
124 fn drop(&mut self) {
125 self.conn.reports.release(self.id);
126 }
127}
128
129/// The latest offset reported per level, for one transfer.
130///
131/// Absolute offsets, so this is a complete picture however many records were
132/// coalesced away: a reader that misses every intermediate record still ends
133/// at the same numbers
134/// ([0023](https://github.com/tuco86/weida/blob/main/docs/decisions/0023-completion-is-a-cursor.md)
135/// §4.3b). Levels are ordered by their wire value, weida's own below the
136/// application floor and the application's above it.
137#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
138pub struct CursorSet {
139 /// `(level wire value, offset)`, sorted by level, `len` entries used.
140 entries: [(u64, u64); MAX_REPORT_LEVELS],
141 len: u8,
142}
143
144impl CursorSet {
145 /// The offset reported for `level`, or `None` if it never was.
146 pub fn offset(&self, level: CursorLevel) -> Option<u64> {
147 let wire = level.to_wire();
148 self.used()
149 .iter()
150 .find(|(w, _)| *w == wire)
151 .map(|(_, offset)| *offset)
152 }
153
154 /// Every reported level with its offset, in ascending level order.
155 pub fn iter(&self) -> impl Iterator<Item = (CursorLevel, u64)> + '_ {
156 self.used().iter().map(|(wire, offset)| {
157 (
158 CursorLevel::from_wire(*wire).expect("only decoded levels are stored"),
159 *offset,
160 )
161 })
162 }
163
164 /// How many levels have been reported.
165 pub fn len(&self) -> usize {
166 usize::from(self.len)
167 }
168
169 /// True while nothing has been reported.
170 pub fn is_empty(&self) -> bool {
171 self.len == 0
172 }
173
174 fn used(&self) -> &[(u64, u64)] {
175 &self.entries[..usize::from(self.len)]
176 }
177
178 /// Records `offset` for `level`, keeping the **maximum**.
179 ///
180 /// Returns whether anything moved. Keeping the maximum is what makes a
181 /// duplicated or reordered record a no-op rather than a correction, and
182 /// returning "did it move" is what lets the connection skip a
183 /// notification nobody would learn anything from.
184 ///
185 /// A level past the cap is dropped: the decoder already refuses a header
186 /// that orders more than `MAX_REPORT_LEVELS`, so this is reachable only
187 /// from a peer reporting levels it never was asked for, which is ignored
188 /// anyway.
189 pub(crate) fn advance(&mut self, level: CursorLevel, offset: u64) -> bool {
190 let wire = level.to_wire();
191 let used = usize::from(self.len);
192 match self.entries[..used].binary_search_by_key(&wire, |(w, _)| *w) {
193 Ok(at) => {
194 if offset <= self.entries[at].1 {
195 return false;
196 }
197 self.entries[at].1 = offset;
198 true
199 }
200 Err(at) => {
201 if used == MAX_REPORT_LEVELS {
202 return false;
203 }
204 self.entries[at..=used].rotate_right(1);
205 self.entries[at] = (wire, offset);
206 self.len += 1;
207 true
208 }
209 }
210 }
211}
212
213/// The reader's end of one transfer's report.
214///
215/// Independent of the transfer it came from, and deliberately so: the terminal
216/// cursor arrives **after** the payload's FIN, so a handle tied to the
217/// transfer would be gone exactly when the interesting record lands.
218#[derive(Debug)]
219pub struct Cursors {
220 rx: watch::Receiver<CursorSet>,
221 guard: ReportGuard,
222}
223
224impl Cursors {
225 /// The latest set, without waiting.
226 pub fn snapshot(&self) -> CursorSet {
227 *self.rx.borrow()
228 }
229
230 /// The latest offset for `level`, without waiting.
231 pub fn offset(&self, level: CursorLevel) -> Option<u64> {
232 self.rx.borrow().offset(level)
233 }
234
235 /// Waits for the next change and returns the new set.
236 ///
237 /// `None` means no further cursors are coming, and it covers three cases
238 /// deliberately indistinguishable: the reporter FINed, the cursor stream
239 /// was reset, or the **connection** went away. The last one is why the
240 /// connection is watched here at all — a peer that simply never reports
241 /// opens no stream, so without it a reader would wait for a FIN nobody
242 /// is going to send. None of the three is a failure of anything: a cursor
243 /// is never load-bearing, so "no more cursors" is the only fact a reader
244 /// can act on.
245 pub async fn changed(&mut self) -> Option<CursorSet> {
246 tokio::select! {
247 changed = self.rx.changed() => {
248 changed.ok()?;
249 Some(*self.rx.borrow_and_update())
250 }
251 _ = self.guard.conn.conn.closed() => None,
252 }
253 }
254}
255
256impl std::fmt::Debug for ReportGuard {
257 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
258 f.debug_struct("ReportGuard").field("id", &self.id).finish()
259 }
260}
261
262/// The writer's end: what a receiver uses to report on a transfer it got.
263///
264/// Every write here is best effort. A peer that reset the cursor stream, or a
265/// connection that died, must not fail the application that is doing the
266/// reporting — so a failed write is logged at `debug` and the reporter goes
267/// quiet. That is the "nothing waits on a cursor" rule seen from the writing
268/// side.
269///
270/// **The granularity is the reporter's own number and is never negotiated**
271/// ([0023](https://github.com/tuco86/weida/blob/main/docs/decisions/0023-completion-is-a-cursor.md)
272/// §4.5): more often is always allowed, less often never. The default is
273/// [`Reporter::DEFAULT_BYTES`] or [`Reporter::DEFAULT_INTERVAL`], whichever
274/// comes first, and [`Reporter::with_granularity`] changes it. Coalescing
275/// loses nothing because cursors are absolute, and
276/// [`Reporter::finish`] always flushes the latest offset per level — so the
277/// terminal cursor is never the one that got coalesced away.
278pub struct Reporter {
279 conn: ConnHandle,
280 report_id: u64,
281 levels: Vec<CursorLevel>,
282 mode: ReportMode,
283 /// Opened on the first record: a reporter that never reports costs no
284 /// stream, which is what makes an ordered level the receiver cannot honour
285 /// free rather than merely cheap.
286 stream: Option<SendHalf>,
287 /// Set once a write failed: the report is over, and retrying would only
288 /// cost the application time.
289 broken: bool,
290 /// Bytes a level must advance before another record is worth writing.
291 bytes: u64,
292 /// Time that must pass before another record is worth writing.
293 interval: Duration,
294 /// The latest offset reported per level, and the last one **emitted**.
295 ///
296 /// Both are needed: the latest is what `finish` flushes, and the emitted
297 /// one is what the two granularity tests are measured against. Fixed at
298 /// the level cap, so a reporter costs no allocation per record.
299 pending: [Option<Pending>; MAX_REPORT_LEVELS],
300}
301
302/// What a reporter remembers about one level between records.
303#[derive(Clone, Copy, Debug)]
304struct Pending {
305 level: CursorLevel,
306 /// Latest offset the application reported.
307 latest: u64,
308 /// Offset of the last record actually written, if any.
309 emitted: Option<u64>,
310 /// When that record was written.
311 at: Option<Instant>,
312}
313
314impl Reporter {
315 /// Default byte granularity: a level must advance this far before another
316 /// record is worth writing.
317 pub const DEFAULT_BYTES: u64 = 1024 * 1024;
318 /// Default time granularity: a level may be reported again this often
319 /// however little it advanced.
320 pub const DEFAULT_INTERVAL: Duration = Duration::from_millis(100);
321
322 pub(crate) fn new(
323 conn: ConnHandle,
324 report_id: u64,
325 levels: Vec<CursorLevel>,
326 mode: ReportMode,
327 ) -> Reporter {
328 Reporter {
329 conn,
330 report_id,
331 levels,
332 mode,
333 stream: None,
334 broken: false,
335 bytes: Reporter::DEFAULT_BYTES,
336 interval: Reporter::DEFAULT_INTERVAL,
337 pending: [None; MAX_REPORT_LEVELS],
338 }
339 }
340
341 /// Sets how often progress records are worth writing.
342 ///
343 /// "Every `bytes` or every `interval`, **whichever comes first**". The
344 /// number is this side's own and is never negotiated: a sender orders
345 /// *which* levels it wants, not how finely
346 /// ([0023](https://github.com/tuco86/weida/blob/main/docs/decisions/0023-completion-is-a-cursor.md)
347 /// §4.5). It has no effect in [`ReportMode::FinalOnly`], where there is
348 /// exactly one record per level whatever the granularity says.
349 pub fn with_granularity(mut self, bytes: u64, interval: Duration) -> Reporter {
350 self.bytes = bytes;
351 self.interval = interval;
352 self
353 }
354
355 /// The levels the sender ordered, ascending.
356 pub fn levels(&self) -> &[CursorLevel] {
357 &self.levels
358 }
359
360 /// The mode the sender asked for.
361 pub fn mode(&self) -> ReportMode {
362 self.mode
363 }
364
365 /// Reports that `level` has reached `offset`.
366 ///
367 /// A level the sender did not order is ignored rather than refused: the
368 /// order says what the sender wants to hear, and volunteering more would
369 /// put records on the wire nobody reads.
370 ///
371 /// What reaches the wire depends on the mode the sender asked for:
372 ///
373 /// * [`ReportMode::Progress`] writes a record when the level has advanced
374 /// by the byte granularity **or** the interval has passed since that
375 /// level's last record, whichever comes first; otherwise the offset is
376 /// only remembered.
377 /// * [`ReportMode::FinalOnly`] writes nothing at all and remembers the
378 /// offset; [`Reporter::finish`] emits one record per level.
379 ///
380 /// Either way nothing is lost, because a cursor is absolute:
381 /// [`Reporter::finish`] flushes the latest offset per level.
382 ///
383 /// Never fails for a transport reason: a broken cursor stream yields
384 /// `Ok(())`, because a cursor is never load-bearing.
385 pub async fn report(&mut self, level: CursorLevel, offset: u64) -> Result<(), Error> {
386 if !self.levels.contains(&level) {
387 return Ok(());
388 }
389 let Some(slot) = self.slot(level) else {
390 return Ok(());
391 };
392 let entry = self.pending[slot].get_or_insert(Pending {
393 level,
394 latest: offset,
395 emitted: None,
396 at: None,
397 });
398 // Absolute offsets: a record that would move a level backwards says
399 // nothing the receiver would keep, so it is not worth a write either.
400 entry.latest = entry.latest.max(offset);
401 let latest = entry.latest;
402 if self.mode == ReportMode::FinalOnly || !self.worth_writing(slot) {
403 return Ok(());
404 }
405 self.emit(slot, latest).await;
406 Ok(())
407 }
408
409 /// Flushes the latest offset per level and FINs the cursor stream.
410 ///
411 /// The flush is what makes coalescing lossless: whatever the granularity
412 /// suppressed, the last number each level reached is on the wire before
413 /// the FIN. A level that was never reported produces **no** record at
414 /// all, which is the honest form of "this side could not report it" — the
415 /// sender sees the level missing from its final snapshot rather than a
416 /// failure.
417 pub async fn finish(mut self) -> Result<(), Error> {
418 for slot in 0..MAX_REPORT_LEVELS {
419 let Some(entry) = self.pending[slot] else {
420 continue;
421 };
422 if entry.emitted == Some(entry.latest) {
423 continue;
424 }
425 self.emit(slot, entry.latest).await;
426 }
427 if let Some(mut stream) = self.stream.take()
428 && let Err(e) = stream.finish()
429 {
430 tracing::debug!(error = %e, "failed to finish a cursor stream");
431 }
432 Ok(())
433 }
434
435 /// The slot this level occupies, allocating one on first use.
436 ///
437 /// `None` only past the cap, which the decoder already refuses: the
438 /// ordered levels are at most `MAX_REPORT_LEVELS`.
439 fn slot(&self, level: CursorLevel) -> Option<usize> {
440 self.levels.iter().position(|l| *l == level)
441 }
442
443 /// Is another record for this level worth a write yet?
444 fn worth_writing(&self, slot: usize) -> bool {
445 let Some(entry) = self.pending[slot] else {
446 return false;
447 };
448 match (entry.emitted, entry.at) {
449 // Nothing written for this level yet: the first record is always
450 // worth it, however small the advance.
451 (None, _) | (_, None) => true,
452 (Some(emitted), Some(at)) => {
453 entry.latest.saturating_sub(emitted) >= self.bytes
454 || self.conn.exec.now().saturating_duration_since(at) >= self.interval
455 }
456 }
457 }
458
459 /// Writes one record for `slot`, opening the stream if this is the first.
460 ///
461 /// Records what was written and when, which is what the granularity is
462 /// measured against — and what makes a `finish` after a fresh record
463 /// write nothing rather than a duplicate.
464 ///
465 /// The open and each write wait at most `header_timeout_ms`: the stream
466 /// credit and the flow control they wait on are the sender's to grant,
467 /// and a cursor is never load-bearing, so a sender that withholds them
468 /// ends the report rather than holding the application.
469 async fn emit(&mut self, slot: usize, offset: u64) {
470 if self.broken {
471 return;
472 }
473 let Some(entry) = self.pending[slot] else {
474 return;
475 };
476 let mut record = Vec::with_capacity(MAX_CURSOR_RECORD_LEN);
477 if let Err(e) = encode_cursor_record(entry.level, offset, &mut record) {
478 // An application level above the varint range. Refusing the
479 // record rather than the transfer keeps the rule that a cursor
480 // fails nothing.
481 tracing::debug!(error = %e, "a cursor level has no wire representation");
482 return;
483 }
484 let deadline = Duration::from_millis(self.conn.limits.header_timeout_ms);
485 if self.stream.is_none() {
486 match self.conn.exec.within(deadline, self.open()).await {
487 Some(Ok(stream)) => self.stream = Some(stream),
488 Some(Err(e)) => {
489 tracing::debug!(error = %e, "failed to open a cursor stream");
490 self.broken = true;
491 return;
492 }
493 None => {
494 tracing::debug!("the sender granted no cursor stream in time");
495 self.broken = true;
496 return;
497 }
498 }
499 }
500 let stream = self.stream.as_mut().expect("opened just above");
501 match self
502 .conn
503 .exec
504 .within(deadline, stream.write_all(&record))
505 .await
506 {
507 Some(Ok(())) => {}
508 Some(Err(e)) => {
509 tracing::debug!(error = %e, "failed to write a cursor record");
510 self.broken = true;
511 return;
512 }
513 None => {
514 // Part of the record may be queued: a reset, not a FIN, so
515 // the sender never reads a record cut short.
516 tracing::debug!("the sender took no cursor record in time");
517 stream.reset(codes::CANCELED);
518 self.stream = None;
519 self.broken = true;
520 return;
521 }
522 }
523 if let Some(entry) = self.pending[slot].as_mut() {
524 entry.emitted = Some(offset);
525 entry.at = Some(self.conn.exec.now());
526 }
527 }
528
529 async fn open(&self) -> Result<SendHalf, Error> {
530 let mut stream = self.conn.open_uni().await?;
531 let head = CursorHeader {
532 report_id: self.report_id,
533 }
534 .encode();
535 let mut frame = Vec::with_capacity(head.len() + 10);
536 encode_preamble(FrameKind::Cursor, head.len() as u64, &mut frame);
537 frame.extend_from_slice(&head);
538 stream.write_all(&frame).await?;
539 Ok(stream)
540 }
541}
542
543impl std::fmt::Debug for Reporter {
544 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
545 f.debug_struct("Reporter")
546 .field("report_id", &self.report_id)
547 .field("levels", &self.levels)
548 .field("mode", &self.mode)
549 .finish_non_exhaustive()
550 }
551}
552
553#[cfg(test)]
554mod tests {
555 use super::*;
556 use weida_protocol::header::Acknowledgement;
557
558 #[test]
559 fn a_set_keeps_the_maximum_offset_per_level() {
560 let mut set = CursorSet::default();
561 let stored = CursorLevel::Known(Acknowledgement::Stored);
562 assert!(set.advance(stored, 100));
563 // Backwards and repeated records are both no-ops, which is what makes
564 // coalescing free.
565 assert!(!set.advance(stored, 40));
566 assert!(!set.advance(stored, 100));
567 assert_eq!(set.offset(stored), Some(100));
568 assert_eq!(set.len(), 1);
569 }
570
571 #[test]
572 fn levels_are_ordered_by_their_wire_value() {
573 let mut set = CursorSet::default();
574 let app = CursorLevel::Application(17);
575 let accepted = CursorLevel::Known(Acknowledgement::Accepted);
576 assert!(set.advance(app, 1));
577 assert!(set.advance(accepted, 2));
578 assert_eq!(
579 set.iter().collect::<Vec<_>>(),
580 vec![(accepted, 2), (app, 1)]
581 );
582 }
583
584 #[test]
585 fn a_set_holds_exactly_the_cap() {
586 let mut set = CursorSet::default();
587 for i in 0..MAX_REPORT_LEVELS as u64 {
588 assert!(set.advance(
589 CursorLevel::Application(CursorLevel::APPLICATION_FLOOR + i),
590 i
591 ));
592 }
593 assert_eq!(set.len(), MAX_REPORT_LEVELS);
594 // One past the cap is dropped rather than overwriting a level: the
595 // decoder already refuses a header that orders this many.
596 assert!(!set.advance(CursorLevel::Known(Acknowledgement::Stored), 9));
597 assert_eq!(
598 set.offset(CursorLevel::Known(Acknowledgement::Stored)),
599 None
600 );
601 }
602}