All files / utils commentCleanup.js

100% Statements 72/72
95.55% Branches 43/45
100% Functions 13/13
100% Lines 67/67

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                          13x 13x 13x 13x 13x 13x       53x   53x 54x 54x 54x   53x                                                     15x               15x     18x     15x 14x       17x 6x       15x 14x           8x           8x     6x                               16x 16x 18x     18x   9x                 9x 9x 4x                     9x 9x   4x 2x 2x     1x 1x   5x                       11x   11x 2x                           9x           9x 4x 4x                     2x   3x                 10x 7x                                     12x           12x 11x     11x 9x             9x     3x       11x 9x             9x     2x       11x 9x               145x 6x                 13x              
/**
 * Cleanup of comments and their moderation footprint when the things they hang
 * from disappear: an item, an entity, a flow or the author's own account.
 *
 * @implements UC-COMMENT-010.1, UC-COMMENT-011.1
 */
 
const {
  QueryCommand,
  GetCommand,
  UpdateCommand,
  DeleteCommand,
  TransactWriteCommand
} = require('@aws-sdk/lib-dynamodb')
const { batchDelete } = require('./batchWrite')
const { deleteCommentCount, adjustCommentCount } = require('./commentCount')
const { taskIdFor } = require('./moderation/taskId')
const { COMMENT_STATUS } = require('./comments')
const { SUBJECT_TYPE } = require('./moderation/constants')
 
/** Every row of a Query, following its cursor. */
async function queryAll(docClient, params) {
  const items = []
  let lastKey
  do {
    const page = await docClient.send(new QueryCommand({ ...params, ExclusiveStartKey: lastKey }))
    items.push(...(page.Items || []))
    lastKey = page.LastEvaluatedKey
  } while (lastKey)
  return items
}
 
/**
 * Deletes every comment of an item that is truly gone (item delete, "clear all",
 * or the item's entity or flow being deleted), its comment counter, and the
 * moderation task of each comment still awaiting review.
 *
 * CommentsTable is keyed itemId-first, so this is a direct Query on the
 * partition key — like deleteAllLikesForItem. Votes are not chased: they
 * expire on their own (TTL), and a task of a deleted comment that this misses
 * is discarded when a reviewer would meet it. See docs/architecture/MODERATION.md.
 *
 * Also serves a deleted store pack: a pack's comments are partitioned under
 * its id, with `subjectType` naming their moderation tasks.
 *
 * @param {import('@aws-sdk/lib-dynamodb').DynamoDBDocumentClient} docClient
 * @param {{ commentsTableName: string, commentCountTableName?: string, moderationTasksTableName?: string }} tables
 * @param {string} itemId the thread key: an item id, or a pack id
 * @param {string} [subjectType] the moderation subject of the thread's comments
 */
async function deleteAllCommentsForItem(
  docClient,
  { commentsTableName, commentCountTableName, moderationTasksTableName },
  itemId,
  subjectType = SUBJECT_TYPE.ITEM_COMMENT
) {
  const comments = await queryAll(docClient, {
    TableName: commentsTableName,
    KeyConditionExpression: 'itemId = :itemId',
    ExpressionAttributeValues: { ':itemId': itemId },
    ProjectionExpression: 'itemId, id, #status',
    ExpressionAttributeNames: { '#status': 'status' }
  })
 
  await batchDelete(
    docClient,
    commentsTableName,
    comments.map((comment) => ({ itemId: comment.itemId, id: comment.id }))
  )
 
  if (moderationTasksTableName) {
    await batchDelete(
      docClient,
      moderationTasksTableName,
      comments
        .filter((comment) => comment.status === COMMENT_STATUS.PENDING)
        .map((comment) => ({ taskId: taskIdFor(subjectType, comment.id) }))
    )
  }
 
  if (commentCountTableName) {
    await deleteCommentCount(docClient, commentCountTableName, itemId)
  }
}
 
