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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
import SwiftUI
import UIKit
import XCTest
@testable import OldFella
@MainActor
final class SignedInAvatarStoreTests: XCTestCase {
func testToolbarShowsCachedAvatarBeforeProfileRestoreFinishes() async throws {
let fixture = Fixture()
fixture.script.addImage(.black, headers: ["ETag": "\"first\""])
let first = fixture.makeStore()
first.update(for: fixture.account)
_ = try await waitForAvatar(in: first)
fixture.script.addResponse(304)
let store = fixture.makeStore()
let gate = ThreadGate()
let service = ModerationTestService()
service.restoredAccount = fixture.account
service.restoreGate = gate
let model = AppModel(service: service, signedInAvatar: store)
let toolbar = AccountAvatar(account: nil, size: 32, showsDuringSessionRestore: true)
XCTAssertEqual(try pixels(in: toolbar, model: model), [[0, 0, 0, 0]])
await gate.waitUntilStarted()
defer { Task { await gate.release() } }
try await waitUntil { store.launchEntry != nil }
let preview = try XCTUnwrap(store.launchEntry)
XCTAssertNil(model.account)
XCTAssertTrue(try pixels(in: toolbar, model: model).contains([0, 0, 0, 255]))
XCTAssertEqual(fixture.script.requests.count, 1)
await gate.release()
try await waitUntil { !model.isRestoringSession }
XCTAssertTrue(store.entry === preview)
XCTAssertNil(store.launchEntry)
try await waitForRequests(2, in: fixture)
XCTAssertEqual(fixture.script.requests.last?.value(forHTTPHeaderField: "If-None-Match"), "\"first\"")
}
func testAvatarPlaceholderUsesTwoGrayColorsInBothAppearances() throws {
let model = AppModel(service: ModerationTestService())
let placeholder = AccountAvatar(account: nil, size: 32)
for (scheme, background, silhouette) in [(ColorScheme.light, 209, 84), (.dark, 69, 184)] {
let colors = try pixels(in: placeholder, model: model, scheme: scheme)
for gray in [background, silhouette] {
XCTAssertTrue(colors.contains { pixel in
pixel[3] == 255 && pixel[0] == pixel[1] && pixel[1] == pixel[2] && abs(Int(pixel[0]) - gray) <= 1
})
}
}
}
func testRelaunchShowsCachedAvatarAndChecksETag() async throws {
let fixture = Fixture()
fixture.script.addImage(.black, headers: ["ETag": "\"first\"", "Last-Modified": Fixture.modified])
let first = fixture.makeStore()
first.update(for: fixture.account)
let original = try await waitForAvatar(in: first)
fixture.script.addResponse(304)
let relaunched = fixture.makeStore()
await relaunched.restore(for: fixture.account)
let cached = try XCTUnwrap(relaunched.entry)
XCTAssertEqual(cached.ringColors, original.ringColors)
try await waitForRequests(2, in: fixture)
XCTAssertEqual(fixture.script.requests.last?.value(forHTTPHeaderField: "If-None-Match"), "\"first\"")
XCTAssertNil(fixture.script.requests.last?.value(forHTTPHeaderField: "If-Modified-Since"))
XCTAssertEqual(fixture.script.requests.last?.url, AvatarImageURL.thumbnail(fixture.url))
}
func testLastModifiedValidatesCachedImageBeforeDisplayWhenRequired() async throws {
let fixture = Fixture()
fixture.script.addImage(.black, headers: ["Cache-Control": "no-cache", "Last-Modified": Fixture.modified])
let first = fixture.makeStore()
first.update(for: fixture.account)
let original = try await waitForAvatar(in: first)
fixture.script.addResponse(304)
let relaunched = fixture.makeStore()
await relaunched.restore(for: fixture.account)
XCTAssertNil(relaunched.entry)
let validated = try await waitForAvatar(in: relaunched)
XCTAssertEqual(validated.ringColors, original.ringColors)
XCTAssertEqual(fixture.script.requests.last?.value(forHTTPHeaderField: "If-Modified-Since"), Fixture.modified)
}
func testChangedImageAtSameURLReplacesDiskCache() async throws {
let fixture = Fixture()
fixture.script.addImage(.black, headers: ["ETag": "\"first\""])
let first = fixture.makeStore()
first.update(for: fixture.account)
let original = try await waitForAvatar(in: first)
fixture.script.addImage(.white, headers: ["ETag": "\"second\""])
let relaunched = fixture.makeStore()
await relaunched.restore(for: fixture.account)
XCTAssertEqual(relaunched.entry?.ringColors, original.ringColors)
let replacement = try await waitForAvatar(in: relaunched, differentFrom: original.ringColors)
fixture.script.addResponse(503)
let restarted = fixture.makeStore()
await restarted.restore(for: fixture.account)
XCTAssertEqual(restarted.entry?.ringColors, replacement.ringColors)
try await waitForRequests(3, in: fixture)
XCTAssertEqual(fixture.script.requests.last?.value(forHTTPHeaderField: "If-None-Match"), "\"second\"")
}
func testNewURLUsesNoOldValidatorAndNoStoreClearsDiskCache() async throws {
let fixture = Fixture()
fixture.script.addImage(.black, headers: ["ETag": "\"first\""])
let first = fixture.makeStore()
first.update(for: fixture.account)
let original = try await waitForAvatar(in: first)
var updated = fixture.account
updated.avatarURL = fixture.url.deletingLastPathComponent().appending(path: "new.jpeg")
fixture.script.addImage(.white, headers: ["Cache-Control": "no-store"])
let relaunched = fixture.makeStore()
await relaunched.restore(for: updated)
XCTAssertEqual(relaunched.entry?.ringColors, original.ringColors)
_ = try await waitForAvatar(in: relaunched, differentFrom: original.ringColors)
XCTAssertNil(fixture.script.requests.last?.value(forHTTPHeaderField: "If-None-Match"))
XCTAssertEqual(fixture.script.requests.last?.url, updated.avatarURL.map(AvatarImageURL.thumbnail))
fixture.script.addResponse(503)
let restarted = fixture.makeStore()
await restarted.restore(for: updated)
XCTAssertNil(restarted.entry)
}
func testSessionRestoreUsesCachedAvatarWhenProfileLookupFailsAndSignOutClearsIt() async throws {
let fixture = Fixture()
fixture.script.addImage(.black, headers: ["ETag": "\"first\""])
let first = fixture.makeStore()
first.update(for: fixture.account)
let original = try await waitForAvatar(in: first)
fixture.script.addResponse(503)
let store = fixture.makeStore()
let service = ModerationTestService()
var account = fixture.account
account.avatarURL = nil
account.isAvatarURLKnown = false
service.restoredAccount = account
let model = AppModel(service: service, signedInAvatar: store)
try await waitUntil { !model.isRestoringSession }
XCTAssertTrue(store.matches(model.account))
XCTAssertEqual(store.entry?.ringColors, original.ringColors)
account.isAvatarURLKnown = true
XCTAssertFalse(store.matches(account))
try await waitForRequests(2, in: fixture)
await model.signOut()
XCTAssertNil(store.entry)
let relaunched = fixture.makeStore()
fixture.script.addResponse(503)
await relaunched.restore(for: fixture.account)
XCTAssertNil(relaunched.entry)
}
private func waitForAvatar(in store: SignedInAvatarStore, differentFrom colors: AvatarRingColors? = nil)
async throws -> AvatarStore.Entry {
try await waitUntil { store.entry != nil && store.entry?.ringColors != colors }
return try XCTUnwrap(store.entry)
}
private func waitForRequests(_ count: Int, in fixture: Fixture) async throws {
try await waitUntil { fixture.script.requests.count >= count }
}
private func waitUntil(_ condition: () -> Bool) async throws {
let deadline = ContinuousClock.now + .seconds(5)
while !condition(), ContinuousClock.now < deadline {
try await Task.sleep(for: .milliseconds(10))
}
_ = try XCTUnwrap(condition() ? true : nil, "The avatar request did not finish in time.")
}
private func pixels(in avatar: AccountAvatar, model: AppModel, scheme: ColorScheme = .light) throws -> Set<[UInt8]> {
let suite = "AvatarRendering.\(UUID().uuidString)"
let defaults = try XCTUnwrap(UserDefaults(suiteName: suite))
defer { defaults.removePersistentDomain(forName: suite) }
defaults.set(false, forKey: "hideAvatars")
let renderer = ImageRenderer(content: avatar.environment(model).environment(\.colorScheme, scheme)
.defaultAppStorage(defaults))
let image = try XCTUnwrap(renderer.cgImage)
let rowBytes = image.width * 4
var bytes = [UInt8](repeating: 0, count: rowBytes * image.height)
try bytes.withUnsafeMutableBytes { buffer in
let context = try XCTUnwrap(CGContext(
data: buffer.baseAddress, width: image.width, height: image.height,
bitsPerComponent: 8, bytesPerRow: rowBytes, space: CGColorSpace(name: CGColorSpace.sRGB)!,
bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue | CGBitmapInfo.byteOrder32Big.rawValue
))
context.draw(image, in: CGRect(x: 0, y: 0, width: image.width, height: image.height))
}
return Set(stride(from: 0, to: bytes.count, by: 4).map { Array(bytes[$0..<($0 + 4)]) })
}
private struct Fixture {
static let modified = "Wed, 01 Jan 2025 12:00:00 GMT"
let url = URL(string: "https://cdn.bsky.app/img/avatar/plain/\(UUID().uuidString)/old.jpeg")!
let fileURL = FileManager.default.temporaryDirectory.appending(path: "\(UUID().uuidString).plist")
let script = SignedInAvatarProtocol.Script()
var account: Account { Account(handle: "demo.bsky.social", displayName: "Demo", id: "demo", avatarURL: url) }
@MainActor func makeStore() -> SignedInAvatarStore {
SignedInAvatarProtocol.register(script, for: url.deletingLastPathComponent().lastPathComponent)
let configuration = URLSessionConfiguration.ephemeral
configuration.protocolClasses = [SignedInAvatarProtocol.self]
configuration.urlCache = nil
return SignedInAvatarStore(fileURL: fileURL, session: URLSession(configuration: configuration))
}
}
}
private final class SignedInAvatarProtocol: URLProtocol {
private static let lock = NSLock()
private static var scripts: [String: Script] = [:]
final class Script {
private let lock = NSLock()
private var responses: [(Int, [String: String], Data)] = []
private var recordedRequests: [URLRequest] = []
var requests: [URLRequest] { lock.withLock { recordedRequests } }
func addImage(_ color: UIColor, headers: [String: String]) {
let data = UIGraphicsImageRenderer(size: CGSize(width: 16, height: 16)).image { context in
color.setFill()
context.fill(CGRect(x: 0, y: 0, width: 16, height: 16))
}.pngData()!
addResponse(200, headers: headers, data: data)
}
func addResponse(_ status: Int, headers: [String: String] = [:], data: Data = Data()) {
lock.withLock { responses.append((status, headers, data)) }
}
func nextResponse(for request: URLRequest) -> (Int, [String: String], Data) {
lock.withLock {
recordedRequests.append(request)
return responses.isEmpty ? (500, [:], Data()) : responses.removeFirst()
}
}
}
static func register(_ script: Script, for id: String) {
lock.withLock { scripts[id] = script }
}
override static func canInit(with request: URLRequest) -> Bool { true }
override static func canonicalRequest(for request: URLRequest) -> URLRequest { request }
override func stopLoading() {}
override func startLoading() {
let url = request.url!
let id = url.deletingLastPathComponent().lastPathComponent
guard let script = Self.lock.withLock({ Self.scripts[id] }) else {
client?.urlProtocol(self, didFailWithError: URLError(.resourceUnavailable))
return
}
let (status, headers, data) = script.nextResponse(for: request)
let response = HTTPURLResponse(url: url, statusCode: status, httpVersion: "HTTP/1.1", headerFields: headers)!
client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)
if !data.isEmpty { client?.urlProtocol(self, didLoad: data) }
client?.urlProtocolDidFinishLoading(self)
}
}