evento-remote 2.0.0-alpha.40

Client/server remote executor for evento — serve any executor over framed TCP
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
//! Wire protocol: tagged bitcode frames over a length-delimited TCP stream.
//!
//! Every frame is a 4-byte header (magic + format version + direction) followed
//! by the bitcode encoding of a [`ClientFrame`] or [`ServerFrame`]. bitcode is
//! positional and not self-describing, so the header is what turns a schema or
//! dialect mismatch into a loud error instead of garbage. The magic (`Er`) is
//! distinct from evento-cluster's (`Ac`), so pointing a remote client at an
//! cluster port fails immediately.

use evento_core::cursor::{Args, PageInfo, Value};
use evento_core::{Event, EventFilter, RoutingKey, TenantFilter, WriteError};
use serde::{de::DeserializeOwned, Deserialize, Serialize};
use ulid::Ulid;

/// Identifies an evento-remote frame. Guards against decoding an unrelated
/// byte stream (a misconfigured port, a different protocol) as a valid frame.
pub const MAGIC: [u8; 2] = *b"Er";

/// Current wire format version. Bump on any breaking change to the frame
/// enums' layout; add the matching decode branch then.
/// v2: `Read` gained `to_micros`; added `SubscriberStatus`, `LatestVersion`
/// and `StreamRoutingKey` requests.
/// v3: the snapshot requests gained `projection` (snapshots are keyed by
/// projection name).
/// v4: `Hello` carries an optional token and its reply may refuse the
/// connection; the server requires `Hello` as the first frame.
/// v5: tenants — events carry their tenant, every scan request a
/// `TenantFilter`, and every identity and snapshot request a tenant.
/// v6: write interests — the client registers what it watches with `Watch`
/// and `Unwatch`, and `Notify` names the watches it wakes instead of being
/// pushed for every write.
pub const FORMAT_VERSION: u8 = 6;

/// Length of the fixed header: `MAGIC (2) + version (1) + kind (1)`.
const HEADER_LEN: usize = 4;

/// Which direction a frame travels. A misconfigured peer that parses its own
/// dialect (client reading client frames) errors instead of mis-decoding.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum RecordKind {
    /// A [`ClientFrame`] (client → server).
    ClientFrame = 1,
    /// A [`ServerFrame`] (server → client).
    ServerFrame = 2,
}

impl RecordKind {
    fn from_byte(b: u8) -> Option<Self> {
        match b {
            1 => Some(Self::ClientFrame),
            2 => Some(Self::ServerFrame),
            _ => None,
        }
    }
}

/// Frames above the codec's 8 MB default exist in practice (large read chunks,
/// snapshot blobs), so both sides raise the cap.
pub const MAX_FRAME_LENGTH: usize = 64 * 1024 * 1024;

/// Serializes `value` as a tagged frame: the 4-byte header followed by its
/// bitcode encoding.
pub fn encode_tagged<T: Serialize>(kind: RecordKind, value: &T) -> anyhow::Result<Vec<u8>> {
    let payload = bitcode::serialize(value)?;
    let mut out = Vec::with_capacity(HEADER_LEN + payload.len());
    out.extend_from_slice(&MAGIC);
    out.push(FORMAT_VERSION);
    out.push(kind as u8);
    out.extend_from_slice(&payload);
    Ok(out)
}

/// Deserializes a tagged frame, validating the header first. Fails loudly —
/// bad magic, an unknown format version, or a mismatched kind all error rather
/// than risk decoding the payload under the wrong schema.
pub fn decode_tagged<T: DeserializeOwned>(expected: RecordKind, bytes: &[u8]) -> anyhow::Result<T> {
    if bytes.len() < HEADER_LEN {
        anyhow::bail!("frame too short: {} bytes", bytes.len());
    }
    if bytes[0..2] != MAGIC {
        anyhow::bail!("bad frame magic");
    }
    let version = bytes[2];
    if version != FORMAT_VERSION {
        anyhow::bail!(
            "unsupported wire format version {version} (this build speaks {FORMAT_VERSION})"
        );
    }
    let kind = RecordKind::from_byte(bytes[3])
        .ok_or_else(|| anyhow::anyhow!("unknown frame kind {}", bytes[3]))?;
    if kind != expected {
        anyhow::bail!("frame kind mismatch: expected {expected:?}, found {kind:?}");
    }
    Ok(bitcode::deserialize(&bytes[HEADER_LEN..])?)
}

