Skip to content

Commit 1bb3ae3

Browse files
committed
fix(plugins): clean stale marketplace upgrades
1 parent f93c18e commit 1bb3ae3

2 files changed

Lines changed: 222 additions & 0 deletions

File tree

‎codex-rs/core-plugins/src/marketplace_upgrade.rs‎

Lines changed: 114 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,10 +18,16 @@ use codex_config::types::MarketplaceConfig;
1818
use codex_config::types::MarketplaceSourceType;
1919
use codex_plugin::validate_plugin_segment;
2020
use codex_utils_absolute_path::AbsolutePathBuf;
21+
use std::fs::File;
2122
use std::path::Path;
2223
use std::time::Duration;
24+
use std::time::SystemTime;
25+
use tracing::warn;
2326

2427
const MARKETPLACE_UPGRADE_GIT_TIMEOUT: Duration = Duration::from_secs(30);
28+
const MARKETPLACE_UPGRADE_LOCK_FILE: &str = ".tmp/marketplaces.upgrade.lock";
29+
// This exceeds the complete bounded Git sequence while still reclaiming interrupted upgrades.
30+
const MARKETPLACE_UPGRADE_STALE_TEMP_DIR_MAX_AGE: Duration = Duration::from_secs(10 * 60);
2531

2632
#[derive(Debug, Clone, PartialEq, Eq)]
2733
pub struct ConfiguredMarketplaceUpgradeError {
@@ -95,6 +101,27 @@ pub fn upgrade_configured_git_marketplaces(
95101
.collect::<Vec<_>>();
96102
selected_marketplaces.sort_unstable();
97103
selected_marketplaces.dedup();
104+
let _upgrade_guard = match lock_configured_marketplace_upgrades(codex_home) {
105+
Ok(upgrade_guard) => upgrade_guard,
106+
Err(message) => {
107+
errors.extend(marketplaces.iter().map(|marketplace| {
108+
ConfiguredMarketplaceUpgradeError {
109+
marketplace_name: marketplace.name.clone(),
110+
message: message.clone(),
111+
}
112+
}));
113+
return ConfiguredMarketplaceUpgradeOutcome {
114+
selected_marketplaces,
115+
upgraded_roots: Vec::new(),
116+
errors,
117+
};
118+
}
119+
};
120+
let stale_before = SystemTime::now()
121+
.checked_sub(MARKETPLACE_UPGRADE_STALE_TEMP_DIR_MAX_AGE)
122+
.unwrap_or(SystemTime::UNIX_EPOCH);
123+
remove_stale_marketplace_upgrade_dirs(&install_root.join(".staging"), stale_before);
124+
98125
let mut upgraded_roots = Vec::new();
99126
let policy = MarketplacePolicy::from_requirements(config_layer_stack.requirements());
100127
for marketplace in marketplaces {
@@ -109,6 +136,17 @@ pub fn upgrade_configured_git_marketplaces(
109136
continue;
110137
}
111138
};
139+
match read_configured_git_marketplace(codex_home, &marketplace.name) {
140+
Ok(Some(current)) if current == marketplace => {}
141+
Ok(_) => continue,
142+
Err(message) => {
143+
errors.push(ConfiguredMarketplaceUpgradeError {
144+
marketplace_name: marketplace.name,
145+
message,
146+
});
147+
continue;
148+
}
149+
}
112150
match upgrade_configured_git_marketplace(
113151
codex_home,
114152
&install_root,
@@ -280,6 +318,82 @@ fn upgrade_configured_git_marketplace(
280318
.map(Some)
281319
.map_err(|err| format!("upgraded marketplace path is not absolute: {err}"))
282320
}
321+
322+
fn lock_configured_marketplace_upgrades(codex_home: &Path) -> Result<File, String> {
323+
let lock_path = codex_home.join(MARKETPLACE_UPGRADE_LOCK_FILE);
324+
let Some(lock_parent) = lock_path.parent() else {
325+
return Err(format!(
326+
"failed to determine configured marketplace upgrade lock parent for {}",
327+
lock_path.display()
328+
));
329+
};
330+
std::fs::create_dir_all(lock_parent).map_err(|err| {
331+
format!(
332+
"failed to create configured marketplace upgrade lock directory {}: {err}",
333+
lock_parent.display()
334+
)
335+
})?;
336+
let lock_file = File::options()
337+
.write(true)
338+
.create(true)
339+
.truncate(false)
340+
.open(&lock_path)
341+
.map_err(|err| {
342+
format!(
343+
"failed to open configured marketplace upgrade lock {}: {err}",
344+
lock_path.display()
345+
)
346+
})?;
347+
lock_file.lock().map_err(|err| {
348+
format!(
349+
"failed to lock configured marketplace upgrades at {}: {err}",
350+
lock_path.display()
351+
)
352+
})?;
353+
Ok(lock_file)
354+
}
355+
356+
fn remove_stale_marketplace_upgrade_dirs(staging_parent: &Path, stale_before: SystemTime) {
357+
let entries = match std::fs::read_dir(staging_parent) {
358+
Ok(entries) => entries,
359+
Err(err) if err.kind() == std::io::ErrorKind::NotFound => return,
360+
Err(err) => {
361+
warn!(
362+
error = %err,
363+
path = %staging_parent.display(),
364+
"failed to list configured marketplace staging directory"
365+
);
366+
return;
367+
}
368+
};
369+
370+
for entry in entries.flatten() {
371+
let path = entry.path();
372+
let is_upgrade_dir = path
373+
.file_name()
374+
.and_then(|name| name.to_str())
375+
.is_some_and(|name| name.starts_with("marketplace-upgrade-"));
376+
let Ok(file_type) = entry.file_type() else {
377+
continue;
378+
};
379+
if !is_upgrade_dir || !file_type.is_dir() || file_type.is_symlink() {
380+
continue;
381+
}
382+
let Ok(modified) = entry.metadata().and_then(|metadata| metadata.modified()) else {
383+
continue;
384+
};
385+
if modified > stale_before {
386+
continue;
387+
}
388+
if let Err(err) = std::fs::remove_dir_all(&path) {
389+
warn!(
390+
error = %err,
391+
path = %path.display(),
392+
"failed to remove stale configured marketplace upgrade directory"
393+
);
394+
}
395+
}
396+
}
283397
fn ensure_configured_git_marketplace_unchanged(
284398
codex_home: &Path,
285399
expected: &ConfiguredGitMarketplace,

‎codex-rs/core-plugins/src/marketplace_upgrade_tests.rs‎

Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,66 @@ use codex_config::ConfigLayerSource;
44
use codex_config::ConfigRequirements;
55
use codex_config::ConfigRequirementsToml;
66
use pretty_assertions::assert_eq;
7+
#[cfg(unix)]
8+
use std::os::unix::fs::symlink;
79
use std::path::Path;
810
use std::process::Command;
11+
use std::sync::Arc;
12+
use std::sync::Barrier;
913
use tempfile::TempDir;
1014

15+
#[test]
16+
fn stale_upgrade_cleanup_preserves_other_staging_entries() {
17+
let staging_parent = TempDir::new().expect("create staging parent");
18+
let stale_upgrade = staging_parent.path().join("marketplace-upgrade-stale");
19+
let backup = staging_parent.path().join("marketplace-backup-stale");
20+
let unrelated = staging_parent.path().join("unrelated");
21+
for path in [&stale_upgrade, &backup, &unrelated] {
22+
std::fs::create_dir(path).expect("create staging entry");
23+
std::fs::write(path.join("payload"), "keep or remove").expect("write staging payload");
24+
}
25+
26+
remove_stale_marketplace_upgrade_dirs(
27+
staging_parent.path(),
28+
SystemTime::now() + Duration::from_secs(1),
29+
);
30+
31+
assert!(!stale_upgrade.exists());
32+
assert!(backup.exists());
33+
assert!(unrelated.exists());
34+
}
35+
36+
#[test]
37+
fn stale_upgrade_cleanup_preserves_recent_upgrade() {
38+
let staging_parent = TempDir::new().expect("create staging parent");
39+
let recent_upgrade = staging_parent.path().join("marketplace-upgrade-recent");
40+
std::fs::create_dir(&recent_upgrade).expect("create recent upgrade");
41+
42+
remove_stale_marketplace_upgrade_dirs(staging_parent.path(), SystemTime::UNIX_EPOCH);
43+
44+
assert!(recent_upgrade.exists());
45+
}
46+
47+
#[cfg(unix)]
48+
#[test]
49+
fn stale_upgrade_cleanup_does_not_follow_symlinks() {
50+
let staging_parent = TempDir::new().expect("create staging parent");
51+
let target = TempDir::new().expect("create symlink target");
52+
std::fs::write(target.path().join("payload"), "keep").expect("write target payload");
53+
symlink(
54+
target.path(),
55+
staging_parent.path().join("marketplace-upgrade-link"),
56+
)
57+
.expect("create staging symlink");
58+
59+
remove_stale_marketplace_upgrade_dirs(
60+
staging_parent.path(),
61+
SystemTime::now() + Duration::from_secs(1),
62+
);
63+
64+
assert!(target.path().join("payload").exists());
65+
}
66+
1167
#[test]
1268
fn readback_ignores_unrelated_malformed_marketplace() {
1369
let codex_home = TempDir::new().expect("create Codex home");
@@ -87,6 +143,58 @@ source = {good_url:?}
87143
);
88144
}
89145

146+
#[test]
147+
fn concurrent_upgrades_serialize_and_skip_stale_config_snapshot() {
148+
let codex_home = TempDir::new().expect("create Codex home");
149+
let remote_repo = TempDir::new().expect("create remote repository");
150+
init_marketplace_repo(remote_repo.path(), "good");
151+
let source = url::Url::from_directory_path(remote_repo.path())
152+
.expect("remote repository URL")
153+
.to_string();
154+
let config = format!(
155+
r#"
156+
[marketplaces.good]
157+
source_type = "git"
158+
source = {source:?}
159+
"#
160+
);
161+
std::fs::write(codex_home.path().join(CONFIG_TOML_FILE), &config).expect("write config");
162+
let start = Arc::new(Barrier::new(2));
163+
164+
let (left, right) = std::thread::scope(|scope| {
165+
let codex_home_path = codex_home.path();
166+
let config = config.as_str();
167+
let left_start = Arc::clone(&start);
168+
let left = scope.spawn(move || {
169+
let stack = config_layer_stack(codex_home_path, config);
170+
left_start.wait();
171+
upgrade_configured_git_marketplaces(
172+
codex_home_path,
173+
&stack,
174+
/*marketplace_name*/ Some("good"),
175+
)
176+
});
177+
let right_start = Arc::clone(&start);
178+
let right = scope.spawn(move || {
179+
let stack = config_layer_stack(codex_home_path, config);
180+
right_start.wait();
181+
upgrade_configured_git_marketplaces(
182+
codex_home_path,
183+
&stack,
184+
/*marketplace_name*/ Some("good"),
185+
)
186+
});
187+
(
188+
left.join().expect("left upgrade thread"),
189+
right.join().expect("right upgrade thread"),
190+
)
191+
});
192+
193+
assert!(left.errors.is_empty());
194+
assert!(right.errors.is_empty());
195+
assert_eq!(left.upgraded_roots.len() + right.upgraded_roots.len(), 1);
196+
}
197+
90198
#[test]
91199
fn upgrade_uses_validated_source_for_git_operations() {
92200
let codex_home = TempDir::new().expect("create Codex home");

0 commit comments

Comments
 (0)