weida 0.1.0-alpha.6

QUIC-native messaging framework: runtime, native QUIC transport, Req/Rep, Push/Pull, Pub/Sub, PAIR, SURVEY and BUS
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
//! Segments: the L0 unit a radio fans out and a dialling `Peer` sends
//! ([decisions/0037](../../../docs/decisions/0037-layered-segments.md) §4.2).
//!
//! A **segment** is a unit whose parts may depend on each other and on
//! nothing earlier — a voice frame, a raw preview frame, a video GOP. It is
//! numbered per `(sender, path, topic)` in DATA key `13`. The machinery here
//! is shared by [`crate::Radio::segment`], one copy per joined dish, and
//! [`crate::Peer::segment`], one copy toward the bound path the peer dialled.
//!
//! A segment carries **layers** `0..MAX_SEGMENT_LAYERS`, ordered by
//! dependency: layer *k* may depend on layers below it and never above
//! (§4.3). Each `(copy, layer)` is its own uni stream, opened on that layer's
//! first chunk, with its own writer task and queue of [`COPY_QUEUE`] chunks;
//! the byte budget is per copy. Every cut removes a suffix of the layers, so
//! what a receiver gets is a prefix a decoder can use:
//!
//! * **the cut rule** — a copy without room for a chunk of layer *k* first
//!   cuts its layers above *k*, whose queued bytes return to the budget at
//!   once; still without room, in the budget or in layer *k*'s queue, it cuts
//!   *k* and above. Layer 0 cut means the copy lost the segment;
//! * **supersession** — opening segment *n+1* resets at once every layer of
//!   segment *n* on that topic whose writer had not finished it, or whose
//!   queued chunks the transport does not take at once, and every layer
//!   above it; a finished layer gets the time its path needs,
//!   `rtt + 50 ms + rtt * bytes / cwnd`, and is reset only if still
//!   unacknowledged then. A copy that follows upstream
//!   ([`SegmentTerms::follows_upstream`]) is treated as finished until a
//!   write has to wait. No other topic's copies are touched;
//! * **expiry** — the smaller of the sender's and the receiver's `max_age`,
//!   on the sender's clock from the segment's open.
//!
//! Each copy counts at most once in `TopicDrops::layers_cut` and at most once
//! under a whole-segment cause. Nothing here ever waits for a receiver:
//! [`Segment::write_layer`] is synchronous.

use std::collections::HashMap;
use std::fmt;
use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
use std::time::{Duration, Instant};

use bytes::Bytes;
use tokio::sync::{Semaphore, mpsc, watch};
use weida_core::Error;
use weida_protocol::{DataHeader, codes};

use crate::conn::ConnHandle;
use crate::pubsub::{Causes, DropCause, DropTable};
use crate::transfer::write_data_preamble;
use crate::transport::SendHalf;

/// How many layers a stream segment can carry: `0..=15`, the cap of DATA
/// key `14`
/// ([decisions/0037](../../../docs/decisions/0037-layered-segments.md)
/// §4.3).
pub const MAX_SEGMENT_LAYERS: u8 = 16;

/// Chunks one copy's layer may hold queued for its writer task. The real
/// bound is the receiver's byte budget; this keeps the channel from growing
/// on tiny chunks.
pub(crate) const COPY_QUEUE: usize = 64;

/// What a finished copy waits beyond one round trip before a successor
/// supersedes it: quinn's default `max_ack_delay` of 25 ms (the transport
/// parameter default, quinn-proto `transport_parameters.rs`; weida's
/// `transport_config` in `tls.rs` keeps it) plus scheduling margin.
const SUPERSEDE_SLACK: Duration = Duration::from_millis(50);

/// How long a finished copy of `sent` bytes may still take to be
/// acknowledged on a path with smoothed round trip `rtt` and congestion
/// window `cwnd`: the time the window needs to carry every byte, one round
/// trip for the receipt and [`SUPERSEDE_SLACK`]. `sent` bounds what is still
/// unsent from above, so a copy whose bytes are already out gets more than
/// it needs, never less.
fn finish_grace(rtt: Duration, cwnd: u64, sent: u64) -> Duration {
    let carry = Duration::try_from_secs_f64(rtt.as_secs_f64() * sent as f64 / cwnd.max(1) as f64)
        .unwrap_or(Duration::MAX);
    rtt.saturating_add(SUPERSEDE_SLACK).saturating_add(carry)
}

/// The `quinn` priority of a copy's stream for `layer`: layer-major, so
/// every base layer on a connection goes before any enhancement layer, and
/// the application's `priority` orders topics within a layer
/// ([decisions/0037](../../../docs/decisions/0037-layered-segments.md)
/// §4.4).
fn copy_priority(layer: u8, priority: i16) -> i32 {
    (15 - i32::from(layer)) * 65_536 + i32::from(priority)
}

fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
    mutex.lock().unwrap_or_else(PoisonError::into_inner)
}

/// How a segment is sent: what the sender decides for every copy of it
/// ([decisions/0037](../../../docs/decisions/0037-layered-segments.md)
/// §4.2).
#[non_exhaustive]
#[derive(Clone, Debug, Default)]
pub struct SegmentTerms {
    /// The sender's latency budget: a copy still unfinished or
    /// unacknowledged this long after the segment opened is reset. At a
    /// radio the dish's own `max_age` applies too, and the smaller wins.
    pub max_age: Option<Duration>,
    /// Orders this segment's copies against other topics' copies of the
    /// same layer on one connection; higher goes first. Layer 0 of every
    /// topic still goes before any higher layer. A no-op on the local
    /// transports.
    pub priority: i16,
    /// The writer relays a segment its upstream is still streaming: the
    /// successor takes a copy's layer only where a write has to wait, and
    /// otherwise the layer keeps taking chunks and gets a finished layer's
    /// grace once it is finished
    /// ([decisions/0037](../../../docs/decisions/0037-layered-segments.md)
    /// §4.11). Dropping the segment unfinished still resets every
    /// unfinished layer.
    pub follows_upstream: bool,
}

impl SegmentTerms {
    /// Sets the sender's latency budget.
    #[must_use]
    pub fn with_max_age(mut self, max_age: Duration) -> Self {
        self.max_age = Some(max_age);
        self
    }

    /// Sets the priority among topics within a layer.
    #[must_use]
    pub fn with_priority(mut self, priority: i16) -> Self {
        self.priority = priority;
        self
    }

    /// Marks the segment as relayed from an upstream that may still be
    /// streaming its predecessor.
    #[must_use]
    pub fn with_follows_upstream(mut self, follows_upstream: bool) -> Self {
        self.follows_upstream = follows_upstream;
        self
    }
}

/// One copy's control, shared by the [`Segment`] and every layer task of
/// the copy: how its segment's successor, a cut or its end reach it.
pub(crate) struct CopyCtl {
    superseded: watch::Sender<bool>,
    /// The lowest cut layer; [`MAX_SEGMENT_LAYERS`] while nothing is cut.
    /// It only ever goes down.
    cut_from: watch::Sender<u8>,
    /// Bytes queued for this copy over all its layers: what the finish
    /// grace has to carry.
    total: AtomicU64,
    /// The segment's handle plus one per running layer task: a copy with
    /// none left has nothing a successor could supersede.
    handles: AtomicUsize,
    /// Supersession treats a layer as finished until a write has to wait
    /// ([`SegmentTerms::follows_upstream`]).
    follows_upstream: bool,
    /// The copy already counted in `layers_cut`.
    cut_counted: AtomicBool,
    /// The copy already counted under a whole-segment cause.
    lost_counted: AtomicBool,
}

impl CopyCtl {
    fn new(follows_upstream: bool) -> CopyCtl {
        CopyCtl {
            superseded: watch::Sender::new(false),
            cut_from: watch::Sender::new(MAX_SEGMENT_LAYERS),
            total: AtomicU64::new(0),
            handles: AtomicUsize::new(1),
            follows_upstream,
            cut_counted: AtomicBool::new(false),
            lost_counted: AtomicBool::new(false),
        }
    }

    fn supersede(&self) {
        self.superseded.send_replace(true);
    }

    fn live(&self) -> bool {
        self.handles.load(Ordering::Acquire) > 0
    }

    fn is_superseded(&self) -> bool {
        *self.superseded.borrow()
    }

    fn cut_now(&self) -> u8 {
        *self.cut_from.borrow()
    }

    /// Cuts layers `from` and above. Counted at most once per copy for a
    /// cut that starts above layer 0 (`layers_cut`) and at most once for the
    /// loss of layer 0 (under `cause`); `None` counts nothing, for a
    /// receiver that refused or left. A layer already cut stays as it was.
    fn cut(&self, from: u8, cause: Option<DropCause>, spec: &CopySpec) {
        let lowered = self.cut_from.send_if_modified(|cut| {
            if from < *cut {
                *cut = from;
                true
            } else {
                false
            }
        });
        if !lowered {
            return;
        }
        let Some(cause) = cause else {
            return;
        };
        if from == 0 {
            if !self.lost_counted.swap(true, Ordering::AcqRel) {
                spec.record(cause);
            }
        } else if !self.cut_counted.swap(true, Ordering::AcqRel) {
            spec.record(DropCause::LayersCut);
        }
    }
}

