repe 7.2.0

Rust implementation of the REPE RPC protocol (JSON-focused)
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
//! End-to-end tests for the async SVS pull driver: a synchronous `Server`
//! producing a streamed value (it honours `Execution::OffReader`) and an
//! `AsyncClient` pulling it from async code, across the async/blocking decode
//! boundary, over a real TCP loopback connection. Covers the value, typed-slice,
//! and complex-slice receivers, each compressed and uncompressed.
#![cfg(feature = "value-stream")]

use repe::value_stream::{Compression, RouterValueStreamExt, StreamOpts};
use repe::{
    AsyncClient, BodyFormat, Complex, RepeError, Router, Server, pull_complex_slice_async,
    pull_consume_async, pull_to_file_async, pull_to_file_trailer_verified_async,
    pull_to_file_verified_async, pull_to_vec_async, pull_typed_slice_async, pull_value_async,
};
use serde::{Deserialize, Serialize};
use std::io::{self, Cursor, Read, Write};
use std::net::{SocketAddr, TcpListener};
use std::thread;

#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
struct Payload {
    id: u64,
    label: String,
    samples: Vec<f64>,
    tags: Vec<String>,
}

fn sample_payload() -> Payload {
    // ~1.6 MiB, spans many 16 KiB chunks so the pull loop / lookahead / blocking
    // decode bridge are exercised across multiple `next` round trips.
    Payload {
        id: 0xFEED_BEEF,
        label: "serialized value stream".to_string(),
        samples: (0..200_000).map(|i| (i as f64) * 0.5 - 1234.5).collect(),
        tags: (0..64).map(|i| format!("tag-{i:03}")).collect(),
    }
}

fn f64_samples() -> Vec<f64> {
    (0..200_000).map(|i| (i as f64) * 0.5 - 1234.5).collect()
}

fn iq_samples() -> Vec<Complex<f32>> {
    (0..200_000)
        .map(|i| Complex {
            re: (i as f32) * 1e-3,
            im: -(i as f32) * 2e-3,
        })
        .collect()
}

fn small_chunks(compression: Compression) -> StreamOpts {
    StreamOpts {
        chunk_bytes: 16 * 1024,
        compression,
        zstd_level: 3,
        session_depth: 4,
    }
}

/// Spawn a detached sync `Server` for `router` on an ephemeral port and return
/// its address (the sync server honours `OffReader`, which the SVS `next`
/// handler reports).
fn spawn(router: Router) -> SocketAddr {
    let server = Server::new(router);
    let listener: TcpListener = server.listen("127.0.0.1:0").expect("bind");
    let addr = listener.local_addr().expect("addr");
    thread::spawn(move || {
        let _ = server.serve(listener);
    });
    addr
}

async fn run_value(compression: Compression) {
    let payload = sample_payload();
    let p = payload.clone();
    let addr = spawn(Router::new().with_value_stream(
        move |resource: &str| (resource == "payload").then(|| p.clone()),
        small_chunks(compression),
    ));
    let client = AsyncClient::connect(addr).await.expect("connect");
    let got: Payload = pull_value_async(&client, "payload").await.expect("pull");
    assert_eq!(got, payload);
}

#[tokio::test]
async fn value_mode_roundtrips_uncompressed() {
    run_value(Compression::None).await;
}

#[tokio::test]
async fn value_mode_roundtrips_compressed() {
    run_value(Compression::Zstd).await;
}

async fn run_typed(compression: Compression) {
    let v = f64_samples();
    let vc = v.clone();
    let addr = spawn(Router::new().with_typed_value_stream(
        move |resource: &str| (resource == "buf").then(|| vc.clone()),
        small_chunks(compression),
    ));
    let client = AsyncClient::connect(addr).await.expect("connect");
    let got: Vec<f64> = pull_typed_slice_async(&client, "buf").await.expect("pull");
    assert_eq!(got, v);
}

#[tokio::test]
async fn typed_slice_roundtrips_uncompressed() {
    run_typed(Compression::None).await;
}

