All files / utils directorySearchIndex.js

100% Statements 114/114
96.55% Branches 56/58
100% Functions 28/28
100% Lines 98/98

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 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346                                                                                      17x 17x 17x 17x 17x 17x   17x               17x   17x     17x       17x     615x       655x                       228x 370x   228x 228x 228x 773x 773x 714x 714x   228x         74x 26x       52x     17x 60x 56x 66x           575x                           52x                   85x 85x 113x     709x   113x 52x   113x 575x     85x     17x 17x               75x 46x 46x   23x         26x 26x       31x 31x               37x                 21x 21x 21x 1x         20x       18x         68x 40x 40x   23x                                       20x 20x   19x 19x   18x 18x 27x                                               20x     20x 20x   19x 19x 19x     20x 20x 28x             28x 712x 28x   6033x       19x 19x 19x 19x   19x 25x 25x 25x 1025x 1025x 1025x 1025x       19x         539x 558x       17x                                  
/**
 * Trigram search index for the platform-wide "directories" — users, flows and
 * store packs.
 *
 * Replaces the full-table Scan + in-memory filter these searches used to run
 * (invite-a-member search, admin Credits lookup, admin Users/Flows lists): a
 * search now costs a Query on one index partition plus BatchGets for one page of
 * candidates, never a read of the whole table. Same engine and same table
 * (FieldValueIndexTable) as the catalog search — see catalogSearchIndex.js — with
 * a key shape of its own:
 *
 *   pk = DIR#<namespace>#txt#<kind>:<token>     sk = <subjectId>
 *
 * Namespaces separate WHO may match on what, since the same user row is searched
 * by different audiences:
 *   - `user`        name + nickname   any member allowed to list users (invites)
 *   - `user-admin`  email             platform admins only (never exposed to members)
 *   - `flow`        name + slug       platform admins only
 *   - `pack`        name + description   any signed-in user (the Store), every language
 *   - `pack-e2e`    the same, for packs of e2e test users, searched by e2e users only
 *
 * Every row also carries `entityId` = `<OWNER>#<id>` and a `fieldId` sentinel so the
 * table's existing `entityIndex` GSI can sweep all of a subject's rows on deletion
 * (deleteAllReservationsForEntity) without knowing which tokens it once had.
 *
 * Search semantics: case- and accent-insensitive substring match, verified against
 * the real row (candidate generation is a superset). A query needs at least one
 * word of 3+ characters to be matched as a substring; a query whose words are all
 * shorter only matches whole words (e.g. "jo" finds "Jo", not "John").
 *
 * Scale: the candidate set for one seed trigram is capped, so an extremely common
 * trigram can hide some matches — reported as `truncated: true`. Verification is
 * lazy and paginated so a request's cost tracks the page size, not the candidate
 * count.
 *
 * @implements UC-ADMIN-006.1, UC-STORE-010.1
 */
 
const {
  TRIGRAM_LENGTH,
  normalizeForSearch,
  getTextSearchTokens,
  tokenizeWords
} = require('./textSearchIndex')
const { queryIdsForExactPk, diffByKey } = require('./fieldValueIndexHelpers')
const { batchWrite } = require('./batchWrite')
const { deleteAllReservationsForEntity } = require('./uniqueFieldValue')
const { batchGetByIds } = require('./platformAdminList')
const { MAX_DIRECTORY_SEARCH_INDEX_RESULTS } = require('./constants')
 
const NAMESPACES = {
  USER: 'user',
  USER_ADMIN: 'user-admin',
  FLOW: 'flow',
  PACK: 'pack',
  PACK_E2E: 'pack-e2e'
}
 
const OWNER_PREFIX = { USER: 'USER', FLOW: 'FLOW', PACK: 'PACK' }
 
const BATCH_GET_SIZE = 100
// Candidates examined per request when many of them fail verification, so a
// query that matches little cannot turn into an unbounded loop.
const MAX_VERIFIED_PER_REQUEST = 500
 
