All files / utils activeUsers.js

97.05% Statements 33/34
100% Branches 13/13
100% Functions 5/5
96.55% Lines 28/29

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                  3x             3x   3x                     15x   12x 15x     15x 21x 15x 15x   15x 15x                               10x   5x 2x                 8x 8x 77x     77x   8x                     7x   75x                 75x       7x 7x 75x   7x     3x  
/**
 * Monthly active users, kept as one HyperLogLog sketch per month (see
 * hyperLogLog.js for why a sketch rather than per-user markers or summed daily
 * counts). One item per month in ActiveUsersMonthlyTable:
 *   { month: 'YYYY-MM', sketch: Binary, activeUsers: number, version: number, updatedAt }
 * `activeUsers` is the pre-computed estimate so a read never has to touch the
 * 16 KB sketch.
 */
 
const { GetCommand, UpdateCommand } = require('@aws-sdk/lib-dynamodb')
const {
  createSketch,
  deserializeSketch,
  serializeSketch,
  addToSketch,
  estimateCardinality
} = require('./hyperLogLog')
 
const MAX_WRITE_ATTEMPTS = 3
 
/**
 * Folds a day's active user ids into their month's sketch. Safe to re-run for
 * the same day (adding an id already in the sketch changes nothing). The write
 * is conditioned on the item version read so two overlapping runs can't
 * silently drop each other's users: the loser re-reads and merges again.
 *
 * @returns {Promise<number|null>} the month's new estimate, or null if there was nothing to record
 */
async function recordActiveUsers(docClient, tableName, month, userIds) {
  if (userIds.length === 0) return null
 
  for (let attempt = 1; attempt <= MAX_WRITE_ATTEMPTS; attempt++) {
    const { Item } = await docClient.send(
      new GetCommand({ TableName: tableName, Key: { month }, ConsistentRead: true })
    )
    const sketch = Item?.sketch ? deserializeSketch(Item.sketch) : createSketch()
    userIds.forEach((userId) => addToSketch(sketch, userId))
    const activeUsers = estimateCardinality(sketch)
    const previousVersion = Item?.version ?? 0
 
    try {
      await docClient.send(
        new UpdateCommand({
          TableName: tableName,
          Key: { month },
          UpdateExpression:
            'SET sketch = :sketch, activeUsers = :activeUsers, version = :version, updatedAt = :now',
          ConditionExpression: 'attribute_not_exists(version) OR version = :previousVersion',
          ExpressionAttributeValues: {
            ':sketch': serializeSketch(sketch),
            ':activeUsers': activeUsers,
            ':version': previousVersion + 1,
            ':previousVersion': previousVersion,
            ':now': new Date().toISOString()
          }
        })
      )
      return activeUsers
    } catch (error) {
      if (error.name !== 'ConditionalCheckFailedException' || attempt === MAX_WRITE_ATTEMPTS) {
        throw error
      }
    }
  }
  return null
}
 
/** The last `count` months ending at `referenceDate`'s month, oldest first (`YYYY-MM`, UTC). */
function getRecentMonths(count, referenceDate = new Date()) {
  const months = []
  for (let offset = count - 1; offset >= 0; offset--) {
    const date = new Date(
      Date.UTC(referenceDate.getUTCFullYear(), referenceDate.getUTCMonth() - offset, 1)
    )
    months.push(date.toISOString().slice(0, 7))
  }
  return months
}
 
/**
 * Estimated active users for each of the given months. Months with no recorded
 * activity (including months from before this was tracked) are simply absent,
 * so a chart doesn't show a misleading 0 for them.
 *
 * @returns {Promise<Record<string, number>>}
 */
async function getActiveUsersByMonth(docClient, tableName, months) {
  const items = await Promise.all(
    months.map(async (month) => {
      const { Item } = await docClient.send(
        new GetCommand({
          TableName: tableName,
          Key: { month },
          // 'month' is a DynamoDB reserved word
          ProjectionExpression: '#month, activeUsers',
          ExpressionAttributeNames: { '#month': 'month' }
        })
      )
      return Item
    })
  )
 
  const byMonth = {}
  for (const item of items) {
    if (item) byMonth[item.month] = item.activeUsers
  }
  return byMonth
}
 
module.exports = { recordActiveUsers, getRecentMonths, getActiveUsersByMonth }