weida 0.1.0-alpha.13

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
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
//! Grouped local connections: the shape shared by `weida+unix://` and
//! `weida+pipe://`.
//!
//! The two local transports with a kernel between the peers
//! ([decision 0010](../../../docs/decisions/0010-local-transport.md) §4.1):
//! a stream socket on a filesystem path, or a named pipe, one connection per
//! transfer, no TLS, and the peer proved by the kernel rather than by a key
//! [0010 §4.4, §4.5]. What differs between the two — how a connection is
//! dialled, how it splits into halves, how its end is signalled, and what
//! the kernel says about the peer — is the [`Stream`] trait; everything
//! about *grouping* is here and written once.
//!
//! **How connections become a peer** is
//! [decision 0012](../../../docs/decisions/0012-local-connection-grouping.md).
//! An accepted connection cannot be dialled back, so the connections of one
//! peer are grouped instead of multiplexed:
//!
//! ```text
//! byte 0x01            control connection: the peer itself
//!   <- 16 bytes        the group token, issued by the server
//!   then HELLO both ways on this connection
//!
//! byte 0x02 + token    transfer connection: one weida stream
//!   accepted only if the token names a live control connection *and* the
//!   kernel credentials match that connection's [0012 §4.2]
//!
//! byte 0x03 + token    reverse connection: parked, so the *accepting* side
//!   can open a stream toward this peer; same admission rule [0012 §4.4]
//! ```
//!
//! The token binds connections and resumes nothing: no subscriptions, no
//! sequence position, no dedup window, meaningless once the control
//! connection closes. That is why it is not the session state
//! [0008](../../../docs/decisions/0008-session-identity.md) §4.5 forbids
//! [0012 §4.5].
//!
//! **Dispatch is by path**, as `docs/PROTOCOL.md` §2.1 already specifies for
//! local transports: a transfer connection carries one frame, and the pattern
//! registered at the path it addresses says whether a reply is expected. A
//! parked connection is the same thing in the other direction: the client
//! reads a DATA header on it and routes it by path, exactly as an accepted
//! unidirectional stream is routed on QUIC.
//!
//! **Fan-out is bounded by the pool.** A publisher takes one parked
//! connection per copy and the subscriber parks a replacement; a publisher
//! that finds none drops that copy and counts it, which is the answer
//! fan-out already gives an exhausted subscriber budget [0012 §4.4].

use std::collections::{BTreeSet, HashMap, VecDeque};
use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
use std::sync::{Arc, Mutex as StdMutex};

use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
use tokio::sync::{Notify, OwnedSemaphorePermit, Semaphore, mpsc, oneshot};
use weida_core::{Error, LossCause, PeerIdentity};
use weida_protocol::codes;

use crate::runtime::Exec;

/// First byte of a control connection.
const KIND_CONTROL: u8 = 0x01;
/// First byte of a transfer connection, followed by the 16-byte group token.
const KIND_TRANSFER: u8 = 0x02;
/// First byte of a parked reverse connection, followed by the same token:
/// a stream the accepting side may take when it needs to write to this peer
/// [0012 §4.4].
const KIND_REVERSE: u8 = 0x03;
/// Length of a group token [0012 §4.2].
const TOKEN_LEN: usize = 16;

const NO_CODE: u64 = u64::MAX;

/// One kind of local connection: what the grouping needs from the OS.
///
/// Implemented by the `AF_UNIX` stream and by the named pipe. The
/// preamble bytes of [0012] are written and read on the raw stream, so the
/// type itself is a byte stream; the halves it splits into are what a weida
/// stream is made of afterwards.
pub(crate) trait Stream: AsyncRead + AsyncWrite + Unpin + Send + Sized + 'static {
    /// What a dial needs to reach the same endpoint again: the socket path,
    /// the pipe path.
    type Endpoint: Send + Sync + 'static;
    /// What the kernel says about the process on the other end.
    type Principal: Clone + Send + Sync + 'static;
    /// The writing half of a split connection.
    type Writer: AsyncWrite + Unpin + Send + 'static;
    /// The reading half of a split connection.
    type Reader: AsyncRead + Unpin + Send + 'static;

    /// Dials a new connection to `endpoint`.
    ///
    /// An endpoint nobody serves is `ConnectionLost(PeerClosed)`, so a
    /// caller can redial; everything else is an I/O error.
    fn connect(endpoint: &Self::Endpoint) -> impl Future<Output = Result<Self, Error>> + Send;

    /// The kernel's answer to who is on the other end.
    ///
    /// Called on the accepting side after the first byte has been read —
    /// a pipe cannot identify a client that has not written yet — and on
    /// the dialling side after the token has been read.
    fn principal(&self) -> Result<Self::Principal, Error>;

    /// Splits into the reading and writing halves.
    fn split(self) -> (Self::Reader, Self::Writer);

    /// Whether the kernel calls two connections the same peer: the account
    /// always, the pid where the platform reports one, and never the pid
    /// alone [0012 §4.2].
    fn same_peer(group: &Self::Principal, asking: &Self::Principal) -> bool;

    /// The principal as a proved identity.
    fn identity(principal: &Self::Principal) -> PeerIdentity;

    /// Ends the payload on `writer`: the FIN the reader sees.
    ///
    /// `claims` is what the connection counts itself against. A transport
    /// that finishes the write on a task keeps it with that task, so it is
    /// released with the OS handle and not before.
    fn finish(writer: Self::Writer, claims: Claims);

    /// Abandons the payload on `writer` with `code`; `claims` as for
    /// [`finish`](Stream::finish).
    fn reset(writer: Self::Writer, code: u64, claims: Claims);

    /// Refuses the rest of the payload on `reader` with `code`. A transport
    /// that drains keeps `claims` with the drain until it has let go of the
    /// handle.
    fn stop(reader: Self::Reader, code: u64, claims: Claims);

    /// A read error as the transport reports it.
    fn read_error(error: std::io::Error) -> Error;
}

/// Both halves of one transfer connection.
pub(crate) type Halves<S> = (LocalSend<S>, LocalRecv<S>);

/// One place of the binding's `max_connections`. A local connection keeps its
/// place for as long as it lives: a control connection for the life of its
/// link, a transfer or parked connection until its last half is gone and
/// until every task that took over a half's descriptor (a drain, an end
/// marker still being written) has let go of it, so that the places bound the
/// descriptors and not only the halves still in hand.
pub(crate) type Place = OwnedSemaphorePermit;

/// The peers a binding has admitted, keyed by their group token.
pub(crate) struct Groups<S: Stream> {
    entries: StdMutex<HashMap<[u8; TOKEN_LEN], Group<S>>>,
    /// What a link whose peer's control connection ended waits on before it
    /// closes: every connection the binding had been handed by then is
    /// admitted.
    barrier: Arc<AcceptBarrier>,
}

impl<S: Stream> Groups<S> {
    /// A registry whose links wait on `barrier`, which the binding's accept
    /// loop serves.
    pub(crate) fn new(barrier: Arc<AcceptBarrier>) -> Groups<S> {
        Groups {
            entries: StdMutex::new(HashMap::new()),
            barrier,
        }
    }
}

impl<S: Stream> Default for Groups<S> {
    /// A registry with no accept loop behind it: its barrier passes at once.
    fn default() -> Groups<S> {
        Groups::new(AcceptBarrier::new().0)
    }
}

