wse 3.2.0

WebSocket engine for reactive user interfaces: topics with message recovery, presence, clustering without a broker, JWT, end-to-end encryption and signed messages.
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
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
//! The cluster wire protocol: message types, frame encoding and decoding, the
//! length-prefix framing and version / capability negotiation.

use bytes::{Buf, BufMut, Bytes, BytesMut};

use super::{
    COMPRESSION_THRESHOLD, FLAG_ARRIVAL, FLAG_COMPRESSED, FLAG_HAS_RECOVERY, FLAG_REPLAYED, MAGIC,
    MAX_CLUSTER_PEERS, MAX_FRAME_SIZE, MAX_KNOWN_PEERS, PROTOCOL_VERSION, PROTOCOL_VERSION_MIN,
};
use crate::server::{Decided, Hole, MAX_HOLES, Refusal};

// ---------------------------------------------------------------------------
// Message types
// ---------------------------------------------------------------------------

#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum MsgType {
    Msg = 0x01,
    Ping = 0x02,
    Pong = 0x03,
    Hello = 0x04,
    Shutdown = 0x05,
    Sub = 0x06,
    Unsub = 0x07,
    Resync = 0x08,
    PeerAnnounce = 0x09,
    PeerList = 0x0A,
    PresenceUpdate = 0x0B,
    PresenceFull = 0x0C,
    Drain = 0x0D,
    Resume = 0x0E,
    /// What the peer took of a client's producer; the peer hands it over.
    ProducerQuery = 0x0F,
    /// The answer to a PRODUCER_QUERY.
    ProducerState = 0x10,
    /// Messages of a topic were published that no node holds.
    Lost = 0x11,
    /// The catch-up covers what the sender published up to an arrival.
    CaughtUp = 0x12,
}

impl MsgType {
    fn from_u8(v: u8) -> Option<Self> {
        match v {
            0x01 => Some(Self::Msg),
            0x02 => Some(Self::Ping),
            0x03 => Some(Self::Pong),
            0x04 => Some(Self::Hello),
            0x05 => Some(Self::Shutdown),
            0x06 => Some(Self::Sub),
            0x07 => Some(Self::Unsub),
            0x08 => Some(Self::Resync),
            0x09 => Some(Self::PeerAnnounce),
            0x0A => Some(Self::PeerList),
            0x0B => Some(Self::PresenceUpdate),
            0x0C => Some(Self::PresenceFull),
            0x0D => Some(Self::Drain),
            0x0E => Some(Self::Resume),
            0x0F => Some(Self::ProducerQuery),
            0x10 => Some(Self::ProducerState),
            0x11 => Some(Self::Lost),
            0x12 => Some(Self::CaughtUp),
            _ => None,
        }
    }
}

// ---------------------------------------------------------------------------
// Wire protocol encoding
// ---------------------------------------------------------------------------

/// Encode a MSG frame into buf. Returns false if topic exceeds 64KB.
/// Format: [u8 type][u8 flags][u16 LE topic_len][u32 LE payload_len][topic][payload]
#[cfg(test)]
pub(crate) fn encode_msg(buf: &mut BytesMut, topic: &str, payload: &str) -> bool {
    let topic_bytes = topic.as_bytes();
    if topic_bytes.len() > u16::MAX as usize {
        tracing::warn!(
            "[WSE-Cluster] Topic too long ({} bytes, max {}), dropping message",
            topic_bytes.len(),
            u16::MAX
        );
        return false;
    }
    let payload_bytes = payload.as_bytes();
    let total_frame = 8 + topic_bytes.len() + payload_bytes.len();
    if total_frame > MAX_FRAME_SIZE {
        tracing::warn!(
            "[WSE-Cluster] Frame too large ({total_frame} bytes, max {MAX_FRAME_SIZE}), dropping message",
        );
        return false;
    }
    buf.reserve(total_frame);
    buf.put_u8(MsgType::Msg as u8);
    buf.put_u8(0); // flags
    buf.put_u16_le(topic_bytes.len() as u16);
    buf.put_u32_le(payload_bytes.len() as u32);
    buf.put_slice(topic_bytes);
    buf.put_slice(payload_bytes);
    true
}

/// Encode a MSG frame with zstd compression on the payload.
/// Compresses only if payload >= COMPRESSION_THRESHOLD and compressed size < original.
/// Falls back to uncompressed encoding if compression doesn't help.
#[cfg(test)]
pub(crate) fn encode_msg_compressed(buf: &mut BytesMut, topic: &str, payload: &str) -> bool {
    let topic_bytes = topic.as_bytes();
    if topic_bytes.len() > u16::MAX as usize {
        tracing::warn!(
            "[WSE-Cluster] Topic too long ({} bytes, max {}), dropping message",
            topic_bytes.len(),
            u16::MAX
        );
        return false;
    }
    let payload_bytes = payload.as_bytes();

    // Only attempt compression for payloads above threshold
    if payload_bytes.len() >= COMPRESSION_THRESHOLD
        && let Ok(compressed) = zstd::bulk::compress(payload_bytes, 1)
        && compressed.len() < payload_bytes.len()
    {
        buf.reserve(8 + topic_bytes.len() + compressed.len());
        buf.put_u8(MsgType::Msg as u8);
        buf.put_u8(FLAG_COMPRESSED);
        buf.put_u16_le(topic_bytes.len() as u16);
        buf.put_u32_le(compressed.len() as u32);
        buf.put_slice(topic_bytes);
        buf.put_slice(&compressed);
        return true;
    }

    // Fallback: uncompressed
    encode_msg(buf, topic, payload)
}

