simulator-client 0.8.0

Async WebSocket client for the Solana simulator backtest API
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
use std::{net::SocketAddr, time::Duration};

use futures::{SinkExt, StreamExt};
use simulator_api::{
    BacktestError, BacktestRequest, BacktestResponse, BacktestStatus, CreateSessionParams,
    SequencedResponse,
};
use simulator_client::{
    BacktestClient, BacktestClientError, Continue, CreateSession, ReadyOutcome,
    managed::{
        ManagedBacktestSession, ManagedEvent, SubscriptionNotification,
        spawn_account_diff_subscription_manager,
    },
};
use tokio::net::{TcpListener, TcpStream};
use tokio_tungstenite::{
    WebSocketStream, accept_async, accept_hdr_async,
    tungstenite::{
        Message,
        handshake::server::{ErrorResponse, Request, Response},
    },
};
use tokio_util::sync::CancellationToken;

fn assert_expected_api_key(req: &Request, expected_api_key: &str) {
    let api_key = req.headers().get("X-API-Key").and_then(|v| v.to_str().ok());
    assert_eq!(api_key, Some(expected_api_key));
}

#[allow(clippy::result_large_err)]
async fn accept_with_expected_api_key(
    stream: tokio::net::TcpStream,
    expected_api_key: &'static str,
) -> tokio_tungstenite::tungstenite::Result<tokio_tungstenite::WebSocketStream<tokio::net::TcpStream>>
{
    accept_hdr_async(stream, move |req: &Request, resp: Response| {
        assert_expected_api_key(req, expected_api_key);
        Ok::<_, ErrorResponse>(resp)
    })
    .await
}

async fn spawn_server(
    expected_api_key: &'static str,
    handler: impl FnOnce(
        tokio_tungstenite::WebSocketStream<tokio::net::TcpStream>,
    ) -> tokio::task::JoinHandle<()>
    + Send
    + 'static,
) -> (String, tokio::task::JoinHandle<()>) {
    let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
    let addr: SocketAddr = listener.local_addr().unwrap();
    let url = format!("ws://{addr}/backtest");

    let join = tokio::spawn(async move {
        let (stream, _) = listener.accept().await.unwrap();

        let ws = accept_with_expected_api_key(stream, expected_api_key)
            .await
            .unwrap();

        handler(ws).await.unwrap();
    });

    (url, join)
}

/// Spawn a bare data-plane (rpc_endpoint) WebSocket server. Unlike
/// [`spawn_server`] it does not assert an `X-API-Key` header, because the
/// subscription manager connects to the rpc endpoint without one. Returns an
/// `http://` URL (the manager rewrites the scheme to `ws://`).
async fn spawn_rpc_server(
    handler: impl FnOnce(WebSocketStream<TcpStream>) -> tokio::task::JoinHandle<()> + Send + 'static,
) -> (String, tokio::task::JoinHandle<()>) {
    let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
    let addr: SocketAddr = listener.local_addr().unwrap();
    let url = format!("http://{addr}");

    let join = tokio::spawn(async move {
        let (stream, _) = listener.accept().await.unwrap();
        let ws = accept_async(stream).await.unwrap();
        handler(ws).await.unwrap();
    });

    (url, join)
}

/// Regression test for the parallel-session transaction-drop race: the manager
/// must deliver every notification and then close its channel on the terminal,
/// without waiting for the socket to close. The server holds the socket open
/// after the terminal to prove the manager stops on the marker, not the close.
#[tokio::test]
async fn subscription_drains_all_notifications_then_terminal_closes_channel() {
    let (url, server) = spawn_rpc_server(|mut ws| {
        tokio::spawn(async move {
            let msg = ws.next().await.unwrap().unwrap();
            let Message::Text(text) = msg else {
                panic!("expected text");
            };
            let req: serde_json::Value = serde_json::from_str(&text).unwrap();
            assert_eq!(req["method"], "accountDiffSubscribe");
            let id = req["id"].clone();

            // Acknowledge with subscription id 1.
            ws.send(Message::Text(
                serde_json::json!({ "jsonrpc": "2.0", "id": id, "result": 1 }).to_string(),
            ))
            .await
            .unwrap();

            for slot in 0..5u64 {
                ws.send(Message::Text(
                    serde_json::json!({
                        "jsonrpc": "2.0",
                        "method": "accountDiffNotification",
                        "params": { "subscription": 1, "result": { "context": { "slot": slot } } },
                    })
                    .to_string(),
                ))
                .await
                .unwrap();
            }

            // Terminal marker, ordered after every notification.
            ws.send(Message::Text(
                serde_json::json!({
                    "jsonrpc": "2.0",
                    "method": "subscriptionComplete",
                    "params": { "subscription": 1 },
                })
                .to_string(),
            ))
            .await
            .unwrap();

            // Hold the socket open: the client must stop on the terminal, not on
            // a socket close.
            tokio::time::sleep(Duration::from_secs(2)).await;
        })
    })
    .await;

    let cancel = CancellationToken::new();
    let mut handle = spawn_account_diff_subscription_manager(url, vec!["prog".to_string()], cancel);

    let mut received = 0;
    while let Some(notification) = handle.notifications.recv().await {
        assert!(matches!(
            notification,
            SubscriptionNotification::AccountDiff(_)
        ));
        received += 1;
    }

    // `recv` returned `None`: the channel closed only after the terminal, having
    // first delivered every notification — no trailing event was dropped.
    assert_eq!(received, 5);
    server.await.unwrap();
}

