polyester-sdk 0.1.0-alpha.28

Official Rust SDK for Polyester APIs.
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
//! Local mock HTTP/WS servers for POLY-3746 L2 tests.

use buffa::Message as BuffaMessage;
use futures_util::{SinkExt, StreamExt};
use polyester::auth::Credentials;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::Duration;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpListener;
use tokio_tungstenite::tungstenite::Message;
use tokio_tungstenite::tungstenite::http::{Request as WsRequest, Response as WsResponse};
use tokio_tungstenite::{WebSocketStream, accept_hdr_async};

pub struct ParsedRequest {
    #[allow(dead_code)]
    pub method: String,
    pub path: String,
    pub body: Vec<u8>,
}

pub enum HttpScript {
    NotFound,
    NeverRespond {
        stall: Duration,
    },
    Json {
        status: u16,
        body: Vec<u8>,
    },
    Raw {
        status: u16,
        headers: Vec<(String, String)>,
        body: Vec<u8>,
    },
    HeadersThenStall {
        status: u16,
        headers: Vec<(String, String)>,
        stall: Duration,
    },
    /// Chunked transfer that keeps sending until `total_bytes` then stops.
    ChunkedBody {
        status: u16,
        total_bytes: usize,
        chunk_size: usize,
    },
    /// Fixed-length response whose body arrives slowly enough to exceed a
    /// whole-request deadline while each individual read still succeeds.
    SlowDrip {
        status: u16,
        headers: Vec<(String, String)>,
        chunks: Vec<Vec<u8>>,
        inter_chunk_delay: Duration,
    },
}

pub struct MockHttpServer {
    base_url: String,
    pub requests: Arc<AtomicUsize>,
    pub in_flight: Arc<AtomicUsize>,
    _join: tokio::task::JoinHandle<()>,
}

impl MockHttpServer {
    pub async fn spawn(
        handler: impl Fn(ParsedRequest) -> HttpScript + Send + Sync + 'static,
    ) -> Self {
        Self::spawn_counted(handler).await
    }