#[tokio::test]
async fn typed_slice_roundtrips_compressed() {
    run_typed(Compression::Zstd).await;
}

async fn run_complex(compression: Compression) {
    let v = iq_samples();
    let vc = v.clone();
    let addr = spawn(Router::new().with_complex_value_stream(
        move |resource: &str| (resource == "iq").then(|| vc.clone()),
        small_chunks(compression),
    ));
    let client = AsyncClient::connect(addr).await.expect("connect");
    let got: Vec<Complex<f32>> = pull_complex_slice_async(&client, "iq").await.expect("pull");
    assert_eq!(got, v);
}

#[tokio::test]
async fn complex_slice_roundtrips_uncompressed() {
    run_complex(Compression::None).await;
}

#[tokio::test]
async fn complex_slice_roundtrips_compressed() {
    run_complex(Compression::Zstd).await;
}

/// A missing resource must surface as an error, not hang.
#[tokio::test]
async fn unknown_resource_errors() {
    let addr = spawn(Router::new().with_value_stream(
        move |resource: &str| (resource == "payload").then(sample_payload),
        small_chunks(Compression::None),
    ));
    let client = AsyncClient::connect(addr).await.expect("connect");
    let got = pull_value_async::<Payload, _>(&client, "does-not-exist").await;
    assert!(got.is_err(), "unknown resource must error");
}

// ---- opaque byte (reader) streams --------------------------------------------

/// ~1 MiB of a non-trivial byte pattern; spans many 16 KiB chunks so reassembly
/// and the async pull/decode bridge are exercised across many `next` round trips.
fn raw_blob() -> Vec<u8> {
    (0..1_000_000u32)
        .map(|i| (i.wrapping_mul(2_654_435_761) >> 24) as u8)
        .collect()
}

/// A fresh, process-unique temp directory for a file-mode test.
fn temp_dir(tag: &str) -> std::path::PathBuf {
    let dir = std::env::temp_dir().join(format!("svs-async-{tag}-{}", std::process::id()));
    std::fs::create_dir_all(&dir).unwrap();
    dir
}

/// A router that streams `blob` verbatim (opaque bytes) for the key `"blob"`.
fn reader_router(blob: Vec<u8>, compression: Compression) -> Router {
    Router::new().with_reader_stream(
        move |resource: &str| (resource == "blob").then(|| Cursor::new(blob.clone())),
        small_chunks(compression),
    )
}

#[tokio::test]
async fn reader_stream_to_file_is_byte_identical() {
    let blob = raw_blob();
    let addr = spawn(reader_router(blob.clone(), Compression::None));
    let client = AsyncClient::connect(addr).await.expect("connect");

    let dir = temp_dir("raw-file");
    let path = dir.join("blob.bin");
    let n = pull_to_file_async(&client, "blob", &path)
        .await
        .expect("pull");
    assert_eq!(n as usize, blob.len());
    assert_eq!(std::fs::read(&path).unwrap(), blob);

    std::fs::remove_dir_all(&dir).ok();
}

#[tokio::test]
async fn consume_async_reads_decompressed_content() {
    let blob = raw_blob();
    let addr = spawn(reader_router(blob.clone(), Compression::Zstd));
    let client = AsyncClient::connect(addr).await.expect("connect");

    let got: Vec<u8> = pull_consume_async(&client, "blob", |mut r: Box<dyn Read>| {
        let mut buf = Vec::new();
        r.read_to_end(&mut buf)?;
        Ok(buf)
    })
    .await
    .expect("consume");
    assert_eq!(got, blob, "consume must see the decompressed content");
}

#[tokio::test]
async fn verified_pull_commits_when_the_digest_matches() {
    let blob = raw_blob();
    let addr = spawn(reader_router(blob.clone(), Compression::None));
    let client = AsyncClient::connect(addr).await.expect("connect");

    let dir = temp_dir("verify-ok");
    let path = dir.join("blob.bin");

    // `Vec<u8>` is the digest sink: it collects every teed content byte, so the
    // verify both checks integrity and proves the tee saw exactly the content.
    let expected = blob.clone();
    pull_to_file_verified_async(
        &client,
        "blob",
        &path,
        Vec::<u8>::new(),
        move |seen: Vec<u8>| {
            if seen == expected {
                Ok(())
            } else {
                Err(RepeError::Io(io::Error::other("digest mismatch")))
            }
        },
    )
    .await
    .expect("verified pull");
    assert_eq!(std::fs::read(&path).unwrap(), blob);

    std::fs::remove_dir_all(&dir).ok();
}