/// Per-topic segment numbering and the copies the next segment supersedes.
#[derive(Default)]
struct TopicState {
    next: u64,
    live: Vec<Arc<CopyCtl>>,
}

/// A sender's topics: the number each takes next, and the copies the next
/// segment on it supersedes. A radio holds one per path, a [`crate::Peer`]
/// one for its own copies.
pub(crate) struct SegmentTopics {
    /// Per-topic state, and the number a topic created after an eviction
    /// starts from.
    topics: Mutex<(HashMap<Arc<str>, TopicState>, u64)>,
    max_scopes: usize,
}

impl SegmentTopics {
    /// A table of at most `max_scopes` topics.
    pub(crate) fn new(max_scopes: usize) -> SegmentTopics {
        SegmentTopics {
            topics: Mutex::new((HashMap::new(), 0)),
            max_scopes,
        }
    }

    /// Takes the next number on `topic` and supersedes every copy of the
    /// previous segment there. Fails with [`Error::LimitExceeded`] when
    /// `max_scopes` topics all have a copy in flight.
    pub(crate) fn next(&self, topic: &Arc<str>) -> Result<u64, Error> {
        let mut guard = lock(&self.topics);
        let (topics, floor) = &mut *guard;
        if !topics.contains_key(topic) && topics.len() >= self.max_scopes {
            // The table is the application's, but still bounded: a topic
            // with no copy in flight has nothing to supersede and can go.
            let idle = topics.iter_mut().find_map(|(topic, state)| {
                state.live.retain(|c| c.live());
                state
                    .live
                    .is_empty()
                    .then(|| (Arc::clone(topic), state.next))
            });
            match idle {
                Some((idle, next)) => {
                    topics.remove(&idle);
                    // A topic that comes back must not restart below what a
                    // receiver already delivered on it, or the receiver would
                    // discard it as stale: numbering resumes above every
                    // number an evicted topic reached.
                    *floor = (*floor).max(next);
                }
                None => return Err(Error::LimitExceeded),
            }
        }
        let state = topics
            .entry(Arc::clone(topic))
            .or_insert_with(|| TopicState {
                next: *floor,
                live: Vec::new(),
            });
        let number = state.next;
        state.next += 1;
        for copy in state.live.drain(..) {
            copy.supersede();
        }
        Ok(number)
    }

    /// Supersedes the previous segment's copies on `topic` without using the
    /// number: the sender takes its numbers elsewhere
    /// ([`SegmentNumbers`]).
    pub(crate) fn supersede(&self, topic: &Arc<str>) -> Result<(), Error> {
        self.next(topic).map(drop)
    }

    fn track(&self, topic: &Arc<str>, copy: &Arc<CopyCtl>) {
        if let Some(state) = lock(&self.topics).0.get_mut(topic) {
            state.live.push(Arc::clone(copy));
        }
    }
}

/// The newest segment per path, per topic: its number and the layers of it
/// delivered, one bit each.
type PerPath = HashMap<Arc<str>, HashMap<Arc<str>, (u64, u16)>>;

/// The newest segment delivered per `(path, topic)` on one connection, with
/// the layers of it already delivered: what every receiver — a dish, an
/// acceptor, a transfer endpoint, a pair — checks an arriving segment
/// against
/// ([decisions/0037](../../../docs/decisions/0037-layered-segments.md)
/// §4.3, §4.11). A redial is a new connection and starts over.
pub(crate) struct Newest {
    /// Per path, per topic, the newest number and its layer mask; and the
    /// entries in total.
    table: Mutex<(PerPath, usize)>,
    max: usize,
}

impl Newest {
    /// A table of at most `max` `(path, topic)` entries.
    pub(crate) fn new(max: usize) -> Newest {
        Newest {
            table: Mutex::new((HashMap::new(), 0)),
            max,
        }
    }

    /// `true` when layer `layer` of `segment` is fresh on (`path`,
    /// `topic`): the segment is newer than the newest delivered there, or it
    /// is the newest and this layer of it was not delivered yet. A fresh
    /// arrival is recorded. At the table's cap an untracked key is always
    /// fresh: the check needs memory, and memory is bounded.
    pub(crate) fn fresh(&self, path: &str, topic: &str, segment: u64, layer: u8) -> bool {
        let bit = 1u16 << (layer % MAX_SEGMENT_LAYERS);
        let mut guard = lock(&self.table);
        let (paths, count) = &mut *guard;
        if let Some((last, mask)) = paths.get_mut(path).and_then(|t| t.get_mut(topic)) {
            if segment > *last {
                (*last, *mask) = (segment, bit);
                return true;
            }
            if segment == *last && *mask & bit == 0 {
                *mask |= bit;
                return true;
            }
            return false;
        }
        if *count < self.max {
            match paths.get_mut(path) {
                Some(topics) => {
                    topics.insert(Arc::from(topic), (segment, bit));
                }
                None => {
                    paths.insert(
                        Arc::from(path),
                        HashMap::from([(Arc::from(topic), (segment, bit))]),
                    );
                }
            }
            *count += 1;
        }
        true
    }
}