    pub async fn spawn_counted(
        handler: impl Fn(ParsedRequest) -> HttpScript + Send + Sync + 'static,
    ) -> Self {
        let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind http");
        let addr = listener.local_addr().expect("addr");
        let handler = Arc::new(handler);
        let requests = Arc::new(AtomicUsize::new(0));
        let in_flight = Arc::new(AtomicUsize::new(0));
        let requests_task = requests.clone();
        let in_flight_task = in_flight.clone();
        let join = tokio::spawn(async move {
            loop {
                let Ok((mut stream, _)) = listener.accept().await else {
                    break;
                };
                let handler = handler.clone();
                let requests = requests_task.clone();
                let in_flight = in_flight_task.clone();
                tokio::spawn(async move {
                    in_flight.fetch_add(1, Ordering::SeqCst);
                    let _guard = ConnGuard(in_flight);
                    let mut buf = vec![0u8; 16 * 1024];
                    let n = match stream.read(&mut buf).await {
                        Ok(0) | Err(_) => return,
                        Ok(n) => n,
                    };
                    requests.fetch_add(1, Ordering::SeqCst);
                    let raw = String::from_utf8_lossy(&buf[..n]);
                    let mut lines = raw.split("\r\n");
                    let request_line = lines.next().unwrap_or("");
                    let mut parts = request_line.split_whitespace();
                    let method = parts.next().unwrap_or("").to_owned();
                    let path = parts.next().unwrap_or("/").to_owned();
                    let path = path.split('?').next().unwrap_or(&path).to_owned();
                    let body = buf[..n]
                        .windows(4)
                        .position(|window| window == b"\r\n\r\n")
                        .map(|index| buf[index + 4..n].to_vec())
                        .unwrap_or_default();
                    match handler(ParsedRequest { method, path, body }) {
                        HttpScript::NotFound => {
                            let _ = stream
                                .write_all(b"HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n")
                                .await;
                        }
                        HttpScript::NeverRespond { stall } => {
                            let mut peek = [0u8; 1];
                            tokio::select! {
                                _ = tokio::time::sleep(stall) => {}
                                _ = stream.read(&mut peek) => {}
                            }
                        }
                        HttpScript::Json { status, body } => {
                            let head = format!(
                                "HTTP/1.1 {status} OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
                                body.len()
                            );
                            let _ = stream.write_all(head.as_bytes()).await;
                            let _ = stream.write_all(&body).await;
                        }
                        HttpScript::Raw {
                            status,
                            headers,
                            body,
                        } => {
                            let mut head = format!("HTTP/1.1 {status} OK\r\n");
                            for (k, v) in headers {
                                head.push_str(&format!("{k}: {v}\r\n"));
                            }
                            head.push_str("Connection: close\r\n\r\n");
                            let _ = stream.write_all(head.as_bytes()).await;
                            let _ = stream.write_all(&body).await;
                        }
                        HttpScript::HeadersThenStall {
                            status,
                            headers,
                            stall,
                        } => {
                            let mut head = format!("HTTP/1.1 {status} OK\r\n");
                            for (k, v) in headers {
                                head.push_str(&format!("{k}: {v}\r\n"));
                            }
                            head.push_str("\r\n");
                            let _ = stream.write_all(head.as_bytes()).await;
                            let _ = stream.flush().await;
                            // Exit early when the client aborts (E6 cancel-orphan).
                            let mut peek = [0u8; 1];
                            tokio::select! {
                                _ = tokio::time::sleep(stall) => {}
                                _ = stream.read(&mut peek) => {}
                            }
                        }
                        HttpScript::ChunkedBody {
                            status,
                            total_bytes,
                            chunk_size,
                        } => {
                            let head = format!(
                                "HTTP/1.1 {status} OK\r\nTransfer-Encoding: chunked\r\nConnection: close\r\n\r\n"
                            );
                            let _ = stream.write_all(head.as_bytes()).await;
                            let mut sent = 0usize;
                            while sent < total_bytes {
                                let n = (total_bytes - sent).min(chunk_size.max(1));
                                let chunk = vec![b'x'; n];
                                let header = format!("{n:x}\r\n");
                                if stream.write_all(header.as_bytes()).await.is_err() {
                                    break;
                                }
                                if stream.write_all(&chunk).await.is_err() {
                                    break;
                                }
                                if stream.write_all(b"\r\n").await.is_err() {
                                    break;
                                }
                                sent += n;
                            }
                            let _ = stream.write_all(b"0\r\n\r\n").await;
                        }
                        HttpScript::SlowDrip {
                            status,
                            headers,
                            chunks,
                            inter_chunk_delay,
                        } => {
                            let total_bytes = chunks.iter().map(Vec::len).sum::<usize>();
                            let mut head = format!("HTTP/1.1 {status} OK\r\n");
                            for (k, v) in headers {
                                head.push_str(&format!("{k}: {v}\r\n"));
                            }
                            head.push_str(&format!(
                                "Content-Length: {total_bytes}\r\nConnection: close\r\n\r\n"
                            ));
                            if stream.write_all(head.as_bytes()).await.is_err() {
                                return;
                            }
                            for chunk in chunks {
                                if stream.write_all(&chunk).await.is_err() {
                                    break;
                                }
                                let _ = stream.flush().await;
                                tokio::time::sleep(inter_chunk_delay).await;
                            }
                        }
                    }
                });
            }
        });
        Self {
            base_url: format!("http://{addr}"),
            requests,
            in_flight,
            _join: join,
        }
    }

    pub fn base_url(&self) -> String {
        self.base_url.clone()
    }
}

pub struct MockWsServer {
    addr: String,
    pub connects: Arc<AtomicUsize>,
    #[allow(dead_code)]
    pub active: Arc<AtomicUsize>,
    _join: tokio::task::JoinHandle<()>,
}

impl MockWsServer {
    pub fn ws_url(&self) -> String {
        format!("ws://{}/connection/websocket", self.addr)
    }

    pub async fn spawn_hang_after_accept() -> Self {
        Self::spawn_hang_after_accept_counted(Arc::new(AtomicUsize::new(0))).await
    }

    pub async fn spawn_hang_after_accept_counted(active: Arc<AtomicUsize>) -> Self {
        let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind ws");
        let addr = listener.local_addr().expect("addr").to_string();
        let connects = Arc::new(AtomicUsize::new(0));
        let connects_task = connects.clone();
        let active_task = active.clone();
        let join = tokio::spawn(async move {
            loop {
                let Ok((stream, _)) = listener.accept().await else {
                    break;
                };
                let active = active_task.clone();
                let connects = connects_task.clone();
                tokio::spawn(async move {
                    let Ok(mut ws) = accept_protobuf_ws(stream).await else {
                        return;
                    };
                    connects.fetch_add(1, Ordering::SeqCst);
                    active.fetch_add(1, Ordering::SeqCst);
                    let _guard = ConnGuard(active);
                    while let Some(Ok(_)) = ws.next().await {}
                });
            }
        });
        Self {
            addr,
            connects,
            active,
            _join: join,
        }
    }

