aequora-codec 0.1.1

Server-authoritative, database-agnostic local-first synchronization for Rust
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
//! Checksummed framing and serialization codecs.

use aequora_types::ProtocolVersion;
use bytes::{Bytes, BytesMut};
use serde::{Deserialize, Serialize, de::DeserializeOwned};
use thiserror::Error;

/// Frame flag indicating a zstd-compressed Postcard payload.
pub const FLAG_ZSTD: u8 = 0b0000_0001;
const KNOWN_FLAGS: u8 = FLAG_ZSTD;

/// Optional payload compression selected after capability negotiation.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum Compression {
    /// Send the serialized payload directly.
    #[default]
    None,
    /// Use zstd when the payload reaches the configured threshold and compression is smaller.
    Zstd { level: i32 },
}

/// Encoding controls for one frame.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct EncodeOptions {
    /// Negotiated compression algorithm.
    pub compression: Compression,
    /// Do not spend CPU compressing payloads smaller than this value.
    pub compression_threshold: usize,
}

impl Default for EncodeOptions {
    fn default() -> Self {
        Self {
            compression: Compression::None,
            compression_threshold: 4_096,
        }
    }
}

/// Independent wire and decompressed limits used to prevent compression bombs.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct DecodeLimits {
    /// Maximum bytes carried by the frame.
    pub max_wire_bytes: usize,
    /// Maximum bytes permitted after decompression.
    pub max_decompressed_bytes: usize,
}

/// Aequora protocol magic.
pub const MAGIC: [u8; 4] = *b"AEQ1";
/// Fixed header size: magic, version, flags, kind, length, and BLAKE3 digest.
pub const HEADER_LEN: usize = 44;

/// Frame message discriminator.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[repr(u8)]
pub enum MessageKind {
    /// A synchronization request.
    SyncRequest = 1,
    /// A synchronization response.
    SyncResponse = 2,
    /// A bootstrap request.
    BootstrapRequest = 3,
    /// A bootstrap response.
    BootstrapResponse = 4,
    /// A request for a sequence of bounded bootstrap pages.
    SnapshotStreamRequest = 5,
    /// One page in a bounded bootstrap stream.
    SnapshotStreamResponse = 6,
    /// An advisory journal-advance notification.
    PushHint = 7,
    /// A transport-level error encoded without domain payloads.
    TransportError = 8,
}

impl TryFrom<u8> for MessageKind {
    type Error = CodecError;

    fn try_from(value: u8) -> Result<Self, Self::Error> {
        match value {
            1 => Ok(Self::SyncRequest),
            2 => Ok(Self::SyncResponse),
            3 => Ok(Self::BootstrapRequest),
            4 => Ok(Self::BootstrapResponse),
            5 => Ok(Self::SnapshotStreamRequest),
            6 => Ok(Self::SnapshotStreamResponse),
            7 => Ok(Self::PushHint),
            8 => Ok(Self::TransportError),
            other => Err(CodecError::MessageKind(other)),
        }
    }
}

/// Decoded, integrity-checked protocol frame.
#[derive(Clone, Copy, Debug)]
pub struct DecodedFrame<'a> {
    /// Protocol version from the frame header.
    pub protocol: ProtocolVersion,
    /// Reserved feature flags.
    pub flags: u8,
    /// Payload message kind.
    pub kind: MessageKind,
    /// Verified serialized payload.
    pub payload: &'a [u8],
}

/// Validated fixed header. Reading this before the payload permits an oversized frame to be
/// rejected without allocating its declared body.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct FrameHeader {
    pub protocol: ProtocolVersion,
    pub flags: u8,
    pub kind: MessageKind,
    pub payload_len: usize,
}