/// Orders a closing link after the connections its peer opened before it
/// went ([B-392](../../../docs/BACKLOG.md)).
///
/// A local peer opens a transfer connection, writes its payload, takes the
/// receipt (the kernel has the bytes) and exits, which ends its control
/// connection. The transfer connection's `connect` returned before that, so
/// it is already in the binding's hands: in the kernel's accept queue (a
/// unix socket), connected to a listening instance (a named pipe), or
/// accepted and reading its preamble. A link that closed when the control
/// connection ended, or after a guessed quiet period, refused it once its
/// token named no group any more, and the receipt had lied.
///
/// So the link asks the accept loop for a barrier: the loop takes every
/// connection it was handed and can take now without waiting for a client
/// (accept until the queue is empty, every instance a client connected to),
/// numbers each, and answers with the last number; the link then waits until
/// every connection up to that number has been admitted or turned away.
/// Every connection numbered holds a [`Ticket`] until then.
///
/// Taking a connection takes a place of the binding's `max_connections`.
/// The request brings the place of the control connection that ended, and
/// the loop takes further ones only if they are free: waiting for one could
/// wait for a link that is itself waiting on a barrier. A peer that went
/// while the binding was full therefore gets its first queued connection
/// for certain and the rest as far as places are free.
pub(crate) struct AcceptBarrier {
    requests: mpsc::UnboundedSender<BarrierRequest>,
    /// Numbers of the connections accepted and not yet admitted.
    in_flight: StdMutex<BTreeSet<u64>>,
    /// The number the next accepted connection gets; numbers start at 1.
    next: AtomicU64,
    settled: Notify,
}

/// One closing link's request: answer with the last number once the
/// queue is taken, spending `place` first.
pub(crate) struct BarrierRequest {
    pub(crate) answer: oneshot::Sender<u64>,
    pub(crate) place: Option<Place>,
}

impl BarrierRequest {
    /// A place to take the next queued connection with: the one the request
    /// brought, then any free one; `None` when the binding is full.
    pub(crate) fn next_place(&mut self, admitted: &Arc<Semaphore>) -> Option<Place> {
        self.place
            .take()
            .or_else(|| Arc::clone(admitted).try_acquire_owned().ok())
    }
}

/// The accept loop's end of an [`AcceptBarrier`]: one request per closing
/// link, answered once the loop has taken what it was handed.
pub(crate) type BarrierRequests = mpsc::UnboundedReceiver<BarrierRequest>;

/// One accepted connection that has not been admitted yet; dropping it
/// marks it settled.
pub(crate) struct Ticket {
    barrier: Arc<AcceptBarrier>,
    number: u64,
}

impl Drop for Ticket {
    fn drop(&mut self) {
        self.barrier
            .in_flight
            .lock()
            .expect("barrier poisoned")
            .remove(&self.number);
        self.barrier.settled.notify_waiters();
    }
}

impl AcceptBarrier {
    pub(crate) fn new() -> (Arc<AcceptBarrier>, BarrierRequests) {
        let (requests, rx) = mpsc::unbounded_channel();
        let barrier = Arc::new(AcceptBarrier {
            requests,
            in_flight: StdMutex::new(BTreeSet::new()),
            next: AtomicU64::new(1),
            settled: Notify::new(),
        });
        (barrier, rx)
    }

    /// Numbers a connection the accept loop just took.
    pub(crate) fn ticket(self: &Arc<AcceptBarrier>) -> Ticket {
        let mut in_flight = self.in_flight.lock().expect("barrier poisoned");
        let number = self.next.fetch_add(1, Ordering::Relaxed);
        in_flight.insert(number);
        Ticket {
            barrier: Arc::clone(self),
            number,
        }
    }

    /// The number of the last connection numbered so far, for the answer to
    /// a request.
    pub(crate) fn last(&self) -> u64 {
        self.next.load(Ordering::Relaxed) - 1
    }

    /// Resolves once every connection the accept loop had been handed when
    /// this was called is admitted or turned away. Passes at once when no
    /// accept loop serves the barrier any more.
    async fn wait(&self, place: Option<Place>) {
        let (answer, answered) = oneshot::channel();
        if self
            .requests
            .send(BarrierRequest { answer, place })
            .is_err()
        {
            return;
        }
        let Ok(upto) = answered.await else { return };
        loop {
            let settled = self.settled.notified();
            let pending = self
                .in_flight
                .lock()
                .expect("barrier poisoned")
                .first()
                .is_some_and(|&first| first <= upto);
            if !pending {
                return;
            }
            settled.await;
        }
    }
}

struct Group<S: Stream> {
    /// Credentials of the control connection: what a transfer connection must
    /// match [0012 §4.2].
    principal: S::Principal,
    /// One permit per transfer connection admitted for this peer that is
    /// still alive, out of [`LIVE_CAP`]: what a link whose peer's control
    /// connection ended waits on before it closes, so that what the peer
    /// sent before it exited is still delivered.
    live: Arc<Semaphore>,
    transfers: mpsc::UnboundedSender<Halves<S>>,
    /// Connections this peer parked for streams in the other direction
    /// [0012 §4.4]. Shared with the peer's link, which is what spends them.
    reverse: Arc<ReversePool<S>>,
    /// The binding's place the control connection holds. Once the peer's
    /// control connection ends, its link hands it to the accept barrier, so
    /// the connections the peer opened before it went can be accepted even
    /// when the binding is at `max_connections`: the peer's count does not
    /// grow, it moves from a connection that is gone to one it sent.
    control_place: Option<Place>,
}

/// The connections one peer parked, and the two bounds they live under.
///
/// `max` is `Limits::max_parked_reverse`, the pool's own ceiling; `slots` is
/// the connection's `max_local_streams` accounting, which a parked
/// connection counts against like any other live local connection
/// [0012 §4.4]. Both are refusals rather than waits: a pool that cannot grow
/// is the peer's fan-out budget, not backpressure on a transfer.
pub(crate) struct ReversePool<S: Stream> {
    parked: StdMutex<VecDeque<LocalSend<S>>>,
    max: usize,
    slots: Arc<Semaphore>,
}

impl<S: Stream> ReversePool<S> {
    fn new(slots: Arc<Semaphore>, max: usize) -> ReversePool<S> {
        ReversePool {
            parked: StdMutex::new(VecDeque::new()),
            max,
            slots,
        }
    }

    /// Takes a parked connection in, or refuses it because a bound says so.
    /// `place` is the binding's place for the connection; it stays with the
    /// write half for as long as that half lives, spent or not.
    fn park(&self, send: S::Writer, place: Place) -> bool {
        let mut parked = self.parked.lock().expect("reverse pool poisoned");
        if parked.len() >= self.max {
            return false;
        }
        let Some(slot) = StreamSlot::try_acquire(&self.slots) else {
            return false;
        };
        parked.push_back(LocalSend::new(send, Some(Arc::new(slot))).placed(Arc::new(place)));
        true
    }

    /// Spends one on a stream toward the peer. `None` is a drop, not a
    /// failure of the connection [0012 §4.4].
    fn take(&self) -> Option<LocalSend<S>> {
        self.parked
            .lock()
            .expect("reverse pool poisoned")
            .pop_front()
    }
}

