raknet-rust 0.2.0

Asynchronous, high-performance RakNet transport library for Rust.
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
use std::io;
use std::net::SocketAddr;
use std::time::{Duration, Instant};

use bytes::Bytes;
use raknet_rust::client::{ClientSendOptions, RaknetClient, RaknetClientEvent};
use raknet_rust::low_level::protocol::reliability::Reliability;
use raknet_rust::low_level::session::RakPriority;
use raknet_rust::low_level::transport::EventOverflowPolicy;
use raknet_rust::proxy::{
    PassthroughRelayPolicy, RaknetRelayProxy, RaknetRelayProxyEvent, RelayContract,
    RelayContractConfig, RelayDecision, RelayDirection, RelayDropReason, RelayOverflowPolicy,
    RelayPolicy, RelayRuntimeConfig, RelaySessionCloseReason, UpstreamConnector,
    UpstreamConnectorConfig,
};
use raknet_rust::server::{PeerId, RaknetServer, RaknetServerEvent, SendOptions};
use tokio::time::timeout;

fn allocate_loopback_bind_addr() -> SocketAddr {
    let socket = std::net::UdpSocket::bind(SocketAddr::from(([127, 0, 0, 1], 0)))
        .expect("ephemeral loopback bind must succeed");
    socket
        .local_addr()
        .expect("ephemeral local addr must be available")
}

async fn start_server(bind_addr: SocketAddr) -> io::Result<RaknetServer> {
    let mut builder = RaknetServer::builder().bind_addr(bind_addr).shard_count(1);

    {
        let transport = builder.transport_config_mut();
        transport.per_ip_packet_limit = 100_000;
        transport.global_packet_limit = 1_000_000;
    }

    {
        let runtime = builder.runtime_config_mut();
        runtime.event_queue_capacity = 4096;
        runtime.metrics_emit_interval = Duration::from_secs(3600);
        runtime.outbound_tick_interval = Duration::from_millis(5);
        runtime.event_overflow_policy = EventOverflowPolicy::ShedNonCritical;
    }

    builder.start().await
}

async fn wait_for_client_connected(client: &mut RaknetClient) {
    let deadline = Instant::now() + Duration::from_secs(3);
    while Instant::now() < deadline {
        let event = timeout(Duration::from_secs(3), client.next_event())
            .await
            .expect("timed out waiting for client event")
            .expect("client event stream unexpectedly ended");

        if matches!(event, RaknetClientEvent::Connected { .. }) {
            return;
        }
    }

    panic!("timed out waiting for client connected event");
}

async fn wait_for_proxy_session_started<P>(
    proxy: &mut RaknetRelayProxy<P>,
) -> (PeerId, SocketAddr, SocketAddr)
where
    P: RelayPolicy,
{
    let deadline = Instant::now() + Duration::from_secs(4);
    while Instant::now() < deadline {
        let event = timeout(Duration::from_secs(1), proxy.next_event())
            .await
            .expect("timed out waiting for proxy session started event")
            .expect("proxy event stream unexpectedly ended");

        if let RaknetRelayProxyEvent::SessionStarted {
            peer_id,
            downstream_addr,
            upstream_addr,
        } = event
        {
            return (peer_id, downstream_addr, upstream_addr);
        }
    }

    panic!("timed out waiting for proxy SessionStarted event");
}

async fn collect_session_closed_reasons<P>(
    proxy: &mut RaknetRelayProxy<P>,
    peer_id: PeerId,
    budget: Duration,
) -> Vec<RelaySessionCloseReason>
where
    P: RelayPolicy,
{
    let deadline = Instant::now() + budget;
    let mut reasons = Vec::new();
    while Instant::now() < deadline {
        if let Ok(Some(RaknetRelayProxyEvent::SessionClosed {
            peer_id: closed_peer_id,
            reason,
        })) = timeout(Duration::from_millis(30), proxy.next_event()).await
            && closed_peer_id == peer_id
        {
            reasons.push(reason);
        }
    }

    reasons
}

