shoes 0.3.2

A multi-protocol proxy server.
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
use std::cell::RefCell;
use std::io::{self, IoSliceMut};
use std::net::SocketAddr;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};

use crate::resources::BudgetPermit;
use quinn::{AsyncUdpSocket, Runtime, UdpPoller};

tokio::task_local! {
    static CONNECTION_MEMORY: RefCell<Option<BudgetPermit>>;
}

/// Quinn replaces connection pollers on rebind, so this wrapper deliberately
/// exposes no rebinding API. Reload creates fresh endpoints instead.
#[derive(Debug)]
pub(crate) struct QuicEndpoint {
    inner: quinn::Endpoint,
    // Transport windows belong to this endpoint, not the latest config generation.
    memory_bytes: usize,
}

impl QuicEndpoint {
    pub fn new(
        config: Option<quinn::ServerConfig>,
        socket: std::net::UdpSocket,
        memory_bytes: usize,
    ) -> io::Result<Self> {
        let socket = MemorySocket {
            inner: quinn::TokioRuntime.wrap_udp_socket(socket)?,
            endpoint_memory: None,
        };
        quinn::Endpoint::new_with_abstract_socket(
            quinn::EndpointConfig::default(),
            config,
            Arc::new(socket),
            Arc::new(quinn::TokioRuntime),
        )
        .map(|inner| Self {
            inner,
            memory_bytes,
        })
    }

    pub fn set_default_client_config(&mut self, config: quinn::ClientConfig) {
        self.inner.set_default_client_config(config);
    }

    pub fn connect(&self, address: SocketAddr, name: &str) -> io::Result<quinn::Connecting> {
        let memory = crate::resources::try_quic_memory(self.memory_bytes)
            .ok_or_else(crate::resources::exhausted)?;
        self.connect_with_memory(address, name, memory)
    }

    fn connect_with_memory(
        &self,
        address: SocketAddr,
        name: &str,
        memory: BudgetPermit,
    ) -> io::Result<quinn::Connecting> {
        CONNECTION_MEMORY.sync_scope(RefCell::new(Some(memory)), || {
            self.inner.connect(address, name).map_err(io::Error::other)
        })
    }

    pub async fn accept(&self) -> Option<Incoming> {
        self.inner.accept().await.map(|inner| Incoming {
            inner,
            memory_bytes: self.memory_bytes,
        })
    }

    pub fn close(&self, code: quinn::VarInt, reason: &[u8]) {
        self.inner.close(code, reason);
    }

    #[cfg(test)]
    pub fn local_addr(&self) -> io::Result<SocketAddr> {
        self.inner.local_addr()
    }

    #[cfg(test)]
    async fn wait_idle(&self) {
        self.inner.wait_idle().await;
    }
}

pub(crate) struct Incoming {
    inner: quinn::Incoming,
    memory_bytes: usize,
}

impl Incoming {
    pub fn remote_address(&self) -> SocketAddr {
        self.inner.remote_address()
    }

    pub fn refuse(self) {
        self.inner.refuse();
    }

    pub fn accept(self) -> io::Result<quinn::Connecting> {
        let Some(memory) = crate::resources::try_quic_memory(self.memory_bytes) else {
            self.refuse();
            return Err(crate::resources::exhausted());
        };
        self.accept_with_memory(memory)
    }

    fn accept_with_memory(self, memory: BudgetPermit) -> io::Result<quinn::Connecting> {
        CONNECTION_MEMORY.sync_scope(RefCell::new(Some(memory)), || {
            self.inner.accept().map_err(io::Error::from)
        })
    }
}

/// For a dedicated single-connection endpoint, such as Hickory's H3 client.
/// Pooled endpoints must reserve each connection through QuicEndpoint instead.
pub(crate) fn socket_with_memory(
    socket: std::net::UdpSocket,
    memory: BudgetPermit,
) -> io::Result<Arc<dyn AsyncUdpSocket>> {
    Ok(Arc::new(MemorySocket {
        inner: quinn::TokioRuntime.wrap_udp_socket(socket)?,
        endpoint_memory: Some(memory),
    }))
}

#[derive(Debug)]
struct MemorySocket {
    inner: Arc<dyn AsyncUdpSocket>,
    endpoint_memory: Option<BudgetPermit>,
}

