import Foundation import Logging /// Decides which comment events one open stream delivers to its viewer. /// /// The read routes leave out comments from either side of a block with the /// viewer. A stream has to do the same, or a comment the list would never /// show arrives live and stays on screen until the next reload. /// /// The viewer's blocks are read when the first new comment arrives and again /// once they are older than ``refreshInterval``, so a block made while a /// stream is open takes effect on it within that time. Only new comments are /// checked: a delete or a like count for a comment the viewer was never sent /// changes nothing on their screen. /// /// Accounts that are banned or inactive need no check here. Their records /// are never announced in the first place (see ``Indexer/Source``). struct StreamVisibility: Sendable { /// The DIDs on either side of a block with `viewer`. typealias BlockLookup = @Sendable (_ viewer: String) async throws -> Set static let refreshInterval: Duration = .seconds(60) /// The account the stream is for, or nil when nobody is named. Without /// a viewer there are no blocks to apply and everything is delivered. let viewer: String? let lookup: BlockLookup let logger: Logger private var blocked: Set = [] private var loadedAt: ContinuousClock.Instant? init(viewer: String?, lookup: @escaping BlockLookup, logger: Logger) { self.viewer = viewer self.lookup = lookup self.logger = logger } /// Whether `event` goes out on this stream. mutating func admits(_ event: CommentStreamEvent, now: ContinuousClock.Instant = .now) async -> Bool { guard let viewer, event.type == .created, let author = event.comment?.did, author != viewer else { return true } await refreshBlocks(of: viewer, now: now) return !blocked.contains(author) } /// Reads the viewer's blocks when they have never been read or have gone /// stale. A failed read keeps what was known and is tried again with the /// next comment, so one bad moment neither opens the stream to everyone /// nor silences it. private mutating func refreshBlocks(of viewer: String, now: ContinuousClock.Instant) async { if let loadedAt, loadedAt.duration(to: now) < Self.refreshInterval { return } do { blocked = try await lookup(viewer) loadedAt = now } catch { logger.warning("could not read blocks for a comment stream", metadata: ["error": "\(ErrorSummary.describe(error))"]) } } }