Commit c48ca87415
Unsigned
Layout: unified · split
DomainDig.xcodeproj/project.pbxproj +4
| @@ -32,6 +32,7 @@ | ||
| 32 | 32 | A1B2C3D40000000000000802 /* LocalAPIRoutingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000000801 /* LocalAPIRoutingTests.swift */; }; |
| 33 | 33 | A1B2C3D40000000000000902 /* MonitoringSchedulingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000000901 /* MonitoringSchedulingTests.swift */; }; |
| 34 | 34 | A1B2C3D40000000000001002 /* DomainViewModelStoreTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000001001 /* DomainViewModelStoreTests.swift */; }; |
| 35 | A1B2C3D40000000000001102 /* LookupCacheTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000001101 /* LookupCacheTests.swift */; }; | |
| 35 | 36 | A1B2C3D40000000000000302 /* AvailabilityTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000000301 /* AvailabilityTests.swift */; }; |
| 36 | 37 | A1B2C3D40000000000000402 /* CloudSyncMergeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000000401 /* CloudSyncMergeTests.swift */; }; |
| 37 | 38 | A1B2C3D40000000000000502 /* DomainNameTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000000501 /* DomainNameTests.swift */; }; |
| @@ -111,6 +112,7 @@ | ||
| 111 | 112 | A1B2C3D40000000000000801 /* LocalAPIRoutingTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = LocalAPIRoutingTests.swift; sourceTree = "<group>"; }; |
| 112 | 113 | A1B2C3D40000000000000901 /* MonitoringSchedulingTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = MonitoringSchedulingTests.swift; sourceTree = "<group>"; }; |
| 113 | 114 | A1B2C3D40000000000001001 /* DomainViewModelStoreTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = DomainViewModelStoreTests.swift; sourceTree = "<group>"; }; |
| 115 | A1B2C3D40000000000001101 /* LookupCacheTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = LookupCacheTests.swift; sourceTree = "<group>"; }; | |
| 114 | 116 | A1B2C3D40000000000000301 /* AvailabilityTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = AvailabilityTests.swift; sourceTree = "<group>"; }; |
| 115 | 117 | A1B2C3D40000000000000401 /* CloudSyncMergeTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = CloudSyncMergeTests.swift; sourceTree = "<group>"; }; |
| 116 | 118 | A1B2C3D40000000000000501 /* DomainNameTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = DomainNameTests.swift; sourceTree = "<group>"; }; |
| @@ -255,6 +257,7 @@ | ||
| 255 | 257 | A1B2C3D40000000000000801 /* LocalAPIRoutingTests.swift */, |
| 256 | 258 | A1B2C3D40000000000000901 /* MonitoringSchedulingTests.swift */, |
| 257 | 259 | A1B2C3D40000000000001001 /* DomainViewModelStoreTests.swift */, |
| 260 | A1B2C3D40000000000001101 /* LookupCacheTests.swift */, | |
| 258 | 261 | A1B2C3D40000000000000301 /* AvailabilityTests.swift */, |
| 259 | 262 | A1B2C3D40000000000000401 /* CloudSyncMergeTests.swift */, |
| 260 | 263 | A1B2C3D40000000000000501 /* DomainNameTests.swift */, |
| @@ -524,6 +527,7 @@ | ||
| 524 | 527 | A1B2C3D40000000000000802 /* LocalAPIRoutingTests.swift in Sources */, |
| 525 | 528 | A1B2C3D40000000000000902 /* MonitoringSchedulingTests.swift in Sources */, |
| 526 | 529 | A1B2C3D40000000000001002 /* DomainViewModelStoreTests.swift in Sources */, |
| 530 | A1B2C3D40000000000001102 /* LookupCacheTests.swift in Sources */, | |
| 527 | 531 | A1B2C3D40000000000000302 /* AvailabilityTests.swift in Sources */, |
| 528 | 532 | A1B2C3D40000000000000402 /* CloudSyncMergeTests.swift in Sources */, |
| 529 | 533 | A1B2C3D40000000000000502 /* DomainNameTests.swift in Sources */, |
DomainDig/ExternalDataService.swift +10 −1
| @@ -145,7 +145,16 @@ actor ExternalDataService { | ||
| 145 | 145 | await self.enforceRateLimit(for: rateLimitBucket) |
| 146 | 146 | return await operation() |
| 147 | 147 | } |
| 148 | inFlight[key] = Task { await task.value as any Sendable } | |
| 148 | // `inFlight` can only hold the erased task, and cancelling that erased | |
| 149 | // wrapper does not reach the work it is waiting on. `clearCache()` | |
| 150 | // cancels what is in flight, so the wrapper forwards cancellation. | |
| 151 | inFlight[key] = Task { | |
| 152 | await withTaskCancellationHandler { | |
| 153 | await task.value as any Sendable | |
| 154 | } onCancel: { | |
| 155 | task.cancel() | |
| 156 | } | |
| 157 | } | |
| 149 | 158 | |
| 150 | 159 | let value = await task.value |
| 151 | 160 | cache[key] = CacheEntry(value: value, expiresAt: Date().addingTimeInterval(ttl)) |
DomainDig/LookupRuntime.swift +34 −99
| @@ -18,12 +18,12 @@ actor LookupRuntime { | ||
| 18 | 18 | |
| 19 | 19 | private let ttl: TimeInterval = 300 |
| 20 | 20 | |
| 21 | private enum RequestKey: Hashable { | |
| 21 | enum RequestKey: Hashable { | |
| 22 | 22 | case domain(String, LookupSectionKind) |
| 23 | 23 | case subject(String, LookupSectionKind) |
| 24 | 24 | } |
| 25 | 25 | |
| 26 | private enum RateLimitBucket: Hashable { | |
| 26 | enum RateLimitBucket: Hashable { | |
| 27 | 27 | case crtsh |
| 28 | 28 | case rdap |
| 29 | 29 | case ipGeolocation |
| @@ -40,30 +40,13 @@ actor LookupRuntime { | ||
| 40 | 40 | } |
| 41 | 41 | } |
| 42 | 42 | |
| 43 | private enum CachedPayload { | |
| 44 | case dns(ServiceResult<[DNSSection]>) | |
| 45 | case availability(DomainAvailabilityResult) | |
| 46 | case ssl(ServiceResult<SSLCertificateInfo>) | |
| 47 | case hsts(Bool?) | |
| 48 | case http(ServiceResult<HTTPHeadersResult>) | |
| 49 | case reachability(ServiceResult<[PortReachability]>) | |
| 50 | case ownership(ServiceResult<DomainOwnership>) | |
| 51 | case redirect(ServiceResult<[RedirectHop]>) | |
| 52 | case subdomains(ServiceResult<[DiscoveredSubdomain]>) | |
| 53 | case portScan(ServiceResult<[PortScanResult]>) | |
| 54 | case email(ServiceResult<EmailSecurityResult>) | |
| 55 | case ptr(ServiceResult<String>) | |
| 56 | case ipGeolocation(ServiceResult<IPGeolocation>) | |
| 57 | case suggestions([DomainSuggestionResult]) | |
| 58 | } | |
| 59 | ||
| 60 | 43 | private struct CacheEntry { |
| 61 | let payload: CachedPayload | |
| 44 | let value: any Sendable | |
| 62 | 45 | let expiresAt: Date |
| 63 | 46 | } |
| 64 | 47 | |
| 65 | 48 | private var cache: [RequestKey: CacheEntry] = [:] |
| 66 | private var inFlight: [RequestKey: Task<CachedPayload, Never>] = [:] | |
| 49 | private var inFlight: [RequestKey: Task<any Sendable, Never>] = [:] | |
| 67 | 50 | private var nextAllowedAt: [RateLimitBucket: Date] = [:] |
| 68 | 51 | |
| 69 | 52 | func clearCache() { |
| @@ -76,12 +59,8 @@ actor LookupRuntime { | ||
| 76 | 59 | func dns(domain: String) async -> CachedLookupResult<ServiceResult<[DNSSection]>> { |
| 77 | 60 | await execute( |
| 78 | 61 | key: .domain(domain, .dns), |
| 79 | extract: { payload in | |
| 80 | guard case let .dns(result) = payload else { return nil } | |
| 81 | return result | |
| 82 | }, | |
| 83 | 62 | operation: { |
| 84 | .dns(await DNSLookupService.lookupAll(domain: domain)) | |
| 63 | await DNSLookupService.lookupAll(domain: domain) | |
| 85 | 64 | } |
| 86 | 65 | ) |
| 87 | 66 | } |
| @@ -96,12 +75,8 @@ actor LookupRuntime { | ||
| 96 | 75 | func ssl(domain: String) async -> CachedLookupResult<ServiceResult<SSLCertificateInfo>> { |
| 97 | 76 | await execute( |
| 98 | 77 | key: .domain(domain, .ssl), |
| 99 | extract: { payload in | |
| 100 | guard case let .ssl(result) = payload else { return nil } | |
| 101 | return result | |
| 102 | }, | |
| 103 | 78 | operation: { |
| 104 | .ssl(await SSLCheckService.check(domain: domain)) | |
| 79 | await SSLCheckService.check(domain: domain) | |
| 105 | 80 | } |
| 106 | 81 | ) |
| 107 | 82 | } |
| @@ -109,12 +84,8 @@ actor LookupRuntime { | ||
| 109 | 84 | func hsts(domain: String) async -> CachedLookupResult<Bool?> { |
| 110 | 85 | await execute( |
| 111 | 86 | key: .domain(domain, .hsts), |
| 112 | extract: { payload in | |
| 113 | guard case let .hsts(result) = payload else { return nil } | |
| 114 | return result | |
| 115 | }, | |
| 116 | 87 | operation: { |
| 117 | .hsts(await SSLCheckService.checkHSTSPreload(domain: domain)) | |
| 88 | await SSLCheckService.checkHSTSPreload(domain: domain) | |
| 118 | 89 | } |
| 119 | 90 | ) |
| 120 | 91 | } |
| @@ -122,12 +93,8 @@ actor LookupRuntime { | ||
| 122 | 93 | func http(domain: String) async -> CachedLookupResult<ServiceResult<HTTPHeadersResult>> { |
| 123 | 94 | await execute( |
| 124 | 95 | key: .domain(domain, .httpHeaders), |
| 125 | extract: { payload in | |
| 126 | guard case let .http(result) = payload else { return nil } | |
| 127 | return result | |
| 128 | }, | |
| 129 | 96 | operation: { |
| 130 | .http(await HTTPHeadersService.fetch(domain: domain)) | |
| 97 | await HTTPHeadersService.fetch(domain: domain) | |
| 131 | 98 | } |
| 132 | 99 | ) |
| 133 | 100 | } |
| @@ -135,12 +102,8 @@ actor LookupRuntime { | ||
| 135 | 102 | func reachability(domain: String) async -> CachedLookupResult<ServiceResult<[PortReachability]>> { |
| 136 | 103 | await execute( |
| 137 | 104 | key: .domain(domain, .reachability), |
| 138 | extract: { payload in | |
| 139 | guard case let .reachability(result) = payload else { return nil } | |
| 140 | return result | |
| 141 | }, | |
| 142 | 105 | operation: { |
| 143 | .reachability(await ReachabilityService.checkAll(domain: domain)) | |
| 106 | await ReachabilityService.checkAll(domain: domain) | |
| 144 | 107 | } |
| 145 | 108 | ) |
| 146 | 109 | } |
| @@ -149,12 +112,8 @@ actor LookupRuntime { | ||
| 149 | 112 | await execute( |
| 150 | 113 | key: .domain(domain, .ownership), |
| 151 | 114 | rateLimitBucket: .rdap, |
| 152 | extract: { payload in | |
| 153 | guard case let .ownership(result) = payload else { return nil } | |
| 154 | return result | |
| 155 | }, | |
| 156 | 115 | operation: { |
| 157 | .ownership(await DomainOwnershipService.lookup(domain: domain)) | |
| 116 | await DomainOwnershipService.lookup(domain: domain) | |
| 158 | 117 | } |
| 159 | 118 | ) |
| 160 | 119 | } |
| @@ -162,12 +121,8 @@ actor LookupRuntime { | ||
| 162 | 121 | func redirectChain(domain: String) async -> CachedLookupResult<ServiceResult<[RedirectHop]>> { |
| 163 | 122 | await execute( |
| 164 | 123 | key: .domain(domain, .redirectChain), |
| 165 | extract: { payload in | |
| 166 | guard case let .redirect(result) = payload else { return nil } | |
| 167 | return result | |
| 168 | }, | |
| 169 | 124 | operation: { |
| 170 | .redirect(await RedirectChainService.trace(domain: domain)) | |
| 125 | await RedirectChainService.trace(domain: domain) | |
| 171 | 126 | } |
| 172 | 127 | ) |
| 173 | 128 | } |
| @@ -176,12 +131,8 @@ actor LookupRuntime { | ||
| 176 | 131 | await execute( |
| 177 | 132 | key: .domain(domain, .subdomains), |
| 178 | 133 | rateLimitBucket: .crtsh, |
| 179 | extract: { payload in | |
| 180 | guard case let .subdomains(result) = payload else { return nil } | |
| 181 | return result | |
| 182 | }, | |
| 183 | 134 | operation: { |
| 184 | .subdomains(await SubdomainDiscoveryService.discover(for: domain)) | |
| 135 | await SubdomainDiscoveryService.discover(for: domain) | |
| 185 | 136 | } |
| 186 | 137 | ) |
| 187 | 138 | } |
| @@ -189,12 +140,8 @@ actor LookupRuntime { | ||
| 189 | 140 | func portScan(domain: String) async -> CachedLookupResult<ServiceResult<[PortScanResult]>> { |
| 190 | 141 | await execute( |
| 191 | 142 | key: .domain(domain, .portScan), |
| 192 | extract: { payload in | |
| 193 | guard case let .portScan(result) = payload else { return nil } | |
| 194 | return result | |
| 195 | }, | |
| 196 | 143 | operation: { |
| 197 | .portScan(await PortScanService.scanAll(domain: domain)) | |
| 144 | await PortScanService.scanAll(domain: domain) | |
| 198 | 145 | } |
| 199 | 146 | ) |
| 200 | 147 | } |
| @@ -202,12 +149,8 @@ actor LookupRuntime { | ||
| 202 | 149 | func email(domain: String, txtRecords: [DNSRecord]) async -> CachedLookupResult<ServiceResult<EmailSecurityResult>> { |
| 203 | 150 | await execute( |
| 204 | 151 | key: .domain(domain, .emailSecurity), |
| 205 | extract: { payload in | |
| 206 | guard case let .email(result) = payload else { return nil } | |
| 207 | return result | |
| 208 | }, | |
| 209 | 152 | operation: { |
| 210 | .email(await EmailSecurityService.analyze(domain: domain, txtRecords: txtRecords)) | |
| 153 | await EmailSecurityService.analyze(domain: domain, txtRecords: txtRecords) | |
| 211 | 154 | } |
| 212 | 155 | ) |
| 213 | 156 | } |
| @@ -215,12 +158,8 @@ actor LookupRuntime { | ||
| 215 | 158 | func ptr(ip: String, resolverURLString: String) async -> CachedLookupResult<ServiceResult<String>> { |
| 216 | 159 | await execute( |
| 217 | 160 | key: .subject("\(resolverURLString)|\(ip)", .ptr), |
| 218 | extract: { payload in | |
| 219 | guard case let .ptr(result) = payload else { return nil } | |
| 220 | return result | |
| 221 | }, | |
| 222 | 161 | operation: { |
| 223 | .ptr(await ReverseDNSService.lookup(ip: ip, resolverURLString: resolverURLString)) | |
| 162 | await ReverseDNSService.lookup(ip: ip, resolverURLString: resolverURLString) | |
| 224 | 163 | } |
| 225 | 164 | ) |
| 226 | 165 | } |
| @@ -229,12 +168,8 @@ actor LookupRuntime { | ||
| 229 | 168 | await execute( |
| 230 | 169 | key: .subject(ip, .ipGeolocation), |
| 231 | 170 | rateLimitBucket: .ipGeolocation, |
| 232 | extract: { payload in | |
| 233 | guard case let .ipGeolocation(result) = payload else { return nil } | |
| 234 | return result | |
| 235 | }, | |
| 236 | 171 | operation: { |
| 237 | .ipGeolocation(await IPGeolocationService.lookup(ip: ip)) | |
| 172 | await IPGeolocationService.lookup(ip: ip) | |
| 238 | 173 | } |
| 239 | 174 | ) |
| 240 | 175 | } |
| @@ -242,46 +177,46 @@ actor LookupRuntime { | ||
| 242 | 177 | func suggestions(domain: String) async -> CachedLookupResult<[DomainSuggestionResult]> { |
| 243 | 178 | await execute( |
| 244 | 179 | key: .domain(domain, .suggestions), |
| 245 | extract: { payload in | |
| 246 | guard case let .suggestions(result) = payload else { return nil } | |
| 247 | return result | |
| 248 | }, | |
| 249 | 180 | operation: { |
| 250 | .suggestions(await DomainAvailabilityService.suggestions(for: domain)) | |
| 181 | await DomainAvailabilityService.suggestions(for: domain) | |
| 251 | 182 | } |
| 252 | 183 | ) |
| 253 | 184 | } |
| 254 | 185 | |
| 255 | private func execute<T>( | |
| 186 | func execute<T: Sendable>( | |
| 256 | 187 | key: RequestKey, |
| 257 | 188 | rateLimitBucket: RateLimitBucket? = nil, |
| 258 | extract: @escaping (CachedPayload) -> T?, | |
| 259 | operation: @escaping @Sendable () async -> CachedPayload | |
| 189 | operation: @escaping @Sendable () async -> T | |
| 260 | 190 | ) async -> CachedLookupResult<T> { |
| 261 | if let cachedEntry = cache[key], cachedEntry.expiresAt > Date(), let value = extract(cachedEntry.payload) { | |
| 191 | if let cachedEntry = cache[key], cachedEntry.expiresAt > Date(), let value = cachedEntry.value as? T { | |
| 262 | 192 | return CachedLookupResult(value: value, source: .cached) |
| 263 | 193 | } |
| 264 | 194 | |
| 265 | if let task = inFlight[key], let value = extract(await task.value) { | |
| 195 | if let task = inFlight[key], let value = await task.value as? T { | |
| 266 | 196 | return CachedLookupResult(value: value, source: .mixed) |
| 267 | 197 | } |
| 268 | 198 | |
| 269 | let task = Task<CachedPayload, Never> { | |
| 199 | let task = Task<T, Never> { | |
| 270 | 200 | if let rateLimitBucket { |
| 271 | 201 | await self.enforceRateLimit(for: rateLimitBucket) |
| 272 | 202 | } |
| 273 | 203 | return await operation() |
| 274 | 204 | } |
| 275 | inFlight[key] = task | |
| 205 | // `inFlight` can only hold the erased task, and cancelling that erased | |
| 206 | // wrapper does not reach the work it is waiting on. `clearCache()` | |
| 207 | // cancels what is in flight, so the wrapper forwards cancellation. | |
| 208 | inFlight[key] = Task { | |
| 209 | await withTaskCancellationHandler { | |
| 210 | await task.value as any Sendable | |
| 211 | } onCancel: { | |
| 212 | task.cancel() | |
| 213 | } | |
| 214 | } | |
| 276 | 215 | |
| 277 | let payload = await task.value | |
| 278 | cache[key] = CacheEntry(payload: payload, expiresAt: Date().addingTimeInterval(ttl)) | |
| 216 | let value = await task.value | |
| 217 | cache[key] = CacheEntry(value: value, expiresAt: Date().addingTimeInterval(ttl)) | |
| 279 | 218 | inFlight[key] = nil |
| 280 | 219 | |
| 281 | guard let value = extract(payload) else { | |
| 282 | fatalError("LookupRuntime payload extraction mismatch") | |
| 283 | } | |
| 284 | ||
| 285 | 220 | return CachedLookupResult(value: value, source: .live) |
| 286 | 221 | } |
| 287 | 222 | |
DomainDigTests/LookupCacheTests.swift added +145
| @@ -0,0 +1,145 @@ | ||
| 1 | import XCTest | |
| 2 | @testable import DomainDig | |
| 3 | ||
| 4 | /// `LookupRuntime.execute` used to cache an enum of fourteen payload kinds and | |
| 5 | /// re-derive the caller's type from it with a closure, trapping on | |
| 6 | /// `fatalError` when the case did not match. It is generic over its value now, | |
| 7 | /// so the mismatch cannot be expressed. These pin what the cache does instead, | |
| 8 | /// which nothing covered when the trap was the only thing guarding it. | |
| 9 | /// | |
| 10 | /// Every public method on the runtime reaches a live service, so `execute` is | |
| 11 | /// the seam. The operations here are closures that count their own calls. | |
| 12 | final class LookupCacheTests: XCTestCase { | |
| 13 | ||
| 14 | private func makeRuntime() -> LookupRuntime { LookupRuntime() } | |
| 15 | ||
| 16 | // MARK: Caching | |
| 17 | ||
| 18 | func testTheFirstCallIsLiveAndTheSecondIsCached() async { | |
| 19 | let runtime = makeRuntime() | |
| 20 | let calls = Counter() | |
| 21 | ||
| 22 | let first = await runtime.execute(key: .domain("example.com", .dns)) { | |
| 23 | await calls.increment() | |
| 24 | return 1 | |
| 25 | } | |
| 26 | let second = await runtime.execute(key: .domain("example.com", .dns)) { | |
| 27 | await calls.increment() | |
| 28 | return 2 | |
| 29 | } | |
| 30 | ||
| 31 | XCTAssertEqual(first.source, .live) | |
| 32 | XCTAssertEqual(first.value, 1) | |
| 33 | XCTAssertEqual(second.source, .cached) | |
| 34 | XCTAssertEqual(second.value, 1, "the cached call returned a fresh value") | |
| 35 | let callCount = await calls.count | |
| 36 | XCTAssertEqual(callCount, 1, "the operation ran twice") | |
| 37 | } | |
| 38 | ||
| 39 | /// The key carries the section kind, so two sections of one domain are | |
| 40 | /// separate entries. Collapsing them is what would have made a payload of | |
| 41 | /// the wrong type reachable under the old design. | |
| 42 | func testTheSameDomainCachesEachSectionSeparately() async { | |
| 43 | let runtime = makeRuntime() | |
| 44 | ||
| 45 | let dns = await runtime.execute(key: .domain("example.com", .dns)) { "dns" } | |
| 46 | let ssl = await runtime.execute(key: .domain("example.com", .ssl)) { "ssl" } | |
| 47 | ||
| 48 | XCTAssertEqual(dns.value, "dns") | |
| 49 | XCTAssertEqual(ssl.value, "ssl") | |
| 50 | XCTAssertEqual(ssl.source, .live, "the ssl key read the dns entry") | |
| 51 | } | |
| 52 | ||
| 53 | func testDomainAndSubjectKeysDoNotCollide() async { | |
| 54 | let runtime = makeRuntime() | |
| 55 | ||
| 56 | let domain = await runtime.execute(key: .domain("x", .ptr)) { "domain" } | |
| 57 | let subject = await runtime.execute(key: .subject("x", .ptr)) { "subject" } | |
| 58 | ||
| 59 | XCTAssertEqual(domain.value, "domain") | |
| 60 | XCTAssertEqual(subject.value, "subject") | |
| 61 | XCTAssertEqual(subject.source, .live) | |
| 62 | } | |
| 63 | ||
| 64 | /// A cached value of another type is not returned as this one. Under the | |
| 65 | /// old design the equivalent check was the `extract` closure, and failing | |
| 66 | /// it after a live fetch is what reached the `fatalError`. Here it must | |
| 67 | /// simply fall through to a live fetch. | |
| 68 | func testAKeyHoldingAnotherTypeFallsThroughToALiveFetch() async { | |
| 69 | let runtime = makeRuntime() | |
| 70 | ||
| 71 | let stored = await runtime.execute(key: .domain("example.com", .dns)) { 42 } | |
| 72 | let reread = await runtime.execute(key: .domain("example.com", .dns)) { "a string" } | |
| 73 | ||
| 74 | XCTAssertEqual(stored.value, 42) | |
| 75 | XCTAssertEqual(reread.value, "a string") | |
| 76 | XCTAssertEqual(reread.source, .live) | |
| 77 | } | |
| 78 | ||
| 79 | // MARK: Clearing | |
| 80 | ||
| 81 | func testClearingTheCacheMakesTheNextCallLive() async { | |
| 82 | let runtime = makeRuntime() | |
| 83 | let calls = Counter() | |
| 84 | ||
| 85 | _ = await runtime.execute(key: .domain("example.com", .dns)) { | |
| 86 | await calls.increment() | |
| 87 | return 1 | |
| 88 | } | |
| 89 | await runtime.clearCache() | |
| 90 | let afterClear = await runtime.execute(key: .domain("example.com", .dns)) { | |
| 91 | await calls.increment() | |
| 92 | return 2 | |
| 93 | } | |
| 94 | ||
| 95 | XCTAssertEqual(afterClear.source, .live) | |
| 96 | XCTAssertEqual(afterClear.value, 2) | |
| 97 | let callCount = await calls.count | |
| 98 | XCTAssertEqual(callCount, 2) | |
| 99 | } | |
| 100 | ||
| 101 | /// `clearCache()` cancels what is in flight, and both callers are | |
| 102 | /// user-initiated — the Clear Lookup Cache action and the full data wipe. | |
| 103 | /// The erased task `inFlight` holds is a wrapper around the real one, so | |
| 104 | /// cancelling the wrapper alone would leave the work running. | |
| 105 | func testClearingTheCacheCancelsWorkInFlight() async { | |
| 106 | let runtime = makeRuntime() | |
| 107 | let observed = CancellationProbe() | |
| 108 | ||
| 109 | let pending = Task { | |
| 110 | await runtime.execute(key: .domain("example.com", .subdomains)) { () -> Int in | |
| 111 | for _ in 0..<200 { | |
| 112 | if Task.isCancelled { | |
| 113 | await observed.record() | |
| 114 | return -1 | |
| 115 | } | |
| 116 | try? await Task.sleep(nanoseconds: 5_000_000) | |
| 117 | } | |
| 118 | return 0 | |
| 119 | } | |
| 120 | } | |
| 121 | ||
| 122 | // Let the operation reach its loop before clearing. | |
| 123 | try? await Task.sleep(nanoseconds: 50_000_000) | |
| 124 | await runtime.clearCache() | |
| 125 | _ = await pending.value | |
| 126 | ||
| 127 | let sawCancellation = await observed.wasCancelled | |
| 128 | XCTAssertTrue( | |
| 129 | sawCancellation, | |
| 130 | "the operation never saw cancellation, so clearCache() did not reach it" | |
| 131 | ) | |
| 132 | } | |
| 133 | } | |
| 134 | ||
| 135 | /// `actor` rather than a captured `var`: the operations run off the test's | |
| 136 | /// context and Swift 6 will not let them mutate shared state otherwise. | |
| 137 | private actor Counter { | |
| 138 | private(set) var count = 0 | |
| 139 | func increment() { count += 1 } | |
| 140 | } | |
| 141 | ||
| 142 | private actor CancellationProbe { | |
| 143 | private(set) var wasCancelled = false | |
| 144 | func record() { wasCancelled = true } | |
| 145 | } | |