ozzy-proto 0.1.0

Sans-I/O application protocol and message types for Ozzy.
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
//! Single-partition subscriptions and bounded multipart reader delivery.
//! Correlated delivery supports request pipelines; notifications support push.
//! Decoding source metadata never proves ownership, persistence, or group confirmation.

mod encoder;
mod start;
mod subscription;
pub use start::{IdPolicy, Start};

pub use encoder::RecordsEncoder;

pub use subscription::{
    Target, decode_unsubscribe, decode_unsubscribed, encode_unsubscribe, encode_unsubscribed,
};

use crate::data::{
    self, Authority, CodecError, Cursor, DataLimits, OwnedRecords, Record, Records, capacity,
};
use crate::{
    ENVELOPE_BYTES, Envelope, EnvelopeLimits, GroupId, Opcode, Packet, PartitionId,
    PartitionIncarnation, ProducerId, SubscriptionId, Topic,
};
use bytes::{Bytes, BytesMut};

/// Identity of one subscribed log. Local logs do not fabricate group authority.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Source {
    /// Embedded owner log; topic is fixed by the subscription.
    Local {
        /// Stable producer owning the log.
        producer: ProducerId,
        /// Producer-local partition number.
        partition: PartitionId,
    },
    /// Confirmed group log; runtime must validate all authority fields.
    Group {
        /// Group and leader generation.
        authority: Authority,
        /// Immutable partition incarnation.
        partition: PartitionIncarnation,
        /// Nonzero ownership fence.
        owner_epoch: u64,
    },
}

/// A subscription replacement must use a fresh generation, even on the same link.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Subscription {
    /// Stable subscription identity.
    pub id: SubscriptionId,
    /// Nonzero generation UUID.
    pub generation: u128,
}

/// Exact-offset, single-topic reader request.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Subscribe {
    /// Session-scoped subscription generation.
    pub subscription: Subscription,
    /// Validated logical stream and topic.
    pub target: Target,
    /// Initial selector, resolved once to an exact retained offset.
    pub start: Start,
}

/// Decoded exact-offset subscription.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DecodedSubscribe {
    /// Session-scoped subscription generation.
    pub subscription: Subscription,
    /// Validated logical stream and topic.
    pub target: Target,
    /// Initial selector, resolved once to an exact retained offset.
    pub start: Start,
}

/// Confirmed subscription source. Does not itself claim durable data.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Subscribed {
    /// Session-scoped subscription generation.
    pub subscription: Subscription,
    /// Source used unchanged by records and receipt observations.
    pub source: Source,
    /// First resolved offset; reconnect resumes ordinary delivered offsets.
    pub resolved_offset: u64,
}

/// Common identity and offset fields of one contiguous reader batch.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct RecordHeader {
    /// Session-scoped subscription generation.
    pub subscription: Subscription,
    /// Owner/partition identity.
    pub source: Source,
    /// First offset; all following offsets are contiguous.
    pub first_offset: u64,
}

/// Identity and offset of one batch shared by every live reader of a partition.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PublicationHeader {
    /// Confirmed group log. Receivers compare it with their subscribed source.
    pub source: Source,
    /// First offset; all following offsets are contiguous.
    pub first_offset: u64,
}

/// Validated shared records borrowing both received frames. Receipt proves
/// neither the sender's authority nor that no earlier publication was lost.
#[derive(Debug, Clone, Copy)]
pub struct Publication<'a> {
    /// Source and first offset.
    pub header: PublicationHeader,
    /// Encoding of the complete records payload frame.
    pub payload_encoding: crate::append::PayloadEncoding,
    /// Opaque multipart records, fully validated before iteration.
    pub records: Records<'a>,
}

/// Validated records borrowing both received frames.
#[derive(Debug, Clone, Copy)]
pub struct Delivery<'a> {
    /// Source, subscription and first offset.
    pub header: RecordHeader,
    /// Encoding of the complete records payload frame.
    pub payload_encoding: crate::append::PayloadEncoding,
    /// Opaque multipart records, fully validated before iteration.
    pub records: Records<'a>,
}

