chadtmiller.com/group-host
atmosphere group host
0
0
The host indexes its groups' spaces, read from each writer's repo
crates/atproto/src/space.rs+86−0
| @@ -211,6 +211,17 @@ pub fn mac_header(kind: &str, mac: &[u8]) -> String { | ||
format!("type=\"{kind}\", ver=1, mac=:{}:", STANDARD.encode(mac)) | ||
} | ||
| ||
/// The MAC a `mac_header` of `kind` carries. | ||
pub fn parse_mac_header(header: &str, kind: &str) -> Result<Vec<u8>, SpaceError> { | ||
let ours = header.contains(&format!("type=\"{kind}\"")) && header.contains("ver=1"); | ||
let mac = header | ||
.split("mac=:") | ||
.nth(1) | ||
.and_then(|m| m.split(':').next()); | ||
let mac = mac.filter(|_| ours).and_then(|m| STANDARD.decode(m).ok()); | ||
mac.ok_or_else(|| SpaceError(format!("not a MAC header of {kind}"))) | ||
} | ||
| ||
/// The header asking for a MAC (`atproto-space-want-mac`), with the key | ||
/// share it is to be agreed from. | ||
pub fn want_mac_header(kind: &str, key_share: &str) -> String { | ||
| @@ -311,3 +322,78 @@ pub fn star(commit: &Commit, records: &BTreeMap<String, Vec<u8>>) -> Vec<u8> { | ||
} | ||
out | ||
} | ||
| ||
/// A varint at the front of `bytes`, and what follows it. | ||
fn read_varint(bytes: &[u8]) -> Result<(usize, &[u8]), SpaceError> { | ||
let mut n = 0usize; | ||
for (i, b) in bytes.iter().enumerate().take(10) { | ||
n |= usize::from(b & 0x7f) << (7 * i); | ||
if b & 0x80 == 0 { | ||
return Ok((n, &bytes[i + 1..])); | ||
} | ||
} | ||
err("a STAR archive cut short") | ||
} | ||
| ||
/// A frame at the front of `bytes`: its length, then that many bytes. | ||
fn read_frame(bytes: &[u8]) -> Result<(&[u8], &[u8]), SpaceError> { | ||
let (len, rest) = read_varint(bytes)?; | ||
if rest.len() < len { | ||
return err("a STAR archive cut short"); | ||
} | ||
Ok(rest.split_at(len)) | ||
} | ||
| ||
/// A repo's STAR archive read: its commit, and each record's DRISL by | ||
/// path. The records are not checked against the commit here: that is | ||
/// the reader's, as their CIDs are its set hash's elements. | ||
pub fn read_star(bytes: &[u8]) -> Result<(Commit, BTreeMap<String, Vec<u8>>), SpaceError> { | ||
let Some(mut rest) = bytes.strip_prefix(&STAR_MAGIC[..]) else { | ||
return err("not a STAR archive"); | ||
}; | ||
let (meta, after) = read_frame(rest)?; | ||
rest = after; | ||
let meta = drisl::decode(meta); | ||
let Ok(Value::Map(meta)) = meta else { | ||
return err("STAR metadata that is not a DRISL map"); | ||
}; | ||
let field = |key: &str| meta.get(key); | ||
let text = |key: &str| match field(key) { | ||
Some(Value::String(s)) => Some(s.clone()), | ||
_ => None, | ||
}; | ||
let data = match field("data") { | ||
Some(Value::Bytes(b)) if b.len() == 32 => { | ||
Some(<[u8; 32]>::try_from(b.as_slice()).expect("32 bytes")) | ||
} | ||
_ => None, | ||
}; | ||
let ours = text("$type").as_deref() == Some(COMMIT_MAC) | ||
&& field("ver") == Some(&Value::Integer(COMMIT_VERSION)); | ||
let (Some(repo), Some(space), Some(rev), Some(data), true) = | ||
(text("repo"), text("space"), text("rev"), data, ours) | ||
else { | ||
return err("not a repo's STAR archive"); | ||
}; | ||
let mut records = BTreeMap::new(); | ||
let mut last: Option<String> = None; | ||
while !rest.is_empty() { | ||
let (key, after) = read_frame(rest)?; | ||
let (value, after) = read_frame(after)?; | ||
rest = after; | ||
let path = String::from_utf8(key.to_vec()) | ||
.map_err(|_| SpaceError("a STAR key that is not text".into()))?; | ||
if last.as_deref().is_some_and(|l| l >= path.as_str()) { | ||
return err("a STAR archive's records out of order"); | ||
} | ||
last = Some(path.clone()); | ||
records.insert(path, value.to_vec()); | ||
} | ||
let commit = Commit { | ||
repo, | ||
space, | ||
rev, | ||
data, | ||
}; | ||
Ok((commit, records)) | ||
} | ||
crates/atproto/tests/space.rs+80−0
| @@ -2,6 +2,7 @@ | ||
//! `@atproto/space` (tests/reference/space-vectors.json, from pds.js). | ||
| ||
use atproto::cid::Cid; | ||
use atproto::drisl; | ||
use atproto::keys::{Curve, Keypair}; | ||
use atproto::space::{ | ||
COMMIT_MAC, Commit, LtHash, RECORD_MAC, STATE_BYTES, SpaceRef, decapsulate, element, | ||
| @@ -86,6 +87,24 @@ fn commits_records_and_archives_as_the_vectors_say() { | ||
let mac = commit.mac(&hex(&c["secretHex"])); | ||
assert_eq!(mac.to_vec(), hex(&c["macHex"])); | ||
assert_eq!(mac_header(COMMIT_MAC, &mac), s(&c["macHeader"])); | ||
assert_eq!( | ||
atproto::space::parse_mac_header(s(&c["macHeader"]), COMMIT_MAC).unwrap(), | ||
mac.to_vec() | ||
); | ||
for bad in [ | ||
"type=\"atproto-space-record\", ver=1, mac=:AAAA:", | ||
"type=\"atproto-space-repo\", ver=2, mac=:AAAA:", | ||
"type=\"atproto-space-repo\", ver=1", | ||
"type=\"atproto-space-repo\", ver=1, mac=:not base64!:", | ||
] { | ||
assert_eq!( | ||
atproto::space::parse_mac_header(bad, COMMIT_MAC) | ||
.unwrap_err() | ||
.to_string(), | ||
"not a MAC header of atproto-space-repo", | ||
"{bad}" | ||
); | ||
} | ||
assert_eq!(star(&commit, &records), hex(&c["starHex"])); | ||
| ||
let r = &v["record"]; | ||
| @@ -189,3 +208,64 @@ fn refuses_keys_and_headers_it_cannot_use() { | ||
); | ||
} | ||
} | ||
| ||
#[test] | ||
fn reads_a_star_archive_back() { | ||
let v = vectors(); | ||
let c = &v["commit"]; | ||
let star_bytes = hex(&c["starHex"]); | ||
let (commit, records) = atproto::space::read_star(&star_bytes).unwrap(); | ||
assert_eq!(commit.repo, s(&c["repo"])); | ||
assert_eq!(commit.space, s(&c["space"])); | ||
assert_eq!(commit.rev, s(&c["rev"])); | ||
assert_eq!(commit.data.to_vec(), hex(&c["dataHex"])); | ||
assert_eq!(star(&commit, &records), star_bytes); | ||
assert_eq!(records.len(), c["records"].as_array().unwrap().len()); | ||
| ||
// An empty repo is its commit alone. | ||
let (empty, none) = atproto::space::read_star(&star(&commit, &BTreeMap::new())).unwrap(); | ||
assert_eq!((empty, none.len()), (commit.clone(), 0)); | ||
| ||
let refused = |bytes: &[u8]| atproto::space::read_star(bytes).unwrap_err().to_string(); | ||
assert_eq!(refused(b"nope"), "not a STAR archive"); | ||
let magic = atproto::space::STAR_MAGIC.to_vec(); | ||
assert_eq!( | ||
refused(&[magic.clone(), vec![0x05, 1]].concat()), | ||
"a STAR archive cut short" | ||
); | ||
assert_eq!( | ||
refused(&[magic.clone(), vec![0xff; 11]].concat()), | ||
"a STAR archive cut short" | ||
); | ||
assert_eq!( | ||
refused(&[magic.clone(), vec![1, 0x00]].concat()), | ||
"STAR metadata that is not a DRISL map" | ||
); | ||
let not_a_commit = drisl::encode(&atproto::Value::Map(BTreeMap::from([( | ||
"$type".into(), | ||
atproto::Value::String("x".into()), | ||
)]))); | ||
let framed = |b: &[u8]| [vec![b.len() as u8], b.to_vec()].concat(); | ||
assert_eq!( | ||
refused(&[magic.clone(), framed(¬_a_commit)].concat()), | ||
"not a repo's STAR archive" | ||
); | ||
let head = star(&commit, &BTreeMap::new()); | ||
let record = |path: &str| [framed(path.as_bytes()), framed(b"\xa0")].concat(); | ||
assert_eq!( | ||
refused(&[head.clone(), record("b/1"), record("a/1")].concat()), | ||
"a STAR archive's records out of order" | ||
); | ||
assert_eq!( | ||
refused(&[head.clone(), record("a/1"), record("a/1")].concat()), | ||
"a STAR archive's records out of order" | ||
); | ||
assert_eq!( | ||
refused(&[head.clone(), framed(b"\xff"), framed(b"\xa0")].concat()), | ||
"a STAR key that is not text" | ||
); | ||
assert_eq!( | ||
refused(&[head, framed(b"a/1")].concat()), | ||
"a STAR archive cut short" | ||
); | ||
} | ||
crates/group-host/src/authority.rs+1−0
| @@ -189,6 +189,7 @@ impl Host { | ||
let Some(prev) = kept else { | ||
return Ok(()); | ||
}; | ||
self.reindex(space); | ||
let mut body = json!({ | ||
"space": space, | ||
"repo": repo, | ||
crates/group-host/src/group_lifecycle.rs+2−1
| @@ -92,7 +92,8 @@ pub async fn activate_group( | ||
/// keeps of them; the services syncing its spaces are told; its DID is | ||
/// ended. They are told first, while the group has a key to sign with: | ||
/// best effort, so a delete that then fails has told them of one that | ||
/// did not happen, and they find it again when they next read. What members wrote in its spaces is theirs, at their own PDSes. | ||
/// did not happen, and they find it again when they next read. What | ||
/// members wrote in its spaces is theirs, at their own PDSes. | ||
pub async fn delete_group( | ||
State(host): State<Arc<Host>>, | ||
headers: HeaderMap, | ||
crates/group-host/src/group_spaces.rs+11−8
| @@ -161,7 +161,10 @@ pub async fn update_space( | ||
let (access_collection, space_collection) = (format!("{NS}.access"), format!("{NS}.space")); | ||
let (space, current) = own_space(&host, &group, &body)?; | ||
let (meta, members) = (meta_space(&group), members_space(&group)); | ||
let readers = audience(&body, "readableBy")?.filter(|r| !r.is_empty()); | ||
let readers = audience(&body, "readableBy")?; | ||
if readers.as_ref().is_some_and(Vec::is_empty) { | ||
return Err(invalid("readableBy names who reads the space")); | ||
} | ||
let writers = audience(&body, "writableBy")?; | ||
let names = |list: &[Value]| -> Vec<String> { | ||
list.iter() | ||
| @@ -174,12 +177,6 @@ pub async fn update_space( | ||
if space == members && !names(readers).iter().any(|r| r == "member") { | ||
return Err(invalid("the members space stays readable by member")); | ||
} | ||
// Meta's readers are the group's visibility: it is declared only | ||
// while anyone may read it. | ||
if space == meta { | ||
host.declare(&group, names(readers).iter().any(|r| r == PUBLIC)) | ||
.await?; | ||
} | ||
} | ||
// Writing in the members space in one's own name is joining: who may | ||
// stays as it is. | ||
| @@ -188,7 +185,7 @@ pub async fn update_space( | ||
} | ||
if readers.is_some() || writers.is_some() || body.get("credentialScopes").is_some() { | ||
let mut access = current.clone(); | ||
if let Some(readers) = readers { | ||
if let Some(readers) = &readers { | ||
access["readableBy"] = json!(readers); | ||
} | ||
if let Some(writers) = writers { | ||
| @@ -204,6 +201,12 @@ pub async fn update_space( | ||
let put = put_in(&host, &group, &space, &access_collection, "self", access); | ||
let _written = put.await?; | ||
} | ||
// Meta's readers are the group's visibility: it is declared only while | ||
// anyone may read it, once the access record says so. | ||
if let Some(readers) = readers.as_ref().filter(|_| space == meta) { | ||
let declared = host.declare(&group, names(readers).iter().any(|r| r == PUBLIC)); | ||
declared.await?; | ||
} | ||
if let Some(name) = body["name"].as_str() { | ||
let (rkey, mut entry) = entry_of(&host, &group, &space)?; | ||
entry["name"] = json!(name); | ||
crates/group-host/src/identity.rs+17−6
| @@ -63,7 +63,13 @@ impl Resolver { | ||
kept_at_most, | ||
plc_url: plc_url.trim_end_matches('/').to_string(), | ||
did_web_scheme: did_web_scheme.to_string(), | ||
http: crate::client(), | ||
// A document or handle is at a host the caller names: one that | ||
// redirects is not followed elsewhere. | ||
http: reqwest::Client::builder() | ||
.timeout(crate::OUTGOING_TIMEOUT) | ||
.redirect(reqwest::redirect::Policy::none()) | ||
.build() | ||
.expect("a client builds"), | ||
kept: Mutex::default(), | ||
} | ||
} | ||
| @@ -118,7 +124,11 @@ impl Resolver { | ||
} | ||
None => { | ||
let url = format!("{resolver}/xrpc/com.atproto.identity.resolveHandle"); | ||
let asked = self.http.get(url).query(&[("handle", handle)]); | ||
let asked = self | ||
.http | ||
.get(url) | ||
.query(&[("handle", handle)]) | ||
.timeout(LOOKUP); | ||
let body = json(asked.send().await).await; | ||
body.and_then(|b| b["did"].as_str().map(String::from)) | ||
} | ||
| @@ -160,12 +170,13 @@ impl Resolver { | ||
} | ||
} | ||
| ||
/// A response's text, if it answered with one. | ||
/// A response's text, if it answered with one no longer than a document | ||
/// may be. | ||
async fn text(res: reqwest::Result<reqwest::Response>) -> Option<String> { | ||
res.ok()?.error_for_status().ok()?.text().await.ok() | ||
String::from_utf8(body(res.ok()?.error_for_status().ok()?).await.ok()?).ok() | ||
} | ||
| ||
/// A response's JSON, if it answered with some. | ||
/// A response's JSON, as [`text`] reads it. | ||
async fn json(res: reqwest::Result<reqwest::Response>) -> Option<Value> { | ||
res.ok()?.error_for_status().ok()?.json().await.ok() | ||
serde_json::from_slice(&body(res.ok()?.error_for_status().ok()?).await.ok()?).ok() | ||
} | ||
crates/group-host/src/index.rsnew+359−0
| @@ -0,0 +1,359 @@ | ||
//! The host's index of its groups' spaces: what each writer has written | ||
//! in each, read from wherever their repo is, so the host can answer for | ||
//! the space (`listSpaceRecords`) to whoever its access record lets read. | ||
//! | ||
//! The host is each space's authority, so it knows its writer set: each | ||
//! writer's revision and digest as their host last said. When a writer's | ||
//! digest is not the one the index came to, the index reads their repo: | ||
//! from the store, for a writer here; otherwise from their PDS, as any | ||
//! syncer reads a space, with a credential the group issues itself and a | ||
//! secret agreed against the writer's `#atproto_kem` key for each request. | ||
//! It reads on from its oplog when it has read the repo before, moving | ||
//! the set hash by each write, and checks it against the commit their | ||
//! host vouches for; or reads it whole, as a STAR archive, and checks it | ||
//! the same way. A record that is not a DRISL map is left out. | ||
//! | ||
//! As knotless's `space_sync.rs` reads a member's repo, and the | ||
//! prototype's `spaceIndex.ts` keeps what it reads. | ||
| ||
use crate::Host; | ||
use crate::store::SpaceHead; | ||
use crate::time::now_millis; | ||
use anyhow::{Context, Result, bail, ensure}; | ||
use atproto::space::{ | ||
COMMIT_MAC, Commit, LtHash, element, encapsulate, parse_mac_header, read_star, want_mac_header, | ||
}; | ||
use atproto::space_auth::{self, Kind, Make, sign_request}; | ||
use atproto::{Cid, Curve, Keypair, Value, did, drisl}; | ||
use serde_json::Value as Json; | ||
use std::collections::{BTreeMap, HashSet}; | ||
| ||
/// The most bytes a repo, or a page of its oplog, is read for. | ||
pub const REPO_AT_MOST: usize = 64 * 1024 * 1024; | ||
| ||
/// How many writes a page of an oplog is asked for. | ||
const PAGE: &str = "500"; | ||
| ||
/// What the index learned of a repo: by path, each record's CID and | ||
/// DRISL, or none for one taken out. | ||
type Changes = BTreeMap<String, Option<(Cid, Vec<u8>)>>; | ||
| ||
/// A writer's repo in a space, at their PDS, and how to ask for it. | ||
struct Remote { | ||
space: String, | ||
did: String, | ||
pds: String, | ||
kem: String, | ||
/// `Atproto-Space-Credential <jwt>`, the group's to its own space. | ||
authorization: String, | ||
/// The key the credential is bound to. | ||
key: Keypair, | ||
} | ||
| ||
/// An answer vouched for: the secret agreed for it, the MAC it carried, | ||
/// and its body. | ||
struct Vouched { | ||
secret: [u8; 32], | ||
mac: Vec<u8>, | ||
body: Vec<u8>, | ||
} | ||
| ||
impl Remote { | ||
async fn ask(&self, host: &Host, method: &str, params: &[(&str, &str)]) -> Result<Vouched> { | ||
let (share, secret) = encapsulate(&self.kem)?; | ||
let mut req = host | ||
.http | ||
.get(format!("{}/xrpc/com.atproto.space.{method}", self.pds)) | ||
.query(&[("space", self.space.as_str()), ("repo", self.did.as_str())]) | ||
.query(params) | ||
.header( | ||
"atproto-space-want-mac", | ||
want_mac_header(COMMIT_MAC, &share), | ||
); | ||
for (k, v) in sign_request(&self.key, &self.authorization, &self.did)? { | ||
req = req.header(k, v); | ||
} | ||
let res = req.send().await?.error_for_status()?; | ||
let header = res.headers().get("atproto-space-mac"); | ||
let header = header.and_then(|h| h.to_str().ok()).unwrap_or_default(); | ||
// A page without a commit carries no MAC. | ||
let mac = parse_mac_header(header, COMMIT_MAC).unwrap_or_default(); | ||
let body = crate::index_api::capped(res, REPO_AT_MOST).await; | ||
let body = body.context("an answer past the most a repo is read for")?; | ||
Ok(Vouched { secret, mac, body }) | ||
} | ||
| ||
/// Whether `commit` is this repo's, vouched for with `mac`. | ||
fn vouched(&self, commit: &Commit, answer: &Vouched) -> Result<()> { | ||
let ours = commit.repo == self.did && commit.space == self.space; | ||
ensure!(ours, "a commit of another repo"); | ||
ensure!( | ||
commit.mac(&answer.secret).to_vec() == answer.mac, | ||
"a commit not vouched for" | ||
); | ||
Ok(()) | ||
} | ||
} | ||
| ||
/// A commit as `listRepoOps` and `getLatestCommit` write it in JSON. | ||
fn commit_of(json: &Json) -> Result<Commit> { | ||
let data = Value::from_json(&json["data"]); | ||
let Ok(Value::Bytes(data)) = data else { | ||
bail!("a commit with no data"); | ||
}; | ||
let text = |k: &str| { | ||
json[k] | ||
.as_str() | ||
.map(String::from) | ||
.context("a commit missing a field") | ||
}; | ||
ensure!(json["ver"] == 1, "a commit of another version"); | ||
Ok(Commit { | ||
repo: text("repo")?, | ||
space: text("space")?, | ||
rev: text("rev")?, | ||
data: data | ||
.as_slice() | ||
.try_into() | ||
.context("a commit's data is 32 bytes")?, | ||
}) | ||
} | ||
| ||
/// A record's DRISL, if it is a map. | ||
fn record_bytes(value: &Json) -> Option<Vec<u8>> { | ||
match Value::from_json(value) { | ||
Ok(v @ Value::Map(_)) => Some(drisl::encode(&v)), | ||
_ => None, | ||
} | ||
} | ||
| ||
impl Host { | ||
/// Marks `space` for the index to read, and wakes it. | ||
pub(crate) fn reindex(&self, space: &str) { | ||
self.indexing | ||
.lock() | ||
.expect("not poisoned") | ||
.insert(space.to_string()); | ||
self.index_wake.notify_one(); | ||
} | ||
| ||
/// Reads each space marked since the last time. | ||
pub async fn index_pending(&self) { | ||
let pending = std::mem::take(&mut *self.indexing.lock().expect("not poisoned")); | ||
for space in pending { | ||
let synced = self.sync_space(&space).await; | ||
tracing::info!(space, ?synced, "indexed"); | ||
} | ||
} | ||
| ||
/// Brings the index of `space`, a group's here, to its writer set. | ||
pub async fn sync_space(&self, space: &str) -> Result<()> { | ||
let Some(hosted) = self.store.space(space)? else { | ||
return Ok(()); | ||
}; | ||
for writer in self.store.writers(space, None, u32::MAX)? { | ||
let indexed = self.store.index_state(space, &writer.did)?; | ||
let at = indexed | ||
.as_ref() | ||
.map(|h| LtHash::from_state(&h.state).map(|s| s.digest())); | ||
if let Some(Ok(digest)) = at | ||
&& digest.as_slice() == writer.data.as_slice() | ||
{ | ||
continue; | ||
} | ||
let synced = self | ||
.sync_writer(space, &hosted.authority, &writer.did, indexed) | ||
.await; | ||
if let Err(e) = synced { | ||
tracing::warn!(space, repo = writer.did, error = %format!("{e:#}"), "a writer not indexed"); | ||
} | ||
} | ||
Ok(()) | ||
} | ||
| ||
async fn sync_writer( | ||
&self, | ||
space: &str, | ||
authority: &str, | ||
did: &str, | ||
indexed: Option<SpaceHead>, | ||
) -> Result<()> { | ||
// A writer here: their repo is in the store. | ||
if self.store.account(did)?.is_some_and(|a| a.did == did) { | ||
let head = self | ||
.store | ||
.space_head(did, space)? | ||
.context("a writer with no repo")?; | ||
let records = self.store.space_records(did, space)?; | ||
let changes = records | ||
.into_iter() | ||
.map(|(path, bytes)| (path, Some((Cid::of_cbor(&bytes), bytes)))) | ||
.collect(); | ||
return self | ||
.store | ||
.index(space, did, &head, true, &changes, now_millis()); | ||
} | ||
let remote = self.remote(space, authority, did).await?; | ||
if let Some(from) = indexed { | ||
match self.read_on(&remote, &from).await { | ||
Ok(()) => return Ok(()), | ||
Err(e) => { | ||
tracing::info!(space, repo = did, error = %format!("{e:#}"), "reading the repo whole") | ||
} | ||
} | ||
} | ||
self.read_whole(&remote).await | ||
} | ||
| ||
/// `did`'s repo in `space`, at their PDS, with a credential to it the | ||
/// group `authority` issues itself. | ||
async fn remote(&self, space: &str, authority: &str, did: &str) -> Result<Remote> { | ||
let doc = self.identity.document(did).await?; | ||
let pds = did::pds(&doc).context("a writer's document names no PDS")?; | ||
let kem = did::kem_key(&doc).context("a writer with no #atproto_kem key")?; | ||
let key = Keypair::generate(Curve::P256); | ||
let signing = self | ||
.store | ||
.account(authority)? | ||
.context("the authority is here")? | ||
.signing; | ||
let kid = key.public().did_key(); | ||
let make = Make { | ||
iss: authority, | ||
sub: space, | ||
key_id: Some(&kid), | ||
..Make::default() | ||
}; | ||
let now = now_millis() as u64 / 1000; | ||
let credential = space_auth::create(Kind::Credential, &make, &signing, now); | ||
let credential = credential?; | ||
Ok(Remote { | ||
space: space.into(), | ||
did: did.into(), | ||
pds, | ||
kem: kem.did_key(), | ||
authorization: format!("Atproto-Space-Credential {credential}"), | ||
key, | ||
}) | ||
} | ||
| ||
/// Reads on from `from`: each page of the writes since, the set hash | ||
/// moved by each, checked against the commit they come to. | ||
async fn read_on(&self, remote: &Remote, from: &SpaceHead) -> Result<()> { | ||
let mut hash = LtHash::from_state(&from.state)?; | ||
let mut last: BTreeMap<String, Json> = BTreeMap::new(); | ||
let mut cursor: Option<String> = None; | ||
let mut seen = HashSet::new(); | ||
let (commit, answer) = loop { | ||
let mut params = vec![("since", from.rev.as_str()), ("limit", PAGE)]; | ||
if let Some(c) = &cursor { | ||
params.push(("cursor", c)); | ||
} | ||
let answer = remote.ask(self, "listRepoOps", ¶ms).await?; | ||
let page: Json = serde_json::from_slice(&answer.body)?; | ||
for op in page["ops"].as_array().context("a page with no ops")? { | ||
let (collection, rkey) = ( | ||
op["collection"] | ||
.as_str() | ||
.context("an op with no collection")?, | ||
op["rkey"].as_str().context("an op with no rkey")?, | ||
); | ||
let cid_of = |k: &str| op[k].as_str().map(Cid::parse).transpose(); | ||
if let Some(prev) = cid_of("prev")? { | ||
hash.remove(&element(collection, rkey, &prev)); | ||
} | ||
if let Some(cid) = cid_of("cid")? { | ||
hash.add(&element(collection, rkey, &cid)); | ||
} | ||
last.insert(format!("{collection}/{rkey}"), op.clone()); | ||
} | ||
cursor = page["cursor"].as_str().map(String::from); | ||
// A server that answers a page it gave would be read forever. | ||
ensure!(seen.insert(cursor.clone()), "the oplog repeats a page"); | ||
if cursor.is_none() { | ||
let commit = | ||
commit_of(&page["commit"]).context("the oplog's head with no commit")?; | ||
break (commit, answer); | ||
} | ||
}; | ||
remote.vouched(&commit, &answer)?; | ||
ensure!( | ||
hash.digest() == commit.data, | ||
"the oplog does not come to its commit" | ||
); | ||
let mut changes = Changes::new(); | ||
for (path, op) in last { | ||
let put = match op["cid"].as_str() { | ||
None => None, | ||
Some(cid) => { | ||
// Its value as it is now: one written again since is | ||
// another, and the repo is read whole instead. | ||
let bytes = record_bytes(&op["value"]).context("a write with no record")?; | ||
ensure!( | ||
Cid::of_cbor(&bytes).to_string() == cid, | ||
"a record not of its CID" | ||
); | ||
Some((Cid::of_cbor(&bytes), bytes)) | ||
} | ||
}; | ||
changes.insert(path, put); | ||
} | ||
let head = SpaceHead { | ||
rev: commit.rev, | ||
state: hash.state(), | ||
}; | ||
self.store.index( | ||
&remote.space, | ||
&remote.did, | ||
&head, | ||
false, | ||
&changes, | ||
now_millis(), | ||
) | ||
} | ||
| ||
/// Reads the repo whole, from its STAR archive, checked against the | ||
/// commit it opens with. | ||
async fn read_whole(&self, remote: &Remote) -> Result<()> { | ||
let answer = remote.ask(self, "getRepo", &[]).await?; | ||
let (commit, records) = read_star(&answer.body)?; | ||
remote.vouched(&commit, &answer)?; | ||
let mut hash = LtHash::default(); | ||
let mut changes = Changes::new(); | ||
for (path, bytes) in records { | ||
let (collection, rkey) = path | ||
.split_once('/') | ||
.context("a record's path with no key")?; | ||
let cid = Cid::of_cbor(&bytes); | ||
hash.add(&element(collection, rkey, &cid)); | ||
// Hashed as it is, kept only if it is a record. | ||
match drisl::decode(&bytes) { | ||
Ok(Value::Map(_)) => { | ||
changes.insert(path, Some((cid, bytes))); | ||
} | ||
_ => tracing::warn!( | ||
space = remote.space, | ||
repo = remote.did, | ||
path, | ||
"a record that is not a DRISL map, left out" | ||
), | ||
} | ||
} | ||
ensure!( | ||
hash.digest() == commit.data, | ||
"the repo does not come to its commit" | ||
); | ||
let head = SpaceHead { | ||
rev: commit.rev, | ||
state: hash.state(), | ||
}; | ||
self.store.index( | ||
&remote.space, | ||
&remote.did, | ||
&head, | ||
true, | ||
&changes, | ||
now_millis(), | ||
) | ||
} | ||
} | ||
crates/group-host/src/index_api.rsnew+258−0
| @@ -0,0 +1,258 @@ | ||
//! The space index, served: what is in one of a group's spaces, and the | ||
//! pictures and files there, for whoever its access record lets read the | ||
//! space, asked on every call. The index holds copies; it never decides | ||
//! who sees them. | ||
//! | ||
//! As the prototype's `methods/spaceRecords.ts`. | ||
| ||
use crate::Host; | ||
use crate::api::{Params, invalid, page, param}; | ||
use crate::group_api::{caller, group_of}; | ||
use crate::rbac::{Access, NS}; | ||
use crate::time::iso; | ||
use crate::xrpc::XrpcError; | ||
use atproto::space::SpaceRef; | ||
use atproto::space_auth::{self, Kind, Make, sign_request}; | ||
use atproto::{Cid, Curve, Keypair, did, drisl}; | ||
use axum::Json; | ||
use axum::extract::{Query, State}; | ||
use axum::http::{HeaderMap, StatusCode, header}; | ||
use axum::response::{IntoResponse, Response}; | ||
use serde_json::{Value, json}; | ||
use std::sync::Arc; | ||
| ||
/// How long a list waits on the index to read the space's writers. | ||
const SYNC_AT_MOST: std::time::Duration = std::time::Duration::from_secs(5); | ||
| ||
/// The most bytes a file is fetched from its writer's PDS for. | ||
pub const FILE_AT_MOST: usize = 5 * 1024 * 1024; | ||
| ||
fn not_found(message: &str) -> XrpcError { | ||
XrpcError::new(StatusCode::BAD_REQUEST, "NotFound", message) | ||
} | ||
| ||
/// The space a read names, once it is one of the group's and the caller | ||
/// may read it by its access record. | ||
async fn readable( | ||
host: &Host, | ||
p: &Params, | ||
headers: &HeaderMap, | ||
lxm: &str, | ||
) -> Result<(String, String), XrpcError> { | ||
let group = param(p, "group")?; | ||
let space = param(p, "space")?; | ||
group_of(host, group).map_err(|_| not_found("unknown group"))?; | ||
host.active(group).map_err(|_| not_found("unknown group"))?; | ||
let me = caller(host, headers, &format!("{NS}.{lxm}")).await?; | ||
let named = SpaceRef::parse(space).ok().filter(|s| s.authority == group); | ||
let access = match named { | ||
Some(_) => host | ||
.group_record(group, space, &format!("{NS}.access"), "self") | ||
.map_err(XrpcError::internal)?, | ||
None => None, | ||
}; | ||
let access = access.ok_or_else(|| not_found("not one of this group's spaces"))?; | ||
let roles = match &me { | ||
Some(me) => host.roles(group, me).map_err(XrpcError::internal)?, | ||
None => Vec::new(), | ||
}; | ||
if !Access::of(&access).can_read(&roles, me.as_deref().unwrap_or_default()) { | ||
return Err(XrpcError::new( | ||
StatusCode::UNAUTHORIZED, | ||
"NotAuthorized", | ||
"not readable by you", | ||
)); | ||
} | ||
Ok((group.to_string(), space.to_string())) | ||
} | ||
| ||
/// The value at a dotted path in a record, as text. | ||
fn at_path<'a>(value: &'a Value, path: &str) -> Option<&'a Value> { | ||
path.split('.').try_fold(value, |v, key| v.get(key)) | ||
} | ||
| ||
fn text_of(value: &Value) -> String { | ||
match value { | ||
Value::String(s) => s.clone(), | ||
other => other.to_string(), | ||
} | ||
} | ||
| ||
/// Records in one of a group's spaces, from the index: one collection or | ||
/// every one, newest first, a page at a time; only those whose `field` | ||
/// equals `equals`, if it says; or the one at `uri`. | ||
pub async fn list_space_records( | ||
State(host): State<Arc<Host>>, | ||
Query(p): Query<Params>, | ||
headers: HeaderMap, | ||
) -> Result<Json<Value>, XrpcError> { | ||
let (_, space) = readable(&host, &p, &headers, "listSpaceRecords").await?; | ||
// A space with writes the index has not read yet is read first. | ||
// Read at most a few seconds: past that, the index as it is. | ||
let synced = tokio::time::timeout(SYNC_AT_MOST, host.sync_space(&space)).await; | ||
tracing::debug!(space, ?synced, "read before listing"); | ||
let limit = page(&p, 50, 100)?; | ||
let view = |r: &crate::store::Indexed| { | ||
let value = drisl::decode(&r.value) | ||
.expect("a record the host indexed") | ||
.to_json(); | ||
json!({ | ||
"uri": format!("{space}/{}/{}/{}", r.did, r.collection, r.rkey), | ||
"cid": r.cid.to_string(), | ||
"repo": r.did, | ||
"value": value, | ||
"createdAt": iso(r.indexed_at), | ||
}) | ||
}; | ||
if let Some(uri) = p.get("uri") { | ||
let rest = uri.strip_prefix(&format!("{space}/")); | ||
let parts: Vec<&str> = rest.unwrap_or_default().splitn(3, '/').collect(); | ||
let [did, collection, rkey] = parts[..] else { | ||
return Err(not_found("not a record in this space")); | ||
}; | ||
let one = host | ||
.store | ||
.indexed_one(&space, did, &format!("{collection}/{rkey}")) | ||
.map_err(XrpcError::internal)?; | ||
let records: Vec<Value> = one.iter().map(view).collect(); | ||
return Ok(Json(json!({ "records": records }))); | ||
} | ||
let collection = p.get("collection").map(String::as_str); | ||
let mut before = match p.get("cursor") { | ||
None => None, | ||
Some(c) => Some( | ||
c.parse::<i64>() | ||
.map_err(|_| invalid("a cursor this host gave"))?, | ||
), | ||
}; | ||
let wanted = p | ||
.get("field") | ||
.map(|f| (f.as_str(), p.get("equals").map_or("", String::as_str))); | ||
let mut records = Vec::new(); | ||
let mut cursor = None; | ||
// A page of what matches: read on through the index until it is full. | ||
loop { | ||
let batch = host | ||
.store | ||
.indexed(&space, collection, before, limit) | ||
.map_err(XrpcError::internal)?; | ||
let ended = batch.len() < limit as usize; | ||
for r in &batch { | ||
before = Some(r.seq); | ||
let shown = view(r); | ||
let matches = wanted.is_none_or(|(field, equals)| { | ||
at_path(&shown["value"], field).is_some_and(|v| text_of(v) == equals) | ||
}); | ||
if matches { | ||
records.push(shown); | ||
if records.len() == limit as usize { | ||
cursor = Some(r.seq.to_string()); | ||
break; | ||
} | ||
} | ||
} | ||
if cursor.is_some() || ended { | ||
break; | ||
} | ||
} | ||
Ok(Json(json!({"records": records, "cursor": cursor}))) | ||
} | ||
| ||
/// A picture or file in one of the group's spaces, read from whoever wrote | ||
/// it, as the space's authority: a page never reaches anyone's own | ||
/// server for it. Served as a download. | ||
pub async fn get_space_blob( | ||
State(host): State<Arc<Host>>, | ||
Query(p): Query<Params>, | ||
headers: HeaderMap, | ||
) -> Result<Response, XrpcError> { | ||
let (group, space) = readable(&host, &p, &headers, "getSpaceBlob").await?; | ||
let repo = param(&p, "repo")?; | ||
let cid = Cid::parse(param(&p, "cid")?).map_err(|e| invalid(format!("cid: {e}")))?; | ||
let fetched = host.space_blob(&group, &space, repo, &cid).await; | ||
let (mime, bytes) = fetched.ok_or_else(|| not_found("no such file in this space"))?; | ||
let headers = [ | ||
(header::CONTENT_TYPE, mime), | ||
(header::X_CONTENT_TYPE_OPTIONS, "nosniff".to_string()), | ||
( | ||
header::CONTENT_SECURITY_POLICY, | ||
"default-src 'none'; sandbox".to_string(), | ||
), | ||
(header::CACHE_CONTROL, "private, max-age=3600".to_string()), | ||
]; | ||
Ok((headers, bytes).into_response()) | ||
} | ||
| ||
impl Host { | ||
/// `repo`'s blob `cid` in `space`, a group's here: from the store for | ||
/// a repo here, else from the repo's PDS, with a credential the group | ||
/// issues itself. Its type and bytes. | ||
async fn space_blob( | ||
&self, | ||
group: &str, | ||
space: &str, | ||
repo: &str, | ||
cid: &Cid, | ||
) -> Option<(String, Vec<u8>)> { | ||
// Only a writer of the space: any other DID would have the host ask | ||
// a server of the caller's choosing, with the group's credential. | ||
let writers = self.store.writers(space, None, u32::MAX).ok()?; | ||
if !writers.iter().any(|w| w.did == repo) { | ||
return None; | ||
} | ||
let here = self | ||
.store | ||
.account(repo) | ||
.ok()? | ||
.is_some_and(|a| a.did == repo); | ||
if here { | ||
if !self.store.space_has_blob(repo, space, cid).ok()? { | ||
return None; | ||
} | ||
let (blob, bytes) = self.read_blob(repo, cid).ok()??; | ||
return Some((blob.mime_type, bytes)); | ||
} | ||
let doc = self.identity.document(repo).await.ok()?; | ||
let pds = did::pds(&doc)?; | ||
let key = Keypair::generate(Curve::P256); | ||
let signing = self.store.account(group).ok()??.signing; | ||
let kid = key.public().did_key(); | ||
let make = Make { | ||
iss: group, | ||
sub: space, | ||
key_id: Some(&kid), | ||
..Make::default() | ||
}; | ||
let now = crate::time::now_millis() as u64 / 1000; | ||
let credential = space_auth::create(Kind::Credential, &make, &signing, now).ok()?; | ||
let authorization = format!("Atproto-Space-Credential {credential}"); | ||
let mut req = self | ||
.http | ||
.get(format!("{pds}/xrpc/com.atproto.space.getBlob")) | ||
.query(&[("space", space), ("repo", repo), ("cid", &cid.to_string())]); | ||
for (k, v) in sign_request(&key, &authorization, repo).ok()? { | ||
req = req.header(k, v); | ||
} | ||
let res = req.send().await.ok()?.error_for_status().ok()?; | ||
let mime = res | ||
.headers() | ||
.get(header::CONTENT_TYPE) | ||
.and_then(|v| v.to_str().ok()); | ||
let mime = mime.unwrap_or("application/octet-stream").to_string(); | ||
let bytes = capped(res, FILE_AT_MOST).await?; | ||
// What the writer sent must be the file asked for. | ||
(Cid::of_raw(&bytes) == *cid).then_some((mime, bytes)) | ||
} | ||
} | ||
| ||
/// A response's bytes, if they are no more than `max`. | ||
pub(crate) async fn capped(mut res: reqwest::Response, max: usize) -> Option<Vec<u8>> { | ||
let mut bytes = Vec::new(); | ||
while let Some(chunk) = res.chunk().await.ok()? { | ||
bytes.extend_from_slice(&chunk); | ||
if bytes.len() > max { | ||
return None; | ||
} | ||
} | ||
Some(bytes) | ||
} | ||
crates/group-host/src/lib.rs+26−0
| @@ -16,6 +16,8 @@ pub mod group_handle; | ||
pub mod group_lifecycle; | ||
pub mod group_spaces; | ||
pub mod identity; | ||
pub mod index; | ||
pub mod index_api; | ||
pub mod lifecycle; | ||
pub mod plc; | ||
pub mod rbac; | ||
| @@ -53,6 +55,9 @@ pub struct Host { | ||
/// 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>>, | ||
index_wake: tokio::sync::Notify, | ||
} | ||
| ||
impl Host { | ||
| @@ -76,6 +81,8 @@ impl Host { | ||
events: tokio::sync::broadcast::channel(16).0, | ||
crawled: Default::default(), | ||
http: client(), | ||
indexing: Default::default(), | ||
index_wake: Default::default(), | ||
}) | ||
} | ||
} | ||
| @@ -216,6 +223,14 @@ pub fn router(host: Arc<Host>) -> Router { | ||
"/xrpc/fyi.opensocial.deleteSpace", | ||
post(group_spaces::delete_space), | ||
) | ||
.route( | ||
"/xrpc/fyi.opensocial.listSpaceRecords", | ||
get(index_api::list_space_records), | ||
) | ||
.route( | ||
"/xrpc/fyi.opensocial.getSpaceBlob", | ||
get(index_api::get_space_blob), | ||
) | ||
.route("/.well-known/did.json", get(api::did_json)) | ||
.route("/.well-known/atproto-did", get(api::atproto_did)) | ||
.route("/xrpc/{nsid}", get(not_implemented).post(not_implemented)) | ||
| @@ -248,6 +263,17 @@ pub async fn serve(config: Config) -> anyhow::Result<()> { | ||
tokio::time::sleep(std::time::Duration::from_secs(60 * 60)).await; | ||
} | ||
}); | ||
// The index reads the spaces whose writers moved, as they move, and | ||
// each minute, so a wake missed waits no longer. | ||
let indexing = host.clone(); | ||
tokio::spawn(async move { | ||
loop { | ||
let woken = indexing.index_wake.notified(); | ||
indexing.index_pending().await; | ||
let minute = std::time::Duration::from_secs(60); | ||
let _ = tokio::time::timeout(minute, woken).await; | ||
} | ||
}); | ||
// Word of writes owed to authorities elsewhere, tried as it falls due. | ||
let delivering = host.clone(); | ||
tokio::spawn(async move { | ||
crates/group-host/src/store.rs+132−0
| @@ -167,6 +167,30 @@ const MIGRATIONS: &[&str] = &[ | ||
did TEXT PRIMARY KEY REFERENCES account (did), | ||
address TEXT NOT NULL UNIQUE | ||
); | ||
", | ||
" | ||
CREATE TABLE index_repo ( | ||
space TEXT NOT NULL, | ||
did TEXT NOT NULL, | ||
rev TEXT NOT NULL, | ||
state BLOB NOT NULL, | ||
PRIMARY KEY (space, did) | ||
); | ||
CREATE TABLE index_record ( | ||
seq INTEGER PRIMARY KEY AUTOINCREMENT, | ||
space TEXT NOT NULL, | ||
did TEXT NOT NULL, | ||
path TEXT NOT NULL, | ||
cid TEXT NOT NULL, | ||
value BLOB NOT NULL, | ||
indexed_at INTEGER NOT NULL, | ||
UNIQUE (space, did, path) | ||
); | ||
CREATE INDEX index_record_newest ON index_record (space, seq); | ||
", | ||
// Accounts made before addresses were kept: each its handle then. | ||
" | ||
INSERT OR IGNORE INTO address (did, address) SELECT did, handle FROM account; | ||
", | ||
]; | ||
| ||
| @@ -242,6 +266,8 @@ const RETRY: &str = "UPDATE outbox SET attempts = attempts + 1, next_at = ?4 WHE | ||
const LAPSED: &str = "DELETE FROM outbox WHERE deliver_by <= ?1 RETURNING repo, space, rev"; | ||
/// What goes with a space whose authority is here. | ||
const FORGET_SPACE: &[&str] = &[ | ||
"DELETE FROM index_record WHERE space = ?1", | ||
"DELETE FROM index_repo WHERE space = ?1", | ||
"DELETE FROM space_recipient WHERE space = ?1", | ||
"DELETE FROM space_writer WHERE space = ?1", | ||
"DELETE FROM space_grant WHERE space = ?1", | ||
| @@ -253,12 +279,21 @@ const FORGET_OWN_REPO: &[&str] = &[ | ||
"DELETE FROM space_record WHERE space = ?1 AND did = ?2", | ||
"DELETE FROM space_repo WHERE space = ?1 AND did = ?2", | ||
]; | ||
const INDEXED_STATE: &str = "SELECT rev, state FROM index_repo WHERE space = ?1 AND did = ?2"; | ||
const INDEX_STATE: &str = "INSERT INTO index_repo (space, did, rev, state) VALUES (?1, ?2, ?3, ?4) ON CONFLICT (space, did) DO UPDATE SET rev = ?3, state = ?4"; | ||
const UNINDEX_REPO: &str = "DELETE FROM index_record WHERE space = ?1 AND did = ?2"; | ||
const UNINDEX: &str = "DELETE FROM index_record WHERE space = ?1 AND did = ?2 AND path = ?3"; | ||
const INDEX: &str = "INSERT INTO index_record (space, did, path, cid, value, indexed_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6)"; | ||
const INDEXED: &str = "SELECT seq, did, path, cid, value, indexed_at FROM index_record WHERE space = ?1 AND (?2 IS NULL OR substr(path, 1, length(?2) + 1) = ?2 || '/') AND seq < ?3 ORDER BY seq DESC LIMIT ?4"; | ||
const INDEXED_ONE: &str = "SELECT seq, did, path, cid, value, indexed_at FROM index_record WHERE space = ?1 AND did = ?2 AND path = ?3"; | ||
const SPACES_OF: &str = "SELECT uri FROM space WHERE authority = ?1 ORDER BY uri"; | ||
const DEACTIVATE: &str = "INSERT INTO deactivation (did, at, by, stewards) VALUES (?1, ?2, ?3, ?4) ON CONFLICT (did) DO NOTHING"; | ||
const DEACTIVATION: &str = "SELECT at, by, stewards FROM deactivation WHERE did = ?1"; | ||
const ACTIVATE: &str = "DELETE FROM deactivation WHERE did = ?1"; | ||
/// What goes with an account, in an order its references allow. | ||
const FORGET_ACCOUNT: &[&str] = &[ | ||
"DELETE FROM index_record WHERE space IN (SELECT uri FROM space WHERE authority = ?1)", | ||
"DELETE FROM index_repo WHERE space IN (SELECT uri FROM space WHERE authority = ?1)", | ||
"DELETE FROM deactivation WHERE did = ?1", | ||
"DELETE FROM address WHERE did = ?1", | ||
"DELETE FROM outbox WHERE repo = ?1", | ||
| @@ -416,6 +451,32 @@ pub struct Deactivation { | ||
pub stewards: Vec<String>, | ||
} | ||
| ||
/// A record in the host's index of a space: when it was indexed, in | ||
/// order, whose it is, where, and its CID and DRISL. | ||
#[derive(Debug, Clone, PartialEq)] | ||
pub struct Indexed { | ||
pub seq: i64, | ||
pub did: String, | ||
pub collection: String, | ||
pub rkey: String, | ||
pub cid: Cid, | ||
pub value: Vec<u8>, | ||
pub indexed_at: i64, | ||
} | ||
| ||
fn indexed(row: &rusqlite::Row) -> rusqlite::Result<Indexed> { | ||
let (collection, rkey) = split(&row.get::<_, String>(2)?); | ||
Ok(Indexed { | ||
seq: row.get(0)?, | ||
did: row.get(1)?, | ||
collection, | ||
rkey, | ||
cid: cid(row.get(3)?), | ||
value: row.get(4)?, | ||
indexed_at: row.get(5)?, | ||
}) | ||
} | ||
| ||
/// A blob as kept: its type, its size, and whether it waits for a record | ||
/// to reference it. | ||
#[derive(Debug, Clone, PartialEq)] | ||
| @@ -1048,6 +1109,77 @@ impl Store { | ||
Ok(orphans) | ||
} | ||
| ||
/// How far the index has read `did`'s repo in `space`: its revision and | ||
/// set hash state then. | ||
pub fn index_state(&self, space: &str, did: &str) -> Result<Option<SpaceHead>> { | ||
let conn = self.conn(); | ||
let found = conn.query_row(INDEXED_STATE, [space, did], |r| { | ||
Ok(SpaceHead { | ||
rev: r.get(0)?, | ||
state: r.get(1)?, | ||
}) | ||
}); | ||
Ok(found.optional()?) | ||
} | ||
| ||
/// Indexes `did`'s repo in `space` as at `head`: its records replaced | ||
/// by `records`, by path, when it was read whole; or each path in | ||
/// `changes` put (a CID and DRISL) or taken out, when it was read on. | ||
pub fn index( | ||
&self, | ||
space: &str, | ||
did: &str, | ||
head: &SpaceHead, | ||
whole: bool, | ||
changes: &BTreeMap<String, Option<(Cid, Vec<u8>)>>, | ||
now: i64, | ||
) -> Result<()> { | ||
let mut conn = self.conn(); | ||
let tx = conn.transaction()?; | ||
if whole { | ||
let cleared = tx.execute(UNINDEX_REPO, [space, did]); | ||
cleared?; | ||
} | ||
for (path, put) in changes { | ||
let gone = tx.execute(UNINDEX, [space, did, path]); | ||
gone?; | ||
if let Some((cid, value)) = put { | ||
let kept = tx.execute( | ||
INDEX, | ||
params![space, did, path, cid.to_string(), value, now], | ||
); | ||
kept?; | ||
} | ||
} | ||
let state = tx.execute(INDEX_STATE, params![space, did, head.rev, head.state]); | ||
state?; | ||
tx.commit()?; | ||
Ok(()) | ||
} | ||
| ||
/// The index's records in `space`, of `collection` or all, newest | ||
/// first, before `before` (a sequence number), at most `limit`. | ||
pub fn indexed( | ||
&self, | ||
space: &str, | ||
collection: Option<&str>, | ||
before: Option<i64>, | ||
limit: u32, | ||
) -> Result<Vec<Indexed>> { | ||
let conn = self.conn(); | ||
let mut q = conn.prepare(INDEXED)?; | ||
let asked = params![space, collection, before.unwrap_or(i64::MAX), limit]; | ||
let rows = q.query_map(asked, indexed)?; | ||
Ok(rows.collect::<rusqlite::Result<_>>()?) | ||
} | ||
| ||
/// One record in the index of `space`: `did`'s at `path`. | ||
pub fn indexed_one(&self, space: &str, did: &str, path: &str) -> Result<Option<Indexed>> { | ||
let conn = self.conn(); | ||
let found = conn.query_row(INDEXED_ONE, [space, did, path], indexed); | ||
Ok(found.optional()?) | ||
} | ||
| ||
/// The spaces `authority` is the authority for. | ||
pub fn spaces_of(&self, authority: &str) -> Result<Vec<String>> { | ||
let conn = self.conn(); | ||
crates/group-host/tests/group_spaces.rs+6−0
crates/group-host/tests/identity.rs+73−0
crates/group-host/tests/index.rsnew+799−0
799 lines changed: not loaded until asked for.