    pub async fn spawn_centrifugo_public(active: Arc<AtomicUsize>) -> Self {
        let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind ws");
        let addr = listener.local_addr().expect("addr").to_string();
        let connects = Arc::new(AtomicUsize::new(0));
        let connects_task = connects.clone();
        let active_task = active.clone();
        let join = tokio::spawn(async move {
            loop {
                let Ok((stream, _)) = listener.accept().await else {
                    break;
                };
                let active = active_task.clone();
                let connects = connects_task.clone();
                tokio::spawn(async move {
                    let Ok(mut ws) = accept_protobuf_ws(stream).await else {
                        return;
                    };
                    connects.fetch_add(1, Ordering::SeqCst);
                    active.fetch_add(1, Ordering::SeqCst);
                    let _guard = ConnGuard(active);
                    let mut replies = 0u8;
                    while let Some(msg) = ws.next().await {
                        let Ok(msg) = msg else { break };
                        match msg {
                            Message::Binary(_) if replies < 2 => {
                                replies += 1;
                                let id = u32::from(replies);
                                let _ = ws
                                    .send(Message::Binary(centrifugo_ok_reply(id).into()))
                                    .await;
                            }
                            Message::Ping(p) => {
                                let _ = ws.send(Message::Pong(p)).await;
                            }
                            Message::Close(_) => break,
                            _ => {}
                        }
                    }
                });
            }
        });
        Self {
            addr,
            connects,
            active,
            _join: join,
        }
    }

    /// Accept connect+subscribe, then send one Centrifugo publication.
    pub async fn spawn_centrifugo_publication_after_handshake(
        active: Arc<AtomicUsize>,
        payload: Vec<u8>,
    ) -> Self {
        let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind ws");
        let addr = listener.local_addr().expect("addr").to_string();
        let connects = Arc::new(AtomicUsize::new(0));
        let connects_task = connects.clone();
        let active_task = active.clone();
        let join = tokio::spawn(async move {
            loop {
                let Ok((stream, _)) = listener.accept().await else {
                    break;
                };
                let active = active_task.clone();
                let connects = connects_task.clone();
                let payload = payload.clone();
                tokio::spawn(async move {
                    let Ok(mut ws) = accept_protobuf_ws(stream).await else {
                        return;
                    };
                    connects.fetch_add(1, Ordering::SeqCst);
                    active.fetch_add(1, Ordering::SeqCst);
                    let _guard = ConnGuard(active);
                    let mut replies = 0u8;
                    while let Some(msg) = ws.next().await {
                        let Ok(msg) = msg else { break };
                        if let Message::Binary(_) = msg
                            && replies < 2
                        {
                            replies += 1;
                            let _ = ws
                                .send(Message::Binary(
                                    centrifugo_ok_reply(u32::from(replies)).into(),
                                ))
                                .await;
                            if replies == 2 {
                                let _ = ws
                                    .send(Message::Binary(centrifugo_publication(&payload).into()))
                                    .await;
                            }
                        }
                    }
                });
            }
        });
        Self {
            addr,
            connects,
            active,
            _join: join,
        }
    }

    /// Accept connect+subscribe, then flood identical publications.
    pub async fn spawn_centrifugo_publication_flood_after_handshake(
        active: Arc<AtomicUsize>,
        payload: Vec<u8>,
        count: usize,
    ) -> Self {
        let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind ws");
        let addr = listener.local_addr().expect("addr").to_string();
        let connects = Arc::new(AtomicUsize::new(0));
        let connects_task = connects.clone();
        let active_task = active.clone();
        let join = tokio::spawn(async move {
            loop {
                let Ok((stream, _)) = listener.accept().await else {
                    break;
                };
                let active = active_task.clone();
                let connects = connects_task.clone();
                let payload = payload.clone();
                tokio::spawn(async move {
                    let Ok(mut ws) = accept_protobuf_ws(stream).await else {
                        return;
                    };
                    connects.fetch_add(1, Ordering::SeqCst);
                    active.fetch_add(1, Ordering::SeqCst);
                    let _guard = ConnGuard(active);
                    let mut replies = 0u8;
                    while let Some(msg) = ws.next().await {
                        let Ok(msg) = msg else { break };
                        if let Message::Binary(_) = msg
                            && replies < 2
                        {
                            replies += 1;
                            let _ = ws
                                .send(Message::Binary(
                                    centrifugo_ok_reply(u32::from(replies)).into(),
                                ))
                                .await;
                            if replies == 2 {
                                // Let snapshot-then-stream finish its initial
                                // snapshot so publications exercise the live
                                // managed output queue rather than coalescing
                                // into the startup buffer.
                                tokio::time::sleep(Duration::from_millis(500)).await;
                                for _ in 0..count {
                                    if ws
                                        .send(Message::Binary(
                                            centrifugo_publication(&payload).into(),
                                        ))
                                        .await
                                        .is_err()
                                    {
                                        break;
                                    }
                                }
                            }
                        }
                    }
                });
            }
        });
        Self {
            addr,
            connects,
            active,
            _join: join,
        }
    }

