~ knotless Search/
↑↓ move↵ open⇧↵ all results
0
0

host: the firehose, with each commit's proof, and relays told of news

Merged chadtmiller.com asked to merge into main from chadtmiller.com/group-host:host/firehose
crates/atproto/src/drisl.rs+18−3
@@ -124,14 +124,21 @@ fn write(value: &Value, out: &mut Vec<u8>) {
/// The value `bytes` hold, all of them, refusing any form but DRISL's one.
pub fn decode(bytes: &[u8]) -> Result<Value, DrislError> {
let mut reader = Reader { bytes, at: 0 };
let value = reader.value(0)?;
if reader.at != bytes.len() {
let (value, read) = decode_first(bytes)?;
if read != bytes.len() {
return err("bytes after the value");
}
Ok(value)
}
/// The first value in `bytes`, and how many bytes it took: a firehose
/// frame is a header and a body, one after the other.
pub fn decode_first(bytes: &[u8]) -> Result<(Value, usize), DrislError> {
let mut reader = Reader { bytes, at: 0 };
let value = reader.value(0)?;
Ok((value, reader.at))
}
struct Reader<'a> {
bytes: &'a [u8],
at: usize,
@@ -243,6 +250,14 @@ impl Reader<'_> {
}
impl Value {
/// The map this is, if it is one.
pub fn into_map(self) -> Option<BTreeMap<String, Value>> {
match self {
Value::Map(map) => Some(map),
_ => None,
}
}
/// The value a record's JSON holds, as atproto writes it: an object
/// of `$link` alone a link, of `$bytes` alone bytes, a number with a
/// fraction refused.
crates/atproto/tests/drisl.rs+21−0
@@ -122,6 +122,27 @@ fn refuses_every_other_form() {
assert!(decode(&[vec![0x81; MAX_DEPTH], vec![0x01]].concat()).is_ok());
}
#[test]
fn says_whether_a_value_is_a_map() {
assert_eq!(
Value::Map(Default::default()).into_map(),
Some(Default::default())
);
assert_eq!(Value::Null.into_map(), None);
}
#[test]
fn reads_values_one_after_another() {
let frame = [
encode(&Value::Integer(1)),
encode(&Value::String("t".into())),
]
.concat();
let (first, read) = drisl::decode_first(&frame).unwrap();
assert_eq!((first, read), (Value::Integer(1), 1));
assert_eq!(decode(&frame[read..]).unwrap(), Value::String("t".into()));
}
#[test]
fn refuses_json_no_record_holds() {
let refused = |j: serde_json::Value| Value::from_json(&j).unwrap_err().to_string();
crates/group-host/src/config.rs+9−0
@@ -21,6 +21,8 @@ pub struct Config {
pub data_dir: PathBuf,
/// The PLC directory groups' identities are published to, `PLC_URL`.
pub plc_url: String,
/// The relays told of this host's news, `PDS_CRAWLERS`, comma-separated.
pub crawlers: Vec<String>,
}
impl Config {
@@ -50,6 +52,12 @@ impl Config {
}
let data_dir = var("DATA_DIR").unwrap_or_else(|| "data".into()).into();
let plc_url = var("PLC_URL").unwrap_or_else(|| "https://plc.directory".into());
let crawlers = var("PDS_CRAWLERS").unwrap_or_default();
let crawlers = crawlers
.split(',')
.map(|c| c.trim().trim_end_matches('/').to_string())
.filter(|c| !c.is_empty())
.collect();
Ok(Config {
port,
public_url,
@@ -57,6 +65,7 @@ impl Config {
handle_domain,
data_dir,
plc_url,
crawlers,
})
}
crates/group-host/src/firehose.rsnew+107−0
@@ -0,0 +1,107 @@
//! The firehose, `com.atproto.sync.subscribeRepos`: every event the host
//! keeps, after a cursor if one is given, then each as it happens, over a
//! WebSocket. A frame is a header (`op` 1 and the event's `t`) then its
//! body, both DRISL; a refusal, a header of `op` -1 and an error body.
use crate::Host;
use crate::store::Sequenced;
use crate::xrpc::XrpcError;
use atproto::{Value, drisl};
use axum::extract::ws::{Message, WebSocket, WebSocketUpgrade};
use axum::extract::{Query, State};
use axum::http::StatusCode;
use axum::response::Response;
use std::collections::{BTreeMap, HashMap};
use std::sync::Arc;
/// How many events are read from the database at a time.
const PAGE: u32 = 500;
fn map<const N: usize>(fields: [(&str, Value); N]) -> Value {
Value::Map(
fields
.into_iter()
.map(|(k, v)| (k.to_string(), v))
.collect(),
)
}
/// An event's frame: its header, then its body with its `seq`.
fn frame(event: &Sequenced) -> Vec<u8> {
let header = map([
("op", Value::Integer(1)),
("t", Value::String(event.kind.clone())),
]);
let body = drisl::decode(&event.body).expect("an event the host wrote");
let mut body = body.into_map().unwrap_or_default();
body.insert("seq".into(), Value::Integer(event.seq));
[drisl::encode(&header), drisl::encode(&Value::Map(body))].concat()
}
/// A refusal's frame.
fn refusal(error: &str, message: &str) -> Vec<u8> {
let header = map([("op", Value::Integer(-1))]);
let body = Value::Map(BTreeMap::from([
("error".into(), Value::String(error.into())),
("message".into(), Value::String(message.into())),
]));
[drisl::encode(&header), drisl::encode(&body)].concat()
}
pub async fn subscribe_repos(
ws: WebSocketUpgrade,
State(host): State<Arc<Host>>,
Query(params): Query<HashMap<String, String>>,
) -> Result<Response, XrpcError> {
let cursor = match params.get("cursor") {
None => None,
Some(c) => Some(c.parse::<i64>().map_err(|_| {
XrpcError::new(
StatusCode::BAD_REQUEST,
"InvalidRequest",
"cursor is a sequence number",
)
})?),
};
Ok(ws.on_upgrade(move |socket| stream(host, socket, cursor)))
}
/// Sends `socket` every event after `cursor`, or from now with none, then
/// each as it is made, until it goes away.
async fn stream(host: Arc<Host>, socket: WebSocket, cursor: Option<i64>) {
let _ = follow(host, socket, cursor).await;
}
/// The stream is over: its socket went away, or its cursor was refused.
struct Gone;
async fn follow(host: Arc<Host>, mut socket: WebSocket, cursor: Option<i64>) -> Result<(), Gone> {
// Told of new events from before the first read, so none goes unseen
// between reading and waiting.
let mut told = host.events.subscribe();
let last = host.store.last_seq().unwrap_or_default();
if cursor.is_some_and(|c| c > last) {
let refused = refusal("FutureCursor", "Cursor in the future.");
let _ = socket.send(Message::Binary(refused.into())).await;
return Err(Gone);
}
let mut from = cursor.unwrap_or(last);
loop {
let events = host.store.events_after(from, PAGE).unwrap_or_default();
for event in &events {
let sent = socket.send(Message::Binary(frame(event).into())).await;
sent.ok().ok_or(Gone)?;
from = event.seq;
}
if events.len() == PAGE as usize {
continue;
}
tokio::select! {
// A lagged receiver missed only wake-ups: the database has them.
_ = told.recv() => {}
said = socket.recv() => {
said.and_then(Result::ok).ok_or(Gone)?;
}
}
}
}
crates/group-host/src/lib.rs+14−0
@@ -5,10 +5,12 @@
pub mod api;
pub mod config;
pub mod firehose;
pub mod plc;
pub mod repo;
pub mod secrets;
pub mod store;
pub mod time;
pub mod xrpc;
use axum::extract::Path;
@@ -30,6 +32,11 @@ pub struct Host {
pub clock: atproto::tid::TidClock,
/// Held while a commit is made, so each builds on the one before.
writing: std::sync::Mutex<()>,
/// Told of each new event, which wakes the firehose's streams.
pub events: tokio::sync::broadcast::Sender<()>,
/// When the relays were last told of news.
crawled: std::sync::Mutex<Option<std::time::Instant>>,
http: reqwest::Client,
}
impl Host {
@@ -48,6 +55,9 @@ impl Host {
plc,
clock,
writing: Default::default(),
events: tokio::sync::broadcast::channel(16).0,
crawled: Default::default(),
http: reqwest::Client::new(),
})
}
}
@@ -68,6 +78,10 @@ pub fn router(host: Arc<Host>) -> Router {
get(api::get_latest_commit),
)
.route("/xrpc/com.atproto.sync.listRepos", get(api::list_repos))
.route(
"/xrpc/com.atproto.sync.subscribeRepos",
get(firehose::subscribe_repos),
)
.route(
"/xrpc/com.atproto.identity.resolveHandle",
get(api::resolve_handle),
crates/group-host/src/repo.rs+162−7
@@ -2,7 +2,8 @@
//! changing its records a signed commit at a time.
use crate::Host;
use crate::store::{Account, Change, Head};
use crate::store::{Account, Change, Event, Head};
use crate::time::{iso, now_millis};
use crate::xrpc::XrpcError;
use anyhow::{Result, ensure};
use atproto::mst::{Entry, Node, Tree};
@@ -106,13 +107,35 @@ impl Host {
handle: handle.to_string(),
signing,
};
let head = self.sign(&account, &Tree::build(&BTreeMap::new()));
let tree = Tree::build(&BTreeMap::new());
let head = self.sign(&account, &tree);
let at = Value::String(iso(now_millis()));
let events = [
event(
"#identity",
[
("did", Value::String(did.clone())),
("handle", Value::String(handle.into())),
("time", at.clone()),
],
),
event(
"#account",
[
("did", Value::String(did.clone())),
("active", Value::Bool(true)),
("time", at),
],
),
commit_event(&did, &head, None, None, Vec::new(), tree.blocks()),
];
// The handle checked above can still be taken as this was made:
// the database's unique handle is what holds.
let kept = self
.store
.create_account(&account, &head, now())
.create_account(&account, &head, now(), &events)
.map_err(XrpcError::internal)?;
self.announce();
kept.then_some(did).ok_or_else(taken)
}
@@ -151,7 +174,10 @@ impl Host {
.store
.paths(&account.did)
.map_err(XrpcError::internal)?;
let before = Tree::build(&paths);
let mut changes: Vec<Change> = Vec::new();
let mut ops = Vec::new();
let mut blocks = BTreeMap::new();
for write in writes {
let (collection, rkey, value, exists) = match write {
Write::Create {
@@ -181,26 +207,83 @@ impl Host {
return Err(invalid(format!("there is {what} {path}")));
}
let put = value.map(|v| record(collection, v)).transpose()?;
match &put {
Some((cid, _)) => paths.insert(path, *cid),
let prev = match &put {
Some((cid, bytes)) => {
blocks.insert(*cid, bytes.clone());
paths.insert(path.clone(), *cid)
}
None => paths.remove(&path),
};
ops.push(op(path, put.as_ref().map(|(cid, _)| *cid), prev));
changes.push((collection.clone(), rkey.clone(), put));
}
let new = self.sign(&account, &Tree::build(&paths));
let moved = self.store.commit(&account.did, &head.cid, &new, &changes);
let tree = Tree::build(&paths);
let new = self.sign(&account, &tree);
// What a reader needs to check the commit against the repo before
// it: the new nodes, and each changed path's covering proof.
blocks.extend(tree.new_since(&before));
for (collection, rkey, _) in &changes {
blocks.extend(tree.covering_proof(&format!("{collection}/{rkey}")));
}
let previous = Commit::from_bytes(&head.block).expect("a commit the host wrote");
let events = [commit_event(
&account.did,
&new,
Some(&head.rev),
Some(previous.data),
ops,
blocks,
)];
let moved = self
.store
.commit(&account.did, &head.cid, &new, &changes, &events);
moved
.and_then(|moved| {
ensure!(moved, "{did}'s repo moved under a write");
Ok(())
})
.map_err(XrpcError::internal)?;
self.announce();
Ok(Committed {
cid: new.cid,
rev: new.rev,
})
}
/// Wakes the firehose's streams, and tells the relays in
/// `PDS_CRAWLERS` this host has news: at most every twenty minutes,
/// and the first time after it starts, so a relay that marked it
/// offline comes back.
fn announce(&self) {
let _ = self.events.send(());
let mut last = self.crawled.lock().expect("not poisoned");
if last.is_some_and(|at| at.elapsed() < CRAWL_EVERY) {
return;
}
*last = Some(std::time::Instant::now());
let hostname = self
.config
.public_url
.split("://")
.nth(1)
.unwrap_or_default()
.to_string();
for crawler in self.config.crawlers.clone() {
let body = serde_json::json!({ "hostname": hostname });
let send = self
.http
.post(format!("{crawler}/xrpc/com.atproto.sync.requestCrawl"))
.json(&body)
.send();
tokio::spawn(async move {
let said = send.await.and_then(|r| r.error_for_status());
if let Err(e) = said {
tracing::warn!(crawler, error = %e, "requestCrawl failed");
}
});
}
}
/// `did`'s whole repo as a CAR file: its commit, then each node of its
/// tree, parents first, with the records it holds in the order it
/// holds them.
@@ -224,6 +307,78 @@ impl Host {
}
}
/// How long between telling the relays of news.
const CRAWL_EVERY: std::time::Duration = std::time::Duration::from_secs(20 * 60);
/// An event of `kind` with the fields given.
fn event<const N: usize>(kind: &'static str, fields: [(&str, Value); N]) -> Event {
let map = fields
.into_iter()
.map(|(k, v)| (k.to_string(), v))
.collect();
Event {
kind,
body: drisl::encode(&Value::Map(map)),
}
}
/// A commit's op: what changed at `path`, as the firehose has it.
fn op(path: String, cid: Option<Cid>, prev: Option<Cid>) -> Value {
let action = match (cid, prev) {
(Some(_), None) => "create",
(Some(_), Some(_)) => "update",
(None, _) => "delete",
};
let mut map = BTreeMap::from([
("action".to_string(), Value::String(action.into())),
("path".to_string(), Value::String(path)),
("cid".to_string(), cid.map_or(Value::Null, Value::Link)),
]);
if let Some(prev) = prev {
map.insert("prev".into(), Value::Link(prev));
}
Value::Map(map)
}
/// A `#commit` of `head`: its ops, and a CAR of `blocks` and the commit.
fn commit_event(
did: &str,
head: &Head,
since: Option<&str>,
prev_data: Option<Cid>,
ops: Vec<Value>,
mut blocks: BTreeMap<Cid, Vec<u8>>,
) -> Event {
blocks.insert(head.cid, head.block.clone());
let car = car::write(&[head.cid], blocks.iter().map(|(c, b)| (c, b.as_slice())));
let mut fields = vec![
("repo", Value::String(did.into())),
("commit", Value::Link(head.cid)),
("rev", Value::String(head.rev.clone())),
(
"since",
since.map_or(Value::Null, |s| Value::String(s.into())),
),
("blocks", Value::Bytes(car)),
("ops", Value::Array(ops)),
("blobs", Value::Array(Vec::new())),
("rebase", Value::Bool(false)),
("tooBig", Value::Bool(false)),
("time", Value::String(iso(now_millis()))),
];
if let Some(data) = prev_data {
fields.push(("prevData", Value::Link(data)));
}
let map = fields
.into_iter()
.map(|(k, v)| (k.to_string(), v))
.collect();
Event {
kind: "#commit",
body: drisl::encode(&Value::Map(map)),
}
}
fn walk<'a>(
node: &'a Node,
records: &'a BTreeMap<Cid, Vec<u8>>,
crates/group-host/src/store.rs+82−8
@@ -11,7 +11,8 @@ use std::path::Path;
use std::sync::{Mutex, MutexGuard};
/// Each version of the schema, applied in order to a database below it.
const MIGRATIONS: &[&str] = &["
const MIGRATIONS: &[&str] = &[
"
CREATE TABLE account (
did TEXT PRIMARY KEY,
handle TEXT NOT NULL UNIQUE,
@@ -33,12 +34,23 @@ const MIGRATIONS: &[&str] = &["
rev TEXT NOT NULL,
PRIMARY KEY (did, collection, rkey)
);
"];
",
"
CREATE TABLE event (
seq INTEGER PRIMARY KEY AUTOINCREMENT,
did TEXT NOT NULL,
kind TEXT NOT NULL,
body BLOB NOT NULL
);
",
];
const NEW_ACCOUNT: &str = "INSERT INTO account (did, handle, signing_key, created_at) VALUES (?1, ?2, ?3, ?4) ON CONFLICT (handle) DO NOTHING";
const PUT_RECORD: &str = "INSERT INTO record (did, collection, rkey, cid, value, rev) VALUES (?1, ?2, ?3, ?4, ?5, ?6) ON CONFLICT (did, collection, rkey) DO UPDATE SET cid = ?4, value = ?5, rev = ?6";
const LIST_UP: &str = "SELECT collection, rkey, cid, value FROM record WHERE did = ?1 AND collection = ?2 AND rkey > ?3 ORDER BY rkey LIMIT ?4";
const LIST_DOWN: &str = "SELECT collection, rkey, cid, value FROM record WHERE did = ?1 AND collection = ?2 AND rkey < ?3 ORDER BY rkey DESC LIMIT ?4";
const SEQUENCE: &str = "INSERT INTO event (did, kind, body) VALUES (?1, ?2, ?3)";
const EVENTS: &str = "SELECT seq, kind, body FROM event WHERE seq > ?1 ORDER BY seq LIMIT ?2";
const ACCOUNTS: &str =
"SELECT did, cid, rev, commit_block FROM repo WHERE did > ?1 ORDER BY did LIMIT ?2";
const COLLECTIONS: &str =
@@ -74,6 +86,31 @@ pub struct Record {
pub value: Vec<u8>,
}
/// An event for the firehose: its kind (`#commit`, `#identity`,
/// `#account`) and its body as DRISL, without its `seq`, which the
/// database gives it.
#[derive(Debug, Clone, PartialEq)]
pub struct Event {
pub kind: &'static str,
pub body: Vec<u8>,
}
/// An event as kept: its `seq`, kind and body.
#[derive(Debug, Clone, PartialEq)]
pub struct Sequenced {
pub seq: i64,
pub kind: String,
pub body: Vec<u8>,
}
fn sequence(tx: &rusqlite::Transaction, did: &str, events: &[Event]) -> Result<()> {
for e in events {
let added = tx.execute(SEQUENCE, params![did, e.kind, e.body]);
added?;
}
Ok(())
}
/// What a commit changes: a record put, or taken out (`None`).
pub type Change = (String, String, Option<(Cid, Vec<u8>)>);
@@ -115,9 +152,15 @@ impl Store {
self.conn.lock().expect("not poisoned")
}
/// Keeps a new account, with its first commit. `false` if its handle
/// is taken.
pub fn create_account(&self, account: &Account, head: &Head, now: i64) -> Result<bool> {
/// Keeps a new account, with its first commit and `events`. `false` if
/// its handle is taken.
pub fn create_account(
&self,
account: &Account,
head: &Head,
now: i64,
events: &[Event],
) -> Result<bool> {
let mut conn = self.conn();
let tx = conn.transaction()?;
let added = tx.execute(
@@ -137,6 +180,7 @@ impl Store {
params![account.did, head.cid.to_string(), head.rev, head.block],
);
kept?;
sequence(&tx, &account.did, events)?;
tx.commit()?;
Ok(true)
}
@@ -268,9 +312,17 @@ impl Store {
Ok(rows.collect::<rusqlite::Result<_>>()?)
}
/// Moves `did`'s repo from `prev` to `head`, with `changes`, unless
/// another commit moved it first: `false` then, and nothing changes.
pub fn commit(&self, did: &str, prev: &Cid, head: &Head, changes: &[Change]) -> Result<bool> {
/// Moves `did`'s repo from `prev` to `head`, with `changes` and
/// `events`, unless another commit moved it first: `false` then, and
/// nothing changes.
pub fn commit(
&self,
did: &str,
prev: &Cid,
head: &Head,
changes: &[Change],
events: &[Event],
) -> Result<bool> {
let mut conn = self.conn();
let tx = conn.transaction()?;
let moved = tx.execute(
@@ -299,7 +351,29 @@ impl Store {
};
done?;
}
sequence(&tx, did, events)?;
tx.commit()?;
Ok(true)
}
/// Up to `limit` events after `cursor`, in order.
pub fn events_after(&self, cursor: i64, limit: u32) -> Result<Vec<Sequenced>> {
let conn = self.conn();
let mut q = conn.prepare(EVENTS)?;
let rows = q.query_map(params![cursor, limit], |r| {
Ok(Sequenced {
seq: r.get(0)?,
kind: r.get(1)?,
body: r.get(2)?,
})
});
let rows = rows?;
Ok(rows.collect::<rusqlite::Result<_>>()?)
}
/// The last event's `seq`, 0 before any.
pub fn last_seq(&self) -> Result<i64> {
let conn = self.conn();
Ok(conn.query_row("SELECT COALESCE(MAX(seq), 0) FROM event", [], |r| r.get(0))?)
}
}
crates/group-host/src/time.rsnew+26−0
@@ -0,0 +1,26 @@
//! Times as atproto writes them: ISO 8601 in UTC, to the millisecond.
use std::time::{SystemTime, UNIX_EPOCH};
/// Milliseconds since 1970.
pub fn now_millis() -> i64 {
let since = SystemTime::now().duration_since(UNIX_EPOCH);
since.expect("after 1970").as_millis() as i64
}
/// `millis` since 1970 as `2026-11-03T21:14:28.123Z`.
pub fn iso(millis: i64) -> String {
let (days, ms) = (millis.div_euclid(86_400_000), millis.rem_euclid(86_400_000));
// Howard Hinnant's days_to_civil, for the proleptic Gregorian calendar.
let z = days + 719_468;
let era = z.div_euclid(146_097);
let doe = z.rem_euclid(146_097);
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let day = doy - (153 * mp + 2) / 5 + 1;
let month = if mp < 10 { mp + 3 } else { mp - 9 };
let year = yoe + era * 400 + i64::from(month <= 2);
let (h, m, s, f) = (ms / 3_600_000, ms / 60_000 % 60, ms / 1000 % 60, ms % 1000);
format!("{year:04}-{month:02}-{day:02}T{h:02}:{m:02}:{s:02}.{f:03}Z")
}
crates/group-host/tests/firehose.rsnew+259−0
@@ -0,0 +1,259 @@
//! The firehose: every event after a cursor, then each as it is made, as
//! sync 1.1 frames them; and the relays told of news.
mod common;
use atproto::{Commit, PublicKey, Value, car, drisl};
use axum::Router;
use axum::routing::post;
use common::{Running, start};
use futures::{SinkExt, StreamExt};
use group_host::repo::Write;
use serde_json::json;
use std::sync::{Arc, Mutex};
use std::time::Duration;
use tokio_tungstenite::tungstenite::Message;
const RIDERS: &str = "riders.groups.test";
fn create(rkey: &str) -> Write {
Write::Create {
collection: "fyi.opensocial.rule".into(),
rkey: rkey.into(),
value: json!({"$type": "fyi.opensocial.rule", "title": "Ride safe", "createdAt": "2026-11-03T00:00:00Z"}),
}
}
type Socket =
tokio_tungstenite::WebSocketStream<tokio_tungstenite::MaybeTlsStream<tokio::net::TcpStream>>;
async fn connect(h: &Running, query: &str) -> Socket {
let url = format!(
"{}/xrpc/com.atproto.sync.subscribeRepos{query}",
h.url.replace("http", "ws")
);
tokio_tungstenite::connect_async(url).await.unwrap().0
}
/// The next frame: its header and body.
async fn next(socket: &mut Socket) -> (Value, Value) {
let message = tokio::time::timeout(Duration::from_secs(5), socket.next())
.await
.unwrap()
.unwrap()
.unwrap();
let Message::Binary(bytes) = message else {
panic!("{message:?}")
};
let (header, read) = drisl::decode_first(&bytes).unwrap();
(header, drisl::decode(&bytes[read..]).unwrap())
}
fn field<'a>(v: &'a Value, k: &str) -> &'a Value {
let Value::Map(m) = v else { panic!("{v:?}") };
&m[k]
}
fn text(v: &Value) -> &str {
let Value::String(s) = v else { panic!("{v:?}") };
s
}
#[tokio::test]
async fn sends_every_event_after_a_cursor() {
let h = start(&[], false).await;
let did = h.host.create_account(RIDERS).await.unwrap();
h.host.write(&did, &[create("a")]).unwrap();
let mut socket = connect(&h, "?cursor=0").await;
let kinds: Vec<(String, i64)> = {
let mut seen = Vec::new();
let mut bodies = Vec::new();
for _ in 0..4 {
let (header, body) = next(&mut socket).await;
assert_eq!(field(&header, "op"), &Value::Integer(1));
let Value::Integer(seq) = field(&body, "seq") else {
panic!()
};
seen.push((text(field(&header, "t")).to_string(), *seq));
bodies.push(body);
}
// The account's first commit: no ops, nothing before it.
let first = &bodies[2];
assert_eq!(field(first, "since"), &Value::Null);
assert_eq!(field(first, "ops"), &Value::Array(vec![]));
assert_eq!(text(field(&bodies[0], "handle")), RIDERS);
assert_eq!(field(&bodies[1], "active"), &Value::Bool(true));
// The write: its op, its rev after the first's, and a CAR slice
// holding the commit, signed by the account, the new root and the
// new record.
let write = &bodies[3];
assert_eq!(text(field(write, "since")), text(field(first, "rev")));
let Value::Array(ops) = field(write, "ops") else {
panic!()
};
assert_eq!(text(field(&ops[0], "action")), "create");
assert_eq!(text(field(&ops[0], "path")), "fyi.opensocial.rule/a");
let Value::Bytes(blocks) = field(write, "blocks") else {
panic!()
};
let car = car::read(blocks).unwrap();
let Value::Link(cid) = field(write, "commit") else {
panic!()
};
assert_eq!(car.roots, vec![*cid]);
let commit = Commit::from_bytes(&car.blocks[cid]).unwrap();
let account = h.host.store.account(&did).unwrap().unwrap();
let key = PublicKey::from_did_key(&account.signing.public().did_key()).unwrap();
assert!(commit.verify(&key));
assert!(car.blocks.contains_key(&commit.data));
let Value::Link(record) = field(&ops[0], "cid") else {
panic!()
};
assert!(car.blocks.contains_key(record));
let previous = Commit::from_bytes(
&car::read(match field(first, "blocks") {
Value::Bytes(b) => b,
_ => panic!(),
})
.unwrap()
.blocks[match field(first, "commit") {
Value::Link(c) => c,
_ => panic!(),
}],
)
.unwrap();
assert_eq!(field(write, "prevData"), &Value::Link(previous.data));
seen
};
assert_eq!(
kinds,
[
("#identity".into(), 1),
("#account".into(), 2),
("#commit".into(), 3),
("#commit".into(), 4)
]
);
// Then each as it is made: an update and a delete, each with its prev.
h.host
.write(
&did,
&[
Write::Update {
collection: "fyi.opensocial.rule".into(),
rkey: "a".into(),
value: json!({"$type": "fyi.opensocial.rule", "title": "Ride safer", "createdAt": "2026-11-03T00:00:00Z"}),
},
],
)
.unwrap();
let (_, update) = next(&mut socket).await;
let Value::Array(ops) = field(&update, "ops") else {
panic!()
};
assert_eq!(text(field(&ops[0], "action")), "update");
assert!(matches!(field(&ops[0], "prev"), Value::Link(_)));
h.host
.write(
&did,
&[Write::Delete {
collection: "fyi.opensocial.rule".into(),
rkey: "a".into(),
}],
)
.unwrap();
let (_, delete) = next(&mut socket).await;
let Value::Array(ops) = field(&delete, "ops") else {
panic!()
};
assert_eq!(text(field(&ops[0], "action")), "delete");
assert_eq!(field(&ops[0], "cid"), &Value::Null);
// A message from the client changes nothing; closing ends the stream.
socket.send(Message::Text("hello".into())).await.unwrap();
socket.close(None).await.unwrap();
tokio::time::sleep(Duration::from_millis(100)).await;
}
#[tokio::test]
async fn follows_from_now_without_a_cursor() {
let h = start(&[], false).await;
let did = h.host.create_account(RIDERS).await.unwrap();
let mut socket = connect(&h, "").await;
h.host.write(&did, &[create("a")]).unwrap();
let (header, body) = next(&mut socket).await;
assert_eq!(text(field(&header, "t")), "#commit");
assert_eq!(field(&body, "seq"), &Value::Integer(4));
}
#[tokio::test]
async fn pages_through_a_long_history() {
let h = start(&[], false).await;
let did = h.host.create_account(RIDERS).await.unwrap();
for i in 0..510 {
h.host.write(&did, &[create(&format!("r{i:03}"))]).unwrap();
}
let mut socket = connect(&h, "?cursor=0").await;
for seq in 1..=513 {
let (_, body) = next(&mut socket).await;
assert_eq!(field(&body, "seq"), &Value::Integer(seq));
}
}
#[tokio::test]
async fn refuses_a_cursor_it_cannot_follow() {
let h = start(&[], false).await;
let mut socket = connect(&h, "?cursor=99").await;
let (header, body) = next(&mut socket).await;
assert_eq!(field(&header, "op"), &Value::Integer(-1));
assert_eq!(text(field(&body, "error")), "FutureCursor");
let url = format!(
"{}/xrpc/com.atproto.sync.subscribeRepos?cursor=x",
h.url.replace("http", "ws")
);
let refused = tokio_tungstenite::connect_async(url).await.unwrap_err();
assert!(refused.to_string().contains("400"), "{refused}");
}
#[tokio::test]
async fn tells_the_relays_of_news() {
let asked: Arc<Mutex<Vec<serde_json::Value>>> = Arc::default();
let seen = asked.clone();
let relay = Router::new().route(
"/xrpc/com.atproto.sync.requestCrawl",
post(
move |axum::Json(body): axum::Json<serde_json::Value>| async move {
seen.lock().unwrap().push(body);
},
),
);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let relay_url = format!("http://{}", listener.local_addr().unwrap());
tokio::spawn(async move { axum::serve(listener, relay).await.unwrap() });
// One relay that answers, one that is not there, and a blank.
let crawlers = format!("{relay_url}/, http://127.0.0.1:1, ");
let h = start(&[("PDS_CRAWLERS", crawlers.as_str())], false).await;
let did = h.host.create_account(RIDERS).await.unwrap();
h.host.write(&did, &[create("a")]).unwrap();
for _ in 0..50 {
if !asked.lock().unwrap().is_empty() {
break;
}
tokio::time::sleep(Duration::from_millis(20)).await;
}
tokio::time::sleep(Duration::from_millis(200)).await;
// Told once, though two things happened, as twenty minutes have not passed.
assert_eq!(
*asked.lock().unwrap(),
vec![json!({"hostname": "host.test"})]
);
assert_eq!(
h.host.config.crawlers,
vec![relay_url, "http://127.0.0.1:1".to_string()]
);
}
crates/group-host/tests/repos.rs+3−3
@@ -471,16 +471,16 @@ fn a_commit_builds_on_the_head_it_read() {
rev: commit.rev.clone(),
block: commit.to_bytes(),
};
assert!(store.create_account(&account, &head, 0).unwrap());
assert!(store.create_account(&account, &head, 0, &[]).unwrap());
// Another account at the same handle is turned away.
let twin = Account {
did: "did:plc:b".into(),
..account
};
assert!(!store.create_account(&twin, &head, 0).unwrap());
assert!(!store.create_account(&twin, &head, 0, &[]).unwrap());
// A commit from a head that is no longer the head changes nothing.
let stale = atproto::Cid::of_cbor(b"\xa0");
assert!(!store.commit("did:plc:a", &stale, &head, &[]).unwrap());
assert!(!store.commit("did:plc:a", &stale, &head, &[], &[]).unwrap());
assert_eq!(store.head("did:plc:a").unwrap().unwrap(), head);
}
crates/group-host/tests/time.rsnew+12−0
crates/group-host/Cargo.toml+2−0
docs/design/README.md+3−2
docs/reference/config.md+3−1
Cargo.lock+192−2
Cargo.toml+2−1