rings-core 0.20.0

Chord DHT implementation with ICE
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
use std::sync::Arc;
use std::sync::Mutex;
#[cfg(test)]
use std::task::Poll;

use super::model::TransferClass;
use crate::dht::Did;
use crate::error::Error;
use crate::error::Result;
use crate::fair_admission::acquire_fair;
use crate::fair_admission::admissible_capacity;
use crate::fair_admission::retained_wire_bytes;
use crate::fair_admission::CountedReservationRejection;
use crate::fair_admission::CountedReservedCapacity;
use crate::fair_admission::FairWaitBudget;
use crate::fair_admission::FairWaitQueue;
use crate::fair_admission::ReservedCapacity;

/// Hard per-peer transfer bound, including queued and delivery-waiting heads.
pub(crate) const OUTBOUND_TRANSFER_QUEUE_CAPACITY: usize = 256;
/// Slots unavailable to non-control transfers, so topology traffic can always enter the scheduler.
pub(crate) const OUTBOUND_CONTROL_RESERVED_TRANSFERS: usize = 16;
pub(super) const OUTBOUND_DATA_RESERVED_TRANSFERS: usize = 8;
/// Per-class minimum transfer reservations preserved under shared-capacity borrowing.
const OUTBOUND_TRANSFER_RESERVATIONS: [usize; TransferClass::COUNT] = [
    OUTBOUND_CONTROL_RESERVED_TRANSFERS,
    OUTBOUND_DATA_RESERVED_TRANSFERS,
    OUTBOUND_DATA_RESERVED_TRANSFERS,
    OUTBOUND_DATA_RESERVED_TRANSFERS,
];
#[cfg(test)]
pub(crate) const OUTBOUND_DATA_TRANSFER_CAPACITY: usize = admissible_capacity(
    OUTBOUND_TRANSFER_QUEUE_CAPACITY,
    &OUTBOUND_TRANSFER_RESERVATIONS,
    TransferClass::Application.index(),
);

/// Weighted outbound memory allowed for one peer.
///
/// Preparation charges twice the exact wire size, covering the owned payload
/// plus either its decoded message body or serialized wire copy. This capacity
/// therefore admits one maximum-sized payload while bounding retained queues to
/// roughly 64 MiB of wire data.
pub(super) const OUTBOUND_PEER_BYTE_CAPACITY: usize = 128 * 1024 * 1024;
/// Per-peer bytes unavailable to non-control traffic.
pub(super) const OUTBOUND_PEER_CONTROL_RESERVED_BYTES: usize = 1024 * 1024;
pub(super) const OUTBOUND_PEER_DATA_RESERVED_BYTES: usize = 1024 * 1024;
const OUTBOUND_PEER_BYTE_RESERVATIONS: [usize; TransferClass::COUNT] = [
    retained_wire_bytes(OUTBOUND_PEER_CONTROL_RESERVED_BYTES),
    OUTBOUND_PEER_DATA_RESERVED_BYTES,
    OUTBOUND_PEER_DATA_RESERVED_BYTES,
    OUTBOUND_PEER_DATA_RESERVED_BYTES,
];

fn fixed_request_bytes(
    reservations: &[usize; TransferClass::COUNT],
    class: TransferClass,
) -> usize {
    reservations.get(class.index()).copied().unwrap_or(0)
}