impl<S: Stream> Groups<S> {
    fn insert(
        &self,
        token: [u8; TOKEN_LEN],
        principal: S::Principal,
        transfers: mpsc::UnboundedSender<Halves<S>>,
        reverse: Arc<ReversePool<S>>,
        control_place: Option<Place>,
    ) {
        self.entries
            .lock()
            .expect("group registry poisoned")
            .insert(
                token,
                Group {
                    principal,
                    live: Arc::new(Semaphore::new(LIVE_CAP)),
                    transfers,
                    reverse,
                    control_place,
                },
            );
    }

    /// The place the group's control connection held, taken once.
    fn take_control_place(&self, token: &[u8; TOKEN_LEN]) -> Option<Place> {
        self.entries
            .lock()
            .expect("group registry poisoned")
            .get_mut(token)
            .and_then(|group| group.control_place.take())
    }

    fn remove(&self, token: &[u8; TOKEN_LEN]) {
        self.entries
            .lock()
            .expect("group registry poisoned")
            .remove(token);
    }

    /// Runs `f` against the group `token` names, if the kernel agrees that
    /// the caller is that group's peer.
    ///
    /// The token names the group; the kernel says who is asking
    /// [0012 §4.2].
    fn with_group<T>(
        &self,
        token: &[u8; TOKEN_LEN],
        principal: &S::Principal,
        f: impl FnOnce(&Group<S>) -> T,
    ) -> Option<T> {
        let entries = self.entries.lock().expect("group registry poisoned");
        let group = entries.get(token)?;
        if !S::same_peer(&group.principal, principal) {
            return None;
        }
        Some(f(group))
    }

    /// Hands a transfer connection to its peer.
    ///
    /// The connection keeps its `place` until both of its halves are gone,
    /// so what a peer can have queued on a binding is bounded by the
    /// binding's `max_connections`, not by the descriptor limit of the
    /// process. It is **not** refused for being one of many: a sender that
    /// outruns a slow consumer is a documented case that waits and loses
    /// nothing (`docs/GUARANTEES.md` §6), and the dialling side frees its own
    /// slot at its FIN, so only the accepting side sees the backlog. What
    /// bounds it is the accept loop, which takes a place before it accepts a
    /// connection and so leaves the surplus waiting in the kernel's queue.
    fn admit(
        &self,
        token: &[u8; TOKEN_LEN],
        principal: &S::Principal,
        stream: S,
        place: Place,
    ) -> bool {
        self.with_group(token, principal, |group| {
            // A slot of the peer's live count, held until both halves are gone.
            let Some(live) = StreamSlot::try_acquire(&group.live) else {
                return false;
            };
            let live = Arc::new(live);
            let place = Arc::new(place);
            let (recv, send) = stream.split();
            let halves = (
                LocalSend::new(send, Some(Arc::clone(&live))).placed(Arc::clone(&place)),
                LocalRecv::new(recv, Some(live)).placed(place),
            );
            group.transfers.send(halves).is_ok()
        })
        .unwrap_or(false)
    }

    /// Parks a reverse connection for its peer, if a bound leaves room.
    fn park(
        &self,
        token: &[u8; TOKEN_LEN],
        principal: &S::Principal,
        send: S::Writer,
        place: Place,
    ) -> bool {
        self.with_group(token, principal, |group| group.reverse.park(send, place))
            .unwrap_or(false)
    }
}

/// The local preamble of an accepted connection, read.
pub(crate) enum Accepted<S: Stream> {
    Control(S, S::Principal),
    Transfer([u8; TOKEN_LEN], S, S::Principal),
    Reverse([u8; TOKEN_LEN], S, S::Principal),
}

/// Reads the local preamble of an accepted connection and asks the kernel
/// who sent it.
///
/// Waits on the peer for as long as the caller lets it: the accepting side
/// bounds this with a deadline.
pub(crate) async fn read_accepted<S: Stream>(mut stream: S) -> Result<Accepted<S>, Error> {
    let mut kind = [0u8; 1];
    stream.read_exact(&mut kind).await.map_err(Error::Io)?;
    // After the first byte, on purpose: a pipe's client is identified
    // through what it wrote.
    let principal = stream.principal()?;
    match kind[0] {
        KIND_CONTROL => Ok(Accepted::Control(stream, principal)),
        KIND_TRANSFER | KIND_REVERSE => {
            let mut token = [0u8; TOKEN_LEN];
            stream.read_exact(&mut token).await.map_err(Error::Io)?;
            Ok(if kind[0] == KIND_TRANSFER {
                Accepted::Transfer(token, stream, principal)
            } else {
                Accepted::Reverse(token, stream, principal)
            })
        }
        other => Err(Error::Protocol(format!(
            "unknown local connection kind {other:#04x}"
        ))),
    }
}

/// Serves one accepted control connection: issues the token and builds the
/// accepting side's link.
///
/// `exec` runs the watch over the peer's control connection, which is how
/// the link learns that a peer left without saying so (see
/// [`Grouped::accept_uni`]). `place` is the binding's place the control
/// connection holds; the group keeps it until the link closes
/// ([`Group::control_place`]).
pub(crate) async fn accept_control<S: Stream>(
    mut stream: S,
    principal: S::Principal,
    groups: Arc<Groups<S>>,
    max_streams: usize,
    max_parked: usize,
    exec: Exec,
    place: Option<Place>,
) -> Result<Grouped<S>, Error> {
    let token = random_token();
    let slots = stream_slots(max_streams);
    let (transfers_tx, transfers_rx) = mpsc::unbounded_channel();
    // The pool is the peer's and the link's at once: the peer fills it over
    // the socket, the link spends it on fan-out [0012 §4.4].
    let reverse = Arc::new(ReversePool::new(Arc::clone(&slots), max_parked));
    // Registered before the token goes out: the peer dials its transfer
    // connections the moment it reads the token, and the accept loop may
    // admit one on another thread before this task runs again. A token the
    // peer can read always names a group.
    groups.insert(
        token,
        principal.clone(),
        transfers_tx,
        Arc::clone(&reverse),
        place,
    );
    let registered = Registered {
        groups: &groups,
        token,
    };
    stream.write_all(&token).await.map_err(Error::Io)?;
    std::mem::forget(registered);
    let mut link = Grouped::new(
        Side::Accept {
            groups: Arc::clone(&groups),
            token,
            exec,
        },
        stream,
        Some(principal),
        slots,
        max_parked,
    );
    link.reverse = Some(reverse);
    link.transfers = tokio::sync::Mutex::new(Some(transfers_rx));
    Ok(link)
}

/// A group registered for a control connection whose token has not gone out
/// yet: dropped, on a failed write or a cancelled accept, it leaves the
/// registry again.
struct Registered<'a, S: Stream> {
    groups: &'a Groups<S>,
    token: [u8; TOKEN_LEN],
}

impl<S: Stream> Drop for Registered<'_, S> {
    fn drop(&mut self) {
        self.groups.remove(&self.token);
    }
}

/// The `max_local_streams` slots of one link; tokio panics above
/// `Semaphore::MAX_PERMITS`.
fn stream_slots(max_streams: usize) -> Arc<Semaphore> {
    Arc::new(Semaphore::new(max_streams.min(Semaphore::MAX_PERMITS)))
}

/// Parks an accepted reverse connection with the peer its token names
/// [0012 §4.4]. The client never writes on it, so only the write half is
/// kept; the read half goes away with this call.
pub(crate) fn admit_reverse<S: Stream>(
    groups: &Groups<S>,
    token: &[u8; TOKEN_LEN],
    principal: &S::Principal,
    stream: S,
    place: Place,
) -> bool {
    let (_recv, send) = stream.split();
    groups.park(token, principal, send, place)
}

