mirror of
https://github.com/storytold/craft-launcher.git
synced 2026-11-28 13:58:17 -08:00
Discover Developer Builds from the signed catalog before GitHub (#1679)
* feat: discover developer builds from the signed catalog first * test: exercise catalog discovery and bounded fallback end to end * fix: use actual reconciliation time and preserve unstarted nightly checks * fix(nightly): retain failed catalog attempts when fallback is held
This commit is contained in:
1 parent
3c954f1c66
commit
8ae67ab4a1
6 files changed
+961
-80
No files matched your search
@@ -67,6 +67,8 @@ pub struct FeedRelease {
|
||||
pub tag: String,
|
||||
pub name: String,
|
||||
pub published_at: Option<i64>,
|
||||
/// Actual release reconciliation time, independent of the website rebuild time.
|
||||
pub reconciled_at: Option<i64>,
|
||||
pub html_url: String,
|
||||
pub prerelease: bool,
|
||||
pub notes: String,
|
||||
@@ -345,6 +347,8 @@ struct CatalogRelease {
|
||||
#[serde(default)]
|
||||
published_at: Option<String>,
|
||||
#[serde(default)]
|
||||
reconciled_at: Option<String>,
|
||||
#[serde(default)]
|
||||
html_url: Option<String>,
|
||||
#[serde(default)]
|
||||
prerelease: bool,
|
||||
@@ -373,6 +377,7 @@ impl CatalogRelease {
|
||||
tag,
|
||||
name: self.name.unwrap_or_default(),
|
||||
published_at: self.published_at.as_deref().and_then(parse_rfc3339),
|
||||
reconciled_at: self.reconciled_at.as_deref().and_then(parse_rfc3339),
|
||||
html_url: self.html_url.unwrap_or_default(),
|
||||
prerelease: self.prerelease,
|
||||
notes: self.notes_markdown.unwrap_or_default(),
|
||||
@@ -490,6 +495,7 @@ impl RawRelease {
|
||||
tag,
|
||||
name: self.name.unwrap_or_default(),
|
||||
published_at: self.published_at.as_deref().and_then(parse_rfc3339),
|
||||
reconciled_at: None,
|
||||
html_url: self.html_url.unwrap_or_default(),
|
||||
prerelease: self.prerelease,
|
||||
notes: self.notes_markdown.unwrap_or_default(),
|
||||
|
||||
@@ -77,9 +77,9 @@ pub struct Isolation {
|
||||
|
||||
/// Validate a bounded, checksum-verified descriptor against a published nightly release.
|
||||
///
|
||||
/// `release` must come from the existing non-draft GitHub versions parser and have its published
|
||||
/// SHA256SUMS applied, or API digests present. No descriptor-provided URL, command, environment,
|
||||
/// path, platform signature or claimed profile capability is accepted on its own authority.
|
||||
/// `release` must come from the non-draft GitHub versions parser with published checksums, or
|
||||
/// the verified signed catalog with exact published asset sizes, time and checksums.
|
||||
/// No descriptor-provided URL, command, environment, path, platform signature or claimed profile capability is accepted on its own authority.
|
||||
///
|
||||
/// # Errors
|
||||
/// Refuses missing checksums, mismatched identity, unknown schema/fields, duplicate targets or
|
||||
|
||||
+175
-41
@@ -148,6 +148,8 @@ struct Shared {
|
||||
nightly_state: Mutex<crate::nightly_lookup::State>,
|
||||
#[cfg(test)]
|
||||
nightly_detection_observer: Mutex<Option<ReviewDetectionHook>>,
|
||||
#[cfg(test)]
|
||||
nightly_catalog_fixture: Mutex<Option<Feed>>,
|
||||
download_sizes: Mutex<HashMap<String, DownloadSize>>,
|
||||
installed: Mutex<HashMap<String, Installed>>,
|
||||
jobs: Mutex<HashMap<String, Arc<Stop>>>,
|
||||
@@ -492,6 +494,8 @@ impl NativeBackend {
|
||||
host: HostDetection::System,
|
||||
#[cfg(test)]
|
||||
nightly_detection_observer: Mutex::new(None),
|
||||
#[cfg(test)]
|
||||
nightly_catalog_fixture: Mutex::new(None),
|
||||
events: Mutex::new(Vec::new()),
|
||||
reporting: Mutex::new(()),
|
||||
system: Mutex::new(None),
|
||||
@@ -734,9 +738,8 @@ impl NativeBackend {
|
||||
self.check_nightly_at(manual, crate::now());
|
||||
}
|
||||
|
||||
// Deliberately use the GitHub Nightly verifier for automatic installation/update checks.
|
||||
// Signed catalog entries are discovery hints; they cannot replace the separately verified
|
||||
// platform-specific Nightly descriptor, checksum, publication and rollback checks.
|
||||
// One signed catalog snapshot supplies all due Nightly candidates; the same descriptor and
|
||||
// platform checks still apply. GitHub enumeration remains the bounded fallback.
|
||||
fn check_nightly_at(&self, manual: bool, now: i64) {
|
||||
let Some(platform) = self.platform else { return };
|
||||
let apps = self.nightly_apps();
|
||||
@@ -795,20 +798,44 @@ impl NativeBackend {
|
||||
(self.spawn)(Box::new(move || {
|
||||
let lease = NightlyCheckLease(shared.clone());
|
||||
shared.emit(Event::CheckStarted);
|
||||
let enabled = || {
|
||||
shared.options.lock().unwrap_or_else(PoisonError::into_inner).nightly_enabled
|
||||
&& shared.nightly_state.lock().unwrap_or_else(PoisonError::into_inner).generation == generation
|
||||
};
|
||||
// One signed catalog fetch (document + detached signature) for the entire roster.
|
||||
let catalog = enabled().then(|| http.as_ref().and_then(|http| nightly_catalog(http, &paths, &shared, &enabled))).flatten();
|
||||
// One sweep and one request at a time. All admitted app lookups share this deadline.
|
||||
let started = Instant::now();
|
||||
let mut discovery_fallbacks = 0;
|
||||
let mut deferred = Vec::new();
|
||||
let mut used_github = false;
|
||||
let mut used_catalog = false;
|
||||
let mut github_blocked = false;
|
||||
// `begin` decided the order: installed copies first, then the front of the queue.
|
||||
let by_key: std::collections::BTreeMap<String, CraftApp> =
|
||||
apps.into_iter().map(|app| (crate::nightly_lookup::key(&app, platform), app)).collect();
|
||||
// Preserve installed-first priority, then prefer catalog candidates in each group.
|
||||
let mut chosen = chosen;
|
||||
if let Some(feed) = &catalog {
|
||||
let state = shared.nightly_state.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
chosen.sort_by_key(|key| {
|
||||
(
|
||||
!installed.contains(key),
|
||||
by_key
|
||||
.get(key)
|
||||
.is_none_or(|app| crate::nightly_lookup::catalog_candidate(feed, app, now, state.record(key).tag.as_deref()).is_none()),
|
||||
)
|
||||
});
|
||||
}
|
||||
// When the launcher's own budget held this sweep back, so the page can say it is waiting
|
||||
// for GitHub instead of reporting a finished check that found nothing.
|
||||
let mut held_back_until = None;
|
||||
if http.is_none() && enabled() {
|
||||
shared.emit(Event::Notice { app: sweep_app.into(), result: Err("Secure Nightly connections are unavailable.".into()) });
|
||||
held_back_until = Some(crate::now().saturating_add(60));
|
||||
}
|
||||
for (index, key) in chosen.iter().enumerate() {
|
||||
let Some(app) = by_key.get(key).copied() else { continue };
|
||||
let enabled = || {
|
||||
shared.options.lock().unwrap_or_else(PoisonError::into_inner).nightly_enabled
|
||||
&& shared.nightly_state.lock().unwrap_or_else(PoisonError::into_inner).generation == generation
|
||||
};
|
||||
if !enabled() {
|
||||
break;
|
||||
}
|
||||
@@ -822,51 +849,103 @@ impl NativeBackend {
|
||||
Priority::Discovery
|
||||
};
|
||||
let backoff = shared.nightly_state.lock().unwrap_or_else(PoisonError::into_inner).backoff(crate::now());
|
||||
let outcome = if let Some(retry_at) = backoff {
|
||||
crate::nightly_lookup::Outcome::Indeterminate(crate::http::NightlyHttpError {
|
||||
over_budget: false,
|
||||
why: "Nightly discovery is waiting for server backoff.".into(),
|
||||
retry_at: Some(retry_at),
|
||||
})
|
||||
} else if let Some(http) = &http {
|
||||
crate::nightly_lookup::lookup(
|
||||
&app,
|
||||
platform,
|
||||
now,
|
||||
&mut |url, max, timeout, now| http.nightly_get_as(url, max, timeout, now, priority),
|
||||
&|| started.elapsed(),
|
||||
&enabled,
|
||||
)
|
||||
} else {
|
||||
crate::nightly_lookup::Outcome::Indeterminate(crate::http::NightlyHttpError {
|
||||
over_budget: false,
|
||||
why: "Secure Nightly connections are unavailable.".into(),
|
||||
retry_at: None,
|
||||
})
|
||||
let previous_tag = shared.nightly_state.lock().unwrap_or_else(PoisonError::into_inner).record(key).tag;
|
||||
let candidate =
|
||||
catalog.as_ref().and_then(|feed| crate::nightly_lookup::catalog_candidate(feed, &app, crate::now(), previous_tag.as_deref()));
|
||||
let previous = shared.nightly_verified.lock().unwrap_or_else(PoisonError::into_inner).get(app.id).cloned();
|
||||
let Some(http) = &http else {
|
||||
shared.nightly_state.lock().unwrap_or_else(PoisonError::into_inner).defer(key);
|
||||
deferred.push(key.clone());
|
||||
continue;
|
||||
};
|
||||
let mut before_lookup = || {
|
||||
let options = shared.options.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
let mut state = shared.nightly_state.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
let error = |why: String| crate::http::NightlyHttpError { over_budget: false, why, retry_at: None };
|
||||
if !options.nightly_enabled || state.generation != generation {
|
||||
return Err(error("Developer build discovery was turned off.".into()));
|
||||
}
|
||||
state.attempt(key, crate::now());
|
||||
state.save(&paths).map_err(error)
|
||||
};
|
||||
let policy = crate::nightly_lookup::LookupPolicy {
|
||||
candidate,
|
||||
previous: previous.as_ref(),
|
||||
backoff,
|
||||
github_blocked,
|
||||
before_lookup: &mut before_lookup,
|
||||
manual,
|
||||
installed: installed.contains(key),
|
||||
fallback_used: &mut discovery_fallbacks,
|
||||
};
|
||||
let Some((outcome, origin)) = crate::nightly_lookup::lookup_prefer_catalog(
|
||||
&app,
|
||||
platform,
|
||||
now,
|
||||
policy,
|
||||
&mut |url, max, timeout, now| http.nightly_get_as(url, max, timeout, now, priority),
|
||||
&|| started.elapsed(),
|
||||
&enabled,
|
||||
) else {
|
||||
shared.nightly_state.lock().unwrap_or_else(PoisonError::into_inner).defer(key);
|
||||
deferred.push(key.clone());
|
||||
continue;
|
||||
};
|
||||
if let crate::nightly_lookup::Outcome::Indeterminate(error) = &outcome
|
||||
&& error.over_budget
|
||||
{
|
||||
// The launcher's own budget refused this lookup and the ones behind it: no app
|
||||
// failed, so every remaining one goes back where it was and keeps its place in
|
||||
// the queue instead of waiting out a cadence for a request never made.
|
||||
let mut state = shared.nightly_state.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
for later in &chosen[index..] {
|
||||
state.defer(later);
|
||||
state.defer(key);
|
||||
deferred.push(key.clone());
|
||||
if started.elapsed() >= crate::nightly_lookup::MAX_TIME {
|
||||
for later in &chosen[index + 1..] {
|
||||
state.defer(later);
|
||||
deferred.push(later.clone());
|
||||
}
|
||||
break;
|
||||
}
|
||||
// A GitHub-only quota refusal does not consume static catalog results.
|
||||
github_blocked = true;
|
||||
held_back_until = http.nightly_budget_retry_at(priority, crate::now());
|
||||
continue;
|
||||
}
|
||||
used_github |= origin == Origin::GitHub;
|
||||
used_catalog |= origin == Origin::ArtCraftApi;
|
||||
finish_nightly_result(&app, platform, generation, outcome, origin, &shared, &paths);
|
||||
}
|
||||
if !deferred.is_empty() {
|
||||
let _reporting = shared.reporting.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
let options = shared.options.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
let state = shared.nightly_state.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
if options.nightly_enabled && state.generation == generation {
|
||||
match state.save(&paths) {
|
||||
Ok(()) => {
|
||||
// Queueing temporarily marked these rows incomplete. Restore their
|
||||
// presentation too when an allowance/backoff left them unattempted.
|
||||
let verified = shared.nightly_verified.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
for key in deferred {
|
||||
if let Some(app) = by_key.get(&key) {
|
||||
let record = state.record(&key);
|
||||
let fresh = state.fresh(&key, crate::now()) && (record.tag.is_none() || verified.contains_key(app.id));
|
||||
shared.emit(Event::NightlyStatus { app: app.id.into(), status: record.status(fresh) });
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(error) => log::warn!("Could not persist deferred Nightly scheduling: {error}"),
|
||||
}
|
||||
if let Err(error) = state.save(&paths) {
|
||||
log::warn!("Could not persist deferred Nightly scheduling: {error}");
|
||||
}
|
||||
held_back_until = http.as_ref().and_then(|http| http.nightly_budget_retry_at(priority, crate::now()));
|
||||
break;
|
||||
}
|
||||
finish_nightly_result(&app, platform, generation, outcome, &shared, &paths);
|
||||
}
|
||||
drop(lease);
|
||||
let retry = shared.nightly_state.lock().unwrap_or_else(PoisonError::into_inner).backoff(crate::now());
|
||||
shared.emit(Event::CheckFinished {
|
||||
at: crate::now(),
|
||||
source: Source::GitHubApi,
|
||||
source: if used_github {
|
||||
Source::GitHubApi
|
||||
} else if used_catalog {
|
||||
Source::Feed
|
||||
} else {
|
||||
Source::Cache
|
||||
},
|
||||
// A server's backoff, or the launcher's own budget: both mean "ask again at this time".
|
||||
rate_limited_until: retry.or(held_back_until),
|
||||
});
|
||||
@@ -1433,6 +1512,7 @@ fn finish_nightly_result(
|
||||
platform: Platform,
|
||||
generation: u64,
|
||||
mut outcome: crate::nightly_lookup::Outcome,
|
||||
origin: Origin,
|
||||
shared: &Shared,
|
||||
paths: &Paths,
|
||||
) {
|
||||
@@ -1487,7 +1567,7 @@ fn finish_nightly_result(
|
||||
let installable = nightly_installable(app, shared, Some(platform), record.complete && state.fresh(&key, now));
|
||||
shared.emit_all([
|
||||
Event::Installable { app: app.id.into(), installable },
|
||||
Event::Latest { app: app.id.into(), latest, from: Origin::GitHub },
|
||||
Event::Latest { app: app.id.into(), latest, from: origin },
|
||||
Event::NightlyStatus { app: app.id.into(), status: record.status(record.complete) },
|
||||
]);
|
||||
}
|
||||
@@ -2666,6 +2746,58 @@ fn fetch_feed_with_catalog(
|
||||
if asked { FeedFetch::Failed } else { FeedFetch::Held }
|
||||
}
|
||||
|
||||
/// Nightly uses the pinned signed endpoint only. A failed/bad/stale catalog never proves absence.
|
||||
/// Cached bytes are reverified; legacy JSON is not a Nightly source.
|
||||
fn nightly_catalog(http: &Http, paths: &Paths, shared: &Shared, enabled: &impl Fn() -> bool) -> Option<Feed> {
|
||||
// Existing backend fixtures and the opt-in local mirror must stay deterministic.
|
||||
if !enabled() || local_mirror().is_some() {
|
||||
return None;
|
||||
}
|
||||
#[cfg(test)]
|
||||
if cfg!(test) {
|
||||
return shared.nightly_catalog_fixture.lock().unwrap_or_else(PoisonError::into_inner).clone();
|
||||
}
|
||||
nightly_catalog_with_fetch(http, paths, &shared.feed_throttle, enabled, |url, max| http.get_catalog_feed_bytes(url, max))
|
||||
}
|
||||
|
||||
fn nightly_catalog_with_fetch(
|
||||
http: &Http,
|
||||
paths: &Paths,
|
||||
throttle: &Mutex<FeedThrottle>,
|
||||
enabled: &impl Fn() -> bool,
|
||||
get: impl Fn(&str, usize) -> Result<Option<Vec<u8>>, FeedError>,
|
||||
) -> Option<Feed> {
|
||||
if !enabled() {
|
||||
return None;
|
||||
}
|
||||
crate::nightly_profile::validate_paths(paths).ok()?;
|
||||
crate::nightly_profile::validate_file(&paths.feed_cache()).ok()?;
|
||||
match fetch_feed_with_catalog(http, paths, artcraft_launcher_core::feed::FEED_URL, throttle, 1, |url, max| {
|
||||
if !enabled() {
|
||||
return Err(FeedError::failed("Developer build discovery was turned off."));
|
||||
}
|
||||
get(url, max)
|
||||
}) {
|
||||
FeedFetch::Answered(feed) => Some(feed),
|
||||
FeedFetch::Held => load_signed_nightly_feed(paths),
|
||||
FeedFetch::Failed => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn load_signed_nightly_feed(paths: &Paths) -> Option<Feed> {
|
||||
use std::io::Read as _;
|
||||
const MAX: usize =
|
||||
artcraft_launcher_core::hosted_catalog::MAX_CATALOG_BYTES * 6 + artcraft_launcher_core::hosted_catalog::MAX_SIGNATURE_BYTES + 128;
|
||||
let mut file = std::fs::File::open(paths.feed_cache()).ok()?;
|
||||
let mut body = Vec::new();
|
||||
file.by_ref().take(MAX as u64 + 1).read_to_end(&mut body).ok()?;
|
||||
if body.len() > MAX {
|
||||
return None;
|
||||
}
|
||||
let saved: SignedFeedCache = serde_json::from_slice(&body).ok()?;
|
||||
Feed::parse_signed_catalog(saved.catalog.as_bytes(), saved.signature.as_bytes()).ok()
|
||||
}
|
||||
|
||||
/// The feed's address. `ARTCRAFT_LAUNCHER_FEED_URL` points at a staging server or a local copy
|
||||
/// (only `https://`, or plain `http://` on localhost).
|
||||
fn feed_url() -> String {
|
||||
@@ -3553,6 +3685,8 @@ mod tests {
|
||||
channel: artcraft_launcher_core::nightly::InstallChannel::Stable,
|
||||
host: HostDetection::Stub(Arc::new(|_| None)),
|
||||
nightly_detection_observer: Mutex::new(None),
|
||||
#[cfg(test)]
|
||||
nightly_catalog_fixture: Mutex::new(None),
|
||||
events: Mutex::new(Vec::new()),
|
||||
reporting: Mutex::new(()),
|
||||
system: Mutex::new(None),
|
||||
|
||||
@@ -16,8 +16,12 @@ fn app() -> &'static CraftApp {
|
||||
fn complete(shared: &Shared, paths: &Paths, platform: Platform, run: u64) {
|
||||
let key = nightly_lookup::key(app(), platform);
|
||||
let now = crate::now();
|
||||
shared.nightly_state.lock().unwrap().begin(&[key], &Default::default(), now, true, true);
|
||||
finish_nightly_result(app(), platform, 0, Outcome::Verified(Box::new(nightly_lookup::tests::verified(run))), shared, paths);
|
||||
{
|
||||
let mut state = shared.nightly_state.lock().unwrap();
|
||||
state.begin(std::slice::from_ref(&key), &Default::default(), now, true, true);
|
||||
state.attempt(&key, now);
|
||||
}
|
||||
finish_nightly_result(app(), platform, 0, Outcome::Verified(Box::new(nightly_lookup::tests::verified(run))), Origin::GitHub, shared, paths);
|
||||
shared.nightly_state.lock().unwrap().finish();
|
||||
}
|
||||
#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))] // A Nightly install plan is staged only there.
|
||||
@@ -35,6 +39,7 @@ fn selection_ui_and_install_gate_agree_and_failed_refresh_retains_stale_success(
|
||||
platform,
|
||||
0,
|
||||
Outcome::Indeterminate(crate::http::NightlyHttpError { over_budget: false, why: "offline".into(), retry_at: Some(crate::now() + 120) }),
|
||||
Origin::GitHub,
|
||||
&shared,
|
||||
&paths,
|
||||
);
|
||||
@@ -53,10 +58,10 @@ fn later_off_and_off_then_on_drop_older_generation_without_promoting_or_advancin
|
||||
let before = shared.nightly_state.lock().unwrap().record(&key).verified_at;
|
||||
shared.options.lock().unwrap().nightly_enabled = false;
|
||||
shared.nightly_state.lock().unwrap().invalidate();
|
||||
finish_nightly_result(app(), platform, 0, Outcome::Verified(Box::new(nightly_lookup::tests::verified(30))), &shared, &paths);
|
||||
finish_nightly_result(app(), platform, 0, Outcome::Verified(Box::new(nightly_lookup::tests::verified(30))), Origin::GitHub, &shared, &paths);
|
||||
shared.options.lock().unwrap().nightly_enabled = true;
|
||||
shared.nightly_state.lock().unwrap().invalidate();
|
||||
finish_nightly_result(app(), platform, 0, Outcome::Verified(Box::new(nightly_lookup::tests::verified(30))), &shared, &paths);
|
||||
finish_nightly_result(app(), platform, 0, Outcome::Verified(Box::new(nightly_lookup::tests::verified(30))), Origin::GitHub, &shared, &paths);
|
||||
assert_eq!(shared.latest.lock().unwrap().get("photocraft"), Some(&previous));
|
||||
assert_eq!(shared.nightly_state.lock().unwrap().record(&key).verified_at, before);
|
||||
assert!(nightly_install_plan(app(), &shared, &paths, Some(platform)).is_err());
|
||||
@@ -67,7 +72,7 @@ fn an_older_complete_response_does_not_implicitly_regress_the_verified_selection
|
||||
complete(&shared, &paths, platform, 20);
|
||||
let key = nightly_lookup::key(app(), platform);
|
||||
let before = shared.nightly_state.lock().unwrap().record(&key).verified_at;
|
||||
finish_nightly_result(app(), platform, 0, Outcome::Verified(Box::new(nightly_lookup::tests::verified(10))), &shared, &paths);
|
||||
finish_nightly_result(app(), platform, 0, Outcome::Verified(Box::new(nightly_lookup::tests::verified(10))), Origin::GitHub, &shared, &paths);
|
||||
assert!(shared.latest.lock().unwrap().get("photocraft").unwrap().tag.contains(".20.1."));
|
||||
let record = shared.nightly_state.lock().unwrap().record(&key);
|
||||
assert_eq!(record.verified_at, before);
|
||||
@@ -104,16 +109,15 @@ fn actual_backend_fresh_off_schedules_nothing_and_later_off_cancels_queued_sweep
|
||||
task();
|
||||
assert!(queued.lock().unwrap().is_empty());
|
||||
assert!(shared.nightly_verified.lock().unwrap().is_empty());
|
||||
// An automatic sweep looks at its three-app discovery allowance now, not at the whole roster,
|
||||
// so check the apps it chose rather than assuming a particular one is among them.
|
||||
// The signed catalog sweep schedules the whole due roster, but withdrawing consent
|
||||
// before the worker starts still prevents every lookup and verified promotion.
|
||||
let state = shared.nightly_state.lock().unwrap();
|
||||
let attempted: Vec<_> = artcraft_launcher_core::hosted_catalog::apps()
|
||||
.iter()
|
||||
.filter(|app| app.has_separate_nightly_channel() && app.runs_on(platform.os))
|
||||
.filter(|app| state.record(&nightly_lookup::key(app, platform)).attempted_at.is_some())
|
||||
.collect();
|
||||
assert_eq!(attempted.len(), 3, "the sweep marks the apps it chose as attempted");
|
||||
assert!(attempted.iter().all(|app| state.record(&nightly_lookup::key(app, platform)).verified_at.is_none()));
|
||||
assert!(attempted.is_empty(), "unstarted apps do not consume their next check turn");
|
||||
assert!(!shared.checking.load(Ordering::SeqCst));
|
||||
}
|
||||
|
||||
@@ -167,6 +171,7 @@ fn failed_result_save_retains_maximum_known_retry_and_flushes_it_before_admissio
|
||||
platform,
|
||||
0,
|
||||
Outcome::Indeterminate(crate::http::NightlyHttpError { over_budget: false, why: "limited".into(), retry_at: Some(deadline) }),
|
||||
Origin::GitHub,
|
||||
&shared,
|
||||
&paths,
|
||||
);
|
||||
@@ -229,6 +234,7 @@ fn unreadable_existing_metadata_blocks_restart_without_replacement_until_valid_r
|
||||
platform,
|
||||
0,
|
||||
Outcome::Indeterminate(crate::http::NightlyHttpError { over_budget: false, why: "limited".into(), retry_at: Some(deadline) }),
|
||||
Origin::GitHub,
|
||||
&original,
|
||||
&paths,
|
||||
);
|
||||
@@ -271,3 +277,132 @@ fn unreadable_existing_metadata_blocks_restart_without_replacement_until_valid_r
|
||||
backend.check_nightly_at(true, deadline);
|
||||
assert_eq!(spawned.load(Ordering::SeqCst), 1, "admission resumes only after valid recovery and the absolute deadline");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn catalog_verified_nightly_publishes_the_same_install_gate_with_feed_origin() {
|
||||
let (_temp, shared, paths, platform) = fixture();
|
||||
finish_nightly_result(app(), platform, 0, Outcome::Verified(Box::new(nightly_lookup::tests::verified(20))), Origin::ArtCraftApi, &shared, &paths);
|
||||
let events = shared.events.lock().unwrap();
|
||||
assert!(
|
||||
events
|
||||
.iter()
|
||||
.any(|event| matches!(event, Event::Latest {app, latest: LatestRelease::Found(_), from: Origin::ArtCraftApi} if app == "photocraft"))
|
||||
);
|
||||
assert!(events.iter().any(|event| matches!(event, Event::Installable { app, installable: true } if app == "photocraft")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nightly_catalog_fetches_one_signed_snapshot_and_reverifies_held_cache() {
|
||||
use artcraft_launcher_core::hosted_catalog::{BUILD_CATALOG_SIG, BUILD_CATALOG_TOML, CATALOG_URL, SIGNATURE_URL};
|
||||
let (_temp, _shared, paths, _) = fixture();
|
||||
let http = Http::new().unwrap();
|
||||
let throttle = Mutex::new(FeedThrottle::new());
|
||||
let hits = std::cell::Cell::new(0);
|
||||
let get = |url: &str, _| {
|
||||
hits.set(hits.get() + 1);
|
||||
match url {
|
||||
CATALOG_URL => Ok(Some(BUILD_CATALOG_TOML.to_vec())),
|
||||
SIGNATURE_URL => Ok(Some(BUILD_CATALOG_SIG.to_vec())),
|
||||
_ => panic!("unexpected URL"),
|
||||
}
|
||||
};
|
||||
let feed = nightly_catalog_with_fetch(&http, &paths, &throttle, &|| true, get).unwrap();
|
||||
assert!(feed.channel_aware);
|
||||
assert_eq!(hits.get(), 2, "document and detached signature exactly once");
|
||||
assert_eq!(nightly_catalog_with_fetch(&http, &paths, &throttle, &|| true, get), Some(feed));
|
||||
assert_eq!(hits.get(), 2, "held request reuses the pinned-key-verified cache");
|
||||
crate::paths::write_atomic(&paths.feed_cache(), b"not a signed catalog").unwrap();
|
||||
assert!(nightly_catalog_with_fetch(&http, &paths, &throttle, &|| true, get).is_none());
|
||||
assert_eq!(hits.get(), 2);
|
||||
assert!(nightly_catalog_with_fetch(&http, &paths, &throttle, &|| false, get).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nightly_catalog_fetch_stops_before_signature_if_consent_is_withdrawn() {
|
||||
use artcraft_launcher_core::hosted_catalog::{BUILD_CATALOG_TOML, CATALOG_URL};
|
||||
let (_temp, _shared, paths, _) = fixture();
|
||||
let http = Http::new().unwrap();
|
||||
let throttle = Mutex::new(FeedThrottle::new());
|
||||
let enabled = std::cell::Cell::new(true);
|
||||
assert!(
|
||||
nightly_catalog_with_fetch(&http, &paths, &throttle, &|| enabled.get(), |url, _| {
|
||||
assert_eq!(url, CATALOG_URL);
|
||||
enabled.set(false);
|
||||
Ok(Some(BUILD_CATALOG_TOML.to_vec()))
|
||||
})
|
||||
.is_none()
|
||||
);
|
||||
assert!(!paths.feed_cache().exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn real_sweep_keeps_installed_priority_and_uses_catalog_after_github_budget_refusal() {
|
||||
let (_temp, shared, paths, platform) = fixture();
|
||||
let now = crate::now();
|
||||
let (mut feed, _, body) = nightly_lookup::tests::catalog_fixture("v1.0.0-nightly.20261120.20.1.gabcdefabcdef", true);
|
||||
feed.last_fetched = Some(now);
|
||||
let entry = feed.apps.get_mut(app().id).unwrap();
|
||||
entry.fetched_at = Some(now);
|
||||
entry.nightly.as_mut().unwrap().reconciled_at = Some(now);
|
||||
let release = nightly_lookup::catalog_candidate(&feed, app(), now, None).unwrap();
|
||||
let verified = crate::nightly::verified_descriptor(app(), release, &body, platform).unwrap().unwrap();
|
||||
shared.nightly_verified.lock().unwrap().insert(app().id.into(), verified);
|
||||
*shared.nightly_catalog_fixture.lock().unwrap() = Some(feed);
|
||||
let cad = CraftApp::by_id("cadcraft").unwrap();
|
||||
shared.manifest.lock().unwrap().apps.insert(
|
||||
cad.id.into(),
|
||||
crate::manifest::Record {
|
||||
version: "1.0.0".into(),
|
||||
kind: PackageKind::TarGz,
|
||||
path: paths.apps().join("cadcraft/cadcraft"),
|
||||
installed_at: now,
|
||||
files: vec![],
|
||||
needs_root: false,
|
||||
},
|
||||
);
|
||||
let budget = crate::github_budget::GitHubBudget::in_memory(crate::github_budget::DEVELOPER_BUILDS);
|
||||
while budget.take(Priority::User, now).is_ok() {}
|
||||
let http = Http::new().unwrap().without_token().with_budget(budget);
|
||||
let backend = NativeBackend {
|
||||
shared: shared.clone(),
|
||||
paths: paths.clone(),
|
||||
http: Some(http),
|
||||
source: None,
|
||||
platform: Some(platform),
|
||||
pins: None,
|
||||
spawn: Arc::new(|task| task()),
|
||||
};
|
||||
backend.check(false);
|
||||
let state = shared.nightly_state.lock().unwrap();
|
||||
assert_eq!(state.record(&nightly_lookup::key(cad, platform)).attempted_at, None, "installed fallback refused before a request stays due");
|
||||
assert!(state.record(&nightly_lookup::key(app(), platform)).complete, "cached verified candidate still completes after quota refusal");
|
||||
assert!(state.record(&nightly_lookup::key(app(), platform)).attempted_at.is_some());
|
||||
let events = shared.events.lock().unwrap();
|
||||
assert!(events.iter().any(|e| matches!(e,Event::Latest {app,from:Origin::ArtCraftApi,latest:LatestRelease::Found(_)} if app=="photocraft")));
|
||||
assert!(events.iter().any(|e| matches!(e, Event::CheckFinished { source: Source::Feed, .. })));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unavailable_https_keeps_unstarted_apps_due() {
|
||||
let (_temp, shared, paths, platform) = fixture();
|
||||
let backend = NativeBackend {
|
||||
shared: shared.clone(),
|
||||
paths,
|
||||
http: None,
|
||||
source: None,
|
||||
platform: Some(platform),
|
||||
pins: None,
|
||||
spawn: Arc::new(|task| task()),
|
||||
};
|
||||
backend.check(false);
|
||||
let state = shared.nightly_state.lock().unwrap();
|
||||
assert!(backend.nightly_apps().iter().all(|app| state.record(&nightly_lookup::key(app, platform)).attempted_at.is_none()));
|
||||
assert!(
|
||||
shared
|
||||
.events
|
||||
.lock()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.any(|event| matches!(event,Event::Notice {result:Err(why),..} if why.contains("Secure Nightly connections")))
|
||||
);
|
||||
}
|
||||
@@ -5,7 +5,7 @@ use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::io::Read;
|
||||
use std::time::Duration;
|
||||
|
||||
use artcraft_launcher_core::protocol::NightlyStatus;
|
||||
use artcraft_launcher_core::protocol::{NightlyStatus, Origin};
|
||||
use artcraft_launcher_core::{CraftApp, Platform, Release, version};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
@@ -18,17 +18,30 @@ pub(crate) const EVERY: i64 = 6 * 60 * 60;
|
||||
const INSTALLED_EVERY: i64 = 60 * 60;
|
||||
/// At most this many apps nobody has installed are looked up in one automatic sweep, so the whole
|
||||
/// roster stays inside its six-hour cadence without spending an hour's GitHub budget at once.
|
||||
const DISCOVERY_PER_SWEEP: usize = 3;
|
||||
pub(crate) const DISCOVERY_PER_SWEEP: usize = 3;
|
||||
const MANUAL_COALESCE: i64 = 60;
|
||||
const PER_PAGE: usize = 100;
|
||||
const MAX_PAGES: usize = 5;
|
||||
const MAX_REQUESTS: usize = 32;
|
||||
const MAX_PAGE_BYTES: usize = 8 * 1024 * 1024;
|
||||
const MAX_BYTES: usize = 32 * 1024 * 1024;
|
||||
const MAX_TIME: Duration = Duration::from_secs(30);
|
||||
pub(crate) const MAX_TIME: Duration = Duration::from_secs(30);
|
||||
const MAX_RECORDS: usize = 64;
|
||||
const MAX_METADATA: u64 = 64 * 1024;
|
||||
|
||||
/// Only per-app GitHub enumeration spends the automatic discovery allowance. Installed apps
|
||||
/// and manual checks keep their existing priority; catalog answers need no allowance.
|
||||
pub(crate) fn reserve_fallback(manual: bool, installed: bool, used: &mut usize) -> bool {
|
||||
if manual || installed {
|
||||
return true;
|
||||
}
|
||||
if *used >= DISCOVERY_PER_SWEEP {
|
||||
return false;
|
||||
}
|
||||
*used += 1;
|
||||
true
|
||||
}
|
||||
|
||||
type Fetch<'a> = dyn FnMut(&str, usize, Duration, i64) -> Result<Option<Vec<u8>>, NightlyHttpError> + 'a;
|
||||
|
||||
#[derive(Debug)]
|
||||
@@ -106,8 +119,14 @@ impl Budget<'_> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn verify(&mut self, app: &CraftApp, mut release: Release, platform: Platform) -> Result<Option<VerifiedRelease>, NightlyHttpError> {
|
||||
if let Some(sums) = release.sums_asset() {
|
||||
fn verify(
|
||||
&mut self,
|
||||
app: &CraftApp,
|
||||
mut release: Release,
|
||||
platform: Platform,
|
||||
fetch_sums: bool,
|
||||
) -> Result<Option<VerifiedRelease>, NightlyHttpError> {
|
||||
if fetch_sums && let Some(sums) = release.sums_asset() {
|
||||
if !artcraft_launcher_core::release::valid_file_name(&sums.name)
|
||||
|| sums.url != format!("https://github.com/{}/releases/download/{}/{}", app.repo, release.tag, sums.name)
|
||||
{
|
||||
@@ -137,6 +156,7 @@ impl Budget<'_> {
|
||||
/// Complete bounded release-page coverage, then verify candidates in canonical preference
|
||||
/// order. Invalid potentially winning evidence is indeterminate; a compatible winner proves
|
||||
/// dominated descriptor bodies unnecessary. A full last page never proves complete coverage.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn lookup<'a>(
|
||||
app: &CraftApp,
|
||||
platform: Platform,
|
||||
@@ -146,13 +166,133 @@ pub(crate) fn lookup<'a>(
|
||||
enabled: &'a dyn Fn() -> bool,
|
||||
) -> Outcome {
|
||||
let mut budget = Budget { fetch, elapsed, enabled, now, requests: 0, bytes: 0 };
|
||||
match scan(app, platform, &mut budget) {
|
||||
outcome(scan(app, platform, &mut budget))
|
||||
}
|
||||
|
||||
fn outcome(result: Result<Option<VerifiedRelease>, NightlyHttpError>) -> Outcome {
|
||||
match result {
|
||||
Ok(Some(verified)) => Outcome::Verified(Box::new(verified)),
|
||||
Ok(None) => Outcome::NoCompatibleBuild,
|
||||
Err(error) => Outcome::Indeterminate(error),
|
||||
}
|
||||
}
|
||||
|
||||
/// The catalog is one signed publication snapshot, not a proof that every older target is absent.
|
||||
/// Only a fresh compatible entry can avoid the GitHub enumeration. Missing/incomplete entries,
|
||||
/// older selections and unsupported targets fall back to complete bounded GitHub discovery.
|
||||
pub(crate) fn catalog_candidate(feed: &artcraft_launcher_core::feed::Feed, app: &CraftApp, now: i64, previous_tag: Option<&str>) -> Option<Release> {
|
||||
use artcraft_launcher_core::feed::FeedAnswer;
|
||||
// Re-signing an unchanged website must not refresh the release reconciliation timestamp.
|
||||
let generated = feed.last_fetched?;
|
||||
let reconciled = feed.apps.get(app.id)?.nightly.as_ref()?.reconciled_at?;
|
||||
if !feed.channel_aware || reconciled > generated || !(0..=2 * 60 * 60).contains(&now.saturating_sub(reconciled)) {
|
||||
return None;
|
||||
}
|
||||
let FeedAnswer::Fresh(Some(release)) = feed.answer_nightly(app, now) else { return None };
|
||||
let version = artcraft_launcher_core::release::canonical_nightly_version(&release)?;
|
||||
if previous_tag.and_then(artcraft_launcher_core::version::parse).is_some_and(|old| artcraft_launcher_core::version::is_newer(&old, &version))
|
||||
|| release.published_at.is_none_or(|at| at <= 0 || at > reconciled)
|
||||
|| !release.assets.iter().any(|a| a.name == artcraft_launcher_core::nightly::MANIFEST_NAME && a.size > 0 && a.sha256.is_some())
|
||||
{
|
||||
return None;
|
||||
}
|
||||
Some(release)
|
||||
}
|
||||
|
||||
/// Verify the catalog's exact immutable candidate with the same descriptor, adapter and size/hash
|
||||
/// checks as the GitHub path. Its signed checksums came from the published SHA256SUMS, so we need
|
||||
/// only the descriptor body, not another checksum-list or release API call. A previously verified
|
||||
/// identical snapshot needs no descriptor download either. Never synthesize a token from metadata.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn verify_catalog<'a>(
|
||||
app: &CraftApp,
|
||||
platform: Platform,
|
||||
now: i64,
|
||||
candidate: (Release, Option<&VerifiedRelease>),
|
||||
fetch: &'a mut Fetch<'a>,
|
||||
elapsed: &'a dyn Fn() -> Duration,
|
||||
enabled: &'a dyn Fn() -> bool,
|
||||
) -> Result<Option<VerifiedRelease>, NightlyHttpError> {
|
||||
let mut budget = Budget { fetch, elapsed, enabled, now, requests: 0, bytes: 0 };
|
||||
verify_catalog_candidate(app, platform, candidate, &mut budget)
|
||||
}
|
||||
|
||||
fn verify_catalog_candidate(
|
||||
app: &CraftApp,
|
||||
platform: Platform,
|
||||
candidate: (Release, Option<&VerifiedRelease>),
|
||||
budget: &mut Budget<'_>,
|
||||
) -> Result<Option<VerifiedRelease>, NightlyHttpError> {
|
||||
crate::nightly_profile::admit_new(app, platform).map_err(failure)?;
|
||||
let (release, previous) = candidate;
|
||||
budget.coverage_complete()?;
|
||||
if let Some(previous) = previous
|
||||
&& previous.release() == &release
|
||||
&& crate::nightly_profile::for_app(app, platform).ok() == Some(previous.adapter())
|
||||
{
|
||||
return Ok(Some(previous.clone()));
|
||||
}
|
||||
let selected = budget.verify(app, release, platform, false)?;
|
||||
budget.coverage_complete()?;
|
||||
Ok(selected)
|
||||
}
|
||||
|
||||
/// Inputs to one app's lookup; the fallback allowance is shared by the entire sweep.
|
||||
pub(crate) struct LookupPolicy<'a> {
|
||||
pub candidate: Option<Release>,
|
||||
pub previous: Option<&'a VerifiedRelease>,
|
||||
pub backoff: Option<i64>,
|
||||
pub github_blocked: bool,
|
||||
pub before_lookup: &'a mut dyn FnMut() -> Result<(), NightlyHttpError>,
|
||||
pub manual: bool,
|
||||
pub installed: bool,
|
||||
pub fallback_used: &'a mut usize,
|
||||
}
|
||||
|
||||
/// A compatible catalog result avoids release enumeration. Fallback uses the same cumulative
|
||||
/// request/byte/deadline budget, and `None` means the app retains its place in the next sweep.
|
||||
pub(crate) fn lookup_prefer_catalog<'a>(
|
||||
app: &CraftApp,
|
||||
platform: Platform,
|
||||
now: i64,
|
||||
policy: LookupPolicy<'_>,
|
||||
fetch: &'a mut Fetch<'a>,
|
||||
elapsed: &'a dyn Fn() -> Duration,
|
||||
enabled: &'a dyn Fn() -> bool,
|
||||
) -> Option<(Outcome, Origin)> {
|
||||
if policy.backoff.is_some() {
|
||||
return None;
|
||||
}
|
||||
let mut budget = Budget { fetch, elapsed, enabled, now, requests: 0, bytes: 0 };
|
||||
let mut started = false;
|
||||
let mut catalog_failure = None;
|
||||
if let Some(release) = policy.candidate {
|
||||
if let Err(error) = (policy.before_lookup)() {
|
||||
return Some((Outcome::Indeterminate(error), Origin::ArtCraftApi));
|
||||
}
|
||||
started = true;
|
||||
match verify_catalog_candidate(app, platform, (release, policy.previous), &mut budget) {
|
||||
Ok(Some(verified)) => return Some((Outcome::Verified(Box::new(verified)), Origin::ArtCraftApi)),
|
||||
Ok(None) => {}
|
||||
Err(error) if error.over_budget || error.retry_at.is_some() => return Some((Outcome::Indeterminate(error), Origin::ArtCraftApi)),
|
||||
Err(error) => {
|
||||
log::info!("{}: catalog Nightly could not be verified; falling back: {}", app.id, error.why);
|
||||
if budget.requests > 0 {
|
||||
catalog_failure = Some(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if policy.github_blocked || !reserve_fallback(policy.manual, policy.installed, policy.fallback_used) {
|
||||
// A failed descriptor request is a real attempt, even if enumeration is withheld.
|
||||
return catalog_failure.map(|error| (Outcome::Indeterminate(error), Origin::ArtCraftApi));
|
||||
}
|
||||
if !started && let Err(error) = (policy.before_lookup)() {
|
||||
return Some((Outcome::Indeterminate(error), Origin::GitHub));
|
||||
}
|
||||
Some((outcome(scan(app, platform, &mut budget)), Origin::GitHub))
|
||||
}
|
||||
|
||||
fn scan(app: &CraftApp, platform: Platform, budget: &mut Budget<'_>) -> Result<Option<VerifiedRelease>, NightlyHttpError> {
|
||||
crate::nightly_profile::admit_new(app, platform).map_err(failure)?;
|
||||
let mut candidates = Vec::new();
|
||||
@@ -205,7 +345,7 @@ fn scan(app: &CraftApp, platform: Platform, budget: &mut Budget<'_>) -> Result<O
|
||||
for release in
|
||||
artcraft_launcher_core::release::ranked_nightly_candidates(&candidates, artcraft_launcher_core::release::NightlySelection::Canonical)
|
||||
{
|
||||
if let Some(verified) = budget.verify(app, release.clone(), platform)? {
|
||||
if let Some(verified) = budget.verify(app, release.clone(), platform, true)? {
|
||||
budget.coverage_complete()?;
|
||||
return Ok(Some(verified));
|
||||
}
|
||||
@@ -385,21 +525,7 @@ impl State {
|
||||
let attempted_at = self.records.get(*key).and_then(|record| record.attempted_at);
|
||||
(!installed.contains(*key), attempted_at, (*key).clone())
|
||||
});
|
||||
let mut chosen = Vec::new();
|
||||
let mut discovered = 0;
|
||||
for key in due {
|
||||
if !manual && !installed.contains(key) {
|
||||
// The roster is sorted installed-first, so the cap ends the sweep here.
|
||||
if discovered >= DISCOVERY_PER_SWEEP {
|
||||
break;
|
||||
}
|
||||
discovered += 1;
|
||||
}
|
||||
chosen.push(key.clone());
|
||||
if chosen.len() >= MAX_RECORDS {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let chosen: Vec<_> = due.into_iter().take(MAX_RECORDS).cloned().collect();
|
||||
if chosen.is_empty() {
|
||||
return chosen;
|
||||
}
|
||||
@@ -408,13 +534,23 @@ impl State {
|
||||
let previous = self.records.get(key).cloned().unwrap_or_default();
|
||||
self.deferred_from.insert(key.clone(), (previous.attempted_at, previous.complete));
|
||||
let record = self.records.entry(key.clone()).or_default();
|
||||
record.attempted_at = Some(now);
|
||||
// Queueing is not an attempt. A crash or opt-out before the worker reaches this app
|
||||
// must not consume its six-hour turn.
|
||||
record.complete = false;
|
||||
}
|
||||
self.in_flight = true;
|
||||
chosen
|
||||
}
|
||||
|
||||
/// Mark a lookup only when it actually starts, never when merely queued.
|
||||
pub(crate) fn attempt(&mut self, key: &str, now: i64) {
|
||||
if self.deferred_from.contains_key(key) {
|
||||
let record = self.records.entry(key.to_owned()).or_default();
|
||||
record.attempted_at = Some(now);
|
||||
record.complete = false;
|
||||
}
|
||||
}
|
||||
|
||||
/// Puts a key this sweep chose back where it was: a budget refusal never happened, so it must not
|
||||
/// cost the app its turn or leave a failure behind. Keys `begin` did not choose are left alone.
|
||||
pub(crate) fn defer(&mut self, key: &str) {
|
||||
|
||||
@@ -44,7 +44,12 @@ fn every_app_is_verified_within_six_hours_under_the_developers_budget() {
|
||||
for _ in 0..6 {
|
||||
let chosen = state.begin(&keys, &installed, now, false, true);
|
||||
let mut refused = false;
|
||||
let mut used = 0;
|
||||
for key in &chosen {
|
||||
if !reserve_fallback(false, false, &mut used) {
|
||||
state.defer(key);
|
||||
continue;
|
||||
}
|
||||
if refused || budget.take(Priority::Discovery, now).is_err() {
|
||||
refused = true;
|
||||
refusals += 1;
|
||||
@@ -52,6 +57,7 @@ fn every_app_is_verified_within_six_hours_under_the_developers_budget() {
|
||||
assert_eq!(state.records.get(key).and_then(|record| record.attempted_at), None, "a refusal leaves the key where it was");
|
||||
continue;
|
||||
}
|
||||
state.attempt(key, now);
|
||||
state.outcome(key, now, &Outcome::NoCompatibleBuild);
|
||||
}
|
||||
state.finish();
|
||||
@@ -91,10 +97,15 @@ fn a_sweep_takes_installed_first_then_never_attempted_then_the_longest_waiting()
|
||||
}
|
||||
assert_eq!(state.begin(&keys, &installed, NOW, false, true), vec!["installed", "never", "stale", "fresh"]);
|
||||
state.finish();
|
||||
// An automatic sweep stops at its three-app discovery allowance.
|
||||
// Catalog discovery can inspect every due app; only fallback uses the old three-app allowance.
|
||||
let mut state = State::default();
|
||||
let keys: Vec<String> = ["a", "b", "c", "d", "e"].iter().map(|key| key.to_string()).collect();
|
||||
assert_eq!(state.begin(&keys, &BTreeSet::new(), NOW, false, true), vec!["a", "b", "c"]);
|
||||
assert_eq!(state.begin(&keys, &BTreeSet::new(), NOW, false, true), vec!["a", "b", "c", "d", "e"]);
|
||||
let mut used = 0;
|
||||
assert!((0..3).all(|_| reserve_fallback(false, false, &mut used)));
|
||||
assert!(!reserve_fallback(false, false, &mut used));
|
||||
assert!(reserve_fallback(false, true, &mut used));
|
||||
assert!(reserve_fallback(true, false, &mut used));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -102,9 +113,11 @@ fn a_deferred_key_keeps_its_place_and_finish_forgets_its_old_values() {
|
||||
let installed = BTreeSet::new();
|
||||
let keys: Vec<String> = ["a", "b", "c", "d"].iter().map(|key| key.to_string()).collect();
|
||||
let mut state = State::default();
|
||||
assert_eq!(state.begin(&keys, &installed, NOW, false, true), vec!["a", "b", "c"]);
|
||||
assert_eq!(state.begin(&keys, &installed, NOW, false, true), vec!["a", "b", "c", "d"]);
|
||||
state.attempt("a", NOW);
|
||||
state.defer("b");
|
||||
state.defer("c");
|
||||
state.defer("d");
|
||||
assert_eq!(state.records.get("b").and_then(|record| record.attempted_at), None, "the refusal never happened");
|
||||
assert!(state.deferred_from.contains_key("b"), "the sweep remembers what it stamped");
|
||||
state.finish();
|
||||
@@ -181,7 +194,7 @@ fn invalidate_forgets_a_sweeps_deferred_snapshot() {
|
||||
state.defer("a");
|
||||
let record = state.records.get("a").unwrap();
|
||||
assert!(!record.complete, "a deferral cannot revive a record across a generation change");
|
||||
assert_eq!(record.attempted_at, Some(NOW), "and it does not restore the older attempt either");
|
||||
assert_eq!(record.attempted_at, None, "the unstarted app remains due");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -435,11 +448,13 @@ fn metadata_keeps_attempt_and_verified_success_distinct_without_body_or_token_ca
|
||||
let key = key(app(), platform());
|
||||
let mut state = State::default();
|
||||
assert_eq!(state.begin(std::slice::from_ref(&key), &Default::default(), NOW, false, true).as_slice(), std::slice::from_ref(&key));
|
||||
state.attempt(&key, NOW);
|
||||
state.persist_outcome(&paths, &key, NOW, &Outcome::Verified(Box::new(verified(20)))).unwrap();
|
||||
state.finish();
|
||||
assert!(state.fresh(&key, NOW));
|
||||
let later = NOW + EVERY;
|
||||
assert!(!state.begin(std::slice::from_ref(&key), &Default::default(), later, false, true).is_empty());
|
||||
state.attempt(&key, later);
|
||||
let error = Outcome::Indeterminate(NightlyHttpError { over_budget: false, why: "offline".into(), retry_at: Some(later + 120) });
|
||||
let record = state.persist_outcome(&paths, &key, later, &error).unwrap();
|
||||
state.finish();
|
||||
@@ -463,17 +478,21 @@ fn six_hour_boundaries_manual_coalescing_and_clock_rollback_are_explicit() {
|
||||
let mut state = State::default();
|
||||
assert!(state.begin(std::slice::from_ref(&key), &Default::default(), NOW, false, false).is_empty());
|
||||
assert!(!state.begin(std::slice::from_ref(&key), &Default::default(), NOW, false, true).is_empty());
|
||||
state.attempt(&key, NOW);
|
||||
state.finish();
|
||||
assert!(state.begin(std::slice::from_ref(&key), &Default::default(), NOW + EVERY - 1, false, true).is_empty());
|
||||
assert!(state.begin(std::slice::from_ref(&key), &Default::default(), NOW + 59, true, true).is_empty());
|
||||
assert!(!state.begin(std::slice::from_ref(&key), &Default::default(), NOW + 60, true, true).is_empty());
|
||||
state.attempt(&key, NOW + 60);
|
||||
state.finish();
|
||||
assert!(!state.begin(std::slice::from_ref(&key), &Default::default(), NOW + 60 + EVERY, false, true).is_empty());
|
||||
state.attempt(&key, NOW + 60 + EVERY);
|
||||
state.finish();
|
||||
assert!(
|
||||
!state.begin(std::slice::from_ref(&key), &Default::default(), NOW - 60, false, true).is_empty(),
|
||||
"future attempts are stale after rollback"
|
||||
);
|
||||
state.attempt(&key, NOW - 60);
|
||||
state.finish();
|
||||
state.outcome(&key, NOW, &Outcome::Indeterminate(NightlyHttpError { over_budget: false, why: "limited".into(), retry_at: Some(NOW + 120) }));
|
||||
assert!(
|
||||
@@ -785,3 +804,454 @@ fn shared_selection_unconfigured_platform_lookup_refuses_before_any_network_body
|
||||
assert!(matches!(result, Outcome::Indeterminate(_)));
|
||||
assert_eq!(requests, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn signed_catalog_selects_all_due_apps_without_the_fallback_cap() {
|
||||
let keys: Vec<_> = (0..15).map(|index| format!("app-{index:02}")).collect();
|
||||
let mut state = State::default();
|
||||
assert_eq!(state.begin(&keys, &BTreeSet::new(), NOW, false, true), keys);
|
||||
}
|
||||
|
||||
pub(crate) fn catalog_fixture(tag: &str, linux: bool) -> (artcraft_launcher_core::feed::Feed, String, Vec<u8>) {
|
||||
use artcraft_launcher_core::feed::{Feed, FeedApp, FeedRelease};
|
||||
let (item, url, body) = candidate(tag, linux);
|
||||
let release = artcraft_launcher_core::release::parse_github_release(&item.to_string(), app().repo).unwrap();
|
||||
let feed = Feed {
|
||||
channel_aware: true,
|
||||
last_fetched: Some(NOW),
|
||||
apps: [(
|
||||
app().id.into(),
|
||||
FeedApp {
|
||||
repo: Some(app().repo.into()),
|
||||
fetched_at: Some(NOW),
|
||||
nightly: Some(FeedRelease {
|
||||
tag: release.tag,
|
||||
published_at: release.published_at,
|
||||
reconciled_at: Some(NOW),
|
||||
prerelease: true,
|
||||
assets: release.assets.into_iter().map(|a| (a.name, a.size, a.url, a.sha256)).collect(),
|
||||
..Default::default()
|
||||
}),
|
||||
..Default::default()
|
||||
},
|
||||
)]
|
||||
.into(),
|
||||
..Default::default()
|
||||
};
|
||||
(feed, url, body)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn complete_catalog_candidate_uses_only_descriptor_then_reuses_same_verified_identity() {
|
||||
let (feed, descriptor_url, body) = catalog_fixture(&tag(20), true);
|
||||
// The fixture represents an already verified signed document. Signature verification is
|
||||
// separately tested at the ingestion boundary; this tests the native selection boundary.
|
||||
let release = catalog_candidate(&feed, app(), NOW + 1, None).unwrap();
|
||||
let mut calls = Vec::new();
|
||||
let verified = verify_catalog(
|
||||
app(),
|
||||
platform(),
|
||||
NOW + 1,
|
||||
(release.clone(), None),
|
||||
&mut |url, _, _, _| {
|
||||
calls.push(url.to_owned());
|
||||
Ok(Some(body.clone()))
|
||||
},
|
||||
&|| Duration::ZERO,
|
||||
&|| true,
|
||||
)
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(calls, [descriptor_url]);
|
||||
assert_eq!(verified.release().tag, tag(20));
|
||||
let again = verify_catalog(
|
||||
app(),
|
||||
platform(),
|
||||
NOW + 2,
|
||||
(release, Some(&verified)),
|
||||
&mut |_, _, _, _| panic!("unchanged catalog needs no GitHub request"),
|
||||
&|| Duration::ZERO,
|
||||
&|| true,
|
||||
)
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(again.release().tag, tag(20));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stale_missing_or_incomplete_catalog_and_a_newer_remembered_tag_require_github() {
|
||||
let (mut feed, _, _) = catalog_fixture(&tag(20), true);
|
||||
assert!(catalog_candidate(&feed, app(), NOW + 2 * 3600 + 1, None).is_none());
|
||||
assert!(catalog_candidate(&feed, app(), NOW + 1, Some(&tag(30))).is_none());
|
||||
feed.apps.get_mut(app().id).unwrap().nightly.as_mut().unwrap().published_at = None;
|
||||
assert!(catalog_candidate(&feed, app(), NOW + 1, None).is_none());
|
||||
feed.apps.get_mut(app().id).unwrap().nightly = None;
|
||||
assert!(catalog_candidate(&feed, app(), NOW + 1, None).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn catalog_without_the_current_platform_target_is_not_authoritative_absence() {
|
||||
let (feed, _, body) = catalog_fixture(&tag(20), false);
|
||||
let release = catalog_candidate(&feed, app(), NOW + 1, None).unwrap();
|
||||
let selected =
|
||||
verify_catalog(app(), platform(), NOW + 1, (release, None), &mut |_, _, _, _| Ok(Some(body.clone())), &|| Duration::ZERO, &|| true).unwrap();
|
||||
assert!(selected.is_none(), "caller must fall back to other GitHub candidates");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn catalog_uses_each_admitted_app_and_platform_row() {
|
||||
use artcraft_launcher_core::feed::{Feed, FeedApp, FeedRelease};
|
||||
let mut checked = 0;
|
||||
for app in artcraft_launcher_core::hosted_catalog::apps().iter().filter(|app| app.has_separate_nightly_channel()) {
|
||||
for (platform, os, arch, format, suffix) in [
|
||||
(Platform { os: Os::Linux, arch: Arch::X64 }, "linux", "x86_64", "tar_gz", "linux-x86_64-nightly.tar.gz"),
|
||||
(Platform { os: Os::MacOs, arch: Arch::Arm64 }, "macos", "aarch64", "portable_zip", "macos-aarch64-nightly.zip"),
|
||||
(Platform { os: Os::Windows, arch: Arch::X64 }, "windows", "x86_64", "portable_zip", "windows-x86_64-nightly.zip"),
|
||||
] {
|
||||
let adapter = crate::nightly_profile::admit_new(app, platform).unwrap();
|
||||
let tag = tag(20);
|
||||
let version = version::parse(&tag).unwrap();
|
||||
let prefix = format!("https://github.com/{}/releases/download/{tag}/", app.repo);
|
||||
let name = format!("{}-{version}-{suffix}", app.id);
|
||||
let url = format!("{prefix}{name}");
|
||||
let sha = "a".repeat(64);
|
||||
let mut artifact = json!({"target":{"os":os,"arch":arch,"format":format}, "asset":{"name":name,"url":url,"size":123,"sha256":sha},"isolation":{"package_identity":format!("ai.storyteller.{}.nightly",app.id),"profile_contract":"nightly","profile_version":1,"associations":"none"}});
|
||||
let mut assets = vec![(name.clone(), 123, url, Some(sha))];
|
||||
if os == "linux" {
|
||||
let signature = format!("{name}.asc");
|
||||
let url = format!("{prefix}{signature}");
|
||||
let sha = "b".repeat(64);
|
||||
artifact["signature"] = json!({"name":signature,"url":url,"size":123,"sha256":sha});
|
||||
assets.push((signature, 123, url, Some(sha)));
|
||||
}
|
||||
let descriptor = serde_json::to_vec(&json!({"schema":"craft-nightly/v2","channel":"nightly","app":app.id,"repository":app.repo,"tag":tag,"source_commit":"abcdefabcdefabcdefabcdefabcdefabcdefabcd","published_at":NOW,"artifacts":[artifact]})).unwrap();
|
||||
let descriptor_url = format!("{prefix}NIGHTLY.json");
|
||||
assets.push(("NIGHTLY.json".into(), descriptor.len() as u64, descriptor_url.clone(), Some(format!("{:x}", Sha256::digest(&descriptor)))));
|
||||
let feed = Feed {
|
||||
channel_aware: true,
|
||||
last_fetched: Some(NOW),
|
||||
apps: [(
|
||||
app.id.into(),
|
||||
FeedApp {
|
||||
repo: Some(app.repo.into()),
|
||||
fetched_at: Some(NOW),
|
||||
nightly: Some(FeedRelease {
|
||||
tag,
|
||||
published_at: Some(NOW),
|
||||
reconciled_at: Some(NOW),
|
||||
prerelease: true,
|
||||
assets,
|
||||
..Default::default()
|
||||
}),
|
||||
..Default::default()
|
||||
},
|
||||
)]
|
||||
.into(),
|
||||
..Default::default()
|
||||
};
|
||||
let release = catalog_candidate(&feed, app, NOW + 1, None).unwrap();
|
||||
let result = verify_catalog(
|
||||
app,
|
||||
platform,
|
||||
NOW + 1,
|
||||
(release, None),
|
||||
&mut |url, _, _, _| {
|
||||
assert_eq!(url, descriptor_url);
|
||||
Ok(Some(descriptor.clone()))
|
||||
},
|
||||
&|| Duration::ZERO,
|
||||
&|| true,
|
||||
)
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(result.adapter(), adapter);
|
||||
checked += 1;
|
||||
}
|
||||
}
|
||||
assert_eq!(checked, 3 * artcraft_launcher_core::hosted_catalog::apps().iter().filter(|app| app.has_separate_nightly_channel()).count());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn catalog_first_lookup_preserves_fallback_selection_and_the_request_allowance() {
|
||||
let (feed, descriptor_url, body) = catalog_fixture(&tag(20), true);
|
||||
let release = catalog_candidate(&feed, app(), NOW + 1, None).unwrap();
|
||||
let mut used = DISCOVERY_PER_SWEEP;
|
||||
let mut calls = Vec::new();
|
||||
let answer = lookup_prefer_catalog(
|
||||
app(),
|
||||
platform(),
|
||||
NOW + 1,
|
||||
LookupPolicy {
|
||||
candidate: Some(release.clone()),
|
||||
previous: None,
|
||||
backoff: None,
|
||||
github_blocked: false,
|
||||
before_lookup: &mut || Ok(()),
|
||||
manual: false,
|
||||
installed: false,
|
||||
fallback_used: &mut used,
|
||||
},
|
||||
&mut |url, _, _, _| {
|
||||
calls.push(url.to_owned());
|
||||
Ok(Some(body.clone()))
|
||||
},
|
||||
&|| Duration::ZERO,
|
||||
&|| true,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(answer.1, Origin::ArtCraftApi);
|
||||
let Outcome::Verified(verified) = answer.0 else { panic!("catalog candidate must verify") };
|
||||
assert_eq!(calls, [descriptor_url]);
|
||||
assert_eq!(used, DISCOVERY_PER_SWEEP);
|
||||
let answer = lookup_prefer_catalog(
|
||||
app(),
|
||||
platform(),
|
||||
NOW + 2,
|
||||
LookupPolicy {
|
||||
candidate: Some(release),
|
||||
previous: Some(&verified),
|
||||
backoff: None,
|
||||
github_blocked: false,
|
||||
before_lookup: &mut || Ok(()),
|
||||
manual: false,
|
||||
installed: false,
|
||||
fallback_used: &mut used,
|
||||
},
|
||||
&mut |_, _, _, _| panic!("unchanged candidate needs no request"),
|
||||
&|| Duration::ZERO,
|
||||
&|| true,
|
||||
)
|
||||
.unwrap();
|
||||
assert!(matches!(answer, (Outcome::Verified(_), Origin::ArtCraftApi)));
|
||||
assert!(
|
||||
lookup_prefer_catalog(
|
||||
app(),
|
||||
platform(),
|
||||
NOW + 2,
|
||||
LookupPolicy {
|
||||
candidate: None,
|
||||
previous: None,
|
||||
backoff: None,
|
||||
github_blocked: false,
|
||||
before_lookup: &mut || Ok(()),
|
||||
manual: false,
|
||||
installed: false,
|
||||
fallback_used: &mut used
|
||||
},
|
||||
&mut |_, _, _, _| panic!("cap must defer missing catalog entries"),
|
||||
&|| Duration::ZERO,
|
||||
&|| true
|
||||
)
|
||||
.is_none()
|
||||
);
|
||||
|
||||
let (api_row, api_descriptor, api_body) = candidate(&tag(10), true);
|
||||
let data = fixtures(vec![api_row], vec![(api_descriptor, api_body)]);
|
||||
let (unsupported_feed, unsupported_url, unsupported_body) = catalog_fixture(&tag(20), false);
|
||||
let unsupported = catalog_candidate(&unsupported_feed, app(), NOW + 1, None).unwrap();
|
||||
let mut used = 0;
|
||||
let mut asked = Vec::new();
|
||||
let answer = lookup_prefer_catalog(
|
||||
app(),
|
||||
platform(),
|
||||
NOW + 1,
|
||||
LookupPolicy {
|
||||
candidate: Some(unsupported),
|
||||
previous: None,
|
||||
backoff: None,
|
||||
github_blocked: false,
|
||||
before_lookup: &mut || Ok(()),
|
||||
manual: false,
|
||||
installed: false,
|
||||
fallback_used: &mut used,
|
||||
},
|
||||
&mut |url, _, _, _| {
|
||||
asked.push(url.to_owned());
|
||||
if url == unsupported_url { Ok(Some(unsupported_body.clone())) } else { Ok(data.get(url).cloned()) }
|
||||
},
|
||||
&|| Duration::ZERO,
|
||||
&|| true,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(answer.1, Origin::GitHub);
|
||||
assert!(matches!(answer.0,Outcome::Verified(v) if v.release().tag==tag(10)));
|
||||
assert_eq!(used, 1);
|
||||
assert_eq!(asked[0], unsupported_url);
|
||||
assert_eq!(asked[1], api(1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn catalog_first_lookup_respects_backoff_and_falls_back_if_descriptor_is_unavailable() {
|
||||
let (feed, _, _) = catalog_fixture(&tag(20), true);
|
||||
let release = catalog_candidate(&feed, app(), NOW + 1, None).unwrap();
|
||||
let mut used = 0;
|
||||
let answer = lookup_prefer_catalog(
|
||||
app(),
|
||||
platform(),
|
||||
NOW + 1,
|
||||
LookupPolicy {
|
||||
candidate: Some(release.clone()),
|
||||
previous: None,
|
||||
backoff: Some(NOW + 600),
|
||||
github_blocked: false,
|
||||
before_lookup: &mut || panic!("backoff is not an attempt"),
|
||||
manual: true,
|
||||
installed: false,
|
||||
fallback_used: &mut used,
|
||||
},
|
||||
&mut |_, _, _, _| panic!("no network during backoff"),
|
||||
&|| Duration::ZERO,
|
||||
&|| true,
|
||||
);
|
||||
assert!(answer.is_none());
|
||||
let answer = lookup_prefer_catalog(
|
||||
app(),
|
||||
platform(),
|
||||
NOW + 1,
|
||||
LookupPolicy {
|
||||
candidate: Some(release.clone()),
|
||||
previous: None,
|
||||
backoff: None,
|
||||
github_blocked: false,
|
||||
before_lookup: &mut || Ok(()),
|
||||
manual: true,
|
||||
installed: false,
|
||||
fallback_used: &mut used,
|
||||
},
|
||||
&mut |_, _, _, _| Err(NightlyHttpError { over_budget: false, why: "server backoff".into(), retry_at: Some(NOW + 600) }),
|
||||
&|| Duration::ZERO,
|
||||
&|| true,
|
||||
)
|
||||
.unwrap();
|
||||
assert!(matches!(answer,(Outcome::Indeterminate(e),Origin::ArtCraftApi) if e.retry_at==Some(NOW+600)));
|
||||
let mut calls = Vec::new();
|
||||
let answer = lookup_prefer_catalog(
|
||||
app(),
|
||||
platform(),
|
||||
NOW + 1,
|
||||
LookupPolicy {
|
||||
candidate: Some(release),
|
||||
previous: None,
|
||||
backoff: None,
|
||||
github_blocked: false,
|
||||
before_lookup: &mut || Ok(()),
|
||||
manual: true,
|
||||
installed: false,
|
||||
fallback_used: &mut used,
|
||||
},
|
||||
&mut |url, _, _, _| {
|
||||
calls.push(url.to_owned());
|
||||
if url == api(1) { Ok(Some(b"[]".to_vec())) } else { Ok(None) }
|
||||
},
|
||||
&|| Duration::ZERO,
|
||||
&|| true,
|
||||
)
|
||||
.unwrap();
|
||||
assert!(matches!(answer, (Outcome::NoCompatibleBuild, Origin::GitHub)));
|
||||
assert_eq!(calls.len(), 2);
|
||||
assert_eq!(calls[1], api(1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn catalog_descriptor_failure_counts_as_attempt_when_fallback_is_unavailable() {
|
||||
let (feed, descriptor_url, _) = catalog_fixture(&tag(20), true);
|
||||
let release = catalog_candidate(&feed, app(), NOW + 1, None).unwrap();
|
||||
for github_blocked in [false, true] {
|
||||
let mut used = if github_blocked { 0 } else { DISCOVERY_PER_SWEEP };
|
||||
let mut attempts = 0;
|
||||
let mut requests = 0;
|
||||
let answer = lookup_prefer_catalog(
|
||||
app(),
|
||||
platform(),
|
||||
NOW + 1,
|
||||
LookupPolicy {
|
||||
candidate: Some(release.clone()),
|
||||
previous: None,
|
||||
backoff: None,
|
||||
github_blocked,
|
||||
before_lookup: &mut || {
|
||||
attempts += 1;
|
||||
Ok(())
|
||||
},
|
||||
manual: false,
|
||||
installed: false,
|
||||
fallback_used: &mut used,
|
||||
},
|
||||
&mut |url, _, _, _| {
|
||||
assert_eq!(url, descriptor_url);
|
||||
requests += 1;
|
||||
Ok(None)
|
||||
},
|
||||
&|| Duration::ZERO,
|
||||
&|| true,
|
||||
);
|
||||
assert!(matches!(answer, Some((Outcome::Indeterminate(error), Origin::ArtCraftApi)) if error.why.contains("not found")));
|
||||
assert_eq!((attempts, requests), (1, 1));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generated_catalog_time_does_not_refresh_old_reconciliation() {
|
||||
let (mut feed, _, _) = catalog_fixture(&tag(20), true);
|
||||
let now = NOW + 3 * 3600;
|
||||
feed.last_fetched = Some(now);
|
||||
let entry = feed.apps.get_mut(app().id).unwrap();
|
||||
entry.fetched_at = Some(now);
|
||||
assert!(catalog_candidate(&feed, app(), now, None).is_none());
|
||||
feed.apps.get_mut(app().id).unwrap().nightly.as_mut().unwrap().reconciled_at = Some(now);
|
||||
assert!(catalog_candidate(&feed, app(), now, None).is_some());
|
||||
feed.apps.get_mut(app().id).unwrap().nightly.as_mut().unwrap().reconciled_at = None;
|
||||
assert!(catalog_candidate(&feed, app(), now, None).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn queued_apps_keep_previous_attempts_across_process_exit_and_server_backoff() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let paths = Paths::under(&temp.path().canonicalize().unwrap()).for_channel(artcraft_launcher_core::nightly::InstallChannel::Nightly);
|
||||
let keys = vec!["first".to_string(), "second".to_string(), "third".to_string()];
|
||||
let mut state = State::default();
|
||||
assert_eq!(state.begin(&keys, &Default::default(), NOW, false, true), keys);
|
||||
state.attempt("first", NOW);
|
||||
state
|
||||
.persist_outcome(
|
||||
&paths,
|
||||
"first",
|
||||
NOW,
|
||||
&Outcome::Indeterminate(NightlyHttpError { over_budget: false, why: "offline".into(), retry_at: Some(NOW + 120) }),
|
||||
)
|
||||
.unwrap();
|
||||
// Simulate a restart before the other two queued apps reached a lookup.
|
||||
let mut restarted = State::load(&paths);
|
||||
assert_eq!(restarted.record("first").attempted_at, Some(NOW));
|
||||
assert_eq!(restarted.record("second").attempted_at, None);
|
||||
assert!(restarted.begin(&keys, &Default::default(), NOW + 119, false, true).is_empty());
|
||||
assert_eq!(restarted.begin(&keys, &Default::default(), NOW + 120, false, true), vec!["second", "third"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn changed_descriptor_metadata_on_same_tag_does_not_reuse_old_token() {
|
||||
let (feed, _, body) = catalog_fixture(&tag(20), true);
|
||||
let mut release = catalog_candidate(&feed, app(), NOW + 1, None).unwrap();
|
||||
let verified =
|
||||
verify_catalog(app(), platform(), NOW + 1, (release.clone(), None), &mut |_, _, _, _| Ok(Some(body.clone())), &|| Duration::ZERO, &|| true)
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
release.assets.iter_mut().find(|a| a.name == "NIGHTLY.json").unwrap().sha256 = Some("c".repeat(64));
|
||||
let mut calls = 0;
|
||||
assert!(
|
||||
verify_catalog(
|
||||
app(),
|
||||
platform(),
|
||||
NOW + 2,
|
||||
(release, Some(&verified)),
|
||||
&mut |_, _, _, _| {
|
||||
calls += 1;
|
||||
Ok(Some(body.clone()))
|
||||
},
|
||||
&|| Duration::ZERO,
|
||||
&|| true
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
assert_eq!(calls, 1);
|
||||
}
|
||||
Reference in new issue
Block a user