// // JetstreamHost.swift // JetstreamKit // import CoreATProtocol import Foundation /// One Jetstream server and the wire format to read it with. public enum JetstreamHost: Sendable, Hashable { /// A `network.bsky.jetstream.subscribeEvents` host with sequence-number /// cursors, such as `wss://jetstream.us-east.bsky.network`. case v2(String) /// A host on the original `/subscribe` wire with microsecond cursors, such /// as `wss://index.tangled.network` or `wss://jetstream2.us-east.bsky.network`. case v1(String) /// Bluesky's recommended hosts. public static let bluesky = JetstreamSubscription.defaultHosts.map(JetstreamHost.v2) /// The base URL, which is also how a ``JetstreamPosition`` names its host. public var url: String { switch self { case .v2(let url), .v1(let url): url } } var subprotocol: String? { switch self { case .v2: JetstreamSubscription.subprotocol case .v1: nil } } /// The cursor that resumes `position` here: its sequence number on the /// v2 host that issued it, otherwise its witnessed time, rewound. func cursor(resuming position: JetstreamPosition) -> JetstreamSubscription.Cursor { if case .v2(let url) = self, url == position.host, let seq = position.seq { return .seq(seq) } let rewound = position.timeMicros - JetstreamClient.timestampRewindMicros return .timestamp(microseconds: max(rewound, JetstreamSubscription.timestampCursorThreshold)) } func subscriptionURL(filter: JetstreamFilter, cursor: JetstreamSubscription.Cursor?) throws -> URL { let maxMessageSize = JetstreamClient.maxFrameSize switch self { case .v2(let host): return try JetstreamSubscription( host: host, kinds: filter.kinds, collections: filter.collections, dids: filter.dids, cursor: cursor, maxMessageSizeBytes: maxMessageSize ).url() case .v1(let host): // The v2 builder checks the host and the limits, which are the same on both wires. let validated = try JetstreamSubscription(host: host, collections: filter.collections, dids: filter.dids).url() guard var components = URLComponents(url: validated, resolvingAgainstBaseURL: false) else { throw JetstreamSubscription.ValidationError.invalidHost(host) } var items = filter.collections.map { URLQueryItem(name: "wantedCollections", value: $0) } items += filter.dids.map { URLQueryItem(name: "wantedDids", value: $0) } // Only an index knows this one; it keeps backfilled history out of the stream. items.append(URLQueryItem(name: "wantedEventTypes", value: "live")) if let cursor { items.append(URLQueryItem(name: "cursor", value: String(cursor.queryValue))) } items.append(URLQueryItem(name: "maxMessageSizeBytes", value: String(maxMessageSize))) components.path = "/subscribe" components.queryItems = items guard let url = components.url else { throw JetstreamSubscription.ValidationError.invalidHost(host) } return url } } /// What one text frame from this host means. func decode(_ text: String) throws -> WireFrame { switch self { case .v2: switch try JetstreamFrame.decode(text) { case .error(let error): return .terminalError(error) case .message(.info(let info)): return .info(info) case .message(.unknown(let type)): return .ignored("unknown payload \(type)") case .message(let event): return .event(event, timeMicros: event.witnessedAt.flatMap(JetstreamTime.microseconds(from:)), isLive: true) } case .v1: let frame = try LegacyJetstreamFrame.decode(text) guard let commit = frame.jetstreamCommit else { return .ignored("\(frame.kind) frame") } return .event(.commit(commit), timeMicros: frame.timeMicros, isLive: frame.commit?.live ?? true) } } /// One text frame, with the differences between the wires removed. enum WireFrame: Sendable { case event(JetstreamEvent, timeMicros: Int64?, isLive: Bool) case info(JetstreamInfo) case terminalError(JetstreamStreamError) case ignored(String) } } /// `wss://…` or `v2:wss://…` is a v2 host and `v1:wss://…` a legacy one, the /// form a command line or an environment variable can carry. extension JetstreamHost: LosslessStringConvertible { public init?(_ description: String) { let host: JetstreamHost if description.hasPrefix("v1:") { host = .v1(String(description.dropFirst(3))) } else if description.hasPrefix("v2:") { host = .v2(String(description.dropFirst(3))) } else { host = .v2(description) } guard (try? JetstreamSubscription(host: host.url).url()) != nil else { return nil } self = host } public var description: String { switch self { case .v2(let url): url case .v1(let url): "v1:\(url)" } } } /// Conversions between the RFC 3339 strings on a v2 wire and the unix /// microseconds that cursors and the legacy wire count in. enum JetstreamTime { static func microseconds(from text: String) -> Int64? { guard let date = try? ATDatetime(text).date else { return nil } return Int64((date.timeIntervalSince1970 * 1_000_000).rounded()) } /// The whole seconds go through `Date`; the fraction is spliced in so that /// no digit passes through a floating-point value. static func timestamp(microseconds: Int64) -> String { let (seconds, fraction) = microseconds.quotientAndRemainder(dividingBy: 1_000_000) let whole = ATDatetime.string(from: Date(timeIntervalSince1970: TimeInterval(seconds))) return whole.dropLast(".000Z".count) + String(format: ".%06lldZ", fraction) } static var nowMicros: Int64 { Int64((Date().timeIntervalSince1970 * 1_000_000).rounded()) } }