All files / utils webSocketPush.js

100% Statements 27/27
100% Branches 10/10
100% Functions 5/5
100% Lines 26/26

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 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89                                    20x 20x         20x   20x 20x   20x   3x 1x       3x       5x                 5x       9x 4x     5x 5x 2x     3x 3x   3x   4x 4x       2x 1x           1x   1x           20x  
/**
 * Best-effort push of a JSON payload to every active WebSocket connection a
 * user has open (they may have several tabs/devices), via
 * WebSocketConnectionsTable's `userIndex` GSI (PK userId).
 *
 * On a stale connection (`GoneException` / HTTP 410 — the client
 * disconnected without API Gateway's $disconnect route firing, e.g. a
 * crashed tab), the dead row is pruned inline rather than left for
 * WebSocketConnectionsTable's TTL to eventually clean up — cheaper than a
 * separate sweep, and keeps future pushes from repeatedly retrying a
 * connection that's already gone.
 *
 * Requires WEBSOCKET_API_ENDPOINT (the API Gateway Management API endpoint
 * for the deployed WebSocket API/stage) to be set; when it isn't (e.g. a
 * lambda invoked outside the full stack, or in a test), this is a no-op —
 * callers treat the push as best-effort and never let it fail the request.
 */
 
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb')
const { DynamoDBDocumentClient, QueryCommand, DeleteCommand } = require('@aws-sdk/lib-dynamodb')
const {
  ApiGatewayManagementApiClient,
  PostToConnectionCommand,
  GoneException
} = require('@aws-sdk/client-apigatewaymanagementapi')
 
const client = new DynamoDBClient({})
const docClient = DynamoDBDocumentClient.from(client)
 
let managementApiClient = null
function getManagementApiClient() {
  if (!managementApiClient) {
    managementApiClient = new ApiGatewayManagementApiClient({
      endpoint: process.env.WEBSOCKET_API_ENDPOINT
    })
  }
  return managementApiClient
}
 
async function getConnectionIdsForUser(userId) {
  const result = await docClient.send(
    new QueryCommand({
      TableName: process.env.WEBSOCKET_CONNECTIONS_TABLE_NAME,
      IndexName: 'userIndex',
      KeyConditionExpression: 'userId = :userId',
      ExpressionAttributeValues: { ':userId': userId },
      ProjectionExpression: 'connectionId'
    })
  )
  return (result.Items || []).map((item) => item.connectionId)
}
 
async function pushToUserConnections(userId, payload) {
  if (!process.env.WEBSOCKET_API_ENDPOINT) {
    return
  }
 
  const connectionIds = await getConnectionIdsForUser(userId)
  if (connectionIds.length === 0) {
    return
  }
 
  const apiClient = getManagementApiClient()
  const data = Buffer.from(JSON.stringify(payload))
 
  await Promise.all(
    connectionIds.map(async (connectionId) => {
      try {
        await apiClient.send(
          new PostToConnectionCommand({ ConnectionId: connectionId, Data: data })
        )
      } catch (error) {
        if (error instanceof GoneException) {
          await docClient.send(
            new DeleteCommand({
              TableName: process.env.WEBSOCKET_CONNECTIONS_TABLE_NAME,
              Key: { connectionId }
            })
          )
          return
        }
        throw error
      }
    })
  )
}
 
module.exports = { pushToUserConnections }