Skip to main content

loro_protocol/
protocol.rs

1//! Protocol types and constants mirrored from `protocol.md` and the TS package.
2//!
3//! These are the source-of-truth structures for the Rust encoder/decoder. The
4//! `ProtocolMessage` enum aggregates all message variants.
5/// Reserved library magic string, aligned with the TypeScript library.
6/// Not part of the message envelope; included for parity.
7pub const MAGIC: &str = "LRSP";
8pub const MAX_MESSAGE_SIZE: usize = 256 * 1024; // 256KB
9
10/// CRDT types supported by the wire format.
11#[derive(Debug, Clone, Copy, PartialEq, Eq)]
12pub enum CrdtType {
13    /// "%LOR"
14    Loro,
15    /// "%EPH"
16    LoroEphemeralStore,
17    /// "%EPS"
18    LoroEphemeralStorePersisted,
19    /// "%YJS"
20    Yjs,
21    /// "%YAW"
22    YjsAwareness,
23    /// "%ELO" (End-to-End Encrypted Loro)
24    Elo,
25    /// "%FLO"
26    Flock,
27}
28
29impl CrdtType {
30    pub fn magic_bytes(self) -> [u8; 4] {
31        match self {
32            CrdtType::Loro => *b"%LOR",
33            CrdtType::LoroEphemeralStore => *b"%EPH",
34            CrdtType::LoroEphemeralStorePersisted => *b"%EPS",
35            CrdtType::Yjs => *b"%YJS",
36            CrdtType::YjsAwareness => *b"%YAW",
37            CrdtType::Elo => *b"%ELO",
38            CrdtType::Flock => *b"%FLO",
39        }
40    }
41
42    pub fn from_magic_bytes(bytes: [u8; 4]) -> Option<Self> {
43        match &bytes {
44            b"%LOR" => Some(CrdtType::Loro),
45            b"%EPH" => Some(CrdtType::LoroEphemeralStore),
46            b"%EPS" => Some(CrdtType::LoroEphemeralStorePersisted),
47            b"%YJS" => Some(CrdtType::Yjs),
48            b"%YAW" => Some(CrdtType::YjsAwareness),
49            b"%ELO" => Some(CrdtType::Elo),
50            b"%FLO" => Some(CrdtType::Flock),
51            _ => None,
52        }
53    }
54}
55
56/// Permission returned by a successful JoinResponse.
57#[derive(Debug, Clone, Copy, PartialEq, Eq)]
58pub enum Permission {
59    Read,
60    Write,
61}
62
63/// Message type tags as defined in protocol.md
64#[derive(Debug, Clone, Copy, PartialEq, Eq)]
65#[repr(u8)]
66pub enum MessageType {
67    JoinRequest = 0x00,
68    JoinResponseOk = 0x01,
69    JoinError = 0x02,
70    DocUpdate = 0x03,
71    DocUpdateFragmentHeader = 0x04,
72    DocUpdateFragment = 0x05,
73    RoomError = 0x06,
74    Leave = 0x07,
75    Ack = 0x08,
76}
77
78impl MessageType {
79    pub fn from_u8(v: u8) -> Option<Self> {
80        Some(match v {
81            0x00 => MessageType::JoinRequest,
82            0x01 => MessageType::JoinResponseOk,
83            0x02 => MessageType::JoinError,
84            0x03 => MessageType::DocUpdate,
85            0x04 => MessageType::DocUpdateFragmentHeader,
86            0x05 => MessageType::DocUpdateFragment,
87            0x06 => MessageType::RoomError,
88            0x07 => MessageType::Leave,
89            0x08 => MessageType::Ack,
90            _ => return None,
91        })
92    }
93}
94
95/// Error codes for JoinError (0x02).
96#[derive(Debug, Clone, Copy, PartialEq, Eq)]
97#[repr(u8)]
98pub enum JoinErrorCode {
99    Unknown = 0x00,
100    VersionUnknown = 0x01,
101    AuthFailed = 0x02,
102    AppError = 0x7f,
103}
104
105impl JoinErrorCode {
106    pub fn from_u8(v: u8) -> Option<Self> {
107        Some(match v {
108            0x00 => JoinErrorCode::Unknown,
109            0x01 => JoinErrorCode::VersionUnknown,
110            0x02 => JoinErrorCode::AuthFailed,
111            0x7f => JoinErrorCode::AppError,
112            _ => return None,
113        })
114    }
115}
116
117/// Status codes carried by Ack (0x08) and mapped from legacy UpdateError codes.
118#[derive(Debug, Clone, Copy, PartialEq, Eq)]
119#[repr(u8)]
120pub enum UpdateStatusCode {
121    Ok = 0x00,
122    Unknown = 0x01,
123    PermissionDenied = 0x03,
124    InvalidUpdate = 0x04,
125    PayloadTooLarge = 0x05,
126    RateLimited = 0x06,
127    FragmentTimeout = 0x07,
128    AppError = 0x7f,
129}
130
131impl UpdateStatusCode {
132    pub fn from_u8(v: u8) -> Option<Self> {
133        Some(match v {
134            0x00 => UpdateStatusCode::Ok,
135            0x01 => UpdateStatusCode::Unknown,
136            0x03 => UpdateStatusCode::PermissionDenied,
137            0x04 => UpdateStatusCode::InvalidUpdate,
138            0x05 => UpdateStatusCode::PayloadTooLarge,
139            0x06 => UpdateStatusCode::RateLimited,
140            0x07 => UpdateStatusCode::FragmentTimeout,
141            0x7f => UpdateStatusCode::AppError,
142            _ => return None,
143        })
144    }
145}
146
147/// Error codes for RoomError (0x06).
148#[derive(Debug, Clone, Copy, PartialEq, Eq)]
149#[repr(u8)]
150pub enum RoomErrorCode {
151    /// Peer requests that we rejoin to recover consistency (e.g., missing updates).
152    RejoinSuggested = 0x01,
153    /// Peer/server evicted us; do not auto-rejoin.
154    Evicted = 0x02,
155    Unknown = 0x7f,
156}
157
158impl RoomErrorCode {
159    pub fn from_u8(v: u8) -> Option<Self> {
160        Some(match v {
161            0x01 => RoomErrorCode::RejoinSuggested,
162            0x02 => RoomErrorCode::Evicted,
163            0x7f => RoomErrorCode::Unknown,
164            _ => return None,
165        })
166    }
167}
168
169/// 8-byte batch ID for fragmenting. On the wire this is exactly 8 raw bytes.
170#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
171pub struct BatchId(pub [u8; 8]);
172
173impl BatchId {
174    pub fn from_hex(s: &str) -> Result<Self, String> {
175        let s = s.strip_prefix("0x").unwrap_or(s);
176        if s.len() != 16 {
177            return Err("batch id hex must be 16 chars".into());
178        }
179        let mut out = [0u8; 8];
180        for (i, slot) in out.iter_mut().enumerate() {
181            let idx = i * 2;
182            let byte =
183                u8::from_str_radix(&s[idx..idx + 2], 16).map_err(|_| "invalid hex".to_string())?;
184            *slot = byte;
185        }
186        Ok(BatchId(out))
187    }
188
189    pub fn to_hex(self) -> String {
190        let mut s = String::from("0x");
191        for b in self.0.iter() {
192            use std::fmt::Write as _;
193            let _ = write!(s, "{:02x}", b);
194        }
195        s
196    }
197}
198
199/// All protocol messages as a single enum. Each variant includes the common
200/// `crdt` magic and `room_id` as part of the struct fields.
201#[derive(Debug, Clone, PartialEq, Eq)]
202pub enum ProtocolMessage {
203    JoinRequest {
204        crdt: CrdtType,
205        room_id: String,
206        auth: Vec<u8>,
207        version: Vec<u8>,
208    },
209    JoinResponseOk {
210        crdt: CrdtType,
211        room_id: String,
212        permission: Permission,
213        version: Vec<u8>,
214        extra: Option<Vec<u8>>,
215    },
216    JoinError {
217        crdt: CrdtType,
218        room_id: String,
219        code: JoinErrorCode,
220        message: String,
221        receiver_version: Option<Vec<u8>>,
222        app_code: Option<String>,
223    },
224    DocUpdate {
225        crdt: CrdtType,
226        room_id: String,
227        updates: Vec<Vec<u8>>,
228        batch_id: BatchId,
229    },
230    DocUpdateFragmentHeader {
231        crdt: CrdtType,
232        room_id: String,
233        batch_id: BatchId,
234        fragment_count: u64,
235        total_size_bytes: u64,
236    },
237    DocUpdateFragment {
238        crdt: CrdtType,
239        room_id: String,
240        batch_id: BatchId,
241        index: u64,
242        fragment: Vec<u8>,
243    },
244    RoomError {
245        crdt: CrdtType,
246        room_id: String,
247        code: RoomErrorCode,
248        message: String,
249    },
250    Ack {
251        crdt: CrdtType,
252        room_id: String,
253        ref_id: BatchId,
254        status: UpdateStatusCode,
255    },
256    Leave {
257        crdt: CrdtType,
258        room_id: String,
259    },
260}