/// Independent cumulative observations. No durable progress commit is implied.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Ack {
    /// Session-scoped subscription generation.
    pub subscription: Subscription,
    /// Same source as the delivered batch.
    pub source: Source,
    /// Highest contiguous offset accepted by the receiving runtime.
    pub received: Option<u64>,
    /// Highest contiguous offset processed by the application.
    pub processed: Option<u64>,
}

/// Read a shared-partition command's fixed subscription/source prefix. This
/// performs no record decoding or payload validation. Legacy local-log selectors
/// are excluded; native broker partitions have explicit group/incarnation IDs.
/// The destination must still decode the complete command and enforce its source.
pub fn route(packet: Packet<'_>, limits: EnvelopeLimits) -> Result<Source, CodecError> {
    route_subscription(packet, limits).map(|(_, source)| source)
}

/// Inspect a shared reader command's fixed generation and source without
/// decoding records. Session and full payload validation remain with the owner.
pub fn route_subscription(
    packet: Packet<'_>,
    limits: EnvelopeLimits,
) -> Result<(Subscription, Source), CodecError> {
    let response = match packet.envelope.opcode {
        Opcode::Subscribed | Opcode::Unsubscribed => true,
        Opcode::Subscribe | Opcode::Records | Opcode::Unsubscribe => false,
        Opcode::Ack => packet.envelope.response,
        _ => return Err(CodecError::Command),
    };
    command(packet.envelope, packet.envelope.opcode, response)?;
    packet
        .envelope
        .validate_frames(packet.metadata.len(), packet.payload.len(), limits)?;
    if packet.envelope.opcode != Opcode::Records && !packet.payload.is_empty() {
        return Err(CodecError::Length);
    }
    let mut cursor = Cursor(packet.metadata);
    let subscription = Subscription::decode(&mut cursor)?;
    if cursor.0.first() != Some(&1) {
        return Err(CodecError::Profile);
    }
    Source::decode(&mut cursor).map(|source| (subscription, source))
}

/// Inspect the fixed source of a live publication. Record descriptors and
/// payloads remain opaque until the destination performs complete decoding.
pub fn route_publication(packet: Packet<'_>, limits: EnvelopeLimits) -> Result<Source, CodecError> {
    command(packet.envelope, Opcode::RecordsPub, false)?;
    packet
        .envelope
        .validate_frames(packet.metadata.len(), packet.payload.len(), limits)?;
    let source = Source::decode(&mut Cursor(packet.metadata))?;
    publication_topic(source)?;
    Ok(source)
}

/// Encode SUBSCRIBE without growing storage; failure preserves its contents.
pub fn encode_subscribe(
    e: Envelope,
    v: &Subscribe,
    out: &mut Vec<u8>,
    limits: EnvelopeLimits,
) -> Result<[u8; ENVELOPE_BYTES], CodecError> {
    v.subscription.validate()?;
    v.target.validate()?;
    v.start.validate()?;
    let size = 32 + v.target.size() + v.start.size();
    let header = prepare(e, Opcode::Subscribe, false, size, out, limits)?;
    v.subscription.encode(out);
    v.target.encode(out);
    v.start.encode(out);
    Ok(header)
}

/// Decode and bound both topic names before allocating their validated value.
pub fn decode_subscribe(
    p: Packet<'_>,
    limits: EnvelopeLimits,
) -> Result<DecodedSubscribe, CodecError> {
    let mut c = control(p, Opcode::Subscribe, false, limits)?;
    let subscription = Subscription::decode(&mut c)?;
    let target = Target::decode(&mut c)?;
    let start = Start::decode(&mut c)?;
    end(c)?;
    Ok(DecodedSubscribe {
        subscription,
        target,
        start,
    })
}