#[tokio::test]
async fn verified_pull_commits_nothing_when_rejected() {
    let blob = raw_blob();
    let addr = spawn(reader_router(blob, Compression::None));
    let client = AsyncClient::connect(addr).await.expect("connect");

    let dir = temp_dir("verify-bad");
    let path = dir.join("blob.bin");

    let err = pull_to_file_verified_async(
        &client,
        "blob",
        &path,
        Vec::<u8>::new(),
        |_seen: Vec<u8>| Err(RepeError::Io(io::Error::other("rejected by test"))),
    )
    .await
    .unwrap_err();
    assert!(matches!(err, RepeError::Io(_)));
    assert!(!path.exists(), "a rejected verify must not commit the file");
    assert!(
        !dir.join("blob.bin.svspart").exists(),
        "the temp sibling must be cleaned up on rejection"
    );

    std::fs::remove_dir_all(&dir).ok();
}

#[tokio::test]
async fn pull_to_vec_async_returns_the_whole_decompressed_payload() {
    let blob = raw_blob();
    let addr = spawn(reader_router(blob.clone(), Compression::Zstd));
    let client = AsyncClient::connect(addr).await.expect("connect");
    let got = pull_to_vec_async(&client, "blob")
        .await
        .expect("pull to vec");
    assert_eq!(
        got, blob,
        "pull_to_vec_async must return the full logical content"
    );
}

// ---- app-written (writer) digest streams: the in-stream trailer hatch --------

const FNV_OFFSET: u64 = 0xcbf2_9ce4_8422_2325;
const FNV_PRIME: u64 = 0x0000_0100_0000_01b3;

/// A `Write` that folds forwarded bytes into an FNV-1a hash — used as the producer
/// tee (wrapping the sink) and, over `io::sink()`, as the consumer digest sink.
struct FnvHash<W> {
    inner: W,
    hash: u64,
}

impl<W> FnvHash<W> {
    fn new(inner: W) -> Self {
        Self {
            inner,
            hash: FNV_OFFSET,
        }
    }
    fn finish(self) -> u64 {
        self.hash
    }
}

impl<W: Write> Write for FnvHash<W> {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        let n = self.inner.write(buf)?;
        for &b in &buf[..n] {
            self.hash ^= b as u64;
            self.hash = self.hash.wrapping_mul(FNV_PRIME);
        }
        Ok(n)
    }
    fn flush(&mut self) -> io::Result<()> {
        self.inner.flush()
    }
}

/// `verify` for the trailer puller: finalize the FNV digest and compare it to the
/// little-endian trailer.
fn check_fnv(digest: FnvHash<io::Sink>, trailer: &[u8]) -> Result<(), RepeError> {
    let claimed = u64::from_le_bytes(trailer.try_into().expect("8-byte trailer"));
    if digest.finish() == claimed {
        Ok(())
    } else {
        Err(RepeError::Io(io::Error::new(
            io::ErrorKind::InvalidData,
            "svs: trailer digest mismatch",
        )))
    }
}

/// A router that streams `payload || fnv8(payload)` for the key `"payload"` in one
/// pass. With `corrupt`, the appended digest is bit-inverted so an honest consumer
/// recompute rejects it.
fn writer_digest_router(payload: Payload, corrupt: bool, compression: Compression) -> Router {
    Router::new().with_writer_stream(
        BodyFormat::RawBinary,
        move |resource: &str| {
            (resource == "payload").then(|| {
                let value = payload.clone();
                move |w: &mut dyn Write| -> io::Result<()> {
                    let mut tee = FnvHash::new(&mut *w);
                    beve::to_writer_streaming(&mut tee, &value)
                        .map_err(|e| io::Error::other(e.to_string()))?;
                    let mut digest = tee.finish();
                    if corrupt {
                        digest ^= u64::MAX;
                    }
                    w.write_all(&digest.to_le_bytes())?;
                    Ok(())
                }
            })
        },
        small_chunks(compression),
    )
}