/// A client → server frame: a request with a per-connection correlation id,
/// or what the client watches the writes for. The watch frames get no reply.
#[derive(Debug, Serialize, Deserialize)]
pub enum ClientFrame {
    Request {
        id: u64,
        request: Request,
    },
    /// Registers a watch: the server pushes a [`ServerFrame::Notify`] naming
    /// `watch` at once, then after each write that holds an event a read
    /// with this filter returns (see
    /// [`WriteInterest`](evento_core::WriteInterest)). `watch` is the
    /// client's choice, unique on the connection.
    Watch {
        watch: u64,
        filters: Option<Vec<EventFilter>>,
        routing_key: Option<RoutingKey>,
        tenant: TenantFilter,
    },
    /// Drops a watch; unknown ids are ignored.
    Unwatch {
        watch: u64,
    },
}

/// A server → client frame: either a correlated reply or an unsolicited write
/// notification. Every frame piggybacks the server executor's
/// `stable_timestamp` so the client's cached watermark is at least as fresh as
/// the data it accompanies (the watermark only advances, so a stale-low cache
/// is merely conservative, never unsafe).
#[derive(Debug, Serialize, Deserialize)]
pub enum ServerFrame {
    Response {
        id: u64,
        response: Response,
        stable_timestamp: Option<u64>,
    },
    /// Pushed when a watch is registered and after each server-side write
    /// one of the connection's watches follows; wakes the client-side
    /// subscriptions behind `watches` without waiting for their poll
    /// interval.
    Notify {
        watches: Vec<u64>,
        stable_timestamp: Option<u64>,
    },
}

/// One variant per [`Executor`](evento_core::Executor) method that crosses the
/// wire, plus the connect-time `Hello` exchange.
#[derive(Debug, Serialize, Deserialize)]
pub enum Request {
    /// The first frame of every connection: the credential the server's
    /// resolver authenticates (none for an open server). The reply carries
    /// connection-scoped facts the sync `Executor` methods need cached
    /// client-side, or the reason the connection is refused.
    Hello {
        token: Option<Token>,
    },
    Write {
        #[serde(with = "wire_events")]
        events: Vec<Event>,
    },
    /// Persist pre-stamped events verbatim (see `Executor::replicate`).
    Replicate {
        #[serde(with = "wire_events")]
        events: Vec<Event>,
    },
    Read {
        aggregators: Option<Vec<EventFilter>>,
        routing_key: Option<RoutingKey>,
        tenant: TenantFilter,
        args: Args,
        /// Exclusive stamp bound (see `Executor::read`).
        to_micros: Option<u64>,
    },
    LatestTimestamp {
        aggregators: Option<Vec<EventFilter>>,
        routing_key: Option<RoutingKey>,
        tenant: TenantFilter,
    },
    GetSubscriberCursor {
        key: String,
    },
    IsSubscriberRunning {
        key: String,
        worker_id: Ulid,
    },
    /// Fencing state + cursor in one round trip (see
    /// `Executor::subscriber_status`).
    SubscriberStatus {
        key: String,
        worker_id: Ulid,
    },
    /// Highest committed version of a stream (see `Executor::latest_version`).
    LatestVersion {
        tenant: String,
        aggregate_type: String,
        aggregate_id: String,
    },
    /// Routing key of an existing stream (see `Executor::stream_routing_key`).
    StreamRoutingKey {
        tenant: String,
        aggregate_type: String,
        aggregate_id: String,
    },
    UpsertSubscriber {
        key: String,
        worker_id: Ulid,
    },
    Acknowledge {
        key: String,
        worker_id: Ulid,
        cursor: Value,
        lag: u64,
    },
    GetSnapshot {
        tenant: String,
        aggregate_type: String,
        projection: String,
        aggregate_revision: String,
        id: String,
    },
    SaveSnapshot {
        tenant: String,
        aggregate_type: String,
        projection: String,
        aggregate_revision: String,
        id: String,
        data: Vec<u8>,
        cursor: Value,
    },
    DeleteSnapshot {
        tenant: String,
        aggregate_type: String,
        projection: String,
        id: String,
    },
}

