Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280import CoreATProtocolimport Foundationimport HTTPTypesimport Loggingimport WSClient
/// Reads the Jetstream firehose and feeds the indexer.////// One connection at a time, to the preferred host; on failure the policy/// backs off and eventually tries the other host. The saved cursor is a seq/// on the host it came from and a witnessed timestamp (rewound a few/// seconds) anywhere else, because seq values are instance-local.////// A session runs until a deadline, until the lease is lost, or until the/// task is cancelled. ``JetstreamConsumerService`` runs it without a/// deadline inside a long-lived process; ``IngestRunner`` runs it with one/// from the cron route, where a process only lives for the length of a/// request.struct JetstreamIngester: Sendable { static let cursorPersistInterval: Duration = .seconds(1) static let cursorPersistMaxFailures = 30 static let failoverRewindMicros: Int64 = 5_000_000 static let maxMessageSize = 4 * 1024 * 1024 /// Upgrade failures while resuming from a cursor before the cursor is /// assumed to be older than the server's retention and dropped. static let cursorFailuresBeforeReset = 2
let hosts: [String] let cursors: CursorStore let lease: IngestLease let indexer: Indexer let accounts: AccountStatusStore let identity: IdentityCache let knownDIDs: KnownDIDs let backfill: BackfillQueue let status: ConsumerStatus let logger: Logger
/// Reads until `deadline` passes (forever when nil), reconnecting after /// failures. `owner` must hold the lease; it is renewed while reading and /// the session ends if another reader takes it. func run(owner: String, until deadline: ContinuousClock.Instant?) async throws -> IngestReport { var policy = ReconnectPolicy(hostCount: hosts.count) var cursorFailures = 0 let progress = IngestProgress() var lastHost: String?
func report(_ outcome: IngestReport.Outcome) -> IngestReport { IngestReport(outcome: outcome, host: lastHost, progress: progress.snapshot) }
while !Task.isCancelled { if let deadline, ContinuousClock.now >= deadline { return report(.deadline) } let host = hosts[policy.hostIndex] lastHost = host let started = ContinuousClock.now var resumedFromCursor = false do { resumedFromCursor = try await connectOnce(host: host, owner: owner, deadline: deadline, progress: progress) policy.connected() cursorFailures = 0 logger.info("jetstream connection closed", metadata: ["host": "\(host)"]) } catch is CancellationError { status.disconnected() return report(.cancelled) } catch IngestError.leaseLost { status.disconnected() logger.warning("another reader took the ingest lease; stopping", metadata: ["host": "\(host)"]) return report(.leaseLost) } catch { let upgradeFailed = (error as? WebSocketClientError) == .webSocketUpgradeFailed if upgradeFailed, resumedFromCursor { cursorFailures += 1 if cursorFailures >= Self.cursorFailuresBeforeReset { logger.warning("jetstream rejected the saved cursor; starting from live and queueing a full backfill", metadata: ["host": "\(host)"]) try? await cursors.clear() await backfill.enqueue(knownDIDs.all) cursorFailures = 0 } } logger.error("jetstream disconnected, reconnecting", metadata: ["host": "\(host)", "error": "\(error)"]) } status.disconnected() if let deadline, ContinuousClock.now >= deadline { return report(.deadline) } policy.connectionEnded(after: started.duration(to: .now)) var delay = policy.nextDelay() if let deadline { delay = min(delay, ContinuousClock.now.duration(to: deadline)) } try await Task.sleep(for: delay) } return report(.cancelled) }
/// Connects, consumes until the connection ends or the deadline passes, /// and reports whether the connection resumed from a saved cursor. func connectOnce(host: String, owner: String, deadline: ContinuousClock.Instant?, progress: IngestProgress) async throws -> Bool { let saved = try await cursors.load() var subscription = JetstreamSubscription(host: host, kinds: JetstreamSubscription.Kind.allCases, collections: Indexer.collections) if let saved { subscription.cursor = saved.host == host ? .seq(saved.seq) : .timestamp(microseconds: max(saved.eventTimeMicros - Self.failoverRewindMicros, JetstreamSubscription.timestampCursorThreshold)) } let url = try subscription.url() logger.info("connecting to jetstream", metadata: ["host": "\(host)", "cursor": "\(subscription.cursor.map { "\($0.queryValue)" } ?? "live")"])
let configuration = WebSocketClientConfiguration( maxFrameSize: Self.maxMessageSize, additionalHeaders: [.secWebSocketProtocol: JetstreamSubscription.subprotocol], // Bounds the close-frame wait. Shutdown still spends NIOSSL's five-second // close_notify timeout on the host, which the client does not expose. closeTimeout: .seconds(2), autoPing: .enabled(timePeriod: .seconds(30)) ) try await WebSocketClient.connect(url: url.absoluteString, configuration: configuration, logger: logger) { inbound, _, _ in status.connected(to: host) try await withThrowingTaskGroup(of: Void.self) { group in group.addTask { for try await message in inbound.messages(maxSize: Self.maxMessageSize) { guard case .text(let text) = message else { continue } try await handle(frameText: text, progress: progress) } } group.addTask { try await persistCursor(host: host, owner: owner, progress: progress) } if let deadline { group.addTask { try await Task.sleep(until: deadline, clock: .continuous) logger.info("ingest run budget spent; disconnecting", metadata: ["host": "\(host)"]) } } try await group.next() group.cancelAll() } if let final = progress.takeIfDirty() { try? await cursors.save(SavedCursor(host: host, seq: final.seq, eventTimeMicros: final.eventTimeMicros)) } } return subscription.cursor != nil }
/// Saves the cursor once a second and renews the lease every few seconds. private func persistCursor(host: String, owner: String, progress: IngestProgress) async throws { var failures = 0 var lastRenewal = ContinuousClock.now while !Task.isCancelled { try await Task.sleep(for: Self.cursorPersistInterval) if let lastEvent = status.lastEventTime { AppMetrics.firehoseLag(seconds: Date().timeIntervalSince(lastEvent)) } do { if lastRenewal.duration(to: .now) >= IngestLease.renewalInterval { guard try await lease.renew(owner: owner) else { throw IngestError.leaseLost } lastRenewal = .now } if let position = progress.takeIfDirty() { try await cursors.save(SavedCursor(host: host, seq: position.seq, eventTimeMicros: position.eventTimeMicros)) } failures = 0 } catch IngestError.leaseLost { throw IngestError.leaseLost } catch { failures += 1 logger.warning("failed to persist cursor or renew the lease", metadata: ["error": "\(error)", "failures": "\(failures)"]) if failures >= Self.cursorPersistMaxFailures { throw IngestError.message("cursor persistence failed \(failures) times; reconnecting") } } } }
func handle(frameText: String, progress: IngestProgress) async throws { let frame: JetstreamFrame do { frame = try JetstreamFrame.decode(frameText) } catch JetstreamDecodingError.unknownEnvelope(let type) { logger.debug("skipping unknown jetstream envelope", metadata: ["type": "\(type)"]) return } switch frame { case .error(let error): throw error case .message(let event): progress.countEvent() if let seq = event.seq { status.observed(seq: seq) if let witnessed = event.witnessedAt, let date = try? ATDatetime(witnessed).date { progress.observe(seq: seq, eventTimeMicros: Int64(date.timeIntervalSince1970 * 1_000_000)) } } await handle(event, progress: progress) } }
func handle(_ event: JetstreamEvent, progress: IngestProgress) async { switch event { case .commit(let commit): await handle(commit, progress: progress) case .account(let account): AppMetrics.firehoseEvent(kind: "account", action: account.account.active ? "active" : "inactive") guard await knownDIDs.contains(account.did) else { return } do { try await accounts.upsert(did: account.did, active: account.account.active, status: account.account.status) } catch { logger.warning("account_status upsert failed", metadata: ["did": "\(account.did)", "error": "\(error)"]) } do { // Counters leave out hidden accounts, so they move when one changes state. try await indexer.refreshStats(touchedBy: account.did) } catch { logger.warning("counter refresh after an account event failed", metadata: ["did": "\(account.did)", "error": "\(ErrorSummary.describe(error))"]) } // An inactive account is hidden. A deleted one is not coming back, // so what was indexed from it is removed as well. guard AccountPurge.isDeletion(active: account.account.active, status: account.account.status) else { return } do { let removed = try await AccountPurge(indexer: indexer).purge(did: account.did) logger.info("purged deleted account", metadata: ["did": "\(account.did)", "rows": "\(removed)"]) } catch { logger.warning("purge of deleted account failed", metadata: ["did": "\(account.did)", "error": "\(ErrorSummary.describe(error))"]) } case .identity(let identityEvent): AppMetrics.firehoseEvent(kind: "identity", action: "") guard await knownDIDs.contains(identityEvent.did) else { return } await identity.noteSeen(identityEvent.did) case .sync(let sync): AppMetrics.firehoseEvent(kind: "sync", action: "") guard await knownDIDs.contains(sync.did) else { return } logger.info("sync event; queueing backfill", metadata: ["did": "\(sync.did)"]) await backfill.enqueue(sync.did) case .info(let info): AppMetrics.firehoseEvent(kind: "info", action: info.name) logger.warning("jetstream info", metadata: ["name": "\(info.name)", "message": "\(info.message ?? "")"]) if info.name == JetstreamInfo.outdatedCursor { await backfill.enqueue(knownDIDs.all) } case .unknown(let type): logger.debug("unknown jetstream event", metadata: ["type": "\(type)"]) } }
private func handle(_ commit: JetstreamCommit, progress: IngestProgress) async { guard Indexer.collections.contains(commit.collection) else { return } AppMetrics.firehoseEvent(kind: "commit", action: commit.operation.rawValue) logger.info("effem record event", metadata: ["action": "\(commit.operation.rawValue)", "collection": "\(commit.collection)", "rkey": "\(commit.rkey)", "repo": "\(commit.did)"]) switch commit.operation { case .create, .update: guard let record = commit.record else { await indexer.recordError(did: commit.did, collection: commit.collection, rkey: commit.rkey, cid: commit.cid, error: IngestError.message("commit has no record payload")) AppMetrics.indexerError(collection: commit.collection, action: commit.operation.rawValue) progress.countCommit(indexed: false) return } do { try await indexer.index(did: commit.did, collection: commit.collection, rkey: commit.rkey, cid: commit.cid, record: record, source: .live) await indexer.markResolved(did: commit.did, collection: commit.collection, rkey: commit.rkey) progress.countCommit(indexed: true) } catch { logger.warning("failed to index record", metadata: ["error": "\(error)", "uri": "\(commit.uri)"]) AppMetrics.indexerError(collection: commit.collection, action: commit.operation.rawValue) await indexer.recordError(did: commit.did, collection: commit.collection, rkey: commit.rkey, cid: commit.cid, error: error) progress.countCommit(indexed: false) } case .delete: do { try await indexer.delete(did: commit.did, collection: commit.collection, rkey: commit.rkey, source: .live) await indexer.markResolved(did: commit.did, collection: commit.collection, rkey: commit.rkey) progress.countCommit(indexed: true) } catch { logger.warning("failed to delete record", metadata: ["error": "\(error)", "uri": "\(commit.uri)"]) AppMetrics.indexerError(collection: commit.collection, action: "delete") await indexer.recordError(did: commit.did, collection: commit.collection, rkey: commit.rkey, cid: nil, error: error) progress.countCommit(indexed: false) } } }}