Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Packages/SPMailCore/Tests/SPMailCoreTests/FakeMailServer.swift3// Description: Test double of the SP Mail JMAP gateway behind a stub URLProtocol — an in-memory mailbox (Mailbox, Email, Thread, EmailSubmission,4// changes log, blobs, EventSource) with failure injection: lost responses after the server acted, 5xx bursts, method errors, refused patches.5// One instance per test, routed by host name, so suites can run in parallel. It models the JMAP semantics the sync core relies on — not Stalwart.6import Foundation7@testable import SPMailCore89/// What the stub answers instead of (or after) doing the work.10enum Fault: Sendable {11 /// The request never reaches the server.12 case unreachable13 /// The server does the work, then the connection drops before the answer arrives.14 case lostResponse15 /// The gateway answers with this HTTP status without doing anything.16 case status(Int)17 /// The named method answers with a JMAP method-level error; the other calls of the request run normally.18 case methodError(method: String, type: String)19}2021final class FakeMailServer: @unchecked Sendable {22 struct Request: Sendable {23 let path: String; let methods: [String]; let headers: [String: String]; let body: JSONValue24 /// The request body mentions this text (an id, a property name…).25 func mentions(_ s: String) -> Bool { (try? body.data()).map { String(decoding: $0, as: UTF8.self).contains(s) } ?? false }26 }2728 let host = "fake-\(UUID().uuidString.lowercased()).test"29 let accountId = "acc"30 let address: String31 private let lock = NSRecursiveLock()32 private var mailboxes: [String: JSONValue] = [:]33 private var emails: [String: JSONValue] = [:]34 private var log: [(state: Int, id: String, kind: String)] = []35 private var emailState = 136 private var mailboxState = 137 private var counter = 038 private var submissions: [String: JSONValue] = [:]39 private var blobs: [String: Data] = [:]40 private var identities: [JSONValue] = []41 private(set) var requests: [Request] = []42 private var clock = Date(timeIntervalSince1970: 1_800_000_000)4344 // ---- knobs45 /// Decides the fate of each request: (request, 1-based index among requests carrying the same first method) → fault.46 var fault: (@Sendable (Request, Int) -> Fault?)?47 var supportsAnchor = true48 var supportsHeaderFilter = true49 /// The header filter is accepted but matches nothing — what the real mail server does for Message-ID (observed 2026-11-20).50 var headerFilterFindsNothing = false51 var supportsSubmissionQuery = true52 /// Email id → SetError type answered to any update of that message.53 var refusedUpdates: [String: String] = [:]54 /// SetError type answered to every EmailSubmission create.55 var submissionError: String?56 /// Events sent on each EventSource connection (index = connection number, last entry repeats), then the stream closes.57 var eventScript: [[String]] = [[]]58 /// Keep EventSource connections open after their script instead of closing them.59 var holdEventStreams = false60 /// Seconds a request waits AFTER the server did the work, before its answer leaves.61 var delay: (@Sendable (Request) -> Double)?6263 init(address: String = "moi@stg.spboucher.ai") {64 self.address = address65 for (id, role) in [("in", "inbox"), ("dr", "drafts"), ("se", "sent"), ("tr", "trash"), ("ju", "junk")] {66 mailboxes[id] = ["id": .string(id), "name": .string(role.capitalized), "role": .string(role), "sortOrder": 0]67 }68 identities = [["id": "ident", "name": "Moi", "email": .string(address)]]69 FakeRouter.register(self)70 }71 deinit { FakeRouter.unregister(host) }7273 var baseURL: URL { URL(string: "http://\(host)")! }74 func api() -> APIClient { APIClient(baseURL: baseURL, token: "t", userAgent: "tests", protocolClasses: [FakeRouter.self]) }75 func engine(_ store: MailStore, account: String = "A", configure: (inout SyncEngine.Configuration) -> Void = { _ in }) -> SyncEngine {76 var c = SyncEngine.Configuration()77 c.autoPrefetch = false78 c.backoff = Backoff(base: 0.05, factor: 1, maximum: 0.05, jitter: 0)79 configure(&c)80 return SyncEngine(account: account, address: address, api: api(), store: store, configuration: c)81 }8283 // ---- inspection and direct manipulation ("another client did this")84 func sync<T>(_ body: () -> T) -> T { lock.lock(); defer { lock.unlock() }; return body() }85 func count(_ method: String) -> Int { sync { requests.reduce(0) { $0 + $1.methods.filter { $0 == method }.count } } }86 func paths(containing s: String) -> [Request] { sync { requests.filter { $0.path.contains(s) } } }87 var allEmails: [JSONValue] { sync { Array(emails.values) } }88 func email(_ id: String) -> JSONValue? { sync { emails[id] } }89 func emails(in box: String) -> [JSONValue] { sync { emails.values.filter { $0["mailboxIds"][box].boolValue == true } } }90 var submissionCount: Int { sync { submissions.count } }91 var currentEmailState: String { sync { String(emailState) } }92 func stateEvent(id: String? = nil) -> String {93 let data = #"{"@type":"StateChange","changed":{"\#(accountId)":{"Email":"\#(sync { emailState })","Mailbox":"\#(sync { mailboxState })"}}}"#94 return (id.map { "id: \($0)\n" } ?? "") + "event: state\ndata: \(data)\n\n"95 }9697 private func record(_ id: String, _ kind: String) { emailState += 1; log.append((emailState, id, kind)) }98 private func recount() {99 for (id, var m) in mailboxes {100 let inside = emails.values.filter { $0["mailboxIds"][id].boolValue == true }101 m["totalEmails"] = JSONValue(inside.count)102 m["unreadEmails"] = JSONValue(inside.filter { $0["keywords"]["$seen"].boolValue != true }.count)103 if m != mailboxes[id] { mailboxes[id] = m; mailboxState += 1 }104 }105 }106107 /// Puts a message straight into a folder, as delivery would.108 @discardableResult109 func seed(_ subject: String, box: String = "in", at date: Date? = nil, thread: String? = nil, keywords: [String] = [], html: String? = nil, text: String = "corps", attachments: [JSONValue] = [], messageId: String? = nil) -> String {110 sync {111 counter += 1112 clock = clock.addingTimeInterval(60)113 let id = "m\(counter)"114 var e: JSONValue = ["id": .string(id), "blobId": .string("blob-\(id)"), "threadId": .string(thread ?? "t-\(id)"), "mailboxIds": [box: true],115 "keywords": .object(Dictionary(uniqueKeysWithValues: keywords.map { ($0, JSONValue.bool(true)) })), "size": 100,116 "receivedAt": .string(ISODate.string(date ?? clock)), "messageId": [.string(messageId ?? "\(id)@fake")], "from": [["name": "Alice", "email": "alice@example.org"]],117 "to": [["email": .string(address)]], "subject": .string(subject), "hasAttachment": .bool(!attachments.isEmpty), "preview": .string(String(text.prefix(80))),118 "textBody": [["partId": "t", "type": "text/plain"]], "bodyValues": ["t": ["value": .string(text)]], "attachments": .array(attachments)]119 if let html { e["htmlBody"] = [["partId": "h", "type": "text/html"]]; e["bodyValues"]["h"] = ["value": .string(html)] }120 emails[id] = e121 record(id, "created")122 recount()123 return id124 }125 }126 func destroy(_ id: String) { sync { if emails.removeValue(forKey: id) != nil { record(id, "destroyed"); recount() } } }127 func patch(_ id: String, _ p: JSONValue) { sync { if let e = emails[id] { emails[id] = Self.apply(p, to: e); record(id, "updated"); recount() } } }128 func addBlob(_ id: String, _ data: Data) { sync { blobs[id] = data } }129 /// Forgets the change log: every `Email/changes` from an older state answers `cannotCalculateChanges`.130 func forgetHistory() { sync { log.removeAll(); emailState += 100 } }131132 static func apply(_ patch: JSONValue, to email: JSONValue) -> JSONValue {133 var e = email134 for (k, v) in (patch.objectValue ?? [:]).sorted(by: { $0.key.count < $1.key.count }) {135 if k == "mailboxIds" || k == "keywords" { e[k] = v; continue }136 for prop in ["mailboxIds", "keywords"] where k.hasPrefix(prop + "/") {137 var o = e[prop].objectValue ?? [:]138 let key = String(k.dropFirst(prop.count + 1))139 if v.boolValue == true { o[key] = true } else { o[key] = nil }140 e[prop] = .object(o)141 }142 }143 return e144 }145146 // ---- HTTP entry point147 enum Response { case json(Int, JSONValue), data(Int, Data), fail(URLError.Code), stream([Data], keepOpen: Bool) }148149 func handle(_ req: URLRequest, body: Data?) -> Response {150 lock.lock(); defer { lock.unlock() }151 let path = req.url?.path ?? ""152 let json = body.flatMap { try? JSONValue.parse($0) } ?? .null153 let methods = (json["methodCalls"].arrayValue ?? []).compactMap { $0[0].stringValue }154 let r = Request(path: path, methods: methods, headers: req.allHTTPHeaderFields ?? [:], body: json)155 requests.append(r)156 let nth = requests.filter { $0.methods.first == methods.first && ($0.path.hasSuffix("/api") == path.hasSuffix("/api")) }.count157 var forced: (String, String)?158 var lost = false159 switch fault?(r, nth) {160 case .unreachable?: return .fail(.notConnectedToInternet)161 case .status(let s)?: return .json(s, ["error": .string("http_\(s)")])162 case .methodError(let m, let t)?: forced = (m, t)163 case .lostResponse?: lost = true164 case nil: break165 }166 var answer: Response167 if path.hasSuffix("/session") {168 answer = .json(200, ["username": .string(address), "state": "s", "primaryAccounts": ["urn:ietf:params:jmap:mail": .string(accountId)],169 "capabilities": ["urn:ietf:params:jmap:core": ["maxCallsInRequest": 16, "maxObjectsInGet": 500, "maxSizeUpload": 50_000_000], "urn:ietf:params:jmap:mail": [:]]])170 } else if path.hasSuffix("/eventsource") {171 let n = requests.filter { $0.path.hasSuffix("/eventsource") }.count - 1172 let script = eventScript.isEmpty ? [] : eventScript[min(n, eventScript.count - 1)]173 answer = .stream(script.map { Data($0.utf8) }, keepOpen: holdEventStreams)174 } else if path.contains("/upload/") {175 counter += 1176 let id = "up\(counter)"177 blobs[id] = body ?? Data()178 answer = .json(200, ["blobId": .string(id), "size": JSONValue(body?.count ?? 0)])179 } else if path.contains("/download/") {180 let parts = path.components(separatedBy: "/")181 let blob = parts.count >= 2 ? parts[parts.count - 2] : ""182 answer = blobs[blob].map { .data(200, $0) } ?? .json(404, ["error": "not_found"])183 } else {184 var results: [JSONValue] = []185 var byCall: [String: (String, JSONValue)] = [:]186 var createdIds: [String: String] = [:]187 for call in json["methodCalls"].arrayValue ?? [] {188 guard let name = call[0].stringValue, let callId = call[2].stringValue else { continue }189 var args = call[1]190 var failed: String?191 for (k, v) in args.objectValue ?? [:] where k.hasPrefix("#") { // result references192 guard let prev = v["resultOf"].stringValue.flatMap({ byCall[$0] }), prev.0 == v["name"].stringValue, let p = v["path"].stringValue else { failed = "invalidResultReference"; continue }193 args[String(k.dropFirst())] = prev.1[String(p.dropFirst())]194 args[k] = nil195 }196 if let f = forced, f.0 == name { failed = f.1 }197 if let failed { results.append(["error", ["type": .string(failed)], .string(callId)]); byCall[callId] = ("error", .null); continue }198 let out = method(name, args, &createdIds)199 for (n, a) in out { results.append([.string(n), a, .string(callId)]) }200 if let first = out.first { byCall[callId] = first }201 }202 answer = .json(200, ["methodResponses": .array(results), "sessionState": "s"])203 }204 if let d = delay?(r), d > 0 { lock.unlock(); usleep(UInt32(d * 1_000_000)); lock.lock() }205 return lost ? .fail(.networkConnectionLost) : answer206 }207208 // ---- JMAP methods209 private func sortedIds(_ filter: JSONValue) -> [String] {210 func matches(_ e: JSONValue, _ f: JSONValue) -> Bool {211 if let op = f["operator"].stringValue {212 let cs = (f["conditions"].arrayValue ?? []).map { matches(e, $0) }213 return op == "OR" ? cs.contains(true) : op == "NOT" ? !cs.contains(true) : !cs.contains(false)214 }215 if let b = f["inMailbox"].stringValue, e["mailboxIds"][b].boolValue != true { return false }216 if let before = ISODate.parse(f["before"].stringValue), let d = ISODate.parse(e["receivedAt"].stringValue), d >= before { return false }217 if let h = f["header"].arrayValue, h.count == 2, h[0].stringValue?.lowercased() == "message-id", !e["messageId"].stringArray.contains(where: { $0.contains(h[1].stringValue ?? "\u{0}") }) { return false }218 if let t = f["text"].stringValue, !(e["subject"].stringValue ?? "").localizedCaseInsensitiveContains(t) { return false }219 if let k = f["hasKeyword"].stringValue, e["keywords"][k].boolValue != true { return false }220 if let k = f["notKeyword"].stringValue, e["keywords"][k].boolValue == true { return false }221 return true222 }223 return emails.values.filter { matches($0, filter) }224 .sorted { (ISODate.parse($0["receivedAt"].stringValue)!, $0["id"].stringValue!) > (ISODate.parse($1["receivedAt"].stringValue)!, $1["id"].stringValue!) }225 .compactMap { $0["id"].stringValue }226 }227228 private func method(_ name: String, _ args: JSONValue, _ createdIds: inout [String: String]) -> [(String, JSONValue)] {229 func err(_ type: String) -> [(String, JSONValue)] { [("error", ["type": .string(type)])] }230 switch name {231 case "Mailbox/get": return [(name, ["accountId": .string(accountId), "state": .string(String(mailboxState)), "list": .array(mailboxes.values.sorted { $0["id"].stringValue! < $1["id"].stringValue! }), "notFound": []])]232 case "Mailbox/changes": return [(name, ["oldState": args["sinceState"], "newState": .string(String(mailboxState)), "hasMoreChanges": false, "created": [], "updated": [], "destroyed": []])]233 case "Mailbox/set":234 var created: JSONValue = [:]235 for (cid, m) in args["create"].objectValue ?? [:] {236 counter += 1237 let id = "box\(counter)"238 var box = m; box["id"] = .string(id)239 mailboxes[id] = box; mailboxState += 1240 created[cid] = ["id": .string(id)]241 }242 return [(name, ["created": created])]243 case "Identity/get": return [(name, ["list": .array(identities), "state": "i"])]244 case "Identity/set": return [(name, ["created": [:]])]245 case "Email/query":246 if args["filter"]["header"].arrayValue != nil, !supportsHeaderFilter { return err("unsupportedFilter") }247 let ids = args["filter"]["header"].arrayValue != nil && headerFilterFindsNothing ? [] : sortedIds(args["filter"])248 var start = args["position"].intValue ?? 0249 if let anchor = args["anchor"].stringValue {250 guard supportsAnchor else { return err("invalidArguments") }251 guard let i = ids.firstIndex(of: anchor) else { return err("anchorNotFound") }252 start = max(0, i + (args["anchorOffset"].intValue ?? 0))253 }254 let limit = args["limit"].intValue ?? 256255 let page = start < ids.count ? Array(ids[start..<min(ids.count, start + limit)]) : []256 return [(name, ["ids": JSONValue(page), "position": JSONValue(start), "queryState": "q", "total": JSONValue(ids.count)])]257 case "Email/get":258 let ids = args["ids"].stringArray259 return [(name, ["accountId": .string(accountId), "state": .string(String(emailState)), "list": .array(ids.compactMap { emails[$0] }), "notFound": JSONValue(ids.filter { emails[$0] == nil })])]260 case "Email/changes":261 guard let since = args["sinceState"].stringValue.flatMap(Int.init), since <= emailState, since >= (log.first?.state ?? emailState) - 1 else { return err("cannotCalculateChanges") }262 let pending = log.filter { $0.state > since }263 let maxChanges = args["maxChanges"].intValue ?? 500264 var taken: [(state: Int, id: String, kind: String)] = [], seen = Set<String>()265 for entry in pending {266 if !seen.contains(entry.id), seen.count >= maxChanges { break }267 seen.insert(entry.id); taken.append(entry)268 }269 let more = taken.count < pending.count270 let newState = more ? (taken.last?.state ?? since) : emailState271 var created: [String] = [], updated: [String] = [], destroyed: [String] = []272 for id in seen.sorted() {273 let kinds = taken.filter { $0.id == id }.map(\.kind)274 let wasCreated = kinds.contains("created"), gone = kinds.last == "destroyed"275 if gone { if !wasCreated { destroyed.append(id) } } else if wasCreated { created.append(id) } else { updated.append(id) }276 }277 return [(name, ["oldState": .string(String(since)), "newState": .string(String(newState)), "hasMoreChanges": .bool(more), "created": JSONValue(created), "updated": JSONValue(updated), "destroyed": JSONValue(destroyed)])]278 case "Email/set":279 var created: JSONValue = [:], updated: JSONValue = [:], notUpdated: JSONValue = [:], notDestroyed: JSONValue = [:]280 var destroyed: [String] = []281 for (cid, e) in args["create"].objectValue ?? [:] {282 counter += 1283 clock = clock.addingTimeInterval(60)284 let id = "c\(counter)"285 var mail = e286 mail["id"] = .string(id); mail["blobId"] = .string("blob-\(id)"); mail["size"] = 200287 mail["receivedAt"] = .string(ISODate.string(clock))288 if mail["messageId"].isNull { mail["messageId"] = [.string("\(id)@server")] }289 let parent = mail["inReplyTo"].stringArray.first290 mail["threadId"] = .string(emails.values.first { parent != nil && $0["messageId"].stringArray.contains(parent!) }?["threadId"].stringValue ?? "t-\(id)")291 mail["preview"] = .string(String((mail["bodyValues"]["t"]["value"].stringValue ?? "").prefix(80)))292 mail["hasAttachment"] = .bool(!(mail["attachments"].arrayValue ?? []).isEmpty)293 emails[id] = mail294 createdIds[cid] = id295 record(id, "created")296 created[cid] = ["id": .string(id), "blobId": mail["blobId"], "threadId": mail["threadId"], "size": 200]297 }298 for (id, p) in args["update"].objectValue ?? [:] {299 if let type = refusedUpdates[id] { notUpdated[id] = ["type": .string(type), "description": "refused by the test"]; continue }300 guard let e = emails[id] else { notUpdated[id] = ["type": "notFound"]; continue }301 if (p.objectValue ?? [:]).keys.contains(where: { !$0.hasPrefix("keywords") && !$0.hasPrefix("mailboxIds") }) { notUpdated[id] = ["type": "invalidPatch"]; continue }302 emails[id] = Self.apply(p, to: e)303 record(id, "updated")304 updated[id] = nil305 }306 for id in args["destroy"].stringArray {307 if emails.removeValue(forKey: id) != nil { destroyed.append(id); record(id, "destroyed") } else { notDestroyed[id] = ["type": "notFound"] }308 }309 recount()310 return [(name, ["created": created, "updated": updated, "destroyed": JSONValue(destroyed), "notCreated": [:], "notUpdated": notUpdated, "notDestroyed": notDestroyed, "newState": .string(String(emailState))])]311 case "EmailSubmission/set":312 var created: JSONValue = [:], notCreated: JSONValue = [:]313 var out: [(String, JSONValue)] = []314 var implicit: JSONValue = [:]315 for (cid, s) in args["create"].objectValue ?? [:] {316 var emailId = s["emailId"].stringValue ?? ""317 if emailId.hasPrefix("#") { emailId = createdIds[String(emailId.dropFirst())] ?? "" }318 if let submissionError { notCreated[cid] = ["type": .string(submissionError), "description": "refused by the test"]; continue }319 guard let mail = emails[emailId] else { notCreated[cid] = ["type": "invalidProperties", "description": "no such email"]; continue }320 counter += 1321 let id = "sub\(counter)"322 var status: JSONValue = [:]323 for r in (mail["to"].arrayValue ?? []) + (mail["cc"].arrayValue ?? []) { if let a = r["email"].stringValue { status[a] = ["delivered": "queued", "smtpReply": "250 queued"] } }324 submissions[id] = ["id": .string(id), "emailId": .string(emailId), "undoStatus": "final", "deliveryStatus": status]325 created[cid] = ["id": .string(id)]326 if let p = args["onSuccessUpdateEmail"]["#\(cid)"].objectValue { emails[emailId] = Self.apply(.object(p), to: mail); record(emailId, "updated"); implicit[emailId] = nil }327 }328 recount()329 out.append((name, ["created": created, "notCreated": notCreated]))330 if !(implicit.objectValue ?? [:]).isEmpty { out.append(("Email/set", ["updated": implicit])) }331 return out332 case "EmailSubmission/query":333 guard supportsSubmissionQuery else { return err("unknownMethod") }334 let wanted = Set(args["filter"]["emailIds"].stringArray)335 return [(name, ["ids": JSONValue(submissions.values.filter { wanted.contains($0["emailId"].stringValue ?? "") }.compactMap { $0["id"].stringValue }.sorted())])]336 case "EmailSubmission/get":337 let ids = args["ids"].stringArray338 return [(name, ["list": .array(ids.compactMap { submissions[$0] }), "notFound": []])]339 case "Thread/get":340 let list: [JSONValue] = args["ids"].stringArray.map { tid in341 let members = emails.values.filter { $0["threadId"].stringValue == tid }.sorted { ISODate.parse($0["receivedAt"].stringValue)! < ISODate.parse($1["receivedAt"].stringValue)! }342 return ["id": .string(tid), "emailIds": JSONValue(members.compactMap { $0["id"].stringValue })]343 }344 return [(name, ["list": .array(list), "notFound": []])]345 default: return err("unknownMethod")346 }347 }348}349350/// Routes every request of a stubbed session to the `FakeMailServer` registered for its host.351final class FakeRouter: URLProtocol, @unchecked Sendable {352 private static let lock = NSLock()353 nonisolated(unsafe) private static var servers: [String: () -> FakeMailServer?] = [:]354 static func register(_ s: FakeMailServer) { lock.withLock { servers[s.host] = { [weak s] in s } } }355 static func unregister(_ host: String) { lock.withLock { servers[host] = nil } }356 final class Flag: @unchecked Sendable { private let lock = NSLock(); private var v = false; var isSet: Bool { lock.withLock { v } }; func set() { lock.withLock { v = true } } }357 private let stopped = Flag()358359 override class func canInit(with request: URLRequest) -> Bool { true }360 override class func canonicalRequest(for request: URLRequest) -> URLRequest { request }361 override func startLoading() {362 var body = request.httpBody363 if body == nil, let s = request.httpBodyStream {364 s.open(); var d = Data(); var buf = [UInt8](repeating: 0, count: 65536)365 while s.hasBytesAvailable { let n = s.read(&buf, maxLength: buf.count); if n <= 0 { break }; d.append(buf, count: n) }366 s.close(); body = d367 }368 let server = Self.lock.withLock { Self.servers[request.url?.host ?? ""]?() }369 nonisolated(unsafe) let me = self370 let flag = stopped371 let req = request372 DispatchQueue.global().async {373 guard let client = me.client else { return }374 guard let server else { client.urlProtocol(me, didFailWithError: URLError(.cannotFindHost)); return }375 func head(_ status: Int, _ type: String) { client.urlProtocol(me, didReceive: HTTPURLResponse(url: req.url!, statusCode: status, httpVersion: "HTTP/1.1", headerFields: ["Content-Type": type])!, cacheStoragePolicy: .notAllowed) }376 switch server.handle(req, body: body) {377 case .fail(let code): client.urlProtocol(me, didFailWithError: URLError(code))378 case .json(let status, let j):379 head(status, "application/json")380 client.urlProtocol(me, didLoad: (try? j.data()) ?? Data())381 client.urlProtocolDidFinishLoading(me)382 case .data(let status, let d):383 head(status, "application/octet-stream")384 client.urlProtocol(me, didLoad: d)385 client.urlProtocolDidFinishLoading(me)386 case .stream(let chunks, let keepOpen):387 head(200, "text/event-stream")388 for c in chunks {389 usleep(20_000)390 if flag.isSet { return }391 client.urlProtocol(me, didLoad: c)392 }393 usleep(60_000)394 if !keepOpen, !flag.isSet { client.urlProtocolDidFinishLoading(me) }395 }396 }397 }398 override func stopLoading() { stopped.set() }399}400401/// Polls until `body` returns a value (unit tests against the fake server: short timeout).402func eventually<T: Sendable>(_ what: String, timeout: Double = 5, _ body: @Sendable () async throws -> T?) async throws -> T {403 let end = Date().addingTimeInterval(timeout)404 while Date() < end {405 if let v = try await body() { return v }406 try await Task.sleep(for: .milliseconds(20))407 }408 throw Timeout(description: "timed out waiting for: \(what)")409}410