/// Reply payloads. `anyhow` errors travel as their `Display` string and are
/// rewrapped client-side; `write` keeps variant fidelity via
/// [`WireWriteError`] because callers match on it (retry-on-conflict).
#[derive(Debug, Serialize, Deserialize)]
pub enum Response {
    Hello(Result<HelloOk, Rejection>),
    Write(Result<(), WireWriteError>),
    Read(Result<WireReadResult, String>),
    LatestTimestamp(Result<u64, String>),
    SubscriberCursor(Result<Option<Value>, String>),
    SubscriberRunning(Result<bool, String>),
    SubscriberStatus(Result<evento_core::SubscriberStatus, String>),
    LatestVersion(Result<u16, String>),
    /// Outer `None`: the stream does not exist; inner: its routing key.
    StreamRoutingKey(Result<Option<Option<String>>, String>),
    /// Whether the fenced cursor update was applied (false: lost ownership).
    Acknowledge(Result<bool, String>),
    /// upsert_subscriber, save_snapshot, delete_snapshot.
    Unit(Result<(), String>),
    Snapshot(Result<Option<(Vec<u8>, Value)>, String>),
}

/// A credential presented at `Hello`. Its `Debug` is redacted: frames are
/// logged at debug level, and a token must never land in a log.
#[derive(Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct Token(pub String);

impl std::fmt::Debug for Token {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("Token(******)")
    }
}

/// What an accepted connection learns at `Hello`.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct HelloOk {
    /// The served executor's default routing key, fixed for the connection.
    pub default_routing_key: Option<String>,
}

/// Why a server refused a connection at `Hello`.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum Rejection {
    /// No token, or one the resolver does not accept.
    Unauthorized,
    /// The token is fine but what it names cannot be served right now; the
    /// text is for the client's logs.
    Unavailable(String),
}

impl std::fmt::Display for Rejection {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Rejection::Unauthorized => f.write_str("unauthorized"),
            Rejection::Unavailable(reason) => write!(f, "unavailable: {reason}"),
        }
    }
}

impl std::error::Error for Rejection {}

/// `ReadResult<Event>` cannot derive serde (`Event` is not serde), so edges
/// travel as parallel `cursors`/`events` vectors and are re-zipped client-side.
#[derive(Debug, Serialize, Deserialize)]
pub struct WireReadResult {
    pub cursors: Vec<Value>,
    #[serde(with = "wire_events")]
    pub events: Vec<Event>,
    pub page_info: PageInfo,
}

impl From<evento_core::cursor::ReadResult<Event>> for WireReadResult {
    fn from(result: evento_core::cursor::ReadResult<Event>) -> Self {
        let (cursors, events) = result.edges.into_iter().map(|e| (e.cursor, e.node)).unzip();
        WireReadResult {
            cursors,
            events,
            page_info: result.page_info,
        }
    }
}

impl From<WireReadResult> for evento_core::cursor::ReadResult<Event> {
    fn from(wire: WireReadResult) -> Self {
        evento_core::cursor::ReadResult {
            edges: wire
                .cursors
                .into_iter()
                .zip(wire.events)
                .map(|(cursor, node)| evento_core::cursor::Edge { cursor, node })
                .collect(),
            page_info: wire.page_info,
        }
    }
}