/// Hands an accepted transfer connection to the peer its token names, if the
/// kernel agrees that it is the same peer [0012 §4.2].
pub(crate) fn admit_transfer<S: Stream>(
    groups: &Groups<S>,
    token: &[u8; TOKEN_LEN],
    principal: &S::Principal,
    stream: S,
    place: Place,
) -> bool {
    groups.admit(token, principal, stream, place)
}

/// Dials `endpoint`, completing the control handshake of [0012 §4.1].
pub(crate) async fn dial<S: Stream>(
    endpoint: S::Endpoint,
    max_streams: usize,
    max_parked: usize,
) -> Result<Grouped<S>, Error> {
    let mut stream = S::connect(&endpoint).await?;
    stream.write_all(&[KIND_CONTROL]).await.map_err(Error::Io)?;
    let mut token = [0u8; TOKEN_LEN];
    stream.read_exact(&mut token).await.map_err(Error::Io)?;
    let principal = stream.principal()?;
    Ok(Grouped::new(
        Side::Dial { endpoint, token },
        stream,
        Some(principal),
        stream_slots(max_streams),
        max_parked,
    ))
}

fn random_token() -> [u8; TOKEN_LEN] {
    use rand::RngCore;
    let mut token = [0u8; TOKEN_LEN];
    rand::rng().fill_bytes(&mut token);
    token
}

/// Which end of a local connection this is, and what it can do with that.
enum Side<S: Stream> {
    /// The dialling side: it may open more connections.
    Dial {
        endpoint: S::Endpoint,
        token: [u8; TOKEN_LEN],
    },
    /// The accepting side: it receives connections, and opens streams toward
    /// the peer only out of the connections that peer parked [0012 §4.4].
    Accept {
        groups: Arc<Groups<S>>,
        token: [u8; TOKEN_LEN],
        /// Runs the watch over the peer's control connection.
        exec: Exec,
    },
}

/// Everything that says a link is closed, shared with what closes it from
/// another task: the watch over the peer's control connection.
struct Closing<S: Stream> {
    code: AtomicU64,
    notify: Notify,
    /// On the accepting side, the group this link registered. It leaves the
    /// binding's table when the link closes: a token that names a closed link
    /// admits nothing.
    group: Option<(Arc<Groups<S>>, [u8; TOKEN_LEN])>,
}

impl<S: Stream> Closing<S> {
    fn new(side: &Side<S>) -> Closing<S> {
        Closing {
            code: AtomicU64::new(NO_CODE),
            notify: Notify::new(),
            group: match side {
                Side::Accept { groups, token, .. } => Some((Arc::clone(groups), *token)),
                Side::Dial { .. } => None,
            },
        }
    }

    /// Closes with `code`; `true` for the call that did.
    fn close(&self, code: u64) -> bool {
        if self
            .code
            .compare_exchange(NO_CODE, code, Ordering::AcqRel, Ordering::Acquire)
            .is_err()
        {
            return false;
        }
        if let Some((groups, token)) = &self.group {
            groups.remove(token);
        }
        self.notify.notify_waiters();
        true
    }

    fn reason(&self) -> Option<Error> {
        let code = self.code.load(Ordering::Acquire);
        (code != NO_CODE).then(|| match code {
            codes::NEGOTIATION_FAILED => {
                Error::Negotiation("peer closed the connection: negotiation failed".into())
            }
            _ => Error::ConnectionLost(LossCause::PeerClosed),
        })
    }

    /// Resolves once the link is closed.
    async fn wait(&self) {
        loop {
            // Created before the state is read, so a close that lands in
            // between is not missed.
            let closed = self.notify.notified();
            if self.reason().is_some() {
                return;
            }
            closed.await;
        }
    }
}

/// The most transfer connections one peer's live count can hold; waiting for
/// all of them back is waiting for the peer's admitted transfers to finish.
/// What a semaphore counts is the platform's own ceiling: a constant above it
/// panics the first time a local peer's group is made.
const LIVE_CAP: usize = Semaphore::MAX_PERMITS;

/// The longest a link whose peer's control connection ended waits for the
/// transfers the peer had already sent before it closes anyway: for the
/// accept loop to reach them ([`AcceptBarrier`]), which waits for a place
/// when the binding is at `max_connections`, and for the admitted ones to
/// finish.
const PEER_GONE_LINGER: std::time::Duration = std::time::Duration::from_secs(10);

/// How often such a link looks at what is still admitted for it. It looks
/// rather than waits for every permit, because a task waiting for all of them
/// would take the free ones as they appear and refuse the peer's late
/// connections.
const PEER_GONE_TICK: std::time::Duration = std::time::Duration::from_millis(50);

impl<S: Stream> Groups<S> {
    /// The live count of the group `token` names, if there still is one.
    fn live(&self, token: &[u8; TOKEN_LEN]) -> Option<Arc<Semaphore>> {
        self.entries
            .lock()
            .expect("group registry poisoned")
            .get(token)
            .map(|group| Arc::clone(&group.live))
    }
}

/// What a peer's control read half is handed to once the HELLO has been read
/// from it: a task that reads until the peer's end goes away and then closes
/// the link.
struct ControlWatch<S: Stream> {
    closing: Arc<Closing<S>>,
    exec: Exec,
}

impl<S: Stream> ControlWatch<S> {
    fn spawn(self, mut io: S::Reader) {
        let ControlWatch { closing, exec } = self;
        let linger = exec.clone();
        exec.spawn(async move {
            // Nothing legitimate follows the HELLO on this connection, so
            // whatever arrives is discarded: what matters is the end.
            let mut scratch = [0u8; 64];
            loop {
                tokio::select! {
                    read = io.read(&mut scratch) => match read {
                        Ok(n) if n > 0 => {}
                        _ => break,
                    },
                    () = closing.wait() => return,
                }
            }
            // The peer's end is gone, and a sender that pushes and exits is
            // an ordinary peer: what it already sent is still delivered. The
            // link closes once every connection the binding had been handed
            // is admitted (the barrier) and the transfers admitted for it are
            // done, or after a bound for one that never completes.
            if let Some((groups, token)) = closing.group.as_ref() {
                let settled = async {
                    groups.barrier.wait(groups.take_control_place(token)).await;
                    let Some(live) = groups.live(token) else {
                        return;
                    };
                    while live.available_permits() != LIVE_CAP {
                        linger.sleep(PEER_GONE_TICK).await;
                    }
                };
                let _ = linger.within(PEER_GONE_LINGER, settled).await;
            }
            if closing.close(codes::SHUTDOWN) {
                tracing::debug!("a local peer's control connection ended; closing its link");
            }
        });
    }
}