/// Native-wide retained outbound bytes across all peers.
#[cfg(not(all(feature = "wasm", target_family = "wasm")))]
pub(crate) const OUTBOUND_GLOBAL_BYTE_CAPACITY: usize = 256 * 1024 * 1024;
/// Browser-wide retained outbound bytes across all peers.
#[cfg(all(feature = "wasm", target_family = "wasm"))]
pub(crate) const OUTBOUND_GLOBAL_BYTE_CAPACITY: usize = 128 * 1024 * 1024;
/// Global bytes unavailable to non-control traffic.
const OUTBOUND_GLOBAL_CONTROL_RESERVED_BYTES: usize = 2 * 1024 * 1024;
const OUTBOUND_GLOBAL_DATA_RESERVED_BYTES: usize = 1024 * 1024;
const OUTBOUND_PENDING_TRANSFER_CAPACITY: usize = OUTBOUND_TRANSFER_QUEUE_CAPACITY;
const OUTBOUND_GLOBAL_BYTE_RESERVATIONS: [usize; TransferClass::COUNT] = [
    OUTBOUND_GLOBAL_CONTROL_RESERVED_BYTES,
    OUTBOUND_GLOBAL_DATA_RESERVED_BYTES,
    OUTBOUND_GLOBAL_DATA_RESERVED_BYTES,
    OUTBOUND_GLOBAL_DATA_RESERVED_BYTES,
];
const NO_RESERVATIONS: [usize; TransferClass::COUNT] = [0; TransferClass::COUNT];

fn class_reservations_enabled() -> bool {
    #[cfg(all(test, feature = "dummy", not(target_family = "wasm")))]
    {
        crate::simulation::protection_profile().class_reservations()
    }
    #[cfg(not(all(test, feature = "dummy", not(target_family = "wasm"))))]
    {
        true
    }
}

fn active_reservations(
    reservations: &'static [usize; TransferClass::COUNT],
) -> &'static [usize; TransferClass::COUNT] {
    if class_reservations_enabled() {
        reservations
    } else {
        &NO_RESERVATIONS
    }
}

fn transfer_reservations() -> &'static [usize; TransferClass::COUNT] {
    active_reservations(&OUTBOUND_TRANSFER_RESERVATIONS)
}

fn peer_byte_reservations() -> &'static [usize; TransferClass::COUNT] {
    active_reservations(&OUTBOUND_PEER_BYTE_RESERVATIONS)
}

fn global_byte_reservations() -> &'static [usize; TransferClass::COUNT] {
    active_reservations(&OUTBOUND_GLOBAL_BYTE_RESERVATIONS)
}

#[derive(Clone, Copy, Eq, PartialEq)]
enum CapacityScope {
    FixedReservation,
    Shared,
}

async fn acquire_with_fixed_reservation<T>(
    waiters: &Arc<FairWaitQueue>,
    bytes: usize,
    fixed_request_limit: usize,
    capacity_error: impl Fn() -> Error,
    try_reserved: impl FnOnce() -> Result<T>,
    mut try_shared: impl FnMut() -> Result<T>,
) -> Result<T> {
    if let Ok(permit) = try_reserved() {
        return Ok(permit);
    }
    if bytes <= fixed_request_limit {
        return waiters.try_admit_unqueued(capacity_error(), try_shared);
    }
    acquire_fair(
        waiters,
        bytes,
        capacity_error(),
        || Error::ChannelSendMessageFailed,
        || try_shared().ok(),
    )
    .await
}

pub(super) struct GlobalTransferCapacity {
    state: Mutex<ReservedCapacity<{ TransferClass::COUNT }>>,
    waiters: Arc<FairWaitQueue>,
    wait_budget: Arc<FairWaitBudget>,
}

impl GlobalTransferCapacity {
    pub(super) fn new() -> Self {
        let wait_budget = Arc::new(FairWaitBudget::new(
            OUTBOUND_PENDING_TRANSFER_CAPACITY,
            OUTBOUND_GLOBAL_BYTE_CAPACITY,
        ));
        Self {
            state: Mutex::new(ReservedCapacity::new()),
            waiters: Arc::new(FairWaitQueue::with_budget(wait_budget.clone())),
            wait_budget,
        }
    }

