DomainDig/LookupRuntime.swift
233 lines · 7726 bytes
1import Foundation
2
3/// Opted out of the project's MainActor default isolation: this is a plain
4/// value pair constructed inside `actor LookupRuntime`, and a MainActor-bound
5/// memberwise init cannot be called from there under Swift 6.
6nonisolated struct CachedLookupResult<Value> {
7 let value: Value
8 let source: LookupResultSource
9}
10
11/// Opting out of MainActor isolation also opted out of the implicit
12/// Sendable that globally-isolated types get, which is what lets this cross
13/// from `actor LookupRuntime` back to its callers.
14extension CachedLookupResult: Sendable where Value: Sendable {}
15
16actor LookupRuntime {
17 static let shared = LookupRuntime()
18
19 private let ttl: TimeInterval = 300
20
21 enum RequestKey: Hashable {
22 case domain(String, LookupSectionKind)
23 case subject(String, LookupSectionKind)
24 }
25
26 enum RateLimitBucket: Hashable {
27 case crtsh
28 case rdap
29 case ipGeolocation
30
31 var minimumSpacing: TimeInterval {
32 switch self {
33 case .crtsh:
34 return 1.0
35 case .rdap:
36 return 0.75
37 case .ipGeolocation:
38 return 0.75
39 }
40 }
41 }
42
43 private struct CacheEntry {
44 let value: any Sendable
45 let expiresAt: Date
46 }
47
48 private var cache: [RequestKey: CacheEntry] = [:]
49 private var inFlight: [RequestKey: Task<any Sendable, Never>] = [:]
50 private var nextAllowedAt: [RateLimitBucket: Date] = [:]
51
52 func clearCache() {
53 cache.removeAll()
54 inFlight.values.forEach { $0.cancel() }
55 inFlight.removeAll()
56 nextAllowedAt.removeAll()
57 }
58
59 func dns(domain: String) async -> CachedLookupResult<ServiceResult<[DNSSection]>> {
60 await execute(
61 key: .domain(domain, .dns),
62 operation: {
63 await DNSLookupService.lookupAll(domain: domain)
64 }
65 )
66 }
67
68 func availability(domain: String, allowsRDAP: Bool) async -> CachedLookupResult<DomainAvailabilityResult> {
69 CachedLookupResult(
70 value: await DomainAvailabilityService.check(domain: domain, allowsRDAP: allowsRDAP),
71 source: .live
72 )
73 }
74
75 func ssl(domain: String) async -> CachedLookupResult<ServiceResult<SSLCertificateInfo>> {
76 await execute(
77 key: .domain(domain, .ssl),
78 operation: {
79 await SSLCheckService.check(domain: domain)
80 }
81 )
82 }
83
84 func hsts(domain: String) async -> CachedLookupResult<Bool?> {
85 await execute(
86 key: .domain(domain, .hsts),
87 operation: {
88 await SSLCheckService.checkHSTSPreload(domain: domain)
89 }
90 )
91 }
92
93 func http(domain: String) async -> CachedLookupResult<ServiceResult<HTTPHeadersResult>> {
94 await execute(
95 key: .domain(domain, .httpHeaders),
96 operation: {
97 await HTTPHeadersService.fetch(domain: domain)
98 }
99 )
100 }
101
102 func reachability(domain: String) async -> CachedLookupResult<ServiceResult<[PortReachability]>> {
103 await execute(
104 key: .domain(domain, .reachability),
105 operation: {
106 await ReachabilityService.checkAll(domain: domain)
107 }
108 )
109 }
110
111 func ownership(domain: String) async -> CachedLookupResult<ServiceResult<DomainOwnership>> {
112 await execute(
113 key: .domain(domain, .ownership),
114 rateLimitBucket: .rdap,
115 operation: {
116 await DomainOwnershipService.lookup(domain: domain)
117 }
118 )
119 }
120
121 func redirectChain(domain: String) async -> CachedLookupResult<ServiceResult<[RedirectHop]>> {
122 await execute(
123 key: .domain(domain, .redirectChain),
124 operation: {
125 await RedirectChainService.trace(domain: domain)
126 }
127 )
128 }
129
130 func subdomains(domain: String) async -> CachedLookupResult<ServiceResult<[DiscoveredSubdomain]>> {
131 await execute(
132 key: .domain(domain, .subdomains),
133 rateLimitBucket: .crtsh,
134 operation: {
135 await SubdomainDiscoveryService.discover(for: domain)
136 }
137 )
138 }
139
140 func portScan(domain: String) async -> CachedLookupResult<ServiceResult<[PortScanResult]>> {
141 await execute(
142 key: .domain(domain, .portScan),
143 operation: {
144 await PortScanService.scanAll(domain: domain)
145 }
146 )
147 }
148
149 func email(domain: String, txtRecords: [DNSRecord]) async -> CachedLookupResult<ServiceResult<EmailSecurityResult>> {
150 await execute(
151 key: .domain(domain, .emailSecurity),
152 operation: {
153 await EmailSecurityService.analyze(domain: domain, txtRecords: txtRecords)
154 }
155 )
156 }
157
158 func ptr(ip: String, resolverURLString: String) async -> CachedLookupResult<ServiceResult<String>> {
159 await execute(
160 key: .subject("\(resolverURLString)|\(ip)", .ptr),
161 operation: {
162 await ReverseDNSService.lookup(ip: ip, resolverURLString: resolverURLString)
163 }
164 )
165 }
166
167 func ipGeolocation(ip: String) async -> CachedLookupResult<ServiceResult<IPGeolocation>> {
168 await execute(
169 key: .subject(ip, .ipGeolocation),
170 rateLimitBucket: .ipGeolocation,
171 operation: {
172 await IPGeolocationService.lookup(ip: ip)
173 }
174 )
175 }
176
177 func suggestions(domain: String) async -> CachedLookupResult<[DomainSuggestionResult]> {
178 await execute(
179 key: .domain(domain, .suggestions),
180 operation: {
181 await DomainAvailabilityService.suggestions(for: domain)
182 }
183 )
184 }
185
186 func execute<T: Sendable>(
187 key: RequestKey,
188 rateLimitBucket: RateLimitBucket? = nil,
189 operation: @escaping @Sendable () async -> T
190 ) async -> CachedLookupResult<T> {
191 if let cachedEntry = cache[key], cachedEntry.expiresAt > Date(), let value = cachedEntry.value as? T {
192 return CachedLookupResult(value: value, source: .cached)
193 }
194
195 if let task = inFlight[key], let value = await task.value as? T {
196 return CachedLookupResult(value: value, source: .mixed)
197 }
198
199 let task = Task<T, Never> {
200 if let rateLimitBucket {
201 await self.enforceRateLimit(for: rateLimitBucket)
202 }
203 return await operation()
204 }
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 }
215
216 let value = await task.value
217 cache[key] = CacheEntry(value: value, expiresAt: Date().addingTimeInterval(ttl))
218 inFlight[key] = nil
219
220 return CachedLookupResult(value: value, source: .live)
221 }
222
223 private func enforceRateLimit(for bucket: RateLimitBucket) async {
224 let now = Date()
225 if let nextAllowed = nextAllowedAt[bucket], nextAllowed > now {
226 let delay = nextAllowed.timeIntervalSince(now)
227 if delay > 0 {
228 try? await Task.sleep(nanoseconds: UInt64(delay * 1_000_000_000))
229 }
230 }
231 nextAllowedAt[bucket] = Date().addingTimeInterval(bucket.minimumSpacing)
232 }
233}