/// Wire decoding or encoding failure.
#[derive(Debug, Error)]
pub enum CodecError {
    /// Frame is shorter than the fixed header.
    #[error("frame is shorter than the {HEADER_LEN}-byte header")]
    Truncated,
    /// Magic bytes do not identify Aequora.
    #[error("invalid protocol magic")]
    Magic,
    /// Message kind is not supported.
    #[error("unsupported message kind {0}")]
    MessageKind(u8),
    /// Declared payload length does not match the frame.
    #[error("declared payload length does not match the frame")]
    Length,
    /// Payload exceeded the configured limit.
    #[error("payload length {actual} exceeds limit {maximum}")]
    PayloadTooLarge { actual: usize, maximum: usize },
    /// Payload digest did not match.
    #[error("payload integrity check failed")]
    Integrity,
    /// Frame uses flag bits unknown to this implementation.
    #[error("frame contains unsupported flags {0:#010b}")]
    Flags(u8),
    /// Borrowed decoding requires the serialized bytes to remain in the caller's stable buffer.
    #[error("borrowed decode is unavailable for compressed frames")]
    BorrowedCompressed,
    /// Peer requested compression that was not compiled into this crate.
    #[error("zstd compression support is not enabled")]
    CompressionUnavailable,
    /// Compression or decompression failed.
    #[error("zstd processing failed: {0}")]
    Compression(String),
    /// Postcard serialization failed.
    #[error("postcard serialization failed: {0}")]
    Postcard(#[from] postcard::Error),
    /// RON diagnostic serialization failed.
    #[cfg(feature = "ron")]
    #[error("RON serialization failed: {0}")]
    Ron(String),
    /// Optional JSON diagnostic serialization or deserialization failed.
    #[cfg(feature = "json")]
    #[error("JSON serialization failed: {0}")]
    Json(String),
}

/// Encodes a serializable value as a checksummed Postcard Aequora frame.
///
/// # Errors
///
/// Returns [`CodecError`] when Postcard serialization fails or the payload cannot fit in
/// the frame's 32-bit length field.
pub fn encode<T: Serialize>(
    protocol: ProtocolVersion,
    kind: MessageKind,
    value: &T,
) -> Result<Vec<u8>, CodecError> {
    Ok(encode_bytes(protocol, kind, value)?.to_vec())
}

/// Encodes directly into immutable reference-counted bytes for transport handoff without a
/// payload clone.
///
/// # Errors
///
/// Returns [`CodecError`] when serialization or framing fails.
pub fn encode_bytes<T: Serialize>(
    protocol: ProtocolVersion,
    kind: MessageKind,
    value: &T,
) -> Result<Bytes, CodecError> {
    encode_bytes_with_options(protocol, kind, value, EncodeOptions::default())
}

/// Encodes a checksummed frame with thresholded negotiated compression.
///
/// # Errors
///
/// Returns [`CodecError`] for serialization, compression, or length failures.
pub fn encode_with_options<T: Serialize>(
    protocol: ProtocolVersion,
    kind: MessageKind,
    value: &T,
    options: EncodeOptions,
) -> Result<Vec<u8>, CodecError> {
    Ok(encode_bytes_with_options(protocol, kind, value, options)?.to_vec())
}

/// Encodes a checksummed frame into a controlled [`BytesMut`] construction buffer and freezes it
/// for immutable sharing at the transport boundary.
///
/// # Errors
///
/// Returns [`CodecError`] for serialization, compression, or length failures.
pub fn encode_bytes_with_options<T: Serialize>(
    protocol: ProtocolVersion,
    kind: MessageKind,
    value: &T,
    options: EncodeOptions,
) -> Result<Bytes, CodecError> {
    let serialized = postcard::to_stdvec(value)?;
    let (flags, payload) = compress_payload(serialized, options)?;
    let length = u32::try_from(payload.len()).map_err(|_| CodecError::PayloadTooLarge {
        actual: payload.len(),
        maximum: u32::MAX as usize,
    })?;
    let mut frame = BytesMut::with_capacity(HEADER_LEN + payload.len());
    frame.extend_from_slice(&MAGIC);
    frame.extend_from_slice(&protocol.0.to_be_bytes());
    frame.extend_from_slice(&[flags, kind as u8]);
    frame.extend_from_slice(&length.to_be_bytes());
    frame.extend_from_slice(blake3::hash(&payload).as_bytes());
    frame.extend_from_slice(&payload);
    Ok(frame.freeze())
}

/// Validates the fixed frame preamble and declared length before callers allocate or read the
/// payload body.
///
/// # Errors
///
/// Returns [`CodecError`] for a short or malformed header, unsupported kind/flags, or a declared
/// payload beyond `max_payload`.
pub fn inspect_header(header: &[u8], max_payload: usize) -> Result<FrameHeader, CodecError> {
    if header.len() < HEADER_LEN {
        return Err(CodecError::Truncated);
    }
    if header[..4] != MAGIC {
        return Err(CodecError::Magic);
    }
    let protocol = ProtocolVersion(u16::from_be_bytes([header[4], header[5]]));
    let flags = header[6];
    if flags & !KNOWN_FLAGS != 0 {
        return Err(CodecError::Flags(flags));
    }
    let kind = MessageKind::try_from(header[7])?;
    let payload_len = u32::from_be_bytes([header[8], header[9], header[10], header[11]]) as usize;
    if payload_len > max_payload {
        return Err(CodecError::PayloadTooLarge {
            actual: payload_len,
            maximum: max_payload,
        });
    }
    Ok(FrameHeader {
        protocol,
        flags,
        kind,
        payload_len,
    })
}

/// Validates and splits a frame without deserializing its payload.
///
/// # Errors
///
/// Returns [`CodecError`] for malformed headers, invalid magic or kinds, excessive sizes,
/// inconsistent lengths, or a payload digest mismatch.
pub fn decode_frame(frame: &[u8], max_payload: usize) -> Result<DecodedFrame<'_>, CodecError> {
    let header = inspect_header(frame, max_payload)?;
    if frame.len() != HEADER_LEN + header.payload_len {
        return Err(CodecError::Length);
    }
    let payload = &frame[HEADER_LEN..];
    let expected = &frame[12..HEADER_LEN];
    if blake3::hash(payload).as_bytes() != expected {
        return Err(CodecError::Integrity);
    }
    Ok(DecodedFrame {
        protocol: header.protocol,
        flags: header.flags,
        kind: header.kind,
        payload,
    })
}

