Skip to main content

flow_tool_protocol/
lib.rs

1//! The Tool process protocol's frames (`abi.md`, *The Tool process
2//! protocol*), which both sides of the exchange speak: the host, a toolkit,
3//! and any process that implements Tools by hand. What a frame carries is in
4//! the value encoding (`flow-abi`), including the answers the dispatch
5//! seam passes, [`Outcome`] and [`Ack`], which this crate only frames.
6//!
7//! A **frame** is a number, its length in bytes, then that many bytes: one
8//! [`Message`], declared once with [`flow_abi::wire!`], so its codec and
9//! its constructor numbers come from the declaration. The reply socket, where
10//! a client outside the host replies to a call, uses the same framing and the
11//! same messages, and each [`Route`] admits only its own kinds
12//! ([`Kind::on`]).
13//!
14//! Values cross in the value encoding at their declared types, so a frame
15//! holds them as a [`Rest`], the bytes after the message's head: the side
16//! that knows the types reads them ([`flow_abi::read_value`]). What describes
17//! them, a `describe` answer's and a generic call's type descriptions,
18//! crosses in the value encoding too ([`flow_abi::TypeSpec`]).
19//!
20//! [`read_frame`] reads one frame from a stream within a size limit. A frame
21//! past the limit is not kept: its head is, its kind and, for a message that
22//! begins with `run` and `call` ([`Kind::names_call`]), those two ids,
23//! so that an answer too large to admit still names the call it answers
24//! ([`Message::reply_head`]); the rest is read and dropped. [`Frames`] reads
25//! the same frames from bytes as they arrive, for a reader that must not
26//! block on a stream.
27
28#![cfg_attr(all(coverage, test), feature(coverage_attribute))]
29
30use std::io::{self, Read, Write};
31
32use flow_abi::description::{CallTypes, Identity};
33use flow_abi::primitives::{NotAUint, Reader, read_uint, wide, write_uint};
34use flow_abi::wire::{Ctor, Layout, Parts, Rest, Wire, WireForm};
35use flow_abi::{
36    Ack, DATA_VERSION, DataVersion, DecodeError, Outcome, ResultType, TypeSpec, Untyped, Versioned,
37    wire,
38};
39use flow_span::{CallRef, RunId};
40use flow_value::Instant;
41
42wire! {
43    /// One message of the protocol, on either route: what one frame's body
44    /// holds. Its number is the frame's kind.
45    #[derive(Clone, PartialEq, Eq, Debug)]
46    pub enum Message {
47        /// `describe`, host or client to its peer: its data version and the
48        /// largest encoded answer, in bytes, it admits; a client sends 0.
49        Describe {
50            /// The sender's data version.
51            version: DataVersion,
52            /// The largest encoded answer it admits, in bytes.
53            reply_limit: u64,
54        } = 1,
55        /// The answer to `describe`, implementation to host: its data version
56        /// and, in that version, each declaration it serves ([`served`]).
57        Described(Versioned) = 2,
58        /// `call`, host to implementation.
59        Call(Call) = 3,
60        /// `reply`, implementation or client to host.
61        Reply(Reply) = 4,
62        /// `cancel`, host to implementation: a request to stop work on a
63        /// call, which proves nothing.
64        Cancel {
65            /// The host's run id.
66            run: RunId,
67            /// The call's history id.
68            call: CallRef,
69        } = 5,
70        /// `no_answer`, implementation to host: it has no answer to a call.
71        /// The call stays open, and the run stops.
72        NoAnswer {
73            /// The host's run id, as the call carried it.
74            run: RunId,
75            /// The call's history id, as the call carried it.
76            call: CallRef,
77            /// Why, as the implementation wrote it.
78            reason: String,
79        } = 6,
80        /// `ack`, host to implementation or client: what became of a `reply`.
81        Ack {
82            /// The host's run id, as the reply carried it.
83            run: RunId,
84            /// The call's history id, as the reply carried it.
85            call: CallRef,
86            /// Whether the answer was recorded.
87            result: Ack,
88        } = 7,
89        /// `hold`, implementation to host: not an answer, but the promise to
90        /// answer the call later. With `retry_at`, the host asks again then.
91        Hold {
92            /// The host's run id, as the call carried it.
93            run: RunId,
94            /// The call's history id, as the call carried it.
95            call: CallRef,
96            /// When to ask again; `None` waits for a reply.
97            retry_at: Option<Instant>,
98        } = 8,
99        /// `log`, implementation to host: one line for a run's log.
100        Log(Log) = 9,
101        /// `type`, client to host: which type a reply to a call is encoded
102        /// at.
103        Type {
104            /// The run's id.
105            run: RunId,
106            /// The call's history id.
107            call: CallRef,
108        } = 10,
109        /// The answer to `type`, host to client.
110        Typed {
111            /// The run's id, as the `type` carried it.
112            run: RunId,
113            /// The call's history id, as the `type` carried it.
114            call: CallRef,
115            /// The call's result type, or why the host has none to give.
116            answer: Result<ResultType, Untyped>,
117        } = 11,
118    }
119
120    /// Which message a frame holds: its kind.
121    pub enum Kind;
122}
123
124/// Where a frame travels: between the host and a Tool process, or on the
125/// reply socket, where a client outside the host replies to a call
126/// (`abi.md`, *Replies from outside a call*).
127#[derive(Clone, Copy, PartialEq, Eq, Debug)]
128pub enum Route {
129    /// The Tool process protocol.
130    Process,
131    /// The reply socket.
132    Socket,
133}
134
135impl Kind {
136    /// Whether a message of this kind travels on `route`: the reply socket
137    /// shares `describe`, `reply` and `ack` with the Tool process protocol
138    /// and has `type` and its answer alone.
139    pub fn on(self, route: Route) -> bool {
140        match self {
141            Kind::Describe | Kind::Reply | Kind::Ack => true,
142            Kind::Described
143            | Kind::Call
144            | Kind::Cancel
145            | Kind::NoAnswer
146            | Kind::Hold
147            | Kind::Log => route == Route::Process,
148            Kind::Type | Kind::Typed => route == Route::Socket,
149        }
150    }
151
152    /// Whether a message of this kind begins with its `run` and `call`:
153    /// what a frame too large to keep keeps of it. Read from the
154    /// declaration, a payload that is one record read as its fields.
155    pub fn names_call(self) -> bool {
156        matches!(
157            leading(self.ctor()).as_slice(),
158            [WireForm::RunId, WireForm::CallRef, ..]
159        )
160    }
161
162    /// The kind of the message `head`, a frame's first bytes, holds.
163    pub fn of_head(head: &[u8]) -> Option<Kind> {
164        Kind::of(Reader::new(head).uint().ok()?)
165    }
166}
167
168/// The forms `ctor`'s payload begins with: its fields, or those of the one
169/// record it carries.
170fn leading(ctor: &Ctor) -> Vec<WireForm> {
171    match ctor.parts {
172        Parts::Empty => Vec::new(),
173        Parts::Named(fields) => fields.iter().map(|field| field.form).collect(),
174        Parts::Positional(&[WireForm::Declared(shape)]) => match shape().layout {
175            Layout::Record(fields) => fields.iter().map(|field| field.form).collect(),
176            Layout::Enum(_) | Layout::Newtype(_) | Layout::Host => Vec::new(),
177        },
178        Parts::Positional(forms) => forms.to_vec(),
179    }
180}
181
182wire! {
183    /// A `call` frame's fields.
184    #[derive(Clone, PartialEq, Eq, Debug)]
185    pub struct Call {
186        /// The host's run id.
187        pub run: RunId,
188        /// The call's history id, as history writes it.
189        pub call: CallRef,
190        /// The declaration's place in the answer to `describe`, from 0.
191        pub tool: u64,
192        /// Whether the call is generic, with its views, and whether it
193        /// withdraws a held call.
194        pub flags: Flags,
195        /// The arguments: each parameter's value in declaration order at its
196        /// (concrete) type.
197        pub args: Rest,
198    }
199}
200
201wire! {
202    /// A `call`'s flags: bit 0 says the call is generic and carries its
203    /// views, a generic call's `CallTypes`; bit 1 says it withdraws a held
204    /// call that was closed (`abi.md`, *Withdrawing a held call*).
205    #[derive(Clone, PartialEq, Eq, Debug)]
206    pub enum Flags {
207        /// Neither.
208        Plain,
209        /// A generic call, and its views.
210        Generic(CallTypes),
211        /// A withdrawal.
212        Cancelled,
213        /// A withdrawal of a generic call, and its views.
214        GenericCancelled(CallTypes),
215    }
216}
217
218impl Call {
219    /// The call to declaration `tool` of `run` named `call`, with
220    /// `generic`'s views for a generic one, and `args`; it withdraws
221    /// nothing.
222    pub fn new(
223        run: RunId,
224        call: CallRef,
225        tool: u64,
226        generic: Option<&CallTypes>,
227        args: &[u8],
228    ) -> Call {
229        Call {
230            run,
231            call,
232            tool,
233            flags: generic.map_or(Flags::Plain, |types| Flags::Generic(types.clone())),
234            args: Rest(args.to_vec()),
235        }
236    }
237
238    /// The same call, withdrawing the held call it names.
239    #[must_use]
240    pub fn withdrawing(self) -> Call {
241        let flags = match self.flags {
242            Flags::Plain | Flags::Cancelled => Flags::Cancelled,
243            Flags::Generic(types) | Flags::GenericCancelled(types) => {
244                Flags::GenericCancelled(types)
245            }
246        };
247        Call { flags, ..self }
248    }
249
250    /// A generic call's views.
251    pub fn views(&self) -> Option<&CallTypes> {
252        match &self.flags {
253            Flags::Plain | Flags::Cancelled => None,
254            Flags::Generic(types) | Flags::GenericCancelled(types) => Some(types),
255        }
256    }
257
258    /// Whether it withdraws a held call that was closed.
259    pub fn cancelled(&self) -> bool {
260        matches!(self.flags, Flags::Cancelled | Flags::GenericCancelled(_))
261    }
262}
263
264wire! {
265    /// A `reply` frame's fields.
266    #[derive(Clone, PartialEq, Eq, Debug)]
267    pub struct Reply {
268        /// The host's run id, as the call carried it.
269        pub run: RunId,
270        /// The call's history id, as the call carried it.
271        pub call: CallRef,
272        /// What became of the call.
273        pub outcome: Outcome,
274    }
275}
276
277wire! {
278    /// A `log` frame's fields.
279    #[derive(Clone, PartialEq, Eq, Debug)]
280    pub struct Log {
281        /// The run the line names, if any.
282        pub run: Option<RunId>,
283        /// The call the line names, if any.
284        pub call: Option<CallRef>,
285        /// How severe it is.
286        pub level: Level,
287        /// The line.
288        pub message: String,
289    }
290}
291
292wire! {
293    /// A log line's level.
294    #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
295    pub enum Level {
296        /// Detail for whoever debugs the Tool.
297        Debug,
298        /// Ordinary progress.
299        Info,
300        /// Something that may need attention.
301        Warning,
302        /// A failure.
303        Error,
304    }
305}
306
307flow_span::spelled! {
308    impl Level {
309        /// Its name: `debug`, `info`, `warning` or `error`.
310        pub fn as_str(self) -> &'static str;
311        /// The level named `text`.
312        pub fn named(&str);
313        [Level::Debug] = "debug",
314        [Level::Info] = "info",
315        [Level::Warning] = "warning",
316        [Level::Error] = "error",
317    }
318}
319
320impl Level {
321    /// Every level, least severe first.
322    pub const ALL: &'static [Level] = &[Level::Debug, Level::Info, Level::Warning, Level::Error];
323}
324
325impl Log {
326    /// The line a `log` frame too large to keep still holds: `head`, its
327    /// first bytes, read with the message cut to the whole characters the
328    /// head holds. `None` when the head does not hold the line's `run`,
329    /// `call` and `level`.
330    pub fn from_head(head: &[u8]) -> Option<Log> {
331        let mut reader = Reader::new(head);
332        if Kind::of(reader.uint().ok()?) != Some(Kind::Log) {
333            return None;
334        }
335        let run = Option::<RunId>::read(&mut reader).ok()?;
336        let call = Option::<CallRef>::read(&mut reader).ok()?;
337        let level = Level::read(&mut reader).ok()?;
338        let length = reader.count().ok()?;
339        let kept = reader.take(length.min(reader.remaining())).ok()?;
340        let message = match std::str::from_utf8(kept) {
341            Ok(text) => text,
342            Err(error) => std::str::from_utf8(&kept[..error.valid_up_to()]).ok()?,
343        };
344        Some(Log {
345            run,
346            call,
347            level,
348            message: message.to_owned(),
349        })
350    }
351
352    /// Cuts the message to at most `limit` bytes, at a character's
353    /// boundary; whether it cut anything.
354    pub fn cut(&mut self, limit: usize) -> bool {
355        if self.message.len() <= limit {
356            return false;
357        }
358        let mut at = limit;
359        while !self.message.is_char_boundary(at) {
360            at -= 1;
361        }
362        self.message.truncate(at);
363        true
364    }
365}
366
367/// What an answer to `describe` serves.
368#[derive(Clone, PartialEq, Eq, Debug)]
369pub enum Served {
370    /// Each declaration's identity and type description, in the order a
371    /// `call` numbers them by.
372    Tools(Vec<(Identity, TypeSpec)>),
373    /// Nothing this build reads: the implementation speaks a data version
374    /// whose major differs from this one's.
375    Elsewhere(DataVersion),
376}
377
378/// What `described`, an answer to `describe`, serves: its declarations
379/// when its data version speaks with this build's.
380///
381/// # Errors
382///
383/// A [`DecodeError`] when the declarations do not read, naming the
384/// declaration whose description is invalid.
385pub fn served(described: &Versioned) -> Result<Served, DecodeError> {
386    if !DATA_VERSION.speaks_with(&described.version) {
387        return Ok(Served::Elsewhere(described.version));
388    }
389    let mut reader = Reader::new(&described.rest.0);
390    let count = reader.count()?;
391    let mut tools = Vec::with_capacity(count.min(reader.remaining()));
392    for _ in 0..count {
393        let identity = Identity::read(&mut reader)?;
394        let spec = TypeSpec::read_from(&mut reader).map_err(|error| DecodeError {
395            problem: format!(
396                "names {}, whose description is invalid: {}",
397                identity.name, error.problem
398            ),
399            ..error
400        })?;
401        tools.push((identity, spec));
402    }
403    if !reader.is_empty() {
404        return Err(DecodeError {
405            path: flow_abi::Place::default(),
406            problem: format!("has {} bytes left over", reader.remaining()),
407            kind: flow_abi::DecodeErrorKind::Mismatch,
408        });
409    }
410    Ok(Served::Tools(tools))
411}
412
413impl Message {
414    /// The answer to `describe` serving `tools`, in this build's data
415    /// version.
416    #[expect(
417        clippy::needless_pass_by_value,
418        reason = "a list's codec is Vec's, so a slice would be copied into one to be written"
419    )]
420    pub fn described(tools: Vec<(Identity, TypeSpec)>) -> Message {
421        Message::Described(Versioned {
422            version: DATA_VERSION,
423            rest: Rest(tools.bytes()),
424        })
425    }
426
427    /// The frame's body: the message.
428    pub fn body(&self) -> Vec<u8> {
429        self.bytes()
430    }
431
432    /// The whole frame: the body's length, then the body.
433    pub fn frame(&self) -> Vec<u8> {
434        let body = self.body();
435        let mut out = Vec::with_capacity(body.len() + 10);
436        write_uint(&mut out, wide(body.len()));
437        out.extend_from_slice(&body);
438        out
439    }
440
441    /// The message `body` holds on `route`, refusing any other bytes: a
442    /// kind the route does not carry, a field that does not read, and bytes
443    /// left over. A `reply` or a `hold` whose `run` and `call` read is
444    /// malformed for its call ([`Malformed::Reply`]).
445    ///
446    /// # Errors
447    ///
448    /// [`Malformed`], saying which of those it met.
449    pub fn parse(route: Route, body: &[u8]) -> Result<Message, Malformed> {
450        if body.is_empty() {
451            return Err(Malformed::Frame("a frame is empty".to_owned()));
452        }
453        if let Some(kind) = Kind::of_head(body).filter(|kind| !kind.on(route)) {
454            return Err(Malformed::Frame(format!(
455                "a frame of kind {}, {kind:?}, is no message of the {}",
456                kind.number(),
457                match route {
458                    Route::Process => "Tool process protocol",
459                    Route::Socket => "reply socket",
460                }
461            )));
462        }
463        Message::decode(body).map_err(|error| match Message::reply_head(body) {
464            Some((run, call)) => Malformed::Reply {
465                run,
466                call,
467                problem: format!("a frame {}", error.problem),
468            },
469            None => Malformed::Frame(format!("a frame {}", error.problem)),
470        })
471    }
472
473    /// The `run` and `call` of a frame whose first bytes are `head`, when it
474    /// begins as a `reply` or a `hold` that names them: what a frame too
475    /// large to keep still says.
476    pub fn reply_head(head: &[u8]) -> Option<(RunId, CallRef)> {
477        Message::head(head, &[Kind::Reply, Kind::Hold])
478    }
479
480    /// The `run` and `call` of a frame whose first bytes are `head`, when its
481    /// kind is one of `kinds` and both ids read whole and are ids.
482    pub fn head(head: &[u8], kinds: &[Kind]) -> Option<(RunId, CallRef)> {
483        let mut reader = Reader::new(head);
484        let kind = Kind::of(reader.uint().ok()?)?;
485        if !kinds.contains(&kind) || !kind.names_call() {
486            return None;
487        }
488        Some((
489            RunId::read(&mut reader).ok()?,
490            CallRef::read(&mut reader).ok()?,
491        ))
492    }
493}
494
495/// Why a frame's body is not a message.
496#[derive(Clone, PartialEq, Eq, Debug)]
497pub enum Malformed {
498    /// It begins as a `reply` or a `hold` whose `run` and `call` were read
499    /// as ids, and the rest is not one: that call has no answer.
500    Reply {
501        /// The run it names.
502        run: RunId,
503        /// The call it names.
504        call: CallRef,
505        /// What is wrong with the rest.
506        problem: String,
507    },
508    /// Anything else: from an implementation, this ends the exchange.
509    Frame(String),
510}
511
512impl std::fmt::Display for Malformed {
513    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
514        match self {
515            Malformed::Reply { problem, .. } | Malformed::Frame(problem) => f.write_str(problem),
516        }
517    }
518}
519
520/// Frames read from bytes as they arrive, one by one as [`read_frame`] reads
521/// them from a stream. It holds at most one frame's bytes within the limit,
522/// or a head's past it: the rest of a frame past the limit is dropped as it
523/// arrives, and the frame is read once the last of it has.
524#[derive(Debug)]
525pub struct Frames {
526    limit: usize,
527    /// Bytes taken and not yet read as a frame.
528    held: Vec<u8>,
529    /// A frame past the limit whose head was read, and how many more of
530    /// its bytes are to be dropped before it is.
531    dropping: Option<(Frame, u64)>,
532}
533
534impl Frames {
535    /// Frames with bodies of at most `limit` bytes kept.
536    pub fn new(limit: usize) -> Frames {
537        Frames {
538            limit,
539            held: Vec::new(),
540            dropping: None,
541        }
542    }
543
544    /// Takes `bytes`, the next the stream gave.
545    pub fn feed(&mut self, bytes: &[u8]) {
546        self.held.extend_from_slice(bytes);
547    }
548
549    /// The next frame the bytes taken complete; `None` until they do.
550    ///
551    /// # Errors
552    ///
553    /// An [`io::ErrorKind::InvalidData`] when a frame's length is not a
554    /// number: nothing after it can be read as a frame.
555    pub fn read(&mut self) -> io::Result<Option<Frame>> {
556        if let Some((frame, left)) = self.dropping.take() {
557            let dropped =
558                usize::try_from(left).map_or(self.held.len(), |left| left.min(self.held.len()));
559            self.held.drain(..dropped);
560            let left = left - wide(dropped);
561            if left > 0 {
562                self.dropping = Some((frame, left));
563                return Ok(None);
564            }
565            return Ok(Some(frame));
566        }
567        let mut rest = self.held.as_slice();
568        let length = match read_length(&mut rest) {
569            Ok(Some(length)) => length,
570            Ok(None) => return Ok(None),
571            Err(error) if error.kind() == io::ErrorKind::UnexpectedEof => return Ok(None),
572            Err(error) => return Err(error),
573        };
574        let at = self.held.len() - rest.len();
575        if length <= wide(self.limit) {
576            let length =
577                usize::try_from(length).map_err(|_| io::Error::from(io::ErrorKind::InvalidData))?;
578            if rest.len() < length {
579                return Ok(None);
580            }
581            let body = self.held[at..at + length].to_vec();
582            self.held.drain(..at + length);
583            return Ok(Some(Frame::Body(body)));
584        }
585        let bound = self.limit.max(HEAD);
586        let needed = usize::try_from(length).map_or(bound, |length| length.min(bound));
587        if rest.len() < needed {
588            return Ok(None);
589        }
590        let head = read_head(&mut &rest[..needed], length, bound)?;
591        self.held.drain(..at + head.len());
592        let left = length - wide(head.len());
593        self.dropping = Some((Frame::TooLarge { length, head }, left));
594        self.read()
595    }
596
597    /// Whether a frame has begun that the bytes taken do not complete.
598    pub fn partial(&self) -> bool {
599        !self.held.is_empty() || self.dropping.is_some()
600    }
601}
602
603/// The fewest bytes of a frame past the size limit [`read_frame`] will keep
604/// for its head, however small the limit: a head is kept up to this or the
605/// limit, whichever is larger.
606pub const HEAD: usize = 4096;
607
608/// One frame as [`read_frame`] read it.
609#[derive(Clone, PartialEq, Eq, Debug)]
610pub enum Frame {
611    /// A frame within the limit: its body.
612    Body(Vec<u8>),
613    /// A frame past the limit: its length and its head, its first byte
614    /// then, for a message that begins with them ([`Kind::names_call`]), its `run`
615    /// and `call` ids, and for a `log` as many of its bytes, as fit in the larger of the
616    /// limit and [`HEAD`] ([`Log::from_head`]). The rest was read and
617    /// dropped.
618    TooLarge {
619        /// The body's length.
620        length: u64,
621        /// Its first bytes.
622        head: Vec<u8>,
623    },
624}
625
626/// Reads the next frame from `input`, keeping a body of at most `limit`
627/// bytes. `None` when the input ends before a frame begins; an
628/// [`io::ErrorKind::UnexpectedEof`] when it ends inside one, and an
629/// [`io::ErrorKind::InvalidData`] when the length is not a number.
630///
631/// # Errors
632///
633/// Those two, and any error reading `input`.
634pub fn read_frame(input: &mut impl Read, limit: usize) -> io::Result<Option<Frame>> {
635    let Some(length) = read_length(input)? else {
636        return Ok(None);
637    };
638    if length > wide(limit) {
639        let head = read_head(input, length, limit.max(HEAD))?;
640        let rest = length - wide(head.len());
641        let dropped = io::copy(&mut input.take(rest), &mut io::sink())?;
642        if dropped < rest {
643            return Err(io::ErrorKind::UnexpectedEof.into());
644        }
645        return Ok(Some(Frame::TooLarge { length, head }));
646    }
647    // No longer than `limit`, so it fits a `usize`.
648    let length =
649        usize::try_from(length).map_err(|_| io::Error::from(io::ErrorKind::InvalidData))?;
650    let mut body = vec![0; length];
651    input.read_exact(&mut body)?;
652    Ok(Some(Frame::Body(body)))
653}
654
655/// The head of a frame of `length` bytes past the limit, at most `bound`
656/// bytes: its first byte, then, when that begins a message whose first
657/// fields are `run` and `call` ([`Kind::names_call`]), the run id's 16
658/// bytes and the call id's numbers, as far as they fit; a number that does
659/// not read ends the head there. The call id is read a number at a time, so
660/// a long one is kept as long as it fits, rather than cut at a fixed size.
661fn read_head(input: &mut impl Read, length: u64, bound: usize) -> io::Result<Vec<u8>> {
662    let mut head = Vec::new();
663    let cap = usize::try_from(length).map_or(bound, |length| length.min(bound));
664    let kind = next_byte(input)?;
665    head.push(kind);
666    let kind = Kind::of(u64::from(kind));
667    if kind == Some(Kind::Log) {
668        // A log line too long is kept cut, so its head is as much of it as
669        // fits.
670        let at = head.len();
671        head.resize(cap, 0);
672        input.read_exact(&mut head[at..])?;
673        return Ok(head);
674    }
675    if !kind.is_some_and(Kind::names_call) {
676        return Ok(head);
677    }
678    let at = head.len();
679    head.resize(cap.min(at + 16), 0);
680    input.read_exact(&mut head[at..])?;
681    if head.len() < at + 16 {
682        return Ok(head);
683    }
684    // The call id: its segment, its task's count of counters, those
685    // counters and the call's counter, each a number read a byte at a time
686    // as far as the head has room.
687    let mut number = || {
688        read_uint(
689            || {
690                if head.len() == cap {
691                    return Err(HeadEnds::Here);
692                }
693                let byte = next_byte(input).map_err(HeadEnds::Failed)?;
694                head.push(byte);
695                Ok(byte)
696            },
697            |_| HeadEnds::Here,
698        )
699    };
700    let mut read = || -> Result<(), HeadEnds> {
701        number()?;
702        let counters = number()?;
703        for _ in 0..=counters {
704            number()?;
705        }
706        Ok(())
707    };
708    match read() {
709        Ok(()) | Err(HeadEnds::Here) => Ok(head),
710        Err(HeadEnds::Failed(error)) => Err(error),
711    }
712}
713
714/// Why a head stops before the ids it would keep.
715enum HeadEnds {
716    /// It has no room left, or a number does not read: the head is
717    /// what was read.
718    Here,
719    /// Reading the frame failed.
720    Failed(io::Error),
721}
722
723/// A frame's length: a number of at most 64 bits in its fewest bytes.
724fn read_length(input: &mut impl Read) -> io::Result<Option<u64>> {
725    let Some(first) = read_byte(input)? else {
726        return Ok(None);
727    };
728    let mut first = Some(first);
729    read_uint(
730        || match first.take() {
731            Some(byte) => Ok(byte),
732            None => next_byte(input),
733        },
734        |not: NotAUint| {
735            io::Error::new(
736                io::ErrorKind::InvalidData,
737                format!("a frame's length is {not}"),
738            )
739        },
740    )
741    .map(Some)
742}
743
744/// The next byte of a frame begun on `input`, which must not end there.
745fn next_byte(input: &mut impl Read) -> io::Result<u8> {
746    read_byte(input)?.ok_or_else(|| io::ErrorKind::UnexpectedEof.into())
747}
748
749/// The next byte of `input`, or `None` where it ends.
750fn read_byte(input: &mut impl Read) -> io::Result<Option<u8>> {
751    let mut byte = [0u8];
752    loop {
753        match input.read(&mut byte) {
754            Ok(0) => return Ok(None),
755            Ok(_) => return Ok(Some(byte[0])),
756            Err(error) if error.kind() == io::ErrorKind::Interrupted => {}
757            Err(error) => return Err(error),
758        }
759    }
760}
761
762/// Writes `message` to `output` as one frame and flushes it.
763///
764/// # Errors
765///
766/// Any error writing to or flushing `output`.
767pub fn write_frame(output: &mut impl Write, message: &Message) -> io::Result<()> {
768    output.write_all(&message.frame())?;
769    output.flush()
770}