import Foundation import Hummingbird import HummingbirdWebSocket import Logging /// `xyz.effem.feed.subscribeComments`: one WebSocket per open episode view. /// The client passes `?subject=at://…` and receives one JSON frame per /// indexed create, delete, like or unlike on that episode's comments. /// /// A client that has a signed-in user also says who is looking, the way it /// does on the read routes (see ``Viewer``). New comments from either side of /// a block with that viewer are then left off the stream, as they are left /// out of `getComments` (see ``StreamVisibility``). struct CommentStreamRoute: Sendable { let events: CommentEventBus let blocks: StreamVisibility.BlockLookup let authRequired: Bool let logger: Logger static let path = "/xrpc/xyz.effem.feed.subscribeComments" func register(on router: Router) { router.ws(RouterPath(Self.path), shouldUpgrade: { request, context in if authRequired, context.identity == nil { throw AppError.authRequired("missing bearer token or x-api-key") } guard QueryValues.trimmed(request.uri.queryParameters["subject"].map(String.init)) != nil else { throw AppError.invalidRequest("subject is required") } return .upgrade([:]) }, onUpgrade: { inbound, outbound, context in guard let subject = QueryValues.trimmed(context.request.uri.queryParameters["subject"].map(String.init)) else { return } let viewer = Viewer.did(of: context.requestContext.identity, in: context.request) let subscription = await events.subscribe(subject: subject) do { try await withThrowingTaskGroup(of: Void.self) { group in group.addTask { // The client sends nothing meaningful; draining keeps pings answered // and ends the stream when the socket closes. for try await _ in inbound {} } group.addTask { var visibility = StreamVisibility(viewer: viewer, lookup: blocks, logger: logger) for await event in subscription.events { guard await visibility.admits(event) else { continue } let data = try WireCoding.encoder.encode(event) try await outbound.write(.text(String(decoding: data, as: UTF8.self))) } } try await group.next() group.cancelAll() } } catch { logger.debug("comment stream ended", metadata: ["subject": "\(subject)", "error": "\(error)"]) } await events.unsubscribe(subject: subject, id: subscription.id) }) } }