All files / utils entitySubscriberCount.js

100% Statements 24/24
100% Branches 8/8
100% Functions 6/6
100% Lines 20/20

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 10912x 12x     12x                             19x                                                 5x 5x 5x     2x                       2x                                     45x 203x 45x   34x 35x 35x     203x       35x     7x     34x     12x            
const { UpdateCommand, DeleteCommand, BatchGetCommand } = require('@aws-sdk/lib-dynamodb')
const { withCountFloor } = require('./counterFloor')
 
// DynamoDB BatchGetItem accepts at most 100 keys per table per request.
const BATCH_GET_LIMIT = 100
 
/**
 * A TransactWriteItems `Update` action adjusting an entity's subscriber
 * count by `delta`. Auto-vivifies the row on first ADD, so nothing needs
 * pre-seeding. A decrement carries a condition so the count never goes below
 * 0; when it fails (count already at 0 or missing) the transaction is
 * cancelled and the caller must retry without the count update
 * (see isCountFloorCancellation in counterFloor.js).
 *
 * @param {string} tableName
 * @param {string} entityId
 * @param {number} delta
 */
function buildSubscriberCountUpdate(tableName, entityId, delta) {
  return {
    Update: withCountFloor(
      {
        TableName: tableName,
        Key: { entityId },
        UpdateExpression: 'ADD #count :delta',
        ExpressionAttributeNames: { '#count': 'count' },
        ExpressionAttributeValues: { ':delta': delta }
      },
      delta
    )
  }
}
 
/**
 * Non-transactional +/- adjustment, for best-effort call sites (deleting a
 * single user's subscriptions across many entities that aren't themselves
 * being deleted) that don't already run inside a TransactWriteCommand.
 *
 * @param {import('@aws-sdk/lib-dynamodb').DynamoDBDocumentClient} docClient
 * @param {string} tableName
 * @param {string} entityId
 * @param {number} delta
 */
async function adjustSubscriberCount(docClient, tableName, entityId, delta) {
  const { Update: update } = buildSubscriberCountUpdate(tableName, entityId, delta)
  try {
    await docClient.send(new UpdateCommand(update))
  } catch (error) {
    // Decrement below 0 is refused: the count is already at its floor.
    if (error.name !== 'ConditionalCheckFailedException') throw error
  }
}
 
/**
 * Deletes an entity's subscriber-count row entirely (entity deletion).
 *
 * @param {import('@aws-sdk/lib-dynamodb').DynamoDBDocumentClient} docClient
 * @param {string} tableName
 * @param {string} entityId
 */
async function deleteSubscriberCount(docClient, tableName, entityId) {
  await docClient.send(
    new DeleteCommand({
      TableName: tableName,
      Key: { entityId }
    })
  )
}
 
/**
 * Batch-reads subscriber counts for many entities at once (entities/list.js,
 * catalog/list.js enrich a whole page of entities per request). Entities
 * with no row yet (never subscribed to) default to 0.
 *
 * @param {import('@aws-sdk/lib-dynamodb').DynamoDBDocumentClient} docClient
 * @param {string} tableName
 * @param {string[]} entityIds
 * @returns {Promise<Map<string, number>>}
 */
async function getSubscriberCounts(docClient, tableName, entityIds) {
  const uniqueIds = Array.from(new Set(entityIds)).filter(Boolean)
  const counts = new Map(uniqueIds.map((entityId) => [entityId, 0]))
  if (uniqueIds.length === 0) return counts
 
  for (let offset = 0; offset < uniqueIds.length; offset += BATCH_GET_LIMIT) {
    const chunk = uniqueIds.slice(offset, offset + BATCH_GET_LIMIT)
    const result = await docClient.send(
      new BatchGetCommand({
        RequestItems: {
          [tableName]: { Keys: chunk.map((entityId) => ({ entityId })) }
        }
      })
    )
    for (const item of result.Responses?.[tableName] || []) {
      // Floor at 0: the stored count can go negative from historical data
      // desyncs, but a negative subscriber count should never be displayed.
      counts.set(item.entityId, Math.max(0, item.count || 0))
    }
  }
  return counts
}
 
module.exports = {
  buildSubscriberCountUpdate,
  adjustSubscriberCount,
  deleteSubscriberCount,
  getSubscriberCounts
}