All files / utils lambdaBillingConfig.js

100% Statements 15/15
83.33% Branches 5/6
100% Functions 3/3
100% Lines 13/13

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 533x                                     3x   3x 3x                   16x 16x   14x 14x 14x 14x         64x 64x     3x          
const { ScanCommand } = require('@aws-sdk/lib-dynamodb')
 
/**
 * Admin-editable set of Lambda functions (`${resource}/${operation}`) that
 * are exempt from the baseline usage-metering pools (lambda_compute,
 * api_gateway, dynamodb_throughput reads — see usage/aggregate.js) —
 * e.g. likes, follows or profile edits that should never make a user feel
 * rationed. A function's mere presence in LambdaBillingTable means "free";
 * there is no partial/percentage override.
 *
 * Cached as module-level state, outside any handler, so it survives across
 * invocations of the same warm Lambda execution environment: the first
 * invocation after a cold start populates it, and it is then reused as-is
 * until CACHE_TTL_MS elapses, at which point the next invocation refreshes
 * it — mirrors pricingConfig.js's own getPricingConfig() exactly, and for
 * the same reason (this runs on the hot path of every metered invocation,
 * so a DynamoDB Scan on every single call would be wasteful). Same 1-hour
 * TTL as pricingConfig.js's own CACHE_TTL_MS.
 */
const CACHE_TTL_MS = 60 * 60 * 1000
 
let cachedFreeFunctionKeys = null
let cacheExpiresAt = 0
 
/**
 * Returns the current set of "always free" function keys.
 *
 * @param {import('@aws-sdk/lib-dynamodb').DynamoDBDocumentClient} docClient
 * @param {string} tableName
 * @returns {Promise<Set<string>>}
 */
async function getFreeFunctionKeys(docClient, tableName) {
  const now = Date.now()
  if (cachedFreeFunctionKeys && now < cacheExpiresAt) return cachedFreeFunctionKeys
 
  const result = await docClient.send(new ScanCommand({ TableName: tableName }))
  cachedFreeFunctionKeys = new Set((result.Items || []).map((item) => item.functionKey))
  cacheExpiresAt = now + CACHE_TTL_MS
  return cachedFreeFunctionKeys
}
 
/** Test-only: forces the next getFreeFunctionKeys() call to re-read the table. */
function clearLambdaBillingConfigCache() {
  cachedFreeFunctionKeys = null
  cacheExpiresAt = 0
}
 
module.exports = {
  CACHE_TTL_MS,
  getFreeFunctionKeys,
  clearLambdaBillingConfigCache
}