// // JetstreamSession.swift // JetstreamKit // import CoreATProtocol import Logging /// One run of a ``JetstreamClient``: its socket, its position and its backoff, /// advanced a delivery at a time by ``next()``. Nothing happens between calls, /// which is what gives a consumer back-pressure all the way to the socket. actor JetstreamSession { private struct OpenSocket { let host: JetstreamHost let connection: any JetstreamConnection var frames: AsyncThrowingStream.Iterator let resumedFromCursor: Bool let openedAt: ContinuousClock.Instant } private let client: JetstreamClient private var position: JetstreamPosition? private var reconnect: ReconnectState private var socket: OpenSocket? private var retryDelay: Duration = .zero private var cursorRefusals = 0 /// Told to the consumer as soon as the socket that follows a dropped position is open. private var announcement: JetstreamInfo? private var isValidated = false init(client: JetstreamClient, resumingFrom position: JetstreamPosition?) { self.client = client self.position = position self.reconnect = ReconnectState(policy: client.policy, hostCount: client.hosts.count) } /// The next delivery, or `nil` once the task is cancelled. func next() async throws -> JetstreamDelivery? { try validateConfiguration() do { while true { try Task.checkCancellation() if let delivery = try await advance() { return delivery } } } catch is CancellationError { await closeSocket() return nil } } /// A misconfigured client would otherwise retry forever, or fail only when /// it reached the bad host, so every host is checked before the first attempt. private func validateConfiguration() throws { guard !isValidated else { return } guard !client.hosts.isEmpty else { throw JetstreamClientError.noHosts } for host in client.hosts { _ = try host.subscriptionURL(filter: client.filter, cursor: nil) } isValidated = true } /// One step: a connection attempt, the pending announcement, or one frame, /// which returns `nil` when it produced nothing for the consumer. private func advance() async throws -> JetstreamDelivery? { guard let socket else { return try await connect() } if let info = announcement { announcement = nil return .info(info) } return try await readFrame(from: socket) } // MARK: - Connecting private func connect() async throws -> JetstreamDelivery { if retryDelay > .zero { try await Task.sleep(for: retryDelay) retryDelay = .zero } let host = client.hosts[reconnect.hostIndex] let cursor = position.map(host.cursor(resuming:)) let url = try host.subscriptionURL(filter: client.filter, cursor: cursor) client.logger.info("jetstream connecting", metadata: ["host": "\(host.url)", "cursor": "\(cursor.map { String($0.queryValue) } ?? "live")"]) do { let connection = try await client.transport.connect(to: url, subprotocol: host.subprotocol, pingInterval: JetstreamClient.pingInterval) cursorRefusals = 0 socket = OpenSocket( host: host, connection: connection, frames: connection.textFrames.makeAsyncIterator(), resumedFromCursor: cursor != nil, openedAt: .now ) client.logger.info("jetstream connected", metadata: ["host": "\(host.url)"]) return .connected(host: host.url, resumedFromCursor: cursor != nil) } catch { try Task.checkCancellation() if error as? JetstreamTransportError == .webSocketsUnavailable { throw error } noteFailedConnect(error, resumedFromCursor: cursor != nil, on: host) retryDelay = reconnect.connectFailed() client.logger.error("jetstream connection failed", metadata: ["host": "\(host.url)", "error": "\(error)", "retryAfter": "\(retryDelay)"]) return .disconnected(host: host.url, reason: .connectFailed(error), willRetryAfter: retryDelay) } } /// Two refused resumes in a row mean the cursor is older than the host's /// retention, so the position goes and the consumer is told once it's live. private func noteFailedConnect(_ error: any Error, resumedFromCursor: Bool, on host: JetstreamHost) { guard resumedFromCursor, (error as? JetstreamTransportError)?.mayMeanCursorRefused == true else { cursorRefusals = 0 return } cursorRefusals += 1 guard cursorRefusals >= JetstreamClient.cursorRefusalsBeforeReset else { return } client.logger.warning("jetstream refused the saved cursor; continuing from the live tail", metadata: ["host": "\(host.url)"]) cursorRefusals = 0 position = nil announcement = JetstreamInfo(name: JetstreamInfo.outdatedCursor, message: "\(host.url) refused the cursor as too old; continuing from the live tail") } // MARK: - Reading private func readFrame(from socket: OpenSocket) async throws -> JetstreamDelivery? { var frames = socket.frames let received: String? do { received = try await frames.next(isolation: self) } catch { try Task.checkCancellation() return await connectionEnded(socket, because: .connectionLost(error)) } self.socket?.frames = frames guard let text = received else { // A cancelled read can look like the end of the stream. try Task.checkCancellation() return await connectionEnded(socket, because: .closedByServer) } guard text.utf8.count <= JetstreamClient.maxFrameSize else { client.logger.warning("skipping oversized jetstream frame", metadata: ["host": "\(socket.host.url)", "bytes": "\(text.utf8.count)"]) return nil } let frame: JetstreamHost.WireFrame do { frame = try socket.host.decode(text) } catch JetstreamDecodingError.unknownEnvelope(let type) { client.logger.debug("skipping unknown jetstream envelope", metadata: ["type": "\(type)"]) return nil } catch { // The same frame would come back on every reconnect, so it can't be fatal. client.logger.warning("skipping undecodable jetstream frame", metadata: ["host": "\(socket.host.url)", "error": "\(error)"]) return nil } switch frame { case .event(let event, let timeMicros, let isLive): let delivered = JetstreamPosition( host: socket.host.url, seq: event.seq, // An unreadable time must not cost the event: the seq is still exact, // and the time only matters for a move to another host. timeMicros: timeMicros ?? position?.timeMicros ?? JetstreamTime.nowMicros ) position = delivered return .event(event, position: delivered, isLive: isLive) case .info(let info) where info.name == JetstreamInfo.outdatedCursor && socket.resumedFromCursor: return await restartLive(socket, announcing: info) case .info(let info): client.logger.info("jetstream info", metadata: ["name": "\(info.name)", "message": "\(info.message ?? "")"]) return .info(info) case .terminalError(let error): return await connectionEnded(socket, because: .streamError(error)) case .ignored(let what): client.logger.debug("skipping jetstream frame", metadata: ["frame": "\(what)"]) return nil } } /// The host clamped a cursor older than its retention and would replay from /// its floor. Reconnecting without one takes the live tail instead, at once, /// because nothing has failed. private func restartLive(_ socket: OpenSocket, announcing info: JetstreamInfo) async -> JetstreamDelivery { client.logger.warning("jetstream cursor is outdated; continuing from the live tail", metadata: ["host": "\(socket.host.url)", "message": "\(info.message ?? "")"]) position = nil announcement = info await closeSocket() return .disconnected(host: socket.host.url, reason: .cursorOutdated, willRetryAfter: .zero) } private func connectionEnded(_ socket: OpenSocket, because reason: JetstreamDisconnectReason) async -> JetstreamDelivery { await closeSocket() retryDelay = reconnect.connectionEnded(after: socket.openedAt.duration(to: .now)) client.logger.warning("jetstream disconnected", metadata: ["host": "\(socket.host.url)", "reason": "\(reason)", "retryAfter": "\(retryDelay)"]) return .disconnected(host: socket.host.url, reason: reason, willRetryAfter: retryDelay) } private func closeSocket() async { guard let socket else { return } self.socket = nil await socket.connection.close() } }