    /// Accept connect+subscribe, then send one binary message of `message_bytes`.
    pub async fn spawn_centrifugo_oversized_after_handshake(
        active: Arc<AtomicUsize>,
        message_bytes: usize,
    ) -> Self {
        let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind ws");
        let addr = listener.local_addr().expect("addr").to_string();
        let connects = Arc::new(AtomicUsize::new(0));
        let connects_task = connects.clone();
        let active_task = active.clone();
        let join = tokio::spawn(async move {
            loop {
                let Ok((stream, _)) = listener.accept().await else {
                    break;
                };
                let active = active_task.clone();
                let connects = connects_task.clone();
                tokio::spawn(async move {
                    let Ok(mut ws) = accept_protobuf_ws(stream).await else {
                        return;
                    };
                    connects.fetch_add(1, Ordering::SeqCst);
                    active.fetch_add(1, Ordering::SeqCst);
                    let _guard = ConnGuard(active);
                    let mut replies = 0u8;
                    while let Some(msg) = ws.next().await {
                        let Ok(msg) = msg else { break };
                        if let Message::Binary(_) = msg
                            && replies < 2
                        {
                            replies += 1;
                            let _ = ws
                                .send(Message::Binary(
                                    centrifugo_ok_reply(u32::from(replies)).into(),
                                ))
                                .await;
                            if replies == 2 {
                                let _ = ws
                                    .send(Message::Binary(vec![0; message_bytes].into()))
                                    .await;
                                break;
                            }
                        }
                    }
                });
            }
        });
        Self {
            addr,
            connects,
            active,
            _join: join,
        }
    }

    /// Accept connect+subscribe, then drop the socket so the client reconnects.
    pub async fn spawn_centrifugo_disconnect_after_handshake(active: Arc<AtomicUsize>) -> Self {
        let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind ws");
        let addr = listener.local_addr().expect("addr").to_string();
        let connects = Arc::new(AtomicUsize::new(0));
        let connects_task = connects.clone();
        let active_task = active.clone();
        let join = tokio::spawn(async move {
            loop {
                let Ok((stream, _)) = listener.accept().await else {
                    break;
                };
                let active = active_task.clone();
                let connects = connects_task.clone();
                tokio::spawn(async move {
                    let Ok(mut ws) = accept_protobuf_ws(stream).await else {
                        return;
                    };
                    connects.fetch_add(1, Ordering::SeqCst);
                    active.fetch_add(1, Ordering::SeqCst);
                    let _guard = ConnGuard(active);
                    let mut replies = 0u8;
                    while let Some(msg) = ws.next().await {
                        let Ok(msg) = msg else { break };
                        if let Message::Binary(_) = msg
                            && replies < 2
                        {
                            replies += 1;
                            let _ = ws
                                .send(Message::Binary(
                                    centrifugo_ok_reply(u32::from(replies)).into(),
                                ))
                                .await;
                            if replies == 2 {
                                break;
                            }
                        }
                    }
                });
            }
        });
        Self {
            addr,
            connects,
            active,
            _join: join,
        }
    }

    /// Disconnect the first subscribed socket, then keep its replacement idle.
    pub async fn spawn_centrifugo_disconnect_once_then_idle(active: Arc<AtomicUsize>) -> Self {
        let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind ws");
        let addr = listener.local_addr().expect("addr").to_string();
        let connects = Arc::new(AtomicUsize::new(0));
        let connects_task = connects.clone();
        let active_task = active.clone();
        let join = tokio::spawn(async move {
            loop {
                let Ok((stream, _)) = listener.accept().await else {
                    break;
                };
                let active = active_task.clone();
                let connects = connects_task.clone();
                tokio::spawn(async move {
                    let Ok(mut ws) = accept_protobuf_ws(stream).await else {
                        return;
                    };
                    let connection_index = connects.fetch_add(1, Ordering::SeqCst);
                    active.fetch_add(1, Ordering::SeqCst);
                    let _guard = ConnGuard(active);
                    let mut replies = 0u8;
                    while let Some(msg) = ws.next().await {
                        let Ok(msg) = msg else { break };
                        if let Message::Binary(_) = msg
                            && replies < 2
                        {
                            replies += 1;
                            let _ = ws
                                .send(Message::Binary(
                                    centrifugo_ok_reply(u32::from(replies)).into(),
                                ))
                                .await;
                            if replies == 2 && connection_index == 0 {
                                // Let SnapshotThenStream finish its initial snapshot
                                // before forcing the reconnect under test.
                                tokio::time::sleep(Duration::from_millis(100)).await;
                                break;
                            }
                        }
                    }
                });
            }
        });
        Self {
            addr,
            connects,
            active,
            _join: join,
        }
    }
}

