|
| 1 | +/** |
| 2 | + * Sanitization for JSON data round-tripped through Redis Lua cjson. |
| 3 | + * |
| 4 | + * Lua's cjson library cannot distinguish between empty arrays `[]` and empty objects `{}`. |
| 5 | + * Both serialize to `{}` in Lua tables. When BullMQ's internal Lua scripts touch job data, |
| 6 | + * any empty array in the payload silently becomes `{}`. |
| 7 | + * |
| 8 | + * Applied once at the worker boundary before data enters the execution engine. |
| 9 | + */ |
| 10 | + |
| 11 | +/** |
| 12 | + * Returns `value` if it's an array, otherwise `[]`. |
| 13 | + */ |
| 14 | +export function ensureArray<T>(value: unknown): T[] { |
| 15 | + return Array.isArray(value) ? value : [] |
| 16 | +} |
| 17 | + |
| 18 | +const EXECUTION_STATE_ARRAY_FIELDS = [ |
| 19 | + 'executedBlocks', |
| 20 | + 'blockLogs', |
| 21 | + 'completedLoops', |
| 22 | + 'activeExecutionPath', |
| 23 | + 'pendingQueue', |
| 24 | + 'remainingEdges', |
| 25 | + 'completedPauseContexts', |
| 26 | +] |
| 27 | + |
| 28 | +/** |
| 29 | + * Normalizes all known array fields on a BullMQ-deserialized workflow execution payload. |
| 30 | + * Mutates in place — call once before passing into the execution engine. |
| 31 | + */ |
| 32 | +// eslint-disable-next-line @typescript-eslint/no-explicit-any |
| 33 | +export function sanitizeBullMQPayload(payload: any): void { |
| 34 | + if (!payload) return |
| 35 | + |
| 36 | + payload.selectedOutputs = ensureArray(payload.selectedOutputs) |
| 37 | + |
| 38 | + if (payload.metadata) { |
| 39 | + payload.metadata.callChain = ensureArray(payload.metadata.callChain) |
| 40 | + |
| 41 | + if (payload.metadata.pendingBlocks !== undefined) { |
| 42 | + payload.metadata.pendingBlocks = ensureArray(payload.metadata.pendingBlocks) |
| 43 | + } |
| 44 | + |
| 45 | + if (payload.metadata.workflowStateOverride?.edges !== undefined) { |
| 46 | + payload.metadata.workflowStateOverride.edges = ensureArray( |
| 47 | + payload.metadata.workflowStateOverride.edges |
| 48 | + ) |
| 49 | + } |
| 50 | + } |
| 51 | + |
| 52 | + if (payload.runFromBlock?.sourceSnapshot) { |
| 53 | + const state = payload.runFromBlock.sourceSnapshot |
| 54 | + for (const field of EXECUTION_STATE_ARRAY_FIELDS) { |
| 55 | + if (field in state && !Array.isArray(state[field])) { |
| 56 | + state[field] = [] |
| 57 | + } |
| 58 | + } |
| 59 | + |
| 60 | + if (state.dagIncomingEdges && typeof state.dagIncomingEdges === 'object') { |
| 61 | + for (const key of Object.keys(state.dagIncomingEdges)) { |
| 62 | + if (!Array.isArray(state.dagIncomingEdges[key])) { |
| 63 | + state.dagIncomingEdges[key] = [] |
| 64 | + } |
| 65 | + } |
| 66 | + } |
| 67 | + } |
| 68 | +} |
0 commit comments