/// Encode a MSG frame with recovery trailer (origin epoch + offset).
/// Optionally compresses the payload with zstd. The 12-byte recovery trailer
/// is appended AFTER the payload (not included in payload_len).
#[cfg(test)]
pub(crate) fn encode_msg_with_recovery(
    buf: &mut BytesMut,
    topic: &str,
    payload: &str,
    origin_epoch: u32,
    origin_offset: u64,
    compress: bool,
) -> bool {
    encode_msg_full(
        buf,
        topic,
        payload,
        Some((origin_epoch, origin_offset)),
        None,
        compress,
    )
}

/// Encode a MSG frame: compressed when `compress` and it helps, with the
/// origin's recovery position (12 bytes after the payload, FLAG_HAS_RECOVERY)
/// and its arrival number (8 bytes after that, FLAG_ARRIVAL) when given.
/// False when the topic or the frame is too large.
pub(crate) fn encode_msg_full(
    buf: &mut BytesMut,
    topic: &str,
    payload: &str,
    recovery: Option<(u32, u64)>,
    arrival: Option<u64>,
    compress: bool,
) -> bool {
    let topic_bytes = topic.as_bytes();
    if topic_bytes.len() > u16::MAX as usize {
        return false;
    }
    let payload_bytes = payload.as_bytes();
    let compressed = (compress && payload_bytes.len() >= COMPRESSION_THRESHOLD)
        .then(|| zstd::bulk::compress(payload_bytes, 1).ok())
        .flatten()
        .filter(|compressed| compressed.len() < payload_bytes.len());
    let body: &[u8] = compressed.as_deref().unwrap_or(payload_bytes);
    let trailers = recovery.map_or(0, |_| 12) + arrival.map_or(0, |_| 8);
    let total = 8 + topic_bytes.len() + body.len() + trailers;
    if total > MAX_FRAME_SIZE {
        return false;
    }
    let mut flags = 0;
    if compressed.is_some() {
        flags |= FLAG_COMPRESSED;
    }
    if recovery.is_some() {
        flags |= FLAG_HAS_RECOVERY;
    }
    if arrival.is_some() {
        flags |= FLAG_ARRIVAL;
    }
    buf.reserve(total);
    buf.put_u8(MsgType::Msg as u8);
    buf.put_u8(flags);
    buf.put_u16_le(topic_bytes.len() as u16);
    buf.put_u32_le(body.len() as u32);
    buf.put_slice(topic_bytes);
    buf.put_slice(body);
    if let Some((epoch, offset)) = recovery {
        buf.put_u32_le(epoch);
        buf.put_u64_le(offset);
    }
    if let Some(seq) = arrival {
        buf.put_u64_le(seq);
    }
    true
}

/// Encode a CAUGHT_UP frame: the catch-up just sent covers what this node
/// published up to arrival `through`.
/// Format: [header: type=0x12, payload_len=8] [8 bytes: through (LE u64)]
pub(crate) fn encode_caught_up(buf: &mut BytesMut, through: u64) {
    buf.reserve(16);
    buf.put_u8(MsgType::CaughtUp as u8);
    buf.put_u8(0);
    buf.put_u16_le(0);
    buf.put_u32_le(8);
    buf.put_u64_le(through);
}

/// Encode a PING frame (header only, 8 bytes).
pub(crate) fn encode_ping(buf: &mut BytesMut) {
    buf.reserve(8);
    buf.put_u8(MsgType::Ping as u8);
    buf.put_u8(0);
    buf.put_u16_le(0);
    buf.put_u32_le(0);
}

/// Encode a PONG frame (header only, 8 bytes).
pub(crate) fn encode_pong(buf: &mut BytesMut) {
    buf.reserve(8);
    buf.put_u8(MsgType::Pong as u8);
    buf.put_u8(0);
    buf.put_u16_le(0);
    buf.put_u32_le(0);
}

/// Encode a HELLO frame.
/// Payload: magic(4) + version(2) + id_len(2) + id_bytes(N) + capabilities(4)
/// HELLO: the node's instance, protocol version and capabilities, and where
/// its peers reach it (`reached_at`: its cluster address, or `:port`, the
/// port on the address its links come from; empty when it does not say). A
/// node before 3.2 reads no further than the capabilities.
pub(crate) fn encode_hello(
    buf: &mut BytesMut,
    instance_id: &str,
    capabilities: u32,
    reached_at: &str,
) {
    let id_bytes = instance_id.as_bytes();
    let at = if reached_at.len() <= MAX_REACHED_AT {
        reached_at.as_bytes()
    } else {
        &[]
    };
    let payload_len = 4 + 2 + 2 + id_bytes.len() + 4 + 2 + at.len();
    buf.reserve(8 + payload_len);
    // Header
    buf.put_u8(MsgType::Hello as u8);
    buf.put_u8(0); // flags
    buf.put_u16_le(0); // topic_len (unused for HELLO)
    buf.put_u32_le(payload_len as u32);
    // Payload
    buf.put_slice(MAGIC);
    buf.put_u16_le(PROTOCOL_VERSION);
    buf.put_u16_le(id_bytes.len() as u16);
    buf.put_slice(id_bytes);
    buf.put_u32_le(capabilities);
    buf.put_u16_le(at.len() as u16);
    buf.put_slice(at);
}

/// The longest address a HELLO says the node is reached at.
const MAX_REACHED_AT: usize = 255;

/// Encode a SHUTDOWN frame (header only, 8 bytes).
pub(crate) fn encode_shutdown(buf: &mut BytesMut) {
    buf.reserve(8);
    buf.put_u8(MsgType::Shutdown as u8);
    buf.put_u8(0);
    buf.put_u16_le(0);
    buf.put_u32_le(0);
}

/// Encode a DRAIN frame. Header-only, 8 bytes (like Shutdown).
/// Tells peers this node is entering lame-duck mode.
/// No user: a client of a server without JWT accepted for none.
const NO_USER: u16 = u16::MAX;

