All files / utils wakeUpScheduler.js

100% Statements 39/39
95.23% Branches 20/21
100% Functions 5/5
100% Lines 33/33

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                                        6x 6x     6x   6x   18x 18x                   17x             10x 10x                           15x 15x   14x 14x 4x 4x   3x   2x     10x                         10x 10x   7x 3x 3x     2x 1x                                   5x 5x   4x 4x 2x 2x                   1x         6x  
// @implements UC-WORKFLOW-009.1
/**
 * One EventBridge Scheduler one-time schedule per item waiting on a timer of
 * an automatic workflow transition (see docs/architecture/AUTOMATION.md
 * "Timers"): created, moved or deleted when the item's `wakeUpAt` changes,
 * and deleted by Scheduler itself once it fired (`ActionAfterCompletion`).
 * Its target, items/timer.js, ignores a wake-up whose `wakeUpAt` is no longer
 * the item's.
 *
 * Needs SCHEDULE_GROUP_NAME, SCHEDULER_ROLE_ARN and TIMER_FUNCTION_ARN; a
 * no-op without them (a lambda outside the full stack, or a test).
 */
 
const {
  SchedulerClient,
  CreateScheduleCommand,
  UpdateScheduleCommand,
  DeleteScheduleCommand,
  ResourceNotFoundException,
  ConflictException
} = require('@aws-sdk/client-scheduler')
const { UpdateCommand } = require('@aws-sdk/lib-dynamodb')
 
// A schedule moment must be in the future: never closer than this
const MIN_DELAY_MS = 60 * 1000
 
let client = null
function getClient() {
  if (!client) client = new SchedulerClient({})
  return client
}
 
/**
 * The schedule name of an item (letters, digits, - and _; 64 characters max).
 *
 * @param {string} itemId
 * @returns {string}
 */
function scheduleName(itemId) {
  return `item-${itemId}`.replace(/[^A-Za-z0-9_-]/g, '_').slice(0, 64)
}
 
// `at(yyyy-mm-ddThh:mm:ss)`, in UTC — rounded up to the second: a wake-up a
// fraction of a second early would find its timer not due yet, and nothing
// would schedule it again
function atExpression(wakeUpAt, nowMs) {
  const ms = Math.max(Date.parse(wakeUpAt), nowMs + MIN_DELAY_MS)
  return `at(${new Date(Math.ceil(ms / 1000) * 1000).toISOString().slice(0, 19)})`
}
 
/**
 * Creates, moves or deletes an item's wake-up schedule.
 *
 * @param {object} params
 * @param {string} params.entityId
 * @param {string} params.itemId
 * @param {string | null} params.wakeUpAt - ISO timestamp, or null for none
 * @param {number} [params.nowMs]
 * @returns {Promise<void>}
 */
async function scheduleWakeUp({ entityId, itemId, wakeUpAt, nowMs = Date.now() }) {
  const { SCHEDULE_GROUP_NAME, SCHEDULER_ROLE_ARN, TIMER_FUNCTION_ARN } = process.env
  if (!SCHEDULE_GROUP_NAME || !SCHEDULER_ROLE_ARN || !TIMER_FUNCTION_ARN) return
 
  const Name = scheduleName(itemId)
  if (!wakeUpAt) {
    try {
      await getClient().send(new DeleteScheduleCommand({ Name, GroupName: SCHEDULE_GROUP_NAME }))
    } catch (error) {
      if (!(error instanceof ResourceNotFoundException)) throw error
    }
    return
  }
 
  const input = {
    Name,
    GroupName: SCHEDULE_GROUP_NAME,
    ScheduleExpression: atExpression(wakeUpAt, nowMs),
    ScheduleExpressionTimezone: 'UTC',
    FlexibleTimeWindow: { Mode: 'OFF' },
    ActionAfterCompletion: 'DELETE',
    Target: {
      Arn: TIMER_FUNCTION_ARN,
      RoleArn: SCHEDULER_ROLE_ARN,
      Input: JSON.stringify({ entityId, itemId, wakeUpAt })
    }
  }
  try {
    await getClient().send(new UpdateScheduleCommand(input))
  } catch (error) {
    if (!(error instanceof ResourceNotFoundException)) throw error
    try {
      await getClient().send(new CreateScheduleCommand(input))
    } catch (createError) {
      // Created concurrently by another write: this one's moment wins
      if (!(createError instanceof ConflictException)) throw createError
      await getClient().send(new UpdateScheduleCommand(input))
    }
  }
}
 
/**
 * scheduleWakeUp, best-effort: a failure is logged, never failing the write
 * that already happened. The item's `wakeUpAt` is then cleared (unless a
 * newer write changed it), so its next save schedules it again — otherwise
 * an unchanged `wakeUpAt` would never be scheduled.
 *
 * @param {Parameters<typeof scheduleWakeUp>[0] & {
 *   docClient?: import('@aws-sdk/lib-dynamodb').DynamoDBDocumentClient,
 *   itemsTableName?: string
 * }} params
 * @returns {Promise<void>}
 */
async function scheduleWakeUpSafely({ docClient, itemsTableName, ...params }) {
  try {
    await scheduleWakeUp(params)
  } catch (error) {
    console.error('Failed to schedule item wake-up:', error)
    if (!params.wakeUpAt || !docClient || !itemsTableName) return
    try {
      await docClient.send(
        new UpdateCommand({
          TableName: itemsTableName,
          Key: { entityId: params.entityId, id: params.itemId },
          UpdateExpression: 'SET wakeUpAt = :none',
          ConditionExpression: 'wakeUpAt = :wakeUpAt',
          ExpressionAttributeValues: { ':none': null, ':wakeUpAt': params.wakeUpAt }
        })
      )
    } catch (resetError) {
      console.error('Failed to reset item wake-up:', resetError)
    }
  }
}
 
module.exports = { scheduleName, scheduleWakeUp, scheduleWakeUpSafely }