crates/edge/proto/src/body.rs 65.8 KiB 2263 lines Raw
1 //! The twenty-four bodies of wire 2, one per frame kind. Wire 1 uses the first sixteen.2 //!3 //! The grammar is `spec/protocol.cddl`. A body is a CBOR map with the short4 //! keys of that grammar. The numeric `u32`/`u64` choice is not a wire rule:5 //! every CBOR uint decodes into the field and a value that does not fit is6 //! `BodyError::Type`.7 //!8 //! A body never carries media. `part` and `artifact` carry either inline bytes9 //! or a descriptor. Nothing here knows a path, a hash, or a blob.10 11 use std::collections::BTreeMap;12 use std::fmt;13 14 use crate::cbor::{self, CborError, Value};15 use crate::frame::Kind;16 17 /// The version range in `hello`.18 #[derive(Clone, Copy, PartialEq, Eq, Debug)]19 pub struct VersionRange {20     pub min: u32,21     pub max: u32,22 }23 24 /// Which side of the socket a peer is.25 #[derive(Clone, Copy, PartialEq, Eq, Debug)]26 pub enum Role {27     Call,28     Serve,29 }30 31 /// What a part or a channel carries.32 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]33 pub enum PartKind {34     Text,35     Image,36     Audio,37     Video,38     Tokens,39     Json,40 }41 42 /// The granularity at which a cancellation stops work.43 ///44 /// A foreign engine may only notice a cancel between requests, so the core45 /// cannot assume that every plugin stops at a token boundary.46 #[derive(Clone, PartialEq, Eq, Debug, Default)]47 pub enum Cancel {48     #[default]49     /// The engine stops inside a token stream.50     Token,51     /// The engine stops at a frame boundary.52     Frame,53     /// The engine only stops between whole requests.54     Request,55     /// A word outside the vocabulary, kept so the catalog can name it.56     Unknown(String),57 }58 59 // The name `from_str` is the wire's, and an unknown word must survive into a60 // `Unknown` value instead of becoming a `Result`, so the trait does not fit.61 #[allow(clippy::should_implement_trait)]62 impl Cancel {63     /// The wire spelling of this granularity.64     pub fn as_str(&self) -> &str {65         match self {66             Cancel::Token => "token",67             Cancel::Frame => "frame",68             Cancel::Request => "request",69             Cancel::Unknown(word) => word.as_str(),70         }71     }72 73     /// Reads a wire spelling. An unknown word is kept, not guessed, because74     /// the catalog must refuse it by name.75     pub fn from_str(word: &str) -> Cancel {76         match word {77             "token" => Cancel::Token,78             "frame" => Cancel::Frame,79             "request" => Cancel::Request,80             other => Cancel::Unknown(other.to_string()),81         }82     }83 }84 85 /// Who strips the stop strings from the output.86 #[derive(Clone, PartialEq, Eq, Debug, Default)]87 pub enum Stops {88     #[default]89     /// The plugin runs the stop strings through its output.90     Plugin,91     /// The engine under the plugin strips them before the wire.92     Native,93     /// Nothing strips them, so the caller must.94     None,95     /// A word outside the vocabulary, kept so the catalog can name it.96     Unknown(String),97 }98 99 // See `Cancel::from_str` for why this is not `std::str::FromStr`.100 #[allow(clippy::should_implement_trait)]101 impl Stops {102     /// The wire spelling of this stop owner.103     pub fn as_str(&self) -> &str {104         match self {105             Stops::Plugin => "plugin",106             Stops::Native => "native",107             Stops::None => "none",108             Stops::Unknown(word) => word.as_str(),109         }110     }111 112     /// Reads a wire spelling. An unknown word is kept, not guessed, because113     /// the catalog must refuse it by name.114     pub fn from_str(word: &str) -> Stops {115         match word {116             "plugin" => Stops::Plugin,117             "native" => Stops::Native,118             "none" => Stops::None,119             other => Stops::Unknown(other.to_string()),120         }121     }122 }123 124 /// Whether the engine queues work inside itself.125 ///126 /// An internal queue makes our credit advisory: the engine accepts frames that127 /// it will not run yet.128 #[derive(Clone, PartialEq, Eq, Debug, Default)]129 pub enum Queue {130     #[default]131     /// The engine starts work as the credit arrives.132     None,133     /// The engine queues inside itself, so credit no longer bounds the work.134     Internal,135     /// A word outside the vocabulary, kept so the catalog can name it.136     Unknown(String),137 }138 139 // See `Cancel::from_str` for why this is not `std::str::FromStr`.140 #[allow(clippy::should_implement_trait)]141 impl Queue {142     /// The wire spelling of this queue mode.143     pub fn as_str(&self) -> &str {144         match self {145             Queue::None => "none",146             Queue::Internal => "internal",147             Queue::Unknown(word) => word.as_str(),148         }149     }150 151     /// Reads a wire spelling. An unknown word is kept, not guessed, because152     /// the catalog must refuse it by name.153     pub fn from_str(word: &str) -> Queue {154         match word {155             "none" => Queue::None,156             "internal" => Queue::Internal,157             other => Queue::Unknown(other.to_string()),158         }159     }160 }161 162 /// The end of a job.163 #[derive(Clone, Copy, PartialEq, Eq, Debug)]164 pub enum Outcome {165     Completed,166     Failed,167     Cancelled,168     Expired,169 }170 171 /// The code in `fatal` and `reject`.172 #[derive(Clone, Copy, PartialEq, Eq, Debug)]173 pub enum ErrorCode {174     Version,175     Frame,176     Stream,177     Size,178     Credit,179     Busy,180     UnknownModel,181     Capability,182     Part,183     Dependency,184     Timeout,185     Cancelled,186     Internal,187 }188 189 impl std::fmt::Display for ErrorCode {190     /// The wire spelling. It is also the word in the refusal table of spec.md191     /// section 12, so a log line and a reply cannot disagree.192     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {193         f.write_str(match self {194             ErrorCode::Version => "version",195             ErrorCode::Frame => "frame",196             ErrorCode::Stream => "stream",197             ErrorCode::Size => "size",198             ErrorCode::Credit => "credit",199             ErrorCode::Busy => "busy",200             ErrorCode::UnknownModel => "unknown_model",201             ErrorCode::Capability => "capability",202             ErrorCode::Part => "part",203             ErrorCode::Dependency => "dependency",204             ErrorCode::Timeout => "timeout",205             ErrorCode::Cancelled => "cancelled",206             ErrorCode::Internal => "internal",207         })208     }209 }210 211 /// `hello` — caller to server, stream 0.212 #[derive(Clone, PartialEq, Eq, Debug)]213 pub struct Hello {214     pub v: VersionRange,215     pub role: Role,216     pub id: String,217 }218 219 /// `welcome` — server to caller, stream 0.220 #[derive(Clone, Copy, PartialEq, Eq, Debug)]221 pub struct Welcome {222     pub v: u32,223     pub max_inflight: u16,224 }225 226 /// The capability limit that names the context window in tokens.227 pub const CONTEXT_LIMIT: &str = "context";228 229 /// The capability limit that names the KV-cache bytes of one token.230 ///231 /// A model that does not declare it has no KV cache to reserve, which is the232 /// honest number for a mock or a model whose engine keeps the cache outside233 /// the ledger's knowledge.234 pub const KV_BYTES_PER_TOKEN_LIMIT: &str = "kv_bytes_per_token";235 236 /// One model that a peer can serve.237 #[derive(Clone, PartialEq, Eq, Debug)]238 pub struct Model {239     pub serve: String,240     /// `None` is `null` on the wire. It names a model that this row renames.241     pub alias_of: Option<String>,242     /// The size of the weights that a grant hands over. Zero is a model that243     /// has no weights, such as the mock.244     pub weights_bytes: u64,245     /// The load time measured at the last load. Zero means never loaded.246     pub load_ms: u32,247     pub capabilities: BTreeMap<String, Capability>,248 }249 250 impl Model {251     /// The bytes that one load of this model reserves.252     ///253     /// The weight bytes are the file that the grant hands over. The KV cache is254     /// the largest one that any capability can ask for: a capability declares255     /// its context and its bytes per token, and one model loads one cache.256     /// Decision D5.257     pub fn reserved_bytes(&self) -> u64 {258         let kv = self259             .capabilities260             .values()261             .map(|capability| {262                 let context = capability.limits.get(CONTEXT_LIMIT).copied().unwrap_or(0);263                 let per_token = capability264                     .limits265                     .get(KV_BYTES_PER_TOKEN_LIMIT)266                     .copied()267                     .unwrap_or(0);268                 context.saturating_mul(per_token)269             })270             .max()271             .unwrap_or(0);272         self.weights_bytes.saturating_add(kv)273     }274 }275 276 /// One capability of one model.277 #[derive(Clone, PartialEq, Eq, Debug)]278 pub struct Capability {279     pub vocab: String,280     pub parts: Vec<PartKind>,281     pub channels: Vec<String>,282     pub limits: BTreeMap<String, u64>,283     /// How finely a cancel stops this engine.284     pub cancel: Cancel,285     /// Who strips stop strings for this engine.286     pub stops: Stops,287     /// Whether the engine queues inside itself.288     pub queue: Queue,289 }290 291 /// The machine that a peer runs on.292 #[derive(Clone, PartialEq, Eq, Debug)]293 pub struct Target {294     pub id: String,295     pub backend: String,296     pub arch: Vec<String>,297     pub devices: u32,298     /// Declared bytes are MiB here. The ledger uses bytes.299     pub vram_mb: Vec<u32>,300 }301 302 /// A foreign runtime that a binding was built against.303 ///304 /// A hand-built shared library is absent from `Cargo.lock`, so the catalogue305 /// names the runtime and the core can refuse a version skew instead of living306 /// with a wrong answer.307 #[derive(Clone, PartialEq, Eq, Debug)]308 pub struct Runtime {309     pub name: String,310     pub version: String,311 }312 313 /// How a plugin's KV codec may be rolled back.314 #[derive(Clone, Copy, PartialEq, Eq, Debug)]315 pub enum CacheStateKind {316     PrefixTruncatable,317     CheckpointExact,318 }319 320 /// The Wire 2 cache declaration in `catalogue`.321 #[derive(Clone, PartialEq, Eq, Debug)]322 pub struct CacheSpec {323     pub codec_version: u64,324     pub slots: u32,325     pub state_kind: CacheStateKind,326     pub max_entry_bytes: u64,327     pub local_ram_bytes: u64,328     pub supports_save: bool,329     pub supports_restore: bool,330     pub supports_erase: bool,331 }332 333 /// `catalogue` — server to caller, stream 0. The only manifest the core reads.334 #[derive(Clone, PartialEq, Eq, Debug)]335 pub struct Catalogue {336     pub target: Target,337     pub models: Vec<Model>,338     /// The foreign runtime that the plugin binds, or `None` for pure Rust.339     pub runtime: Option<Runtime>,340     /// The Wire 2 cache declaration, or `None` for a plugin without a cache.341     pub cache: Option<CacheSpec>,342 }343 344 /// One file that the core grants to a plugin.345 #[derive(Clone, PartialEq, Eq, Debug)]346 pub struct Dependency {347     pub role: String,348     pub fd: u32,349     pub len: u64,350     pub path: String,351 }352 353 /// `grant` — caller to server, stream 0.354 #[derive(Clone, PartialEq, Eq, Debug)]355 pub struct Grant {356     pub deps: Vec<Dependency>,357 }358 359 /// `ready` — server to caller, stream 0. The load time is measured.360 #[derive(Clone, Copy, PartialEq, Eq, Debug)]361 pub struct Ready {362     pub load_ms: u32,363     /// The bundle's half of the Wire 2 composite fingerprint.364     pub cache_fingerprint: Option<[u8; 32]>,365 }366 367 /// `window` — caller to server, any stream. The value is absolute.368 #[derive(Clone, Copy, PartialEq, Eq, Debug)]369 pub struct Window {370     pub credit: u64,371 }372 373 /// `ping` and `pong` share this body.374 #[derive(Clone, Copy, PartialEq, Eq, Debug)]375 pub struct Tick {376     pub t: u64,377 }378 379 /// `bye` — caller to server, stream 0.380 #[derive(Clone, PartialEq, Eq, Debug)]381 pub struct Bye {382     pub reason: String,383 }384 385 /// `fatal` and `reject` share this body.386 #[derive(Clone, PartialEq, Eq, Debug)]387 pub struct Refusal {388     pub code: ErrorCode,389     pub detail: Option<String>,390 }391 392 /// Where the bytes of a part or an artifact are.393 #[derive(Clone, PartialEq, Eq, Debug)]394 pub enum Hold {395     /// The bytes are in the frame.396     Inline(Vec<u8>),397     /// The bytes are at this descriptor. The core opened it.398     Fd(u32),399 }400 401 /// One input of a job.402 #[derive(Clone, PartialEq, Eq, Debug)]403 pub struct Part {404     pub kind: PartKind,405     pub mime: String,406     pub role: Option<String>,407     pub len: u64,408     pub hold: Hold,409 }410 411 /// `open` — caller to server, stream n.412 #[derive(Clone, PartialEq, Debug)]413 pub struct Open {414     pub request_id: String,415     pub model: String,416     pub capability: String,417     pub credit: u64,418     pub budget_ms: u32,419     pub parts: Vec<Part>,420     /// Capability parameters, opaque at this hop.421     pub params: Value,422 }423 424 /// `accept` — server to caller, stream n.425 #[derive(Clone, Copy, PartialEq, Eq, Debug)]426 pub struct Accepted {427     /// `None` is `null` on the wire.428     pub est_ms: Option<u32>,429 }430 431 /// `event` — server to caller, stream n.432 #[derive(Clone, PartialEq, Eq, Debug)]433 pub struct Event {434     pub ch: String,435     pub mime: String,436     pub data: Vec<u8>,437 }438 439 /// One output of a job.440 #[derive(Clone, PartialEq, Eq, Debug)]441 pub struct Artifact {442     pub ch: String,443     pub mime: String,444     pub len: u64,445     pub hold: Hold,446 }447 448 /// `done` — server to caller, stream n. The terminal frame.449 #[derive(Clone, PartialEq, Debug)]450 pub struct Done {451     pub outcome: Outcome,452     pub artifacts: Vec<Artifact>,453     pub usage: BTreeMap<String, u64>,454     /// Omitted when `None`.455     pub meta: Option<BTreeMap<String, Value>>,456 }457 458 /// `cache_lookup` — plugin to core, stream 0.459 #[derive(Clone, PartialEq, Eq, Debug)]460 pub struct CacheLookup {461     pub req_id: u64,462     pub keys: Vec<[u8; 32]>,463     pub lineage: Option<[u8; 32]>,464 }465 466 /// One hit in `cache_lookup_res`.467 #[derive(Clone, PartialEq, Eq, Debug)]468 pub struct CacheHit {469     pub key: [u8; 32],470     pub lease_id: u64,471     pub bytes: u64,472     pub crc32c: u32,473     pub token_count: u64,474     pub tier: String,475     pub fd: u32,476 }477 478 /// `cache_lookup_res` — core to plugin, stream 0.479 #[derive(Clone, PartialEq, Eq, Debug)]480 pub struct CacheLookupRes {481     pub req_id: u64,482     pub hit: Option<CacheHit>,483 }484 485 /// `cache_release` — plugin to core, stream 0.486 #[derive(Clone, Copy, PartialEq, Eq, Debug)]487 pub struct CacheRelease {488     pub lease_id: u64,489     pub ok: bool,490     pub restore_ms: u32,491     /// The caller timed out before it could restore the entry. Release the492     /// lease without counting a hit or a saved prefill.493     pub abandoned: bool,494 }495 496 /// Whether a saved checkpoint is a tip or a protected anchor.497 #[derive(Clone, Copy, PartialEq, Eq, Debug)]498 pub enum CacheEntryKind {499     Tip,500     Anchor,501 }502 503 /// `cache_reserve` — plugin to core, stream 0.504 #[derive(Clone, PartialEq, Eq, Debug)]505 pub struct CacheReserve {506     pub req_id: u64,507     pub key: [u8; 32],508     pub lineage: Option<[u8; 32]>,509     pub supersedes: Option<[u8; 32]>,510     pub kind: CacheEntryKind,511     pub est_bytes: u64,512     pub prefill_ms: u32,513     pub token_count: u64,514     pub pin: bool,515 }516 517 /// One granted write lease in `cache_grant`.518 #[derive(Clone, PartialEq, Eq, Debug)]519 pub struct CacheWriteGrant {520     pub lease_id: u64,521     pub max_bytes: u64,522     pub tier: String,523     pub fd: u32,524 }525 526 /// `cache_grant` — core to plugin, stream 0.527 #[derive(Clone, PartialEq, Eq, Debug)]528 pub struct CacheGrant {529     pub req_id: u64,530     pub grant: Option<CacheWriteGrant>,531     pub reason: Option<String>,532 }533 534 /// `cache_commit` — plugin to core, stream 0.535 #[derive(Clone, Copy, PartialEq, Eq, Debug)]536 pub struct CacheCommit {537     pub lease_id: u64,538     pub ok: bool,539     pub bytes: u64,540     pub crc32c: u32,541     pub token_count: u64,542     pub save_ms: u32,543 }544 545 /// `cache_flush` — core to plugin, stream 0.546 #[derive(Clone, Copy, PartialEq, Eq, Debug)]547 pub struct CacheFlush {548     pub req_id: u64,549     pub budget_ms: u32,550 }551 552 /// `cache_flushed` — plugin to core, stream 0.553 #[derive(Clone, Copy, PartialEq, Eq, Debug)]554 pub struct CacheFlushed {555     pub req_id: u64,556     pub saved: u32,557     pub skipped: u32,558     pub dirty_remaining: u32,559 }560 561 /// `cancel` — caller to server, stream n.562 ///563 /// The name keeps `Cancel` for the lifecycle fact, which a catalogue carries.564 #[derive(Clone, PartialEq, Eq, Debug)]565 pub struct CancelJob {566     pub reason: String,567 }568 569 /// One body, tagged by its kind.570 #[derive(Clone, PartialEq, Debug)]571 pub enum Body {572     Hello(Hello),573     Welcome(Welcome),574     Catalogue(Catalogue),575     Grant(Grant),576     Ready(Ready),577     Window(Window),578     Ping(Tick),579     Pong(Tick),580     Bye(Bye),581     Fatal(Refusal),582     Open(Open),583     Accept(Accepted),584     Event(Event),585     Done(Done),586     Reject(Refusal),587     Cancel(CancelJob),588     CacheLookup(CacheLookup),589     CacheLookupRes(CacheLookupRes),590     CacheRelease(CacheRelease),591     CacheReserve(CacheReserve),592     CacheGrant(CacheGrant),593     CacheCommit(CacheCommit),594     CacheFlush(CacheFlush),595     CacheFlushed(CacheFlushed),596 }597 598 impl Body {599     /// The frame kind of this body.600     pub fn kind(&self) -> Kind {601         body_kind(self)602     }603 604     /// The canonical CBOR bytes of this body.605     pub fn encode(&self) -> Vec<u8> {606         body_encode(self)607     }608 609     /// Reads the body of a frame. `payload` is the frame payload.610     pub fn decode(kind: Kind, payload: &[u8]) -> Result<Body, BodyError> {611         body_decode(kind, payload)612     }613 614     /// The CBOR value of this body.615     pub fn to_value(&self) -> Value {616         body_to_value(self)617     }618 }619 620 impl Hello {621     pub fn to_value(&self) -> Value {622         hello_to_value(self)623     }624     pub fn from_value(v: &Value) -> Result<Hello, BodyError> {625         hello_from_value(v)626     }627 }628 629 impl Welcome {630     pub fn to_value(&self) -> Value {631         welcome_to_value(self)632     }633     pub fn from_value(v: &Value) -> Result<Welcome, BodyError> {634         welcome_from_value(v)635     }636 }637 638 impl Capability {639     /// Whether this capability cannot promise the engine's streaming contract.640     ///641     /// A degraded capability still serves jobs, but a background job may hold a642     /// slot for its whole duration, and a cancel lands at the frame or the643     /// request boundary. The label exists so the core refuses what the engine644     /// cannot honour instead of discovering it mid-job.645     pub fn degraded(&self) -> bool {646         self.cancel != Cancel::Token || self.queue == Queue::Internal647     }648 649     /// The capability as a JSON-shaped value: the vocabulary, the parts, the650     /// channels, and the limits.651     pub fn to_value(&self) -> Value {652         Value::Map(vec![653             (654                 Value::Text("vocab".to_string()),655                 Value::Text(self.vocab.clone()),656             ),657             (658                 Value::Text("parts".to_string()),659                 Value::Array(660                     self.parts661                         .iter()662                         .map(|kind| Value::Text(part_kind_name(*kind).to_string()))663                         .collect(),664                 ),665             ),666             (667                 Value::Text("channels".to_string()),668                 Value::Array(self.channels.iter().cloned().map(Value::Text).collect()),669             ),670             (671                 Value::Text("limits".to_string()),672                 Value::Map(673                     self.limits674                         .iter()675                         .map(|(key, value)| (Value::Text(key.clone()), Value::Uint(*value)))676                         .collect(),677                 ),678             ),679             (680                 Value::Text("cancel".to_string()),681                 Value::Text(self.cancel.as_str().to_string()),682             ),683             (684                 Value::Text("stops".to_string()),685                 Value::Text(self.stops.as_str().to_string()),686             ),687             (688                 Value::Text("queue".to_string()),689                 Value::Text(self.queue.as_str().to_string()),690             ),691         ])692     }693 }694 695 impl Catalogue {696     pub fn to_value(&self) -> Value {697         catalogue_to_value(self)698     }699     pub fn from_value(v: &Value) -> Result<Catalogue, BodyError> {700         catalogue_from_value(v)701     }702 }703 704 impl Grant {705     pub fn to_value(&self) -> Value {706         grant_to_value(self)707     }708     pub fn from_value(v: &Value) -> Result<Grant, BodyError> {709         grant_from_value(v)710     }711 }712 713 impl Ready {714     pub fn to_value(&self) -> Value {715         ready_to_value(self)716     }717     pub fn from_value(v: &Value) -> Result<Ready, BodyError> {718         ready_from_value(v)719     }720 }721 722 impl Window {723     pub fn to_value(&self) -> Value {724         window_to_value(self)725     }726     pub fn from_value(v: &Value) -> Result<Window, BodyError> {727         window_from_value(v)728     }729 }730 731 impl Tick {732     pub fn to_value(&self) -> Value {733         tick_to_value(self)734     }735     pub fn from_value(v: &Value) -> Result<Tick, BodyError> {736         tick_from_value(v)737     }738 }739 740 impl Bye {741     pub fn to_value(&self) -> Value {742         bye_to_value(self)743     }744     pub fn from_value(v: &Value) -> Result<Bye, BodyError> {745         bye_from_value(v)746     }747 }748 749 impl Refusal {750     pub fn to_value(&self) -> Value {751         refusal_to_value(self)752     }753     pub fn from_value(v: &Value) -> Result<Refusal, BodyError> {754         refusal_from_value(v)755     }756 }757 758 impl Open {759     pub fn to_value(&self) -> Value {760         open_to_value(self)761     }762     pub fn from_value(v: &Value) -> Result<Open, BodyError> {763         open_from_value(v)764     }765 }766 767 impl Accepted {768     pub fn to_value(&self) -> Value {769         accepted_to_value(self)770     }771     pub fn from_value(v: &Value) -> Result<Accepted, BodyError> {772         accepted_from_value(v)773     }774 }775 776 impl Event {777     pub fn to_value(&self) -> Value {778         event_to_value(self)779     }780     pub fn from_value(v: &Value) -> Result<Event, BodyError> {781         event_from_value(v)782     }783 }784 785 impl Done {786     pub fn to_value(&self) -> Value {787         done_to_value(self)788     }789     pub fn from_value(v: &Value) -> Result<Done, BodyError> {790         done_from_value(v)791     }792 }793 794 impl CancelJob {795     pub fn to_value(&self) -> Value {796         cancel_to_value(self)797     }798     pub fn from_value(v: &Value) -> Result<CancelJob, BodyError> {799         cancel_from_value(v)800     }801 }802 803 /// A body that does not match the grammar.804 #[derive(Clone, PartialEq, Debug)]805 pub enum BodyError {806     Cbor(CborError),807     /// A key that the grammar requires is absent.808     Missing(&'static str),809     /// A value does not fit the field.810     Type {811         field: &'static str,812         want: &'static str,813         got: &'static str,814     },815     /// A text that is not one of the grammar literals.816     Literal {817         field: &'static str,818         got: String,819     },820     /// A uint that does not fit the field.821     Range(&'static str),822     /// The frame kind is not one of the sixteen.823     Unassigned(Kind),824 }825 826 impl fmt::Display for BodyError {827     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {828         write!(f, "{}", body_error_text(self))829     }830 }831 832 impl std::error::Error for BodyError {}833 834 impl From<CborError> for BodyError {835     fn from(e: CborError) -> BodyError {836         BodyError::Cbor(e)837     }838 }839 840 // ---- the grammar, key by key ------------------------------------------------841 //842 // A helper names a key exactly as `spec/protocol.cddl` spells it, so an error843 // always names the wire and never a Rust field.844 845 const ROLES: [&str; 2] = ["call", "serve"];846 const PART_KINDS: [&str; 6] = ["text", "image", "audio", "video", "tokens", "json"];847 const OUTCOMES: [&str; 4] = ["completed", "failed", "cancelled", "expired"];848 const ERROR_CODES: [&str; 13] = [849     "version",850     "frame",851     "stream",852     "size",853     "credit",854     "busy",855     "unknown_model",856     "capability",857     "part",858     "dependency",859     "timeout",860     "cancelled",861     "internal",862 ];863 864 /// A text key or value on the wire.865 fn t(s: impl Into<String>) -> Value {866     Value::Text(s.into())867 }868 869 /// A uint on the wire.870 fn n(x: u64) -> Value {871     Value::Uint(x)872 }873 874 /// The entries of a map value, or a type error named by `field`.875 fn entries_of<'a>(v: &'a Value, field: &'static str) -> Result<&'a [(Value, Value)], BodyError> {876     match v {877         Value::Map(entries) => Ok(entries),878         other => Err(BodyError::Type {879             field,880             want: "map",881             got: other.kind(),882         }),883     }884 }885 886 /// The value that a text key carries.887 fn get<'a>(entries: &'a [(Value, Value)], key: &'static str) -> Option<&'a Value> {888     entries889         .iter()890         .find(|(k, _)| matches!(k, Value::Text(s) if s.as_str() == key))891         .map(|(_, v)| v)892 }893 894 /// A key that the grammar requires.895 fn req<'a>(entries: &'a [(Value, Value)], key: &'static str) -> Result<&'a Value, BodyError> {896     get(entries, key).ok_or(BodyError::Missing(key))897 }898 899 fn uint_value(v: &Value, field: &'static str) -> Result<u64, BodyError> {900     match v {901         Value::Uint(x) => Ok(*x),902         other => Err(BodyError::Type {903             field,904             want: "uint",905             got: other.kind(),906         }),907     }908 }909 910 /// A uint that the grammar requires.911 fn u64_at(entries: &[(Value, Value)], key: &'static str) -> Result<u64, BodyError> {912     uint_value(req(entries, key)?, key)913 }914 915 /// A uint that must also fit a `u32` field.916 fn u32_value(v: &Value, field: &'static str) -> Result<u32, BodyError> {917     let x = uint_value(v, field)?;918     u32::try_from(x).map_err(|_| BodyError::Range(field))919 }920 921 fn u32_at(entries: &[(Value, Value)], key: &'static str) -> Result<u32, BodyError> {922     u32_value(req(entries, key)?, key)923 }924 925 /// A uint that must also fit a `u16` field.926 fn u16_at(entries: &[(Value, Value)], key: &'static str) -> Result<u16, BodyError> {927     let x = u64_at(entries, key)?;928     u16::try_from(x).map_err(|_| BodyError::Range(key))929 }930 931 /// `tstr`, required.932 fn text_at<'a>(entries: &'a [(Value, Value)], key: &'static str) -> Result<&'a str, BodyError> {933     match req(entries, key)? {934         Value::Text(s) => Ok(s.as_str()),935         other => Err(BodyError::Type {936             field: key,937             want: "text",938             got: other.kind(),939         }),940     }941 }942 943 fn text_value(v: &Value, field: &'static str) -> Result<String, BodyError> {944     match v {945         Value::Text(s) => Ok(s.clone()),946         other => Err(BodyError::Type {947             field,948             want: "text",949             got: other.kind(),950         }),951     }952 }953 954 /// `tstr / null`. The key is always present; `null` is `None`.955 fn opt_text_at(entries: &[(Value, Value)], key: &'static str) -> Result<Option<String>, BodyError> {956     match req(entries, key)? {957         Value::Null => Ok(None),958         Value::Text(s) => Ok(Some(s.clone())),959         other => Err(BodyError::Type {960             field: key,961             want: "text",962             got: other.kind(),963         }),964     }965 }966 967 /// `uint / null`. The key is always present; `null` is `None`.968 fn opt_u32_at(entries: &[(Value, Value)], key: &'static str) -> Result<Option<u32>, BodyError> {969     match req(entries, key)? {970         Value::Null => Ok(None),971         v => Ok(Some(u32_value(v, key)?)),972     }973 }974 975 /// An optional text that is absent or `null` when the grammar does not require976 /// it.977 fn opt_text<'a>(978     entries: &'a [(Value, Value)],979     key: &'static str,980 ) -> Result<Option<&'a str>, BodyError> {981     match get(entries, key) {982         None | Some(Value::Null) => Ok(None),983         Some(Value::Text(s)) => Ok(Some(s.as_str())),984         Some(other) => Err(BodyError::Type {985             field: key,986             want: "text",987             got: other.kind(),988         }),989     }990 }991 992 /// An optional uint that is absent or `null` when the grammar does not require993 /// it.994 fn opt_uint(entries: &[(Value, Value)], key: &'static str) -> Result<Option<u64>, BodyError> {995     match get(entries, key) {996         None | Some(Value::Null) => Ok(None),997         Some(v) => Ok(Some(uint_value(v, key)?)),998     }999 }1000 1001 /// An optional uint that must also fit a `u32` field.1002 fn opt_u32(entries: &[(Value, Value)], key: &'static str) -> Result<Option<u32>, BodyError> {1003     match opt_uint(entries, key)? {1004         None => Ok(None),1005         Some(x) => u32::try_from(x)1006             .map(Some)1007             .map_err(|_| BodyError::Range(key)),1008     }1009 }1010 1011 /// `bstr`.1012 fn bytes_at(entries: &[(Value, Value)], key: &'static str) -> Result<Vec<u8>, BodyError> {1013     match req(entries, key)? {1014         Value::Bytes(b) => Ok(b.clone()),1015         other => Err(BodyError::Type {1016             field: key,1017             want: "bytes",1018             got: other.kind(),1019         }),1020     }1021 }1022 /// `bool`.1023 fn bool_at(entries: &[(Value, Value)], key: &'static str) -> Result<bool, BodyError> {1024     match req(entries, key)? {1025         Value::Bool(b) => Ok(*b),1026         other => Err(BodyError::Type {1027             field: key,1028             want: "bool",1029             got: other.kind(),1030         }),1031     }1032 }1033 1034 /// `bstr .size 32`.1035 fn key_at(entries: &[(Value, Value)], key: &'static str) -> Result<[u8; 32], BodyError> {1036     key_from_value(req(entries, key)?, key)1037 }1038 1039 fn key_from_value(value: &Value, field: &'static str) -> Result<[u8; 32], BodyError> {1040     match value {1041         Value::Bytes(bytes) => bytes.as_slice().try_into().map_err(|_| BodyError::Type {1042             field,1043             want: "32 bytes",1044             got: "bytes",1045         }),1046         other => Err(BodyError::Type {1047             field,1048             want: "32 bytes",1049             got: other.kind(),1050         }),1051     }1052 }1053 1054 fn opt_key_at(1055     entries: &[(Value, Value)],1056     key: &'static str,1057 ) -> Result<Option<[u8; 32]>, BodyError> {1058     match get(entries, key) {1059         None | Some(Value::Null) => Ok(None),1060         Some(value) => key_from_value(value, key).map(Some),1061     }1062 }1063 1064 /// `[+ bstr .size 32]`.1065 fn keys_at(entries: &[(Value, Value)], key: &'static str) -> Result<Vec<[u8; 32]>, BodyError> {1066     array_at(entries, key)?1067         .iter()1068         .map(|value| key_from_value(value, key))1069         .collect()1070 }1071 1072 /// `[* x]`.1073 fn array_at<'a>(1074     entries: &'a [(Value, Value)],1075     key: &'static str,1076 ) -> Result<&'a [Value], BodyError> {1077     match req(entries, key)? {1078         Value::Array(items) => Ok(items),1079         other => Err(BodyError::Type {1080             field: key,1081             want: "array",1082             got: other.kind(),1083         }),1084     }1085 }1086 1087 /// A required map, whether a named rule or `{ * tstr => x }`.1088 fn map_at<'a>(1089     entries: &'a [(Value, Value)],1090     key: &'static str,1091 ) -> Result<&'a [(Value, Value)], BodyError> {1092     entries_of(req(entries, key)?, key)1093 }1094 1095 /// `[* tstr]`.1096 fn texts(items: &[Value], field: &'static str) -> Result<Vec<String>, BodyError> {1097     items.iter().map(|v| text_value(v, field)).collect()1098 }1099 1100 /// `[* uint]` into a field of `u32`.1101 fn u32s(items: &[Value], field: &'static str) -> Result<Vec<u32>, BodyError> {1102     items.iter().map(|v| u32_value(v, field)).collect()1103 }1104 1105 /// `{ * tstr => uint }`.1106 fn uint_map_at(1107     entries: &[(Value, Value)],1108     key: &'static str,1109 ) -> Result<BTreeMap<String, u64>, BodyError> {1110     let mut out = BTreeMap::new();1111     for (k, v) in map_at(entries, key)? {1112         out.insert(text_value(k, key)?, uint_value(v, key)?);1113     }1114     Ok(out)1115 }1116 1117 /// A grammar literal.1118 fn literal_value<'a>(1119     v: &'a Value,1120     field: &'static str,1121     names: &[&'static str],1122 ) -> Result<&'a str, BodyError> {1123     match v {1124         Value::Text(s) => {1125             if names.iter().copied().any(|name| name == s.as_str()) {1126                 Ok(s.as_str())1127             } else {1128                 Err(BodyError::Literal {1129                     field,1130                     got: s.clone(),1131                 })1132             }1133         }1134         other => Err(BodyError::Type {1135             field,1136             want: "text",1137             got: other.kind(),1138         }),1139     }1140 }1141 1142 fn literal_at<'a>(1143     entries: &'a [(Value, Value)],1144     key: &'static str,1145     names: &[&'static str],1146 ) -> Result<&'a str, BodyError> {1147     literal_value(req(entries, key)?, key, names)1148 }1149 1150 fn role_name(role: Role) -> &'static str {1151     match role {1152         Role::Call => "call",1153         Role::Serve => "serve",1154     }1155 }1156 1157 fn role_at(entries: &[(Value, Value)], key: &'static str) -> Result<Role, BodyError> {1158     Ok(match literal_at(entries, key, &ROLES)? {1159         "call" => Role::Call,1160         _ => Role::Serve,1161     })1162 }1163 1164 /// The name of a part kind, as the wire and the catalogue spell it.1165 pub fn part_kind_name(kind: PartKind) -> &'static str {1166     match kind {1167         PartKind::Text => "text",1168         PartKind::Image => "image",1169         PartKind::Audio => "audio",1170         PartKind::Video => "video",1171         PartKind::Tokens => "tokens",1172         PartKind::Json => "json",1173     }1174 }1175 1176 fn part_kind_value(v: &Value, field: &'static str) -> Result<PartKind, BodyError> {1177     Ok(match literal_value(v, field, &PART_KINDS)? {1178         "text" => PartKind::Text,1179         "image" => PartKind::Image,1180         "audio" => PartKind::Audio,1181         "video" => PartKind::Video,1182         "tokens" => PartKind::Tokens,1183         _ => PartKind::Json,1184     })1185 }1186 1187 fn part_kind_at(entries: &[(Value, Value)], key: &'static str) -> Result<PartKind, BodyError> {1188     part_kind_value(req(entries, key)?, key)1189 }1190 1191 fn outcome_name(outcome: Outcome) -> &'static str {1192     match outcome {1193         Outcome::Completed => "completed",1194         Outcome::Failed => "failed",1195         Outcome::Cancelled => "cancelled",1196         Outcome::Expired => "expired",1197     }1198 }1199 1200 fn outcome_at(entries: &[(Value, Value)], key: &'static str) -> Result<Outcome, BodyError> {1201     Ok(match literal_at(entries, key, &OUTCOMES)? {1202         "completed" => Outcome::Completed,1203         "failed" => Outcome::Failed,1204         "cancelled" => Outcome::Cancelled,1205         _ => Outcome::Expired,1206     })1207 }1208 1209 fn error_code_name(code: ErrorCode) -> &'static str {1210     match code {1211         ErrorCode::Version => "version",1212         ErrorCode::Frame => "frame",1213         ErrorCode::Stream => "stream",1214         ErrorCode::Size => "size",1215         ErrorCode::Credit => "credit",1216         ErrorCode::Busy => "busy",1217         ErrorCode::UnknownModel => "unknown_model",1218         ErrorCode::Capability => "capability",1219         ErrorCode::Part => "part",1220         ErrorCode::Dependency => "dependency",1221         ErrorCode::Timeout => "timeout",1222         ErrorCode::Cancelled => "cancelled",1223         ErrorCode::Internal => "internal",1224     }1225 }1226 1227 fn error_code_at(entries: &[(Value, Value)], key: &'static str) -> Result<ErrorCode, BodyError> {1228     Ok(match literal_at(entries, key, &ERROR_CODES)? {1229         "version" => ErrorCode::Version,1230         "frame" => ErrorCode::Frame,1231         "stream" => ErrorCode::Stream,1232         "size" => ErrorCode::Size,1233         "credit" => ErrorCode::Credit,1234         "busy" => ErrorCode::Busy,1235         "unknown_model" => ErrorCode::UnknownModel,1236         "capability" => ErrorCode::Capability,1237         "part" => ErrorCode::Part,1238         "dependency" => ErrorCode::Dependency,1239         "timeout" => ErrorCode::Timeout,1240         "cancelled" => ErrorCode::Cancelled,1241         _ => ErrorCode::Internal,1242     })1243 }1244 1245 // ---- the rules of the grammar -----------------------------------------------1246 1247 fn version_range_value(range: &VersionRange) -> Value {1248     Value::Array(vec![n(u64::from(range.min)), n(u64::from(range.max))])1249 }1250 1251 fn version_range_at(1252     entries: &[(Value, Value)],1253     key: &'static str,1254 ) -> Result<VersionRange, BodyError> {1255     match array_at(entries, key)? {1256         [min, max] => Ok(VersionRange {1257             min: u32_value(min, key)?,1258             max: u32_value(max, key)?,1259         }),1260         _ => Err(BodyError::Type {1261             field: key,1262             want: "uint pair",1263             got: "array",1264         }),1265     }1266 }1267 1268 fn target_value(target: &Target) -> Value {1269     Value::map([1270         (t("id"), t(target.id.as_str())),1271         (t("backend"), t(target.backend.as_str())),1272         (1273             t("arch"),1274             Value::Array(target.arch.iter().map(|s| t(s.as_str())).collect()),1275         ),1276         (t("devices"), n(u64::from(target.devices))),1277         (1278             t("vram_mb"),1279             Value::Array(target.vram_mb.iter().map(|m| n(u64::from(*m))).collect()),1280         ),1281     ])1282 }1283 1284 fn target_from(v: &Value) -> Result<Target, BodyError> {1285     let entries = entries_of(v, "target")?;1286     Ok(Target {1287         id: text_at(entries, "id")?.to_string(),1288         backend: text_at(entries, "backend")?.to_string(),1289         arch: texts(array_at(entries, "arch")?, "arch")?,1290         devices: u32_at(entries, "devices")?,1291         vram_mb: u32s(array_at(entries, "vram_mb")?, "vram_mb")?,1292     })1293 }1294 1295 fn runtime_value(runtime: &Runtime) -> Value {1296     Value::map([1297         (t("name"), t(runtime.name.as_str())),1298         (t("version"), t(runtime.version.as_str())),1299     ])1300 }1301 1302 fn runtime_from(v: &Value) -> Result<Runtime, BodyError> {1303     let entries = entries_of(v, "runtime")?;1304     Ok(Runtime {1305         name: text_at(entries, "name")?.to_string(),1306         version: text_at(entries, "version")?.to_string(),1307     })1308 }1309 1310 fn capability_value(cap: &Capability) -> Value {1311     Value::map([1312         (t("vocab"), t(cap.vocab.as_str())),1313         (1314             t("parts"),1315             Value::Array(cap.parts.iter().map(|k| t(part_kind_name(*k))).collect()),1316         ),1317         (1318             t("channels"),1319             Value::Array(cap.channels.iter().map(|s| t(s.as_str())).collect()),1320         ),1321         (1322             t("limits"),1323             Value::map(1324                 cap.limits1325                     .iter()1326                     .map(|(k, v)| (t(k.as_str()), n(*v)))1327                     .collect::<Vec<(Value, Value)>>(),1328             ),1329         ),1330         (t("cancel"), t(cap.cancel.as_str())),1331         (t("stops"), t(cap.stops.as_str())),1332         (t("queue"), t(cap.queue.as_str())),1333     ])1334 }1335 1336 fn capability_from(v: &Value) -> Result<Capability, BodyError> {1337     let entries = entries_of(v, "capability")?;1338     Ok(Capability {1339         vocab: text_at(entries, "vocab")?.to_string(),1340         parts: array_at(entries, "parts")?1341             .iter()1342             .map(|v| part_kind_value(v, "parts"))1343             .collect::<Result<Vec<PartKind>, BodyError>>()?,1344         channels: texts(array_at(entries, "channels")?, "channels")?,1345         limits: uint_map_at(entries, "limits")?,1346         // A key that the grammar has not taught this peer yet falls back to the1347         // default, so an old peer and a new one still agree.1348         cancel: Cancel::from_str(opt_text(entries, "cancel")?.unwrap_or("token")),1349         stops: Stops::from_str(opt_text(entries, "stops")?.unwrap_or("plugin")),1350         queue: Queue::from_str(opt_text(entries, "queue")?.unwrap_or("none")),1351     })1352 }1353 1354 fn model_value(model: &Model) -> Value {1355     Value::map([1356         (t("serve"), t(model.serve.as_str())),1357         // `alias_of: tstr / null` always writes the key.1358         (1359             t("alias_of"),1360             match &model.alias_of {1361                 Some(name) => t(name.as_str()),1362                 None => Value::Null,1363             },1364         ),1365         (1366             t("capabilities"),1367             Value::map(1368                 model1369                     .capabilities1370                     .iter()1371                     .map(|(k, c)| (t(k.as_str()), capability_value(c)))1372                     .collect::<Vec<(Value, Value)>>(),1373             ),1374         ),1375         (t("weights_bytes"), n(model.weights_bytes)),1376         (t("load_ms"), n(u64::from(model.load_ms))),1377     ])1378 }1379 1380 fn model_from(v: &Value) -> Result<Model, BodyError> {1381     let entries = entries_of(v, "model")?;1382     let mut capabilities = BTreeMap::new();1383     for (k, c) in map_at(entries, "capabilities")? {1384         capabilities.insert(text_value(k, "capabilities")?, capability_from(c)?);1385     }1386     Ok(Model {1387         serve: text_at(entries, "serve")?.to_string(),1388         alias_of: opt_text_at(entries, "alias_of")?,1389         weights_bytes: opt_uint(entries, "weights_bytes")?.unwrap_or(0),1390         load_ms: opt_u32(entries, "load_ms")?.unwrap_or(0),1391         capabilities,1392     })1393 }1394 1395 fn dependency_value(dep: &Dependency) -> Value {1396     Value::map([1397         (t("role"), t(dep.role.as_str())),1398         (t("fd"), n(u64::from(dep.fd))),1399         (t("len"), n(dep.len)),1400         (t("path"), t(dep.path.as_str())),1401     ])1402 }1403 1404 fn dependency_from(v: &Value) -> Result<Dependency, BodyError> {1405     let entries = entries_of(v, "dependency")?;1406     Ok(Dependency {1407         role: text_at(entries, "role")?.to_string(),1408         fd: u32_at(entries, "fd")?,1409         len: u64_at(entries, "len")?,1410         path: text_at(entries, "path")?.to_string(),1411     })1412 }1413 1414 /// `inline: bstr // fd: uint`. Exactly one of the two keys is written.1415 fn hold_value(hold: &Hold, entries: &mut Vec<(Value, Value)>) {1416     match hold {1417         Hold::Inline(bytes) => entries.push((t("inline"), Value::Bytes(bytes.clone()))),1418         Hold::Fd(fd) => entries.push((t("fd"), n(u64::from(*fd)))),1419     }1420 }1421 1422 fn hold_from(entries: &[(Value, Value)]) -> Result<Hold, BodyError> {1423     match (get(entries, "inline"), get(entries, "fd")) {1424         (Some(_), Some(_)) => Err(BodyError::Type {1425             field: "fd",1426             want: "one of inline or fd",1427             got: "both",1428         }),1429         (Some(v), None) => match v {1430             Value::Bytes(b) => Ok(Hold::Inline(b.clone())),1431             other => Err(BodyError::Type {1432                 field: "inline",1433                 want: "bytes",1434                 got: other.kind(),1435             }),1436         },1437         (None, Some(v)) => Ok(Hold::Fd(u32_value(v, "fd")?)),1438         (None, None) => Err(BodyError::Missing("inline")),1439     }1440 }1441 1442 fn part_value(part: &Part) -> Value {1443     let mut entries = vec![1444         (t("kind"), t(part_kind_name(part.kind))),1445         (t("mime"), t(part.mime.as_str())),1446         (1447             t("role"),1448             match &part.role {1449                 Some(role) => t(role.as_str()),1450                 None => Value::Null,1451             },1452         ),1453         (t("len"), n(part.len)),1454     ];1455     hold_value(&part.hold, &mut entries);1456     Value::map(entries)1457 }1458 1459 fn part_from(v: &Value) -> Result<Part, BodyError> {1460     let entries = entries_of(v, "parts")?;1461     Ok(Part {1462         kind: part_kind_at(entries, "kind")?,1463         mime: text_at(entries, "mime")?.to_string(),1464         role: opt_text_at(entries, "role")?,1465         len: u64_at(entries, "len")?,1466         hold: hold_from(entries)?,1467     })1468 }1469 1470 fn artifact_value(artifact: &Artifact) -> Value {1471     let mut entries = vec![1472         (t("ch"), t(artifact.ch.as_str())),1473         (t("mime"), t(artifact.mime.as_str())),1474         (t("len"), n(artifact.len)),1475     ];1476     hold_value(&artifact.hold, &mut entries);1477     Value::map(entries)1478 }1479 1480 fn artifact_from(v: &Value) -> Result<Artifact, BodyError> {1481     let entries = entries_of(v, "artifacts")?;1482     Ok(Artifact {1483         ch: text_at(entries, "ch")?.to_string(),1484         mime: text_at(entries, "mime")?.to_string(),1485         len: u64_at(entries, "len")?,1486         hold: hold_from(entries)?,1487     })1488 }1489 1490 /// `{ * tstr => any }`.1491 fn any_map_from(v: &Value, key: &'static str) -> Result<BTreeMap<String, Value>, BodyError> {1492     let mut out = BTreeMap::new();1493     for (k, v) in entries_of(v, key)? {1494         out.insert(text_value(k, key)?, v.clone());1495     }1496     Ok(out)1497 }1498 1499 // ---- the sixteen bodies -----------------------------------------------------1500 1501 fn body_kind(body: &Body) -> Kind {1502     match body {1503         Body::Hello(_) => Kind::Hello,1504         Body::Welcome(_) => Kind::Welcome,1505         Body::Catalogue(_) => Kind::Catalogue,1506         Body::Grant(_) => Kind::Grant,1507         Body::Ready(_) => Kind::Ready,1508         Body::Window(_) => Kind::Window,1509         Body::Ping(_) => Kind::Ping,1510         Body::Pong(_) => Kind::Pong,1511         Body::Bye(_) => Kind::Bye,1512         Body::Fatal(_) => Kind::Fatal,1513         Body::Open(_) => Kind::Open,1514         Body::Accept(_) => Kind::Accept,1515         Body::Event(_) => Kind::Event,1516         Body::Done(_) => Kind::Done,1517         Body::Reject(_) => Kind::Reject,1518         Body::Cancel(_) => Kind::Cancel,1519         Body::CacheLookup(_) => Kind::CacheLookup,1520         Body::CacheLookupRes(_) => Kind::CacheLookupRes,1521         Body::CacheRelease(_) => Kind::CacheRelease,1522         Body::CacheReserve(_) => Kind::CacheReserve,1523         Body::CacheGrant(_) => Kind::CacheGrant,1524         Body::CacheCommit(_) => Kind::CacheCommit,1525         Body::CacheFlush(_) => Kind::CacheFlush,1526         Body::CacheFlushed(_) => Kind::CacheFlushed,1527     }1528 }1529 1530 fn body_to_value(body: &Body) -> Value {1531     match body {1532         Body::Hello(b) => b.to_value(),1533         Body::Welcome(b) => b.to_value(),1534         Body::Catalogue(b) => b.to_value(),1535         Body::Grant(b) => b.to_value(),1536         Body::Ready(b) => b.to_value(),1537         Body::Window(b) => b.to_value(),1538         Body::Ping(b) => b.to_value(),1539         Body::Pong(b) => b.to_value(),1540         Body::Bye(b) => b.to_value(),1541         Body::Fatal(b) | Body::Reject(b) => b.to_value(),1542         Body::Open(b) => b.to_value(),1543         Body::Accept(b) => b.to_value(),1544         Body::Event(b) => b.to_value(),1545         Body::Done(b) => b.to_value(),1546         Body::Cancel(b) => b.to_value(),1547         Body::CacheLookup(b) => cache_lookup_to_value(b),1548         Body::CacheLookupRes(b) => cache_lookup_res_to_value(b),1549         Body::CacheRelease(b) => cache_release_to_value(b),1550         Body::CacheReserve(b) => cache_reserve_to_value(b),1551         Body::CacheGrant(b) => cache_grant_to_value(b),1552         Body::CacheCommit(b) => cache_commit_to_value(b),1553         Body::CacheFlush(b) => cache_flush_to_value(b),1554         Body::CacheFlushed(b) => cache_flushed_to_value(b),1555     }1556 }1557 1558 fn body_encode(body: &Body) -> Vec<u8> {1559     let value = body_to_value(body);1560     let mut out = Vec::new();1561     cbor::encode(&value, &mut out);1562     out1563 }1564 1565 fn body_decode(kind: Kind, payload: &[u8]) -> Result<Body, BodyError> {1566     // An extension frame has no body, and that is settled before any byte is1567     // read.1568     if let Kind::Extension(_) = kind {1569         return Err(BodyError::Unassigned(kind));1570     }1571     let item = cbor::decode(payload)?;1572     Ok(match kind {1573         Kind::Hello => Body::Hello(Hello::from_value(&item)?),1574         Kind::Welcome => Body::Welcome(Welcome::from_value(&item)?),1575         Kind::Catalogue => Body::Catalogue(Catalogue::from_value(&item)?),1576         Kind::Grant => Body::Grant(Grant::from_value(&item)?),1577         Kind::Ready => Body::Ready(Ready::from_value(&item)?),1578         Kind::Window => Body::Window(Window::from_value(&item)?),1579         Kind::Ping => Body::Ping(Tick::from_value(&item)?),1580         Kind::Pong => Body::Pong(Tick::from_value(&item)?),1581         Kind::Bye => Body::Bye(Bye::from_value(&item)?),1582         Kind::Fatal => Body::Fatal(Refusal::from_value(&item)?),1583         Kind::Open => Body::Open(Open::from_value(&item)?),1584         Kind::Accept => Body::Accept(Accepted::from_value(&item)?),1585         Kind::Event => Body::Event(Event::from_value(&item)?),1586         Kind::Done => Body::Done(Done::from_value(&item)?),1587         Kind::Reject => Body::Reject(Refusal::from_value(&item)?),1588         Kind::Cancel => Body::Cancel(CancelJob::from_value(&item)?),1589         Kind::CacheLookup => Body::CacheLookup(CacheLookup::from_value(&item)?),1590         Kind::CacheLookupRes => Body::CacheLookupRes(CacheLookupRes::from_value(&item)?),1591         Kind::CacheRelease => Body::CacheRelease(CacheRelease::from_value(&item)?),1592         Kind::CacheReserve => Body::CacheReserve(CacheReserve::from_value(&item)?),1593         Kind::CacheGrant => Body::CacheGrant(CacheGrant::from_value(&item)?),1594         Kind::CacheCommit => Body::CacheCommit(CacheCommit::from_value(&item)?),1595         Kind::CacheFlush => Body::CacheFlush(CacheFlush::from_value(&item)?),1596         Kind::CacheFlushed => Body::CacheFlushed(CacheFlushed::from_value(&item)?),1597         Kind::Extension(_) => return Err(BodyError::Unassigned(kind)),1598     })1599 }1600 1601 fn body_error_text(err: &BodyError) -> String {1602     match err {1603         BodyError::Cbor(e) => format!("cbor: {e}"),1604         BodyError::Missing(key) => format!("the key {key} is required and absent"),1605         BodyError::Type { field, want, got } => {1606             format!("{field} must be {want}, it is {got}")1607         }1608         BodyError::Literal { field, got } => {1609             format!("{field} is not a literal of the grammar: {got}")1610         }1611         BodyError::Range(key) => format!("{key} does not fit its field"),1612         BodyError::Unassigned(kind) => format!("frame kind {kind:?} has no body"),1613     }1614 }1615 1616 // ---- one pair per body ------------------------------------------------------1617 1618 fn hello_to_value(hello: &Hello) -> Value {1619     Value::map([1620         (t("v"), version_range_value(&hello.v)),1621         (t("role"), t(role_name(hello.role))),1622         (t("id"), t(hello.id.as_str())),1623     ])1624 }1625 1626 fn hello_from_value(v: &Value) -> Result<Hello, BodyError> {1627     let entries = entries_of(v, "hello")?;1628     let range = version_range_at(entries, "v")?;1629     let role = role_at(entries, "role")?;1630     let id = text_at(entries, "id")?;1631     Ok(Hello {1632         v: range,1633         role,1634         id: id.to_string(),1635     })1636 }1637 1638 fn welcome_to_value(welcome: &Welcome) -> Value {1639     Value::map([1640         (t("v"), n(u64::from(welcome.v))),1641         (t("max_inflight"), n(u64::from(welcome.max_inflight))),1642     ])1643 }1644 1645 fn welcome_from_value(v: &Value) -> Result<Welcome, BodyError> {1646     let entries = entries_of(v, "welcome")?;1647     let version = u32_at(entries, "v")?;1648     let max_inflight = u16_at(entries, "max_inflight")?;1649     Ok(Welcome {1650         v: version,1651         max_inflight,1652     })1653 }1654 1655 fn catalogue_to_value(catalogue: &Catalogue) -> Value {1656     let mut entries = vec![1657         (t("target"), target_value(&catalogue.target)),1658         (1659             t("models"),1660             Value::Array(catalogue.models.iter().map(model_value).collect()),1661         ),1662     ];1663     if let Some(runtime) = &catalogue.runtime {1664         entries.push((t("runtime"), runtime_value(runtime)));1665     }1666     if let Some(cache) = &catalogue.cache {1667         entries.push((t("cache"), cache_spec_value(cache)));1668     }1669     Value::map(entries)1670 }1671 1672 fn catalogue_from_value(v: &Value) -> Result<Catalogue, BodyError> {1673     let entries = entries_of(v, "catalogue")?;1674     let target = target_from(req(entries, "target")?)?;1675     let models = array_at(entries, "models")?1676         .iter()1677         .map(model_from)1678         .collect::<Result<Vec<Model>, BodyError>>()?;1679     let runtime = match get(entries, "runtime") {1680         None => None,1681         Some(value) => Some(runtime_from(value)?),1682     };1683     let cache = match get(entries, "cache") {1684         None => None,1685         Some(value) => Some(cache_spec_from(value)?),1686     };1687     Ok(Catalogue {1688         target,1689         models,1690         runtime,1691         cache,1692     })1693 }1694 1695 fn grant_to_value(grant: &Grant) -> Value {1696     Value::map([(1697         t("deps"),1698         Value::Array(grant.deps.iter().map(dependency_value).collect()),1699     )])1700 }1701 1702 fn grant_from_value(v: &Value) -> Result<Grant, BodyError> {1703     let entries = entries_of(v, "grant")?;1704     let deps = array_at(entries, "deps")?1705         .iter()1706         .map(dependency_from)1707         .collect::<Result<Vec<Dependency>, BodyError>>()?;1708     Ok(Grant { deps })1709 }1710 1711 fn ready_to_value(ready: &Ready) -> Value {1712     let mut entries = vec![(t("load_ms"), n(u64::from(ready.load_ms)))];1713     if let Some(fingerprint) = ready.cache_fingerprint {1714         entries.push((t("cache_fingerprint"), Value::Bytes(fingerprint.to_vec())));1715     }1716     Value::map(entries)1717 }1718 1719 fn ready_from_value(v: &Value) -> Result<Ready, BodyError> {1720     let entries = entries_of(v, "ready")?;1721     Ok(Ready {1722         load_ms: u32_at(entries, "load_ms")?,1723         cache_fingerprint: opt_key_at(entries, "cache_fingerprint")?,1724     })1725 }1726 1727 fn window_to_value(window: &Window) -> Value {1728     Value::map([(t("credit"), n(window.credit))])1729 }1730 1731 fn window_from_value(v: &Value) -> Result<Window, BodyError> {1732     let entries = entries_of(v, "window")?;1733     Ok(Window {1734         credit: u64_at(entries, "credit")?,1735     })1736 }1737 1738 fn tick_to_value(tick: &Tick) -> Value {1739     Value::map([(t("t"), n(tick.t))])1740 }1741 1742 fn tick_from_value(v: &Value) -> Result<Tick, BodyError> {1743     let entries = entries_of(v, "ping")?;1744     Ok(Tick {1745         t: u64_at(entries, "t")?,1746     })1747 }1748 1749 fn bye_to_value(bye: &Bye) -> Value {1750     Value::map([(t("reason"), t(bye.reason.as_str()))])1751 }1752 1753 fn bye_from_value(v: &Value) -> Result<Bye, BodyError> {1754     let entries = entries_of(v, "bye")?;1755     Ok(Bye {1756         reason: text_at(entries, "reason")?.to_string(),1757     })1758 }1759 1760 fn refusal_to_value(refusal: &Refusal) -> Value {1761     Value::map([1762         (t("code"), t(error_code_name(refusal.code))),1763         (1764             t("detail"),1765             match &refusal.detail {1766                 Some(detail) => t(detail.as_str()),1767                 None => Value::Null,1768             },1769         ),1770     ])1771 }1772 1773 fn refusal_from_value(v: &Value) -> Result<Refusal, BodyError> {1774     let entries = entries_of(v, "fatal")?;1775     let code = error_code_at(entries, "code")?;1776     let detail = opt_text_at(entries, "detail")?;1777     Ok(Refusal { code, detail })1778 }1779 1780 fn open_to_value(open: &Open) -> Value {1781     Value::map([1782         (t("request_id"), t(open.request_id.as_str())),1783         (t("model"), t(open.model.as_str())),1784         (t("capability"), t(open.capability.as_str())),1785         (t("credit"), n(open.credit)),1786         (t("budget_ms"), n(u64::from(open.budget_ms))),1787         (1788             t("parts"),1789             Value::Array(open.parts.iter().map(part_value).collect()),1790         ),1791         (t("params"), open.params.clone()),1792     ])1793 }1794 1795 fn open_from_value(v: &Value) -> Result<Open, BodyError> {1796     let entries = entries_of(v, "open")?;1797     let request_id = text_at(entries, "request_id")?.to_string();1798     let model = text_at(entries, "model")?.to_string();1799     let capability = text_at(entries, "capability")?.to_string();1800     let credit = u64_at(entries, "credit")?;1801     let budget_ms = u32_at(entries, "budget_ms")?;1802     let parts = array_at(entries, "parts")?1803         .iter()1804         .map(part_from)1805         .collect::<Result<Vec<Part>, BodyError>>()?;1806     let params = req(entries, "params")?.clone();1807     Ok(Open {1808         request_id,1809         model,1810         capability,1811         credit,1812         budget_ms,1813         parts,1814         params,1815     })1816 }1817 1818 fn accepted_to_value(accepted: &Accepted) -> Value {1819     Value::map([(1820         t("est_ms"),1821         match accepted.est_ms {1822             Some(ms) => n(u64::from(ms)),1823             None => Value::Null,1824         },1825     )])1826 }1827 1828 fn accepted_from_value(v: &Value) -> Result<Accepted, BodyError> {1829     let entries = entries_of(v, "accept")?;1830     Ok(Accepted {1831         est_ms: opt_u32_at(entries, "est_ms")?,1832     })1833 }1834 1835 fn event_to_value(event: &Event) -> Value {1836     Value::map([1837         (t("ch"), t(event.ch.as_str())),1838         (t("mime"), t(event.mime.as_str())),1839         (t("data"), Value::Bytes(event.data.clone())),1840     ])1841 }1842 1843 fn event_from_value(v: &Value) -> Result<Event, BodyError> {1844     let entries = entries_of(v, "event")?;1845     let ch = text_at(entries, "ch")?.to_string();1846     let mime = text_at(entries, "mime")?.to_string();1847     let data = bytes_at(entries, "data")?;1848     Ok(Event { ch, mime, data })1849 }1850 1851 fn done_to_value(done: &Done) -> Value {1852     let mut entries = vec![1853         (t("outcome"), t(outcome_name(done.outcome))),1854         (1855             t("artifacts"),1856             Value::Array(done.artifacts.iter().map(artifact_value).collect()),1857         ),1858         (1859             t("usage"),1860             Value::map(1861                 done.usage1862                     .iter()1863                     .map(|(k, v)| (t(k.as_str()), n(*v)))1864                     .collect::<Vec<(Value, Value)>>(),1865             ),1866         ),1867     ];1868     // `? meta` writes the key only when it is there.1869     if let Some(meta) = &done.meta {1870         entries.push((1871             t("meta"),1872             Value::map(1873                 meta.iter()1874                     .map(|(k, v)| (t(k.as_str()), v.clone()))1875                     .collect::<Vec<(Value, Value)>>(),1876             ),1877         ));1878     }1879     Value::map(entries)1880 }1881 1882 fn done_from_value(v: &Value) -> Result<Done, BodyError> {1883     let entries = entries_of(v, "done")?;1884     let outcome = outcome_at(entries, "outcome")?;1885     let artifacts = array_at(entries, "artifacts")?1886         .iter()1887         .map(artifact_from)1888         .collect::<Result<Vec<Artifact>, BodyError>>()?;1889     let usage = uint_map_at(entries, "usage")?;1890     let meta = match get(entries, "meta") {1891         None | Some(Value::Null) => None,1892         Some(m) => Some(any_map_from(m, "meta")?),1893     };1894     Ok(Done {1895         outcome,1896         artifacts,1897         usage,1898         meta,1899     })1900 }1901 1902 fn cancel_to_value(cancel: &CancelJob) -> Value {1903     Value::map([(t("reason"), t(cancel.reason.as_str()))])1904 }1905 1906 fn cancel_from_value(v: &Value) -> Result<CancelJob, BodyError> {1907     let entries = entries_of(v, "cancel")?;1908     Ok(CancelJob {1909         reason: text_at(entries, "reason")?.to_string(),1910     })1911 }1912 1913 fn cache_state_name(state: CacheStateKind) -> &'static str {1914     match state {1915         CacheStateKind::PrefixTruncatable => "prefix_truncatable",1916         CacheStateKind::CheckpointExact => "checkpoint_exact",1917     }1918 }1919 1920 fn cache_state_at(1921     entries: &[(Value, Value)],1922     key: &'static str,1923 ) -> Result<CacheStateKind, BodyError> {1924     Ok(1925         match literal_at(entries, key, &["prefix_truncatable", "checkpoint_exact"])? {1926             "prefix_truncatable" => CacheStateKind::PrefixTruncatable,1927             _ => CacheStateKind::CheckpointExact,1928         },1929     )1930 }1931 1932 fn cache_spec_value(spec: &CacheSpec) -> Value {1933     Value::map([1934         (t("codec_version"), n(spec.codec_version)),1935         (t("slots"), n(u64::from(spec.slots))),1936         (t("state_kind"), t(cache_state_name(spec.state_kind))),1937         (t("max_entry_bytes"), n(spec.max_entry_bytes)),1938         (t("local_ram_bytes"), n(spec.local_ram_bytes)),1939         (t("supports_save"), Value::Bool(spec.supports_save)),1940         (t("supports_restore"), Value::Bool(spec.supports_restore)),1941         (t("supports_erase"), Value::Bool(spec.supports_erase)),1942     ])1943 }1944 1945 fn cache_spec_from(v: &Value) -> Result<CacheSpec, BodyError> {1946     let entries = entries_of(v, "cache")?;1947     Ok(CacheSpec {1948         codec_version: u64_at(entries, "codec_version")?,1949         slots: u32_at(entries, "slots")?,1950         state_kind: cache_state_at(entries, "state_kind")?,1951         max_entry_bytes: u64_at(entries, "max_entry_bytes")?,1952         local_ram_bytes: u64_at(entries, "local_ram_bytes")?,1953         supports_save: bool_at(entries, "supports_save")?,1954         supports_restore: bool_at(entries, "supports_restore")?,1955         supports_erase: bool_at(entries, "supports_erase")?,1956     })1957 }1958 1959 impl CacheLookup {1960     fn to_value(&self) -> Value {1961         let mut entries = vec![1962             (t("req_id"), n(self.req_id)),1963             (1964                 t("keys"),1965                 Value::Array(1966                     self.keys1967                         .iter()1968                         .map(|key| Value::Bytes(key.to_vec()))1969                         .collect(),1970                 ),1971             ),1972         ];1973         if let Some(lineage) = self.lineage {1974             entries.push((t("lineage"), Value::Bytes(lineage.to_vec())));1975         }1976         Value::map(entries)1977     }1978 1979     fn from_value(v: &Value) -> Result<CacheLookup, BodyError> {1980         let entries = entries_of(v, "cache_lookup")?;1981         Ok(CacheLookup {1982             req_id: u64_at(entries, "req_id")?,1983             keys: keys_at(entries, "keys")?,1984             lineage: opt_key_at(entries, "lineage")?,1985         })1986     }1987 }1988 1989 impl CacheLookupRes {1990     fn to_value(&self) -> Value {1991         Value::map([1992             (t("req_id"), n(self.req_id)),1993             (1994                 t("hit"),1995                 match &self.hit {1996                     Some(hit) => cache_hit_value(hit),1997                     None => Value::Null,1998                 },1999             ),2000         ])2001     }2002 2003     fn from_value(v: &Value) -> Result<CacheLookupRes, BodyError> {2004         let entries = entries_of(v, "cache_lookup_res")?;2005         let hit = match get(entries, "hit") {2006             None | Some(Value::Null) => None,2007             Some(value) => Some(cache_hit_from(value)?),2008         };2009         Ok(CacheLookupRes {2010             req_id: u64_at(entries, "req_id")?,2011             hit,2012         })2013     }2014 }2015 2016 fn cache_hit_value(hit: &CacheHit) -> Value {2017     Value::map([2018         (t("key"), Value::Bytes(hit.key.to_vec())),2019         (t("lease_id"), n(hit.lease_id)),2020         (t("bytes"), n(hit.bytes)),2021         (t("crc32c"), n(u64::from(hit.crc32c))),2022         (t("token_count"), n(hit.token_count)),2023         (t("tier"), t(hit.tier.as_str())),2024         (t("fd"), n(u64::from(hit.fd))),2025     ])2026 }2027 2028 fn cache_hit_from(v: &Value) -> Result<CacheHit, BodyError> {2029     let entries = entries_of(v, "hit")?;2030     Ok(CacheHit {2031         key: key_at(entries, "key")?,2032         lease_id: u64_at(entries, "lease_id")?,2033         bytes: u64_at(entries, "bytes")?,2034         crc32c: u32_at(entries, "crc32c")?,2035         token_count: opt_uint(entries, "token_count")?.unwrap_or(0),2036         tier: text_at(entries, "tier")?.to_string(),2037         fd: u32_at(entries, "fd")?,2038     })2039 }2040 2041 #[allow(clippy::wrong_self_convention)]2042 impl CacheRelease {2043     fn to_value(&self) -> Value {2044         Value::map([2045             (t("lease_id"), n(self.lease_id)),2046             (t("ok"), Value::Bool(self.ok)),2047             (t("restore_ms"), n(u64::from(self.restore_ms))),2048             (t("abandoned"), Value::Bool(self.abandoned)),2049         ])2050     }2051 2052     fn from_value(v: &Value) -> Result<CacheRelease, BodyError> {2053         let entries = entries_of(v, "cache_release")?;2054         Ok(CacheRelease {2055             lease_id: u64_at(entries, "lease_id")?,2056             ok: bool_at(entries, "ok")?,2057             restore_ms: u32_at(entries, "restore_ms")?,2058             abandoned: bool_at(entries, "abandoned")?,2059         })2060     }2061 }2062 2063 fn cache_entry_kind_name(kind: CacheEntryKind) -> &'static str {2064     match kind {2065         CacheEntryKind::Tip => "tip",2066         CacheEntryKind::Anchor => "anchor",2067     }2068 }2069 2070 fn cache_entry_kind_at(2071     entries: &[(Value, Value)],2072     key: &'static str,2073 ) -> Result<CacheEntryKind, BodyError> {2074     Ok(match literal_at(entries, key, &["tip", "anchor"])? {2075         "tip" => CacheEntryKind::Tip,2076         _ => CacheEntryKind::Anchor,2077     })2078 }2079 2080 impl CacheReserve {2081     fn to_value(&self) -> Value {2082         let mut entries = vec![2083             (t("req_id"), n(self.req_id)),2084             (t("key"), Value::Bytes(self.key.to_vec())),2085             (t("kind"), t(cache_entry_kind_name(self.kind))),2086             (t("est_bytes"), n(self.est_bytes)),2087             (t("prefill_ms"), n(u64::from(self.prefill_ms))),2088             (t("token_count"), n(self.token_count)),2089             (t("pin"), Value::Bool(self.pin)),2090         ];2091         if let Some(lineage) = self.lineage {2092             entries.push((t("lineage"), Value::Bytes(lineage.to_vec())));2093         }2094         if let Some(supersedes) = self.supersedes {2095             entries.push((t("supersedes"), Value::Bytes(supersedes.to_vec())));2096         }2097         Value::map(entries)2098     }2099 2100     fn from_value(v: &Value) -> Result<CacheReserve, BodyError> {2101         let entries = entries_of(v, "cache_reserve")?;2102         Ok(CacheReserve {2103             req_id: u64_at(entries, "req_id")?,2104             key: key_at(entries, "key")?,2105             lineage: opt_key_at(entries, "lineage")?,2106             supersedes: opt_key_at(entries, "supersedes")?,2107             kind: cache_entry_kind_at(entries, "kind")?,2108             est_bytes: u64_at(entries, "est_bytes")?,2109             prefill_ms: u32_at(entries, "prefill_ms")?,2110             token_count: u64_at(entries, "token_count")?,2111             pin: bool_at(entries, "pin")?,2112         })2113     }2114 }2115 2116 impl CacheGrant {2117     fn to_value(&self) -> Value {2118         let mut entries = vec![2119             (t("req_id"), n(self.req_id)),2120             (2121                 t("grant"),2122                 match &self.grant {2123                     Some(grant) => cache_write_grant_value(grant),2124                     None => Value::Null,2125                 },2126             ),2127         ];2128         if let Some(reason) = &self.reason {2129             entries.push((t("reason"), t(reason.as_str())));2130         }2131         Value::map(entries)2132     }2133 2134     fn from_value(v: &Value) -> Result<CacheGrant, BodyError> {2135         let entries = entries_of(v, "cache_grant")?;2136         let grant = match get(entries, "grant") {2137             None | Some(Value::Null) => None,2138             Some(value) => Some(cache_write_grant_from(value)?),2139         };2140         Ok(CacheGrant {2141             req_id: u64_at(entries, "req_id")?,2142             grant,2143             reason: opt_text(entries, "reason")?.map(str::to_string),2144         })2145     }2146 }2147 2148 fn cache_write_grant_value(grant: &CacheWriteGrant) -> Value {2149     Value::map([2150         (t("lease_id"), n(grant.lease_id)),2151         (t("max_bytes"), n(grant.max_bytes)),2152         (t("tier"), t(grant.tier.as_str())),2153         (t("fd"), n(u64::from(grant.fd))),2154     ])2155 }2156 2157 fn cache_write_grant_from(v: &Value) -> Result<CacheWriteGrant, BodyError> {2158     let entries = entries_of(v, "grant")?;2159     Ok(CacheWriteGrant {2160         lease_id: u64_at(entries, "lease_id")?,2161         max_bytes: u64_at(entries, "max_bytes")?,2162         tier: text_at(entries, "tier")?.to_string(),2163         fd: u32_at(entries, "fd")?,2164     })2165 }2166 2167 #[allow(clippy::wrong_self_convention)]2168 impl CacheCommit {2169     fn to_value(&self) -> Value {2170         Value::map([2171             (t("lease_id"), n(self.lease_id)),2172             (t("ok"), Value::Bool(self.ok)),2173             (t("bytes"), n(self.bytes)),2174             (t("crc32c"), n(u64::from(self.crc32c))),2175             (t("token_count"), n(self.token_count)),2176             (t("save_ms"), n(u64::from(self.save_ms))),2177         ])2178     }2179 2180     fn from_value(v: &Value) -> Result<CacheCommit, BodyError> {2181         let entries = entries_of(v, "cache_commit")?;2182         Ok(CacheCommit {2183             lease_id: u64_at(entries, "lease_id")?,2184             ok: bool_at(entries, "ok")?,2185             bytes: u64_at(entries, "bytes")?,2186             crc32c: u32_at(entries, "crc32c")?,2187             token_count: u64_at(entries, "token_count")?,2188             save_ms: u32_at(entries, "save_ms")?,2189         })2190     }2191 }2192 2193 #[allow(clippy::wrong_self_convention)]2194 impl CacheFlush {2195     fn to_value(&self) -> Value {2196         Value::map([2197             (t("req_id"), n(self.req_id)),2198             (t("budget_ms"), n(u64::from(self.budget_ms))),2199         ])2200     }2201 2202     fn from_value(v: &Value) -> Result<CacheFlush, BodyError> {2203         let entries = entries_of(v, "cache_flush")?;2204         Ok(CacheFlush {2205             req_id: u64_at(entries, "req_id")?,2206             budget_ms: u32_at(entries, "budget_ms")?,2207         })2208     }2209 }2210 2211 #[allow(clippy::wrong_self_convention)]2212 impl CacheFlushed {2213     fn to_value(&self) -> Value {2214         Value::map([2215             (t("req_id"), n(self.req_id)),2216             (t("saved"), n(u64::from(self.saved))),2217             (t("skipped"), n(u64::from(self.skipped))),2218             (t("dirty_remaining"), n(u64::from(self.dirty_remaining))),2219         ])2220     }2221 2222     fn from_value(v: &Value) -> Result<CacheFlushed, BodyError> {2223         let entries = entries_of(v, "cache_flushed")?;2224         Ok(CacheFlushed {2225             req_id: u64_at(entries, "req_id")?,2226             saved: u32_at(entries, "saved")?,2227             skipped: u32_at(entries, "skipped")?,2228             dirty_remaining: u32_at(entries, "dirty_remaining")?,2229         })2230     }2231 }2232 2233 fn cache_lookup_to_value(body: &CacheLookup) -> Value {2234     body.to_value()2235 }2236 2237 fn cache_lookup_res_to_value(body: &CacheLookupRes) -> Value {2238     body.to_value()2239 }2240 2241 fn cache_release_to_value(body: &CacheRelease) -> Value {2242     body.to_value()2243 }2244 2245 fn cache_reserve_to_value(body: &CacheReserve) -> Value {2246     body.to_value()2247 }2248 2249 fn cache_grant_to_value(body: &CacheGrant) -> Value {2250     body.to_value()2251 }2252 2253 fn cache_commit_to_value(body: &CacheCommit) -> Value {2254     body.to_value()2255 }2256 2257 fn cache_flush_to_value(body: &CacheFlush) -> Value {2258     body.to_value()2259 }2260 2261 fn cache_flushed_to_value(body: &CacheFlushed) -> Value {2262     body.to_value()2263 }