Skip to main content

ostrya_remote/proto/
message.rs

1//! The messages of the protocol and their GVariant bodies.
2
3use std::sync::LazyLock;
4
5use ostrya_core::{Checksum, ObjectName, ObjectType};
6use ostrya_gvariant::{
7    ArrayIter, DictBuilder, GvDecode, GvEncode, GvType, Slice, Type, Value, encode_to_vec, to_bytes,
8};
9
10use super::{
11    Encoding, Expected, Kind, MAX_FRAME_LIMIT, MIN_FRAME_LIMIT, RefOutcome, RefState, RefUpdate,
12    checksum, have_type, header_type, maybe_value, object_name, object_name_value, protocol,
13};
14use crate::error::{Error, ErrorCode, Result};
15
16/// The type of the `server-commit` value of a `Commit`.
17const SERVER_COMMIT_SIGNATURE: &str = "(sasas(ayay)ssa{sv}a(say)a{sv})";
18
19fn parse(signature: &str) -> Type {
20    Type::parse(signature).expect("valid signature")
21}
22
23static HELLO: LazyLock<Type> = LazyLock::new(|| parse("(ua{sv}as)"));
24static HELLO_REPLY: LazyLock<Type> = LazyLock::new(|| parse("(ua{sv}a(smay))"));
25static OBJECT_NAMES: LazyLock<Type> = LazyLock::new(|| parse("a(yay)"));
26static BYTES: LazyLock<Type> = LazyLock::new(|| parse("ay"));
27static OBJECT_HEADER: LazyLock<Type> = LazyLock::new(|| parse("(yayy)"));
28static OBJECTS_REPLY: LazyLock<Type> = LazyLock::new(|| parse("(ut)"));
29static UPDATES: LazyLock<Type> = LazyLock::new(|| parse("a(symaymay)"));
30static SERVER_COMMIT: LazyLock<Type> = LazyLock::new(|| parse(SERVER_COMMIT_SIGNATURE));
31static COMMIT_REPLY: LazyLock<Type> = LazyLock::new(|| parse("a(smaymay)"));
32static ERROR: LazyLock<Type> = LazyLock::new(|| parse("(ssa{sv})"));
33static STRV: LazyLock<Type> = LazyLock::new(|| parse("as"));
34static MAYBE_CHECKSUM: LazyLock<Type> = LazyLock::new(|| parse("may"));
35static PULL_HELLO: LazyLock<Type> = LazyLock::new(|| parse("(ua{sv})"));
36static GET_REPLY: LazyLock<Type> = LazyLock::new(|| parse("(bmt)"));
37static LIST_REFS: LazyLock<Type> = LazyLock::new(|| parse("(asa{sv})"));
38static VALUE_IN_COMMIT: LazyLock<Type> = LazyLock::new(|| parse("((v))"));
39
40/// The first message of a push client.
41#[derive(Debug, Clone, PartialEq, Eq)]
42pub struct Hello {
43    /// The protocol version that the client requests.
44    pub version: u32,
45    /// The name and version of the client, under the key `agent`.
46    pub agent: Option<String>,
47    /// The refs that the client intends to update, each `NAME` or
48    /// `@ID:NAME`, and in a one-way stream also `REMOTE:NAME`.
49    ///
50    /// The server reads `@ID:NAME` with `ID` its own collection id as the
51    /// local ref `NAME`.
52    pub refs: Vec<String>,
53    /// The flag that is `true` if the `Hello` opens a
54    /// [one-way stream](super#one-way-stream).
55    ///
56    /// In a one-way stream, the receiver sends no message. The key is
57    /// `one-way`. The encoder writes the key only if the value is `true`, and
58    /// the decoder reads an absent key as `false`.
59    pub one_way: bool,
60}
61
62/// The reply to a `Hello`, with the facts and limits of the server.
63///
64/// It also gives the state of each ref that the `Hello` names.
65#[derive(Debug, Clone, PartialEq, Eq)]
66pub struct HelloReply {
67    /// The protocol version that the server speaks for the session.
68    pub version: u32,
69    /// The repository mode, under the key `mode`.
70    pub mode: String,
71    /// The collection id of the repository, under the key `collection-id`.
72    ///
73    /// The refs of this collection are the local refs of the server.
74    pub collection_id: Option<String>,
75    /// The frame limit that the server announces, under the key `max-frame`.
76    ///
77    /// Encode and decode return [`Error::Protocol`] for a value outside
78    /// [`MIN_FRAME_LIMIT`](super::MIN_FRAME_LIMIT)`..=`[`MAX_FRAME_LIMIT`](super::MAX_FRAME_LIMIT).
79    pub max_frame: u32,
80    /// The maximum number of entries in one `Have`, under the key `max-have`.
81    ///
82    /// The value is at least 1. For the value 0, encode and decode return
83    /// [`Error::Protocol`].
84    pub max_have: u32,
85    /// The content encodings that the server accepts, under the key
86    /// `encodings`.
87    ///
88    /// The decoder drops a name that is not an encoding.
89    pub encodings: Vec<Encoding>,
90    /// The most object streams at a time, under the key `parallel-uploads`.
91    ///
92    /// The server serves at most this number of object streams at the same
93    /// time in one session. The value is at least 1. For the value 0, encode and
94    /// decode return [`Error::Protocol`].
95    pub parallel_uploads: u32,
96    /// The state of each ref that the `Hello` names, one entry for each ref.
97    pub refs: Vec<RefState>,
98}
99
100/// The reply to a `Have`, with one bit for each entry.
101///
102/// Bit `i` is bit `i % 8` of byte `i / 8`, counted from the least significant
103/// bit. If a bit is set, the server does not hold the object, and the client
104/// must send it.
105#[derive(Debug, Clone, PartialEq, Eq)]
106pub struct HaveReply {
107    /// The bitmap of the entries.
108    pub bitmap: Vec<u8>,
109}
110
111impl HaveReply {
112    /// Creates a reply from one `bool` for each entry of the `Have`.
113    ///
114    /// Bit `i` is set if entry `i` of `missing` is `true`. For `n` entries,
115    /// the bitmap has `n.div_ceil(8)` bytes.
116    pub fn from_missing(missing: impl IntoIterator<Item = bool>) -> HaveReply {
117        let mut bitmap = Vec::new();
118        for (i, set) in missing.into_iter().enumerate() {
119            if i % 8 == 0 {
120                bitmap.push(0);
121            }
122            if set {
123                bitmap[i / 8] |= 1 << (i % 8);
124            }
125        }
126        HaveReply { bitmap }
127    }
128
129    /// Returns `true` if the server does not hold entry `index`.
130    ///
131    /// For an `index` after the end of the bitmap, it returns `false`.
132    pub fn is_missing(&self, index: usize) -> bool {
133        self.bitmap
134            .get(index / 8)
135            .is_some_and(|b| b & (1 << (index % 8)) != 0)
136    }
137
138    /// Checks the reply against a `Have` of `entries` entries.
139    ///
140    /// The bitmap must be `entries.div_ceil(8)` bytes long, and the bits
141    /// after the last entry must be zero.
142    ///
143    /// # Errors
144    ///
145    /// - [`Error::Protocol`] if the bitmap has a different length.
146    /// - [`Error::Protocol`] if the bitmap sets a bit after the last entry.
147    pub fn check_len(&self, entries: usize) -> Result<()> {
148        if self.bitmap.len() != entries.div_ceil(8) {
149            return Err(protocol(format!(
150                "HaveReply of {} bytes for {entries} entries",
151                self.bitmap.len()
152            )));
153        }
154        let tail = entries % 8;
155        if tail != 0 && self.bitmap[entries / 8] >> tail != 0 {
156            return Err(protocol("HaveReply sets a bit after the last entry"));
157        }
158        Ok(())
159    }
160}
161
162/// The message that starts one object in the
163/// [object stream](super#object-stream).
164#[derive(Debug, Clone, PartialEq, Eq)]
165pub struct ObjectHeader {
166    /// The type and the checksum of the object.
167    ///
168    /// For a `CommitMeta` object, the checksum is the checksum of its commit.
169    pub name: ObjectName,
170    /// The encoding of the object bytes.
171    ///
172    /// [`Encoding::Deflate`] is allowed for a file object alone.
173    pub encoding: Encoding,
174}
175
176/// The reply of the server at the end of one object stream.
177///
178/// The counts are those of one stream. If two streams of one session send the
179/// same content, dirtree, dirmeta, or commit object at the same time, both
180/// can count it. A second detached metadata object for one commit is
181/// [`Error::Protocol`], also from another stream, and the session ends.
182#[derive(Debug, Clone, PartialEq, Eq)]
183pub struct ObjectsReply {
184    /// The number of objects that the server stored.
185    pub objects: u32,
186    /// The number of payload bytes that the server wrote.
187    pub payload_bytes: u64,
188}
189
190/// The `Commit` message, with the ref updates of the transaction.
191#[derive(Debug, Clone, PartialEq, Eq)]
192pub struct CommitRequest {
193    /// The ref updates.
194    ///
195    /// A `Commit` with a [`server_commit`](Self::server_commit) holds no
196    /// update.
197    pub updates: Vec<RefUpdate>,
198    /// The flag that allows a ref update that is not a fast-forward.
199    ///
200    /// The key is `force`. The encoder writes the key only if the value is
201    /// `true`, and the decoder reads an absent key as `false`.
202    pub force: bool,
203    /// The commit that the server makes, under the key `server-commit`.
204    ///
205    /// The encoder writes the key only if the value is `Some`, and the
206    /// decoder reads an absent key as `None`. The value is boxed, so a
207    /// [`Message`] of another kind stays small.
208    pub server_commit: Option<Box<ServerCommit>>,
209}
210
211/// A commit that the server makes from a tree and the fields that the client
212/// sends, the value of the `server-commit` key of a `Commit`.
213///
214/// The value has the type `(sasas(ayay)ssa{sv}a(say)a{sv})`. Its members hold the
215/// fields in the order of this struct. The root dirtree and the root dirmeta
216/// make one `(ayay)` member. [`timestamp`](Self::timestamp) and
217/// [`orphan`](Self::orphan) are keys of the last member, a dict of options.
218///
219/// The server reads the tip of the branch under its update lock, and writes
220/// the commit with that tip as its parent. It moves the branch and creates
221/// each tag at the new commit. The `CommitReply` of a server commit holds
222/// one entry for the branch, then one entry for each tag. The `new` commit of
223/// each entry is the commit that the server wrote.
224#[derive(Debug, Clone, PartialEq, Eq)]
225pub struct ServerCommit {
226    /// The branch that the server moves to the new commit: `NAME` or
227    /// `@ID:NAME`.
228    pub branch: String,
229    /// The tags that the server creates at the new commit, in order, each
230    /// `NAME` or `@ID:NAME`.
231    ///
232    /// The branch and each tag are in one namespace, after the server reads
233    /// `@ID:` with `ID` its own collection id as a local ref.
234    pub tags: Vec<String>,
235    /// The names that the commit binds and that get no ref, in order, each a
236    /// plain `NAME`.
237    ///
238    /// The `ostree.ref-binding` of the commit holds the name part of the
239    /// branch and of each tag, and each of these names.
240    pub bind_refs: Vec<String>,
241    /// The checksum of the root dirtree of the commit.
242    pub root_dirtree: Checksum,
243    /// The checksum of the root dirmeta of the commit.
244    pub root_dirmeta: Checksum,
245    /// The subject of the commit.
246    pub subject: String,
247    /// The body of the commit.
248    pub body: String,
249    /// The metadata entries of the client, in order.
250    ///
251    /// Each entry is a key and the bytes of a `v` in normal form: the bytes
252    /// of the value, a zero byte, and the type signature of the value.
253    /// [`to_bytes`](ostrya_gvariant::to_bytes) with [`Type::Variant`] gives
254    /// these bytes. The dict is data, and the rules of a protocol dict do not
255    /// apply to it: the decoder keeps each entry in order, also a key that
256    /// occurs two times. The decoder and the encoder check the bytes of each
257    /// entry and build no value tree.
258    pub metadata: Vec<(String, Vec<u8>)>,
259    /// The attachments of the commit, in the order of the client: field 2 of
260    /// the commit.
261    ///
262    /// Each entry is a name and the checksum of a commit. The member has the
263    /// type `a(say)`, with the 32 bytes of each checksum. The encoder and the
264    /// decoder refuse an entry with an empty name. The decoder refuses a
265    /// checksum that is not 32 bytes. Both keep two entries with one name, and
266    /// the server refuses them. The server writes the entries sorted by name
267    /// in byte order.
268    pub related: Vec<(String, Checksum)>,
269    /// The commit time in seconds since the Unix epoch, UTC, under the key
270    /// `timestamp`.
271    ///
272    /// `None` gives the clock of the server. The encoder writes the key only
273    /// if the value is `Some`.
274    pub timestamp: Option<u64>,
275    /// The flag that makes a commit with no parent, under the key `orphan`.
276    ///
277    /// The encoder writes the key only if the value is `true`, and the
278    /// decoder reads an absent key as `false`.
279    pub orphan: bool,
280}
281
282/// The `Error` message, which the server sends to report a failure.
283///
284/// The session ends after this message. The `Error` message converts to the
285/// [`Error`] variant of its code, and [`Error::to_message`] converts back.
286#[derive(Debug, Clone, PartialEq, Eq)]
287pub struct ErrorMessage {
288    /// The code of the failure.
289    pub code: ErrorCode,
290    /// The text of the failure for a human reader.
291    pub message: String,
292    /// The missing objects, for the code `missing-objects`.
293    ///
294    /// The key is `missing`. The encoder writes the key only if the list is
295    /// not empty. Each object is of type 1 to 4. For another type,
296    /// encode and decode return [`Error::Protocol`].
297    pub missing: Vec<ObjectName>,
298    /// The current state of the ref, for the code `ref-mismatch`.
299    ///
300    /// The keys are `ref` and `current`. If the code is `ref-mismatch` and
301    /// this field is `None`, encode and decode return [`Error::Protocol`]. The
302    /// decode of a body with one of the two keys alone also returns
303    /// [`Error::Protocol`].
304    pub current: Option<RefState>,
305}
306
307/// The first message of a pull client.
308#[derive(Debug, Clone, PartialEq, Eq)]
309pub struct PullHello {
310    /// The highest pull protocol version that the client speaks.
311    pub version: u32,
312    /// The name and version of the client, under the key `agent`.
313    pub agent: Option<String>,
314}
315
316/// The reply to a `PullHello`, with the pull version of the session.
317///
318/// The dict of the reply is empty in version 1. A decoder ignores a key that
319/// it does not know.
320#[derive(Debug, Clone, PartialEq, Eq)]
321pub struct PullHelloReply {
322    /// The pull protocol version of the session.
323    ///
324    /// It is the lower of the version of the `PullHello` and the highest
325    /// version of the server.
326    pub version: u32,
327}
328
329/// The reply to one `Get` or one `ListRefs`.
330#[derive(Debug, Clone, PartialEq, Eq)]
331pub struct GetReply {
332    /// The flag that is `true` if the server serves the path or the listing.
333    ///
334    /// If `found` is `true`, a body of chunks follows the reply, as
335    /// [Object stream](super#object-stream) states.
336    pub found: bool,
337    /// The length of the body, if the server knows it.
338    ///
339    /// A reply to a `ListRefs` must hold it, as the specification of
340    /// [`ListRefs`](https://github.com/growler/ostrya/blob/main/docs/format-reference.md#listrefs) states. If `found` is `false` and the length
341    /// is present, encode and decode return [`Error::Protocol`].
342    pub len: Option<u64>,
343}
344
345/// The `ListRefs` message: the entries of a ref listing request.
346///
347/// Each entry is a ref pattern of a
348/// [`RefSelector`](ostrya_core::RefSelector), with an optional leading `!`.
349/// The codec does not check the entries.
350/// [`MAX_REF_PATTERNS`](super::MAX_REF_PATTERNS),
351/// [`MAX_REF_ENTRY_PARTS`](super::MAX_REF_ENTRY_PARTS), and
352/// [`MAX_REF_ENTRY_LEN`](super::MAX_REF_ENTRY_LEN) are the limits of a
353/// request. The two lists share the limit of entries. The specification of
354/// [`ListRefs`](https://github.com/growler/ostrya/blob/main/docs/format-reference.md#listrefs)
355/// states the reply.
356#[derive(Debug, Clone, PartialEq, Eq, Default)]
357pub struct ListRefsRequest {
358    /// The entries that the server matches against the names of the local
359    /// refs.
360    pub refs: Vec<String>,
361    /// The entries that the server matches against `ID/NAME` of the
362    /// collection refs, under the key `collections`.
363    ///
364    /// `None` asks for no collection ref. The encoder writes the key only if
365    /// the value is `Some`, also for an empty list. An empty list selects
366    /// each collection ref.
367    pub collections: Option<Vec<String>>,
368}
369
370/// A message of the push or the pull protocol.
371///
372/// A later protocol version can add messages.
373#[derive(Debug, Clone, PartialEq, Eq)]
374#[non_exhaustive]
375pub enum Message {
376    /// The `Hello` message.
377    Hello(Hello),
378    /// The `HelloReply` message.
379    HelloReply(HelloReply),
380    /// The `Have` message, with the objects that the client offers.
381    ///
382    /// Each object is of type 1 to 4.
383    Have(Vec<ObjectName>),
384    /// The `HaveReply` message.
385    HaveReply(HaveReply),
386    /// The `ObjectHeader` message.
387    ObjectHeader(ObjectHeader),
388    /// The `ObjectsEnd` message.
389    ObjectsEnd,
390    /// The `ObjectsReply` message.
391    ObjectsReply(ObjectsReply),
392    /// The `Commit` message.
393    Commit(CommitRequest),
394    /// The `CommitReply` message, with one outcome for each ref update, or
395    /// for each ref of a [`ServerCommit`].
396    CommitReply(Vec<RefOutcome>),
397    /// The `Error` message.
398    Error(ErrorMessage),
399    /// The `Abort` message.
400    Abort,
401    /// The `PullHello` message.
402    PullHello(PullHello),
403    /// The `PullHelloReply` message.
404    PullHelloReply(PullHelloReply),
405    /// The `Get` message, with the path of one file.
406    ///
407    /// The path is relative to the repository root.
408    Get(String),
409    /// The `GetReply` message.
410    GetReply(GetReply),
411    /// The `ListRefs` message, with the entries of a ref listing request.
412    ListRefs(ListRefsRequest),
413}
414
415impl Message {
416    /// Returns the kind of the message.
417    pub fn kind(&self) -> Kind {
418        match self {
419            Message::Hello(_) => Kind::Hello,
420            Message::HelloReply(_) => Kind::HelloReply,
421            Message::Have(_) => Kind::Have,
422            Message::HaveReply(_) => Kind::HaveReply,
423            Message::ObjectHeader(_) => Kind::ObjectHeader,
424            Message::ObjectsEnd => Kind::ObjectsEnd,
425            Message::ObjectsReply(_) => Kind::ObjectsReply,
426            Message::Commit(_) => Kind::Commit,
427            Message::CommitReply(_) => Kind::CommitReply,
428            Message::Error(_) => Kind::Error,
429            Message::Abort => Kind::Abort,
430            Message::PullHello(_) => Kind::PullHello,
431            Message::PullHelloReply(_) => Kind::PullHelloReply,
432            Message::Get(_) => Kind::Get,
433            Message::GetReply(_) => Kind::GetReply,
434            Message::ListRefs(_) => Kind::ListRefs,
435        }
436    }
437
438    /// Encodes the body of the message, with no frame length and no kind byte.
439    ///
440    /// # Errors
441    ///
442    /// [`Error::Protocol`] if the message holds a value that it cannot carry:
443    ///
444    /// - a `HelloReply` whose `max_frame`, `max_have`, or `parallel_uploads`
445    ///   is out of range
446    /// - a `Have` entry or a `missing` object of a type other than 1 to 4, for
447    ///   example type 6
448    /// - an `ObjectHeader` of a type other than 1 to 4 and 6, or with
449    ///   [`Encoding::Deflate`] for an object that is not a file
450    /// - an `Error` message with the code `ref-mismatch` and no `current`
451    ///   state
452    /// - a `GetReply` whose `found` is `false` and that has a length
453    /// - a metadata entry of a [`ServerCommit`] whose bytes are not a `v` in
454    ///   normal form
455    /// - a string with an interior NUL byte, which the GVariant serializer
456    ///   refuses
457    pub fn encode_body(&self) -> Result<Vec<u8>> {
458        let (ty, value): (&Type, Value) = match self {
459            Message::Commit(c) => return encode_commit(c),
460            Message::ObjectsEnd => return Ok(Vec::new()),
461            Message::Abort => return Ok(vec![0]),
462            Message::Hello(h) => {
463                let mut opts = DictBuilder::new();
464                if let Some(agent) = &h.agent {
465                    opts.insert_str("agent", agent);
466                }
467                if h.one_way {
468                    opts.insert_bool("one-way", true);
469                }
470                let refs = h.refs.iter().cloned().map(Value::Str).collect();
471                let v = Value::Tuple(vec![
472                    Value::U32(h.version),
473                    opts.build(),
474                    Value::Array(refs),
475                ]);
476                (&HELLO, v)
477            }
478            Message::HelloReply(r) => {
479                check_limits(r.max_frame, r.max_have, r.parallel_uploads)?;
480                let mut opts = DictBuilder::new();
481                opts.insert_str("mode", &r.mode);
482                if let Some(id) = &r.collection_id {
483                    opts.insert_str("collection-id", id);
484                }
485                let encodings: Vec<String> =
486                    r.encodings.iter().map(|e| e.as_str().to_owned()).collect();
487                opts.insert("max-frame", Type::U32, Value::U32(r.max_frame))
488                    .insert("max-have", Type::U32, Value::U32(r.max_have))
489                    .insert_strv("encodings", &encodings)
490                    .insert(
491                        "parallel-uploads",
492                        Type::U32,
493                        Value::U32(r.parallel_uploads),
494                    );
495                let refs = r
496                    .refs
497                    .iter()
498                    .map(|s| Value::Tuple(vec![Value::Str(s.name.clone()), maybe_value(s.commit)]))
499                    .collect();
500                let v = Value::Tuple(vec![
501                    Value::U32(r.version),
502                    opts.build(),
503                    Value::Array(refs),
504                ]);
505                (&HELLO_REPLY, v)
506            }
507            Message::Have(names) => (&OBJECT_NAMES, object_names_value(names)?),
508            Message::HaveReply(r) => (&BYTES, Value::Bytes(r.bitmap.clone())),
509            Message::ObjectHeader(h) => {
510                check_header(&h.name, h.encoding)?;
511                let v = Value::Tuple(vec![
512                    Value::Byte(h.name.ty.as_u32() as u8),
513                    Value::Bytes(h.name.checksum.as_bytes().to_vec()),
514                    Value::Byte(h.encoding.as_u8()),
515                ]);
516                (&OBJECT_HEADER, v)
517            }
518            Message::ObjectsReply(r) => {
519                let v = Value::Tuple(vec![Value::U32(r.objects), Value::U64(r.payload_bytes)]);
520                (&OBJECTS_REPLY, v)
521            }
522            Message::CommitReply(outcomes) => {
523                let v = outcomes
524                    .iter()
525                    .map(|o| {
526                        Value::Tuple(vec![
527                            Value::Str(o.name.clone()),
528                            maybe_value(o.old),
529                            maybe_value(o.new),
530                        ])
531                    })
532                    .collect();
533                (&COMMIT_REPLY, Value::Array(v))
534            }
535            Message::Error(e) => {
536                check_error(e)?;
537                let mut detail = DictBuilder::new();
538                if !e.missing.is_empty() {
539                    detail.insert(
540                        "missing",
541                        OBJECT_NAMES.clone(),
542                        object_names_value(&e.missing)?,
543                    );
544                }
545                if let Some(state) = &e.current {
546                    detail.insert_str("ref", &state.name).insert(
547                        "current",
548                        MAYBE_CHECKSUM.clone(),
549                        maybe_value(state.commit),
550                    );
551                }
552                let v = Value::Tuple(vec![
553                    Value::Str(e.code.as_str().to_owned()),
554                    Value::Str(e.message.clone()),
555                    detail.build(),
556                ]);
557                (&ERROR, v)
558            }
559            Message::PullHello(h) => {
560                let mut opts = DictBuilder::new();
561                if let Some(agent) = &h.agent {
562                    opts.insert_str("agent", agent);
563                }
564                let v = Value::Tuple(vec![Value::U32(h.version), opts.build()]);
565                (&PULL_HELLO, v)
566            }
567            Message::PullHelloReply(r) => {
568                let v = Value::Tuple(vec![Value::U32(r.version), DictBuilder::new().build()]);
569                (&PULL_HELLO, v)
570            }
571            Message::Get(path) => (&Type::Str, Value::Str(path.clone())),
572            Message::GetReply(r) => {
573                check_get_reply(r)?;
574                let len = Value::Maybe(r.len.map(|n| Box::new(Value::U64(n))));
575                (&GET_REPLY, Value::Tuple(vec![Value::Bool(r.found), len]))
576            }
577            Message::ListRefs(r) => {
578                let mut opts = DictBuilder::new();
579                if let Some(collections) = &r.collections {
580                    opts.insert_strv("collections", collections);
581                }
582                let refs = r.refs.iter().cloned().map(Value::Str).collect();
583                (
584                    &LIST_REFS,
585                    Value::Tuple(vec![Value::Array(refs), opts.build()]),
586                )
587            }
588        };
589        to_bytes(ty, &value).map_err(encode_error)
590    }
591
592    /// Decodes the body of a message of `kind`.
593    ///
594    /// The decoder borrows strings and byte arrays from `body` and reads each
595    /// array one entry at a time. It allocates the decoded message. It checks
596    /// a dict value under a key that it does not know for normal form in
597    /// place, with no value tree, and then drops it. If a dict holds a key
598    /// two times, the first value counts, and the decoder checks each later
599    /// value for normal form alone. It checks each metadata entry of a
600    /// server commit in place and copies its bytes, with no value tree.
601    /// [`MAX_FRAME`](super::MAX_FRAME) states the measured peaks.
602    ///
603    /// # Errors
604    ///
605    /// [`Error::Protocol`] if the body is malformed:
606    ///
607    /// - the body is not in normal form for the type of `kind`
608    /// - an `ObjectsEnd` body is not empty, or an `Abort` body is not the one
609    ///   byte `0x00`
610    /// - a known dict key holds a value of the wrong type
611    /// - a `HelloReply` has no `mode`, `max-frame`, `max-have`, `encodings`,
612    ///   or `parallel-uploads` key, or a limit is out of range
613    /// - a checksum is not 32 bytes long
614    /// - an object type or an encoding byte is not allowed in the message
615    /// - a ref update of a `Commit` has an unknown expected state, or a state
616    ///   that does not match its expected commit
617    /// - the value under `server-commit` of a `Commit`, or under `timestamp`
618    ///   or `orphan` of its options, has the wrong type
619    /// - an attachment of a server commit has an empty name
620    /// - an `Error` message has an unknown code, has one of the keys `ref`
621    ///   and `current` alone, or has the code `ref-mismatch` with neither
622    /// - a `GetReply` whose `found` is `false` has a length
623    pub fn decode(kind: Kind, body: &[u8]) -> Result<Message> {
624        Ok(match kind {
625            Kind::ObjectsEnd => {
626                if !body.is_empty() {
627                    return Err(protocol("ObjectsEnd body is not empty"));
628                }
629                Message::ObjectsEnd
630            }
631            Kind::Abort => {
632                if body != [0] {
633                    return Err(protocol("Abort body is not the unit tuple"));
634                }
635                Message::Abort
636            }
637            Kind::Hello => {
638                let (version, opts, refs): (u32, Dict, ArrayIter<&str>) = parse_body(body)?;
639                let [agent, one_way] = dict(opts, ["agent", "one-way"])?;
640                let agent: Option<&str> = field(agent, "agent", &Type::Str)?;
641                let one_way = field(one_way, "one-way", &Type::Bool)?.unwrap_or(false);
642                Message::Hello(Hello {
643                    version,
644                    agent: agent.map(str::to_owned),
645                    refs: collect(refs, |r| Ok(r.to_owned()))?,
646                    one_way,
647                })
648            }
649            Kind::HelloReply => Message::HelloReply(decode_hello_reply(body)?),
650            Kind::Have => Message::Have(object_names(parse_body(body)?)?),
651            Kind::HaveReply => {
652                let bitmap: &[u8] = parse_body(body)?;
653                Message::HaveReply(HaveReply {
654                    bitmap: bitmap.to_vec(),
655                })
656            }
657            Kind::ObjectHeader => {
658                let (ty, sum, enc): (u8, &[u8], u8) = parse_body(body)?;
659                let name = object_name((ty, sum), header_type)?;
660                let encoding = Encoding::from_u8(enc)?;
661                check_header(&name, encoding)?;
662                Message::ObjectHeader(ObjectHeader { name, encoding })
663            }
664            Kind::ObjectsReply => {
665                let (objects, payload_bytes) = parse_body(body)?;
666                Message::ObjectsReply(ObjectsReply {
667                    objects,
668                    payload_bytes,
669                })
670            }
671            Kind::Commit => {
672                let (updates, opts): (ArrayIter<UpdateView>, Dict) = parse_body(body)?;
673                let updates = collect(updates, decode_update)?;
674                let [force, server_commit] = dict(opts, ["force", "server-commit"])?;
675                let force = field(force, "force", &Type::Bool)?.unwrap_or(false);
676                let server_commit = field(server_commit, "server-commit", &SERVER_COMMIT)?
677                    .map(decode_server_commit)
678                    .transpose()?
679                    .map(Box::new);
680                Message::Commit(CommitRequest {
681                    updates,
682                    force,
683                    server_commit,
684                })
685            }
686            Kind::CommitReply => {
687                let outcomes: ArrayIter<(&str, MaybeBytes, MaybeBytes)> = parse_body(body)?;
688                Message::CommitReply(collect(outcomes, |(name, old, new)| {
689                    Ok(RefOutcome {
690                        name: name.to_owned(),
691                        old: maybe_checksum(old)?,
692                        new: maybe_checksum(new)?,
693                    })
694                })?)
695            }
696            Kind::Error => Message::Error(decode_error(body)?),
697            Kind::PullHello => {
698                let (version, opts): (u32, Dict) = parse_body(body)?;
699                let [agent] = dict(opts, ["agent"])?;
700                let agent: Option<&str> = field(agent, "agent", &Type::Str)?;
701                Message::PullHello(PullHello {
702                    version,
703                    agent: agent.map(str::to_owned),
704                })
705            }
706            Kind::PullHelloReply => {
707                let (version, opts): (u32, Dict) = parse_body(body)?;
708                let [] = dict(opts, [])?;
709                Message::PullHelloReply(PullHelloReply { version })
710            }
711            Kind::Get => {
712                let path: &str = parse_body(body)?;
713                Message::Get(path.to_owned())
714            }
715            Kind::GetReply => {
716                let (found, len): (bool, MaybeU64) = parse_body(body)?;
717                let r = GetReply { found, len: len.0 };
718                check_get_reply(&r)?;
719                Message::GetReply(r)
720            }
721            Kind::ListRefs => {
722                let (refs, opts): (ArrayIter<&str>, Dict) = parse_body(body)?;
723                let [collections] = dict(opts, ["collections"])?;
724                let collections: Option<ArrayIter<&str>> =
725                    field(collections, "collections", &STRV)?;
726                Message::ListRefs(ListRefsRequest {
727                    refs: collect(refs, |e| Ok(e.to_owned()))?,
728                    collections: collections
729                        .map(|entries| collect(entries, |e| Ok(e.to_owned())))
730                        .transpose()?,
731                })
732            }
733        })
734    }
735}
736
737/// Checks the limits of a `HelloReply`.
738///
739/// `max-frame` must be in `MIN_FRAME_LIMIT..=MAX_FRAME_LIMIT`, and `max-have`
740/// and `parallel-uploads` must be at least 1. Otherwise the function returns
741/// `Error::Protocol`.
742fn check_limits(max_frame: u32, max_have: u32, parallel_uploads: u32) -> Result<()> {
743    if !(MIN_FRAME_LIMIT..=MAX_FRAME_LIMIT).contains(&max_frame) {
744        return Err(protocol(format!("max-frame {max_frame} is out of range")));
745    }
746    if max_have == 0 || parallel_uploads == 0 {
747        return Err(protocol("max-have and parallel-uploads must be at least 1"));
748    }
749    Ok(())
750}
751
752/// Checks that a `ref-mismatch` message carries the ref and its current
753/// state.
754fn check_error(e: &ErrorMessage) -> Result<()> {
755    if e.code == ErrorCode::RefMismatch && e.current.is_none() {
756        return Err(protocol("ref-mismatch lacks ref and current"));
757    }
758    Ok(())
759}
760
761fn decode_hello_reply(body: &[u8]) -> Result<HelloReply> {
762    let (version, opts, refs): (u32, Dict, ArrayIter<(&str, MaybeBytes)>) = parse_body(body)?;
763    let [
764        mode,
765        collection_id,
766        max_frame,
767        max_have,
768        encodings,
769        parallel_uploads,
770    ] = dict(
771        opts,
772        [
773            "mode",
774            "collection-id",
775            "max-frame",
776            "max-have",
777            "encodings",
778            "parallel-uploads",
779        ],
780    )?;
781    let mode: &str = required(mode, "mode", &Type::Str)?;
782    let collection_id: Option<&str> = field(collection_id, "collection-id", &Type::Str)?;
783    let max_frame = required(max_frame, "max-frame", &Type::U32)?;
784    let max_have = required(max_have, "max-have", &Type::U32)?;
785    let parallel_uploads = required(parallel_uploads, "parallel-uploads", &Type::U32)?;
786    check_limits(max_frame, max_have, parallel_uploads)?;
787    let names: ArrayIter<&str> = required(encodings, "encodings", &STRV)?;
788    let mut encodings = Vec::new();
789    for name in names {
790        encodings.extend(Encoding::from_name(name.map_err(malformed)?));
791    }
792    let refs = collect(refs, |(name, commit)| {
793        Ok(RefState {
794            name: name.to_owned(),
795            commit: maybe_checksum(commit)?,
796        })
797    })?;
798    Ok(HelloReply {
799        version,
800        mode: mode.to_owned(),
801        collection_id: collection_id.map(str::to_owned),
802        max_frame,
803        max_have,
804        encodings,
805        parallel_uploads,
806        refs,
807    })
808}
809
810/// A `(symaymay)` ref update, as the body holds it.
811type UpdateView<'a> = (&'a str, u8, MaybeBytes<'a>, MaybeBytes<'a>);
812
813fn decode_update((name, state, expected, new): UpdateView) -> Result<RefUpdate> {
814    let expected = match (state, maybe_checksum(expected)?) {
815        (0, None) => Expected::Absent,
816        (1, Some(c)) => Expected::Commit(c),
817        (2, None) => Expected::Any,
818        (s @ 0..=2, _) => {
819            return Err(protocol(format!(
820                "expected state {s} does not match its commit"
821            )));
822        }
823        (s, _) => return Err(protocol(format!("unknown expected state {s}"))),
824    };
825    Ok(RefUpdate {
826        name: name.to_owned(),
827        expected,
828        new: maybe_checksum(new)?,
829    })
830}
831
832/// Returns the [`Error::Protocol`] of an encode that fails.
833fn encode_error(e: ostrya_gvariant::Error) -> Error {
834    protocol(format!("encode: {e}"))
835}
836
837/// Returns the bytes of a `v` that holds `value` of the type `ty`.
838fn variant_bytes(ty: Type, value: Value) -> Result<Vec<u8>> {
839    to_bytes(&Type::Variant, &Value::variant(ty, value)).map_err(encode_error)
840}
841
842/// Returns the `a{sv}` entries of `entries`, each a key and the bytes of a
843/// `v`, in the form that the typed encoder writes.
844fn dict_entries<'a>(
845    entries: &'a [(&'static str, Vec<u8>)],
846) -> Vec<(&'static str, VariantSlice<'a>)> {
847    entries
848        .iter()
849        .map(|(key, value)| (*key, VariantSlice { inner: value }))
850        .collect()
851}
852
853/// Encodes the body of a `Commit` message.
854///
855/// The typed encoder writes the metadata of a server commit from its bytes,
856/// so the encode builds no value tree for it, and the depth of a metadata
857/// value inside the message does not count against the depth limit of the
858/// serializer.
859fn encode_commit(c: &CommitRequest) -> Result<Vec<u8>> {
860    encode_commit_parts(&c.updates, c.force, c.server_commit.as_deref())
861}
862
863/// Returns the length of the frame of a `Commit` that holds the server
864/// commit `sc` and no ref update: the kind byte and the body.
865///
866/// The bytes of each metadata entry of `sc` must be a `v` in normal form,
867/// else the call returns [`Error::Protocol`].
868pub(crate) fn server_commit_frame_len(sc: &ServerCommit) -> Result<u64> {
869    Ok(encode_commit_parts(&[], false, Some(sc))?.len() as u64 + 1)
870}
871
872/// Checks that a commit can hold each metadata value of the server commit
873/// `sc`.
874///
875/// A commit holds the depth limit of 128 levels of containers, counted from
876/// its metadata dict. In that dict, the `v` of each value is under two
877/// containers, the dict and its entry. A tuple with one member of variable
878/// size holds the bytes of the member and no framing, so the bytes of a `v`
879/// are also the bytes of `((v))`. The check reads the bytes as that type and
880/// builds no value tree.
881///
882/// Bytes that are not a `v` in normal form are [`Error::Protocol`], as the
883/// encode of the message gives. A `v` that a commit cannot hold is
884/// [`Error::InvalidInput`].
885pub(crate) fn check_server_commit_metadata(sc: &ServerCommit) -> Result<()> {
886    for (key, value) in &sc.metadata {
887        let Err(deep) = ostrya_gvariant::validate(&VALUE_IN_COMMIT, value) else {
888            continue;
889        };
890        if let Err(e) = ostrya_gvariant::validate(&Type::Variant, value) {
891            return Err(protocol(format!("encode: metadata entry '{key}': {e}")));
892        }
893        return Err(Error::InvalidInput(format!(
894            "a commit cannot hold the metadata value under '{key}': {deep}"
895        )));
896    }
897    Ok(())
898}
899
900/// Returns the length of the frame of the longest `CommitReply` to the
901/// server commit `sc`: the kind byte and the body.
902///
903/// The reply holds the branch with an old commit and each tag with no old
904/// commit, each with a new commit.
905pub(crate) fn server_commit_reply_frame_len(sc: &ServerCommit) -> Result<u64> {
906    let any_commit = Some(Checksum::from_bytes([0; 32]));
907    let refs = std::iter::once(RefOutcome {
908        name: sc.branch.clone(),
909        old: any_commit,
910        new: any_commit,
911    })
912    .chain(sc.tags.iter().map(|tag| RefOutcome {
913        name: tag.clone(),
914        old: None,
915        new: any_commit,
916    }))
917    .collect();
918    Ok(Message::CommitReply(refs).encode_body()?.len() as u64 + 1)
919}
920
921/// Encodes the body of a `Commit` message from its parts.
922fn encode_commit_parts(
923    updates: &[RefUpdate],
924    force: bool,
925    server_commit: Option<&ServerCommit>,
926) -> Result<Vec<u8>> {
927    let updates = updates
928        .iter()
929        .map(|u| {
930            let (state, expected) = match u.expected {
931                Expected::Absent => (0, None),
932                Expected::Commit(c) => (1, Some(c)),
933                Expected::Any => (2, None),
934            };
935            Value::Tuple(vec![
936                Value::Str(u.name.clone()),
937                Value::Byte(state),
938                maybe_value(expected),
939                maybe_value(u.new),
940            ])
941        })
942        .collect();
943    let updates = to_bytes(&UPDATES, &Value::Array(updates)).map_err(encode_error)?;
944    let mut opts = Vec::new();
945    if force {
946        opts.push(("force", variant_bytes(Type::Bool, Value::Bool(true))?));
947    }
948    if let Some(sc) = server_commit {
949        let mut value = server_commit_bytes(sc)?;
950        value.push(0);
951        value.extend_from_slice(SERVER_COMMIT_SIGNATURE.as_bytes());
952        opts.push(("server-commit", value));
953    }
954    encode_to_vec(&(updates.as_slice(), Slice(&dict_entries(&opts)))).map_err(encode_error)
955}
956
957/// Returns the bytes of the `server-commit` value of a `Commit`.
958///
959/// The bytes of each metadata entry must be a `v` in normal form, and each
960/// attachment must have a name that is not empty, else the call returns
961/// [`Error::Protocol`].
962fn server_commit_bytes(sc: &ServerCommit) -> Result<Vec<u8>> {
963    let tags: Vec<&str> = sc.tags.iter().map(String::as_str).collect();
964    let bind_refs: Vec<&str> = sc.bind_refs.iter().map(String::as_str).collect();
965    let metadata = sc
966        .metadata
967        .iter()
968        .map(|(key, value)| {
969            ostrya_gvariant::validate(&Type::Variant, value)
970                .map_err(|e| protocol(format!("encode: metadata entry '{key}': {e}")))?;
971            Ok((key.as_str(), VariantSlice { inner: value }))
972        })
973        .collect::<Result<Vec<_>>>()?;
974    if sc.related.iter().any(|(name, _)| name.is_empty()) {
975        return Err(protocol("encode: an attachment has an empty name"));
976    }
977    let mut opts = Vec::new();
978    if let Some(timestamp) = sc.timestamp {
979        opts.push((
980            "timestamp",
981            variant_bytes(Type::U64, Value::U64(timestamp))?,
982        ));
983    }
984    if sc.orphan {
985        opts.push(("orphan", variant_bytes(Type::Bool, Value::Bool(true))?));
986    }
987    encode_to_vec(&(
988        sc.branch.as_str(),
989        Slice(&tags),
990        Slice(&bind_refs),
991        (sc.root_dirtree, sc.root_dirmeta),
992        sc.subject.as_str(),
993        sc.body.as_str(),
994        Slice(&metadata),
995        Slice(&sc.related),
996        Slice(&dict_entries(&opts)),
997    ))
998    .map_err(encode_error)
999}
1000
1001/// A `(sasas(ayay)ssa{sv}a(say)a{sv})` server commit, as the body holds it.
1002type ServerCommitView<'a> = (
1003    &'a str,
1004    ArrayIter<'a, &'a str>,
1005    ArrayIter<'a, &'a str>,
1006    (&'a [u8], &'a [u8]),
1007    &'a str,
1008    &'a str,
1009    ArrayIter<'a, (&'a str, VariantSlice<'a>)>,
1010    ArrayIter<'a, (&'a str, &'a [u8])>,
1011    Dict<'a>,
1012);
1013
1014/// Decodes the `server-commit` value of a `Commit`.
1015///
1016/// The decoder checks that the bytes of each entry of the metadata dict are
1017/// a `v` in normal form, and keeps the bytes, in order, also a key that occurs
1018/// two times. It builds no value tree. It keeps the attachments in order, also
1019/// two entries with one name.
1020fn decode_server_commit(
1021    (branch, tags, bind_refs, (dirtree, dirmeta), subject, body, metadata, related, opts): ServerCommitView,
1022) -> Result<ServerCommit> {
1023    let [timestamp, orphan] = dict(opts, ["timestamp", "orphan"])?;
1024    let timestamp = field(timestamp, "timestamp", &Type::U64)?;
1025    let orphan = field(orphan, "orphan", &Type::Bool)?.unwrap_or(false);
1026    let metadata = collect(metadata, |(key, value)| {
1027        ostrya_gvariant::validate(&Type::Variant, value.inner).map_err(malformed)?;
1028        Ok((key.to_owned(), value.inner.to_vec()))
1029    })?;
1030    // The list grows with each entry. An element of a hostile body can take
1031    // a few bytes, so a capacity from the count of the elements can be many
1032    // times the size of the frame.
1033    let mut attachments = Vec::new();
1034    for entry in related {
1035        let (name, sum) = entry.map_err(malformed)?;
1036        if name.is_empty() {
1037            return Err(protocol(
1038                "an attachment of a server commit has an empty name",
1039            ));
1040        }
1041        attachments.push((name.to_owned(), checksum(sum)?));
1042    }
1043    Ok(ServerCommit {
1044        branch: branch.to_owned(),
1045        tags: collect(tags, |t| Ok(t.to_owned()))?,
1046        bind_refs: collect(bind_refs, |n| Ok(n.to_owned()))?,
1047        root_dirtree: checksum(dirtree)?,
1048        root_dirmeta: checksum(dirmeta)?,
1049        subject: subject.to_owned(),
1050        body: body.to_owned(),
1051        metadata,
1052        related: attachments,
1053        timestamp,
1054        orphan,
1055    })
1056}
1057
1058fn decode_error(body: &[u8]) -> Result<ErrorMessage> {
1059    let (name, message, detail): (&str, &str, Dict) = parse_body(body)?;
1060    let code =
1061        ErrorCode::from_name(name).ok_or_else(|| protocol(format!("unknown error code {name}")))?;
1062    let [missing, ref_name, current] = dict(detail, ["missing", "ref", "current"])?;
1063    let missing = match field(missing, "missing", &OBJECT_NAMES)? {
1064        Some(names) => object_names(names)?,
1065        None => Vec::new(),
1066    };
1067    let ref_name: Option<&str> = field(ref_name, "ref", &Type::Str)?;
1068    let current = match (ref_name, field(current, "current", &MAYBE_CHECKSUM)?) {
1069        (Some(name), Some(commit)) => Some(RefState {
1070            name: name.to_owned(),
1071            commit: maybe_checksum(commit)?,
1072        }),
1073        (None, None) => None,
1074        _ => return Err(protocol("Error carries one of ref and current alone")),
1075    };
1076    let e = ErrorMessage {
1077        code,
1078        message: message.to_owned(),
1079        missing,
1080        current,
1081    };
1082    check_error(&e)?;
1083    Ok(e)
1084}
1085
1086/// Checks that a reply whose `found` is `false` carries no length.
1087fn check_get_reply(r: &GetReply) -> Result<()> {
1088    if !r.found && r.len.is_some() {
1089        return Err(protocol("GetReply with found false carries a length"));
1090    }
1091    Ok(())
1092}
1093
1094/// Checks the object type of an `ObjectHeader`, and that `deflate` occurs
1095/// for a file object alone.
1096fn check_header(name: &ObjectName, encoding: Encoding) -> Result<()> {
1097    if !header_type(name.ty) {
1098        return Err(protocol(format!(
1099            "object type {} is not allowed in ObjectHeader",
1100            name.ty.as_u32()
1101        )));
1102    }
1103    if encoding == Encoding::Deflate && name.ty != ObjectType::File {
1104        return Err(protocol("deflate is allowed for a file object alone"));
1105    }
1106    Ok(())
1107}
1108
1109/// The length of an `ObjectHeader` frame: the 4 length bytes, the kind, and
1110/// the 35 bytes of the body.
1111pub(super) const OBJECT_HEADER_FRAME: usize = 40;
1112
1113/// Builds the frame of an `ObjectHeader` with no allocation.
1114///
1115/// The body `(yayy)` is the type, the 32 checksum bytes, the encoding, and
1116/// one framing offset: the end of the checksum array, 33. The bytes equal the
1117/// length, the kind, and the bytes of [`Message::encode_body`].
1118pub(super) fn object_header_frame(h: &ObjectHeader) -> Result<[u8; OBJECT_HEADER_FRAME]> {
1119    check_header(&h.name, h.encoding)?;
1120    let mut frame = [0u8; OBJECT_HEADER_FRAME];
1121    frame[..4].copy_from_slice(&(OBJECT_HEADER_FRAME as u32 - 4).to_be_bytes());
1122    frame[4] = Kind::ObjectHeader.as_u8();
1123    frame[5] = h.name.ty.as_u32() as u8;
1124    frame[6..38].copy_from_slice(h.name.checksum.as_bytes());
1125    frame[38] = h.encoding.as_u8();
1126    frame[39] = 33;
1127    Ok(frame)
1128}
1129
1130/// The length of the longest `GetReply` frame: the 4 length bytes, the
1131/// kind, and the 16 bytes of a body with a length.
1132pub(super) const GET_REPLY_FRAME: usize = 21;
1133
1134/// Builds the frame of a `GetReply` with no allocation.
1135///
1136/// The function also returns the number of bytes in use: 13 with no length,
1137/// 21 with one.
1138///
1139/// The body `(bmt)` is the found byte, 7 bytes of padding to the alignment
1140/// of the `mt`, and, if there is a length, its 8 bytes in little-endian
1141/// order. A fixed-size first member and a last member take no framing
1142/// offset. The bytes equal the length, the kind, and the bytes of
1143/// [`Message::encode_body`].
1144pub(super) fn get_reply_frame(r: &GetReply) -> Result<([u8; GET_REPLY_FRAME], usize)> {
1145    check_get_reply(r)?;
1146    let mut frame = [0u8; GET_REPLY_FRAME];
1147    let used = match r.len {
1148        Some(len) => {
1149            frame[13..].copy_from_slice(&len.to_le_bytes());
1150            GET_REPLY_FRAME
1151        }
1152        None => 13,
1153    };
1154    frame[..4].copy_from_slice(&(used as u32 - 4).to_be_bytes());
1155    frame[4] = Kind::GetReply.as_u8();
1156    frame[5] = u8::from(r.found);
1157    Ok((frame, used))
1158}
1159
1160fn object_names_value(names: &[ObjectName]) -> Result<Value> {
1161    if let Some(bad) = names.iter().find(|n| !have_type(n.ty)) {
1162        return Err(protocol(format!(
1163            "object type {} is not allowed in an object list",
1164            bad.ty.as_u32()
1165        )));
1166    }
1167    Ok(Value::Array(names.iter().map(object_name_value).collect()))
1168}
1169
1170fn object_names(names: ArrayIter<(u8, &[u8])>) -> Result<Vec<ObjectName>> {
1171    collect(names, |e| object_name(e, have_type))
1172}
1173
1174fn malformed(e: ostrya_gvariant::Error) -> Error {
1175    protocol(format!("malformed body: {e}"))
1176}
1177
1178fn parse_body<'a, T: GvDecode<'a>>(body: &'a [u8]) -> Result<T> {
1179    T::decode(body).map_err(malformed)
1180}
1181
1182/// Decodes every entry of `items` and maps it with `f`.
1183///
1184/// A first pass counts the entries, so the function allocates the result
1185/// once, at its final size.
1186fn collect<'a, E: GvDecode<'a> + Copy, T>(
1187    items: ArrayIter<'a, E>,
1188    mut f: impl FnMut(E) -> Result<T>,
1189) -> Result<Vec<T>> {
1190    let mut out = Vec::with_capacity(items.count());
1191    for e in items {
1192        out.push(f(e.map_err(malformed)?)?);
1193    }
1194    Ok(out)
1195}
1196
1197fn maybe_checksum(m: MaybeBytes) -> Result<Option<Checksum>> {
1198    m.0.map(checksum).transpose()
1199}
1200
1201/// A `may` in the body: no bytes for `None`, or the bytes of the array and a
1202/// zero byte.
1203#[derive(Clone, Copy)]
1204struct MaybeBytes<'a>(Option<&'a [u8]>);
1205
1206impl GvType for MaybeBytes<'_> {
1207    const ALIGNMENT: usize = 1;
1208    const FIXED_SIZE: Option<usize> = None;
1209}
1210
1211impl<'a> GvDecode<'a> for MaybeBytes<'a> {
1212    fn decode(data: &'a [u8]) -> ostrya_gvariant::Result<Self> {
1213        match data.split_last() {
1214            None => Ok(MaybeBytes(None)),
1215            Some((0, rest)) => Ok(MaybeBytes(Some(rest))),
1216            Some(_) => Err(ostrya_gvariant::Error::NotNormal(
1217                "maybe lacks its terminating zero byte",
1218            )),
1219        }
1220    }
1221}
1222
1223/// An `mt` in the body: no bytes for `None`, or the 8 bytes of the `t`.
1224///
1225/// A maybe of a fixed-size type has no terminating zero byte.
1226struct MaybeU64(Option<u64>);
1227
1228impl GvType for MaybeU64 {
1229    const ALIGNMENT: usize = 8;
1230    const FIXED_SIZE: Option<usize> = None;
1231}
1232
1233impl<'a> GvDecode<'a> for MaybeU64 {
1234    fn decode(data: &'a [u8]) -> ostrya_gvariant::Result<Self> {
1235        match data.len() {
1236            0 => Ok(MaybeU64(None)),
1237            8 => u64::decode(data).map(|n| MaybeU64(Some(n))),
1238            _ => Err(ostrya_gvariant::Error::NotNormal(
1239                "maybe of a u64 is not 0 or 8 bytes",
1240            )),
1241        }
1242    }
1243}
1244
1245/// A `v` in the body: the type of the child and the child bytes, not yet
1246/// decoded.
1247struct RawVariant<'a> {
1248    ty: Type,
1249    child: &'a [u8],
1250}
1251
1252impl GvType for RawVariant<'_> {
1253    const ALIGNMENT: usize = 8;
1254    const FIXED_SIZE: Option<usize> = None;
1255}
1256
1257impl<'a> GvDecode<'a> for RawVariant<'a> {
1258    fn decode(data: &'a [u8]) -> ostrya_gvariant::Result<Self> {
1259        let not_normal = ostrya_gvariant::Error::NotNormal;
1260        let sep = data
1261            .iter()
1262            .rposition(|&b| b == 0)
1263            .ok_or(not_normal("variant lacks a type separator"))?;
1264        let signature = std::str::from_utf8(&data[sep + 1..])
1265            .map_err(|_| not_normal("variant type signature is not UTF-8"))?;
1266        let ty =
1267            Type::parse(signature).map_err(|_| not_normal("variant type signature is invalid"))?;
1268        Ok(RawVariant {
1269            ty,
1270            child: &data[..sep],
1271        })
1272    }
1273}
1274
1275/// An `a{sv}` in the body.
1276type Dict<'a> = ArrayIter<'a, (&'a str, RawVariant<'a>)>;
1277
1278/// A `v` in the body as its bytes, not yet checked.
1279#[derive(Clone, Copy)]
1280struct VariantSlice<'a> {
1281    inner: &'a [u8],
1282}
1283
1284impl GvType for VariantSlice<'_> {
1285    const ALIGNMENT: usize = 8;
1286    const FIXED_SIZE: Option<usize> = None;
1287}
1288
1289impl<'a> GvDecode<'a> for VariantSlice<'a> {
1290    fn decode(data: &'a [u8]) -> ostrya_gvariant::Result<Self> {
1291        Ok(VariantSlice { inner: data })
1292    }
1293}
1294
1295impl GvEncode for VariantSlice<'_> {
1296    fn encode(&self, out: &mut Vec<u8>) -> ostrya_gvariant::Result<()> {
1297        out.extend_from_slice(self.inner);
1298        Ok(())
1299    }
1300}
1301
1302/// Returns the first entry of each of `keys` in `entries`.
1303///
1304/// The function checks every other entry for normal form and then drops it.
1305/// The caller decodes each returned entry with [`field`].
1306fn dict<'a, const N: usize>(
1307    entries: Dict<'a>,
1308    keys: [&str; N],
1309) -> Result<[Option<RawVariant<'a>>; N]> {
1310    let mut found = [const { None }; N];
1311    for entry in entries {
1312        let (key, value) = entry.map_err(malformed)?;
1313        match keys.iter().position(|k| *k == key) {
1314            Some(i) if found[i].is_none() => found[i] = Some(value),
1315            _ => {
1316                ostrya_gvariant::validate(&value.ty, value.child).map_err(malformed)?;
1317            }
1318        }
1319    }
1320    Ok(found)
1321}
1322
1323/// Returns the value of the dict entry `key`.
1324///
1325/// If the key is absent, the function returns `Ok(None)`. If the variant
1326/// does not hold `ty`, it returns `Error::Protocol`.
1327fn field<'a, T: GvDecode<'a>>(
1328    entry: Option<RawVariant<'a>>,
1329    key: &str,
1330    ty: &Type,
1331) -> Result<Option<T>> {
1332    let Some(v) = entry else {
1333        return Ok(None);
1334    };
1335    if v.ty != *ty {
1336        return Err(protocol(format!("key {key} has the wrong type")));
1337    }
1338    T::decode(v.child).map(Some).map_err(malformed)
1339}
1340
1341/// Returns the value of the `HelloReply` key `key`, which must be present.
1342///
1343/// If the key is absent, the function returns `Error::Protocol`.
1344fn required<'a, T: GvDecode<'a>>(entry: Option<RawVariant<'a>>, key: &str, ty: &Type) -> Result<T> {
1345    field(entry, key, ty)?.ok_or_else(|| protocol(format!("HelloReply lacks {key}")))
1346}