/// Encode the source accepted for this subscription.
pub fn encode_subscribed(
    e: Envelope,
    v: Subscribed,
    out: &mut Vec<u8>,
    limits: EnvelopeLimits,
) -> Result<[u8; ENVELOPE_BYTES], CodecError> {
    v.subscription.validate()?;
    v.source.validate()?;
    let header = prepare(
        e,
        Opcode::Subscribed,
        true,
        40 + v.source.size(),
        out,
        limits,
    )?;
    v.subscription.encode(out);
    v.source.encode(out);
    out.extend_from_slice(&v.resolved_offset.to_be_bytes());
    Ok(header)
}

/// Decode the source accepted for this subscription.
pub fn decode_subscribed(p: Packet<'_>, limits: EnvelopeLimits) -> Result<Subscribed, CodecError> {
    let mut c = control(p, Opcode::Subscribed, true, limits)?;
    let v = Subscribed {
        subscription: Subscription::decode(&mut c)?,
        source: Source::decode(&mut c)?,
        resolved_offset: c.u64()?,
    };
    end(c)?;
    Ok(v)
}

/// Encode one nonempty contiguous batch using caller-reserved frames.
pub fn encode_records(
    e: Envelope,
    v: RecordHeader,
    records: &[Record<'_>],
    metadata: &mut Vec<u8>,
    payload: &mut Vec<u8>,
    limits: DataLimits,
) -> Result<[u8; ENVELOPE_BYTES], CodecError> {
    encode_records_from(
        e,
        v,
        records
            .iter()
            .map(|r| (r.message_id, r.encoding, r.parts.iter().copied())),
        metadata,
        payload,
        limits,
    )
}

/// Encode directly from a repeatable record iterator, without a temporary record table.
/// Cloning the iterator must yield the same IDs and multipart bytes.
pub fn encode_records_from<'a, I, P>(
    e: Envelope,
    v: RecordHeader,
    records: I,
    metadata: &mut Vec<u8>,
    payload: &mut Vec<u8>,
    limits: DataLimits,
) -> Result<[u8; ENVELOPE_BYTES], CodecError>
where
    I: ExactSizeIterator<Item = (crate::MessageId, data::Encoding, P)> + Clone,
    P: Iterator<Item = &'a [u8]>,
{
    command(e, Opcode::Records, false)?;
    v.subscription.validate()?;
    v.source.validate()?;
    let (descriptors, bytes) = data::record_sizes(records.clone(), v.first_offset, limits)?;
    let size = data::add(45 + v.source.size(), descriptors)?;
    let header = e.encode_header(size, bytes, limits.envelope)?;
    capacity(metadata, size)?;
    capacity(payload, bytes)?;
    metadata.clear();
    payload.clear();
    v.subscription.encode(metadata);
    v.source.encode(metadata);
    metadata.extend_from_slice(&v.first_offset.to_be_bytes());
    crate::append::encode_payload_encoding(metadata, crate::append::PayloadEncoding::Raw, bytes)?;
    data::write_records(records, metadata, payload);
    Ok(header)
}