/// One local peer: its control connection plus the transfer connections
/// grouped with it.
pub(crate) struct Grouped<S: Stream> {
    side: Side<S>,
    /// The control connection's halves, handed out once each: the first
    /// outbound stream is this side's HELLO, the first inbound one the peer's
    /// [0012 §4.1].
    control_send: StdMutex<Option<S::Writer>>,
    control_recv: StdMutex<Option<S::Reader>>,
    /// The dialling side's control write half after its HELLO, which stays
    /// open for as long as the link does. The accepting side reads the other
    /// end of it, and its end is how a peer that exited without a word is
    /// noticed: a local transport has no keep-alive and no idle timeout to
    /// learn it from.
    control_hold: Arc<StdMutex<Option<S::Writer>>>,
    /// Transfer connections the peer opened, for the accepting side.
    transfers: tokio::sync::Mutex<Option<mpsc::UnboundedReceiver<Halves<S>>>>,
    /// Connections this peer parked for us, for the accepting side: the only
    /// way a server opens a stream toward a peer that dialled it.
    reverse: Option<Arc<ReversePool<S>>>,
    /// Connections this side parked, on the dialling side: their read halves
    /// arrive here and are handed to the connection driver, which dispatches
    /// whatever the peer writes on them by path [0012 §4.4].
    parked_tx: mpsc::UnboundedSender<LocalRecv<S>>,
    parked_rx: tokio::sync::Mutex<mpsc::UnboundedReceiver<LocalRecv<S>>>,
    /// Parked connections that have been spent and need replacing.
    deficit: Arc<Deficit>,
    peer: Option<S::Principal>,
    /// One permit per live local connection that counts against
    /// `max_local_streams`: a transfer this side opens, and a connection
    /// parked for the reverse pool, held by whichever side keeps it. An `open`
    /// with none free waits for one rather than failing
    /// (`docs/GUARANTEES.md` §6). A transfer connection the *peer* opens
    /// toward the accepting side does not draw on it: `Groups::admit` counts
    /// it against the group's live count and the binding's `max_connections`
    /// places.
    slots: Arc<Semaphore>,
    max_parked: usize,
    closing: Arc<Closing<S>>,
    id: usize,
}

/// How many parked connections have been consumed since the last refill.
///
/// A parked connection is spent the moment the peer writes its first byte on
/// it, not when the copy ends: refilling then keeps the pool at its size
/// while a long copy is still streaming.
#[derive(Default)]
pub(crate) struct Deficit {
    count: AtomicUsize,
    notify: Notify,
}

impl Deficit {
    fn record(&self) {
        self.count.fetch_add(1, Ordering::Relaxed);
        self.notify.notify_one();
    }

    /// Waits until at least one connection needs replacing, and claims them.
    async fn take(&self) -> usize {
        loop {
            let owed = self.count.swap(0, Ordering::Relaxed);
            if owed > 0 {
                return owed;
            }
            self.notify.notified().await;
        }
    }
}

impl<S: Stream> Grouped<S> {
    fn new(
        side: Side<S>,
        control: S,
        peer: Option<S::Principal>,
        slots: Arc<Semaphore>,
        max_parked: usize,
    ) -> Grouped<S> {
        let (recv, send) = control.split();
        let (parked_tx, parked_rx) = mpsc::unbounded_channel();
        let closing = Arc::new(Closing::new(&side));
        Grouped {
            side,
            control_send: StdMutex::new(Some(send)),
            control_recv: StdMutex::new(Some(recv)),
            control_hold: Arc::new(StdMutex::new(None)),
            transfers: tokio::sync::Mutex::new(None),
            reverse: None,
            parked_tx,
            parked_rx: tokio::sync::Mutex::new(parked_rx),
            deficit: Arc::new(Deficit::default()),
            peer,
            slots,
            max_parked,
            closing,
            id: crate::transport::next_serial(),
        }
    }

    pub(crate) fn stable_id(&self) -> usize {
        self.id
    }

    pub(crate) fn peer(&self) -> Option<PeerIdentity> {
        self.peer.as_ref().map(S::identity)
    }

    pub(crate) fn close_reason(&self) -> Option<Error> {
        self.closing.reason()
    }

    pub(crate) fn close(&self, code: u64, _reason: &str) {
        if self.closing.close(code) {
            // Dropping the control halves is the close on the wire: there is
            // no frame for it and no code to carry [0012 §4.7].
            self.control_send.lock().expect("poisoned").take();
            self.control_recv.lock().expect("poisoned").take();
            self.control_hold.lock().expect("poisoned").take();
        }
    }

    pub(crate) async fn closed(&self) -> Error {
        loop {
            self.closing.wait().await;
            if let Some(reason) = self.close_reason() {
                return reason;
            }
        }
    }

    /// Whether every slot is taken right now.
    ///
    /// One atomic load, for the caller that has something to free before it
    /// parks on a slot (`ConnCtx::open_uni`).
    pub(crate) fn slots_exhausted(&self) -> bool {
        self.slots.available_permits() == 0
    }

    /// A slot for one more local connection, waiting for one where
    /// `max_local_streams` are already live.
    ///
    /// This is the local shape of what `quinn` does with the peer's
    /// `max_concurrent_uni_streams`: an `open` with no budget left parks until
    /// a stream ends, and the deadline is the caller's, not the transport's.
    /// Dropping the future is the cancellation and it releases nothing,
    /// because a waiter holds no descriptor.
    async fn slot(&self) -> Result<StreamSlot, Error> {
        let waiting = Arc::clone(&self.slots).acquire_owned();
        tokio::select! {
            permit = waiting => match permit {
                Ok(permit) => Ok(StreamSlot { _permit: permit }),
                Err(_) => Err(Error::ConnectionLost(LossCause::LocallyClosed)),
            },
            reason = self.closed() => Err(reason),
        }
    }

    /// Opens one stream toward the peer.
    ///
    /// On the dialling side that is a new transfer connection. On the
    /// accepting side there is nothing to dial, so it is one of the
    /// connections the peer parked; an empty pool is
    /// [`Error::NoParkedConnection`], which fan-out counts as a drop rather
    /// than as a failure of the subscription [0012 §4.4].
    ///
    /// The control connection's own write half is never handed out here: it
    /// belongs to `open_control`, so that a fan-out copy can never take the
    /// stream the HELLO is owed.
    pub(crate) async fn open_uni(&self) -> Result<LocalSend<S>, Error> {
        if let Side::Accept { .. } = &self.side {
            if let Some(closed) = self.close_reason() {
                return Err(closed);
            }
            return self
                .reverse
                .as_ref()
                .and_then(|pool| pool.take())
                .ok_or(Error::NoParkedConnection);
        }
        let (send, _recv) = self.open_transfer().await?;
        Ok(send)
    }

    /// Hands out the control connection's write half, once.
    ///
    /// This is the one stream each side has toward the other without dialling
    /// anything, and both sides spend it on HELLO ([0012 §4.1]). The
    /// dialling side's does not end with it: that half is kept open for the
    /// life of the link, because the accepting side watches the other end.
    pub(crate) fn open_control(&self) -> Result<LocalSend<S>, Error> {
        match self.take_control_send() {
            Some(send) => {
                let mut send = LocalSend::new(send, None);
                if matches!(self.side, Side::Dial { .. }) {
                    send.keep = Some(Arc::clone(&self.control_hold));
                }
                Ok(send)
            }
            None => Err(Error::Transport("control stream already used".into())),
        }
    }

    pub(crate) async fn open_bi(&self) -> Result<Halves<S>, Error> {
        self.open_transfer().await
    }

    fn take_control_send(&self) -> Option<S::Writer> {
        self.control_send.lock().expect("poisoned").take()
    }

