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 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 9x 9x 10x 10x 10x 9x 9x 9x 9x 9x 9x 9x 9x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 13x 13x 13x 13x 13x 2x 13x 8x 1x 8x 1x 8x 22x 22x 22x 2x 32x 32x 4x 28x 28x 28x 28x 28x 28x 28x 27x 27x 27x 27x 1x 26x 1x 25x 1x 24x 24x 2x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 21x 21x 21x 21x 21x 9x 20x 2x 21x 2x 2x 2x 20x 8x 8x 28x 21x 21x 21x 21x 21x 21x 1x 1x 32x 32x 32x | /**
* SQS-driven async worker for POST /v1/entities/{entityId}/fork.
*
* Creates the forked entity, copies its picture and (optionally) every item
* with its images/files, reporting progress on the job record as it goes.
* Debits dynamodb_storage/dynamodb_throughput credits for what was actually
* written — even when the job fails partway, since a partial fork still cost
* real storage; s3_storage is debited by uploads/s3-usage-consumer.js as each
* copy lands. See docs/architecture/USAGE_METERING.md "Gap found and closed:
* bulk import and entity fork bypassed credits entirely".
*
* @implements UC-CREDITS-005.1
*/
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb')
const { DynamoDBDocumentClient, GetCommand, QueryCommand } = require('@aws-sdk/lib-dynamodb')
const { randomUUID } = require('crypto')
const { checkPermissionDirect } = require('../utils/requirePermission')
const { permissionChecker } = require('../utils/PermissionChecker')
const { findEntityNameConflict } = require('../utils/nameUniqueness')
const { renameDuplicateFieldNames } = require('../utils/fieldNameUniqueness')
const { copyImageObject, copyImageFields, copyFileFields } = require('../utils/entityImageCopy')
const { createItem } = require('../items/createItem')
const { putEntityRecord } = require('./createEntityRecord')
const { batchWrite } = require('../utils/batchWrite')
const {
getCatalogSearchTokens,
buildCatalogSearchPutRequest
} = require('../utils/catalogSearchIndex')
const { adjustCounters } = require('../utils/referenceCounters')
const { debitCredits } = require('../utils/creditsLedger')
const { getPricingConfig } = require('../utils/pricingConfig')
const { getConsumedCapacity } = require('../shared/usage-tracking')
const { itemDataBytes } = require('../utils/forkCostEstimate')
const {
getJob,
markJobProcessing,
markJobCompleted,
markJobFailed,
createThrottledProgressReporter
} = require('../utils/jobsTable')
const client = new DynamoDBClient({})
const docClient = DynamoDBDocumentClient.from(client)
// An expected, user-presentable failure (its message is shown to the user, as
// opposed to an unexpected error, whose message may leak internals).
class ForkJobError extends Error {}
// Unlike the submit-time estimate (which only samples the first page), the
// copy must see every item.
async function fetchAllEntityItems(entityId) {
const items = []
let exclusiveStartKey
do {
const page = await docClient.send(
new QueryCommand({
TableName: process.env.ITEMS_TABLE_NAME,
KeyConditionExpression: 'entityId = :entityId',
ExpressionAttributeValues: { ':entityId': entityId },
...(exclusiveStartKey && { ExclusiveStartKey: exclusiveStartKey })
})
)
items.push(...(page.Items || []))
exclusiveStartKey = page.LastEvaluatedKey
} while (exclusiveStartKey)
return items
}
async function copyEntityItems({
sourceItems,
targetEntityId,
targetFlowId,
userId,
fields,
costTracker,
report
}) {
const now = new Date().toISOString()
const owner = { userId, flowId: targetFlowId }
const textSearchRequests = []
const referencedEntityCounts = new Map()
// +1: the forked entity itself was step 1 (see processForkJob).
const total = sourceItems.length + 1
let copied = 0
for (const sourceItem of sourceItems) {
// eslint-disable-next-line no-unused-vars
const { id, entityId, flowId, createdBy, createdAt, updatedAt, ...data } = sourceItem
const newItem = {
...data,
entityId: targetEntityId,
id: randomUUID(),
flowId: targetFlowId,
createdBy: userId,
createdAt: now,
updatedAt: now
}
// copyImageFields/copyFileFields key their S3 copies off newItem.id, so
// they must run on the full envelope before the envelope fields are
// stripped back off for the shared write path below.
await copyImageFields({ item: newItem, fields, targetEntityId, owner })
await copyFileFields({ item: newItem, fields, targetEntityId, owner })
const itemId = newItem.id
const finalData = { ...newItem }
delete finalData.entityId
delete finalData.id
delete finalData.flowId
delete finalData.createdBy
delete finalData.createdAt
delete finalData.updatedAt
// Writes the item plus a reservation for each unique field's value in
// the (fresh, empty) forked entity's partition, atomically — see
// items/createItem.js. A conflict is structurally impossible here (the
// source entity's own uniqueness was already valid, and the fork gets a
// brand-new entityId, so no other item can already hold these values
// under it), so it's treated as an unexpected error rather than handled.
const {
conflictFieldId,
textSearchRequests: itemTextSearchRequests,
referencedEntityIds
} = await createItem({
docClient,
itemsTableName: process.env.ITEMS_TABLE_NAME,
fieldValueIndexTableName: process.env.FIELD_VALUE_INDEX_TABLE_NAME,
entityItemCountTableName: process.env.ENTITY_ITEM_COUNT_TABLE_NAME,
entityId: targetEntityId,
flowId: targetFlowId,
fields,
data: finalData,
itemId,
createdBy: userId,
createdAt: now
})
Iif (conflictFieldId) {
throw new Error(
`Unexpected unique-field conflict (${conflictFieldId}) copying item ${sourceItem.id}`
)
}
costTracker.itemsBytes += itemDataBytes(sourceItem)
copied += 1
textSearchRequests.push(...itemTextSearchRequests)
for (const refEntityId of referencedEntityIds) {
referencedEntityCounts.set(refEntityId, (referencedEntityCounts.get(refEntityId) || 0) + 1)
}
await report(copied + 1, total)
}
// Text-search index rows are flushed once, batched, after every item is
// copied — a rich text field copied across many items can produce far more
// rows than is sensible to write one-by-one.
if (process.env.FIELD_VALUE_INDEX_TABLE_NAME && textSearchRequests.length > 0) {
await batchWrite(docClient, process.env.FIELD_VALUE_INDEX_TABLE_NAME, textSearchRequests)
}
if (process.env.ENTITY_REFERENCE_COUNTERS_TABLE_NAME && referencedEntityCounts.size > 0) {
await adjustCounters(
docClient,
process.env.ENTITY_REFERENCE_COUNTERS_TABLE_NAME,
targetFlowId,
referencedEntityCounts
)
}
return copied
}
function toPlainJson(value, fallback) {
Iif (value === undefined || value === null) return fallback
try {
return JSON.parse(JSON.stringify(value))
} catch {
return fallback
}
}
function displayName(name, fallback) {
return typeof name === 'string' ? name : name?.en || name?.fr || fallback
}
async function processForkJob(jobId) {
const job = await getJob(jobId)
// Only ever run a job from `pending` — a redelivered message for a job that
// already ran (or crashed while `processing`) must not fork a second time:
// every attempt assigns brand new ids, so a re-run would leave duplicate
// entities and copied items behind. A job stuck at `processing` is left for
// the DLQ alarm to surface rather than auto-retried.
if (!job || job.status !== 'pending') {
return
}
const { flowId: targetFlowId, userId, request } = job
const { sourceEntityId, name: forkedName, visibility, copyItems } = request
const report = createThrottledProgressReporter(jobId)
// Accumulated as things are actually written, so the debit below charges
// exactly what landed — including a partial fork that failed midway.
const costTracker = { entityBytes: 0, itemsBytes: 0 }
let forkedEntity = null
try {
await checkPermissionDirect(userId, targetFlowId, 'entities:create')
await markJobProcessing(jobId)
const sourceResult = await docClient.send(
new GetCommand({ TableName: process.env.TABLE_NAME, Key: { id: sourceEntityId } })
)
const sourceEntity = sourceResult.Item
if (!sourceEntity) {
throw new ForkJobError('Source entity not found')
}
// Re-checked: the source may have been made private or deleted while the
// job waited in the queue.
if (sourceEntity.visibility !== 'public' && sourceEntity.flowId !== targetFlowId) {
throw new ForkJobError('This entity cannot be forked')
}
if (
sourceEntity.visibility === 'restricted' &&
!permissionChecker.grantsEntityAndItemsRead(
(await permissionChecker.getUserPermissions(userId, targetFlowId)).permissions,
sourceEntity
)
) {
throw new ForkJobError('This entity cannot be forked')
}
const nameConflict = await findEntityNameConflict(docClient, {
tableName: process.env.TABLE_NAME,
flowId: targetFlowId,
name: forkedName
})
if (nameConflict) {
throw new ForkJobError(
`Entity name "${displayName(forkedName, 'Forked Entity')}" already exists in this flow`
)
}
const now = new Date().toISOString()
// A source written before field names became unique may hold duplicates:
// the later field takes "Name (2)" (utils/fieldNameUniqueness.js)
const { fields: inheritedFields, renamedFields } = renameDuplicateFieldNames(
Array.isArray(sourceEntity.fields) ? toPlainJson(sourceEntity.fields, []) : [],
sourceEntity.defaultLanguage
)
const inheritedForms = Array.isArray(sourceEntity.forms)
? toPlainJson(sourceEntity.forms, [])
: undefined
const inheritedEmailTemplates = Array.isArray(sourceEntity.emailTemplates)
? toPlainJson(sourceEntity.emailTemplates, [])
: []
const inheritedEnabledLanguages = Array.isArray(sourceEntity.enabledLanguages)
? toPlainJson(sourceEntity.enabledLanguages, [])
: undefined
const inheritedPublicPermissions = Array.isArray(sourceEntity.publicPermissions)
? toPlainJson(sourceEntity.publicPermissions, [])
: undefined
const sourceItems = copyItems ? await fetchAllEntityItems(sourceEntity.id) : []
const totalSteps = 1 + sourceItems.length
const forkedEntityId = randomUUID()
// Entity pictures are stored at `entities/${entityId}/entity-picture/...`
// — no itemId, since it isn't tied to any item — so this must not share
// the source entity's S3 object either.
const forkedPicture = sourceEntity.picture
? await copyImageObject({
sourceKey: sourceEntity.picture,
targetEntityId: forkedEntityId,
fieldId: 'entity-picture',
owner: { userId, flowId: targetFlowId }
})
: undefined
const entityRecord = {
id: forkedEntityId,
flowId: targetFlowId,
name: forkedName,
fields: inheritedFields,
visibility,
...(sourceEntity.description && {
description: toPlainJson(sourceEntity.description, undefined)
}),
...(forkedPicture && { picture: forkedPicture }),
...(sourceEntity.icon && { icon: sourceEntity.icon }),
...(inheritedForms && inheritedForms.length > 0 && { forms: inheritedForms }),
// The transitions' Email actions come with the fields: so do their templates
...(inheritedEmailTemplates.length > 0 && { emailTemplates: inheritedEmailTemplates }),
// Comments themselves are never forked, only whether the entity accepts them
commentsEnabled: sourceEntity.commentsEnabled === true,
...(sourceEntity.defaultLanguage && { defaultLanguage: sourceEntity.defaultLanguage }),
...(inheritedEnabledLanguages && {
enabledLanguages: inheritedEnabledLanguages
}),
...(visibility === 'public' &&
inheritedPublicPermissions && {
publicPermissions: inheritedPublicPermissions
}),
forkedFromEntityId: sourceEntity.id,
forkedFromFlowId: sourceEntity.flowId,
forkedAt: now,
forkedBy: userId,
sourceSnapshotVersion: sourceEntity.updatedAt || sourceEntity.createdAt || now,
createdBy: userId,
createdAt: now,
updatedAt: now
}
await putEntityRecord(docClient, process.env.TABLE_NAME, entityRecord)
forkedEntity = entityRecord
costTracker.entityBytes = Buffer.byteLength(
JSON.stringify({ fields: inheritedFields, forms: inheritedForms || [] })
)
await report(1, totalSteps)
let copiedItemsCount = 0
if (copyItems) {
copiedItemsCount = await copyEntityItems({
sourceItems,
targetEntityId: forkedEntity.id,
targetFlowId,
userId,
fields: inheritedFields,
costTracker,
report
})
}
// Catalog-search index rows are best-effort and non-transactional, same
// reasoning as entities/create.js and items/create.js.
if (process.env.FIELD_VALUE_INDEX_TABLE_NAME) {
const catalogSearchRequests = getCatalogSearchTokens(forkedEntity.name).map(
({ kind, token }) => buildCatalogSearchPutRequest(kind, token, forkedEntity.id)
)
Eif (catalogSearchRequests.length > 0) {
try {
await batchWrite(
docClient,
process.env.FIELD_VALUE_INDEX_TABLE_NAME,
catalogSearchRequests
)
} catch (catalogSearchError) {
console.error('Failed to write catalog-search index rows:', catalogSearchError)
}
}
}
await markJobCompleted(jobId, {
entity: { ...forkedEntity, copiedItemsCount },
...(renamedFields.length > 0 && { renamedFields })
})
} catch (error) {
console.error('[fork-worker] Job failed:', jobId, error.message, error.stack)
await markJobFailed(
jobId,
error instanceof ForkJobError ? error.message : 'Failed to fork entity'
)
}
// Best-effort from here: a failure doesn't unwind the writes, nor does it
// retroactively change the job's outcome — see items/create.js's identical
// reasoning. Nothing to charge if the fork failed before writing anything.
if (!forkedEntity) return
try {
const pricing = await getPricingConfig(docClient, process.env.PRICING_CONFIG_TABLE_NAME)
const storageCreditCost = Math.ceil(
((costTracker.entityBytes + costTracker.itemsBytes) / 1024) *
pricing.dynamodb_storage_credits_per_kb
)
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,
flowId: targetFlowId,
charges: [
{
pool: 'dynamodb_storage',
operation: 'entity_fork',
costCredits: storageCreditCost,
referenceId: forkedEntity.id
},
{
pool: 'dynamodb_throughput',
operation: 'entity_fork',
costCredits: throughputCreditCost,
referenceId: forkedEntity.id
}
]
})
} catch (creditError) {
console.error('Failed to debit credits for entity fork:', jobId, creditError)
}
}
exports.handler = async (event) => {
for (const record of event.Records) {
const { jobId } = JSON.parse(record.body)
await processForkJob(jobId)
}
}
|