/// Serde mirror of [`WriteError`], which is not itself serializable.
/// `InvalidOriginalVersion` and `MissingData` map 1:1 — `WriteBuilder`'s
/// retry-on-conflict matches on the variant, so fidelity matters — and so
/// does `Unavailable`, which a client shows as a transient refusal rather
/// than a failure (its cause travels as its `Display` string);
/// `Unknown`/`SystemTime` collapse to their `Display` strings.
#[derive(Debug, Serialize, Deserialize)]
pub enum WireWriteError {
    InvalidOriginalVersion,
    MissingData,
    Other(String),
    Unavailable(String),
}

impl From<&WriteError> for WireWriteError {
    fn from(e: &WriteError) -> Self {
        match e {
            WriteError::InvalidOriginalVersion => WireWriteError::InvalidOriginalVersion,
            WriteError::MissingData => WireWriteError::MissingData,
            WriteError::Unavailable(cause) => WireWriteError::Unavailable(cause.to_string()),
            other => WireWriteError::Other(other.to_string()),
        }
    }
}

impl From<WireWriteError> for WriteError {
    fn from(e: WireWriteError) -> Self {
        match e {
            WireWriteError::InvalidOriginalVersion => WriteError::InvalidOriginalVersion,
            WireWriteError::MissingData => WriteError::MissingData,
            WireWriteError::Other(msg) => WriteError::Unknown(anyhow::anyhow!(msg)),
            WireWriteError::Unavailable(cause) => WriteError::Unavailable(anyhow::anyhow!(cause)),
        }
    }
}

// NOTE: keep in sync with evento-cluster/src/message.rs `mod wire_events`.
/// Serde bridge for `Vec<Event>`. evento's [`Event`] is not itself
/// (de)serializable, so it is mirrored field-for-field by [`WireEvent`], whose
/// only non-trivial field is the bitcode-encoded
/// [`Metadata`](evento_core::metadata::Metadata). This lets the frame enums
/// derive serde without modifying evento-core.
mod wire_events {
    use evento_core::{metadata::Metadata, Event};
    use serde::{Deserialize, Deserializer, Serialize, Serializer};
    use ulid::Ulid;

    #[derive(Serialize, Deserialize)]
    struct WireEvent {
        id: Ulid,
        aggregate_id: String,
        aggregate_type: String,
        version: u16,
        name: String,
        routing_key: Option<String>,
        tenant: String,
        data: Vec<u8>,
        /// bitcode-encoded [`Metadata`].
        metadata: Vec<u8>,
        timestamp: u64,
        timestamp_subsec: u32,
    }

    impl From<&Event> for WireEvent {
        fn from(e: &Event) -> Self {
            WireEvent {
                id: e.id,
                aggregate_id: e.aggregate_id.clone(),
                aggregate_type: e.aggregate_type.clone(),
                version: e.version,
                name: e.name.clone(),
                routing_key: e.routing_key.clone(),
                tenant: e.tenant.clone(),
                data: e.data.clone(),
                metadata: bitcode::encode(&e.metadata),
                timestamp: e.timestamp,
                timestamp_subsec: e.timestamp_subsec,
            }
        }
    }

    impl TryFrom<WireEvent> for Event {
        type Error = bitcode::Error;

        fn try_from(w: WireEvent) -> Result<Self, Self::Error> {
            Ok(Event {
                id: w.id,
                aggregate_id: w.aggregate_id,
                aggregate_type: w.aggregate_type,
                version: w.version,
                name: w.name,
                routing_key: w.routing_key,
                tenant: w.tenant,
                data: w.data,
                metadata: bitcode::decode::<Metadata>(&w.metadata)?,
                timestamp: w.timestamp,
                timestamp_subsec: w.timestamp_subsec,
            })
        }
    }

