// // JetstreamTransport.swift // JetstreamKit // import Foundation /// How a ``JetstreamClient`` opens sockets. ``URLSessionJetstreamTransport`` /// is the default; a server can supply one built on its own event loop, and /// tests use ``ScriptedJetstreamTransport``. public protocol JetstreamTransport: Sendable { /// Opens a WebSocket and returns once the server has accepted the upgrade. /// Throw ``JetstreamTransportError/upgradeRefused(status:)`` when it doesn't, /// which is how the client learns that a cursor is too old. /// /// - Parameters: /// - subprotocol: The `Sec-WebSocket-Protocol` to request, if any. /// - pingInterval: How often to ping. A ping left unanswered for a whole /// interval means the connection is dead: fail ``JetstreamConnection/textFrames`` /// with ``JetstreamTransportError/pingTimedOut``. func connect(to url: URL, subprotocol: String?, pingInterval: Duration) async throws -> any JetstreamConnection } /// One open WebSocket. /// /// Consumers can abandon a stream without warning, by breaking out of its loop /// for instance, and then nothing is left to call ``close()``. A conforming /// type must release its socket when it is deallocated. public protocol JetstreamConnection: Sendable { /// The server's text frames: finishes when the server closes normally, /// throws when the connection fails. Binary frames are not included. /// /// Read a frame from the socket only when the next one is asked for, so /// that a consumer's pace reaches the server. var textFrames: AsyncThrowingStream { get } /// Closes the socket. Calling it more than once does nothing. func close() async } public enum JetstreamTransportError: Error, Equatable, Sendable { /// The server answered the WebSocket upgrade with something other than /// `101`. `status` is `nil` when the transport can't see it. case upgradeRefused(status: Int?) /// The socket closed before the server accepted the upgrade. case closedBeforeOpen /// A ping went a whole interval without a pong, so the connection is dead. case pingTimedOut /// This platform can't open WebSockets with this transport, and retrying /// won't change that. It ends the stream rather than a connection. case webSocketsUnavailable /// Jetstream refuses a cursor below its retention floor with HTTP 400 /// before the upgrade. Any other status is about the host, not the cursor. var mayMeanCursorRefused: Bool { switch self { case .upgradeRefused(let status): status == nil || status == 400 case .closedBeforeOpen, .pingTimedOut, .webSocketsUnavailable: false } } }