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

johnandersen777.bsky.social/vuln-notif

0
0
main
63 lines · 2.2 KB Raw History
//! `snapshot`: write every affected repository record to JSONL before apply.
//!
//! One file per collection (`<collection>.jsonl`), one JSON object per record
//! with `uri`, `cid`, and `value`. Writing the full collection is a superset of
//! the affected records and keeps rollback simple.

use std::io::Write as _;
use std::path::Path;

use anyhow::{Context, Result, bail};

use super::{ALL_COLLECTIONS, MigrationPlan, RemoteInventory};
use crate::pds::Publisher;

fn write_inventory(remote: &RemoteInventory, snapshot_dir: &Path) -> Result<usize> {
    let mut total = 0;
    std::fs::create_dir_all(snapshot_dir)
        .with_context(|| format!("create snapshot dir {}", snapshot_dir.display()))?;
    for collection in ALL_COLLECTIONS {
        let path = snapshot_dir.join(format!("{collection}.jsonl"));
        let file = std::fs::File::create(&path)
            .with_context(|| format!("create snapshot {}", path.display()))?;
        let mut writer = std::io::BufWriter::new(file);
        for record in remote.records(collection) {
            serde_json::to_writer(
                &mut writer,
                &serde_json::json!({
                    "uri": record.uri,
                    "cid": record.cid,
                    "value": record.value,
                }),
            )?;
            writer.write_all(b"\n")?;
            total += 1;
        }
        writer.flush()?;
    }
    Ok(total)
}

/// Snapshot the collections a plan touches. The plan's repository must match
/// the session repository; the payload is the live record set, not plan data.
pub async fn write_snapshot(
    publisher: &Publisher,
    plan: &MigrationPlan,
    snapshot_dir: &Path,
) -> Result<usize> {
    if publisher.repo() != plan.repo_did {
        bail!(
            "plan repo {} does not match session repo {}",
            plan.repo_did,
            publisher.repo()
        );
    }
    let remote = RemoteInventory::load(publisher, ALL_COLLECTIONS).await?;
    write_inventory(&remote, snapshot_dir)
}

/// Snapshot every migration collection without requiring a plan.
pub async fn snapshot_all(publisher: &Publisher, snapshot_dir: &Path) -> Result<usize> {
    let remote = RemoteInventory::load(publisher, ALL_COLLECTIONS).await?;
    write_inventory(&remote, snapshot_dir)
}