diff --git a/src/podcasts/mod.rs b/src/podcasts/mod.rs index fe0bc38..aafa3f2 100644 --- a/src/podcasts/mod.rs +++ b/src/podcasts/mod.rs @@ -82,11 +82,26 @@ pub fn covers_dir() -> Result { /// without writing anything, a database from a newer Furumi or a file that /// is not a podcast database. Blocking: call it on the blocking pool. pub fn open_services(db_path: &Path, covers_dir: PathBuf, log: Arc) -> Result { - let from_prototype = is_prototype_database(db_path); + // The import commits inside `PodcastStore::open`; dropping its + // validators happens afterwards. A marker written before the import and + // removed only once every podcast was handled makes that step resumable + // after a crash or a failed write in between. + let marker = validators_marker(db_path); + let mut pending = marker.is_file(); + if is_prototype_database(db_path) { + if let Err(err) = std::fs::write(&marker, b"") { + tracing::warn!("cannot record the pending prototype feed checks: {err}"); + } + pending = true; + } let store = PodcastStore::open(db_path)?; tracing::info!(path = %db_path.display(), "podcast store opened"); - if from_prototype { - forget_prototype_validators(&store); + if pending && forget_prototype_validators(&store) { + match std::fs::remove_file(&marker) { + Ok(()) => {} + Err(err) if err.kind() == std::io::ErrorKind::NotFound => {} + Err(err) => tracing::warn!("cannot remove {}: {err}", marker.display()), + } } match store.legacy_quarantine() { Ok(entries) if !entries.is_empty() => tracing::warn!( @@ -116,7 +131,21 @@ fn is_prototype_database(path: &Path) -> bool { .is_ok_and(|version| version == LEGACY_PROTOTYPE_SCHEMA_VERSION) } -/// Drops the HTTP validators imported from a prototype database. +/// Marker next to the podcast store: the validators imported from a +/// prototype database still have to be dropped +/// ([`forget_prototype_validators`]). +fn validators_marker(db_path: &Path) -> PathBuf { + let mut name = db_path + .file_name() + .map(std::ffi::OsStr::to_os_string) + .unwrap_or_default(); + name.push(".full-check-pending"); + db_path.with_file_name(name) +} + +/// Drops the HTTP validators imported from a prototype database. Returns +/// whether every podcast was handled (otherwise it runs again at the next +/// start). /// /// The prototype stored no seasons, episode numbers or episode types, and /// its GUID-less episodes stay provisional until a feed is parsed again. With @@ -124,9 +153,17 @@ fn is_prototype_database(path: &Path) -> bool { /// "304 Not Modified" and the feed never parsed while it does not change, so /// a finished series would never show its seasons. Without them the first /// check downloads and applies the feed. The fetch state is local (never -/// synced). Contract gap: FRID's prototype import should not carry the -/// validators over. -fn forget_prototype_validators(store: &PodcastStore) { +/// synced). +/// +/// Only the public fetch-state API exists for this: the validators are +/// cleared by recording a success at the last check, keeping the next check +/// time, and an imported error is recorded again as many times as it was +/// counted, so the back-off stays as imported. The one side effect is that a +/// podcast imported with an error gets a last success time (its last check), +/// which is not shown while the error is. Running this again only costs one +/// unconditional feed download per podcast. Contract gap: FRID's prototype +/// import should not carry the validators over. +fn forget_prototype_validators(store: &PodcastStore) -> bool { let result = (|| -> Result { let mut cleared = 0; for podcast in store.list_podcasts(PodcastListFilter::All)? { @@ -141,24 +178,35 @@ fn forget_prototype_validators(store: &PodcastStore) { .unwrap_or(0); store.record_fetch_success(id, checked, None, None, state.next_check_at_ms)?; if let Some(error) = &state.last_error { - store.record_fetch_failure( - id, - state.checked_at_ms.unwrap_or(checked), - error, - state.next_check_at_ms, - )?; + for _ in 0..state.consecutive_failures.max(1) { + store.record_fetch_failure( + id, + state.checked_at_ms.unwrap_or(checked), + error, + state.next_check_at_ms, + )?; + } } cleared += 1; } Ok(cleared) })(); match result { - Ok(0) => {} - Ok(cleared) => tracing::info!( - cleared, - "imported podcasts get a full first feed check (prototype validators dropped)" - ), - Err(err) => tracing::warn!("dropping imported podcast validators failed: {err:#}"), + Ok(cleared) => { + if cleared > 0 { + tracing::info!( + cleared, + "imported podcasts get a full first feed check (prototype validators dropped)" + ); + } + true + } + Err(err) => { + tracing::warn!( + "dropping imported podcast validators failed (retried at the next start): {err:#}" + ); + false + } } } diff --git a/src/podcasts/tests.rs b/src/podcasts/tests.rs index c0f3ba6..482d19d 100644 --- a/src/podcasts/tests.rs +++ b/src/podcasts/tests.rs @@ -743,6 +743,83 @@ async fn imported_podcasts_get_their_seasons_on_the_first_check() { ); } +/// The import commits inside `PodcastStore::open` and the validators are +/// dropped afterwards. A start that stopped in between (killed, or a failed +/// write) finishes the job at the next start, and the imported back-off is +/// kept. +#[test] +fn dropping_prototype_validators_resumes_after_an_interrupted_start() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join(furumi_library::podcasts::PODCAST_DB_FILE); + { + let conn = rusqlite::Connection::open(&path).unwrap(); + conn.execute_batch(PROTOTYPE_SCHEMA).unwrap(); + conn.execute( + "INSERT INTO podcasts (feed_url, title, etag, added_at, last_checked_at) + VALUES ('https://example.test/ok.xml', 'Fine Show', '\"e1\"', 1700000000, 1700000100)", + [], + ) + .unwrap(); + conn.execute( + "INSERT INTO podcasts + (feed_url, title, last_modified, added_at, last_checked_at, last_error) + VALUES ('https://example.test/broken.xml', 'Broken Show', + 'Sat, 15 Jun 2024 10:00:00 GMT', 1700000000, 1700000200, 'HTTP 500')", + [], + ) + .unwrap(); + conn.pragma_update(None, "user_version", 1).unwrap(); + } + let ok = PodcastId::from_feed_url(&FeedUrl::parse("https://example.test/ok.xml").unwrap()); + let broken = + PodcastId::from_feed_url(&FeedUrl::parse("https://example.test/broken.xml").unwrap()); + + // The first start: the marker is written, then the import commits, and + // the process stops before the validators are dropped. + let marker = super::validators_marker(&path); + assert!(super::is_prototype_database(&path)); + std::fs::write(&marker, b"").unwrap(); + drop(PodcastStore::open(&path).unwrap()); + assert!(!super::is_prototype_database(&path), "migrated"); + + // The next start finishes the job. + let services = super::open_services( + &path, + dir.path().join("covers"), + Arc::new(MemoryLog::default()), + ) + .unwrap(); + let store = &services.store; + let fetch = store.fetch_state(&ok).unwrap(); + assert_eq!(fetch.etag, None); + assert_eq!(fetch.last_error, None); + let fetch = store.fetch_state(&broken).unwrap(); + assert_eq!(fetch.last_modified, None); + assert_eq!(fetch.last_error.as_deref(), Some("HTTP 500")); + assert_eq!( + fetch.consecutive_failures, 1, + "the imported back-off is kept" + ); + assert_eq!(fetch.checked_at_ms, Some(1_700_000_200_000)); + assert!(!marker.exists(), "done once"); + + // Validators of later checks are kept on every start after that. + store + .record_fetch_success(&ok, NOW, Some("\"e2\""), None, None) + .unwrap(); + drop(services); + let services = super::open_services( + &path, + dir.path().join("covers"), + Arc::new(MemoryLog::default()), + ) + .unwrap(); + assert_eq!( + services.store.fetch_state(&ok).unwrap().etag.as_deref(), + Some("\"e2\"") + ); +} + fn feed_url(f: &Fixture, path: &str) -> FeedUrl { FeedUrl::parse(&f.server.url(path)).unwrap() }