async fn wait_for_upstream_packet<P>(
    proxy: &mut RaknetRelayProxy<P>,
    upstream: &mut RaknetServer,
) -> (u64, Bytes)
where
    P: RelayPolicy,
{
    let deadline = Instant::now() + Duration::from_secs(4);
    while Instant::now() < deadline {
        if let Ok(Some(_proxy_event)) = timeout(Duration::from_millis(20), proxy.next_event()).await
        {
        }

        if let Ok(Some(server_event)) =
            timeout(Duration::from_millis(20), upstream.next_event()).await
        {
            match server_event {
                RaknetServerEvent::Packet {
                    peer_id, payload, ..
                } => return (peer_id.as_u64(), payload),
                RaknetServerEvent::Metrics { .. } => {}
                _ => {}
            }
        }
    }

    panic!("timed out waiting for upstream packet");
}

async fn wait_for_upstream_packet_with_metadata<P>(
    proxy: &mut RaknetRelayProxy<P>,
    upstream: &mut RaknetServer,
) -> (u64, Bytes, Reliability, Option<u8>)
where
    P: RelayPolicy,
{
    let deadline = Instant::now() + Duration::from_secs(4);
    while Instant::now() < deadline {
        if let Ok(Some(_proxy_event)) = timeout(Duration::from_millis(20), proxy.next_event()).await
        {
        }

        if let Ok(Some(server_event)) =
            timeout(Duration::from_millis(20), upstream.next_event()).await
        {
            match server_event {
                RaknetServerEvent::Packet {
                    peer_id,
                    payload,
                    reliability,
                    ordering_channel,
                    ..
                } => return (peer_id.as_u64(), payload, reliability, ordering_channel),
                RaknetServerEvent::Metrics { .. } => {}
                _ => {}
            }
        }
    }

    panic!("timed out waiting for upstream packet");
}

async fn wait_for_client_payload_through_proxy<P>(
    proxy: &mut RaknetRelayProxy<P>,
    client: &mut RaknetClient,
) -> Bytes
where
    P: RelayPolicy,
{
    let deadline = Instant::now() + Duration::from_secs(4);
    while Instant::now() < deadline {
        if let Ok(Some(_proxy_event)) = timeout(Duration::from_millis(20), proxy.next_event()).await
        {
        }

        if let Ok(Some(client_event)) =
            timeout(Duration::from_millis(20), client.next_event()).await
        {
            match client_event {
                RaknetClientEvent::Packet { payload, .. } => return payload,
                RaknetClientEvent::Disconnected { reason } => {
                    panic!("client disconnected unexpectedly while waiting for payload: {reason:?}")
                }
                RaknetClientEvent::Connected { .. }
                | RaknetClientEvent::ReceiptAcked { .. }
                | RaknetClientEvent::DecodeError { .. } => {}
            }
        }
    }

    panic!("timed out waiting for client payload through proxy");
}

#[tokio::test(flavor = "current_thread")]
async fn proxy_forwards_bidirectionally_between_downstream_and_upstream() -> io::Result<()> {
    let upstream_addr = allocate_loopback_bind_addr();
    let downstream_addr = allocate_loopback_bind_addr();

    let mut upstream = start_server(upstream_addr).await?;
    let downstream = start_server(downstream_addr).await?;

    let connector = UpstreamConnector::new(upstream_addr, UpstreamConnectorConfig::default());
    let contract = RelayContract::new(RelayContractConfig::default(), PassthroughRelayPolicy);
    let mut proxy = RaknetRelayProxy::new(
        downstream,
        connector,
        contract,
        RelayRuntimeConfig::default(),
    );

    let mut client = RaknetClient::connect(downstream_addr).await?;
    wait_for_client_connected(&mut client).await;
    let _ = wait_for_proxy_session_started(&mut proxy).await;

    let down_payload = Bytes::from_static(b"\xFEproxy-d2u");
    client.send(down_payload.clone()).await?;

    let (upstream_peer_id_raw, got_upstream_payload) =
        wait_for_upstream_packet(&mut proxy, &mut upstream).await;
    assert_eq!(got_upstream_payload, down_payload);

    let upstream_peer_id = raknet_rust::server::PeerId::from_u64(upstream_peer_id_raw);
    let up_payload = Bytes::from_static(b"\xFEproxy-u2d");
    upstream.send(upstream_peer_id, up_payload.clone()).await?;

    let got_client_payload = wait_for_client_payload_through_proxy(&mut proxy, &mut client).await;
    assert_eq!(got_client_payload, up_payload);

    client.disconnect(None).await?;
    proxy.shutdown().await?;
    upstream.shutdown().await
}

