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 | 17x 17x 17x 75x 75x 97x 23x 23x 17x 17x 17x 17x 15x 75x 6x 6x 4x 6x 4x 6x 10x 8x 9x 32x 32x 5x 14x 14x 2x 12x 12x 12x 10x 15x 10x 19x 9x 17x | const { QueryCommand, UpdateCommand } = require('@aws-sdk/lib-dynamodb')
const { isDeletedPlaceholder } = require('./deletedPlaceholder')
const { batchDelete } = require('./batchWrite')
/**
* Given an entity's schema fields and an item's data, returns the distinct set
* of target entityIds that item currently references through `entity_ref`
* fields. Two fields (or a multi-value field with several ids) pointing at the
* same target entity still count once — the counter tracks "distinct items
* referencing this entity", not "distinct references".
*
* @param {Array} fields
* @param {Record<string, unknown>} itemData
* @returns {Set<string>}
*/
function getReferencedEntityIds(fields, itemData) {
const referencedEntityIds = new Set()
for (const field of fields || []) {
if (field.type !== 'entity_ref' || !field.reference?.entityId) continue
const value = itemData?.[field.fieldId]
if (value === undefined || value === null || value === '') continue
const isMultiple = field.reference?.multiple === true
const values = isMultiple && Array.isArray(value) ? value : [value]
const hasLiveReference = values.some((v) => !isDeletedPlaceholder(v))
if (hasLiveReference) {
referencedEntityIds.add(field.reference.entityId)
}
}
return referencedEntityIds
}
/**
* Diffs two "referenced entity" sets (e.g. before/after an item update) into a
* delta map suitable for adjustCounters: +1 for entities newly referenced,
* -1 for entities no longer referenced.
*
* @param {Set<string>} oldSet
* @param {Set<string>} newSet
* @returns {Map<string, number>}
*/
function diffReferencedEntityIds(oldSet, newSet) {
const deltas = new Map()
for (const entityId of newSet) {
if (!oldSet.has(entityId)) deltas.set(entityId, 1)
}
for (const entityId of oldSet) {
if (!newSet.has(entityId)) deltas.set(entityId, -1)
}
return deltas
}
/**
* Applies atomic +/- deltas to EntityReferenceCountersTable rows. Rows
* auto-vivify on first ADD, so nothing needs pre-seeding.
*
* @param {import('@aws-sdk/lib-dynamodb').DynamoDBDocumentClient} docClient
* @param {string} tableName
* @param {string} flowId
* @param {Map<string, number>} entityIdToDelta
*/
async function adjustCounters(docClient, tableName, flowId, entityIdToDelta) {
const entries = [...entityIdToDelta.entries()].filter(([, delta]) => delta !== 0)
await Promise.all(
entries.map(([entityId, delta]) =>
docClient.send(
new UpdateCommand({
TableName: tableName,
Key: { flowId, entityId },
UpdateExpression: 'ADD #count :delta',
ExpressionAttributeNames: { '#count': 'count' },
ExpressionAttributeValues: { ':delta': delta }
})
)
)
)
}
/**
* Removes every counter row contributed by a flow that is being deleted
* entirely. Cheaper and just as correct as decrementing item-by-item, since
* once the flow (and all its items) are gone, its contribution to every
* target entity's count is unconditionally zero.
*
* @param {import('@aws-sdk/lib-dynamodb').DynamoDBDocumentClient} docClient
* @param {string} tableName
* @param {string} flowId
*/
async function deleteAllCountersForFlow(docClient, tableName, flowId) {
const result = await docClient.send(
new QueryCommand({
TableName: tableName,
KeyConditionExpression: 'flowId = :flowId',
ExpressionAttributeValues: { ':flowId': flowId }
})
)
await batchDelete(
docClient,
tableName,
(result.Items || []).map((item) => ({ flowId: item.flowId, entityId: item.entityId }))
)
}
/**
* Removes every counter row pointing at an entity that is being deleted
* entirely (no consumer flow can reference a deleted entity's items anymore).
*
* @param {import('@aws-sdk/lib-dynamodb').DynamoDBDocumentClient} docClient
* @param {string} tableName
* @param {string} entityId
*/
async function deleteAllCountersForEntity(docClient, tableName, entityId) {
const result = await docClient.send(
new QueryCommand({
TableName: tableName,
IndexName: 'entityIndex',
KeyConditionExpression: 'entityId = :entityId',
ExpressionAttributeValues: { ':entityId': entityId }
})
)
await batchDelete(
docClient,
tableName,
(result.Items || []).map((item) => ({ flowId: item.flowId, entityId: item.entityId }))
)
}
/**
* Ranks the flows currently linking a public entity by how many of their own
* items reference it, most-referencing first. Ties broken by earliest link
* (oldest, most established consumer) for determinism. Flows with a link but
* no counter row yet rank last with count 0.
*
* @param {import('@aws-sdk/lib-dynamodb').DynamoDBDocumentClient} docClient
* @param {{ entityLinksTableName: string, countersTableName: string, entityId: string }} params
* @returns {Promise<Array<{ flowId: string, itemReferenceCount: number, linkedAt: string }>>}
*/
async function rankConsumerFlows(docClient, { entityLinksTableName, countersTableName, entityId }) {
const linksResult = await docClient.send(
new QueryCommand({
TableName: entityLinksTableName,
IndexName: 'entityIndex',
KeyConditionExpression: 'entityId = :entityId',
ExpressionAttributeValues: { ':entityId': entityId }
})
)
const links = linksResult.Items || []
if (links.length === 0) return []
const countersResult = await docClient.send(
new QueryCommand({
TableName: countersTableName,
IndexName: 'entityIndex',
KeyConditionExpression: 'entityId = :entityId',
ExpressionAttributeValues: { ':entityId': entityId }
})
)
const countByFlowId = new Map((countersResult.Items || []).map((c) => [c.flowId, c.count || 0]))
return links
.map((link) => ({
flowId: link.flowId,
linkedAt: link.linkedAt,
itemReferenceCount: countByFlowId.get(link.flowId) || 0
}))
.sort(
(a, b) =>
b.itemReferenceCount - a.itemReferenceCount ||
(a.linkedAt || '').localeCompare(b.linkedAt || '')
)
}
module.exports = {
getReferencedEntityIds,
diffReferencedEntityIds,
adjustCounters,
deleteAllCountersForFlow,
deleteAllCountersForEntity,
rankConsumerFlows
}
|