// Field descriptor for textSearchIndex's tokenizer, which reads `data[fieldId]` as
// either a string or a { lang: string } map — here a map of "source -> value".
const SEARCH_FIELD = { fieldId: 'values' }
 
function ownerEntityId(ownerPrefix, id) {
  return `${OWNER_PREFIX[ownerPrefix]}#${id}`
}
 
function buildDirectoryKey(namespace, kind, token) {
  return `DIR#${namespace}#txt#${kind}:${token}`
}
 
/**
 * Flat, de-duplicated `{kind, token}` list for a set of text values. Tokens from
 * every value collapse into one set, so a token shared by two values (e.g. a
 * user's name and nickname) is a single row, released only when no value keeps it.
 *
 * @param {Array<string | null | undefined>} values
 * @returns {Array<{ kind: string, token: string }>}
 */
function getDirectoryTokens(values) {
  const valueMap = Object.fromEntries(
    values.filter((value) => typeof value === 'string' && value !== '').map((v, i) => [`v${i}`, v])
  )
  const seen = new Set()
  const tokens = []
  for (const { kind, token } of getTextSearchTokens(SEARCH_FIELD, { values: valueMap })) {
    const key = `${kind}:${token}`
    if (seen.has(key)) continue
    seen.add(key)
    tokens.push({ kind, token })
  }
  return tokens
}
 
/** The texts of a plain string or of a { lang: text } map, every language included. */
function textsOf(value) {
  if (typeof value === 'string') return [value]
  return value && typeof value === 'object' ? Object.values(value) : []
}
 
/** A pack's searchable texts: its name and description, in every language. */
const packTexts = (pack) => (pack ? [...textsOf(pack.name), ...textsOf(pack.description)] : [])
 
/** Indexed values per namespace: which fields of a subject feed which namespace. */
const SOURCES = {
  [NAMESPACES.USER]: (user) => [user?.name, user?.nickname],
  [NAMESPACES.USER_ADMIN]: (user) => [user?.email],
  [NAMESPACES.FLOW]: (flow) => [flow?.name, flow?.slug],
  [NAMESPACES.PACK]: packTexts,
  [NAMESPACES.PACK_E2E]: packTexts
}
 
function buildPutRequest(namespace, ownerPrefix, kind, token, subjectId) {
  return {
    PutRequest: {
      Item: {
        pk: buildDirectoryKey(namespace, kind, token),
        sk: subjectId,
        subjectId,
        entityId: ownerEntityId(ownerPrefix, subjectId),
        fieldId: `directory:${namespace}`
      }
    }
  }
}
 
function buildDeleteRequest(namespace, kind, token, subjectId) {
  return {
    DeleteRequest: { Key: { pk: buildDirectoryKey(namespace, kind, token), sk: subjectId } }
  }
}
 
/**
 * Write/delete requests bringing a subject's index rows from `oldSubject` to
 * `newSubject` (either may be null: create → old is null, delete → new is null).
 */
function buildSyncRequests(namespaces, ownerPrefix, subjectId, oldSubject, newSubject) {
  const requests = []
  for (const namespace of namespaces) {
    const { toRelease, toClaim } = diffByKey(
      getDirectoryTokens(SOURCES[namespace](oldSubject)),
      getDirectoryTokens(SOURCES[namespace](newSubject)),
      (t) => `${t.kind}:${t.token}`
    )
    for (const { kind, token } of toRelease) {
      requests.push(buildDeleteRequest(namespace, kind, token, subjectId))
    }
    for (const { kind, token } of toClaim) {
      requests.push(buildPutRequest(namespace, ownerPrefix, kind, token, subjectId))
    }
  }
  return requests
}
 
const USER_NAMESPACES = [NAMESPACES.USER, NAMESPACES.USER_ADMIN]
const FLOW_NAMESPACES = [NAMESPACES.FLOW]
 