#[tokio::test(flavor = "current_thread")]
async fn proxy_preserves_packet_reliability_and_channel_across_both_directions() -> io::Result<()> {
    let upstream_addr = allocate_loopback_bind_addr();
    let downstream_addr = allocate_loopback_bind_addr();

    let mut upstream = start_server(upstream_addr).await?;
    let downstream = start_server(downstream_addr).await?;

    let connector = UpstreamConnector::new(upstream_addr, UpstreamConnectorConfig::default());
    let contract = RelayContract::new(RelayContractConfig::default(), PassthroughRelayPolicy);
    let mut proxy = RaknetRelayProxy::new(
        downstream,
        connector,
        contract,
        RelayRuntimeConfig::default(),
    );

    let mut client = RaknetClient::connect(downstream_addr).await?;
    wait_for_client_connected(&mut client).await;
    let _ = wait_for_proxy_session_started(&mut proxy).await;

    let down_payload = Bytes::from_static(b"\xFEproxy-meta-d2u");
    let down_options = ClientSendOptions {
        reliability: Reliability::ReliableOrdered,
        channel: 5,
        priority: RakPriority::High,
    };
    client
        .send_with_options(down_payload.clone(), down_options)
        .await?;

    let (upstream_peer_id_raw, got_upstream_payload, got_reliability, got_channel) =
        wait_for_upstream_packet_with_metadata(&mut proxy, &mut upstream).await;
    assert_eq!(got_upstream_payload, down_payload);
    assert_eq!(got_reliability, down_options.reliability);
    assert_eq!(got_channel, Some(down_options.channel));

    let upstream_peer_id = PeerId::from_u64(upstream_peer_id_raw);
    let up_payload = Bytes::from_static(b"\xFEproxy-meta-u2d");
    let up_options = SendOptions {
        reliability: Reliability::ReliableOrdered,
        channel: 7,
        priority: RakPriority::High,
    };
    upstream
        .send_with_options(upstream_peer_id, up_payload.clone(), up_options)
        .await?;

    let deadline = Instant::now() + Duration::from_secs(4);
    while Instant::now() < deadline {
        if let Ok(Some(_proxy_event)) = timeout(Duration::from_millis(20), proxy.next_event()).await
        {
        }

        if let Ok(Some(client_event)) =
            timeout(Duration::from_millis(20), client.next_event()).await
        {
            match client_event {
                RaknetClientEvent::Packet {
                    payload,
                    reliability,
                    ordering_channel,
                    ..
                } => {
                    assert_eq!(payload, up_payload);
                    assert_eq!(reliability, up_options.reliability);
                    assert_eq!(ordering_channel, Some(up_options.channel));
                    client.disconnect(None).await?;
                    proxy.shutdown().await?;
                    return upstream.shutdown().await;
                }
                RaknetClientEvent::Disconnected { reason } => {
                    panic!(
                        "client disconnected unexpectedly while waiting for metadata packet: {reason:?}"
                    )
                }
                RaknetClientEvent::Connected { .. }
                | RaknetClientEvent::ReceiptAcked { .. }
                | RaknetClientEvent::DecodeError { .. } => {}
            }
        }
    }

    panic!("timed out waiting for client metadata packet")
}

#[derive(Debug, Clone, Copy)]
struct DropDownstreamPolicy;

impl RelayPolicy for DropDownstreamPolicy {
    fn decide(&self, direction: RelayDirection, payload: &Bytes) -> RelayDecision {
        if matches!(direction, RelayDirection::DownstreamToUpstream) {
            RelayDecision::Drop
        } else {
            RelayDecision::Forward(payload.clone())
        }
    }
}

