unb-server 2.0.3

unb inbound server: Node, request/subscribe handlers, catalog, relay orchestration, accept
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
mod common;
use common::TestCall;

use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
use std::time::Duration;

use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use unb::{handler, Handler, HandlerError, Reply, Request};
use unb_core::ErrorCode;
use unb_server::{Endpoint, EndpointSet, Node, TransportKind};
use unb_server::{HostConfig, TcpTransport};

fn ws_endpoint(address: String) -> Endpoint {
    Endpoint {
        kind: TransportKind::WebSocket,
        address,
        cert_hash: None,
    }
}

#[derive(Deserialize, Serialize, JsonSchema)]
#[serde(transparent)]
struct EchoPayload(Value);

#[derive(Deserialize, JsonSchema)]
struct Doubling {
    n: i64,
}

#[derive(Deserialize, JsonSchema)]
struct Probe {}

#[handler]
async fn echo(request: Request<EchoPayload>) -> Result<Reply<Value>, HandlerError> {
    Ok(Reply::new(
        json!({ "served_by": request.subject(), "got": request.payload() }),
    ))
}

#[handler]
async fn double(request: Request<Doubling>) -> Result<Reply<Value>, HandlerError> {
    let n = request.payload().n;
    Ok(Reply::new(json!({ "n": n * 2 })))
}

#[handler]
async fn fail(_request: Request<Probe>) -> Result<Reply<Value>, HandlerError> {
    Err(HandlerError::new(ErrorCode::InvalidInput, "no such city"))
}

#[handler]
async fn plan(request: Request<Probe>) -> Result<Reply<Value>, HandlerError> {
    let outlook = request
        .call("/weather/forecast", json!({ "city": "hue" }))
        .await?;
    Ok(Reply::new(
        json!({ "plan": format!("{}C day", outlook["temp_c"]) }),
    ))
}

#[handler]
async fn forecast(_request: Request<Probe>) -> Result<Reply<Value>, HandlerError> {
    Ok(Reply::new(json!({ "temp_c": 21 })))
}

static NO_REPLAY_INVOCATIONS: AtomicUsize = AtomicUsize::new(0);

#[handler]
async fn no_replay_stall(_request: Request<Probe>) -> Result<Reply<Value>, HandlerError> {
    NO_REPLAY_INVOCATIONS.fetch_add(1, Ordering::SeqCst);
    std::future::pending::<()>().await;
    unreachable!("the original in-flight handler is cancelled with its failed session")
}

#[handler]
async fn no_replay_replacement(_request: Request<Probe>) -> Result<Reply<Value>, HandlerError> {
    let invocation = NO_REPLAY_INVOCATIONS.fetch_add(1, Ordering::SeqCst) + 1;
    Ok(Reply::new(json!({ "invocation": invocation })))
}

fn service(name: &str, subject: &'static str) -> std::sync::Arc<Node> {
    Node::builder(name)
        .service(echo.at_subject(subject))
        .insecure_accept_declared_peer_identities()
        .build()
        .unwrap()
}

#[tokio::test(flavor = "multi_thread")]
async fn a_local_request_executes_the_handler_directly() {
    let node = service("solo", "echo");
    let reply = node.request("/solo/echo", json!({ "n": 1 })).await.unwrap();
    assert_eq!(reply["served_by"], "echo");
    assert_eq!(reply["got"]["n"], 1);
}

#[tokio::test(flavor = "multi_thread")]
async fn linked_nodes_request_each_other_immediately_after_link_returns() {
    let a = service("node-a", "a.echo");
    let b = service("node-b", "b.echo");
    a.link(&b).await.unwrap();

    let from_a = a
        .request("/node-b/b/echo", json!({ "hello": "b" }))
        .await
        .unwrap();
    assert_eq!(from_a["served_by"], "b.echo");
    let from_b = b
        .request("/node-a/a/echo", json!({ "hello": "a" }))
        .await
        .unwrap();
    assert_eq!(from_b["served_by"], "a.echo");
}

