All files / admin growth-events.js

100% Statements 20/20
100% Branches 4/4
100% Functions 5/5
100% Lines 19/19

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                          1x 1x 1x   1x     5x                 12x         5x 5x 5x 12x 12x 10x     10x 10x   5x     1x 5x 5x   4x        
// @implements UC-ADMIN-002.1
/**
 * Counts platform growth events per UTC day, fed by the UsersTable, FlowsTable
 * and EntitiesTable DynamoDB streams (KEYS_ONLY, INSERT and REMOVE only — see
 * admin-analytics-nested-stack.ts). Reading the streams rather than instrumenting
 * each write path also covers cascades, imports and forks. The e2e account reset
 * overwrites an existing row: that is a MODIFY, so it counts as neither.
 *
 * Streams deliver at least once and ADD is not idempotent, so a retried batch can
 * count a few events twice: an accepted error for a dashboard, not worth a
 * stored marker per event.
 */
 
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb')
const { DynamoDBDocumentClient } = require('@aws-sdk/lib-dynamodb')
const { addDailyCounts } = require('../utils/platformGrowth')
 
const docClient = DynamoDBDocumentClient.from(new DynamoDBClient({}))
 
function getCountersByTable() {
  return {
    [process.env.USERS_TABLE_NAME]: { INSERT: 'signups', REMOVE: 'usersDeleted' },
    [process.env.FLOWS_TABLE_NAME]: { INSERT: 'flowsCreated', REMOVE: 'flowsDeleted' },
    [process.env.ENTITIES_TABLE_NAME]: { INSERT: 'entitiesCreated', REMOVE: 'entitiesDeleted' }
  }
}
 
/** arn:aws:dynamodb:<region>:<account>:table/<name>/stream/<label> → <name> */
function tableNameOf(record) {
  return record.eventSourceARN.split('/')[1]
}
 
/** @returns {Record<string, Record<string, number>>} day -> counter -> count */
function countEventsByDay(records) {
  const countersByTable = getCountersByTable()
  const byDay = {}
  for (const record of records) {
    const counter = countersByTable[tableNameOf(record)]?.[record.eventName]
    if (!counter) continue
    const day = new Date(record.dynamodb.ApproximateCreationDateTime * 1000)
      .toISOString()
      .slice(0, 10)
    byDay[day] ??= {}
    byDay[day][counter] = (byDay[day][counter] ?? 0) + 1
  }
  return byDay
}
 
exports.handler = async (event) => {
  const byDay = countEventsByDay(event.Records)
  await Promise.all(
    Object.entries(byDay).map(([day, counts]) =>
      addDailyCounts(docClient, process.env.PLATFORM_GROWTH_DAILY_TABLE_NAME, day, counts)
    )
  )
}