Something went wrong. Try again.
Something went wrong. Try again.
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647import Foundationimport Logging
/// The form a comment event takes on the Postgres notification channel:/// what happened and to which record, never the record itself. The/// receiving side reads the comment from the table, so the payload stays/// far below the 8000-byte limit on notifications and every stream sends/// the same shape the read routes return.struct CommentNotification: Codable, Sendable, Equatable { let subject: String let type: CommentStreamEvent.Kind var uri: String? var commentUri: String? var likeCount: Int? var actorDid: String?
init(subject: String, event: CommentStreamEvent) { self.subject = subject self.type = event.type self.uri = event.type == .created ? event.comment?.uri : event.uri self.commentUri = event.commentUri self.likeCount = event.likeCount self.actorDid = event.actorDid }}
/// Publishes comment events with `NOTIFY`, so every instance with an open/// stream for the subject delivers them, whichever instance indexed the/// record. A failed publish is logged and dropped: the comment is in the/// table, and a client that reloads sees it.struct CommentEventPublisher: Sendable { static let channel = "effem_comments"
let database: Database let logger: Logger
func publish(subject: String, _ event: CommentStreamEvent) async { guard !subject.isEmpty else { return } do { let payload = String(decoding: try WireCoding.encoder.encode(CommentNotification(subject: subject, event: event)), as: UTF8.self) try await database.execute("SELECT pg_notify(\(Self.channel), \(payload))") } catch { logger.warning("comment event publish failed", metadata: ["subject": "\(subject)", "type": "\(event.type.rawValue)", "error": "\(error)"]) } }}