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 | 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 45x 45x 45x 45x 45x 45x 46x 46x 1x 44x 44x 44x 44x 44x 89x 89x 89x 89x 89x 89x 44x 43x 43x 43x 43x 43x 43x 45x 2x 2x 2x 1x 1x 43x 42x 43x 15x 15x 3x 15x 10x 43x 43x 42x 43x 43x 43x 2x 1x 1x 41x 40x 1x 40x 40x 40x 39x 39x 40x 6x 6x 20x 6x 8x 39x 5x 5x 4x 40x 3x 3x 2x 40x 39x 4x | /**
* Shared write path for updating one item, used by items/update.js's HTTP
* handler and by the writes the system makes on a member's membership item
* (membership-requests/decide.js reusing a former member's item,
* flows/remove-member.js moving it to the former member state), so an item
* changed either way gets the same automatic transitions, timers, unique
* values and index rows.
*
* What stays with the caller: who may write (permissions, workflow transition
* rules), validation of the fields it accepts, and credits.
*/
const { resolveAutomaticTransitions } = require('./workflow-transitions')
const { loadLinkedItems } = require('../utils/expressions/linkedItems')
const { scheduleWakeUpSafely } = require('../utils/wakeUpScheduler')
const { validateFieldReference } = require('./reference-validation')
const {
diffUniqueLanguageValues,
buildReservationPut,
buildReservationDelete,
sendTransactWriteWithUniqueCheck
} = require('../utils/uniqueFieldValue')
const {
needsEqualityIndex,
diffEqualityIndexValues,
buildEqualityIndexPut,
buildEqualityIndexDelete
} = require('../utils/equalityIndexValue')
const {
needsTextSearchIndex,
diffTextSearchTokens,
buildTextSearchPutRequest,
buildTextSearchDeleteRequest
} = require('../utils/textSearchIndex')
const { batchWrite } = require('../utils/batchWrite')
const {
getReferencedEntityIds,
diffReferencedEntityIds,
adjustCounters
} = require('../utils/referenceCounters')
const {
getItemFileKeys,
getRemovedKeys,
entityKeyGuard,
deleteKeys
} = require('../utils/s3Cleanup')
/**
* Writes `changes` on top of `existing`: automatic transitions computed in
* memory on top of them (so the item is still written once: an automatic
* transition can never re-trigger itself through a later write), references
* checked, the item and its unique/equality index rows written in one
* transaction, conditioned on the item not having changed since `existing`
* was read; then the wake-up of a moved timer is scheduled.
*
* @param {object} params
* @param {object} params.docClient
* @param {string} params.itemsTableName
* @param {string} params.entityId
* @param {object} params.existing - The item as read
* @param {Array} params.fields - The entity's field definitions
* @param {object} params.changes - Accepted changes (mutated: automatic changes are added)
* @param {string} params.actor - Who writes, for the transitions' history
* @param {string} params.flowId
* @param {string} params.now - ISO date of the write
* @returns {Promise<
* | { status: 'ok', item: object, changes: object }
* | { status: 'invalid', error: string, fieldId?: string, referenceType?: string }
* | { status: 'conflict', fieldId: string }
* | { status: 'modified' }
* | { status: 'empty' }
* >}
*/
async function writeItemUpdate({
docClient,
itemsTableName,
entityId,
existing,
fields,
changes,
actor,
flowId,
now
}) {
const id = existing.id
let mergedData = { ...existing, ...changes }
const automatic = resolveAutomaticTransitions({
fields,
before: existing,
after: mergedData,
actor,
now,
linked: await loadLinkedItems({
docClient,
entitiesTableName: process.env.ENTITIES_TABLE_NAME,
itemsTableName,
fields,
item: mergedData,
flowId
})
})
Object.assign(changes, automatic.changes, automatic.system)
mergedData = { ...existing, ...changes }
for (const field of fields) {
const referenceCheck = await validateFieldReference({
docClient,
field,
value: changes[field.fieldId],
flowId,
flowMembershipsTableName: process.env.FLOW_MEMBERSHIPS_TABLE_NAME,
itemsTableName
})
if (!referenceCheck.valid) {
return {
status: 'invalid',
error: referenceCheck.error,
fieldId: referenceCheck.fieldId,
referenceType: referenceCheck.referenceType
}
}
}
// Build update expression from the changes
const updateExpressions = []
const expressionAttributeNames = {}
const expressionAttributeValues = {}
let attrIndex = 0
for (const [key, value] of Object.entries(changes)) {
const nameKey = `#attr${attrIndex}`
const valueKey = `:val${attrIndex}`
updateExpressions.push(`${nameKey} = ${valueKey}`)
expressionAttributeNames[nameKey] = key
expressionAttributeValues[valueKey] = value
attrIndex++
}
if (updateExpressions.length === 0) return { status: 'empty' }
updateExpressions.push('#updatedAt = :updatedAt')
expressionAttributeNames['#updatedAt'] = 'updatedAt'
expressionAttributeValues[':updatedAt'] = now
// Uniqueness is enforced atomically alongside the item update: for every
// unique field whose (language, value) pairs changed, release the old
// reservation and/or claim the new one in the same TransactWriteCommand as
// the item write — a language whose value is unchanged is skipped
// entirely (DynamoDB forbids two actions against the same primary key in
// one transaction, and an unchanged value maps to the same reservation
// row anyway).
const reservationFieldIds = []
const reservationActions = []
for (const field of fields) {
if (!field.unique) continue
const { toRelease, toClaim } = diffUniqueLanguageValues(field, existing, mergedData)
for (const { lang, value } of toRelease) {
reservationActions.push(
buildReservationDelete(
process.env.FIELD_VALUE_INDEX_TABLE_NAME,
entityId,
field.fieldId,
lang,
value
)
)
reservationFieldIds.push(field.fieldId)
}
for (const { lang, value } of toClaim) {
reservationActions.push(
buildReservationPut(
process.env.FIELD_VALUE_INDEX_TABLE_NAME,
entityId,
field.fieldId,
lang,
value,
id
)
)
reservationFieldIds.push(field.fieldId)
}
}
// Equality-index rows for automatic scalar-type fields, diffed and
// maintained the same way as the reservation rows above. Text/textarea/
// email fields use a separate trigram index (see finishItemUpdate) — they
// never use whole-value equality indexing.
if (process.env.FIELD_VALUE_INDEX_TABLE_NAME) {
for (const field of fields) {
if (!needsEqualityIndex(field)) continue
const { toRelease, toClaim } = diffEqualityIndexValues(field, existing, mergedData)
for (const { lang, value } of toRelease) {
reservationActions.push(
buildEqualityIndexDelete(
process.env.FIELD_VALUE_INDEX_TABLE_NAME,
entityId,
field.fieldId,
lang,
value,
id
)
)
}
for (const { lang, value } of toClaim) {
reservationActions.push(
buildEqualityIndexPut(
process.env.FIELD_VALUE_INDEX_TABLE_NAME,
entityId,
field.fieldId,
lang,
value,
id
)
)
}
}
}
// The item must still be the one read: a write in between (another user, a
// timer's wake-up) makes this one fail rather than overwrite it.
const previousUpdatedAt = existing.updatedAt
if (previousUpdatedAt !== undefined) {
expressionAttributeValues[':previousUpdatedAt'] = previousUpdatedAt
}
const transactItems = [
{
Update: {
TableName: itemsTableName,
Key: { entityId, id },
UpdateExpression: 'SET ' + updateExpressions.join(', '),
ConditionExpression:
previousUpdatedAt === undefined
? 'attribute_not_exists(#updatedAt)'
: '#updatedAt = :previousUpdatedAt',
ExpressionAttributeNames: expressionAttributeNames,
ExpressionAttributeValues: expressionAttributeValues
}
},
...reservationActions
]
let conflictFieldId
try {
;({ conflictFieldId } = await sendTransactWriteWithUniqueCheck(
docClient,
transactItems,
reservationFieldIds
))
} catch (error) {
if (
error.name === 'TransactionCanceledException' &&
error.CancellationReasons?.[0]?.Code === 'ConditionalCheckFailed'
) {
return { status: 'modified' }
}
throw error
}
if (conflictFieldId) return { status: 'conflict', fieldId: conflictFieldId }
// A timer of the item's state moved: (re)schedule its wake-up (UC-WORKFLOW-009.1)
if ('wakeUpAt' in automatic.system) {
await scheduleWakeUpSafely({
entityId,
itemId: id,
wakeUpAt: automatic.system.wakeUpAt,
docClient,
itemsTableName
})
}
// A transactional Update can't return the post-write item (no ReturnValues
// support), so it is reconstructed from what we know was written.
return { status: 'ok', item: { ...existing, ...changes, updatedAt: now }, changes }
}
/**
* The best-effort steps after writeItemUpdate succeeded (the item itself is
* already correctly updated): trigram-index rows, reference counters, and the
* deletion of replaced or cleared images/files.
*
* Trigram-index rows are non-transactional — a large textarea edit can touch
* far more tokens than TransactWriteItems' 100-action limit allows. A failure
* there only delays that field's searchability.
*/
async function finishItemUpdate({ docClient, s3Client, entityId, existing, fields, item, flowId }) {
const id = existing.id
if (process.env.FIELD_VALUE_INDEX_TABLE_NAME) {
const textSearchRequests = []
for (const field of fields) {
if (!needsTextSearchIndex(field)) continue
const { toRelease, toClaim } = diffTextSearchTokens(field, existing, item)
for (const { lang, kind, token } of toRelease) {
textSearchRequests.push(
buildTextSearchDeleteRequest(entityId, field.fieldId, lang, kind, token, id)
)
}
for (const { lang, kind, token } of toClaim) {
textSearchRequests.push(
buildTextSearchPutRequest(entityId, field.fieldId, lang, kind, token, id)
)
}
}
if (textSearchRequests.length > 0) {
try {
await batchWrite(docClient, process.env.FIELD_VALUE_INDEX_TABLE_NAME, textSearchRequests)
} catch (textSearchError) {
console.error('Failed to update text-search index rows:', textSearchError)
}
}
}
if (process.env.ENTITY_REFERENCE_COUNTERS_TABLE_NAME) {
const deltas = diffReferencedEntityIds(
getReferencedEntityIds(fields, existing),
getReferencedEntityIds(fields, item)
)
if (deltas.size > 0) {
await adjustCounters(
docClient,
process.env.ENTITY_REFERENCE_COUNTERS_TABLE_NAME,
flowId,
deltas
)
}
}
// A replaced or cleared image/file is now unreferenced: delete it, last, so
// the item never points at a missing object.
if (s3Client) {
await deleteKeys(
s3Client,
process.env.ATTACHMENTS_BUCKET_NAME,
getRemovedKeys(getItemFileKeys(fields, existing), getItemFileKeys(fields, item)),
entityKeyGuard(entityId)
)
}
}
module.exports = { writeItemUpdate, finishItemUpdate }
|