All files / shared lambda-stats.js

92.85% Statements 26/28
92.85% Branches 13/14
100% Functions 6/6
96.15% Lines 25/26

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                              1x                         5x 1x 1x 1x 1x 1x       1x       10x 10x                         9x           5x 5x   5x                                                     6x 6x 6x 6x   6x 6x 5x 5x 5x               1x             1x  
// Per-Lambda operational stats: invocation count + average execution time,
// surfaced on the platform-admin "Lambda stats" page (see
// admin/lambda-stats.js). Wired in for every Lambda from the same CDK-level
// seam as usage-tracking.js (see api-stack.ts's newTrackedFunction /
// shared/usage-entrypoint.js) — zero business-logic files touched.
//
// A DynamoDB write on every single invocation would add a network round-trip
// to the hot path of all ~100 lambdas. Instead, each invocation is recorded
// with probability 1/LAMBDA_STATS_SAMPLE_RATE (DEFAULT_SAMPLE_RATE unless the
// env var overrides it — api-stack.ts doesn't set it, to keep the template
// small), and the sampled write is
// extrapolated (both invocationCount and durationMs scaled by the sample
// rate) so the stored totals stay an unbiased estimate of the real ones —
// the same inverse-probability-weighting trick used by e.g. X-Ray sampling.
// A rate of 1 (or an invalid/missing env var) means "record every call".
const DEFAULT_SAMPLE_RATE = 20
 
let docClient
let UpdateCommandRef
 
/**
 * Lazily requires @aws-sdk/lib-dynamodb and builds the client once per
 * container (not once per sampled invocation) — mirrors
 * usage-tracking.js's installDynamoDBCapacityPatch, including the try/catch:
 * a handful of lambdas (docs/static endpoints) have no DynamoDB dependency
 * at all, and this must never fail to load for those.
 */
function getDocClient() {
  if (docClient !== undefined) return docClient
  try {
    const { DynamoDBClient } = require('@aws-sdk/client-dynamodb')
    const { DynamoDBDocumentClient, UpdateCommand } = require('@aws-sdk/lib-dynamodb')
    UpdateCommandRef = UpdateCommand
    docClient = DynamoDBDocumentClient.from(new DynamoDBClient({}))
  } catch {
    docClient = null
  }
  return docClient
}
 
function sampleRateFrom(env) {
  const parsed = parseInt(env.LAMBDA_STATS_SAMPLE_RATE, 10)
  return Number.isFinite(parsed) && parsed > 0 ? parsed : DEFAULT_SAMPLE_RATE
}
 
// 'always' | 'conditional' | 'never' — set on this function's own
// environment by api-stack.ts's addIntegration, derived from the OpenAPI
// spec's `security` requirement for its route (see the comment there).
// Never set at all (a lambda not reachable via API Gateway — a Cognito
// trigger, WebSocket handler, CloudFront edge function, or an SQS/S3-
// triggered worker) defaults to 'never': correct for this *baseline*
// usage-pool classification, even though some of those workers do charge
// credits through their own separate, explicit debit — see
// admin/lambda-stats.js's EXTRA_CREDIT_CHARGES.
function billingClassification(env) {
  return env.CREDITS_BILLING === 'always' || env.CREDITS_BILLING === 'conditional'
    ? env.CREDITS_BILLING
    : 'never'
}
 
async function recordSample(tableName, functionKey, durationMs, sampleRate, billing) {
  const client = getDocClient()
  Iif (!client) return
 
  await client.send(
    new UpdateCommandRef({
      TableName: tableName,
      Key: { functionKey },
      UpdateExpression:
        'SET gsiPk = if_not_exists(gsiPk, :gsiPk), lastSeenAt = :now, billing = :billing ' +
        'ADD invocationCount :count, totalDurationMs :duration',
      ExpressionAttributeValues: {
        ':gsiPk': 'LAMBDA_STAT',
        ':now': new Date().toISOString(),
        ':billing': billing,
        ':count': sampleRate,
        ':duration': durationMs * sampleRate
      }
    })
  )
}
 
/**
 * Wraps a Lambda handler to sample-record its execution time into
 * LambdaStatsTable. Mirrors withUsageTracking's contract: the target's
 * return value and thrown errors both pass through completely unchanged,
 * and a failure in the recording step (missing table, throttled write, SDK
 * not bundled for this lambda) is only ever logged, never surfaced as a
 * request failure.
 */
function withLambdaStats(handler, meta) {
  return async (event, context) => {
    const start = Date.now()
    try {
      return await handler(event, context)
    } finally {
      const sampleRate = sampleRateFrom(process.env)
      if (Math.random() < 1 / sampleRate) {
        try {
          const functionKey = `${meta.resource}/${meta.operation}`
          await recordSample(
            process.env.LAMBDA_STATS_TABLE_NAME,
            functionKey,
            Date.now() - start,
            sampleRate,
            billingClassification(process.env)
          )
        } catch (error) {
          console.error('lambda-stats: failed to record invocation sample', error)
        }
      }
    }
  }
}
 
module.exports = { withLambdaStats, sampleRateFrom, billingClassification, DEFAULT_SAMPLE_RATE }