All files / apps / api/src / server / hub workspace-hub.ts

100% Statements 15/15
100% Branches 4/4
100% Functions 2/2
100% Lines 14/14

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37              4x 2x     2x   2x   1x 1x   1x         2x 2x   2x 2x 1x 1x       2x      
import { HTTP_STATUS, type RealtimeEvent } from '@chattra/shared'
import { DurableObject } from 'cloudflare:workers'
 
// One per workspace; holds every socket, tagged by user id (design #12, 2.3).
// Not routed yet: /ws opens only after the one-time ticket check lands in M3.
export class WorkspaceHub extends DurableObject<Env> {
  override async fetch(request: Request): Promise<Response> {
    if (request.headers.get('Upgrade') !== 'websocket') {
      return new Response('Expected WebSocket', { status: HTTP_STATUS.upgradeRequired })
    }
 
    const userId = new URL(request.url).searchParams.get('userId')
 
    if (!userId) return new Response('Missing userId', { status: HTTP_STATUS.badRequest })
 
    const { 0: client, 1: server } = new WebSocketPair()
    this.ctx.acceptWebSocket(server, [userId])
 
    return new Response(null, { status: HTTP_STATUS.switchingProtocols, webSocket: client })
  }
 
  // Sends one event to every socket of the given users.
  broadcast(userIds: string[], event: RealtimeEvent): number {
    const payload = JSON.stringify(event)
    let sent = 0
 
    for (const userId of userIds) {
      for (const socket of this.ctx.getWebSockets(userId)) {
        socket.send(payload)
        sent++
      }
    }
 
    return sent
  }
}