All files / items createItem.js

97.67% Statements 42/43
88.88% Branches 16/18
100% Functions 3/3
97.43% Lines 38/39

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                8x         8x         8x         8x 8x 8x                                     69x 69x   69x 92x 7x 7x     7x       69x 55x 86x 38x 15x                           69x       69x                       66x   53x 53x 83x 38x 52x         53x                                                               54x     54x                   54x                 54x                     54x         52x 1x     51x             51x   51x     8x  
/**
 * Shared write path for creating one item, used by items/create.js's HTTP
 * handler and, for the parts that fit, entities/fork.js and
 * entities/import-worker.js — see docs/architecture/USAGE_METERING.md "Gap
 * found and closed: bulk import and entity fork bypassed credits entirely"
 * for what duplicating this by hand already cost once.
 */
 
const { randomUUID } = require('crypto')
const {
  getUniqueLanguageValues,
  buildReservationPut,
  sendTransactWriteWithUniqueCheck
} = require('../utils/uniqueFieldValue')
const {
  needsEqualityIndex,
  getEqualityIndexValues,
  buildEqualityIndexPut
} = require('../utils/equalityIndexValue')
const {
  needsTextSearchIndex,
  getTextSearchTokens,
  buildTextSearchPutRequest
} = require('../utils/textSearchIndex')
const { buildItemCountUpdate } = require('../utils/entityItemCount')
const { getReferencedEntityIds } = require('../utils/referenceCounters')
 
/**
 * Builds the reservation/equality-index/item-count TransactWriteItems actions
 * for one item's data — everything besides the item's own primary write.
 * Order matters: callers that prepend a primary write action (items/create.js
 * via createItem below) rely on reservations coming first, matching the
 * `offset: 1` default of sendTransactWriteWithUniqueCheck; callers with no
 * primary action of their own (import-worker.js's reservations-only claim)
 * use `offset: 0` instead.
 */
function buildItemIndexTransactItems({
  fieldValueIndexTableName,
  entityItemCountTableName,
  entityId,
  fields,
  data,
  itemId
}) {
  const reservationFieldIds = []
  const transactItems = []
 
  for (const field of fields) {
    if (!field.unique) continue
    for (const { lang, value } of getUniqueLanguageValues(field, data)) {
      transactItems.push(
        buildReservationPut(fieldValueIndexTableName, entityId, field.fieldId, lang, value, itemId)
      )
      reservationFieldIds.push(field.fieldId)
    }
  }
 
  if (fieldValueIndexTableName) {
    for (const field of fields) {
      if (!needsEqualityIndex(field)) continue
      for (const { lang, value } of getEqualityIndexValues(field, data)) {
        transactItems.push(
          buildEqualityIndexPut(
            fieldValueIndexTableName,
            entityId,
            field.fieldId,
            lang,
            value,
            itemId
          )
        )
      }
    }
  }
 
  Iif (entityItemCountTableName) {
    transactItems.push(buildItemCountUpdate(entityItemCountTableName, entityId, 1))
  }
 
  return { transactItems, reservationFieldIds }
}
 
/**
 * Builds (but does not write) the trigram text-search index Put requests for
 * one item's data. Non-transactional by nature (see items/create.js's
 * original comment: a large textarea can produce far more actions than
 * TransactWriteItems' 100-action limit allows) — callers flush these via
 * utils/batchWrite.js on whatever cadence fits them (immediately, or batched
 * across many items).
 */
function buildItemTextSearchRequests({ fieldValueIndexTableName, entityId, fields, data, itemId }) {
  if (!fieldValueIndexTableName) return []
 
  const textSearchRequests = []
  for (const field of fields) {
    if (!needsTextSearchIndex(field)) continue
    for (const { lang, kind, token } of getTextSearchTokens(field, data)) {
      textSearchRequests.push(
        buildTextSearchPutRequest(entityId, field.fieldId, lang, kind, token, itemId)
      )
    }
  }
  return textSearchRequests
}
 
/**
 * Atomically creates one item: its own row plus every reservation/equality-
 * index/item-count action from buildItemIndexTransactItems, all inside one
 * TransactWriteCommand so a uniqueness conflict can never leave a partial
 * write behind. Returns the trigram text-search requests and the set of
 * newly-referenced entity ids for the caller to apply — both differ enough
 * per caller (immediate vs. batched-across-many-items, guarded vs. unguarded)
 * that this stays a pure write rather than an orchestrator.
 *
 * @returns {Promise<{
 *   conflictFieldId: string | null,
 *   item: Record<string, unknown> | null,
 *   textSearchRequests: unknown[],
 *   referencedEntityIds: Set<string>
 * }>}
 */
async function createItem({
  docClient,
  itemsTableName,
  fieldValueIndexTableName,
  entityItemCountTableName,
  entityId,
  flowId,
  fields,
  data,
  itemId,
  createdBy,
  createdAt
}) {
  const timestamp = createdAt || new Date().toISOString()
  // The envelope comes last: whatever `data` holds, it can't move the item
  // to another entity/flow or rewrite who created it and when.
  const item = {
    ...data,
    entityId,
    id: itemId || randomUUID(),
    flowId,
    createdBy,
    createdAt: timestamp,
    updatedAt: timestamp
  }
 
  const { transactItems: indexTransactItems, reservationFieldIds } = buildItemIndexTransactItems({
    fieldValueIndexTableName,
    entityItemCountTableName,
    entityId,
    fields,
    data,
    itemId: item.id
  })
 
  const transactItems = [
    {
      Put: {
        TableName: itemsTableName,
        Item: item,
        ConditionExpression: 'attribute_not_exists(id)'
      }
    },
    ...indexTransactItems
  ]
 
  const { conflictFieldId } = await sendTransactWriteWithUniqueCheck(
    docClient,
    transactItems,
    reservationFieldIds
  )
  if (conflictFieldId) {
    return { conflictFieldId, item: null, textSearchRequests: [], referencedEntityIds: new Set() }
  }
 
  const textSearchRequests = buildItemTextSearchRequests({
    fieldValueIndexTableName,
    entityId,
    fields,
    data,
    itemId: item.id
  })
  const referencedEntityIds = getReferencedEntityIds(fields, item)
 
  return { conflictFieldId: null, item, textSearchRequests, referencedEntityIds }
}
 
module.exports = { createItem, buildItemIndexTransactItems, buildItemTextSearchRequests }