/// Decode complete descriptors and payload lengths before exposing any record.
pub fn decode_records(p: Packet<'_>, limits: DataLimits) -> Result<Delivery<'_>, CodecError> {
    command(p.envelope, Opcode::Records, false)?;
    p.envelope
        .validate_frames(p.metadata.len(), p.payload.len(), limits.envelope)?;
    let mut c = Cursor(p.metadata);
    let header = RecordHeader {
        subscription: Subscription::decode(&mut c)?,
        source: Source::decode(&mut c)?,
        first_offset: c.u64()?,
    };
    let payload_encoding = crate::append::PayloadEncoding::try_from(c.byte()?)?;
    let decoded_bytes = c.u32()? as usize;
    crate::append::validate_payload_encoding(
        payload_encoding,
        decoded_bytes,
        p.payload.len(),
        limits,
    )?;
    if payload_encoding != crate::append::PayloadEncoding::Raw {
        return Err(CodecError::Profile);
    }
    let records = data::decode_records(c.0, p.payload, header.first_offset, limits)?;
    Ok(Delivery {
        header,
        payload_encoding,
        records,
    })
}

/// Owned records of one delivery or publication.
#[derive(Debug, Clone)]
pub struct OwnedDelivery<H> {
    /// Delivery or publication header.
    pub header: H,
    /// Encoding of the received payload frame.
    pub payload_encoding: crate::append::PayloadEncoding,
    /// Records sharing the received frames or the decompressed payload.
    pub records: OwnedRecords,
}

fn owned_delivery<H>(
    mut c: Cursor<'_>,
    first_offset: u64,
    header: H,
    metadata: &Bytes,
    payload: &Bytes,
    limits: DataLimits,
    buffer: &mut BytesMut,
) -> Result<OwnedDelivery<H>, CodecError> {
    let (payload_encoding, payload) =
        crate::append::decode_owned_payload(&mut c, payload, buffer, limits)?;
    let records = data::decode_records(c.0, &payload, first_offset, limits)?;
    Ok(OwnedDelivery {
        header,
        payload_encoding,
        records: records.to_owned(metadata, &payload),
    })
}

/// Decode a raw or whole-group LZ4 delivery into owned records. Raw records
/// share `metadata` and `payload`, the frames `p` was decoded from. LZ4 records
/// own bytes decompressed into `buffer`, whose allocation is reused once every
/// record of earlier deliveries is released.
pub fn decode_owned_records(
    p: Packet<'_>,
    metadata: &Bytes,
    payload: &Bytes,
    limits: DataLimits,
    buffer: &mut BytesMut,
) -> Result<OwnedDelivery<RecordHeader>, CodecError> {
    command(p.envelope, Opcode::Records, false)?;
    p.envelope
        .validate_frames(p.metadata.len(), p.payload.len(), limits.envelope)?;
    let mut c = Cursor(p.metadata);
    let header = RecordHeader {
        subscription: Subscription::decode(&mut c)?,
        source: Source::decode(&mut c)?,
        first_offset: c.u64()?,
    };
    owned_delivery(
        c,
        header.first_offset,
        header,
        metadata,
        payload,
        limits,
        buffer,
    )
}

/// Decode one shared publication. Descriptors and payload lengths are complete
/// before any record is exposed.
pub fn decode_publication(
    p: Packet<'_>,
    limits: DataLimits,
) -> Result<Publication<'_>, CodecError> {
    command(p.envelope, Opcode::RecordsPub, false)?;
    p.envelope
        .validate_frames(p.metadata.len(), p.payload.len(), limits.envelope)?;
    let mut c = Cursor(p.metadata);
    let header = PublicationHeader {
        source: Source::decode(&mut c)?,
        first_offset: c.u64()?,
    };
    publication_topic(header.source)?;
    let payload_encoding = crate::append::PayloadEncoding::try_from(c.byte()?)?;
    let decoded_bytes = c.u32()? as usize;
    crate::append::validate_payload_encoding(
        payload_encoding,
        decoded_bytes,
        p.payload.len(),
        limits,
    )?;
    if payload_encoding != crate::append::PayloadEncoding::Raw {
        return Err(CodecError::Profile);
    }
    let records = data::decode_records(c.0, p.payload, header.first_offset, limits)?;
    Ok(Publication {
        header,
        payload_encoding,
        records,
    })
}

/// Decode a raw or whole-group LZ4 publication into owned records, with the
/// frame and buffer ownership of [`decode_owned_records`].
pub fn decode_owned_publication(
    p: Packet<'_>,
    metadata: &Bytes,
    payload: &Bytes,
    limits: DataLimits,
    buffer: &mut BytesMut,
) -> Result<OwnedDelivery<PublicationHeader>, CodecError> {
    command(p.envelope, Opcode::RecordsPub, false)?;
    p.envelope
        .validate_frames(p.metadata.len(), p.payload.len(), limits.envelope)?;
    let mut c = Cursor(p.metadata);
    let header = PublicationHeader {
        source: Source::decode(&mut c)?,
        first_offset: c.u64()?,
    };
    publication_topic(header.source)?;
    owned_delivery(
        c,
        header.first_offset,
        header,
        metadata,
        payload,
        limits,
        buffer,
    )
}