/// Encode a PRODUCER_QUERY: what the peer took of `user`'s `producer`.
/// Format: [header, payload_len][u64 LE id][u16 LE user_len, 0xFFFF for none][user][u16 LE producer_len][producer]
pub(crate) fn encode_producer_query(
    buf: &mut BytesMut,
    id: u64,
    user: Option<&str>,
    producer: &str,
) {
    // Users and producers are short ids; anything longer is cut, and the
    // peer then knows nothing of it.
    let user = user.map(|u| &u.as_bytes()[..u.len().min(usize::from(NO_USER) - 1)]);
    let producer = &producer.as_bytes()[..producer.len().min(usize::from(u16::MAX))];
    let payload_len = 8 + 2 + user.map_or(0, <[u8]>::len) + 2 + producer.len();
    buf.reserve(8 + payload_len);
    buf.put_u8(MsgType::ProducerQuery as u8);
    buf.put_u8(0);
    buf.put_u16_le(0);
    buf.put_u32_le(payload_len as u32);
    buf.put_u64_le(id);
    match user {
        Some(user) => {
            buf.put_u16_le(user.len() as u16);
            buf.put_slice(user);
        }
        None => buf.put_u16_le(NO_USER),
    }
    buf.put_u16_le(producer.len() as u16);
    buf.put_slice(producer);
}

/// A PRODUCER_STATE's payload before its holes: id, known, mark, forgot,
/// undecided, unsure and the count of holes.
const PRODUCER_STATE_FIXED: usize = 8 + 1 + 8 + 8 + 8 + 8 + 2;

/// Encode a PRODUCER_STATE: the answer to question `id`, what the peer
/// decided of the producer, the refusals behind it, and what it could not
/// tell.
/// Format: [header, payload_len][u64 LE id][u8 known][u64 LE mark]
/// [u64 LE forgot][u64 LE undecided, 0: none][u64 LE unsure]
/// [u16 LE holes][per hole: u64 LE from, u64 LE to, u8 why]
pub(crate) fn encode_producer_state(buf: &mut BytesMut, id: u64, decided: Option<&Decided>) {
    let holes = decided.map_or(&[][..], |d| &d.holes[..]);
    let holes = &holes[..holes.len().min(MAX_HOLES)];
    let payload_len = PRODUCER_STATE_FIXED + holes.len() * 17;
    buf.reserve(8 + payload_len);
    buf.put_u8(MsgType::ProducerState as u8);
    buf.put_u8(0);
    buf.put_u16_le(0);
    buf.put_u32_le(payload_len as u32);
    buf.put_u64_le(id);
    buf.put_u8(u8::from(decided.is_some()));
    buf.put_u64_le(decided.map_or(0, |d| d.mark));
    buf.put_u64_le(decided.map_or(0, |d| d.forgot));
    buf.put_u64_le(decided.and_then(|d| d.undecided).unwrap_or(0));
    buf.put_u64_le(decided.map_or(0, |d| d.unsure));
    buf.put_u16_le(holes.len() as u16);
    for hole in holes {
        buf.put_u64_le(hole.from);
        buf.put_u64_le(hole.to);
        buf.put_u8(hole.why.code());
    }
}

pub(crate) fn encode_drain(buf: &mut BytesMut) {
    buf.reserve(8);
    buf.put_u8(MsgType::Drain as u8);
    buf.put_u8(0);
    buf.put_u16_le(0);
    buf.put_u32_le(0);
}

/// Encode a SUB frame. Returns false if topic exceeds 64KB.
/// Format: [u8 type=0x06][u8 flags][u16 LE topic_len][u32 LE payload_len=0][topic]
pub(crate) fn encode_sub(buf: &mut BytesMut, topic: &str) -> bool {
    let topic_bytes = topic.as_bytes();
    if topic_bytes.len() > u16::MAX as usize {
        return false;
    }
    buf.reserve(8 + topic_bytes.len());
    buf.put_u8(MsgType::Sub as u8);
    buf.put_u8(0); // flags
    buf.put_u16_le(topic_bytes.len() as u16);
    buf.put_u32_le(0); // no payload
    buf.put_slice(topic_bytes);
    true
}

/// Encode a LOST frame: messages of `topic` (a name, or a pattern of them)
/// were published here that no node holds. False if the topic exceeds 64KB.
/// Format: [header: type=0x11, topic_len=N] [N bytes: topic]
pub(crate) fn encode_lost(buf: &mut BytesMut, topic: &str) -> bool {
    let topic_bytes = topic.as_bytes();
    if topic_bytes.len() > u16::MAX as usize {
        return false;
    }
    buf.reserve(8 + topic_bytes.len());
    buf.put_u8(MsgType::Lost as u8);
    buf.put_u8(0); // flags
    buf.put_u16_le(topic_bytes.len() as u16);
    buf.put_u32_le(0); // no payload
    buf.put_slice(topic_bytes);
    true
}

/// Encode an UNSUB frame. Returns false if topic exceeds 64KB.
/// Format: [u8 type=0x07][u8 flags][u16 LE topic_len][u32 LE payload_len=0][topic]
pub(crate) fn encode_unsub(buf: &mut BytesMut, topic: &str) -> bool {
    let topic_bytes = topic.as_bytes();
    if topic_bytes.len() > u16::MAX as usize {
        return false;
    }
    buf.reserve(8 + topic_bytes.len());
    buf.put_u8(MsgType::Unsub as u8);
    buf.put_u8(0); // flags
    buf.put_u16_le(topic_bytes.len() as u16);
    buf.put_u32_le(0); // no payload
    buf.put_slice(topic_bytes);
    true
}

