1use 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
25pub const PROTOCOL_VERSION: u32 = 2;
30pub const EVOLUTION_RULE: &str = kute::bpe::sequence::EVOLVE_GENERATOR;
34pub const DEFAULT_MAX_FRAME: u64 = 64 * 1024 * 1024;
36
37#[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 OutOfOrder,
64 UnsupportedProtocol,
65 UnsupportedAlgorithm,
66 VocabularyConflict,
68 UnknownVocabulary,
69 Invalid,
71 Refused,
73 TooLarge,
74 UnsupportedRule,
76 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 #[serde(default)]
92 evolution_rules: Vec<String>,
93 #[serde(default)]
95 kvf_versions: Vec<String>,
96 },
97 VocabAnnounce { vocabulary: VocabRef },
99 VocabRequest { digest: String },
101 VocabData {
104 digest: String,
105 #[serde(with = "kute::b64")]
106 kvf: Vec<u8>,
107 },
108 VocabAccept { digest: String },
110 SymbolQuery { digest: String, symbols: Vec<String> },
112 SymbolInfo { digest: String, token_id: Option<u32>, content_hash: String },
114 SymbolPropose {
119 digest: String,
120 additions: Vec<Vec<String>>,
121 version: String,
122 #[serde(default)]
123 rule: String,
124 },
125 Translate {
127 id: u64,
128 #[serde(with = "kute::b64")]
129 container: Vec<u8>,
130 to_digest: String,
131 },
132 EncodedMessage {
134 id: u64,
135 #[serde(with = "kute::b64")]
136 container: Vec<u8>,
137 },
138 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#[derive(Clone, Debug, PartialEq, Eq)]
156pub struct Policy {
157 pub give_vocabularies: bool,
159 pub answer_queries: bool,
161 pub translate: bool,
163 pub vocabularies: Option<std::collections::BTreeSet<String>>,
168 pub max_message_tokens: u64,
171 pub accept_vocabularies: bool,
173 pub accept_proposals: bool,
175 pub max_frame_bytes: u64,
176 pub max_vocabulary_tokens: u64,
177 pub max_decoded_units: u64,
179 pub max_held_vocabularies: u64,
182 pub max_held_tokens: u64,
184 pub max_inbox_messages: u64,
187 pub max_inbox_bytes: u64,
190 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#[derive(Clone, Debug, PartialEq)]
219pub struct Delivered {
220 pub id: u64,
221 pub sequence: TokenSequence,
222 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
238pub type VocabularyCheck = Box<dyn Fn(&Vocabulary) -> std::result::Result<(), String> + Send>;
243
244pub 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 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 pub fn require_vocabulary_check(&mut self, check: VocabularyCheck) {
285 self.check = Some(check);
286 }
287
288 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 pub fn take_inbox(&mut self) -> Vec<Delivered> {
317 self.inbox_bytes = 0;
318 std::mem::take(&mut self.inbox)
319 }
320
321 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 fn sees(&self, digest: &str) -> bool {
347 self.policy.vocabularies.as_ref().is_none_or(|listed| listed.contains(digest))
348 }
349
350 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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
629pub trait Transport {
631 fn send(&mut self, message: &Message) -> Result<()>;
632 fn recv(&mut self) -> Result<Option<Message>>;
634}
635
636pub 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 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#[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
703pub 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 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 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 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 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 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 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 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}