/// The next segment number per `(path, topic)`.
type NextNumbers = HashMap<(Arc<str>, Arc<str>), u64>;

/// The segment numbers per `(path, topic)` of one dialling connection: every
/// [`crate::Peer`] that sends segments over it shares one sequence, so the
/// receiver sees them only rise
/// ([decisions/0037](../../../docs/decisions/0037-layered-segments.md)
/// §4.11).
pub(crate) struct SegmentNumbers {
    /// The next number per `(path, topic)`, and the number a key created
    /// after an eviction starts from.
    table: Mutex<(NextNumbers, u64)>,
    max: usize,
}

impl SegmentNumbers {
    /// A table of at most `max` `(path, topic)` entries.
    pub(crate) fn new(max: usize) -> SegmentNumbers {
        SegmentNumbers {
            table: Mutex::new((HashMap::new(), 0)),
            max,
        }
    }

    /// Takes the next number on (`path`, `topic`). Never fails: at the cap
    /// it evicts an entry, and a key that comes back resumes above every
    /// number an evicted one reached, so a receiver never takes it as stale.
    pub(crate) fn next(&self, path: &Arc<str>, topic: &Arc<str>) -> u64 {
        let mut guard = lock(&self.table);
        let (table, floor) = &mut *guard;
        let key = (Arc::clone(path), Arc::clone(topic));
        if let Some(next) = table.get_mut(&key) {
            let number = *next;
            *next += 1;
            return number;
        }
        if table.len() >= self.max {
            let evicted = table.keys().next().cloned();
            if let Some(evicted) = evicted
                && let Some(next) = table.remove(&evicted)
            {
                *floor = (*floor).max(next);
            }
        }
        let number = *floor;
        if table.len() < self.max {
            table.insert(key, number + 1);
        } else {
            // A table of no entries at all: every segment takes the floor.
            *floor += 1;
        }
        number
    }
}

/// What a layer's writer task is told.
enum SegItem {
    Chunk(Bytes),
    Finish,
}

/// What every layer task of one copy shares: where it goes and what it is.
struct CopySpec {
    conn: ConnHandle,
    path: Arc<str>,
    topic: Arc<str>,
    number: u64,
    priority: i16,
    /// The smaller of the sender's and the receiver's `max_age`, from the
    /// segment's open.
    deadline: Option<Instant>,
    drops: Arc<DropTable>,
    /// The receiving dish's own record, for a radio copy
    /// ([decisions/0037](../../../docs/decisions/0037-layered-segments.md)
    /// §4.6); `None` for a `Peer::segment` copy.
    dish: Option<Arc<Causes>>,
}

impl CopySpec {
    fn expired(&self) -> bool {
        self.deadline.is_some_and(|d| Instant::now() >= d)
    }

    /// Counts one drop on the topic, and on the dish's record when there
    /// is one.
    fn record(&self, cause: DropCause) {
        self.drops.record(&self.topic, cause);
        if let Some(dish) = &self.dish {
            dish.record(cause);
        }
    }
}

/// The sending side of one layer of one copy.
struct LayerTx {
    tx: mpsc::Sender<SegItem>,
    /// Bytes queued and not yet written: what a Segment-side cut returns to
    /// the budget.
    queued: Arc<AtomicU64>,
    /// The writer finished this layer: every chunk of it is queued.
    finished: Arc<AtomicBool>,
}

/// The sending side of one copy, kept by the [`Segment`].
struct CopyTx {
    spec: Arc<CopySpec>,
    ctl: Arc<CopyCtl>,
    /// The highest layer the receiver wants.
    cap: u8,
    /// Chunk bytes this receiver's copies may hold unwritten.
    budget: Arc<Semaphore>,
    layers: [Option<LayerTx>; MAX_SEGMENT_LAYERS as usize],
}

impl CopyTx {
    /// Cuts layers `from` and above on the segment's side: the cut is
    /// recorded, and their queued bytes go back to the budget at once.
    fn cut(&mut self, from: u8, cause: DropCause) {
        self.ctl.cut(from, Some(cause), &self.spec);
        for slot in &mut self.layers[usize::from(from)..] {
            if let Some(layer) = slot.take() {
                let queued = layer.queued.swap(0, Ordering::AcqRel);
                self.budget
                    .add_permits(usize::try_from(queued).unwrap_or(usize::MAX));
            }
        }
    }