/** Deletes the list of users blocked from commenting on an entity, or a pack, that is gone. */
async function deleteAllCommentBlocksForEntity(docClient, tableName, entityId) {
  const blocks = await queryAll(docClient, {
    TableName: tableName,
    KeyConditionExpression: 'entityId = :entityId',
    ExpressionAttributeValues: { ':entityId': entityId },
    ProjectionExpression: 'entityId, userId'
  })
  await batchDelete(
    docClient,
    tableName,
    blocks.map((block) => ({ entityId: block.entityId, userId: block.userId }))
  )
}
 
/**
 * Removes the tombstone `commentId` once it has no reply left — it was only
 * kept for its replies — then climbs the thread: a tombstone is itself a reply,
 * so its own parent may be left an empty tombstone in turn. Called after a
 * reply was removed and its parent's reply counter decremented; does nothing
 * when that parent is not an empty tombstone.
 *
 * Each level is one read and one transaction removing the tombstone and
 * decrementing its parent's counter together: bounded by the depth of the
 * thread, never by its size.
 */
async function removeEmptyTombstones(docClient, commentsTableName, itemId, commentId) {
  let id = commentId
  while (id) {
    const { Item: comment } = await docClient.send(
      new GetCommand({ TableName: commentsTableName, Key: { itemId, id }, ConsistentRead: true })
    )
    if (comment?.status !== COMMENT_STATUS.DELETED || (comment.replyCount || 0) > 0) return
 
    const removal = {
      TableName: commentsTableName,
      Key: { itemId, id },
      // A reply approved meanwhile keeps the tombstone in place
      ConditionExpression:
        '#status = :deleted AND (attribute_not_exists(replyCount) OR replyCount = :zero)',
      ExpressionAttributeNames: { '#status': 'status' },
      ExpressionAttributeValues: { ':deleted': COMMENT_STATUS.DELETED, ':zero': 0 }
    }
    const items = [{ Delete: removal }]
    if (comment.parentId) {
      items.push({
        Update: {
          TableName: commentsTableName,
          Key: { itemId, id: comment.parentId },
          UpdateExpression: 'ADD replyCount :minusOne',
          ConditionExpression: 'replyCount >= :one',
          ExpressionAttributeValues: { ':minusOne': -1, ':one': 1 }
        }
      })
    }
 
    try {
      await docClient.send(new TransactWriteCommand({ TransactItems: items }))
    } catch (error) {
      if (error.name !== 'TransactionCanceledException') throw error
      const reasons = error.CancellationReasons || []
      if (reasons[0]?.Code === 'ConditionalCheckFailed') return
      // The parent is gone or its counter at its floor: the tombstone still
      // goes, but there is no counter left to follow up the thread
      await docClient.send(new DeleteCommand(removal))
      return
    }
    id = comment.parentId
  }
}
 
/**
 * Removes one comment of a user whose account is being deleted, on items that
 * stay. A comment that still has visible replies becomes a tombstone — its text
 * and author erased, the thread intact; any other is deleted, along with the
 * tombstones it leaves without replies. Counters follow, best-effort like the
 * rest of the account cascade.
 */
async function removeAuthoredComment(docClient, tables, comment) {
  const counted = comment.status === COMMENT_STATUS.APPROVED
 
  if (counted && (comment.replyCount || 0) > 0) {
    await docClient.send(
      new UpdateCommand({
        TableName: tables.commentsTableName,
        Key: { itemId: comment.itemId, id: comment.id },
        UpdateExpression: 'SET #status = :deleted REMOVE #body, authorId',
        ConditionExpression: '#status = :approved',
        ExpressionAttributeNames: { '#status': 'status', '#body': 'body' },
        ExpressionAttributeValues: {
          ':deleted': COMMENT_STATUS.DELETED,
          ':approved': COMMENT_STATUS.APPROVED
        }
      })
    )
  } else {
    await docClient.send(
      new DeleteCommand({
        TableName: tables.commentsTableName,
        Key: { itemId: comment.itemId, id: comment.id }
      })
    )
    if (counted && comment.parentId) {
      try {
        await docClient.send(
          new UpdateCommand({
            TableName: tables.commentsTableName,
            Key: { itemId: comment.itemId, id: comment.parentId },
            UpdateExpression: 'ADD replyCount :minusOne',
            ConditionExpression: 'replyCount >= :one',
            ExpressionAttributeValues: { ':minusOne': -1, ':one': 1 }
          })
        )
      } catch (error) {
        // The parent is gone or already at its floor: nothing to decrement
        if (error.name !== 'ConditionalCheckFailedException') throw error
      }
      await removeEmptyTombstones(
        docClient,
        tables.commentsTableName,
        comment.itemId,
        comment.parentId
      )
    }
  }
 
  if (counted && tables.commentCountTableName) {
    await adjustCommentCount(docClient, tables.commentCountTableName, comment.itemId, -1)
  }
}
 