    pub fn serialize<S: Serializer>(events: &[Event], s: S) -> Result<S::Ok, S::Error> {
        let wire: Vec<WireEvent> = events.iter().map(WireEvent::from).collect();
        wire.serialize(s)
    }

    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Vec<Event>, D::Error> {
        Vec::<WireEvent>::deserialize(d)?
            .into_iter()
            .map(|w| Event::try_from(w).map_err(serde::de::Error::custom))
            .collect()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use evento_core::metadata::Metadata;

    fn sample_event() -> Event {
        let mut metadata = Metadata::default();
        metadata.set_requested_by("tester");
        Event {
            id: Ulid::generate(),
            aggregate_id: "agg-1".to_owned(),
            aggregate_type: "account".to_owned(),
            version: 7,
            name: "opened".to_owned(),
            routing_key: Some("eu".to_owned()),
            tenant: "acme".to_owned(),
            data: vec![1, 2, 3],
            metadata,
            timestamp: 1_700_000_000,
            timestamp_subsec: 42,
        }
    }

    #[test]
    fn round_trips_each_kind() {
        for kind in [RecordKind::ClientFrame, RecordKind::ServerFrame] {
            let value = (42u64, "hello".to_string());
            let bytes = encode_tagged(kind, &value).unwrap();
            let back: (u64, String) = decode_tagged(kind, &bytes).unwrap();
            assert_eq!(back, value);
        }
    }

    #[test]
    fn rejects_bad_magic() {
        let mut bytes = encode_tagged(RecordKind::ClientFrame, &7u64).unwrap();
        bytes[0] = b'X';
        let err = decode_tagged::<u64>(RecordKind::ClientFrame, &bytes).unwrap_err();
        assert!(err.to_string().contains("magic"));
    }

    #[test]
    fn rejects_unknown_version() {
        let mut bytes = encode_tagged(RecordKind::ClientFrame, &7u64).unwrap();
        bytes[2] = FORMAT_VERSION + 1;
        let err = decode_tagged::<u64>(RecordKind::ClientFrame, &bytes).unwrap_err();
        assert!(err.to_string().contains("format version"));
    }

    #[test]
    fn rejects_kind_mismatch() {
        let bytes = encode_tagged(RecordKind::ClientFrame, &7u64).unwrap();
        let err = decode_tagged::<u64>(RecordKind::ServerFrame, &bytes).unwrap_err();
        assert!(err.to_string().contains("kind mismatch"));
    }

    #[test]
    fn rejects_truncated_input() {
        let bytes = [b'E', b'r', FORMAT_VERSION]; // one byte short of the header
        let err = decode_tagged::<u64>(RecordKind::ClientFrame, &bytes).unwrap_err();
        assert!(err.to_string().contains("too short"));
    }

    #[test]
    fn event_round_trip() {
        let event = sample_event();
        let frame = ClientFrame::Request {
            id: 9,
            request: Request::Write {
                events: vec![event.clone()],
            },
        };
        let bytes = encode_tagged(RecordKind::ClientFrame, &frame).unwrap();
        let back: ClientFrame = decode_tagged(RecordKind::ClientFrame, &bytes).unwrap();
        let ClientFrame::Request {
            id,
            request: Request::Write { events },
        } = back
        else {
            panic!("wrong frame");
        };
        assert_eq!(id, 9);
        assert_eq!(events, vec![event]);
    }

    #[test]
    fn watch_round_trip() {
        let frame = ClientFrame::Watch {
            watch: 3,
            filters: Some(vec![EventFilter::by_event_raw("account", "opened")]),
            routing_key: Some(RoutingKey::Value(Some("eu".to_owned()))),
            tenant: TenantFilter::Only("acme".to_owned()),
        };
        let bytes = encode_tagged(RecordKind::ClientFrame, &frame).unwrap();
        let back: ClientFrame = decode_tagged(RecordKind::ClientFrame, &bytes).unwrap();
        let ClientFrame::Watch {
            watch,
            filters,
            routing_key,
            tenant,
        } = back
        else {
            panic!("wrong frame");
        };
        assert_eq!(watch, 3);
        assert_eq!(
            filters,
            Some(vec![EventFilter::by_event_raw("account", "opened")])
        );
        assert!(matches!(
            routing_key,
            Some(RoutingKey::Value(Some(key))) if key == "eu"
        ));
        assert_eq!(tenant, TenantFilter::Only("acme".to_owned()));

        let frame = ServerFrame::Notify {
            watches: vec![3, 7],
            stable_timestamp: Some(9),
        };
        let bytes = encode_tagged(RecordKind::ServerFrame, &frame).unwrap();
        let back: ServerFrame = decode_tagged(RecordKind::ServerFrame, &bytes).unwrap();
        assert!(matches!(
            back,
            ServerFrame::Notify { watches, stable_timestamp: Some(9) } if watches == [3, 7]
        ));
    }

    #[test]
    fn hello_round_trip() {
        let hello = ClientFrame::Request {
            id: 0,
            request: Request::Hello {
                token: Some(Token("secret".to_owned())),
            },
        };
        let bytes = encode_tagged(RecordKind::ClientFrame, &hello).unwrap();
        let back: ClientFrame = decode_tagged(RecordKind::ClientFrame, &bytes).unwrap();
        let ClientFrame::Request {
            request: Request::Hello { token: Some(token) },
            ..
        } = back
        else {
            panic!("wrong frame");
        };
        assert_eq!(token.0, "secret");
        assert!(!format!("{token:?}").contains("secret"), "{token:?}");

        for response in [
            Response::Hello(Ok(HelloOk {
                default_routing_key: Some("eu".to_owned()),
            })),
            Response::Hello(Err(Rejection::Unavailable("down".to_owned()))),
        ] {
            let frame = ServerFrame::Response {
                id: 0,
                response,
                stable_timestamp: None,
            };
            let bytes = encode_tagged(RecordKind::ServerFrame, &frame).unwrap();
            let back: ServerFrame = decode_tagged(RecordKind::ServerFrame, &bytes).unwrap();
            let ServerFrame::Response {
                response: Response::Hello(reply),
                ..
            } = back
            else {
                panic!("wrong frame");
            };
            match reply {
                Ok(ok) => assert_eq!(ok.default_routing_key.as_deref(), Some("eu")),
                Err(err) => assert_eq!(err.to_string(), "unavailable: down"),
            }
        }
    }

    #[test]
    fn read_result_round_trip() {
        let event = sample_event();
        let read = evento_core::cursor::ReadResult {
            edges: vec![evento_core::cursor::Edge {
                cursor: Value("cur".to_owned()),
                node: event,
            }],
            page_info: PageInfo {
                has_previous_page: true,
                has_next_page: false,
                start_cursor: Some(Value("cur".to_owned())),
                end_cursor: Some(Value("cur".to_owned())),
            },
        };
        let wire = WireReadResult::from(read.clone());
        let bytes = bitcode::serialize(&wire).unwrap();
        let back: WireReadResult = bitcode::deserialize(&bytes).unwrap();
        assert_eq!(evento_core::cursor::ReadResult::<Event>::from(back), read);
    }

    #[test]
    fn write_error_round_trip() {
        let cases = [
            WriteError::InvalidOriginalVersion,
            WriteError::MissingData,
            WriteError::Unknown(anyhow::anyhow!("boom")),
            WriteError::Unavailable(anyhow::anyhow!("backlog at cap")),
        ];
        for original in cases {
            let wire = WireWriteError::from(&original);
            let bytes = bitcode::serialize(&wire).unwrap();
            let back: WireWriteError = bitcode::deserialize(&bytes).unwrap();
            let back = WriteError::from(back);
            assert_eq!(back.to_string(), original.to_string(), "message fidelity");
            assert_eq!(
                matches!(back, WriteError::Unavailable(_)),
                matches!(original, WriteError::Unavailable(_)),
                "a transient refusal stays one across the wire"
            );
        }
    }
}