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 | 48x 48x 48x 48x 48x 93x 93x 82x 68x 14x 14x 22x 21x 6x 7x 6x 6x 6x 8x 8x 8x 5x 5x 6x 60x 13x 2x 14x 13x 12x 6x 12x 111x 113x 113x 100x 13x 10x 10x 10x 5x 2x 2x 3x 45x 45x 46x 45x 23x 22x 16x 7x 10x 7x 8x 5x 4x 37x 38x 37x 38x 38x 37x 37x 5x 5x 37x 6x 6x 7x 7x 11x 12x 7x 6x 6x 6x 12x 12x 12x 2x 10x 6x 3x 4x 4x 48x | const { QueryCommand, PutCommand, TransactWriteCommand } = require('@aws-sdk/lib-dynamodb')
const { batchDelete } = require('./batchWrite')
// Sentinel language key for a plain (non-multilingual) string value, so it
// never collides with a real ISO language code like 'en'/'fr'.
const PLAIN_VALUE_LANG = 'default'
// Sort key is fixed for every row this module writes — reserved so a future
// exact-match filter/search feature can add differently-shaped rows (e.g.
// sk = itemId, allowing multiple items per value) under the same table
// without a migration.
const RESERVATION_SK = 'unique'
const TRANSIENT_CANCELLATION_CODES = new Set([
'TransactionConflict',
'ThrottlingError',
'ProvisionedThroughputExceeded'
])
/**
* Canonicalizes a `unique: true` field's value into the set of (language,
* value) pairs that need a reservation row — one per non-empty language.
* Text/email values are almost always stored as a multilingual map
* ({en, fr, ...}); a plain string is treated as a single value under the
* PLAIN_VALUE_LANG sentinel. Uniqueness is enforced per language
* independently: two items can't share the same `en` value, and separately
* can't share the same `fr` value, but one item's `en` colliding with
* another item's `fr` is not a conflict.
*
* @param {{ fieldId: string }} field
* @param {Record<string, unknown>} data
* @returns {Array<{ lang: string, value: string }>}
*/
function getUniqueLanguageValues(field, data) {
const raw = data[field.fieldId]
if (raw === undefined || raw === null || raw === '') return []
if (typeof raw === 'string') {
return [{ lang: PLAIN_VALUE_LANG, value: raw }]
}
Eif (typeof raw === 'object' && !Array.isArray(raw)) {
return Object.entries(raw)
.filter(([, value]) => typeof value === 'string' && value !== '')
.map(([lang, value]) => ({ lang, value }))
}
return []
}
/**
* Diffs a unique field's value between an item's old and new state into the
* (language, value) pairs whose reservation must be released and/or claimed.
* A language whose value is unchanged is included in neither list — needed
* because DynamoDB forbids two actions against the same primary key within
* one TransactWriteItems call, and an unchanged value maps to the same `pk`.
*
* @param {{ fieldId: string }} field
* @param {Record<string, unknown>} oldData
* @param {Record<string, unknown>} newData
* @returns {{ toRelease: Array<{lang:string,value:string}>, toClaim: Array<{lang:string,value:string}> }}
*/
function diffUniqueLanguageValues(field, oldData, newData) {
const oldValues = new Map(getUniqueLanguageValues(field, oldData).map((v) => [v.lang, v.value]))
const newValues = new Map(getUniqueLanguageValues(field, newData).map((v) => [v.lang, v.value]))
const toRelease = []
const toClaim = []
for (const lang of new Set([...oldValues.keys(), ...newValues.keys()])) {
const oldValue = oldValues.get(lang)
const newValue = newValues.get(lang)
if (oldValue === newValue) continue
if (oldValue !== undefined) toRelease.push({ lang, value: oldValue })
if (newValue !== undefined) toClaim.push({ lang, value: newValue })
}
return { toRelease, toClaim }
}
function buildReservationKey(entityId, fieldId, lang, value) {
return `${entityId}#${fieldId}#${lang}#${value}`
}
/**
* A TransactWriteItems `Put` action reserving one (field, language, value)
* for `itemId` — conditioned so a second item can never claim the same
* reservation, closing the check-then-write race a plain Query can't.
*/
function buildReservationPut(tableName, entityId, fieldId, lang, value, itemId) {
return {
Put: {
TableName: tableName,
Item: {
pk: buildReservationKey(entityId, fieldId, lang, value),
sk: RESERVATION_SK,
entityId,
fieldId,
itemId
},
ConditionExpression: 'attribute_not_exists(pk)'
}
}
}
/** A TransactWriteItems (or standalone) `Delete` action releasing a reservation. */
function buildReservationDelete(tableName, entityId, fieldId, lang, value) {
return {
Delete: {
TableName: tableName,
Key: { pk: buildReservationKey(entityId, fieldId, lang, value), sk: RESERVATION_SK }
}
}
}
/**
* Given a `TransactionCanceledException`'s `CancellationReasons` (a parallel
* array to the TransactItems that were sent) and the fieldId each reservation
* action corresponds to (in the same order, immediately after the primary
* item write action at index `offset`), returns the fieldId whose reservation
* lost the race — or null if no reservation action actually failed its
* condition (e.g. the primary item write itself failed for an unrelated
* reason). `offset` defaults to 1 (a primary write action precedes the
* reservations); pass 0 when the transaction is reservations-only (e.g.
* entities/import.js claims a bundle item's reservations up front, before the
* item itself is ever written, to avoid a cross-item entity_ref id being
* assigned for an item that might still fail its own field validation).
*
* @param {Array<{Code?: string}> | undefined} reasons
* @param {string[]} reservationFieldIds
* @param {number} [offset]
* @returns {string | null}
*/
function mapCancellationReasonToField(reasons, reservationFieldIds, offset = 1) {
if (!Array.isArray(reasons)) return null
for (let i = 0; i < reservationFieldIds.length; i++) {
if (reasons[i + offset]?.Code === 'ConditionalCheckFailed') return reservationFieldIds[i]
}
return null
}
function hasTransientCancellation(reasons) {
return Array.isArray(reasons) && reasons.some((r) => TRANSIENT_CANCELLATION_CODES.has(r?.Code))
}
/**
* Sends a TransactWriteCommand — by default one whose first action is the
* primary write (item create/update) and whose remaining actions are
* unique-field reservation Puts/Deletes (pass `offset: 0` for a
* reservations-only transaction, see mapCancellationReasonToField) — retrying
* a bounded number of times on transient cancellation codes
* (TransactionConflict/ThrottlingError/ProvisionedThroughputExceeded) before
* giving up. A real conflict (ConditionalCheckFailed on a reservation) is
* reported back as a fieldId, not thrown, so the caller can return its usual
* 400 UNIQUE_FIELD_CONFLICT shape.
*
* @param {import('@aws-sdk/lib-dynamodb').DynamoDBDocumentClient} docClient
* @param {unknown[]} transactItems
* @param {string[]} reservationFieldIds
* @param {{ maxAttempts?: number, offset?: number }} [options]
* @returns {Promise<{ conflictFieldId: string | null }>}
*/
async function sendTransactWriteWithUniqueCheck(
docClient,
transactItems,
reservationFieldIds,
{ maxAttempts = 3, offset = 1 } = {}
) {
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
try {
await docClient.send(new TransactWriteCommand({ TransactItems: transactItems }))
return { conflictFieldId: null }
} catch (error) {
if (error.name !== 'TransactionCanceledException') throw error
const reasons = error.CancellationReasons
const conflictFieldId = mapCancellationReasonToField(reasons, reservationFieldIds, offset)
if (conflictFieldId) return { conflictFieldId }
if (hasTransientCancellation(reasons) && attempt < maxAttempts) {
// Short, bounded backoff — this runs inline in the item create/update
// request path, so it must stay well under the Lambda/API Gateway
// timeout even at the max retry count.
await new Promise((resolve) => setTimeout(resolve, 25 * attempt))
continue
}
throw error
}
}
// Unreachable (the loop always returns or throws), kept for lint clarity.
throw new Error('sendTransactWriteWithUniqueCheck: exhausted retries without resolution')
}
/**
* Bulk-releases every reservation row for an entity (entity or flow
* deletion) via the `entityIndex` GSI, mirroring
* referenceCounters.js's deleteAllCountersForEntity.
*/
async function deleteAllReservationsForEntity(docClient, tableName, entityId) {
const items = []
let ExclusiveStartKey
do {
const result = await docClient.send(
new QueryCommand({
TableName: tableName,
IndexName: 'entityIndex',
KeyConditionExpression: 'entityId = :entityId',
ExpressionAttributeValues: { ':entityId': entityId },
ExclusiveStartKey
})
)
items.push(...(result.Items || []))
ExclusiveStartKey = result.LastEvaluatedKey
} while (ExclusiveStartKey)
await batchDelete(
docClient,
tableName,
items.map((item) => ({ pk: item.pk, sk: item.sk }))
)
}
/**
* Bulk-deletes rows for one field of an entity via the `entityIndex` GSI,
* optionally keeping only rows matching a given `sk` predicate. A text/email
* field can independently be `unique` (reservation row, sk === RESERVATION_SK)
* and text-search-indexed (trigram rows, sk === itemId) at the same time —
* both shapes can coexist under the same (entityId, fieldId), so releasing a
* reservation must only delete the reservation row, not the trigram index the
* field keeps regardless. (Scalar-type equality-index rows never coexist with
* a reservation row for the same field — `unique` is restricted to text/email,
* disjoint from the scalar types eligible for equality indexing — so no
* analogous "keep the other shape" cleanup is needed on that side.)
*
* @param {import('@aws-sdk/lib-dynamodb').DynamoDBDocumentClient} docClient
* @param {string} tableName
* @param {string} entityId
* @param {string} fieldId
* @param {(sk: string) => boolean} [skPredicate] omit to delete every row for the field
*/
async function deleteRowsForField(docClient, tableName, entityId, fieldId, skPredicate) {
const result = await docClient.send(
new QueryCommand({
TableName: tableName,
IndexName: 'entityIndex',
KeyConditionExpression: 'entityId = :entityId AND fieldId = :fieldId',
ExpressionAttributeValues: { ':entityId': entityId, ':fieldId': fieldId }
})
)
const items = (result.Items || []).filter((item) => !skPredicate || skPredicate(item.sk))
await batchDelete(
docClient,
tableName,
items.map((item) => ({ pk: item.pk, sk: item.sk }))
)
}
/**
* Bulk-deletes every row for one field of an entity (the field removed from
* the schema entirely — nothing about it is worth keeping).
*/
async function deleteAllReservationsForField(docClient, tableName, entityId, fieldId) {
await deleteRowsForField(docClient, tableName, entityId, fieldId)
}
/**
* Deletes only the reservation row for a field whose `unique` flag turned
* off, leaving its (always-on, automatic) text-search trigram rows untouched.
*/
async function deleteUniqueReservationForField(docClient, tableName, entityId, fieldId) {
await deleteRowsForField(docClient, tableName, entityId, fieldId, (sk) => sk === RESERVATION_SK)
}
/**
* Diffs an entity's field definitions (old vs. new, e.g. on entities/update.js)
* for `unique` transitions that need reservation-table action:
* - `newlyUniqueFields`: fields that just became `unique: true` — existing
* items must be checked for duplicates before the schema change is allowed,
* then backfilled (see scanUniqueFieldValues/backfillUniqueFieldReservations).
* - `noLongerUniqueFieldIds`: fields that lost `unique: true`, or were removed
* from the schema entirely — their reservation rows are now orphaned and
* must be bulk-released (see deleteAllReservationsForField).
*
* @param {Array<{fieldId: string, unique?: boolean}>} previousFields
* @param {Array<{fieldId: string, unique?: boolean}>} nextFields
* @returns {{ newlyUniqueFields: Array, noLongerUniqueFieldIds: string[] }}
*/
function diffUniqueFieldChanges(previousFields, nextFields) {
const previousByFieldId = new Map((previousFields || []).map((f) => [f.fieldId, f]))
const nextByFieldId = new Map((nextFields || []).map((f) => [f.fieldId, f]))
const newlyUniqueFields = (nextFields || []).filter((field) => {
const previous = previousByFieldId.get(field.fieldId)
return field.unique === true && previous?.unique !== true
})
const noLongerUniqueFieldIds = (previousFields || [])
.filter((field) => field.unique === true)
.map((field) => field.fieldId)
.filter((fieldId) => nextByFieldId.get(fieldId)?.unique !== true)
return { newlyUniqueFields, noLongerUniqueFieldIds }
}
/**
* For a field newly marked `unique: true`, scans every existing item of the
* entity (paginated — a rare admin action on the schema, not a hot path, so
* O(n) here is acceptable) and detects duplicate (language, value) pairs
* among them. Returns the scanned values alongside any conflicts found, so a
* clean result can be hand off directly to backfillUniqueFieldReservations
* without re-querying.
*
* @param {import('@aws-sdk/lib-dynamodb').DynamoDBDocumentClient} docClient
* @param {string} itemsTableName
* @param {string} entityId
* @param {{ fieldId: string }} field
* @returns {Promise<{
* valueEntries: Array<{ lang: string, value: string, itemId: string }>,
* conflicts: Array<{ lang: string, value: string, itemIds: string[] }>
* }>}
*/
async function scanUniqueFieldValues(docClient, itemsTableName, entityId, field) {
const valueEntries = []
let ExclusiveStartKey
do {
const result = await docClient.send(
new QueryCommand({
TableName: itemsTableName,
KeyConditionExpression: 'entityId = :eid',
ExpressionAttributeValues: { ':eid': entityId },
ExclusiveStartKey
})
)
for (const item of result.Items || []) {
for (const { lang, value } of getUniqueLanguageValues(field, item)) {
valueEntries.push({ lang, value, itemId: item.id })
}
}
ExclusiveStartKey = result.LastEvaluatedKey
} while (ExclusiveStartKey)
const firstItemIdByKey = new Map()
const conflicts = []
for (const entry of valueEntries) {
const key = `${entry.lang}::${entry.value}`
const firstItemId = firstItemIdByKey.get(key)
if (firstItemId) {
conflicts.push({ lang: entry.lang, value: entry.value, itemIds: [firstItemId, entry.itemId] })
} else {
firstItemIdByKey.set(key, entry.itemId)
}
}
return { valueEntries, conflicts }
}
/**
* Writes a reservation row for every (language, value) pair already scanned
* by scanUniqueFieldValues — call only once its `conflicts` array is empty.
* Unconditioned: duplicates among these exact entries were already ruled out
* by the scan: a rare conflict against something new that snuck in during the
* scan-to-write window is accepted (see entities/update.js) and would surface
* on that item's next update instead of blocking this backfill.
*
* @param {import('@aws-sdk/lib-dynamodb').DynamoDBDocumentClient} docClient
* @param {string} fieldValueIndexTableName
* @param {string} entityId
* @param {string} fieldId
* @param {Array<{ lang: string, value: string, itemId: string }>} valueEntries
*/
async function backfillUniqueFieldReservations(
docClient,
fieldValueIndexTableName,
entityId,
fieldId,
valueEntries
) {
for (const { lang, value, itemId } of valueEntries) {
const { Put } = buildReservationPut(
fieldValueIndexTableName,
entityId,
fieldId,
lang,
value,
itemId
)
await docClient.send(new PutCommand(Put))
}
}
module.exports = {
PLAIN_VALUE_LANG,
RESERVATION_SK,
getUniqueLanguageValues,
diffUniqueLanguageValues,
buildReservationKey,
buildReservationPut,
buildReservationDelete,
mapCancellationReasonToField,
hasTransientCancellation,
sendTransactWriteWithUniqueCheck,
deleteAllReservationsForEntity,
deleteAllReservationsForField,
deleteUniqueReservationForField,
diffUniqueFieldChanges,
scanUniqueFieldValues,
backfillUniqueFieldReservations
}
|