    /// Whether an uncut layer above `layer` is open, whose queued bytes a
    /// cut could free.
    fn upper_open(&self, layer: u8) -> bool {
        let cut = usize::from(self.ctl.cut_now());
        self.layers[usize::from(layer) + 1..cut.max(usize::from(layer) + 1)]
            .iter()
            .any(Option::is_some)
    }

    /// Opens layer `layer`: its writer task starts and opens its stream.
    fn open(&mut self, layer: u8) {
        let (tx, rx) = mpsc::channel(COPY_QUEUE);
        let queued = Arc::new(AtomicU64::new(0));
        let finished = Arc::new(AtomicBool::new(false));
        self.ctl.handles.fetch_add(1, Ordering::AcqRel);
        self.spec.conn.exec.spawn(layer_copy(
            Arc::clone(&self.spec),
            Arc::clone(&self.ctl),
            layer,
            rx,
            Arc::clone(&queued),
            Arc::clone(&finished),
            Arc::clone(&self.budget),
        ));
        self.layers[usize::from(layer)] = Some(LayerTx {
            tx,
            queued,
            finished,
        });
    }
}

impl Drop for CopyTx {
    fn drop(&mut self) {
        self.ctl.handles.fetch_sub(1, Ordering::AcqRel);
    }
}

/// Where one copy of a segment goes.
pub(crate) struct CopyTarget {
    pub(crate) conn: ConnHandle,
    pub(crate) path: Arc<str>,
    /// Chunk bytes this receiver's copies may hold unwritten.
    pub(crate) budget: Arc<Semaphore>,
    /// The receiver's own latency budget; `None` for a `Peer::segment` copy.
    pub(crate) max_age: Option<Duration>,
    /// The highest layer the receiver wants; `None` for every layer.
    pub(crate) max_layer: Option<u8>,
    /// The receiving dish's record; `None` for a `Peer::segment` copy.
    pub(crate) dish: Option<Arc<Causes>>,
}

/// Opens segment `number` on `topic` toward every target, under `terms`.
///
/// The caller took `number` and superseded the previous segment on `topics`
/// already; the copies are tracked there so the next segment supersedes
/// them. No stream opens here: each layer's opens on its first chunk.
pub(crate) fn open_segment(
    topics: &SegmentTopics,
    drops: &Arc<DropTable>,
    topic: Arc<str>,
    number: u64,
    terms: &SegmentTerms,
    targets: Vec<CopyTarget>,
) -> Segment {
    let opened = Instant::now();
    let mut copies = Vec::with_capacity(targets.len());
    for target in targets {
        let ctl = Arc::new(CopyCtl::new(terms.follows_upstream));
        topics.track(&topic, &ctl);
        // Expiry is the smaller of the sender's and the receiver's budget,
        // MOQT's "smaller non-zero value"
        // ([decisions/0037](../../../docs/decisions/0037-layered-segments.md)
        // §4.2).
        let max_age = match (terms.max_age, target.max_age) {
            (Some(a), Some(b)) => Some(a.min(b)),
            (a, b) => a.or(b),
        };
        copies.push(CopyTx {
            spec: Arc::new(CopySpec {
                conn: target.conn,
                path: target.path,
                topic: Arc::clone(&topic),
                number,
                priority: terms.priority,
                deadline: max_age.and_then(|age| opened.checked_add(age)),
                drops: Arc::clone(drops),
                dish: target.dish,
            }),
            ctl,
            cap: target.max_layer.unwrap_or(MAX_SEGMENT_LAYERS - 1),
            budget: target.budget,
            layers: Default::default(),
        });
    }
    Segment {
        number,
        topic,
        copies,
        finished: 0,
    }
}

/// One segment, open on every receiver it was opened toward.
///
/// [`Segment::write_layer`] never waits: a receiver without room for a chunk
/// loses that layer and every layer above it, counted, and loses the
/// segment if the layer is 0. Dropping a segment resets every layer not yet
/// finished, so no receiver mistakes a partial layer for a whole one.
pub struct Segment {
    number: u64,
    topic: Arc<str>,
    copies: Vec<CopyTx>,
    /// The layers [`Segment::finish_layer`] was called on, one bit each.
    finished: u16,
}

impl Segment {
    /// This segment's number on its topic.
    pub fn number(&self) -> u64 {
        self.number
    }

    /// The topic this segment belongs to.
    pub fn topic(&self) -> &str {
        &self.topic
    }

    /// Hands `chunk` to layer 0 of every copy still open; returns how many
    /// copies took it. See [`Segment::write_layer`].
    ///
    /// # Errors
    ///
    /// As [`Segment::write_layer`].
    pub fn write(&mut self, chunk: impl Into<Bytes>) -> Result<usize, Error> {
        self.write_layer(0, chunk)
    }