/// The managed wrapper drains trailing subscription notifications automatically
/// on `Completed`: a caller pumping only `next_event` still sees every
/// notification, and `Completed` arrives last.
#[tokio::test]
async fn next_event_drains_subscriptions_before_completed() {
    // Data plane: ack the subscribe, emit 5 notifications + terminal, hold open.
    let (rpc_url, rpc_server) = spawn_rpc_server(|mut ws| {
        tokio::spawn(async move {
            let msg = ws.next().await.unwrap().unwrap();
            let Message::Text(text) = msg else {
                panic!("expected text");
            };
            let req: serde_json::Value = serde_json::from_str(&text).unwrap();
            assert_eq!(req["method"], "accountDiffSubscribe");
            let id = req["id"].clone();
            ws.send(Message::Text(
                serde_json::json!({ "jsonrpc": "2.0", "id": id, "result": 1 }).to_string(),
            ))
            .await
            .unwrap();

            for slot in 0..5u64 {
                ws.send(Message::Text(
                    serde_json::json!({
                        "jsonrpc": "2.0",
                        "method": "accountDiffNotification",
                        "params": { "subscription": 1, "result": { "context": { "slot": slot } } },
                    })
                    .to_string(),
                ))
                .await
                .unwrap();
            }

            ws.send(Message::Text(
                serde_json::json!({
                    "jsonrpc": "2.0",
                    "method": "subscriptionComplete",
                    "params": { "subscription": 1 },
                })
                .to_string(),
            ))
            .await
            .unwrap();

            tokio::time::sleep(Duration::from_secs(2)).await;
        })
    })
    .await;

    // Control plane: create -> ready -> completed (sent eagerly, so `Completed`
    // races the data-plane notifications — the drain must still collect them).
    let (ctrl_url, ctrl_server) = spawn_server("k", move |mut ws| {
        tokio::spawn(async move {
            let msg = ws.next().await.unwrap().unwrap();
            let Message::Text(text) = msg else {
                panic!("expected text");
            };
            let req: BacktestRequest = serde_json::from_str(&text).unwrap();
            assert!(matches!(req, BacktestRequest::CreateBacktestSession(_)));

            ws.send(Message::Text(
                serde_json::to_string(&BacktestResponse::SessionCreated {
                    session_id: "s1".to_string(),
                    rpc_endpoint: rpc_url,
                    task_id: None,
                })
                .unwrap(),
            ))
            .await
            .unwrap();
            ws.send(Message::Text(
                serde_json::to_string(&BacktestResponse::ReadyForContinue).unwrap(),
            ))
            .await
            .unwrap();
            ws.send(Message::Text(
                serde_json::to_string(&BacktestResponse::Completed {
                    summary: None,
                    agent_stats: None,
                })
                .unwrap(),
            ))
            .await
            .unwrap();

            tokio::time::sleep(Duration::from_secs(2)).await;
        })
    })
    .await;

    let create = CreateSession::builder()
        .start_slot(100)
        .end_slot(105)
        .build()
        .into_request()
        .unwrap();
    let mut session = ManagedBacktestSession::start(ctrl_url, "k".to_string(), create)
        .await
        .unwrap();
    session.subscribe_account_diffs(vec!["prog".to_string()]);

    let mut account_diffs = 0;
    loop {
        match session.next_event().await.unwrap() {
            ManagedEvent::AccountDiff(_) => account_diffs += 1,
            ManagedEvent::Completed => break,
            ManagedEvent::Error(e) => panic!("unexpected error: {e}"),
            // ReadyForContinue / Slot / Status are not relevant here.
            _ => {}
        }
    }

    // All 5 trailing notifications arrived before `Completed`, with no explicit
    // drain call from this loop.
    assert_eq!(account_diffs, 5);

    session.shutdown().await;
    let _ = rpc_server.await;
    let _ = ctrl_server.await;
}

