Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Tests/CoreTests/FaultProxy.swift3// Description: A TCP proxy between the app and the test backend, used to produce real network trouble on demand.4import Foundation5import Network67/// A TCP proxy between the app and the test backend, used to produce real network trouble on demand: refuse8/// connections, cut a transfer after N bytes, slow it down, corrupt a byte. It also counts what really went over9/// the wire, which is how the tests prove that offline playback makes no request and that a resumed download does10/// not fetch the same bytes twice.11final class FaultProxy: @unchecked Sendable {12 private(set) var port: UInt16 = 013 private let upstreamPort: UInt1614 private let listener: NWListener15 private let queue = DispatchQueue(label: "faultproxy")16 private let lock = NSLock()17 private var _down = false18 private var _cutAfter: Int?19 private var _bytesPerSecond: Int?20 private var _corruptAt: Int?21 private var _connections = 022 private var _bytesDown = 023 private var _requests: [String] = []24 private var live: [ObjectIdentifier: (NWConnection, NWConnection)] = [:]2526 var url: URL { URL(string: "http://127.0.0.1:\(port)")! }27 var connections: Int { lock.withLock { _connections } }28 var bytesFromServer: Int { lock.withLock { _bytesDown } }29 /// Request lines and Range headers seen, e.g. "GET /api/v1/stream/<id> | bytes=1048576-".30 var requests: [String] { lock.withLock { _requests } }31 func resetCounters() { lock.withLock { _connections = 0; _bytesDown = 0; _requests = [] } }3233 /// Server unreachable: new connections are closed at once and the ones in flight are dropped.34 var down: Bool {35 get { lock.withLock { _down } }36 set { let conns = lock.withLock { () -> [(NWConnection, NWConnection)] in _down = newValue; return newValue ? Array(live.values) : [] }; for (a, b) in conns { a.cancel(); b.cancel() } }37 }38 /// Cut each connection once this many body bytes went from server to client (one shot).39 var cutAfter: Int? { get { lock.withLock { _cutAfter } } set { lock.withLock { _cutAfter = newValue } } }40 var bytesPerSecond: Int? { get { lock.withLock { _bytesPerSecond } } set { lock.withLock { _bytesPerSecond = newValue } } }41 /// Flip one byte at this offset of the next large response (one shot).42 var corruptAt: Int? { get { lock.withLock { _corruptAt } } set { lock.withLock { _corruptAt = newValue } } }4344 init(upstreamPort: UInt16) throws {45 self.upstreamPort = upstreamPort46 let params = NWParameters.tcp; params.allowLocalEndpointReuse = true47 listener = try NWListener(using: params, on: .any)48 let ready = DispatchSemaphore(value: 0)49 listener.stateUpdateHandler = { if case .ready = $0 { ready.signal() } }50 listener.newConnectionHandler = { [weak self] c in self?.accept(c) }51 listener.start(queue: queue)52 _ = ready.wait(timeout: .now() + 5)53 port = listener.port?.rawValue ?? 054 }55 deinit { listener.cancel() }56 func stop() { listener.cancel(); let conns = lock.withLock { Array(live.values) }; for (a, b) in conns { a.cancel(); b.cancel() } }5758 private func accept(_ client: NWConnection) {59 if down { client.start(queue: queue); client.cancel(); return }60 lock.withLock { _connections += 1 }61 let server = NWConnection(host: "127.0.0.1", port: NWEndpoint.Port(rawValue: upstreamPort)!, using: .tcp)62 let key = ObjectIdentifier(client)63 lock.withLock { live[key] = (client, server) }64 let close: @Sendable () -> Void = { [weak self] in client.cancel(); server.cancel(); self?.lock.withLock { self?.live[key] = nil } }65 client.start(queue: queue); server.start(queue: queue)66 pumpUp(client, server, close)67 pumpDown(server, client, sent: 0, close)68 }6970 private func pumpUp(_ from: NWConnection, _ to: NWConnection, _ close: @escaping @Sendable () -> Void) {71 from.receive(minimumIncompleteLength: 1, maximumLength: 65536) { [weak self] data, _, done, error in72 guard let self else { return }73 if let data, !data.isEmpty {74 if case let text = String(decoding: data.prefix(2048), as: UTF8.self), let first = text.split(separator: "\r\n").first, first.contains(" HTTP/1.") {75 let range = text.split(separator: "\r\n").first { $0.lowercased().hasPrefix("range:") }.map { " | " + $0.dropFirst(6).trimmingCharacters(in: .whitespaces) } ?? ""76 self.lock.withLock { self._requests.append(first.replacingOccurrences(of: " HTTP/1.1", with: "") + range) }77 }78 to.send(content: data, completion: .contentProcessed { e in if e != nil { close() } else { self.pumpUp(from, to, close) } })79 } else if done || error != nil { close() } else { self.pumpUp(from, to, close) }80 }81 }8283 private func pumpDown(_ from: NWConnection, _ to: NWConnection, sent: Int, _ close: @escaping @Sendable () -> Void) {84 from.receive(minimumIncompleteLength: 1, maximumLength: 32768) { [weak self] data, _, done, error in85 guard let self else { return }86 guard var data, !data.isEmpty else { if done || error != nil { close() } else { self.pumpDown(from, to, sent: sent, close) }; return }87 if self.down { close(); return }88 let (payload, cutNow): (Data, Bool) = self.lock.withLock {89 var cut = false90 if let at = self._corruptAt, sent <= at, at < sent + data.count { data[data.startIndex + (at - sent)] ^= 0xff; self._corruptAt = nil }91 if let limit = self._cutAfter, sent + data.count >= limit { data = data.prefix(max(0, limit - sent)); self._cutAfter = nil; cut = true }92 self._bytesDown += data.count93 return (data, cut)94 }95 let total = sent + payload.count96 let delay: Double = self.bytesPerSecond.map { Double(payload.count) / Double(max(1, $0)) } ?? 097 self.queue.asyncAfter(deadline: .now() + delay) {98 to.send(content: payload, completion: .contentProcessed { e in99 if e != nil || cutNow { close() } else { self.pumpDown(from, to, sent: total, close) }100 })101 }102 }103 }104}105