// // JetstreamClient.swift // JetstreamKit // import CoreATProtocol import Logging /// Reads the Jetstream event stream and keeps reading, whatever the network does. /// /// A client connects to the first of its hosts and delivers events until the /// task iterating ``deliveries(resumingFrom:)`` is cancelled. Reconnecting, /// backing off, moving to the next host and working out where to resume all /// happen inside; the consumer sees them only as ``JetstreamDelivery`` values. /// /// ```swift /// let client = JetstreamClient( /// hosts: JetstreamHost.bluesky, /// filter: JetstreamFilter(collections: ["org.tangled.*"], kinds: [.commit]) /// ) /// for try await delivery in client.deliveries(resumingFrom: savedPosition) { /// if case .event(.commit(let commit), let position, _) = delivery { /// try await store(commit, at: position) /// } /// } /// ``` /// /// Delivery is at least once: cursors are inclusive and a move to another host /// rewinds a few seconds, so handlers must tolerate seeing an event twice. /// Persisting positions is the consumer's job. public struct JetstreamClient: Sendable { /// Frames larger than this many bytes are skipped. public static let maxFrameSize = 4 * 1024 * 1024 /// How often the transport pings. Filtered streams can go minutes between /// frames, so this is what keeps idle connections alive and exposes dead ones. public static let pingInterval: Duration = .seconds(30) /// How far before a witnessed time a timestamp cursor starts, because /// instances stamp events slightly differently. static let timestampRewindMicros: Int64 = 5_000_000 /// Consecutive refused resumes before the position is dropped. One refusal /// could be the host having a bad moment; two means the cursor is the problem. static let cursorRefusalsBeforeReset = 2 let hosts: [JetstreamHost] let filter: JetstreamFilter let transport: any JetstreamTransport let policy: ReconnectPolicy let logger: Logger /// - Parameters: /// - hosts: Where to read from, in order of preference. /// - filter: Which events to ask for. /// - transport: How sockets are opened. The default uses `URLSession`, /// which has no WebSockets on Linux; see ``URLSessionJetstreamTransport``. /// - policy: The pacing of reconnects and when to move to the next host. /// - logger: Receives connection changes and skipped frames. public init( hosts: [JetstreamHost], filter: JetstreamFilter, transport: any JetstreamTransport = URLSessionJetstreamTransport(), policy: ReconnectPolicy = .init(), logger: Logger = Logger(label: "JetstreamKit") ) { self.hosts = hosts self.filter = filter self.transport = transport self.policy = policy self.logger = logger } /// Connects, decodes, fails over, backs off and resumes until the task is /// cancelled, which ends the sequence and closes the socket. /// /// A frame is only read when the consumer asks for the next delivery, so a /// consumer that falls behind slows the socket down rather than filling a /// buffer. Iterate from a single task. /// /// The sequence never ends on its own. It throws only when the client can /// never work: no hosts, a malformed host, too many collections or DIDs, or /// a transport that can't open WebSockets on this platform. /// /// - Parameter position: Where to resume, or `nil` for the live tail. public func deliveries(resumingFrom position: JetstreamPosition? = nil) -> AsyncThrowingStream { let session = JetstreamSession(client: self, resumingFrom: position) return AsyncThrowingStream(unfolding: { try await session.next() }) } } /// A ``JetstreamClient`` that can never connect. public enum JetstreamClientError: Error, Equatable, Sendable { case noHosts }