All files / shared usage-tracking.js

97.87% Statements 46/47
94.44% Branches 34/36
100% Functions 8/8
97.72% Lines 43/44

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 15016x 16x                 16x   16x                         20x 6x     6x 6x         6x 6x 8x 8x 7x     8x   8x 8x 8x 6x 7x 7x     8x                 6x 6x 1x 1x       20x 20x 20x     20x 20x   20x                                     1x                         20x   20x 20x 20x     20x 20x 18x 18x   20x                                         284x     16x          
const { getResolvedActiveFlowId } = require('./activeFlow')
const { AsyncLocalStorage } = require('async_hooks')
 
// Per-invocation accumulator for DynamoDB consumed capacity, scoped via
// AsyncLocalStorage so a handler that calls several DynamoDB tables across
// several files (see items/create.js's unique-field reservations, equality
// index, text-search index, counters...) still gets one correct total, with
// zero changes to any of those files. See
// docs/architecture/USAGE_METERING.md "Capturing DynamoDB throughput
// automatically".
const capacityStore = new AsyncLocalStorage()
 
let dynamoDbPatched = false
 
/**
 * Patches DynamoDBDocumentClient.prototype.send once (idempotent) so every
 * DynamoDB call made by any handler — regardless of which file constructed
 * the client instance — requests and accumulates real ConsumedCapacity into
 * whatever invocation's capacityStore is currently active.
 *
 * Lazily requires @aws-sdk/lib-dynamodb rather than requiring it at module
 * top: a handful of lambdas (docs/static endpoints) have no DynamoDB
 * dependency at all, and this must not fail to load for those.
 */
function installDynamoDBCapacityPatch() {
  if (dynamoDbPatched) return
  dynamoDbPatched = true
 
  let DynamoDBDocumentClient
  try {
    ;({ DynamoDBDocumentClient } = require('@aws-sdk/lib-dynamodb'))
  } catch {
    return
  }
 
  const originalSend = DynamoDBDocumentClient.prototype.send
  DynamoDBDocumentClient.prototype.send = async function patchedSend(command, ...args) {
    command.input = command.input || {}
    if (command.input.ReturnConsumedCapacity === undefined) {
      command.input.ReturnConsumedCapacity = 'TOTAL' // no cost/behavior change, just extra data back
    }
 
    const result = await originalSend.call(this, command, ...args)
 
    const store = capacityStore.getStore()
    const consumed = result && result.ConsumedCapacity
    if (store && consumed) {
      for (const c of Array.isArray(consumed) ? consumed : [consumed]) {
        store.readUnits += c.ReadCapacityUnits || 0
        store.writeUnits += c.WriteCapacityUnits || 0
      }
    }
    return result
  }
}
 
// Best-effort: the second underscore-delimited segment of an
// `apikey_{id}_{secret}` header is the key id — free to read, no hash, no DB
// call (mirrors shared/auth-helper.js's own parsing, kept independent here
// so usage capture never depends on that module's async DB-backed path).
function extractApiKeyId(event) {
  const apiKey = event?.headers?.['x-api-key'] || event?.headers?.['X-API-Key']
  if (!apiKey || !apiKey.startsWith('apikey_')) return null
  const parts = apiKey.split('_')
  return parts.length >= 3 ? parts[1] : null
}
 
function emitUsageEvent({ meta, event, context, durationMs, memoryMB, capacity, statusCode }) {
  try {
    const claims = event?.requestContext?.authorizer?.claims
    const userId = claims?.sub || null
    // Only a flow verified during the request (an active membership), never
    // the raw X-Flow-Id header: usage must not land on a flow merely named
    const flowId = getResolvedActiveFlowId(event)
    const apiKeyId = !userId ? extractApiKeyId(event) : null
 
    console.log(
      JSON.stringify({
        type: 'usage_event',
        unit: 'lambda_invocation_ms',
        resource: meta.resource,
        operation: meta.operation,
        userId,
        flowId,
        apiKeyId,
        durationMs,
        memoryMB,
        readUnits: capacity?.readUnits || 0,
        statusCode,
        requestId: context?.awsRequestId,
        timestamp: new Date().toISOString()
      })
    )
  } catch (error) {
    // A usage-logging bug must never surface as a request failure.
    console.error('usage-tracking: failed to emit usage event', error)
  }
}
 
/**
 * Wraps a Lambda handler to measure duration/memory and DynamoDB read
 * throughput for every invocation, emitting one JSON log line for later
 * async aggregation (see docs/architecture/USAGE_METERING.md). Never
 * touches the response or swallows an error: the target's return value and
 * thrown errors both pass through unchanged; only the logging step (in a
 * `finally`) is wrapped in its own try/catch.
 */
function withUsageTracking(handler, meta) {
  installDynamoDBCapacityPatch()
 
  return async (event, context) => {
    const start = Date.now()
    const capacity = { readUnits: 0, writeUnits: 0 }
    let statusCode
 
    try {
      const result = await capacityStore.run(capacity, () => handler(event, context))
      statusCode = result?.statusCode
      return result
    } finally {
      emitUsageEvent({
        meta,
        event,
        context,
        durationMs: Date.now() - start,
        memoryMB: Number(context?.memoryLimitInMB) || 0,
        capacity,
        statusCode
      })
    }
  }
}
 
/**
 * Real, SDK-reported consumed capacity for the invocation currently running
 * inside withUsageTracking — used synchronously by handlers that debit
 * dynamodb_throughput credits for their own write (see items/create.js).
 * Returns zeros outside of a tracked invocation (e.g. a unit test calling
 * the raw handler directly) rather than throwing.
 */
function getConsumedCapacity() {
  return capacityStore.getStore() || { readUnits: 0, writeUnits: 0 }
}
 
module.exports = {
  withUsageTracking,
  getConsumedCapacity,
  installDynamoDBCapacityPatch
}