#[tokio::test(flavor = "current_thread")]
async fn proxy_policy_can_drop_downstream_payloads_before_upstream() -> io::Result<()> {
    let upstream_addr = allocate_loopback_bind_addr();
    let downstream_addr = allocate_loopback_bind_addr();

    let mut upstream = start_server(upstream_addr).await?;
    let downstream = start_server(downstream_addr).await?;

    let connector = UpstreamConnector::new(upstream_addr, UpstreamConnectorConfig::default());
    let contract = RelayContract::new(RelayContractConfig::default(), DropDownstreamPolicy);
    let mut proxy = RaknetRelayProxy::new(
        downstream,
        connector,
        contract,
        RelayRuntimeConfig::default(),
    );

    let mut client = RaknetClient::connect(downstream_addr).await?;
    wait_for_client_connected(&mut client).await;
    let _ = wait_for_proxy_session_started(&mut proxy).await;

    client.send(Bytes::from_static(b"\xFEdropped")).await?;

    let deadline = Instant::now() + Duration::from_secs(2);
    let mut saw_upstream_packet = false;
    let mut saw_drop_event = false;

    while Instant::now() < deadline {
        if let Ok(Some(RaknetRelayProxyEvent::Dropped {
            direction: RelayDirection::DownstreamToUpstream,
            ..
        })) = timeout(Duration::from_millis(20), proxy.next_event()).await
        {
            saw_drop_event = true;
        }

        if let Ok(Some(server_event)) =
            timeout(Duration::from_millis(20), upstream.next_event()).await
        {
            match server_event {
                RaknetServerEvent::Packet { .. } => {
                    saw_upstream_packet = true;
                    break;
                }
                RaknetServerEvent::Metrics { .. } => {}
                _ => {}
            }
        }
    }

    assert!(
        !saw_upstream_packet,
        "upstream must not receive dropped payload"
    );
    assert!(
        saw_drop_event,
        "proxy should emit dropped event for policy drop"
    );

    client.disconnect(None).await?;
    proxy.shutdown().await?;
    upstream.shutdown().await
}

#[derive(Debug, Clone, Copy)]
struct DisconnectDownstreamPolicy;

impl RelayPolicy for DisconnectDownstreamPolicy {
    fn decide(&self, direction: RelayDirection, payload: &Bytes) -> RelayDecision {
        if matches!(direction, RelayDirection::DownstreamToUpstream) {
            RelayDecision::Disconnect {
                reason: "blocked_by_policy",
            }
        } else {
            RelayDecision::Forward(payload.clone())
        }
    }
}

#[tokio::test(flavor = "current_thread")]
async fn proxy_policy_disconnect_closes_downstream_session() -> io::Result<()> {
    let upstream_addr = allocate_loopback_bind_addr();
    let downstream_addr = allocate_loopback_bind_addr();

    let upstream = start_server(upstream_addr).await?;
    let downstream = start_server(downstream_addr).await?;

    let connector = UpstreamConnector::new(upstream_addr, UpstreamConnectorConfig::default());
    let contract = RelayContract::new(RelayContractConfig::default(), DisconnectDownstreamPolicy);
    let mut proxy = RaknetRelayProxy::new(
        downstream,
        connector,
        contract,
        RelayRuntimeConfig::default(),
    );

    let mut client = RaknetClient::connect(downstream_addr).await?;
    wait_for_client_connected(&mut client).await;
    let (session_peer_id, _, _) = wait_for_proxy_session_started(&mut proxy).await;

    client
        .send(Bytes::from_static(b"\xFEdisconnect-me"))
        .await?;

    let deadline = Instant::now() + Duration::from_secs(4);
    let mut saw_policy_disconnect = false;
    let mut saw_client_disconnect = false;

    while Instant::now() < deadline {
        if let Ok(Some(RaknetRelayProxyEvent::SessionClosed {
            reason:
                RelaySessionCloseReason::PolicyDisconnect {
                    direction: RelayDirection::DownstreamToUpstream,
                    reason: "blocked_by_policy",
                },
            ..
        })) = timeout(Duration::from_millis(20), proxy.next_event()).await
        {
            saw_policy_disconnect = true;
        }

        if let Ok(Some(RaknetClientEvent::Disconnected { .. })) =
            timeout(Duration::from_millis(20), client.next_event()).await
        {
            saw_client_disconnect = true;
            break;
        }
    }

    assert!(
        saw_policy_disconnect,
        "proxy should close session with policy disconnect reason"
    );
    assert_eq!(
        proxy.session_count(),
        0,
        "proxy session must be torn down after policy disconnect"
    );

    if !saw_client_disconnect {
        let _ = client.disconnect(None).await;
    }

    let close_reasons =
        collect_session_closed_reasons(&mut proxy, session_peer_id, Duration::from_millis(300))
            .await;
    assert!(
        close_reasons.is_empty(),
        "session should not emit duplicate close after initial policy close"
    );

    proxy.shutdown().await?;
    upstream.shutdown().await
}

