Commit c48ca87415

c48ca874157d43eae84ca23363f88527ec61a865

parent: 7bca632797

Unsigned

cmc <hello@cleberg.net> · 2026-10-24 15:12 UTC

Make the lookup cache generic over its value (!22)

`LookupRuntime` cached an enum of fourteen payload kinds and re-derived the
caller's type from it with an `extract` closure, trapping on `fatalError` when
the case did not match. It is generic over its value now — the enum, thirteen
`extract` closures and the trap are gone. Same shape !17 gave
`ExternalDataService`; this is C4's remaining half.

`execute`, `RequestKey` and `RateLimitBucket` become internal. Every public
method on the runtime reaches a live service, so the cache mechanics were only
reachable through one, which is why they had no coverage and why C4 asked for
tests before the conversion.

## Coverage

6 tests, 203 to 209:

- the first call is live, the second is cached, and the operation runs once
- each section kind of one domain is a separate entry
- `.domain` and `.subject` keys do not collide
- a key holding another type falls through to a live fetch — the case that
  reached the `fatalError` under the old design
- clearing the cache makes the next call live and runs the operation again
- clearing the cache cancels work in flight

## C10, found while converting

!17 erased the in-flight task to fit one dictionary:

```swift
inFlight[key] = Task { await task.value as any Sendable }
```

That wrapper is not the parent of `task`, so `clearCache()`'s
`inFlight.values.forEach { $0.cancel() }` cancelled only wrappers — the
network call it was meant to stop kept running. `ExternalDataService` has
carried this since !17. Converting `LookupRuntime` the same way would have
extended it to the inspection cache, whose `clearCache()` has two
user-initiated callers: the Clear Lookup Cache action and the full data wipe
(`DataResetService:25`).

Both wrappers forward cancellation now via `withTaskCancellationHandler`,
restoring what the pre-!17 typed cache did. The last test above is the only
cancellation coverage either service has.

## Verification

Each tier as its own invocation, per E2: 209 tests, 0 failures on iOS 18.6
(iPhone 16) and iOS 27.0 (iPhone Air). Releasing an `actor` does not hit E1's
deinit abort, so these tests need no retained instances.

Layout: unified · split

