Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : SP Search iOS9// File : Core/Sources/SPSearchKit/SearchClient.swift10// Description : HTTP client of the public search API: async/await, error11// mapping, Retry-After.12// Module : SPSearchKit13// Repository : https://git.spboucher.ai/sp-search-ios14// Project Website : https://search.spboucher.ai15// Created : 2026-12-0116// Last Modified : 2026-12-0117//18// =============================================================================19// AUTHOR & PROFESSIONAL AFFILIATION20// =============================================================================21//22// Author : Simon-Pierre Boucher23// Position : Professor of Finance24// Institution : Université du Québec en Outaouais (UQO)25// Department : Département des sciences administratives26// Organization : SP Boucher27//28// Website : https://spboucher.ai29// Git : https://git.spboucher.ai30//31// =============================================================================32// OFFICIAL CONTACT DIRECTORY33// =============================================================================34//35// General : info@spboucher.ai36// Professional : contact@spboucher.ai37// Direct : simon@spboucher.ai38// Research : research@spboucher.ai39// Development : dev@spboucher.ai40// Support : support@spboucher.ai41// Security/Admin : admin@spboucher.ai42// Notifications : notifications@spboucher.ai43//44// Preferred Contact: support@spboucher.ai45//46// =============================================================================47// COPYRIGHT & INTELLECTUAL PROPERTY48// =============================================================================49//50// Copyright (c) 202651// Simon-Pierre Boucher52//53// All rights reserved where applicable.54//55// This file is governed by the applicable project license,56// copyright notices, institutional agreements and relevant law.57//58// Unless expressly authorized by the applicable license or59// rights holder, copying, redistribution, sublicensing,60// publication and commercial exploitation are not permitted.61//62// Existing third-party rights and notices remain unaffected.63//64// =============================================================================65// CONFIDENTIALITY & SECURITY66// =============================================================================67//68// Classification : Public69// Distribution : Public repository; use is governed by the project license70// Security Contact : admin@spboucher.ai71//72// Access to this source does not independently grant permission73// to redistribute or disclose confidential materials.74//75// Do not embed credentials, private keys, access tokens,76// certificates or confidential personal information.77//78// =============================================================================79// LICENSE & MAINTENANCE80// =============================================================================81//82// License : None specified (no license file in this repository)83// Maintainer : Simon-Pierre Boucher84// Technical Contact: dev@spboucher.ai85//86// =============================================================================87// END OF SP BOUCHER SOURCE HEADER88// =============================================================================8990import Foundation9192public enum SearchError: Error, Sendable, Equatable {93 /// 400: the server's own message says what is wrong with the query.94 case badRequest(message: String)95 /// 429: too many requests from this address; seconds to wait.96 case rateLimited(retryAfter: TimeInterval)97 /// 503: the engine is temporarily unable to answer.98 case unavailable(message: String?)99 case http(status: Int, message: String?)100 case offline101 case timedOut102 case network(code: Int)103 /// The answer was not the expected JSON.104 case invalidResponse105 case cancelled106}107108/// Whether an answer may come from the short-lived cache.109public enum CachePolicy: Sendable { case useCache, reload }110111public protocol SearchService: Sendable {112 func search(_ request: SearchRequest, policy: CachePolicy) async throws -> SearchResponse113 func autocomplete(_ query: String) async throws -> [Suggestion]114 func filters() async throws -> FilterCatalog115 func status() async throws -> EngineStatus116}117118extension SearchService {119 public func search(_ request: SearchRequest) async throws -> SearchResponse { try await search(request, policy: .useCache) }120}121122/// Remembers, for a while, that the server answered a V2 route as a server that does not have it.123actor APIGate {124 static let retryAfter: TimeInterval = 600125 private var missingUntil: Date?126 func useV2(now: Date = Date()) -> Bool { missingUntil.map { now >= $0 } ?? true }127 func markMissing(now: Date = Date()) { missingUntil = now.addingTimeInterval(Self.retryAfter) }128 func markPresent() { missingUntil = nil }129}130131/// Client of the public API. It speaks V2 (`/v2/search`, `/v2/autocomplete`, `/v2/filters`, `/v2/status`). When the132/// server does not know a V2 route — it answers 404, or 200 with a page that is not JSON — the same call is made on133/// its V1 equivalent and the answer is read into the same models; V2 is tried again ten minutes later. Ranking is the134/// server's in both cases: nothing is reordered or filtered here.135public struct SPSearchClient: SearchService {136 public static let searchAge: TimeInterval = 300137 public static let autocompleteAge: TimeInterval = 120138 public static let filtersAge: TimeInterval = 6 * 3_600139 public static let statusAge: TimeInterval = 60140141 public let baseURL: URL142 public let cache: ResponseCache?143 private let session: URLSession144 private let userAgent: String145 private let interfaceLanguage: String?146 private let gate = APIGate()147148 /// No cookie, no credential, no URL cache: the app keeps nothing about a search on the network side.149 public static func makeSession(protocolClasses: [AnyClass]? = nil) -> URLSession {150 let c = URLSessionConfiguration.ephemeral151 c.httpCookieStorage = nil152 c.httpShouldSetCookies = false153 c.httpCookieAcceptPolicy = .never154 c.urlCredentialStorage = nil155 c.urlCache = nil156 c.requestCachePolicy = .reloadIgnoringLocalCacheData157 c.timeoutIntervalForRequest = 15158 c.timeoutIntervalForResource = 30159 c.waitsForConnectivity = false160 if let protocolClasses { c.protocolClasses = protocolClasses }161 return URLSession(configuration: c)162 }163164 public init(baseURL: URL = Endpoint.production, session: URLSession = SPSearchClient.makeSession(), userAgent: String = "SPSearch-iOS",165 interfaceLanguage: String? = nil, cache: ResponseCache? = nil) {166 self.baseURL = baseURL; self.session = session; self.userAgent = userAgent167 self.interfaceLanguage = interfaceLanguage; self.cache = cache168 }169170 public static func decoder(_ version: APIVersion) -> JSONDecoder {171 let d = JSONDecoder()172 d.userInfo[.apiVersion] = version173 return d174 }175176 // MARK: Calls177178 public func search(_ request: SearchRequest, policy: CachePolicy) async throws -> SearchResponse {179 let response = try await versioned(SearchResponse.self, maxAge: Self.searchAge, policy: policy,180 v2: Endpoint.search(request, version: .v2, base: baseURL),181 v1: Endpoint.search(request, version: .v1, base: baseURL),182 indexVersion: \.indexVersion, cacheable: Self.cacheable)183 await cache?.noteIndexVersion(response.indexVersion)184 return response185 }186187 /// An answer that describes a passing condition of the server is not kept.188 static func cacheable(_ r: SearchResponse) -> Bool {189 !r.partial && !r.notices.contains(where: { [.partialShards, .cursorExpired, .degradedMetadata, .semanticUnavailable].contains($0) })190 }191192 public func autocomplete(_ query: String) async throws -> [Suggestion] {193 try await versioned(AutocompleteResponse.self, maxAge: Self.autocompleteAge, policy: .useCache, onDisk: false,194 v2: Endpoint.autocomplete(query, interfaceLanguage: interfaceLanguage, base: baseURL),195 v1: Endpoint.suggest(query, base: baseURL)).suggestions196 }197198 public func filters() async throws -> FilterCatalog {199 guard await gate.useV2() else { return .minimal }200 do {201 return try await get(Endpoint.filters(base: baseURL), as: FilterCatalog.self, version: .v2, maxAge: Self.filtersAge, policy: .useCache)202 } catch Missing.route {203 await gate.markMissing()204 return .minimal205 }206 }207208 public func status() async throws -> EngineStatus {209 if await gate.useV2() {210 do {211 // `index.version` of the status is not the `index_version` of a search answer (the real server counts212 // them differently: 19732 against 68 on 2026-12-01). Only search answers date the cached searches.213 return try await get(Endpoint.status(base: baseURL), as: EngineStatus.self, version: .v2, maxAge: Self.statusAge, policy: .useCache, onDisk: false)214 } catch Missing.route {215 await gate.markMissing()216 }217 }218 return EngineStatus(stats: try await stats())219 }220221 // V1 calls, kept for a server without the V2 routes.222223 public func suggest(_ query: String) async throws -> [String] {224 let all = try await get(Endpoint.suggest(query, base: baseURL), as: SuggestResponse.self, version: .v1).suggestions225 return Array(all.map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty }.prefix(8))226 }227228 public func stats() async throws -> IndexStats {229 do { return try await get(Endpoint.stats(base: baseURL), as: IndexStats.self, version: .v1) } catch Missing.route { throw SearchError.invalidResponse }230 }231232 /// Which API the client is talking at the moment (for the about screen and the tests).233 public var isUsingV2: Bool { get async { await gate.useV2() } }234235 // MARK: Transport236237 private enum Missing: Error { case route }238239 private func versioned<T: Decodable & Sendable>(_ type: T.Type, maxAge: TimeInterval, policy: CachePolicy, onDisk: Bool = true, v2: URL, v1: URL,240 indexVersion: KeyPath<T, Int>? = nil, cacheable: (@Sendable (T) -> Bool)? = nil) async throws -> T {241 if await gate.useV2() {242 do {243 return try await get(v2, as: type, version: .v2, maxAge: maxAge, policy: policy, onDisk: onDisk, indexVersion: indexVersion, cacheable: cacheable)244 } catch Missing.route {245 await gate.markMissing()246 }247 }248 do {249 return try await get(v1, as: type, version: .v1, maxAge: maxAge, policy: policy, onDisk: onDisk, indexVersion: indexVersion, cacheable: cacheable)250 } catch Missing.route {251 throw SearchError.invalidResponse252 }253 }254255 private func get<T: Decodable & Sendable>(_ url: URL, as type: T.Type, version: APIVersion, maxAge: TimeInterval = 0, policy: CachePolicy = .reload,256 onDisk: Bool = true, indexVersion: KeyPath<T, Int>? = nil, cacheable: (@Sendable (T) -> Bool)? = nil) async throws -> T {257 let key = url.absoluteString258 let decoder = Self.decoder(version)259 if policy == .useCache, maxAge > 0, let cached = await cache?.data(for: key, maxAge: maxAge), let value = try? decoder.decode(T.self, from: cached) {260 return value261 }262 var req = URLRequest(url: url)263 req.httpMethod = "GET"264 req.setValue("application/json", forHTTPHeaderField: "Accept")265 req.setValue(userAgent, forHTTPHeaderField: "User-Agent")266 if let interfaceLanguage { req.setValue(interfaceLanguage == "en" ? "en-CA, en;q=0.9, fr;q=0.5" : "fr-CA, fr;q=0.9, en;q=0.5", forHTTPHeaderField: "Accept-Language") }267 let data: Data, response: URLResponse268 do {269 do {270 (data, response) = try await session.data(for: req)271 } catch let e as URLError where e.code == .networkConnectionLost {272 // A kept-alive connection the server (or a relay) closed in the meantime: the request never arrived.273 // A GET is asked once more on a new connection before the reader is told anything.274 (data, response) = try await session.data(for: req)275 }276 } catch {277 throw Self.map(error)278 }279 guard let http = response as? HTTPURLResponse else { throw SearchError.invalidResponse }280 if http.statusCode == 404 { throw Missing.route }281 guard (200..<300).contains(http.statusCode) else { throw Self.error(status: http.statusCode, headers: http, body: data) }282 // A site that answers every unknown path with its HTML shell does not have the route.283 guard Self.looksLikeJSON(data) else { throw Missing.route }284 let value: T285 do {286 value = try decoder.decode(T.self, from: data)287 } catch {288 throw SearchError.invalidResponse289 }290 if version == .v2 { await gate.markPresent() }291 if maxAge > 0, cacheable?(value) ?? true {292 await cache?.store(data, for: key, indexVersion: indexVersion.map { value[keyPath: $0] } ?? 0, onDisk: onDisk)293 }294 return value295 }296297 static func looksLikeJSON(_ data: Data) -> Bool {298 for byte in data.prefix(64) {299 switch byte {300 case 0x20, 0x09, 0x0A, 0x0D, 0xEF, 0xBB, 0xBF: continue301 case UInt8(ascii: "{"), UInt8(ascii: "["): return true302 default: return false303 }304 }305 return false306 }307308 public static func map(_ error: Error) -> SearchError {309 if error is CancellationError { return .cancelled }310 if let e = error as? SearchError { return e }311 guard let u = error as? URLError else { return .network(code: (error as NSError).code) }312 switch u.code {313 case .cancelled: return .cancelled314 case .notConnectedToInternet, .networkConnectionLost, .dataNotAllowed, .internationalRoamingOff: return .offline315 case .timedOut: return .timedOut316 default: return .network(code: u.code.rawValue)317 }318 }319320 static func error(status: Int, headers: HTTPURLResponse, body: Data) -> SearchError {321 let message = (try? JSONDecoder().decode(APIErrorBody.self, from: body))?.error?.message.flatMap { $0.isEmpty ? nil : $0 }322 switch status {323 case 400: return .badRequest(message: message ?? "")324 case 429: return .rateLimited(retryAfter: retryAfter(headers.value(forHTTPHeaderField: "Retry-After")))325 case 503: return .unavailable(message: message)326 default: return .http(status: status, message: message)327 }328 }329330 /// Seconds form only (the API sends seconds); kept between 1 s and 2 min, 5 s when absent or unreadable.331 static func retryAfter(_ header: String?) -> TimeInterval {332 guard let h = header?.trimmingCharacters(in: .whitespaces), let s = Double(h), s.isFinite else { return 5 }333 return min(120, max(1, s))334 }335}336