/// Live-stream topic of one group partition: the group, then the partition. A
/// reader that subscribes to the bare group receives all of its partitions.
/// Local logs have no shared live stream.
pub fn publication_topic(source: Source) -> Result<[u8; 32], CodecError> {
    let Source::Group {
        authority,
        partition,
        ..
    } = source
    else {
        return Err(CodecError::Profile);
    };
    let mut topic = [0; 32];
    topic[..16].copy_from_slice(authority.group_id.as_bytes());
    topic[16..].copy_from_slice(partition.as_bytes());
    Ok(topic)
}

/// Encode cumulative receipt/processing observations; never claim persistence.
pub fn encode_ack(
    e: Envelope,
    v: Ack,
    out: &mut Vec<u8>,
    limits: EnvelopeLimits,
) -> Result<[u8; ENVELOPE_BYTES], CodecError> {
    v.validate()?;
    let size = 34
        + v.source.size()
        + 8 * (usize::from(v.received.is_some()) + usize::from(v.processed.is_some()));
    let header = prepare(e, Opcode::Ack, e.response, size, out, limits)?;
    v.subscription.encode(out);
    v.source.encode(out);
    position(out, v.received);
    position(out, v.processed);
    Ok(header)
}

/// Decode independent progress positions, rejecting processing beyond receipt.
pub fn decode_ack(p: Packet<'_>, limits: EnvelopeLimits) -> Result<Ack, CodecError> {
    let mut c = control(p, Opcode::Ack, p.envelope.response, limits)?;
    let v = Ack {
        subscription: Subscription::decode(&mut c)?,
        source: Source::decode(&mut c)?,
        received: read_position(&mut c)?,
        processed: read_position(&mut c)?,
    };
    end(c)?;
    v.validate()?;
    Ok(v)
}

impl Ack {
    fn validate(self) -> Result<(), CodecError> {
        self.subscription.validate()?;
        self.source.validate()?;
        if self
            .processed
            .is_some_and(|p| self.received.is_none_or(|r| p > r))
        {
            return Err(CodecError::Position);
        }
        Ok(())
    }
}

impl Subscription {
    fn validate(self) -> Result<(), CodecError> {
        nonzero(self.id.as_bytes())?;
        nonzero(&self.generation.to_be_bytes())
    }
    fn encode(self, out: &mut Vec<u8>) {
        out.extend_from_slice(self.id.as_bytes());
        out.extend_from_slice(&self.generation.to_be_bytes());
    }
    fn decode(c: &mut Cursor<'_>) -> Result<Self, CodecError> {
        let v = Self {
            id: SubscriptionId::from_bytes(c.array()?),
            generation: u128::from_be_bytes(c.array()?),
        };
        v.validate()?;
        Ok(v)
    }
}

