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 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 | 2x 2x 2x 2x 2x 2x 5x 32x 15x 15x 32x 15x 204x 79x 48x 13x 12x 12x 115x 115x 25x 40x 25x 25x 4x 8x 8x 8x 8x 8x 8x 4x 3x 3x 4x 1x 1x 1x 4x 4x 30x 120x 30x 30x 30x 109x 115x 115x 115x 115x 40x 115x 40x 39x 38x 38x 37x 37x 1x 1x 36x 7x 5x 29x 2x 2x 27x 4x 23x 113x 7x 107x 28x 8x 8x 7x 7x 7x 7x 5x 5x 2x 3x 5x 5x 5x 5x 5x 13x 13x 19x 19x 19x 17x 17x 19x 19x 19x 19x 19x 7x 6x 6x 4x 4x 1x 1x 1x 12x 12x 17x 73x 56x 49x 18x 17x 17x 13x 13x 11x 26x 23x 23x 23x 22x 21x 20x 20x 19x 19x 1x 1x 18x 1x 1x 17x 1x 1x 16x 16x 16x 4x 3x 3x 2x 1x 12x 12x 11x 9x 2x 2x 2x | /**
* The community moderation engine — see docs/architecture/MODERATION.md.
*
* It moderates *subjects* (comments today; store packs, pack comments... later)
* without knowing what they are: everything specific to a kind of content lives
* in its subject file (subjects/) and is reached through the registry.
*
* Life of a task:
* 1. `prepareSubmission` — the subject's creation transaction adds the task
* (and spends the author's review points, unless waived).
* 2. `listReviewableTasks` — reviewers are shown candidates from the front of
* the queue (oldest first), lightly shuffled: several reviewers opening the
* page at once land on different ones instead of all converging on the
* exact same task and leaving the rest of the front unreviewed.
* 3. `castVote` — votes accumulate; when one side reaches the subject's
* `requiredVotes`, the task is decided in one transaction that also applies
* the decision to the subject and updates every voter's reputation.
* 4. The subject may have its author notified of the decision
* (`buildAuthorNotification`), within the deciding transaction.
* 5. A task met while its subject can no longer be reviewed (its entity went
* private, or stopped taking comments) is discarded with its subject
* (`discardTask`), the author notified likewise.
* 6. A task met still pending with its threshold reached (the deciding
* transaction failed after the vote was recorded) is decided then
* (`settleReachedDecision`).
*
* Nobody can decide a task otherwise: not the content's owners, not platform
* admins. The community alone decides — see docs/architecture/MODERATION.md.
* Should the deciding transaction fail after the vote was recorded, the task
* stays in the queue with its threshold reached: whoever meets it next — a
* reviewer reading the queue or voting, its author listing their submissions —
* applies the decision. No background job is needed for it.
*
* Everything is bounded: no Scan, at most QUEUE_QUERY_BUDGET Queries to find
* work, at most MAX_TASKS_PER_REQUEST subjects loaded per request.
*
* @implements UC-MOD-011.1, UC-MOD-008.1
*/
const {
GetCommand,
QueryCommand,
BatchGetCommand,
DeleteCommand,
TransactWriteCommand
} = require('@aws-sdk/lib-dynamodb')
const { getSubject } = require('./subjects')
const { buildNotificationWrites, pushNotification } = require('../notifications')
const { taskIdFor } = require('./taskId')
const {
PENDING_SHARDS,
QUEUE_PAGE_SIZE,
QUEUE_QUERY_BUDGET,
MAX_TASKS_PER_REQUEST,
REPUTATION_AGREE,
REPUTATION_DISAGREE,
DECIDED_TASK_TTL_SECONDS,
VOTE_TTL_SECONDS,
DECISION,
DISCARDED
} = require('./constants')
const TASK_STATUS = { PENDING: 'pending', APPROVED: 'approved', REJECTED: 'rejected' }
function randomShard() {
return PENDING_SHARDS[Math.floor(Math.random() * PENDING_SHARDS.length)]
}
/**
* Fisher–Yates, in place. Only ever called on `found`, capped at
* MAX_TASKS_PER_REQUEST (a handful of items) — never a cost concern.
*/
function shuffle(array) {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1))
;[array[i], array[j]] = [array[j], array[i]]
}
return array
}
function isCanceled(error) {
return error?.name === 'TransactionCanceledException'
}
const tasksTable = () => process.env.MODERATION_TASKS_TABLE_NAME
const votesTable = () => process.env.MODERATION_VOTES_TABLE_NAME
const statsTable = () => process.env.MODERATOR_STATS_TABLE_NAME
// ─── Stats ────────────────────────────────────────────────────────────────────
/** A user's review points (the quota), reputation and vote counters. */
async function getStats(docClient, userId) {
const result = await docClient.send(new GetCommand({ TableName: statsTable(), Key: { userId } }))
const item = result.Item || {}
return {
reviewPoints: item.reviewPoints || 0,
reputationScore: item.reputationScore || 0,
votesCast: item.votesCast || 0,
votesAgreed: item.votesAgreed || 0
}
}
// ─── Review queue ─────────────────────────────────────────────────────────────
/** Which of `taskIds` the user already voted on: one bounded BatchGet. */
async function votedTaskIds(docClient, userId, taskIds) {
const voted = new Set()
if (taskIds.length === 0) return voted
const result = await docClient.send(
new BatchGetCommand({
RequestItems: {
[votesTable()]: { Keys: taskIds.map((taskId) => ({ taskId, userId })) }
}
})
)
for (const vote of result.Responses?.[votesTable()] || []) voted.add(vote.taskId)
return voted
}
async function deleteTask(docClient, taskId) {
await docClient.send(new DeleteCommand({ TableName: tasksTable(), Key: { taskId } }))
}
/**
* Deletes a pending task whose subject exists but can no longer be reviewed
* (its entity stopped being public, or stopped taking comments), together with
* the subject itself (`buildDiscardWrites`) and, when the subject asks for it,
* a notification to its author (`buildAuthorNotification` with DISCARDED) —
* one transaction, so it happens exactly once. Nothing is parked: a subject
* left out of the queue would stay pending forever, as nothing could find it
* again without an index. Votes already cast expire on their own (TTL).
*
* @returns {Promise<boolean>} whether this call discarded it
*/
async function discardTask(docClient, { task, subject, context }) {
const items = [
{
Delete: {
TableName: tasksTable(),
Key: { taskId: task.taskId },
ConditionExpression: '#status = :pending',
ExpressionAttributeNames: { '#status': 'status' },
ExpressionAttributeValues: { ':pending': TASK_STATUS.PENDING }
}
},
...subject.buildDiscardWrites(task, context)
]
const content = subject.buildAuthorNotification?.(task, DISCARDED, context) ?? null
const delivery = content ? buildNotificationWrites(task.authorId, content) : null
if (delivery) items.push(...delivery.writes)
try {
await docClient.send(new TransactWriteCommand({ TransactItems: items }))
} catch (error) {
if (!isCanceled(error)) throw error
const reasons = error.CancellationReasons || []
// Decided or deleted meanwhile: nothing left to discard
if (reasons[0]?.Code === 'ConditionalCheckFailed') return false
// The subject changed meanwhile (withdrawn by its author...): only the
// task is left to remove, and there is nothing to tell anybody.
if (reasons.some((r) => r?.Code === 'ConditionalCheckFailed')) {
await deleteTask(docClient, task.taskId)
return false
}
throw error
}
if (delivery) await pushNotification(task.authorId, delivery.notification)
return true
}
/**
* Finds up to `limit` pending tasks the user can review: not their own, not
* already voted by them, and still reviewable. Reads the queue shard by shard
* from a random start, oldest first within a shard, within a fixed Query
* budget — when the queue is short that covers all of it, when it is long it
* is a bounded sample. The result is then shuffled: without it, every reviewer
* hitting a short queue at once would see the very same task first (the oldest
* of whichever shard is read first), all converging their first vote on it
* while the rest of the front goes unreviewed. Tasks whose subject is gone are
* deleted, unreviewable ones discarded, and ones whose threshold is already
* reached decided, as they are met — none of them is offered.
*
* @returns {Promise<Array<{ task: object, view: object }>>}
*/
async function listReviewableTasks(
docClient,
userId,
{ limit = MAX_TASKS_PER_REQUEST, reviewerIsTest = false } = {}
) {
const start = Math.floor(Math.random() * PENDING_SHARDS.length)
const shards = PENDING_SHARDS.map((_, i) => PENDING_SHARDS[(start + i) % PENDING_SHARDS.length])
const found = []
let queries = 0
for (const shard of shards) {
let startKey
while (found.length < limit && queries < QUEUE_QUERY_BUDGET) {
const page = await docClient.send(
new QueryCommand({
TableName: tasksTable(),
IndexName: 'pendingIndex',
KeyConditionExpression: 'pendingShard = :shard',
ExpressionAttributeValues: { ':shard': shard },
Limit: QUEUE_PAGE_SIZE,
ExclusiveStartKey: startKey
})
)
queries++
const candidates = (page.Items || []).filter((task) => task.authorId !== userId)
const voted = await votedTaskIds(
docClient,
userId,
candidates.map((task) => task.taskId)
)
for (const task of candidates) {
if (found.length >= limit) break
if (voted.has(task.taskId)) continue
const subject = getSubject(task.subjectType)
if (!subject) continue
const context = await subject.loadContext(docClient, task)
if (context === null) {
await deleteTask(docClient, task.taskId)
continue
}
if (!subject.isReviewable(context)) {
await discardTask(docClient, { task, subject, context })
continue
}
// Even if deciding fails again, a vote on it would only retry the same
if (decisionFor(task, subject)) {
await settleReachedDecision(docClient, { task, subject, context })
continue
}
// Not reviewable by everyone (e.g. a real/test split) — reviewable as
// such, so left in the queue for whoever it is meant for, not discarded.
if (
subject.isVisibleToReviewer &&
!subject.isVisibleToReviewer(context, { reviewerIsTest })
) {
continue
}
found.push({ task, view: subject.describe(context) })
}
if (!page.LastEvaluatedKey) break
startKey = page.LastEvaluatedKey
}
if (found.length >= limit || queries >= QUEUE_QUERY_BUDGET) break
}
return shuffle(found)
}
// ─── Submission ───────────────────────────────────────────────────────────────
/**
* Prepares the moderation part of a subject's creation: the task to put, and
* the spend of the author's review points. The caller adds both to the
* subject's own TransactWrite, so a refused submission never spends points and
* an accepted one always does.
*
* The quota is waived when the author has too few points but there is nothing
* (or too little) for them to review — quiet hours, launch, a small community —
* since nobody could ever publish otherwise. That existence check must use the
* same real/test split as the review queue itself (`authorIsTest`): otherwise
* an e2e test author's queue would always look empty (real content is invisible
* to them) and the quota would always be waived, never actually exercised.
*
* @returns {Promise<
* { ok: false, required: number, have: number } |
* { ok: true, waived: boolean, have: number, taskItem: object, spendItem: object | null }
* >}
*/
async function prepareSubmission(
docClient,
{ subjectType, subjectId, authorId, scopeFlowId, subjectRef, authorIsTest = false }
) {
const subject = getSubject(subjectType)
if (!subject) throw new Error(`Unknown moderation subject type: ${subjectType}`)
const required = subject.quotaCost
const stats = await getStats(docClient, authorId)
let waived = false
if (stats.reviewPoints < required) {
const reviewable = await listReviewableTasks(docClient, authorId, {
limit: required,
reviewerIsTest: authorIsTest
})
if (reviewable.length >= required) {
return { ok: false, required, have: stats.reviewPoints }
}
waived = true
}
const createdAt = new Date().toISOString()
const taskId = taskIdFor(subjectType, subjectId)
const taskItem = {
Put: {
TableName: tasksTable(),
Item: {
taskId,
subjectType,
subjectId,
subjectRef,
authorId,
scopeFlowId,
status: TASK_STATUS.PENDING,
approveVotes: 0,
rejectVotes: 0,
createdAt,
pendingShard: randomShard(),
sortKey: `${createdAt}#${taskId}`
},
ConditionExpression: 'attribute_not_exists(taskId)'
}
}
const spendItem = waived
? null
: {
Update: {
TableName: statsTable(),
Key: { userId: authorId },
UpdateExpression: 'ADD reviewPoints :spent',
// A missing row has no points: the condition fails, as it should
ConditionExpression: 'reviewPoints >= :required',
ExpressionAttributeValues: { ':spent': -required, ':required': required }
}
}
return { ok: true, waived, have: stats.reviewPoints, taskItem, spendItem }
}
// ─── Decision ─────────────────────────────────────────────────────────────────
/** Every vote cast on a task (at most `maxVotes`: a bounded Query on the partition). */
async function loadVotes(docClient, taskId) {
const result = await docClient.send(
new QueryCommand({
TableName: votesTable(),
KeyConditionExpression: 'taskId = :taskId',
ExpressionAttributeValues: { ':taskId': taskId }
})
)
return result.Items || []
}
/**
* Decides a task: the task's own update, the subject's writes, when votes are
* given every voter's reputation and, when the subject asks for it, the
* author's notification — one transaction, so a decision applies (and is
* notified) exactly once and never half-way. The task update is conditioned on
* `pending`: of two requests finalizing concurrently, one wins and the other is
* told so. The notification is then pushed live, best-effort.
*
* @returns {Promise<{ decided: true } | { decided: false, reason: 'already-decided' | 'subject-changed' }>}
*/
async function finalizeTask(docClient, { task, decision, subject, context, votes }) {
const nowMs = Date.now()
const items = [
{
Update: {
TableName: tasksTable(),
Key: { taskId: task.taskId },
UpdateExpression:
'SET #status = :decision, decidedAt = :now, expiresAt = :expiresAt REMOVE pendingShard',
ConditionExpression: '#status = :pending',
ExpressionAttributeNames: { '#status': 'status' },
ExpressionAttributeValues: {
':decision': decision,
':pending': TASK_STATUS.PENDING,
':now': new Date(nowMs).toISOString(),
':expiresAt': Math.floor(nowMs / 1000) + DECIDED_TASK_TTL_SECONDS
}
}
},
...subject.buildDecisionWrites(task, decision, context)
]
for (const vote of votes || []) {
const agreed = voteMatchesDecision(vote.vote, decision)
items.push({
Update: {
TableName: statsTable(),
Key: { userId: vote.userId },
UpdateExpression: 'ADD reputationScore :reputation, votesAgreed :agreed',
ExpressionAttributeValues: {
':reputation': agreed ? REPUTATION_AGREE : REPUTATION_DISAGREE,
':agreed': agreed ? 1 : 0
}
}
})
}
const content = subject.buildAuthorNotification?.(task, decision, context) ?? null
const delivery = content ? buildNotificationWrites(task.authorId, content) : null
if (delivery) items.push(...delivery.writes)
try {
await docClient.send(new TransactWriteCommand({ TransactItems: items }))
} catch (error) {
if (!isCanceled(error)) throw error
const reasons = error.CancellationReasons || []
if (reasons[0]?.Code === 'ConditionalCheckFailed') {
return { decided: false, reason: 'already-decided' }
}
// The task was fine but the subject no longer is (deleted, or decided by
// other means): nothing left to moderate.
if (reasons.some((r) => r?.Code === 'ConditionalCheckFailed')) {
await deleteTask(docClient, task.taskId)
return { decided: false, reason: 'subject-changed' }
}
throw error
}
if (delivery) await pushNotification(task.authorId, delivery.notification)
return { decided: true }
}
/** A vote ('approve' | 'reject') agrees with a decision ('approved' | 'rejected') when it names the same side. */
function voteMatchesDecision(vote, decision) {
return (vote === 'approve') === (decision === DECISION.APPROVED)
}
/** The side that reached the subject's threshold, if any. */
function decisionFor(task, subject) {
if ((task.approveVotes || 0) >= subject.requiredVotes) return DECISION.APPROVED
if ((task.rejectVotes || 0) >= subject.requiredVotes) return DECISION.REJECTED
return null
}
/**
* Decides a task left pending with its threshold already reached — its deciding
* transaction failed after the last vote was recorded. Nothing to do for a task
* still short of its threshold, or no longer pending.
*
* @returns {Promise<string | null>} the decision this call applied, or null
*/
async function settleReachedDecision(docClient, { task, subject, context }) {
if (task.status !== TASK_STATUS.PENDING) return null
const decision = decisionFor(task, subject)
if (!decision) return null
const votes = await loadVotes(docClient, task.taskId)
const outcome = await finalizeTask(docClient, { task, decision, subject, context, votes })
return outcome.decided ? decision : null
}
/**
* Records a vote and, if it completes the consensus, decides the task. A task
* found with its threshold already reached is decided instead, without
* recording a vote that could not count anyway.
*
* @param {{ userId: string, taskId: string, vote: 'approve' | 'reject' }} params
* @returns {Promise<
* { ok: true, status: string } |
* { ok: false, code: 'INVALID_VOTE' | 'NOT_FOUND' | 'OWN_CONTENT' | 'TASK_DECIDED' | 'NOT_REVIEWABLE' | 'ALREADY_VOTED' }
* >}
*/
async function castVote(docClient, { userId, taskId, vote }) {
if (vote !== 'approve' && vote !== 'reject') return { ok: false, code: 'INVALID_VOTE' }
const taskResult = await docClient.send(
new GetCommand({ TableName: tasksTable(), Key: { taskId }, ConsistentRead: true })
)
const task = taskResult.Item
if (!task) return { ok: false, code: 'NOT_FOUND' }
if (task.status !== TASK_STATUS.PENDING) return { ok: false, code: 'TASK_DECIDED' }
// Never on one's own content. Nothing else bars a vote: not reputation, not
// an owner's block — see docs/architecture/MODERATION.md "Principles".
if (task.authorId === userId) return { ok: false, code: 'OWN_CONTENT' }
const subject = getSubject(task.subjectType)
if (!subject) return { ok: false, code: 'NOT_FOUND' }
const context = await subject.loadContext(docClient, task)
if (context === null) {
await deleteTask(docClient, taskId)
return { ok: false, code: 'NOT_FOUND' }
}
if (!subject.isReviewable(context)) {
await discardTask(docClient, { task, subject, context })
return { ok: false, code: 'NOT_REVIEWABLE' }
}
if (decisionFor(task, subject)) {
await settleReachedDecision(docClient, { task, subject, context })
return { ok: false, code: 'TASK_DECIDED' }
}
const voteField = vote === 'approve' ? 'approveVotes' : 'rejectVotes'
try {
await docClient.send(
new TransactWriteCommand({
TransactItems: [
{
Put: {
TableName: votesTable(),
Item: {
taskId,
userId,
vote,
createdAt: new Date().toISOString(),
expiresAt: Math.floor(Date.now() / 1000) + VOTE_TTL_SECONDS
},
ConditionExpression: 'attribute_not_exists(taskId)'
}
},
{
Update: {
TableName: tasksTable(),
Key: { taskId },
UpdateExpression: 'ADD #votes :one',
ConditionExpression: '#status = :pending',
ExpressionAttributeNames: { '#votes': voteField, '#status': 'status' },
ExpressionAttributeValues: { ':one': 1, ':pending': TASK_STATUS.PENDING }
}
},
{
Update: {
TableName: statsTable(),
Key: { userId },
UpdateExpression: 'ADD reviewPoints :one, votesCast :one',
ExpressionAttributeValues: { ':one': 1 }
}
}
]
})
)
} catch (error) {
if (!isCanceled(error)) throw error
const reasons = error.CancellationReasons || []
if (reasons[0]?.Code === 'ConditionalCheckFailed') return { ok: false, code: 'ALREADY_VOTED' }
if (reasons[1]?.Code === 'ConditionalCheckFailed') return { ok: false, code: 'TASK_DECIDED' }
throw error
}
// Read the counters back (they are only known after the write) and decide if
// this vote completed the consensus. Two concurrent last votes may both see
// the threshold: finalizeTask lets exactly one apply it.
const fresh = await docClient.send(
new GetCommand({ TableName: tasksTable(), Key: { taskId }, ConsistentRead: true })
)
if (!fresh.Item) return { ok: true, status: TASK_STATUS.PENDING }
const decision = await settleReachedDecision(docClient, { task: fresh.Item, subject, context })
return { ok: true, status: decision ?? TASK_STATUS.PENDING }
}
// ─── My submissions ───────────────────────────────────────────────────────────
/**
* The user's own recent submissions with their status, newest first. Decided
* tasks stay for DECIDED_TASK_TTL_SECONDS, so this is recent history.
*
* @returns {Promise<{ tasks: object[], lastEvaluatedKey: object | undefined }>}
*/
async function listSubmissions(docClient, userId, { limit, exclusiveStartKey }) {
const result = await docClient.send(
new QueryCommand({
TableName: tasksTable(),
IndexName: 'authorIndex',
KeyConditionExpression: 'authorId = :authorId',
ExpressionAttributeValues: { ':authorId': userId },
ScanIndexForward: false,
Limit: limit,
ExclusiveStartKey: exclusiveStartKey
})
)
return { tasks: result.Items || [], lastEvaluatedKey: result.LastEvaluatedKey }
}
module.exports = {
TASK_STATUS,
taskIdFor,
getStats,
listReviewableTasks,
prepareSubmission,
castVote,
settleReachedDecision,
listSubmissions,
// exposed for tests
finalizeTask,
discardTask,
decisionFor,
shuffle
}
|