/// Deserializes a borrowed typed view directly from an uncompressed stable frame buffer. The
/// returned value cannot outlive `frame`, keeping borrowed lifetimes away from durable state.
///
/// # Errors
///
/// Returns [`CodecError`] for invalid framing, a kind mismatch, compression, size, or Postcard
/// decoding failure.
pub fn decode_borrowed<'a, T>(
    frame: &'a [u8],
    expected_kind: MessageKind,
    max_payload: usize,
) -> Result<(ProtocolVersion, T), CodecError>
where
    T: Deserialize<'a>,
{
    let decoded = decode_frame(frame, max_payload)?;
    if decoded.kind != expected_kind {
        return Err(CodecError::MessageKind(decoded.kind as u8));
    }
    if decoded.flags & FLAG_ZSTD != 0 {
        return Err(CodecError::BorrowedCompressed);
    }
    Ok((decoded.protocol, postcard::from_bytes(decoded.payload)?))
}

/// Decodes and deserializes a framed Postcard value of the expected kind.
///
/// # Errors
///
/// Returns [`CodecError`] when frame validation or Postcard deserialization fails.
pub fn decode<T: DeserializeOwned>(
    frame: &[u8],
    expected_kind: MessageKind,
    max_payload: usize,
) -> Result<(ProtocolVersion, T), CodecError> {
    decode_with_limits(
        frame,
        expected_kind,
        DecodeLimits {
            max_wire_bytes: max_payload,
            max_decompressed_bytes: max_payload,
        },
    )
}

