Refresh subscribed podcast feeds in a background job

The podcast_refresh job runs every five minutes and refreshes the podcasts
whose next check is due: conditional requests (ETag, Last-Modified), 32 MiB
and 60 s limits, the shared music-dht parser and PodcastStore::apply_feed.
A chain of permanent redirects moves the feed and becomes an alias.
Healthy feeds are checked hourly with a stable spread; failures back off
from 15 minutes up to a day, honouring Retry-After. Accounts subscribed to
the same feed URL share one request, at most four run at once, and one
run at a time holds an advisory lock. runner::refresh_now is the manual
refresh for one subscribed podcast, at most every 30 seconds.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
sanapachandClaude Opus 5.5 committed 2026-11-20 15:12:38 +02:00
1 parent 04ae7d5bd1
commit bf9a6abc3f
9 files changed
+1273 -4

No files matched your search

+253
View File
@@ -1465,3 +1465,256 @@ async fn postgres_podcast_migrations_import_the_relay_state() {
.await
.unwrap();
}
// ---------------------------------------------------------------------------
// RSS refresh job
// ---------------------------------------------------------------------------
fn refresh_item(guid: &str) -> String {
format!(
r#"<item><title>Episode {guid}</title><guid>{guid}</guid>
<enclosure url="/audio/{guid}.mp3" type="audio/mpeg" length="1000"/></item>"#
)
}
/// A fetcher that may reach the local test server (loopback is allowed
/// only by the test policy).
fn local_fetcher() -> FeedFetcher {
FeedFetcher::with_http(
net::SafeHttp::with_lookup(
fetch::FEED_HTTP,
net::AddressPolicy::test_allow_loopback(),
std::sync::Arc::new(net::SystemLookup),
)
.unwrap(),
)
}
/// Due groups of the given accounts only (other tests share the database).
async fn due_for(store: &PodcastStore, users: &[i64], now: i64) -> runner::RefreshGroups {
let due = store
.podcasts_due_for_refresh(now, 100_000)
.await
.unwrap()
.into_iter()
.filter(|(user_id, _, _)| users.contains(user_id))
.collect();
runner::group_targets(due)
}
async fn run_due(
store: &PodcastStore,
fetcher: &FeedFetcher,
users: &[i64],
now: i64,
) -> runner::RunSummary {
let groups = due_for(store, users, now).await;
runner::refresh_groups(store, fetcher, groups, now, 4)
.await
.unwrap()
}
#[tokio::test]
#[ignore = "requires a disposable database in FURU_DEVICE_SYNC_TEST_DATABASE_URL"]
async fn postgres_podcast_refresh_job_schedules_backs_off_and_moves_feeds() {
use super::runner::{BACKOFF_BASE_MS, ManualRefreshError, TargetResult};
use super::test_server::{Route, TestServer};
let pool = test_pool().await;
let store = PodcastStore::new(pool.clone());
let (a, b, c) = (random_user(), random_user(), random_user());
cleanup(&pool, [a, b, c]).await;
let users = [a, b, c];
let server = TestServer::start();
server.set(
"/show.xml",
Route::new(rss(&refresh_item("one")), "application/rss+xml").etag("\"v1\""),
);
let show = PodcastMeta {
feed_url: FeedUrl::parse(&server.url("/show.xml")).unwrap(),
title: "Local Show".into(),
author: None,
description: None,
link: None,
image_url: None,
};
let podcast_id = store.subscribe(a, &show).await.unwrap().podcast_id;
assert_eq!(
store.subscribe(b, &show).await.unwrap().podcast_id,
podcast_id
);
let fetcher = local_fetcher();
// First run: one request serves both accounts.
let t0 = super::now_ms();
let summary = run_due(&store, &fetcher, &users, t0).await;
assert_eq!((summary.targets, summary.feeds), (2, 1), "{summary}");
assert_eq!((summary.updated, summary.new_episodes), (2, 2), "{summary}");
assert_eq!(server.requests("/show.xml").len(), 1);
for user in [a, b] {
let state = store.fetch_state(user, &podcast_id).await.unwrap();
assert_eq!(state.etag.as_deref(), Some("\"v1\""));
assert_eq!(state.consecutive_failures, 0);
let next = state.next_check_at_ms.unwrap();
assert!((t0 + runner::REFRESH_INTERVAL_MS..t0 + 70 * 60 * 1000).contains(&next));
}
let episodes = store
.episodes(a, &EpisodeQuery::new(podcast_id.clone()))
.await
.unwrap();
assert_eq!(episodes.len(), 1);
let episode_id = episodes[0].episode.episode_id.clone();
assert_eq!(episodes[0].episode.audio_url, server.url("/audio/one.mp3"));
// Nothing is due before the interval; afterwards the request is
// conditional and the catalog stays as it is.
assert!(due_for(&store, &users, t0 + 1000).await.is_empty());
let t1 = t0 + 2 * runner::REFRESH_INTERVAL_MS;
let summary = run_due(&store, &fetcher, &users, t1).await;
assert_eq!(summary.not_modified, 2, "{summary}");
assert_eq!(server.requests("/show.xml")[1]["if-none-match"], "\"v1\"");
// Failures back off exponentially and keep the catalog.
server.set("/show.xml", Route::new("boom", "text/plain").status(500));
let t2 = t1 + 2 * runner::REFRESH_INTERVAL_MS;
let summary = run_due(&store, &fetcher, &users, t2).await;
assert_eq!(summary.failed, 2, "{summary}");
assert_eq!(summary.failures.len(), 2);
let state = store.fetch_state(a, &podcast_id).await.unwrap();
assert_eq!(state.consecutive_failures, 1);
assert_eq!(state.next_check_at_ms, Some(t2 + BACKOFF_BASE_MS));
assert!(state.last_error.as_deref().unwrap().contains("500"));
assert_eq!(state.etag.as_deref(), Some("\"v1\""), "validators are kept");
assert!(
due_for(&store, &users, t2 + BACKOFF_BASE_MS - 1)
.await
.is_empty()
);
let t3 = t2 + BACKOFF_BASE_MS;
let summary = run_due(&store, &fetcher, &users, t3).await;
assert_eq!(summary.failed, 2, "{summary}");
let state = store.fetch_state(a, &podcast_id).await.unwrap();
assert_eq!(state.consecutive_failures, 2);
assert_eq!(state.next_check_at_ms, Some(t3 + 2 * BACKOFF_BASE_MS));
assert_eq!(
store
.episodes(a, &EpisodeQuery::new(podcast_id.clone()))
.await
.unwrap()
.len(),
1
);
// Recovery resets the backoff. Accounts with different validators are
// fetched unconditionally.
server.set(
"/show.xml",
Route::new(
rss(&format!("{}{}", refresh_item("two"), refresh_item("one"))),
"application/rss+xml",
)
.etag("\"v2\""),
);
store
.record_fetch_success(b, &podcast_id, t3, Some("\"other\""), None, Some(t3))
.await
.unwrap();
let t4 = t3 + 2 * BACKOFF_BASE_MS;
let summary = run_due(&store, &fetcher, &users, t4).await;
assert_eq!((summary.updated, summary.new_episodes), (2, 2), "{summary}");
let last = server.requests("/show.xml").pop().unwrap();
assert!(!last.contains_key("if-none-match"), "{last:?}");
let state = store.fetch_state(a, &podcast_id).await.unwrap();
assert_eq!((state.consecutive_failures, state.last_error), (0, None));
assert_eq!(state.etag.as_deref(), Some("\"v2\""));
// Manual refresh: not more often than every 30 s, only when subscribed.
let manual = runner::refresh_now(&store, &fetcher, a, &podcast_id, t4 + 10_000).await;
assert_eq!(
manual.unwrap_err().downcast_ref::<ManualRefreshError>(),
Some(&ManualRefreshError::TooSoon {
retry_after_ms: 20_000
})
);
let manual = runner::refresh_now(&store, &fetcher, a, &podcast_id, t4 + 31_000)
.await
.unwrap();
assert_eq!(manual, TargetResult::NotModified);
let unknown = runner::refresh_now(&store, &fetcher, c, &podcast_id, t4 + 31_000).await;
assert_eq!(
unknown.unwrap_err().downcast_ref::<ManualRefreshError>(),
Some(&ManualRefreshError::UnknownPodcast)
);
store.unsubscribe(b, &podcast_id).await.unwrap();
let unsubscribed = runner::refresh_now(&store, &fetcher, b, &podcast_id, t4 + 31_000).await;
assert_eq!(
unsubscribed
.unwrap_err()
.downcast_ref::<ManualRefreshError>(),
Some(&ManualRefreshError::NotSubscribed)
);
let far = t4 + 10 * runner::REFRESH_INTERVAL_MS;
let due = due_for(&store, &users, far).await;
assert_eq!(
due.values().flatten().count(),
1,
"unsubscribing stops monitoring"
);
// A permanent move becomes an alias (one sync operation) and the new
// fetch URL; later refreshes go to the new URL without new operations.
server.set("/show.xml", Route::redirect(301, "/moved.xml"));
server.set(
"/moved.xml",
Route::new(rss(&refresh_item("one")), "application/rss+xml"),
);
let moved = FeedUrl::parse(&server.url("/moved.xml")).unwrap();
let result = runner::refresh_now(&store, &fetcher, a, &podcast_id, far)
.await
.unwrap();
let TargetResult::Updated(outcome) = result else {
panic!("{result:?}");
};
assert_eq!(outcome.feed_url.as_ref(), Some(&moved));
assert_eq!(outcome.ops.len(), 1);
assert_eq!(
store
.podcast(a, &podcast_id)
.await
.unwrap()
.unwrap()
.meta
.feed_url,
moved
);
let due = due_for(&store, &users, far + 10 * runner::REFRESH_INTERVAL_MS).await;
assert_eq!(due.keys().collect::<Vec<_>>(), vec![&moved]);
let summary = run_due(
&store,
&fetcher,
&users,
far + 10 * runner::REFRESH_INTERVAL_MS,
)
.await;
assert_eq!(summary.updated, 1, "{summary}");
assert_eq!(server.requests("/moved.xml").len(), 2);
assert_eq!(server.requests("/show.xml").len(), 7);
let TargetResult::Updated(again) = runner::refresh_now(
&store,
&fetcher,
a,
&podcast_id,
far + 20 * runner::REFRESH_INTERVAL_MS,
)
.await
.unwrap() else {
panic!("expected a document");
};
assert!(again.ops.is_empty());
// The episode keeps its id; its audio now resolves against the new URL
// (same host here).
let after_move = store.episode(a, &episode_id).await.unwrap().unwrap();
assert_eq!(after_move.episode.audio_url, server.url("/audio/one.mp3"));
cleanup(&pool, [a, b, c]).await;
}