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 | 12x 12x 12x 12x 12x 319x 303x 7x 70x 70x 70x 70x 370x 370x 368x 368x 70x 7x 64x 7x 7x 6x 6x 6x 6x 6x 5x 5x 5x 5x 54x 54x 5007x 54x 5x 3x 5x 12x | const { BatchGetCommand } = require('@aws-sdk/lib-dynamodb')
const {
TRIGRAM_LENGTH,
normalizeForSearch,
getTextSearchTokens,
matchesContains
} = require('./textSearchIndex')
const { queryIdsForExactPk, diffByKey } = require('./fieldValueIndexHelpers')
// Synthetic field/data wrapper so textSearchIndex.js's tokenization engine
// (normalizeForSearch, tokenizeWords, tokensForWord, getTextSearchTokens,
// matchesContains) can be reused unchanged for an entity's own `name`
// property, which is shaped exactly like any other text field's value
// (a plain string, or a multilingual { en, fr, ... } map).
const CATALOG_NAME_FIELD = { fieldId: 'name' }
// Plain top-level attribute written onto every catalog-search row purely so
// the FieldValueIndexTable's existing `entityIndex` GSI (pk=entityId,
// sk=fieldId) picks them up — meaning entities/delete.js's existing
// deleteAllReservationsForEntity sweep already cleans these rows up on
// entity deletion, with no new code needed there. Never a real fieldId, so
// it's namespaced to make that obvious if ever seen in the raw table.
const CATALOG_FIELD_ID_SENTINEL = 'catalog:name'
/**
* Builds the FieldValueIndexTable partition key for one catalog-search
* token. Deliberately GLOBAL — unlike textSearchIndex.js's
* buildTextSearchKey, which starts with a specific entityId because
* item-field search is always scoped "within one entity, find its items",
* catalog search is the opposite: "across every entity platform-wide, find
* ones whose name matches" — so the key must be the same for a given token
* regardless of which entity contributed it. The entity's own id lives in
* `sk` instead (see buildCatalogSearchPutRequest). Also deliberately has no
* `lang` segment — a name's trigrams are merged across every language it
* has, so a query typed in French still finds a match that only exists in
* an English name. The literal `CATALOG#` prefix can never collide with
* the other three FieldValueIndexTable key conventions (reservation,
* equality-index, per-entity text-search), since their `pk` always starts
* with a real entityId (a UUID), never this literal string.
*
* @param {string} kind 'trgm' or 'stok'
* @param {string} token
* @returns {string}
*/
function buildCatalogSearchKey(kind, token) {
return `CATALOG#name#txt#${kind}:${token}`
}
/** A BatchWriteItem `PutRequest` indexing `entityId` under one catalog-search token. */
function buildCatalogSearchPutRequest(kind, token, entityId) {
return {
PutRequest: {
Item: {
pk: buildCatalogSearchKey(kind, token),
sk: entityId,
entityId,
fieldId: CATALOG_FIELD_ID_SENTINEL
}
}
}
}
/** A BatchWriteItem `DeleteRequest` removing one catalog-search index row. */
function buildCatalogSearchDeleteRequest(kind, token, entityId) {
return {
DeleteRequest: {
Key: { pk: buildCatalogSearchKey(kind, token), sk: entityId }
}
}
}
/**
* Tokenizes an entity's `name` for catalog search, reusing
* textSearchIndex.js's getTextSearchTokens (the normalize/tokenize/
* trigram-window engine, unchanged) for the per-language token lists, then
* collapsing across languages down to flat `{kind, token}` pairs —
* deliberately losing the `lang` dimension, since the catalog pk doesn't
* carry it (see buildCatalogSearchKey). Two languages sharing a trigram
* must collapse to the SAME physical row, not two — otherwise diffing by
* language independently could release a row one language still needs
* while only the other language's value actually changed.
*
* @param {string | Record<string, string> | undefined | null} entityName
* @returns {Array<{ kind: string, token: string }>}
*/
function getCatalogSearchTokens(entityName) {
const triples = getTextSearchTokens(CATALOG_NAME_FIELD, { name: entityName })
const seen = new Set()
const tokens = []
for (const { kind, token } of triples) {
const key = `${kind}:${token}`
if (seen.has(key)) continue
seen.add(key)
tokens.push({ kind, token })
}
return tokens
}
/**
* Diffs an entity's `name` between its old and new state into the
* `{kind, token}` pairs whose catalog-search row must be released and/or
* claimed. Deliberately NOT a call to textSearchIndex.js's
* diffTextSearchTokens — that diffs lang-aware triples, which would be
* wrong here (see getCatalogSearchTokens's doc comment) — so this diffs the
* already-language-collapsed token lists instead, via the same generic
* diffByKey mechanics.
*
* @param {string | Record<string, string> | undefined | null} oldName
* @param {string | Record<string, string> | undefined | null} newName
* @returns {{ toRelease: Array<{kind:string,token:string}>, toClaim: Array<{kind:string,token:string}> }}
*/
function diffCatalogSearchTokens(oldName, newName) {
return diffByKey(
getCatalogSearchTokens(oldName),
getCatalogSearchTokens(newName),
(t) => `${t.kind}:${t.token}`
)
}
/**
* Returns the set of entity ids indexed under one exact catalog-search
* token (paginated, bounded by `maxResults`) — the coarse candidate-
* generation step, see resolveCatalogSearchCandidates for the full
* pipeline.
*
* @param {import('@aws-sdk/lib-dynamodb').DynamoDBDocumentClient} docClient
* @param {string} tableName
* @param {string} kind
* @param {string} token
* @param {{ maxResults?: number }} [options]
* @returns {Promise<Set<string>>}
*/
async function queryEntityIdsForCatalogSearchToken(
docClient,
tableName,
kind,
token,
{ maxResults = Infinity } = {}
) {
const pk = buildCatalogSearchKey(kind, token)
return queryIdsForExactPk(docClient, tableName, pk, 'entityId', { maxResults })
}
/**
* Resolves a catalog search term to a verified set of matching entity ids.
* Mirrors textSearchIndex.js's resolveContainsCandidates: queries only the
* seed trigram (the search value's first 3 normalized characters — see that
* function's doc comment for why a single seed trigram is provably
* sufficient, no false negatives), then verifies every candidate against
* the entity's *actual* stored name before returning it (candidate
* generation is a superset, not proof).
*
* Callers must only invoke this for search values whose normalized length
* is >= TRIGRAM_LENGTH — shorter terms have no seed trigram to query and
* should fall back to a different path (see catalog/list.js).
*
* @param {import('@aws-sdk/lib-dynamodb').DynamoDBDocumentClient} docClient
* @param {{ fieldValueIndexTableName: string, entitiesTableName: string,
* searchValue: string, maxResults?: number }} params
* @returns {Promise<{ entityIds: Set<string>, truncated: boolean }>}
*/
async function resolveCatalogSearchCandidates(
docClient,
{ fieldValueIndexTableName, entitiesTableName, searchValue, maxResults = Infinity }
) {
const normalized = normalizeForSearch(String(searchValue))
const seedTrigram = normalized.slice(0, TRIGRAM_LENGTH)
const coarseIds = await queryEntityIdsForCatalogSearchToken(
docClient,
fieldValueIndexTableName,
'trgm',
seedTrigram,
{
maxResults
}
)
const truncated = coarseIds.size >= maxResults
if (coarseIds.size === 0) return { entityIds: new Set(), truncated }
const candidateIds = [...coarseIds]
const verifiedIds = new Set()
const BATCH_GET_SIZE = 100
for (let i = 0; i < candidateIds.length; i += BATCH_GET_SIZE) {
const batchIds = candidateIds.slice(i, i + BATCH_GET_SIZE)
const result = await docClient.send(
new BatchGetCommand({
RequestItems: {
[entitiesTableName]: { Keys: batchIds.map((id) => ({ id })) }
}
})
)
for (const entity of result.Responses?.[entitiesTableName] || []) {
if (matchesContains(entity, CATALOG_NAME_FIELD, [], [searchValue])) {
verifiedIds.add(entity.id)
}
}
}
return { entityIds: verifiedIds, truncated }
}
module.exports = {
CATALOG_NAME_FIELD,
CATALOG_FIELD_ID_SENTINEL,
buildCatalogSearchKey,
buildCatalogSearchPutRequest,
buildCatalogSearchDeleteRequest,
getCatalogSearchTokens,
diffCatalogSearchTokens,
queryEntityIdsForCatalogSearchToken,
resolveCatalogSearchCandidates
}
|