    /// Hands `chunk` to layer `layer` of every copy that wants it; returns
    /// how many copies took it.
    ///
    /// A copy whose receiver capped its layers below `layer` is skipped, and
    /// that is not a drop. A copy without room cuts by the cut rule: its
    /// layers above `layer` first, then `layer` and above
    /// ([decisions/0037](../../../docs/decisions/0037-layered-segments.md)
    /// §4.3). A layer opened after the successor segment opened, or after
    /// the deadline, is cut at once. Never waits.
    ///
    /// # Errors
    ///
    /// [`Error::LimitExceeded`] for a layer of 16 or above, or a chunk above
    /// 4 GiB, which no budget can account; [`Error::Runtime`] for a layer
    /// [`Segment::finish_layer`] already finished.
    pub fn write_layer(&mut self, layer: u8, chunk: impl Into<Bytes>) -> Result<usize, Error> {
        if layer >= MAX_SEGMENT_LAYERS {
            return Err(Error::LimitExceeded);
        }
        let chunk = chunk.into();
        let len = u32::try_from(chunk.len()).map_err(|_| Error::LimitExceeded)?;
        if self.finished & (1 << layer) != 0 {
            return Err(Error::Runtime(format!(
                "layer {layer} of segment {} is finished",
                self.number
            )));
        }
        let index = usize::from(layer);
        let mut took = 0;
        for copy in &mut self.copies {
            if layer > copy.cap || copy.ctl.cut_now() <= layer {
                continue;
            }
            if copy.layers[index].is_none() {
                if copy.ctl.is_superseded() && !copy.ctl.follows_upstream {
                    copy.cut(layer, DropCause::Superseded);
                    continue;
                }
                if copy.spec.expired() {
                    copy.cut(layer, DropCause::Expired);
                    continue;
                }
            }
            let permit = match Arc::clone(&copy.budget).try_acquire_many_owned(len) {
                Ok(permit) => permit,
                Err(_) => {
                    // The cut rule: the layers above give their room first.
                    if copy.upper_open(layer) {
                        copy.cut(layer + 1, DropCause::SubscriberBudget);
                    }
                    match Arc::clone(&copy.budget).try_acquire_many_owned(len) {
                        Ok(permit) => permit,
                        Err(_) => {
                            copy.cut(layer, DropCause::SubscriberBudget);
                            continue;
                        }
                    }
                }
            };
            if copy.layers[index].is_none() {
                copy.open(layer);
            }
            let Some(tx) = copy.layers[index].as_ref() else {
                continue;
            };
            match tx.tx.try_send(SegItem::Chunk(chunk.clone())) {
                Ok(()) => {
                    // Given back by the writer once the bytes are written,
                    // or by a cut that takes them first.
                    permit.forget();
                    tx.queued.fetch_add(u64::from(len), Ordering::AcqRel);
                    copy.ctl.total.fetch_add(u64::from(len), Ordering::AcqRel);
                    took += 1;
                }
                Err(mpsc::error::TrySendError::Full(_)) => {
                    drop(permit);
                    copy.cut(layer, DropCause::SubscriberQueue);
                }
                // The layer's task already ended and cut what it had to.
                Err(mpsc::error::TrySendError::Closed(_)) => {}
            }
        }
        self.copies.retain(|copy| copy.ctl.cut_now() > 0);
        Ok(took)
    }

    /// Ends layer `layer` on every copy that has it open and uncut; a layer
    /// of 16 or above is ignored. A later write to it is an error.
    pub fn finish_layer(&mut self, layer: u8) {
        if layer >= MAX_SEGMENT_LAYERS {
            return;
        }
        self.finished |= 1 << layer;
        let index = usize::from(layer);
        for copy in &mut self.copies {
            if copy.ctl.cut_now() <= layer {
                continue;
            }
            let Some(tx) = copy.layers[index].as_ref() else {
                continue;
            };
            match tx.tx.try_send(SegItem::Finish) {
                // Stored once the FIN is queued: a FIN that found the queue
                // full leaves the layer unfinished, and it is cut.
                Ok(()) => tx.finished.store(true, Ordering::Release),
                Err(mpsc::error::TrySendError::Full(_)) => {
                    copy.cut(layer, DropCause::SubscriberQueue);
                }
                Err(mpsc::error::TrySendError::Closed(_)) => {}
            }
        }
        self.copies.retain(|copy| copy.ctl.cut_now() > 0);
    }

