Commit 08ae53b6 authored by Kourser's avatar Kourser
Browse files

fix(feeds): refreshing a feed always asks the server

Feeds were loaded under URLSession's default cache policy. A response
with Last-Modified and no Cache-Control is then kept fresh for about a
tenth of its age — most of a day for a feed last changed a week ago —
and a refresh in that window missed the new episode.

FeedFetcher now loads feeds with .reloadRevalidatingCacheData, through
URLSessionFeedLoader.feeds(): a conditional request each time, so an
unchanged feed costs a 304, not a download. Chapters and transcripts
keep the default policy.

Checked against a local server: after the feed changed, the old policy
still returned the stale copy and the new one the fresh feed, then a
304; on the iOS simulator, cold launches went from cache hits to a 200
and then 304s.

Co-Authored-By: default avatarClaude Opus 5.5 <noreply@anthropic.com>
parent 12f61d2f
Loading
Loading
Loading
Loading
+4
Changes for CHANGELOG.md: 4 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -44,6 +44,10 @@ adopte le [versionnage sémantique](https://semver.org/lang/fr/).
  avant le chargement de la bibliothèque. Elle l'attend désormais, comme la
  synchronisation qui la précède, qui aurait pu sinon comparer le serveur à
  une bibliothèque vide.
- Un flux dont le serveur ne précise pas de durée de cache pouvait être
  resservi depuis la copie locale pendant des heures, et une actualisation ne
  montrait pas le nouvel épisode. Chaque actualisation interroge désormais le
  serveur, sans retélécharger un flux qui n'a pas changé.

## [1.5.0] - 2026-10-31

+14 −2
Changes for Packages/Core/Sources/FeedKit/FeedFetcher.swift: 14 added lines, 2 removed lines.
Original line number Diff line number Diff line
@@ -19,9 +19,20 @@ public extension FeedDataLoading {
/// Default loader backed by `URLSession`.
public struct URLSessionFeedLoader: FeedDataLoading {
    private let session: URLSession
    private let cachePolicy: URLRequest.CachePolicy

    public init(session: URLSession = .shared) {
    public init(session: URLSession = .shared, cachePolicy: URLRequest.CachePolicy = .useProtocolCachePolicy) {
        self.session = session
        self.cachePolicy = cachePolicy
    }

    /// For feeds: every fetch asks the server — conditionally, so an unchanged
    /// feed costs a 304, not a download. Left to the default policy, URLCache
    /// served a feed sent without `Cache-Control` from its own copy for a
    /// tenth of the time since its `Last-Modified` — most of a day for a feed
    /// last changed a week ago — and a refresh missed the new episode.
    public static func feeds(session: URLSession = .shared) -> URLSessionFeedLoader {
        URLSessionFeedLoader(session: session, cachePolicy: .reloadRevalidatingCacheData)
    }

    public func loadData(from url: URL) async throws -> Data {
@@ -30,6 +41,7 @@ public struct URLSessionFeedLoader: FeedDataLoading {

    public func loadData(from url: URL, authorization: String?) async throws -> Data {
        var request = URLRequest(url: url)
        request.cachePolicy = cachePolicy
        if let authorization {
            request.setValue(authorization, forHTTPHeaderField: "Authorization")
        }
@@ -49,7 +61,7 @@ public enum FeedFetchError: Error, Equatable, Sendable {
public struct FeedFetcher: Sendable {
    private let loader: FeedDataLoading

    public init(loader: FeedDataLoading = URLSessionFeedLoader()) {
    public init(loader: FeedDataLoading = URLSessionFeedLoader.feeds()) {
        self.loader = loader
    }

+35
Changes for Packages/Core/Tests/FeedKitTests/FeedFetcherTests.swift: 35 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -21,6 +21,25 @@ private final class AuthSpyLoader: FeedDataLoading, @unchecked Sendable {
    }
}

/// Answers every request with an empty body, noting the cache policy each one
/// was sent with.
private final class CachePolicySpy: URLProtocol {
    nonisolated(unsafe) static var policies: [URL: URLRequest.CachePolicy] = [:]

    override class func canInit(with request: URLRequest) -> Bool { true }
    override class func canonicalRequest(for request: URLRequest) -> URLRequest { request }

    override func startLoading() {
        if let url = request.url { Self.policies[url] = request.cachePolicy }
        let response = HTTPURLResponse(url: request.url!, statusCode: 200, httpVersion: nil, headerFields: nil)!
        client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)
        client?.urlProtocol(self, didLoad: Data())
        client?.urlProtocolDidFinishLoading(self)
    }

    override func stopLoading() {}
}

@Suite struct FeedFetcherTests {
    private func sampleFeedData() throws -> Data {
        let url = try #require(
@@ -56,4 +75,20 @@ private final class AuthSpyLoader: FeedDataLoading, @unchecked Sendable {
        _ = try await fetcher.fetch(url: URL(string: "https://example.com/feed.xml")!)
        #expect(loader.authorization == nil)
    }

    @Test func feedsAreAskedOfTheServerEveryTime() async throws {
        let configuration = URLSessionConfiguration.ephemeral
        configuration.protocolClasses = [CachePolicySpy.self]
        let session = URLSession(configuration: configuration)
        let feed = URL(string: "https://example.com/feed-policy.xml")!
        let chapters = URL(string: "https://example.com/chapters-policy.json")!

        _ = try await URLSessionFeedLoader.feeds(session: session).loadData(from: feed)
        _ = try await URLSessionFeedLoader(session: session).loadData(from: chapters)

        // A feed is revalidated, never taken from the cache on trust; other
        // resources (chapters, transcripts) keep the protocol's rules.
        #expect(CachePolicySpy.policies[feed] == .reloadRevalidatingCacheData)
        #expect(CachePolicySpy.policies[chapters] == .useProtocolCachePolicy)
    }
}