    fn try_acquire_inner(
        self: &Arc<Self>,
        peer: Did,
        class: TransferClass,
        bytes: usize,
        scope: CapacityScope,
    ) -> Result<GlobalCapacityPermit> {
        let mut state = self
            .state
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        let mut next = *state;
        let reservations = global_byte_reservations();
        if scope == CapacityScope::FixedReservation
            && !next.reservation_covers(class.index(), bytes, reservations)
        {
            return Err(memory_capacity_error(peer, bytes, global_byte_limit(class)));
        }
        if !next.try_reserve(
            class.index(),
            bytes,
            OUTBOUND_GLOBAL_BYTE_CAPACITY,
            reservations,
        ) {
            return Err(memory_capacity_error(peer, bytes, global_byte_limit(class)));
        }
        #[cfg(all(test, feature = "dummy", not(target_family = "wasm")))]
        crate::simulation::observe_outbound_global_capacity(
            next.admitted(),
            OUTBOUND_GLOBAL_BYTE_CAPACITY,
        );
        *state = next;
        Ok(GlobalCapacityPermit {
            capacity: self.clone(),
            class,
            bytes,
        })
    }

    async fn acquire(
        self: &Arc<Self>,
        peer: Did,
        class: TransferClass,
        bytes: usize,
    ) -> Result<GlobalCapacityPermit> {
        acquire_with_fixed_reservation(
            &self.waiters,
            bytes,
            fixed_request_bytes(global_byte_reservations(), class),
            || memory_capacity_error(peer, bytes, global_byte_limit(class)),
            || self.try_acquire_inner(peer, class, bytes, CapacityScope::FixedReservation),
            || self.try_acquire_inner(peer, class, bytes, CapacityScope::Shared),
        )
        .await
    }
}

#[derive(Clone, Copy)]
struct PeerCapacityState {
    capacity: CountedReservedCapacity<{ TransferClass::COUNT }>,
}

impl PeerCapacityState {
    const fn new() -> Self {
        Self {
            capacity: CountedReservedCapacity::new(),
        }
    }

    fn reservation_covers(&self, class: TransferClass, bytes: usize) -> bool {
        self.capacity.reservation_covers(
            class.index(),
            bytes,
            transfer_reservations(),
            peer_byte_reservations(),
        )
    }

    fn try_reserve(
        &mut self,
        class: TransferClass,
        bytes: usize,
    ) -> std::result::Result<(), CountedReservationRejection> {
        self.capacity.try_reserve(
            class.index(),
            bytes,
            OUTBOUND_TRANSFER_QUEUE_CAPACITY,
            transfer_reservations(),
            OUTBOUND_PEER_BYTE_CAPACITY,
            peer_byte_reservations(),
        )
    }

    fn release(&mut self, class: TransferClass, bytes: usize) {
        self.capacity.release(class.index(), bytes);
    }
}

pub(super) struct TransferCapacity {
    state: Mutex<PeerCapacityState>,
    global: Arc<GlobalTransferCapacity>,
    waiters: Arc<FairWaitQueue>,
}

impl TransferCapacity {
    pub(super) fn new(global: Arc<GlobalTransferCapacity>) -> Self {
        let wait_budget = global.wait_budget.clone();
        Self {
            state: Mutex::new(PeerCapacityState::new()),
            global,
            waiters: Arc::new(FairWaitQueue::with_budget(wait_budget)),
        }
    }

    fn try_acquire_peer_inner(
        self: &Arc<Self>,
        peer: Did,
        class: TransferClass,
        bytes: usize,
        scope: CapacityScope,
    ) -> Result<PeerCapacityPermit> {
        let mut state = self
            .state
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        let mut next = *state;
        if scope == CapacityScope::FixedReservation && !next.reservation_covers(class, bytes) {
            return Err(memory_capacity_error(peer, bytes, peer_byte_limit(class)));
        }
        match next.try_reserve(class, bytes) {
            Ok(()) => {}
            Err(CountedReservationRejection::Count) => {
                return Err(Error::OutboundTransferCapacityExceeded {
                    peer,
                    capacity: transfer_limit(class),
                });
            }
            Err(CountedReservationRejection::Bytes) => {
                return Err(memory_capacity_error(peer, bytes, peer_byte_limit(class)));
            }
        }
        #[cfg(all(test, feature = "dummy", not(target_family = "wasm")))]
        crate::simulation::observe_outbound_peer_capacity(
            next.capacity.admitted_count(),
            OUTBOUND_TRANSFER_QUEUE_CAPACITY,
            next.capacity.admitted_bytes(),
            OUTBOUND_PEER_BYTE_CAPACITY,
        );
        *state = next;
        Ok(PeerCapacityPermit {
            capacity: self.clone(),
            class,
            bytes,
        })
    }