    /// Ends every layer still open; returns how many copies still hold
    /// layer 0. A copy that holds no layer at all — nothing was written to
    /// it — gets an empty layer 0, so an empty segment arrives as an empty
    /// stream wherever this counts it.
    pub fn finish(mut self) -> usize {
        if self.finished & 1 == 0 {
            for copy in &mut self.copies {
                if copy.ctl.cut_now() == 0 || copy.layers.iter().any(Option::is_some) {
                    continue;
                }
                if copy.ctl.is_superseded() && !copy.ctl.follows_upstream {
                    copy.cut(0, DropCause::Superseded);
                } else if copy.spec.expired() {
                    copy.cut(0, DropCause::Expired);
                } else {
                    copy.open(0);
                }
            }
            self.copies.retain(|copy| copy.ctl.cut_now() > 0);
        }
        let opened = self.copies.iter().fold(0u16, |mask, copy| {
            copy.layers
                .iter()
                .enumerate()
                .filter(|(_, slot)| slot.is_some())
                .fold(mask, |mask, (layer, _)| mask | (1 << layer))
        });
        for layer in 0..MAX_SEGMENT_LAYERS {
            if opened & (1 << layer) != 0 && self.finished & (1 << layer) == 0 {
                self.finish_layer(layer);
            }
        }
        self.copies.len()
    }
}

impl fmt::Debug for Segment {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Segment")
            .field("topic", &self.topic)
            .field("number", &self.number)
            .field("copies", &self.copies.len())
            .finish()
    }
}

/// Returns `len` bytes of a layer's queue to the budget, at most what is
/// still counted as queued: a Segment-side cut may have returned them
/// already, and a byte goes back exactly once.
fn release(queued: &AtomicU64, len: usize, budget: &Semaphore) {
    let len = u64::try_from(len).unwrap_or(u64::MAX);
    let mut before = queued.load(Ordering::Acquire);
    while let Err(seen) = queued.compare_exchange_weak(
        before,
        before.saturating_sub(len),
        Ordering::AcqRel,
        Ordering::Acquire,
    ) {
        before = seen;
    }
    let returned = before.min(len);
    if returned > 0 {
        budget.add_permits(usize::try_from(returned).unwrap_or(usize::MAX));
    }
}

/// Resolves once layer `layer` or one below it is cut.
async fn cut_reached(ctl: &CopyCtl, layer: u8) {
    let mut cut = ctl.cut_from.subscribe();
    let _ = cut.wait_for(|cut| *cut <= layer).await;
}

/// Resolves once the copy's segment is superseded.
async fn superseded(ctl: &CopyCtl) {
    let mut superseded = ctl.superseded.subscribe();
    let _ = superseded.wait_for(|s| *s).await;
}

/// Resolves when the copy is superseded while this layer's writer is still
/// writing it: such a layer is reset at once. A layer finished before the
/// successor opened, and a copy that follows upstream, go on: see
/// [`run_layer`].
async fn superseded_unfinished(ctl: &CopyCtl, finished: &AtomicBool) {
    superseded(ctl).await;
    if ctl.follows_upstream || finished.load(Ordering::Acquire) {
        std::future::pending::<()>().await;
    }
}

/// Resolves at the copy's deadline, or never.
async fn expiry(spec: &CopySpec) {
    match spec.deadline {
        Some(deadline) => {
            spec.conn
                .exec
                .sleep(deadline.saturating_duration_since(Instant::now()))
                .await;
        }
        None => std::future::pending().await,
    }
}

/// Resolves when a layer past its FIN has had its grace after supersession:
/// the time its path needs to carry the copy's bytes at the congestion
/// window, one round trip for the receipt and [`SUPERSEDE_SLACK`].
async fn finish_grace_over(ctl: &CopyCtl, spec: &CopySpec) {
    superseded(ctl).await;
    let wait = spec
        .conn
        .conn
        .transport_stats()
        .map(|t| t.path)
        .map_or(Duration::ZERO, |p| {
            finish_grace(p.rtt, p.cwnd, ctl.total.load(Ordering::Acquire))
        });
    spec.conn.exec.sleep(wait).await;
}

/// Writes one layer of one copy, racing every step against cuts,
/// supersession and the deadline; on exit, the chunks never written go back
/// to the budget.
async fn layer_copy(
    spec: Arc<CopySpec>,
    ctl: Arc<CopyCtl>,
    layer: u8,
    mut rx: mpsc::Receiver<SegItem>,
    queued: Arc<AtomicU64>,
    finished: Arc<AtomicBool>,
    budget: Arc<Semaphore>,
) {
    run_layer(&spec, &ctl, layer, &mut rx, &queued, &finished, &budget).await;
    rx.close();
    while let Ok(item) = rx.try_recv() {
        if let SegItem::Chunk(chunk) = item {
            release(&queued, chunk.len(), &budget);
        }
    }
    ctl.handles.fetch_sub(1, Ordering::AcqRel);
}

