Repository Public
1import Foundation23/// A small async/await client of the SP Mail REST API (`https://mail.spboucher.ai/api/v1`). Foundation only.4///5/// Keep the API key out of an app bundle shipped to third parties: a key is a server-side secret. In an app of your own,6/// store it in the Keychain and use a key restricted to one sending address with `mail.send` only.7public final class SPMailClient: Sendable {8 public let baseURL: URL9 private let apiKey: String10 private let session: URLSession11 private let maxRetries: Int1213 /// - Parameters:14 /// - apiKey: `spm_<prefix>_<secret>`.15 /// - baseURL: origin of the instance; `/api/v1` is appended when missing.16 /// - session: inject a session (tests, custom configuration). Redirects are never followed with the default one.17 /// - maxRetries: retries for retryable failures (429, 502/503/504, network) of idempotent requests.18 public init(apiKey: String, baseURL: URL = URL(string: "https://mail.spboucher.ai")!, session: URLSession? = nil, maxRetries: Int = 2) throws {19 let key = apiKey.trimmingCharacters(in: .whitespacesAndNewlines)20 guard !key.isEmpty else { throw SPMailError.configuration("apiKey is empty (read it from the Keychain or from SPMAIL_API_KEY)") }21 var base = baseURL.absoluteString22 while base.hasSuffix("/") { base.removeLast() }23 if !base.hasSuffix("/api/v1") { base += "/api/v1" }24 guard let url = URL(string: base), let scheme = url.scheme, let host = url.host, scheme == "https" || scheme == "http" else {25 throw SPMailError.configuration("baseURL must be an http(s) URL")26 }27 if scheme == "http" && !["localhost", "127.0.0.1", "::1"].contains(host) {28 throw SPMailError.configuration("refusing a plain http base URL: the API key would travel in clear")29 }30 self.apiKey = key31 self.baseURL = url32 self.maxRetries = max(0, maxRetries)33 if let session {34 self.session = session35 } else {36 let cfg = URLSessionConfiguration.ephemeral37 cfg.timeoutIntervalForRequest = 3038 cfg.httpCookieStorage = nil39 cfg.urlCache = nil40 self.session = URLSession(configuration: cfg, delegate: NoRedirect(), delegateQueue: nil)41 }42 }4344 // MARK: Introspection4546 /// Scopes, usable addresses and limits of this key.47 public func me() async throws -> Me { try await call("GET", "/me") }4849 // MARK: Sending5051 /// Sends a message. Check `status`: `.sent`, `.scheduled`, or `.pendingApproval` — in which case NOTHING was sent52 /// and the owner must approve in SP Mail. An `Idempotency-Key` is generated per call, so the built-in retries can53 /// never duplicate a message; pass your own key to make a retry of your app idempotent too.54 public func send(_ request: SendRequest, idempotencyKey: String? = nil) async throws -> OutboundMessage {55 try await call("POST", "/messages/send", body: request, idempotencyKey: idempotencyKey ?? Self.newIdempotencyKey())56 }5758 /// Sends a template of the owner's library, rendered with `variables`.59 public func sendTemplate(_ templateID: String, from: String, to: [Recipient], variables: [String: String], subject: String? = nil,60 idempotencyKey: String? = nil) async throws -> OutboundMessage {61 try await send(SendRequest(from: from, to: to, subject: subject, templateID: templateID, variables: variables), idempotencyKey: idempotencyKey)62 }6364 /// Replies to a message; recipients and threading headers come from the original.65 public func reply(to messageID: String, _ request: ReplyRequest, idempotencyKey: String? = nil) async throws -> OutboundMessage {66 try await call("POST", "/messages/\(Self.escape(messageID))/reply", body: request, idempotencyKey: idempotencyKey ?? Self.newIdempotencyKey())67 }6869 /// Current status of a send, with one status per recipient.70 public func deliveryStatus(_ outboundID: String) async throws -> OutboundMessage {71 try await call("GET", "/messages/outbound/\(Self.escape(outboundID))")72 }7374 /// Polls a send until its status is final. Throws `.deliveryTimeout(last)` when `timeout` elapses first — which is75 /// what happens for a message waiting for approval.76 public func waitForDelivery(_ outboundID: String, timeout: TimeInterval = 60, interval: TimeInterval = 1.5) async throws -> OutboundMessage {77 let deadline = Date().addingTimeInterval(timeout)78 while true {79 let o = try await deliveryStatus(outboundID)80 if o.status.isFinal { return o }81 if Date().addingTimeInterval(interval) > deadline { throw SPMailError.deliveryTimeout(o) }82 try await Task.sleep(nanoseconds: UInt64(max(0.1, interval) * 1_000_000_000))83 }84 }8586 // MARK: Reading8788 /// Lists messages, newest first. Follow `nextCursor` while `hasMore`.89 public func listMessages(_ query: MessageQuery = MessageQuery()) async throws -> Page<MessageSummary> {90 try await call("GET", "/messages", query: query.items)91 }9293 /// Unread messages of the inbox (first page).94 public func listUnread(address: String? = nil, limit: Int = 25) async throws -> [MessageSummary] {95 try await listMessages(MessageQuery(address: address, folder: "inbox", unread: true, limit: limit)).data96 }9798 public func getMessage(_ id: String) async throws -> Message { try await call("GET", "/messages/\(Self.escape(id))") }99100 /// Marks a message read (or unread).101 @discardableResult102 public func markRead(_ id: String, read: Bool = true) async throws -> MessageSummary {103 try await call("PATCH", "/messages/\(Self.escape(id))", body: ["unread": !read], repeatable: true)104 }105106 // MARK: Files107108 /// Uploads raw bytes (max 50 MB) and returns a `file_…` id to pass in `SendRequest.attachments`. Never retried.109 public func uploadFile(_ data: Data, filename: String, contentType: String = "application/octet-stream", address: String? = nil) async throws -> UploadedFile {110 var q = [URLQueryItem(name: "filename", value: filename)]111 if let address { q.append(URLQueryItem(name: "address", value: address)) }112 return try await call("POST", "/files", query: q, body: Optional<Empty>.none, raw: (data, contentType))113 }114115 // MARK: Core116117 private struct Empty: Encodable {}118 private struct Envelope: Decodable {119 struct Inner: Decodable { let code: String?; let message: String? }120 let error: Inner121 }122123 static func newIdempotencyKey() -> String { "swift-\(UUID().uuidString.lowercased())" }124 static func escape(_ s: String) -> String {125 var allowed = CharacterSet.urlPathAllowed126 allowed.remove(charactersIn: "/?#")127 return s.addingPercentEncoding(withAllowedCharacters: allowed) ?? s128 }129130 private func call<T: Decodable>(_ method: String, _ path: String, query: [URLQueryItem] = [], idempotencyKey: String? = nil, repeatable: Bool = false) async throws -> T {131 try await call(method, path, query: query, body: Optional<Empty>.none, idempotencyKey: idempotencyKey, repeatable: repeatable)132 }133134 private func call<T: Decodable, B: Encodable>(_ method: String, _ path: String, query: [URLQueryItem] = [], body: B? = nil, raw: (Data, String)? = nil,135 idempotencyKey: String? = nil, repeatable: Bool = false) async throws -> T {136 guard var parts = URLComponents(string: baseURL.absoluteString + path) else { throw SPMailError.configuration("invalid path") }137 if !query.isEmpty {138 parts.queryItems = query139 // "+" must be escaped in a query value (addresses may contain it).140 parts.percentEncodedQuery = parts.percentEncodedQuery?.replacingOccurrences(of: "+", with: "%2B")141 }142 guard let url = parts.url else { throw SPMailError.configuration("invalid URL") }143 var req = URLRequest(url: url)144 req.httpMethod = method145 req.setValue("Bearer \(apiKey)", forHTTPHeaderField: "Authorization")146 req.setValue("application/json", forHTTPHeaderField: "Accept")147 if let raw {148 req.httpBody = raw.0149 req.setValue(raw.1, forHTTPHeaderField: "Content-Type")150 } else if let body {151 req.httpBody = try JSONEncoder().encode(body)152 req.setValue("application/json", forHTTPHeaderField: "Content-Type")153 }154 if let idempotencyKey { req.setValue(idempotencyKey, forHTTPHeaderField: "Idempotency-Key") }155 let safe = method == "GET" || method == "PUT" || method == "DELETE" || repeatable || idempotencyKey != nil156157 var attempt = 0158 while true {159 let data: Data, response: URLResponse160 do {161 (data, response) = try await session.data(for: req)162 } catch let e as URLError {163 if e.code == .cancelled { throw SPMailError.transport(e) }164 if safe && attempt < maxRetries { try await backoff(attempt, nil); attempt += 1; continue }165 throw SPMailError.transport(e)166 }167 guard let http = response as? HTTPURLResponse else { throw SPMailError.decoding("not an HTTP answer") }168 if (200..<300).contains(http.statusCode) {169 do { return try JSONDecoder().decode(T.self, from: data) } catch { throw SPMailError.decoding(String(describing: error)) }170 }171 let env = try? JSONDecoder().decode(Envelope.self, from: data)172 let retryAfter = http.value(forHTTPHeaderField: "Retry-After").flatMap(TimeInterval.init)173 let err = APIError(status: http.statusCode, code: env?.error.code ?? "http_error", message: env?.error.message ?? "SP Mail answered \(http.statusCode)",174 requestID: http.value(forHTTPHeaderField: "X-Request-Id"), retryAfter: retryAfter, detailsJSON: Self.details(in: data))175 if attempt < maxRetries {176 // 429 rate_limited was refused before being processed: repeating it is safe for any method.177 if http.statusCode == 429 && err.code != "daily_send_limit_exceeded" && (retryAfter ?? 0) <= 60 {178 try await backoff(attempt, retryAfter); attempt += 1; continue179 }180 if safe && ([502, 503, 504].contains(http.statusCode) || err.code == "idempotency_in_progress") {181 try await backoff(attempt, nil); attempt += 1; continue182 }183 }184 throw SPMailError.api(err)185 }186 }187188 private func backoff(_ attempt: Int, _ retryAfter: TimeInterval?) async throws {189 let cap = min(8.0, 0.5 * pow(2.0, Double(attempt)))190 let delay = retryAfter ?? (cap / 2 + Double.random(in: 0...(cap / 2)))191 try await Task.sleep(nanoseconds: UInt64(delay * 1_000_000_000))192 }193194 private static func details(in data: Data) -> String? {195 guard let root = try? JSONSerialization.jsonObject(with: data) as? [String: Any], let e = root["error"] as? [String: Any], let d = e["details"],196 JSONSerialization.isValidJSONObject(d), let out = try? JSONSerialization.data(withJSONObject: d, options: [.sortedKeys]) else { return nil }197 return String(data: out, encoding: .utf8)198 }199}200201/// Redirects are never followed: the Authorization header must not travel to another URL.202private final class NoRedirect: NSObject, URLSessionTaskDelegate, Sendable {203 func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest) async -> URLRequest? { nil }204}205206extension SPMailClient: CustomStringConvertible, CustomDebugStringConvertible {207 /// Never prints the key.208 public var description: String { "SPMailClient(\(baseURL.absoluteString))" }209 public var debugDescription: String { description }210}211