All files / entities delete-export-job.js

88.46% Statements 23/26
92.85% Branches 13/14
100% Functions 2/2
88.46% Lines 23/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 681x 1x 1x 1x   1x     6x                     9x 9x 9x 9x       9x 9x 9x 4x                     5x 2x     3x 2x 2x             1x       3x   3x             1x  
const { getActiveFlowId } = require('../shared/activeFlow')
const { S3Client, DeleteObjectCommand } = require('@aws-sdk/client-s3')
const { requirePermission } = require('../utils/requirePermission')
const { getJob, deleteJob } = require('../utils/jobsTable')
 
const s3Client = new S3Client({})
 
function jsonResponse(statusCode, body) {
  return {
    statusCode,
    headers: {
      'Content-Type': 'application/json',
      'Access-Control-Allow-Origin': '*'
    },
    body: JSON.stringify(body)
  }
}
 
async function deleteExportJobHandler(event) {
  try {
    const flowId = await getActiveFlowId(event)
    const userId = event.requestContext?.authorizer?.claims?.sub
    Iif (!flowId) {
      return jsonResponse(401, { error: 'Missing flow context' })
    }
 
    const jobId = event.pathParameters?.jobId
    const job = await getJob(jobId)
    if (!job || job.type !== 'export' || job.flowId !== flowId || job.userId !== userId) {
      return jsonResponse(404, { error: 'Export job not found' })
    }
 
    // The worker's own writes (markJobProcessing/updateJobProgress/
    // markJobCompleted) are unconditional UpdateCommands with no
    // ConditionExpression — deleting the row while the worker is still
    // mid-flight would let its next write resurrect a partial row after this
    // call returns, and its S3 upload would still land, orphaned. Blocking
    // delete until the job is terminal (the worker's last write for a given
    // job is always its own markJobCompleted/markJobFailed) avoids that
    // entirely without needing to touch the worker's already-shipped code.
    if (job.status === 'pending' || job.status === 'processing') {
      return jsonResponse(409, { error: 'Cannot delete a job that is still in progress' })
    }
 
    if (job.result?.zipKey) {
      try {
        await s3Client.send(
          new DeleteObjectCommand({
            Bucket: process.env.ATTACHMENTS_BUCKET_NAME,
            Key: job.result.zipKey
          })
        )
      } catch (error) {
        console.error('[delete-export-job] Could not delete zip from S3:', error.message)
      }
    }
 
    await deleteJob(jobId)
 
    return { statusCode: 204, headers: { 'Access-Control-Allow-Origin': '*' }, body: '' }
  } catch (error) {
    console.error('[delete-export-job] Exception:', error.message, error.stack)
    return jsonResponse(500, { error: 'Failed to delete export job' })
  }
}
 
exports.handler = requirePermission(deleteExportJobHandler, { permission: 'entities:list' })