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 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 | 17x 17x 47x 336x 336x 201x 46x 233x 5x 5x 1x 5x 557x 283x 85x 85x 198x 190x 190x 190x 373x 192x 189x 10x 7x 7x 7x 7x 54x 49x 49x 9x 1x 40x 40x 4x 3x 3x 36x 36x 17x | const { GetCommand, UpdateCommand, PutCommand, DeleteCommand } = require('@aws-sdk/lib-dynamodb')
const { randomUUID } = require('crypto')
/**
* Resolves which user's credits balance a request should be charged
* against. A JWT-authenticated request already carries its own userId. An
* API-key-authenticated request has no userId of its own (auth.userId is
* always null for it — see shared/auth-helper.js's validateApiKey) but acts
* for the key's creator (auth.createdBy), who is charged — the same person a
* JWT call of theirs would be charged to, and the same attribution the
* daily usage aggregation applies (usage/aggregate.js).
*
* @implements UC-CREDITS-010.1
*
* @param {{ type: 'jwt' | 'apikey', userId: string | null, createdBy?: string | null }} auth
* @returns {string | null} null if no billable user could be resolved
*/
function resolveBillingUserId(auth) {
return auth.userId || auth.createdBy || null
}
/**
* Reads a user's credits balance, defaulting to 0 if the user row doesn't
* carry one yet (e.g. before any monthly grant has been issued — there is
* currently no signup grant at all, see TODO.md "Credits System"). Used as a
* cheap preflight gate before an expensive write — see
* docs/architecture/USAGE_METERING.md "DynamoDB storage credits".
*
* Also returns `isPlatformAdmin` from the same row/read so every preflight
* call site can let a platform admin through regardless of balance — a
* platform admin must never be blocked from using the app by a credits
* shortfall. This is a bypass of the *check* only: a debit that happens
* after a successful write still applies normally, floored at 0 like any
* other debit (see clampBalanceFloor) rather than taking an admin's balance
* negative.
*
* @param {import('@aws-sdk/lib-dynamodb').DynamoDBDocumentClient} docClient
* @param {string} usersTableName
* @param {string} userId
* @returns {Promise<{ balance: number, isPlatformAdmin: boolean }>}
*/
async function getCreditsBalance(docClient, usersTableName, userId) {
const result = await docClient.send(
new GetCommand({ TableName: usersTableName, Key: { id: userId } })
)
return {
balance: result.Item?.creditsBalance || 0,
isPlatformAdmin: result.Item?.isPlatformAdmin === true
}
}
/**
* A lexicographically time-sortable transaction id for CreditsLedgerTable's
* sort key — an epoch-ms prefix (fixed-width until the year 2286) followed
* by a random suffix so concurrent debits from the same user never collide.
*
* @returns {string}
*/
function buildTransactionId() {
return `${Date.now()}#${randomUUID()}`
}
/**
* The deterministic transactionId debitCreditsIdempotent claims, with the
* same epoch-ms prefix as buildTransactionId. The prefix is what keeps the
* ledger time-sorted: GET /v1/credits reads it newest-first by sort key
* alone, and an unprefixed id (`usage#…`, `s3#…`, as these were first
* written) sorts after every digit, so those rows used to come before every
* other transaction regardless of their date. `epochMs` must be derived from
* the event itself (never Date.now()) so a redelivery rebuilds the same id.
*
* @param {number} epochMs - when the charged usage happened
* @param {string} key - what makes the charge unique (e.g. `s3#{objectKey}`)
* @returns {string}
*/
function buildIdempotentTransactionId(epochMs, key) {
return `${String(Math.floor(epochMs)).padStart(13, '0')}#${key}`
}
/**
* Floors a balance at 0 after a debit/deduction that just applied via `ADD`
* pushed it negative — a user (or, since the platform decides its own
* batching/async-enforcement trade-offs, an admin's deliberate deduction
* too) must never be left owing a "debt" that a future grant would have to
* pay off before becoming usable again. Applies uniformly to every kind of
* decrease: an automatic system debit that overshot because its real cost
* wasn't knowable at preflight time, and a manual admin deduction alike —
* see docs/architecture/USAGE_METERING.md "bounded overshoot".
*
* Conditioned on the balance still being negative *at write time*
* (`ConditionExpression`), so this is safe under concurrent writes: if
* another write (e.g. a grant landing in the same moment) already brought
* the balance back to >= 0 between the caller's own `ADD` and this call,
* the clamp is skipped instead of clobbering that newer, legitimate value
* back down to 0.
*
* @implements UC-CREDITS-008.1
*
* @param {import('@aws-sdk/lib-dynamodb').DynamoDBDocumentClient} docClient
* @param {string} usersTableName
* @param {string} userId
* @param {number} balanceAfter the balance immediately after the ADD that just ran
* @returns {Promise<number>} 0 if clamped, `balanceAfter` unchanged otherwise
*/
async function clampBalanceFloor(docClient, usersTableName, userId, balanceAfter) {
if (balanceAfter >= 0) return balanceAfter
try {
await docClient.send(
new UpdateCommand({
TableName: usersTableName,
Key: { id: userId },
UpdateExpression: 'SET creditsBalance = :zero',
ConditionExpression: 'creditsBalance < :zero',
ExpressionAttributeValues: { ':zero': 0 }
})
)
} catch (error) {
Iif (error.name !== 'ConditionalCheckFailedException') throw error
}
return 0
}
/**
* Debits a user's credits balance for one or more charges against different
* pools (see docs/architecture/USAGE_METERING.md), unconditionally — the
* "prepaid, no refund, bounded overshoot" model: a request already admitted
* by an earlier preflight check (see getCreditsBalance) is allowed to
* complete even if its real cost overshoots what was left, but the balance
* is then floored at 0 (see clampBalanceFloor) rather than left negative —
* the *next* request's preflight is what blocks further spending, not a
* debt this one's already-completed write would otherwise leave behind.
*
* Deliberately not one atomic transaction with the caller's own write: by
* the time this runs, that write has already happened, since some charges
* (dynamodb_throughput) can only be computed from its real, SDK-reported
* cost (see shared/usage-tracking.js's getConsumedCapacity). The balance
* update and its ledger row(s) are themselves atomic with each other,
* though: the balance changes exactly once, before any ledger row is
* written from its result.
*
* @param {import('@aws-sdk/lib-dynamodb').DynamoDBDocumentClient} docClient
* @param {{
* usersTableName: string,
* creditsLedgerTableName: string,
* userId: string,
* flowId?: string | null,
* charges: Array<{ pool: string, operation: string, costCredits: number, referenceId?: string }>
* }} params
* @returns {Promise<number>} the balance after all charges are applied
*/
async function debitCredits(
docClient,
{ usersTableName, creditsLedgerTableName, userId, flowId, charges }
) {
const totalCost = charges.reduce((sum, charge) => sum + charge.costCredits, 0)
if (totalCost <= 0) {
const { balance } = await getCreditsBalance(docClient, usersTableName, userId)
return balance
}
const updateResult = await docClient.send(
new UpdateCommand({
TableName: usersTableName,
Key: { id: userId },
// The user row must already exist (created at signup — see
// auth/post-confirmation.js) — never silently upsert a phantom user
// via DynamoDB's default create-on-update behavior for a financial
// ledger.
ConditionExpression: 'attribute_exists(id)',
UpdateExpression: 'ADD creditsBalance :negCost',
ExpressionAttributeValues: { ':negCost': -totalCost },
ReturnValues: 'UPDATED_NEW'
})
)
const balanceAfter = await clampBalanceFloor(
docClient,
usersTableName,
userId,
updateResult.Attributes?.creditsBalance ?? 0
)
const timestamp = new Date().toISOString()
// A charge whose cost rounded to 0 (e.g. an update whose throughput was
// real but whose storage didn't grow) contributes nothing to the balance
// and would only add noise to the audit trail — skip its ledger row
// entirely rather than writing an `amount: 0` line.
await Promise.all(
charges
.filter((charge) => charge.costCredits > 0)
.map((charge) =>
docClient.send(
new PutCommand({
TableName: creditsLedgerTableName,
// flowId must be omitted, not written as null, when there is no
// flow: it's the flowIndex GSI's partition key, and DynamoDB
// rejects a NULL-typed value for an indexed key attribute
// (ValidationException) — omitting it instead keeps the item out
// of that sparse index, which is what we want anyway.
Item: {
userId,
transactionId: buildTransactionId(),
...(flowId ? { flowId } : {}),
pool: charge.pool,
operation: charge.operation,
amount: -charge.costCredits,
referenceId: charge.referenceId || null,
balanceAfter,
timestamp
}
})
)
)
)
return balanceAfter
}
/**
* Applies a manual, platform-admin-initiated balance adjustment — the
* stop-gap for granting or correcting a user's balance before Stripe
* purchases exist (see docs/architecture/USAGE_METERING.md "Phased
* rollout" step 8). Unlike debitCredits (usage-based charges, always
* negative, computed from real consumption), `amount` here is admin-
* supplied and can be positive (grant) or negative (correction/clawback) —
* a large enough deduction is floored at 0 the same as any other debit (see
* clampBalanceFloor), never left negative.
* A `note` is required on every call so the ledger always carries a
* human-readable reason — there's no automated operation to infer one from.
*
* @param {import('@aws-sdk/lib-dynamodb').DynamoDBDocumentClient} docClient
* @param {{
* usersTableName: string,
* creditsLedgerTableName: string,
* userId: string,
* amount: number,
* note: string,
* adminUserId: string
* }} params
* @returns {Promise<{ balanceAfter: number, transactionId: string }>}
*/
async function adjustCreditsBalance(
docClient,
{ usersTableName, creditsLedgerTableName, userId, amount, note, adminUserId }
) {
const updateResult = await docClient.send(
new UpdateCommand({
TableName: usersTableName,
Key: { id: userId },
// Never upsert a phantom user via a financial ledger write — same
// guard as debitCredits.
ConditionExpression: 'attribute_exists(id)',
UpdateExpression: 'ADD creditsBalance :amount',
ExpressionAttributeValues: { ':amount': amount },
ReturnValues: 'UPDATED_NEW'
})
)
const balanceAfter = await clampBalanceFloor(
docClient,
usersTableName,
userId,
updateResult.Attributes?.creditsBalance ?? 0
)
const transactionId = buildTransactionId()
await docClient.send(
new PutCommand({
TableName: creditsLedgerTableName,
// flowId omitted (not null) — see the comment in debitCredits' own
// PutCommand: a NULL-typed flowId is rejected by the flowIndex GSI.
// Admin adjustments are never flow-scoped anyway.
Item: {
userId,
transactionId,
pool: 'admin_adjustment',
operation: amount >= 0 ? 'admin_grant' : 'admin_deduction',
amount,
referenceId: null,
adminUserId,
note,
balanceAfter,
timestamp: new Date().toISOString()
}
})
)
return { balanceAfter, transactionId }
}
/**
* Idempotent variant of debitCredits for at-least-once-delivered events (S3
* Event Notifications specifically, which can redeliver the same event) —
* see docs/architecture/USAGE_METERING.md "S3 storage credits". Unlike
* debitCredits (used by synchronous request/response handlers that run
* exactly once per write), this claims a caller-supplied, deterministic
* `transactionId` via a conditional PutCommand *before* touching the
* balance, so a duplicate delivery becomes a no-op instead of a double
* charge — the ledger row itself is the idempotency guard, not a separate
* mechanism. That ordering means `balanceAfter` isn't known yet when the
* claim is written, so this ledger row omits it (unlike debitCredits' rows).
*
* If the balance UpdateCommand fails *after* the claim already succeeded,
* the charge is permanently lost rather than retried (a retry of the same
* event now sees its transactionId already claimed and skips it) — an
* accepted, user-favorable gap consistent with this system's existing
* "prepaid, no refund" bias never over-charging rather than always
* capturing every cent.
*
* @param {import('@aws-sdk/lib-dynamodb').DynamoDBDocumentClient} docClient
* @param {{
* usersTableName: string,
* creditsLedgerTableName: string,
* userId: string,
* flowId?: string | null,
* transactionId: string,
* pool: string,
* operation: string,
* costCredits: number,
* referenceId?: string
* }} params
* @returns {Promise<boolean>} true if this call actually applied the debit,
* false if it was a no-op (zero cost, an already-claimed duplicate, or an
* account deleted since the usage happened)
*/
async function debitCreditsIdempotent(
docClient,
{
usersTableName,
creditsLedgerTableName,
userId,
flowId,
transactionId,
pool,
operation,
costCredits,
referenceId
}
) {
if (costCredits <= 0) return false
try {
await docClient.send(
new PutCommand({
TableName: creditsLedgerTableName,
// flowId omitted (not null) — see the comment in debitCredits' own
// PutCommand: a NULL-typed flowId is rejected by the flowIndex GSI.
Item: {
userId,
transactionId,
...(flowId ? { flowId } : {}),
pool,
operation,
amount: -costCredits,
referenceId: referenceId || null,
timestamp: new Date().toISOString()
},
ConditionExpression: 'attribute_not_exists(transactionId)'
})
)
} catch (error) {
if (error.name === 'ConditionalCheckFailedException') return false
throw error
}
let updateResult
try {
updateResult = await docClient.send(
new UpdateCommand({
TableName: usersTableName,
Key: { id: userId },
// Same "must already exist" guard as debitCredits — never upsert a
// phantom user via a financial ledger write.
ConditionExpression: 'attribute_exists(id)',
UpdateExpression: 'ADD creditsBalance :negCost',
ExpressionAttributeValues: { ':negCost': -costCredits },
ReturnValues: 'UPDATED_NEW'
})
)
} catch (error) {
if (error.name !== 'ConditionalCheckFailedException') throw error
// The account was deleted after the usage happened (daily aggregation
// bills yesterday, e2e accounts are deleted every night): there is no
// balance left to charge. Throwing here would fail the caller's whole
// batch for every other user, so release the claim instead — the ledger
// is an accounting trail and must not show a debit that never applied.
await docClient.send(
new DeleteCommand({
TableName: creditsLedgerTableName,
Key: { userId, transactionId }
})
)
return false
}
await clampBalanceFloor(
docClient,
usersTableName,
userId,
updateResult.Attributes?.creditsBalance ?? 0
)
return true
}
module.exports = {
resolveBillingUserId,
getCreditsBalance,
debitCredits,
debitCreditsIdempotent,
adjustCreditsBalance,
buildTransactionId,
buildIdempotentTransactionId
}
|