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 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 8x 7x 12x 11x 1x 16x 16x 16x 15x 15x 14x 1x 13x 13x 1x 12x 11x 9x 1x 8x 8x 4x 4x 4x 3x 3x 3x 3x 1x 2x 2x 2x 1x 1x | /**
* POST /v1/store/{packId}/import
*
* Installs the current version of a pack in the active flow, through the existing
* import pipeline (entities/import-worker.js): 202 and a job to poll with
* GET /v1/entities/import/jobs/{jobId}. Body:
* { version: number, choices: [{ tempId, mode: 'create' | 'skip', name? }] }
*
* `version` is the one the caller reviewed: if it is no longer current the request
* is refused, so nobody installs an old version, or one they did not see. The API
* only ever imports the stored schema, never one sent by the client, and the job
* carries a reference to it, which keeps large schemas out of the jobs table.
*
* @implements UC-STORE-005.1
*/
const { SQSClient, SendMessageCommand } = require('@aws-sdk/client-sqs')
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb')
const { DynamoDBDocumentClient } = require('@aws-sdk/lib-dynamodb')
const {
authenticateModerator: authenticateUser,
errorResponse,
jsonResponse
} = require('../utils/moderation/access')
const { hasPermission } = require('../shared/auth-helper')
const { createJob } = require('../utils/jobsTable')
const { getCreditsBalance } = require('../utils/creditsLedger')
const { getPricingConfig } = require('../utils/pricingConfig')
const { estimateImportCreditCost } = require('../utils/importCreditEstimate')
const { getPack } = require('../utils/packs')
const { readSnapshot, buildPackImportEntries } = require('../utils/packSnapshot')
const sqsClient = new SQSClient({})
const docClient = DynamoDBDocumentClient.from(new DynamoDBClient({}))
/** See entities/import.js: the phases import-worker.js reports progress over. */
const IMPORT_JOB_PHASE_COUNT = 4
function parseChoices(raw) {
if (!Array.isArray(raw)) return []
return raw
.filter((choice) => typeof choice?.tempId === 'string')
.map((choice) => ({
tempId: choice.tempId,
mode: choice.mode === 'create' ? 'create' : 'skip',
...(typeof choice.name === 'string' && choice.name.trim() && { name: choice.name.trim() }),
...(choice.name && typeof choice.name === 'object' && { name: choice.name }),
// The pack's items for that entity come with it, unless declined
...(choice.includeItems === false && { includeItems: false })
}))
}
exports.handler = async (event) => {
try {
const caller = await authenticateUser(event)
if (caller.response) return caller.response
const { auth } = caller
if (!auth.flowId) return errorResponse(403, 'NO_ACTIVE_FLOW')
if (!(await hasPermission(auth, 'entities:create'))) {
return errorResponse(403, 'Permission denied: entities:create required')
}
let payload
try {
payload = JSON.parse(event.body || '{}')
} catch {
return errorResponse(400, 'Invalid JSON body')
}
const pack = await getPack(docClient, event.pathParameters?.packId, { consistent: true })
if (!pack?.currentVersion) return errorResponse(404, 'Pack not found')
if (payload.version !== pack.currentVersion) {
return errorResponse(409, 'PACK_VERSION_OUTDATED', { currentVersion: pack.currentVersion })
}
const choices = parseChoices(payload.choices)
if (!choices.some((choice) => choice.mode === 'create')) {
return errorResponse(400, 'Nothing to install')
}
const bundle = await readSnapshot(pack.snapshotKey)
if (!bundle) return errorResponse(404, 'Pack not found')
const pricing = await getPricingConfig(docClient, process.env.PRICING_CONFIG_TABLE_NAME)
const required = estimateImportCreditCost(
buildPackImportEntries(bundle, choices),
pricing.dynamodb_storage_credits_per_kb
)
const { balance, isPlatformAdmin } = await getCreditsBalance(
docClient,
process.env.USERS_TABLE_NAME,
auth.userId
)
if (!isPlatformAdmin && balance < required) {
return errorResponse(402, 'INSUFFICIENT_CREDITS', { required, balance })
}
const job = await createJob({
type: 'import',
flowId: auth.flowId,
userId: auth.userId,
request: {
pack: {
packId: pack.id,
version: pack.currentVersion,
snapshotKey: pack.snapshotKey,
ownerFlowId: pack.flowId,
choices
}
},
total: IMPORT_JOB_PHASE_COUNT
})
await sqsClient.send(
new SendMessageCommand({
QueueUrl: process.env.IMPORT_JOBS_QUEUE_URL,
MessageBody: JSON.stringify({ jobId: job.id })
})
)
return jsonResponse(202, { jobId: job.id })
} catch (error) {
console.error('[store/import] Exception:', error.message, error.stack)
return errorResponse(500, 'Failed to install pack')
}
}
|