    async fn open_transfer(&self) -> Result<Halves<S>, Error> {
        if let Some(closed) = self.close_reason() {
            return Err(closed);
        }
        let (endpoint, token) = match &self.side {
            Side::Dial { endpoint, token } => (endpoint, token),
            // An exchange opened *by* the server does not exist: a parked
            // connection carries one stream, and the pattern that needs two
            // is always initiated by the dialling side.
            Side::Accept { .. } => return Err(Error::Unsupported),
        };
        let slot = self.slot().await?;
        let mut stream = match S::connect(endpoint).await {
            Ok(stream) => stream,
            // Nobody answers on the address any more: the peer is gone, and
            // the group with it. Learned here, at the next open, because a
            // local transport has no idle timeout and carries nothing on the
            // control connection after the HELLOs to learn it from earlier
            // (`docs/PATTERNS.md` §1.10). Marking the link closed is what
            // lets a redial start [0031 §4.10].
            Err(e @ Error::ConnectionLost(_)) => {
                self.close(codes::SHUTDOWN, "nobody answers on the address");
                return Err(e);
            }
            Err(e) => return Err(e),
        };
        let mut preamble = [0u8; 1 + TOKEN_LEN];
        preamble[0] = KIND_TRANSFER;
        preamble[1..].copy_from_slice(token);
        stream.write_all(&preamble).await.map_err(Error::Io)?;
        let (recv, send) = stream.split();
        let slot = Arc::new(slot);
        Ok((
            LocalSend::new(send, Some(Arc::clone(&slot))),
            LocalRecv::new(recv, Some(slot)),
        ))
    }

    /// Streams the peer opened toward this side.
    ///
    /// The control connection's read half is the peer's HELLO, and after it
    /// come the connections this side parked: whatever the peer writes on
    /// one is read here and dispatched by path, which is what an accepted
    /// unidirectional stream is on QUIC [0012 §4.4]. A transfer connection
    /// the peer *opened* is not one of these - that is `accept_bi`, and it
    /// is dispatched by path too [0012 §4.3].
    ///
    /// On the accepting side the control read half is handed to a watch when
    /// the HELLO has been read from it: the peer keeps its end open for as
    /// long as it lives, so that end going away is how a peer that left
    /// without a word is noticed, and the link closes with it. Nothing else
    /// would: a local transport has no keep-alive and no idle timeout, and
    /// the control connection carries nothing after the HELLOs.
    pub(crate) async fn accept_uni(&self) -> Result<LocalRecv<S>, Error> {
        if let Some(recv) = self.control_recv.lock().expect("poisoned").take() {
            let mut recv = LocalRecv::new(recv, None);
            if let Side::Accept { exec, .. } = &self.side {
                recv.watch = Some(ControlWatch {
                    closing: Arc::clone(&self.closing),
                    exec: exec.clone(),
                });
            }
            return Ok(recv);
        }
        let mut parked = self.parked_rx.lock().await;
        tokio::select! {
            arrived = parked.recv() => arrived.ok_or(Error::ConnectionLost(LossCause::PeerClosed)),
            reason = self.closed() => Err(reason),
        }
    }

    /// Fills the reverse pool up to `max_parked_reverse`.
    ///
    /// Returns how many connections are parked. Zero with an error means the
    /// peer cannot fan out to this side at all, which is what a subscriber
    /// reports at subscribe time rather than discovering as silence
    /// [0012 §4.4].
    pub(crate) async fn park_reverse(&self) -> Result<usize, Error> {
        let mut parked = 0;
        for _ in 0..self.max_parked {
            match self.park_one().await {
                Ok(()) => parked += 1,
                Err(e) if parked == 0 => return Err(e),
                // A bound reached part way is the pool being smaller than
                // asked for, not a failure: the publisher's answer to an
                // empty pool is a counted drop either way.
                Err(e) => {
                    tracing::debug!(error = %e, parked, "reverse pool filled short");
                    break;
                }
            }
        }
        Ok(parked)
    }

    /// Replaces parked connections as they are spent, until the connection
    /// closes. Spawned once per subscribing connection.
    pub(crate) async fn maintain_reverse(&self) {
        loop {
            let owed = tokio::select! {
                owed = self.deficit.take() => owed,
                _ = self.closed() => return,
            };
            for _ in 0..owed {
                if let Err(e) = self.park_one().await {
                    tracing::debug!(error = %e, "reverse pool not replenished");
                    return;
                }
            }
        }
    }

    /// Dials one connection, marks it `reverse` and hands its read half to
    /// the connection driver to wait on.
    async fn park_one(&self) -> Result<(), Error> {
        if let Some(closed) = self.close_reason() {
            return Err(closed);
        }
        let Side::Dial { endpoint, token } = &self.side else {
            return Err(Error::Unsupported);
        };
        // A pool that cannot grow is a refusal, not backpressure: filling it
        // must never park on a slot a transfer is waiting for.
        let slot = Arc::new(StreamSlot::try_acquire(&self.slots).ok_or(Error::LimitExceeded)?);
        let mut stream = S::connect(endpoint).await?;
        let mut preamble = [0u8; 1 + TOKEN_LEN];
        preamble[0] = KIND_REVERSE;
        preamble[1..].copy_from_slice(token);
        stream.write_all(&preamble).await.map_err(Error::Io)?;
        // This side never writes on a parked connection; letting the write
        // half go costs nothing, because the peer never reads on it either.
        let (recv, _send) = stream.split();
        let mut recv = LocalRecv::new(recv, Some(slot));
        recv.deficit = Some(Arc::clone(&self.deficit));
        self.parked_tx
            .send(recv)
            .map_err(|_| Error::ConnectionLost(LossCause::LocallyClosed))
    }

    /// Transfer connections, for the accepting side.
    pub(crate) async fn accept_bi(&self) -> Result<Halves<S>, Error> {
        let mut queue = self.transfers.lock().await;
        let Some(queue) = queue.as_mut() else {
            return Err(self.closed().await);
        };
        tokio::select! {
            accepted = queue.recv() => accepted.ok_or(Error::ConnectionLost(LossCause::PeerClosed)),
            reason = self.closed() => Err(reason),
        }
    }
}

/// Keeps one live transfer connection counted against `max_local_streams`:
/// the permit is returned when the last half of that connection is dropped.
struct StreamSlot {
    _permit: OwnedSemaphorePermit,
}

impl StreamSlot {
    /// Counts one more live local connection, or `None` at the cap, without
    /// waiting: on this transport a stream *is* a connection, so
    /// `max_local_streams` is a file-descriptor count [0010 §4.2].
    ///
    /// Only the callers whose answer to a full budget is a refusal use this;
    /// a transfer waits, in `Grouped::slot`.
    fn try_acquire(slots: &Arc<Semaphore>) -> Option<StreamSlot> {
        Arc::clone(slots)
            .try_acquire_owned()
            .ok()
            .map(|permit| StreamSlot { _permit: permit })
    }
}

/// What one local connection is counted against while its descriptor is
/// open: its slot of `max_local_streams` and, on the accepting side, its place
/// of the binding's `max_connections`. Both halves hold the same ones, so
/// they come back when the last holder lets go.
///
/// A half that hands its OS handle to a task of its own hands its claims
/// along ([`Stream::stop`], [`Stream::finish`], [`Stream::reset`]). Without
/// that, a drain still reading a refused transfer would hold a descriptor
/// the count no longer includes, and a peer that never ends it could make the
/// binding hold as many as the process may open instead of as many as it
/// admits.
#[derive(Default)]
pub(crate) struct Claims {
    _slot: Option<Arc<StreamSlot>>,
    _place: Option<Arc<Place>>,
}

