All files / utils platformGrowth.js

100% Statements 31/31
81.81% Branches 9/11
100% Functions 9/9
100% Lines 27/27

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                  3x 3x   3x                                     60x 59x 59x                 4x 4x       9x   9x               12x                       6x 6x 180x             180x   6x                   6x   180x 180x       54x 6x 180x 1x 9x 9x       6x     3x              
/**
 * Daily platform growth history, one item per UTC day in PlatformGrowthDailyTable:
 *   { day: 'YYYY-MM-DD', signups, usersDeleted, flowsCreated, flowsDeleted,
 *     entitiesCreated, entitiesDeleted, totalUsers, totalFlows, totalEntities }
 * The counters record events as they happen (admin/growth-events.js), so a
 * deleted row keeps its creation in the history, which counting surviving rows
 * by `createdAt` cannot do. The totals are a daily snapshot (usage/aggregate.js).
 */
 
const { DescribeTableCommand } = require('@aws-sdk/client-dynamodb')
const { GetCommand, UpdateCommand } = require('@aws-sdk/lib-dynamodb')
 
const GROWTH_ATTRIBUTES = [
  'signups',
  'usersDeleted',
  'flowsCreated',
  'flowsDeleted',
  'entitiesCreated',
  'entitiesDeleted',
  'totalUsers',
  'totalFlows',
  'totalEntities'
]
 
/**
 * DynamoDB refreshes a table's ItemCount roughly every 6 hours — a coarse but
 * zero-cost snapshot, and avoids the full table Scan a live count would need.
 *
 * @param {import('@aws-sdk/client-dynamodb').DynamoDBClient} client
 */
async function getApproximateItemCount(client, tableName) {
  if (!tableName) return null
  const result = await client.send(new DescribeTableCommand({ TableName: tableName }))
  return result.Table?.ItemCount ?? null
}
 
/**
 * Adds events to a day's counters.
 *
 * @param {Record<string, number>} counts e.g. `{ signups: 2, flowsDeleted: 1 }`
 */
async function addDailyCounts(docClient, tableName, day, counts) {
  const counters = Object.keys(counts)
  await docClient.send(
    new UpdateCommand({
      TableName: tableName,
      Key: { day },
      UpdateExpression: `ADD ${counters.map((counter) => `${counter} :${counter}`).join(', ')}`,
      ExpressionAttributeValues: Object.fromEntries(
        counters.map((counter) => [`:${counter}`, counts[counter]])
      )
    })
  )
}
 
/** Idempotent overwrite (SET, not ADD): a re-run for the same day replaces its snapshot. */
async function recordDailyTotals(docClient, tableName, day, { users, flows, entities }) {
  await docClient.send(
    new UpdateCommand({
      TableName: tableName,
      Key: { day },
      UpdateExpression: 'SET totalUsers = :users, totalFlows = :flows, totalEntities = :entities',
      ExpressionAttributeValues: { ':users': users, ':flows': flows, ':entities': entities }
    })
  )
}
 
/** The last `count` UTC days ending at `referenceDate`'s day, oldest first (`YYYY-MM-DD`). */
function getRecentDays(count, referenceDate = new Date()) {
  const days = []
  for (let offset = count - 1; offset >= 0; offset--) {
    const date = new Date(
      Date.UTC(
        referenceDate.getUTCFullYear(),
        referenceDate.getUTCMonth(),
        referenceDate.getUTCDate() - offset
      )
    )
    days.push(date.toISOString().slice(0, 10))
  }
  return days
}
 
/**
 * Each attribute's values over the given days. A day or attribute with nothing
 * recorded is absent, so a chart can tell "not tracked yet" from a real 0.
 *
 * @returns {Promise<Record<string, Record<string, number>>>} attribute -> day -> value
 */
async function getDailyGrowth(docClient, tableName, days) {
  const items = await Promise.all(
    days.map(async (day) => {
      const { Item } = await docClient.send(new GetCommand({ TableName: tableName, Key: { day } }))
      return Item
    })
  )
 
  const growth = Object.fromEntries(GROWTH_ATTRIBUTES.map((attribute) => [attribute, {}]))
  for (const item of items) {
    if (!item) continue
    for (const attribute of GROWTH_ATTRIBUTES) {
      Eif (item[attribute] !== undefined && item[attribute] !== null) {
        growth[attribute][item.day] = item[attribute]
      }
    }
  }
  return growth
}
 
module.exports = {
  getApproximateItemCount,
  addDailyCounts,
  recordDailyTotals,
  getRecentDays,
  getDailyGrowth
}