All files / utils equalityIndexValue.js

100% Statements 51/51
84.84% Branches 28/33
100% Functions 16/16
100% Lines 42/42

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 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 22023x 23x 23x         23x                         263x                                   96x 96x 60x   59x                           18x 18x   18x 18x   18x 18x 18x 18x 13x 13x     18x                 29x                               5x                                                                   10x 10x                               36x 37x   35x 37x 37x     35x 36x 13x 13x   35x                                               2x 2x               2x 3x 3x               3x     2x       23x                    
const { QueryCommand, PutCommand } = require('@aws-sdk/lib-dynamodb')
const { PLAIN_VALUE_LANG, buildReservationKey } = require('./uniqueFieldValue')
const { queryIdsForExactPk } = require('./fieldValueIndexHelpers')
 
// Scalar field types whose value is a single, naturally short/bounded
// string once stringified — never multilingual-map-shaped, unlike
// text/email/textarea (see utils/textSearchIndex.js for those).
const EQUALITY_INDEX_TYPES = ['number', 'date', 'boolean', 'select', 'entity_ref', 'user']
 
/**
 * True when a field needs a whole-value equality-index row (sk = itemId) in
 * the FieldValueIndexTable. Purely a function of type — every eligible field
 * is indexed automatically, no opt-in flag. Multi-value entity_ref/user
 * (reference.multiple: true) is array-shaped and excluded — one row per
 * array entry isn't supported.
 *
 * @param {{ type?: string, reference?: { multiple?: boolean } }} [field]
 * @returns {boolean}
 */
function needsEqualityIndex(field) {
  return (
    EQUALITY_INDEX_TYPES.includes(field?.type) &&
    !(['entity_ref', 'user'].includes(field?.type) && field?.reference?.multiple === true)
  )
}
 
/**
 * Canonicalizes a scalar-type field's value into the (language, value) pair
 * that needs an equality-index row. These types are never multilingual-map-
 * shaped, so there's always at most one entry, bucketed under the
 * PLAIN_VALUE_LANG sentinel. Array-shaped values return [] defensively
 * (needsEqualityIndex already excludes multi-value entity_ref/user).
 *
 * @param {{ fieldId: string }} field
 * @param {Record<string, unknown>} data
 * @returns {Array<{ lang: string, value: string }>}
 */
function getEqualityIndexValues(field, data) {
  const raw = data[field.fieldId]
  if (raw === undefined || raw === null || raw === '') return []
  if (Array.isArray(raw) || typeof raw === 'object') return []
 
  return [{ lang: PLAIN_VALUE_LANG, value: String(raw) }]
}
 
/**
 * Diffs an equality-indexed field's value between an item's old and new
 * state into the (language, value) pair whose row must be released and/or
 * claimed. Same shape as uniqueFieldValue.js's diffUniqueLanguageValues.
 *
 * @param {{ fieldId: string }} field
 * @param {Record<string, unknown>} oldData
 * @param {Record<string, unknown>} newData
 * @returns {{ toRelease: Array<{lang:string,value:string}>, toClaim: Array<{lang:string,value:string}> }}
 */
function diffEqualityIndexValues(field, oldData, newData) {
  const oldValues = new Map(getEqualityIndexValues(field, oldData).map((v) => [v.lang, v.value]))
  const newValues = new Map(getEqualityIndexValues(field, newData).map((v) => [v.lang, v.value]))
 
  const toRelease = []
  const toClaim = []
 
  for (const lang of new Set([...oldValues.keys(), ...newValues.keys()])) {
    const oldValue = oldValues.get(lang)
    const newValue = newValues.get(lang)
    if (oldValue === newValue) continue
    if (oldValue !== undefined) toRelease.push({ lang, value: oldValue })
    if (newValue !== undefined) toClaim.push({ lang, value: newValue })
  }
 
  return { toRelease, toClaim }
}
 
/**
 * A TransactWriteItems (or standalone) `Put` action indexing `itemId` under
 * one (field, language, value) — unconditioned, since many items may
 * legitimately share the same value.
 */
function buildEqualityIndexPut(tableName, entityId, fieldId, lang, value, itemId) {
  return {
    Put: {
      TableName: tableName,
      Item: {
        pk: buildReservationKey(entityId, fieldId, lang, value),
        sk: itemId,
        entityId,
        fieldId,
        itemId
      }
    }
  }
}
 
/** A TransactWriteItems (or standalone) `Delete` action removing one equality-index row. */
function buildEqualityIndexDelete(tableName, entityId, fieldId, lang, value, itemId) {
  return {
    Delete: {
      TableName: tableName,
      Key: { pk: buildReservationKey(entityId, fieldId, lang, value), sk: itemId }
    }
  }
}
 