#[tokio::test(flavor = "current_thread")]
async fn proxy_simultaneous_upstream_and_downstream_disconnect_emits_single_close() -> io::Result<()>
{
    let upstream_addr = allocate_loopback_bind_addr();
    let downstream_addr = allocate_loopback_bind_addr();

    let mut upstream = start_server(upstream_addr).await?;
    let downstream = start_server(downstream_addr).await?;

    let connector = UpstreamConnector::new(upstream_addr, UpstreamConnectorConfig::default());
    let contract = RelayContract::new(RelayContractConfig::default(), PassthroughRelayPolicy);
    let mut proxy = RaknetRelayProxy::new(
        downstream,
        connector,
        contract,
        RelayRuntimeConfig::default(),
    );

    let mut client = RaknetClient::connect(downstream_addr).await?;
    wait_for_client_connected(&mut client).await;
    let (session_peer_id, _, _) = wait_for_proxy_session_started(&mut proxy).await;

    client.send(Bytes::from_static(b"\xFErace-init")).await?;
    let (upstream_peer_raw, _) = wait_for_upstream_packet(&mut proxy, &mut upstream).await;
    let upstream_peer_id = PeerId::from_u64(upstream_peer_raw);

    let (client_disconnect_result, upstream_disconnect_result) = tokio::join!(
        client.disconnect(None),
        upstream.disconnect(upstream_peer_id)
    );
    let _ = client_disconnect_result;
    let _ = upstream_disconnect_result;

    let close_reasons =
        collect_session_closed_reasons(&mut proxy, session_peer_id, Duration::from_secs(2)).await;
    assert_eq!(
        close_reasons.len(),
        1,
        "disconnect race must emit exactly one SessionClosed for the same session"
    );
    assert_eq!(
        proxy.session_count(),
        0,
        "proxy must not leak session after disconnect race"
    );

    proxy.shutdown().await?;
    upstream.shutdown().await
}

#[tokio::test(flavor = "current_thread")]
async fn proxy_shutdown_terminates_active_session_without_hanging() -> io::Result<()> {
    let upstream_addr = allocate_loopback_bind_addr();
    let downstream_addr = allocate_loopback_bind_addr();

    let upstream = start_server(upstream_addr).await?;
    let downstream = start_server(downstream_addr).await?;

    let connector = UpstreamConnector::new(upstream_addr, UpstreamConnectorConfig::default());
    let contract = RelayContract::new(RelayContractConfig::default(), PassthroughRelayPolicy);
    let proxy = RaknetRelayProxy::new(
        downstream,
        connector,
        contract,
        RelayRuntimeConfig::default(),
    );

    let mut client = RaknetClient::connect(downstream_addr).await?;
    wait_for_client_connected(&mut client).await;

    let mut proxy = proxy;
    let _ = wait_for_proxy_session_started(&mut proxy).await;
    assert_eq!(
        proxy.session_count(),
        1,
        "proxy should hold one active session"
    );

    timeout(Duration::from_secs(2), proxy.shutdown())
        .await
        .expect("proxy shutdown timed out")?;
    let _ = client.disconnect(None).await;
    upstream.shutdown().await
}

