wse 3.0.1

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
//! 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_COMPRESSED, FLAG_HAS_RECOVERY, FLAG_REPLAYED, MAGIC,
    MAX_CLUSTER_PEERS, MAX_FRAME_SIZE, MAX_KNOWN_PEERS, PROTOCOL_VERSION, PROTOCOL_VERSION_MIN,
};

// ---------------------------------------------------------------------------
// 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,
}

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),
            _ => 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]
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.
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).
pub(crate) fn encode_msg_with_recovery(
    buf: &mut BytesMut,
    topic: &str,
    payload: &str,
    origin_epoch: u32,
    origin_offset: 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();

    if compress
        && payload_bytes.len() >= COMPRESSION_THRESHOLD
        && let Ok(compressed) = zstd::bulk::compress(payload_bytes, 1)
        && compressed.len() < payload_bytes.len()
    {
        let total = 8 + topic_bytes.len() + compressed.len() + 12; // +12 for recovery trailer
        if total > MAX_FRAME_SIZE {
            return false;
        }
        buf.reserve(total);
        buf.put_u8(MsgType::Msg as u8);
        buf.put_u8(FLAG_COMPRESSED | FLAG_HAS_RECOVERY);
        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);
        buf.put_u32_le(origin_epoch);
        buf.put_u64_le(origin_offset);
        return true;
    }

    // Uncompressed with recovery trailer
    let total = 8 + topic_bytes.len() + payload_bytes.len() + 12;
    if total > MAX_FRAME_SIZE {
        return false;
    }
    buf.reserve(total);
    buf.put_u8(MsgType::Msg as u8);
    buf.put_u8(FLAG_HAS_RECOVERY);
    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);
    buf.put_u32_le(origin_epoch);
    buf.put_u64_le(origin_offset);
    true
}

/// 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)
pub(crate) fn encode_hello(buf: &mut BytesMut, instance_id: &str, capabilities: u32) {
    let id_bytes = instance_id.as_bytes();
    let payload_len = 4 + 2 + 2 + id_bytes.len() + 4;
    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);
}

/// 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.
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 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();
    if !encode_msg_with_recovery(buf, topic, payload, origin_epoch, origin_offset, 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;

/// 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);

/// Encode a node's RESUME request: one frame or more, the last flagged.
/// 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].
pub(crate) fn encode_resume(points: &[ResumePoint]) -> Vec<BytesMut> {
    fn header(buf: &mut BytesMut) {
        buf.put_u8(MsgType::Resume as u8);
        buf.put_u8(0);
        buf.put_u16_le(0);
        buf.put_u32_le(0);
    }
    let mut frames = Vec::new();
    let mut buf = BytesMut::new();
    header(&mut buf);
    for (topic, epoch, offset) in points {
        let topic = topic.as_bytes();
        let Ok(len) = u16::try_from(topic.len()) else {
            continue;
        };
        let entry = 2 + topic.len() + 12;
        if buf.len() + entry > MAX_FRAME_SIZE && buf.len() > 8 {
            frames.push(std::mem::take(&mut buf));
            header(&mut buf);
        }
        buf.put_u16_le(len);
        buf.put_slice(topic);
        buf.put_u32_le(*epoch);
        buf.put_u64_le(*offset);
    }
    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)>,
    },
    Ping,
    Pong,
    Hello {
        instance_id: String,
        protocol_version: u16,
        capabilities: u32,
    },
    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 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),
    },
    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
            };
            if flags & FLAG_REPLAYED != 0
                && let Some(position) = recovery
            {
                return Some(ClusterFrame::Replayed {
                    topic,
                    payload,
                    position,
                });
            }
            Some(ClusterFrame::Msg {
                topic,
                payload,
                recovery,
            })
        }
        Some(MsgType::Resume) => {
            if data.remaining() < payload_len {
                return None;
            }
            let mut payload = data.split_to(payload_len);
            let mut points = Vec::new();
            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();
                points.push((topic, epoch, offset));
            }
            Some(ClusterFrame::Resume {
                points,
                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();
            Some(ClusterFrame::Hello {
                instance_id,
                protocol_version: version,
                capabilities,
            })
        }
        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::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 })
        }
        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
}