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 | 18x 18x 18x 18x 18x 18x 18x 18x 4x 10x 10x 3x 6x 3x 2x 1x 4x 4x 2x 5x 43x 43x 43x 43x 23x 23x 6x 37x 10x 34x 34x 34x 34x 1287x 34x 35x 35x 786x 35x 35x 34x 5x 5x 5x 5x 6x 6x 6x 8x 6x 8x 8x 6x 6x 5x 18x | /**
* Shared helpers for the platform-admin "all users" / "all flows" lists.
*
* Both tables carry a constant `gsiPk` ('USER' / 'FLOW') feeding the
* `platformStatsIndex` GSI (sorted by `createdAt`), so a page of the platform-wide
* list is a Query on that index, never a table Scan. The GSI is KEYS_ONLY, so each
* page of keys is then hydrated with a BatchGet on the base table.
*
* Rows created before the GSI existed are only listed once
* `scripts/backfill-gsi-pk.js` has been run.
*
* Searching does NOT go through here: a text search is answered by the trigram
* directory index (see directorySearchIndex.js), so this list is only ever the
* unfiltered, newest-first browse.
*/
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb')
const { DynamoDBDocumentClient, QueryCommand, BatchGetCommand } = require('@aws-sdk/lib-dynamodb')
const client = new DynamoDBClient({})
const docClient = DynamoDBDocumentClient.from(client)
const DEFAULT_LIMIT = 25
const MAX_LIMIT = 100
const BATCH_GET_MAX_KEYS = 100
const BATCH_GET_MAX_ATTEMPTS = 3
class InvalidListParamsError extends Error {}
function encodeCursor(payload) {
return Buffer.from(JSON.stringify(payload)).toString('base64url')
}
function decodeCursorPayload(cursor) {
try {
return JSON.parse(Buffer.from(cursor, 'base64url').toString('utf8'))
} catch {
throw new InvalidListParamsError('Invalid cursor')
}
}
/** Cursor of the browse list: the GSI key to resume after. */
function decodeKeyCursor(cursor) {
const key = decodeCursorPayload(cursor)
if (typeof key?.id !== 'string' || typeof key?.gsiPk !== 'string') {
throw new InvalidListParamsError('Invalid cursor')
}
return { id: key.id, gsiPk: key.gsiPk, createdAt: key.createdAt }
}
/** Cursor of a search: the position in the (stable) candidate list to resume from. */
function decodeOffsetCursor(cursor) {
const { offset } = decodeCursorPayload(cursor) ?? {}
if (!Number.isInteger(offset) || offset < 0) throw new InvalidListParamsError('Invalid cursor')
return offset
}
function encodeOffsetCursor(offset) {
return offset === null ? null : encodeCursor({ offset })
}
/**
* Parse and validate `search`, `limit` and `cursor` query parameters. The cursor's
* meaning depends on the mode: a GSI key when browsing, a candidate offset when
* searching — a cursor from one mode is rejected by the other.
* @throws {InvalidListParamsError} on a malformed limit or cursor
*/
function parseListParams(event) {
const params = event.queryStringParameters || {}
const search = params.search?.trim() || null
let limit = DEFAULT_LIMIT
if (params.limit !== undefined) {
limit = Number(params.limit)
if (!Number.isInteger(limit) || limit < 1 || limit > MAX_LIMIT) {
throw new InvalidListParamsError(`limit must be an integer between 1 and ${MAX_LIMIT}`)
}
}
if (!params.cursor) return { search, limit, cursor: undefined, offset: 0 }
return search
? { search, limit, cursor: undefined, offset: decodeOffsetCursor(params.cursor) }
: { search, limit, cursor: decodeKeyCursor(params.cursor), offset: 0 }
}
/**
* Fetch full items by `id` from a table whose partition key is `id`.
* @returns {Promise<Map<string, object>>} items keyed by id (missing ids are absent)
*/
async function batchGetByIds(tableName, ids) {
const uniqueIds = [...new Set(ids)]
const found = new Map()
for (let i = 0; i < uniqueIds.length; i += BATCH_GET_MAX_KEYS) {
let requestItems = {
[tableName]: { Keys: uniqueIds.slice(i, i + BATCH_GET_MAX_KEYS).map((id) => ({ id })) }
}
for (let attempt = 0; attempt < BATCH_GET_MAX_ATTEMPTS && requestItems; attempt++) {
const result = await docClient.send(new BatchGetCommand({ RequestItems: requestItems }))
for (const item of result.Responses?.[tableName] ?? []) {
found.set(item.id, item)
}
const unprocessed = result.UnprocessedKeys
requestItems = unprocessed && Object.keys(unprocessed).length > 0 ? unprocessed : null
}
}
return found
}
/**
* One page of the platform-wide list, newest first.
*
* @param {object} options
* @param {string} options.tableName
* @param {string} options.gsiPkValue - constant partition value ('USER' / 'FLOW')
* @param {number} options.limit
* @param {object} [options.cursor] - decoded cursor from a previous page
* @returns {Promise<{ items: object[], nextCursor: string | null }>}
*/
async function listByCreatedAt({ tableName, gsiPkValue, limit, cursor }) {
const items = []
let startKey = cursor
let nextKey = null
// Read exactly what's still needed; the loop only repeats when an index row's base
// item was deleted in between (the GSI is eventually consistent) and left a gap.
do {
const page = await docClient.send(
new QueryCommand({
TableName: tableName,
IndexName: 'platformStatsIndex',
KeyConditionExpression: 'gsiPk = :pk',
ExpressionAttributeValues: { ':pk': gsiPkValue },
ScanIndexForward: false,
Limit: limit - items.length,
ExclusiveStartKey: startKey
})
)
const keys = page.Items ?? []
const fullItems = await batchGetByIds(
tableName,
keys.map((key) => key.id)
)
for (const key of keys) {
const item = fullItems.get(key.id)
if (item) items.push(item)
}
startKey = page.LastEvaluatedKey
nextKey = startKey ?? null
} while (startKey && items.length < limit)
return {
items,
nextCursor: nextKey
? encodeCursor({ id: nextKey.id, gsiPk: nextKey.gsiPk, createdAt: nextKey.createdAt })
: null
}
}
module.exports = {
InvalidListParamsError,
parseListParams,
encodeOffsetCursor,
batchGetByIds,
listByCreatedAt
}
|