/// A local stream's write failure as an outcome: the peer closing its read
/// side is the local equivalent of `STOP_SENDING`, without a code to carry
/// [0012 §4.7].
pub(crate) fn write_failure(e: std::io::Error) -> Error {
    match e.kind() {
        std::io::ErrorKind::BrokenPipe | std::io::ErrorKind::ConnectionReset => Error::Canceled,
        _ => Error::Transport(format!("local stream write failed: {e}")),
    }
}

/// The writing half of one local stream.
pub(crate) struct LocalSend<S: Stream> {
    io: Option<S::Writer>,
    /// The connection's slot and place, shared with its other half.
    claims: Claims,
    /// Set on the dialling side's control stream: where its half goes when
    /// the HELLO is done, instead of being ended and closed.
    keep: Option<Arc<StdMutex<Option<S::Writer>>>>,
}

impl<S: Stream> LocalSend<S> {
    fn new(io: S::Writer, slot: Option<Arc<StreamSlot>>) -> LocalSend<S> {
        LocalSend {
            io: Some(io),
            claims: Claims {
                _slot: slot,
                _place: None,
            },
            keep: None,
        }
    }

    /// Ties the binding's place for this connection to this half.
    fn placed(mut self, place: Arc<Place>) -> LocalSend<S> {
        self.claims._place = Some(place);
        self
    }

    pub(crate) fn io_mut(&mut self) -> Option<&mut S::Writer> {
        self.io.as_mut()
    }

    pub(crate) async fn write_all(&mut self, buf: &[u8]) -> Result<(), Error> {
        let Some(io) = self.io.as_mut() else {
            return Err(Error::Transport("stream already closed".into()));
        };
        io.write_all(buf).await.map_err(write_failure)
    }

    /// Ends the payload: the FIN the reader sees.
    ///
    /// The control stream's is the exception. Its HELLO is a whole frame and
    /// the reader needs nothing after it, so the half is parked in the link
    /// instead of ended: closing it would be the peer's end of the control
    /// connection going away, which is what the accepting side reads as the
    /// peer having left.
    pub(crate) fn finish(&mut self) -> Result<(), Error> {
        match self.io.take() {
            Some(io) => {
                match &self.keep {
                    Some(keep) => *keep.lock().expect("poisoned") = Some(io),
                    None => S::finish(io, std::mem::take(&mut self.claims)),
                }
                Ok(())
            }
            None => Err(Error::Transport("stream already closed".into())),
        }
    }

    /// Abandons the payload.
    pub(crate) fn reset(&mut self, code: u64) {
        if let Some(io) = self.io.take() {
            S::reset(io, code, std::mem::take(&mut self.claims));
        }
    }

    /// The receipt: on a socket the bytes are the peer's transport's as soon
    /// as `write_all` returned, and the FIN follows when this half drops, so
    /// there is nothing left to wait for (`docs/GUARANTEES.md` §3).
    ///
    /// **Named loss:** a local stream carries no code, so a refusal cannot be
    /// reported here the way `STOP_SENDING` is on QUIC. A peer that refuses
    /// surfaces on the *write*, as `Error::Canceled`, not on the receipt
    /// ([decisions/0012](../../../docs/decisions/0012-local-connection-grouping.md)
    /// §4.7).
    pub(crate) fn stopped(
        &self,
    ) -> impl Future<Output = Result<Option<u64>, Error>> + Send + Sync + use<S> {
        async move { Ok(None) }
    }
}

impl<S: Stream> Drop for LocalSend<S> {
    /// A half dropped without `finish` or `reset` is an abandoned payload.
    fn drop(&mut self) {
        if let Some(io) = self.io.take() {
            S::reset(io, codes::CANCELED, std::mem::take(&mut self.claims));
        }
    }
}

/// The reading half of one local stream.
pub(crate) struct LocalRecv<S: Stream> {
    io: Option<S::Reader>,
    /// The connection's slot and place, shared with its other half.
    claims: Claims,
    /// Set on a parked reverse connection: the pool this one was taken from
    /// wants a replacement once the peer has spent it [0012 §4.4].
    deficit: Option<Arc<Deficit>>,
    spent: bool,
    /// The first byte of a parked connection, read by
    /// [`LocalRecv::opened`] and handed out by the next read.
    first: Option<u8>,
    /// Set on the accepting side's control read half: what it is handed to
    /// when it is dropped, instead of being refused.
    watch: Option<ControlWatch<S>>,
}

impl<S: Stream> LocalRecv<S> {
    fn new(io: S::Reader, slot: Option<Arc<StreamSlot>>) -> LocalRecv<S> {
        LocalRecv {
            io: Some(io),
            claims: Claims {
                _slot: slot,
                _place: None,
            },
            deficit: None,
            spent: false,
            first: None,
            watch: None,
        }
    }

    /// Ties the binding's place for this connection to this half.
    fn placed(mut self, place: Arc<Place>) -> LocalRecv<S> {
        self.claims._place = Some(place);
        self
    }

    pub(crate) fn io_mut(&mut self) -> Option<&mut S::Reader> {
        self.io.as_mut()
    }

    /// Reports a parked connection as spent, once.
    ///
    /// The first byte the peer writes is the moment this connection stopped
    /// being available, so that is when the replacement is asked for - not
    /// when the copy it carries has been read.
    fn spend(&mut self) {
        if self.spent {
            return;
        }
        self.spent = true;
        if let Some(deficit) = &self.deficit {
            deficit.record();
        }
    }

    /// Waits until the peer opens this stream: at once for every stream but
    /// a parked reverse connection, which is opened by the peer's first
    /// byte, however long the peer has nothing to send. `false` is a parked
    /// connection the peer closed without using.
    pub(crate) async fn opened(&mut self) -> Result<bool, Error> {
        if self.deficit.is_none() || self.spent {
            return Ok(true);
        }
        let mut byte = [0u8; 1];
        match self.read(&mut byte).await? {
            Some(_) => {
                self.first = Some(byte[0]);
                Ok(true)
            }
            None => Ok(false),
        }
    }

    pub(crate) async fn read(&mut self, buf: &mut [u8]) -> Result<Option<usize>, Error> {
        if let Some(slot) = buf.first_mut()
            && let Some(byte) = self.first.take()
        {
            *slot = byte;
            return Ok(Some(1));
        }
        let Some(io) = self.io.as_mut() else {
            return Ok(None);
        };
        let read = io.read(buf).await.map_err(S::read_error)?;
        if read > 0 {
            self.spend();
        }
        Ok((read > 0).then_some(read))
    }

    /// Refuses the rest of the payload.
    pub(crate) fn stop(&mut self, code: u64) {
        if let Some(io) = self.io.take() {
            S::stop(io, code, std::mem::take(&mut self.claims));
        }
    }
}

