react-native-audio-browser 0.2.0-next.42 → 0.2.0-next.44

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,42 @@
1
+ import Foundation
2
+
3
+ enum ArtworkFreshness {
4
+ /// The lifetime when no response states one: Kingfisher's own disk expiry.
5
+ static let defaultLifetime: TimeInterval = 7 * 24 * 60 * 60
6
+
7
+ /// The shortest lifetime any of `responses` (a fetch's redirects and its final response) states:
8
+ /// its `max-age` less its `Age`, or zero for `no-cache` or `no-store`. A response that states
9
+ /// none is skipped; `defaultLifetime` when none does.
10
+ static func lifetime(of responses: [HTTPURLResponse]) -> TimeInterval {
11
+ responses.compactMap(lifetime(of:)).min() ?? defaultLifetime
12
+ }
13
+
14
+ private static func lifetime(of response: HTTPURLResponse) -> TimeInterval? {
15
+ guard let cacheControl = response.value(forHTTPHeaderField: "Cache-Control") else { return nil }
16
+ var maxAge: TimeInterval?
17
+ for directive in cacheControl.split(separator: ",") {
18
+ let parts = directive.split(separator: "=", maxSplits: 1, omittingEmptySubsequences: false)
19
+ let name = parts[0].trimmingCharacters(in: .whitespaces).lowercased()
20
+ let value = parts.count == 2 ? parts[1].trimmingCharacters(in: .whitespaces).trimmingCharacters(in: ["\""]) : nil
21
+ switch name {
22
+ // `no-cache="field"` forbids reusing only that field, not the response.
23
+ case "no-cache" where value == nil, "no-store":
24
+ return 0
25
+ case "max-age":
26
+ maxAge = value.flatMap(deltaSeconds) ?? maxAge
27
+ default:
28
+ break
29
+ }
30
+ }
31
+ guard let maxAge else { return nil }
32
+ let age = response.value(forHTTPHeaderField: "Age").flatMap(deltaSeconds) ?? 0
33
+ return max(0, maxAge - age)
34
+ }
35
+
36
+ /// RFC 9111's delta-seconds: digits only, so `inf` or `1e999` state nothing, and capped at 2^31.
37
+ private static func deltaSeconds(_ value: String) -> TimeInterval? {
38
+ guard !value.isEmpty, value.allSatisfy({ ("0" ... "9").contains($0) }), let seconds = TimeInterval(value)
39
+ else { return nil }
40
+ return min(seconds, 2_147_483_648)
41
+ }
42
+ }
@@ -30,8 +30,9 @@ enum ArtworkImageFetcher {
30
30
  }
31
31
  options.append(.requestModifier(modifier))
32
32
  }