/// The exact bytes `beve::to_writer_streaming` produces for `payload`.
fn streamed_payload_bytes(payload: &Payload) -> Vec<u8> {
    let mut buf = Vec::new();
    beve::to_writer_streaming(&mut buf, payload).expect("stream-encode payload");
    buf
}

#[tokio::test]
async fn trailer_verified_async_commits_payload_only() {
    let payload = sample_payload();
    let addr = spawn(writer_digest_router(
        payload.clone(),
        false,
        Compression::Zstd,
    ));
    let client = AsyncClient::connect(addr).await.expect("connect");

    let dir = temp_dir("tv-ok");
    let path = dir.join("payload.beve");
    pull_to_file_trailer_verified_async(
        &client,
        "payload",
        &path,
        8,
        FnvHash::new(io::sink()),
        check_fnv,
    )
    .await
    .expect("verified trailer pull");

    let bytes = std::fs::read(&path).unwrap();
    assert_eq!(
        bytes,
        streamed_payload_bytes(&payload),
        "committed file must be the payload with the 8-byte trailer stripped"
    );
    let decoded: Payload = beve::from_slice(&bytes).unwrap();
    assert_eq!(decoded, payload);

    std::fs::remove_dir_all(&dir).ok();
}

#[tokio::test]
async fn trailer_verified_async_rejects_a_tampered_trailer_and_commits_nothing() {
    let payload = sample_payload();
    let addr = spawn(writer_digest_router(payload, true, Compression::None));
    let client = AsyncClient::connect(addr).await.expect("connect");

    let dir = temp_dir("tv-bad");
    let path = dir.join("payload.beve");
    let err = pull_to_file_trailer_verified_async(
        &client,
        "payload",
        &path,
        8,
        FnvHash::new(io::sink()),
        check_fnv,
    )
    .await
    .unwrap_err();
    assert!(matches!(err, RepeError::Io(_)));
    assert!(!path.exists(), "a digest mismatch must not commit a file");
    assert!(
        !dir.join("payload.beve.svspart").exists(),
        "the temp sibling must be cleaned up on rejection"
    );

    std::fs::remove_dir_all(&dir).ok();
}

/// A router that streams several real chunks and then aborts the producer before
/// the terminating chunk — the async twin of the sync mid-stream-abort test,
/// exercising the `Msg::Fail` path (a genuine mid-stream failure, not a clean-short
/// stream and not a failure at `open`). The 64 KiB write flushes past the 16 KiB
/// chunk size and the one-chunk lookahead, so real payload reaches the consumer's
/// temp file before the abort surfaces. Uncompressed keeps the chunk flow
/// deterministic (a zstd encoder buffers, so an abort mid-frame might emit nothing).
fn writer_aborts_midstream_router() -> Router {
    Router::new().with_writer_stream(
        BodyFormat::RawBinary,
        move |resource: &str| {
            (resource == "aborts").then_some(|w: &mut dyn Write| -> io::Result<()> {
                w.write_all(&vec![0xA5u8; 64 * 1024])?;
                Err(io::Error::other("svs: producer aborted mid-stream"))
            })
        },
        small_chunks(Compression::None),
    )
}

