Repository Public License
1import Foundation2import Network34// MARK: - Request / response model56public struct FixtureRequest: Sendable {7 public var method: String8 /// Percent-decoded path, without the query.9 public var path: String10 /// Raw request target as received (path + query, still percent-encoded).11 public var target: String12 public var query: [String: String]13 /// Header names are lowercased.14 public var headers: [String: String]15 public var body: Data16 /// Port the server listens on, so handlers can build absolute URLs.17 public var serverPort: Int18 public var isTLS: Bool1920 public var bodyText: String { String(decoding: body, as: UTF8.self) }21 public func header(_ name: String) -> String? { headers[name.lowercased()] }22 public var origin: String { "\(isTLS ? "https" : "http")://127.0.0.1:\(serverPort)" }23}2425public struct FixtureResponse: Sendable {26 /// How the bytes are put on the wire.27 public enum Delivery: Sendable, Equatable {28 case immediate29 /// Wait before sending anything.30 case delayed(milliseconds: Int)31 /// Send headers at once, then the body in chunks with a pause between them.32 case throttled(chunkSize: Int, pauseMilliseconds: Int)33 /// Close the connection without sending a byte.34 case reset35 /// Announce the full Content-Length but close after `bytes` body bytes.36 case truncated(bytes: Int)37 }3839 public var status: Int40 public var headers: [(String, String)]41 public var body: Data42 public var delivery: Delivery4344 public init(status: Int = 200, headers: [(String, String)] = [], body: Data = Data(),45 delivery: Delivery = .immediate) {46 self.status = status; self.headers = headers; self.body = body; self.delivery = delivery47 }4849 public static func html(_ html: String, status: Int = 200, headers: [(String, String)] = []) -> FixtureResponse {50 FixtureResponse(status: status, headers: [("Content-Type", "text/html; charset=utf-8")] + headers,51 body: Data(html.utf8))52 }5354 public static func text(_ text: String, status: Int = 200, contentType: String = "text/plain; charset=utf-8",55 headers: [(String, String)] = []) -> FixtureResponse {56 FixtureResponse(status: status, headers: [("Content-Type", contentType)] + headers, body: Data(text.utf8))57 }5859 public static func redirect(_ location: String, status: Int = 302) -> FixtureResponse {60 FixtureResponse(status: status, headers: [("Location", location), ("Content-Type", "text/plain")],61 body: Data("Redirecting".utf8))62 }6364 static func reasonPhrase(_ status: Int) -> String {65 switch status {66 case 200: "OK"67 case 206: "Partial Content"68 case 301: "Moved Permanently"69 case 302: "Found"70 case 303: "See Other"71 case 307: "Temporary Redirect"72 case 308: "Permanent Redirect"73 case 400: "Bad Request"74 case 401: "Unauthorized"75 case 404: "Not Found"76 case 416: "Range Not Satisfiable"77 case 500: "Internal Server Error"78 default: "Status"79 }80 }81}8283public typealias FixtureHandler = @Sendable (FixtureRequest) -> FixtureResponse8485public enum FixtureServerError: Error, CustomStringConvertible {86 case startFailed(String)87 case notStarted8889 public var description: String {90 switch self {91 case .startFailed(let message): "Fixture server failed to start: \(message)"92 case .notStarted: "Fixture server is not started"93 }94 }95}9697// MARK: - Server9899/// A local HTTP/1.1 server for tests. One request per connection (`Connection: close`), which keeps the parser100/// trivial and makes every request observable in `requests`.101public final class FixtureServer: @unchecked Sendable {102 private let queue = DispatchQueue(label: "orix.testsupport.fixture-server")103 private let lock = NSLock()104 private var listener: NWListener?105 private var connections: [ObjectIdentifier: NWConnection] = [:]106 private var customRoutes: [String: FixtureHandler] = [:]107 private var recorded: [FixtureRequest] = []108 private var boundPort: Int = 0109 private let tlsOptions: NWProtocolTLS.Options?110111 /// Plain HTTP server.112 public init() { tlsOptions = nil }113114 /// HTTPS server presenting `tls` (see `FixtureTLSIdentity`).115 public init(tls: NWProtocolTLS.Options) { tlsOptions = tls }116117 deinit { listener?.cancel() }118119 public var isTLS: Bool { tlsOptions != nil }120121 public var port: Int { lock.withLock { boundPort } }122123 /// `http://127.0.0.1:<port>` (or `https://…` for a TLS server).124 public var baseURL: URL { URL(string: "\(isTLS ? "https" : "http")://127.0.0.1:\(port)")! }125126 /// URL for `path` (must start with `/`; may contain a query). `host` lets a test use `localhost`, a different127 /// origin served by the same listener.128 public func url(_ path: String, host: String = "127.0.0.1") -> URL {129 URL(string: "\(isTLS ? "https" : "http")://\(host):\(port)\(path)")!130 }131132 /// Every request received so far, in arrival order.133 public var requests: [FixtureRequest] { lock.withLock { recorded } }134135 public func requests(path: String) -> [FixtureRequest] { requests.filter { $0.path == path } }136137 public func resetRequests() { lock.withLock { recorded.removeAll() } }138139 /// Adds or replaces a route for an exact decoded path. Custom routes win over built-in ones.140 public func route(_ path: String, _ handler: @escaping FixtureHandler) {141 lock.withLock { customRoutes[path] = handler }142 }143144 public func start() async throws {145 let parameters: NWParameters146 if let tlsOptions {147 parameters = NWParameters(tls: tlsOptions, tcp: NWProtocolTCP.Options())148 } else {149 parameters = NWParameters.tcp150 }151 parameters.allowLocalEndpointReuse = true152 parameters.requiredLocalEndpoint = .hostPort(host: .ipv4(.loopback), port: .any)153154 let listener: NWListener155 do { listener = try NWListener(using: parameters) } catch {156 throw FixtureServerError.startFailed(String(describing: error))157 }158 listener.newConnectionHandler = { [weak self] connection in self?.accept(connection) }159160 let resumed = ResumeOnce()161 try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, Error>) in162 listener.stateUpdateHandler = { [weak self] state in163 switch state {164 case .ready:165 let port = Int(listener.port?.rawValue ?? 0)166 self?.lock.withLock { self?.boundPort = port }167 if resumed.claim() { continuation.resume() }168 case .failed(let error):169 if resumed.claim() {170 continuation.resume(throwing: FixtureServerError.startFailed(String(describing: error)))171 }172 case .cancelled:173 if resumed.claim() { continuation.resume(throwing: FixtureServerError.startFailed("cancelled")) }174 default:175 break176 }177 }178 listener.start(queue: queue)179 }180 lock.withLock { self.listener = listener }181 }182183 public func stop() {184 let (listener, open) = lock.withLock { () -> (NWListener?, [NWConnection]) in185 let result = (self.listener, Array(connections.values))186 self.listener = nil187 connections.removeAll()188 return result189 }190 listener?.cancel()191 open.forEach { $0.cancel() }192 }193194 // MARK: Connection handling (all on `queue`)195196 private func accept(_ connection: NWConnection) {197 let key = ObjectIdentifier(connection)198 lock.withLock { connections[key] = connection }199 connection.stateUpdateHandler = { [weak self] state in200 switch state {201 case .failed, .cancelled: self?.lock.withLock { _ = self?.connections.removeValue(forKey: key) }202 default: break203 }204 }205 connection.start(queue: queue)206 receive(on: connection, buffer: Data())207 }208209 private func receive(on connection: NWConnection, buffer: Data) {210 connection.receive(minimumIncompleteLength: 1, maximumLength: 64 * 1024) { [weak self] data, _, isComplete, error in211 guard let self else { return }212 var buffer = buffer213 if let data { buffer.append(data) }214 switch HTTPRequestParser.parse(buffer, port: self.port, isTLS: self.isTLS) {215 case .complete(let request):216 self.respond(to: request, on: connection)217 case .incomplete:218 if isComplete || error != nil || buffer.count > 8 * 1024 * 1024 {219 connection.cancel()220 } else {221 self.receive(on: connection, buffer: buffer)222 }223 case .malformed:224 connection.cancel()225 }226 }227 }228229 private func respond(to request: FixtureRequest, on connection: NWConnection) {230 let custom = lock.withLock { () -> FixtureHandler? in231 recorded.append(request)232 return customRoutes[request.path]233 }234 let response = custom?(request) ?? FixtureRoutes.response(for: request)235 send(response, on: connection, isHead: request.method == "HEAD")236 }237238 private func send(_ response: FixtureResponse, on connection: NWConnection, isHead: Bool = false) {239 var head = "HTTP/1.1 \(response.status) \(FixtureResponse.reasonPhrase(response.status))\r\n"240 var names = Set<String>()241 for (name, value) in response.headers {242 head += "\(name): \(value)\r\n"243 names.insert(name.lowercased())244 }245 if !names.contains("content-length") { head += "Content-Length: \(response.body.count)\r\n" }246 if !names.contains("cache-control") { head += "Cache-Control: no-store\r\n" }247 head += "Connection: close\r\n\r\n"248 let headData = Data(head.utf8)249 let body = isHead ? Data() : response.body250251 switch response.delivery {252 case .reset:253 // A cancel without any byte sent surfaces in WebKit as a network error ("connection lost").254 connection.cancel()255 case .immediate:256 finish(connection, sending: headData + body)257 case .delayed(let milliseconds):258 queue.asyncAfter(deadline: .now() + .milliseconds(milliseconds)) { [weak self] in259 self?.finish(connection, sending: headData + body)260 }261 case .truncated(let bytes):262 finish(connection, sending: headData + body.prefix(max(0, bytes)))263 case .throttled(let chunkSize, let pause):264 connection.send(content: headData, completion: .contentProcessed { [weak self] error in265 guard error == nil else { connection.cancel(); return }266 self?.sendThrottled(body, offset: 0, chunkSize: max(1, chunkSize), pause: pause, on: connection)267 })268 }269 }270271 private func sendThrottled(_ body: Data, offset: Int, chunkSize: Int, pause: Int, on connection: NWConnection) {272 guard offset < body.count else {273 connection.send(content: nil, contentContext: .finalMessage, isComplete: true,274 completion: .contentProcessed { _ in connection.cancel() })275 return276 }277 let end = min(body.count, offset + chunkSize)278 let chunk = body.subdata(in: (body.startIndex + offset)..<(body.startIndex + end))279 connection.send(content: chunk, completion: .contentProcessed { [weak self] error in280 // The client went away (cancelled download): stop producing.281 guard error == nil, let self else { connection.cancel(); return }282 self.queue.asyncAfter(deadline: .now() + .milliseconds(pause)) {283 self.sendThrottled(body, offset: end, chunkSize: chunkSize, pause: pause, on: connection)284 }285 })286 }287288 private func finish(_ connection: NWConnection, sending data: Data) {289 connection.send(content: data, contentContext: .finalMessage, isComplete: true,290 completion: .contentProcessed { _ in connection.cancel() })291 }292}293294/// Guards a continuation against the listener reporting several terminal states.295private final class ResumeOnce: @unchecked Sendable {296 private let lock = NSLock()297 private var done = false298 func claim() -> Bool { lock.withLock { if done { return false }; done = true; return true } }299}300301// MARK: - HTTP parsing302303enum HTTPRequestParser {304 enum Result { case complete(FixtureRequest), incomplete, malformed }305306 static func parse(_ data: Data, port: Int, isTLS: Bool) -> Result {307 // A TLS ClientHello sent to the plain-text listener (https:// against an http server): refuse at once308 // instead of waiting for a request line that will never come.309 if !isTLS, data.first == 0x16 { return .malformed }310 let terminator = Data("\r\n\r\n".utf8)311 guard let headerEnd = data.range(of: terminator) else { return .incomplete }312 guard let head = String(data: data[data.startIndex..<headerEnd.lowerBound], encoding: .utf8) else {313 return .malformed314 }315 var lines = head.components(separatedBy: "\r\n")316 guard !lines.isEmpty else { return .malformed }317 let requestLine = lines.removeFirst().split(separator: " ", omittingEmptySubsequences: true)318 guard requestLine.count >= 2 else { return .malformed }319 let method = String(requestLine[0]).uppercased()320 let target = String(requestLine[1])321322 var headers: [String: String] = [:]323 for line in lines {324 guard let colon = line.firstIndex(of: ":") else { continue }325 let name = line[..<colon].trimmingCharacters(in: .whitespaces).lowercased()326 let value = line[line.index(after: colon)...].trimmingCharacters(in: .whitespaces)327 headers[name] = value328 }329330 let bodyStart = headerEnd.upperBound331 let contentLength = Int(headers["content-length"] ?? "") ?? 0332 guard contentLength >= 0 else { return .malformed }333 let available = data.endIndex - bodyStart334 if available < contentLength { return .incomplete }335 let body = data.subdata(in: bodyStart..<(bodyStart + contentLength))336337 let (path, query) = splitTarget(target)338 return .complete(FixtureRequest(method: method, path: path, target: target, query: query, headers: headers,339 body: body, serverPort: port, isTLS: isTLS))340 }341342 static func splitTarget(_ target: String) -> (path: String, query: [String: String]) {343 let parts = target.split(separator: "?", maxSplits: 1, omittingEmptySubsequences: false)344 let rawPath = parts.first.map(String.init) ?? "/"345 let path = rawPath.removingPercentEncoding ?? rawPath346 let query = parts.count > 1 ? parseForm(String(parts[1])) : [:]347 return (path, query)348 }349350 /// Parses `application/x-www-form-urlencoded` text (also used for query strings).351 static func parseForm(_ text: String) -> [String: String] {352 var result: [String: String] = [:]353 for pair in text.split(separator: "&") {354 let kv = pair.split(separator: "=", maxSplits: 1, omittingEmptySubsequences: false)355 let decode: (Substring) -> String = {356 let plus = $0.replacingOccurrences(of: "+", with: " ")357 return plus.removingPercentEncoding ?? plus358 }359 guard let key = kv.first else { continue }360 result[decode(key)] = kv.count > 1 ? decode(kv[1]) : ""361 }362 return result363 }364}365