#[tokio::test(flavor = "multi_thread")]
async fn empty_nodes_link_successfully() {
    let a = Node::builder("empty-a")
        .insecure_accept_declared_peer_identities()
        .build()
        .unwrap();
    let b = Node::builder("empty-b")
        .insecure_accept_declared_peer_identities()
        .build()
        .unwrap();
    a.link(&b).await.unwrap();
}

#[tokio::test(flavor = "multi_thread")]
async fn concurrent_requests_resolve_to_their_own_responses() {
    let a = Node::builder("caller")
        .insecure_accept_declared_peer_identities()
        .build()
        .unwrap();
    let b = Node::builder("worker")
        .service(double)
        .insecure_accept_declared_peer_identities()
        .build()
        .unwrap();
    a.link(&b).await.unwrap();

    let calls: Vec<_> = (0..16)
        .map(|n| {
            let a = a.clone();
            tokio::spawn(async move { a.request("/worker/double", json!({ "n": n })).await })
        })
        .collect();
    for (n, call) in calls.into_iter().enumerate() {
        let reply = call.await.unwrap().unwrap();
        assert_eq!(reply["n"], (n as i64) * 2);
    }
}

#[tokio::test(flavor = "multi_thread")]
async fn an_unknown_subject_teaches_the_known_names() {
    let node = service("solo", "echo");
    let error = node.request("/solo/eco", json!({})).await.unwrap_err();
    assert_eq!(error.code, ErrorCode::UnknownSubject);
    assert!(error.message.contains("echo"), "{}", error.message);
}

#[tokio::test(flavor = "multi_thread")]
async fn a_downstream_error_keeps_its_code_and_message() {
    let a = Node::builder("caller")
        .insecure_accept_declared_peer_identities()
        .build()
        .unwrap();
    let b = Node::builder("worker")
        .service(fail)
        .insecure_accept_declared_peer_identities()
        .build()
        .unwrap();
    a.link(&b).await.unwrap();

    let error = a.request("/worker/fail", json!({})).await.unwrap_err();
    assert_eq!(error.code, ErrorCode::InvalidInput);
    assert_eq!(error.message, "no such city");
}

#[tokio::test(flavor = "multi_thread")]
async fn a_handler_nested_request_reaches_a_linked_peer() {
    let planner = Node::builder("planner")
        .service(plan)
        .insecure_accept_declared_peer_identities()
        .build()
        .unwrap();
    let weather = Node::builder("weather")
        .service(forecast)
        .insecure_accept_declared_peer_identities()
        .build()
        .unwrap();
    planner.link(&weather).await.unwrap();

    let reply = planner.request("/planner/plan", json!({})).await.unwrap();
    assert_eq!(reply["plan"], "21C day");
}

#[tokio::test(flavor = "multi_thread")]
async fn a_three_node_chain_routes_transit_subjects_in_both_directions() {
    let a = service("chain-a", "alpha");
    let b = Node::builder("chain-b")
        .insecure_accept_declared_peer_identities()
        .build()
        .unwrap();
    let c = service("chain-c", "gamma");
    a.link(&b).await.unwrap();
    b.link(&c).await.unwrap();

    common::wait_until("a learns the transit route to chain-c", || {
        a.reachable_names().contains(&"chain-c".to_string())
    })
    .await;
    common::wait_until("c learns the transit route to chain-a", || {
        c.reachable_names().contains(&"chain-a".to_string())
    })
    .await;
    let via_b = a.request("/chain-c/gamma", json!({})).await.unwrap();
    assert_eq!(via_b["served_by"], "gamma");
    let reverse = c.request("/chain-a/alpha", json!({})).await.unwrap();
    assert_eq!(reverse["served_by"], "alpha");
}

#[tokio::test(flavor = "multi_thread")]
async fn a_request_works_immediately_after_connect_returns() {
    let (server, url) = hosted("weather-1", "weather").await;
    let dialer = Node::builder("caller")
        .insecure_accept_declared_peer_identities()
        .build()
        .unwrap();
    dialer
        .connect(EndpointSet::from(ws_endpoint(url)))
        .await
        .unwrap();
    let reply = dialer
        .request("/weather-1/weather", json!({}))
        .await
        .unwrap();
    assert_eq!(reply["served_by"], "weather");
    drop(server);
}

