| 1 | //! Persistence for locally-added marketplace catalogs (#5311). |
| 2 | //! |
| 3 | //! Catalogs live in one sibling JSON file next to the plugin registry's |
| 4 | //! `state.json`, under the same Codewhale-owned `plugins/` root, and reuse the |
| 5 | //! registry's audited persistence machinery: private parent directory, atomic |
| 6 | //! temp-file publication, no-follow opens, and an `fd_lock` sidecar lock so a |
| 7 | //! concurrent TUI cannot interleave `add`/`remove` with a read. |
| 8 | //! |
| 9 | //! This is deliberately not a second database — it is the same store pattern |
| 10 | //! with a different schema, and it hard-fails closed on a malformed file |
| 11 | //! rather than rewriting it. |
| 12 | |
| 13 | use std::collections::BTreeMap; |
| 14 | use std::io::Read; |
| 15 | use std::path::{Path, PathBuf}; |
| 16 | |
| 17 | use serde::{Deserialize, Serialize}; |
| 18 | |
| 19 | use super::types::{MarketplaceCatalog, MarketplaceCatalogId}; |
| 20 | use crate::registry::{ |
| 21 | ensure_private_plugin_state_directory, harden_plugin_state_file, open_existing_regular_file, |
| 22 | open_state_lock, path_entry_exists, save_state_with_hardener, state_lock_path, |
| 23 | validate_existing_plugin_state_parent, |
| 24 | }; |
| 25 | |
| 26 | const MARKETPLACE_SCHEMA_VERSION: u32 = 2; |
| 27 | const MARKETPLACE_STATE_FILE: &str = "marketplaces.json"; |
| 28 | |
| 29 | /// One stored catalog: the parsed result plus where the document was read |
| 30 | /// from, so relative sources resolve against the catalog's own location at |
| 31 | /// install time. |
| 32 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 33 | pub struct StoredMarketplaceCatalog { |
| 34 | pub added_at: String, |
| 35 | /// Absolute path the catalog document was read from. |
| 36 | pub source_path: String, |
| 37 | pub catalog: MarketplaceCatalog, |
| 38 | } |
| 39 | |
| 40 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 41 | pub struct MarketplaceState { |
| 42 | schema_version: u32, |
| 43 | #[serde(default)] |
| 44 | first_party_removed: bool, |
| 45 | #[serde(default)] |
| 46 | catalogs: BTreeMap<String, StoredMarketplaceCatalog>, |
| 47 | } |
| 48 | |
| 49 | impl Default for MarketplaceState { |
| 50 | fn default() -> Self { |
| 51 | Self { |
| 52 | schema_version: MARKETPLACE_SCHEMA_VERSION, |
| 53 | first_party_removed: false, |
| 54 | catalogs: BTreeMap::new(), |
| 55 | } |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | impl MarketplaceState { |
| 60 | #[must_use] |
| 61 | pub fn catalogs(&self) -> &BTreeMap<String, StoredMarketplaceCatalog> { |
| 62 | &self.catalogs |
| 63 | } |
| 64 | |
| 65 | pub fn get(&self, name: &str) -> Option<&StoredMarketplaceCatalog> { |
| 66 | self.catalogs.get(name) |
| 67 | } |
| 68 | } |
| 69 | |
| 70 | /// Handle on the sibling catalog store. `None` from [`MarketplaceStore::open`] |
| 71 | /// means the registry has no persistence root at all (fail-closed registry); |
| 72 | /// callers report that honestly instead of inventing a location. |
| 73 | pub struct MarketplaceStore { |
| 74 | path: PathBuf, |
| 75 | } |
| 76 | |
| 77 | impl MarketplaceStore { |
| 78 | /// Open the store that siblings the registry's `state.json`. |
| 79 | #[must_use] |
| 80 | pub fn open(state_path: Option<&Path>) -> Option<Self> { |
| 81 | let parent = state_path?.parent()?.to_path_buf(); |
| 82 | Some(Self { |
| 83 | path: parent.join(MARKETPLACE_STATE_FILE), |
| 84 | }) |
| 85 | } |
| 86 | |
| 87 | #[must_use] |
| 88 | pub fn path(&self) -> &Path { |
| 89 | &self.path |
| 90 | } |
| 91 | |
| 92 | /// Read all catalogs. Never writes; never creates the file or its lock. |
| 93 | pub fn load(&self) -> Result<MarketplaceState, String> { |
| 94 | validate_existing_plugin_state_parent(&self.path)?; |
| 95 | let lock_path = state_lock_path(&self.path); |
| 96 | let mut state = if path_entry_exists(&lock_path)? { |
| 97 | let lock_file = open_state_lock(&lock_path, false)?; |
| 98 | let lock = fd_lock::RwLock::new(lock_file); |
| 99 | let _guard = lock |
| 100 | .read() |
| 101 | .map_err(|e| format!("failed to read-lock marketplace state: {e}"))?; |
| 102 | self.load_unlocked()? |
| 103 | } else { |
| 104 | self.load_unlocked()? |
| 105 | }; |
| 106 | // Every surface consumes this same projection. Browsing is offline |
| 107 | // and read-only; installation and updates use the reviewed installer. |
| 108 | // A user's local catalog or removal always takes precedence. |
| 109 | replace_superseded_embedded_catalog(&mut state)?; |
| 110 | if !state.first_party_removed && !state.catalogs.contains_key("codewhale") { |
| 111 | state |
| 112 | .catalogs |
| 113 | .insert("codewhale".into(), first_party_catalog()?); |
| 114 | } |
| 115 | Ok(state) |
| 116 | } |
| 117 | |
| 118 | /// Maximum bytes read from the marketplace state file. |
| 119 | const MAX_STATE_BYTES: u64 = 1024 * 1024; |
| 120 | |
| 121 | fn load_unlocked(&self) -> Result<MarketplaceState, String> { |
| 122 | let Some(file) = open_existing_regular_file(&self.path, false)? else { |
| 123 | return Ok(MarketplaceState::default()); |
| 124 | }; |
| 125 | let mut raw = String::new(); |
| 126 | file.take(Self::MAX_STATE_BYTES + 1) |
| 127 | .read_to_string(&mut raw) |
| 128 | .map_err(|e| format!("failed to read {}: {e}", self.path.display()))?; |
| 129 | if raw.len() as u64 > Self::MAX_STATE_BYTES { |
| 130 | return Err(format!( |
| 131 | "marketplace state {} exceeds the 1 MiB limit", |
| 132 | self.path.display() |
| 133 | )); |
| 134 | } |
| 135 | let mut state: MarketplaceState = serde_json::from_str(&raw) |
| 136 | .map_err(|e| format!("failed to parse {}: {e}", self.path.display()))?; |
| 137 | if state.schema_version == 1 { |
| 138 | for entry in state.catalogs.values_mut().filter(|entry| { |
| 139 | matches!( |
| 140 | entry.catalog.format, |
| 141 | super::types::MarketplaceFormat::Claude |
| 142 | | super::types::MarketplaceFormat::Codex |
| 143 | ) |
| 144 | }) { |
| 145 | for candidate in &mut entry.catalog.candidates { |
| 146 | if candidate.install_plan.is_supported() |
| 147 | && matches!( |
| 148 | candidate.source, |
| 149 | super::types::MarketplaceSourceSpec::GitHub { .. } |
| 150 | ) |
| 151 | { |
| 152 | candidate.install_plan = super::types::MarketplaceInstallPlan::Unsupported { |
| 153 | reason: "Re-import this catalog to recover its original Git source, subdirectory and revision.".to_string(), |
| 154 | raw: candidate.name.clone(), |
| 155 | }; |
| 156 | } |
| 157 | } |
| 158 | } |
| 159 | state.schema_version = MARKETPLACE_SCHEMA_VERSION; |
| 160 | } |
| 161 | if state.schema_version != MARKETPLACE_SCHEMA_VERSION { |
| 162 | return Err(format!( |
| 163 | "unsupported marketplace state schema {}; expected {MARKETPLACE_SCHEMA_VERSION} at {}", |
| 164 | state.schema_version, |
| 165 | self.path.display() |
| 166 | )); |
| 167 | } |
| 168 | Ok(collapse_same_source_catalogs(state)) |
| 169 | } |
| 170 | |
| 171 | /// Insert a catalog under `id`, keyed by its source document. |
| 172 | /// |
| 173 | /// A catalog *is* its source: re-adding the same document updates that |
| 174 | /// catalog in place — and renames it to the requested `id` when the name |
| 175 | /// differs — instead of colliding on whatever name the previous add chose. |
| 176 | /// That collision is what produced a second, stale snapshot of the |
| 177 | /// codewhale marketplace under a hand-made name ("cw2") sitting beside |
| 178 | /// `codewhale`, two copies of one source. An existing *different* source |
| 179 | /// under `id` still refuses, so a name never silently re-points. |
| 180 | pub fn add( |
| 181 | &self, |
| 182 | id: &MarketplaceCatalogId, |
| 183 | entry: StoredMarketplaceCatalog, |
| 184 | ) -> Result<(), String> { |
| 185 | self.mutate(|state| { |
| 186 | let source = canonical_source_path(&entry.source_path); |
| 187 | if let Some(existing) = state.catalogs.get(id.as_str()) |
| 188 | && canonical_source_path(&existing.source_path) != source |
| 189 | { |
| 190 | return Err(format!( |
| 191 | "a marketplace named `{}` already exists; /plugin marketplace remove {} first", |
| 192 | id.as_str(), |
| 193 | id.as_str() |
| 194 | )); |
| 195 | } |
| 196 | let duplicates: Vec<String> = state |
| 197 | .catalogs |
| 198 | .iter() |
| 199 | .filter(|(key, catalog)| { |
| 200 | key.as_str() != id.as_str() |
| 201 | && canonical_source_path(&catalog.source_path) == source |
| 202 | }) |
| 203 | .map(|(key, _)| key.clone()) |
| 204 | .collect(); |
| 205 | for key in duplicates { |
| 206 | state.catalogs.remove(&key); |
| 207 | } |
| 208 | state.catalogs.insert(id.as_str().to_string(), entry); |
| 209 | Ok(()) |
| 210 | }) |
| 211 | } |
| 212 | |
| 213 | /// Remove a catalog by name. `Ok(false)` means it was not stored. |
| 214 | pub fn remove(&self, name: &str) -> Result<bool, String> { |
| 215 | self.mutate(|state| { |
| 216 | let removed = state.catalogs.remove(name).is_some(); |
| 217 | let bundled = name == "codewhale" && !state.first_party_removed; |
| 218 | if name == "codewhale" { |
| 219 | state.first_party_removed = true; |
| 220 | } |
| 221 | Ok(removed || bundled) |
| 222 | }) |
| 223 | } |
| 224 | |
| 225 | fn mutate<R>( |
| 226 | &self, |
| 227 | mutate: impl FnOnce(&mut MarketplaceState) -> Result<R, String>, |
| 228 | ) -> Result<R, String> { |
| 229 | let lock_path = state_lock_path(&self.path); |
| 230 | if let Some(parent) = lock_path.parent() { |
| 231 | ensure_private_plugin_state_directory(parent)?; |
| 232 | } |
| 233 | let lock_file = open_state_lock(&lock_path, true)?; |
| 234 | let mut lock = fd_lock::RwLock::new(lock_file); |
| 235 | let _guard = lock |
| 236 | .write() |
| 237 | .map_err(|e| format!("failed to lock marketplace state for update: {e}"))?; |
| 238 | let mut next = self.load_unlocked()?; |
| 239 | replace_superseded_embedded_catalog(&mut next)?; |
| 240 | let result = mutate(&mut next)?; |
| 241 | save_state_with_hardener(&self.path, &next, harden_plugin_state_file)?; |
| 242 | Ok(result) |
| 243 | } |
| 244 | } |
| 245 | |
| 246 | /// Canonical form of a catalog's source document, for source-identity |
| 247 | /// comparison. This is the identity the store keys updates and duplicate |
| 248 | /// detection on (the marketplace sibling of grokbuild's |
| 249 | /// `MarketplaceSource::identity`). Falls back to the stored string when the |
| 250 | /// path is not readable as a file — a GitHub URL, or a document that has |
| 251 | /// since moved away. |
| 252 | /// |
| 253 | /// The `std::fs` site below carries a budget entry in |
| 254 | /// `scripts/check-blocking-calls-budget.json`: the ratchet counts a |
| 255 | /// synchronous helper's site regardless of its callers, and this helper |
| 256 | /// cannot move to the blocking pool without restructuring the store's |
| 257 | /// synchronous `load`/`add`/`remove` API (#6149). Async callers such as |
| 258 | /// `runtime_api::plugins` run the store under `spawn_blocking`. |
| 259 | fn canonical_source_path(path: &str) -> PathBuf { |
| 260 | std::fs::canonicalize(path).unwrap_or_else(|_| PathBuf::from(path)) |
| 261 | } |
| 262 | |
| 263 | /// Collapse catalogs that point at the same source document. |
| 264 | /// |
| 265 | /// Older states can hold one marketplace twice under two names (that is what |
| 266 | /// `"cw2"` was: a second snapshot of the same document, taken only because the |
| 267 | /// first name was already in use). Every surface should see one catalog per |
| 268 | /// source. The survivor is the entry whose key is the document's own declared |
| 269 | /// name when one exists, otherwise the most recently added; the projection is |
| 270 | /// in-memory, and the next write persists it. |
| 271 | fn collapse_same_source_catalogs(mut state: MarketplaceState) -> MarketplaceState { |
| 272 | let mut groups: BTreeMap<PathBuf, Vec<String>> = BTreeMap::new(); |
| 273 | for (key, catalog) in &state.catalogs { |
| 274 | groups |
| 275 | .entry(canonical_source_path(&catalog.source_path)) |
| 276 | .or_default() |
| 277 | .push(key.clone()); |
| 278 | } |
| 279 | for keys in groups.values() { |
| 280 | if keys.len() < 2 { |
| 281 | continue; |
| 282 | } |
| 283 | let named_after_document = keys.iter().find(|key| { |
| 284 | state |
| 285 | .catalogs |
| 286 | .get(key.as_str()) |
| 287 | .is_some_and(|catalog| catalog.catalog.name == key.as_str()) |
| 288 | }); |
| 289 | let keeper = named_after_document.cloned().or_else(|| { |
| 290 | keys.iter() |
| 291 | .max_by(|left, right| { |
| 292 | let added = |key: &String| { |
| 293 | state |
| 294 | .catalogs |
| 295 | .get(key.as_str()) |
| 296 | .map(|catalog| catalog.added_at.as_str()) |
| 297 | .unwrap_or_default() |
| 298 | }; |
| 299 | added(left).cmp(added(right)) |
| 300 | }) |
| 301 | .cloned() |
| 302 | }); |
| 303 | let Some(keeper) = keeper else { continue }; |
| 304 | for key in keys { |
| 305 | if *key != keeper { |
| 306 | state.catalogs.remove(key); |
| 307 | } |
| 308 | } |
| 309 | } |
| 310 | state |
| 311 | } |
| 312 | |
| 313 | #[derive(Deserialize)] |
| 314 | struct EmbeddedSnapshot { |
| 315 | repository: String, |
| 316 | revision: String, |
| 317 | catalog: serde_json::Value, |
| 318 | } |
| 319 | |
| 320 | impl EmbeddedSnapshot { |
| 321 | fn embedded() -> Result<Self, String> { |
| 322 | serde_json::from_str(include_str!("../../assets/first-party-marketplace.json")) |
| 323 | .map_err(|error| format!("invalid bundled marketplace: {error}")) |
| 324 | } |
| 325 | |
| 326 | fn source(&self) -> String { |
| 327 | format!("{}/tree/{}", self.repository, self.revision) |
| 328 | } |
| 329 | |
| 330 | fn supersedes(&self, source_path: &str) -> bool { |
| 331 | source_path |
| 332 | .strip_prefix(&format!("{}/tree/", self.repository)) |
| 333 | .is_some_and(|revision| { |
| 334 | revision != self.revision |
| 335 | && revision.len() == 40 |
| 336 | && revision.bytes().all(|byte| byte.is_ascii_hexdigit()) |
| 337 | }) |
| 338 | } |
| 339 | } |
| 340 | |
| 341 | fn replace_superseded_embedded_catalog(state: &mut MarketplaceState) -> Result<(), String> { |
| 342 | if state.first_party_removed { |
| 343 | return Ok(()); |
| 344 | } |
| 345 | let Some(stored) = state.catalogs.get("codewhale") else { |
| 346 | return Ok(()); |
| 347 | }; |
| 348 | let snapshot = EmbeddedSnapshot::embedded()?; |
| 349 | if snapshot.supersedes(&stored.source_path) { |
| 350 | state |
| 351 | .catalogs |
| 352 | .insert("codewhale".into(), first_party_catalog()?); |
| 353 | } |
| 354 | Ok(()) |
| 355 | } |
| 356 | |
| 357 | fn first_party_catalog() -> Result<StoredMarketplaceCatalog, String> { |
| 358 | let snapshot = EmbeddedSnapshot::embedded()?; |
| 359 | let source = snapshot.source(); |
| 360 | let mut catalog = super::parsers::parse_catalog(super::parsers::MarketplaceDocument { |
| 361 | catalog_id: MarketplaceCatalogId::new("codewhale"), |
| 362 | format: super::types::MarketplaceFormat::Codewhale, |
| 363 | root: snapshot.catalog, |
| 364 | base: Some(source.clone()), |
| 365 | }); |
| 366 | if catalog.error_count() > 0 { |
| 367 | return Err("bundled marketplace contains invalid entries".into()); |
| 368 | } |
| 369 | catalog.provenance.tier = super::types::CatalogTier::Official; |
| 370 | catalog.provenance.source_url = Some(source.clone()); |
| 371 | for candidate in &mut catalog.candidates { |
| 372 | candidate.provenance = catalog.provenance.clone(); |
| 373 | } |
| 374 | Ok(StoredMarketplaceCatalog { |
| 375 | added_at: String::new(), |
| 376 | source_path: source, |
| 377 | catalog, |
| 378 | }) |
| 379 | } |
| 380 | |
| 381 | #[cfg(test)] |
| 382 | mod tests { |
| 383 | use super::*; |
| 384 | use std::fs; |
| 385 | |
| 386 | #[test] |
| 387 | fn bundled_catalog_is_offline_installable_and_removable_without_rewriting_plugin_state() { |
| 388 | let root = tempfile::tempdir().unwrap(); |
| 389 | let state_path = root.path().join("plugins/state.json"); |
| 390 | let store = MarketplaceStore::open(Some(&state_path)).unwrap(); |
| 391 | let initial = store.load().unwrap(); |
| 392 | let catalog = initial.get("codewhale").expect("first-party catalog"); |
| 393 | let entries = snapshot_plugins(); |
| 394 | assert_eq!(catalog.catalog.total_candidates(), entries.len()); |
| 395 | assert_eq!(catalog.catalog.error_count(), 0); |
| 396 | assert_eq!(catalog.catalog.warning_count(), 0); |
| 397 | assert!(!catalog.catalog.provenance.grants_trust()); |
| 398 | let registry = crate::PluginRegistry::empty(root.path()); |
| 399 | for entry in entries { |
| 400 | let name = entry["name"].as_str().unwrap(); |
| 401 | let candidate = catalog.catalog.candidate_by_name(name).unwrap(); |
| 402 | assert!(candidate.install_plan.is_supported()); |
| 403 | assert!(!candidate.provenance.grants_trust()); |
| 404 | let super::super::document::CatalogInstallResolution::Supported { spec, .. } = |
| 405 | super::super::document::resolve_candidate_install(catalog, candidate, ®istry) |
| 406 | else { |
| 407 | panic!("uninstallable candidate") |
| 408 | }; |
| 409 | let source = entry["source"].as_str().unwrap(); |
| 410 | if let Some(sha256) = entry["sha256"].as_str() { |
| 411 | assert_eq!(spec, format!("{source}#sha256={sha256}")); |
| 412 | } else { |
| 413 | assert_eq!(spec, source); |
| 414 | assert!(spec.starts_with( |
| 415 | "https://codeload.github.com/codewhale-hq/codewhale-plugin-marketplace/" |
| 416 | )); |
| 417 | assert!(spec.contains("#path=")); |
| 418 | } |
| 419 | } |
| 420 | assert!(!store.path().exists(), "browsing must not write or fetch"); |
| 421 | assert!(store.remove("codewhale").unwrap()); |
| 422 | assert!(!store.remove("codewhale").unwrap()); |
| 423 | assert!(store.load().unwrap().catalogs().is_empty()); |
| 424 | assert!( |
| 425 | !state_path.exists(), |
| 426 | "catalog removal must not change plugin trust state" |
| 427 | ); |
| 428 | let mut local = first_party_catalog().unwrap(); |
| 429 | local.source_path = "/reviewed/local/marketplace.json".into(); |
| 430 | store |
| 431 | .add(&MarketplaceCatalogId::new("codewhale"), local) |
| 432 | .unwrap(); |
| 433 | assert_eq!( |
| 434 | store.load().unwrap().get("codewhale").unwrap().source_path, |
| 435 | "/reviewed/local/marketplace.json" |
| 436 | ); |
| 437 | } |
| 438 | |
| 439 | fn snapshot_plugins() -> Vec<serde_json::Value> { |
| 440 | let snapshot: serde_json::Value = |
| 441 | serde_json::from_str(include_str!("../../assets/first-party-marketplace.json")) |
| 442 | .unwrap(); |
| 443 | snapshot["catalog"]["plugins"].as_array().unwrap().clone() |
| 444 | } |
| 445 | |
| 446 | #[test] |
| 447 | fn every_remote_snapshot_entry_carries_a_sha256() { |
| 448 | let snapshot = EmbeddedSnapshot::embedded().unwrap(); |
| 449 | let pinned_bundle = format!( |
| 450 | "https://codeload.github.com/codewhale-hq/codewhale-plugin-marketplace/tar.gz/{}#", |
| 451 | snapshot.revision |
| 452 | ); |
| 453 | let mut remote = 0; |
| 454 | for entry in snapshot_plugins() { |
| 455 | let source = entry["source"].as_str().unwrap(); |
| 456 | assert!( |
| 457 | source.starts_with("https://"), |
| 458 | "{source} is not a pinned remote source" |
| 459 | ); |
| 460 | if source.starts_with(&pinned_bundle) { |
| 461 | continue; |
| 462 | } |
| 463 | remote += 1; |
| 464 | let sha256 = entry["sha256"].as_str().unwrap_or_default(); |
| 465 | assert!( |
| 466 | sha256.len() == 64 |
| 467 | && sha256 |
| 468 | .bytes() |
| 469 | .all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f')), |
| 470 | "{} has no sha256", |
| 471 | entry["name"] |
| 472 | ); |
| 473 | assert!( |
| 474 | !source.contains("/latest/"), |
| 475 | "{} follows a floating release", |
| 476 | entry["name"] |
| 477 | ); |
| 478 | } |
| 479 | assert!(remote >= 1, "the computer-use release asset is remote"); |
| 480 | } |
| 481 | |
| 482 | fn write_state(store: &MarketplaceStore, source_path: &str) { |
| 483 | let mut catalog = first_party_catalog().unwrap(); |
| 484 | catalog.source_path = source_path.to_string(); |
| 485 | catalog.catalog.candidates.clear(); |
| 486 | let mut state = MarketplaceState::default(); |
| 487 | state.catalogs.insert("codewhale".into(), catalog); |
| 488 | ensure_private_plugin_state_directory(store.path().parent().unwrap()).unwrap(); |
| 489 | fs::write(store.path(), serde_json::to_string(&state).unwrap()).unwrap(); |
| 490 | } |
| 491 | |
| 492 | #[test] |
| 493 | fn a_saved_copy_of_an_older_embedded_snapshot_is_replaced() { |
| 494 | let root = tempfile::tempdir().unwrap(); |
| 495 | let store = MarketplaceStore::open(Some(&root.path().join("plugins/state.json"))).unwrap(); |
| 496 | let snapshot = EmbeddedSnapshot::embedded().unwrap(); |
| 497 | let older = format!("{}/tree/{}", snapshot.repository, "0".repeat(40)); |
| 498 | write_state(&store, &older); |
| 499 | |
| 500 | let loaded = store.load().unwrap(); |
| 501 | let kept = loaded.get("codewhale").unwrap(); |
| 502 | assert_eq!(kept.source_path, snapshot.source()); |
| 503 | assert!(kept.catalog.total_candidates() > 0); |
| 504 | |
| 505 | store |
| 506 | .add( |
| 507 | &MarketplaceCatalogId::new("codewhale"), |
| 508 | first_party_catalog().unwrap(), |
| 509 | ) |
| 510 | .unwrap(); |
| 511 | let persisted: MarketplaceState = |
| 512 | serde_json::from_str(&fs::read_to_string(store.path()).unwrap()).unwrap(); |
| 513 | assert_eq!( |
| 514 | persisted.get("codewhale").unwrap().source_path, |
| 515 | snapshot.source() |
| 516 | ); |
| 517 | } |
| 518 | |
| 519 | #[test] |
| 520 | fn desktop_bundled_and_person_added_catalogs_are_kept() { |
| 521 | let snapshot = EmbeddedSnapshot::embedded().unwrap(); |
| 522 | let bundled_file = Path::new("resources") |
| 523 | .join("marketplace") |
| 524 | .join("marketplace.json") |
| 525 | .display() |
| 526 | .to_string(); |
| 527 | let moving_branch = format!("{}/tree/main", snapshot.repository); |
| 528 | for source in [ |
| 529 | bundled_file.as_str(), |
| 530 | "https://example.com/team/marketplace.json", |
| 531 | moving_branch.as_str(), |
| 532 | ] { |
| 533 | let root = tempfile::tempdir().unwrap(); |
| 534 | let store = |
| 535 | MarketplaceStore::open(Some(&root.path().join("plugins/state.json"))).unwrap(); |
| 536 | write_state(&store, source); |
| 537 | let loaded = store.load().unwrap(); |
| 538 | let kept = loaded.get("codewhale").unwrap(); |
| 539 | assert_eq!(kept.source_path, source); |
| 540 | assert_eq!(kept.catalog.total_candidates(), 0); |
| 541 | } |
| 542 | } |
| 543 | |
| 544 | #[test] |
| 545 | fn malformed_store_is_not_hidden_by_bundled_catalog() { |
| 546 | let root = tempfile::tempdir().unwrap(); |
| 547 | let store = MarketplaceStore::open(Some(&root.path().join("state.json"))).unwrap(); |
| 548 | fs::write(store.path(), "broken").unwrap(); |
| 549 | assert!(store.load().is_err()); |
| 550 | assert_eq!(fs::read_to_string(store.path()).unwrap(), "broken"); |
| 551 | } |
| 552 | |
| 553 | fn catalog_from_source(source: &Path) -> StoredMarketplaceCatalog { |
| 554 | let mut catalog = first_party_catalog().unwrap(); |
| 555 | catalog.source_path = source.display().to_string(); |
| 556 | catalog |
| 557 | } |
| 558 | |
| 559 | /// `add` keys on the source document, not the name the previous add used: |
| 560 | /// re-adding the same marketplace under its real name replaces the |
| 561 | /// hand-made duplicate instead of colliding or leaving both behind. |
| 562 | #[test] |
| 563 | fn re_adding_the_same_source_renames_in_place() { |
| 564 | let root = tempfile::tempdir().unwrap(); |
| 565 | let store = MarketplaceStore::open(Some(&root.path().join("plugins/state.json"))).unwrap(); |
| 566 | let document = root.path().join("marketplace.json"); |
| 567 | fs::write(&document, "{}").unwrap(); |
| 568 | |
| 569 | store |
| 570 | .add( |
| 571 | &MarketplaceCatalogId::new("cw2"), |
| 572 | catalog_from_source(&document), |
| 573 | ) |
| 574 | .unwrap(); |
| 575 | store |
| 576 | .add( |
| 577 | &MarketplaceCatalogId::new("codewhale"), |
| 578 | catalog_from_source(&document), |
| 579 | ) |
| 580 | .unwrap(); |
| 581 | |
| 582 | let state = store.load().unwrap(); |
| 583 | assert!(state.get("cw2").is_none(), "the duplicate name is gone"); |
| 584 | assert_eq!( |
| 585 | state.get("codewhale").unwrap().source_path, |
| 586 | document.display().to_string() |
| 587 | ); |
| 588 | } |
| 589 | |
| 590 | /// A name is never silently re-pointed at a different source. |
| 591 | #[test] |
| 592 | fn a_name_never_re_points_at_a_different_source() { |
| 593 | let root = tempfile::tempdir().unwrap(); |
| 594 | let store = MarketplaceStore::open(Some(&root.path().join("plugins/state.json"))).unwrap(); |
| 595 | let first = root.path().join("first.json"); |
| 596 | let second = root.path().join("second.json"); |
| 597 | fs::write(&first, "{}").unwrap(); |
| 598 | fs::write(&second, "{}").unwrap(); |
| 599 | |
| 600 | store |
| 601 | .add( |
| 602 | &MarketplaceCatalogId::new("codewhale"), |
| 603 | catalog_from_source(&first), |
| 604 | ) |
| 605 | .unwrap(); |
| 606 | let refused = store |
| 607 | .add( |
| 608 | &MarketplaceCatalogId::new("codewhale"), |
| 609 | catalog_from_source(&second), |
| 610 | ) |
| 611 | .expect_err("a different source under a taken name must refuse"); |
| 612 | assert!(refused.contains("already exists"), "{refused}"); |
| 613 | assert_eq!( |
| 614 | store.load().unwrap().get("codewhale").unwrap().source_path, |
| 615 | first.display().to_string() |
| 616 | ); |
| 617 | } |
| 618 | |
| 619 | /// A state written before source identity was keyed can hold one source |
| 620 | /// twice under two names; the projection collapses it to the entry named |
| 621 | /// after the document itself. |
| 622 | #[test] |
| 623 | fn load_collapses_one_source_stored_under_two_names() { |
| 624 | let root = tempfile::tempdir().unwrap(); |
| 625 | let store = MarketplaceStore::open(Some(&root.path().join("plugins/state.json"))).unwrap(); |
| 626 | let document = root.path().join("marketplace.json"); |
| 627 | fs::write(&document, "{}").unwrap(); |
| 628 | |
| 629 | let mut state = MarketplaceState::default(); |
| 630 | for (key, added_at) in [ |
| 631 | ("codewhale", "2026-09-02T00:00:00Z"), |
| 632 | ("cw2", "2026-09-16T00:00:00Z"), |
| 633 | ] { |
| 634 | let mut catalog = catalog_from_source(&document); |
| 635 | catalog.added_at = added_at.to_string(); |
| 636 | state.catalogs.insert(key.to_string(), catalog); |
| 637 | } |
| 638 | ensure_private_plugin_state_directory(store.path().parent().unwrap()).unwrap(); |
| 639 | fs::write(store.path(), serde_json::to_string(&state).unwrap()).unwrap(); |
| 640 | |
| 641 | let loaded = store.load().unwrap(); |
| 642 | assert!(loaded.get("cw2").is_none()); |
| 643 | assert!(loaded.get("codewhale").is_some()); |
| 644 | assert_eq!( |
| 645 | loaded.get("codewhale").unwrap().source_path, |
| 646 | document.display().to_string() |
| 647 | ); |
| 648 | } |
| 649 | } |
| 650 |