ostrya_remote/proto/mod.rs
1//! The wire format of the push and the pull, and its codec.
2//!
3//! Each wire code is the [`Error`] variant of the same name, for example
4//! [`Error::Protocol`] for the code `protocol`. [`ErrorCode`] names the
5//! codes.
6//!
7//! `docs/format-reference.md` of the repository specifies the wire format,
8//! and this module implements it. The sections below link to each part of the
9//! specification.
10//!
11//! # Frames
12//!
13//! [Wire conventions] specifies the byte orders. [Frame layout] and
14//! [Frame limits] specify the frame and its limits. [Messages] specifies the
15//! message kinds with their bodies, and [Error codes] specifies the wire
16//! codes.
17//!
18//! A client writes frames up to the limit that the server announces. It reads
19//! frames up to a limit of its own, because the reader allocates each frame
20//! body in full.
21//!
22//! The codec reads and writes every kind. A session refuses a kind of the
23//! other protocol with [`Error::Protocol`].
24//!
25//! # Object stream
26//!
27//! [Chunks and the abandon marker] specifies the chunks of an object that
28//! follow an `ObjectHeader`, and [Object streams] states the rules of the
29//! server. [`ABANDON`] is the chunk length of the abandon marker.
30//!
31//! # One-way stream
32//!
33//! [The one-way stream] specifies the stream that carries a push in one
34//! direction.
35//!
36//! # Pull
37//!
38//! [The pull session over a stream] specifies `PullHello`, `Get`, and
39//! `ListRefs`. [`PULL_PROTOCOL_VERSION`] is the highest pull version that this
40//! crate speaks. A [`GetReply`] answers each `Get` and each `ListRefs`.
41//!
42//! # Ref listing
43//!
44//! [The ref listing] specifies the body of a listing. A `ListRefs`
45//! ([`ListRefsRequest`]) holds two lists of entries of a
46//! [`RefSelector`](ostrya_core::RefSelector), which parses them: the entries
47//! of the local refs, and the optional entries of the collection refs.
48//! [`MAX_REF_PATTERNS`], [`MAX_REF_ENTRY_PARTS`], [`MAX_REF_ENTRY_LEN`], and
49//! [`MAX_REF_LISTING`] are the limits of a request and of a listing.
50//!
51//! # Codec
52//!
53//! [`FrameReader`] and [`FrameWriter`] implement the frames, the object
54//! stream, and the pull bodies over the `futures-io` traits, so the codec
55//! needs no async runtime. Both enter the body state after an `ObjectHeader`
56//! and after a `GetReply` whose `found` is `true`. One set of methods reads
57//! and writes the bytes of both body kinds.
58//!
59//! The bytes pass through a buffer of the caller in bounded pieces, so no
60//! call holds a whole object. [`ObjectBody`] presents the bytes of one body
61//! as an `AsyncRead`.
62//!
63//! [`ErrorCode`]: crate::ErrorCode
64//! [Wire conventions]: https://github.com/growler/ostrya/blob/main/docs/format-reference.md#wire-conventions
65//! [Frame layout]: https://github.com/growler/ostrya/blob/main/docs/format-reference.md#frame-layout
66//! [Frame limits]: https://github.com/growler/ostrya/blob/main/docs/format-reference.md#frame-limits
67//! [Messages]: https://github.com/growler/ostrya/blob/main/docs/format-reference.md#messages
68//! [Error codes]: https://github.com/growler/ostrya/blob/main/docs/format-reference.md#error-codes
69//! [Chunks and the abandon marker]: https://github.com/growler/ostrya/blob/main/docs/format-reference.md#chunks-and-the-abandon-marker
70//! [Object streams]: https://github.com/growler/ostrya/blob/main/docs/format-reference.md#object-streams
71//! [The one-way stream]: https://github.com/growler/ostrya/blob/main/docs/format-reference.md#the-one-way-stream
72//! [The pull session over a stream]: https://github.com/growler/ostrya/blob/main/docs/format-reference.md#the-pull-session-over-a-stream
73//! [The ref listing]: https://github.com/growler/ostrya/blob/main/docs/format-reference.md#the-ref-listing
74
75mod frame;
76mod message;
77
78pub use frame::{FrameReader, FrameWriter, ObjectBody, ObjectRead};
79pub(crate) use frame::{Step, encode_frame};
80pub use message::{
81 CommitRequest, ErrorMessage, GetReply, HaveReply, Hello, HelloReply, ListRefsRequest, Message,
82 ObjectHeader, ObjectsReply, PullHello, PullHelloReply, ServerCommit,
83};
84pub(crate) use message::{
85 check_server_commit_metadata, server_commit_frame_len, server_commit_reply_frame_len,
86};
87
88use ostrya_core::{Checksum, ObjectName, ObjectType};
89use ostrya_gvariant::Value;
90
91use crate::error::{Error, Result};
92
93/// The push protocol version that this crate speaks.
94pub const PROTOCOL_VERSION: u32 = 1;
95
96/// The highest pull protocol version that this crate speaks.
97///
98/// It is the version of `PullHello` and `PullHelloReply`. It is separate from
99/// [`PROTOCOL_VERSION`], and each version changes on its own.
100pub const PULL_PROTOCOL_VERSION: u32 = 1;
101
102/// The lowest frame limit: 1 MiB.
103///
104/// This value is:
105///
106/// - the frame limit before the server announces one
107/// - the lowest limit that a server can announce
108/// - the limit of a stream that carries no announcement
109pub const MIN_FRAME_LIMIT: u32 = 1 << 20;
110
111/// The `max-frame` value that an ostrya server announces: 1 MiB.
112///
113/// Object bytes travel as chunks, so a frame carries only metadata messages.
114/// The largest bounded message is a `Have` of [`MAX_HAVE`] entries, with a
115/// frame length of 606,209 bytes. `Hello`, `HelloReply`, `Commit`, and the
116/// `Error` message hold lists with no count limit. Only the frame limit
117/// bounds them.
118///
119/// A chunk can be as long as the limit, so the framing costs 4 bytes for
120/// each MiB of object data.
121///
122/// # Memory
123///
124/// The reader allocates a frame body in full. The decoder then keeps the body
125/// and the decoded message together. On 1 MiB frames, the measured peak is:
126///
127/// - 2 times the frame for a `Have`
128/// - 12 times the frame for a `HelloReply` of refs with empty names
129/// - 13 times the frame for a `Commit` of ref updates with empty names
130/// - 1 time the frame for a `Hello` whose one unknown key holds an `ab` of
131/// 1 MiB, or an array of one-byte values in 8 or 64 levels of one-member
132/// tuples
133/// - 2 times the frame for a `Commit` whose server commit holds one metadata
134/// entry with an `ab` of 1 MiB, or with an array of one-byte values in 8 or
135/// 64 levels of one-member tuples
136///
137/// The decoder checks a dict value under an unknown key, and a value under a
138/// repeated key, in place with no value tree, and then drops it. The decoder
139/// checks each metadata entry of a server commit in place and keeps a copy
140/// of its bytes, with no value tree. The peak grows in proportion to the
141/// limit.
142pub const MAX_FRAME: u32 = 1 << 20;
143
144/// The largest ref listing: 128 MiB.
145///
146/// A ref listing is the summary of the refs that the ref patterns of one
147/// request select. An ostrya server builds a listing for each request. The
148/// build refuses a larger listing with [`Error::LimitExceeded`]. Over a
149/// stream, the server sends this error as the code `limit-exceeded`. Over
150/// HTTP, the server answers with the status 500.
151///
152/// [`PullSession::fetch_refs`](crate::session::PullSession::fetch_refs) reads
153/// a listing of at most this many bytes.
154pub const MAX_REF_LISTING: u64 = 128 * 1024 * 1024;
155
156/// The most entries in one request of a ref listing: 256.
157///
158/// Positive and negative entries count together, and the entries of the
159/// local refs and of the collection refs count together. A server refuses a
160/// request with more entries. It counts an entry that the request holds two
161/// times as two entries. Over HTTP, each `pattern=VALUE` pair and each
162/// `collection=VALUE` pair of the query is one entry.
163///
164/// Before it counts, a client removes each exact duplicate of an entry of the
165/// same kind in the same list. The
166/// [ref patterns](crate::session::PullSession#ref-patterns) of a pull give
167/// the client rules.
168pub const MAX_REF_PATTERNS: usize = 256;
169
170/// The most parts in one entry of a ref listing request: 256.
171///
172/// A part is one element of the entry split at each `/`, the first and the
173/// last included. For example, `a` has 1 part, and `a/b` has 2 parts. The
174/// leading `!` of a negative entry adds no part.
175///
176/// A server refuses an entry with more parts before it parses the entry. The
177/// cost of a match is the product of the part counts of the pattern and the
178/// name, so the limit bounds the work of one entry.
179pub const MAX_REF_ENTRY_PARTS: usize = 256;
180
181/// The most bytes in one entry of a ref listing request: 4,096.
182///
183/// The leading `!` of a negative entry counts as one byte. A server refuses a
184/// longer entry before it parses the entry.
185pub const MAX_REF_ENTRY_LEN: usize = 4096;
186
187/// The `max-have` value that an ostrya server announces: 16,384 entries.
188///
189/// A `Have` entry is 33 bytes plus a 4-byte offset. A `Have` of 16,384
190/// entries has a frame length of 606,209 bytes, which fits in [`MAX_FRAME`].
191/// A `Have` of 32,768 entries does not fit. A full `HaveReply` of 16,384
192/// entries is 2,048 bytes.
193pub const MAX_HAVE: u32 = 16_384;
194
195/// The chunk length that abandons an object or a pull body.
196pub const ABANDON: u32 = 0xFFFF_FFFF;
197
198/// The highest valid frame limit.
199///
200/// It is one less than [`ABANDON`], so a chunk length that the limit allows
201/// never equals the abandon marker.
202pub const MAX_FRAME_LIMIT: u32 = 0xFFFF_FFFE;
203
204/// A message kind, the byte after the frame length.
205///
206/// A later protocol version can add kinds.
207#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
208#[repr(u8)]
209#[non_exhaustive]
210pub enum Kind {
211 /// The `Hello` message, from the client to the server.
212 Hello = 1,
213 /// The `HelloReply` message, from the server to the client.
214 HelloReply = 2,
215 /// The `Have` message, from the client to the server.
216 Have = 3,
217 /// The `HaveReply` message, from the server to the client.
218 HaveReply = 4,
219 /// The `ObjectHeader` message, from the client to the server.
220 ///
221 /// The chunks of the object follow it.
222 ObjectHeader = 5,
223 /// The `ObjectsEnd` message, from the client to the server.
224 ///
225 /// It closes the object stream.
226 ObjectsEnd = 6,
227 /// The `ObjectsReply` message, from the server to the client.
228 ObjectsReply = 7,
229 /// The `Commit` message, from the client to the server.
230 Commit = 8,
231 /// The `CommitReply` message, from the server to the client.
232 CommitReply = 9,
233 /// The `Error` message, from the server to the client.
234 ///
235 /// The push and the pull both use it.
236 Error = 10,
237 /// The `Abort` message, from the client to the server.
238 Abort = 11,
239 /// The `PullHello` message, from a pull client to the server.
240 PullHello = 12,
241 /// The `PullHelloReply` message, from the server to a pull client.
242 PullHelloReply = 13,
243 /// The `Get` message, from a pull client to the server.
244 Get = 14,
245 /// The `GetReply` message, from the server to a pull client.
246 ///
247 /// It answers a `Get` or a `ListRefs`. A body follows a reply whose
248 /// `found` is `true`.
249 GetReply = 15,
250 /// The `ListRefs` message, from a pull client to the server.
251 ///
252 /// The server answers it with one `GetReply`.
253 ListRefs = 16,
254}
255
256impl Kind {
257 /// Returns the kind of a kind byte.
258 ///
259 /// # Errors
260 ///
261 /// - [`Error::Protocol`] if the byte is not a kind.
262 pub fn from_u8(byte: u8) -> Result<Kind> {
263 Ok(match byte {
264 1 => Kind::Hello,
265 2 => Kind::HelloReply,
266 3 => Kind::Have,
267 4 => Kind::HaveReply,
268 5 => Kind::ObjectHeader,
269 6 => Kind::ObjectsEnd,
270 7 => Kind::ObjectsReply,
271 8 => Kind::Commit,
272 9 => Kind::CommitReply,
273 10 => Kind::Error,
274 11 => Kind::Abort,
275 12 => Kind::PullHello,
276 13 => Kind::PullHelloReply,
277 14 => Kind::Get,
278 15 => Kind::GetReply,
279 16 => Kind::ListRefs,
280 _ => return Err(protocol(format!("unknown message kind {byte}"))),
281 })
282 }
283
284 /// Returns the kind byte.
285 pub fn as_u8(self) -> u8 {
286 self as u8
287 }
288}
289
290/// The encoding of an object in the object stream.
291#[derive(Debug, Clone, Copy, PartialEq, Eq)]
292pub enum Encoding {
293 /// The uncompressed object bytes.
294 ///
295 /// For a content object, the bytes are the framed file header and the
296 /// payload.
297 Raw,
298 /// A content object in the compressed form of an archive repository.
299 Deflate,
300}
301
302impl Encoding {
303 /// Returns the wire byte: 0 for `raw`, 1 for `deflate`.
304 pub fn as_u8(self) -> u8 {
305 match self {
306 Encoding::Raw => 0,
307 Encoding::Deflate => 1,
308 }
309 }
310
311 /// Returns the encoding of a wire byte.
312 ///
313 /// # Errors
314 ///
315 /// - [`Error::Protocol`] if the byte is not 0 or 1.
316 pub fn from_u8(byte: u8) -> Result<Encoding> {
317 match byte {
318 0 => Ok(Encoding::Raw),
319 1 => Ok(Encoding::Deflate),
320 _ => Err(protocol(format!("unknown encoding {byte}"))),
321 }
322 }
323
324 /// Returns the name in the `encodings` list of `HelloReply`.
325 pub fn as_str(self) -> &'static str {
326 match self {
327 Encoding::Raw => "raw",
328 Encoding::Deflate => "deflate",
329 }
330 }
331
332 /// Returns the encoding of a name, or `None` if the name is not an
333 /// encoding.
334 pub fn from_name(name: &str) -> Option<Encoding> {
335 match name {
336 "raw" => Some(Encoding::Raw),
337 "deflate" => Some(Encoding::Deflate),
338 _ => None,
339 }
340 }
341}
342
343/// The state of a ref as the server reads it.
344#[derive(Debug, Clone, PartialEq, Eq)]
345pub struct RefState {
346 /// The ref name, as the `Hello` holds it.
347 pub name: String,
348 /// The commit of the ref, or `None` if the ref is absent.
349 pub commit: Option<Checksum>,
350}
351
352/// The state that a ref update expects the ref to be in.
353#[derive(Debug, Clone, Copy, PartialEq, Eq)]
354pub enum Expected {
355 /// The ref is absent (wire state 0).
356 Absent,
357 /// The ref points at this commit (wire state 1).
358 Commit(Checksum),
359 /// The ref is in any state (wire state 2).
360 Any,
361}
362
363/// One ref update of a `Commit` message.
364#[derive(Debug, Clone, PartialEq, Eq)]
365pub struct RefUpdate {
366 /// The ref name, as the `Hello` holds it: `NAME` or `@ID:NAME`, and in a
367 /// one-way stream also `REMOTE:NAME`.
368 pub name: String,
369 /// The state that the ref must be in before the write.
370 pub expected: Expected,
371 /// The new commit, or `None` to delete the ref.
372 pub new: Option<Checksum>,
373}
374
375/// The result of one ref update in a `CommitReply` message.
376#[derive(Debug, Clone, PartialEq, Eq)]
377pub struct RefOutcome {
378 /// The ref name, as the client sent it.
379 pub name: String,
380 /// The commit before the write, or `None` if the ref was absent.
381 pub old: Option<Checksum>,
382 /// The commit after the write, or `None` if the ref is now absent.
383 pub new: Option<Checksum>,
384}
385
386pub(crate) fn protocol(msg: impl Into<String>) -> Error {
387 Error::Protocol(msg.into())
388}
389
390/// Returns a checksum from an `ay` of 32 bytes.
391fn checksum(bytes: &[u8]) -> Result<Checksum> {
392 Checksum::from_ay(bytes).map_err(|_| protocol("checksum is not 32 bytes"))
393}
394
395fn checksum_value(c: &Checksum) -> Value {
396 Value::Bytes(c.as_bytes().to_vec())
397}
398
399fn maybe_value(c: Option<Checksum>) -> Value {
400 Value::Maybe(c.map(|c| Box::new(checksum_value(&c))))
401}
402
403/// Returns an object name from a `(y, ay)` pair whose type `allowed`
404/// accepts.
405fn object_name((byte, sum): (u8, &[u8]), allowed: fn(ObjectType) -> bool) -> Result<ObjectName> {
406 let ty = ObjectType::from_u32(u32::from(byte))
407 .ok()
408 .filter(|t| allowed(*t))
409 .ok_or_else(|| protocol(format!("object type {byte} is not allowed here")))?;
410 Ok(ObjectName::new(checksum(sum)?, ty))
411}
412
413fn object_name_value(name: &ObjectName) -> Value {
414 Value::Tuple(vec![
415 Value::Byte(name.ty.as_u32() as u8),
416 checksum_value(&name.checksum),
417 ])
418}
419
420/// The length of one `Have` entry in a body of 65,536 bytes or more: the
421/// type byte, the 32 bytes of the checksum, and an offset of 4 bytes. A
422/// shorter body has offsets of 1 or 2 bytes.
423const HAVE_ENTRY_LEN: u32 = 37;
424
425/// Returns the most entries of a `Have` whose frame fits in `limit`.
426///
427/// The frame length counts the kind byte and the body. Fewer entries make a
428/// shorter frame.
429pub(crate) fn have_entries_within(limit: u32) -> u32 {
430 (limit - 1) / HAVE_ENTRY_LEN
431}
432
433/// Returns `true` if a `Have` entry or a `missing` entry can name the type.
434///
435/// These are the types 1 to 4.
436pub(crate) fn have_type(ty: ObjectType) -> bool {
437 matches!(
438 ty,
439 ObjectType::File | ObjectType::DirTree | ObjectType::DirMeta | ObjectType::Commit
440 )
441}
442
443/// Returns `true` if an `ObjectHeader` can name the type.
444///
445/// These are the types 1 to 4 and 6.
446fn header_type(ty: ObjectType) -> bool {
447 have_type(ty) || ty == ObjectType::CommitMeta
448}