#[tokio::test(flavor = "multi_thread")]
async fn websocket_candidate_stays_established_after_connect_returns() {
    let (server, url) = hosted("weather-1", "weather").await;
    let dialer = Node::builder("caller")
        .insecure_accept_declared_peer_identities()
        .build()
        .unwrap();
    dialer
        .connect(EndpointSet::from(ws_endpoint(url)))
        .await
        .unwrap();

    tokio::task::yield_now().await;
    assert!(dialer.reachable_names().contains(&"weather-1".to_string()));
    let reply = dialer
        .request("/weather-1/weather", json!({}))
        .await
        .unwrap();
    assert_eq!(reply["served_by"], "weather");
    drop(server);
}

async fn hosted(
    name: &str,
    subject: &'static str,
) -> ((std::sync::Arc<Node>, unb_server::Hosting), String) {
    let node = service(name, subject);
    hosted_node(node).await
}

async fn hosted_node(
    node: std::sync::Arc<Node>,
) -> ((std::sync::Arc<Node>, unb_server::Hosting), String) {
    let hosting = HostConfig::tcp(([127, 0, 0, 1], 0), TcpTransport::plain())
        .start(&node)
        .await
        .unwrap();
    let url = format!("ws://{}", hosting.websocket_addr().unwrap());
    ((node, hosting), url)
}

async fn stalling_websocket() -> (String, Arc<AtomicUsize>) {
    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
    let address = listener.local_addr().unwrap();
    let accepted = Arc::new(AtomicUsize::new(0));
    tokio::spawn({
        let accepted = accepted.clone();
        async move {
            while let Ok((stream, _)) = listener.accept().await {
                accepted.fetch_add(1, Ordering::SeqCst);
                tokio::spawn(async move {
                    let _stream = stream;
                    std::future::pending::<()>().await;
                });
            }
        }
    });
    (format!("ws://{address}"), accepted)
}

#[tokio::test(flavor = "multi_thread")]
async fn repeating_connect_against_a_live_connection_converges() {
    let (server, url) = hosted("weather-1", "weather").await;
    let dialer = Node::builder("caller")
        .insecure_accept_declared_peer_identities()
        .build()
        .unwrap();
    let set = EndpointSet::from(ws_endpoint(url));
    dialer.connect(set.clone()).await.unwrap();
    dialer.connect(set).await.unwrap();

    tokio::time::sleep(Duration::from_millis(100)).await;
    let reply = dialer
        .request("/weather-1/weather", json!({}))
        .await
        .unwrap();
    assert_eq!(reply["served_by"], "weather");
    drop(server);
}

#[tokio::test(flavor = "multi_thread")]
async fn a_later_deliberate_connect_replaces_the_endpoints_after_loss() {
    let dialer = Node::builder("caller")
        .connect_timeout(Duration::from_secs(2))
        .insecure_accept_declared_peer_identities()
        .build()
        .unwrap();

    let first = hosted("weather-1", "weather").await;
    let connection = dialer
        .connect(EndpointSet::from(ws_endpoint(first.1.clone())))
        .await
        .unwrap();
    assert!(dialer.reachable_names().contains(&"weather-1".to_string()));

    drop(first.0);
    common::wait_until("the lost link withdraws its routes", || {
        !dialer.reachable_names().contains(&"weather-1".to_string())
    })
    .await;
    assert!(matches!(
        connection.status(),
        unb_server::ConnectionStatus::Connecting
    ));

    let second = hosted("weather-1", "weather").await;
    dialer
        .connect(EndpointSet::from(ws_endpoint(second.1.clone())))
        .await
        .unwrap();
    let reply = dialer
        .request("/weather-1/weather", json!({}))
        .await
        .unwrap();
    assert_eq!(reply["served_by"], "weather");
    drop(second.0);
}

