DomainDig/LookupRuntime.swift
296 lines · 10175 bytes
1import Foundation
2
3struct CachedLookupResult<Value> {
4 let value: Value
5 let source: LookupResultSource
6}
7
8actor LookupRuntime {
9 static let shared = LookupRuntime()
10
11 private let ttl: TimeInterval = 300
12
13 private enum RequestKey: Hashable {
14 case domain(String, LookupSectionKind)
15 case subject(String, LookupSectionKind)
16 }
17
18 private enum RateLimitBucket: Hashable {
19 case crtsh
20 case rdap
21 case ipGeolocation
22
23 var minimumSpacing: TimeInterval {
24 switch self {
25 case .crtsh:
26 return 1.0
27 case .rdap:
28 return 0.75
29 case .ipGeolocation:
30 return 0.75
31 }
32 }
33 }
34
35 private enum CachedPayload {
36 case dns(ServiceResult<[DNSSection]>)
37 case availability(DomainAvailabilityResult)
38 case ssl(ServiceResult<SSLCertificateInfo>)
39 case hsts(Bool?)
40 case http(ServiceResult<HTTPHeadersResult>)
41 case reachability(ServiceResult<[PortReachability]>)
42 case ownership(ServiceResult<DomainOwnership>)
43 case redirect(ServiceResult<[RedirectHop]>)
44 case subdomains(ServiceResult<[DiscoveredSubdomain]>)
45 case portScan(ServiceResult<[PortScanResult]>)
46 case email(ServiceResult<EmailSecurityResult>)
47 case ptr(ServiceResult<String>)
48 case ipGeolocation(ServiceResult<IPGeolocation>)
49 case suggestions([DomainSuggestionResult])
50 }
51
52 private struct CacheEntry {
53 let payload: CachedPayload
54 let expiresAt: Date
55 }
56
57 private var cache: [RequestKey: CacheEntry] = [:]
58 private var inFlight: [RequestKey: Task<CachedPayload, Never>] = [:]
59 private var nextAllowedAt: [RateLimitBucket: Date] = [:]
60
61 func clearCache() {
62 cache.removeAll()
63 inFlight.values.forEach { $0.cancel() }
64 inFlight.removeAll()
65 nextAllowedAt.removeAll()
66 }
67
68 func dns(domain: String) async -> CachedLookupResult<ServiceResult<[DNSSection]>> {
69 await execute(
70 key: .domain(domain, .dns),
71 extract: { payload in
72 guard case let .dns(result) = payload else { return nil }
73 return result
74 },
75 operation: {
76 .dns(await DNSLookupService.lookupAll(domain: domain))
77 }
78 )
79 }
80
81 func availability(domain: String) async -> CachedLookupResult<DomainAvailabilityResult> {
82 await execute(
83 key: .domain(domain, .availability),
84 extract: { payload in
85 guard case let .availability(result) = payload else { return nil }
86 return result
87 },
88 operation: {
89 .availability(await DomainAvailabilityService.check(domain: domain))
90 }
91 )
92 }
93
94 func ssl(domain: String) async -> CachedLookupResult<ServiceResult<SSLCertificateInfo>> {
95 await execute(
96 key: .domain(domain, .ssl),
97 extract: { payload in
98 guard case let .ssl(result) = payload else { return nil }
99 return result
100 },
101 operation: {
102 .ssl(await SSLCheckService.check(domain: domain))
103 }
104 )
105 }
106
107 func hsts(domain: String) async -> CachedLookupResult<Bool?> {
108 await execute(
109 key: .domain(domain, .hsts),
110 extract: { payload in
111 guard case let .hsts(result) = payload else { return nil }
112 return result
113 },
114 operation: {
115 .hsts(await SSLCheckService.checkHSTSPreload(domain: domain))
116 }
117 )
118 }
119
120 func http(domain: String) async -> CachedLookupResult<ServiceResult<HTTPHeadersResult>> {
121 await execute(
122 key: .domain(domain, .httpHeaders),
123 extract: { payload in
124 guard case let .http(result) = payload else { return nil }
125 return result
126 },
127 operation: {
128 .http(await HTTPHeadersService.fetch(domain: domain))
129 }
130 )
131 }
132
133 func reachability(domain: String) async -> CachedLookupResult<ServiceResult<[PortReachability]>> {
134 await execute(
135 key: .domain(domain, .reachability),
136 extract: { payload in
137 guard case let .reachability(result) = payload else { return nil }
138 return result
139 },
140 operation: {
141 .reachability(await ReachabilityService.checkAll(domain: domain))
142 }
143 )
144 }
145
146 func ownership(domain: String) async -> CachedLookupResult<ServiceResult<DomainOwnership>> {
147 await execute(
148 key: .domain(domain, .ownership),
149 rateLimitBucket: .rdap,
150 extract: { payload in
151 guard case let .ownership(result) = payload else { return nil }
152 return result
153 },
154 operation: {
155 .ownership(await DomainOwnershipService.lookup(domain: domain))
156 }
157 )
158 }
159
160 func redirectChain(domain: String) async -> CachedLookupResult<ServiceResult<[RedirectHop]>> {
161 await execute(
162 key: .domain(domain, .redirectChain),
163 extract: { payload in
164 guard case let .redirect(result) = payload else { return nil }
165 return result
166 },
167 operation: {
168 .redirect(await RedirectChainService.trace(domain: domain))
169 }
170 )
171 }
172
173 func subdomains(domain: String) async -> CachedLookupResult<ServiceResult<[DiscoveredSubdomain]>> {
174 await execute(
175 key: .domain(domain, .subdomains),
176 rateLimitBucket: .crtsh,
177 extract: { payload in
178 guard case let .subdomains(result) = payload else { return nil }
179 return result
180 },
181 operation: {
182 .subdomains(await SubdomainDiscoveryService.discover(for: domain))
183 }
184 )
185 }
186
187 func portScan(domain: String) async -> CachedLookupResult<ServiceResult<[PortScanResult]>> {
188 await execute(
189 key: .domain(domain, .portScan),
190 extract: { payload in
191 guard case let .portScan(result) = payload else { return nil }
192 return result
193 },
194 operation: {
195 .portScan(await PortScanService.scanAll(domain: domain))
196 }
197 )
198 }
199
200 func email(domain: String, txtRecords: [DNSRecord]) async -> CachedLookupResult<ServiceResult<EmailSecurityResult>> {
201 await execute(
202 key: .domain(domain, .emailSecurity),
203 extract: { payload in
204 guard case let .email(result) = payload else { return nil }
205 return result
206 },
207 operation: {
208 .email(await EmailSecurityService.analyze(domain: domain, txtRecords: txtRecords))
209 }
210 )
211 }
212
213 func ptr(ip: String, resolverURLString: String) async -> CachedLookupResult<ServiceResult<String>> {
214 await execute(
215 key: .subject("\(resolverURLString)|\(ip)", .ptr),
216 extract: { payload in
217 guard case let .ptr(result) = payload else { return nil }
218 return result
219 },
220 operation: {
221 .ptr(await ReverseDNSService.lookup(ip: ip, resolverURLString: resolverURLString))
222 }
223 )
224 }
225
226 func ipGeolocation(ip: String) async -> CachedLookupResult<ServiceResult<IPGeolocation>> {
227 await execute(
228 key: .subject(ip, .ipGeolocation),
229 rateLimitBucket: .ipGeolocation,
230 extract: { payload in
231 guard case let .ipGeolocation(result) = payload else { return nil }
232 return result
233 },
234 operation: {
235 .ipGeolocation(await IPGeolocationService.lookup(ip: ip))
236 }
237 )
238 }
239
240 func suggestions(domain: String) async -> CachedLookupResult<[DomainSuggestionResult]> {
241 await execute(
242 key: .domain(domain, .suggestions),
243 extract: { payload in
244 guard case let .suggestions(result) = payload else { return nil }
245 return result
246 },
247 operation: {
248 .suggestions(await DomainAvailabilityService.suggestions(for: domain))
249 }
250 )
251 }
252
253 private func execute<T>(
254 key: RequestKey,
255 rateLimitBucket: RateLimitBucket? = nil,
256 extract: @escaping (CachedPayload) -> T?,
257 operation: @escaping @Sendable () async -> CachedPayload
258 ) async -> CachedLookupResult<T> {
259 if let cachedEntry = cache[key], cachedEntry.expiresAt > Date(), let value = extract(cachedEntry.payload) {
260 return CachedLookupResult(value: value, source: .cached)
261 }
262
263 if let task = inFlight[key], let value = extract(await task.value) {
264 return CachedLookupResult(value: value, source: .mixed)
265 }
266
267 let task = Task<CachedPayload, Never> {
268 if let rateLimitBucket {
269 await self.enforceRateLimit(for: rateLimitBucket)
270 }
271 return await operation()
272 }
273 inFlight[key] = task
274
275 let payload = await task.value
276 cache[key] = CacheEntry(payload: payload, expiresAt: Date().addingTimeInterval(ttl))
277 inFlight[key] = nil
278
279 guard let value = extract(payload) else {
280 fatalError("LookupRuntime payload extraction mismatch")
281 }
282
283 return CachedLookupResult(value: value, source: .live)
284 }
285
286 private func enforceRateLimit(for bucket: RateLimitBucket) async {
287 let now = Date()
288 if let nextAllowed = nextAllowedAt[bucket], nextAllowed > now {
289 let delay = nextAllowed.timeIntervalSince(now)
290 if delay > 0 {
291 try? await Task.sleep(nanoseconds: UInt64(delay * 1_000_000_000))
292 }
293 }
294 nextAllowedAt[bucket] = Date().addingTimeInterval(bucket.minimumSpacing)
295 }
296}