/// Decodes a frame with separate compressed-wire and decompressed payload limits.
///
/// # Errors
///
/// Returns [`CodecError`] for framing, integrity, decompression, size, or Postcard failures.
pub fn decode_with_limits<T: DeserializeOwned>(
    frame: &[u8],
    expected_kind: MessageKind,
    limits: DecodeLimits,
) -> Result<(ProtocolVersion, T), CodecError> {
    let decoded = decode_frame(frame, limits.max_wire_bytes)?;
    if decoded.kind != expected_kind {
        return Err(CodecError::MessageKind(decoded.kind as u8));
    }
    let decompressed;
    let payload = if decoded.flags & FLAG_ZSTD != 0 {
        decompressed = decompress_payload(decoded.payload, limits.max_decompressed_bytes)?;
        decompressed.as_slice()
    } else {
        if decoded.payload.len() > limits.max_decompressed_bytes {
            return Err(CodecError::PayloadTooLarge {
                actual: decoded.payload.len(),
                maximum: limits.max_decompressed_bytes,
            });
        }
        decoded.payload
    };
    let value = postcard::from_bytes(payload)?;
    Ok((decoded.protocol, value))
}

fn compress_payload(payload: Vec<u8>, options: EncodeOptions) -> Result<(u8, Vec<u8>), CodecError> {
    match options.compression {
        Compression::None => Ok((0, payload)),
        Compression::Zstd { level: _ } if payload.len() < options.compression_threshold => {
            Ok((0, payload))
        }
        #[cfg(feature = "zstd")]
        Compression::Zstd { level } => {
            let compressed = zstd::stream::encode_all(payload.as_slice(), level)
                .map_err(|error| CodecError::Compression(error.to_string()))?;
            if compressed.len() < payload.len() {
                Ok((FLAG_ZSTD, compressed))
            } else {
                Ok((0, payload))
            }
        }
        #[cfg(not(feature = "zstd"))]
        Compression::Zstd { .. } => Err(CodecError::CompressionUnavailable),
    }
}

#[cfg(feature = "zstd")]
fn decompress_payload(payload: &[u8], maximum: usize) -> Result<Vec<u8>, CodecError> {
    use std::io::Read;
    let decoder = zstd::stream::read::Decoder::new(payload)
        .map_err(|error| CodecError::Compression(error.to_string()))?;
    let take_limit = u64::try_from(maximum).unwrap_or(u64::MAX).saturating_add(1);
    let mut bounded = decoder.take(take_limit);
    let mut output = Vec::new();
    bounded
        .read_to_end(&mut output)
        .map_err(|error| CodecError::Compression(error.to_string()))?;
    if output.len() > maximum {
        return Err(CodecError::PayloadTooLarge {
            actual: output.len(),
            maximum,
        });
    }
    Ok(output)
}

#[cfg(not(feature = "zstd"))]
fn decompress_payload(_payload: &[u8], _maximum: usize) -> Result<Vec<u8>, CodecError> {
    Err(CodecError::CompressionUnavailable)
}

/// Serializes a value for human-readable diagnostics and fixtures.
///
/// # Errors
///
/// Returns [`CodecError`] when the value cannot be represented as RON.
#[cfg(feature = "ron")]
pub fn to_ron<T: Serialize>(value: &T) -> Result<String, CodecError> {
    ron::ser::to_string_pretty(value, ron::ser::PrettyConfig::default())
        .map_err(|error| CodecError::Ron(error.to_string()))
}

/// Serializes a value as optional human-readable JSON for debugging, administration, or web
/// interoperability. JSON is never used by the primary synchronization transport.
///
/// # Errors
///
/// Returns [`CodecError`] when the value cannot be represented as JSON.
#[cfg(feature = "json")]
pub fn to_json<T: Serialize>(value: &T) -> Result<String, CodecError> {
    serde_json::to_string(value).map_err(|error| CodecError::Json(error.to_string()))
}

