All files / credits get.js

100% Statements 80/80
94.64% Branches 53/56
100% Functions 14/14
100% Lines 71/71

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                        1x           1x   1x 1x   1x         1x 1x 1x 1x     1x   1x 1x                 4x 4x 4x     4x 5x 5x 5x 5x     4x                       5x 5x   5x 5x 15x                             15x 13x   15x 15x     5x                 5x     5x 4x     5x   2x   3x           2x 3x                                     5x 2x   4x     2x       5x       5x 5x 3x 3x     5x 5x                     1x 19x   19x 1x             18x   18x       18x                             18x 18x 2x 2x   1x               17x 17x             16x 16x                         16x       16x       16x                           1x 1x              
/**
 * GET /v1/credits
 *
 * Current user's credits balance plus a most-recent-first, paginated page of
 * their CreditsLedgerTable rows. With `details=true` (the Credits page; the
 * sidebar badge leaves it off), also what makes the page readable: the last
 * 30 days' spending, the per-flow/per-function breakdown of each usage day
 * on the page, and the names of the flows involved.
 *
 * @implements UC-CREDITS-001.1, UC-CREDITS-011.1
 */
 
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb')
const {
  DynamoDBDocumentClient,
  GetCommand,
  QueryCommand,
  BatchGetCommand
} = require('@aws-sdk/lib-dynamodb')
 
const client = new DynamoDBClient({})
const docClient = DynamoDBDocumentClient.from(client)
 
const corsHeaders = {
  'Content-Type': 'application/json',
  'Access-Control-Allow-Origin': '*'
}
 
const DEFAULT_LIMIT = 30
const MAX_LIMIT = 100
const SUMMARY_DAYS = 30
const DAY_MS = 24 * 60 * 60 * 1000
// Bounds the spending summary's read for a very active account: past this
// many 1 MB pages the total is returned as a lower bound (`complete: false`)
const SUMMARY_MAX_PAGES = 10
// DynamoDB BatchGetItem caps at 100 keys per call
const BATCH_GET_CHUNK_SIZE = 100
const BATCH_GET_MAX_ATTEMPTS = 3
 
/**
 * BatchGet of `keys` from one table, chunked and retrying what DynamoDB
 * returns as unprocessed (throttling) a few times. A key still unprocessed
 * after that is left out: these reads only add context to the page, and the
 * caller treats a missing row as "no detail".
 */
async function batchGetAll(tableName, keys, projection) {
  const items = []
  for (let i = 0; i < keys.length; i += BATCH_GET_CHUNK_SIZE) {
    let requestItems = {
      [tableName]: { Keys: keys.slice(i, i + BATCH_GET_CHUNK_SIZE), ...projection }
    }
    for (let attempt = 0; attempt < BATCH_GET_MAX_ATTEMPTS && requestItems; attempt++) {
      const result = await docClient.send(new BatchGetCommand({ RequestItems: requestItems }))
      items.push(...(result.Responses?.[tableName] ?? []))
      const unprocessed = result.UnprocessedKeys?.[tableName]
      requestItems = unprocessed?.Keys?.length ? { [tableName]: unprocessed } : null
    }
  }
  return items
}
 
/**
 * What was spent over the last SUMMARY_DAYS days: a key-range Query on the
 * time-prefixed transactionId (see utils/creditsLedger.js
 * buildIdempotentTransactionId), never a scan. The timestamp filter drops
 * rows written before idempotent ids were time-prefixed (`usage#…`, `s3#…`
 * sort after every digit, so the range alone would include all of them).
 * Only debits count: a grant is not spending.
 */
async function summarizeRecentSpending(userId, now) {
  const sinceMs = now - SUMMARY_DAYS * DAY_MS
  let spent = 0
  let lastKey
  let pages = 0
  do {
    const result = await docClient.send(
      new QueryCommand({
        TableName: process.env.CREDITS_LEDGER_TABLE_NAME,
        KeyConditionExpression: 'userId = :userId AND transactionId >= :since',
        FilterExpression: '#timestamp >= :sinceIso',
        ProjectionExpression: '#amount',
        ExpressionAttributeNames: { '#timestamp': 'timestamp', '#amount': 'amount' },
        ExpressionAttributeValues: {
          ':userId': userId,
          ':since': String(sinceMs),
          ':sinceIso': new Date(sinceMs).toISOString()
        },
        ...(lastKey && { ExclusiveStartKey: lastKey })
      })
    )
    for (const item of result.Items ?? []) {
      if (item.amount < 0) spent -= item.amount
    }
    lastKey = result.LastEvaluatedKey
    pages++
  } while (lastKey && pages < SUMMARY_MAX_PAGES)
 
  return { days: SUMMARY_DAYS, spent, complete: !lastKey }
}
 
/**
 * The breakdown of each usage day among `transactions` (a daily aggregation
 * debit's referenceId is the day it charges), read by key from
 * UsageDailySummaryTable. A day past that table's TTL simply has no entry.
 */
