Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142import Loggingimport ServiceLifecycle
/// The in-process Jetstream reader, for hosts where the process lives as/// long as the service does (local runs, the Docker image). It takes the/// ingest lease and reads until shutdown; if a cron run or another instance/// holds the lease it waits and tries again.struct JetstreamConsumerService: Service { static let leaseRetryInterval: Duration = .seconds(5)
let ingester: JetstreamIngester let lease: IngestLease let logger: Logger
func run() async throws { let owner = IngestLease.makeOwner() try await cancelWhenGracefulShutdown { while !Task.isCancelled { let acquired: Bool do { acquired = try await lease.acquire(owner: owner) } catch { logger.warning("could not check the ingest lease", metadata: ["error": "\(error)"]) try await Task.sleep(for: Self.leaseRetryInterval) continue } guard acquired else { logger.debug("ingest lease is held elsewhere; waiting") try await Task.sleep(for: Self.leaseRetryInterval) continue } let report = try await ingester.run(owner: owner, until: nil) if report.outcome == .cancelled { return } try await Task.sleep(for: Self.leaseRetryInterval) } } // Graceful shutdown cancels the work above, not this task, so the lease // can still be handed back for the next process to take at once. try? await lease.release(owner: owner) }}