/// Opens and writes one layer. Supersession takes a layer the writer had not
/// finished at once. A layer the writer finished first, or of a copy that
/// follows upstream, is not stalled merely because its successor opened: it
/// hands its chunks to the transport if the transport takes them at once —
/// a write the receiver's flow control holds back means a stalled receiver,
/// and the layer is reset — and once its FIN is written it gets
/// [`finish_grace_over`] before the reset. Every reset cuts the layers
/// above too.
async fn run_layer(
    spec: &CopySpec,
    ctl: &CopyCtl,
    layer: u8,
    rx: &mut mpsc::Receiver<SegItem>,
    queued: &AtomicU64,
    finished: &AtomicBool,
    budget: &Semaphore,
) {
    let opened = tokio::select! {
        biased;
        () = cut_reached(ctl, layer) => return,
        () = superseded_unfinished(ctl, finished) => {
            ctl.cut(layer, Some(DropCause::Superseded), spec);
            return;
        }
        () = expiry(spec) => {
            ctl.cut(layer, Some(DropCause::Expired), spec);
            return;
        }
        opened = open_layer(spec, layer) => opened,
    };
    let mut stream = match opened {
        Ok(stream) => stream,
        Err(Error::NoParkedConnection) => {
            ctl.cut(layer, Some(DropCause::NoParkedConnection), spec);
            return;
        }
        Err(e) => {
            tracing::debug!(error = %e, layer, "a segment layer could not be opened");
            ctl.cut(layer, None, spec);
            return;
        }
    };
    loop {
        let item = tokio::select! {
            biased;
            () = cut_reached(ctl, layer) => {
                stream.reset(codes::CANCELED);
                return;
            }
            () = superseded_unfinished(ctl, finished) => {
                stream.reset(codes::CANCELED);
                ctl.cut(layer, Some(DropCause::Superseded), spec);
                return;
            }
            () = expiry(spec) => {
                stream.reset(codes::CANCELED);
                ctl.cut(layer, Some(DropCause::Expired), spec);
                return;
            }
            item = rx.recv() => item,
        };
        match item {
            Some(SegItem::Chunk(chunk)) => {
                // The write first: supersession only takes a write that has
                // to wait.
                let written = tokio::select! {
                    biased;
                    written = stream.write_all(&chunk) => Ok(written),
                    () = cut_reached(ctl, layer) => Err(None),
                    () = superseded(ctl) => Err(Some(DropCause::Superseded)),
                    () = expiry(spec) => Err(Some(DropCause::Expired)),
                };
                release(queued, chunk.len(), budget);
                match written {
                    Ok(Ok(())) => {}
                    // The receiver refused the stream or went away.
                    Ok(Err(_)) => {
                        ctl.cut(layer, None, spec);
                        return;
                    }
                    Err(cause) => {
                        stream.reset(codes::CANCELED);
                        if let Some(cause) = cause {
                            ctl.cut(layer, Some(cause), spec);
                        }
                        return;
                    }
                }
            }
            Some(SegItem::Finish) => {
                if stream.finish().is_err() {
                    ctl.cut(layer, None, spec);
                    return;
                }
                // Until the receiver's transport holds every byte, the layer
                // can still be cut, superseded or expire: a reset is
                // accepted after FIN until then.
                tokio::select! {
                    biased;
                    () = cut_reached(ctl, layer) => stream.reset(codes::CANCELED),
                    () = expiry(spec) => {
                        stream.reset(codes::CANCELED);
                        ctl.cut(layer, Some(DropCause::Expired), spec);
                    }
                    _ = stream.stopped() => {}
                    () = finish_grace_over(ctl, spec) => {
                        stream.reset(codes::CANCELED);
                        ctl.cut(layer, Some(DropCause::Superseded), spec);
                    }
                }
                return;
            }
            // The segment was dropped without finishing this layer.
            None => {
                stream.reset(codes::CANCELED);
                return;
            }
        }
    }
}

/// Opens one layer's stream: the DATA header names the path, the topic, the
/// segment number and, above layer 0, the layer (key `14`); the stream gets
/// its layer-major priority before any byte is queued, the only time
/// `quinn` guarantees it takes effect.
async fn open_layer(spec: &CopySpec, layer: u8) -> Result<SendHalf, Error> {
    let header = DataHeader {
        topic: Some(spec.topic.to_string()),
        segment: Some(spec.number),
        layer: (layer > 0).then_some(layer),
        ..DataHeader::addressed(spec.path.as_ref())
    };
    let mut stream = spec.conn.open_uni().await?;
    stream.set_priority(copy_priority(layer, spec.priority));
    write_data_preamble(&mut stream, &header).await?;
    Ok(stream)
}