struct ConnGuard(Arc<AtomicUsize>);
impl Drop for ConnGuard {
    fn drop(&mut self) {
        self.0.fetch_sub(1, Ordering::SeqCst);
    }
}

async fn accept_protobuf_ws(
    stream: tokio::net::TcpStream,
) -> Result<WebSocketStream<tokio::net::TcpStream>, ()> {
    accept_hdr_async(
        stream,
        #[allow(clippy::result_large_err)]
        |req: &WsRequest<()>, mut response: WsResponse<()>| {
            let proto = req
                .headers()
                .get("Sec-WebSocket-Protocol")
                .and_then(|v| v.to_str().ok())
                .unwrap_or("");
            if proto.split(',').any(|p| p.trim() == "centrifuge-protobuf") {
                response.headers_mut().insert(
                    "Sec-WebSocket-Protocol",
                    "centrifuge-protobuf".parse().unwrap(),
                );
            }
            Ok(response)
        },
    )
    .await
    .map_err(|_| ())
}

/// Encode a Centrifugo protobuf Reply with `id` and no error.
pub fn centrifugo_ok_reply(id: u32) -> Vec<u8> {
    let mut message = Vec::new();
    // Field 1 (id), wire type 0 (varint).
    message.push(0x08);
    put_varint(&mut message, u64::from(id));
    length_delimit(message)
}

pub fn centrifugo_publication(payload: &[u8]) -> Vec<u8> {
    let mut publication = Vec::new();
    put_bytes_field(&mut publication, 4, payload);
    let mut push = Vec::new();
    put_bytes_field(&mut push, 4, &publication);
    let mut reply = Vec::new();
    put_bytes_field(&mut reply, 4, &push);
    length_delimit(reply)
}

fn put_bytes_field(buf: &mut Vec<u8>, field: u32, value: &[u8]) {
    put_varint(buf, u64::from((field << 3) | 2));
    put_varint(buf, value.len() as u64);
    buf.extend_from_slice(value);
}

fn put_varint(buf: &mut Vec<u8>, mut value: u64) {
    loop {
        let mut byte = (value & 0x7f) as u8;
        value >>= 7;
        if value != 0 {
            byte |= 0x80;
        }
        buf.push(byte);
        if value == 0 {
            break;
        }
    }
}

fn length_delimit(message: Vec<u8>) -> Vec<u8> {
    let mut out = Vec::new();
    put_varint(&mut out, message.len() as u64);
    out.extend(message);
    out
}

pub fn test_credentials(key_id: &str, private_hex: &str) -> Credentials {
    Credentials::new(key_id, private_hex).expect("test credentials")
}

/// Connect unary protobuf success response (`Content-Type: application/proto`).
pub fn connect_proto_ok<M: BuffaMessage>(msg: &M) -> HttpScript {
    HttpScript::Raw {
        status: 200,
        headers: vec![("Content-Type".into(), "application/proto".into())],
        body: msg.encode_to_bytes().to_vec(),
    }
}

pub const SPOT_CONFIG_PATH: &str = "/marketdata.v1.MarketDataService/GetSpotConfig";
pub const ZIPPER_CONFIG_PATH: &str = "/chain.zipper.v1.ZipperService/GetDepositWithdrawConfig";
pub const GET_ORDER_PATH: &str = "/orders.v1.OrdersReadService/GetOrder";
pub const GET_BALANCES_PATH: &str = "/ledger.read.v1.LedgerReadService/GetBalances";
pub const GET_TRADES_PATH: &str = "/marketdata.v1.MarketDataService/GetTrades";

pub async fn wait_until(mut pred: impl FnMut() -> bool, timeout: Duration) {
    let start = std::time::Instant::now();
    while !pred() {
        if start.elapsed() > timeout {
            panic!("condition not met within {timeout:?}");
        }
        tokio::time::sleep(Duration::from_millis(10)).await;
    }
}