#[tokio::test(flavor = "multi_thread")]
async fn explicit_disconnect_withdraws_the_selected_peer_routes() {
    let (server, url) = hosted("weather-1", "weather").await;
    let dialer = Node::builder("caller")
        .insecure_accept_declared_peer_identities()
        .build()
        .unwrap();
    let connection = dialer
        .connect(EndpointSet::from(ws_endpoint(url)))
        .await
        .unwrap();
    assert!(dialer.reachable_names().contains(&"weather-1".to_string()));

    connection.disconnect();

    common::wait_until("explicit disconnect withdraws routes", || {
        !dialer.reachable_names().contains(&"weather-1".to_string())
    })
    .await;
    assert!(matches!(
        connection.status(),
        unb_server::ConnectionStatus::Disconnected {
            reason: unb_server::DisconnectReason::ExplicitDisconnect
        }
    ));
    drop(server);
}

#[tokio::test(flavor = "multi_thread")]
async fn a_unary_request_waits_for_already_running_recovery() {
    let first = hosted("weather-1", "weather").await;
    let admissions = Arc::new(AtomicUsize::new(0));
    let release = Arc::new(tokio::sync::Notify::new());
    let replacement = Node::builder("weather-1")
        .service(echo.at_subject("weather"))
        .peer_layer_fn({
            let admissions = admissions.clone();
            let release = release.clone();
            move |mut request, next| {
                let admissions = admissions.clone();
                let release = release.clone();
                async move {
                    admissions.fetch_add(1, Ordering::SeqCst);
                    release.notified().await;
                    request.accept_declared();
                    next.admit(request).await
                }
            }
        })
        .build()
        .unwrap();
    let replacement_hosting = HostConfig::tcp(([127, 0, 0, 1], 0), TcpTransport::plain())
        .start(&replacement)
        .await
        .unwrap();
    let replacement_url = format!("ws://{}", replacement_hosting.websocket_addr().unwrap());
    let dialer = Node::builder("caller")
        .connect_timeout(Duration::from_secs(1))
        .insecure_accept_declared_peer_identities()
        .build()
        .unwrap();
    let connection = dialer
        .connect(EndpointSet::from([
            ws_endpoint(first.1.clone()),
            ws_endpoint(replacement_url),
        ]))
        .await
        .unwrap();
    first.0 .0.shutdown();
    drop(first);
    common::wait_until("the old route is withdrawn", || {
        !dialer.reachable_names().contains(&"weather-1".to_string())
    })
    .await;

    tokio::time::timeout(Duration::from_secs(1), async {
        while admissions.load(Ordering::SeqCst) == 0 {
            tokio::task::yield_now().await;
        }
    })
    .await
    .unwrap();
    let request = dialer.request("/weather-1/weather", json!({ "after": "reconnect" }));
    tokio::pin!(request);
    tokio::select! {
        result = &mut request => panic!("request completed before reconnect: {result:?}"),
        () = tokio::task::yield_now() => {}
    }
    let subscription = dialer.subscribe("/weather-1/weather", json!({}));
    tokio::pin!(subscription);
    tokio::select! {
        _ = &mut subscription => panic!("subscription completed before recovery"),
        () = tokio::task::yield_now() => {}
    }

    release.notify_waiters();

    common::wait_until("automatic recovery installs the replacement", || {
        connection.status() == unb_server::ConnectionStatus::Connected
    })
    .await;
    let reply = tokio::time::timeout(Duration::from_secs(1), &mut request)
        .await
        .unwrap()
        .unwrap();
    assert_eq!(reply["got"]["after"], "reconnect");
    let _ = tokio::time::timeout(Duration::from_secs(1), &mut subscription)
        .await
        .unwrap();
    drop(replacement_hosting);
    drop(replacement);
}

