Repository Public License
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : ORIX OS Automation9// File : Packages/ORIXProviderAdapters/Tests/ORIXProviderAdaptersTests/StubServer.swift10// Description : Test double for the network: a URLProtocol that replays11// scripted HTTP/SSE responses per fake host and records the12// requests it received.13// Module : ORIXProviderAdaptersTests14// Repository : https://git.spboucher.ai/orix-automation15// Created : 2026-11-2116// Last Modified : 2026-11-2117//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 : Proprietary, all rights reserved (see license file)83// License File : LICENSE84// Maintainer : Simon-Pierre Boucher85// Technical Contact: dev@spboucher.ai86//87// =============================================================================88// END OF SP BOUCHER SOURCE HEADER89// =============================================================================9091import Foundation92import Synchronization93import ORIXCore94@testable import ORIXProviderAdapters9596/// A scripted fake server. Each instance owns a unique host name, so tests can run in parallel without sharing state.97final class StubServer: Sendable {98 struct Response: Sendable {99 var status = 200100 var headers: [String: String] = ["Content-Type": "text/event-stream"]101 var chunks: [Data] = []102 /// When set, the connection fails with this error after the chunks were delivered (mid-stream disconnect).103 var failure: URLError.Code?104 }105 struct Recorded: Sendable {106 var method: String107 var path: String108 var query: String?109 var headers: [String: String]110 var body: JSONValue?111 func header(_ name: String) -> String? { headers.first { $0.key.lowercased() == name.lowercased() }?.value }112 }113 private struct State { var queue: [Response] = []; var recorded: [Recorded] = [] }114115 static let registry = Mutex<[String: StubServer]>([:])116 let host = "stub-\(UUID().uuidString.lowercased()).test"117 private let state = Mutex(State())118119 init() { Self.registry.withLock { $0[host] = self } }120 deinit { Self.registry.withLock { $0[host] = nil } }121122 var baseURL: URL { URL(string: "https://\(host)")! }123 var session: URLSession {124 let c = URLSessionConfiguration.ephemeral125 c.protocolClasses = [StubURLProtocol.self]126 return URLSession(configuration: c)127 }128 var requests: [Recorded] { state.withLock { $0.recorded } }129130 @discardableResult func enqueue(_ r: Response) -> StubServer { state.withLock { $0.queue.append(r) }; return self }131 @discardableResult func sse(_ text: String, chunkSize: Int? = nil, failure: URLError.Code? = nil) -> StubServer {132 let bytes = Array(text.utf8)133 let chunks: [Data] = chunkSize.map { n in stride(from: 0, to: bytes.count, by: n).map { Data(bytes[$0..<min($0 + n, bytes.count)]) } } ?? [Data(bytes)]134 return enqueue(Response(chunks: chunks, failure: failure))135 }136 @discardableResult func json(_ status: Int, _ body: String, headers: [String: String] = [:]) -> StubServer {137 enqueue(Response(status: status, headers: ["Content-Type": "application/json"].merging(headers) { _, b in b }, chunks: [Data(body.utf8)]))138 }139140 fileprivate func next(for request: Recorded) -> Response? {141 state.withLock { s in142 s.recorded.append(request)143 return s.queue.isEmpty ? nil : s.queue.removeFirst()144 }145 }146}147148final class StubURLProtocol: URLProtocol, @unchecked Sendable {149 override class func canInit(with request: URLRequest) -> Bool { request.url?.host?.hasSuffix(".test") == true }150 override class func canonicalRequest(for request: URLRequest) -> URLRequest { request }151 override func stopLoading() {}152153 override func startLoading() {154 guard let url = request.url, let host = url.host, let server = StubServer.registry.withLock({ $0[host] }) else {155 client?.urlProtocol(self, didFailWithError: URLError(.cannotFindHost)); return156 }157 var body = request.httpBody158 if body == nil, let stream = request.httpBodyStream {159 stream.open()160 var data = Data()161 var buffer = [UInt8](repeating: 0, count: 16 * 1024)162 while stream.hasBytesAvailable {163 let n = stream.read(&buffer, maxLength: buffer.count)164 if n <= 0 { break }165 data.append(buffer, count: n)166 }167 stream.close()168 body = data169 }170 let recorded = StubServer.Recorded(method: request.httpMethod ?? "GET", path: url.path, query: url.query,171 headers: request.allHTTPHeaderFields ?? [:], body: body.flatMap { try? JSONValue.parse($0) })172 guard let response = server.next(for: recorded) else {173 client?.urlProtocol(self, didFailWithError: URLError(.badServerResponse)); return174 }175 let http = HTTPURLResponse(url: url, statusCode: response.status, httpVersion: "HTTP/1.1", headerFields: response.headers)!176 client?.urlProtocol(self, didReceive: http, cacheStoragePolicy: .notAllowed)177 for chunk in response.chunks { client?.urlProtocol(self, didLoad: chunk) }178 if let failure = response.failure {179 // Let the delivered bytes reach the consumer first, as on a real connection that drops later.180 if !response.chunks.isEmpty { Thread.sleep(forTimeInterval: 0.15) }181 client?.urlProtocol(self, didFailWithError: URLError(failure))182 }183 else { client?.urlProtocolDidFinishLoading(self) }184 }185}186187/// Collects a provider stream: the events delivered and the error that ended it, if any.188func collect(_ stream: AsyncThrowingStream<LLMStreamEvent, Error>) async -> (events: [LLMStreamEvent], error: LLMError?) {189 var events: [LLMStreamEvent] = []190 do {191 for try await e in stream { events.append(e) }192 return (events, nil)193 } catch {194 return (events, error as? LLMError ?? .network("non-LLMError: \(type(of: error))"))195 }196}197198extension Array where Element == LLMStreamEvent {199 var text: String { compactMap { if case .textDelta(let t) = $0 { return t }; return nil }.joined() }200 var reasoning: String { compactMap { if case .reasoningSummaryDelta(let t) = $0 { return t }; return nil }.joined() }201 var toolUses: [LLMToolUse] { compactMap { if case .toolUse(let u) = $0 { return u }; return nil } }202 var lastUsage: TokenUsage? { compactMap { if case .usage(let u) = $0 { return u }; return nil }.last }203 var stop: LLMStopReason? { compactMap { if case .stop(let s) = $0 { return s }; return nil }.last }204 var inputDeltas: [String] { compactMap { if case .toolUseInputDelta(_, let p) = $0 { return p }; return nil } }205 var started: [String] { compactMap { if case .toolUseStarted(let i, let id, let name) = $0 { return "\(i):\(id):\(name)" }; return nil } }206}207208/// A key-shaped value that is obviously not a real credential; used to assert that keys never leak into errors.209let fixtureKey = "sk-fixture-0000-not-a-real-key-0000"210211/// Builds an Anthropic-style SSE transcript from (event, JSON) pairs.212func anthropicSSE(_ events: [(String, String)]) -> String {213 events.map { "event: \($0.0)\ndata: \($0.1)\n\n" }.joined()214}215216/// Builds a Chat Completions SSE transcript from JSON chunks, closed by `[DONE]`.217func chatSSE(_ chunks: [String], done: Bool = true) -> String {218 chunks.map { "data: \($0)\n\n" }.joined() + (done ? "data: [DONE]\n\n" : "")219}220221let weatherTool = LLMToolSpec(name: "get_weather", description: "Returns the weather for a city.",222 inputSchema: .object(["city": .string("City name")], required: ["city"]))223