/**
 * Returns the set of item ids holding an exact (field, language, value).
 * Queries by `pk` only (no FilterExpression) — a coexisting reservation row
 * (sk = 'unique') is itself a valid, correct singleton answer, so results
 * don't need to distinguish row shape. Paginated; stops early once
 * `maxResults` is reached (the caller is responsible for choosing a sensible
 * bound — see MAX_FILTER_INDEX_RESULTS in utils/constants.js).
 *
 * @param {import('@aws-sdk/lib-dynamodb').DynamoDBDocumentClient} docClient
 * @param {string} tableName
 * @param {string} entityId
 * @param {string} fieldId
 * @param {string} lang
 * @param {string} value
 * @param {{ maxResults?: number }} [options]
 * @returns {Promise<Set<string>>}
 */
async function queryItemIdsForEqualityValue(
  docClient,
  tableName,
  entityId,
  fieldId,
  lang,
  value,
  { maxResults = Infinity } = {}
) {
  const pk = buildReservationKey(entityId, fieldId, lang, value)
  return queryIdsForExactPk(docClient, tableName, pk, 'itemId', { maxResults })
}
 
/**
 * Diffs an entity's field definitions (old vs. new, e.g. on entities/update.js)
 * for equality-index-eligibility transitions. Since a field's `type` is
 * immutable once created, the only live post-creation transition is
 * `reference.multiple` flipping on an entity_ref/user field (multi-value
 * fields are excluded from equality indexing). A field being added or
 * removed entirely is handled separately (see entities/update.js).
 *
 * @param {Array<{fieldId: string, type?: string, reference?: {multiple?: boolean}}>} previousFields
 * @param {Array<{fieldId: string, type?: string, reference?: {multiple?: boolean}}>} nextFields
 * @returns {{ newlyEligibleFields: Array, noLongerEligibleFieldIds: string[] }}
 */
function diffEqualityIndexFieldChanges(previousFields, nextFields) {
  const previousByFieldId = new Map((previousFields || []).map((f) => [f.fieldId, f]))
  const nextByFieldId = new Map((nextFields || []).map((f) => [f.fieldId, f]))
 
  const newlyEligibleFields = (nextFields || []).filter((field) => {
    const previous = previousByFieldId.get(field.fieldId)
    return needsEqualityIndex(field) && !needsEqualityIndex(previous)
  })
 
  const noLongerEligibleFieldIds = (previousFields || [])
    .filter((field) => needsEqualityIndex(field))
    .map((field) => field.fieldId)
    .filter((fieldId) => !needsEqualityIndex(nextByFieldId.get(fieldId)))
 
  return { newlyEligibleFields, noLongerEligibleFieldIds }
}
 
/**
 * For a field newly eligible for equality indexing, scans every existing
 * item of the entity (paginated — a rare admin action on the schema, not a
 * hot path) and writes one equality-index row per (language, value) found.
 * No conflict detection needed (equality indexing isn't exclusive).
 *
 * @param {import('@aws-sdk/lib-dynamodb').DynamoDBDocumentClient} docClient
 * @param {string} itemsTableName
 * @param {string} fieldValueIndexTableName
 * @param {string} entityId
 * @param {{ fieldId: string }} field
 */
async function backfillEqualityIndexRows(
  docClient,
  itemsTableName,
  fieldValueIndexTableName,
  entityId,
  field
) {
  let ExclusiveStartKey
 
  do {
    const result = await docClient.send(
      new QueryCommand({
        TableName: itemsTableName,
        KeyConditionExpression: 'entityId = :eid',
        ExpressionAttributeValues: { ':eid': entityId },
        ExclusiveStartKey
      })
    )
    for (const item of result.Items || []) {
      for (const { lang, value } of getEqualityIndexValues(field, item)) {
        const { Put } = buildEqualityIndexPut(
          fieldValueIndexTableName,
          entityId,
          field.fieldId,
          lang,
          value,
          item.id
        )
        await docClient.send(new PutCommand(Put))
      }
    }
    ExclusiveStartKey = result.LastEvaluatedKey
  } while (ExclusiveStartKey)
}
 
module.exports = {
  needsEqualityIndex,
  getEqualityIndexValues,
  diffEqualityIndexValues,
  buildEqualityIndexPut,
  buildEqualityIndexDelete,
  queryItemIdsForEqualityValue,
  diffEqualityIndexFieldChanges,
  backfillEqualityIndexRows
}