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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
//! One-time canonical identity migration (admin tool only).
//!
//! The service never runs this implicitly. `plan` inventories the local cache
//! and the remote repository, emits a reviewable JSON map, `apply` executes
//! that map in dependency order with a persisted cursor, `verify` re-reads the
//! repository, and `snapshot` writes the affected records to JSONL before any
//! write. The migration is idempotent: a `done` cursor row is skipped.
//!
//! `software_purls.software_slug` is normalized in place by the one-time
//! `normalize-purl-slugs` command (there is no startup `ALTER`).
pub mod apply;
pub mod plan;
pub mod remap;
pub mod snapshot;
pub mod verify;
use std::collections::BTreeMap;
use std::path::Path;
use anyhow::{Context, Result, bail};
use rusqlite::{Connection, OpenFlags};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use crate::constants::{
ATPROTO_COLLECTION, CHANNEL_COLLECTION, MANIFEST_COLLECTION, PROJECT_COLLECTION,
PURL_COLLECTION, SOFTWARE_COLLECTION, STATUS_COLLECTION, VERSION_COLLECTION,
};
use crate::pds::{Publisher, RecordItem};
/// Default `applyWrites` batch size for delete records.
pub const DEFAULT_BATCH: usize = 200;
const LIST_PAGE: usize = 100;
pub const RELEASE_COLLECTIONS: &[&str] = &[
PROJECT_COLLECTION,
CHANNEL_COLLECTION,
VERSION_COLLECTION,
MANIFEST_COLLECTION,
STATUS_COLLECTION,
];
pub const NAHDIG_COLLECTIONS: &[&str] = &[SOFTWARE_COLLECTION, PURL_COLLECTION, ATPROTO_COLLECTION];
pub const ALL_COLLECTIONS: &[&str] = &[
PROJECT_COLLECTION,
CHANNEL_COLLECTION,
VERSION_COLLECTION,
MANIFEST_COLLECTION,
STATUS_COLLECTION,
SOFTWARE_COLLECTION,
PURL_COLLECTION,
ATPROTO_COLLECTION,
];
/// One reviewable migration step.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum MigrationAction {
CreateProject,
RepointSoftware,
RepointPurl,
RepointCve,
RepointStatus,
DeleteReleaseRecord,
NormalizePurlSlug,
}
impl MigrationAction {
pub fn as_str(self) -> &'static str {
match self {
Self::CreateProject => "create_project",
Self::RepointSoftware => "repoint_software",
Self::RepointPurl => "repoint_purl",
Self::RepointCve => "repoint_cve",
Self::RepointStatus => "repoint_status",
Self::DeleteReleaseRecord => "delete_release_record",
Self::NormalizePurlSlug => "normalize_purl_slug",
}
}
/// Apply order: create projects, then move refs, then delete old records.
fn order(self) -> u8 {
match self {
Self::CreateProject => 0,
Self::RepointSoftware => 1,
Self::RepointPurl => 2,
Self::RepointCve => 3,
Self::RepointStatus => 4,
Self::NormalizePurlSlug => 5,
Self::DeleteReleaseRecord => 6,
}
}
}
/// One planned write. `legacy_uri` identifies the record being changed or
/// deleted; `canonical_uri` is the successor record or the same in-place
/// record for repoints. Values are resolved from the live inventory at apply
/// time, never rebuilt from stale plan data.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct MigrationEntry {
pub action: MigrationAction,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub legacy_slug: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub legacy_uri: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub canonical_slug: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub canonical_uri: Option<String>,
pub reason: String,
}
impl MigrationEntry {
/// Stable cursor key inside `identity_migration` (phase = action).
pub fn key(&self) -> String {
match self.action {
MigrationAction::CreateProject => self.canonical_slug.clone().unwrap_or_default(),
_ => self
.legacy_uri
.clone()
.or_else(|| self.legacy_slug.clone())
.unwrap_or_default(),
}
}
}
/// The complete, reviewable map written to `--out`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MigrationPlan {
pub repo_did: String,
pub generated_at: String,
pub entries: Vec<MigrationEntry>,
}
impl MigrationPlan {
pub fn sort(&mut self) {
self.entries.sort_by(|left, right| {
left.action
.order()
.cmp(&right.action.order())
.then_with(|| left.key().cmp(&right.key()))
});
}
pub fn count(&self, action: MigrationAction) -> usize {
self.entries
.iter()
.filter(|entry| entry.action == action)
.count()
}
}
/// One record read back from the repository through `listRecords`.
#[derive(Debug, Clone, PartialEq)]
pub struct RemoteRecord {
pub collection: String,
pub rkey: String,
pub uri: String,
pub cid: String,
pub value: Value,
}
/// Remote records grouped by collection. Built only from `listRecords`; local
/// link rows are never rebuilt from it.
#[derive(Debug, Clone, Default)]
pub struct RemoteInventory {
records: BTreeMap<String, Vec<RemoteRecord>>,
}
impl RemoteInventory {
pub async fn load(publisher: &Publisher, collections: &[&str]) -> Result<Self> {
let mut inventory = Self::default();
for collection in collections {
let mut cursor: Option<String> = None;
loop {
let page = publisher
.list_records(collection, cursor.as_deref(), Some(LIST_PAGE))
.await?;
for item in page.records {
inventory.insert(collection, item);
}
match page.cursor {
Some(next) if Some(next.as_str()) != cursor.as_deref() => cursor = Some(next),
_ => break,
}
}
}
Ok(inventory)
}
fn insert(&mut self, collection: &str, item: RecordItem) {
let Some((_, _, rkey)) = split_uri(&item.uri) else {
return;
};
self.records
.entry(collection.to_owned())
.or_default()
.push(RemoteRecord {
collection: collection.to_owned(),
rkey: rkey.to_owned(),
uri: item.uri,
cid: item.cid,
value: item.value,
});
}
pub fn records(&self, collection: &str) -> &[RemoteRecord] {
self.records
.get(collection)
.map(Vec::as_slice)
.unwrap_or_default()
}
pub fn all(&self) -> impl Iterator<Item = &RemoteRecord> {
self.records.values().flatten()
}
pub fn find_uri(&self, uri: &str) -> Option<&RemoteRecord> {
self.all().find(|record| record.uri == uri)
}
pub fn find_rkey(&self, collection: &str, rkey: &str) -> Option<&RemoteRecord> {
self.records(collection)
.iter()
.find(|record| record.rkey == rkey)
}
}
pub fn record_uri(repo: &str, collection: &str, rkey: &str) -> String {
format!("at://{repo}/{collection}/{rkey}")
}
pub fn project_uri(repo: &str, slug: &str) -> String {
record_uri(repo, PROJECT_COLLECTION, slug)
}
/// Split `at://did/collection/rkey`.
pub fn split_uri(uri: &str) -> Option<(&str, &str, &str)> {
let rest = uri.strip_prefix("at://")?;
let mut parts = rest.splitn(3, '/');
let did = parts.next()?;
let collection = parts.next()?;
let rkey = parts.next()?;
if did.is_empty() || collection.is_empty() || rkey.is_empty() {
return None;
}
Some((did, collection, rkey))
}
pub fn slug_of_project_uri(uri: &str) -> Option<&str> {
let (_, collection, rkey) = split_uri(uri)?;
(collection == PROJECT_COLLECTION).then_some(rkey)
}
/// Normalize a legacy `software_purls.software_slug`: some rows store the full
/// AT-URI instead of the slug.
pub fn normalized_purl_slug(raw: &str) -> &str {
if raw.starts_with("at://") {
split_uri(raw).map(|(_, _, rkey)| rkey).unwrap_or(raw)
} else {
raw
}
}
/// Every write in the migration is same-DID with the plan's repository.
pub fn assert_same_did(repo: &str, uri: &str) -> Result<()> {
match split_uri(uri) {
Some((did, _, _)) if did == repo => Ok(()),
Some((did, _, _)) => bail!("cross-DID reference {uri:?}: expected {repo}, got {did}"),
None => bail!("invalid at-uri {uri:?}"),
}
}
pub fn collect_strong_refs(value: &Value, out: &mut Vec<(String, String)>) {
match value {
Value::Object(map) => {
if let (Some(uri), Some(cid)) = (
map.get("uri").and_then(Value::as_str),
map.get("cid").and_then(Value::as_str),
) {
out.push((uri.to_owned(), cid.to_owned()));
}
for item in map.values() {
collect_strong_refs(item, out);
}
}
Value::Array(items) => {
for item in items {
collect_strong_refs(item, out);
}
}
_ => {}
}
}
/// Run the one-time `software_purls.software_slug` normalization.
pub async fn normalize_purl_slugs(db: &crate::db::DbHandle, repo_did: &str) -> Result<usize> {
let updated = db.normalize_purl_slugs(repo_did).await?;
db.commit().await?;
Ok(updated)
}
/// Read the repository DIDs recorded in a cache, for local-only commands.
pub fn local_repo_dids(cache_db: &Path) -> Result<Vec<String>> {
let connection = Connection::open_with_flags(cache_db, OpenFlags::SQLITE_OPEN_READ_ONLY)
.with_context(|| format!("open cache {} read-only", cache_db.display()))?;
connection.execute_batch("PRAGMA query_only=ON;")?;
let mut statement = connection.prepare(
"SELECT repo_did FROM software UNION SELECT repo_did FROM software_purls \
UNION SELECT repo_did FROM identity_migration ORDER BY repo_did",
)?;
let rows = statement.query_map([], |row| row.get::<_, String>(0))?;
Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?)
}