1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
//! `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)
}