Skip to main content

kute_protocol/
lib.rs

1//! Vocabulary exchange between two KUTE peers (development directive v0.2,
2//! R9). Before one side sends encoded data, both must hold the same
3//! vocabulary, identified by its content digest. The protocol lets them
4//! find out, transfer the vocabulary if needed, extend it together, and
5//! check that what was sent is what was decoded.
6//!
7//! [`Peer`] is the state machine: it takes a message and returns replies,
8//! and does no I/O. [`Session`] drives the initiating side over a
9//! [`Transport`]. [`Framed`] is a transport over any byte stream.
10//!
11//! There is no encryption and no authentication here. A peer treats
12//! everything it receives as untrusted: vocabularies are validated and
13//! their digests recomputed, sizes are bounded before allocation, and
14//! decoding is bounded before output is produced.
15
16use kute::{Engine, KuteError, Result, TokenPayload, TokenSequence, Tokenizer, UnknownPolicy, Version, Vocabulary};
17use serde::{Deserialize, Serialize};
18use sha2::{Digest, Sha256};
19use std::collections::BTreeMap;
20use std::io::{Read, Write};
21
22#[cfg(feature = "tls")]
23pub mod tls;
24
25/// Version 2 added the evolution rule to `CAPABILITIES` and to
26/// `SYMBOL_PROPOSE`, the `UNSUPPORTED_RULE` and `BUSY` errors, and the
27/// delivery contract for repeated message ids. A version 1 peer is refused
28/// at `HELLO`.
29pub const PROTOCOL_VERSION: u32 = 2;
30/// The rule by which this build derives an evolved vocabulary. Two peers
31/// that name different rules would derive different children from the same
32/// proposal, so a proposal is only taken under this exact name.
33pub const EVOLUTION_RULE: &str = kute::bpe::sequence::EVOLVE_GENERATOR;
34/// Default and largest frame a peer will read.
35pub const DEFAULT_MAX_FRAME: u64 = 64 * 1024 * 1024;
36
37/// What identifies a vocabulary to the other side.
38#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
39pub struct VocabRef {
40    pub id: String,
41    pub version: String,
42    pub digest: String,
43    pub algorithm: String,
44    pub tokens: u64,
45}
46
47impl VocabRef {
48    pub fn of(vocabulary: &Vocabulary) -> Result<Self> {
49        Ok(Self {
50            id: vocabulary.id().to_string(),
51            version: vocabulary.version().to_string(),
52            digest: vocabulary.digest()?,
53            algorithm: vocabulary.manifest.algorithm.clone(),
54            tokens: vocabulary.len() as u64,
55        })
56    }
57}
58
59#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
60#[serde(rename_all = "snake_case")]
61pub enum ErrorCode {
62    /// A message arrived before the handshake allowed it.
63    OutOfOrder,
64    UnsupportedProtocol,
65    UnsupportedAlgorithm,
66    /// Same id and version as a vocabulary the peer holds, different content.
67    VocabularyConflict,
68    UnknownVocabulary,
69    /// The vocabulary, message or proposal failed validation.
70    Invalid,
71    /// The peer's policy does not allow the request.
72    Refused,
73    TooLarge,
74    /// The proposal names an evolution rule this peer does not implement.
75    UnsupportedRule,
76    /// The peer's inbox is full; nothing was delivered. Send again later.
77    Busy,
78}
79
80#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
81#[serde(tag = "type", rename_all = "SCREAMING_SNAKE_CASE")]
82pub enum Message {
83    Hello { protocol: u32, peer: String, software: String },
84    Capabilities {
85        algorithms: Vec<String>,
86        adapters: Vec<String>,
87        max_frame_bytes: u64,
88        accepts_vocabularies: bool,
89        accepts_proposals: bool,
90        /// Evolution rules this peer can apply to a proposal.
91        #[serde(default)]
92        evolution_rules: Vec<String>,
93        /// KVF versions this peer reads.
94        #[serde(default)]
95        kvf_versions: Vec<String>,
96    },
97    /// "I intend to use this vocabulary."
98    VocabAnnounce { vocabulary: VocabRef },
99    /// "I do not have it; send it."
100    VocabRequest { digest: String },
101    /// The vocabulary as a KVF document. Not in the directive's list; it is
102    /// the answer to `VOCAB_REQUEST`.
103    VocabData {
104        digest: String,
105        #[serde(with = "kute::b64")]
106        kvf: Vec<u8>,
107    },
108    /// "I hold a validated vocabulary with this digest."
109    VocabAccept { digest: String },
110    /// "Is this symbol sequence a token of that vocabulary?"
111    SymbolQuery { digest: String, symbols: Vec<String> },
112    /// Answer to `SYMBOL_QUERY`.
113    SymbolInfo { digest: String, token_id: Option<u32>, content_hash: String },
114    /// "Extend that vocabulary with these symbols and sequences, as this
115    /// version." Accepted with `VOCAB_ACCEPT` naming the new digest.
116    /// `rule` names the derivation the proposer used; a peer that does not
117    /// implement exactly that rule refuses before deriving anything.
118    SymbolPropose {
119        digest: String,
120        additions: Vec<Vec<String>>,
121        version: String,
122        #[serde(default)]
123        rule: String,
124    },
125    /// "Re-encode this sequence under another vocabulary you hold."
126    Translate {
127        id: u64,
128        #[serde(with = "kute::b64")]
129        container: Vec<u8>,
130        to_digest: String,
131    },
132    /// A `.kute` container.
133    EncodedMessage {
134        id: u64,
135        #[serde(with = "kute::b64")]
136        container: Vec<u8>,
137    },
138    /// Receipt for an encoded message: how much it decoded to, and the
139    /// SHA-256 of the decoded bytes.
140    Ack { id: u64, units: u64, sha256: String },
141    Error { code: ErrorCode, message: String },
142}
143
144fn refuse(code: ErrorCode, message: impl Into<String>) -> Vec<Message> {
145    vec![Message::Error { code, message: message.into() }]
146}
147
148/// What a peer is willing to do for the other side.
149///
150/// The default takes nothing new from the other side (no vocabularies, no
151/// proposals) and gives nothing away (no vocabulary files, no answers
152/// about symbols, no translation). It delivers messages encoded under a
153/// vocabulary this peer holds, and that is all. Everything else has to be
154/// switched on.
155#[derive(Clone, Debug, PartialEq, Eq)]
156pub struct Policy {
157    /// Send a held vocabulary's file to the other side when it asks.
158    pub give_vocabularies: bool,
159    /// Say whether a held vocabulary has a token for given symbols.
160    pub answer_queries: bool,
161    /// Re-encode the other side's sequences under another held vocabulary.
162    pub translate: bool,
163    /// The held vocabularies the other side may use at all, by digest;
164    /// `None` is every one held. One that is held but not listed is
165    /// answered as if it were not held. A vocabulary the other side adds
166    /// itself (when it may) joins the list.
167    pub vocabularies: Option<std::collections::BTreeSet<String>>,
168    /// Refuse a container that declares more tokens than this, before its
169    /// ids are decompressed. Four bytes of memory per token.
170    pub max_message_tokens: u64,
171    /// Take vocabularies it does not have from the other side.
172    pub accept_vocabularies: bool,
173    /// Extend a held vocabulary when the other side proposes it.
174    pub accept_proposals: bool,
175    pub max_frame_bytes: u64,
176    pub max_vocabulary_tokens: u64,
177    /// Refuse a message that would decode to more than this.
178    pub max_decoded_units: u64,
179    /// The most vocabularies this peer will hold, counting its own. The
180    /// other side cannot add one past this.
181    pub max_held_vocabularies: u64,
182    /// The most tokens over all held vocabularies, counting its own.
183    pub max_held_tokens: u64,
184    /// Delivered messages kept until `take_inbox`. When full, a message is
185    /// answered `BUSY` and not delivered.
186    pub max_inbox_messages: u64,
187    /// Bytes kept until `take_inbox`: for each message its decoded bytes,
188    /// its token ids at four bytes each, and its container.
189    pub max_inbox_bytes: u64,
190    /// How many of the latest message ids are remembered, so that a repeat
191    /// gets its first receipt again instead of a second delivery.
192    pub replay_window: u64,
193}
194
195impl Default for Policy {
196    fn default() -> Self {
197        Self {
198            give_vocabularies: false,
199            answer_queries: false,
200            translate: false,
201            vocabularies: None,
202            max_message_tokens: 16 * 1024 * 1024,
203            accept_vocabularies: false,
204            accept_proposals: false,
205            max_frame_bytes: DEFAULT_MAX_FRAME,
206            max_vocabulary_tokens: 1_000_000,
207            max_decoded_units: 256 * 1024 * 1024,
208            max_held_vocabularies: 64,
209            max_held_tokens: 4_000_000,
210            max_inbox_messages: 1024,
211            max_inbox_bytes: 256 * 1024 * 1024,
212            replay_window: 1024,
213        }
214    }
215}
216
217/// A message this peer received and decoded.
218#[derive(Clone, Debug, PartialEq)]
219pub struct Delivered {
220    pub id: u64,
221    pub sequence: TokenSequence,
222    /// The decoded bytes, through the vocabulary's adapter.
223    pub bytes: Vec<u8>,
224}
225
226struct Held {
227    vocabulary: Vocabulary,
228    tokenizer: Box<dyn Tokenizer>,
229}
230
231#[derive(Clone, Copy, PartialEq, Eq)]
232enum Stage {
233    New,
234    Greeted,
235    Ready,
236}
237
238/// A test a vocabulary must pass before it is taken from the other side.
239/// It is given the vocabulary after its digest has been recomputed and
240/// matched; an `Err` is the reason it is refused. The protocol does no
241/// cryptography of its own: a caller that wants signatures checks them here.
242pub type VocabularyCheck = Box<dyn Fn(&Vocabulary) -> std::result::Result<(), String> + Send>;
243
244/// One side of the protocol.
245pub struct Peer {
246    name: String,
247    engine: Engine,
248    policy: Policy,
249    check: Option<VocabularyCheck>,
250    held: BTreeMap<String, Held>,
251    stage: Stage,
252    wanted: Option<VocabRef>,
253    inbox: Vec<Delivered>,
254    inbox_bytes: u64,
255    /// The latest message ids: id, SHA-256 of the container, receipt sent.
256    seen: std::collections::VecDeque<(u64, String, Message)>,
257}
258
259pub fn sha256_hex(bytes: &[u8]) -> String {
260    kute::hex(&Sha256::digest(bytes))
261}
262
263impl Peer {
264    pub fn new(name: &str, engine: Engine, policy: Policy) -> Self {
265        Self {
266            name: name.to_string(),
267            engine,
268            policy,
269            check: None,
270            held: BTreeMap::new(),
271            stage: Stage::New,
272            wanted: None,
273            inbox: Vec::new(),
274            inbox_bytes: 0,
275            seen: Default::default(),
276        }
277    }
278
279    /// Take a vocabulary from the other side only if `check` passes it.
280    /// Vocabularies this side adds itself are not checked: their holder
281    /// chose them. While a check is set, proposals are refused, since a
282    /// vocabulary derived here from a proposal is one nobody has vouched
283    /// for.
284    pub fn require_vocabulary_check(&mut self, check: VocabularyCheck) {
285        self.check = Some(check);
286    }
287
288    /// Hold `vocabulary`. Returns its digest.
289    pub fn add_vocabulary(&mut self, vocabulary: Vocabulary) -> Result<String> {
290        vocabulary.validate()?;
291        let digest = vocabulary.compute_digest()?;
292        if let Some(other) = self.held.values().find(|h| h.vocabulary.id() == vocabulary.id() && h.vocabulary.version() == vocabulary.version()) {
293            if other.vocabulary.digest()? != digest {
294                return Err(KuteError::VocabularyMismatch(format!(
295                    "a different vocabulary is already held as {} {}",
296                    vocabulary.id(),
297                    vocabulary.version()
298                )));
299            }
300        }
301        let tokenizer = self.engine.tokenizer(vocabulary.clone())?;
302        let vocabulary = tokenizer.vocabulary().cloned().unwrap_or(vocabulary);
303        self.held.insert(digest.clone(), Held { vocabulary, tokenizer });
304        Ok(digest)
305    }
306
307    pub fn vocabulary(&self, digest: &str) -> Option<&Vocabulary> {
308        self.held.get(digest).map(|h| &h.vocabulary)
309    }
310
311    pub fn digests(&self) -> Vec<String> {
312        self.held.keys().cloned().collect()
313    }
314
315    /// Messages received and decoded since the last call.
316    pub fn take_inbox(&mut self) -> Vec<Delivered> {
317        self.inbox_bytes = 0;
318        std::mem::take(&mut self.inbox)
319    }
320
321    /// Whether the other side may add a vocabulary of `tokens` tokens: the
322    /// refusal if it would pass what this peer is willing to hold in all.
323    fn over_budget(&self, tokens: u64) -> Option<Vec<Message>> {
324        if self.held.len() as u64 >= self.policy.max_held_vocabularies {
325            return Some(refuse(ErrorCode::TooLarge, format!("this peer already holds {} vocabularies, its limit", self.held.len())));
326        }
327        let held: u64 = self.held.values().map(|h| h.vocabulary.len() as u64).sum();
328        if held.saturating_add(tokens) > self.policy.max_held_tokens {
329            return Some(refuse(
330                ErrorCode::TooLarge,
331                format!("this peer holds {held} tokens and takes at most {} in all", self.policy.max_held_tokens),
332            ));
333        }
334        None
335    }
336
337    pub fn engine(&self) -> &Engine {
338        &self.engine
339    }
340
341    fn hold(&self, digest: &str) -> Result<&Held> {
342        self.held.get(digest).ok_or_else(|| KuteError::VocabularyMismatch(format!("no vocabulary with digest {digest} is held")))
343    }
344
345    /// Whether the other side may use the vocabulary with this digest.
346    fn sees(&self, digest: &str) -> bool {
347        self.policy.vocabularies.as_ref().is_none_or(|listed| listed.contains(digest))
348    }
349
350    /// A held vocabulary, for the other side: one it may not use is
351    /// answered exactly as one that is not held.
352    fn usable(&self, digest: &str) -> Result<&Held> {
353        if !self.sees(digest) {
354            return Err(KuteError::VocabularyMismatch(format!("no vocabulary with digest {digest} is held")));
355        }
356        self.hold(digest)
357    }
358
359    /// A vocabulary the other side added is one it may use.
360    fn show(&mut self, digest: &str) {
361        if let Some(listed) = &mut self.policy.vocabularies {
362            listed.insert(digest.to_string());
363        }
364    }
365
366    /// The most tokens a container from the other side may declare. Every
367    /// token decodes to at least one unit, so the unit limit bounds it too.
368    fn token_limit(&self) -> u64 {
369        self.policy.max_message_tokens.min(self.policy.max_decoded_units)
370    }
371
372    pub fn hello(&self) -> Message {
373        Message::Hello { protocol: PROTOCOL_VERSION, peer: self.name.clone(), software: format!("kute {}", kute::KUTE_VERSION) }
374    }
375
376    pub fn capabilities(&self) -> Message {
377        Message::Capabilities {
378            algorithms: self.engine.registry().algorithm_names(),
379            adapters: self.engine.registry().adapter_names(),
380            max_frame_bytes: self.policy.max_frame_bytes,
381            accepts_vocabularies: self.policy.accept_vocabularies,
382            accepts_proposals: self.policy.accept_proposals,
383            evolution_rules: vec![EVOLUTION_RULE.to_string()],
384            kvf_versions: vec![kute::KVF_VERSION.to_string()],
385        }
386    }
387
388    /// Encode `raw` under a held vocabulary and wrap it as a message.
389    /// Returns the message and the SHA-256 the receiver's `ACK` must carry.
390    pub fn encode_message(&self, id: u64, digest: &str, raw: &[u8], policy: UnknownPolicy) -> Result<(Message, String)> {
391        let held = self.hold(digest)?;
392        let sequence = self.engine.encode_raw_open(held.tokenizer.as_ref(), raw, policy)?;
393        let expected = sha256_hex(&self.engine.decode_raw(held.tokenizer.as_ref(), &sequence)?);
394        Ok((Message::EncodedMessage { id, container: sequence.to_bytes_compressed()? }, expected))
395    }
396
397    /// Apply an evolution step to a held vocabulary and hold the result.
398    pub fn evolve(&mut self, digest: &str, additions: &[Vec<String>], version: &str) -> Result<String> {
399        let version = Version::parse(version).map_err(|e| KuteError::InvalidIdentifier(format!("version {version:?}: {e}")))?;
400        let child = kute::bpe::sequence::evolve(&self.hold(digest)?.vocabulary, additions, version)?;
401        self.add_vocabulary(child)
402    }
403
404    /// Re-encode a sequence under another held vocabulary. Symbols the
405    /// target lacks are escaped, so nothing is lost.
406    pub fn translate(&self, sequence: &TokenSequence, to_digest: &str) -> Result<TokenSequence> {
407        let from = self.hold(&sequence.vocabulary_digest)?;
408        let to = self.hold(to_digest)?;
409        let units = kute::decoded_units(&from.vocabulary, sequence)?;
410        if units > self.policy.max_decoded_units {
411            return Err(KuteError::LimitExceeded(format!("the sequence decodes to {units} units")));
412        }
413        // Symbols can be a kilobyte each, so their count is not their size.
414        // The translation goes back in one frame, so a frame bounds it.
415        let bytes = kute::decoded_bytes_at_least(&from.vocabulary, sequence)?;
416        if bytes > self.policy.max_frame_bytes {
417            return Err(KuteError::LimitExceeded(format!("the sequence decodes to at least {bytes} bytes; a frame holds {}", self.policy.max_frame_bytes)));
418        }
419        to.tokenizer.encode_open(&from.tokenizer.decode(sequence)?, UnknownPolicy::Escape)
420    }
421
422    /// Handle one message from the other side. Never fails: anything wrong
423    /// is answered with an `ERROR` message.
424    pub fn handle(&mut self, message: Message) -> Vec<Message> {
425        match (self.stage, &message) {
426            (Stage::New, Message::Hello { protocol, .. }) => {
427                if *protocol != PROTOCOL_VERSION {
428                    return refuse(ErrorCode::UnsupportedProtocol, format!("this peer speaks protocol {PROTOCOL_VERSION}, not {protocol}"));
429                }
430                self.stage = Stage::Greeted;
431                return vec![self.hello()];
432            }
433            (Stage::Greeted, Message::Capabilities { .. }) => {
434                self.stage = Stage::Ready;
435                return vec![self.capabilities()];
436            }
437            (Stage::Ready, Message::Hello { .. } | Message::Capabilities { .. }) | (Stage::New | Stage::Greeted, _) => {
438                return refuse(ErrorCode::OutOfOrder, "expected HELLO, then CAPABILITIES, before anything else");
439            }
440            (Stage::Ready, _) => {}
441        }
442        match self.respond(message) {
443            Ok(replies) => replies,
444            Err(e) => {
445                let code = match e {
446                    KuteError::LimitExceeded(_) => ErrorCode::TooLarge,
447                    KuteError::VocabularyMismatch(_) => ErrorCode::UnknownVocabulary,
448                    _ => ErrorCode::Invalid,
449                };
450                refuse(code, e.to_string())
451            }
452        }
453    }
454
455    fn respond(&mut self, message: Message) -> Result<Vec<Message>> {
456        match message {
457            Message::VocabAnnounce { vocabulary } => {
458                // A vocabulary that is held but not this peer's to use is
459                // treated from here on exactly as one that is not held: the
460                // same checks, the same request for its content. If the
461                // peer then sends it, it had the content already, and it
462                // becomes one it may use.
463                if self.held.contains_key(&vocabulary.digest) && self.sees(&vocabulary.digest) {
464                    return Ok(vec![Message::VocabAccept { digest: vocabulary.digest }]);
465                }
466                if self.held.values().any(|h| {
467                    h.vocabulary.id().as_str() == vocabulary.id && h.vocabulary.version().to_string() == vocabulary.version && h.vocabulary.integrity.as_ref().is_none_or(|i| i.digest != vocabulary.digest)
468                }) {
469                    // This does tell a peer that the id and version are
470                    // taken, whether or not it may use the holder. Two
471                    // vocabularies cannot share them, so the refusal cannot
472                    // be avoided, only worded the same in both cases.
473                    return Ok(refuse(
474                        ErrorCode::VocabularyConflict,
475                        format!("{} {} is held here with different content", vocabulary.id, vocabulary.version),
476                    ));
477                }
478                if !self.engine.registry().algorithm_names().contains(&vocabulary.algorithm) {
479                    return Ok(refuse(ErrorCode::UnsupportedAlgorithm, format!("algorithm {:?} is not available here", vocabulary.algorithm)));
480                }
481                if !self.policy.accept_vocabularies {
482                    return Ok(refuse(ErrorCode::Refused, "this peer does not take vocabularies from the other side"));
483                }
484                if vocabulary.tokens > self.policy.max_vocabulary_tokens {
485                    return Ok(refuse(ErrorCode::TooLarge, format!("vocabularies above {} tokens are not taken", self.policy.max_vocabulary_tokens)));
486                }
487                if let Some(refusal) = self.over_budget(vocabulary.tokens) {
488                    return Ok(refusal);
489                }
490                let digest = vocabulary.digest.clone();
491                self.wanted = Some(vocabulary);
492                Ok(vec![Message::VocabRequest { digest }])
493            }
494            Message::VocabRequest { digest } => {
495                if !self.policy.give_vocabularies {
496                    return Ok(refuse(ErrorCode::Refused, "this peer does not give out vocabularies"));
497                }
498                let kvf = kute::vocab::to_vec(&self.usable(&digest)?.vocabulary)?;
499                Ok(vec![Message::VocabData { digest, kvf }])
500            }
501            Message::VocabData { digest, kvf } => {
502                let Some(wanted) = self.wanted.take().filter(|w| w.digest == digest) else {
503                    return Ok(refuse(ErrorCode::OutOfOrder, "vocabulary data that was not requested"));
504                };
505                let vocabulary = kute::vocab::from_slice(&kvf)?;
506                // The digest is recomputed from content; the one in the file
507                // and the one announced are both only claims.
508                if vocabulary.compute_digest()? != digest || VocabRef::of(&vocabulary)? != wanted {
509                    return Ok(refuse(ErrorCode::Invalid, "the vocabulary sent is not the one announced"));
510                }
511                if vocabulary.len() as u64 > self.policy.max_vocabulary_tokens {
512                    return Ok(refuse(ErrorCode::TooLarge, "vocabulary exceeds the token limit"));
513                }
514                // Again, on what was sent and not on what was announced.
515                if let Some(refusal) = self.over_budget(vocabulary.len() as u64) {
516                    return Ok(refusal);
517                }
518                if let Some(check) = &self.check {
519                    if let Err(why) = check(&vocabulary) {
520                        return Ok(refuse(ErrorCode::Refused, format!("the vocabulary is not taken: {why}")));
521                    }
522                }
523                let report = self.engine.verify(&vocabulary)?;
524                if !report.ok() {
525                    return Ok(refuse(ErrorCode::Invalid, format!("the vocabulary fails its own test vectors: {}", report.failures.join("; "))));
526                }
527                let digest = self.add_vocabulary(vocabulary)?;
528                self.show(&digest);
529                Ok(vec![Message::VocabAccept { digest }])
530            }
531            Message::SymbolQuery { digest, symbols } => {
532                if !self.policy.answer_queries {
533                    return Ok(refuse(ErrorCode::Refused, "this peer does not answer questions about its vocabularies"));
534                }
535                let payload = TokenPayload::Symbols(symbols);
536                let token_id = self.usable(&digest)?.vocabulary.tokens.iter().find(|t| t.payload == payload).map(|t| t.id);
537                Ok(vec![Message::SymbolInfo { digest, token_id, content_hash: payload.content_hash() }])
538            }
539            Message::SymbolPropose { digest, additions, version, rule } => {
540                if !self.policy.accept_proposals {
541                    return Ok(refuse(ErrorCode::Refused, "this peer does not accept vocabulary proposals"));
542                }
543                if self.check.is_some() {
544                    return Ok(refuse(ErrorCode::Refused, "this peer takes only vocabularies that pass its check, and one derived from a proposal has nobody vouching for it"));
545                }
546                // Before anything is derived: under another rule the child
547                // would differ, and the two sides would part silently.
548                if rule != EVOLUTION_RULE {
549                    return Ok(refuse(
550                        ErrorCode::UnsupportedRule,
551                        format!("the proposal uses evolution rule {rule:?}; this peer implements {EVOLUTION_RULE:?}"),
552                    ));
553                }
554                // An addition of n symbols adds at most n symbols and n merges.
555                let most: u64 = additions.iter().map(|a| 2 * a.len() as u64).sum();
556                let parent = self.usable(&digest)?.vocabulary.len() as u64;
557                if parent.saturating_add(most) > self.policy.max_vocabulary_tokens {
558                    return Ok(refuse(ErrorCode::TooLarge, "the proposal would pass the vocabulary token limit"));
559                }
560                if let Some(refusal) = self.over_budget(parent.saturating_add(most)) {
561                    return Ok(refusal);
562                }
563                // The child is derived even when its id and version are
564                // already held: a repeat of the same proposal has to be
565                // accepted again, and only the derivation tells a repeat
566                // from a conflict. Its cost is bounded by the checks above.
567                let digest = match self.evolve(&digest, &additions, &version) {
568                    Ok(digest) => digest,
569                    Err(KuteError::VocabularyMismatch(why)) => return Ok(refuse(ErrorCode::VocabularyConflict, why)),
570                    Err(e) => return Err(e),
571                };
572                self.show(&digest);
573                Ok(vec![Message::VocabAccept { digest }])
574            }
575            Message::Translate { id, container, to_digest } => {
576                if !self.policy.translate {
577                    return Ok(refuse(ErrorCode::Refused, "this peer does not translate for the other side"));
578                }
579                // A container that declares more tokens than the limit is
580                // refused before its ids are decompressed.
581                let sequence = TokenSequence::from_bytes_bounded(&container, self.token_limit())?;
582                self.usable(&sequence.vocabulary_digest)?;
583                self.usable(&to_digest)?;
584                let translated = self.translate(&sequence, &to_digest)?;
585                Ok(vec![Message::EncodedMessage { id, container: translated.to_bytes_compressed()? }])
586            }
587            Message::EncodedMessage { id, container } => {
588                // A repeat of a delivered message gets its receipt again and
589                // is not delivered twice; the same id on other content is an
590                // error. Ids older than the window are not remembered.
591                let fingerprint = sha256_hex(&container);
592                if let Some((_, first, receipt)) = self.seen.iter().find(|(seen, _, _)| *seen == id) {
593                    return Ok(if *first == fingerprint {
594                        vec![receipt.clone()]
595                    } else {
596                        refuse(ErrorCode::Invalid, format!("message id {id} was already used for different content"))
597                    });
598                }
599                if self.inbox.len() as u64 >= self.policy.max_inbox_messages {
600                    return Ok(refuse(ErrorCode::Busy, format!("the inbox holds {} messages, its limit", self.inbox.len())));
601                }
602                let sequence = TokenSequence::from_bytes_bounded(&container, self.token_limit())?;
603                let held = self.usable(&sequence.vocabulary_digest)?;
604                let units = kute::decoded_units(&held.vocabulary, &sequence)?;
605                let bytes = self.engine.decode_raw_within(held.tokenizer.as_ref(), &sequence, self.policy.max_decoded_units, self.policy.max_inbox_bytes)?;
606                // What the inbox keeps for this message: the decoded bytes
607                // and the sequence (ids, and the escapes the container holds).
608                let kept = (bytes.len() as u64).saturating_add(4 * sequence.ids.len() as u64).saturating_add(container.len() as u64);
609                if self.inbox_bytes.saturating_add(kept) > self.policy.max_inbox_bytes {
610                    return Ok(refuse(ErrorCode::Busy, format!("the inbox holds {} bytes and takes at most {}", self.inbox_bytes, self.policy.max_inbox_bytes)));
611                }
612                let receipt = Message::Ack { id, units, sha256: sha256_hex(&bytes) };
613                self.inbox_bytes += kept;
614                self.inbox.push(Delivered { id, sequence, bytes });
615                self.seen.push_back((id, fingerprint, receipt.clone()));
616                while self.seen.len() as u64 > self.policy.replay_window {
617                    self.seen.pop_front();
618                }
619                Ok(vec![receipt])
620            }
621            Message::VocabAccept { .. } | Message::SymbolInfo { .. } | Message::Ack { .. } | Message::Error { .. } => {
622                Ok(refuse(ErrorCode::OutOfOrder, "a reply arrived where a request was expected"))
623            }
624            Message::Hello { .. } | Message::Capabilities { .. } => Ok(refuse(ErrorCode::OutOfOrder, "the handshake is already complete")),
625        }
626    }
627}
628
629/// Something that carries messages to the other peer and back.
630pub trait Transport {
631    fn send(&mut self, message: &Message) -> Result<()>;
632    /// The next message, or `None` when the other side has closed.
633    fn recv(&mut self) -> Result<Option<Message>>;
634}
635
636/// Messages over a byte stream: a four-byte little-endian length, then that
637/// many bytes of JSON.
638pub struct Framed<S: Read + Write> {
639    stream: S,
640    max_frame: u64,
641}
642
643impl<S: Read + Write> Framed<S> {
644    pub fn new(stream: S, max_frame: u64) -> Self {
645        Self { stream, max_frame: max_frame.min(DEFAULT_MAX_FRAME) }
646    }
647}
648
649impl<S: Read + Write> Transport for Framed<S> {
650    fn send(&mut self, message: &Message) -> Result<()> {
651        let body = serde_json::to_vec(message)?;
652        if body.len() as u64 > self.max_frame {
653            return Err(KuteError::LimitExceeded(format!("message of {} bytes exceeds the frame limit of {}", body.len(), self.max_frame)));
654        }
655        self.stream.write_all(&(body.len() as u32).to_le_bytes())?;
656        self.stream.write_all(&body)?;
657        self.stream.flush()?;
658        Ok(())
659    }
660
661    fn recv(&mut self) -> Result<Option<Message>> {
662        let mut length = [0u8; 4];
663        let mut got = 0;
664        while got < 4 {
665            match self.stream.read(&mut length[got..]) {
666                Ok(0) if got == 0 => return Ok(None),
667                Ok(0) => return Err(KuteError::InvalidInput("the stream ended inside a frame header".into())),
668                Ok(n) => got += n,
669                Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}
670                Err(e) => return Err(e.into()),
671            }
672        }
673        let length = u32::from_le_bytes(length) as u64;
674        if length > self.max_frame {
675            return Err(KuteError::LimitExceeded(format!("incoming frame of {length} bytes exceeds the limit of {}", self.max_frame)));
676        }
677        // Read through `take` so a forged length cannot make us allocate
678        // more than actually arrives.
679        let mut body = Vec::new();
680        (&mut self.stream).take(length).read_to_end(&mut body)?;
681        if body.len() as u64 != length {
682            return Err(KuteError::InvalidInput("the stream ended inside a frame".into()));
683        }
684        serde_json::from_slice(&body).map(Some).map_err(|e| KuteError::InvalidInput(format!("not a protocol message: {e}")))
685    }
686}
687
688/// The other side's answer to `CAPABILITIES`.
689#[derive(Clone, Debug, PartialEq, Eq)]
690pub struct Remote {
691    pub peer: String,
692    pub software: String,
693    pub algorithms: Vec<String>,
694    pub accepts_vocabularies: bool,
695    pub accepts_proposals: bool,
696    pub evolution_rules: Vec<String>,
697}
698
699fn peer_error(code: ErrorCode, message: String) -> KuteError {
700    KuteError::Backend(format!("the peer answered {code:?}: {message}"))
701}
702
703/// A peer together with its connection.
704pub struct Session<T: Transport> {
705    pub peer: Peer,
706    transport: T,
707    next_id: u64,
708    remote: Option<Remote>,
709}
710
711impl<T: Transport> Session<T> {
712    pub fn new(peer: Peer, transport: T) -> Self {
713        Self { peer, transport, next_id: 1, remote: None }
714    }
715
716    fn ask(&mut self, message: &Message) -> Result<Message> {
717        self.transport.send(message)?;
718        match self.transport.recv()? {
719            Some(Message::Error { code, message }) => Err(peer_error(code, message)),
720            Some(reply) => Ok(reply),
721            None => Err(KuteError::Backend("the peer closed the connection".into())),
722        }
723    }
724
725    fn unexpected<R>(reply: Message) -> Result<R> {
726        Err(KuteError::Backend(format!("unexpected reply from the peer: {reply:?}")))
727    }
728
729    /// Initiator: handshake and capability exchange.
730    pub fn connect(&mut self) -> Result<Remote> {
731        let (peer, software) = match self.ask(&self.peer.hello())? {
732            Message::Hello { protocol, peer, software } if protocol == PROTOCOL_VERSION => (peer, software),
733            other => return Self::unexpected(other),
734        };
735        match self.ask(&self.peer.capabilities())? {
736            Message::Capabilities { algorithms, accepts_vocabularies, accepts_proposals, evolution_rules, .. } => {
737                let remote = Remote { peer, software, algorithms, accepts_vocabularies, accepts_proposals, evolution_rules };
738                self.remote = Some(remote.clone());
739                Ok(remote)
740            }
741            other => Self::unexpected(other),
742        }
743    }
744
745    /// Initiator: make sure the other side holds the vocabulary `digest`,
746    /// sending it if asked. Returns true if it had to be transferred.
747    pub fn share(&mut self, digest: &str) -> Result<bool> {
748        let vocabulary = VocabRef::of(&self.peer.hold(digest)?.vocabulary)?;
749        match self.ask(&Message::VocabAnnounce { vocabulary })? {
750            Message::VocabAccept { digest: d } if d == digest => Ok(false),
751            Message::VocabRequest { digest: d } if d == digest => {
752                let kvf = kute::vocab::to_vec(&self.peer.hold(digest)?.vocabulary)?;
753                match self.ask(&Message::VocabData { digest: digest.to_string(), kvf })? {
754                    Message::VocabAccept { digest: d } if d == digest => Ok(true),
755                    other => Self::unexpected(other),
756                }
757            }
758            other => Self::unexpected(other),
759        }
760    }
761
762    /// Initiator: encode `raw`, send it, and check the receipt. Returns the
763    /// number of units the other side decoded. Fails if the other side
764    /// decoded anything other than what this side's decoder gives.
765    pub fn send(&mut self, digest: &str, raw: &[u8], policy: UnknownPolicy) -> Result<u64> {
766        let id = self.next_id;
767        self.next_id += 1;
768        let (message, expected) = self.peer.encode_message(id, digest, raw, policy)?;
769        match self.ask(&message)? {
770            Message::Ack { id: acked, units, sha256 } if acked == id => {
771                if sha256 != expected {
772                    return Err(KuteError::Integrity("the peer decoded the message to different content".into()));
773                }
774                Ok(units)
775            }
776            other => Self::unexpected(other),
777        }
778    }
779
780    /// Initiator: extend a shared vocabulary on both sides. Each side
781    /// applies the step itself; the digests must agree. Returns the new
782    /// digest. Nothing changes locally if the other side refuses.
783    pub fn propose(&mut self, digest: &str, additions: &[Vec<String>], version: &str) -> Result<String> {
784        if let Some(remote) = &self.remote {
785            if !remote.evolution_rules.iter().any(|r| r == EVOLUTION_RULE) {
786                return Err(KuteError::Unsupported(format!(
787                    "the peer implements evolution rules {:?}, not {EVOLUTION_RULE:?}; a proposal would derive different vocabularies on the two sides",
788                    remote.evolution_rules
789                )));
790            }
791        }
792        let parsed = Version::parse(version).map_err(|e| KuteError::InvalidIdentifier(format!("version {version:?}: {e}")))?;
793        let child = kute::bpe::sequence::evolve(&self.peer.hold(digest)?.vocabulary, additions, parsed)?;
794        let expected = child.digest()?;
795        let propose = Message::SymbolPropose {
796            digest: digest.to_string(),
797            additions: additions.to_vec(),
798            version: version.to_string(),
799            rule: EVOLUTION_RULE.to_string(),
800        };
801        match self.ask(&propose)? {
802            Message::VocabAccept { digest: theirs } if theirs == expected => self.peer.add_vocabulary(child),
803            Message::VocabAccept { digest: theirs } => {
804                Err(KuteError::Integrity(format!("the peer derived {theirs}, this side derived {expected}")))
805            }
806            other => Self::unexpected(other),
807        }
808    }
809
810    /// Initiator: ask whether a symbol sequence is a token over there.
811    pub fn query(&mut self, digest: &str, symbols: &[String]) -> Result<Option<u32>> {
812        match self.ask(&Message::SymbolQuery { digest: digest.to_string(), symbols: symbols.to_vec() })? {
813            Message::SymbolInfo { token_id, .. } => Ok(token_id),
814            other => Self::unexpected(other),
815        }
816    }
817
818    /// Initiator: have the other side re-encode a sequence under another
819    /// vocabulary it holds.
820    pub fn translate(&mut self, sequence: &TokenSequence, to_digest: &str) -> Result<TokenSequence> {
821        let id = self.next_id;
822        self.next_id += 1;
823        let ask = Message::Translate { id, container: sequence.to_bytes_compressed()?, to_digest: to_digest.to_string() };
824        match self.ask(&ask)? {
825            Message::EncodedMessage { id: got, container } if got == id => {
826                let translated = TokenSequence::from_bytes(&container)?;
827                if translated.vocabulary_digest != to_digest {
828                    return Err(KuteError::Integrity("the peer translated to a different vocabulary".into()));
829                }
830                Ok(translated)
831            }
832            other => Self::unexpected(other),
833        }
834    }
835
836    /// Responder: answer messages until the other side closes. Returns the
837    /// number of messages handled.
838    pub fn serve(&mut self) -> Result<u64> {
839        let mut handled = 0;
840        while let Some(message) = self.transport.recv()? {
841            for reply in self.peer.handle(message) {
842                self.transport.send(&reply)?;
843            }
844            handled += 1;
845        }
846        Ok(handled)
847    }
848}