All files / utils membershipRequestCleanup.js

100% Statements 28/28
87.5% Branches 14/16
100% Functions 4/4
100% Lines 26/26

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            5x 5x 5x 5x       32x   1x 2x                 2x     2x   2x                           35x   3x 3x                 3x   6x 6x               1x 1x   5x 1x   5x 3x                       2x 1x         3x       5x  
/**
 * Deletes membership requests (docs/architecture/FLOW_SPACE.md) when what they
 * belong to goes away: a deleted flow takes all its requests, a deleted
 * account all of its own (GDPR erasure — the answers are personal data), with
 * their images and files (UC-SPACE-020.1).
 */
const { QueryCommand, DeleteCommand, UpdateCommand } = require('@aws-sdk/lib-dynamodb')
const { batchDelete } = require('./batchWrite')
const { deletePrefix } = require('./s3Cleanup')
const { requestPrefix } = require('./membershipRequestFiles')
 
/** Every request of a flow, a page at a time (the table's partition is the flow) */
async function deleteMembershipRequestsForFlow(docClient, tableName, flowId) {
  if (!tableName) return
  let ExclusiveStartKey
  do {
    const page = await docClient.send(
      new QueryCommand({
        TableName: tableName,
        KeyConditionExpression: 'flowId = :flowId',
        ExpressionAttributeValues: { ':flowId': flowId },
        ProjectionExpression: 'flowId, userId',
        ExclusiveStartKey
      })
    )
    await batchDelete(
      docClient,
      tableName,
      (page.Items || []).map(({ flowId: rowFlowId, userId }) => ({ flowId: rowFlowId, userId }))
    )
    ExclusiveStartKey = page.LastEvaluatedKey
  } while (ExclusiveStartKey)
}
 
/**
 * Every request of a user (GSI `userIndex`), with its files when a bucket is
 * given. A pending one also lowers its flow's pending count, which would
 * otherwise keep counting it forever.
 */
async function deleteMembershipRequestsOfUser(
  docClient,
  { tableName, flowsTableName, s3Client, attachmentsBucketName },
  userId
) {
  if (!tableName) return
  let ExclusiveStartKey
  do {
    const page = await docClient.send(
      new QueryCommand({
        TableName: tableName,
        IndexName: 'userIndex',
        KeyConditionExpression: 'userId = :userId',
        ExpressionAttributeValues: { ':userId': userId },
        ExclusiveStartKey
      })
    )
    for (const { flowId } of page.Items || []) {
      let deleted
      try {
        deleted = await docClient.send(
          new DeleteCommand({
            TableName: tableName,
            Key: { flowId, userId },
            ReturnValues: 'ALL_OLD'
          })
        )
      } catch (error) {
        console.error('Failed to delete membership request:', { flowId, error: error.name })
        continue
      }
      if (s3Client) {
        await deletePrefix(s3Client, attachmentsBucketName, requestPrefix(flowId, userId))
      }
      if (deleted.Attributes?.status === 'pending' && flowsTableName) {
        await docClient
          .send(
            new UpdateCommand({
              TableName: flowsTableName,
              Key: { id: flowId },
              // Never recreates a flow deleted meanwhile
              ConditionExpression: 'attribute_exists(id)',
              UpdateExpression: 'ADD pendingRequestCount :minusOne',
              ExpressionAttributeValues: { ':minusOne': -1 }
            })
          )
          .catch((error) => {
            if (error.name !== 'ConditionalCheckFailedException') {
              console.error('Failed to lower pending request count:', { flowId, error: error.name })
            }
          })
      }
    }
    ExclusiveStartKey = page.LastEvaluatedKey
  } while (ExclusiveStartKey)
}
 
module.exports = { deleteMembershipRequestsForFlow, deleteMembershipRequestsOfUser }