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 | 21x 21x 21x 21x 21x 21x 21x 53x 21x 21x 21x 21x 21x 21x 21x 21x 5x 5x 21x 258x 45x 86x 85x 93x 23x 65x 25x 137x 120x 120x 17x 14x 14x 21x 18x 18x 16x 9x 74x 74x 72x 63x 63x 2x 61x 59x 139x 138x 134x 22x 58x 58x 57x 57x 35x 32x 22x 22x 4x 18x 2x 16x 15x 120x 120x 79x 79x 120x 36x 36x 36x 26x 26x 24x 36x 36x 36x 36x 26x 30x 21x | /**
* Store packs: what the store/ Lambdas and the cascades share. See
* docs/architecture/ENTITY_STORE.md.
*
* A pack has one row in PacksTable, which carries a copy of its current (latest
* published) version so listing the Store never reads versions, and one row per
* publication in PackVersionsTable. A name identifies a pack within a flow:
* PackNamesTable reserves it atomically, as FlowSlugsTable does for slugs.
*
* @implements UC-STORE-008.2
*/
const { GetCommand, BatchGetCommand } = require('@aws-sdk/lib-dynamodb')
const { normalizeName } = require('./nameUniqueness')
const { isValidLanguage } = require('./i18n')
const { permissionChecker } = require('./PermissionChecker')
const { isValidUuid } = require('./isValidUuid')
const { getCommentCounts } = require('./commentCount')
/**
* The partitions of `storeIndex`: see ENTITY_STORE.md "Scalability". Packs
* published by e2e test users go to their own, so that real users never see
* them and e2e runs see only theirs.
*/
const STORE_PARTITION = { PUBLIC: 'PUBLIC', E2E: 'E2E' }
function storePartitionFor({ isTest }) {
return isTest ? STORE_PARTITION.E2E : STORE_PARTITION.PUBLIC
}
/**
* The flow permission publishing needs, on top of editing every entity of the
* pack. Only the Admin role (`*:*`), which the owner always holds, has it by
* default.
*/
const PUBLISH_PERMISSION = 'packs:publish'
const MAX_PACK_ENTITIES = 20
/**
* The snapshot, uncompressed. The pack page reads it whole in one synchronous
* Lambda response (store/get.js), which AWS caps at 6 MB: 5 MB leaves room for
* the rest of the response. Past that, the page would need to fetch the
* snapshot from S3 itself (a presigned URL), not through the API.
*/
const MAX_PACK_SNAPSHOT_BYTES = 5 * 1024 * 1024
/**
* A pack carries items for linked entities (reference lists: countries,
* statuses...), never to replicate content: at most 20 per entity, the
* entities chosen by the publisher. The limit is the Store's, not the bundle
* format's: an export of everything has none.
*/
const MAX_PACK_ITEMS_PER_ENTITY = 20
/** Images and files of a version's items, copied into the pack at publication. */
const MAX_PACK_ITEM_FILES = 200
const MAX_PACK_NAME_LENGTH = 100
const MAX_PACK_DESCRIPTION_LENGTH = 1000
/** The pack's picture, shown on its card: uploaded under the pack (uploads/presigned-url.js). */
const packPicturePrefix = (packId) => `packs/${packId}/pack-picture/`
/** Whether `picture` is a key of the pack's own picture: anything else is refused. */
function isPackPictureKey(packId, picture) {
const prefix = packPicturePrefix(packId)
return (
typeof picture === 'string' &&
picture.startsWith(prefix) &&
picture.length > prefix.length &&
!picture.slice(prefix.length).includes('/')
)
}
/** DynamoDB BatchGetItem accepts at most 100 keys per request. */
const BATCH_GET_LIMIT = 100
const packsTable = () => process.env.PACKS_TABLE_NAME
const versionsTable = () => process.env.PACK_VERSIONS_TABLE_NAME
const namesTable = () => process.env.PACK_NAMES_TABLE_NAME
const statsTable = () => process.env.PACK_STATS_TABLE_NAME
const likesTable = () => process.env.PACK_LIKES_TABLE_NAME
/**
* The `Update` putting a pack's counters in its Store partition, which
* `likesIndex` sorts by (UC-STORE-011.1). Counters start at 0, and are kept
* when the row exists: a like may have created it. Written by every
* publication, as a new version may move the pack to the other partition.
*/
function buildPackStatsSync(packId, storeKey) {
return {
TableName: statsTable(),
Key: { packId },
UpdateExpression:
'SET storeKey = :storeKey, likesCount = if_not_exists(likesCount, :zero), importsCount = if_not_exists(importsCount, :zero)',
ExpressionAttributeValues: { ':storeKey': storeKey, ':zero': 0 }
}
}
function packNameKey(flowId, name) {
return `${flowId}#${normalizeName(name)}`
}
function snapshotKeyFor(packId, version) {
return `packs/${packId}/${version}/bundle.json.gz`
}
/**
* Cleans a pack text: a plain string, or an object keyed by language code like
* entity names. Translations are trimmed, empty ones dropped, and each is held
* to `maxLength`. A plain string stays a string, as for entities.
*
* @returns {{ value: string | Record<string, string> } | { error: 'INVALID' | 'TOO_LONG' }}
*/
function cleanPackText(raw, maxLength) {
if (typeof raw === 'string') {
const value = raw.trim()
return value.length > maxLength ? { error: 'TOO_LONG' } : { value }
}
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return { error: 'INVALID' }
const value = {}
for (const [lang, text] of Object.entries(raw)) {
if (!isValidLanguage(lang) || typeof text !== 'string') return { error: 'INVALID' }
const trimmed = text.trim()
if (trimmed.length > maxLength) return { error: 'TOO_LONG' }
if (trimmed) value[lang] = trimmed
}
return { value: Object.keys(value).length > 0 ? value : '' }
}
/**
* Name and description are multilingual, each translation held to the limits.
* The name identifies the pack within its flow through `normalizeName`, the
* rule entity and flow names follow (English, else French, else the first).
*
* @returns {{
* valid: true,
* name: string | Record<string, string>,
* description: string | Record<string, string>
* } | { valid: false, error: string }}
*/
function validatePackInput(payload) {
const name = cleanPackText(payload?.name ?? '', MAX_PACK_NAME_LENGTH)
if (name.error === 'TOO_LONG') return { valid: false, error: 'PACK_NAME_TOO_LONG' }
if (name.error || !normalizeName(name.value)) return { valid: false, error: 'PACK_NAME_REQUIRED' }
const description = cleanPackText(payload.description ?? '', MAX_PACK_DESCRIPTION_LENGTH)
if (description.error === 'TOO_LONG') {
return { valid: false, error: 'PACK_DESCRIPTION_TOO_LONG' }
}
if (description.error) return { valid: false, error: 'PACK_DESCRIPTION_INVALID' }
return { valid: true, name: name.value, description: description.value }
}
async function getPack(docClient, packId, { consistent = false } = {}) {
if (!isValidUuid(packId)) return null
const result = await docClient.send(
new GetCommand({ TableName: packsTable(), Key: { id: packId }, ConsistentRead: consistent })
)
return result.Item || null
}
/**
* Whether the caller may publish a new version of `pack`: its author, or the
* owner of its flow. A new version retires the previous one for good, so
* editing rights on one entity are not enough.
*/
async function maintainsPack(pack, userId) {
return pack.authorId === userId || permissionChecker.isOwner(userId, pack.flowId)
}
/**
* What publishing `name` from `flowId` would do (UC-STORE-008.2). Without
* `packId`, a new pack, refused when another pack of the flow holds the name.
* With `packId`, the next version of that pack of the flow, which may take a
* new name, English one included, as long as no other pack of the flow holds
* it.
*
* @returns {Promise<
* { isNew: true, nameKey: string, version: 1 } |
* { isNew: false, nameKey: string, version: number, pack: object } |
* { refusal: 'PACK_NAME_TAKEN' | 'PACK_NOT_FOUND' | 'PACK_NOT_MAINTAINED', status: number }
* >}
*/
async function resolvePublication(docClient, { flowId, userId, name, packId }) {
const nameKey = packNameKey(flowId, name)
const reservation = await docClient.send(
new GetCommand({ TableName: namesTable(), Key: { nameKey }, ConsistentRead: true })
)
const holder = reservation.Item?.packId
if (packId === undefined || packId === null) {
if (holder) return { refusal: 'PACK_NAME_TAKEN', status: 409 }
return { isNew: true, nameKey, version: 1 }
}
const pack = await getPack(docClient, packId, { consistent: true })
// Only a published pack of the active flow takes a new version from it
if (!pack?.currentVersion || pack.flowId !== flowId) {
return { refusal: 'PACK_NOT_FOUND', status: 404 }
}
if (!(await maintainsPack(pack, userId))) {
return { refusal: 'PACK_NOT_MAINTAINED', status: 403 }
}
if (holder && holder !== pack.id) return { refusal: 'PACK_NAME_TAKEN', status: 409 }
return { isNew: false, nameKey, pack, version: pack.currentVersion + 1 }
}
async function batchGet(docClient, tableName, keys) {
const rows = []
for (let offset = 0; offset < keys.length; offset += BATCH_GET_LIMIT) {
const result = await docClient.send(
new BatchGetCommand({
RequestItems: { [tableName]: { Keys: keys.slice(offset, offset + BATCH_GET_LIMIT) } }
})
)
rows.push(...(result.Responses?.[tableName] || []))
}
return rows
}
/**
* What a page of packs needs beyond the rows themselves, in reads bounded by the
* page size: their counters, the caller's likes and their flows' names.
*
* @returns {Promise<(pack: object) => object>} turns a pack into its public shape
*/
async function buildPackPresenter(docClient, packs, userId) {
const packIds = packs.map((pack) => pack.id)
const flowIds = [...new Set(packs.map((pack) => pack.flowId))]
const [stats, likes, flows, commentCounts] = await Promise.all([
batchGet(
docClient,
statsTable(),
packIds.map((packId) => ({ packId }))
),
batchGet(
docClient,
likesTable(),
packIds.map((packId) => ({ packId, userId }))
),
batchGet(
docClient,
process.env.FLOWS_TABLE_NAME,
flowIds.map((id) => ({ id }))
),
// A pack's comments are counted under its id, as an item's are
process.env.ITEM_COMMENT_COUNT_TABLE_NAME
? getCommentCounts(docClient, process.env.ITEM_COMMENT_COUNT_TABLE_NAME, packIds)
: Promise.resolve(new Map())
])
const statsByPack = new Map(stats.map((row) => [row.packId, row]))
const likedPacks = new Set(likes.map((row) => row.packId))
const flowById = new Map(flows.map((flow) => [flow.id, flow]))
return (pack) =>
toPublicPack(pack, {
flow: flowById.get(pack.flowId),
stats: statsByPack.get(pack.id),
likedByMe: likedPacks.has(pack.id),
commentsCount: commentCounts.get(pack.id) ?? 0
})
}
/** The shape any user sees: the current version, and never who published it. */
function toPublicPack(pack, { flow, stats, likedByMe, commentsCount = 0 }) {
return {
id: pack.id,
name: pack.name,
description: pack.description ?? '',
version: pack.currentVersion,
entities: pack.entitiesPreview ?? [],
publishedAt: pack.publishedAt,
picture: pack.picture ?? null,
flow: { id: pack.flowId, name: flow?.name ?? null, slug: flow?.slug ?? null },
likesCount: Math.max(0, stats?.likesCount || 0),
importsCount: Math.max(0, stats?.importsCount || 0),
likedByMe: likedByMe === true,
// Off for packs published before comments existed: their managers turn them on
commentsEnabled: pack.commentsEnabled === true,
commentsCount: Math.max(0, commentsCount)
}
}
module.exports = {
STORE_PARTITION,
storePartitionFor,
PUBLISH_PERMISSION,
MAX_PACK_ENTITIES,
MAX_PACK_SNAPSHOT_BYTES,
MAX_PACK_ITEMS_PER_ENTITY,
MAX_PACK_ITEM_FILES,
MAX_PACK_NAME_LENGTH,
MAX_PACK_DESCRIPTION_LENGTH,
packPicturePrefix,
isPackPictureKey,
packsTable,
versionsTable,
namesTable,
statsTable,
likesTable,
buildPackStatsSync,
batchGet,
packNameKey,
snapshotKeyFor,
validatePackInput,
getPack,
resolvePublication,
maintainsPack,
buildPackPresenter,
toPublicPack
}
|