    async fn acquire_peer(
        self: &Arc<Self>,
        peer: Did,
        class: TransferClass,
        bytes: usize,
    ) -> Result<PeerCapacityPermit> {
        acquire_with_fixed_reservation(
            &self.waiters,
            bytes,
            fixed_request_bytes(peer_byte_reservations(), class),
            || memory_capacity_error(peer, bytes, peer_byte_limit(class)),
            || self.try_acquire_peer_inner(peer, class, bytes, CapacityScope::FixedReservation),
            || self.try_acquire_peer_inner(peer, class, bytes, CapacityScope::Shared),
        )
        .await
    }

    #[cfg(test)]
    pub(super) fn try_acquire(
        self: &Arc<Self>,
        peer: Did,
        class: TransferClass,
        bytes: usize,
    ) -> Result<TransferCapacityPermit> {
        validate_memory_request(peer, class, bytes)?;
        let bytes = bytes.max(1);
        let peer_permit = self.try_acquire_peer_inner(peer, class, bytes, CapacityScope::Shared)?;
        let global_permit =
            self.global
                .try_acquire_inner(peer, class, bytes, CapacityScope::Shared)?;
        Ok(TransferCapacityPermit {
            _peer: peer_permit,
            _global: global_permit,
        })
    }

    pub(super) async fn acquire(
        self: &Arc<Self>,
        peer: Did,
        class: TransferClass,
        bytes: usize,
    ) -> Result<TransferCapacityPermit> {
        validate_memory_request(peer, class, bytes)?;
        let bytes = bytes.max(1);
        let peer_permit = self.acquire_peer(peer, class, bytes).await?;
        let global_permit = self.global.acquire(peer, class, bytes).await?;
        Ok(TransferCapacityPermit {
            _peer: peer_permit,
            _global: global_permit,
        })
    }

    #[cfg(all(test, not(target_family = "wasm")))]
    pub(super) fn admitted(&self) -> usize {
        self.state
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .capacity
            .admitted_count()
    }

    #[cfg(test)]
    pub(super) fn admitted_bytes(&self) -> usize {
        self.state
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .capacity
            .admitted_bytes()
    }
}

pub(in crate::swarm::transport) struct TransferCapacityPermit {
    _peer: PeerCapacityPermit,
    _global: GlobalCapacityPermit,
}

struct PeerCapacityPermit {
    capacity: Arc<TransferCapacity>,
    class: TransferClass,
    bytes: usize,
}

impl Drop for PeerCapacityPermit {
    fn drop(&mut self) {
        self.capacity
            .state
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .release(self.class, self.bytes);
        self.capacity.waiters.wake_front();
    }
}

struct GlobalCapacityPermit {
    capacity: Arc<GlobalTransferCapacity>,
    class: TransferClass,
    bytes: usize,
}

impl Drop for GlobalCapacityPermit {
    fn drop(&mut self) {
        self.capacity
            .state
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .release(self.class.index(), self.bytes);
        self.capacity.waiters.wake_front();
    }
}

pub(super) fn transfer_limit(class: TransferClass) -> usize {
    admissible_capacity(
        OUTBOUND_TRANSFER_QUEUE_CAPACITY,
        transfer_reservations(),
        class.index(),
    )
}