#[tokio::test]
async fn creates_session_waits_ready_advances_and_closes() {
    let (url, server) = spawn_server("k", |mut ws| {
        tokio::spawn(async move {
            eprintln!("server: waiting for resume request");
            let msg = ws.next().await.unwrap().unwrap();
            let Message::Text(text) = msg else {
                panic!("expected text");
            };
            let req: BacktestRequest = serde_json::from_str(&text).unwrap();
            let BacktestRequest::CreateBacktestSession(request) = req else {
                panic!("expected create");
            };
            let (
                CreateSessionParams {
                    start_slot,
                    end_slot,
                    ..
                },
                parallel,
            ) = request.into_request_and_parallel();
            assert!(!parallel);
            assert_eq!(start_slot, 100);
            assert_eq!(end_slot, 105);

            ws.send(Message::Text(
                serde_json::to_string(&BacktestResponse::SessionCreated {
                    session_id: "s1".to_string(),
                    rpc_endpoint: "http://rpc".to_string(),
                    task_id: None,
                })
                .unwrap(),
            ))
            .await
            .unwrap();

            ws.send(Message::Text(
                serde_json::to_string(&BacktestResponse::ReadyForContinue).unwrap(),
            ))
            .await
            .unwrap();

            let msg = ws.next().await.unwrap().unwrap();
            let Message::Text(text) = msg else {
                panic!("expected text");
            };
            let req: BacktestRequest = serde_json::from_str(&text).unwrap();
            assert!(matches!(req, BacktestRequest::Continue(_)));

            ws.send(Message::Text(
                serde_json::to_string(&BacktestResponse::Status {
                    status: BacktestStatus::DecodedTransactions,
                })
                .unwrap(),
            ))
            .await
            .unwrap();

            ws.send(Message::Text(
                serde_json::to_string(&BacktestResponse::SlotNotification(101)).unwrap(),
            ))
            .await
            .unwrap();
            ws.send(Message::Text(
                serde_json::to_string(&BacktestResponse::SlotNotification(102)).unwrap(),
            ))
            .await
            .unwrap();
            ws.send(Message::Text(
                serde_json::to_string(&BacktestResponse::ReadyForContinue).unwrap(),
            ))
            .await
            .unwrap();

            let msg = ws.next().await.unwrap().unwrap();
            let Message::Text(text) = msg else {
                panic!("expected text");
            };
            let req: BacktestRequest = serde_json::from_str(&text).unwrap();
            assert!(matches!(req, BacktestRequest::CloseBacktestSession));

            eprintln!("server: sending success");
            ws.send(Message::Text(
                serde_json::to_string(&BacktestResponse::Success).unwrap(),
            ))
            .await
            .unwrap();
        })
    })
    .await;

    let client = BacktestClient::builder().url(url).api_key("k").build();

    let mut session = client
        .create_session(
            CreateSession::builder()
                .start_slot(100)
                .slot_count(5)
                .build(),
        )
        .await
        .unwrap();

    assert_eq!(session.session_id(), Some("s1"));
    assert_eq!(session.rpc_endpoint(), Some("http://rpc"));

    let ready = session
        .ensure_ready(Some(Duration::from_secs(2)))
        .await
        .unwrap();
    assert_eq!(ready, ReadyOutcome::Ready);

    let result = session
        .advance(
            Continue::builder().advance_count(2).build(),
            Some(Duration::from_secs(2)),
            |_| {},
        )
        .await
        .unwrap();

    assert_eq!(result.slot_notifications, 2);
    assert_eq!(result.last_slot, Some(102));
    assert!(result.ready_for_continue);

    session.close(Some(Duration::from_secs(2))).await.unwrap();

    server.await.unwrap();
}