#[tokio::test(flavor = "multi_thread")]
async fn an_in_flight_request_fails_on_session_loss_and_is_never_replayed() {
    NO_REPLAY_INVOCATIONS.store(0, Ordering::SeqCst);
    let first_owner = Node::builder("no-replay-owner")
        .service(no_replay_stall.at_subject("work"))
        .insecure_accept_declared_peer_identities()
        .build()
        .unwrap();
    let (first, first_url) = hosted_node(first_owner).await;
    let replacement_owner = Node::builder("no-replay-owner")
        .service(no_replay_replacement.at_subject("work"))
        .insecure_accept_declared_peer_identities()
        .build()
        .unwrap();
    let (replacement, replacement_url) = hosted_node(replacement_owner).await;
    let caller = Node::builder("no-replay-caller")
        .connect_timeout(Duration::from_millis(200))
        .insecure_accept_declared_peer_identities()
        .build()
        .unwrap();
    let connection = caller
        .connect(EndpointSet::from([
            ws_endpoint(first_url),
            ws_endpoint(replacement_url),
        ]))
        .await
        .unwrap();
    let in_flight = tokio::spawn({
        let caller = caller.clone();
        async move { caller.request("/no-replay-owner/work", json!({})).await }
    });
    tokio::time::timeout(Duration::from_secs(1), async {
        while NO_REPLAY_INVOCATIONS.load(Ordering::SeqCst) != 1 {
            tokio::task::yield_now().await;
        }
    })
    .await
    .expect("the original handler receives the request");

    first.0.shutdown();
    drop(first);

    let error = tokio::time::timeout(Duration::from_secs(1), in_flight)
        .await
        .expect("the failed session terminates the in-flight operation")
        .unwrap()
        .unwrap_err();
    assert_eq!(error.code, ErrorCode::PeerUnreachable);
    common::wait_until("automatic maintenance admits the replacement", || {
        connection.status() == unb_server::ConnectionStatus::Connected
    })
    .await;
    assert_eq!(NO_REPLAY_INVOCATIONS.load(Ordering::SeqCst), 1);

    let reply = caller
        .request("/no-replay-owner/work", json!({}))
        .await
        .unwrap();
    assert_eq!(reply["invocation"], 2);
    assert_eq!(NO_REPLAY_INVOCATIONS.load(Ordering::SeqCst), 2);
    drop(replacement);
}

#[tokio::test(flavor = "multi_thread")]
async fn reconnect_without_the_old_subject_returns_refreshed_unknown() {
    let first = hosted("weather-1", "weather").await;
    let admissions = Arc::new(AtomicUsize::new(0));
    let release = Arc::new(tokio::sync::Notify::new());
    let replacement = Node::builder("weather-1")
        .peer_layer_fn({
            let admissions = admissions.clone();
            let release = release.clone();
            move |mut request, next| {
                let admissions = admissions.clone();
                let release = release.clone();
                async move {
                    admissions.fetch_add(1, Ordering::SeqCst);
                    release.notified().await;
                    request.accept_declared();
                    next.admit(request).await
                }
            }
        })
        .build()
        .unwrap();
    let (replacement_server, replacement_url) = hosted_node(replacement).await;
    let dialer = Node::builder("caller")
        .connect_timeout(Duration::from_secs(1))
        .insecure_accept_declared_peer_identities()
        .build()
        .unwrap();
    let connection = dialer
        .connect(EndpointSet::from([
            ws_endpoint(first.1.clone()),
            ws_endpoint(replacement_url),
        ]))
        .await
        .unwrap();
    first.0 .0.shutdown();
    drop(first);
    common::wait_until("the old route is withdrawn", || {
        !dialer.reachable_names().contains(&"weather-1".to_string())
    })
    .await;
    tokio::time::timeout(Duration::from_secs(1), async {
        while admissions.load(Ordering::SeqCst) == 0 {
            tokio::task::yield_now().await;
        }
    })
    .await
    .unwrap();
    let request = dialer.request("/weather-1/weather", json!({}));
    tokio::pin!(request);
    tokio::select! {
        result = &mut request => panic!("request completed before reconnect: {result:?}"),
        () = tokio::task::yield_now() => {}
    }

    release.notify_waiters();

    common::wait_until("automatic recovery installs the replacement", || {
        connection.status() == unb_server::ConnectionStatus::Connected
    })
    .await;
    let error = request.await.unwrap_err();
    assert_eq!(error.code, ErrorCode::UnknownSubject);
    assert_eq!(connection.status(), unb_server::ConnectionStatus::Connected);
    drop(replacement_server);
}