#[tokio::test]
async fn trailer_verified_async_rejects_a_midstream_abort_and_commits_nothing() {
    // Chunks flow, then the producer fails before `last`. `run_pull` surfaces the
    // pull error *before* the consume result, so the otherwise-`Ok` temp guard is
    // dropped and removed and nothing is committed. The surfaced error is the raw
    // server error (`ServerError`), not the sync path's `io`-wrapped form.
    let addr = spawn(writer_aborts_midstream_router());
    let client = AsyncClient::connect(addr).await.expect("connect");

    let dir = temp_dir("tv-abort");
    let path = dir.join("payload.beve");
    let err = pull_to_file_trailer_verified_async(
        &client,
        "aborts",
        &path,
        8,
        FnvHash::new(io::sink()),
        check_fnv,
    )
    .await
    .unwrap_err();
    assert!(
        matches!(err, RepeError::ServerError { .. }),
        "a mid-stream abort must surface as an error, got {err:?}"
    );
    assert!(
        err.to_string().contains("aborted mid-stream"),
        "the error must be the producer's mid-stream abort, not an open failure: {err:?}"
    );
    assert!(
        !path.exists(),
        "a truncated transfer must not commit a file"
    );
    assert!(
        !dir.join("payload.beve.svspart").exists(),
        "the temp sibling must be cleaned up after a mid-stream abort"
    );

    std::fs::remove_dir_all(&dir).ok();
}

// The same async pullers drive a `WebSocketClient`. The WebSocket server runs
// the SVS `next` handler off the reader task (it honours `Execution::OffReader`),
// so blocking for backpressure there is fine.
#[cfg(feature = "websocket")]
mod websocket {
    use super::*;
    use repe::{WebSocketClient, WebSocketServer};

    /// Spawn a detached WebSocket server for `router` on path `/repe` and return a
    /// connected client.
    async fn ws_client(router: Router) -> WebSocketClient {
        let listener = WebSocketServer::listen("127.0.0.1:0").await.expect("bind");
        let addr = listener.local_addr().expect("addr");
        tokio::spawn(async move {
            let _ = WebSocketServer::new(router)
                .serve_listener(listener, "/repe")
                .await;
        });
        WebSocketClient::connect(&format!("ws://{addr}/repe"))
            .await
            .expect("connect")
    }

    #[tokio::test]
    async fn value_mode_over_websocket() {
        let payload = sample_payload();
        let p = payload.clone();
        let client = ws_client(Router::new().with_value_stream(
            move |resource: &str| (resource == "payload").then(|| p.clone()),
            small_chunks(Compression::Zstd),
        ))
        .await;
        let got: Payload = pull_value_async(&client, "payload").await.expect("pull");
        assert_eq!(got, payload);
    }

    #[tokio::test]
    async fn typed_slice_over_websocket() {
        let v = f64_samples();
        let vc = v.clone();
        let client = ws_client(Router::new().with_typed_value_stream(
            move |resource: &str| (resource == "buf").then(|| vc.clone()),
            small_chunks(Compression::None),
        ))
        .await;
        let got: Vec<f64> = pull_typed_slice_async(&client, "buf").await.expect("pull");
        assert_eq!(got, v);
    }

    #[tokio::test]
    async fn complex_slice_over_websocket() {
        let v = iq_samples();
        let vc = v.clone();
        let client = ws_client(Router::new().with_complex_value_stream(
            move |resource: &str| (resource == "iq").then(|| vc.clone()),
            small_chunks(Compression::Zstd),
        ))
        .await;
        let got: Vec<Complex<f32>> = pull_complex_slice_async(&client, "iq").await.expect("pull");
        assert_eq!(got, v);
    }

    // An opaque byte stream pulled to a verified file over WebSocket: the exact
    // shape a remote save uses (server streams bytes it already holds, client
    // writes a byte-identical copy and gates the rename on a content digest).
    #[tokio::test]
    async fn verified_reader_stream_over_websocket() {
        let blob = raw_blob();
        let client = ws_client(reader_router(blob.clone(), Compression::None)).await;

        let dir = temp_dir("ws-verify");
        let path = dir.join("blob.bin");
        let expected = blob.clone();
        pull_to_file_verified_async(
            &client,
            "blob",
            &path,
            Vec::<u8>::new(),
            move |seen: Vec<u8>| {
                (seen == expected)
                    .then_some(())
                    .ok_or_else(|| RepeError::Io(io::Error::other("digest mismatch")))
            },
        )
        .await
        .expect("verified ws pull");
        assert_eq!(std::fs::read(&path).unwrap(), blob);

        std::fs::remove_dir_all(&dir).ok();
    }
}