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 414 415 416 417 418 419 420 421 422 423 424 425 426 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 65x 65x 65x 1x 64x 1x 63x 62x 1x 61x 61x 61x 1x 60x 1x 59x 59x 1x 58x 58x 1x 57x 56x 1x 55x 55x 1x 54x 54x 54x 54x 2x 52x 52x 3x 49x 49x 5x 44x 78x 78x 1x 43x 43x 43x 43x 43x 43x 43x 43x 4x 39x 38x 1x 37x 1x 37x 37x 37x 37x 1x 37x 6x 6x 5x 37x 1x 1x 37x 3x 3x 1x 2x 1x | /**
* POST /v1/entities/{entityId}/items
*
* Storage-credit preflight + synchronous post-write debit — see
* docs/architecture/USAGE_METERING.md "DynamoDB storage credits".
*
* @implements UC-CREDITS-002.1, UC-CREDITS-003.1, UC-APIKEY-007.1, UC-WORKFLOW-007.1, UC-WORKFLOW-008.1, UC-WORKFLOW-009.1
*/
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb')
const { DynamoDBDocumentClient, GetCommand } = require('@aws-sdk/lib-dynamodb')
const { authenticateRequest, hasPermission, canAccessEntity } = require('../shared/auth-helper')
const { validateFieldReference } = require('./reference-validation')
const {
validateMandatoryFields,
validateFieldConstraints,
validateFieldTypes
} = require('./field-validation')
const { createItem } = require('./createItem')
const { prepareNewItemData } = require('./newItemData')
const { withoutReservedKeys } = require('./reservedKeys')
const { scheduleWakeUpSafely } = require('../utils/wakeUpScheduler')
const { batchWrite } = require('../utils/batchWrite')
const { adjustCounters } = require('../utils/referenceCounters')
const { isValidUuid } = require('../utils/isValidUuid')
const { MAX_ITEM_SIZE_BYTES } = require('../utils/constants')
const { resolveBillingUserId, getCreditsBalance, debitCredits } = require('../utils/creditsLedger')
const { getPricingConfig } = require('../utils/pricingConfig')
const { getConsumedCapacity } = require('../shared/usage-tracking')
const client = new DynamoDBClient({})
const docClient = DynamoDBDocumentClient.from(client)
const createItemHandler = async (event) => {
try {
// Authenticate — supports Cognito JWT (gateway or header) and API keys
const auth = await authenticateRequest(event)
if (!auth || auth.error) {
return {
statusCode: 401,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
body: JSON.stringify({ error: auth?.error || 'Authentication required' })
}
}
if (auth.type === 'jwt' && !auth.flowId) {
return {
statusCode: 401,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
body: JSON.stringify({ error: 'No valid authentication provided' })
}
}
const body = JSON.parse(event.body || '{}')
if (!body.data) {
return {
statusCode: 400,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
body: JSON.stringify({ error: 'Missing required fields: entityId, data' })
}
}
// Server-maintained attributes (flowId, createdBy, ...) are never taken
// from the client
body.data = withoutReservedKeys(body.data)
const dataSizeBytes = Buffer.byteLength(JSON.stringify(body.data))
if (dataSizeBytes > MAX_ITEM_SIZE_BYTES) {
return {
statusCode: 400,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
body: JSON.stringify({
error: 'ITEM_TOO_LARGE',
maxBytes: MAX_ITEM_SIZE_BYTES,
actualBytes: dataSizeBytes
})
}
}
// Callers may supply the item's id up front (generated client-side before
// the first request), so image fields uploaded during creation can be
// keyed by the real id from the start instead of a throwaway placeholder
// that would never get reconciled afterward.
if (body.id !== undefined && !isValidUuid(body.id)) {
return {
statusCode: 400,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
body: JSON.stringify({ error: 'Invalid id: must be a UUID' })
}
}
// entityId comes from path parameter; body.entityId kept for backward compatibility
const entityId = event.pathParameters?.entityId || body.entityId
if (!entityId) {
return {
statusCode: 400,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
body: JSON.stringify({ error: 'Missing entityId' })
}
}
const requiredPermission = `entities-${entityId}:items:create`
if (!(await hasPermission(auth, requiredPermission))) {
return {
statusCode: 403,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
body: JSON.stringify({ error: `Permission denied: ${requiredPermission} required` })
}
}
// Verify entity exists and caller has access
const entityResult = await docClient.send(
new GetCommand({
TableName: process.env.ENTITIES_TABLE_NAME,
Key: { id: entityId }
})
)
if (!entityResult.Item) {
return {
statusCode: 404,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
body: JSON.stringify({ error: 'Entity not found' })
}
}
const entity = entityResult.Item
// canAccessEntity handles: public entities, flow ownership
if (!canAccessEntity(auth, entity)) {
return {
statusCode: 403,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
body: JSON.stringify({ error: 'Access denied to this entity' })
}
}
const flowId = auth.flowId
const fields = entity.fields || []
// Validate mandatory fields (boolean/workflow types are never required)
const mandatoryCheck = validateMandatoryFields(fields, body.data)
if (!mandatoryCheck.valid) {
return {
statusCode: 400,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
body: JSON.stringify({ error: 'MANDATORY_FIELD_MISSING', fieldId: mandatoryCheck.fieldId })
}
}
// Validate max length / max line count
const constraintsCheck = validateFieldConstraints(fields, body.data)
if (!constraintsCheck.valid) {
return {
statusCode: 400,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
body: JSON.stringify({ error: constraintsCheck.error, fieldId: constraintsCheck.fieldId })
}
}
// Validate type/shape correctness (numbers are numbers, dates are valid,
// select/multiselect values are among the field's options, etc.)
const typeCheck = validateFieldTypes(fields, body.data)
if (!typeCheck.valid) {
return {
statusCode: 400,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
body: JSON.stringify({ error: typeCheck.error, fieldId: typeCheck.fieldId })
}
}
// Validate foreign-key style references against their target scope.
for (const field of fields) {
const referenceCheck = await validateFieldReference({
docClient,
field,
value: body.data[field.fieldId],
flowId,
flowMembershipsTableName: process.env.FLOW_MEMBERSHIPS_TABLE_NAME,
itemsTableName: process.env.TABLE_NAME
})
if (!referenceCheck.valid) {
return {
statusCode: 400,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
body: JSON.stringify({
error: referenceCheck.error,
fieldId: referenceCheck.fieldId,
referenceType: referenceCheck.referenceType
})
}
}
}
// Workflow start states, then the automatic transitions leaving them
// (UC-WORKFLOW-007.1), in memory before the single write
const createdBy = auth.userId || auth.createdBy
const createdAt = new Date().toISOString()
const { wakeUpAt } = await prepareNewItemData({
docClient,
fields,
data: body.data,
actor: createdBy,
now: createdAt,
flowId
})
// Storage-credit preflight: reject before writing anything if the
// account plainly can't cover even the (deterministic, known pre-write)
// storage cost. The exact dynamodb_throughput cost is only known after
// the write below actually happens — see the debit after the transaction
// succeeds. See docs/architecture/USAGE_METERING.md "DynamoDB storage
// credits".
const pricing = await getPricingConfig(docClient, process.env.PRICING_CONFIG_TABLE_NAME)
const storageCreditEstimate = Math.ceil(
(dataSizeBytes / 1024) * pricing.dynamodb_storage_credits_per_kb
)
const billingUserId = resolveBillingUserId(auth)
const { balance: creditsBalance, isPlatformAdmin } = billingUserId
? await getCreditsBalance(docClient, process.env.USERS_TABLE_NAME, billingUserId)
: { balance: 0, isPlatformAdmin: false }
if (!billingUserId || (!isPlatformAdmin && creditsBalance < storageCreditEstimate)) {
return {
statusCode: 402,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
body: JSON.stringify({
error: 'INSUFFICIENT_CREDITS',
required: storageCreditEstimate,
balance: creditsBalance
})
}
}
// Uniqueness is enforced atomically alongside the item write: a
// conditioned reservation Put per (unique field × non-empty language
// value) in the same TransactWriteCommand, so two concurrent creates
// with the same value can never both succeed (unlike a Query-then-write
// check, which is racy no matter how it's implemented). See
// items/createItem.js for the shared write path (also used by
// entities/fork.js and entities/import-worker.js).
const { conflictFieldId, item, textSearchRequests, referencedEntityIds } = await createItem({
docClient,
itemsTableName: process.env.TABLE_NAME,
fieldValueIndexTableName: process.env.FIELD_VALUE_INDEX_TABLE_NAME,
entityItemCountTableName: process.env.ENTITY_ITEM_COUNT_TABLE_NAME,
entityId,
flowId,
fields,
data: body.data,
itemId: body.id,
// An API key acts for its creator
createdBy,
createdAt
})
if (conflictFieldId) {
return {
statusCode: 400,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
body: JSON.stringify({ error: 'UNIQUE_FIELD_CONFLICT', fieldId: conflictFieldId })
}
}
// A timer of the item's state is waiting: schedule its wake-up (UC-WORKFLOW-009.1)
if (wakeUpAt) {
await scheduleWakeUpSafely({
entityId,
itemId: item.id,
wakeUpAt,
docClient,
itemsTableName: process.env.TABLE_NAME
})
}
// The item now durably exists — debit credits for the real cost of
// writing it (storage estimate finalized above, throughput now known
// exactly from every DynamoDB call this invocation made, via the SDK
// patch in shared/usage-tracking.js). Best-effort from here: a failure
// doesn't unwind the write (there's nothing to roll back to), it only
// means this write went unbilled — see docs/architecture/USAGE_METERING.md
// "DynamoDB storage credits" for why that's an accepted, bounded gap
// rather than something to retry/block on.
try {
const { writeUnits } = getConsumedCapacity()
const throughputCreditCost = Math.ceil(
writeUnits * pricing.dynamodb_throughput_credits_per_wru
)
await debitCredits(docClient, {
usersTableName: process.env.USERS_TABLE_NAME,
creditsLedgerTableName: process.env.CREDITS_LEDGER_TABLE_NAME,
userId: billingUserId,
flowId,
charges: [
{
pool: 'dynamodb_storage',
operation: 'item_create',
costCredits: storageCreditEstimate,
referenceId: item.id
},
{
pool: 'dynamodb_throughput',
operation: 'item_create',
costCredits: throughputCreditCost,
referenceId: item.id
}
]
})
} catch (creditError) {
console.error('Failed to debit credits for item create:', creditError)
}
// Trigram-index rows for text/textarea/email fields are best-effort and
// non-transactional — a large textarea can produce far more actions than
// TransactWriteItems' 100-action limit allows, so this can't ride in the
// transaction above. The item itself is already correctly written; a
// failure here only delays that field's searchability, so it's logged
// and swallowed rather than failing the create response.
if (textSearchRequests.length > 0) {
try {
await batchWrite(docClient, process.env.FIELD_VALUE_INDEX_TABLE_NAME, textSearchRequests)
} catch (textSearchError) {
console.error('Failed to write text-search index rows:', textSearchError)
}
}
if (process.env.ENTITY_REFERENCE_COUNTERS_TABLE_NAME && referencedEntityIds.size > 0) {
await adjustCounters(
docClient,
process.env.ENTITY_REFERENCE_COUNTERS_TABLE_NAME,
flowId,
new Map([...referencedEntityIds].map((refEntityId) => [refEntityId, 1]))
)
}
return {
statusCode: 201,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
body: JSON.stringify(item)
}
} catch (error) {
console.error('Error:', error)
// The item's own id collision (client-supplied id already exists) surfaces
// as index 0 of a TransactWriteCommand's CancellationReasons — every
// reservation Put failing its condition instead is already handled above
// by sendTransactWriteWithUniqueCheck, so reaching here means it was the
// item write itself that failed.
if (
error.name === 'ConditionalCheckFailedException' ||
(error.name === 'TransactionCanceledException' &&
error.CancellationReasons?.[0]?.Code === 'ConditionalCheckFailed')
) {
return {
statusCode: 409,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
body: JSON.stringify({ error: 'An item with this id already exists' })
}
}
return {
statusCode: 500,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
body: JSON.stringify({ error: 'Failed to create item' })
}
}
}
exports.handler = createItemHandler
|