impl<S: Stream> Drop for LocalRecv<S> {
    /// A parked connection that dies without ever carrying a copy still has
    /// to be replaced, or the pool shrinks silently. A reader that walks away
    /// mid-payload refuses the rest of it, except the control connection's,
    /// which is watched until the peer's end goes away.
    fn drop(&mut self) {
        self.spend();
        if let Some(io) = self.io.take() {
            match self.watch.take() {
                Some(watch) => watch.spawn(io),
                None => S::stop(io, codes::CANCELED, std::mem::take(&mut self.claims)),
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::pin::Pin;
    use std::task::{Context, Poll};
    use tokio::io::{DuplexStream, ReadBuf, ReadHalf, WriteHalf};
    use weida_core::LocalPrincipal;

    use crate::chunked::{ChunkReader, ChunkWriter, Marker};

    /// The principal every in-memory connection reports.
    const PEER: LocalPrincipal = LocalPrincipal {
        uid: 1000,
        gid: 1000,
        pid: Some(4242),
    };

    /// What a raw write is shown to before it reaches the other end.
    type WriteHook = Box<dyn FnMut(&[u8]) + Send>;

    /// A local connection in memory: one end of a `tokio::io::duplex`, with
    /// the chunk framing of the socket transports on its halves. `on_write`
    /// sees every raw write before the other end can read it, which is how a
    /// test looks at the state the moment bytes go out.
    struct Mem {
        io: DuplexStream,
        exec: Exec,
        on_write: Option<WriteHook>,
    }

    impl Mem {
        fn new(io: DuplexStream) -> Mem {
            Mem {
                io,
                exec: Exec::current().expect("a tokio runtime"),
                on_write: None,
            }
        }
    }

    /// Where an in-memory dial lands: the accepting side's queue.
    struct MemEndpoint {
        accept: mpsc::UnboundedSender<Mem>,
    }

    impl AsyncRead for Mem {
        fn poll_read(
            self: Pin<&mut Self>,
            cx: &mut Context<'_>,
            buf: &mut ReadBuf<'_>,
        ) -> Poll<std::io::Result<()>> {
            Pin::new(&mut self.get_mut().io).poll_read(cx, buf)
        }
    }

    impl AsyncWrite for Mem {
        fn poll_write(
            self: Pin<&mut Self>,
            cx: &mut Context<'_>,
            buf: &[u8],
        ) -> Poll<std::io::Result<usize>> {
            let this = self.get_mut();
            if let Some(hook) = this.on_write.as_mut() {
                hook(buf);
            }
            Pin::new(&mut this.io).poll_write(cx, buf)
        }

        fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
            Pin::new(&mut self.get_mut().io).poll_flush(cx)
        }

        fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
            Pin::new(&mut self.get_mut().io).poll_shutdown(cx)
        }
    }

    impl Stream for Mem {
        type Endpoint = MemEndpoint;
        type Principal = LocalPrincipal;
        type Writer = ChunkWriter<WriteHalf<DuplexStream>>;
        type Reader = ChunkReader<ReadHalf<DuplexStream>>;

        async fn connect(endpoint: &MemEndpoint) -> Result<Mem, Error> {
            let (ours, theirs) = tokio::io::duplex(64 * 1024);
            endpoint
                .accept
                .send(Mem::new(theirs))
                .map_err(|_| Error::ConnectionLost(LossCause::PeerClosed))?;
            Ok(Mem::new(ours))
        }

        fn principal(&self) -> Result<LocalPrincipal, Error> {
            Ok(PEER)
        }

        fn split(self) -> (Self::Reader, Self::Writer) {
            let (recv, send) = tokio::io::split(self.io);
            (
                ChunkReader::new(recv, self.exec.clone()),
                ChunkWriter::new(send, self.exec),
            )
        }

        fn same_peer(group: &LocalPrincipal, asking: &LocalPrincipal) -> bool {
            group == asking
        }

        fn identity(principal: &LocalPrincipal) -> PeerIdentity {
            PeerIdentity::Local(*principal)
        }

        fn finish(writer: Self::Writer, claims: Claims) {
            writer.end(Marker::Fin, claims);
        }

        fn reset(writer: Self::Writer, code: u64, claims: Claims) {
            writer.end(Marker::Reset(code), claims);
        }

        fn stop(reader: Self::Reader, _code: u64, claims: Claims) {
            reader.drain(claims);
        }

        fn read_error(error: std::io::Error) -> Error {
            crate::chunked::read_error(error)
        }
    }

    /// A place of a binding's `max_connections`, for an admitted connection.
    fn place() -> Place {
        Arc::new(Semaphore::new(1))
            .try_acquire_owned()
            .expect("a free place")
    }

    /// The peer dials its transfer connections the moment it reads the
    /// token, and the accept loop may admit one on another thread before the
    /// control task runs again: a token that went out before its group was
    /// registered refused that transfer, and the sender, whose bytes the
    /// kernel had already taken, reported it delivered.
    #[tokio::test]
    async fn a_token_names_its_group_before_the_peer_can_read_it() {
        let groups = Arc::new(Groups::<Mem>::default());
        let (mut dialler, accepted) = tokio::io::duplex(1024);
        let mut accepted = Mem::new(accepted);
        let registered = Arc::new(StdMutex::new(Vec::new()));
        accepted.on_write = Some({
            let groups = Arc::clone(&groups);
            let registered = Arc::clone(&registered);
            Box::new(move |bytes: &[u8]| {
                let token: [u8; TOKEN_LEN] = bytes.try_into().expect("the token in one write");
                registered
                    .lock()
                    .expect("poisoned")
                    .push(groups.live(&token).is_some());
            })
        });
        let link = accept_control(
            accepted,
            PEER,
            Arc::clone(&groups),
            8,
            8,
            Exec::current().expect("a tokio runtime"),
            None,
        )
        .await
        .expect("accepted");
        assert_eq!(*registered.lock().expect("poisoned"), [true]);

        // A transfer connection with the token the peer read joins the link.
        let mut token = [0u8; TOKEN_LEN];
        dialler.read_exact(&mut token).await.expect("the token");
        let (_transfer, admitted) = tokio::io::duplex(1024);
        assert!(admit_transfer(
            &groups,
            &token,
            &PEER,
            Mem::new(admitted),
            place()
        ));
        drop(link);
    }

    /// An accept that ends before its token went out, cancelled or failed,
    /// leaves no group behind: nothing could ever close it.
    #[tokio::test]
    async fn an_accept_cut_short_leaves_no_group() {
        let groups = Arc::new(Groups::<Mem>::default());
        // Room for one octet of the token, and a peer that never reads.
        let (_dialler, accepted) = tokio::io::duplex(1);
        let mut accepting = Box::pin(accept_control(
            Mem::new(accepted),
            PEER,
            Arc::clone(&groups),
            8,
            8,
            Exec::current().expect("a tokio runtime"),
            None,
        ));
        let polled =
            std::future::poll_fn(|cx| Poll::Ready(accepting.as_mut().poll(cx).is_pending())).await;
        assert!(polled, "the token does not fit");
        assert_eq!(groups.entries.lock().expect("poisoned").len(), 1);
        drop(accepting);
        assert!(groups.entries.lock().expect("poisoned").is_empty());
    }

    /// The live count is a semaphore, and tokio refuses one larger than its
    /// platform's ceiling with a panic: on a 32-bit target the first local
    /// control connection would have taken its accept task down. The settle
    /// check of a link whose peer left compares against the same constant.
    #[test]
    fn the_live_count_fits_the_platforms_semaphore() {
        const _: () = assert!(LIVE_CAP <= Semaphore::MAX_PERMITS);
        let live = Semaphore::new(LIVE_CAP);
        assert_eq!(live.available_permits(), LIVE_CAP);
        let transfer = live.try_acquire().expect("a permit for a transfer");
        assert_ne!(
            live.available_permits(),
            LIVE_CAP,
            "a live transfer is visible"
        );
        drop(transfer);
        assert_eq!(live.available_permits(), LIVE_CAP, "and gone once it ends");
    }
}