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/// One side of the protocol.
239pub struct Peer {
240    name: String,
241    engine: Engine,
242    policy: Policy,
243    held: BTreeMap<String, Held>,
244    stage: Stage,
245    wanted: Option<VocabRef>,
246    inbox: Vec<Delivered>,
247    inbox_bytes: u64,
248    /// The latest message ids: id, SHA-256 of the container, receipt sent.
249    seen: std::collections::VecDeque<(u64, String, Message)>,
250}
251
252pub fn sha256_hex(bytes: &[u8]) -> String {
253    kute::hex(&Sha256::digest(bytes))
254}
255
256impl Peer {
257    pub fn new(name: &str, engine: Engine, policy: Policy) -> Self {
258        Self {
259            name: name.to_string(),
260            engine,
261            policy,
262            held: BTreeMap::new(),
263            stage: Stage::New,
264            wanted: None,
265            inbox: Vec::new(),
266            inbox_bytes: 0,
267            seen: Default::default(),
268        }
269    }
270
271    /// Hold `vocabulary`. Returns its digest.
272    pub fn add_vocabulary(&mut self, vocabulary: Vocabulary) -> Result<String> {
273        vocabulary.validate()?;
274        let digest = vocabulary.compute_digest()?;
275        if let Some(other) = self.held.values().find(|h| h.vocabulary.id() == vocabulary.id() && h.vocabulary.version() == vocabulary.version()) {
276            if other.vocabulary.digest()? != digest {
277                return Err(KuteError::VocabularyMismatch(format!(
278                    "a different vocabulary is already held as {} {}",
279                    vocabulary.id(),
280                    vocabulary.version()
281                )));
282            }
283        }
284        let tokenizer = self.engine.tokenizer(vocabulary.clone())?;
285        let vocabulary = tokenizer.vocabulary().cloned().unwrap_or(vocabulary);
286        self.held.insert(digest.clone(), Held { vocabulary, tokenizer });
287        Ok(digest)
288    }
289
290    pub fn vocabulary(&self, digest: &str) -> Option<&Vocabulary> {
291        self.held.get(digest).map(|h| &h.vocabulary)
292    }
293
294    pub fn digests(&self) -> Vec<String> {
295        self.held.keys().cloned().collect()
296    }
297
298    /// Messages received and decoded since the last call.
299    pub fn take_inbox(&mut self) -> Vec<Delivered> {
300        self.inbox_bytes = 0;
301        std::mem::take(&mut self.inbox)
302    }
303
304    /// Whether the other side may add a vocabulary of `tokens` tokens: the
305    /// refusal if it would pass what this peer is willing to hold in all.
306    fn over_budget(&self, tokens: u64) -> Option<Vec<Message>> {
307        if self.held.len() as u64 >= self.policy.max_held_vocabularies {
308            return Some(refuse(ErrorCode::TooLarge, format!("this peer already holds {} vocabularies, its limit", self.held.len())));
309        }
310        let held: u64 = self.held.values().map(|h| h.vocabulary.len() as u64).sum();
311        if held.saturating_add(tokens) > self.policy.max_held_tokens {
312            return Some(refuse(
313                ErrorCode::TooLarge,
314                format!("this peer holds {held} tokens and takes at most {} in all", self.policy.max_held_tokens),
315            ));
316        }
317        None
318    }
319
320    pub fn engine(&self) -> &Engine {
321        &self.engine
322    }
323
324    fn hold(&self, digest: &str) -> Result<&Held> {
325        self.held.get(digest).ok_or_else(|| KuteError::VocabularyMismatch(format!("no vocabulary with digest {digest} is held")))
326    }
327
328    /// Whether the other side may use the vocabulary with this digest.
329    fn sees(&self, digest: &str) -> bool {
330        self.policy.vocabularies.as_ref().is_none_or(|listed| listed.contains(digest))
331    }
332
333    /// A held vocabulary, for the other side: one it may not use is
334    /// answered exactly as one that is not held.
335    fn usable(&self, digest: &str) -> Result<&Held> {
336        if !self.sees(digest) {
337            return Err(KuteError::VocabularyMismatch(format!("no vocabulary with digest {digest} is held")));
338        }
339        self.hold(digest)
340    }
341
342    /// A vocabulary the other side added is one it may use.
343    fn show(&mut self, digest: &str) {
344        if let Some(listed) = &mut self.policy.vocabularies {
345            listed.insert(digest.to_string());
346        }
347    }
348
349    /// The most tokens a container from the other side may declare. Every
350    /// token decodes to at least one unit, so the unit limit bounds it too.
351    fn token_limit(&self) -> u64 {
352        self.policy.max_message_tokens.min(self.policy.max_decoded_units)
353    }
354
355    pub fn hello(&self) -> Message {
356        Message::Hello { protocol: PROTOCOL_VERSION, peer: self.name.clone(), software: format!("kute {}", kute::KUTE_VERSION) }
357    }
358
359    pub fn capabilities(&self) -> Message {
360        Message::Capabilities {
361            algorithms: self.engine.registry().algorithm_names(),
362            adapters: self.engine.registry().adapter_names(),
363            max_frame_bytes: self.policy.max_frame_bytes,
364            accepts_vocabularies: self.policy.accept_vocabularies,
365            accepts_proposals: self.policy.accept_proposals,
366            evolution_rules: vec![EVOLUTION_RULE.to_string()],
367            kvf_versions: vec![kute::KVF_VERSION.to_string()],
368        }
369    }
370
371    /// Encode `raw` under a held vocabulary and wrap it as a message.
372    /// Returns the message and the SHA-256 the receiver's `ACK` must carry.
373    pub fn encode_message(&self, id: u64, digest: &str, raw: &[u8], policy: UnknownPolicy) -> Result<(Message, String)> {
374        let held = self.hold(digest)?;
375        let sequence = self.engine.encode_raw_open(held.tokenizer.as_ref(), raw, policy)?;
376        let expected = sha256_hex(&self.engine.decode_raw(held.tokenizer.as_ref(), &sequence)?);
377        Ok((Message::EncodedMessage { id, container: sequence.to_bytes_compressed()? }, expected))
378    }
379
380    /// Apply an evolution step to a held vocabulary and hold the result.
381    pub fn evolve(&mut self, digest: &str, additions: &[Vec<String>], version: &str) -> Result<String> {
382        let version = Version::parse(version).map_err(|e| KuteError::InvalidIdentifier(format!("version {version:?}: {e}")))?;
383        let child = kute::bpe::sequence::evolve(&self.hold(digest)?.vocabulary, additions, version)?;
384        self.add_vocabulary(child)
385    }
386
387    /// Re-encode a sequence under another held vocabulary. Symbols the
388    /// target lacks are escaped, so nothing is lost.
389    pub fn translate(&self, sequence: &TokenSequence, to_digest: &str) -> Result<TokenSequence> {
390        let from = self.hold(&sequence.vocabulary_digest)?;
391        let to = self.hold(to_digest)?;
392        let units = kute::decoded_units(&from.vocabulary, sequence)?;
393        if units > self.policy.max_decoded_units {
394            return Err(KuteError::LimitExceeded(format!("the sequence decodes to {units} units")));
395        }
396        // Symbols can be a kilobyte each, so their count is not their size.
397        // The translation goes back in one frame, so a frame bounds it.
398        let bytes = kute::decoded_bytes_at_least(&from.vocabulary, sequence)?;
399        if bytes > self.policy.max_frame_bytes {
400            return Err(KuteError::LimitExceeded(format!("the sequence decodes to at least {bytes} bytes; a frame holds {}", self.policy.max_frame_bytes)));
401        }
402        to.tokenizer.encode_open(&from.tokenizer.decode(sequence)?, UnknownPolicy::Escape)
403    }
404
405    /// Handle one message from the other side. Never fails: anything wrong
406    /// is answered with an `ERROR` message.
407    pub fn handle(&mut self, message: Message) -> Vec<Message> {
408        match (self.stage, &message) {
409            (Stage::New, Message::Hello { protocol, .. }) => {
410                if *protocol != PROTOCOL_VERSION {
411                    return refuse(ErrorCode::UnsupportedProtocol, format!("this peer speaks protocol {PROTOCOL_VERSION}, not {protocol}"));
412                }
413                self.stage = Stage::Greeted;
414                return vec![self.hello()];
415            }
416            (Stage::Greeted, Message::Capabilities { .. }) => {
417                self.stage = Stage::Ready;
418                return vec![self.capabilities()];
419            }
420            (Stage::Ready, Message::Hello { .. } | Message::Capabilities { .. }) | (Stage::New | Stage::Greeted, _) => {
421                return refuse(ErrorCode::OutOfOrder, "expected HELLO, then CAPABILITIES, before anything else");
422            }
423            (Stage::Ready, _) => {}
424        }
425        match self.respond(message) {
426            Ok(replies) => replies,
427            Err(e) => {
428                let code = match e {
429                    KuteError::LimitExceeded(_) => ErrorCode::TooLarge,
430                    KuteError::VocabularyMismatch(_) => ErrorCode::UnknownVocabulary,
431                    _ => ErrorCode::Invalid,
432                };
433                refuse(code, e.to_string())
434            }
435        }
436    }
437
438    fn respond(&mut self, message: Message) -> Result<Vec<Message>> {
439        match message {
440            Message::VocabAnnounce { vocabulary } => {
441                // A vocabulary that is held but not this peer's to use is
442                // treated from here on exactly as one that is not held: the
443                // same checks, the same request for its content. If the
444                // peer then sends it, it had the content already, and it
445                // becomes one it may use.
446                if self.held.contains_key(&vocabulary.digest) && self.sees(&vocabulary.digest) {
447                    return Ok(vec![Message::VocabAccept { digest: vocabulary.digest }]);
448                }
449                if self.held.values().any(|h| {
450                    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)
451                }) {
452                    // This does tell a peer that the id and version are
453                    // taken, whether or not it may use the holder. Two
454                    // vocabularies cannot share them, so the refusal cannot
455                    // be avoided, only worded the same in both cases.
456                    return Ok(refuse(
457                        ErrorCode::VocabularyConflict,
458                        format!("{} {} is held here with different content", vocabulary.id, vocabulary.version),
459                    ));
460                }
461                if !self.engine.registry().algorithm_names().contains(&vocabulary.algorithm) {
462                    return Ok(refuse(ErrorCode::UnsupportedAlgorithm, format!("algorithm {:?} is not available here", vocabulary.algorithm)));
463                }
464                if !self.policy.accept_vocabularies {
465                    return Ok(refuse(ErrorCode::Refused, "this peer does not take vocabularies from the other side"));
466                }
467                if vocabulary.tokens > self.policy.max_vocabulary_tokens {
468                    return Ok(refuse(ErrorCode::TooLarge, format!("vocabularies above {} tokens are not taken", self.policy.max_vocabulary_tokens)));
469                }
470                if let Some(refusal) = self.over_budget(vocabulary.tokens) {
471                    return Ok(refusal);
472                }
473                let digest = vocabulary.digest.clone();
474                self.wanted = Some(vocabulary);
475                Ok(vec![Message::VocabRequest { digest }])
476            }
477            Message::VocabRequest { digest } => {
478                if !self.policy.give_vocabularies {
479                    return Ok(refuse(ErrorCode::Refused, "this peer does not give out vocabularies"));
480                }
481                let kvf = kute::vocab::to_vec(&self.usable(&digest)?.vocabulary)?;
482                Ok(vec![Message::VocabData { digest, kvf }])
483            }
484            Message::VocabData { digest, kvf } => {
485                let Some(wanted) = self.wanted.take().filter(|w| w.digest == digest) else {
486                    return Ok(refuse(ErrorCode::OutOfOrder, "vocabulary data that was not requested"));
487                };
488                let vocabulary = kute::vocab::from_slice(&kvf)?;
489                // The digest is recomputed from content; the one in the file
490                // and the one announced are both only claims.
491                if vocabulary.compute_digest()? != digest || VocabRef::of(&vocabulary)? != wanted {
492                    return Ok(refuse(ErrorCode::Invalid, "the vocabulary sent is not the one announced"));
493                }
494                if vocabulary.len() as u64 > self.policy.max_vocabulary_tokens {
495                    return Ok(refuse(ErrorCode::TooLarge, "vocabulary exceeds the token limit"));
496                }
497                // Again, on what was sent and not on what was announced.
498                if let Some(refusal) = self.over_budget(vocabulary.len() as u64) {
499                    return Ok(refusal);
500                }
501                let report = self.engine.verify(&vocabulary)?;
502                if !report.ok() {
503                    return Ok(refuse(ErrorCode::Invalid, format!("the vocabulary fails its own test vectors: {}", report.failures.join("; "))));
504                }
505                let digest = self.add_vocabulary(vocabulary)?;
506                self.show(&digest);
507                Ok(vec![Message::VocabAccept { digest }])
508            }
509            Message::SymbolQuery { digest, symbols } => {
510                if !self.policy.answer_queries {
511                    return Ok(refuse(ErrorCode::Refused, "this peer does not answer questions about its vocabularies"));
512                }
513                let payload = TokenPayload::Symbols(symbols);
514                let token_id = self.usable(&digest)?.vocabulary.tokens.iter().find(|t| t.payload == payload).map(|t| t.id);
515                Ok(vec![Message::SymbolInfo { digest, token_id, content_hash: payload.content_hash() }])
516            }
517            Message::SymbolPropose { digest, additions, version, rule } => {
518                if !self.policy.accept_proposals {
519                    return Ok(refuse(ErrorCode::Refused, "this peer does not accept vocabulary proposals"));
520                }
521                // Before anything is derived: under another rule the child
522                // would differ, and the two sides would part silently.
523                if rule != EVOLUTION_RULE {
524                    return Ok(refuse(
525                        ErrorCode::UnsupportedRule,
526                        format!("the proposal uses evolution rule {rule:?}; this peer implements {EVOLUTION_RULE:?}"),
527                    ));
528                }
529                // An addition of n symbols adds at most n symbols and n merges.
530                let most: u64 = additions.iter().map(|a| 2 * a.len() as u64).sum();
531                let parent = self.usable(&digest)?.vocabulary.len() as u64;
532                if parent.saturating_add(most) > self.policy.max_vocabulary_tokens {
533                    return Ok(refuse(ErrorCode::TooLarge, "the proposal would pass the vocabulary token limit"));
534                }
535                if let Some(refusal) = self.over_budget(parent.saturating_add(most)) {
536                    return Ok(refusal);
537                }
538                // The child is derived even when its id and version are
539                // already held: a repeat of the same proposal has to be
540                // accepted again, and only the derivation tells a repeat
541                // from a conflict. Its cost is bounded by the checks above.
542                let digest = match self.evolve(&digest, &additions, &version) {
543                    Ok(digest) => digest,
544                    Err(KuteError::VocabularyMismatch(why)) => return Ok(refuse(ErrorCode::VocabularyConflict, why)),
545                    Err(e) => return Err(e),
546                };
547                self.show(&digest);
548                Ok(vec![Message::VocabAccept { digest }])
549            }
550            Message::Translate { id, container, to_digest } => {
551                if !self.policy.translate {
552                    return Ok(refuse(ErrorCode::Refused, "this peer does not translate for the other side"));
553                }
554                // A container that declares more tokens than the limit is
555                // refused before its ids are decompressed.
556                let sequence = TokenSequence::from_bytes_bounded(&container, self.token_limit())?;
557                self.usable(&sequence.vocabulary_digest)?;
558                self.usable(&to_digest)?;
559                let translated = self.translate(&sequence, &to_digest)?;
560                Ok(vec![Message::EncodedMessage { id, container: translated.to_bytes_compressed()? }])
561            }
562            Message::EncodedMessage { id, container } => {
563                // A repeat of a delivered message gets its receipt again and
564                // is not delivered twice; the same id on other content is an
565                // error. Ids older than the window are not remembered.
566                let fingerprint = sha256_hex(&container);
567                if let Some((_, first, receipt)) = self.seen.iter().find(|(seen, _, _)| *seen == id) {
568                    return Ok(if *first == fingerprint {
569                        vec![receipt.clone()]
570                    } else {
571                        refuse(ErrorCode::Invalid, format!("message id {id} was already used for different content"))
572                    });
573                }
574                if self.inbox.len() as u64 >= self.policy.max_inbox_messages {
575                    return Ok(refuse(ErrorCode::Busy, format!("the inbox holds {} messages, its limit", self.inbox.len())));
576                }
577                let sequence = TokenSequence::from_bytes_bounded(&container, self.token_limit())?;
578                let held = self.usable(&sequence.vocabulary_digest)?;
579                let units = kute::decoded_units(&held.vocabulary, &sequence)?;
580                let bytes = self.engine.decode_raw_within(held.tokenizer.as_ref(), &sequence, self.policy.max_decoded_units, self.policy.max_inbox_bytes)?;
581                // What the inbox keeps for this message: the decoded bytes
582                // and the sequence (ids, and the escapes the container holds).
583                let kept = (bytes.len() as u64).saturating_add(4 * sequence.ids.len() as u64).saturating_add(container.len() as u64);
584                if self.inbox_bytes.saturating_add(kept) > self.policy.max_inbox_bytes {
585                    return Ok(refuse(ErrorCode::Busy, format!("the inbox holds {} bytes and takes at most {}", self.inbox_bytes, self.policy.max_inbox_bytes)));
586                }
587                let receipt = Message::Ack { id, units, sha256: sha256_hex(&bytes) };
588                self.inbox_bytes += kept;
589                self.inbox.push(Delivered { id, sequence, bytes });
590                self.seen.push_back((id, fingerprint, receipt.clone()));
591                while self.seen.len() as u64 > self.policy.replay_window {
592                    self.seen.pop_front();
593                }
594                Ok(vec![receipt])
595            }
596            Message::VocabAccept { .. } | Message::SymbolInfo { .. } | Message::Ack { .. } | Message::Error { .. } => {
597                Ok(refuse(ErrorCode::OutOfOrder, "a reply arrived where a request was expected"))
598            }
599            Message::Hello { .. } | Message::Capabilities { .. } => Ok(refuse(ErrorCode::OutOfOrder, "the handshake is already complete")),
600        }
601    }
602}
603
604/// Something that carries messages to the other peer and back.
605pub trait Transport {
606    fn send(&mut self, message: &Message) -> Result<()>;
607    /// The next message, or `None` when the other side has closed.
608    fn recv(&mut self) -> Result<Option<Message>>;
609}
610
611/// Messages over a byte stream: a four-byte little-endian length, then that
612/// many bytes of JSON.
613pub struct Framed<S: Read + Write> {
614    stream: S,
615    max_frame: u64,
616}
617
618impl<S: Read + Write> Framed<S> {
619    pub fn new(stream: S, max_frame: u64) -> Self {
620        Self { stream, max_frame: max_frame.min(DEFAULT_MAX_FRAME) }
621    }
622}
623
624impl<S: Read + Write> Transport for Framed<S> {
625    fn send(&mut self, message: &Message) -> Result<()> {
626        let body = serde_json::to_vec(message)?;
627        if body.len() as u64 > self.max_frame {
628            return Err(KuteError::LimitExceeded(format!("message of {} bytes exceeds the frame limit of {}", body.len(), self.max_frame)));
629        }
630        self.stream.write_all(&(body.len() as u32).to_le_bytes())?;
631        self.stream.write_all(&body)?;
632        self.stream.flush()?;
633        Ok(())
634    }
635
636    fn recv(&mut self) -> Result<Option<Message>> {
637        let mut length = [0u8; 4];
638        let mut got = 0;
639        while got < 4 {
640            match self.stream.read(&mut length[got..]) {
641                Ok(0) if got == 0 => return Ok(None),
642                Ok(0) => return Err(KuteError::InvalidInput("the stream ended inside a frame header".into())),
643                Ok(n) => got += n,
644                Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}
645                Err(e) => return Err(e.into()),
646            }
647        }
648        let length = u32::from_le_bytes(length) as u64;
649        if length > self.max_frame {
650            return Err(KuteError::LimitExceeded(format!("incoming frame of {length} bytes exceeds the limit of {}", self.max_frame)));
651        }
652        // Read through `take` so a forged length cannot make us allocate
653        // more than actually arrives.
654        let mut body = Vec::new();
655        (&mut self.stream).take(length).read_to_end(&mut body)?;
656        if body.len() as u64 != length {
657            return Err(KuteError::InvalidInput("the stream ended inside a frame".into()));
658        }
659        serde_json::from_slice(&body).map(Some).map_err(|e| KuteError::InvalidInput(format!("not a protocol message: {e}")))
660    }
661}
662
663/// The other side's answer to `CAPABILITIES`.
664#[derive(Clone, Debug, PartialEq, Eq)]
665pub struct Remote {
666    pub peer: String,
667    pub software: String,
668    pub algorithms: Vec<String>,
669    pub accepts_vocabularies: bool,
670    pub accepts_proposals: bool,
671    pub evolution_rules: Vec<String>,
672}
673
674fn peer_error(code: ErrorCode, message: String) -> KuteError {
675    KuteError::Backend(format!("the peer answered {code:?}: {message}"))
676}
677
678/// A peer together with its connection.
679pub struct Session<T: Transport> {
680    pub peer: Peer,
681    transport: T,
682    next_id: u64,
683    remote: Option<Remote>,
684}
685
686impl<T: Transport> Session<T> {
687    pub fn new(peer: Peer, transport: T) -> Self {
688        Self { peer, transport, next_id: 1, remote: None }
689    }
690
691    fn ask(&mut self, message: &Message) -> Result<Message> {
692        self.transport.send(message)?;
693        match self.transport.recv()? {
694            Some(Message::Error { code, message }) => Err(peer_error(code, message)),
695            Some(reply) => Ok(reply),
696            None => Err(KuteError::Backend("the peer closed the connection".into())),
697        }
698    }
699
700    fn unexpected<R>(reply: Message) -> Result<R> {
701        Err(KuteError::Backend(format!("unexpected reply from the peer: {reply:?}")))
702    }
703
704    /// Initiator: handshake and capability exchange.
705    pub fn connect(&mut self) -> Result<Remote> {
706        let (peer, software) = match self.ask(&self.peer.hello())? {
707            Message::Hello { protocol, peer, software } if protocol == PROTOCOL_VERSION => (peer, software),
708            other => return Self::unexpected(other),
709        };
710        match self.ask(&self.peer.capabilities())? {
711            Message::Capabilities { algorithms, accepts_vocabularies, accepts_proposals, evolution_rules, .. } => {
712                let remote = Remote { peer, software, algorithms, accepts_vocabularies, accepts_proposals, evolution_rules };
713                self.remote = Some(remote.clone());
714                Ok(remote)
715            }
716            other => Self::unexpected(other),
717        }
718    }
719
720    /// Initiator: make sure the other side holds the vocabulary `digest`,
721    /// sending it if asked. Returns true if it had to be transferred.
722    pub fn share(&mut self, digest: &str) -> Result<bool> {
723        let vocabulary = VocabRef::of(&self.peer.hold(digest)?.vocabulary)?;
724        match self.ask(&Message::VocabAnnounce { vocabulary })? {
725            Message::VocabAccept { digest: d } if d == digest => Ok(false),
726            Message::VocabRequest { digest: d } if d == digest => {
727                let kvf = kute::vocab::to_vec(&self.peer.hold(digest)?.vocabulary)?;
728                match self.ask(&Message::VocabData { digest: digest.to_string(), kvf })? {
729                    Message::VocabAccept { digest: d } if d == digest => Ok(true),
730                    other => Self::unexpected(other),
731                }
732            }
733            other => Self::unexpected(other),
734        }
735    }
736
737    /// Initiator: encode `raw`, send it, and check the receipt. Returns the
738    /// number of units the other side decoded. Fails if the other side
739    /// decoded anything other than what this side's decoder gives.
740    pub fn send(&mut self, digest: &str, raw: &[u8], policy: UnknownPolicy) -> Result<u64> {
741        let id = self.next_id;
742        self.next_id += 1;
743        let (message, expected) = self.peer.encode_message(id, digest, raw, policy)?;
744        match self.ask(&message)? {
745            Message::Ack { id: acked, units, sha256 } if acked == id => {
746                if sha256 != expected {
747                    return Err(KuteError::Integrity("the peer decoded the message to different content".into()));
748                }
749                Ok(units)
750            }
751            other => Self::unexpected(other),
752        }
753    }
754
755    /// Initiator: extend a shared vocabulary on both sides. Each side
756    /// applies the step itself; the digests must agree. Returns the new
757    /// digest. Nothing changes locally if the other side refuses.
758    pub fn propose(&mut self, digest: &str, additions: &[Vec<String>], version: &str) -> Result<String> {
759        if let Some(remote) = &self.remote {
760            if !remote.evolution_rules.iter().any(|r| r == EVOLUTION_RULE) {
761                return Err(KuteError::Unsupported(format!(
762                    "the peer implements evolution rules {:?}, not {EVOLUTION_RULE:?}; a proposal would derive different vocabularies on the two sides",
763                    remote.evolution_rules
764                )));
765            }
766        }
767        let parsed = Version::parse(version).map_err(|e| KuteError::InvalidIdentifier(format!("version {version:?}: {e}")))?;
768        let child = kute::bpe::sequence::evolve(&self.peer.hold(digest)?.vocabulary, additions, parsed)?;
769        let expected = child.digest()?;
770        let propose = Message::SymbolPropose {
771            digest: digest.to_string(),
772            additions: additions.to_vec(),
773            version: version.to_string(),
774            rule: EVOLUTION_RULE.to_string(),
775        };
776        match self.ask(&propose)? {
777            Message::VocabAccept { digest: theirs } if theirs == expected => self.peer.add_vocabulary(child),
778            Message::VocabAccept { digest: theirs } => {
779                Err(KuteError::Integrity(format!("the peer derived {theirs}, this side derived {expected}")))
780            }
781            other => Self::unexpected(other),
782        }
783    }
784
785    /// Initiator: ask whether a symbol sequence is a token over there.
786    pub fn query(&mut self, digest: &str, symbols: &[String]) -> Result<Option<u32>> {
787        match self.ask(&Message::SymbolQuery { digest: digest.to_string(), symbols: symbols.to_vec() })? {
788            Message::SymbolInfo { token_id, .. } => Ok(token_id),
789            other => Self::unexpected(other),
790        }
791    }
792
793    /// Initiator: have the other side re-encode a sequence under another
794    /// vocabulary it holds.
795    pub fn translate(&mut self, sequence: &TokenSequence, to_digest: &str) -> Result<TokenSequence> {
796        let id = self.next_id;
797        self.next_id += 1;
798        let ask = Message::Translate { id, container: sequence.to_bytes_compressed()?, to_digest: to_digest.to_string() };
799        match self.ask(&ask)? {
800            Message::EncodedMessage { id: got, container } if got == id => {
801                let translated = TokenSequence::from_bytes(&container)?;
802                if translated.vocabulary_digest != to_digest {
803                    return Err(KuteError::Integrity("the peer translated to a different vocabulary".into()));
804                }
805                Ok(translated)
806            }
807            other => Self::unexpected(other),
808        }
809    }
810
811    /// Responder: answer messages until the other side closes. Returns the
812    /// number of messages handled.
813    pub fn serve(&mut self) -> Result<u64> {
814        let mut handled = 0;
815        while let Some(message) = self.transport.recv()? {
816            for reply in self.peer.handle(message) {
817                self.transport.send(&reply)?;
818            }
819            handled += 1;
820        }
821        Ok(handled)
822    }
823}