Something went wrong. Try again.
in-pds plc directory archive bundles
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271use anyhow::{Context, Result, bail};use bytes::Bytes;use rusqlite::Connection;
use crate::{ atproto::{self, Client, list_records, resolve_handle, resolve_pds_url}, bundle, config::{Args, PloxCommand}, db,};
const COLLECTION: &str = "blue.cerulea.plox.bundle";
#[derive(Clone)]struct BundleRecord { after: u64, count: u64, size: u64, cid: String,}
pub async fn pull(args: &Args) -> Result<()> { let PloxCommand::Pull { target, pds_host } = &args.command else { bail!("expected Pull command"); };
let http = reqwest::Client::builder().no_proxy().build()?;
let did = if target.starts_with("did:") { target.clone() } else { resolve_handle(&http, target).await? }; let pds_url = match pds_host.as_deref() { Some(url) => url.trim_end_matches('/').to_string(), None => resolve_pds_url(&http, &args.plc_url, &did).await?, };
let mut client = Client::anonymous(http.clone(), pds_url.clone()); tracing::info!(did, %pds_url, "enumerating bundles");
let mut bundles = Vec::new(); let mut cursor: Option<String> = None; loop { let page = list_records(&mut client, &did, COLLECTION, 100, false, cursor.as_deref()) .await .context("listRecords")?; if page.records.is_empty() { break; } for record in &page.records { bundles.push(parse_bundle_record(record)?); } match page.cursor { Some(c) if !c.is_empty() => cursor = Some(c), _ => break, } } bundles.sort_by_key(|b| b.after);
if bundles.is_empty() { bail!("no bundle records found in {did}"); } if bundles[0].after != 0 { tracing::warn!( first_after = bundles[0].after, "archive does not start at seq 0" ); } for (i, b) in bundles.iter().enumerate() { let expected = i as u64 * args.bundle_size; if b.after != expected { tracing::warn!( index = i, after = b.after, expected, "bundle gap or unexpected ordering" ); } } let total = bundles.len(); let covers_until = bundles.last().unwrap().after + bundles.last().unwrap().count; tracing::info!(total, covers_until, "archive enumerated");
let conn = db::open(&args.db_path)?;
let mut to_fetch: Vec<BundleRecord> = Vec::new(); for b in bundles { if bundle_covered(&conn, b.after, b.count)? { tracing::debug!(after = b.after, "already imported, skipping"); continue; } to_fetch.push(b); } tracing::info!( remaining = to_fetch.len(), skipped = total - to_fetch.len(), "bundles to pull" );
let start = std::time::Instant::now(); let mut imported: u64 = 0; let mut inflight: Option<tokio::task::JoinHandle<Result<Bytes>>> = None;
for (k, record) in to_fetch.iter().enumerate() { let bytes = match inflight.take() { Some(handle) => handle.await.context("join fetch task")??, None => fetch_logged(&http, &pds_url, &did, record, k + 1, to_fetch.len()).await?, };
// we can fetch the next blob _while_ this one is being inserted, so pipeline if k + 1 < to_fetch.len() { let next = to_fetch[k + 1].clone(); let num = k + 2; let total = to_fetch.len(); let http = http.clone(); let pds_url = pds_url.clone(); let did = did.clone(); inflight = Some(tokio::spawn(async move { fetch_logged(&http, &pds_url, &did, &next, num, total).await })); }
let ops = verify_and_decode(record, bytes)?; db::insert_ops(&conn, &ops)?; imported += ops.len() as u64;
let secs = start.elapsed().as_secs_f64(); tracing::info!( bundle = format!("{}/{}", k + 1, to_fetch.len()), after = record.after, "ops/s" = format!("{:.0}", imported as f64 / secs), "imported bundle" ); }
let max_seq = db::max_seq(&conn)?.unwrap_or(0); tracing::info!( imported, max_seq, secs = format!("{:.0}", start.elapsed().as_secs_f64()), "pull complete" ); if max_seq < covers_until { tracing::warn!( max_seq, covers_until, "local db does not cover the full archive" ); } tracing::info!("run `plox stream` to keep the db current");
Ok(())}
fn parse_bundle_record(record: &atproto::ListRecordsRecord) -> Result<BundleRecord> { let after = record .value .get("after") .and_then(|v| v.as_u64()) .with_context(|| format!("record {} missing 'after'", record.uri))?; let count = record .value .get("count") .and_then(|v| v.as_u64()) .with_context(|| format!("record {} missing 'count'", record.uri))?; let size = record .value .get("blob") .and_then(|b| b.get("size")) .and_then(|v| v.as_u64()) .unwrap_or(0); let cid = record .value .get("blob") .and_then(|b| b.get("ref")) .and_then(|r| r.get("$link")) .and_then(|l| l.as_str()) .with_context(|| format!("record {} missing blob.ref.$link", record.uri))? .to_string(); Ok(BundleRecord { after, count, size, cid, })}
async fn fetch_logged( http: &reqwest::Client, pds_url: &str, did: &str, record: &BundleRecord, num: usize, total: usize,) -> Result<Bytes> { let mb = record.size as f64 / 1_000_000.0; tracing::info!( bundle = format!("{num}/{total}"), after = record.after, "fetching bundle ({mb:.0}MB)" ); let fetch_start = std::time::Instant::now(); let bytes = fetch_blob(http, pds_url, did, &record.cid).await?; let secs = fetch_start.elapsed().as_secs_f64(); tracing::info!( bundle = format!("{num}/{total}"), after = record.after, "fetched bundle ({:.1} MB/s in {secs:.0}s)", mb / secs ); Ok(bytes)}
async fn fetch_blob(http: &reqwest::Client, pds_url: &str, did: &str, cid: &str) -> Result<Bytes> { let resp = http .get(format!("{pds_url}/xrpc/com.atproto.sync.getBlob")) .query(&[("did", did), ("cid", cid)]) .send() .await .with_context(|| format!("fetching blob {cid}"))?; if !resp.status().is_success() { let status = resp.status(); let body = resp.text().await.unwrap_or_default(); bail!("getBlob {cid} returned {status}: {body}"); } resp.bytes().await.with_context(|| format!("reading blob {cid}"))}
fn verify_and_decode(record: &BundleRecord, data: Bytes) -> Result<Vec<db::PlcSequencedOp>> { let cid = atproto::blob_cid(&data).to_string(); if cid != record.cid { bail!( "blob cid mismatch for after={after}: got {cid}, expected {expected}", after = record.after, expected = record.cid ); } let ops = bundle::decode_bundle(&data)?; if ops.len() != record.count as usize { bail!( "bundle after={} has {} ops, expected {}", record.after, ops.len(), record.count ); } let first = ops.first().map(|o| o.seq); let last = ops.last().map(|o| o.seq); if first != Some(record.after + 1) || last != Some(record.after + record.count) { bail!( "bundle after={} covers seq {:?}..{:?}, expected {}..{}", record.after, first, last, record.after + 1, record.after + record.count ); } Ok(ops)}
fn bundle_covered(conn: &Connection, after: u64, count: u64) -> Result<bool> { let have: i64 = conn.query_row( "SELECT COUNT(*) FROM ops WHERE seq > ?1 AND seq <= ?2", rusqlite::params![after as i64, (after + count) as i64], |r| r.get(0), )?; Ok(have as u64 == count)}