33
+ let processor: (any ImageProcessor)?
33
34
  if let svgScale {
34
- options.append(.processor(SVGProcessor(size: nil, scale: svgScale)))
35
+ processor = SVGProcessor(size: nil, scale: svgScale)
35
36
  } else if let downsampleTo {
36
37
  // Downsample rasters at decode time. Any size hint passed upstream (the
37
38
  // resolver's ImageContext) is advisory — a CDN can ignore it and return
@@ -40,22 +41,105 @@ enum ArtworkImageFetcher {
40
41
  // cacheOriginalImage keeps the untouched original in the disk cache so
41
42
  // the same URL at another target size re-processes instead of
42
43
  // re-downloading.
43
- options.append(.processor(DownsamplingImageProcessor(size: downsampleTo.size)))
44
+ processor = DownsamplingImageProcessor(size: downsampleTo.size)
44
45
  options.append(.scaleFactor(downsampleTo.scale))
45
46
  options.append(.cacheOriginalImage)
47
+ } else {
48
+ processor = nil
46
49
  }
50
+ if let processor { options.append(.processor(processor)) }
51
+ let retry: KingfisherOptionsInfo = waitsForConnectivity ? [.retryStrategy(ConnectivityRetry())] : []
47
52
 
48
- if waitsForConnectivity {
49
- options.append(.retryStrategy(ConnectivityRetry()))
53
+ // Each processed variant is fresh on its own: a variant cached before the image changed
54
+ // would otherwise outlive the refetch of another.
55
+ let key = url.absoluteString + (processor?.identifier ?? "")
56
+ // Only an HTTP fetch records a lifetime: a file: or data: image would be refetched on every show.
57
+ let isFresh = if ["http", "https"].contains(url.scheme?.lowercased()) { await freshness.isFresh(key) } else { true }
58
+ let result: Result<UIImage, any Error> = if isFresh {
59
+ await retrieve(url, options: options + retry, freshnessKey: key)
60
+ } else {
61
+ await refetch(url, options: options, retry: retry, freshnessKey: key)
50
62
  }
63
+ switch result {
64
+ case let .success(image):
65
+ return image
66
+ case let .failure(error):
67
+ logger.error("Failed to load artwork from \(source.uri): \(error.localizedDescription)")
68
+ return nil
69
+ }
70
+ }
71
+
72
+ private static let freshness = FreshnessStore()
73
+
74
+ /// Fetches a stale or never-fetched image again. When that fails, the cached copy, if any, is
75
+ /// shown; with `retry`, a fetch that failed for want of a connection waits for one first.
76
+ @MainActor
77
+ private static func refetch(
78
+ _ url: URL,
79
+ options: KingfisherOptionsInfo,
80
+ retry: KingfisherOptionsInfo,
81
+ freshnessKey: String,
82
+ ) async -> Result<UIImage, any Error> {
83
+ let fetched = await retrieve(url, options: options + [.forceRefresh], freshnessKey: freshnessKey)
84
+ guard case let .failure(error) = fetched else { return fetched }
85
+ if let cached = try? await KingfisherManager.shared.retrieveImage(with: url, options: options + [.onlyFromCache]) {
86
+ return .success(cached.image)
87
+ }
88
+ guard !retry.isEmpty, (error as? KingfisherError)?.isConnectivity == true else { return fetched }
89
+ return await retrieve(url, options: options + [.forceRefresh] + retry, freshnessKey: freshnessKey)
90
+ }
51
91
 
92
+ /// Fetches through Kingfisher, and records how long an image from the network stays fresh.
93
+ @MainActor
94
+ private static func retrieve(
95
+ _ url: URL,
96
+ options: KingfisherOptionsInfo,
97
+ freshnessKey: String,
98
+ ) async -> Result<UIImage, any Error> {
52
99
  do {
53
100
  let result = try await KingfisherManager.shared.retrieveImage(with: url, options: options)
54
- return result.image
101
+ // Metrics mark a download: an image re-made from the cached original is `.none` too.
102
+ if result.cacheType == .none, let metrics = result.metrics {
103
+ let responses = metrics.rawMetrics.transactionMetrics.compactMap { $0.response as? HTTPURLResponse }
104
+ await freshness.record(freshnessKey, lifetime: ArtworkFreshness.lifetime(of: responses))
105
+ }
106
+ return .success(result.image)
55
107
  } catch {
56
- logger.error("Failed to load artwork from \(source.uri): \(error.localizedDescription)")
57
- return nil
108
+ return .failure(error)
109
+ }
110
+ }
111
+ }
112
+
113
+ /// The cache keys whose image is still fresh, each kept on disk until its lifetime ends.
114
+ private actor FreshnessStore {
115
+ private let storage = try? DiskStorage.Backend<Data>(
116
+ config: DiskStorage.Config(name: "com.audiobrowser.artwork-freshness", sizeLimit: 0),
117
+ )
118
+ private var sweptExpired = false
119
+
120
+ func isFresh(_ key: String) -> Bool {
121
+ guard let storage else { return false }
122
+ if !sweptExpired {
123
+ sweptExpired = true
124
+ _ = try? storage.removeExpiredValues()
58
125
  }
126
+ return storage.isCached(forKey: key)
127
+ }
128
+
129
+ func record(_ key: String, lifetime: TimeInterval) {
130
+ guard let storage else { return }
131
+ if lifetime > 0 {
132
+ try? storage.store(value: Data(), forKey: key, expiration: .seconds(lifetime))
133
+ } else {
134
+ try? storage.remove(forKey: key)
135
+ }
136
+ }
137
+ }
138
+
139
+ private extension KingfisherError {
140
+ var isConnectivity: Bool {
141
+ guard case let .responseError(reason: .URLSessionError(error)) = self else { return false }
142
+ return (error as? URLError)?.isConnectivity == true
59
143
  }
60
144
  }
61
145
 
@@ -65,10 +149,7 @@ private struct ConnectivityRetry: RetryStrategy {
65
149
  private static let maxRetries = 3
66
150
 
67
151
  func retry(context: RetryContext, retryHandler: @escaping @Sendable (RetryDecision) -> Void) {
68
- guard context.retriedCount < Self.maxRetries,
69
- case let .responseError(reason: .URLSessionError(error)) = context.error,
70
- (error as? URLError)?.isConnectivity == true
71
- else {
152
+ guard context.retriedCount < Self.maxRetries, context.error.isConnectivity else {
72
153
  retryHandler(.stop)
73
154
  return
74
155
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "react-native-audio-browser",
3
- "version": "0.2.0-next.42",
3
+ "version": "0.2.0-next.44",
4
4
  "description": "react-native-audio-browser is a react native package built with Nitro",
5
5
  "keywords": [
6
6
  "react-native",