267 lines
13 KiB
Rust
267 lines
13 KiB
Rust
//! The Persona organ's chat transport: CultNet RUDP to Bifrost's Matrix mouth.
|
|
//!
|
|
//! The mouth (Bifrost `tools/persona-matrix-mouth.mjs`, `persona-chat-documents.mjs`)
|
|
//! listens on loopback as a RUDP server. Its connection id is derived from the
|
|
//! chat credential, so a peer without the credential cannot open the session:
|
|
//! the first four bytes of the SHA-256 of the key file's text, trimmed, read big
|
|
//! endian (`connection_id`). Each request is a `cultnet.document_put_raw.v0`
|
|
//! message on the `schema` channel carrying one `chat_client` document as a
|
|
//! positional MessagePack tuple; the mouth answers a pending request with a
|
|
//! pending document and a send with a receipt, and answers an ack with nothing.
|
|
//! A request it rejects (another Persona's name, a malformed tuple) gets no
|
|
//! answer either, so every wait here is bounded by `reply_timeout`.
|
|
//!
|
|
//! The session opens on the first call and closes when `RudpChat` drops; a
|
|
//! start that dies between a send and its ack repeats the send with the same
|
|
//! request id, which the mouth treats as the same send (`chat_client`).
|
|
|
|
use std::cell::RefCell;
|
|
use std::collections::BTreeSet;
|
|
use std::net::{SocketAddr, UdpSocket};
|
|
use std::time::{Duration, Instant};
|
|
|
|
use anyhow::{Context, Result, anyhow, bail};
|
|
use chrono::{SecondsFormat, Utc};
|
|
use cultnet_rs::{
|
|
CultNetMessage, CultNetRawDocumentRecord, CultNetRawPayloadEncoding, CultNetRudpSocketTransportConnection, CultNetRudpSocketTransportOptions,
|
|
};
|
|
use serde::Serialize;
|
|
use serde::de::DeserializeOwned;
|
|
use sha2::{Digest, Sha256};
|
|
|
|
use crate::chat_client::{
|
|
ACK, Chat, ChatAck, ChatFetchReceipt, ChatFetchRequest, ChatOpenDirectReceipt, ChatOpenDirectRequest, ChatPending, ChatPendingRequest, ChatRead, ChatRefusal, MouthRefused, Refusal, reply_warnings, ChatSendReceipt, ChatSendRequest, PENDING, PENDING_REQUEST, PENDING_REQUEST_V1, PENDING_REQUEST_V4, PENDING_V2, PENDING_V4, OPEN_DIRECT_RECEIPT, OPEN_DIRECT_REQUEST, FETCH_RECEIPT, FETCH_REQUEST, PENDING_V1, READ, REFUSAL, SEND_RECEIPT,
|
|
SEND_REQUEST, decode, encode,
|
|
};
|
|
|
|
/// The tag every chat document carries; the mouth refuses any other.
|
|
const TAG: &str = "cultnet.transport.rudp.v0";
|
|
/// The source role the mouth sees on a request.
|
|
const SOURCE_ROLE: &str = "persona-organ";
|
|
/// How long one datagram read waits before the loop polls resends.
|
|
const POLL: Duration = Duration::from_millis(20);
|
|
/// How soon an unacknowledged packet is sent again.
|
|
const RESEND_DELAY_MS: u64 = 50;
|
|
|
|
/// The mouth's connection id for a chat credential: `sha256(key)` first four
|
|
/// bytes, big endian, where `key` is the credential file's text trimmed of
|
|
/// surrounding whitespace as the mouth reads it.
|
|
pub fn connection_id(key_file_text: &str) -> u32 {
|
|
let digest = Sha256::digest(key_file_text.trim().as_bytes());
|
|
u32::from_be_bytes([digest[0], digest[1], digest[2], digest[3]])
|
|
}
|
|
|
|
struct Link {
|
|
transport: CultNetRudpSocketTransportConnection,
|
|
runtime_id: String,
|
|
}
|
|
|
|
/// `Chat` over one RUDP session to the mouth of one Persona.
|
|
pub struct RudpChat {
|
|
remote: SocketAddr,
|
|
connection_id: u32,
|
|
persona: String,
|
|
reply_timeout: Duration,
|
|
/// Ask for the answer with the reply link first. Off by default: a mouth that has not been told to answer it refuses the kind.
|
|
reply_link: bool,
|
|
/// Event ids whose dropped reply link has been warned of: one warning per event however often the answer is polled.
|
|
warned: RefCell<BTreeSet<String>>,
|
|
link: RefCell<Option<Link>>,
|
|
}
|
|
|
|
impl RudpChat {
|
|
/// `remote` is the mouth's loopback address, `connection_id` the credential's
|
|
/// (`connection_id`), `persona` the instance the mouth serves. Nothing is
|
|
/// sent until the first call.
|
|
pub fn new(remote: SocketAddr, connection_id: u32, persona: impl Into<String>, reply_timeout: Duration) -> Self {
|
|
Self { remote, connection_id, persona: persona.into(), reply_timeout, reply_link: false, warned: RefCell::new(BTreeSet::new()), link: RefCell::new(None) }
|
|
}
|
|
|
|
/// Ask the mouth for the reply link (`chat_pending.v4`) first. A mouth that refuses the kind is asked the older way.
|
|
pub fn with_reply_link(mut self, on: bool) -> Self {
|
|
self.reply_link = on;
|
|
self
|
|
}
|
|
|
|
/// How many distinct events this process has seen arrive with a reply link out of the mouth's contract, dropped.
|
|
pub fn reply_defects(&self) -> usize {
|
|
self.warned.borrow().len()
|
|
}
|
|
|
|
fn open(&self) -> Result<Link> {
|
|
let bind: SocketAddr = if self.remote.is_ipv4() { ([0, 0, 0, 0], 0).into() } else { ([0_u16; 8], 0).into() };
|
|
let socket = UdpSocket::bind(bind).context("the chat socket could not be opened")?;
|
|
socket.set_read_timeout(Some(POLL))?;
|
|
let runtime_id = format!("mind-persona-{}", self.persona);
|
|
let mut options = CultNetRudpSocketTransportOptions::client(runtime_id.clone(), socket, self.remote, self.connection_id);
|
|
options.resend_delay_ms = RESEND_DELAY_MS;
|
|
let mut transport = CultNetRudpSocketTransportConnection::new(options)?;
|
|
transport.connect(Vec::new())?;
|
|
let deadline = Instant::now() + self.reply_timeout;
|
|
while !transport.connected() {
|
|
if Instant::now() >= deadline {
|
|
bail!("the chat mouth did not accept the session");
|
|
}
|
|
transport.receive_once()?;
|
|
transport.poll_resends()?;
|
|
}
|
|
Ok(Link { transport, runtime_id })
|
|
}
|
|
|
|
/// Puts one document and, when `answer` names (kind, record key) pairs, waits for
|
|
/// the document the mouth answers it with. Documents of other kinds or keys
|
|
/// (a late receipt of an earlier send) are skipped.
|
|
///
|
|
/// A failed exchange drops the link: a restarted mouth silently ignores packets from a sender it has not connected, so a held link
|
|
/// would time out on every call after it. The next call opens a fresh one. Nothing is repeated on it: the caller's request id is
|
|
/// what makes a repeat of a send the same send.
|
|
fn exchange<T: Serialize>(&self, kind: &str, record_key: &str, document: &T, answer: Option<&[(&str, &str)]>) -> Result<Option<(String, Vec<u8>)>> {
|
|
let result = self.exchange_on_link(kind, record_key, document, answer);
|
|
if result.is_err()
|
|
&& let Some(mut link) = self.link.borrow_mut().take()
|
|
{
|
|
let _ = link.transport.disconnect(Vec::new());
|
|
}
|
|
result
|
|
}
|
|
|
|
fn exchange_on_link<T: Serialize>(&self, kind: &str, record_key: &str, document: &T, answer: Option<&[(&str, &str)]>) -> Result<Option<(String, Vec<u8>)>> {
|
|
let mut slot = self.link.borrow_mut();
|
|
if slot.is_none() {
|
|
*slot = Some(self.open()?);
|
|
}
|
|
let link = slot.as_mut().ok_or_else(|| anyhow!("the chat session is not open"))?;
|
|
let message = CultNetMessage::DocumentPutRaw {
|
|
message_id: format!("{kind}:{record_key}"),
|
|
document: CultNetRawDocumentRecord {
|
|
schema_id: kind.to_string(),
|
|
record_key: record_key.to_string(),
|
|
stored_at: Utc::now().to_rfc3339_opts(SecondsFormat::Millis, true),
|
|
payload_encoding: CultNetRawPayloadEncoding::Messagepack,
|
|
payload: encode(document)?,
|
|
source_runtime_id: Some(link.runtime_id.clone()),
|
|
source_agent_id: Some(self.persona.clone()),
|
|
source_role: Some(SOURCE_ROLE.to_string()),
|
|
tags: Some(vec![TAG.to_string()]),
|
|
},
|
|
};
|
|
link.transport.send_schema_message(&message)?;
|
|
let deadline = Instant::now() + self.reply_timeout;
|
|
let Some(answers) = answer else {
|
|
// Nothing is answered; the ack is done when the mouth has the packet.
|
|
let left = deadline.saturating_duration_since(Instant::now());
|
|
link.transport.flush_reliable(left)?;
|
|
return Ok(None);
|
|
};
|
|
loop {
|
|
if Instant::now() >= deadline {
|
|
bail!("the chat mouth did not answer {kind}");
|
|
}
|
|
link.transport.poll_resends()?;
|
|
if let Some(CultNetMessage::DocumentPutRaw { document, .. }) = link.transport.receive_schema_message_once()? {
|
|
let tagged = document.tags.as_deref() == Some(&[TAG.to_string()][..]);
|
|
if tagged && answers.contains(&(document.schema_id.as_str(), document.record_key.as_str())) {
|
|
return Ok(Some((document.schema_id, document.payload)));
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
fn call<Q: Serialize, A: DeserializeOwned>(&self, kind: &str, key: &str, request: &Q, answer: (&str, &str)) -> Result<A> {
|
|
let (_, payload) = self.exchange(kind, key, request, Some(&[answer]))?.ok_or_else(|| anyhow!("no answer payload"))?;
|
|
decode(&payload)
|
|
}
|
|
}
|
|
|
|
impl Chat for RudpChat {
|
|
fn pending(&self, after_seq: u64) -> Result<ChatPending> {
|
|
let request = ChatPendingRequest { persona: self.persona.clone(), after_seq };
|
|
let p = self.persona.as_str();
|
|
let answers = [(PENDING_V4, p), (PENDING, p), (PENDING_V2, p), (PENDING_V1, p), (REFUSAL, p)];
|
|
// The newest kind first; a mouth that does not serve it answers `UnknownKind`, and is asked the next older way: v4 (reply link,
|
|
// only when on), v2 (addressing facts), v1 (none).
|
|
let asks: &[&str] = if self.reply_link { &[PENDING_REQUEST_V4, PENDING_REQUEST, PENDING_REQUEST_V1] } else { &[PENDING_REQUEST, PENDING_REQUEST_V1] };
|
|
let mut asked = asks.iter();
|
|
let (mut kind, mut payload) = self.exchange(asked.next().expect("at least one kind"), p, &request, Some(&answers))?.ok_or_else(|| anyhow!("no answer payload"))?;
|
|
while kind == REFUSAL && decode::<ChatRefusal>(&payload)?.refusal == Refusal::UnknownKind {
|
|
let Some(older) = asked.next() else { break };
|
|
(kind, payload) = self.exchange(older, p, &request, Some(&answers))?.ok_or_else(|| anyhow!("no answer payload"))?;
|
|
}
|
|
if kind == REFUSAL {
|
|
let refusal: ChatRefusal = decode(&payload)?;
|
|
bail!("the mouth refused the pending request: {}", refusal.refusal.name());
|
|
}
|
|
let pending: ChatPending = decode(&payload)?;
|
|
if pending.persona != self.persona {
|
|
bail!("the mouth answered for another Persona");
|
|
}
|
|
for line in reply_warnings(&pending, &mut self.warned.borrow_mut()) {
|
|
eprintln!("mind-chat: {line}");
|
|
}
|
|
Ok(pending)
|
|
}
|
|
|
|
fn send(&self, request: &ChatSendRequest) -> Result<ChatSendReceipt> {
|
|
let receipt: ChatSendReceipt = self.call(SEND_REQUEST, &request.request_id, request, (SEND_RECEIPT, &request.request_id))?;
|
|
if receipt.request_id != request.request_id {
|
|
bail!("the mouth answered another send");
|
|
}
|
|
Ok(receipt)
|
|
}
|
|
|
|
fn open_direct(&self, request: &ChatOpenDirectRequest) -> Result<ChatOpenDirectReceipt> {
|
|
// A mouth that does not serve the kind answers with a refusal keyed by the persona, not by the request: heard here,
|
|
// it ends the wait, and the open is known not to have been sent.
|
|
let p = self.persona.as_str();
|
|
let answers = [(OPEN_DIRECT_RECEIPT, request.request_id.as_str()), (REFUSAL, p)];
|
|
let (kind, payload) = self.exchange(OPEN_DIRECT_REQUEST, &request.request_id, request, Some(&answers))?.ok_or_else(|| anyhow!("no answer payload"))?;
|
|
if kind == REFUSAL {
|
|
let refusal: ChatRefusal = decode(&payload)?;
|
|
if refusal.persona != self.persona || refusal.refusal != Refusal::UnknownKind {
|
|
bail!("the mouth refused the open: {}", refusal.refusal.name());
|
|
}
|
|
return Err(MouthRefused(refusal.refusal).into());
|
|
}
|
|
let receipt: ChatOpenDirectReceipt = decode(&payload)?;
|
|
if receipt.request_id != request.request_id {
|
|
bail!("the mouth answered another open");
|
|
}
|
|
Ok(receipt)
|
|
}
|
|
|
|
fn fetch(&self, request: &ChatFetchRequest) -> Result<ChatFetchReceipt> {
|
|
// As an open: a mouth that does not serve the kind answers a refusal keyed by the persona, and the fetch is known not sent.
|
|
let p = self.persona.as_str();
|
|
let answers = [(FETCH_RECEIPT, request.request_id.as_str()), (REFUSAL, p)];
|
|
let (kind, payload) = self.exchange(FETCH_REQUEST, &request.request_id, request, Some(&answers))?.ok_or_else(|| anyhow!("no answer payload"))?;
|
|
if kind == REFUSAL {
|
|
let refusal: ChatRefusal = decode(&payload)?;
|
|
if refusal.persona != self.persona || refusal.refusal != Refusal::UnknownKind {
|
|
bail!("the mouth refused the fetch: {}", refusal.refusal.name());
|
|
}
|
|
return Err(MouthRefused(refusal.refusal).into());
|
|
}
|
|
let receipt: ChatFetchReceipt = decode(&payload)?;
|
|
if receipt.request_id != request.request_id {
|
|
bail!("the mouth answered another fetch");
|
|
}
|
|
Ok(receipt)
|
|
}
|
|
|
|
fn ack(&self, through_seq: u64) -> Result<()> {
|
|
let ack = ChatAck { persona: self.persona.clone(), through_seq };
|
|
self.exchange(ACK, &format!("{}:{through_seq}", self.persona), &ack, None).map(|_| ())
|
|
}
|
|
|
|
fn read(&self, read: &ChatRead) -> Result<()> {
|
|
self.exchange(READ, &format!("{}:{}", self.persona, read.event_id), read, None).map(|_| ())
|
|
}
|
|
}
|
|
|
|
impl Drop for RudpChat {
|
|
fn drop(&mut self) {
|
|
if let Some(mut link) = self.link.borrow_mut().take() {
|
|
let _ = link.transport.disconnect(Vec::new());
|
|
}
|
|
}
|
|
}
|