const fn production_transfer_limit(class: TransferClass) -> usize {
    admissible_capacity(
        OUTBOUND_TRANSFER_QUEUE_CAPACITY,
        &OUTBOUND_TRANSFER_RESERVATIONS,
        class.index(),
    )
}

pub(super) fn peer_byte_limit(class: TransferClass) -> usize {
    admissible_capacity(
        OUTBOUND_PEER_BYTE_CAPACITY,
        peer_byte_reservations(),
        class.index(),
    )
}

const fn production_peer_byte_limit(class: TransferClass) -> usize {
    admissible_capacity(
        OUTBOUND_PEER_BYTE_CAPACITY,
        &OUTBOUND_PEER_BYTE_RESERVATIONS,
        class.index(),
    )
}

fn global_byte_limit(class: TransferClass) -> usize {
    admissible_capacity(
        OUTBOUND_GLOBAL_BYTE_CAPACITY,
        global_byte_reservations(),
        class.index(),
    )
}

const fn production_global_byte_limit(class: TransferClass) -> usize {
    admissible_capacity(
        OUTBOUND_GLOBAL_BYTE_CAPACITY,
        &OUTBOUND_GLOBAL_BYTE_RESERVATIONS,
        class.index(),
    )
}

const _: () = {
    let maximum_payload_reservation = retained_wire_bytes(crate::consts::TRANSPORT_MAX_SIZE);
    assert_production_capacity(TransferClass::DhtControl, maximum_payload_reservation);
    assert_production_capacity(TransferClass::Storage, maximum_payload_reservation);
    assert_production_capacity(TransferClass::E2e, maximum_payload_reservation);
    assert_production_capacity(TransferClass::Application, maximum_payload_reservation);
};

const fn assert_production_capacity(class: TransferClass, maximum_payload_reservation: usize) {
    assert!(production_transfer_limit(class) > 0);
    assert!(maximum_payload_reservation <= production_peer_byte_limit(class));
    assert!(maximum_payload_reservation <= production_global_byte_limit(class));
}

fn memory_capacity_error(peer: Did, requested_bytes: usize, capacity_bytes: usize) -> Error {
    Error::OutboundTransferMemoryCapacityExceeded {
        peer,
        requested_bytes,
        capacity_bytes,
    }
}