impl Source {
    fn size(self) -> usize {
        match self {
            Self::Local { .. } => 21,
            Self::Group { .. } => 57,
        }
    }
    fn validate(self) -> Result<(), CodecError> {
        match self {
            Self::Local { producer, .. } => nonzero(producer.as_bytes()),
            Self::Group {
                authority,
                partition,
                owner_epoch,
            } => {
                nonzero(authority.group_id.as_bytes())?;
                nonzero(partition.as_bytes())?;
                if authority.config_epoch == 0 || owner_epoch == 0 {
                    return Err(CodecError::Identity);
                }
                Ok(())
            }
        }
    }
    fn encode(self, out: &mut Vec<u8>) {
        match self {
            Self::Local {
                producer,
                partition,
            } => {
                out.push(0);
                out.extend_from_slice(producer.as_bytes());
                out.extend_from_slice(&partition.get().to_be_bytes());
            }
            Self::Group {
                authority,
                partition,
                owner_epoch,
            } => {
                out.push(1);
                out.extend_from_slice(authority.group_id.as_bytes());
                out.extend_from_slice(&authority.config_epoch.to_be_bytes());
                out.extend_from_slice(&authority.view.to_be_bytes());
                out.extend_from_slice(partition.as_bytes());
                out.extend_from_slice(&owner_epoch.to_be_bytes());
            }
        }
    }
    fn decode(c: &mut Cursor<'_>) -> Result<Self, CodecError> {
        let v = match c.byte()? {
            0 => Self::Local {
                producer: ProducerId::from_bytes(c.array()?),
                partition: PartitionId::new(c.u32()?),
            },
            1 => Self::Group {
                authority: Authority {
                    group_id: GroupId::from_bytes(c.array()?),
                    config_epoch: c.u64()?,
                    view: c.u64()?,
                },
                partition: PartitionIncarnation::from_bytes(c.array()?),
                owner_epoch: c.u64()?,
            },
            _ => return Err(CodecError::Profile),
        };
        v.validate()?;
        Ok(v)
    }
}

fn nonzero(id: &[u8; 16]) -> Result<(), CodecError> {
    if id == &[0; 16] {
        return Err(CodecError::Identity);
    }
    Ok(())
}

fn text(out: &mut Vec<u8>, v: &str) {
    out.extend_from_slice(&(v.len() as u32).to_be_bytes());
    out.extend_from_slice(v.as_bytes());
}

fn read_text<'a>(c: &mut Cursor<'a>) -> Result<&'a str, CodecError> {
    let n = c.u32()? as usize;
    if n == 0 || n > 255 {
        return Err(CodecError::Profile);
    }
    std::str::from_utf8(c.take(n)?).map_err(|_| CodecError::Profile)
}

fn position(out: &mut Vec<u8>, v: Option<u64>) {
    out.push(u8::from(v.is_some()));
    if let Some(v) = v {
        out.extend_from_slice(&v.to_be_bytes());
    }
}

fn read_position(c: &mut Cursor<'_>) -> Result<Option<u64>, CodecError> {
    match c.byte()? {
        0 => Ok(None),
        1 => Ok(Some(c.u64()?)),
        _ => Err(CodecError::Profile),
    }
}

fn command(e: Envelope, opcode: Opcode, response: bool) -> Result<(), CodecError> {
    if e.opcode != opcode
        || e.response != response
        || (!matches!(opcode, Opcode::Records | Opcode::RecordsPub | Opcode::Ack)
            && e.request_id.is_none())
        || (opcode == Opcode::RecordsPub && e.request_id.is_some())
        || (opcode == Opcode::Ack && e.response && e.request_id.is_none())
    {
        return Err(CodecError::Command);
    }
    Ok(())
}

fn prepare(
    e: Envelope,
    opcode: Opcode,
    response: bool,
    size: usize,
    out: &mut Vec<u8>,
    limits: EnvelopeLimits,
) -> Result<[u8; ENVELOPE_BYTES], CodecError> {
    command(e, opcode, response)?;
    let header = e.encode_header(size, 0, limits)?;
    capacity(out, size)?;
    out.clear();
    Ok(header)
}

fn control(
    p: Packet<'_>,
    opcode: Opcode,
    response: bool,
    limits: EnvelopeLimits,
) -> Result<Cursor<'_>, CodecError> {
    command(p.envelope, opcode, response)?;
    p.envelope
        .validate_frames(p.metadata.len(), p.payload.len(), limits)?;
    if !p.payload.is_empty() {
        return Err(CodecError::Length);
    }
    Ok(Cursor(p.metadata))
}

fn end(c: Cursor<'_>) -> Result<(), CodecError> {
    if c.0.is_empty() {
        Ok(())
    } else {
        Err(CodecError::Length)
    }
}