/**
 * Best-effort index maintenance: a failure is logged, never thrown, so a search-index
 * hiccup can't fail the user-facing write. A missing row only makes the subject
 * unfindable by search until `scripts/backfill-directory-search-index.js` repairs it.
 */
async function syncIndex(docClient, tableName, requests, label) {
  if (!tableName || requests.length === 0) return
  try {
    await batchWrite(docClient, tableName, requests)
  } catch (error) {
    console.error(`Failed to update ${label} search index rows:`, error)
  }
}
 
async function syncUserSearchIndex(docClient, tableName, userId, oldUser, newUser) {
  const requests = buildSyncRequests(USER_NAMESPACES, 'USER', userId, oldUser, newUser)
  await syncIndex(docClient, tableName, requests, 'user')
}
 
async function syncFlowSearchIndex(docClient, tableName, flowId, oldFlow, newFlow) {
  const requests = buildSyncRequests(FLOW_NAMESPACES, 'FLOW', flowId, oldFlow, newFlow)
  await syncIndex(docClient, tableName, requests, 'flow')
}
 
/**
 * The namespace a pack is searched in: its Store partition's, so that e2e test
 * users and real users never find each other's packs (see utils/packs.js).
 */
function packNamespace(storeKey) {
  return storeKey === 'E2E' ? NAMESPACES.PACK_E2E : NAMESPACES.PACK
}
 
/**
 * The write/delete requests moving a pack's rows from `oldPack` to `newPack`
 * (either may be null). A new version can move the pack to the other Store
 * partition (the owner taking over an e2e user's pack), hence another namespace.
 */
function buildPackSyncRequests(packId, oldPack, newPack) {
  const oldNamespace = oldPack ? packNamespace(oldPack.storeKey) : null
  const newNamespace = newPack ? packNamespace(newPack.storeKey) : null
  if (oldNamespace && newNamespace && oldNamespace !== newNamespace) {
    return [
      ...buildSyncRequests([oldNamespace], 'PACK', packId, oldPack, null),
      ...buildSyncRequests([newNamespace], 'PACK', packId, null, newPack)
    ]
  }
  return buildSyncRequests([oldNamespace || newNamespace], 'PACK', packId, oldPack, newPack)
}
 
async function syncPackSearchIndex(docClient, tableName, packId, oldPack, newPack) {
  await syncIndex(docClient, tableName, buildPackSyncRequests(packId, oldPack, newPack), 'pack')
}
 
/** Removes every index row of one subject, whatever tokens it once had. */
async function deleteSearchIndexRows(docClient, tableName, ownerPrefix, id) {
  if (!tableName) return
  try {
    await deleteAllReservationsForEntity(docClient, tableName, ownerEntityId(ownerPrefix, id))
  } catch (error) {
    console.error(`Failed to delete ${ownerPrefix} search index rows:`, error)
  }
}
 
/**
 * Picks the tokens to seed candidate generation from. Tokenization only splits on
 * non-alphanumeric runs, so a query word that occurs in a stored value lies entirely
 * inside one of its words — hence every 3-character window of a query word of 3+
 * characters is an indexed trigram of that value (no false negatives). The first and
 * last windows of the LONGEST query word are used: a longer word is likelier to be
 * distinctive, and requiring two trigrams to co-occur shrinks the candidate set far
 * below what any single common trigram ("joh", "e2e") would give. Punctuation the
 * tokenizer drops (a leading "@" typed before a nickname) is never part of a word, so
 * it can't poison a seed. A query with no word of 3+ characters falls back to its
 * longest word as a whole-word token.
 *
 * @param {string} normalizedQuery
 * @returns {Array<{ kind: 'trgm' | 'stok', token: string }>} empty when the query has no words
 */
function pickSeeds(normalizedQuery) {
  const words = tokenizeWords(normalizedQuery)
  if (words.length === 0) return []
 
  const longest = words.reduce((best, word) => (word.length > best.length ? word : best))
  if (longest.length < TRIGRAM_LENGTH) return [{ kind: 'stok', token: longest }]
 
  const first = longest.slice(0, TRIGRAM_LENGTH)
  const last = longest.slice(-TRIGRAM_LENGTH)
  return [...new Set([first, last])].map((token) => ({ kind: 'trgm', token }))
}
 