/// RESYNC flag: not the round's first frame.
const RESYNC_CONTINUATION: u8 = 0x01;
/// RESYNC flag: more frames of the round follow.
const RESYNC_MORE: u8 = 0x02;

/// A MSG frame of a message the peer missed while its link was down, sent
/// again from where its RESUME said it stands: compressed like any, with its
/// recovery trailer, and marked so the peer waits for room to deliver it
/// instead of shedding it. False when it does not fit a frame.
pub(crate) fn encode_replayed(
    buf: &mut BytesMut,
    topic: &str,
    payload: &str,
    origin_epoch: u32,
    origin_offset: u64,
) -> bool {
    let start = buf.len();
    let position = Some((origin_epoch, origin_offset));
    if !encode_msg_full(buf, topic, payload, position, None, true) {
        return false;
    }
    if buf.len() - start > MAX_FRAME_SIZE {
        buf.truncate(start);
        return false;
    }
    buf[start + 1] |= FLAG_REPLAYED;
    true
}

/// The last RESUME frame of a node's request.
pub(crate) const RESUME_LAST: u8 = 0x01;
/// A RESUME frame that names the topics the node has (CAP_RESUME_TOPICS).
pub(crate) const RESUME_TOPICS: u8 = 0x02;
/// A RESUME frame naming, in one entry (no topic, epoch 0), the last of the
/// receiver's arrivals the sender heard of (CAP_ARRIVAL).
pub(crate) const RESUME_HEARD: u8 = 0x04;

/// Where a node stands in the streams other nodes relay to it, as it asks on
/// a new link for what it missed: (topic, the origin's epoch, the last offset
/// it holds with nothing missing before it).
pub(crate) type ResumePoint = (String, u32, u64);

/// A topic the asking node has, and how long ago its interest in it began
/// (milliseconds): what the other published to it since, of a stream not
/// named, is sent too.
pub(crate) type ResumeTopic = (String, u64);

/// Encode a node's RESUME request: one frame or more, the last flagged; the
/// frames of `topics` (flagged RESUME_TOPICS) after those of `points`.
/// Format: [u8 type=0x0E][u8 flags][u16 LE 0][u32 LE payload_len][payload],
/// the payload a run of [u16 LE topic_len][topic][u32 LE epoch][u64 LE offset];
/// in a frame of topics the epoch is 0 and the offset the interest's age.
pub(crate) fn encode_resume(
    points: &[ResumePoint],
    topics: &[ResumeTopic],
    heard: Option<u64>,
) -> Vec<BytesMut> {
    fn header(buf: &mut BytesMut, flags: u8) {
        buf.put_u8(MsgType::Resume as u8);
        buf.put_u8(flags);
        buf.put_u16_le(0);
        buf.put_u32_le(0);
    }
    fn entry(frames: &mut Vec<BytesMut>, buf: &mut BytesMut, flags: u8, at: (&str, u32, u64)) {
        let topic = at.0.as_bytes();
        let Ok(len) = u16::try_from(topic.len()) else {
            return;
        };
        if buf.len() + 2 + topic.len() + 12 > MAX_FRAME_SIZE && buf.len() > 8 {
            frames.push(std::mem::take(buf));
            header(buf, flags);
        }
        buf.put_u16_le(len);
        buf.put_slice(topic);
        buf.put_u32_le(at.1);
        buf.put_u64_le(at.2);
    }
    let mut frames = Vec::new();
    let mut buf = BytesMut::new();
    header(&mut buf, 0);
    for (topic, epoch, offset) in points {
        entry(&mut frames, &mut buf, 0, (topic, *epoch, *offset));
    }
    if let Some(heard) = heard {
        frames.push(std::mem::take(&mut buf));
        header(&mut buf, RESUME_HEARD);
        entry(&mut frames, &mut buf, RESUME_HEARD, ("", 0, heard));
    }
    if !topics.is_empty() {
        frames.push(std::mem::take(&mut buf));
        header(&mut buf, RESUME_TOPICS);
        for (topic, age) in topics {
            entry(&mut frames, &mut buf, RESUME_TOPICS, (topic, 0, *age));
        }
    }
    frames.push(buf);
    if let Some(last) = frames.last_mut() {
        last[1] |= RESUME_LAST;
    }
    for frame in &mut frames {
        let len = (frame.len() - 8) as u32;
        frame[4..8].copy_from_slice(&len.to_le_bytes());
    }
    frames
}

/// Encode RESYNC frame(s). Topics are joined by "\n" in the payload.
/// Format: [u8 type=0x08][u8 flags][u16 LE topic_len=0][u32 LE payload_len][payload]
/// flags: 0x01 on a continuation (not the round's first frame), 0x02 when more
/// frames of the round follow, so the receiver takes the new set only whole.
/// Returns multiple frames if the payload exceeds MAX_FRAME_SIZE.
pub(crate) fn encode_resync(topics: &[String]) -> Vec<BytesMut> {
    let payload = topics.join("\n");
    let payload_bytes = payload.as_bytes();

    fn encode_single(chunk: &[u8], flags: u8) -> BytesMut {
        let mut buf = BytesMut::with_capacity(8 + chunk.len());
        buf.put_u8(MsgType::Resync as u8);
        buf.put_u8(flags);
        buf.put_u16_le(0);
        buf.put_u32_le(chunk.len() as u32);
        buf.put_slice(chunk);
        buf
    }

    // The 8-byte header counts against the frame limit the receiver enforces.
    if payload_bytes.len() <= MAX_FRAME_SIZE - 8 {
        return vec![encode_single(payload_bytes, 0x00)];
    }
    // Multi-frame: split at newline boundaries to stay under MAX_FRAME_SIZE
    // First frame: flags=0x00 (replace), continuation frames: flags=0x01 (extend)
    let mut frames = Vec::new();
    let mut start = 0;
    while start < payload_bytes.len() {
        let remaining = payload_bytes.len() - start;
        // Reserve 8 bytes for the wire header to stay under MAX_FRAME_SIZE on the wire
        let chunk_limit = MAX_FRAME_SIZE - 8;
        let chunk_end = if remaining <= chunk_limit {
            payload_bytes.len()
        } else {
            let window_end = start + chunk_limit;
            match payload_bytes[start..window_end]
                .iter()
                .rposition(|&b| b == b'\n')
            {
                Some(pos) => start + pos,
                None => window_end,
            }
        };
        let mut flags = if frames.is_empty() {
            0x00
        } else {
            RESYNC_CONTINUATION
        };
        if chunk_end < payload_bytes.len() {
            flags |= RESYNC_MORE;
        }
        frames.push(encode_single(&payload_bytes[start..chunk_end], flags));
        start = if chunk_end < payload_bytes.len() && payload_bytes[chunk_end] == b'\n' {
            chunk_end + 1
        } else {
            chunk_end
        };
    }
    frames
}

