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

The relays are asked to read the host as it starts and every 20 minutes

Merged chadtmiller.com asked to merge into main from chadtmiller.com/group-host:relay/crawl-at-start
.changeset/crawl-at-start.mdnew+7−0
@@ -0,0 +1,7 @@
---
default: patch
---
# The relays are asked to read the host as it starts
The host asks each relay in `PDS_CRAWLERS` to read its firehose (`com.atproto.sync.requestCrawl`) as it starts, before it writes anything, and every 20 minutes after, whether or not it wrote anything. It asked only after writing an event, which a relay reading the host for the first time never received, so a new host's first group could miss the relays entirely. It logs `asked the relay to crawl` or `requestCrawl failed` for each relay each time.
crates/group-host/src/config.rs+2−1
@@ -37,7 +37,8 @@ pub struct Config {
/// Who this host starts groups for, `GROUP_FOUNDERS`, comma-separated
/// DIDs: anyone when it names none.
pub group_founders: Vec<String>,
/// The relays told of this host's news, `PDS_CRAWLERS`, comma-separated.
/// The relays asked to read this host's firehose, `PDS_CRAWLERS`,
/// comma-separated.
pub crawlers: Vec<String>,
/// The most bytes one blob may be, `BLOB_UPLOAD_LIMIT`.
pub blob_upload_limit: u64,
crates/group-host/src/firehose.rs+28−0
@@ -2,6 +2,7 @@
//! 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.
//! And the relays, asked to read it.
use crate::Host;
use crate::store::Sequenced;
@@ -13,10 +14,37 @@ use axum::http::StatusCode;
use axum::response::Response;
use std::collections::{BTreeMap, HashMap};
use std::sync::Arc;
use std::time::Duration;
/// How many events are read from the database at a time.
const PAGE: u32 = 500;
/// How long between asking the relays to read the firehose.
pub const CRAWL_EVERY: Duration = Duration::from_secs(20 * 60);
/// Asks each relay `PDS_CRAWLERS` names to read the firehose
/// (`requestCrawl`), now and then every `every`, whether or not anything
/// was written. A relay that starts reading a host takes only the events
/// after it connects, so it must be reading before a group's first events
/// go out. One that stopped reading a host, as after failing to reach it a
/// while, reads it again only when asked; asking one that reads already
/// changes nothing.
pub async fn crawling(host: Arc<Host>, every: Duration) {
let hostname = host.config.public_url.split("://").nth(1);
let body = serde_json::json!({ "hostname": hostname.unwrap_or_default() });
loop {
for crawler in &host.config.crawlers {
let url = format!("{crawler}/xrpc/com.atproto.sync.requestCrawl");
let asked = host.http.post(url).json(&body).send().await;
match asked.and_then(|r| r.error_for_status()) {
Ok(_) => tracing::info!(crawler, "asked the relay to crawl"),
Err(e) => tracing::warn!(crawler, error = %e, "requestCrawl failed"),
}
}
tokio::time::sleep(every).await;
}
}
fn map<const N: usize>(fields: [(&str, Value); N]) -> Value {
Value::Map(
fields
crates/group-host/src/lib.rs+4−3
@@ -87,8 +87,6 @@ pub struct Host {
writing: repo::Writing,
/// 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>>,
pub(crate) http: reqwest::Client,
/// The spaces the index is to read, and its wake.
indexing: std::sync::Mutex<std::collections::BTreeSet<String>>,
@@ -128,7 +126,6 @@ impl Host {
clock,
writing: Default::default(),
events: tokio::sync::broadcast::channel(16).0,
crawled: Default::default(),
http: client(),
indexing: Default::default(),
index_wake: Default::default(),
@@ -690,6 +687,10 @@ pub async fn serve(config: Config) -> anyhow::Result<()> {
// Every line from here kept for the operators too, written as it goes.
logs::sink(&host.logs);
tokio::spawn(admin::keeping(host.clone(), admin::FLUSH));
// The relays asked to read the firehose now, before anything is
// written, and again every twenty minutes, so one is reading when a
// group's first events go out.
tokio::spawn(firehose::crawling(host.clone(), firehose::CRAWL_EVERY));
let config = &host.config;
tracing::info!(
public_url = %config.public_url,
crates/group-host/src/repo.rs+1−33
@@ -467,38 +467,9 @@ impl Host {
Ok(Checked { path, put, blobs })
}
/// 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.
/// Wakes the firehose's streams: an event was written.
pub(crate) 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
@@ -519,9 +490,6 @@ impl Host {
}
}
/// How long between telling the relays of news.
const CRAWL_EVERY: std::time::Duration = std::time::Duration::from_secs(20 * 60);
/// An `#identity` event: `did` known as `handle`, for the relays to
/// read its document afresh.
pub(crate) fn identity(did: &str, handle: &str) -> Event {
crates/group-host/tests/firehose.rs+16−12
@@ -1,5 +1,5 @@
//! 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.
//! sync 1.1 frames them; and the relays asked to read it.
mod common;
@@ -323,8 +323,11 @@ async fn refuses_a_cursor_it_cannot_follow() {
assert!(refused.to_string().contains("400"), "{refused}");
}
/// The relays are asked to read the firehose at once and again every so
/// often, with nothing written, so one that stopped reading the host reads
/// it again before its next events.
#[tokio::test]
async fn tells_the_relays_of_news() {
async fn asks_the_relays_to_crawl_every_so_often() {
let asked: Arc<Mutex<Vec<serde_json::Value>>> = Arc::default();
let seen = asked.clone();
let relay = Router::new().route(
@@ -342,20 +345,21 @@ async fn tells_the_relays_of_news() {
// 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() {
let every = Duration::from_millis(50);
let crawling = group_host::firehose::crawling(h.host.clone(), every);
let going = tokio::spawn(crawling);
for _ in 0..100 {
if asked.lock().unwrap().len() >= 3 {
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"})]
);
going.abort();
let asked = asked.lock().unwrap().clone();
assert!(asked.len() >= 3, "{asked:?}");
assert!(asked.iter().all(|a| *a == json!({"hostname": "host.test"})));
// Nothing was written: the host asks all the same.
assert_eq!(h.host.store.last_seq().unwrap(), 0);
assert_eq!(
h.host.config.crawlers,
vec![relay_url, "http://127.0.0.1:1".to_string()]
crates/group-host/tests/serve.rs+40−4
@@ -17,15 +17,17 @@ impl Running {
}
fn start(data: &std::path::Path) -> Running {
start_logging(data, "off")
start_logging(data, "off", &[])
}
/// The binary, logging what `filter` lets through.
fn start_logging(data: &std::path::Path, filter: &str) -> Running {
/// The binary, logging what `filter` lets through, its environment `vars`
/// besides.
fn start_logging(data: &std::path::Path, filter: &str, vars: &[(&str, &str)]) -> Running {
let mut child = Command::new(env!("CARGO_BIN_EXE_group-host"))
.env("PORT", "0")
.env("DATA_DIR", data)
.env("RUST_LOG", filter)
.envs(vars.iter().copied())
.stdout(Stdio::piped())
.spawn()
.unwrap();
@@ -77,7 +79,7 @@ async fn answers_health_and_refuses_unknown_methods() {
#[tokio::test]
async fn keeps_the_lines_it_logs_and_counts_its_requests() {
let data = tempfile::tempdir().unwrap();
let host = start_logging(data.path(), "info");
let host = start_logging(data.path(), "info", &[]);
let http = reqwest::Client::new();
let asked = http.get(format!("{}/xrpc/org.atgrp.noSuchQuery", host.1));
let res = asked.send().await.unwrap();
@@ -124,6 +126,40 @@ async fn keeps_the_lines_it_logs_and_counts_its_requests() {
assert_eq!(report["routes"][0]["route"], "/xrpc/{nsid}");
}
/// As it starts, with nothing written, the host asks the relays to read
/// its firehose, so a relay reads it before a group's first events.
#[tokio::test]
async fn asks_the_relays_to_crawl_as_it_starts() {
let (told, mut asked) = tokio::sync::mpsc::unbounded_channel();
let ask = move |axum::Json(body): axum::Json<serde_json::Value>| {
let told = told.clone();
async move { told.send(body).unwrap() }
};
let route = "/xrpc/com.atproto.sync.requestCrawl";
let relay = axum::Router::new().route(route, axum::routing::post(ask));
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() });
let data = tempfile::tempdir().unwrap();
let vars = [
("PDS_CRAWLERS", relay_url.as_str()),
("PUBLIC_URL", "https://groups.example.com"),
];
let host = start_logging(data.path(), "off", &vars);
let wait = std::time::Duration::from_secs(10);
let said = tokio::time::timeout(wait, asked.recv()).await.unwrap();
assert_eq!(
said,
Some(serde_json::json!({"hostname": "groups.example.com"}))
);
// The relay may be asked before the host serves, and so before it
// listens for SIGTERM: once it answers, it stops as it should.
let health = reqwest::get(format!("{}/xrpc/_health", host.1)).await;
assert_eq!(health.unwrap().status(), 200);
assert!(host.stop().success());
}
#[test]
fn refuses_a_bad_environment() {
let out = Command::new(env!("CARGO_BIN_EXE_group-host"))
docs/design/groups.md+29−0
@@ -65,6 +65,35 @@ Details:
group's display name is 64 graphemes at most, and its description
2,000.
## How relays hear of a group
Apps learn of a group the way they learn of any account. A relay reads
the host's firehose (`com.atproto.sync.subscribeRepos`) and passes its
events on to them. Starting a group puts out its `#identity` and
`#account` events and its first commits, the declaration among them. A
relay that reads a host for the first time connects with no cursor, so
it takes only the events after it connects. If no relay is reading when
a group starts, none of them ever sees those events.
So the host asks each relay in `PDS_CRAWLERS` to read its firehose
(`com.atproto.sync.requestCrawl`) as it starts, before it writes
anything, and every 20 minutes after. It asks whether or not it wrote
anything, and asking a relay that's already reading changes nothing. A
relay stops reading a host it can't reach for a few minutes, as during a
long upgrade, and reads it again only when asked. The ask at the start
and the one every 20 minutes bring it back. Once a relay has taken one
event from the host, it reconnects with a cursor, and the host sends it
every event it missed, since the host keeps them all.
The host doesn't send a relay that connects with no cursor any events
from before it connected. An event stream starts such a subscriber at
its current position, and the host's events are one log that every
subscriber reads, so it can't put out events for one of them. A group
whose first events no relay saw reaches the relays with its next event,
such as a commit or a handle change. An app that reads only the
relays' commits still lacks the records written before that, and has to
read the group's repo itself (`com.atproto.sync.getRepo`).
## Its address
A group needs a name before it has a domain of its own. So the host gives
docs/design/README.md+2−2
@@ -56,8 +56,8 @@ under `org.atgrp.internal.*`, and may change.
- [Spaces](spaces.md): what a space is, who reads and writes, credentials,
and the index.
- [Groups](groups.md): starting a group, what it shows, its `about` record,
spaces, handle and own domain, and ending it.
- [Groups](groups.md): starting a group, how relays hear of it, what it
shows, its `about` record, spaces, handle and own domain, and ending it.
- [Membership](membership.md): roles, joining, invites, and leaving.
- [Signing in](signing-in.md): people, apps and MCP clients, and what a
token may do.
docs/reference/config.md+1−1
@@ -28,7 +28,7 @@ item of spaces and a trailing `/`.
| `ACTOR_SEARCH` | where `searchActors` looks up a handle as someone types it. `plc` reads the handles in `PLC_URL`'s own export a page at a time and keeps them a minute. Otherwise it's the URL of a service answering `tech.waow.typeahead.searchActors` | typeahead.waow.tech's when `PLC_URL` is `https://plc.directory`, else `plc` |
| `SIGNUP_PDS` | the PDS where someone without an account makes one, from the console's "Create one", through its authorization server's sign-up (`prompt=create`). It drops a trailing `/` | `https://bsky.social` |
| `DOMAIN_CHECK_AT` | where the host checks that a group's own domain reaches this host before it serves the group there. It asks this URL in the domain's place, with the domain as its `Host`. Use it when a host can't reach its own public addresses | the domain itself, over https |
| `PDS_CRAWLERS` | relays the host tells of news with `requestCrawl`, comma-separated, a trailing `/` dropped. It tells them at most every 20 minutes, and the first time after a start | none |
| `PDS_CRAWLERS` | relays the host asks to read its firehose with `requestCrawl`, comma-separated, a trailing `/` dropped. It asks them as it starts, before it writes anything, and every 20 minutes after, whether or not it wrote anything ([how relays hear of a group](../design/groups.md#how-relays-hear-of-a-group)) | none |
| `RUST_LOG` | what it logs, as `tracing-subscriber`'s filter reads it. Lines are JSON, written to stdout and kept in `logs.sqlite` for its operators | `info` |
| `HOST_ADMINS` | its operators, as comma-separated DIDs. These accounts may read its logs (`getLogs`) and how it's used (`getStats`) | none |
| `LOGS_KEEP` | how many lines logged at info and below it keeps to read back. It keeps a warning or an error the full 30 days, which is the most it keeps any line | 500000 |
docs/deploying.md+1−1