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 | 3x 3x 3x 3x 3x 3x 3x 3x 639x 639x 56x 305x 56x 3x 56x 313x 616x 616x 305x 304x 304x 1x 1x 1x 1x 56x 208x 207x 207x 206x 1x 1x 208x 56x 7x 7x 7x 16x 208x 7x 28x 28x 11x 11x 11x 11x 28x 28x 313x 28x 28x 28x 28x 28x 313x 28x 28x 3x | /**
* Credit-cost estimate for forking an entity, shared by fork.js (which
* refuses the fork up front when the balance can't cover it) and
* fork-preview.js (which shows the same number in the confirmation dialog) —
* so what the user is told is exactly what the fork will require.
*
* Covers the three pools a fork bills — see docs/architecture/USAGE_METERING.md:
* - dynamodb_storage: entity schema + every copied item, sized from the data
* - s3_storage: each copied image/file, per object with a 1-credit minimum
* (mirrors uploads/s3-usage-consumer.js, which does the real debit)
* - dynamodb_throughput: only an allowance — the real number is SDK-reported
* after the write (shared/usage-tracking.js), so it can't be known here
*/
const { S3Client, HeadObjectCommand } = require('@aws-sdk/client-s3')
const { QueryCommand } = require('@aws-sdk/lib-dynamodb')
const { getItemCount } = require('./entityItemCount')
const s3Client = new S3Client({})
// Per-item write allowance beyond the item's own 2 WRU per KB (a transactional
// write costs double): the item-count update, unique-field reservations,
// equality-index and text-search rows each add writes, and how many depends on
// the entity's fields. Deliberately generous — an under-estimate is what lets a
// fork start and then overshoot the balance. To be calibrated against the real
// `entity_fork` dynamodb_throughput ledger rows.
const THROUGHPUT_ALLOWANCE_WRU_PER_ITEM = 10
const THROUGHPUT_ALLOWANCE_WRU_ENTITY = 10
// The estimate is approximate by nature, so past this many images/files it
// measures a sample and extrapolates instead of HEAD-ing every object (each
// HEAD is a network call, and API Gateway cuts requests off at 29s).
const MAX_MEDIA_OBJECTS_MEASURED = 200
const MEDIA_HEAD_CONCURRENCY = 20
// The item's own data, excluding the envelope fields every item carries —
// matches items/create.js's `dataSizeBytes` exactly (same fields stripped),
// so a copied item is priced identically to a freshly-created one.
function itemDataBytes(sourceItem) {
// eslint-disable-next-line no-unused-vars
const { id, entityId, flowId, createdBy, createdAt, updatedAt, ...data } = sourceItem
return Buffer.byteLength(JSON.stringify(data))
}
// Every image/file the fork would copy: `image`/`image_set` values are bare
// S3 keys (size unknown until HEAD), `file`/`file_set` values are
// `{ key, size, ... }` objects that already carry their size. The entity's
// own picture is always copied, whether or not items are.
function collectMediaObjects({ picture, fields, items }) {
const objects = []
const toArray = (value) => (Array.isArray(value) ? value : [value])
if (typeof picture === 'string' && picture) {
objects.push({ key: picture })
}
for (const item of items) {
for (const field of fields) {
const value = item[field.fieldId]
if (!value) continue
if (field.type === 'image' || field.type === 'image_set') {
for (const key of toArray(value)) {
Eif (typeof key === 'string' && key) objects.push({ key })
}
} else Eif (field.type === 'file' || field.type === 'file_set') {
for (const file of toArray(value)) {
Eif (file && typeof file.key === 'string') {
objects.push({ key: file.key, size: Number(file.size) || undefined })
}
}
}
}
}
return objects
}
async function measureObjectSize(object) {
if (object.size !== undefined) return object.size
try {
const head = await s3Client.send(
new HeadObjectCommand({ Bucket: process.env.ATTACHMENTS_BUCKET_NAME, Key: object.key })
)
return head.ContentLength || 0
} catch (error) {
// A missing/unreadable object is simply not sized — the real fork falls
// back to the shared source key for it too (entityImageCopy.js).
console.error(`[forkCostEstimate] Failed to HEAD ${object.key}:`, error.message)
return 0
}
}
// s3_storage is charged per copied object with a 1-credit minimum, so costs
// must be summed per object, not derived from the total byte count.
function s3CreditsForSize(sizeBytes, s3StorageCreditsPerMb) {
return Math.max(1, Math.ceil((sizeBytes / (1024 * 1024)) * s3StorageCreditsPerMb))
}
async function estimateMediaCredits(objects, s3StorageCreditsPerMb) {
if (objects.length === 0) return 0
const measured = objects.slice(0, MAX_MEDIA_OBJECTS_MEASURED)
let credits = 0
for (let i = 0; i < measured.length; i += MEDIA_HEAD_CONCURRENCY) {
const sizes = await Promise.all(
measured.slice(i, i + MEDIA_HEAD_CONCURRENCY).map(measureObjectSize)
)
credits += sizes.reduce((sum, size) => sum + s3CreditsForSize(size, s3StorageCreditsPerMb), 0)
}
return Math.ceil((credits / measured.length) * objects.length)
}
/**
* Reads what the estimate needs from the source entity: its total item count
* (an O(1) read on EntityItemCountTable) and, when items will be copied, a
* *sample* — the first Query page only (up to 1MB), never the whole
* partition. Submit and preview both call this, so neither has to read every
* item of a huge entity just to put a number on the cost; estimateForkCost
* scales the sample up to the full count.
*/
async function loadForkEstimateInputs({ docClient, entityId, copyItems }) {
const countedItems = await getItemCount(
docClient,
process.env.ENTITY_ITEM_COUNT_TABLE_NAME,
entityId
)
if (!copyItems) return { items: [], totalItemCount: countedItems }
const page = await docClient.send(
new QueryCommand({
TableName: process.env.ITEMS_TABLE_NAME,
KeyConditionExpression: 'entityId = :entityId',
ExpressionAttributeValues: { ':entityId': entityId }
})
)
const items = page.Items || []
// A page with no LastEvaluatedKey is the whole partition: the real count.
// Otherwise the counter is the best figure available, but never below what
// was actually read.
const totalItemCount = page.LastEvaluatedKey ? Math.max(countedItems, items.length) : items.length
return { items, totalItemCount }
}
/**
* @param {object} params
* @param {Array} params.fields - the source entity's fields
* @param {Array} params.forms - the source entity's forms
* @param {string} [params.picture] - the source entity's picture S3 key
* @param {Array} params.items - the source items that will be copied, or a sample of them (empty when not copying)
* @param {number} [params.totalItemCount] - how many items will really be copied when `items` is only a sample
* @param {{ dynamodb_storage_credits_per_kb: number, dynamodb_throughput_credits_per_wru: number, s3_storage_credits_per_mb: number }} params.pricing
* current admin-editable rates — see utils/pricingConfig.js
* @returns {Promise<{dynamoStorageCredits: number, s3StorageCredits: number, throughputCredits: number, totalCredits: number}>}
*/
async function estimateForkCost({
fields,
forms,
picture,
items,
totalItemCount = items.length,
pricing
}) {
// Item-driven costs are measured on the sample and scaled to the full set.
const scale = items.length > 0 ? Math.max(totalItemCount, items.length) / items.length : 1
const entitySizeBytes = Buffer.byteLength(JSON.stringify({ fields, forms }))
const itemsSizeBytes = items.reduce((sum, item) => sum + itemDataBytes(item), 0) * scale
const dynamoStorageCredits = Math.ceil(
((entitySizeBytes + itemsSizeBytes) / 1024) * pricing.dynamodb_storage_credits_per_kb
)
const pictureCredits = await estimateMediaCredits(
collectMediaObjects({ picture, fields, items: [] }),
pricing.s3_storage_credits_per_mb
)
const itemMediaCredits = await estimateMediaCredits(
collectMediaObjects({ fields, items }),
pricing.s3_storage_credits_per_mb
)
const s3StorageCredits = pictureCredits + Math.ceil(itemMediaCredits * scale)
const allowanceWru =
THROUGHPUT_ALLOWANCE_WRU_ENTITY +
items.reduce(
(sum, item) =>
sum + 2 * Math.ceil(itemDataBytes(item) / 1024) + THROUGHPUT_ALLOWANCE_WRU_PER_ITEM,
0
) *
scale
const throughputCredits = Math.ceil(allowanceWru * pricing.dynamodb_throughput_credits_per_wru)
return {
dynamoStorageCredits,
s3StorageCredits,
throughputCredits,
totalCredits: dynamoStorageCredits + s3StorageCredits + throughputCredits
}
}
module.exports = {
estimateForkCost,
itemDataBytes,
loadForkEstimateInputs,
MAX_MEDIA_OBJECTS_MEASURED
}
|