/// Encode PEER_ANNOUNCE: announces this node's cluster address to a peer.
/// Format: [u8 type=0x09][u8 flags][u16 LE addr_len][u32 LE 0][addr_bytes]
pub(crate) fn encode_peer_announce(buf: &mut BytesMut, addr: &str) {
    let addr_bytes = addr.as_bytes();
    if addr_bytes.len() > u16::MAX as usize {
        tracing::warn!(
            "[WSE-Cluster] Peer address too long ({} bytes), dropping announce",
            addr_bytes.len()
        );
        return;
    }
    buf.reserve(8 + addr_bytes.len());
    buf.put_u8(MsgType::PeerAnnounce as u8);
    buf.put_u8(0); // flags
    buf.put_u16_le(addr_bytes.len() as u16);
    buf.put_u32_le(0); // payload_len (unused)
    buf.put_slice(addr_bytes);
}

/// Encode PEER_LIST: sends the list of all known peer addresses.
/// Format: [u8 type=0x0A][u8 flags][u16 LE 0][u32 LE payload_len][payload]
/// Payload: [u16 LE count][u16 LE addr1_len][addr1_bytes]...
pub(crate) fn encode_peer_list(buf: &mut BytesMut, addrs: &[String]) {
    // At most MAX_KNOWN_PEERS addresses, within one frame.
    let mut size = 2;
    let safe_addrs: Vec<&String> = addrs
        .iter()
        .filter(|a| a.len() <= u16::MAX as usize)
        .take(MAX_KNOWN_PEERS)
        .take_while(|a| {
            size += 2 + a.len();
            size <= MAX_FRAME_SIZE - 8
        })
        .collect();
    let mut payload = BytesMut::new();
    payload.put_u16_le(safe_addrs.len() as u16);
    for addr in &safe_addrs {
        payload.put_u16_le(addr.len() as u16);
        payload.extend_from_slice(addr.as_bytes());
    }
    buf.reserve(8 + payload.len());
    buf.put_u8(MsgType::PeerList as u8);
    buf.put_u8(0); // flags
    buf.put_u16_le(0); // topic_len (unused)
    buf.put_u32_le(payload.len() as u32);
    buf.extend_from_slice(&payload);
}

/// Encode a PRESENCE_UPDATE frame.
/// Payload: [action(1)][updated_at(8)][user_id_len(2)][user_id][data]
pub(crate) fn encode_presence_update(
    buf: &mut BytesMut,
    topic: &str,
    user_id: &str,
    action: u8,
    data: &str,
    updated_at: u64,
) -> bool {
    let topic_bytes = topic.as_bytes();
    let user_id_bytes = user_id.as_bytes();
    let data_bytes = data.as_bytes();
    if topic_bytes.len() > u16::MAX as usize || user_id_bytes.len() > u16::MAX as usize {
        return false;
    }
    let payload_len = 1 + 8 + 2 + user_id_bytes.len() + data_bytes.len();
    let total_frame = 8 + topic_bytes.len() + payload_len;
    // Guard the total frame like every other encoder. presence_max_data_size is
    // operator-configurable; without this a large presence update would emit a
    // frame the receiving peer_reader rejects (> MAX_FRAME_SIZE), disconnecting
    // the peer and flapping the link on ordinary presence traffic.
    if total_frame > MAX_FRAME_SIZE {
        tracing::warn!(
            "[WSE-Cluster] PresenceUpdate frame too large ({total_frame} bytes, max {MAX_FRAME_SIZE}), dropping",
        );
        return false;
    }
    buf.reserve(total_frame);
    buf.put_u8(MsgType::PresenceUpdate as u8);
    buf.put_u8(0); // flags
    buf.put_u16_le(topic_bytes.len() as u16);
    buf.put_u32_le(payload_len as u32);
    buf.put_slice(topic_bytes);
    buf.put_u8(action);
    buf.put_u64_le(updated_at);
    buf.put_u16_le(user_id_bytes.len() as u16);
    buf.put_slice(user_id_bytes);
    buf.put_slice(data_bytes);
    true
}

/// PRESENCE_FULL flags of a sync round: its frames carry the sender's whole
/// local presence, from the first frame to the last, and whatever the
/// receiver holds for the sender outside them is gone. Older nodes ignore
/// the flags and merge every frame as it comes, like a frame without them.
pub(crate) const PRESENCE_ROUND: u8 = 0x04;
pub(crate) const PRESENCE_ROUND_FIRST: u8 = 0x01;
pub(crate) const PRESENCE_ROUND_LAST: u8 = 0x02;