async function loadUsageDays(userId, transactions) {
  const days = [
    ...new Set(
      transactions
        .filter((tx) => tx.operation === 'usage_aggregation' && tx.referenceId)
        .map((tx) => tx.referenceId)
    )
  ]
  if (days.length === 0) return {}
 
  const rows = await batchGetAll(
    process.env.USAGE_DAILY_SUMMARY_TABLE_NAME,
    days.map((day) => ({ userId, day })),
    {
      ProjectionExpression: '#day, eventCount, gbSeconds, totalReadUnits, creditCost, breakdown',
      ExpressionAttributeNames: { '#day': 'day' }
    }
  )
  return Object.fromEntries(
    rows.map((row) => [
      row.day,
      {
        events: row.eventCount ?? 0,
        gbSeconds: row.gbSeconds ?? 0,
        readUnits: row.totalReadUnits ?? 0,
        credits: row.creditCost ?? 0,
        breakdown: row.breakdown ?? []
      }
    ])
  )
}
 
/**
 * Names of the flows the page mentions, so a row can say which flow it is
 * about. A deleted flow has no entry, and the page shows it as such. The
 * flows are the caller's own spending, so naming them reveals nothing new.
 */
async function loadFlowNames(flowIds) {
  if (flowIds.length === 0) return {}
  const flows = await batchGetAll(
    process.env.FLOWS_TABLE_NAME,
    flowIds.map((id) => ({ id })),
    { ProjectionExpression: 'id, #name', ExpressionAttributeNames: { '#name': 'name' } }
  )
  return Object.fromEntries(flows.map((flow) => [flow.id, flow.name]))
}
 
async function loadDetails(userId, transactions) {
  const [summary, usageDays] = await Promise.all([
    summarizeRecentSpending(userId, Date.now()),
    loadUsageDays(userId, transactions)
  ])
  const flowIds = new Set(transactions.map((tx) => tx.flowId).filter(Boolean))
  for (const day of Object.values(usageDays)) {
    for (const line of day.breakdown) {
      if (line.flowId) flowIds.add(line.flowId)
    }
  }
  const flows = await loadFlowNames([...flowIds])
  return { summary, usageDays, flows }
}
 
/**
 * Returns the authenticated user's current credits balance plus a
 * most-recent-first, paginated page of their CreditsLedgerTable rows — see
 * docs/architecture/USAGE_METERING.md. transactionId is epoch-ms-prefixed
 * and lexicographically time-sortable (see utils/creditsLedger.js's
 * buildTransactionId), so ScanIndexForward: false alone gives newest-first
 * with no separate sort attribute needed.
 */
exports.handler = async (event) => {
  const userId = event.requestContext?.authorizer?.claims?.sub
 
  if (!userId) {
    return {
      statusCode: 401,
      headers: corsHeaders,
      body: JSON.stringify({ error: 'Unauthorized' })
    }
  }
 
  const parsedLimit = parseInt(event.queryStringParameters?.limit, 10)
  const limit =
    Number.isFinite(parsedLimit) && parsedLimit > 0
      ? Math.min(parsedLimit, MAX_LIMIT)
      : DEFAULT_LIMIT
 
  const params = {
    TableName: process.env.CREDITS_LEDGER_TABLE_NAME,
    KeyConditionExpression: 'userId = :userId',
    ExpressionAttributeValues: { ':userId': userId },
    ScanIndexForward: false,
    Limit: limit,
    // Strongly consistent: this is a base-table query (partition key
    // userId), so it's available, and it must be — a debit's ledger row is
    // written synchronously right before this is called again (page reload
    // right after a spend, or the admin panel reflecting a just-applied
    // grant), and an eventually consistent read can still miss a write
    // that's only milliseconds old.
    ConsistentRead: true
  }
 
  const nextToken = event.queryStringParameters?.nextToken
  if (nextToken) {
    try {
      params.ExclusiveStartKey = JSON.parse(Buffer.from(nextToken, 'base64').toString())
    } catch {
      return {
        statusCode: 400,
        headers: corsHeaders,
        body: JSON.stringify({ error: 'Invalid nextToken' })
      }
    }
  }
 
  try {
    const [userResult, ledgerResult] = await Promise.all([
      docClient.send(
        new GetCommand({ TableName: process.env.USERS_TABLE_NAME, Key: { id: userId } })
      ),
      docClient.send(new QueryCommand(params))
    ])
 
    const balance = userResult.Item?.creditsBalance || 0
    const transactions = (ledgerResult.Items || []).map((item) => ({
      transactionId: item.transactionId,
      flowId: item.flowId ?? null,
      pool: item.pool,
      operation: item.operation,
      amount: item.amount,
      referenceId: item.referenceId ?? null,
      note: item.note ?? null,
      balanceAfter: item.balanceAfter ?? null,
      timestamp: item.timestamp
    }))
 
    const details =
      event.queryStringParameters?.details === 'true'
        ? await loadDetails(userId, transactions)
        : null
 
    const responseNextToken = ledgerResult.LastEvaluatedKey
      ? Buffer.from(JSON.stringify(ledgerResult.LastEvaluatedKey)).toString('base64')
      : null
 
    return {
      statusCode: 200,
      headers: corsHeaders,
      body: JSON.stringify({
        balance,
        transactions: {
          items: transactions,
          nextToken: responseNextToken,
          hasMore: !!responseNextToken
        },
        ...details
      })
    }
  } catch (error) {
    console.error('Error fetching credits:', error)
    return {
      statusCode: 500,
      headers: corsHeaders,
      body: JSON.stringify({ error: 'Failed to fetch credits' })
    }
  }
}