All files / store upgrade.js

100% Statements 68/68
95.23% Branches 40/42
100% Functions 8/8
100% Lines 62/62

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                                              1x 1x 1x         1x 1x 1x 1x 1x 1x 1x 1x             1x   1x 1x     1x             8x 8x 8x   8x   3x   8x         1x 20x 20x 20x 19x 19x     18x 18x   1x     17x 16x   15x 1x     14x 14x 1x     13x 13x   12x 12x   12x 1x     11x 11x   10x   10x       10x   8x 8x         8x 7x         7x 1x       7x                     7x   5x     1x                   7x             7x   1x 1x      
/**
 * POST /v1/store/{packId}/upgrade
 *
 * Upgrades the active flow's copies of the pack to its current version
 * (UC-STORE-013.1), through the import worker: 202 and a job to
 * poll with GET /v1/entities/import/jobs/{jobId}. Body:
 * { version, copies: [{ entityId, fieldIds, fieldNames?, renames?, changedFieldIds?, sections? }],
 *   entities: [{ tempId, name? }] }
 * `changedFieldIds` and `sections` ('forms', 'emailTemplates') take the
 * version's definition of what only the pack changed since the copy took it.
 * `fieldNames` names an added field in some languages, `renames` a field of
 * the copy the version removed: `{ [fieldId]: { [language]: name } }`.
 * A field name the copy would then hold twice in a language is refused:
 * 409 PACK_FIELD_NAME_TAKEN { entityId, fieldId, language }.
 *
 * Each copy listed is moved to `version` with the fields chosen among those
 * the version adds, none possibly; the entities listed are installed, linked
 * to the copies. Only what the preview offers is kept: the worker computes it
 * again from the stored snapshot, never from the client.
 *
 * @implements UC-STORE-013.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 {
  loadPackCopies,
  planUpgrade,
  selectUpgrade,
  findUpgradeNameCollision,
  parseUpgradeChoices
} = require('../utils/packUpgrade')
 
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
 
/**
 * Fields added cost what they store, as in entities/update.js; a definition
 * changed, at most what it stores.
 */
function estimateUpgradeCreditCost(bundle, selection, creditsPerKb) {
  const fieldBytes = selection.copies.reduce((total, { fields, changes }) => {
    const written = [...fields, ...changes]
    return total + (written.length > 0 ? Buffer.byteLength(JSON.stringify(written)) : 0)
  }, 0)
  const entries = buildPackImportEntries(
    bundle,
    selection.entities.map((choice) => ({ ...choice, mode: 'create' }))
  )
  return (
    Math.ceil((fieldBytes / 1024) * creditsPerKb) + estimateImportCreditCost(entries, creditsPerKb)
  )
}
 
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')
 
    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 chosen = parseUpgradeChoices(payload)
    if (chosen.copies.length === 0 && chosen.entities.length === 0) {
      return errorResponse(400, 'Nothing to upgrade')
    }
 
    const bundle = await readSnapshot(pack.snapshotKey)
    if (!bundle) return errorResponse(404, 'Pack not found')
 
    const copies = await loadPackCopies(docClient, pack.id, auth.flowId)
    const selection = selectUpgrade(planUpgrade(bundle, copies, pack.currentVersion), chosen)
    // Upgraded meanwhile, or never offered: the panel shows the preview again
    if (selection.copies.length === 0 && selection.entities.length === 0) {
      return errorResponse(409, 'PACK_UPGRADE_UNAVAILABLE')
    }
 
    const collision = findUpgradeNameCollision(selection)
    if (collision) return errorResponse(409, 'PACK_FIELD_NAME_TAKEN', collision)
 
    const allowed = await Promise.all([
      ...selection.copies.map(({ copy }) =>
        hasPermission(auth, `entities-${copy.entityId}:update`)
      ),
      ...(selection.entities.length > 0 ? [hasPermission(auth, 'entities:create')] : [])
    ])
    if (allowed.includes(false)) return errorResponse(403, 'Permission denied')
 
    const pricing = await getPricingConfig(docClient, process.env.PRICING_CONFIG_TABLE_NAME)
    const required = estimateUpgradeCreditCost(
      bundle,
      selection,
      pricing.dynamodb_storage_credits_per_kb
    )
    if (required > 0) {
      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: {
        upgrade: {
          packId: pack.id,
          version: pack.currentVersion,
          snapshotKey: pack.snapshotKey,
          ownerFlowId: pack.flowId,
          copies: selection.copies.map(
            ({ copy, fields, fieldNames, renames, changes, sections }) => ({
              entityId: copy.entityId,
              fieldIds: fields.map((field) => field.fieldId),
              ...(Object.keys(fieldNames).length > 0 && { fieldNames }),
              ...(Object.keys(renames).length > 0 && { renames }),
              ...(changes.length > 0 && { changedFieldIds: changes.map((f) => f.fieldId) }),
              ...(sections.length > 0 && { sections })
            })
          ),
          entities: selection.entities
        }
      },
      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/upgrade] Exception:', error.message, error.stack)
    return errorResponse(500, 'Failed to upgrade the copies')
  }
}