impl AsyncUdpSocket for MemorySocket {
    fn create_io_poller(self: Arc<Self>) -> Pin<Box<dyn UdpPoller>> {
        if self.endpoint_memory.is_some() {
            return self.inner.clone().create_io_poller();
        }
        // Quinn creates one poller synchronously inside connect/accept. Its State
        // drops protocol stream/datagram buffers before dropping this poller,
        // including when application handles survive driver completion.
        let memory = CONNECTION_MEMORY.with(|memory| {
            memory
                .borrow_mut()
                .take()
                .expect("QUIC memory reserved once per connection")
        });
        Box::pin(MemoryPoller {
            inner: self.inner.clone().create_io_poller(),
            _memory: memory,
        })
    }

    fn try_send(&self, transmit: &quinn::udp::Transmit<'_>) -> io::Result<()> {
        self.inner.try_send(transmit)
    }

    fn poll_recv(
        &self,
        cx: &mut Context<'_>,
        bufs: &mut [IoSliceMut<'_>],
        meta: &mut [quinn::udp::RecvMeta],
    ) -> Poll<io::Result<usize>> {
        self.inner.poll_recv(cx, bufs, meta)
    }

    fn local_addr(&self) -> io::Result<SocketAddr> {
        self.inner.local_addr()
    }

    fn max_transmit_segments(&self) -> usize {
        self.inner.max_transmit_segments()
    }

    fn max_receive_segments(&self) -> usize {
        self.inner.max_receive_segments()
    }

    fn may_fragment(&self) -> bool {
        self.inner.may_fragment()
    }
}

#[derive(Debug)]
struct MemoryPoller {
    inner: Pin<Box<dyn UdpPoller>>,
    _memory: BudgetPermit,
}

impl UdpPoller for MemoryPoller {
    fn poll_writable(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
        self.inner.as_mut().poll_writable(cx)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::atomic::{AtomicUsize, Ordering};
    use std::time::Duration;

    use crate::resources::Budget;
    use bytes::Bytes;
    use tokio::time::timeout;

    async fn wait_for_slot(budget: &Arc<Budget>) -> BudgetPermit {
        loop {
            if let Some(permit) = budget.acquire(1) {
                return permit;
            }
            tokio::time::sleep(Duration::from_millis(1)).await;
        }
    }

    fn configs() -> (quinn::ClientConfig, quinn::ServerConfig) {
        let cert = rcgen::generate_simple_self_signed(vec!["localhost".into()]).unwrap();
        let mut roots = rustls::RootCertStore::empty();
        roots.add(cert.cert.der().clone()).unwrap();
        let server_config = quinn::ServerConfig::with_single_cert(
            vec![cert.cert.der().clone()],
            rustls::pki_types::PrivatePkcs8KeyDer::from(cert.signing_key.serialize_der()).into(),
        )
        .unwrap();
        let client_config = quinn::ClientConfig::with_root_certificates(Arc::new(roots)).unwrap();
        (client_config, server_config)
    }

    fn endpoints() -> (QuicEndpoint, QuicEndpoint) {
        let (client_config, server_config) = configs();
        endpoints_with_configs(client_config, server_config, 1)
    }

    fn endpoints_with_configs(
        client_config: quinn::ClientConfig,
        server_config: quinn::ServerConfig,
        memory_bytes: usize,
    ) -> (QuicEndpoint, QuicEndpoint) {
        let server = QuicEndpoint::new(
            Some(server_config),
            std::net::UdpSocket::bind("0.0.0.0:0").unwrap(),
            memory_bytes,
        )
        .unwrap();
        let mut client = QuicEndpoint::new(
            None,
            std::net::UdpSocket::bind("0.0.0.0:0").unwrap(),
            memory_bytes,
        )
        .unwrap();
        client.set_default_client_config(client_config);
        (client, server)
    }

    #[tokio::test]
    async fn pending_handshake_backlog_does_not_limit_active_connections() {
        let (client_config, mut server_config) = configs();
        let memory_bytes = crate::resources::configure_quic(&mut server_config, 100, 0);
        let server = QuicEndpoint::new(
            Some(server_config),
            std::net::UdpSocket::bind("0.0.0.0:0").unwrap(),
            memory_bytes,
        )
        .unwrap();
        let mut client = quinn::Endpoint::client("0.0.0.0:0".parse().unwrap()).unwrap();
        client.set_default_client_config(client_config);
        let address = SocketAddr::from(([127, 0, 0, 1], server.local_addr().unwrap().port()));
        let mut pending = Vec::new();
        timeout(Duration::from_secs(5), async {
            for _ in 0..128 {
                let connecting = client.connect(address, "localhost").unwrap();
                let incoming = server.accept().await.unwrap();
                // Holding Incoming without accepting it keeps its transport backlog slot.
                pending.push((connecting, incoming));
            }
        })
        .await
        .unwrap();

        let extra = client.connect(address, "localhost").unwrap();
        assert!(
            timeout(Duration::from_secs(1), server.accept())
                .await
                .is_err(),
            "pending handshakes exceeded the transport backlog",
        );

        let mut active = Vec::new();
        timeout(Duration::from_secs(10), async {
            for (connecting, incoming) in pending {
                let (connected, accepted) = tokio::join!(connecting, incoming.accept().unwrap());
                active.push((connected.unwrap(), accepted.unwrap()));
            }
            let incoming = server.accept().await.unwrap();
            let (connected, accepted) = tokio::join!(extra, incoming.accept().unwrap());
            active.push((connected.unwrap(), accepted.unwrap()));
        })
        .await
        .unwrap();
        assert_eq!(active.len(), 129);
        for (connected, accepted) in [&active[0], active.last().unwrap()] {
            connected
                .send_datagram(Bytes::from_static(b"active"))
                .unwrap();
            assert_eq!(
                timeout(Duration::from_secs(5), accepted.read_datagram())
                    .await
                    .unwrap()
                    .unwrap(),
                b"active"[..],
            );
        }
        client.close(0u32.into(), b"done");
        server.close(0u32.into(), b"done");
        drop(active);
    }

    #[tokio::test]
    async fn endpoint_reservations_survive_window_reload() {
        use crate::config::GlobalLimits;

        if std::env::var_os("SHOES_QUIC_RELOAD_TEST_CHILD").is_none() {
            let status = std::process::Command::new(std::env::current_exe().unwrap())
                .args([
                    "--exact",
                    "quic_endpoint::tests::endpoint_reservations_survive_window_reload",
                    "--nocapture",
                ])
                .env("SHOES_QUIC_RELOAD_TEST_CHILD", "1")
                .status()
                .unwrap();
            assert!(status.success());
            return;
        }

        let configured_endpoints = || {
            let (mut client_config, mut server_config) = configs();
            let memory_bytes = crate::resources::configure_quic(&mut server_config, 100, 0);
            let mut transport = quinn::TransportConfig::default();
            assert_eq!(
                crate::resources::configure_quic_transport(&mut transport),
                memory_bytes,
            );
            client_config.transport_config(Arc::new(transport));
            endpoints_with_configs(client_config, server_config, memory_bytes)
        };
        crate::resources::configure(GlobalLimits::default()).unwrap();
        let (large_client, large_server) = configured_endpoints();
        crate::resources::configure(GlobalLimits {
            quic_memory_bytes: Some(1 << 20),
            quic_receive_window: 65536,
            quic_send_window: 65536,
            quic_stream_window: 16384,
            ..Default::default()
        })
        .unwrap();
        let (small_client, small_server) = configured_endpoints();
        let large_address =
            SocketAddr::from(([127, 0, 0, 1], large_server.local_addr().unwrap().port()));
        let small_address =
            SocketAddr::from(([127, 0, 0, 1], small_server.local_addr().unwrap().port()));
        assert_eq!(
            large_client
                .connect(small_address, "localhost")
                .err()
                .unwrap()
                .kind(),
            io::ErrorKind::ConnectionRefused,
        );
        let connecting = small_client.connect(large_address, "localhost").unwrap();
        let incoming = timeout(Duration::from_secs(5), large_server.accept())
            .await
            .unwrap()
            .unwrap();
        assert_eq!(
            incoming.accept().err().unwrap().kind(),
            io::ErrorKind::ConnectionRefused,
        );
        assert!(
            timeout(Duration::from_secs(5), connecting)
                .await
                .unwrap()
                .is_err()
        );
        timeout(Duration::from_secs(5), small_client.wait_idle())
            .await
            .unwrap();
        assert_eq!(crate::resources::snapshot().quic_buffer_bytes.active, 0);

        let small_reservation = 2 * 65536 + (512 << 10);
        crate::resources::configure(GlobalLimits {
            quic_memory_bytes: Some(2 * small_reservation),
            ..Default::default()
        })
        .unwrap();
        let (client, server) = timeout(Duration::from_secs(5), async {
            tokio::join!(
                async {
                    small_client
                        .connect(small_address, "localhost")
                        .unwrap()
                        .await
                        .unwrap()
                },
                async {
                    small_server
                        .accept()
                        .await
                        .unwrap()
                        .accept()
                        .unwrap()
                        .await
                        .unwrap()
                },
            )
        })
        .await
        .unwrap();
        assert_eq!(
            crate::resources::snapshot().quic_buffer_bytes.active,
            2 * small_reservation,
        );
        client.close(0u32.into(), b"done");
        drop((client, server));
        timeout(Duration::from_secs(5), async {
            tokio::join!(small_client.wait_idle(), small_server.wait_idle());
        })
        .await
        .unwrap();
        assert_eq!(crate::resources::snapshot().quic_buffer_bytes.active, 0);
    }

    async fn connect(
        client: &QuicEndpoint,
        server: &QuicEndpoint,
        client_budget: &Arc<Budget>,
        server_budget: &Arc<Budget>,
    ) -> (quinn::Connection, quinn::Connection) {
        let address = SocketAddr::from(([127, 0, 0, 1], server.local_addr().unwrap().port()));
        timeout(Duration::from_secs(5), async {
            tokio::join!(
                async {
                    client
                        .connect_with_memory(
                            address,
                            "localhost",
                            client_budget.acquire(1).unwrap(),
                        )
                        .unwrap()
                        .await
                        .unwrap()
                },
                async {
                    let incoming = server.accept().await.unwrap();
                    let connecting = incoming
                        .accept_with_memory(server_budget.acquire(1).unwrap())
                        .unwrap();
                    // Exercise TUIC's incoming 0.5-RTT path as well as ordinary clients.
                    connecting.into_0rtt().unwrap().0
                },
            )
        })
        .await
        .unwrap()
    }

    struct Payload {
        bytes: Vec<u8>,
        live: Arc<AtomicUsize>,
        budget: Arc<Budget>,
    }

    impl AsRef<[u8]> for Payload {
        fn as_ref(&self) -> &[u8] {
            &self.bytes
        }
    }

    impl Drop for Payload {
        fn drop(&mut self) {
            assert_eq!(
                self.budget.available_permits(),
                0,
                "payload outlived reservation"
            );
            self.live.fetch_sub(1, Ordering::SeqCst);
        }
    }

    fn payload(live: &Arc<AtomicUsize>, budget: &Arc<Budget>) -> Bytes {
        live.fetch_add(1, Ordering::SeqCst);
        Bytes::from_owner(Payload {
            bytes: vec![0; 1 << 20],
            live: live.clone(),
            budget: budget.clone(),
        })
    }

    #[tokio::test]
    async fn churn_reservations_cover_draining_without_waiting_for_other_connections() {
        let (client, server) = endpoints();
        let client_budget = Arc::new(Budget::new(Some(2)));
        let server_budget = Arc::new(Budget::new(Some(2)));
        let live = Arc::new(AtomicUsize::new(0));
        let (keeper, keeper_peer) = connect(&client, &server, &client_budget, &server_budget).await;
        for _ in 0..4 {
            let (connection, peer) =
                connect(&client, &server, &client_budget, &server_budget).await;
            let (mut send, recv) = connection.open_bi().await.unwrap();
            send.write_all(b"open").await.unwrap();
            let (mut peer_send, peer_recv) = peer.accept_bi().await.unwrap();
            send.write_chunk(payload(&live, &client_budget))
                .await
                .unwrap();
            peer_send
                .write_chunk(payload(&live, &server_budget))
                .await
                .unwrap();
            drop((connection, peer, send, recv, peer_send, peer_recv));
            assert_eq!(live.load(Ordering::SeqCst), 2);
            assert!(client_budget.acquire(1).is_none());
            assert!(server_budget.acquire(1).is_none());

            let client_slot = timeout(Duration::from_secs(5), wait_for_slot(&client_budget))
                .await
                .unwrap();
            let server_slot = timeout(Duration::from_secs(5), wait_for_slot(&server_budget))
                .await
                .unwrap();
            assert_eq!(live.load(Ordering::SeqCst), 0);
            drop((client_slot, server_slot));
            keeper
                .send_datagram(Bytes::from_static(b"still active"))
                .unwrap();
            assert_eq!(
                timeout(Duration::from_secs(1), keeper_peer.read_datagram())
                    .await
                    .unwrap()
                    .unwrap(),
                b"still active"[..],
            );
        }
        drop((keeper, keeper_peer));
        timeout(Duration::from_secs(5), client.wait_idle())
            .await
            .unwrap();
        timeout(Duration::from_secs(5), server.wait_idle())
            .await
            .unwrap();
        assert_eq!(client_budget.available_permits(), 2);
        assert_eq!(server_budget.available_permits(), 2);
    }

    #[tokio::test]
    async fn reservations_survive_driver_completion_until_last_stream_handle_drops() {
        let (client, server) = endpoints();
        let client_budget = Arc::new(Budget::new(Some(1)));
        let server_budget = Arc::new(Budget::new(Some(1)));
        let live = Arc::new(AtomicUsize::new(0));
        let (connection, peer) = connect(&client, &server, &client_budget, &server_budget).await;
        let (mut send, recv) = connection.open_bi().await.unwrap();
        send.write_chunk(payload(&live, &client_budget))
            .await
            .unwrap();
        connection.close(0u32.into(), b"closed with handles alive");
        timeout(Duration::from_secs(5), client.wait_idle())
            .await
            .unwrap();
        timeout(Duration::from_secs(5), server.wait_idle())
            .await
            .unwrap();
        assert_eq!(client_budget.available_permits(), 0);
        assert_eq!(server_budget.available_permits(), 0);
        assert_eq!(live.load(Ordering::SeqCst), 1);
        drop((connection, send));
        assert_eq!(client_budget.available_permits(), 0);
        drop(recv);
        assert_eq!(live.load(Ordering::SeqCst), 0);
        assert_eq!(client_budget.available_permits(), 1);
        drop(peer);
        assert_eq!(server_budget.available_permits(), 1);
    }

    #[tokio::test]
    async fn socket_reservation_survives_draining_and_retained_streams() {
        let (client_config, server_config) = configs();
        let budget = Arc::new(Budget::new(Some(1)));
        let socket = socket_with_memory(
            std::net::UdpSocket::bind("0.0.0.0:0").unwrap(),
            budget.acquire(1).unwrap(),
        )
        .unwrap();
        let mut client = quinn::Endpoint::new_with_abstract_socket(
            quinn::EndpointConfig::default(),
            None,
            socket,
            Arc::new(quinn::TokioRuntime),
        )
        .unwrap();
        client.set_default_client_config(client_config);
        let server = QuicEndpoint::new(
            Some(server_config),
            std::net::UdpSocket::bind("0.0.0.0:0").unwrap(),
            1,
        )
        .unwrap();
        let server_budget = Arc::new(Budget::new(Some(1)));
        let address = SocketAddr::from(([127, 0, 0, 1], server.local_addr().unwrap().port()));
        let (connection, peer) = timeout(Duration::from_secs(5), async {
            tokio::join!(
                async { client.connect(address, "localhost").unwrap().await.unwrap() },
                async {
                    server
                        .accept()
                        .await
                        .unwrap()
                        .accept_with_memory(server_budget.acquire(1).unwrap())
                        .unwrap()
                        .await
                        .unwrap()
                },
            )
        })
        .await
        .unwrap();
        let live = Arc::new(AtomicUsize::new(0));
        let (mut send, recv) = connection.open_bi().await.unwrap();
        send.write_chunk(payload(&live, &budget)).await.unwrap();
        connection.close(0u32.into(), b"closed with handles alive");
        assert_eq!(budget.available_permits(), 0);
        assert_eq!(live.load(Ordering::SeqCst), 1);
        timeout(Duration::from_secs(5), client.wait_idle())
            .await
            .unwrap();
        drop((client, connection, send));
        assert_eq!(budget.available_permits(), 0);
        assert_eq!(live.load(Ordering::SeqCst), 1);
        drop(recv);
        let _returned = timeout(Duration::from_secs(5), wait_for_slot(&budget))
            .await
            .unwrap();
        assert_eq!(live.load(Ordering::SeqCst), 0);
        drop(peer);
        timeout(Duration::from_secs(5), server.wait_idle())
            .await
            .unwrap();
        assert_eq!(server_budget.available_permits(), 1);
    }

    #[tokio::test]
    async fn failed_and_cancelled_handshakes_return_reservations() {
        let (client, _server) = endpoints();
        let budget = Arc::new(Budget::new(Some(1)));
        assert!(
            client
                .connect_with_memory(
                    "127.0.0.1:0".parse().unwrap(),
                    "localhost",
                    budget.acquire(1).unwrap(),
                )
                .is_err()
        );
        assert_eq!(budget.available_permits(), 1);
        let unreachable = std::net::UdpSocket::bind("0.0.0.0:0").unwrap();
        let address = SocketAddr::from(([127, 0, 0, 1], unreachable.local_addr().unwrap().port()));
        let connecting = client
            .connect_with_memory(address, "localhost", budget.acquire(1).unwrap())
            .unwrap();
        drop(connecting);
        assert_eq!(budget.available_permits(), 0);
        timeout(Duration::from_secs(5), client.wait_idle())
            .await
            .unwrap();
        assert_eq!(budget.available_permits(), 1);
    }
}