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 take_inbox(&mut self) -> Vec<Delivered> {
326 self.inbox_bytes = 0;
327 std::mem::take(&mut self.inbox)
328 }
329
330 fn over_budget(&self, tokens: u64) -> Option<Vec<Message>> {
333 if self.held.len() as u64 >= self.policy.max_held_vocabularies {
334 return Some(refuse(ErrorCode::TooLarge, format!("this peer already holds {} vocabularies, its limit", self.held.len())));
335 }
336 let held: u64 = self.held.values().map(|h| h.vocabulary.len() as u64).sum();
337 if held.saturating_add(tokens) > self.policy.max_held_tokens {
338 return Some(refuse(
339 ErrorCode::TooLarge,
340 format!("this peer holds {held} tokens and takes at most {} in all", self.policy.max_held_tokens),
341 ));
342 }
343 None
344 }
345
346 pub fn engine(&self) -> &Engine {
347 &self.engine
348 }
349
350 fn hold(&self, digest: &str) -> Result<&Held> {
351 self.held.get(digest).ok_or_else(|| KuteError::VocabularyMismatch(format!("no vocabulary with digest {digest} is held")))
352 }
353
354 fn sees(&self, digest: &str) -> bool {
356 self.policy.vocabularies.as_ref().is_none_or(|listed| listed.contains(digest))
357 }
358
359 fn usable(&self, digest: &str) -> Result<&Held> {
362 if !self.sees(digest) {
363 return Err(KuteError::VocabularyMismatch(format!("no vocabulary with digest {digest} is held")));
364 }
365 self.hold(digest)
366 }
367
368 fn show(&mut self, digest: &str) {
370 if let Some(listed) = &mut self.policy.vocabularies {
371 listed.insert(digest.to_string());
372 }
373 }
374
375 fn token_limit(&self) -> u64 {
378 self.policy.max_message_tokens.min(self.policy.max_decoded_units)
379 }
380
381 pub fn hello(&self) -> Message {
382 Message::Hello { protocol: PROTOCOL_VERSION, peer: self.name.clone(), software: format!("kute {}", kute::KUTE_VERSION) }
383 }
384
385 pub fn capabilities(&self) -> Message {
386 Message::Capabilities {
387 algorithms: self.engine.registry().algorithm_names(),
388 adapters: self.engine.registry().adapter_names(),
389 max_frame_bytes: self.policy.max_frame_bytes,
390 accepts_vocabularies: self.policy.accept_vocabularies,
391 accepts_proposals: self.policy.accept_proposals,
392 evolution_rules: vec![EVOLUTION_RULE.to_string()],
393 kvf_versions: vec![kute::KVF_VERSION.to_string()],
394 }
395 }
396
397 pub fn encode_message(&self, id: u64, digest: &str, raw: &[u8], policy: UnknownPolicy) -> Result<(Message, String)> {
400 let held = self.hold(digest)?;
401 let sequence = self.engine.encode_raw_open(held.tokenizer.as_ref(), raw, policy)?;
402 let expected = sha256_hex(&self.engine.decode_raw(held.tokenizer.as_ref(), &sequence)?);
403 Ok((Message::EncodedMessage { id, container: sequence.to_bytes_compressed()? }, expected))
404 }
405
406 pub fn evolve(&mut self, digest: &str, additions: &[Vec<String>], version: &str) -> Result<String> {
408 let version = Version::parse(version).map_err(|e| KuteError::InvalidIdentifier(format!("version {version:?}: {e}")))?;
409 let child = kute::bpe::sequence::evolve(&self.hold(digest)?.vocabulary, additions, version)?;
410 self.add_vocabulary(child)
411 }
412
413 pub fn translate(&self, sequence: &TokenSequence, to_digest: &str) -> Result<TokenSequence> {
416 let from = self.hold(&sequence.vocabulary_digest)?;
417 let to = self.hold(to_digest)?;
418 let units = kute::decoded_units(&from.vocabulary, sequence)?;
419 if units > self.policy.max_decoded_units {
420 return Err(KuteError::LimitExceeded(format!("the sequence decodes to {units} units")));
421 }
422 let bytes = kute::decoded_bytes_at_least(&from.vocabulary, sequence)?;
425 if bytes > self.policy.max_frame_bytes {
426 return Err(KuteError::LimitExceeded(format!("the sequence decodes to at least {bytes} bytes; a frame holds {}", self.policy.max_frame_bytes)));
427 }
428 to.tokenizer.encode_open(&from.tokenizer.decode(sequence)?, UnknownPolicy::Escape)
429 }
430
431 pub fn handle(&mut self, message: Message) -> Vec<Message> {
434 match (self.stage, &message) {
435 (Stage::New, Message::Hello { protocol, .. }) => {
436 if *protocol != PROTOCOL_VERSION {
437 return refuse(ErrorCode::UnsupportedProtocol, format!("this peer speaks protocol {PROTOCOL_VERSION}, not {protocol}"));
438 }
439 self.stage = Stage::Greeted;
440 return vec![self.hello()];
441 }
442 (Stage::Greeted, Message::Capabilities { .. }) => {
443 self.stage = Stage::Ready;
444 return vec![self.capabilities()];
445 }
446 (Stage::Ready, Message::Hello { .. } | Message::Capabilities { .. }) | (Stage::New | Stage::Greeted, _) => {
447 return refuse(ErrorCode::OutOfOrder, "expected HELLO, then CAPABILITIES, before anything else");
448 }
449 (Stage::Ready, _) => {}
450 }
451 match self.respond(message) {
452 Ok(replies) => replies,
453 Err(e) => {
454 let code = match e {
455 KuteError::LimitExceeded(_) => ErrorCode::TooLarge,
456 KuteError::VocabularyMismatch(_) => ErrorCode::UnknownVocabulary,
457 _ => ErrorCode::Invalid,
458 };
459 refuse(code, e.to_string())
460 }
461 }
462 }
463
464 fn respond(&mut self, message: Message) -> Result<Vec<Message>> {
465 match message {
466 Message::VocabAnnounce { vocabulary } => {
467 if self.held.contains_key(&vocabulary.digest) && self.sees(&vocabulary.digest) {
473 return Ok(vec![Message::VocabAccept { digest: vocabulary.digest }]);
474 }
475 if self.held.values().any(|h| {
476 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)
477 }) {
478 return Ok(refuse(
483 ErrorCode::VocabularyConflict,
484 format!("{} {} is held here with different content", vocabulary.id, vocabulary.version),
485 ));
486 }
487 if !self.engine.registry().algorithm_names().contains(&vocabulary.algorithm) {
488 return Ok(refuse(ErrorCode::UnsupportedAlgorithm, format!("algorithm {:?} is not available here", vocabulary.algorithm)));
489 }
490 if !self.policy.accept_vocabularies {
491 return Ok(refuse(ErrorCode::Refused, "this peer does not take vocabularies from the other side"));
492 }
493 if vocabulary.tokens > self.policy.max_vocabulary_tokens {
494 return Ok(refuse(ErrorCode::TooLarge, format!("vocabularies above {} tokens are not taken", self.policy.max_vocabulary_tokens)));
495 }
496 if let Some(refusal) = self.over_budget(vocabulary.tokens) {
497 return Ok(refusal);
498 }
499 let digest = vocabulary.digest.clone();
500 self.wanted = Some(vocabulary);
501 Ok(vec![Message::VocabRequest { digest }])
502 }
503 Message::VocabRequest { digest } => {
504 if !self.policy.give_vocabularies {
505 return Ok(refuse(ErrorCode::Refused, "this peer does not give out vocabularies"));
506 }
507 let kvf = kute::vocab::to_vec(&self.usable(&digest)?.vocabulary)?;
508 Ok(vec![Message::VocabData { digest, kvf }])
509 }
510 Message::VocabData { digest, kvf } => {
511 let Some(wanted) = self.wanted.take().filter(|w| w.digest == digest) else {
512 return Ok(refuse(ErrorCode::OutOfOrder, "vocabulary data that was not requested"));
513 };
514 let vocabulary = kute::vocab::from_slice(&kvf)?;
515 if vocabulary.compute_digest()? != digest || VocabRef::of(&vocabulary)? != wanted {
518 return Ok(refuse(ErrorCode::Invalid, "the vocabulary sent is not the one announced"));
519 }
520 if vocabulary.len() as u64 > self.policy.max_vocabulary_tokens {
521 return Ok(refuse(ErrorCode::TooLarge, "vocabulary exceeds the token limit"));
522 }
523 if let Some(refusal) = self.over_budget(vocabulary.len() as u64) {
525 return Ok(refusal);
526 }
527 if let Some(check) = &self.check {
528 if let Err(why) = check(&vocabulary) {
529 return Ok(refuse(ErrorCode::Refused, format!("the vocabulary is not taken: {why}")));
530 }
531 }
532 let report = self.engine.verify(&vocabulary)?;
533 if !report.ok() {
534 return Ok(refuse(ErrorCode::Invalid, format!("the vocabulary fails its own test vectors: {}", report.failures.join("; "))));
535 }
536 let digest = self.add_vocabulary(vocabulary)?;
537 self.show(&digest);
538 Ok(vec![Message::VocabAccept { digest }])
539 }
540 Message::SymbolQuery { digest, symbols } => {
541 if !self.policy.answer_queries {
542 return Ok(refuse(ErrorCode::Refused, "this peer does not answer questions about its vocabularies"));
543 }
544 let payload = TokenPayload::Symbols(symbols);
545 let token_id = self.usable(&digest)?.vocabulary.tokens.iter().find(|t| t.payload == payload).map(|t| t.id);
546 Ok(vec![Message::SymbolInfo { digest, token_id, content_hash: payload.content_hash() }])
547 }
548 Message::SymbolPropose { digest, additions, version, rule, signatures } => {
549 if !self.policy.accept_proposals {
550 return Ok(refuse(ErrorCode::Refused, "this peer does not accept vocabulary proposals"));
551 }
552 if self.check.is_some() && signatures.is_empty() {
553 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"));
554 }
555 if signatures.len() > MAX_PROPOSAL_SIGNATURES || signatures.iter().any(|s| s.key_id.len() > 256 || s.algorithm.len() > 64 || s.signature.len() > 1024) {
556 return Ok(refuse(ErrorCode::TooLarge, format!("a proposal carries at most {MAX_PROPOSAL_SIGNATURES} signatures, none with an overlong field")));
557 }
558 if rule != EVOLUTION_RULE {
561 return Ok(refuse(
562 ErrorCode::UnsupportedRule,
563 format!("the proposal uses evolution rule {rule:?}; this peer implements {EVOLUTION_RULE:?}"),
564 ));
565 }
566 let most: u64 = additions.iter().map(|a| 2 * a.len() as u64).sum();
568 let parent = self.usable(&digest)?.vocabulary.len() as u64;
569 if parent.saturating_add(most) > self.policy.max_vocabulary_tokens {
570 return Ok(refuse(ErrorCode::TooLarge, "the proposal would pass the vocabulary token limit"));
571 }
572 if let Some(refusal) = self.over_budget(parent.saturating_add(most)) {
573 return Ok(refusal);
574 }
575 let parsed = Version::parse(&version).map_err(|e| KuteError::InvalidIdentifier(format!("version {version:?}: {e}")))?;
580 let mut child = kute::bpe::sequence::evolve(&self.hold(&digest)?.vocabulary, &additions, parsed)?;
581 if !signatures.is_empty() {
582 child.seal()?;
586 child.integrity.as_mut().expect("sealed").signatures = signatures;
587 }
588 if let Some(check) = &self.check {
589 if let Err(why) = check(&child) {
590 return Ok(refuse(ErrorCode::Refused, format!("the proposed vocabulary is not taken: {why}")));
591 }
592 }
593 let digest = match self.add_vocabulary(child) {
594 Ok(digest) => digest,
595 Err(KuteError::VocabularyMismatch(why)) => return Ok(refuse(ErrorCode::VocabularyConflict, why)),
596 Err(e) => return Err(e),
597 };
598 self.show(&digest);
599 Ok(vec![Message::VocabAccept { digest }])
600 }
601 Message::Translate { id, container, to_digest } => {
602 if !self.policy.translate {
603 return Ok(refuse(ErrorCode::Refused, "this peer does not translate for the other side"));
604 }
605 let sequence = TokenSequence::from_bytes_bounded(&container, self.token_limit())?;
608 self.usable(&sequence.vocabulary_digest)?;
609 self.usable(&to_digest)?;
610 let translated = self.translate(&sequence, &to_digest)?;
611 Ok(vec![Message::EncodedMessage { id, container: translated.to_bytes_compressed()? }])
612 }
613 Message::EncodedMessage { id, container } => {
614 let fingerprint = sha256_hex(&container);
618 if let Some((_, first, receipt)) = self.seen.iter().find(|(seen, _, _)| *seen == id) {
619 return Ok(if *first == fingerprint {
620 vec![receipt.clone()]
621 } else {
622 refuse(ErrorCode::Invalid, format!("message id {id} was already used for different content"))
623 });
624 }
625 if self.inbox.len() as u64 >= self.policy.max_inbox_messages {
626 return Ok(refuse(ErrorCode::Busy, format!("the inbox holds {} messages, its limit", self.inbox.len())));
627 }
628 let sequence = TokenSequence::from_bytes_bounded(&container, self.token_limit())?;
629 let held = self.usable(&sequence.vocabulary_digest)?;
630 let units = kute::decoded_units(&held.vocabulary, &sequence)?;
631 let bytes = self.engine.decode_raw_within(held.tokenizer.as_ref(), &sequence, self.policy.max_decoded_units, self.policy.max_inbox_bytes)?;
632 let kept = (bytes.len() as u64).saturating_add(4 * sequence.ids.len() as u64).saturating_add(container.len() as u64);
635 if self.inbox_bytes.saturating_add(kept) > self.policy.max_inbox_bytes {
636 return Ok(refuse(ErrorCode::Busy, format!("the inbox holds {} bytes and takes at most {}", self.inbox_bytes, self.policy.max_inbox_bytes)));
637 }
638 let receipt = Message::Ack { id, units, sha256: sha256_hex(&bytes) };
639 self.inbox_bytes += kept;
640 self.inbox.push(Delivered { id, sequence, bytes });
641 self.seen.push_back((id, fingerprint, receipt.clone()));
642 while self.seen.len() as u64 > self.policy.replay_window {
643 self.seen.pop_front();
644 }
645 Ok(vec![receipt])
646 }
647 Message::VocabAccept { .. } | Message::SymbolInfo { .. } | Message::Ack { .. } | Message::Error { .. } => {
648 Ok(refuse(ErrorCode::OutOfOrder, "a reply arrived where a request was expected"))
649 }
650 Message::Hello { .. } | Message::Capabilities { .. } => Ok(refuse(ErrorCode::OutOfOrder, "the handshake is already complete")),
651 }
652 }
653}
654
655pub trait Transport {
657 fn send(&mut self, message: &Message) -> Result<()>;
658 fn recv(&mut self) -> Result<Option<Message>>;
660}
661
662pub struct Framed<S: Read + Write> {
665 stream: S,
666 max_frame: u64,
667}
668
669impl<S: Read + Write> Framed<S> {
670 pub fn new(stream: S, max_frame: u64) -> Self {
671 Self { stream, max_frame: max_frame.min(DEFAULT_MAX_FRAME) }
672 }
673}
674
675impl<S: Read + Write> Transport for Framed<S> {
676 fn send(&mut self, message: &Message) -> Result<()> {
677 let body = serde_json::to_vec(message)?;
678 if body.len() as u64 > self.max_frame {
679 return Err(KuteError::LimitExceeded(format!("message of {} bytes exceeds the frame limit of {}", body.len(), self.max_frame)));
680 }
681 self.stream.write_all(&(body.len() as u32).to_le_bytes())?;
682 self.stream.write_all(&body)?;
683 self.stream.flush()?;
684 Ok(())
685 }
686
687 fn recv(&mut self) -> Result<Option<Message>> {
688 let mut length = [0u8; 4];
689 let mut got = 0;
690 while got < 4 {
691 match self.stream.read(&mut length[got..]) {
692 Ok(0) if got == 0 => return Ok(None),
693 Ok(0) => return Err(KuteError::InvalidInput("the stream ended inside a frame header".into())),
694 Ok(n) => got += n,
695 Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}
696 Err(e) => return Err(e.into()),
697 }
698 }
699 let length = u32::from_le_bytes(length) as u64;
700 if length > self.max_frame {
701 return Err(KuteError::LimitExceeded(format!("incoming frame of {length} bytes exceeds the limit of {}", self.max_frame)));
702 }
703 let mut body = Vec::new();
706 (&mut self.stream).take(length).read_to_end(&mut body)?;
707 if body.len() as u64 != length {
708 return Err(KuteError::InvalidInput("the stream ended inside a frame".into()));
709 }
710 serde_json::from_slice(&body).map(Some).map_err(|e| KuteError::InvalidInput(format!("not a protocol message: {e}")))
711 }
712}
713
714#[derive(Clone, Debug, PartialEq, Eq)]
716pub struct Remote {
717 pub peer: String,
718 pub software: String,
719 pub algorithms: Vec<String>,
720 pub accepts_vocabularies: bool,
721 pub accepts_proposals: bool,
722 pub evolution_rules: Vec<String>,
723}
724
725fn peer_error(code: ErrorCode, message: String) -> KuteError {
726 KuteError::Backend(format!("the peer answered {code:?}: {message}"))
727}
728
729pub struct Session<T: Transport> {
731 pub peer: Peer,
732 transport: T,
733 next_id: u64,
734 remote: Option<Remote>,
735}
736
737impl<T: Transport> Session<T> {
738 pub fn new(peer: Peer, transport: T) -> Self {
739 Self { peer, transport, next_id: 1, remote: None }
740 }
741
742 fn ask(&mut self, message: &Message) -> Result<Message> {
743 self.transport.send(message)?;
744 match self.transport.recv()? {
745 Some(Message::Error { code, message }) => Err(peer_error(code, message)),
746 Some(reply) => Ok(reply),
747 None => Err(KuteError::Backend("the peer closed the connection".into())),
748 }
749 }
750
751 fn unexpected<R>(reply: Message) -> Result<R> {
752 Err(KuteError::Backend(format!("unexpected reply from the peer: {reply:?}")))
753 }
754
755 pub fn connect(&mut self) -> Result<Remote> {
757 let (peer, software) = match self.ask(&self.peer.hello())? {
758 Message::Hello { protocol, peer, software } if protocol == PROTOCOL_VERSION => (peer, software),
759 other => return Self::unexpected(other),
760 };
761 match self.ask(&self.peer.capabilities())? {
762 Message::Capabilities { algorithms, accepts_vocabularies, accepts_proposals, evolution_rules, .. } => {
763 let remote = Remote { peer, software, algorithms, accepts_vocabularies, accepts_proposals, evolution_rules };
764 self.remote = Some(remote.clone());
765 Ok(remote)
766 }
767 other => Self::unexpected(other),
768 }
769 }
770
771 pub fn share(&mut self, digest: &str) -> Result<bool> {
774 let vocabulary = VocabRef::of(&self.peer.hold(digest)?.vocabulary)?;
775 match self.ask(&Message::VocabAnnounce { vocabulary })? {
776 Message::VocabAccept { digest: d } if d == digest => Ok(false),
777 Message::VocabRequest { digest: d } if d == digest => {
778 let kvf = kute::vocab::to_vec(&self.peer.hold(digest)?.vocabulary)?;
779 match self.ask(&Message::VocabData { digest: digest.to_string(), kvf })? {
780 Message::VocabAccept { digest: d } if d == digest => Ok(true),
781 other => Self::unexpected(other),
782 }
783 }
784 other => Self::unexpected(other),
785 }
786 }
787
788 pub fn send(&mut self, digest: &str, raw: &[u8], policy: UnknownPolicy) -> Result<u64> {
792 let id = self.next_id;
793 self.next_id += 1;
794 let (message, expected) = self.peer.encode_message(id, digest, raw, policy)?;
795 match self.ask(&message)? {
796 Message::Ack { id: acked, units, sha256 } if acked == id => {
797 if sha256 != expected {
798 return Err(KuteError::Integrity("the peer decoded the message to different content".into()));
799 }
800 Ok(units)
801 }
802 other => Self::unexpected(other),
803 }
804 }
805
806 pub fn propose(&mut self, digest: &str, additions: &[Vec<String>], version: &str) -> Result<String> {
810 self.propose_signed(digest, additions, version, &|_| Ok(()))
811 }
812
813 pub fn propose_signed(&mut self, digest: &str, additions: &[Vec<String>], version: &str, sign: &dyn Fn(&mut Vocabulary) -> Result<()>) -> Result<String> {
818 if let Some(remote) = &self.remote {
819 if !remote.evolution_rules.iter().any(|r| r == EVOLUTION_RULE) {
820 return Err(KuteError::Unsupported(format!(
821 "the peer implements evolution rules {:?}, not {EVOLUTION_RULE:?}; a proposal would derive different vocabularies on the two sides",
822 remote.evolution_rules
823 )));
824 }
825 }
826 let parsed = Version::parse(version).map_err(|e| KuteError::InvalidIdentifier(format!("version {version:?}: {e}")))?;
827 let mut child = kute::bpe::sequence::evolve(&self.peer.hold(digest)?.vocabulary, additions, parsed)?;
828 child.seal()?;
829 let expected = child.digest()?;
830 sign(&mut child)?;
831 if child.compute_digest()? != expected {
832 return Err(KuteError::Integrity("signing changed the vocabulary".into()));
833 }
834 let propose = Message::SymbolPropose {
835 digest: digest.to_string(),
836 additions: additions.to_vec(),
837 version: version.to_string(),
838 rule: EVOLUTION_RULE.to_string(),
839 signatures: child.integrity.as_ref().map(|i| i.signatures.clone()).unwrap_or_default(),
840 };
841 match self.ask(&propose)? {
842 Message::VocabAccept { digest: theirs } if theirs == expected => self.peer.add_vocabulary(child),
843 Message::VocabAccept { digest: theirs } => {
844 Err(KuteError::Integrity(format!("the peer derived {theirs}, this side derived {expected}")))
845 }
846 other => Self::unexpected(other),
847 }
848 }
849
850 pub fn query(&mut self, digest: &str, symbols: &[String]) -> Result<Option<u32>> {
852 match self.ask(&Message::SymbolQuery { digest: digest.to_string(), symbols: symbols.to_vec() })? {
853 Message::SymbolInfo { token_id, .. } => Ok(token_id),
854 other => Self::unexpected(other),
855 }
856 }
857
858 pub fn translate(&mut self, sequence: &TokenSequence, to_digest: &str) -> Result<TokenSequence> {
861 let id = self.next_id;
862 self.next_id += 1;
863 let ask = Message::Translate { id, container: sequence.to_bytes_compressed()?, to_digest: to_digest.to_string() };
864 match self.ask(&ask)? {
865 Message::EncodedMessage { id: got, container } if got == id => {
866 let translated = TokenSequence::from_bytes(&container)?;
867 if translated.vocabulary_digest != to_digest {
868 return Err(KuteError::Integrity("the peer translated to a different vocabulary".into()));
869 }
870 Ok(translated)
871 }
872 other => Self::unexpected(other),
873 }
874 }
875
876 pub fn serve(&mut self) -> Result<u64> {
879 let mut handled = 0;
880 while let Some(message) = self.transport.recv()? {
881 for reply in self.peer.handle(message) {
882 self.transport.send(&reply)?;
883 }
884 handled += 1;
885 }
886 Ok(handled)
887 }
888}