/// Encode a PRESENCE_FULL frame outside any round: what older nodes send, a
/// full state merged as it comes.
#[cfg(test)]
pub(crate) fn encode_presence_full(buf: &mut BytesMut, entries_json: &str) -> bool {
    encode_presence_frame(buf, entries_json, 0)
}

/// Encode one PRESENCE_FULL frame of a sync round; `edges` holds
/// PRESENCE_ROUND_FIRST and/or PRESENCE_ROUND_LAST.
pub(crate) fn encode_presence_round(buf: &mut BytesMut, entries_json: &str, edges: u8) -> bool {
    encode_presence_frame(buf, entries_json, PRESENCE_ROUND | edges)
}

fn encode_presence_frame(buf: &mut BytesMut, entries_json: &str, flags: u8) -> bool {
    let payload_bytes = entries_json.as_bytes();
    let total_frame = 8 + payload_bytes.len();
    if total_frame > MAX_FRAME_SIZE {
        tracing::warn!(
            "[WSE-Cluster] PresenceFull frame too large ({total_frame} bytes, max {MAX_FRAME_SIZE}), dropping",
        );
        return false;
    }
    let topic_len: u16 = 0; // No topic for full sync
    buf.reserve(total_frame);
    buf.put_u8(MsgType::PresenceFull as u8);
    buf.put_u8(flags);
    buf.put_u16_le(topic_len);
    buf.put_u32_le(payload_bytes.len() as u32);
    buf.put_slice(payload_bytes);
    true
}

// ---------------------------------------------------------------------------
// Framing helpers (4-byte BE length prefix)
// ---------------------------------------------------------------------------

pub(super) fn write_framed(buf: &mut BytesMut, inner: &[u8]) {
    buf.reserve(4 + inner.len());
    buf.put_u32(inner.len() as u32); // big-endian length prefix
    buf.put_slice(inner);
}

// ---------------------------------------------------------------------------
// Wire protocol decoding
// ---------------------------------------------------------------------------

/// Decoded frame from a peer.
#[derive(Debug, PartialEq)]
pub(crate) enum ClusterFrame {
    Msg {
        topic: String,
        payload: Bytes,
        /// Origin node's recovery position (epoch, offset) for cross-node recovery.
        recovery: Option<(u32, u64)>,
        /// The message's number in the origin's arrival order (CAP_ARRIVAL).
        arrival: Option<u64>,
    },
    Ping,
    Pong,
    Hello {
        instance_id: String,
        protocol_version: u16,
        capabilities: u32,
        /// Where the node is reached: its cluster address, or `:port` on the
        /// address its links come from. None from a node before 3.2.
        reached_at: Option<String>,
    },
    Shutdown,
    Sub {
        topic: String,
    },
    Unsub {
        topic: String,
    },
    Resync {
        topics: Vec<String>,
        is_continuation: bool,
        /// More frames of this round follow.
        more: bool,
    },
    PeerAnnounce {
        addr: String,
    },
    PeerList {
        addrs: Vec<String>,
    },
    PresenceUpdate {
        topic: String,
        user_id: String,
        action: u8,
        data: String,
        updated_at: u64,
    },
    PresenceFull {
        entries: String,
        /// PRESENCE_ROUND bits; 0 from older nodes.
        flags: u8,
    },
    /// Graceful drain: this node is shutting down, migrate connections.
    Drain,
    /// Part of a peer's request, on a new link, for what it missed.
    Resume {
        points: Vec<ResumePoint>,
        /// The topics the node has (a frame flagged RESUME_TOPICS).
        topics: Vec<ResumeTopic>,
        /// The last arrival of the receiver's the node heard of (a frame
        /// flagged RESUME_HEARD).
        heard: Option<u64>,
        /// The request's last frame.
        last: bool,
    },
    /// A message sent again for a peer that missed it (a MSG frame marked
    /// replayed): always with its origin's position.
    Replayed {
        topic: String,
        payload: Bytes,
        position: (u32, u64),
    },
    /// What a peer took of a client's producer (`server::acks`).
    ProducerQuery {
        id: u64,
        user: Option<String>,
        producer: String,
    },
    /// The answer: what the peer decided of it and the refusals behind
    /// that; None when it knows nothing of it.
    ProducerState {
        id: u64,
        decided: Option<Decided>,
    },
    /// Messages of a topic (or of each topic a pattern matches) were
    /// published on the peer that no node holds.
    Lost {
        topic: String,
    },
    /// The catch-up the peer just sent covers what it published up to
    /// arrival `through`.
    CaughtUp {
        through: u64,
    },
    Unknown {
        msg_type: u8,
    },
}

