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 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 21x 21x 21x 21x 21x 21x 1x 17x 3x 1x 2x 1x 1x 14x 1x 21x 21x 21x 1x 20x 20x 20x 20x 20x 20x 20x 1x 19x 19x 19x 19x 1x 18x 1x 17x 17x 2x 15x 15x 15x 15x 2x 2x 13x 13x 13x 13x 13x 13x 4x 9x 8x 8x 1x 1x 1x | /**
* POST /v1/entities/{entityId}/fork
*
* Submit handler — validates the request, runs the credit preflight, then
* hands the actual copy to fork-worker.js via SQS and returns a job id to
* poll (GET /v1/entities/fork/jobs/{jobId}). Async for the same reason as
* import: copying every item (and its images) of a large entity can far
* exceed API Gateway's 29s integration timeout, and a Lambda killed halfway
* would leave a partial fork that never gets billed.
*
* The preflight gates on the fork's *whole* estimated cost — DynamoDB storage,
* copied images/files and a write-throughput allowance (see
* utils/forkCostEstimate.js) — so a fork is refused up front rather than
* starting and overshooting the balance. The exact debit happens in the
* worker; see docs/architecture/USAGE_METERING.md "Gap found and closed: bulk
* import and entity fork bypassed credits entirely".
*
* @implements UC-CREDITS-005.1
*/
const { getActiveFlowId } = require('../shared/activeFlow')
const { SQSClient, SendMessageCommand } = require('@aws-sdk/client-sqs')
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb')
const { DynamoDBDocumentClient, GetCommand } = require('@aws-sdk/lib-dynamodb')
const { requirePermission } = require('../utils/requirePermission')
const { permissionChecker } = require('../utils/PermissionChecker')
const { VISIBILITY_LEVELS } = require('../utils/constants')
const { findEntityNameConflict } = require('../utils/nameUniqueness')
const { getCreditsBalance } = require('../utils/creditsLedger')
const { getPricingConfig } = require('../utils/pricingConfig')
const { createJob } = require('../utils/jobsTable')
const { estimateForkCost, loadForkEstimateInputs } = require('../utils/forkCostEstimate')
const sqsClient = new SQSClient({})
const docClient = DynamoDBDocumentClient.from(new DynamoDBClient({}))
function jsonResponse(statusCode, body) {
return {
statusCode,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
body: JSON.stringify(body)
}
}
function safeParseBody(rawBody) {
Iif (!rawBody) return {}
Iif (typeof rawBody === 'object') return rawBody
Iif (typeof rawBody !== 'string') return {}
try {
return JSON.parse(rawBody)
} catch {
return null
}
}
function getResolvedVisibility(body) {
if (body.visibility !== undefined) {
if (!VISIBILITY_LEVELS.includes(body.visibility)) {
return { error: `Invalid visibility level. Must be one of: ${VISIBILITY_LEVELS.join(', ')}` }
}
// A restricted entity comes with its own roles (UC-RBAC-008.1), which only
// entities/create.js and entities/update.js write — restrict the fork once
// it exists instead.
if (body.visibility === 'restricted') {
return { error: 'A fork cannot be created as restricted — restrict it once forked' }
}
return { value: body.visibility }
}
// Fork defaults to private-in-flow unless explicitly requested.
return { value: 'flow-members' }
}
const forkEntityHandler = async (event) => {
try {
const body = safeParseBody(event.body)
if (body === null) {
return jsonResponse(400, { error: 'Invalid JSON body' })
}
const sourceEntityId = event.pathParameters?.entityId
const targetFlowId = await getActiveFlowId(event)
const userId = event.requestContext?.authorizer?.claims?.sub
Iif (!targetFlowId) {
return jsonResponse(401, { error: 'Missing flow context' })
}
Iif (!sourceEntityId) {
return jsonResponse(400, { error: 'Missing source entity id' })
}
const sourceResult = await docClient.send(
new GetCommand({
TableName: process.env.TABLE_NAME,
Key: { id: sourceEntityId }
})
)
if (!sourceResult.Item) {
return jsonResponse(404, { error: 'Source entity not found' })
}
const sourceEntity = sourceResult.Item
const isSourcePublic = sourceEntity.visibility === 'public'
const isOwnEntity = sourceEntity.flowId === targetFlowId
if (!isSourcePublic && !isOwnEntity) {
return jsonResponse(403, { error: 'This entity cannot be forked' })
}
if (
sourceEntity.visibility === 'restricted' &&
!permissionChecker.grantsEntityAndItemsRead(
(await permissionChecker.getUserPermissions(userId, targetFlowId)).permissions,
sourceEntity
)
) {
return jsonResponse(403, { error: 'This entity cannot be forked' })
}
const resolvedVisibilityResult = getResolvedVisibility(body)
if (resolvedVisibilityResult.error) {
return jsonResponse(400, { error: resolvedVisibilityResult.error })
}
const sourceName =
typeof sourceEntity.name === 'string'
? sourceEntity.name
: sourceEntity?.name?.en || sourceEntity?.name?.fr || 'Forked Entity'
const forkedName = body.name || `${sourceName} (Fork)`
// Checked again by the worker (a name could be taken while the job waits
// in the queue), but the common case is worth failing fast on.
const nameConflict = await findEntityNameConflict(docClient, {
tableName: process.env.TABLE_NAME,
flowId: targetFlowId,
name: forkedName
})
if (nameConflict) {
const displayForkedName =
typeof forkedName === 'string' ? forkedName : forkedName?.en || forkedName?.fr || sourceName
return jsonResponse(409, {
error: `Entity name "${displayForkedName}" already exists in this flow`
})
}
const copyItems = body.copyItems === true
const { items, totalItemCount } = await loadForkEstimateInputs({
docClient,
entityId: sourceEntity.id,
copyItems
})
const pricing = await getPricingConfig(docClient, process.env.PRICING_CONFIG_TABLE_NAME)
const { totalCredits: estimatedCredits } = await estimateForkCost({
fields: Array.isArray(sourceEntity.fields) ? sourceEntity.fields : [],
forms: Array.isArray(sourceEntity.forms) ? sourceEntity.forms : [],
picture: sourceEntity.picture,
items,
totalItemCount,
pricing
})
const { balance: creditsBalance, isPlatformAdmin } = userId
? await getCreditsBalance(docClient, process.env.USERS_TABLE_NAME, userId)
: { balance: 0, isPlatformAdmin: false }
if (!userId || (!isPlatformAdmin && creditsBalance < estimatedCredits)) {
return jsonResponse(402, {
error: 'INSUFFICIENT_CREDITS',
required: estimatedCredits,
balance: creditsBalance
})
}
const job = await createJob({
type: 'fork',
flowId: targetFlowId,
userId,
request: {
sourceEntityId: sourceEntity.id,
name: forkedName,
visibility: resolvedVisibilityResult.value,
copyItems
},
// The entity itself, then one step per copied item. The worker
// corrects the total once it has read the real item list.
total: 1 + (copyItems ? totalItemCount : 0)
})
await sqsClient.send(
new SendMessageCommand({
QueueUrl: process.env.FORK_JOBS_QUEUE_URL,
MessageBody: JSON.stringify({ jobId: job.id })
})
)
return jsonResponse(202, { jobId: job.id })
} catch (error) {
console.error('[fork] Exception:', error.message, error.stack)
return jsonResponse(500, { error: 'Failed to fork entity' })
}
}
exports.handler = requirePermission(forkEntityHandler, {
permission: 'entities:create'
})
|