All files / automation dispatcher.js

100% Statements 85/85
90.56% Branches 48/53
100% Functions 9/9
100% Lines 72/72

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 175 176 177 178 179 180 181 182 183 184 185 186                                      1x 1x 1x 1x 1x 1x 1x 1x   1x 1x   1x                   18x 18x 18x 17x 17x   15x 14x 14x 26x                   18x                       13x 13x   12x 12x 11x     11x 11x 11x 11x 28x 10x 10x               10x   10x     11x 11x 59x 21x 30x   21x 29x 28x 20x                     20x 20x               11x       5x 6x 6x     20x               6x   1x                   8x 8x 12x 7x     7x   12x     8x 8x 15x 14x 14x 13x 13x 13x     8x 7x     1x 1x 1x  
// @implements UC-WORKFLOW-011.1
/**
 * Dispatcher of the Email actions of workflow transitions, fed by the
 * ItemsTable DynamoDB stream (NEW_AND_OLD_IMAGES). See
 * docs/architecture/AUTOMATION.md "Email actions".
 *
 * A write that moved a workflow field records the states it went through in
 * `lastTransitionPath[fieldId]` and who fired each step in
 * `lastTransitionActors[fieldId]` (items/workflow-transitions.js); every step
 * of that path is a transition whose actions run — intermediate steps of an
 * automatic chain included. A field moved by this write is told apart from one
 * moved earlier by its `workflowStateEnteredAt`, which only a move changes.
 *
 * An action's `when` is evaluated here, on the item as this write left it. Each
 * action that holds becomes one message of the FIFO email queue, deduplicated
 * by (item, field, move, step, action): a stream batch retried after a failure
 * enqueues nothing twice. The consumer (./email-consumer.js) does the rest.
 */
 
const { createHash } = require('crypto')
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb')
const { DynamoDBDocumentClient, GetCommand } = require('@aws-sdk/lib-dynamodb')
const { SQSClient, SendMessageBatchCommand } = require('@aws-sdk/client-sqs')
const { unmarshall } = require('@aws-sdk/util-dynamodb')
const { evaluateCondition } = require('../utils/expressions/condition')
const { loadLinkedItems } = require('../utils/expressions/linkedItems')
const { SYSTEM_ACTOR } = require('../items/workflow-transitions')
 
const docClient = DynamoDBDocumentClient.from(new DynamoDBClient({}))
const sqsClient = new SQSClient({})
 
const SQS_BATCH_SIZE = 10
 
/**
 * The transitions an item write fired, step by step.
 *
 * @param {object | undefined} oldItem - The item before the write (none on create)
 * @param {object} newItem - The item after the write
 * @returns {{ fieldId: string, from: string, to: string, step: number, actor: string, movedAt: string }[]}
 */
function firedSteps(oldItem, newItem) {
  const steps = []
  const paths = newItem?.lastTransitionPath || {}
  for (const [fieldId, path] of Object.entries(paths)) {
    const movedAt = newItem.workflowStateEnteredAt?.[fieldId]
    if (!Array.isArray(path) || path.length < 2 || !movedAt) continue
    // Moved by an earlier write: this one left the field where it was
    if (oldItem?.workflowStateEnteredAt?.[fieldId] === movedAt) continue
    const actors = newItem.lastTransitionActors?.[fieldId] || []
    for (let step = 0; step < path.length - 1; step++) {
      steps.push({
        fieldId,
        from: path[step],
        to: path[step + 1],
        step,
        actor: actors[step] ?? SYSTEM_ACTOR,
        movedAt
      })
    }
  }
  return steps
}
 
/**
 * The Email action messages of one item write.
 *
 * @param {object | undefined} oldItem
 * @param {object} newItem
 * @param {(entityId: string) => Promise<object | undefined>} getEntity
 * @returns {Promise<object[]>} queue messages: { id, body, groupId, deduplicationId }
 */
