AnyBot/src/wire.rs

92 lines
3.4 KiB
Rust

// (Shared with relay/.)
#![allow(dead_code)]
// One frame on the lasting connection between an AnyBot and the account server (a WebSocket):
// a small JSON header, then the body as raw bytes (no base64), in one binary message.
//
// Headers ("t" says which):
// server → AnyBot job {id, method, path, query, user, role, z, z_ok} a request for this AnyBot
// AnyBot → server reply {id, status, ctype, headers, z} its answer
// AnyBot → server call {id, to, method, path, query, z} a request for another AnyBot of the account
// server → AnyBot ret {id, status, ctype, z} that one's answer
// AnyBot → server hello {brain} what this AnyBot shows
// "z": the body is deflate-compressed. "z_ok": the asker can read a compressed answer.
use serde_json::Value;
pub fn pack(head: &Value, body: &[u8]) -> Vec<u8> {
let h = head.to_string();
let mut out = Vec::with_capacity(4 + h.len() + body.len());
out.extend_from_slice(&(h.len() as u32).to_be_bytes());
out.extend_from_slice(h.as_bytes());
out.extend_from_slice(body);
out
}
const MAX_HEAD: usize = 1024 * 1024;
pub fn unpack(b: &[u8]) -> Option<(Value, Vec<u8>)> {
let n = u32::from_be_bytes(b.get(..4)?.try_into().ok()?) as usize;
if n > MAX_HEAD {
return None;
}
let end = 4usize.checked_add(n)?;
let head = serde_json::from_slice(b.get(4..end)?).ok()?;
Some((head, b.get(end..)?.to_vec()))
}
/// How long a connection's loop waits to read before it sends what is queued: 2 ms while things
/// move (a live screen), 40 ms when quiet, 200 ms once nothing has moved for a while. A fixed
/// 40 ms added up to 40 ms to every message on each side of each hop — and woke every idle
/// connection 25 times a second, which on a relay with many machines is the whole CPU bill.
pub struct Pace {
moved: std::time::Instant,
wait: u64,
}
impl Pace {
pub fn new() -> Pace {
Pace { moved: std::time::Instant::now() - std::time::Duration::from_secs(5), wait: 0 }
}
/// Something was read or sent.
pub fn moved(&mut self) {
self.moved = std::time::Instant::now();
}
/// The read wait (ms) after this long without anything moving.
pub fn wait_for(quiet: std::time::Duration) -> u64 {
match quiet.as_secs() {
0..=1 => 2,
2..=19 => 40,
_ => 200,
}
}
/// Set the socket's read wait for now (only when it changes).
pub fn tune(&mut self, c: &std::net::TcpStream) {
let wait = Pace::wait_for(self.moved.elapsed());
if self.wait != wait {
self.wait = wait;
let _ = c.set_read_timeout(Some(std::time::Duration::from_millis(wait)));
}
}
}
#[cfg(test)]
mod tests {
#[test]
fn frames_round_trip() {
let head = serde_json::json!({"t": "job", "id": "a"});
let f = super::pack(&head, b"\x00\x01body");
let (h, b) = super::unpack(&f).unwrap();
assert_eq!(h, head);
assert_eq!(b, b"\x00\x01body");
assert!(super::unpack(&f[..3]).is_none());
}
#[test]
fn an_idle_connection_wakes_rarely() {
let s = std::time::Duration::from_secs;
assert_eq!(super::Pace::wait_for(s(0)), 2);
assert_eq!(super::Pace::wait_for(s(5)), 40);
assert_eq!(super::Pace::wait_for(s(60)), 200);
}
}