fn validate_memory_request(peer: Did, class: TransferClass, requested_bytes: usize) -> Result<()> {
    let requested_bytes = requested_bytes.max(1);
    let limit = peer_byte_limit(class).min(global_byte_limit(class));
    if requested_bytes > limit {
        return Err(memory_capacity_error(peer, requested_bytes, limit));
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_reserved_capacity_bound_holds_for_all_short_reserve_release_traces() {
        const CAPACITY: usize = 5;
        const RESERVATIONS: [usize; TransferClass::COUNT] = [2, 1, 1, 1];
        const ACTIONS: usize = TransferClass::COUNT * 2;
        const TRACE_LENGTH: u32 = 6;
        let trace_count = ACTIONS.pow(TRACE_LENGTH);

        for encoded in 0..trace_count {
            let mut code = encoded;
            let mut capacity = ReservedCapacity::<{ TransferClass::COUNT }>::new();
            let mut admitted_by_class = [0usize; TransferClass::COUNT];
            for _ in 0..TRACE_LENGTH {
                let action = code % ACTIONS;
                code /= ACTIONS;
                let class_index = action % TransferClass::COUNT;
                if action < TransferClass::COUNT {
                    if capacity.try_reserve(class_index, 1, CAPACITY, &RESERVATIONS) {
                        admitted_by_class[class_index] =
                            admitted_by_class[class_index].saturating_add(1);
                    }
                } else if admitted_by_class[class_index] > 0 {
                    capacity.release(class_index, 1);
                    admitted_by_class[class_index] =
                        admitted_by_class[class_index].saturating_sub(1);
                }
                assert_eq!(capacity.admitted(), admitted_by_class.iter().sum::<usize>());
                assert!(capacity.admitted() <= CAPACITY);
            }
        }
    }

    #[cfg(all(feature = "dummy", not(target_family = "wasm")))]
    #[test]
    fn test_class_reservation_ablation_changes_real_admission_limits() {
        assert!(transfer_limit(TransferClass::Application) < OUTBOUND_TRANSFER_QUEUE_CAPACITY);
        assert!(peer_byte_limit(TransferClass::Application) < OUTBOUND_PEER_BYTE_CAPACITY);

        let _runtime = crate::simulation::SimulationRuntimeGuard::enter(
            42,
            1_700_000_000_000,
            crate::simulation::ProtectionProfile::without_class_reservations(),
        )
        .expect("simulation runtime must install");
        assert_eq!(
            transfer_limit(TransferClass::Application),
            OUTBOUND_TRANSFER_QUEUE_CAPACITY
        );
        assert_eq!(
            peer_byte_limit(TransferClass::Application),
            OUTBOUND_PEER_BYTE_CAPACITY
        );
    }

    #[cfg_attr(
        all(feature = "wasm", target_family = "wasm"),
        wasm_bindgen_test::wasm_bindgen_test
    )]
    #[cfg_attr(not(all(feature = "wasm", target_family = "wasm")), tokio::test)]
    async fn test_reserved_outbound_request_bypasses_borrower_waiter() {
        let global = Arc::new(GlobalTransferCapacity::new());
        let capacity = Arc::new(TransferCapacity::new(global.clone()));
        let unrelated_capacity = Arc::new(TransferCapacity::new(global));
        let peer = Did::from(90_u32);
        let unrelated_peer = Did::from(91_u32);
        let blocker = capacity
            .try_acquire(peer, TransferClass::Application, 100 * 1024 * 1024)
            .expect("blocker must fit");
        let mut large = Box::pin(capacity.acquire(peer, TransferClass::Storage, 120 * 1024 * 1024));
        let mut unrelated = Box::pin(unrelated_capacity.acquire(
            unrelated_peer,
            TransferClass::Application,
            2 * 1024 * 1024,
        ));

        assert!(matches!(futures::poll!(large.as_mut()), Poll::Pending));
        let reserved = futures::future::join_all(
            (0..OUTBOUND_CONTROL_RESERVED_TRANSFERS)
                .map(|_| capacity.acquire(peer, TransferClass::DhtControl, 1)),
        )
        .await
        .into_iter()
        .collect::<Result<Vec<_>>>()
        .expect("control requests within their reservation must bypass");
        let mut later = Box::pin(capacity.acquire(peer, TransferClass::DhtControl, 1));
        assert!(matches!(
            futures::poll!(later.as_mut()),
            Poll::Ready(Err(_))
        ));
        assert!(matches!(
            futures::poll!(unrelated.as_mut()),
            Poll::Ready(Ok(_))
        ));
        drop(blocker);
        assert!(matches!(futures::poll!(large.as_mut()), Poll::Ready(Ok(_))));
        drop(reserved);
    }

    #[cfg_attr(
        all(feature = "wasm", target_family = "wasm"),
        wasm_bindgen_test::wasm_bindgen_test
    )]
    #[cfg_attr(not(all(feature = "wasm", target_family = "wasm")), tokio::test)]
    async fn test_global_borrowers_are_fifo_while_reserved_control_bypasses() {
        const BLOCKER_BYTES: usize = (OUTBOUND_GLOBAL_BYTE_CAPACITY - 16 * 1024 * 1024) / 2;
        let global = Arc::new(GlobalTransferCapacity::new());
        let first = Arc::new(TransferCapacity::new(global.clone()));
        let second = Arc::new(TransferCapacity::new(global.clone()));
        let waiting = Arc::new(TransferCapacity::new(global.clone()));
        let later = Arc::new(TransferCapacity::new(global.clone()));
        let control = Arc::new(TransferCapacity::new(global));
        let first_blocker = first
            .try_acquire(
                Did::from(101_u32),
                TransferClass::Application,
                BLOCKER_BYTES,
            )
            .expect("first global blocker must fit");
        let _second_blocker = second
            .try_acquire(
                Did::from(102_u32),
                TransferClass::Application,
                BLOCKER_BYTES,
            )
            .expect("second global blocker must fit");
        let mut front =
            Box::pin(waiting.acquire(Did::from(103_u32), TransferClass::Storage, 20 * 1024 * 1024));
        let mut behind =
            Box::pin(later.acquire(Did::from(104_u32), TransferClass::E2e, 8 * 1024 * 1024));
        let mut reserved =
            Box::pin(control.acquire(Did::from(105_u32), TransferClass::DhtControl, 1));

        assert!(matches!(futures::poll!(front.as_mut()), Poll::Pending));
        assert!(matches!(futures::poll!(behind.as_mut()), Poll::Pending));
        assert!(matches!(
            futures::poll!(reserved.as_mut()),
            Poll::Ready(Ok(_))
        ));
        drop(first_blocker);
        assert!(matches!(futures::poll!(front.as_mut()), Poll::Ready(Ok(_))));
        assert!(matches!(
            futures::poll!(behind.as_mut()),
            Poll::Ready(Ok(_))
        ));
    }

    #[cfg_attr(
        all(feature = "wasm", target_family = "wasm"),
        wasm_bindgen_test::wasm_bindgen_test
    )]
    #[cfg_attr(not(all(feature = "wasm", target_family = "wasm")), tokio::test)]
    async fn test_shared_wait_budget_bounds_payloads_outside_admitted_capacity() {
        const HEADROOM_BYTES: usize = 16 * 1024 * 1024;
        const WAIT_BYTES: usize = 20 * 1024 * 1024;
        let global = Arc::new(GlobalTransferCapacity::new());
        let first = Arc::new(TransferCapacity::new(global.clone()));
        let second = Arc::new(TransferCapacity::new(global.clone()));
        let blocker_bytes = (OUTBOUND_GLOBAL_BYTE_CAPACITY - HEADROOM_BYTES) / 2;
        let _first_blocker = first
            .try_acquire(
                Did::from(201_u32),
                TransferClass::Application,
                blocker_bytes,
            )
            .expect("first global blocker must fit");
        let _second_blocker = second
            .try_acquire(
                Did::from(202_u32),
                TransferClass::Application,
                blocker_bytes,
            )
            .expect("second global blocker must fit");
        let waiter_count = OUTBOUND_GLOBAL_BYTE_CAPACITY / WAIT_BYTES;
        let capacities = (0..=waiter_count)
            .map(|_| Arc::new(TransferCapacity::new(global.clone())))
            .collect::<Vec<_>>();
        let mut waiters = capacities
            .iter()
            .take(waiter_count)
            .enumerate()
            .map(|(index, capacity)| {
                Box::pin(capacity.acquire(
                    Did::from(
                        300_u32 + u32::try_from(index).expect("waiter index must fit in u32"),
                    ),
                    TransferClass::Storage,
                    WAIT_BYTES,
                ))
            })
            .collect::<Vec<_>>();

        for waiter in &mut waiters {
            assert!(matches!(futures::poll!(waiter.as_mut()), Poll::Pending));
        }
        let overflow_capacity = capacities.last().expect("overflow capacity must exist");
        let mut overflow = Box::pin(overflow_capacity.acquire(
            Did::from(400_u32),
            TransferClass::Storage,
            WAIT_BYTES,
        ));
        assert!(matches!(
            futures::poll!(overflow.as_mut()),
            Poll::Ready(Err(Error::OutboundTransferMemoryCapacityExceeded { .. }))
        ));
    }
}