async function messagesForWrite(oldItem, newItem, getEntity) {
  const steps = firedSteps(oldItem, newItem)
  if (steps.length === 0) return []
 
  const entity = await getEntity(newItem.entityId)
  if (!entity) return []
  const fields = entity.fields || []
 
  let linked
  let linkedLoaded = false
  const compiled = new Map()
  const nowMs = Date.now()
  const holds = async (when) => {
    if (when === undefined) return true
    Eif (!linkedLoaded) {
      linked = await loadLinkedItems({
        docClient,
        entitiesTableName: process.env.ENTITIES_TABLE_NAME,
        itemsTableName: process.env.ITEMS_TABLE_NAME,
        fields,
        item: newItem,
        flowId: newItem.flowId
      })
      linkedLoaded = true
    }
    return evaluateCondition(when, newItem, fields, compiled, linked, nowMs)
  }
 
  const messages = []
  for (const step of steps) {
    const field = fields.find((f) => f.fieldId === step.fieldId && f.type === 'workflow')
    const transition = (field?.workflowDefinition?.transitions || []).find(
      (t) => t.from === step.from && t.to === step.to
    )
    for (const action of Array.isArray(transition?.actions) ? transition.actions : []) {
      if (action?.type !== 'email') continue
      if (!(await holds(action.when))) continue
      const body = {
        entityId: newItem.entityId,
        itemId: newItem.id,
        fieldId: step.fieldId,
        from: step.from,
        to: step.to,
        step: step.step,
        actionId: action.id,
        actor: step.actor,
        movedAt: step.movedAt
      }
      const key = [body.itemId, body.fieldId, body.movedAt, body.step, body.actionId].join('#')
      messages.push({
        body,
        // One group per item: an item's emails go out in order, items in parallel
        groupId: body.itemId,
        deduplicationId: createHash('sha256').update(key).digest('hex')
      })
    }
  }
  return messages
}
 
async function sendMessages(messages) {
  for (let i = 0; i < messages.length; i += SQS_BATCH_SIZE) {
    const batch = messages.slice(i, i + SQS_BATCH_SIZE)
    const result = await sqsClient.send(
      new SendMessageBatchCommand({
        QueueUrl: process.env.EMAIL_QUEUE_URL,
        Entries: batch.map((message, index) => ({
          Id: String(index),
          MessageBody: JSON.stringify(message.body),
          MessageGroupId: message.groupId,
          MessageDeduplicationId: message.deduplicationId
        }))
      })
    )
    if (result.Failed?.length) {
      // The stream batch is retried; deduplication drops what was already sent
      throw new Error(`Failed to enqueue ${result.Failed.length} email action(s)`)
    }
  }
}
 
/**
 * @param {{ Records?: object[] }} event - DynamoDB stream event
 * @returns {Promise<{ enqueued: number }>}
 */
async function dispatcherHandler(event) {
  const entities = new Map()
  const getEntity = async (entityId) => {
    if (!entities.has(entityId)) {
      const { Item } = await docClient.send(
        new GetCommand({ TableName: process.env.ENTITIES_TABLE_NAME, Key: { id: entityId } })
      )
      entities.set(entityId, Item)
    }
    return entities.get(entityId)
  }
 
  const messages = []
  for (const record of event?.Records || []) {
    if (record.eventName !== 'INSERT' && record.eventName !== 'MODIFY') continue
    const image = record.dynamodb || {}
    if (!image.NewImage) continue
    const newItem = unmarshall(image.NewImage)
    const oldItem = image.OldImage ? unmarshall(image.OldImage) : undefined
    messages.push(...(await messagesForWrite(oldItem, newItem, getEntity)))
  }
 
  if (messages.length > 0) await sendMessages(messages)
  return { enqueued: messages.length }
}
 
exports.handler = dispatcherHandler
exports.firedSteps = firedSteps
exports.messagesForWrite = messagesForWrite