//! `plan`: inventory the cache and repository and emit a reviewable map. //! //! The local cache is read read-only: the service's [`DbHandle`] exposes point //! lookups only, so bulk inventory uses a read-only SQLite connection to the //! same file. Nothing is written to the cache or the PDS. use std::collections::{BTreeMap, BTreeSet}; use std::path::Path; use anyhow::{Context, Result}; use rusqlite::{Connection, OpenFlags}; use serde_json::Value; use super::remap::{LegacyReleaseKind, RemapMap, StrongRef, legacy_release_records, project_ref}; use super::{ ALL_COLLECTIONS, MigrationAction, MigrationEntry, MigrationPlan, RemoteInventory, RemoteRecord, project_uri, slug_of_project_uri, split_uri, }; use crate::constants::{ ATPROTO_COLLECTION, CHANNEL_COLLECTION, MANIFEST_COLLECTION, PROJECT_COLLECTION, PURL_COLLECTION, SOFTWARE_COLLECTION, STATUS_COLLECTION, VERSION_COLLECTION, }; use crate::db::purl2cpe::{cpe_product_key, load_purl_map, versionless_purl}; use crate::identity::{ ObservedProduct, aliases, canonical_slug, canonicalize, canonicalize_all, observations_from_cve, }; use crate::pds::Publisher; /// Legacy `vendor-product` slug exactly as pre-identity `software.rs` produced it. /// /// The migration must match rows already present in old caches, so this keeps /// the old rules (lowercase ASCII, non-alphanumeric runs to `-`, 64-char cap, /// part as empty fallback) even though the live sync path no longer uses them. fn slugify(part: &str, vendor: &str, product: &str) -> String { let mut raw = String::new(); let mut pending_dash = false; for ch in format!("{vendor}-{product}").to_lowercase().chars() { if ch.is_ascii_alphanumeric() { raw.push(ch); pending_dash = false; } else if !pending_dash && !raw.is_empty() { raw.push('-'); pending_dash = true; } } let mut raw = raw.trim_matches('-').to_owned(); if raw.is_empty() { raw = part.to_owned(); } let mut slug: String = raw.chars().take(64).collect(); slug = slug.trim_matches('-').to_owned(); if slug.is_empty() { "software".to_owned() } else { slug } } /// One cached software row (`software` table). #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct LocalSoftwareRow { pub slug: String, pub part: Option, pub vendor: Option, pub product: Option, } /// One cached PURL row (`software_purls` table). #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct LocalPurlRow { pub purl: String, pub software_slug: String, } /// Cached CVE JSON plus its id. #[derive(Debug, Clone, PartialEq)] pub struct LocalCve { pub id: String, pub value: Value, } #[derive(Debug, Clone, Default)] pub struct LocalInventory { pub software: Vec, pub purls: Vec, pub cves: Vec, } impl LocalInventory { pub fn load(cache_db: &Path, repo_did: &str) -> Result { 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 software = { let mut statement = connection.prepare( "SELECT slug, part, vendor, product FROM software \ WHERE repo_did=?1 ORDER BY slug", )?; let rows = statement.query_map([repo_did], |row| { Ok(LocalSoftwareRow { slug: row.get(0)?, part: row.get(1)?, vendor: row.get(2)?, product: row.get(3)?, }) })?; rows.collect::>>()? }; let purls = { let mut statement = connection.prepare( "SELECT purl, software_slug FROM software_purls \ WHERE repo_did=?1 ORDER BY purl", )?; let rows = statement.query_map([repo_did], |row| { Ok(LocalPurlRow { purl: row.get(0)?, software_slug: row.get(1)?, }) })?; rows.collect::>>()? }; let mut cves = Vec::new(); { let mut statement = connection.prepare("SELECT id, data FROM cves ORDER BY id")?; let rows = statement.query_map([], |row| { Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?)) })?; for row in rows { let (id, data) = row?; let value = serde_json::from_str(&data) .with_context(|| format!("parse cached CVE {id}"))?; cves.push(LocalCve { id, value }); } } Ok(Self { software, purls, cves, }) } } fn row_observation(row: &LocalSoftwareRow) -> ObservedProduct { ObservedProduct { source: "software-row".to_owned(), part: row.part.clone(), vendor: row.vendor.clone().unwrap_or_default(), product: row.product.clone().unwrap_or_default(), ..ObservedProduct::default() } } fn row_cpe_key(row: &LocalSoftwareRow) -> Option { let part = row.part.as_deref().filter(|part| !part.is_empty())?; let vendor = row.vendor.as_deref().unwrap_or_default(); let product = row.product.as_deref().unwrap_or_default(); if vendor.is_empty() || product.is_empty() { return None; } Some(format!( "{part}:{}:{}", vendor.replace(' ', "_").to_lowercase(), product.replace(' ', "_").to_lowercase() )) } fn reason_for(observed: &ObservedProduct, assigned: &str) -> String { let Some(identity) = canonicalize(observed) else { return format!("no canonical identity (placeholder or empty vendor/product); {assigned}"); }; let base = canonical_slug(&identity.canonical_vendor, &identity.canonical_family); let mut reason = format!( "canonical identity {}:{}:{} -> {assigned}", identity.class.as_str(), identity.canonical_vendor, identity.canonical_family ); if assigned != base { reason.push_str(" (slug collision: deterministic hash suffix)"); } else if aliases::aliases() .families .contains_key(&identity.canonical_family) { reason.push_str(" (curated alias)"); } reason } fn ref_field<'a>(value: &'a Value, key: &str, field: &str) -> Option<&'a str> { value.get(key)?.get(field)?.as_str() } fn project_cid<'a>(remote: &'a RemoteInventory, slug: &str) -> Option<&'a str> { remote .find_rkey(PROJECT_COLLECTION, slug) .map(|record| record.cid.as_str()) } /// The project a release record belongs to. Channels/versions repeat it in the /// rkey prefix as a fallback for records written before the field was required. fn record_project_slug(record: &RemoteRecord) -> Option { if record.collection == PROJECT_COLLECTION { return Some(record.rkey.clone()); } if let Some(uri) = record.value.get("project").and_then(Value::as_str) && let Some((_, _, rkey)) = split_uri(uri) { return Some(rkey.to_owned()); } if matches!( record.collection.as_str(), CHANNEL_COLLECTION | VERSION_COLLECTION ) { return record .rkey .split_once(':') .map(|(project, _)| project.to_owned()); } None } /// Build the migration plan. Read-only on both the cache and the PDS. pub async fn build_plan( publisher: &Publisher, repo_did: &str, cache_db: &Path, purldb: Option<&Path>, ) -> Result { let local = LocalInventory::load(cache_db, repo_did)?; let remote = RemoteInventory::load(publisher, ALL_COLLECTIONS).await?; let mut observations: Vec = local .software .iter() .map(row_observation) .filter(|observed| !observed.vendor.is_empty() && !observed.product.is_empty()) .collect(); for cve in &local.cves { observations.extend(observations_from_cve(&cve.value)); } observations.sort(); observations.dedup(); let identities = canonicalize_all(&observations); let mut assigned_slug: BTreeMap = BTreeMap::new(); for identity in &identities { assigned_slug.insert(identity.identity_key.clone(), identity.slug.clone()); } let mut cpe_identity: BTreeMap = BTreeMap::new(); for observed in &observations { let Some(identity) = canonicalize(observed) else { continue; }; for cpe in &observed.cpes { if let Some(key) = cpe_product_key(cpe) { cpe_identity .entry(key) .or_insert_with(|| identity.identity_key.clone()); } } } let mut purl_identity: BTreeMap = BTreeMap::new(); if let Some(purldb) = purldb.filter(|path| path.exists()) { let mut wanted: BTreeSet = cpe_identity.keys().cloned().collect(); wanted.extend(local.software.iter().filter_map(row_cpe_key)); let purl_map = load_purl_map(purldb, &wanted).await?; for (key, purls) in purl_map { let Some(identity_key) = cpe_identity.get(&key) else { continue; }; for purl in purls { purl_identity.insert(versionless_purl(&purl), identity_key.clone()); } } } // Legacy raw slug -> canonical slug. Software rows are authoritative; // CVE observations and purl2cpe fill gaps for variants without a row. let mut canonical_for_slug: BTreeMap = BTreeMap::new(); let mut canonical_slugs: BTreeSet = BTreeSet::new(); let mut reason_for_slug: BTreeMap = BTreeMap::new(); for row in &local.software { let observed = row_observation(row); let Some(identity) = canonicalize(&observed) else { continue; }; let Some(slug) = assigned_slug.get(&identity.identity_key) else { continue; }; canonical_for_slug.insert(row.slug.clone(), slug.clone()); canonical_slugs.insert(slug.clone()); reason_for_slug.insert(row.slug.clone(), reason_for(&observed, slug)); } for observed in &observations { let Some(identity) = canonicalize(observed) else { continue; }; let Some(slug) = assigned_slug.get(&identity.identity_key) else { continue; }; let legacy = slugify( observed.part.as_deref().unwrap_or("a"), &observed.vendor, &observed.product, ); if !legacy.is_empty() && !canonical_for_slug.contains_key(&legacy) { canonical_for_slug.insert(legacy.clone(), slug.clone()); reason_for_slug.insert(legacy, reason_for(observed, slug)); } } for row in &local.purls { let normalized = super::normalized_purl_slug(&row.software_slug).to_owned(); let Some(identity_key) = purl_identity.get(&versionless_purl(&row.purl)) else { continue; }; let Some(slug) = assigned_slug.get(identity_key) else { continue; }; canonical_for_slug .entry(normalized) .or_insert_with(|| slug.clone()); canonical_slugs.insert(slug.clone()); } let mut entries: Vec = Vec::new(); // Release projects that are legacy variants of a canonical project. The // mapping covers orphan channel/version/manifest records whose project // record is already gone. A slug owned by any identity as its canonical // project is never treated as legacy (collision safety). let canonical_owner: BTreeSet = assigned_slug.values().cloned().collect(); let mut legacy_project: BTreeMap = BTreeMap::new(); for (slug, target) in &canonical_for_slug { if slug != target && !canonical_owner.contains(slug) { legacy_project.insert(slug.clone(), target.clone()); } } for record in remote.records(PROJECT_COLLECTION) { if let Some(target) = canonical_for_slug.get(&record.rkey) && target != &record.rkey && !canonical_owner.contains(&record.rkey) { legacy_project.insert(record.rkey.clone(), target.clone()); canonical_slugs.insert(target.clone()); } } // Map every legacy project and existing canonical project, then mark the // release records that will be retired. let mut remap = RemapMap::new(repo_did); for (legacy, canonical) in &legacy_project { canonical_slugs.insert(canonical.clone()); let reference = project_ref(&remote, repo_did, canonical); remap.add_project(&project_uri(repo_did, legacy), reference.clone()); remap.add_project(legacy, reference); } for record in remote.records(PROJECT_COLLECTION) { if legacy_project.contains_key(&record.rkey) { remap.mark_deleted(&record.uri); continue; } let reference = StrongRef::new(record.uri.clone(), record.cid.clone()); remap.add_project(&record.uri, reference.clone()); remap.add_project(&record.rkey, reference); } // Legacy channel/version records follow the canonical record with the same // suffix when one exists, so status subjects can be repointed before the // legacy record is deleted. for collection in [CHANNEL_COLLECTION, VERSION_COLLECTION] { for record in remote.records(collection) { let Some(project) = record_project_slug(record) else { continue; }; let Some(target) = legacy_project.get(&project) else { continue; }; remap.mark_deleted(&record.uri); let Some((_, suffix)) = record.rkey.split_once(':') else { continue; }; let canonical_rkey = format!("{target}:{suffix}"); if let Some(canonical_record) = remote.find_rkey(collection, &canonical_rkey) { remap.add_release( &record.uri, StrongRef::new(canonical_record.uri.clone(), canonical_record.cid.clone()), ); } } } for record in remote.records(MANIFEST_COLLECTION) { if record_project_slug(record).is_some_and(|project| legacy_project.contains_key(&project)) { remap.mark_deleted(&record.uri); } } for legacy in legacy_release_records(&remote, &remap)? { if let Some(canonical) = &legacy.canonical_slug { canonical_slugs.insert(canonical.clone()); } entries.push(MigrationEntry { action: MigrationAction::DeleteReleaseRecord, legacy_slug: legacy.legacy_project.clone().or_else(|| { (legacy.kind == LegacyReleaseKind::Project).then(|| legacy.rkey.clone()) }), legacy_uri: Some(legacy.uri.clone()), canonical_slug: legacy.canonical_slug.clone(), canonical_uri: legacy .canonical_slug .as_ref() .map(|slug| project_uri(repo_did, slug)), reason: format!("{}: {}", legacy.reason.code(), legacy.reason.describe()), }); } // Repoint raw software records at their canonical project. let mut repointed_software: BTreeSet = BTreeSet::new(); for record in remote.records(SOFTWARE_COLLECTION) { let Some(target) = canonical_for_slug.get(&record.rkey) else { continue; }; canonical_slugs.insert(target.clone()); let expected_uri = project_uri(repo_did, target); let expected_cid = project_cid(&remote, target); let current_uri = ref_field(&record.value, "project", "uri"); let current_cid = ref_field(&record.value, "project", "cid"); let needs = current_uri != Some(expected_uri.as_str()) || expected_cid.is_none() || current_cid != expected_cid; if !needs { continue; } let reason = reason_for_slug .get(&record.rkey) .cloned() .unwrap_or_else(|| format!("raw software slug maps to {target}")); entries.push(MigrationEntry { action: MigrationAction::RepointSoftware, legacy_slug: Some(record.rkey.clone()), legacy_uri: Some(record.uri.clone()), canonical_slug: Some(target.clone()), canonical_uri: Some(expected_uri), reason, }); repointed_software.insert(record.uri.clone()); } // Repoint CVEs. A repoint is needed when a project ref is legacy, stale, // duplicated, or carries a strongRef to a record being deleted. for record in remote.records(ATPROTO_COLLECTION) { let Some(software) = record.value.get("software").and_then(Value::as_array) else { continue; }; if software.is_empty() { continue; } let mut needs = false; let mut targets: Vec = Vec::new(); for item in software { if let Some(project) = item.get("project") { let uri = project .get("uri") .and_then(Value::as_str) .unwrap_or_default(); if let Some(slug) = slug_of_project_uri(uri) { let target = canonical_for_slug .get(slug) .cloned() .or_else(|| canonical_slugs.contains(slug).then(|| slug.to_owned())); if let Some(target) = target { canonical_slugs.insert(target.clone()); if target != slug { needs = true; } match project_cid(&remote, &target) { Some(expected) => { if project.get("cid").and_then(Value::as_str) != Some(expected) { needs = true; } } None => needs = true, } targets.push(target); } } } } let unique: BTreeSet<&String> = targets.iter().collect(); if unique.len() != targets.len() { needs = true; } if !needs { continue; } let canonical_slug = if unique.len() == 1 { unique.first().map(|slug| (*slug).clone()) } else { None }; entries.push(MigrationEntry { action: MigrationAction::RepointCve, legacy_slug: Some( record .value .get("cve") .and_then(Value::as_str) .unwrap_or(&record.rkey) .to_owned(), ), legacy_uri: Some(record.uri.clone()), canonical_slug, canonical_uri: Some(record.uri.clone()), reason: format!( "CVE software refs move to canonical projects ({} distinct)", unique.len() ), }); } // PURL records hold strongRefs to the software records repointed above. for record in remote.records(PURL_COLLECTION) { let Some(refs) = record.value.get("software").and_then(Value::as_array) else { continue; }; let needs = refs.iter().any(|reference| { let uri = reference .get("uri") .and_then(Value::as_str) .unwrap_or_default(); if repointed_software.contains(uri) { return true; } match remote.find_uri(uri) { Some(software) => { reference.get("cid").and_then(Value::as_str) != Some(software.cid.as_str()) } None => false, } }); if !needs { continue; } entries.push(MigrationEntry { action: MigrationAction::RepointPurl, legacy_slug: record .value .get("purl") .and_then(Value::as_str) .map(str::to_owned), legacy_uri: Some(record.uri.clone()), canonical_slug: None, canonical_uri: Some(record.uri.clone()), reason: "purl software strongRefs follow the repointed software records".to_owned(), }); } // Status records follow a remappable subject; orphaned statuses were // classified for deletion above. for record in remote.records(STATUS_COLLECTION) { let Some(subject) = record.value.get("subject").and_then(Value::as_str) else { continue; }; let Some(target) = remap .release_for(subject) .or_else(|| remap.project_for(subject)) .filter(|target| target.uri != subject) else { continue; }; let canonical_slug = slug_of_project_uri(&target.uri).map(str::to_owned); if let Some(slug) = &canonical_slug { canonical_slugs.insert(slug.clone()); } entries.push(MigrationEntry { action: MigrationAction::RepointStatus, legacy_slug: record .rkey .split_once(':') .map(|(project, _)| project.to_owned()), legacy_uri: Some(record.uri.clone()), canonical_slug, canonical_uri: Some(target.uri.clone()), reason: format!("status subject {subject} moves to {}", target.uri), }); } // Canonical projects must exist before any reference points at them. for slug in &canonical_slugs { if remote.find_rkey(PROJECT_COLLECTION, slug).is_some() { continue; } entries.push(MigrationEntry { action: MigrationAction::CreateProject, legacy_slug: None, legacy_uri: None, canonical_slug: Some(slug.clone()), canonical_uri: Some(project_uri(repo_did, slug)), reason: format!("canonical project {slug} is missing; create before repointing refs"), }); } for row in &local.purls { if !row.software_slug.starts_with("at://") { continue; } let normalized = super::normalized_purl_slug(&row.software_slug); entries.push(MigrationEntry { action: MigrationAction::NormalizePurlSlug, legacy_slug: Some(row.software_slug.clone()), legacy_uri: None, canonical_slug: Some(normalized.to_owned()), canonical_uri: None, reason: format!( "software_purls.software_slug stores an AT-URI; normalize to {normalized}" ), }); } let mut plan = MigrationPlan { repo_did: repo_did.to_owned(), generated_at: crate::time::created_at(chrono::Utc::now()), entries, }; plan.sort(); Ok(plan) }