import type { EventHubService } from '@pikku/core/channel' import type * as uWS from 'uWebSockets.js' export class UWSEventHubService< Mappings extends Record = {}, > implements EventHubService { private sockets: Map> = new Map() constructor() {} public async subscribe( topic: T, channelId: string ): Promise { const socket = this.sockets.get(channelId) socket?.subscribe(topic as string) } public async unsubscribe( topic: T, channelId: string ): Promise { const socket = this.sockets.get(channelId) socket?.unsubscribe(topic as string) } public async publish( topic: T, channelId: string | null, message: Mappings[T], isBinary?: boolean ): Promise { let socket: uWS.WebSocket | undefined if (channelId) { socket = this.sockets.get(channelId) } else { socket = this.sockets.values().next().value } if (socket) { this.forwardPublishMessage(socket, topic as string, message, isBinary) } } public async onChannelOpened( channelId: string, socket: uWS.WebSocket ): Promise { this.sockets.set(channelId, socket) } public async onChannelClosed(channelId: string): Promise { this.sockets.delete(channelId) } private forwardPublishMessage( source: uWS.TemplatedApp | uWS.WebSocket, topic: string, message: any, isBinary?: boolean ): void { if (isBinary) { source?.publish(topic, message, true) } else { source?.publish(topic, JSON.stringify(message), false) } } }