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 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 21x 21x 23x 21x 14x 14x 15x 71x 15x 14x 14x 14x 15x 15x 2x 1x 1x 1x 14x 14x 78x 12x 15x 15x 88x 15x 15x 12x 12x 18x 18x 18x 2x 2x 2x 16x 12x 16x 8x 8x 8x 8x 8x 6x 8x 20x 17x 8x 8x 11x 9x 9x 18x 14x 14x 20x 20x 15x 15x 5x 1x 1x 20x 20x 20x 20x 20x 20x 20x 1x 1x 1x 19x 15x 105x 14x 37x 24x 14x 14x 14x 1x 3x 35x 13x 12x 12x 12x 36x 13x 13x 13x 13x 13x 13x 2x 1x 16x 16x 16x 25x 25x 25x 12x 36x 12x 1x 12x 12x 12x 12x 12x 12x 10x 10x 11x 11x 10x 10x 10x 10x 10x 11x 10x 10x 10x 10x 9x 9x 9x 9x 1x | /**
* Daily usage aggregation: credits debits and monthly active users
*
* @implements UC-CREDITS-007.1, UC-CREDITS-010.1, UC-CREDITS-011.1, UC-ADMIN-002.1
*/
const {
CloudWatchLogsClient,
DescribeLogGroupsCommand,
StartQueryCommand,
GetQueryResultsCommand
} = require('@aws-sdk/client-cloudwatch-logs')
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb')
const { DynamoDBDocumentClient, BatchGetCommand, UpdateCommand } = require('@aws-sdk/lib-dynamodb')
const { debitCreditsIdempotent, buildIdempotentTransactionId } = require('../utils/creditsLedger')
const { getPricingConfig } = require('../utils/pricingConfig')
const { getFreeFunctionKeys } = require('../utils/lambdaBillingConfig')
const { recordActiveUsers } = require('../utils/activeUsers')
const { getApproximateItemCount, recordDailyTotals } = require('../utils/platformGrowth')
const logsClient = new CloudWatchLogsClient({})
const dynamoClient = new DynamoDBClient({})
const docClient = DynamoDBDocumentClient.from(dynamoClient)
// See docs/architecture/USAGE_METERING.md "Aggregation (compute and
// throughput)" — StartQuery caps at 50 log groups per call.
const LOG_GROUP_CHUNK_SIZE = 50
// DynamoDB BatchGetItem caps at 100 keys per call.
const BATCH_GET_CHUNK_SIZE = 100
const QUERY_POLL_INTERVAL_MS = 1000
const QUERY_TIMEOUT_MS = 60000
// Daily rows only need to cover the current + previous billing cycle's
// drill-down — see "Monthly rollup" for what makes the data permanent.
const DAILY_SUMMARY_TTL_DAYS = 90
// How many (flow, function) lines of a user's day are kept by name on the
// daily row, busiest first; the rest are folded into one "other" line. Keeps
// the row far below DynamoDB's 400 KB item limit however many functions and
// flows a user touched.
const BREAKDOWN_MAX_ENTRIES = 20
// No bin(1d) here: StartQuery's own startTime/endTime already scope the
// query to exactly one calendar day (see dayToEpochRange), so the day is
// attached in code rather than re-derived from the query results. apiKeyId
// is a group-by dimension (not just a projected field) — without it, every
// API-key-authenticated call (userId and flowId both null at capture time,
// see "Attribution") would collapse into one undifferentiated group,
// making the later apiKeyId -> flowId -> owner resolution meaningless.
// resource/operation are likewise grouped on (not just projected) so a
// function marked "always free" in LambdaBillingTable (see
// filterFreeFunctions) can be excluded before its usage is folded into a
// user's billable total — without this, an admin's free-lambda override
// would have no per-function usage left to exclude by the time the query
// collapses everything down to one row per identity.
const USAGE_QUERY = `
fields userId, flowId, apiKeyId, resource, operation, durationMs, memoryMB, readUnits
| filter type = "usage_event" and unit = "lambda_invocation_ms"
| stats sum(durationMs * memoryMB / 1024 / 1000) as gbSeconds,
sum(readUnits) as totalReadUnits,
count(*) as events
by userId, flowId, apiKeyId, resource, operation
`
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms))
}
function chunkBy(items, size) {
const chunks = []
for (let i = 0; i < items.length; i += size) {
chunks.push(items.slice(i, i + size))
}
return chunks
}
/**
* None of the 75 lambdas set an explicit `functionName`, so CloudFormation's
* default naming (`{stackName}-{logicalId}-{hash}`) means every one of this
* stack's log groups shares the `/aws/lambda/${stackName}-` prefix — no
* hardcoded list to keep in sync as lambdas are added/removed. Paginates via
* DescribeLogGroups' own nextToken.
*/
async function discoverLogGroups(stackName) {
const logGroups = []
let nextToken
do {
const result = await logsClient.send(
new DescribeLogGroupsCommand({
logGroupNamePrefix: `/aws/lambda/${stackName}-`,
nextToken
})
)
logGroups.push(...(result.logGroups ?? []).map((g) => g.logGroupName))
nextToken = result.nextToken
} while (nextToken)
return logGroups
}
async function pollQueryResults(queryId) {
const deadline = Date.now() + QUERY_TIMEOUT_MS
for (;;) {
const result = await logsClient.send(new GetQueryResultsCommand({ queryId }))
if (result.status === 'Complete') return result.results ?? []
if (
result.status === 'Failed' ||
result.status === 'Cancelled' ||
result.status === 'Timeout'
) {
throw new Error(`Logs Insights query ${queryId} ended with status ${result.status}`)
}
Iif (Date.now() >= deadline) {
throw new Error(
`Logs Insights query ${queryId} did not complete within ${QUERY_TIMEOUT_MS}ms`
)
}
await sleep(QUERY_POLL_INTERVAL_MS)
}
}
async function runUsageQuery(logGroupNames, startTime, endTime) {
const { queryId } = await logsClient.send(
new StartQueryCommand({ logGroupNames, startTime, endTime, queryString: USAGE_QUERY })
)
return pollQueryResults(queryId)
}
/**
* A Logs Insights `stats ... by` group with no value for a dimension (e.g.
* userId on an API-key call) renders as an empty string rather than being
* omitted — normalized to `null` here so downstream code has one falsy
* representation to check, not two.
*/
function normalizeGroupValue(value) {
return value === undefined || value === null || value === '' ? null : value
}
function parseQueryResults(results) {
return results.map((row) => {
const obj = {}
for (const { field, value } of row) {
obj[field] = value
}
return obj
})
}
function toUsageRow(obj) {
return {
userId: normalizeGroupValue(obj.userId),
flowId: normalizeGroupValue(obj.flowId),
apiKeyId: normalizeGroupValue(obj.apiKeyId),
resource: normalizeGroupValue(obj.resource),
operation: normalizeGroupValue(obj.operation),
gbSeconds: Number(obj.gbSeconds) || 0,
totalReadUnits: Number(obj.totalReadUnits) || 0,
events: Number(obj.events) || 0
}
}
/**
* Undoes the log-group chunking from the caller's side: a user active
* across lambdas in more than one chunk gets one partial row per chunk,
* which must be summed — not concatenated — before anything downstream
* treats a (userId, flowId, apiKeyId, resource, operation) tuple as a single
* fact.
*/
function mergeUsageRows(rows) {
const merged = new Map()
for (const row of rows) {
const key = `${row.userId ?? ''}#${row.flowId ?? ''}#${row.apiKeyId ?? ''}#${row.resource ?? ''}/${row.operation ?? ''}`
const existing = merged.get(key)
if (existing) {
existing.gbSeconds += row.gbSeconds
existing.totalReadUnits += row.totalReadUnits
existing.events += row.events
} else {
merged.set(key, { ...row })
}
}
return [...merged.values()]
}
/**
* Drops every row belonging to a function an admin has marked "always free"
* in LambdaBillingTable (see utils/lambdaBillingConfig.js) — its compute,
* API Gateway calls and DynamoDB reads never reach a user's billable total,
* however busy that function is. Applied before mergeByUserId collapses
* rows down to one per identity, since a function's own usage can no longer
* be singled out once that happens.
*/
function filterFreeFunctions(rows, freeFunctionKeys) {
return rows.filter((row) => !freeFunctionKeys.has(`${row.resource}/${row.operation}`))
}
async function batchGetMap(tableName, ids, keyAttr, pick) {
const map = {}
for (const chunk of chunkBy(ids, BATCH_GET_CHUNK_SIZE)) {
const result = await docClient.send(
new BatchGetCommand({
RequestItems: { [tableName]: { Keys: chunk.map((id) => ({ [keyAttr]: id })) } }
})
)
for (const item of result.Responses?.[tableName] ?? []) {
map[item[keyAttr]] = pick(item)
}
}
return map
}
/**
* Resolves a user for API-key-driven rows (userId null, apiKeyId set): the
* key's creator (`createdBy` in ApiKeysTable) — the person the key acts for,
* consistent with a JWT call being charged to its own caller (see
* utils/creditsLedger.js's resolveBillingUserId, which does the same for the
* synchronous debits). The same user is who counts as "active" for the day.
* A deleted key or one with no creator resolves to null and is dropped by
* the caller — no user, no charge. flowId is kept for attribution, taken from
* the key's record when the row carries none. JWT rows (userId already set)
* pass through untouched.
*/
async function resolveApiKeyUserIds(rows, { apiKeysTableName }) {
const apiKeyIds = [...new Set(rows.filter((r) => !r.userId && r.apiKeyId).map((r) => r.apiKeyId))]
if (apiKeyIds.length === 0) return rows
const keyRecords = await batchGetMap(apiKeysTableName, apiKeyIds, 'id', (item) => ({
flowId: item.flowId || null,
createdBy: item.createdBy || null
}))
return rows.map((row) => {
if (row.userId || !row.apiKeyId) return row
const record = keyRecords[row.apiKeyId]
return {
...row,
userId: record?.createdBy || null,
flowId: row.flowId || record?.flowId || null
}
})
}
/**
* The distinct people who were active on the day: every row's userId once
* API keys are resolved to their creators. Taken before the free-function
* filter, since a call that costs nothing is still activity.
*/
function collectActiveUserIds(rows) {
return [...new Set(rows.filter((r) => r.userId).map((r) => r.userId))]
}
/**
* Final reduction to one row per billable userId for the day — a user can
* appear multiple times after billing resolution (their own JWT calls plus
* one or more API keys, possibly across different flows). flowId is a
* display/attribution convenience only (the billing key is userId — see
* "Attribution"), so the flowId from whichever contributing group had the
* most events is kept as "the" representative flow for that user's day.
*
* `usage` keeps what the merge would otherwise throw away: the day's usage
* per (flow, function, via an API key or not), so the Credits page can tell
* where a day's debit came from — see buildUsageBreakdown. Two API keys on
* the same flow are one line, as the user only needs to know the call came
* through a key.
*/
function mergeByUserId(rows) {
const merged = new Map()
for (const row of rows) {
let existing = merged.get(row.userId)
if (!existing) {
existing = {
userId: row.userId,
flowId: row.flowId,
gbSeconds: 0,
totalReadUnits: 0,
events: 0,
_topFlowEvents: row.flowId ? row.events : -1,
_usage: new Map()
}
merged.set(row.userId, existing)
} else if (row.flowId && row.events > existing._topFlowEvents) {
existing.flowId = row.flowId
existing._topFlowEvents = row.events
}
existing.gbSeconds += row.gbSeconds
existing.totalReadUnits += row.totalReadUnits
existing.events += row.events
const viaApiKey = !!row.apiKeyId
const usageKey = `${row.flowId ?? ''}#${row.resource ?? ''}/${row.operation ?? ''}#${viaApiKey}`
const line = existing._usage.get(usageKey)
if (line) {
line.gbSeconds += row.gbSeconds
line.totalReadUnits += row.totalReadUnits
line.events += row.events
} else {
existing._usage.set(usageKey, {
flowId: row.flowId ?? null,
resource: row.resource ?? null,
operation: row.operation ?? null,
viaApiKey,
gbSeconds: row.gbSeconds,
totalReadUnits: row.totalReadUnits,
events: row.events
})
}
}
return [...merged.values()].map(({ _topFlowEvents: _unused, _usage, ...rest }) => ({
...rest,
usage: [..._usage.values()]
}))
}
/** Credits to 2 decimals: a breakdown line is a share of a rounded total */
function roundCredits(value) {
return Math.round(value * 100) / 100
}
/**
* The user's day as the Credits page shows it: one line per (flow,
* function, via API key) with its own calls, compute, reads and credits,
* busiest first. Credits stay unrounded (2 decimals): the debit rounds each
* pool up once for the whole day, so rounding every line too would make
* them add up to more than what was charged — the lines are a split of the
* debit, the debit itself stays the reference. Beyond BREAKDOWN_MAX_ENTRIES,
* the remaining lines are summed into one `other` line, `count` saying how
* many it holds.
*/
function buildUsageBreakdown(usage, pricing) {
const lines = (usage ?? [])
.map((line) => ({
flowId: line.flowId,
resource: line.resource,
operation: line.operation,
viaApiKey: line.viaApiKey,
events: line.events,
gbSeconds: line.gbSeconds,
readUnits: line.totalReadUnits,
credits:
line.gbSeconds * pricing.lambda_compute_credits_per_gb_second +
line.events * pricing.api_gateway_credits_per_call +
line.totalReadUnits * pricing.dynamodb_read_credits_per_ru
}))
.sort((a, b) => b.credits - a.credits || b.events - a.events)
const kept = lines.slice(0, BREAKDOWN_MAX_ENTRIES)
const rest = lines.slice(BREAKDOWN_MAX_ENTRIES)
if (rest.length > 0) {
kept.push(
rest.reduce(
(other, line) => ({
...other,
events: other.events + line.events,
gbSeconds: other.gbSeconds + line.gbSeconds,
readUnits: other.readUnits + line.readUnits,
credits: other.credits + line.credits
}),
{
other: true,
count: rest.length,
flowId: null,
resource: null,
operation: null,
viaApiKey: false,
events: 0,
gbSeconds: 0,
readUnits: 0,
credits: 0
}
)
)
}
return kept.map((line) => ({
...line,
gbSeconds: roundCredits(line.gbSeconds),
readUnits: roundCredits(line.readUnits),
credits: roundCredits(line.credits)
}))
}
function computeCreditCost({ gbSeconds, events, totalReadUnits }, pricing) {
return Math.ceil(
gbSeconds * pricing.lambda_compute_credits_per_gb_second +
events * pricing.api_gateway_credits_per_call +
totalReadUnits * pricing.dynamodb_read_credits_per_ru
)
}
/**
* Applies the actual balance debit for one user's day of aggregated usage —
* the step the rest of this file's output (the two summary tables) was
* always meant to feed, but never actually triggered until now. Split into
* up to three ledger rows, one per pool (lambda_compute, api_gateway,
* dynamodb_throughput for reads), mirroring how a synchronous item write
* already debits storage and throughput as separate rows — see
* debitCredits in utils/creditsLedger.js.
*
* Each row's transactionId is deterministic (`usage#{day}#{pool}#{userId}`,
* prefixed by the end of the day — see buildIdempotentTransactionId — so the
* debit sorts with that day's other transactions rather than ahead of all of
* them),
* so debitCreditsIdempotent's own claim-before-debit guard makes a retried
* or duplicate invocation for the same day a no-op instead of a double
* charge — the same mechanism already used for S3 upload events, which can
* also be redelivered. debitCreditsIdempotent itself already skips a
* zero-cost charge, so no pre-filtering is needed here.
*/
async function debitAggregatedUsage(day, row, pricing) {
const dayEndMs = dayToEpochRange(day).endTime * 1000 + 999
const charges = [
{
pool: 'lambda_compute',
costCredits: Math.ceil(row.gbSeconds * pricing.lambda_compute_credits_per_gb_second)
},
{
pool: 'api_gateway',
costCredits: Math.ceil(row.events * pricing.api_gateway_credits_per_call)
},
{
pool: 'dynamodb_throughput',
costCredits: Math.ceil(row.totalReadUnits * pricing.dynamodb_read_credits_per_ru)
}
]
for (const charge of charges) {
await debitCreditsIdempotent(docClient, {
usersTableName: process.env.USERS_TABLE_NAME,
creditsLedgerTableName: process.env.CREDITS_LEDGER_TABLE_NAME,
userId: row.userId,
flowId: row.flowId,
transactionId: buildIdempotentTransactionId(
dayEndMs,
`usage#${day}#${charge.pool}#${row.userId}`
),
pool: charge.pool,
operation: 'usage_aggregation',
costCredits: charge.costCredits,
referenceId: day
})
}
}
/**
* Idempotent overwrite (SET, not ADD): re-running this lambda for a day
* already aggregated recomputes from the same immutable CloudWatch Logs
* source and replaces the row, rather than double-counting on retry.
* `breakdown` (see buildUsageBreakdown) is what GET /v1/credits?details=true
* returns for the day; it shares the row's TTL, so a day's detail is gone
* after DAILY_SUMMARY_TTL_DAYS while its ledger debit stays.
*/
async function writeDailySummary(tableName, day, row, creditCost, breakdown = []) {
const expiresAt = Math.floor(Date.now() / 1000) + DAILY_SUMMARY_TTL_DAYS * 24 * 60 * 60
const values =
'gbSeconds = :gbSeconds, totalReadUnits = :totalReadUnits, ' +
'eventCount = :eventCount, creditCost = :creditCost, breakdown = :breakdown, ' +
'expiresAt = :expiresAt'
await docClient.send(
new UpdateCommand({
TableName: tableName,
Key: { userId: row.userId, day },
// flowId is the flowIndex GSI key, which rejects a NULL value: a day with
// no flow attribution removes it instead (keeping the overwrite idempotent)
UpdateExpression: row.flowId
? `SET flowId = :flowId, ${values}`
: `SET ${values} REMOVE flowId`,
ExpressionAttributeValues: {
...(row.flowId ? { ':flowId': row.flowId } : {}),
':gbSeconds': row.gbSeconds,
':totalReadUnits': row.totalReadUnits,
':eventCount': row.events,
':creditCost': creditCost,
':breakdown': breakdown,
':expiresAt': expiresAt
}
})
)
}
/**
* Keeps UsageMonthlySummaryTable current incrementally, one day at a time,
* instead of a separate monthly job scanning UsageDailySummaryTable — see
* docs/architecture/USAGE_METERING.md "Monthly rollup" for why: that table
* is keyed by userId with no secondary way to enumerate "every user active
* in month X" without a full table scan (at the doc's own 100k-user,
* ~9M-row estimate, an unbounded monthly Scan the original design didn't
* account for). ADD accumulates the raw numbers *and* the day's already-
* rounded creditCost — cheaper than reading back and re-summing raw totals
* for one extra rounding operation, and the resulting drift (at most +1
* credit/day/user) is negligible next to the volumes at play.
*
* Idempotent against a re-run for the same day via `appliedDays`, a string
* set of every day already folded into this month's totals: the whole
* UpdateCommand (including the numeric ADDs) is conditioned on `day` not
* already being a member, and `day` is added to the set as part of the same
* write. A retried/duplicate invocation for a day already applied hits
* ConditionalCheckFailedException and is treated as a no-op, the same
* "claim before applying" shape as debitCreditsIdempotent. This was found
* missing (and this table found double-counted in practice) alongside the
* credits debit itself never having been wired up — see
* docs/architecture/USAGE_METERING.md "No signup grant yet, and platform
* admins bypass the check entirely" sibling section on aggregation.
*/
async function writeMonthlyIncrement(tableName, day, row, creditCost) {
const month = day.slice(0, 7)
try {
await docClient.send(
new UpdateCommand({
TableName: tableName,
Key: { userId: row.userId, month },
// No flowId to record leaves the attribute alone: a NULL would be
// rejected by the flowIndex GSI, whose key it is
UpdateExpression:
(row.flowId ? 'SET flowId = if_not_exists(flowId, :flowId) ' : '') +
'ADD gbSeconds :gbSeconds, totalReadUnits :totalReadUnits, eventCount :eventCount, ' +
'creditCost :creditCost, appliedDays :day',
ConditionExpression:
'attribute_not_exists(appliedDays) OR NOT contains(appliedDays, :dayValue)',
ExpressionAttributeValues: {
...(row.flowId ? { ':flowId': row.flowId } : {}),
':gbSeconds': row.gbSeconds,
':totalReadUnits': row.totalReadUnits,
':eventCount': row.events,
':creditCost': creditCost,
':day': new Set([day]),
':dayValue': day
}
})
)
} catch (error) {
if (error.name === 'ConditionalCheckFailedException') return
throw error
}
}
/** Yesterday (UTC), as `YYYY-MM-DD` — see [Aggregation] for why the lambda
* always aggregates the previous full day rather than "today so far". */
function getTargetDay(referenceDate = new Date()) {
const yesterday = new Date(referenceDate)
yesterday.setUTCDate(yesterday.getUTCDate() - 1)
return yesterday.toISOString().slice(0, 10)
}
function dayToEpochRange(day) {
const startTime = Math.floor(new Date(`${day}T00:00:00.000Z`).getTime() / 1000)
const endTime = startTime + 24 * 60 * 60 - 1
return { startTime, endTime }
}
/**
* Snapshots yesterday's platform totals for the admin growth charts. Filed
* under the day just ended: taken at 03:00 UTC, and ItemCount lags by up to
* 6 hours anyway, so this is the closest available end-of-day figure.
*/
async function recordGrowthTotals(day) {
const [users, flows, entities] = await Promise.all(
[
process.env.USERS_TABLE_NAME,
process.env.FLOWS_TABLE_NAME,
process.env.ENTITIES_TABLE_NAME
].map((tableName) => getApproximateItemCount(dynamoClient, tableName))
)
await recordDailyTotals(docClient, process.env.PLATFORM_GROWTH_DAILY_TABLE_NAME, day, {
users,
flows,
entities
})
}
const handler = async () => {
const stackName = process.env.STACK_NAME
const day = getTargetDay()
const { startTime, endTime } = dayToEpochRange(day)
// First, as it depends on nothing below: a billing failure (the whole run is
// retried) or a day without logs must not leave a gap in the growth charts.
// An idempotent overwrite, so a retried run changes nothing.
await recordGrowthTotals(day)
const logGroups = await discoverLogGroups(stackName)
if (logGroups.length === 0) return { day, billedUsers: 0 }
const chunks = chunkBy(logGroups, LOG_GROUP_CHUNK_SIZE)
const resultSets = await Promise.all(
chunks.map((group) => runUsageQuery(group, startTime, endTime))
)
const rawRows = resultSets.flatMap((results) => parseQueryResults(results).map(toUsageRow))
const merged = mergeUsageRows(rawRows)
const resolved = await resolveApiKeyUserIds(merged, {
apiKeysTableName: process.env.API_KEYS_TABLE_NAME
})
const activeUserIds = collectActiveUserIds(resolved)
const freeFunctionKeys = await getFreeFunctionKeys(
docClient,
process.env.LAMBDA_BILLING_TABLE_NAME
)
const chargeable = filterFreeFunctions(resolved, freeFunctionKeys)
const billable = mergeByUserId(chargeable.filter((row) => row.userId))
const pricing = await getPricingConfig(docClient, process.env.PRICING_CONFIG_TABLE_NAME)
await Promise.all(
billable.map(async (row) => {
const creditCost = computeCreditCost(row, pricing)
await writeDailySummary(
process.env.USAGE_DAILY_SUMMARY_TABLE_NAME,
day,
row,
creditCost,
buildUsageBreakdown(row.usage, pricing)
)
await writeMonthlyIncrement(
process.env.USAGE_MONTHLY_SUMMARY_TABLE_NAME,
day,
row,
creditCost
)
await debitAggregatedUsage(day, row, pricing)
})
)
// After billing so an activity-stats problem can never hold up the debits
// (the whole run is retried, and both steps are idempotent for a given day)
await recordActiveUsers(
docClient,
process.env.ACTIVE_USERS_MONTHLY_TABLE_NAME,
day.slice(0, 7),
activeUserIds
)
return { day, billedUsers: billable.length, activeUsers: activeUserIds.length }
}
module.exports = {
handler,
discoverLogGroups,
chunkBy,
runUsageQuery,
parseQueryResults,
normalizeGroupValue,
toUsageRow,
mergeUsageRows,
filterFreeFunctions,
resolveApiKeyUserIds,
collectActiveUserIds,
mergeByUserId,
buildUsageBreakdown,
computeCreditCost,
debitAggregatedUsage,
writeDailySummary,
writeMonthlyIncrement,
getTargetDay,
dayToEpochRange
}
|