[relay] Wake-up: a push endpoint per mailbox, and a constant wake to it when a blob arrives
ci / check (pull_request) Has been cancelled

This commit is contained in:
2026-11-20 12:04:55 +01:00
parent f075fae0e3
commit f852b1a6d1
21 changed files with 1606 additions and 40 deletions
+54 -3
View File
@@ -2,6 +2,7 @@
//! address, and nothing here writes a request anywhere.
use crate::store::{Refused, Store};
use crate::wake::Waker;
use axum::body::Bytes;
use axum::extract::{DefaultBodyLimit, Path, State};
use axum::http::{header, HeaderMap, StatusCode};
@@ -11,8 +12,8 @@ use axum::{Json, Router};
use serde::de::DeserializeOwned;
use std::sync::Arc;
use tabellarius_protocol::{
CreateInvite, CreateMailbox, FetchedBlobs, InviteId, MailboxId, RotatePostToken, Sha256Hash,
Token, VersionInfo, MAX_BLOB_BYTES, VERSION,
CreateInvite, CreateMailbox, FetchedBlobs, InviteId, MailboxId, RotatePostToken, SetPush,
Sha256Hash, Token, VersionInfo, MAX_BLOB_BYTES, VERSION,
};
/// Unix seconds. The server passes the system clock; tests pass their own.
@@ -22,6 +23,23 @@ pub type Clock = Arc<dyn Fn() -> i64 + Send + Sync>;
pub struct AppState {
pub store: Arc<Store>,
pub clock: Clock,
/// Wakes a mailbox's owner when a blob arrives (`PROTOCOL.md` §6).
pub waker: Arc<Waker>,
}
impl AppState {
/// A relay that wakes only global `https://` endpoints: what a relay facing the internet runs.
pub fn new(store: Arc<Store>, clock: Clock) -> Self {
Self::with_waker(store, clock, Waker::new(false))
}
pub fn with_waker(store: Arc<Store>, clock: Clock, waker: Waker) -> Self {
Self {
store,
clock,
waker: Arc::new(waker),
}
}
}
/// JSON bodies are small: the largest is an invite with a 16 KiB KeyPackage in base64url.
@@ -35,6 +53,7 @@ pub fn router(state: AppState) -> Router {
.route("/v0/mailboxes", post(create_mailbox))
.route("/v0/mailboxes/{id}/blobs/{hash}", delete(acknowledge))
.route("/v0/mailboxes/{id}/post-token", put(rotate_post_token))
.route("/v0/mailboxes/{id}/push", put(set_push).delete(clear_push))
.route("/v0/invites", post(create_invite))
.route("/v0/invites/{id}", get(claim_invite))
.route("/version", get(version))
@@ -98,7 +117,12 @@ async fn post_blob(
) -> Result<StatusCode, Status> {
let id = mailbox(&id)?;
let token = bearer(&headers)?;
s.store.post(&id, &token, &body, (s.clock)())?;
let now = (s.clock)();
s.store.post(&id, &token, &body, now)?;
// Only after the blob is stored under a valid post token; the 201 does not wait for the wake.
if let Ok(Some(endpoint)) = s.store.push_endpoint(&id) {
s.waker.wake(Arc::clone(&s.store), id, endpoint, now);
}
Ok(StatusCode::CREATED)
}
@@ -139,6 +163,33 @@ async fn rotate_post_token(
Ok(StatusCode::NO_CONTENT)
}
async fn set_push(
State(s): State<AppState>,
Path(id): Path<String>,
headers: HeaderMap,
body: Bytes,
) -> Result<StatusCode, Status> {
let id = mailbox(&id)?;
let token = bearer(&headers)?;
let req: SetPush = json(&body)?;
if !s.waker.accepts(&req.endpoint) {
return Err(Status(StatusCode::BAD_REQUEST));
}
s.store.set_push(&id, &token, Some(&req.endpoint))?;
Ok(StatusCode::NO_CONTENT)
}
async fn clear_push(
State(s): State<AppState>,
Path(id): Path<String>,
headers: HeaderMap,
) -> Result<StatusCode, Status> {
let id = mailbox(&id)?;
let token = bearer(&headers)?;
s.store.set_push(&id, &token, None)?;
Ok(StatusCode::NO_CONTENT)
}
async fn create_invite(State(s): State<AppState>, body: Bytes) -> Result<StatusCode, Status> {
let req: CreateInvite = json(&body)?;
s.store.create_invite(&req, (s.clock)())?;
+13 -3
View File
@@ -4,6 +4,7 @@
pub mod http;
pub mod join;
pub mod store;
pub mod wake;
use std::net::SocketAddr;
use std::path::PathBuf;
@@ -17,17 +18,20 @@ pub struct Args {
pub listen: SocketAddr,
pub db: PathBuf,
pub limits: store::Limits,
/// `--push-loopback`: accept and wake `http://` loopback push endpoints. Tests only.
pub push_loopback: bool,
}
/// `--listen <addr:port>`, `--db <path>`, and the relay-wide quotas `--max-bytes`,
/// `--max-mailboxes`, `--max-invites` (positive integers). Anything else is refused with a usage
/// `--max-mailboxes`, `--max-invites` (positive integers), and `--push-loopback` (tests). Anything else is refused with a usage
/// line.
pub fn parse_args<I: IntoIterator<Item = String>>(args: I) -> Result<Args, String> {
let usage = "usage: tabellarius-relay [--listen 127.0.0.1:8470] [--db tabellarius-relay.db] \
[--max-bytes 1073741824] [--max-mailboxes 100000] [--max-invites 10000]";
[--max-bytes 1073741824] [--max-mailboxes 100000] [--max-invites 10000] \n [--push-loopback]";
let mut listen: SocketAddr = DEFAULT_LISTEN.parse().map_err(|_| usage.to_string())?;
let mut db = PathBuf::from(DEFAULT_DB);
let mut limits = store::Limits::default();
let mut push_loopback = false;
let mut it = args.into_iter();
let positive = |v: Option<String>| -> Result<i64, String> {
v.and_then(|v| v.parse::<i64>().ok())
@@ -39,6 +43,7 @@ pub fn parse_args<I: IntoIterator<Item = String>>(args: I) -> Result<Args, Strin
"--max-bytes" => limits.total_bytes = positive(it.next())?,
"--max-mailboxes" => limits.mailboxes = positive(it.next())?,
"--max-invites" => limits.invites = positive(it.next())?,
"--push-loopback" => push_loopback = true,
"--listen" => {
listen = it
.next()
@@ -54,5 +59,10 @@ pub fn parse_args<I: IntoIterator<Item = String>>(args: I) -> Result<Args, Strin
_ => return Err(usage.to_string()),
}
}
Ok(Args { listen, db, limits })
Ok(Args {
listen,
db,
limits,
push_loopback,
})
}
+7 -2
View File
@@ -1,5 +1,5 @@
//! `tabellarius-relay [--listen 127.0.0.1:8470] [--db tabellarius-relay.db] [--max-bytes N]
//! [--max-mailboxes N] [--max-invites N]`
//! [--max-mailboxes N] [--max-invites N] [--push-loopback]`
//!
//! Prints one line at start (version and address) and nothing per request.
@@ -8,6 +8,7 @@ use std::time::{Duration, SystemTime, UNIX_EPOCH};
use tabellarius_relay::http::{router, AppState, Clock};
use tabellarius_relay::parse_args;
use tabellarius_relay::store::Store;
use tabellarius_relay::wake::Waker;
fn now() -> i64 {
SystemTime::now()
@@ -63,7 +64,11 @@ async fn main() {
});
let clock: Clock = Arc::new(now);
let app = router(AppState { store, clock });
let app = router(AppState::with_waker(
store,
clock,
Waker::new(args.push_loopback),
));
let shutdown = async {
let _ = tokio::signal::ctrl_c().await;
};
+51 -3
View File
@@ -1,6 +1,6 @@
//! Every rule of the relay, over SQLite, with the clock passed in.
//!
//! The database holds exactly `docs/PROTOCOL.md` §5: three tables, and nothing about who connected.
//! The database holds exactly `docs/PROTOCOL.md` §5: four tables, and nothing about who connected.
//! A wrong token and an unknown id give the same [`Refused::NotFound`], so nobody can probe which
//! mailboxes or invites exist.
@@ -10,8 +10,8 @@ use std::sync::Mutex;
use subtle::ConstantTimeEq;
use tabellarius_protocol::{
blob_hash, day_of, hour_of, BlobBytes, ClaimedInvite, CreateInvite, CreateMailbox, FetchedBlob,
InviteId, KeyPackageBytes, MailboxId, Sha256Hash, Token, BLOB_TTL_SECS, INVITE_TTL_SECS,
MAX_BLOBS_PER_FETCH, MAX_BLOB_BYTES,
InviteId, KeyPackageBytes, MailboxId, PushEndpoint, Sha256Hash, Token, BLOB_TTL_SECS,
INVITE_TTL_SECS, MAX_BLOBS_PER_FETCH, MAX_BLOB_BYTES,
};
/// The schema, and nothing else (`PROTOCOL.md` §5). A column added here is a protocol change.
@@ -35,6 +35,10 @@ CREATE TABLE IF NOT EXISTS invites (
key_package BLOB NOT NULL,
expiry INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS push (
mailbox_id BLOB PRIMARY KEY NOT NULL,
endpoint TEXT NOT NULL
);
";
/// Why a request was refused. Deliberately coarse: it says nothing about which part was wrong.
@@ -351,6 +355,50 @@ impl Store {
})
}
/// Sets (`Some`) or removes (`None`) the mailbox's push endpoint. Needs the fetch token: only the
/// owner says where to be woken (`PROTOCOL.md` §6).
pub fn set_push(
&self,
id: &MailboxId,
token: &Token,
endpoint: Option<&PushEndpoint>,
) -> Result<(), Refused> {
let conn = self.conn();
Self::authorize(&conn, id, token, Column::Fetch)?;
match endpoint {
Some(e) => conn.execute(
"INSERT OR REPLACE INTO push (mailbox_id, endpoint) VALUES (?1, ?2)",
params![&id.as_bytes()[..], e.as_str()],
)?,
None => conn.execute(
"DELETE FROM push WHERE mailbox_id = ?1",
[&id.as_bytes()[..]],
)?,
};
Ok(())
}
/// The endpoint to wake after a blob was stored for this mailbox, if its owner gave one.
pub fn push_endpoint(&self, id: &MailboxId) -> Result<Option<String>, Refused> {
Ok(self
.conn()
.query_row(
"SELECT endpoint FROM push WHERE mailbox_id = ?1",
[&id.as_bytes()[..]],
|r| r.get(0),
)
.optional()?)
}
/// The push server said the endpoint is gone: removes it, unless the owner has set another since.
pub fn drop_push_if(&self, id: &MailboxId, endpoint: &str) -> Result<(), Refused> {
self.conn().execute(
"DELETE FROM push WHERE mailbox_id = ?1 AND endpoint = ?2",
params![&id.as_bytes()[..], endpoint],
)?;
Ok(())
}
/// Deletes blobs older than 30 days and invites past their expiry.
pub fn purge(&self, now: i64) -> Result<Purged, Refused> {
let conn = self.conn();
+257
View File
@@ -0,0 +1,257 @@
//! The relay's only outgoing request: a wake to a mailbox owner's push endpoint when a blob arrived
//! (`docs/PROTOCOL.md` §6, `.agents/features/wake-up.md` §2.2).
//!
//! The body is a constant; nothing of the mailbox, the blob or its sender goes out. A mailbox is
//! woken at most once a minute, remembered in memory only. The endpoint's host is resolved here and
//! every address that is not global is dropped before connecting, so a mailbox owner cannot point
//! the relay at its own network. Nothing about a wake is printed.
use crate::store::Store;
use std::collections::HashMap;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
use std::sync::{Arc, Mutex};
use std::time::Duration;
use tabellarius_protocol::{MailboxId, PushEndpoint, WAKE_BODY, WAKE_EVERY_SECS};
use tokio::sync::Semaphore;
use ureq::config::Config;
use ureq::http::Uri;
use ureq::unversioned::resolver::{DefaultResolver, ResolvedSocketAddrs, Resolver};
use ureq::unversioned::transport::{DefaultConnector, NextTimeout};
/// At most this many wakes are on their way at once; beyond that a wake is dropped.
pub const MAX_IN_FLIGHT: usize = 16;
/// A wake gives up after this long.
pub const WAKE_TIMEOUT: Duration = Duration::from_secs(10);
/// The in-memory "woken lately" map is pruned when it reaches this size.
const MAX_REMEMBERED: usize = 100_000;
pub struct Waker {
allow_loopback: bool,
/// Mailbox → the second it was last woken. Memory only: `PROTOCOL.md` §5 does not change.
woken: Mutex<HashMap<MailboxId, i64>>,
slots: Arc<Semaphore>,
agent: ureq::Agent,
}
/// What a wake came to; the tests read it, the relay only acts on `Gone`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Outcome {
Delivered,
/// 404 or 410: the endpoint no longer exists, so it is removed.
Gone,
/// Anything else: the network, a refused address, a timeout, another status.
Failed,
}
impl Waker {
/// `allow_loopback`: `http://` to a loopback host, and loopback addresses, for tests only
/// (`--push-loopback`). A relay facing the internet never sets it.
pub fn new(allow_loopback: bool) -> Self {
let config = Config::builder()
.timeout_global(Some(WAKE_TIMEOUT))
.max_redirects(0)
.http_status_as_error(false)
.proxy(None)
.build();
let agent = ureq::Agent::with_parts(
config,
DefaultConnector::default(),
GlobalOnly { allow_loopback },
);
Self {
allow_loopback,
woken: Mutex::new(HashMap::new()),
slots: Arc::new(Semaphore::new(MAX_IN_FLIGHT)),
agent,
}
}
/// Whether this relay accepts the endpoint at all.
pub fn accepts(&self, endpoint: &PushEndpoint) -> bool {
!endpoint.is_loopback_http() || self.allow_loopback
}
/// After a blob was stored: wakes the mailbox's owner, unless it was woken in the last minute or
/// too many wakes are on their way. Returns at once; the request runs in the background.
pub fn wake(&self, store: Arc<Store>, id: MailboxId, endpoint: String, now: i64) -> bool {
if !self.due(id, now) {
return false;
}
let Ok(slot) = Arc::clone(&self.slots).try_acquire_owned() else {
return false;
};
let agent = self.agent.clone();
tokio::task::spawn_blocking(move || {
let _slot = slot;
if send(&agent, &endpoint) == Outcome::Gone {
let _ = store.drop_push_if(&id, &endpoint);
}
});
true
}
/// Once a minute per mailbox. A clock that went back counts as due.
fn due(&self, id: MailboxId, now: i64) -> bool {
let mut woken = self.woken.lock().unwrap_or_else(|e| e.into_inner());
if let Some(&last) = woken.get(&id) {
if (0..WAKE_EVERY_SECS).contains(&(now - last)) {
return false;
}
}
if woken.len() >= MAX_REMEMBERED {
woken.retain(|_, last| now - *last < WAKE_EVERY_SECS);
}
woken.insert(id, now);
true
}
}
/// One wake: the constant body and nothing else of the relay's.
pub fn send(agent: &ureq::Agent, endpoint: &str) -> Outcome {
let sent = agent
.post(endpoint)
.header("TTL", "86400")
.header("Urgency", "normal")
.header("Content-Type", "application/octet-stream")
.send(WAKE_BODY);
match sent.map(|r| r.status().as_u16()) {
Ok(200..=299) => Outcome::Delivered,
Ok(404 | 410) => Outcome::Gone,
_ => Outcome::Failed,
}
}
/// The system's resolver, with every address that is not global dropped.
#[derive(Debug)]
struct GlobalOnly {
allow_loopback: bool,
}
impl Resolver for GlobalOnly {
fn resolve(
&self,
uri: &Uri,
config: &Config,
timeout: NextTimeout,
) -> Result<ResolvedSocketAddrs, ureq::Error> {
let all = DefaultResolver::default().resolve(uri, config, timeout)?;
let mut kept = self.empty();
for addr in &all {
if reachable(addr.ip(), self.allow_loopback) {
kept.push(*addr);
}
}
if kept.is_empty() {
Err(ureq::Error::HostNotFound)
} else {
Ok(kept)
}
}
}
/// Whether the relay may connect to this address: global unicast only (loopback when allowed).
pub fn reachable(ip: IpAddr, allow_loopback: bool) -> bool {
match ip {
IpAddr::V4(v4) => v4_reachable(v4, allow_loopback),
IpAddr::V6(v6) => {
// An IPv4 address in IPv6 clothing is judged as the IPv4 address.
if let Some(v4) = v6.to_ipv4_mapped() {
return v4_reachable(v4, allow_loopback);
}
let s = v6.segments();
// NAT64 (64:ff9b::/96) reaches the IPv4 address in its last 32 bits.
if s[..6] == [0x64, 0xff9b, 0, 0, 0, 0] {
let v4 =
Ipv4Addr::new((s[6] >> 8) as u8, s[6] as u8, (s[7] >> 8) as u8, s[7] as u8);
return v4_reachable(v4, allow_loopback);
}
v6_reachable(v6, allow_loopback)
}
}
}
fn v4_reachable(ip: Ipv4Addr, allow_loopback: bool) -> bool {
if ip.is_loopback() {
return allow_loopback;
}
let o = ip.octets();
!(o[0] == 0 // "this network"
|| ip.is_private() // 10/8, 172.16/12, 192.168/16
|| ip.is_link_local() // 169.254/16
|| (o[0] == 100 && (o[1] & 0xc0) == 64) // CGNAT 100.64/10
|| (o[0] == 192 && o[1] == 0 && o[2] == 0) // IETF 192.0.0/24
|| ip.is_documentation()
|| (o[0] == 198 && (o[1] & 0xfe) == 18) // benchmarking 198.18/15
|| ip.is_multicast()
|| o[0] >= 240) // reserved and broadcast
}
fn v6_reachable(ip: Ipv6Addr, allow_loopback: bool) -> bool {
if ip.is_loopback() {
return allow_loopback;
}
let s = ip.segments();
!(ip.is_unspecified()
|| ip.is_multicast()
|| s[..6] == [0; 6] // IPv4-compatible ::/96
|| (s[0] & 0xfe00) == 0xfc00 // unique local fc00::/7
|| (s[0] & 0xffc0) == 0xfe80 // link-local fe80::/10
|| (s[0] & 0xffc0) == 0xfec0 // site-local fec0::/10
|| (s[0] == 0x2001 && s[1] == 0x0db8) // documentation
|| s[0] == 0x2002 // 6to4: an IPv4 address inside
|| (s[0] == 0x2001 && s[1] == 0) // Teredo
|| (s[0] == 0x0100 && s[1..4] == [0; 3])) // discard-only 100::/64
}
#[cfg(test)]
mod tests {
use super::*;
fn ok(text: &str) -> bool {
reachable(text.parse().expect("an address"), false)
}
#[test]
fn only_global_addresses_are_reachable() {
for global in ["1.1.1.1", "159.69.10.20", "2a01:4f8::1", "64:ff9b::808:808"] {
assert!(ok(global), "{global}");
}
for not in [
"127.0.0.1",
"10.1.2.3",
"172.16.0.1",
"192.168.1.1",
"169.254.169.254",
"100.64.0.1",
"0.0.0.0",
"192.0.0.8",
"192.0.2.1",
"198.18.0.1",
"224.0.0.1",
"255.255.255.255",
"::1",
"::",
"fc00::1",
"fd12::1",
"fe80::1",
"ff02::1",
"2001:db8::1",
"::ffff:10.0.0.1",
"::ffff:127.0.0.1",
"::10.0.0.1",
"64:ff9b::a00:1",
"2002:a00:1::",
"2001:0:4136:e378::1",
"100::1",
] {
assert!(!ok(not), "{not}");
}
}
#[test]
fn loopback_only_when_allowed() {
assert!(reachable("127.0.0.1".parse().expect("v4"), true));
assert!(reachable("::1".parse().expect("v6"), true));
assert!(!reachable("10.0.0.1".parse().expect("v4"), true));
}
}