All files / store upgrade-preview.js

100% Statements 34/34
91.66% Branches 11/12
100% Functions 3/3
100% Lines 29/29

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                              1x 1x         1x 1x 1x 1x 1x 1x   1x   1x 8x 8x 8x 7x 7x   6x 6x   5x               5x 4x 1x     3x 3x   2x 2x   2x                       2x         1x 1x      
/**
 * GET /v1/store/{packId}/upgrade
 *
 * What upgrading the active flow's copies of the pack to its current version
 * would add (UC-STORE-013.1): for each copy installed from an earlier version,
 * the fields the version adds and what else differs, then the version's
 * entities the flow has no copy of. An added field whose name the copy
 * already has carries `nameConflicts`, a new entity whose name the flow has
 * `nameTaken`. Empty `copies` when nothing is behind, in
 * which case the snapshot is not read. One Get on the flow's install row, and
 * reads bounded by the copies it remembers.
 *
 * @implements UC-STORE-013.1
 */
 
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 { getPack } = require('../utils/packs')
const { readSnapshot } = require('../utils/packSnapshot')
const { loadPackCopies, planUpgrade, toUpgradePreview } = require('../utils/packUpgrade')
const { listEntityNames } = require('../utils/nameUniqueness')
 
const docClient = DynamoDBDocumentClient.from(new DynamoDBClient({}))
 
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')
 
    const pack = await getPack(docClient, event.pathParameters?.packId, { consistent: true })
    if (!pack?.currentVersion) return errorResponse(404, 'Pack not found')
 
    const nothing = {
      fromVersion: null,
      toVersion: pack.currentVersion,
      copies: [],
      newEntities: [],
      canCreate: false
    }
 
    const copies = await loadPackCopies(docClient, pack.id, auth.flowId)
    if (!copies.some((copy) => copy.packOrigin.version < pack.currentVersion)) {
      return jsonResponse(200, nothing)
    }
 
    const bundle = await readSnapshot(pack.snapshotKey)
    if (!bundle) return jsonResponse(200, nothing)
 
    const plan = planUpgrade(bundle, copies, pack.currentVersion)
    const [updates, canCreate, takenEntityNames] = await Promise.all([
      Promise.all(
        plan.copies.map(async (copy) => [
          copy.entityId,
          await hasPermission(auth, `entities-${copy.entityId}:update`)
        ])
      ),
      hasPermission(auth, 'entities:create'),
      // A new entity whose name the flow has needs another one
      plan.newEntities.length > 0
        ? listEntityNames(docClient, { tableName: process.env.TABLE_NAME, flowId: auth.flowId })
        : new Set()
    ])
 
    return jsonResponse(
      200,
      toUpgradePreview(plan, { canUpdate: new Map(updates), canCreate, takenEntityNames })
    )
  } catch (error) {
    console.error('[store/upgrade-preview] Exception:', error.message, error.stack)
    return errorResponse(500, 'Failed to preview the upgrade')
  }
}