#[tokio::test(flavor = "current_thread")]
async fn proxy_budget_overflow_drop_newest_drops_packet_without_closing_session() -> io::Result<()>
{
    let upstream_addr = allocate_loopback_bind_addr();
    let downstream_addr = allocate_loopback_bind_addr();

    let mut upstream = start_server(upstream_addr).await?;
    let downstream = start_server(downstream_addr).await?;

    let connector = UpstreamConnector::new(upstream_addr, UpstreamConnectorConfig::default());
    let contract = RelayContract::new(RelayContractConfig::default(), PassthroughRelayPolicy);
    let runtime = RelayRuntimeConfig {
        budget_overflow_policy: RelayOverflowPolicy::DropNewest,
        downstream_max_pending_packets: 1,
        downstream_max_pending_bytes: 1,
        session_total_max_pending_bytes: 1,
        ..RelayRuntimeConfig::default()
    };
    let mut proxy = RaknetRelayProxy::new(downstream, connector, contract, runtime);

    let mut client = RaknetClient::connect(downstream_addr).await?;
    wait_for_client_connected(&mut client).await;
    let _ = wait_for_proxy_session_started(&mut proxy).await;

    client.send(Bytes::from_static(b"\xFEbudget")).await?;

    let deadline = Instant::now() + Duration::from_secs(3);
    let mut saw_budget_drop = false;
    let mut saw_upstream_packet = false;
    while Instant::now() < deadline {
        if let Ok(Some(RaknetRelayProxyEvent::Dropped {
            direction: RelayDirection::DownstreamToUpstream,
            reason: RelayDropReason::BudgetExceeded(_),
            ..
        })) = timeout(Duration::from_millis(20), proxy.next_event()).await
        {
            saw_budget_drop = true;
        }

        if let Ok(Some(RaknetServerEvent::Packet { .. })) =
            timeout(Duration::from_millis(20), upstream.next_event()).await
        {
            saw_upstream_packet = true;
            break;
        }
    }

    assert!(saw_budget_drop, "expected budget-based drop event");
    assert!(
        !saw_upstream_packet,
        "budget dropped packet must not reach upstream"
    );
    assert_eq!(
        proxy.session_count(),
        1,
        "drop policy should keep session alive"
    );

    let _ = client.disconnect(None).await;
    proxy.shutdown().await?;
    upstream.shutdown().await
}

#[tokio::test(flavor = "current_thread")]
async fn proxy_budget_overflow_disconnect_closes_session() -> io::Result<()> {
    let upstream_addr = allocate_loopback_bind_addr();
    let downstream_addr = allocate_loopback_bind_addr();

    let upstream = start_server(upstream_addr).await?;
    let downstream = start_server(downstream_addr).await?;

    let connector = UpstreamConnector::new(upstream_addr, UpstreamConnectorConfig::default());
    let contract = RelayContract::new(RelayContractConfig::default(), PassthroughRelayPolicy);
    let runtime = RelayRuntimeConfig {
        budget_overflow_policy: RelayOverflowPolicy::DisconnectSession,
        downstream_max_pending_packets: 1,
        downstream_max_pending_bytes: 1,
        session_total_max_pending_bytes: 1,
        ..RelayRuntimeConfig::default()
    };
    let mut proxy = RaknetRelayProxy::new(downstream, connector, contract, runtime);

    let mut client = RaknetClient::connect(downstream_addr).await?;
    wait_for_client_connected(&mut client).await;
    let (session_peer_id, _, _) = wait_for_proxy_session_started(&mut proxy).await;

    client.send(Bytes::from_static(b"\xFEbudget")).await?;

    let deadline = Instant::now() + Duration::from_secs(3);
    let mut saw_budget_close = false;
    while Instant::now() < deadline {
        if let Ok(Some(RaknetRelayProxyEvent::SessionClosed {
            peer_id,
            reason:
                RelaySessionCloseReason::BudgetExceeded {
                    direction: RelayDirection::DownstreamToUpstream,
                    ..
                },
        })) = timeout(Duration::from_millis(20), proxy.next_event()).await
            && peer_id == session_peer_id
        {
            saw_budget_close = true;
            break;
        }
    }

    assert!(saw_budget_close, "expected budget-based session close");
    assert_eq!(
        proxy.session_count(),
        0,
        "disconnect budget policy must close session"
    );

    let _ = client.disconnect(None).await;
    proxy.shutdown().await?;
    upstream.shutdown().await
}