/**
 * One page of subjects whose indexed text contains `searchValue`.
 *
 * @param {import('@aws-sdk/lib-dynamodb').DynamoDBDocumentClient} docClient
 * @param {object} params
 * @param {string} params.indexTableName FieldValueIndexTable
 * @param {string} params.subjectsTableName table holding the full rows (partition key `id`)
 * @param {string[]} params.namespaces which namespaces this caller may search
 * @param {string} params.searchValue raw user input
 * @param {(subject: object, normalizedQuery: string) => boolean} params.verify
 *   final check against the stored row (candidates are a superset)
 * @param {number} params.limit
 * @param {number} [params.offset] position in the candidate list to resume from
 * @returns {Promise<{ items: object[], nextOffset: number | null, truncated: boolean }>}
 */
async function searchDirectory(
  docClient,
  { indexTableName, subjectsTableName, namespaces, searchValue, verify, limit, offset = 0 }
) {
  // Leading punctuation (a "@" typed before a nickname) is not part of any indexed
  // word, so it is dropped before both seeding and verification.
  const normalizedQuery = normalizeForSearch(String(searchValue))
    .trim()
    .replace(/^[^\p{L}\p{N}]+/u, '')
  const seeds = pickSeeds(normalizedQuery)
  if (seeds.length === 0) return { items: [], nextOffset: null, truncated: false }
 
  const candidateSet = new Set()
  let truncated = false
  for (const namespace of namespaces) {
    // Within one namespace a subject must carry EVERY seed (they come from the same
    // query word, hence the same stored value); across namespaces the results union.
    let namespaceIds = null
    for (const { kind, token } of seeds) {
      const ids = await queryIdsForExactPk(
        docClient,
        indexTableName,
        buildDirectoryKey(namespace, kind, token),
        'subjectId',
        { maxResults: MAX_DIRECTORY_SEARCH_INDEX_RESULTS }
      )
      truncated = truncated || ids.size >= MAX_DIRECTORY_SEARCH_INDEX_RESULTS
      namespaceIds = namespaceIds ? new Set([...namespaceIds].filter((id) => ids.has(id))) : ids
      if (namespaceIds.size === 0) break
    }
    for (const id of namespaceIds) candidateSet.add(id)
  }
 
  // Sorted so an offset means the same position on every request of one search.
  const candidates = [...candidateSet].sort()
  const items = []
  let position = offset
  const stopAt = Math.min(candidates.length, offset + MAX_VERIFIED_PER_REQUEST)
 
  while (position < stopAt && items.length < limit) {
    const chunk = candidates.slice(position, Math.min(position + BATCH_GET_SIZE, stopAt))
    const subjects = await batchGetByIds(subjectsTableName, chunk)
    for (const id of chunk) {
      position++
      const subject = subjects.get(id)
      if (subject && verify(subject, normalizedQuery)) items.push(subject)
      if (items.length === limit) break
    }
  }
 
  return { items, nextOffset: position < candidates.length ? position : null, truncated }
}
 
/** True when the normalized query is a substring of any of the normalized values. */
function containsQuery(normalizedQuery, values) {
  return values.some(
    (value) => typeof value === 'string' && normalizeForSearch(value).includes(normalizedQuery)
  )
}
 
module.exports = {
  NAMESPACES,
  getDirectoryTokens,
  buildSyncRequests,
  syncUserSearchIndex,
  syncFlowSearchIndex,
  packNamespace,
  packTexts,
  buildPackSyncRequests,
  syncPackSearchIndex,
  deleteSearchIndexRows,
  searchDirectory,
  containsQuery,
  SOURCES,
  USER_NAMESPACES,
  FLOW_NAMESPACES
}