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 MAX_PROPOSAL_SIGNATURES: usize = 16;
32pub const EVOLUTION_RULE: &str = kute::bpe::sequence::EVOLVE_GENERATOR;
36pub const DEFAULT_MAX_FRAME: u64 = 64 * 1024 * 1024;
38
39#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
41pub struct VocabRef {
42 pub id: String,
43 pub version: String,
44 pub digest: String,
45 pub algorithm: String,
46 pub tokens: u64,
47}
48
49impl VocabRef {
50 pub fn of(vocabulary: &Vocabulary) -> Result<Self> {
51 Ok(Self {
52 id: vocabulary.id().to_string(),
53 version: vocabulary.version().to_string(),
54 digest: vocabulary.digest()?,
55 algorithm: vocabulary.manifest.algorithm.clone(),
56 tokens: vocabulary.len() as u64,
57 })
58 }
59}
60
61#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
62#[serde(rename_all = "snake_case")]
63pub enum ErrorCode {
64 OutOfOrder,
66 UnsupportedProtocol,
67 UnsupportedAlgorithm,
68 VocabularyConflict,
70 UnknownVocabulary,
71 Invalid,
73 Refused,
75 TooLarge,
76 UnsupportedRule,
78 Busy,
80}
81
82#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
83#[serde(tag = "type", rename_all = "SCREAMING_SNAKE_CASE")]
84pub enum Message {
85 Hello { protocol: u32, peer: String, software: String },
86 Capabilities {
87 algorithms: Vec<String>,
88 adapters: Vec<String>,
89 max_frame_bytes: u64,
90 accepts_vocabularies: bool,
91 accepts_proposals: bool,
92 #[serde(default)]
94 evolution_rules: Vec<String>,
95 #[serde(default)]
97 kvf_versions: Vec<String>,
98 },
99 VocabAnnounce { vocabulary: VocabRef },
101 VocabRequest { digest: String },
103 VocabData {
106 digest: String,
107 #[serde(with = "kute::b64")]
108 kvf: Vec<u8>,
109 },
110 VocabAccept { digest: String },
112 SymbolQuery { digest: String, symbols: Vec<String> },
114 SymbolInfo { digest: String, token_id: Option<u32>, content_hash: String },
116 SymbolPropose {
125 digest: String,
126 additions: Vec<Vec<String>>,
127 version: String,
128 #[serde(default)]
129 rule: String,
130 #[serde(default, skip_serializing_if = "Vec::is_empty")]
131 signatures: Vec<kute::Signature>,
132 },
133 Translate {
135 id: u64,
136 #[serde(with = "kute::b64")]
137 container: Vec<u8>,
138 to_digest: String,
139 },
140 EncodedMessage {
142 id: u64,
143 #[serde(with = "kute::b64")]
144 container: Vec<u8>,
145 },
146 Ack { id: u64, units: u64, sha256: String },
149 Error { code: ErrorCode, message: String },
150}
151
152fn refuse(code: ErrorCode, message: impl Into<String>) -> Vec<Message> {
153 vec![Message::Error { code, message: message.into() }]
154}
155
156#[derive(Clone, Debug, PartialEq, Eq)]
164pub struct Policy {
165 pub give_vocabularies: bool,
167 pub answer_queries: bool,
169 pub translate: bool,
171 pub vocabularies: Option<std::collections::BTreeSet<String>>,
176 pub max_message_tokens: u64,
179 pub accept_vocabularies: bool,
181 pub accept_proposals: bool,
183 pub max_frame_bytes: u64,
184 pub max_vocabulary_tokens: u64,
185 pub max_decoded_units: u64,
187 pub max_held_vocabularies: u64,
190 pub max_held_tokens: u64,
192 pub max_inbox_messages: u64,
195 pub max_inbox_bytes: u64,
198 pub replay_window: u64,
201}
202
203impl Default for Policy {
204 fn default() -> Self {
205 Self {
206 give_vocabularies: false,
207 answer_queries: false,
208 translate: false,
209 vocabularies: None,
210 max_message_tokens: 16 * 1024 * 1024,
211 accept_vocabularies: false,
212 accept_proposals: false,
213 max_frame_bytes: DEFAULT_MAX_FRAME,
214 max_vocabulary_tokens: 1_000_000,
215 max_decoded_units: 256 * 1024 * 1024,
216 max_held_vocabularies: 64,
217 max_held_tokens: 4_000_000,
218 max_inbox_messages: 1024,
219 max_inbox_bytes: 256 * 1024 * 1024,
220 replay_window: 1024,
221 }
222 }
223}
224
225#[derive(Clone, Debug, PartialEq)]
227pub struct Delivered {
228 pub id: u64,
229 pub sequence: TokenSequence,
230 pub bytes: Vec<u8>,
232}
233
234struct Held {
235 vocabulary: Vocabulary,
236 tokenizer: Box<dyn Tokenizer>,
237}
238
239#[derive(Clone, Copy, PartialEq, Eq)]
240enum Stage {
241 New,
242 Greeted,
243 Ready,
244}
245
246pub type VocabularyCheck = Box<dyn Fn(&Vocabulary) -> std::result::Result<(), String> + Send>;
251
252pub struct Peer {
254 name: String,
255 engine: Engine,
256 policy: Policy,
257 check: Option<VocabularyCheck>,
258 held: BTreeMap<String, Held>,
259 stage: Stage,
260 wanted: Option<VocabRef>,
261 inbox: Vec<Delivered>,
262 inbox_bytes: u64,
263 seen: std::collections::VecDeque<(u64, String, Message)>,
265}
266
267pub fn sha256_hex(bytes: &[u8]) -> String {
268 kute::hex(&Sha256::digest(bytes))
269}
270
271impl Peer {
272 pub fn new(name: &str, engine: Engine, policy: Policy) -> Self {
273 Self {
274 name: name.to_string(),
275 engine,
276 policy,
277 check: None,
278 held: BTreeMap::new(),
279 stage: Stage::New,
280 wanted: None,
281 inbox: Vec::new(),
282 inbox_bytes: 0,
283 seen: Default::default(),
284 }
285 }
286
287 pub fn require_vocabulary_check(&mut self, check: VocabularyCheck) {
294 self.check = Some(check);
295 }
296
297 pub fn add_vocabulary(&mut self, vocabulary: Vocabulary) -> Result<String> {
299 vocabulary.validate()?;
300 let digest = vocabulary.compute_digest()?;
301 if let Some(other) = self.held.values().find(|h| h.vocabulary.id() == vocabulary.id() && h.vocabulary.version() == vocabulary.version()) {
302 if other.vocabulary.digest()? != digest {
303 return Err(KuteError::VocabularyMismatch(format!(
304 "a different vocabulary is already held as {} {}",
305 vocabulary.id(),
306 vocabulary.version()
307 )));
308 }
309 }
310 let tokenizer = self.engine.tokenizer(vocabulary.clone())?;
311 let vocabulary = tokenizer.vocabulary().cloned().unwrap_or(vocabulary);
312 self.held.insert(digest.clone(), Held { vocabulary, tokenizer });
313 Ok(digest)
314 }
315
316 pub fn vocabulary(&self, digest: &str) -> Option<&Vocabulary> {
317 self.held.get(digest).map(|h| &h.vocabulary)
318 }
319
320 pub fn digests(&self) -> Vec<String> {
321 self.held.keys().cloned().collect()
322 }
323
324 pub fn inbox_len(&self) -> usize {
326 self.inbox.len()
327 }
328
329 pub fn take_inbox(&mut self) -> Vec<Delivered> {
331 self.inbox_bytes = 0;
332 std::mem::take(&mut self.inbox)
333 }
334
335 fn over_budget(&self, tokens: u64) -> Option<Vec<Message>> {
338 if self.held.len() as u64 >= self.policy.max_held_vocabularies {
339 return Some(refuse(ErrorCode::TooLarge, format!("this peer already holds {} vocabularies, its limit", self.held.len())));
340 }
341 let held: u64 = self.held.values().map(|h| h.vocabulary.len() as u64).sum();
342 if held.saturating_add(tokens) > self.policy.max_held_tokens {
343 return Some(refuse(
344 ErrorCode::TooLarge,
345 format!("this peer holds {held} tokens and takes at most {} in all", self.policy.max_held_tokens),
346 ));
347 }
348 None
349 }
350
351 pub fn engine(&self) -> &Engine {
352 &self.engine
353 }
354
355 fn hold(&self, digest: &str) -> Result<&Held> {
356 self.held.get(digest).ok_or_else(|| KuteError::VocabularyMismatch(format!("no vocabulary with digest {digest} is held")))
357 }
358
359 fn sees(&self, digest: &str) -> bool {
361 self.policy.vocabularies.as_ref().is_none_or(|listed| listed.contains(digest))
362 }
363
364 fn usable(&self, digest: &str) -> Result<&Held> {
367 if !self.sees(digest) {
368 return Err(KuteError::VocabularyMismatch(format!("no vocabulary with digest {digest} is held")));
369 }
370 self.hold(digest)
371 }
372
373 fn show(&mut self, digest: &str) {
375 if let Some(listed) = &mut self.policy.vocabularies {
376 listed.insert(digest.to_string());
377 }
378 }
379
380 fn token_limit(&self) -> u64 {
383 self.policy.max_message_tokens.min(self.policy.max_decoded_units)
384 }
385
386 pub fn hello(&self) -> Message {
387 Message::Hello { protocol: PROTOCOL_VERSION, peer: self.name.clone(), software: format!("kute {}", kute::KUTE_VERSION) }
388 }
389
390 pub fn capabilities(&self) -> Message {
391 Message::Capabilities {
392 algorithms: self.engine.registry().algorithm_names(),
393 adapters: self.engine.registry().adapter_names(),
394 max_frame_bytes: self.policy.max_frame_bytes,
395 accepts_vocabularies: self.policy.accept_vocabularies,
396 accepts_proposals: self.policy.accept_proposals,
397 evolution_rules: vec![EVOLUTION_RULE.to_string()],
398 kvf_versions: vec![kute::KVF_VERSION.to_string()],
399 }
400 }
401
402 pub fn encode_message(&self, id: u64, digest: &str, raw: &[u8], policy: UnknownPolicy) -> Result<(Message, String)> {
405 let held = self.hold(digest)?;
406 let sequence = self.engine.encode_raw_open(held.tokenizer.as_ref(), raw, policy)?;
407 let expected = sha256_hex(&self.engine.decode_raw(held.tokenizer.as_ref(), &sequence)?);
408 Ok((Message::EncodedMessage { id, container: sequence.to_bytes_compressed()? }, expected))
409 }
410
411 pub fn evolve(&mut self, digest: &str, additions: &[Vec<String>], version: &str) -> Result<String> {
413 let version = Version::parse(version).map_err(|e| KuteError::InvalidIdentifier(format!("version {version:?}: {e}")))?;
414 let child = kute::bpe::sequence::evolve(&self.hold(digest)?.vocabulary, additions, version)?;
415 self.add_vocabulary(child)
416 }
417
418 pub fn translate(&self, sequence: &TokenSequence, to_digest: &str) -> Result<TokenSequence> {
421 let from = self.hold(&sequence.vocabulary_digest)?;
422 let to = self.hold(to_digest)?;
423 let units = kute::decoded_units(&from.vocabulary, sequence)?;
424 if units > self.policy.max_decoded_units {
425 return Err(KuteError::LimitExceeded(format!("the sequence decodes to {units} units")));
426 }
427 let bytes = kute::decoded_bytes_at_least(&from.vocabulary, sequence)?;
430 if bytes > self.policy.max_frame_bytes {
431 return Err(KuteError::LimitExceeded(format!("the sequence decodes to at least {bytes} bytes; a frame holds {}", self.policy.max_frame_bytes)));
432 }
433 to.tokenizer.encode_open(&from.tokenizer.decode(sequence)?, UnknownPolicy::Escape)
434 }
435
436 pub fn handle(&mut self, message: Message) -> Vec<Message> {
439 match (self.stage, &message) {
440 (Stage::New, Message::Hello { protocol, .. }) => {
441 if *protocol != PROTOCOL_VERSION {
442 return refuse(ErrorCode::UnsupportedProtocol, format!("this peer speaks protocol {PROTOCOL_VERSION}, not {protocol}"));
443 }
444 self.stage = Stage::Greeted;
445 return vec![self.hello()];
446 }
447 (Stage::Greeted, Message::Capabilities { .. }) => {
448 self.stage = Stage::Ready;
449 return vec![self.capabilities()];
450 }
451 (Stage::Ready, Message::Hello { .. } | Message::Capabilities { .. }) | (Stage::New | Stage::Greeted, _) => {
452 return refuse(ErrorCode::OutOfOrder, "expected HELLO, then CAPABILITIES, before anything else");
453 }
454 (Stage::Ready, _) => {}
455 }
456 match self.respond(message) {
457 Ok(replies) => replies,
458 Err(e) => {
459 let code = match e {
460 KuteError::LimitExceeded(_) => ErrorCode::TooLarge,
461 KuteError::VocabularyMismatch(_) => ErrorCode::UnknownVocabulary,
462 _ => ErrorCode::Invalid,
463 };
464 refuse(code, e.to_string())
465 }
466 }
467 }
468
469 fn respond(&mut self, message: Message) -> Result<Vec<Message>> {
470 match message {
471 Message::VocabAnnounce { vocabulary } => {
472 if self.held.contains_key(&vocabulary.digest) && self.sees(&vocabulary.digest) {
478 return Ok(vec![Message::VocabAccept { digest: vocabulary.digest }]);
479 }
480 if self.held.values().any(|h| {
481 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)
482 }) {
483 return Ok(refuse(
488 ErrorCode::VocabularyConflict,
489 format!("{} {} is held here with different content", vocabulary.id, vocabulary.version),
490 ));
491 }
492 if !self.engine.registry().algorithm_names().contains(&vocabulary.algorithm) {
493 return Ok(refuse(ErrorCode::UnsupportedAlgorithm, format!("algorithm {:?} is not available here", vocabulary.algorithm)));
494 }
495 if !self.policy.accept_vocabularies {
496 return Ok(refuse(ErrorCode::Refused, "this peer does not take vocabularies from the other side"));
497 }
498 if vocabulary.tokens > self.policy.max_vocabulary_tokens {
499 return Ok(refuse(ErrorCode::TooLarge, format!("vocabularies above {} tokens are not taken", self.policy.max_vocabulary_tokens)));
500 }
501 if let Some(refusal) = self.over_budget(vocabulary.tokens) {
502 return Ok(refusal);
503 }
504 let digest = vocabulary.digest.clone();
505 self.wanted = Some(vocabulary);
506 Ok(vec![Message::VocabRequest { digest }])
507 }
508 Message::VocabRequest { digest } => {
509 if !self.policy.give_vocabularies {
510 return Ok(refuse(ErrorCode::Refused, "this peer does not give out vocabularies"));
511 }
512 let kvf = kute::vocab::to_vec(&self.usable(&digest)?.vocabulary)?;
513 Ok(vec![Message::VocabData { digest, kvf }])
514 }
515 Message::VocabData { digest, kvf } => {
516 let Some(wanted) = self.wanted.take().filter(|w| w.digest == digest) else {
517 return Ok(refuse(ErrorCode::OutOfOrder, "vocabulary data that was not requested"));
518 };
519 let vocabulary = kute::vocab::from_slice(&kvf)?;
520 if vocabulary.compute_digest()? != digest || VocabRef::of(&vocabulary)? != wanted {
523 return Ok(refuse(ErrorCode::Invalid, "the vocabulary sent is not the one announced"));
524 }
525 if vocabulary.len() as u64 > self.policy.max_vocabulary_tokens {
526 return Ok(refuse(ErrorCode::TooLarge, "vocabulary exceeds the token limit"));
527 }
528 if let Some(refusal) = self.over_budget(vocabulary.len() as u64) {
530 return Ok(refusal);
531 }
532 if let Some(check) = &self.check {
533 if let Err(why) = check(&vocabulary) {
534 return Ok(refuse(ErrorCode::Refused, format!("the vocabulary is not taken: {why}")));
535 }
536 }
537 let report = self.engine.verify(&vocabulary)?;
538 if !report.ok() {
539 return Ok(refuse(ErrorCode::Invalid, format!("the vocabulary fails its own test vectors: {}", report.failures.join("; "))));
540 }
541 let digest = self.add_vocabulary(vocabulary)?;
542 self.show(&digest);
543 Ok(vec![Message::VocabAccept { digest }])
544 }
545 Message::SymbolQuery { digest, symbols } => {
546 if !self.policy.answer_queries {
547 return Ok(refuse(ErrorCode::Refused, "this peer does not answer questions about its vocabularies"));
548 }
549 let payload = TokenPayload::Symbols(symbols);
550 let token_id = self.usable(&digest)?.vocabulary.tokens.iter().find(|t| t.payload == payload).map(|t| t.id);
551 Ok(vec![Message::SymbolInfo { digest, token_id, content_hash: payload.content_hash() }])
552 }
553 Message::SymbolPropose { digest, additions, version, rule, signatures } => {
554 if !self.policy.accept_proposals {
555 return Ok(refuse(ErrorCode::Refused, "this peer does not accept vocabulary proposals"));
556 }
557 if self.check.is_some() && signatures.is_empty() {
558 return Ok(refuse(ErrorCode::Refused, "this peer takes only vocabularies that pass its check, and this proposal carries no signature of the vocabulary it derives"));
559 }
560 if signatures.len() > MAX_PROPOSAL_SIGNATURES || signatures.iter().any(|s| s.key_id.len() > 256 || s.algorithm.len() > 64 || s.signature.len() > 1024) {
561 return Ok(refuse(ErrorCode::TooLarge, format!("a proposal carries at most {MAX_PROPOSAL_SIGNATURES} signatures, none with an overlong field")));
562 }
563 if rule != EVOLUTION_RULE {
566 return Ok(refuse(
567 ErrorCode::UnsupportedRule,
568 format!("the proposal uses evolution rule {rule:?}; this peer implements {EVOLUTION_RULE:?}"),
569 ));
570 }
571 let most: u64 = additions.iter().map(|a| 2 * a.len() as u64).sum();
573 let parent = self.usable(&digest)?.vocabulary.len() as u64;
574 if parent.saturating_add(most) > self.policy.max_vocabulary_tokens {
575 return Ok(refuse(ErrorCode::TooLarge, "the proposal would pass the vocabulary token limit"));
576 }
577 if let Some(refusal) = self.over_budget(parent.saturating_add(most)) {
578 return Ok(refusal);
579 }
580 let parsed = Version::parse(&version).map_err(|e| KuteError::InvalidIdentifier(format!("version {version:?}: {e}")))?;
585 let mut child = kute::bpe::sequence::evolve(&self.hold(&digest)?.vocabulary, &additions, parsed)?;
586 if !signatures.is_empty() {
587 child.seal()?;
591 child.integrity.as_mut().expect("sealed").signatures = signatures;
592 }
593 if let Some(check) = &self.check {
594 if let Err(why) = check(&child) {
595 return Ok(refuse(ErrorCode::Refused, format!("the proposed vocabulary is not taken: {why}")));
596 }
597 }
598 let digest = match self.add_vocabulary(child) {
599 Ok(digest) => digest,
600 Err(KuteError::VocabularyMismatch(why)) => return Ok(refuse(ErrorCode::VocabularyConflict, why)),
601 Err(e) => return Err(e),
602 };
603 self.show(&digest);
604 Ok(vec![Message::VocabAccept { digest }])
605 }
606 Message::Translate { id, container, to_digest } => {
607 if !self.policy.translate {
608 return Ok(refuse(ErrorCode::Refused, "this peer does not translate for the other side"));
609 }
610 let sequence = TokenSequence::from_bytes_bounded(&container, self.token_limit())?;
613 self.usable(&sequence.vocabulary_digest)?;
614 self.usable(&to_digest)?;
615 let translated = self.translate(&sequence, &to_digest)?;
616 Ok(vec![Message::EncodedMessage { id, container: translated.to_bytes_compressed()? }])
617 }
618 Message::EncodedMessage { id, container } => {
619 let fingerprint = sha256_hex(&container);
623 if let Some((_, first, receipt)) = self.seen.iter().find(|(seen, _, _)| *seen == id) {
624 return Ok(if *first == fingerprint {
625 vec![receipt.clone()]
626 } else {
627 refuse(ErrorCode::Invalid, format!("message id {id} was already used for different content"))
628 });
629 }
630 if self.inbox.len() as u64 >= self.policy.max_inbox_messages {
631 return Ok(refuse(ErrorCode::Busy, format!("the inbox holds {} messages, its limit", self.inbox.len())));
632 }
633 let sequence = TokenSequence::from_bytes_bounded(&container, self.token_limit())?;
634 let held = self.usable(&sequence.vocabulary_digest)?;
635 let units = kute::decoded_units(&held.vocabulary, &sequence)?;
636 let bytes = self.engine.decode_raw_within(held.tokenizer.as_ref(), &sequence, self.policy.max_decoded_units, self.policy.max_inbox_bytes)?;
637 let kept = (bytes.len() as u64).saturating_add(4 * sequence.ids.len() as u64).saturating_add(container.len() as u64);
640 if self.inbox_bytes.saturating_add(kept) > self.policy.max_inbox_bytes {
641 return Ok(refuse(ErrorCode::Busy, format!("the inbox holds {} bytes and takes at most {}", self.inbox_bytes, self.policy.max_inbox_bytes)));
642 }
643 let receipt = Message::Ack { id, units, sha256: sha256_hex(&bytes) };
644 self.inbox_bytes += kept;
645 self.inbox.push(Delivered { id, sequence, bytes });
646 self.seen.push_back((id, fingerprint, receipt.clone()));
647 while self.seen.len() as u64 > self.policy.replay_window {
648 self.seen.pop_front();
649 }
650 Ok(vec![receipt])
651 }
652 Message::VocabAccept { .. } | Message::SymbolInfo { .. } | Message::Ack { .. } | Message::Error { .. } => {
653 Ok(refuse(ErrorCode::OutOfOrder, "a reply arrived where a request was expected"))
654 }
655 Message::Hello { .. } | Message::Capabilities { .. } => Ok(refuse(ErrorCode::OutOfOrder, "the handshake is already complete")),
656 }
657 }
658}
659
660pub trait Transport {
662 fn send(&mut self, message: &Message) -> Result<()>;
663 fn recv(&mut self) -> Result<Option<Message>>;
665}
666
667pub struct Framed<S: Read + Write> {
670 stream: S,
671 max_frame: u64,
672}
673
674impl<S: Read + Write> Framed<S> {
675 pub fn new(stream: S, max_frame: u64) -> Self {
676 Self { stream, max_frame: max_frame.min(DEFAULT_MAX_FRAME) }
677 }
678}
679
680impl<S: Read + Write> Transport for Framed<S> {
681 fn send(&mut self, message: &Message) -> Result<()> {
682 let body = serde_json::to_vec(message)?;
683 if body.len() as u64 > self.max_frame {
684 return Err(KuteError::LimitExceeded(format!("message of {} bytes exceeds the frame limit of {}", body.len(), self.max_frame)));
685 }
686 self.stream.write_all(&(body.len() as u32).to_le_bytes())?;
687 self.stream.write_all(&body)?;
688 self.stream.flush()?;
689 Ok(())
690 }
691
692 fn recv(&mut self) -> Result<Option<Message>> {
693 let mut length = [0u8; 4];
694 let mut got = 0;
695 while got < 4 {
696 match self.stream.read(&mut length[got..]) {
697 Ok(0) if got == 0 => return Ok(None),
698 Ok(0) => return Err(KuteError::InvalidInput("the stream ended inside a frame header".into())),
699 Ok(n) => got += n,
700 Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}
701 Err(e) => return Err(e.into()),
702 }
703 }
704 let length = u32::from_le_bytes(length) as u64;
705 if length > self.max_frame {
706 return Err(KuteError::LimitExceeded(format!("incoming frame of {length} bytes exceeds the limit of {}", self.max_frame)));
707 }
708 let mut body = Vec::new();
711 (&mut self.stream).take(length).read_to_end(&mut body)?;
712 if body.len() as u64 != length {
713 return Err(KuteError::InvalidInput("the stream ended inside a frame".into()));
714 }
715 serde_json::from_slice(&body).map(Some).map_err(|e| KuteError::InvalidInput(format!("not a protocol message: {e}")))
716 }
717}
718
719#[derive(Clone, Debug, PartialEq, Eq)]
721pub struct Remote {
722 pub peer: String,
723 pub software: String,
724 pub algorithms: Vec<String>,
725 pub accepts_vocabularies: bool,
726 pub accepts_proposals: bool,
727 pub evolution_rules: Vec<String>,
728}
729
730fn peer_error(code: ErrorCode, message: String) -> KuteError {
731 KuteError::Backend(format!("the peer answered {code:?}: {message}"))
732}
733
734pub struct Session<T: Transport> {
736 pub peer: Peer,
737 transport: T,
738 next_id: u64,
739 remote: Option<Remote>,
740}
741
742impl<T: Transport> Session<T> {
743 pub fn new(peer: Peer, transport: T) -> Self {
744 Self { peer, transport, next_id: 1, remote: None }
745 }
746
747 fn ask(&mut self, message: &Message) -> Result<Message> {
748 self.transport.send(message)?;
749 match self.transport.recv()? {
750 Some(Message::Error { code, message }) => Err(peer_error(code, message)),
751 Some(reply) => Ok(reply),
752 None => Err(KuteError::Backend("the peer closed the connection".into())),
753 }
754 }
755
756 fn unexpected<R>(reply: Message) -> Result<R> {
757 Err(KuteError::Backend(format!("unexpected reply from the peer: {reply:?}")))
758 }
759
760 pub fn connect(&mut self) -> Result<Remote> {
762 let (peer, software) = match self.ask(&self.peer.hello())? {
763 Message::Hello { protocol, peer, software } if protocol == PROTOCOL_VERSION => (peer, software),
764 other => return Self::unexpected(other),
765 };
766 match self.ask(&self.peer.capabilities())? {
767 Message::Capabilities { algorithms, accepts_vocabularies, accepts_proposals, evolution_rules, .. } => {
768 let remote = Remote { peer, software, algorithms, accepts_vocabularies, accepts_proposals, evolution_rules };
769 self.remote = Some(remote.clone());
770 Ok(remote)
771 }
772 other => Self::unexpected(other),
773 }
774 }
775
776 pub fn share(&mut self, digest: &str) -> Result<bool> {
779 let vocabulary = VocabRef::of(&self.peer.hold(digest)?.vocabulary)?;
780 match self.ask(&Message::VocabAnnounce { vocabulary })? {
781 Message::VocabAccept { digest: d } if d == digest => Ok(false),
782 Message::VocabRequest { digest: d } if d == digest => {
783 let kvf = kute::vocab::to_vec(&self.peer.hold(digest)?.vocabulary)?;
784 match self.ask(&Message::VocabData { digest: digest.to_string(), kvf })? {
785 Message::VocabAccept { digest: d } if d == digest => Ok(true),
786 other => Self::unexpected(other),
787 }
788 }
789 other => Self::unexpected(other),
790 }
791 }
792
793 pub fn send(&mut self, digest: &str, raw: &[u8], policy: UnknownPolicy) -> Result<u64> {
797 let id = self.next_id;
798 self.next_id += 1;
799 let (message, expected) = self.peer.encode_message(id, digest, raw, policy)?;
800 match self.ask(&message)? {
801 Message::Ack { id: acked, units, sha256 } if acked == id => {
802 if sha256 != expected {
803 return Err(KuteError::Integrity("the peer decoded the message to different content".into()));
804 }
805 Ok(units)
806 }
807 other => Self::unexpected(other),
808 }
809 }
810
811 pub fn propose(&mut self, digest: &str, additions: &[Vec<String>], version: &str) -> Result<String> {
815 self.propose_signed(digest, additions, version, &|_| Ok(()))
816 }
817
818 pub fn propose_signed(&mut self, digest: &str, additions: &[Vec<String>], version: &str, sign: &dyn Fn(&mut Vocabulary) -> Result<()>) -> Result<String> {
823 if let Some(remote) = &self.remote {
824 if !remote.evolution_rules.iter().any(|r| r == EVOLUTION_RULE) {
825 return Err(KuteError::Unsupported(format!(
826 "the peer implements evolution rules {:?}, not {EVOLUTION_RULE:?}; a proposal would derive different vocabularies on the two sides",
827 remote.evolution_rules
828 )));
829 }
830 }
831 let parsed = Version::parse(version).map_err(|e| KuteError::InvalidIdentifier(format!("version {version:?}: {e}")))?;
832 let mut child = kute::bpe::sequence::evolve(&self.peer.hold(digest)?.vocabulary, additions, parsed)?;
833 child.seal()?;
834 let expected = child.digest()?;
835 sign(&mut child)?;
836 if child.compute_digest()? != expected {
837 return Err(KuteError::Integrity("signing changed the vocabulary".into()));
838 }
839 let propose = Message::SymbolPropose {
840 digest: digest.to_string(),
841 additions: additions.to_vec(),
842 version: version.to_string(),
843 rule: EVOLUTION_RULE.to_string(),
844 signatures: child.integrity.as_ref().map(|i| i.signatures.clone()).unwrap_or_default(),
845 };
846 match self.ask(&propose)? {
847 Message::VocabAccept { digest: theirs } if theirs == expected => self.peer.add_vocabulary(child),
848 Message::VocabAccept { digest: theirs } => {
849 Err(KuteError::Integrity(format!("the peer derived {theirs}, this side derived {expected}")))
850 }
851 other => Self::unexpected(other),
852 }
853 }
854
855 pub fn query(&mut self, digest: &str, symbols: &[String]) -> Result<Option<u32>> {
857 match self.ask(&Message::SymbolQuery { digest: digest.to_string(), symbols: symbols.to_vec() })? {
858 Message::SymbolInfo { token_id, .. } => Ok(token_id),
859 other => Self::unexpected(other),
860 }
861 }
862
863 pub fn translate(&mut self, sequence: &TokenSequence, to_digest: &str) -> Result<TokenSequence> {
866 let id = self.next_id;
867 self.next_id += 1;
868 let ask = Message::Translate { id, container: sequence.to_bytes_compressed()?, to_digest: to_digest.to_string() };
869 match self.ask(&ask)? {
870 Message::EncodedMessage { id: got, container } if got == id => {
871 let translated = TokenSequence::from_bytes(&container)?;
872 if translated.vocabulary_digest != to_digest {
873 return Err(KuteError::Integrity("the peer translated to a different vocabulary".into()));
874 }
875 Ok(translated)
876 }
877 other => Self::unexpected(other),
878 }
879 }
880
881 pub fn serve(&mut self) -> Result<u64> {
884 self.serve_observed(&mut |_, _| {})
885 }
886
887 pub fn serve_observed(&mut self, after: &mut dyn FnMut(&Peer, u64)) -> Result<u64> {
891 let mut handled = 0;
892 while let Some(message) = self.transport.recv()? {
893 for reply in self.peer.handle(message) {
894 self.transport.send(&reply)?;
895 }
896 handled += 1;
897 after(&self.peer, handled);
898 }
899 Ok(handled)
900 }
901}