All files / store notify-worker.js

100% Statements 58/58
93.54% Branches 29/31
100% Functions 9/9
100% Lines 47/47

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                                        1x           1x 1x 1x         1x   1x 1x     1x 1x   12x 15x       7x 7x 6x   11x         6x 9x 9x 9x 9x   6x 5x               5x                   5x 5x                                     2x 1x   3x 3x       9x 9x   7x                     7x   27x   11x 6x 6x 8x 8x 5x     5x 1x             5x     1x 9x 9x       1x  
/**
 * SQS-driven: tells the owner of each flow that installed a pack that a new
 * version is out, linking to the pack page, where its copies can be updated
 * (UC-STORE-013.1). Queued by store/publish.js for a new version, never for a
 * new pack. The flows that installed it are unbounded: one message notifies a
 * page of them, then queues the next page.
 *
 * - Only flows whose copies the pack remembers (`copyEntityIds`) are told:
 *   the others are never offered the update.
 * - Exactly once per flow and version: the notification is written in one
 *   transaction with `notifiedVersion` on the flow's `PackImportsTable` row,
 *   conditional on it being lower, so a retried message tells no one twice.
 * - A pack deleted, or moved to another version meanwhile, stops the run: the
 *   newer version's own run tells the flows about it.
 *
 * Message: { packId, version, cursor? }
 *
 * @implements UC-STORE-013.1
 */
 
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb')
const {
  DynamoDBDocumentClient,
  BatchGetCommand,
  QueryCommand,
  TransactWriteCommand
} = require('@aws-sdk/lib-dynamodb')
const { SQSClient, SendMessageCommand } = require('@aws-sdk/client-sqs')
const { getPack } = require('../utils/packs')
const {
  NOTIFICATION_TYPE,
  buildNotificationWrites,
  pushNotification
} = require('../utils/notifications')
 
const docClient = DynamoDBDocumentClient.from(new DynamoDBClient({}))
const sqsClient = new SQSClient({})
 
/** Flows told per message: one Query page, one BatchGet, a transaction each. */
const PAGE_SIZE = 25
const BATCH_GET_MAX_ATTEMPTS = 3
 
const importsTable = () => process.env.PACK_IMPORTS_TABLE_NAME
const flowsTable = () => process.env.FLOWS_TABLE_NAME
 
/** The flows of the page, by id: their owner and name only. */
async function getFlows(flowIds) {
  const flows = new Map()
  if (flowIds.length === 0) return flows
  let request = {
    [flowsTable()]: {
      Keys: flowIds.map((id) => ({ id })),
      ProjectionExpression: 'id, ownerId, #name',
      ExpressionAttributeNames: { '#name': 'name' }
    }
  }
  for (let attempt = 0; attempt < BATCH_GET_MAX_ATTEMPTS && request; attempt++) {
    const result = await docClient.send(new BatchGetCommand({ RequestItems: request }))
    for (const flow of result.Responses?.[flowsTable()] || []) flows.set(flow.id, flow)
    const unprocessed = result.UnprocessedKeys
    request = unprocessed && Object.keys(unprocessed).length > 0 ? unprocessed : null
  }
  if (request) throw new Error('Could not read the flows that installed the pack')
  return flows
}
 
/**
 * Tells one flow's owner, unless this version already did. Returns whether
 * a notification was written.
 */
async function notifyFlow(pack, version, flow) {
  const { notification, writes } = buildNotificationWrites(flow.ownerId, {
    type: NOTIFICATION_TYPE.PACK_VERSION_PUBLISHED,
    data: {
      packId: pack.id,
      packName: pack.name,
      version,
      flowId: flow.id,
      flowName: flow.name
    }
  })
  try {
    await docClient.send(
      new TransactWriteCommand({
        TransactItems: [
          {
            Update: {
              TableName: importsTable(),
              Key: { packId: pack.id, flowId: flow.id },
              UpdateExpression: 'SET notifiedVersion = :version',
              ConditionExpression:
                'attribute_exists(packId) AND (attribute_not_exists(notifiedVersion) OR notifiedVersion < :version)',
              ExpressionAttributeValues: { ':version': version }
            }
          },
          ...writes
        ]
      })
    )
  } catch (error) {
    // Told already, or the pack's cleanup removed the row meanwhile
    if (error.name === 'TransactionCanceledException') return false
    throw error
  }
  await pushNotification(flow.ownerId, notification)
  return true
}
 
async function notifyPage({ packId, version, cursor }) {
  const pack = await getPack(docClient, packId, { consistent: true })
  if (!pack || pack.currentVersion !== version) return { notified: 0, stopped: true }
 
  const page = await docClient.send(
    new QueryCommand({
      TableName: importsTable(),
      KeyConditionExpression: 'packId = :packId',
      ExpressionAttributeValues: { ':packId': packId },
      ProjectionExpression: 'flowId, copyEntityIds, notifiedVersion',
      Limit: PAGE_SIZE,
      ...(cursor && { ExclusiveStartKey: cursor })
    })
  )
 
  const rows = (page.Items || []).filter(
    (row) =>
      row.flowId !== pack.flowId && row.copyEntityIds?.size > 0 && !(row.notifiedVersion >= version)
  )
  const flows = await getFlows(rows.map((row) => row.flowId))
  let notified = 0
  for (const row of rows) {
    const flow = flows.get(row.flowId)
    if (!flow?.ownerId) continue
    if (await notifyFlow(pack, version, flow)) notified++
  }
 
  if (page.LastEvaluatedKey) {
    await sqsClient.send(
      new SendMessageCommand({
        QueueUrl: process.env.PACK_NOTIFY_QUEUE_URL,
        MessageBody: JSON.stringify({ packId, version, cursor: page.LastEvaluatedKey })
      })
    )
  }
  return { notified, stopped: false }
}
 
exports.handler = async (event) => {
  for (const record of event.Records) {
    await notifyPage(JSON.parse(record.body))
  }
}
 
exports.PAGE_SIZE = PAGE_SIZE