#[tokio::test]
async fn surfaces_remote_error() {
    let (url, server) = spawn_server("k", |mut ws| {
        tokio::spawn(async move {
            let msg = ws.next().await.unwrap().unwrap();
            let Message::Text(text) = msg else {
                panic!("expected text");
            };
            let req: BacktestRequest = serde_json::from_str(&text).unwrap();
            assert!(matches!(req, BacktestRequest::CreateBacktestSession(_)));

            ws.send(Message::Text(
                serde_json::to_string(&BacktestResponse::SessionCreated {
                    session_id: "s1".to_string(),
                    rpc_endpoint: "http://rpc".to_string(),
                    task_id: None,
                })
                .unwrap(),
            ))
            .await
            .unwrap();

            ws.send(Message::Text(
                serde_json::to_string(&BacktestResponse::ReadyForContinue).unwrap(),
            ))
            .await
            .unwrap();

            let msg = ws.next().await.unwrap().unwrap();
            let Message::Text(text) = msg else {
                panic!("expected text");
            };
            let req: BacktestRequest = serde_json::from_str(&text).unwrap();
            assert!(matches!(req, BacktestRequest::Continue(_)));

            ws.send(Message::Text(
                serde_json::to_string(&BacktestResponse::Error(BacktestError::NoMoreBlocks))
                    .unwrap(),
            ))
            .await
            .unwrap();
        })
    })
    .await;

    let client = BacktestClient::builder().url(url).api_key("k").build();

    let mut session = client
        .create_session(
            CreateSession::builder()
                .start_slot(100)
                .end_slot(100)
                .build(),
        )
        .await
        .unwrap();

    session
        .ensure_ready(Some(Duration::from_secs(2)))
        .await
        .unwrap();

    let err = session
        .continue_until_ready(
            Continue::builder().advance_count(1).build(),
            Some(Duration::from_secs(2)),
            |_| {},
        )
        .await
        .unwrap_err();

    assert!(matches!(
        err,
        BacktestClientError::Remote(BacktestError::NoMoreBlocks)
    ));

    server.await.unwrap();
}

#[tokio::test]
async fn creates_parallel_sessions_and_returns_ids() {
    let (url, server) = spawn_server("k", |mut ws| {
        tokio::spawn(async move {
            let msg = ws.next().await.unwrap().unwrap();
            let Message::Text(text) = msg else {
                panic!("expected text");
            };
            let payload: serde_json::Value = serde_json::from_str(&text).unwrap();
            assert_eq!(payload["method"], "createBacktestSession");
            assert_eq!(payload["params"]["parallel"], true);
            assert_eq!(payload["params"]["startSlot"], 100);
            assert!(payload["params"].get("request").is_none());

            let req: BacktestRequest = serde_json::from_str(&text).unwrap();
            let BacktestRequest::CreateBacktestSession(request) = req else {
                panic!("expected create");
            };
            let (_, parallel) = request.into_request_and_parallel();
            assert!(parallel);

            ws.send(Message::Text(
                serde_json::to_string(&BacktestResponse::SessionsCreated {
                    session_ids: vec!["s1".to_string(), "s2".to_string()],
                })
                .unwrap(),
            ))
            .await
            .unwrap();
        })
    })
    .await;

    let client = BacktestClient::builder().url(url).api_key("k").build();

    let session_ids = client
        .create_sessions(
            CreateSession::builder()
                .start_slot(100)
                .end_slot(105)
                .parallel(true)
                .build(),
        )
        .await
        .unwrap();

    assert_eq!(session_ids, vec!["s1".to_string(), "s2".to_string()]);
    server.await.unwrap();
}

