chadtmiller.com/group-host
atmosphere group host
0
0
host: blobs, kept while a record references them, served and listed
crates/group-host/src/api.rs+48−0
| @@ -168,6 +168,54 @@ pub async fn resolve_handle(State(host): State<Arc<Host>>, Query(p): Params) -> | ||
Ok(Json(json!({"did": account.ok_or_else(not_found)?.did}))) | ||
} | ||
| ||
/// A blob a record of the account references, served as a download: a | ||
/// browser neither sniffs nor runs it. | ||
pub async fn get_blob( | ||
State(host): State<Arc<Host>>, | ||
Query(p): Params, | ||
) -> Result<Response, XrpcError> { | ||
let did = did_of(&host, param(&p, "did")?)?; | ||
let cid = param(&p, "cid")?; | ||
let cid = atproto::Cid::parse(cid).map_err(|e| invalid(format!("cid: {e}")))?; | ||
let found = host.read_blob(&did, &cid).map_err(XrpcError::internal)?; | ||
let not_found = || { | ||
XrpcError::new( | ||
StatusCode::BAD_REQUEST, | ||
"BlobNotFound", | ||
format!("no blob {cid} here"), | ||
) | ||
}; | ||
let (blob, bytes) = found.ok_or_else(not_found)?; | ||
let headers = [ | ||
(header::CONTENT_TYPE, blob.mime_type), | ||
(header::X_CONTENT_TYPE_OPTIONS, "nosniff".to_string()), | ||
( | ||
header::CONTENT_SECURITY_POLICY, | ||
"default-src 'none'; sandbox".to_string(), | ||
), | ||
]; | ||
Ok((headers, bytes).into_response()) | ||
} | ||
| ||
pub async fn list_blobs(State(host): State<Arc<Host>>, Query(p): Params) -> Answer { | ||
let did = did_of(&host, param(&p, "did")?)?; | ||
let limit = limit(&p)?; | ||
let (since, cursor) = ( | ||
p.get("since").map(String::as_str), | ||
p.get("cursor").map(String::as_str), | ||
); | ||
let cids = host | ||
.store | ||
.list_blobs(&did, since, cursor, limit) | ||
.map_err(XrpcError::internal)?; | ||
let cursor = cids | ||
.last() | ||
.filter(|_| cids.len() == limit as usize) | ||
.map(ToString::to_string); | ||
let cids: Vec<String> = cids.iter().map(ToString::to_string).collect(); | ||
Ok(Json(json!({"cids": cids, "cursor": cursor}))) | ||
} | ||
| ||
/// The host's own DID document, when its DID is a `did:web` of its address. | ||
pub async fn did_json(State(host): State<Arc<Host>>) -> Result<Json<Value>, StatusCode> { | ||
let did = &host.config.service_did; | ||
crates/group-host/src/blobs.rsnew+132−0
| @@ -0,0 +1,132 @@ | ||
//! Blobs: files on disk under `DATA_DIR/blobs`, named by CID in each | ||
//! account's own directory. An upload is temporary; a write whose record | ||
//! references it makes it permanent, and one that drops the last reference | ||
//! deletes it. Temporary blobs no record took within a day are swept. Only | ||
//! a blob a record references is served. | ||
| ||
use crate::Host; | ||
use crate::store::Blob; | ||
use crate::time::now_millis; | ||
use crate::xrpc::XrpcError; | ||
use atproto::Cid; | ||
use axum::http::StatusCode; | ||
use serde_json::{Value, json}; | ||
use std::path::PathBuf; | ||
| ||
/// How long an upload waits for a record to reference it. | ||
pub const TEMPORARY_FOR: i64 = 24 * 60 * 60 * 1000; | ||
| ||
impl Host { | ||
fn blob_path(&self, did: &str, cid: &Cid) -> PathBuf { | ||
let dir = did.replace(':', "_"); | ||
self.config | ||
.data_dir | ||
.join("blobs") | ||
.join(dir) | ||
.join(cid.to_string()) | ||
} | ||
| ||
/// Keeps `bytes` as a temporary blob of `did`'s, answering the | ||
/// reference a record holds it by. | ||
pub fn upload_blob( | ||
&self, | ||
did: &str, | ||
bytes: &[u8], | ||
mime_type: &str, | ||
) -> Result<Value, XrpcError> { | ||
let account = self.store.account(did).map_err(XrpcError::internal)?; | ||
if account.is_none() { | ||
return Err(XrpcError::new( | ||
StatusCode::BAD_REQUEST, | ||
"RepoNotFound", | ||
format!("no repo {did} here"), | ||
)); | ||
} | ||
let limit = self.config.blob_upload_limit; | ||
if bytes.len() as u64 > limit { | ||
let said = format!("a blob is {limit} bytes at most"); | ||
return Err(XrpcError::new( | ||
StatusCode::BAD_REQUEST, | ||
"BlobTooLarge", | ||
said, | ||
)); | ||
} | ||
let cid = Cid::of_raw(bytes); | ||
let mime_type = if mime_type.is_empty() { | ||
"application/octet-stream" | ||
} else { | ||
mime_type | ||
}; | ||
self.write_blob(did, &cid, bytes) | ||
.map_err(XrpcError::internal)?; | ||
let kept = self | ||
.store | ||
.put_blob(did, &cid, mime_type, bytes.len() as i64, now_millis()); | ||
kept.map_err(XrpcError::internal)?; | ||
Ok( | ||
json!({"$type": "blob", "ref": {"$link": cid.to_string()}, "mimeType": mime_type, "size": bytes.len()}), | ||
) | ||
} | ||
| ||
/// Writes the file whole or not at all: a reader never sees part of it. | ||
fn write_blob(&self, did: &str, cid: &Cid, bytes: &[u8]) -> std::io::Result<()> { | ||
let path = self.blob_path(did, cid); | ||
std::fs::create_dir_all(path.parent().expect("a blob's file is in a directory"))?; | ||
let part = path.with_extension(format!("{}.part", std::process::id())); | ||
std::fs::write(&part, bytes)?; | ||
std::fs::rename(&part, &path) | ||
} | ||
| ||
/// `did`'s blob `cid`, and its bytes, once a record references it. | ||
pub fn read_blob(&self, did: &str, cid: &Cid) -> anyhow::Result<Option<(Blob, Vec<u8>)>> { | ||
let Some(blob) = self.store.blob(did, cid)?.filter(|b| !b.temporary) else { | ||
return Ok(None); | ||
}; | ||
let bytes = std::fs::read(self.blob_path(did, cid))?; | ||
Ok(Some((blob, bytes))) | ||
} | ||
| ||
/// Deletes the files of blobs the database has let go. | ||
pub(crate) fn remove_blobs<'a>(&self, blobs: impl IntoIterator<Item = (&'a str, &'a Cid)>) { | ||
for (did, cid) in blobs { | ||
let _ = std::fs::remove_file(self.blob_path(did, cid)); | ||
} | ||
} | ||
| ||
/// Removes the uploads no record took before `now` less a day, saying | ||
/// how many. | ||
pub fn sweep_blobs(&self, now: i64) -> anyhow::Result<usize> { | ||
let swept = self.store.sweep_blobs(now - TEMPORARY_FOR)?; | ||
self.remove_blobs(swept.iter().map(|(did, cid)| (did.as_str(), cid))); | ||
Ok(swept.len()) | ||
} | ||
} | ||
| ||
/// The blobs a record's JSON references: each `{"$type": "blob", "ref": | ||
/// {"$link": cid}}` in it, at any depth. | ||
pub fn blob_refs(record: &Value) -> Vec<Cid> { | ||
let mut found = Vec::new(); | ||
collect(record, &mut found); | ||
found.sort(); | ||
found.dedup(); | ||
found | ||
} | ||
| ||
fn collect(value: &Value, found: &mut Vec<Cid>) { | ||
match value { | ||
Value::Array(items) => items.iter().for_each(|v| collect(v, found)), | ||
Value::Object(map) => { | ||
let link = map | ||
.get("ref") | ||
.and_then(|r| r.get("$link")) | ||
.and_then(Value::as_str); | ||
if map.get("$type").and_then(Value::as_str) == Some("blob") | ||
&& let Some(cid) = link.and_then(|l| Cid::parse(l).ok()) | ||
{ | ||
found.push(cid); | ||
} | ||
map.values().for_each(|v| collect(v, found)); | ||
} | ||
_ => {} | ||
} | ||
} | ||
crates/group-host/src/config.rs+9−0
| @@ -23,6 +23,8 @@ pub struct Config { | ||
pub plc_url: String, | ||
/// The relays told of this host's news, `PDS_CRAWLERS`, comma-separated. | ||
pub crawlers: Vec<String>, | ||
/// The most bytes one blob may be, `BLOB_UPLOAD_LIMIT`. | ||
pub blob_upload_limit: u64, | ||
} | ||
| ||
impl Config { | ||
| @@ -58,6 +60,12 @@ impl Config { | ||
.map(|c| c.trim().trim_end_matches('/').to_string()) | ||
.filter(|c| !c.is_empty()) | ||
.collect(); | ||
let blob_upload_limit = match var("BLOB_UPLOAD_LIMIT") { | ||
Some(l) => l | ||
.parse() | ||
.with_context(|| format!("BLOB_UPLOAD_LIMIT is no number of bytes: {l}"))?, | ||
None => 50 * 1024 * 1024, | ||
}; | ||
Ok(Config { | ||
port, | ||
public_url, | ||
| @@ -66,6 +74,7 @@ impl Config { | ||
data_dir, | ||
plc_url, | ||
crawlers, | ||
blob_upload_limit, | ||
}) | ||
} | ||
| ||
crates/group-host/src/lib.rs+14−1
| @@ -4,6 +4,7 @@ | ||
//! says how it is built and what is still to come. | ||
| ||
pub mod api; | ||
pub mod blobs; | ||
pub mod config; | ||
pub mod firehose; | ||
pub mod plc; | ||
| @@ -78,6 +79,8 @@ 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.getBlob", get(api::get_blob)) | ||
.route("/xrpc/com.atproto.sync.listBlobs", get(api::list_blobs)) | ||
.route( | ||
"/xrpc/com.atproto.sync.subscribeRepos", | ||
get(firehose::subscribe_repos), | ||
| @@ -108,7 +111,17 @@ pub async fn serve(config: Config) -> anyhow::Result<()> { | ||
let listener = TcpListener::bind(("0.0.0.0", config.port)).await?; | ||
println!("listening on {}", listener.local_addr()?); | ||
tracing::info!(public_url = %config.public_url, did = %config.service_did, "serving"); | ||
let app = router(Arc::new(Host::open(config)?)); | ||
let host = Arc::new(Host::open(config)?); | ||
// Uploads no record took, swept now and each hour after. | ||
let sweeping = host.clone(); | ||
tokio::spawn(async move { | ||
loop { | ||
let swept = sweeping.sweep_blobs(time::now_millis()); | ||
tracing::info!(?swept, "swept the uploads no record took"); | ||
tokio::time::sleep(std::time::Duration::from_secs(60 * 60)).await; | ||
} | ||
}); | ||
let app = router(host); | ||
axum::serve(listener, app) | ||
.with_graceful_shutdown(stopped()) | ||
.await?; | ||
crates/group-host/src/repo.rs+42−11
| @@ -2,10 +2,11 @@ | ||
//! changing its records a signed commit at a time. | ||
| ||
use crate::Host; | ||
use crate::blobs::blob_refs; | ||
use crate::store::{Account, Change, Event, Head}; | ||
use crate::time::{iso, now_millis}; | ||
use crate::xrpc::XrpcError; | ||
use anyhow::{Result, ensure}; | ||
use anyhow::{Context, Result}; | ||
use atproto::mst::{Entry, Node, Tree}; | ||
use atproto::plc::Op; | ||
use atproto::{Cid, Commit, Curve, Keypair, Value, car, drisl, syntax}; | ||
| @@ -127,7 +128,15 @@ impl Host { | ||
("time", at), | ||
], | ||
), | ||
commit_event(&did, &head, None, None, Vec::new(), tree.blocks()), | ||
commit_event( | ||
&did, | ||
&head, | ||
None, | ||
None, | ||
Vec::new(), | ||
Vec::new(), | ||
tree.blocks(), | ||
), | ||
]; | ||
// The handle checked above can still be taken as this was made: | ||
// the database's unique handle is what holds. | ||
| @@ -177,6 +186,7 @@ impl Host { | ||
let before = Tree::build(&paths); | ||
let mut changes: Vec<Change> = Vec::new(); | ||
let mut ops = Vec::new(); | ||
let mut new_blobs = Vec::new(); | ||
let mut blocks = BTreeMap::new(); | ||
for write in writes { | ||
let (collection, rkey, value, exists) = match write { | ||
| @@ -207,6 +217,18 @@ impl Host { | ||
return Err(invalid(format!("there is {what} {path}"))); | ||
} | ||
let put = value.map(|v| record(collection, v)).transpose()?; | ||
// A record may reference only blobs uploaded to its account. | ||
let refs = value.map(blob_refs).unwrap_or_default(); | ||
for cid in &refs { | ||
let blob = self | ||
.store | ||
.blob(&account.did, cid) | ||
.map_err(XrpcError::internal)?; | ||
if blob.is_none() { | ||
return Err(invalid(format!("blob {cid} was not uploaded to {did}"))); | ||
} | ||
} | ||
new_blobs.extend(refs.iter().copied()); | ||
let prev = match &put { | ||
Some((cid, bytes)) => { | ||
blocks.insert(*cid, bytes.clone()); | ||
| @@ -215,15 +237,20 @@ impl Host { | ||
None => paths.remove(&path), | ||
}; | ||
ops.push(op(path, put.as_ref().map(|(cid, _)| *cid), prev)); | ||
changes.push((collection.clone(), rkey.clone(), put)); | ||
changes.push(Change { | ||
collection: collection.clone(), | ||
rkey: rkey.clone(), | ||
put, | ||
blobs: refs, | ||
}); | ||
} | ||
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}"))); | ||
for c in &changes { | ||
blocks.extend(tree.covering_proof(&format!("{}/{}", c.collection, c.rkey))); | ||
} | ||
let previous = Commit::from_bytes(&head.block).expect("a commit the host wrote"); | ||
let events = [commit_event( | ||
| @@ -232,17 +259,17 @@ impl Host { | ||
Some(&head.rev), | ||
Some(previous.data), | ||
ops, | ||
new_blobs, | ||
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(()) | ||
}) | ||
let raced = format!("{did}'s repo moved under a write"); | ||
let orphans = moved | ||
.and_then(|moved| moved.context(raced)) | ||
.map_err(XrpcError::internal)?; | ||
self.remove_blobs(orphans.iter().map(|cid| (account.did.as_str(), cid))); | ||
self.announce(); | ||
Ok(Committed { | ||
cid: new.cid, | ||
| @@ -347,6 +374,7 @@ fn commit_event( | ||
since: Option<&str>, | ||
prev_data: Option<Cid>, | ||
ops: Vec<Value>, | ||
blobs: Vec<Cid>, | ||
mut blocks: BTreeMap<Cid, Vec<u8>>, | ||
) -> Event { | ||
blocks.insert(head.cid, head.block.clone()); | ||
| @@ -361,7 +389,10 @@ fn commit_event( | ||
), | ||
("blocks", Value::Bytes(car)), | ||
("ops", Value::Array(ops)), | ||
("blobs", Value::Array(Vec::new())), | ||
( | ||
"blobs", | ||
Value::Array(blobs.into_iter().map(Value::Link).collect()), | ||
), | ||
("rebase", Value::Bool(false)), | ||
("tooBig", Value::Bool(false)), | ||
("time", Value::String(iso(now_millis()))), | ||
crates/group-host/src/store.rs+147−8
| @@ -42,6 +42,26 @@ const MIGRATIONS: &[&str] = &[ | ||
kind TEXT NOT NULL, | ||
body BLOB NOT NULL | ||
); | ||
", | ||
" | ||
CREATE TABLE blob ( | ||
did TEXT NOT NULL REFERENCES account (did), | ||
cid TEXT NOT NULL, | ||
mime_type TEXT NOT NULL, | ||
size INTEGER NOT NULL, | ||
temporary INTEGER NOT NULL, | ||
created_at INTEGER NOT NULL, | ||
PRIMARY KEY (did, cid) | ||
); | ||
CREATE INDEX blob_temporary ON blob (temporary, created_at); | ||
CREATE TABLE record_blob ( | ||
did TEXT NOT NULL, | ||
collection TEXT NOT NULL, | ||
rkey TEXT NOT NULL, | ||
cid TEXT NOT NULL, | ||
PRIMARY KEY (did, collection, rkey, cid) | ||
); | ||
CREATE INDEX record_blob_cid ON record_blob (did, cid); | ||
", | ||
]; | ||
| ||
| @@ -49,6 +69,17 @@ const NEW_ACCOUNT: &str = "INSERT INTO account (did, handle, signing_key, create | ||
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 LINKED: &str = "SELECT cid FROM record_blob WHERE did = ?1 AND collection = ?2 AND rkey = ?3"; | ||
const UNLINK: &str = "DELETE FROM record_blob WHERE did = ?1 AND collection = ?2 AND rkey = ?3"; | ||
const LINK: &str = | ||
"INSERT OR IGNORE INTO record_blob (did, collection, rkey, cid) VALUES (?1, ?2, ?3, ?4)"; | ||
const KEEP_BLOB: &str = "UPDATE blob SET temporary = 0 WHERE did = ?1 AND cid = ?2"; | ||
const FORGET_ORPHAN: &str = "DELETE FROM blob WHERE did = ?1 AND cid = ?2 AND temporary = 0 AND NOT EXISTS (SELECT 1 FROM record_blob WHERE did = ?1 AND cid = ?2)"; | ||
const PUT_BLOB: &str = "INSERT INTO blob (did, cid, mime_type, size, temporary, created_at) VALUES (?1, ?2, ?3, ?4, 1, ?5) ON CONFLICT (did, cid) DO UPDATE SET mime_type = excluded.mime_type"; | ||
const GET_BLOB: &str = "SELECT mime_type, size, temporary FROM blob WHERE did = ?1 AND cid = ?2"; | ||
const LIST_BLOBS: &str = "SELECT DISTINCT rb.cid FROM record_blob rb JOIN record r ON r.did = rb.did AND r.collection = rb.collection AND r.rkey = rb.rkey WHERE rb.did = ?1 AND r.rev > ?2 AND rb.cid > ?3 ORDER BY rb.cid LIMIT ?4"; | ||
const SWEEP_BLOBS: &str = | ||
"DELETE FROM blob WHERE temporary = 1 AND created_at < ?1 RETURNING did, cid"; | ||
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 = | ||
| @@ -103,6 +134,14 @@ pub struct Sequenced { | ||
pub body: Vec<u8>, | ||
} | ||
| ||
/// The blobs the record at `collection/rkey` references now. | ||
fn linked(tx: &rusqlite::Transaction, did: &str, collection: &str, rkey: &str) -> Result<Vec<Cid>> { | ||
let mut q = tx.prepare(LINKED)?; | ||
let rows = q.query_map(params![did, collection, rkey], |r| Ok(cid(r.get(0)?))); | ||
let rows = rows?; | ||
Ok(rows.collect::<rusqlite::Result<_>>()?) | ||
} | ||
| ||
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]); | ||
| @@ -111,8 +150,25 @@ fn sequence(tx: &rusqlite::Transaction, did: &str, events: &[Event]) -> Result<( | ||
Ok(()) | ||
} | ||
| ||
/// What a commit changes: a record put, or taken out (`None`). | ||
pub type Change = (String, String, Option<(Cid, Vec<u8>)>); | ||
/// What a commit changes at one path: a record put, or taken out. | ||
#[derive(Debug, Clone, PartialEq)] | ||
pub struct Change { | ||
pub collection: String, | ||
pub rkey: String, | ||
/// The record's CID and DRISL, or none for a delete. | ||
pub put: Option<(Cid, Vec<u8>)>, | ||
/// The blobs the record put references. | ||
pub blobs: Vec<Cid>, | ||
} | ||
| ||
/// A blob as kept: its type, its size, and whether it waits for a record | ||
/// to reference it. | ||
#[derive(Debug, Clone, PartialEq)] | ||
pub struct Blob { | ||
pub mime_type: String, | ||
pub size: i64, | ||
pub temporary: bool, | ||
} | ||
| ||
/// A CID the host wrote: one that does not read is a database broken. | ||
fn cid(text: String) -> Cid { | ||
| @@ -313,8 +369,10 @@ impl Store { | ||
} | ||
| ||
/// Moves `did`'s repo from `prev` to `head`, with `changes` and | ||
/// `events`, unless another commit moved it first: `false` then, and | ||
/// nothing changes. | ||
/// `events`, unless another commit moved it first: none then, and | ||
/// nothing changes. Each record's blobs are linked to it and made | ||
/// permanent; the blobs no record references any more are forgotten, | ||
/// and answered, for their files to go. | ||
pub fn commit( | ||
&self, | ||
did: &str, | ||
| @@ -322,7 +380,7 @@ impl Store { | ||
head: &Head, | ||
changes: &[Change], | ||
events: &[Event], | ||
) -> Result<bool> { | ||
) -> Result<Option<Vec<Cid>>> { | ||
let mut conn = self.conn(); | ||
let tx = conn.transaction()?; | ||
let moved = tx.execute( | ||
| @@ -336,9 +394,25 @@ impl Store { | ||
], | ||
); | ||
if moved? == 0 { | ||
return Ok(false); | ||
return Ok(None); | ||
} | ||
for (collection, rkey, put) in changes { | ||
let mut unlinked = Vec::new(); | ||
for Change { | ||
collection, | ||
rkey, | ||
put, | ||
blobs, | ||
} in changes | ||
{ | ||
unlinked.extend(linked(&tx, did, collection, rkey)?); | ||
let cleared = tx.execute(UNLINK, params![did, collection, rkey]); | ||
cleared?; | ||
for cid in blobs { | ||
let link = tx.execute(LINK, params![did, collection, rkey, cid.to_string()]); | ||
link?; | ||
let kept = tx.execute(KEEP_BLOB, params![did, cid.to_string()]); | ||
kept?; | ||
} | ||
let done = match put { | ||
Some((cid, value)) => tx.execute( | ||
PUT_RECORD, | ||
| @@ -351,9 +425,74 @@ impl Store { | ||
}; | ||
done?; | ||
} | ||
let mut orphans = Vec::new(); | ||
for cid in unlinked { | ||
let gone = tx.execute(FORGET_ORPHAN, params![did, cid.to_string()]); | ||
if gone? > 0 { | ||
orphans.push(cid); | ||
} | ||
} | ||
sequence(&tx, did, events)?; | ||
tx.commit()?; | ||
Ok(true) | ||
Ok(Some(orphans)) | ||
} | ||
| ||
/// Keeps a blob of `did`'s, temporary until a record references it; one | ||
/// kept already keeps its standing. | ||
pub fn put_blob( | ||
&self, | ||
did: &str, | ||
cid: &Cid, | ||
mime_type: &str, | ||
size: i64, | ||
now: i64, | ||
) -> Result<()> { | ||
let conn = self.conn(); | ||
conn.execute( | ||
PUT_BLOB, | ||
params![did, cid.to_string(), mime_type, size, now], | ||
)?; | ||
Ok(()) | ||
} | ||
| ||
/// `did`'s blob `cid`. | ||
pub fn blob(&self, did: &str, cid: &Cid) -> Result<Option<Blob>> { | ||
let conn = self.conn(); | ||
let found = conn.query_row(GET_BLOB, params![did, cid.to_string()], |r| { | ||
Ok(Blob { | ||
mime_type: r.get(0)?, | ||
size: r.get(1)?, | ||
temporary: r.get(2)?, | ||
}) | ||
}); | ||
Ok(found.optional()?) | ||
} | ||
| ||
/// The blobs `did`'s records reference, in CID order after `cursor`, | ||
/// at most `limit`; with `since`, of records written after that rev. | ||
pub fn list_blobs( | ||
&self, | ||
did: &str, | ||
since: Option<&str>, | ||
cursor: Option<&str>, | ||
limit: u32, | ||
) -> Result<Vec<Cid>> { | ||
let conn = self.conn(); | ||
let mut q = conn.prepare(LIST_BLOBS)?; | ||
let asked = params![did, since.unwrap_or(""), cursor.unwrap_or(""), limit]; | ||
let rows = q.query_map(asked, |r| Ok(cid(r.get(0)?))); | ||
let rows = rows?; | ||
Ok(rows.collect::<rusqlite::Result<_>>()?) | ||
} | ||
| ||
/// Forgets the temporary blobs made before `cutoff`, answering them, | ||
/// for their files to go. | ||
pub fn sweep_blobs(&self, cutoff: i64) -> Result<Vec<(String, Cid)>> { | ||
let conn = self.conn(); | ||
let mut q = conn.prepare(SWEEP_BLOBS)?; | ||
let rows = q.query_map([cutoff], |r| Ok((r.get(0)?, cid(r.get(1)?)))); | ||
let rows = rows?; | ||
Ok(rows.collect::<rusqlite::Result<_>>()?) | ||
} | ||
| ||
/// Up to `limit` events after `cursor`, in order. | ||
crates/group-host/tests/blobs.rsnew+241−0
| @@ -0,0 +1,241 @@ | ||
//! Blobs: uploaded, made permanent by a record that references them, | ||
//! served and listed, and gone once nothing references them. | ||
| ||
mod common; | ||
| ||
use atproto::{Cid, Value, drisl}; | ||
use common::{Running, start}; | ||
use group_host::blobs::{TEMPORARY_FOR, blob_refs}; | ||
use group_host::repo::Write; | ||
use group_host::time::now_millis; | ||
use serde_json::{Value as Json, json}; | ||
| ||
const RIDERS: &str = "riders.groups.test"; | ||
| ||
fn profile(rkey: &str, avatar: &Json) -> Write { | ||
Write::Create { | ||
collection: "fyi.opensocial.profile".into(), | ||
rkey: rkey.into(), | ||
value: json!({"$type": "fyi.opensocial.profile", "displayName": "Riders", "avatar": avatar}), | ||
} | ||
} | ||
| ||
async fn blob(h: &Running, did: &str, cid: &str) -> (u16, reqwest::header::HeaderMap, Vec<u8>) { | ||
let url = format!( | ||
"{}/xrpc/com.atproto.sync.getBlob?did={did}&cid={cid}", | ||
h.url | ||
); | ||
let res = h.http.get(url).send().await.unwrap(); | ||
( | ||
res.status().as_u16(), | ||
res.headers().clone(), | ||
res.bytes().await.unwrap().to_vec(), | ||
) | ||
} | ||
| ||
fn link(r: &Json) -> String { | ||
r["ref"]["$link"].as_str().unwrap().to_string() | ||
} | ||
| ||
#[tokio::test] | ||
async fn serves_a_blob_once_a_record_references_it() { | ||
let h = start(&[], false).await; | ||
let did = h.host.create_account(RIDERS).await.unwrap(); | ||
let picture = b"\x89PNG not really".to_vec(); | ||
let r = h.host.upload_blob(&did, &picture, "image/png").unwrap(); | ||
assert_eq!(r["mimeType"], "image/png"); | ||
assert_eq!(r["size"], picture.len()); | ||
let cid = link(&r); | ||
assert_eq!(cid, Cid::of_raw(&picture).to_string()); | ||
| ||
// Uploaded and not yet referenced: not served, not listed. | ||
let (status, _, body) = blob(&h, &did, &cid).await; | ||
assert_eq!(status, 400); | ||
assert_eq!( | ||
serde_json::from_slice::<Json>(&body).unwrap()["error"], | ||
"BlobNotFound" | ||
); | ||
| ||
h.host.write(&did, &[profile("self", &r)]).unwrap(); | ||
let (status, headers, body) = blob(&h, &did, &cid).await; | ||
assert_eq!(status, 200); | ||
assert_eq!(body, picture); | ||
assert_eq!(headers["content-type"], "image/png"); | ||
assert_eq!(headers["x-content-type-options"], "nosniff"); | ||
assert_eq!( | ||
headers["content-security-policy"], | ||
"default-src 'none'; sandbox" | ||
); | ||
let (_, listed) = h | ||
.get("com.atproto.sync.listBlobs", &format!("did={did}")) | ||
.await; | ||
assert_eq!(listed, json!({"cids": [cid], "cursor": null})); | ||
| ||
// The commit's event names the blob. | ||
let events = h.host.store.events_after(0, 100).unwrap(); | ||
let body = drisl::decode(&events.last().unwrap().body) | ||
.unwrap() | ||
.into_map() | ||
.unwrap(); | ||
assert_eq!( | ||
body["blobs"], | ||
Value::Array(vec![Value::Link(Cid::parse(&cid).unwrap())]) | ||
); | ||
} | ||
| ||
#[tokio::test] | ||
async fn keeps_a_blob_while_any_record_references_it() { | ||
let h = start(&[], false).await; | ||
let did = h.host.create_account(RIDERS).await.unwrap(); | ||
let r = h.host.upload_blob(&did, b"shared", "image/png").unwrap(); | ||
let cid = link(&r); | ||
h.host | ||
.write(&did, &[profile("a", &r), profile("b", &r)]) | ||
.unwrap(); | ||
h.host | ||
.write( | ||
&did, | ||
&[Write::Delete { | ||
collection: "fyi.opensocial.profile".into(), | ||
rkey: "a".into(), | ||
}], | ||
) | ||
.unwrap(); | ||
assert_eq!(blob(&h, &did, &cid).await.0, 200); | ||
h.host | ||
.write( | ||
&did, | ||
&[Write::Delete { | ||
collection: "fyi.opensocial.profile".into(), | ||
rkey: "b".into(), | ||
}], | ||
) | ||
.unwrap(); | ||
assert_eq!(blob(&h, &did, &cid).await.0, 400); | ||
let file = h | ||
.data | ||
.path() | ||
.join("blobs") | ||
.join(did.replace(':', "_")) | ||
.join(&cid); | ||
assert!(!file.exists()); | ||
} | ||
| ||
#[tokio::test] | ||
async fn lists_blobs_a_page_at_a_time_and_since_a_rev() { | ||
let h = start(&[], false).await; | ||
let did = h.host.create_account(RIDERS).await.unwrap(); | ||
let a = h.host.upload_blob(&did, b"one", "").unwrap(); | ||
assert_eq!(a["mimeType"], "application/octet-stream"); | ||
let first = h.host.write(&did, &[profile("a", &a)]).unwrap(); | ||
let b = h.host.upload_blob(&did, b"two", "image/png").unwrap(); | ||
h.host.write(&did, &[profile("b", &b)]).unwrap(); | ||
let mut both = [link(&a), link(&b)]; | ||
both.sort(); | ||
| ||
let (_, page) = h | ||
.get("com.atproto.sync.listBlobs", &format!("did={did}&limit=1")) | ||
.await; | ||
assert_eq!(page["cids"], json!([both[0]])); | ||
let cursor = page["cursor"].as_str().unwrap(); | ||
let (_, page) = h | ||
.get( | ||
"com.atproto.sync.listBlobs", | ||
&format!("did={did}&limit=1&cursor={cursor}"), | ||
) | ||
.await; | ||
assert_eq!(page["cids"], json!([both[1]])); | ||
let (_, since) = h | ||
.get( | ||
"com.atproto.sync.listBlobs", | ||
&format!("did={did}&since={}", first.rev), | ||
) | ||
.await; | ||
assert_eq!(since["cids"], json!([link(&b)])); | ||
} | ||
| ||
#[tokio::test] | ||
async fn refuses_what_it_cannot_keep_or_find() { | ||
let h = start(&[("BLOB_UPLOAD_LIMIT", "4")], false).await; | ||
let did = h.host.create_account(RIDERS).await.unwrap(); | ||
assert_eq!( | ||
h.host | ||
.upload_blob(&did, b"too big", "image/png") | ||
.unwrap_err() | ||
.error, | ||
"BlobTooLarge" | ||
); | ||
assert_eq!( | ||
h.host | ||
.upload_blob("did:plc:nobody", b"x", "image/png") | ||
.unwrap_err() | ||
.error, | ||
"RepoNotFound" | ||
); | ||
let stranger = json!({"$type": "blob", "ref": {"$link": Cid::of_raw(b"elsewhere").to_string()}, "mimeType": "image/png", "size": 9}); | ||
let refused = h | ||
.host | ||
.write(&did, &[profile("self", &stranger)]) | ||
.unwrap_err(); | ||
assert!( | ||
refused.message.contains("was not uploaded to"), | ||
"{}", | ||
refused.message | ||
); | ||
| ||
for (nsid, query, error) in [ | ||
( | ||
"com.atproto.sync.getBlob", | ||
"did=did:plc:nobody&cid=x", | ||
"RepoNotFound", | ||
), | ||
( | ||
"com.atproto.sync.getBlob", | ||
&format!("did={did}&cid=x") as &str, | ||
"InvalidRequest", | ||
), | ||
( | ||
"com.atproto.sync.listBlobs", | ||
"did=did:plc:nobody", | ||
"RepoNotFound", | ||
), | ||
] { | ||
let (_, body) = h.get(nsid, query).await; | ||
assert_eq!(body["error"], error, "{nsid}?{query}"); | ||
} | ||
} | ||
| ||
#[tokio::test] | ||
async fn sweeps_uploads_no_record_took() { | ||
let h = start(&[], false).await; | ||
let did = h.host.create_account(RIDERS).await.unwrap(); | ||
let kept = h.host.upload_blob(&did, b"kept", "image/png").unwrap(); | ||
h.host.write(&did, &[profile("self", &kept)]).unwrap(); | ||
let left = h.host.upload_blob(&did, b"left", "image/png").unwrap(); | ||
assert_eq!(h.host.sweep_blobs(now_millis()).unwrap(), 0); | ||
assert_eq!( | ||
h.host | ||
.sweep_blobs(now_millis() + TEMPORARY_FOR + 1000) | ||
.unwrap(), | ||
1 | ||
); | ||
let dir = h.data.path().join("blobs").join(did.replace(':', "_")); | ||
assert!(!dir.join(link(&left)).exists()); | ||
assert!(dir.join(link(&kept)).exists()); | ||
} | ||
| ||
#[test] | ||
fn finds_every_blob_a_record_references() { | ||
let a = Cid::of_raw(b"a"); | ||
let b = Cid::of_raw(b"b"); | ||
let blob = |c: &Cid| json!({"$type": "blob", "ref": {"$link": c.to_string()}}); | ||
let record = json!({ | ||
"avatar": blob(&a), | ||
"gallery": [blob(&b), blob(&a), {"$type": "blob", "ref": {"$link": "not a cid"}}], | ||
"other": {"$type": "fyi.opensocial.rule", "ref": {"$link": b.to_string()}}, | ||
"n": 1, | ||
}); | ||
let mut want = vec![a, b]; | ||
want.sort(); | ||
assert_eq!(blob_refs(&record), want); | ||
} | ||
crates/group-host/tests/config.rs+4−0
| @@ -51,6 +51,10 @@ fn refuses_what_does_not_read() { | ||
err(&[("PUBLIC_URL", "https://example.com/path")]), | ||
"PUBLIC_URL is no origin: https://example.com/path" | ||
); | ||
assert_eq!( | ||
err(&[("BLOB_UPLOAD_LIMIT", "lots")]), | ||
"BLOB_UPLOAD_LIMIT is no number of bytes: lots" | ||
); | ||
assert_eq!( | ||
err(&[("HANDLE_DOMAIN", "example.com")]), | ||
"HANDLE_DOMAIN starts with a dot: .example.com" | ||
crates/group-host/tests/repos.rs+6−1
| @@ -480,7 +480,12 @@ fn a_commit_builds_on_the_head_it_read() { | ||
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() | ||
.is_none() | ||
); | ||
assert_eq!(store.head("did:plc:a").unwrap().unwrap(), head); | ||
} | ||
| ||
docs/design/README.md+2−1
| @@ -63,7 +63,8 @@ says otherwise. | ||
3. **Accounts and repos.** The SQLite store, group accounts and their | ||
keys, `did:plc` creation, records and commits, `sync.*` and `did:web` | ||
for the host (done); the firehose (`subscribeRepos`, sync 1.1's | ||
commits with their proofs) and crawlers (done); blobs: | ||
commits with their proofs) and crawlers (done); blobs, kept on disk | ||
until no record references them (done): | ||
`pds/*`, `db/*`, `didWeb.ts`, `actors.ts`. | ||
4. **Groups and spaces.** `createGroup`, `getGroup`, `listGroups`, | ||
handles, profile, rules, activating and deleting; the meta and members | ||