DomainDig.xcodeproj/project.pbxproj +4
@@ -32,6 +32,7 @@
3232 A1B2C3D40000000000000802 /* LocalAPIRoutingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000000801 /* LocalAPIRoutingTests.swift */; };
3333 A1B2C3D40000000000000902 /* MonitoringSchedulingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000000901 /* MonitoringSchedulingTests.swift */; };
3434 A1B2C3D40000000000001002 /* DomainViewModelStoreTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000001001 /* DomainViewModelStoreTests.swift */; };
35 A1B2C3D40000000000001102 /* LookupCacheTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000001101 /* LookupCacheTests.swift */; };
3536 A1B2C3D40000000000000302 /* AvailabilityTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000000301 /* AvailabilityTests.swift */; };
3637 A1B2C3D40000000000000402 /* CloudSyncMergeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000000401 /* CloudSyncMergeTests.swift */; };
3738 A1B2C3D40000000000000502 /* DomainNameTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000000501 /* DomainNameTests.swift */; };
@@ -111,6 +112,7 @@
111112 A1B2C3D40000000000000801 /* LocalAPIRoutingTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = LocalAPIRoutingTests.swift; sourceTree = "<group>"; };
112113 A1B2C3D40000000000000901 /* MonitoringSchedulingTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = MonitoringSchedulingTests.swift; sourceTree = "<group>"; };
113114 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>"; };
114116 A1B2C3D40000000000000301 /* AvailabilityTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = AvailabilityTests.swift; sourceTree = "<group>"; };
115117 A1B2C3D40000000000000401 /* CloudSyncMergeTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = CloudSyncMergeTests.swift; sourceTree = "<group>"; };
116118 A1B2C3D40000000000000501 /* DomainNameTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = DomainNameTests.swift; sourceTree = "<group>"; };
@@ -255,6 +257,7 @@
255257 A1B2C3D40000000000000801 /* LocalAPIRoutingTests.swift */,
256258 A1B2C3D40000000000000901 /* MonitoringSchedulingTests.swift */,
257259 A1B2C3D40000000000001001 /* DomainViewModelStoreTests.swift */,
260 A1B2C3D40000000000001101 /* LookupCacheTests.swift */,
258261 A1B2C3D40000000000000301 /* AvailabilityTests.swift */,
259262 A1B2C3D40000000000000401 /* CloudSyncMergeTests.swift */,
260263 A1B2C3D40000000000000501 /* DomainNameTests.swift */,
@@ -524,6 +527,7 @@
524527 A1B2C3D40000000000000802 /* LocalAPIRoutingTests.swift in Sources */,
525528 A1B2C3D40000000000000902 /* MonitoringSchedulingTests.swift in Sources */,
526529 A1B2C3D40000000000001002 /* DomainViewModelStoreTests.swift in Sources */,
530 A1B2C3D40000000000001102 /* LookupCacheTests.swift in Sources */,
527531 A1B2C3D40000000000000302 /* AvailabilityTests.swift in Sources */,
528532 A1B2C3D40000000000000402 /* CloudSyncMergeTests.swift in Sources */,
529533 A1B2C3D40000000000000502 /* DomainNameTests.swift in Sources */,
DomainDig/ExternalDataService.swift +10 −1
@@ -145,7 +145,16 @@ actor ExternalDataService {
145145 await self.enforceRateLimit(for: rateLimitBucket)
146146 return await operation()
147147 }
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 }
149158
150159 let value = await task.value
151160 cache[key] = CacheEntry(value: value, expiresAt: Date().addingTimeInterval(ttl))
DomainDig/LookupRuntime.swift +34 −99
@@ -18,12 +18,12 @@ actor LookupRuntime {
1818
1919 private let ttl: TimeInterval = 300
2020
21 private enum RequestKey: Hashable {
21 enum RequestKey: Hashable {
2222 case domain(String, LookupSectionKind)
2323 case subject(String, LookupSectionKind)
2424 }
2525
26 private enum RateLimitBucket: Hashable {
26 enum RateLimitBucket: Hashable {
2727 case crtsh
2828 case rdap
2929 case ipGeolocation
@@ -40,30 +40,13 @@ actor LookupRuntime {
4040 }
4141 }
4242
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
6043 private struct CacheEntry {
61 let payload: CachedPayload
44 let value: any Sendable
6245 let expiresAt: Date
6346 }
6447
6548 private var cache: [RequestKey: CacheEntry] = [:]
66 private var inFlight: [RequestKey: Task<CachedPayload, Never>] = [:]
49 private var inFlight: [RequestKey: Task<any Sendable, Never>] = [:]
6750 private var nextAllowedAt: [RateLimitBucket: Date] = [:]
6851
6952 func clearCache() {
@@ -76,12 +59,8 @@ actor LookupRuntime {
7659 func dns(domain: String) async -> CachedLookupResult<ServiceResult<[DNSSection]>> {
7760 await execute(
7861 key: .domain(domain, .dns),
79 extract: { payload in
80 guard case let .dns(result) = payload else { return nil }
81 return result
82 },
8362 operation: {
84 .dns(await DNSLookupService.lookupAll(domain: domain))
63 await DNSLookupService.lookupAll(domain: domain)
8564 }
8665 )
8766 }
@@ -96,12 +75,8 @@ actor LookupRuntime {
9675 func ssl(domain: String) async -> CachedLookupResult<ServiceResult<SSLCertificateInfo>> {
9776 await execute(
9877 key: .domain(domain, .ssl),
99 extract: { payload in
100 guard case let .ssl(result) = payload else { return nil }
101 return result
102 },
10378 operation: {
104 .ssl(await SSLCheckService.check(domain: domain))
79 await SSLCheckService.check(domain: domain)
10580 }
10681 )
10782 }
@@ -109,12 +84,8 @@ actor LookupRuntime {
10984 func hsts(domain: String) async -> CachedLookupResult<Bool?> {
11085 await execute(
11186 key: .domain(domain, .hsts),
112 extract: { payload in
113 guard case let .hsts(result) = payload else { return nil }
114 return result
115 },
11687 operation: {
117 .hsts(await SSLCheckService.checkHSTSPreload(domain: domain))
88 await SSLCheckService.checkHSTSPreload(domain: domain)
11889 }
11990 )
12091 }
@@ -122,12 +93,8 @@ actor LookupRuntime {
12293 func http(domain: String) async -> CachedLookupResult<ServiceResult<HTTPHeadersResult>> {
12394 await execute(
12495 key: .domain(domain, .httpHeaders),
125 extract: { payload in
126 guard case let .http(result) = payload else { return nil }
127 return result
128 },
12996 operation: {
130 .http(await HTTPHeadersService.fetch(domain: domain))
97 await HTTPHeadersService.fetch(domain: domain)
13198 }
13299 )
133100 }
@@ -135,12 +102,8 @@ actor LookupRuntime {
135102 func reachability(domain: String) async -> CachedLookupResult<ServiceResult<[PortReachability]>> {
136103 await execute(
137104 key: .domain(domain, .reachability),
138 extract: { payload in
139 guard case let .reachability(result) = payload else { return nil }
140 return result
141 },
142105 operation: {
143 .reachability(await ReachabilityService.checkAll(domain: domain))
106 await ReachabilityService.checkAll(domain: domain)
144107 }
145108 )
146109 }
@@ -149,12 +112,8 @@ actor LookupRuntime {
149112 await execute(
150113 key: .domain(domain, .ownership),
151114 rateLimitBucket: .rdap,
152 extract: { payload in
153 guard case let .ownership(result) = payload else { return nil }
154 return result
155 },
156115 operation: {
157 .ownership(await DomainOwnershipService.lookup(domain: domain))
116 await DomainOwnershipService.lookup(domain: domain)
158117 }
159118 )
160119 }
@@ -162,12 +121,8 @@ actor LookupRuntime {
162121 func redirectChain(domain: String) async -> CachedLookupResult<ServiceResult<[RedirectHop]>> {
163122 await execute(
164123 key: .domain(domain, .redirectChain),
165 extract: { payload in
166 guard case let .redirect(result) = payload else { return nil }
167 return result
168 },
169124 operation: {
170 .redirect(await RedirectChainService.trace(domain: domain))
125 await RedirectChainService.trace(domain: domain)
171126 }
172127 )
173128 }
@@ -176,12 +131,8 @@ actor LookupRuntime {
176131 await execute(
177132 key: .domain(domain, .subdomains),
178133 rateLimitBucket: .crtsh,
179 extract: { payload in
180 guard case let .subdomains(result) = payload else { return nil }
181 return result
182 },
183134 operation: {
184 .subdomains(await SubdomainDiscoveryService.discover(for: domain))
135 await SubdomainDiscoveryService.discover(for: domain)
185136 }
186137 )
187138 }
@@ -189,12 +140,8 @@ actor LookupRuntime {
189140 func portScan(domain: String) async -> CachedLookupResult<ServiceResult<[PortScanResult]>> {
190141 await execute(
191142 key: .domain(domain, .portScan),
192 extract: { payload in
193 guard case let .portScan(result) = payload else { return nil }
194 return result
195 },
196143 operation: {
197 .portScan(await PortScanService.scanAll(domain: domain))
144 await PortScanService.scanAll(domain: domain)
198145 }
199146 )
200147 }
@@ -202,12 +149,8 @@ actor LookupRuntime {
202149 func email(domain: String, txtRecords: [DNSRecord]) async -> CachedLookupResult<ServiceResult<EmailSecurityResult>> {
203150 await execute(
204151 key: .domain(domain, .emailSecurity),
205 extract: { payload in
206 guard case let .email(result) = payload else { return nil }
207 return result
208 },
209152 operation: {
210 .email(await EmailSecurityService.analyze(domain: domain, txtRecords: txtRecords))
153 await EmailSecurityService.analyze(domain: domain, txtRecords: txtRecords)
211154 }
212155 )
213156 }
@@ -215,12 +158,8 @@ actor LookupRuntime {
215158 func ptr(ip: String, resolverURLString: String) async -> CachedLookupResult<ServiceResult<String>> {
216159 await execute(
217160 key: .subject("\(resolverURLString)|\(ip)", .ptr),
218 extract: { payload in
219 guard case let .ptr(result) = payload else { return nil }
220 return result
221 },
222161 operation: {
223 .ptr(await ReverseDNSService.lookup(ip: ip, resolverURLString: resolverURLString))
162 await ReverseDNSService.lookup(ip: ip, resolverURLString: resolverURLString)
224163 }
225164 )
226165 }
@@ -229,12 +168,8 @@ actor LookupRuntime {
229168 await execute(
230169 key: .subject(ip, .ipGeolocation),
231170 rateLimitBucket: .ipGeolocation,
232 extract: { payload in
233 guard case let .ipGeolocation(result) = payload else { return nil }
234 return result
235 },
236171 operation: {
237 .ipGeolocation(await IPGeolocationService.lookup(ip: ip))
172 await IPGeolocationService.lookup(ip: ip)
238173 }
239174 )
240175 }
@@ -242,46 +177,46 @@ actor LookupRuntime {
242177 func suggestions(domain: String) async -> CachedLookupResult<[DomainSuggestionResult]> {
243178 await execute(
244179 key: .domain(domain, .suggestions),
245 extract: { payload in
246 guard case let .suggestions(result) = payload else { return nil }
247 return result
248 },
249180 operation: {
250 .suggestions(await DomainAvailabilityService.suggestions(for: domain))
181 await DomainAvailabilityService.suggestions(for: domain)
251182 }
252183 )
253184 }
254185
255 private func execute<T>(
186 func execute<T: Sendable>(
256187 key: RequestKey,
257188 rateLimitBucket: RateLimitBucket? = nil,
258 extract: @escaping (CachedPayload) -> T?,
259 operation: @escaping @Sendable () async -> CachedPayload
189 operation: @escaping @Sendable () async -> T
260190 ) 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 {
262192 return CachedLookupResult(value: value, source: .cached)
263193 }
264194
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 {
266196 return CachedLookupResult(value: value, source: .mixed)
267197 }
268198
269 let task = Task<CachedPayload, Never> {
199 let task = Task<T, Never> {
270200 if let rateLimitBucket {
271201 await self.enforceRateLimit(for: rateLimitBucket)
272202 }
273203 return await operation()
274204 }
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 }
276215
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))
279218 inFlight[key] = nil
280219
281 guard let value = extract(payload) else {
282 fatalError("LookupRuntime payload extraction mismatch")
283 }
284
285220 return CachedLookupResult(value: value, source: .live)
286221 }
287222
DomainDigTests/LookupCacheTests.swift added +145
@@ -0,0 +1,145 @@
1import 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.
12final 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.
137private actor Counter {
138 private(set) var count = 0
139 func increment() { count += 1 }
140}
141
142private actor CancellationProbe {
143 private(set) var wasCancelled = false
144 func record() { wasCancelled = true }
145}