Commit c48ca87415
Unsigned
Layout: unified · split
DomainDig.xcodeproj/project.pbxproj +4
| @@ -32,6 +32,7 @@ | |||
| 32 | A1B2C3D40000000000000802 /* LocalAPIRoutingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000000801 /* LocalAPIRoutingTests.swift */; }; | 32 | A1B2C3D40000000000000802 /* LocalAPIRoutingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000000801 /* LocalAPIRoutingTests.swift */; }; |
| 33 | A1B2C3D40000000000000902 /* MonitoringSchedulingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000000901 /* MonitoringSchedulingTests.swift */; }; | 33 | A1B2C3D40000000000000902 /* MonitoringSchedulingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000000901 /* MonitoringSchedulingTests.swift */; }; |
| 34 | A1B2C3D40000000000001002 /* DomainViewModelStoreTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000001001 /* DomainViewModelStoreTests.swift */; }; | 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 | A1B2C3D40000000000000302 /* AvailabilityTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000000301 /* AvailabilityTests.swift */; }; | 36 | A1B2C3D40000000000000302 /* AvailabilityTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000000301 /* AvailabilityTests.swift */; }; |
| 36 | A1B2C3D40000000000000402 /* CloudSyncMergeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000000401 /* CloudSyncMergeTests.swift */; }; | 37 | A1B2C3D40000000000000402 /* CloudSyncMergeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000000401 /* CloudSyncMergeTests.swift */; }; |
| 37 | A1B2C3D40000000000000502 /* DomainNameTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000000501 /* DomainNameTests.swift */; }; | 38 | A1B2C3D40000000000000502 /* DomainNameTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000000501 /* DomainNameTests.swift */; }; |
| @@ -111,6 +112,7 @@ | |||
| 111 | A1B2C3D40000000000000801 /* LocalAPIRoutingTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = LocalAPIRoutingTests.swift; sourceTree = "<group>"; }; | 112 | A1B2C3D40000000000000801 /* LocalAPIRoutingTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = LocalAPIRoutingTests.swift; sourceTree = "<group>"; }; |
| 112 | A1B2C3D40000000000000901 /* MonitoringSchedulingTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = MonitoringSchedulingTests.swift; sourceTree = "<group>"; }; | 113 | A1B2C3D40000000000000901 /* MonitoringSchedulingTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = MonitoringSchedulingTests.swift; sourceTree = "<group>"; }; |
| 113 | A1B2C3D40000000000001001 /* DomainViewModelStoreTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = DomainViewModelStoreTests.swift; sourceTree = "<group>"; }; | 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 | A1B2C3D40000000000000301 /* AvailabilityTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = AvailabilityTests.swift; sourceTree = "<group>"; }; | 116 | A1B2C3D40000000000000301 /* AvailabilityTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = AvailabilityTests.swift; sourceTree = "<group>"; }; |
| 115 | A1B2C3D40000000000000401 /* CloudSyncMergeTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = CloudSyncMergeTests.swift; sourceTree = "<group>"; }; | 117 | A1B2C3D40000000000000401 /* CloudSyncMergeTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = CloudSyncMergeTests.swift; sourceTree = "<group>"; }; |
| 116 | A1B2C3D40000000000000501 /* DomainNameTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = DomainNameTests.swift; sourceTree = "<group>"; }; | 118 | A1B2C3D40000000000000501 /* DomainNameTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = DomainNameTests.swift; sourceTree = "<group>"; }; |
| @@ -255,6 +257,7 @@ | |||
| 255 | A1B2C3D40000000000000801 /* LocalAPIRoutingTests.swift */, | 257 | A1B2C3D40000000000000801 /* LocalAPIRoutingTests.swift */, |
| 256 | A1B2C3D40000000000000901 /* MonitoringSchedulingTests.swift */, | 258 | A1B2C3D40000000000000901 /* MonitoringSchedulingTests.swift */, |
| 257 | A1B2C3D40000000000001001 /* DomainViewModelStoreTests.swift */, | 259 | A1B2C3D40000000000001001 /* DomainViewModelStoreTests.swift */, |
| 260 | A1B2C3D40000000000001101 /* LookupCacheTests.swift */, | ||
| 258 | A1B2C3D40000000000000301 /* AvailabilityTests.swift */, | 261 | A1B2C3D40000000000000301 /* AvailabilityTests.swift */, |
| 259 | A1B2C3D40000000000000401 /* CloudSyncMergeTests.swift */, | 262 | A1B2C3D40000000000000401 /* CloudSyncMergeTests.swift */, |
| 260 | A1B2C3D40000000000000501 /* DomainNameTests.swift */, | 263 | A1B2C3D40000000000000501 /* DomainNameTests.swift */, |
| @@ -524,6 +527,7 @@ | |||
| 524 | A1B2C3D40000000000000802 /* LocalAPIRoutingTests.swift in Sources */, | 527 | A1B2C3D40000000000000802 /* LocalAPIRoutingTests.swift in Sources */, |
| 525 | A1B2C3D40000000000000902 /* MonitoringSchedulingTests.swift in Sources */, | 528 | A1B2C3D40000000000000902 /* MonitoringSchedulingTests.swift in Sources */, |
| 526 | A1B2C3D40000000000001002 /* DomainViewModelStoreTests.swift in Sources */, | 529 | A1B2C3D40000000000001002 /* DomainViewModelStoreTests.swift in Sources */, |
| 530 | A1B2C3D40000000000001102 /* LookupCacheTests.swift in Sources */, | ||
| 527 | A1B2C3D40000000000000302 /* AvailabilityTests.swift in Sources */, | 531 | A1B2C3D40000000000000302 /* AvailabilityTests.swift in Sources */, |
| 528 | A1B2C3D40000000000000402 /* CloudSyncMergeTests.swift in Sources */, | 532 | A1B2C3D40000000000000402 /* CloudSyncMergeTests.swift in Sources */, |
| 529 | A1B2C3D40000000000000502 /* DomainNameTests.swift in Sources */, | 533 | A1B2C3D40000000000000502 /* DomainNameTests.swift in Sources */, |
DomainDig/ExternalDataService.swift +10 −1
| @@ -145,7 +145,16 @@ actor ExternalDataService { | |||
| 145 | await self.enforceRateLimit(for: rateLimitBucket) | 145 | await self.enforceRateLimit(for: rateLimitBucket) |
| 146 | return await operation() | 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 | let value = await task.value | 159 | let value = await task.value |
| 151 | cache[key] = CacheEntry(value: value, expiresAt: Date().addingTimeInterval(ttl)) | 160 | cache[key] = CacheEntry(value: value, expiresAt: Date().addingTimeInterval(ttl)) |
DomainDig/LookupRuntime.swift +34 −99
| @@ -18,12 +18,12 @@ actor LookupRuntime { | |||
| 18 | 18 | ||
| 19 | private let ttl: TimeInterval = 300 | 19 | private let ttl: TimeInterval = 300 |
| 20 | 20 | ||
| 21 | private enum RequestKey: Hashable { | 21 | enum RequestKey: Hashable { |
| 22 | case domain(String, LookupSectionKind) | 22 | case domain(String, LookupSectionKind) |
| 23 | case subject(String, LookupSectionKind) | 23 | case subject(String, LookupSectionKind) |
| 24 | } | 24 | } |
| 25 | 25 | ||
| 26 | private enum RateLimitBucket: Hashable { | 26 | enum RateLimitBucket: Hashable { |
| 27 | case crtsh | 27 | case crtsh |
| 28 | case rdap | 28 | case rdap |
| 29 | case ipGeolocation | 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 | private struct CacheEntry { | 43 | private struct CacheEntry { |
| 61 | let payload: CachedPayload | 44 | let value: any Sendable |
| 62 | let expiresAt: Date | 45 | let expiresAt: Date |
| 63 | } | 46 | } |
| 64 | 47 | ||
| 65 | private var cache: [RequestKey: CacheEntry] = [:] | 48 | private var cache: [RequestKey: CacheEntry] = [:] |
| 66 | private var inFlight: [RequestKey: Task<CachedPayload, Never>] = [:] | 49 | private var inFlight: [RequestKey: Task<any Sendable, Never>] = [:] |
| 67 | private var nextAllowedAt: [RateLimitBucket: Date] = [:] | 50 | private var nextAllowedAt: [RateLimitBucket: Date] = [:] |
| 68 | 51 | ||
| 69 | func clearCache() { | 52 | func clearCache() { |
| @@ -76,12 +59,8 @@ actor LookupRuntime { | |||
| 76 | func dns(domain: String) async -> CachedLookupResult<ServiceResult<[DNSSection]>> { | 59 | func dns(domain: String) async -> CachedLookupResult<ServiceResult<[DNSSection]>> { |
| 77 | await execute( | 60 | await execute( |
| 78 | key: .domain(domain, .dns), | 61 | key: .domain(domain, .dns), |
| 79 | extract: { payload in | ||
| 80 | guard case let .dns(result) = payload else { return nil } | ||
| 81 | return result | ||
| 82 | }, | ||
| 83 | operation: { | 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 | func ssl(domain: String) async -> CachedLookupResult<ServiceResult<SSLCertificateInfo>> { | 75 | func ssl(domain: String) async -> CachedLookupResult<ServiceResult<SSLCertificateInfo>> { |
| 97 | await execute( | 76 | await execute( |
| 98 | key: .domain(domain, .ssl), | 77 | key: .domain(domain, .ssl), |
| 99 | extract: { payload in | ||
| 100 | guard case let .ssl(result) = payload else { return nil } | ||
| 101 | return result | ||
| 102 | }, | ||
| 103 | operation: { | 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 | func hsts(domain: String) async -> CachedLookupResult<Bool?> { | 84 | func hsts(domain: String) async -> CachedLookupResult<Bool?> { |
| 110 | await execute( | 85 | await execute( |
| 111 | key: .domain(domain, .hsts), | 86 | key: .domain(domain, .hsts), |
| 112 | extract: { payload in | ||
| 113 | guard case let .hsts(result) = payload else { return nil } | ||
| 114 | return result | ||
| 115 | }, | ||
| 116 | operation: { | 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 | func http(domain: String) async -> CachedLookupResult<ServiceResult<HTTPHeadersResult>> { | 93 | func http(domain: String) async -> CachedLookupResult<ServiceResult<HTTPHeadersResult>> { |
| 123 | await execute( | 94 | await execute( |
| 124 | key: .domain(domain, .httpHeaders), | 95 | key: .domain(domain, .httpHeaders), |
| 125 | extract: { payload in | ||
| 126 | guard case let .http(result) = payload else { return nil } | ||
| 127 | return result | ||
| 128 | }, | ||
| 129 | operation: { | 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 | func reachability(domain: String) async -> CachedLookupResult<ServiceResult<[PortReachability]>> { | 102 | func reachability(domain: String) async -> CachedLookupResult<ServiceResult<[PortReachability]>> { |
| 136 | await execute( | 103 | await execute( |
| 137 | key: .domain(domain, .reachability), | 104 | key: .domain(domain, .reachability), |
| 138 | extract: { payload in | ||
| 139 | guard case let .reachability(result) = payload else { return nil } | ||
| 140 | return result | ||
| 141 | }, | ||
| 142 | operation: { | 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 | await execute( | 112 | await execute( |
| 150 | key: .domain(domain, .ownership), | 113 | key: .domain(domain, .ownership), |
| 151 | rateLimitBucket: .rdap, | 114 | rateLimitBucket: .rdap, |
| 152 | extract: { payload in | ||
| 153 | guard case let .ownership(result) = payload else { return nil } | ||
| 154 | return result | ||
| 155 | }, | ||
| 156 | operation: { | 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 | func redirectChain(domain: String) async -> CachedLookupResult<ServiceResult<[RedirectHop]>> { | 121 | func redirectChain(domain: String) async -> CachedLookupResult<ServiceResult<[RedirectHop]>> { |
| 163 | await execute( | 122 | await execute( |
| 164 | key: .domain(domain, .redirectChain), | 123 | key: .domain(domain, .redirectChain), |
| 165 | extract: { payload in | ||
| 166 | guard case let .redirect(result) = payload else { return nil } | ||
| 167 | return result | ||
| 168 | }, | ||
| 169 | operation: { | 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 | await execute( | 131 | await execute( |
| 177 | key: .domain(domain, .subdomains), | 132 | key: .domain(domain, .subdomains), |
| 178 | rateLimitBucket: .crtsh, | 133 | rateLimitBucket: .crtsh, |
| 179 | extract: { payload in | ||
| 180 | guard case let .subdomains(result) = payload else { return nil } | ||
| 181 | return result | ||
| 182 | }, | ||
| 183 | operation: { | 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 | func portScan(domain: String) async -> CachedLookupResult<ServiceResult<[PortScanResult]>> { | 140 | func portScan(domain: String) async -> CachedLookupResult<ServiceResult<[PortScanResult]>> { |
| 190 | await execute( | 141 | await execute( |
| 191 | key: .domain(domain, .portScan), | 142 | key: .domain(domain, .portScan), |
| 192 | extract: { payload in | ||
| 193 | guard case let .portScan(result) = payload else { return nil } | ||
| 194 | return result | ||
| 195 | }, | ||
| 196 | operation: { | 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 | func email(domain: String, txtRecords: [DNSRecord]) async -> CachedLookupResult<ServiceResult<EmailSecurityResult>> { | 149 | func email(domain: String, txtRecords: [DNSRecord]) async -> CachedLookupResult<ServiceResult<EmailSecurityResult>> { |
| 203 | await execute( | 150 | await execute( |
| 204 | key: .domain(domain, .emailSecurity), | 151 | key: .domain(domain, .emailSecurity), |
| 205 | extract: { payload in | ||
| 206 | guard case let .email(result) = payload else { return nil } | ||
| 207 | return result | ||
| 208 | }, | ||
| 209 | operation: { | 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 | func ptr(ip: String, resolverURLString: String) async -> CachedLookupResult<ServiceResult<String>> { | 158 | func ptr(ip: String, resolverURLString: String) async -> CachedLookupResult<ServiceResult<String>> { |
| 216 | await execute( | 159 | await execute( |
| 217 | key: .subject("\(resolverURLString)|\(ip)", .ptr), | 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 | operation: { | 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 | await execute( | 168 | await execute( |
| 230 | key: .subject(ip, .ipGeolocation), | 169 | key: .subject(ip, .ipGeolocation), |
| 231 | rateLimitBucket: .ipGeolocation, | 170 | rateLimitBucket: .ipGeolocation, |
| 232 | extract: { payload in | ||
| 233 | guard case let .ipGeolocation(result) = payload else { return nil } | ||
| 234 | return result | ||
| 235 | }, | ||
| 236 | operation: { | 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 | func suggestions(domain: String) async -> CachedLookupResult<[DomainSuggestionResult]> { | 177 | func suggestions(domain: String) async -> CachedLookupResult<[DomainSuggestionResult]> { |
| 243 | await execute( | 178 | await execute( |
| 244 | key: .domain(domain, .suggestions), | 179 | key: .domain(domain, .suggestions), |
| 245 | extract: { payload in | ||
| 246 | guard case let .suggestions(result) = payload else { return nil } | ||
| 247 | return result | ||
| 248 | }, | ||
| 249 | operation: { | 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 | key: RequestKey, | 187 | key: RequestKey, |
| 257 | rateLimitBucket: RateLimitBucket? = nil, | 188 | rateLimitBucket: RateLimitBucket? = nil, |
| 258 | extract: @escaping (CachedPayload) -> T?, | 189 | operation: @escaping @Sendable () async -> T |
| 259 | operation: @escaping @Sendable () async -> CachedPayload | ||
| 260 | ) async -> CachedLookupResult<T> { | 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 | return CachedLookupResult(value: value, source: .cached) | 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 | return CachedLookupResult(value: value, source: .mixed) | 196 | return CachedLookupResult(value: value, source: .mixed) |
| 267 | } | 197 | } |
| 268 | 198 | ||
| 269 | let task = Task<CachedPayload, Never> { | 199 | let task = Task<T, Never> { |
| 270 | if let rateLimitBucket { | 200 | if let rateLimitBucket { |
| 271 | await self.enforceRateLimit(for: rateLimitBucket) | 201 | await self.enforceRateLimit(for: rateLimitBucket) |
| 272 | } | 202 | } |
| 273 | return await operation() | 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 | 216 | let value = await task.value |
| 278 | cache[key] = CacheEntry(payload: payload, expiresAt: Date().addingTimeInterval(ttl)) | 217 | cache[key] = CacheEntry(value: value, expiresAt: Date().addingTimeInterval(ttl)) |
| 279 | inFlight[key] = nil | 218 | inFlight[key] = nil |
| 280 | 219 | ||
| 281 | guard let value = extract(payload) else { | ||
| 282 | fatalError("LookupRuntime payload extraction mismatch") | ||
| 283 | } | ||
| 284 | |||
| 285 | return CachedLookupResult(value: value, source: .live) | 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 | } | ||