Commit 68287d06b7

68287d06b71b8d077e4be842459fc3f485c86d88

parent: ac4279f4d2

Verified · cmc

cmc <hello@cleberg.net> · 2026-10-24 06:18 UTC

Make the external data cache typed

execute was generic over an enum of every payload kind and handed each caller a
closure to pull its own case back out. When the two disagreed it called
fatalError. It is generic over the value now: the payload enum and the three
extract closures are gone, operations return their value directly, and the live
path runs a typed Task and returns its result with no cast — so the mismatch
cannot arise rather than merely being unlikely. A cached or in-flight value of
the wrong type falls through to a fetch instead of ending the process.

LookupRuntime carries the identical trap with fourteen callers. It is the
inspection cache — provenance, cache-source attribution, in-flight coalescing —
and it has no tests, because that is W2's unfinished half. Converting it blind
is how the bug this prevents gets introduced, so C4 stays half open until those
tests exist.

Layout: unified · split

DomainDig/ExternalDataService.swift +20 −37
@@ -23,14 +23,8 @@ actor ExternalDataService {
23 } 23 }
24 } 24 }
25 25
26 private enum CachedPayload {
27 case ownershipHistory(ServiceResult<[DomainOwnershipHistoryEvent]>)
28 case dnsHistory(ServiceResult<[DNSHistoryEvent]>)
29 case extendedSubdomains(ServiceResult<[DiscoveredSubdomain]>)
30 }
31
32 private struct CacheEntry { 26 private struct CacheEntry {
33 let payload: CachedPayload 27 let value: any Sendable
34 let expiresAt: Date 28 let expiresAt: Date
35 } 29 }
36 30
@@ -43,7 +37,7 @@ actor ExternalDataService {
43 private let ttl: TimeInterval = 900 37 private let ttl: TimeInterval = 900
44 private let session: URLSession = .shared 38 private let session: URLSession = .shared
45 private var cache: [RequestKey: CacheEntry] = [:] 39 private var cache: [RequestKey: CacheEntry] = [:]
46 private var inFlight: [RequestKey: Task<CachedPayload, Never>] = [:] 40 private var inFlight: [RequestKey: Task<any Sendable, Never>] = [:]
47 private var nextAllowedAt: [RateLimitBucket: Date] = [:] 41 private var nextAllowedAt: [RateLimitBucket: Date] = [:]
48 42
49 func clearCache() { 43 func clearCache() {
@@ -62,10 +56,6 @@ actor ExternalDataService {
62 return await execute( 56 return await execute(
63 key: .ownershipHistory(normalizedDomain), 57 key: .ownershipHistory(normalizedDomain),
64 rateLimitBucket: .history, 58 rateLimitBucket: .history,
65 extract: { payload in
66 guard case let .ownershipHistory(result) = payload else { return nil }
67 return result
68 },
69 operation: { [configuration = configuration()] in 59 operation: { [configuration = configuration()] in
70 let localEvents = Self.localOwnershipHistory( 60 let localEvents = Self.localOwnershipHistory(
71 domain: normalizedDomain, 61 domain: normalizedDomain,
@@ -73,7 +63,7 @@ actor ExternalDataService {
73 historyEntries: historyEntries 63 historyEntries: historyEntries
74 ) 64 )
75 let externalEvents = await self.fetchOwnershipHistory(domain: normalizedDomain, configuration: configuration) 65 let externalEvents = await self.fetchOwnershipHistory(domain: normalizedDomain, configuration: configuration)
76 return .ownershipHistory(Self.mergeOwnershipHistory(localEvents: localEvents, externalEvents: externalEvents)) 66 return Self.mergeOwnershipHistory(localEvents: localEvents, externalEvents: externalEvents)
77 } 67 }
78 ) 68 )
79 } 69 }
@@ -87,10 +77,6 @@ actor ExternalDataService {
87 return await execute( 77 return await execute(
88 key: .dnsHistory(normalizedDomain), 78 key: .dnsHistory(normalizedDomain),
89 rateLimitBucket: .history, 79 rateLimitBucket: .history,
90 extract: { payload in
91 guard case let .dnsHistory(result) = payload else { return nil }
92 return result
93 },
94 operation: { [configuration = configuration()] in 80 operation: { [configuration = configuration()] in
95 let localEvents = Self.localDNSHistory( 81 let localEvents = Self.localDNSHistory(
96 domain: normalizedDomain, 82 domain: normalizedDomain,
@@ -98,7 +84,7 @@ actor ExternalDataService {
98 historyEntries: historyEntries 84 historyEntries: historyEntries
99 ) 85 )
100 let externalEvents = await self.fetchDNSHistory(domain: normalizedDomain, configuration: configuration) 86 let externalEvents = await self.fetchDNSHistory(domain: normalizedDomain, configuration: configuration)
101 return .dnsHistory(Self.mergeDNSHistory(localEvents: localEvents, externalEvents: externalEvents)) 87 return Self.mergeDNSHistory(localEvents: localEvents, externalEvents: externalEvents)
102 } 88 }
103 ) 89 )
104 } 90 }
@@ -111,10 +97,6 @@ actor ExternalDataService {
111 return await execute( 97 return await execute(
112 key: .extendedSubdomains(normalizedDomain), 98 key: .extendedSubdomains(normalizedDomain),
113 rateLimitBucket: .subdomains, 99 rateLimitBucket: .subdomains,
114 extract: { payload in
115 guard case let .extendedSubdomains(result) = payload else { return nil }
116 return result
117 },
118 operation: { [configuration = configuration()] in 100 operation: { [configuration = configuration()] in
119 var merged = existing 101 var merged = existing
120 switch await SubdomainDiscoveryService.discover(for: normalizedDomain, limit: 100) { 102 switch await SubdomainDiscoveryService.discover(for: normalizedDomain, limit: 100) {
@@ -131,43 +113,44 @@ actor ExternalDataService {
131 } 113 }
132 114
133 if merged.count <= existing.count { 115 if merged.count <= existing.count {
134 return .extendedSubdomains(.empty("No extended subdomains available")) 116 return .empty("No extended subdomains available")
135 } 117 }
136 118
137 let onlyExtended = merged.filter(\.isExtended) 119 let onlyExtended = merged.filter(\.isExtended)
138 return .extendedSubdomains(.success(onlyExtended.sorted { $0.hostname < $1.hostname })) 120 return .success(onlyExtended.sorted { $0.hostname < $1.hostname })
139 } 121 }
140 ) 122 )
141 } 123 }
142 124
143 private func execute<T>( 125 /// Generic over the value rather than over an enum of every payload kind.
126 /// The previous shape stored that enum and handed each caller a closure to
127 /// pull its own case back out, which trapped when the two disagreed; the
128 /// live path here has no cast at all, so the mismatch cannot arise. A
129 /// cached or in-flight value of the wrong type falls through to a fetch
130 /// instead of ending the process.
131 private func execute<T: Sendable>(
144 key: RequestKey, 132 key: RequestKey,
145 rateLimitBucket: RateLimitBucket, 133 rateLimitBucket: RateLimitBucket,
146 extract: @escaping (CachedPayload) -> T?, 134 operation: @escaping @Sendable () async -> T
147 operation: @escaping @Sendable () async -> CachedPayload
148 ) async -> CachedLookupResult<T> { 135 ) async -> CachedLookupResult<T> {
149 if let cachedEntry = cache[key], cachedEntry.expiresAt > Date(), let value = extract(cachedEntry.payload) { 136 if let cachedEntry = cache[key], cachedEntry.expiresAt > Date(), let value = cachedEntry.value as? T {
150 return CachedLookupResult(value: value, source: .cached) 137 return CachedLookupResult(value: value, source: .cached)
151 } 138 }
152 139
153 if let task = inFlight[key], let value = extract(await task.value) { 140 if let task = inFlight[key], let value = await task.value as? T {
154 return CachedLookupResult(value: value, source: .mixed) 141 return CachedLookupResult(value: value, source: .mixed)
155 } 142 }
156 143
157 let task = Task<CachedPayload, Never> { 144 let task = Task<T, Never> {
158 await self.enforceRateLimit(for: rateLimitBucket) 145 await self.enforceRateLimit(for: rateLimitBucket)
159 return await operation() 146 return await operation()
160 } 147 }
161 inFlight[key] = task 148 inFlight[key] = Task { await task.value as any Sendable }
162 149
163 let payload = await task.value 150 let value = await task.value
164 cache[key] = CacheEntry(payload: payload, expiresAt: Date().addingTimeInterval(ttl)) 151 cache[key] = CacheEntry(value: value, expiresAt: Date().addingTimeInterval(ttl))
165 inFlight[key] = nil 152 inFlight[key] = nil
166 153
167 guard let value = extract(payload) else {
168 fatalError("ExternalDataService payload extraction mismatch")
169 }
170
171 return CachedLookupResult(value: value, source: .live) 154 return CachedLookupResult(value: value, source: .live)
172 } 155 }
173 156