/// Decode a frame from raw bytes (after outer length prefix is stripped).
/// Returns None on any parse error (except unknown message types, which return Unknown).
pub(crate) fn decode_frame(mut data: BytesMut) -> Option<ClusterFrame> {
    if data.remaining() < 8 {
        return None;
    }
    let raw_type = data.get_u8();
    let flags = data.get_u8();
    let topic_len = data.get_u16_le() as usize;
    let payload_len = data.get_u32_le() as usize;

    match MsgType::from_u8(raw_type) {
        Some(MsgType::Msg) => {
            if data.remaining() < topic_len + payload_len {
                return None;
            }
            let topic = String::from_utf8(data.split_to(topic_len).to_vec()).ok()?;
            let payload = if flags & FLAG_COMPRESSED != 0 {
                let compressed = data.split_to(payload_len);
                // zstd::bulk::decompress enforces MAX_FRAME_SIZE output cap (decompression bomb protection).
                let mut decompressed = match zstd::bulk::decompress(&compressed, MAX_FRAME_SIZE) {
                    Ok(d) => d,
                    Err(e) => {
                        tracing::warn!(
                            "[WSE-Cluster] Decompression failed ({payload_len} bytes compressed): {e}"
                        );
                        return None;
                    }
                };
                // A frame that names no content size is decompressed into the
                // whole cap: what is kept (a recovery copy, say) holds only
                // its length, as the memory budget counts it.
                decompressed.shrink_to_fit();
                Bytes::from(decompressed)
            } else {
                data.split_to(payload_len).freeze() // zero-copy: BytesMut -> Bytes
            };
            // Parse optional recovery trailer (12 bytes: u32 epoch + u64 offset)
            let recovery = if flags & FLAG_HAS_RECOVERY != 0 {
                if data.remaining() < 12 {
                    return None; // malformed: flag set but recovery trailer missing
                }
                let epoch = data.get_u32_le();
                let offset = data.get_u64_le();
                Some((epoch, offset))
            } else {
                None
            };
            let arrival = if flags & FLAG_ARRIVAL != 0 {
                if data.remaining() < 8 {
                    return None;
                }
                Some(data.get_u64_le())
            } else {
                None
            };
            if flags & FLAG_REPLAYED != 0
                && let Some(position) = recovery
            {
                return Some(ClusterFrame::Replayed {
                    topic,
                    payload,
                    position,
                });
            }
            Some(ClusterFrame::Msg {
                topic,
                payload,
                recovery,
                arrival,
            })
        }
        Some(MsgType::Resume) => {
            if data.remaining() < payload_len {
                return None;
            }
            let mut payload = data.split_to(payload_len);
            let (mut points, mut topics, mut heard) = (Vec::new(), Vec::new(), None);
            while payload.has_remaining() {
                if payload.remaining() < 2 {
                    return None;
                }
                let topic_len = payload.get_u16_le() as usize;
                if payload.remaining() < topic_len + 12 {
                    return None;
                }
                let topic = String::from_utf8(payload.split_to(topic_len).to_vec()).ok()?;
                let epoch = payload.get_u32_le();
                let offset = payload.get_u64_le();
                if flags & RESUME_HEARD != 0 {
                    heard = Some(offset);
                } else if flags & RESUME_TOPICS != 0 {
                    topics.push((topic, offset));
                } else {
                    points.push((topic, epoch, offset));
                }
            }
            Some(ClusterFrame::Resume {
                points,
                topics,
                heard,
                last: flags & RESUME_LAST != 0,
            })
        }
        Some(MsgType::Ping) => Some(ClusterFrame::Ping),
        Some(MsgType::Pong) => Some(ClusterFrame::Pong),
        Some(MsgType::Hello) => {
            // Minimum HELLO payload: magic(4) + version(2) + id_len(2) + capabilities(4) = 12
            if payload_len < 12 || data.remaining() < payload_len {
                return None;
            }
            let magic = data.split_to(4);
            if magic.as_ref() != MAGIC {
                return None;
            }
            let version = data.get_u16_le();
            let id_len = data.get_u16_le() as usize;
            if id_len > 256 {
                tracing::warn!(
                    "[WSE-Cluster] Instance ID too long: {} bytes, max 256",
                    id_len
                );
                return None;
            }
            if data.remaining() < id_len + 4 {
                return None;
            }
            let instance_id = String::from_utf8(data.split_to(id_len).to_vec()).ok()?;
            let capabilities = data.get_u32_le();
            // Where the node is reached, from 3.2 on.
            let reached_at = (data.remaining() >= 2)
                .then(|| data.get_u16_le() as usize)
                .filter(|len| *len > 0 && *len <= MAX_REACHED_AT && data.remaining() >= *len)
                .and_then(|len| String::from_utf8(data.split_to(len).to_vec()).ok());
            Some(ClusterFrame::Hello {
                instance_id,
                protocol_version: version,
                capabilities,
                reached_at,
            })
        }
        Some(MsgType::Shutdown) => Some(ClusterFrame::Shutdown),
        Some(MsgType::Drain) => Some(ClusterFrame::Drain),
        Some(MsgType::Sub) => {
            if data.remaining() < topic_len {
                return None;
            }
            let topic = String::from_utf8(data.split_to(topic_len).to_vec()).ok()?;
            Some(ClusterFrame::Sub { topic })
        }
        Some(MsgType::CaughtUp) => {
            if data.remaining() < 8 {
                return None;
            }
            Some(ClusterFrame::CaughtUp {
                through: data.get_u64_le(),
            })
        }
        Some(MsgType::Lost) => {
            if data.remaining() < topic_len {
                return None;
            }
            let topic = String::from_utf8(data.split_to(topic_len).to_vec()).ok()?;
            Some(ClusterFrame::Lost { topic })
        }
        Some(MsgType::Unsub) => {
            if data.remaining() < topic_len {
                return None;
            }
            let topic = String::from_utf8(data.split_to(topic_len).to_vec()).ok()?;
            Some(ClusterFrame::Unsub { topic })
        }
        Some(MsgType::Resync) => {
            if data.remaining() < payload_len {
                return None;
            }
            let topics = if payload_len == 0 {
                Vec::new()
            } else {
                let raw_bytes = data.split_to(payload_len);
                let slice: &[u8] = &raw_bytes;
                slice
                    .split(|&b| b == b'\n')
                    .filter(|chunk| !chunk.is_empty())
                    .filter_map(|chunk| String::from_utf8(chunk.to_vec()).ok())
                    .collect()
            };
            Some(ClusterFrame::Resync {
                topics,
                is_continuation: flags & RESYNC_CONTINUATION != 0,
                more: flags & RESYNC_MORE != 0,
            })
        }
        Some(MsgType::PeerAnnounce) => {
            if data.remaining() < topic_len {
                return None;
            }
            let addr = String::from_utf8(data.split_to(topic_len).to_vec()).ok()?;
            Some(ClusterFrame::PeerAnnounce { addr })
        }
        Some(MsgType::PeerList) => {
            if data.remaining() < payload_len {
                return None;
            }
            if payload_len < 2 {
                return Some(ClusterFrame::PeerList { addrs: Vec::new() });
            }
            let payload = data.split_to(payload_len);
            // Cap both the pre-allocation and the loop at MAX_CLUSTER_PEERS so a
            // declared count (u16, up to 65535) cannot force a large transient
            // allocation, and a 1 MB frame of tiny entries cannot expand into a
            // huge addr Vec. A real peer list never exceeds the peer cap.
            let count =
                (u16::from_le_bytes([payload[0], payload[1]]) as usize).min(MAX_CLUSTER_PEERS);
            let mut addrs = Vec::with_capacity(count);
            let mut pos = 2usize;
            for _ in 0..count {
                if pos + 2 > payload.len() {
                    break;
                }
                let alen = u16::from_le_bytes([payload[pos], payload[pos + 1]]) as usize;
                pos += 2;
                if pos + alen > payload.len() {
                    break;
                }
                if let Ok(a) = std::str::from_utf8(&payload[pos..pos + alen]) {
                    addrs.push(a.to_string());
                }
                pos += alen;
            }
            Some(ClusterFrame::PeerList { addrs })
        }
        Some(MsgType::PresenceUpdate) => {
            if data.remaining() < topic_len + payload_len {
                return None;
            }
            let topic = String::from_utf8(data.split_to(topic_len).to_vec()).ok()?;
            if data.remaining() < 1 + 8 + 2 {
                return None;
            }
            let action = data.get_u8();
            let updated_at = data.get_u64_le();
            let user_id_len = data.get_u16_le() as usize;
            if data.remaining() < user_id_len {
                return None;
            }
            let user_id = String::from_utf8(data.split_to(user_id_len).to_vec()).ok()?;
            let remaining_data = payload_len.saturating_sub(1 + 8 + 2 + user_id_len);
            let presence_data = if remaining_data > 0 && data.remaining() >= remaining_data {
                String::from_utf8(data.split_to(remaining_data).to_vec()).ok()?
            } else {
                String::new()
            };
            Some(ClusterFrame::PresenceUpdate {
                topic,
                user_id,
                action,
                data: presence_data,
                updated_at,
            })
        }
        Some(MsgType::PresenceFull) => {
            if data.remaining() < payload_len {
                return None;
            }
            let entries = String::from_utf8(data.split_to(payload_len).to_vec()).ok()?;
            Some(ClusterFrame::PresenceFull { entries, flags })
        }
        Some(MsgType::ProducerQuery) => {
            if data.remaining() < payload_len || payload_len < 12 {
                return None;
            }
            let mut payload = data.split_to(payload_len);
            let id = payload.get_u64_le();
            let user_len = payload.get_u16_le();
            let user = if user_len == NO_USER {
                None
            } else {
                let user_len = usize::from(user_len);
                if payload.remaining() < user_len {
                    return None;
                }
                Some(String::from_utf8(payload.split_to(user_len).to_vec()).ok()?)
            };
            if payload.remaining() < 2 {
                return None;
            }
            let producer_len = usize::from(payload.get_u16_le());
            if payload.remaining() < producer_len {
                return None;
            }
            let producer = String::from_utf8(payload.split_to(producer_len).to_vec()).ok()?;
            Some(ClusterFrame::ProducerQuery { id, user, producer })
        }
        Some(MsgType::ProducerState) => {
            if data.remaining() < payload_len || payload_len < PRODUCER_STATE_FIXED {
                return None;
            }
            let mut payload = data.split_to(payload_len);
            let id = payload.get_u64_le();
            let known = payload.get_u8() != 0;
            let mark = payload.get_u64_le();
            let forgot = payload.get_u64_le();
            let undecided = payload.get_u64_le();
            // What a node could not tell may reach past what it decided.
            let unsure = payload.get_u64_le();
            if forgot > mark || undecided > mark {
                return None;
            }
            let count = usize::from(payload.get_u16_le()).min(MAX_HOLES);
            if payload.remaining() < count * 17 {
                return None;
            }
            let mut holes = Vec::with_capacity(count);
            for _ in 0..count {
                let (from, to) = (payload.get_u64_le(), payload.get_u64_le());
                let why = Refusal::from_code(payload.get_u8())?;
                if from > to || to > mark {
                    return None;
                }
                holes.push(Hole { from, to, why });
            }
            Some(ClusterFrame::ProducerState {
                id,
                decided: known.then_some(Decided {
                    mark,
                    holes,
                    forgot,
                    undecided: (undecided > 0).then_some(undecided),
                    unsure,
                }),
            })
        }
        None => {
            // Unknown message type from a newer peer -- safe to skip
            // (outer 4-byte framing means we already consumed the right number of bytes)
            Some(ClusterFrame::Unknown { msg_type: raw_type })
        }
    }
}

// ---------------------------------------------------------------------------
// Version / capability negotiation
// ---------------------------------------------------------------------------

/// Negotiate protocol version. Returns min(local, remote) if >= PROTOCOL_VERSION_MIN.
pub(crate) fn negotiate_version(local_ver: u16, remote_ver: u16) -> Option<u16> {
    let negotiated = local_ver.min(remote_ver);
    if negotiated >= PROTOCOL_VERSION_MIN {
        Some(negotiated)
    } else {
        None
    }
}

/// Negotiate capabilities: bitwise AND (both must support a feature for it to be active).
pub(crate) fn negotiate_capabilities(local: u32, remote: u32) -> u32 {
    local & remote
}