All files / uploads s3-usage-consumer.js

100% Statements 30/30
92.85% Branches 13/14
100% Functions 3/3
100% Lines 28/28

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 861x 1x 1x 1x 1x   1x 1x                                 1x 13x 15x 15x           1x             10x 10x       15x   14x   14x 14x     14x   12x     11x 11x 11x 1x 1x     10x 10x         10x                            
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb')
const { DynamoDBDocumentClient } = require('@aws-sdk/lib-dynamodb')
const { S3Client, HeadObjectCommand } = require('@aws-sdk/client-s3')
const { debitCreditsIdempotent, buildIdempotentTransactionId } = require('../utils/creditsLedger')
const { getPricingConfig } = require('../utils/pricingConfig')
 
const docClient = DynamoDBDocumentClient.from(new DynamoDBClient({}))
const s3Client = new S3Client({})
 
/**
 * S3 Event Notification consumer that applies the exact, size-proportional
 * `s3_storage` credit debit once an upload actually completes — the
 * post-upload half of the two-part enforcement described in
 * docs/architecture/USAGE_METERING.md "S3 storage credits" (the other half,
 * a balance-non-negative preflight, lives in uploads/presigned-url.js).
 *
 * S3 Event Notifications are at-least-once: a single upload can trigger
 * this handler more than once for the same object. Each record's own
 * deterministic transactionId (the S3 key, time-prefixed by the event time — see
 * debitCreditsIdempotent) makes a redelivery a no-op rather than a double
 * charge, so no other deduplication is needed here.
 *
 * @implements UC-CREDITS-004.1, UC-CREDITS-011.1
 */
exports.handler = async (event) => {
  for (const record of event.Records || []) {
    try {
      await processRecord(record)
    } catch (error) {
      // One malformed/unresolvable record must not stop the rest of the
      // batch, nor prevent S3 from redelivering just that record — same
      // "best-effort, never unwind" reasoning as the synchronous credit
      // debits in items/create.js.
      console.error('Failed to process S3 usage event record:', error)
    }
  }
}
 
/** When the object was created, falling back to now for a record without it */
function eventEpochMs(record) {
  const parsed = Date.parse(record.eventTime)
  return Number.isFinite(parsed) ? parsed : Date.now()
}
 
async function processRecord(record) {
  if (!record.eventName || !record.eventName.startsWith('ObjectCreated:')) return
 
  const bucket = record.s3.bucket.name
  // S3 event keys are URL-encoded (`+` for spaces) — decode before use.
  const key = decodeURIComponent(record.s3.object.key.replace(/\+/g, ' '))
  const sizeBytes = record.s3.object.size
  // A membership request's files are free (UC-SPACE-020.1): the approver pays
  // when they are copied into the membership item, under `entities/`
  if (key.startsWith('membership-requests/')) return
 
  const head = await s3Client.send(new HeadObjectCommand({ Bucket: bucket, Key: key }))
  // S3 always lower-cases custom metadata keys, regardless of how
  // presigned-url.js set them (`x-amz-meta-userId` -> `userid`).
  const userId = head.Metadata?.userid
  const flowId = head.Metadata?.flowid || null
  if (!userId) {
    console.error('S3 usage event has no userId in object metadata, skipping:', key)
    return
  }
 
  const pricing = await getPricingConfig(docClient, process.env.PRICING_CONFIG_TABLE_NAME)
  const creditCost = Math.max(
    1,
    Math.ceil((sizeBytes / (1024 * 1024)) * pricing.s3_storage_credits_per_mb)
  )
 
  await debitCreditsIdempotent(docClient, {
    usersTableName: process.env.USERS_TABLE_NAME,
    creditsLedgerTableName: process.env.CREDITS_LEDGER_TABLE_NAME,
    userId,
    flowId,
    // eventTime is carried unchanged by a redelivered event, so the id stays
    // deterministic; the key alone (a UUID per upload) is what makes it unique
    transactionId: buildIdempotentTransactionId(eventEpochMs(record), `s3#${key}`),
    pool: 's3_storage',
    operation: 'file_upload',
    costCredits: creditCost,
    referenceId: key
  })
}