#[tokio::test]
async fn creates_parallel_sessions_from_streamed_session_created_events() {
    let (url, server) = spawn_server("k", |mut ws| {
        tokio::spawn(async move {
            let msg = ws.next().await.unwrap().unwrap();
            let Message::Text(text) = msg else {
                panic!("expected text");
            };

            let req: BacktestRequest = serde_json::from_str(&text).unwrap();
            let BacktestRequest::CreateBacktestSession(request) = req else {
                panic!("expected create");
            };
            let (_, parallel) = request.into_request_and_parallel();
            assert!(parallel);

            ws.send(Message::Text(
                serde_json::to_string(&BacktestResponse::SessionCreated {
                    session_id: "s1".to_string(),
                    rpc_endpoint: "/backtest/s1".to_string(),
                    task_id: None,
                })
                .unwrap(),
            ))
            .await
            .unwrap();

            ws.send(Message::Text(
                serde_json::to_string(&BacktestResponse::SessionCreated {
                    session_id: "s2".to_string(),
                    rpc_endpoint: "/backtest/s2".to_string(),
                    task_id: None,
                })
                .unwrap(),
            ))
            .await
            .unwrap();

            ws.send(Message::Text(
                serde_json::to_string(&BacktestResponse::SessionsCreated {
                    session_ids: Vec::new(),
                })
                .unwrap(),
            ))
            .await
            .unwrap();
        })
    })
    .await;

    let client = BacktestClient::builder().url(url).api_key("k").build();
    let mut streamed = Vec::new();

    let session_ids = client
        .create_sessions_with_progress(
            CreateSession::builder()
                .start_slot(100)
                .end_slot(105)
                .parallel(true)
                .build(),
            |session_id| streamed.push(session_id),
        )
        .await
        .unwrap();

    assert_eq!(streamed, vec!["s1".to_string(), "s2".to_string()]);
    assert_eq!(session_ids, vec!["s1".to_string(), "s2".to_string()]);
    server.await.unwrap();
}

#[tokio::test]
async fn attaches_to_existing_session() {
    let (url, server) = spawn_server("k", |mut ws| {
        tokio::spawn(async move {
            let msg = ws.next().await.unwrap().unwrap();
            let Message::Text(text) = msg else {
                panic!("expected text");
            };

            let req: BacktestRequest = serde_json::from_str(&text).unwrap();
            let BacktestRequest::AttachBacktestSession {
                session_id,
                last_sequence,
            } = req
            else {
                panic!("expected attach");
            };
            assert_eq!(session_id, "s1");
            assert_eq!(last_sequence, Some(7));

            eprintln!("server: sending session attached");
            ws.send(Message::Text(
                serde_json::to_string(&BacktestResponse::SessionAttached {
                    session_id: "s1".to_string(),
                    rpc_endpoint: "http://rpc/s1".to_string(),
                    task_id: None,
                })
                .unwrap(),
            ))
            .await
            .unwrap();
        })
    })
    .await;

    let client = BacktestClient::builder().url(url).api_key("k").build();
    let session = client.attach_session("s1", Some(7)).await.unwrap();

    assert_eq!(session.session_id(), Some("s1"));
    assert_eq!(session.rpc_endpoint(), Some("http://rpc/s1"));
    server.await.unwrap();
}

#[tokio::test]
async fn tracks_last_sequence_from_sequenced_control_responses() {
    let (url, server) = spawn_server("k", |mut ws| {
        tokio::spawn(async move {
            let msg = ws.next().await.unwrap().unwrap();
            let Message::Text(text) = msg else {
                panic!("expected text");
            };

            let req: BacktestRequest = serde_json::from_str(&text).unwrap();
            let BacktestRequest::AttachBacktestSession {
                session_id,
                last_sequence,
            } = req
            else {
                panic!("expected attach");
            };
            assert_eq!(session_id, "s1");
            assert_eq!(last_sequence, None);

            ws.send(Message::Text(
                serde_json::to_string(&BacktestResponse::SessionAttached {
                    session_id: "s1".to_string(),
                    rpc_endpoint: "http://rpc/s1".to_string(),
                    task_id: None,
                })
                .unwrap(),
            ))
            .await
            .unwrap();

            ws.send(Message::Text(
                serde_json::to_string(&SequencedResponse {
                    seq_id: 41,
                    response: BacktestResponse::ReadyForContinue,
                })
                .unwrap(),
            ))
            .await
            .unwrap();

            ws.send(Message::Text(
                serde_json::to_string(&SequencedResponse {
                    seq_id: 42,
                    response: BacktestResponse::Status {
                        status: BacktestStatus::DecodedTransactions,
                    },
                })
                .unwrap(),
            ))
            .await
            .unwrap();
        })
    })
    .await;

    let client = BacktestClient::builder().url(url).api_key("k").build();
    let mut session = client.attach_session("s1", None).await.unwrap();

    assert_eq!(session.last_sequence(), None);
    let ready = session
        .ensure_ready(Some(Duration::from_secs(2)))
        .await
        .unwrap();
    assert_eq!(ready, ReadyOutcome::Ready);
    assert_eq!(session.last_sequence(), Some(41));

    session
        .wait_for_status(
            BacktestStatus::DecodedTransactions,
            Some(Duration::from_secs(2)),
        )
        .await
        .unwrap();
    assert_eq!(session.last_sequence(), Some(42));

    server.await.unwrap();
}