All files / utils jobsTable.js

100% Statements 32/32
92.85% Branches 13/14
100% Functions 10/10
100% Lines 31/31

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 16514x               14x 14x   14x 14x   14x     24x 24x                       24x 23x       152x     152x                         7x                   7x 1x     7x 7x       7x       4x       108x                       177x                     98x                               16x                                                   114x 114x 300x 300x 300x 176x 176x       14x                      
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb')
const {
  DynamoDBDocumentClient,
  PutCommand,
  GetCommand,
  UpdateCommand,
  QueryCommand,
  DeleteCommand
} = require('@aws-sdk/lib-dynamodb')
const { randomUUID } = require('crypto')
 
const client = new DynamoDBClient({})
const docClient = DynamoDBDocumentClient.from(client)
 
const JOB_TTL_SECONDS = 7 * 24 * 60 * 60
 
async function createJob({ type, flowId, userId, request, total }) {
  const timestamp = new Date().toISOString()
  const job = {
    id: randomUUID(),
    type,
    status: 'pending',
    flowId,
    userId,
    request,
    progress: { done: 0, total },
    createdAt: timestamp,
    updatedAt: timestamp,
    expiresAt: Math.floor(Date.now() / 1000) + JOB_TTL_SECONDS
  }
  await docClient.send(new PutCommand({ TableName: process.env.JOBS_TABLE_NAME, Item: job }))
  return job
}
 
async function getJob(id) {
  const result = await docClient.send(
    new GetCommand({ TableName: process.env.JOBS_TABLE_NAME, Key: { id } })
  )
  return result.Item || null
}
 
/**
 * Lists one user's jobs of a given type in a flow, most recent first, via
 * the table's `flowIndex` GSI (partitionKey `flowId`, sortKey `createdAt`).
 * `type`/`userId` are applied as a `FilterExpression` rather than baked into
 * the GSI's key shape — simpler than a second GSI, and fine at the job
 * volumes a single flow/user is expected to accumulate. Follows the same
 * `Limit`/base64 `nextToken`/`LastEvaluatedKey` pagination convention as
 * `roles/list.js`.
 */
async function queryJobsByFlow({ flowId, userId, type, limit, nextToken }) {
  const queryParams = {
    TableName: process.env.JOBS_TABLE_NAME,
    IndexName: 'flowIndex',
    KeyConditionExpression: 'flowId = :flowId',
    FilterExpression: '#type = :type AND userId = :userId',
    ExpressionAttributeNames: { '#type': 'type' },
    ExpressionAttributeValues: { ':flowId': flowId, ':type': type, ':userId': userId },
    ScanIndexForward: false,
    Limit: limit
  }
  if (nextToken) {
    queryParams.ExclusiveStartKey = JSON.parse(Buffer.from(nextToken, 'base64').toString())
  }
 
  const result = await docClient.send(new QueryCommand(queryParams))
  const responseNextToken = result.LastEvaluatedKey
    ? Buffer.from(JSON.stringify(result.LastEvaluatedKey)).toString('base64')
    : null
 
  return { items: result.Items || [], nextToken: responseNextToken }
}
 
async function deleteJob(id) {
  await docClient.send(new DeleteCommand({ TableName: process.env.JOBS_TABLE_NAME, Key: { id } }))
}
 
async function markJobProcessing(id) {
  await docClient.send(
    new UpdateCommand({
      TableName: process.env.JOBS_TABLE_NAME,
      Key: { id },
      UpdateExpression: 'SET #status = :status, updatedAt = :updatedAt',
      ExpressionAttributeNames: { '#status': 'status' },
      ExpressionAttributeValues: { ':status': 'processing', ':updatedAt': new Date().toISOString() }
    })
  )
}
 
async function updateJobProgress(id, progress) {
  await docClient.send(
    new UpdateCommand({
      TableName: process.env.JOBS_TABLE_NAME,
      Key: { id },
      UpdateExpression: 'SET progress = :progress, updatedAt = :updatedAt',
      ExpressionAttributeValues: { ':progress': progress, ':updatedAt': new Date().toISOString() }
    })
  )
}
 
async function markJobCompleted(id, result) {
  await docClient.send(
    new UpdateCommand({
      TableName: process.env.JOBS_TABLE_NAME,
      Key: { id },
      UpdateExpression: 'SET #status = :status, #result = :result, updatedAt = :updatedAt',
      ExpressionAttributeNames: { '#status': 'status', '#result': 'result' },
      ExpressionAttributeValues: {
        ':status': 'completed',
        ':result': result,
        ':updatedAt': new Date().toISOString()
      }
    })
  )
}
 
async function markJobFailed(id, errorMessage) {
  await docClient.send(
    new UpdateCommand({
      TableName: process.env.JOBS_TABLE_NAME,
      Key: { id },
      UpdateExpression: 'SET #status = :status, #error = :error, updatedAt = :updatedAt',
      ExpressionAttributeNames: { '#status': 'status', '#error': 'error' },
      ExpressionAttributeValues: {
        ':status': 'failed',
        ':error': errorMessage,
        ':updatedAt': new Date().toISOString()
      }
    })
  )
}
 
/**
 * Returns a `report(done, total)` function that writes progress to the job
 * record at most once per `minIntervalMs` (default 1s) — a bundle can have
 * thousands of units of work, and the frontend only polls every few seconds
 * anyway. `total` is passed on each call rather than fixed upfront, since for
 * some jobs (e.g. export, whose image count isn't known until discovery/
 * stripping has run) it's only discovered partway through. The final call
 * (`done === total`) always writes, regardless of throttling, so the job's
 * last-known progress is never stale once work actually finishes.
 */
function createThrottledProgressReporter(jobId, { minIntervalMs = 1000 } = {}) {
  let lastWriteAt = 0
  return async function report(done, total) {
    const isFinal = done >= total
    const now = Date.now()
    if (!isFinal && now - lastWriteAt < minIntervalMs) return
    lastWriteAt = now
    await updateJobProgress(jobId, { done, total })
  }
}
 
module.exports = {
  createJob,
  getJob,
  queryJobsByFlow,
  deleteJob,
  markJobProcessing,
  updateJobProgress,
  markJobCompleted,
  markJobFailed,
  createThrottledProgressReporter
}