[relay] Calls: a long-poll on the fetch route, TURN credentials for coturn, wakes every 10 s; the module passes the TURN secret by systemd credential

This commit is contained in:
2026-12-03 00:29:07 +01:00
parent 1e2eed8e5b
commit 776e4ce39b
15 changed files with 654 additions and 22 deletions
+71 -4
View File
@@ -1,21 +1,24 @@
//! The HTTP face of the store. No logging, no connection info: a handler never sees the client's
//! address, and nothing here writes a request anywhere.
use crate::arrivals::{Arrivals, MAX_WAITERS};
use crate::store::{Refused, Store};
use crate::turn::Turn;
use crate::wake::Waker;
use axum::body::Bytes;
use axum::extract::rejection::BytesRejection;
use axum::extract::{DefaultBodyLimit, Path, State};
use axum::extract::{DefaultBodyLimit, Path, Query, State};
use axum::http::{header, HeaderMap, StatusCode};
use axum::response::{IntoResponse, Response};
use axum::routing::{delete, get, post, put};
use axum::{Json, Router};
use serde::de::DeserializeOwned;
use std::sync::Arc;
use std::time::Duration;
use tabellarius_protocol::{
CreateFile, CreateInvite, CreateMailbox, FetchedBlobs, FileId, InviteId, MailboxId,
RotatePostToken, SetPush, Sha256Hash, Token, VersionInfo, FILE_CHUNK_BYTES, MAX_BLOB_BYTES,
VERSION,
RotatePostToken, SetPush, Sha256Hash, Token, TurnCredentials, VersionInfo, FILE_CHUNK_BYTES,
MAX_BLOB_BYTES, MAX_WAIT_SECS, VERSION,
};
/// Unix seconds. The server passes the system clock; tests pass their own.
@@ -27,6 +30,10 @@ pub struct AppState {
pub clock: Clock,
/// Wakes a mailbox's owner when a blob arrives (`PROTOCOL.md` §6).
pub waker: Arc<Waker>,
/// Who is long-polling which mailbox, in memory only (`calls-relay.md`).
pub arrivals: Arc<Arrivals>,
/// TURN credentials for calls; `None` when the relay was started without a TURN secret.
pub turn: Option<Arc<Turn>>,
}
impl AppState {
@@ -40,8 +47,22 @@ impl AppState {
store,
clock,
waker: Arc::new(waker),
arrivals: Arc::new(Arrivals::new(MAX_WAITERS)),
turn: None,
}
}
/// Hands out TURN credentials under this secret and these URLs (`POST /v0/mailboxes/{id}/turn`).
pub fn with_turn(mut self, turn: Turn) -> Self {
self.turn = Some(Arc::new(turn));
self
}
/// At most `max` long-polls held at once, relay-wide (tests set a small one).
pub fn with_max_waiters(mut self, max: usize) -> Self {
self.arrivals = Arc::new(Arrivals::new(max));
self
}
}
/// JSON bodies are small: the largest is an invite with a 16 KiB KeyPackage in base64url.
@@ -63,6 +84,7 @@ pub fn router(state: AppState) -> Router {
.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/mailboxes/{id}/turn", post(turn_credentials))
.route("/v0/files", post(create_file))
.route("/v0/files/{id}", delete(delete_file))
.route("/v0/invites", post(create_invite))
@@ -141,6 +163,8 @@ async fn post_blob(
let token = bearer(&headers)?;
let now = (s.clock)();
s.store.post(&id, &token, &body, now)?;
// Anyone long-polling this mailbox is answered now.
s.arrivals.arrived(&id);
// 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);
@@ -148,15 +172,58 @@ async fn post_blob(
Ok(StatusCode::CREATED)
}
#[derive(serde::Deserialize)]
pub struct Wait {
wait: Option<u64>,
}
/// How long a fetch may be held: `?wait=` in seconds, at most [`MAX_WAIT_SECS`]; none means not at all.
pub fn clamp_wait(wait: Option<u64>) -> Duration {
Duration::from_secs(wait.unwrap_or(0).min(MAX_WAIT_SECS))
}
/// `GET …/blobs[?wait=N]`: the waiting blobs; with `wait` and none waiting, held until one arrives or N seconds
/// pass. The token is checked before anything is held, and the place is taken before the store is read, so a blob
/// posted in between is never missed.
async fn fetch_blobs(
State(s): State<AppState>,
Path(id): Path<String>,
Query(q): Query<Wait>,
headers: HeaderMap,
) -> Result<Json<FetchedBlobs>, Status> {
let id = mailbox(&id)?;
let token = bearer(&headers)?;
let wait = clamp_wait(q.wait);
let place = if wait.is_zero() { None } else { s.arrivals.enter(id) };
let Some(place) = place else {
return Ok(Json(FetchedBlobs { blobs: s.store.fetch(&id, &token)? }));
};
let notified = place.notify.notified();
tokio::pin!(notified);
notified.as_mut().enable();
let blobs = s.store.fetch(&id, &token)?;
Ok(Json(FetchedBlobs { blobs }))
if !blobs.is_empty() {
return Ok(Json(FetchedBlobs { blobs }));
}
let _ = tokio::time::timeout(wait, notified).await;
// The place is left when this returns.
Ok(Json(FetchedBlobs { blobs: s.store.fetch(&id, &token)? }))
}
/// `POST …/turn` with the fetch token: a TURN REST pair (`calls-relay.md`). 404 without a TURN secret or with a
/// wrong token, 429 over [`tabellarius_protocol::TURN_PER_HOUR`]. Nothing is stored.
async fn turn_credentials(
State(s): State<AppState>,
Path(id): Path<String>,
headers: HeaderMap,
) -> Result<Json<TurnCredentials>, Status> {
let turn = s.turn.as_ref().ok_or(Status(StatusCode::NOT_FOUND))?;
let id = mailbox(&id)?;
let token = bearer(&headers)?;
s.store.authorize_fetch(&id, &token)?;
turn.credentials(id, (s.clock)())
.map(Json)
.ok_or(Status(StatusCode::TOO_MANY_REQUESTS))
}
async fn acknowledge(