/**
 * Erases a deleted account's comments and moderation footprint: its comments
 * (see removeAuthoredComment), its moderation submissions, its votes and its
 * review points / reputation. Counters that the votes already moved on tasks
 * still pending are not rolled back — see docs/architecture/MODERATION.md.
 *
 * @param {import('@aws-sdk/lib-dynamodb').DynamoDBDocumentClient} docClient
 * @param {{
 *   commentsTableName: string, commentCountTableName?: string,
 *   moderationTasksTableName?: string, moderationVotesTableName?: string,
 *   moderatorStatsTableName?: string
 * }} tables
 * @param {string} userId
 */
async function deleteAllCommentDataForUser(docClient, tables, userId) {
  const comments = await queryAll(docClient, {
    TableName: tables.commentsTableName,
    IndexName: 'authorIndex',
    KeyConditionExpression: 'authorId = :userId',
    ExpressionAttributeValues: { ':userId': userId }
  })
  for (const comment of comments) {
    await removeAuthoredComment(docClient, tables, comment)
  }
 
  if (tables.moderationTasksTableName) {
    const submissions = await queryAll(docClient, {
      TableName: tables.moderationTasksTableName,
      IndexName: 'authorIndex',
      KeyConditionExpression: 'authorId = :userId',
      ExpressionAttributeValues: { ':userId': userId },
      ProjectionExpression: 'taskId'
    })
    await batchDelete(
      docClient,
      tables.moderationTasksTableName,
      submissions.map((task) => ({ taskId: task.taskId }))
    )
  }
 
  if (tables.moderationVotesTableName) {
    const votes = await queryAll(docClient, {
      TableName: tables.moderationVotesTableName,
      IndexName: 'userIndex',
      KeyConditionExpression: 'userId = :userId',
      ExpressionAttributeValues: { ':userId': userId },
      ProjectionExpression: 'taskId, userId'
    })
    await batchDelete(
      docClient,
      tables.moderationVotesTableName,
      votes.map((vote) => ({ taskId: vote.taskId, userId: vote.userId }))
    )
  }
 
  if (tables.moderatorStatsTableName) {
    await docClient.send(
      new DeleteCommand({ TableName: tables.moderatorStatsTableName, Key: { userId } })
    )
  }
}
 
/** The comment cleanup tables the current Lambda is configured with (env), or null when comments are not wired in. */
function commentTablesFromEnv() {
  if (!process.env.COMMENTS_TABLE_NAME) return null
  return {
    commentsTableName: process.env.COMMENTS_TABLE_NAME,
    commentCountTableName: process.env.ITEM_COMMENT_COUNT_TABLE_NAME,
    moderationTasksTableName: process.env.MODERATION_TASKS_TABLE_NAME,
    moderationVotesTableName: process.env.MODERATION_VOTES_TABLE_NAME,
    moderatorStatsTableName: process.env.MODERATOR_STATS_TABLE_NAME
  }
}
 
module.exports = {
  deleteAllCommentsForItem,
  deleteAllCommentBlocksForEntity,
  deleteAllCommentDataForUser,
  removeEmptyTombstones,
  commentTablesFromEnv
}