All files / items timer.js

100% Statements 58/58
90.32% Branches 28/31
100% Functions 6/6
100% Lines 54/54

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                            1x 1x 1x 1x 1x 1x 1x 1x   1x 1x     4x         4x 4x                   2x                 15x 15x 2x 2x     13x       13x   11x     11x     11x 1x 1x     10x 10x         10x 3x 3x 2x     7x 7x 7x                                 7x 7x 7x 7x 7x 7x       44x     44x   44x           2x 1x       5x 5x                   5x 5x 5x 5x                                         1x     5x     1x  
// @implements UC-WORKFLOW-009.1
/**
 * Wake-up of an item waiting on a timer of an automatic workflow transition,
 * invoked by its EventBridge Scheduler one-time schedule (see
 * utils/wakeUpScheduler.js) with `{ entityId, itemId, wakeUpAt }`.
 *
 * Evaluates the automatic transitions of the item's states, exactly as a save
 * would (items/workflow-transitions.js) — time may have made a condition true —
 * writes the item once and schedules its next wake-up, if a state it moved
 * into has a timer. Paid by the flow owner — nobody else triggered it: with a
 * zero balance, it does nothing and schedules nothing more until the item is
 * saved again (docs/architecture/AUTOMATION.md "Credits").
 */
 
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb')
const { DynamoDBDocumentClient, GetCommand, UpdateCommand } = require('@aws-sdk/lib-dynamodb')
const { resolveAutomaticTransitions, SYSTEM_ACTOR } = require('./workflow-transitions')
const { loadLinkedItems } = require('../utils/expressions/linkedItems')
const { scheduleWakeUpSafely } = require('../utils/wakeUpScheduler')
const { getCreditsBalance, debitCredits } = require('../utils/creditsLedger')
const { getPricingConfig } = require('../utils/pricingConfig')
const { getConsumedCapacity } = require('../shared/usage-tracking')
 
const client = new DynamoDBClient({})
const docClient = DynamoDBDocumentClient.from(client)
 
function isConditionalCheckFailed(error) {
  return error?.name === 'ConditionalCheckFailedException'
}
 
// Clears a wake-up that won't run, so the item's next save schedules it again
async function dropWakeUp(entityId, itemId, wakeUpAt) {
  try {
    await docClient.send(
      new UpdateCommand({
        TableName: process.env.TABLE_NAME,
        Key: { entityId, id: itemId },
        UpdateExpression: 'SET wakeUpAt = :none',
        ConditionExpression: 'wakeUpAt = :wakeUpAt',
        ExpressionAttributeValues: { ':none': null, ':wakeUpAt': wakeUpAt }
      })
    )
  } catch (error) {
    if (!isConditionalCheckFailed(error)) throw error
  }
}
 
/**
 * @param {{ entityId?: string, itemId?: string, wakeUpAt?: string }} event
 * @returns {Promise<{ status: string, fired?: number }>}
 */
async function timerHandler(event) {
  const { entityId, itemId, wakeUpAt } = event || {}
  if (!entityId || !itemId || !wakeUpAt) {
    console.error('Invalid wake-up event:', JSON.stringify(event))
    return { status: 'invalid' }
  }
 
  const { Item: item } = await docClient.send(
    new GetCommand({ TableName: process.env.TABLE_NAME, Key: { entityId, id: itemId } })
  )
  // Deleted since, or saved with another wake-up: this one is stale
  if (!item || item.wakeUpAt !== wakeUpAt) return { status: 'stale' }
 
  const { Item: entity } = await docClient.send(
    new GetCommand({ TableName: process.env.ENTITIES_TABLE_NAME, Key: { id: entityId } })
  )
  const { Item: flow } = await docClient.send(
    new GetCommand({ TableName: process.env.FLOWS_TABLE_NAME, Key: { id: item.flowId } })
  )
  if (!entity || !flow?.ownerId) {
    await dropWakeUp(entityId, itemId, wakeUpAt)
    return { status: 'orphan' }
  }
 
  const ownerId = flow.ownerId
  const { balance, isPlatformAdmin } = await getCreditsBalance(
    docClient,
    process.env.USERS_TABLE_NAME,
    ownerId
  )
  if (!isPlatformAdmin && balance <= 0) {
    console.error(`Wake-up skipped: flow owner ${ownerId} has no credits left`, itemId)
    await dropWakeUp(entityId, itemId, wakeUpAt)
    return { status: 'no-credits' }
  }
 
  const fields = entity.fields || []
  const now = new Date().toISOString()
  const automatic = resolveAutomaticTransitions({
    fields,
    before: item,
    after: item,
    actor: SYSTEM_ACTOR,
    now,
    wakeUp: true,
    linked: await loadLinkedItems({
      docClient,
      entitiesTableName: process.env.ENTITIES_TABLE_NAME,
      itemsTableName: process.env.TABLE_NAME,
      fields,
      item,
      flowId: item.flowId
    })
  })
 
  const attributes = { ...automatic.changes, ...automatic.system }
  if (automatic.fired > 0) attributes.updatedAt = now
  const entries = Object.entries(attributes)
  Eif (entries.length > 0) {
    try {
      await docClient.send(
        new UpdateCommand({
          TableName: process.env.TABLE_NAME,
          Key: { entityId, id: itemId },
          UpdateExpression: `SET ${entries.map((_, i) => `#a${i} = :v${i}`).join(', ')}`,
          // A save since the read decided the item's next wake-up itself
          ConditionExpression: 'wakeUpAt = :expected',
          ExpressionAttributeNames: Object.fromEntries(entries.map(([key], i) => [`#a${i}`, key])),
          ExpressionAttributeValues: {
            ...Object.fromEntries(entries.map(([, value], i) => [`:v${i}`, value])),
            ':expected': wakeUpAt
          }
        })
      )
    } catch (error) {
      if (isConditionalCheckFailed(error)) return { status: 'stale' }
      throw error
    }
  }
 
  Eif ('wakeUpAt' in automatic.system) {
    await scheduleWakeUpSafely({
      entityId,
      itemId,
      wakeUpAt: automatic.system.wakeUpAt,
      docClient,
      itemsTableName: process.env.TABLE_NAME
    })
  }
 
  // Best-effort, like every post-write debit (docs/architecture/USAGE_METERING.md)
  try {
    const pricing = await getPricingConfig(docClient, process.env.PRICING_CONFIG_TABLE_NAME)
    const { writeUnits } = getConsumedCapacity()
    await debitCredits(docClient, {
      usersTableName: process.env.USERS_TABLE_NAME,
      creditsLedgerTableName: process.env.CREDITS_LEDGER_TABLE_NAME,
      userId: ownerId,
      flowId: item.flowId,
      charges: [
        {
          pool: 'lambda_compute',
          operation: 'item_wake_up',
          costCredits: pricing.automation_wake_up_credits,
          referenceId: itemId
        },
        {
          pool: 'dynamodb_throughput',
          operation: 'item_wake_up',
          costCredits: Math.ceil(writeUnits * pricing.dynamodb_throughput_credits_per_wru),
          referenceId: itemId
        }
      ]
    })
  } catch (error) {
    console.error('Failed to debit credits for item wake-up:', error)
  }
 
  return { status: 'done', fired: automatic.fired }
}
 
exports.handler = timerHandler