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 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 7x 12x 12x 1x 7x 7x 3x 3x 1x 5x 6x 5x 9x 5x 5x 3x 2x 6x 9x 6x 9x 8x 6x 9x 9x 1x 30x 30x 30x 29x 29x 29x 29x 29x 29x 29x 2x 27x 2x 25x 9x 9x 6x 6x 16x 7x 7x 5x 5x 9x 9x 4x 4x 3x 1x 6x 5x 5x 5x 1x 1x | /**
* GET /v1/store
*
* Packs, the most recently published version first. One Query on `storeIndex`,
* plus reads bounded by the page size: no Scan and no in-memory filtering. See
* docs/architecture/ENTITY_STORE.md "Scalability". An e2e test user sees the
* e2e partition, and everyone else the public one.
*
* With `search`, the packs whose name or description, in any language,
* contains the text (ignoring case and accents), through the trigram index the
* users and flows directories use (utils/directorySearchIndex.js): one Query per
* seed trigram and reads bounded by the page size, never a Scan. Search results
* come in no particular order, and `truncated` says an extremely common text
* may have hidden some.
*
* With `sort=likes` or `sort=imports`, the most liked or most installed packs
* first, across the whole partition: one Query on PackStatsTable's
* `likesIndex` or `importsIndex`, then the page's packs read by key.
* A search is never sorted: its matches come from another index, and ordering
* them all would mean reading every one of them first.
*
* Query params:
* - search: text to look for (optional)
* - sort: `recent` (default), `likes` or `imports`; only `recent` goes with `search`
* - limit: page size (default 30, max 100)
* - nextToken: opaque cursor returned by the previous page
*
* @implements UC-STORE-001.1, UC-STORE-010.1, UC-STORE-011.1, UC-STORE-012.1
*/
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb')
const { DynamoDBDocumentClient, GetCommand, QueryCommand } = require('@aws-sdk/lib-dynamodb')
const {
authenticateModerator: authenticateUser,
errorResponse,
jsonResponse
} = require('../utils/moderation/access')
const {
storePartitionFor,
packsTable,
statsTable,
batchGet,
buildPackPresenter
} = require('../utils/packs')
const { isE2eTestEmail } = require('../utils/e2eTestUser')
const {
searchDirectory,
containsQuery,
packNamespace,
packTexts
} = require('../utils/directorySearchIndex')
const docClient = DynamoDBDocumentClient.from(new DynamoDBClient({}))
const DEFAULT_LIMIT = 30
const MAX_LIMIT = 100
// The counter each sort orders by, and its index on PackStatsTable
const COUNTER_SORTS = {
likes: { indexName: 'likesIndex', counter: 'likesCount' },
imports: { indexName: 'importsIndex', counter: 'importsCount' }
}
const encodeToken = (key) => Buffer.from(JSON.stringify(key)).toString('base64')
function decodeToken(token) {
try {
return JSON.parse(Buffer.from(token, 'base64').toString())
} catch {
return null
}
}
/** One page of the caller's partition whose packs contain `search`. */
async function searchPacks({ storeKey, search, limit, nextToken }) {
let offset = 0
if (nextToken) {
const key = decodeToken(nextToken)
// A search cursor is a position among the candidates of that very search
if (!Number.isInteger(key?.offset) || key.offset < 0 || key.search !== search) return null
offset = key.offset
}
const { items, nextOffset, truncated } = await searchDirectory(docClient, {
indexTableName: process.env.FIELD_VALUE_INDEX_TABLE_NAME,
subjectsTableName: packsTable(),
namespaces: [packNamespace(storeKey)],
searchValue: search,
// A pack moved to the other partition since it was indexed is not shown
verify: (pack, normalizedQuery) =>
pack.storeKey === storeKey && containsQuery(normalizedQuery, packTexts(pack)),
limit,
offset
})
return {
packs: items,
nextToken: nextOffset === null ? null : encodeToken({ offset: nextOffset, search }),
truncated
}
}
/**
* One page of the caller's partition, the highest counter first. A pack
* deleted, or moved to the other partition, since the index answered is left
* out: the page may come shorter, never with someone else's pack.
*/
async function packsByCounter({ indexName, counter }, { storeKey, limit, nextToken }) {
let exclusiveStartKey
if (nextToken) {
const key = decodeToken(nextToken)
// A client-controlled cursor must stay in the caller's partition
if (
key?.storeKey !== storeKey ||
typeof key.packId !== 'string' ||
typeof key[counter] !== 'number'
) {
return null
}
exclusiveStartKey = { packId: key.packId, storeKey, [counter]: key[counter] }
}
const result = await docClient.send(
new QueryCommand({
TableName: statsTable(),
IndexName: indexName,
KeyConditionExpression: 'storeKey = :storeKey',
ExpressionAttributeValues: { ':storeKey': storeKey },
ScanIndexForward: false,
Limit: limit,
ExclusiveStartKey: exclusiveStartKey
})
)
const packIds = (result.Items || []).map((row) => row.packId)
const rows = await batchGet(
docClient,
packsTable(),
packIds.map((id) => ({ id }))
)
const byId = new Map(rows.map((pack) => [pack.id, pack]))
return {
packs: packIds
.map((id) => byId.get(id))
.filter((pack) => pack?.currentVersion && pack.storeKey === storeKey),
nextToken: result.LastEvaluatedKey ? encodeToken(result.LastEvaluatedKey) : null
}
}
exports.handler = async (event) => {
try {
const caller = await authenticateUser(event)
if (caller.response) return caller.response
const rawLimit = parseInt(event.queryStringParameters?.limit, 10)
const limit = Number.isFinite(rawLimit)
? Math.min(Math.max(rawLimit, 1), MAX_LIMIT)
: DEFAULT_LIMIT
const user = await docClient.send(
new GetCommand({
TableName: process.env.USERS_TABLE_NAME,
Key: { id: caller.auth.userId },
ProjectionExpression: 'email'
})
)
const storeKey = storePartitionFor({ isTest: isE2eTestEmail(user.Item?.email) })
const search = event.queryStringParameters?.search?.trim()
const sort = event.queryStringParameters?.sort || 'recent'
if (sort !== 'recent' && !Object.hasOwn(COUNTER_SORTS, sort)) {
return errorResponse(400, 'Invalid sort')
}
if (search && sort !== 'recent') {
return errorResponse(400, 'A search cannot be sorted')
}
if (sort !== 'recent') {
const page = await packsByCounter(COUNTER_SORTS[sort], {
storeKey,
limit,
nextToken: event.queryStringParameters?.nextToken
})
if (!page) return errorResponse(400, 'Invalid nextToken')
const present = await buildPackPresenter(docClient, page.packs, caller.auth.userId)
return jsonResponse(200, { items: page.packs.map(present), nextToken: page.nextToken })
}
if (search) {
const page = await searchPacks({
storeKey,
search,
limit,
nextToken: event.queryStringParameters?.nextToken
})
if (!page) return errorResponse(400, 'Invalid nextToken')
const present = await buildPackPresenter(docClient, page.packs, caller.auth.userId)
return jsonResponse(200, {
items: page.packs.map(present),
nextToken: page.nextToken,
truncated: page.truncated
})
}
let exclusiveStartKey
const nextToken = event.queryStringParameters?.nextToken
if (nextToken) {
const key = decodeToken(nextToken)
// A client-controlled cursor must stay in the caller's partition
if (key?.storeKey !== storeKey || typeof key.id !== 'string') {
return errorResponse(400, 'Invalid nextToken')
}
exclusiveStartKey = { id: key.id, storeKey: key.storeKey, storeSortKey: key.storeSortKey }
}
const result = await docClient.send(
new QueryCommand({
TableName: packsTable(),
IndexName: 'storeIndex',
KeyConditionExpression: 'storeKey = :storeKey',
ExpressionAttributeValues: { ':storeKey': storeKey },
ScanIndexForward: false,
Limit: limit,
ExclusiveStartKey: exclusiveStartKey
})
)
const packs = result.Items || []
const present = await buildPackPresenter(docClient, packs, caller.auth.userId)
return jsonResponse(200, {
items: packs.map(present),
nextToken: result.LastEvaluatedKey ? encodeToken(result.LastEvaluatedKey) : null
})
} catch (error) {
console.error('[store/list] Exception:', error.message, error.stack)
return errorResponse(500, 'Failed to list packs')
}
}
|