// // ScriptedJetstreamTransport.swift // JetstreamKit // import Foundation import Synchronization /// A ``JetstreamTransport`` that plays a script instead of touching the /// network, for testing anything built on a ``JetstreamClient``. /// /// Each connection attempt takes the next ``Attempt``. Once the script has run /// out, further attempts wait until their task is cancelled. /// /// ```swift /// let transport = ScriptedJetstreamTransport([ /// .refused(JetstreamTransportError.upgradeRefused(status: 503)), /// .opens(frames: capturedFrames, then: .staysOpen), /// ]) /// ``` public final class ScriptedJetstreamTransport: JetstreamTransport { /// One connection attempt. public enum Attempt: Sendable { case refused(any Error) case opens(frames: [String], then: Ending) } /// What a connection does after its last frame. public enum Ending: Sendable { /// The server closes it normally. case closes /// The connection fails. case fails(any Error) /// It stays silent until its task is cancelled. case staysOpen } /// What the client asked for on one attempt. public struct Request: Sendable, Equatable { public let url: URL public let subprotocol: String? public let pingInterval: Duration } private struct State { var script: ArraySlice var requests: [Request] = [] var framesRead = 0 var connectionsClosed = 0 var connectionsReleased = 0 } private let state: Mutex public init(_ script: [Attempt]) { self.state = Mutex(State(script: script[...])) } /// Every attempt so far, oldest first. public var requests: [Request] { state.withLock { $0.requests } } /// How many frames have been handed to the client across all connections. public var framesRead: Int { state.withLock { $0.framesRead } } /// How many connections the client has closed. public var connectionsClosed: Int { state.withLock { $0.connectionsClosed } } /// How many connections have been deallocated, closed or not. A consumer /// that abandons its loop leaves nothing to call ``JetstreamConnection/close()``, /// so this is what shows the socket would still have been released. public var connectionsReleased: Int { state.withLock { $0.connectionsReleased } } public func connect(to url: URL, subprotocol: String?, pingInterval: Duration) async throws -> any JetstreamConnection { let attempt = state.withLock { state in state.requests.append(Request(url: url, subprotocol: subprotocol, pingInterval: pingInterval)) return state.script.popFirst() } switch attempt { case .refused(let error): throw error case .opens(let frames, let ending): return ScriptedConnection(transport: self, frames: frames, ending: ending) case nil: try await Self.waitUntilCancelled() throw CancellationError() } } fileprivate func noteFrameRead() { state.withLock { $0.framesRead += 1 } } fileprivate func noteConnectionClosed() { state.withLock { $0.connectionsClosed += 1 } } fileprivate func noteConnectionReleased() { state.withLock { $0.connectionsReleased += 1 } } fileprivate static func waitUntilCancelled() async throws { while true { try await Task.sleep(for: .seconds(3600)) } } } private final class ScriptedConnection: JetstreamConnection { private enum Step: Sendable { case frame(String) case end(ScriptedJetstreamTransport.Ending) } private final class Playback: Sendable { private let steps: Mutex> init(_ steps: [Step]) { self.steps = Mutex(steps[...]) } func next() -> Step { steps.withLock { $0.popFirst() } ?? .end(.closes) } } let textFrames: AsyncThrowingStream private let transport: ScriptedJetstreamTransport private let isClosed = Mutex(false) init(transport: ScriptedJetstreamTransport, frames: [String], ending: ScriptedJetstreamTransport.Ending) { self.transport = transport let playback = Playback(frames.map(Step.frame) + [.end(ending)]) self.textFrames = AsyncThrowingStream(unfolding: { switch playback.next() { case .frame(let text): transport.noteFrameRead() return text case .end(.closes): return nil case .end(.fails(let error)): throw error case .end(.staysOpen): try await ScriptedJetstreamTransport.waitUntilCancelled() return nil } }) } func close() async { let wasOpen = isClosed.withLock { isClosed in defer { isClosed = true } return !isClosed } if wasOpen { transport.noteConnectionClosed() } } deinit { transport.noteConnectionReleased() } }