#[tokio::test(flavor = "multi_thread")]
async fn request_joining_a_failed_reconnect_returns_peer_unreachable() {
    let first = hosted("weather-1", "weather").await;
    let admissions = Arc::new(AtomicUsize::new(0));
    let reject = Arc::new(tokio::sync::Notify::new());
    let replacement = Node::builder("weather-1")
        .peer_layer_fn({
            let admissions = admissions.clone();
            let reject = reject.clone();
            move |request, _next| {
                let admissions = admissions.clone();
                let reject = reject.clone();
                async move {
                    admissions.fetch_add(1, Ordering::SeqCst);
                    reject.notified().await;
                    Err(unb_server::HandlerError::new(
                        ErrorCode::Unauthorized,
                        format!("rejected {}", request.remote().node_id),
                    ))
                }
            }
        })
        .build()
        .unwrap();
    let (replacement_server, replacement_url) = hosted_node(replacement).await;
    let dialer = Node::builder("caller")
        .connect_timeout(Duration::from_secs(1))
        .insecure_accept_declared_peer_identities()
        .build()
        .unwrap();
    let connection = dialer
        .connect(EndpointSet::from([
            ws_endpoint(first.1.clone()),
            ws_endpoint(replacement_url),
        ]))
        .await
        .unwrap();
    first.0 .0.shutdown();
    drop(first);
    common::wait_until("the old route is withdrawn", || {
        !dialer.reachable_names().contains(&"weather-1".to_string())
    })
    .await;
    tokio::time::timeout(Duration::from_secs(1), async {
        while admissions.load(Ordering::SeqCst) == 0 {
            tokio::task::yield_now().await;
        }
    })
    .await
    .unwrap();
    let request = dialer.request("/weather-1/weather", json!({}));
    tokio::pin!(request);
    tokio::select! {
        result = &mut request => panic!("request completed before reconnect: {result:?}"),
        () = tokio::task::yield_now() => {}
    }

    reject.notify_waiters();

    connection.disconnect();
    let error = request.await.unwrap_err();
    assert_eq!(error.code, ErrorCode::PeerUnreachable);
    assert!(matches!(
        connection.status(),
        unb_server::ConnectionStatus::Disconnected {
            reason: unb_server::DisconnectReason::ExplicitDisconnect
        }
    ));
    assert_eq!(admissions.load(Ordering::SeqCst), 1);
    drop(replacement_server);
}

#[tokio::test]
async fn unary_deadline_can_expire_without_cancelling_maintenance() {
    let first = hosted("weather-1", "weather").await;
    let (stalling_url, accepted) = stalling_websocket().await;
    let dialer = Node::builder("caller")
        .connect_timeout(Duration::from_secs(60))
        .insecure_accept_declared_peer_identities()
        .build()
        .unwrap();
    let connection = dialer
        .connect(EndpointSet::from([
            ws_endpoint(first.1.clone()),
            ws_endpoint(stalling_url),
        ]))
        .await
        .unwrap();
    tokio::time::pause();
    first.0 .0.shutdown();
    drop(first);
    common::wait_until("the old route is withdrawn", || {
        !dialer.reachable_names().contains(&"weather-1".to_string())
    })
    .await;
    tokio::time::timeout(Duration::from_secs(1), async {
        while accepted.load(Ordering::SeqCst) == 0 {
            tokio::task::yield_now().await;
        }
    })
    .await
    .unwrap();
    let request = tokio::spawn({
        let dialer = dialer.clone();
        async move { dialer.request("/weather-1/weather", json!({})).await }
    });
    tokio::task::yield_now().await;

    tokio::time::advance(Duration::from_secs(31)).await;

    let error = request.await.unwrap().unwrap_err();
    assert_eq!(error.code, ErrorCode::PeerUnreachable);
    assert_eq!(
        connection.status(),
        unb_server::ConnectionStatus::Connecting
    );
    connection.disconnect();
}