/// Deserializes optional diagnostic JSON into a caller-selected DTO.
///
/// # Errors
///
/// Returns [`CodecError`] when the JSON is malformed or does not match the DTO.
#[cfg(feature = "json")]
pub fn from_json<T: DeserializeOwned>(value: &str) -> Result<T, CodecError> {
    serde_json::from_str(value).map_err(|error| CodecError::Json(error.to_string()))
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde::{Deserialize, Serialize};

    #[derive(Debug, Deserialize, Eq, PartialEq, Serialize)]
    struct Example {
        value: u32,
    }

    #[derive(Debug, Deserialize, Eq, PartialEq, Serialize)]
    struct BorrowedExample<'a> {
        value: &'a str,
    }

    #[test]
    fn framed_values_round_trip() -> Result<(), CodecError> {
        let frame = encode(
            ProtocolVersion::V1,
            MessageKind::SyncRequest,
            &Example { value: 42 },
        )?;
        let (version, decoded) = decode::<Example>(&frame, MessageKind::SyncRequest, 1_024)?;
        assert_eq!(version, ProtocolVersion::V1);
        assert_eq!(decoded, Example { value: 42 });
        Ok(())
    }

    #[test]
    fn payload_tampering_is_detected() -> Result<(), CodecError> {
        let mut frame = encode(
            ProtocolVersion::V1,
            MessageKind::SyncRequest,
            &Example { value: 1 },
        )?;
        let last = frame.len().saturating_sub(1);
        frame[last] ^= 1;
        assert!(matches!(
            decode_frame(&frame, 1_024),
            Err(CodecError::Integrity)
        ));
        Ok(())
    }

    #[test]
    fn header_limit_rejects_declared_payload_before_body_is_present() -> Result<(), CodecError> {
        let frame = encode_bytes(
            ProtocolVersion::V1,
            MessageKind::SyncRequest,
            &Example { value: 42 },
        )?;
        let header = inspect_header(&frame[..HEADER_LEN], 1_024)?;
        assert_eq!(header.kind, MessageKind::SyncRequest);
        assert!(matches!(
            inspect_header(&frame[..HEADER_LEN], 0),
            Err(CodecError::PayloadTooLarge { .. })
        ));
        Ok(())
    }

    #[test]
    fn borrowed_postcard_view_lives_in_the_frame_buffer() -> Result<(), CodecError> {
        let frame = encode_bytes(
            ProtocolVersion::V1,
            MessageKind::SyncRequest,
            &BorrowedExample { value: "borrowed" },
        )?;
        let (_, decoded) =
            decode_borrowed::<BorrowedExample<'_>>(&frame, MessageKind::SyncRequest, 1_024)?;
        assert_eq!(decoded.value, "borrowed");
        Ok(())
    }

    #[cfg(feature = "zstd")]
    #[test]
    fn compressed_payloads_round_trip_with_a_decompressed_limit() -> Result<(), CodecError> {
        let value = vec![42_u8; 32_768];
        let frame = encode_with_options(
            ProtocolVersion::V1,
            MessageKind::SyncResponse,
            &value,
            EncodeOptions {
                compression: Compression::Zstd { level: 1 },
                compression_threshold: 1,
            },
        )?;
        assert_ne!(decode_frame(&frame, 1_024)?.flags & FLAG_ZSTD, 0);
        let (_, decoded) = decode_with_limits::<Vec<u8>>(
            &frame,
            MessageKind::SyncResponse,
            DecodeLimits {
                max_wire_bytes: 1_024,
                max_decompressed_bytes: 64 * 1_024,
            },
        )?;
        assert_eq!(decoded, value);
        assert!(matches!(
            decode_with_limits::<Vec<u8>>(
                &frame,
                MessageKind::SyncResponse,
                DecodeLimits {
                    max_wire_bytes: 1_024,
                    max_decompressed_bytes: 1_024
                },
            ),
            Err(CodecError::PayloadTooLarge { .. })
        ));
        Ok(())
    }

    #[cfg(feature = "json")]
    #[test]
    fn optional_json_round_trips_without_changing_wire_framing() -> Result<(), CodecError> {
        let encoded = to_json(&Example { value: 42 })?;
        assert_eq!(from_json::<Example>(&encoded)?, Example { value: 42 });
        Ok(())
    }
}