1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
import Foundation
import Observation
@MainActor
@Observable
final class SignedInAvatarStore {
private struct Record: Codable, Equatable {
let accountID: String
let url: URL
let data: Data
var headers: [String: String] = [:]
var receivedAt = Date()
var policy: AvatarCachePolicy? {
HTTPURLResponse(url: url, statusCode: 200, httpVersion: nil, headerFields: headers)
.map { AvatarCachePolicy(response: $0, now: receivedAt) }
}
mutating func updateHeaders(from response: HTTPURLResponse) {
headers["Date"] = nil
headers["Age"] = nil
for name in ["ETag", "Last-Modified", "Cache-Control", "Expires", "Vary", "Date", "Age"] {
if let value = response.value(forHTTPHeaderField: name) { headers[name] = value }
}
receivedAt = Date()
}
}
private struct Snapshot {
let record: Record
let entry: AvatarStore.Entry
var displayableEntry: AvatarStore.Entry? {
entry.policy.allowsDisplayWhileValidating ? entry : nil
}
init?(record: Record) {
guard record.data.count <= AvatarStore.maximumImageBytes,
let policy = record.policy, let image = AvatarStore.decode(record.data)
else { return nil }
self.init(record: record, entry: AvatarStore.Entry(image: image, policy: policy))
}
init(record: Record, entry: AvatarStore.Entry) {
self.record = record
self.entry = entry
}
}
private static let disk = DispatchQueue(label: "OldFella.SignedInAvatarStore", qos: .utility)
private let fileURL: URL
private let session: URLSession
private var account: Account?
private(set) var entry: AvatarStore.Entry?
private(set) var launchEntry: AvatarStore.Entry?
@ObservationIgnored private var preloadTask: (accountID: String, task: Task<Snapshot?, Never>)?
@ObservationIgnored private var revision = UUID()
@ObservationIgnored private var refreshTask: Task<Void, Never>?
init(
fileURL: URL = URL.cachesDirectory.appending(path: "signed-in-avatar.plist"),
session: URLSession = {
let configuration = URLSessionConfiguration.ephemeral
configuration.urlCache = nil
return URLSession(configuration: configuration)
}()
) {
self.fileURL = fileURL
self.session = session
}
func matches(_ account: Account?) -> Bool {
guard let account, account.id == self.account?.id else { return false }
if let url = account.avatarURL {
return AvatarImageURL.thumbnail(url) == self.account?.avatarURL.map(AvatarImageURL.thumbnail)
}
return !account.isAvatarURLKnown && self.account?.isAvatarURLKnown == false
}
func preload(for accountID: String) {
finishPreload()
let task = Task { [fileURL, weak self] () -> Snapshot? in
let cached = await Self.read(fileURL, accountID: accountID)
guard !Task.isCancelled else { return nil }
self?.launchEntry = cached?.displayableEntry
return cached
}
preloadTask = (accountID, task)
}
func finishPreload() {
preloadTask?.task.cancel()
preloadTask = nil
launchEntry = nil
}
func restore(for account: Account) async {
cancelRefresh()
let revision = revision
let cached: Snapshot?
if let preload = preloadTask, preload.accountID == account.id {
cached = await preload.task.value
} else {
cached = await Self.read(fileURL, accountID: account.id)
}
guard revision == self.revision, !Task.isCancelled else { return }
entry = cached?.displayableEntry
startRefresh(for: account, cached: cached)
}
func update(for account: Account) {
cancelRefresh()
if self.account?.id != account.id {
entry = nil
write(nil)
}
startRefresh(for: account, cached: nil)
}
func clear() {
finishPreload()
cancelRefresh()
account = nil
entry = nil
write(nil)
}
private func startRefresh(for account: Account, cached: Snapshot?) {
self.account = account
let reportedURL = account.avatarURL.map(AvatarImageURL.thumbnail)
if reportedURL == nil, account.isAvatarURLKnown {
clear()
return
}
guard let url = reportedURL ?? cached?.record.url else { return }
let candidate = cached?.record.url == url ? cached : nil
refreshTask = Task {
guard let result = try? await Self.fetch(url, accountID: account.id, cached: candidate, session: session),
!Task.isCancelled
else { return }
if entry !== result.entry { entry = result.entry }
if result.record.policy?.allowsStorage != true {
write(nil)
} else if result.record != candidate?.record {
write(result.record)
}
}
}
private func cancelRefresh() {
revision = UUID()
refreshTask?.cancel()
refreshTask = nil
}
@concurrent
private static func fetch(_ url: URL, accountID: String, cached: Snapshot?, session: URLSession) async throws
-> Snapshot? {
var request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData)
request.setValue("no-cache", forHTTPHeaderField: "Cache-Control")
if let tag = cached?.record.headers["ETag"] {
request.setValue(tag, forHTTPHeaderField: "If-None-Match")
} else if let modified = cached?.record.headers["Last-Modified"] {
request.setValue(modified, forHTTPHeaderField: "If-Modified-Since")
}
let (data, response) = try await session.data(for: request)
guard let response = response as? HTTPURLResponse else { return nil }
if response.statusCode == 304, let cached,
request.value(forHTTPHeaderField: "If-None-Match") != nil
|| request.value(forHTTPHeaderField: "If-Modified-Since") != nil {
var record = cached.record
record.updateHeaders(from: response)
return Snapshot(record: record, entry: cached.entry)
}
guard response.statusCode == 200 else { return nil }
var record = Record(accountID: accountID, url: url, data: data)
record.updateHeaders(from: response)
return Snapshot(record: record)
}
private static func read(_ url: URL, accountID: String) async -> Snapshot? {
await withCheckedContinuation { continuation in
disk.async {
let snapshot = (try? Data(contentsOf: url))
.flatMap { try? PropertyListDecoder().decode(Record.self, from: $0) }
.flatMap { $0.accountID == accountID ? Snapshot(record: $0) : nil }
continuation.resume(returning: snapshot)
}
}
}
private func write(_ record: Record?) {
let url = fileURL
Self.disk.async {
guard let record else {
try? FileManager.default.removeItem(at: url)
return
}
guard let data = try? PropertyListEncoder().encode(record) else { return }
try? data.write(to: url, options: .atomic)
}
}
}