All files / utils notifications.js

100% Statements 26/26
100% Branches 2/2
100% Functions 5/5
100% Lines 25/25

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 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137                                    18x 18x 18x 18x   18x 18x     18x   18x                                       249x       96x                         91x 91x 91x 91x                 91x                                         5x 5x   1x           33x   33x 34x                 34x 34x   33x     18x                    
/**
 * The notifications inbox: things that happened to a user that they should
 * hear about, as opposed to Direct Messages someone wrote to them. Built on the
 * same plumbing as DMs — a per-user partition, a denormalized unread counter
 * reset by "mark as read", and a best-effort WebSocket push after the write
 * commits (utils/webSocketPush.js), with REST as the source of truth.
 *
 * NotificationsTable (PK userId, SK sortKey) holds two kinds of rows per user:
 * - one notification per row, sortKey `N#{createdAt}#{id}`, so a Query on the
 *   `N#` prefix lists them newest first; TTL'd, so the inbox is recent history
 * - one state row, sortKey `STATE`: `unreadCount` and `lastReadAt`
 *
 * A notification is written by the producer's own transaction (see
 * `buildNotificationWrites`), so it exists exactly when the event does.
 *
 * @implements UC-NOTIF-001.1, UC-NOTIF-002.1
 */
 
const { randomUUID } = require('crypto')
const { QueryCommand } = require('@aws-sdk/lib-dynamodb')
const { batchDelete } = require('./batchWrite')
const { pushToUserConnections } = require('./webSocketPush')
 
const NOTIFICATION_PREFIX = 'N#'
const STATE_SORT_KEY = 'STATE'
 
/** A notification lives 90 days, then DynamoDB TTL removes it. */
const NOTIFICATION_TTL_SECONDS = 90 * 24 * 60 * 60
 
const NOTIFICATION_TYPE = {
  COMMENT_REJECTED: 'comment-rejected',
  COMMENT_REMOVED: 'comment-removed',
  // An Email action could not reach some recipients (UC-WORKFLOW-011.1), told to the flow owner
  AUTOMATION_EMAIL_SKIPPED: 'automation-email-skipped',
  // A pack the flow installed has a new version (UC-STORE-013.1), told to the flow owner
  PACK_VERSION_PUBLISHED: 'pack-version-published',
  // A platform admin acted on reports of the user's content (UC-REPORT-006.1):
  // what was decided, why, and how to contest it
  MODERATION_DECISION: 'moderation-decision',
  // A platform admin decided on content the user reported (UC-REPORT-006.1)
  REPORT_DECIDED: 'report-decided',
  // A platform admin decided the user's appeal of a moderation decision (UC-REPORT-010.1)
  APPEAL_DECIDED: 'appeal-decided',
  // Many of the user's reports were found unfounded: reporting may be suspended (UC-REPORT-011.1)
  REPORTING_WARNING: 'reporting-warning',
  // The user's reports are refused until a date (UC-REPORT-011.1)
  REPORTING_SUSPENDED: 'reporting-suspended'
}
 
const notificationsTable = () => process.env.NOTIFICATIONS_TABLE_NAME
 
/** The shape a client sees: no keys, no TTL. */
function toPublicNotification(row) {
  return { id: row.id, type: row.type, data: row.data, createdAt: row.createdAt }
}
 
/**
 * The TransactItems that deliver a notification: the notification row and the
 * recipient's unread counter. The caller adds them to its own transaction.
 *
 * @param {string} userId the recipient
 * @param {{ type: string, data: object }} content
 * @returns {{ notification: object, writes: object[] }} the public notification
 *   (to push once the transaction commits) and the writes
 */
function buildNotificationWrites(userId, { type, data }) {
  const nowMs = Date.now()
  const createdAt = new Date(nowMs).toISOString()
  const id = randomUUID()
  const row = {
    userId,
    sortKey: `${NOTIFICATION_PREFIX}${createdAt}#${id}`,
    id,
    type,
    data,
    createdAt,
    expiresAt: Math.floor(nowMs / 1000) + NOTIFICATION_TTL_SECONDS
  }
  return {
    notification: toPublicNotification(row),
    writes: [
      { Put: { TableName: notificationsTable(), Item: row } },
      {
        Update: {
          TableName: notificationsTable(),
          Key: { userId, sortKey: STATE_SORT_KEY },
          UpdateExpression: 'ADD unreadCount :one',
          ExpressionAttributeValues: { ':one': 1 }
        }
      }
    ]
  }
}
 
/**
 * Best-effort live delivery of a committed notification: a failure is logged
 * and swallowed — the recipient still gets it on their next fetch.
 */
async function pushNotification(userId, notification) {
  try {
    await pushToUserConnections(userId, { type: 'notification', notification })
  } catch (error) {
    console.error('[notifications] WebSocket push failed:', error.message)
  }
}
 
/** Every row of a user's partition: their notifications and their state row. */
async function deleteAllNotificationsForUser(docClient, userId) {
  const keys = []
  let lastKey
  do {
    const result = await docClient.send(
      new QueryCommand({
        TableName: notificationsTable(),
        KeyConditionExpression: 'userId = :userId',
        ExpressionAttributeValues: { ':userId': userId },
        ProjectionExpression: 'userId, sortKey',
        ExclusiveStartKey: lastKey
      })
    )
    keys.push(...(result.Items || []))
    lastKey = result.LastEvaluatedKey
  } while (lastKey)
  await batchDelete(docClient, notificationsTable(), keys)
}
 
module.exports = {
  NOTIFICATION_PREFIX,
  STATE_SORT_KEY,
  NOTIFICATION_TTL_SECONDS,
  NOTIFICATION_TYPE,
  toPublicNotification,
  buildNotificationWrites,
  pushNotification,
  deleteAllNotificationsForUser
}