use 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 = 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 = 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>> = 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 { 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 { 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 { 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> { 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 { 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) }