All files / entities import.js

86.36% Statements 38/44
76.19% Branches 16/21
100% Functions 3/3
92.68% Lines 38/41

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 1121x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x             1x     8x                     8x 8x 8x   8x 8x   1x                       8x 8x 8x 1x     7x 7x   7x       7x 7x 1x           6x 6x       6x     6x 3x             3x               3x             3x             1x  
const { getActiveFlowId } = require('../shared/activeFlow')
const { SQSClient, SendMessageCommand } = require('@aws-sdk/client-sqs')
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb')
const { DynamoDBDocumentClient } = require('@aws-sdk/lib-dynamodb')
const { requirePermission } = require('../utils/requirePermission')
const { createJob } = require('../utils/jobsTable')
const { getCreditsBalance } = require('../utils/creditsLedger')
const { getPricingConfig } = require('../utils/pricingConfig')
const { estimateImportCreditCost } = require('../utils/importCreditEstimate')
 
const sqsClient = new SQSClient({})
const docClient = DynamoDBDocumentClient.from(new DynamoDBClient({}))
 
// Number of commit phases import-worker.js runs (resolvePhase0..3) — used as
// the job's progress `total` since the phases process every entry together
// (an entry's entity_ref values can point at another entry in the same
// bundle by tempId, so all entries must finish one phase before any can move
// to the next), which rules out reporting true per-entry progress.
const IMPORT_JOB_PHASE_COUNT = 4
 
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
  }
}
 
/**
 * Submit handler — validates the request shape, then hands the actual
 * resolve/commit work to import-worker.js via SQS. Runs async because a
 * multi-entity bundle (field/reference remapping across every entity +
 * per-item user/entity_ref resolution) can far exceed API Gateway's 29s
 * hard integration timeout.
 */
async function importEntitiesHandler(event) {
  try {
    const body = safeParseBody(event.body)
    if (body === null) {
      return jsonResponse(400, { error: 'Invalid JSON body' })
    }
 
    const flowId = await getActiveFlowId(event)
    const userId = event.requestContext?.authorizer?.claims?.sub
 
    Iif (!flowId) {
      return jsonResponse(401, { error: 'Missing flow context' })
    }
 
    const entries = Array.isArray(body.entities) ? body.entities : []
    if (entries.length === 0) {
      return jsonResponse(400, { error: 'Missing entities' })
    }
 
    // Preflight, on the full request's estimated size — the exact debit
    // happens later, in import-worker.js, once the real write cost is known
    // (see docs/architecture/USAGE_METERING.md "DynamoDB storage credits").
    const pricing = await getPricingConfig(docClient, process.env.PRICING_CONFIG_TABLE_NAME)
    const storageCreditEstimate = estimateImportCreditCost(
      entries,
      pricing.dynamodb_storage_credits_per_kb
    )
    const { balance: creditsBalance, isPlatformAdmin } = userId
      ? await getCreditsBalance(docClient, process.env.USERS_TABLE_NAME, userId)
      : { balance: 0, isPlatformAdmin: false }
    if (!userId || (!isPlatformAdmin && creditsBalance < storageCreditEstimate)) {
      return jsonResponse(402, {
        error: 'INSUFFICIENT_CREDITS',
        required: storageCreditEstimate,
        balance: creditsBalance
      })
    }
 
    const job = await createJob({
      type: 'import',
      flowId,
      userId,
      request: { entries },
      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('[import] Exception:', error.message, error.stack)
    return jsonResponse(500, { error: 'Failed to import entities' })
  }
}
 
exports.handler = requirePermission(importEntitiesHandler, { permission: 'entities:create' })