ZZZ Digital Lab

Back to n8n workflow hardening

lib/replay.cjs

'use strict';
// OFFLINE CONTRACT SIMULATOR. It is not an n8n execution engine or an HTTP client.
const fs=require('node:fs'),path=require('node:path'),vm=require('node:vm');
const root=path.join(__dirname,'..');
function exports(){return ['after/main.json','after/error-workflow.json'].map(p=>JSON.parse(fs.readFileSync(path.join(root,p),'utf8')));}
function runCode(node,input,{originals=[],executionId='SYN-EXEC-1'}={}){
 const items=input.map(json=>({json}));
 const context={$input:{all:()=>items,first:()=>items[0]},$execution:{id:executionId},
  $:name=>{if(name!=='Prepare Events')throw new Error('UNEXPECTED_LINK');return {itemMatching:i=>({json:originals[i]})};}};
 return vm.runInNewContext('(function(){\n'+node.parameters.jsCode+'\n})()',context,{timeout:1000});
}
function prepare(envelope,main=exports()[0]){return JSON.parse(JSON.stringify(runCode(main.nodes.find(n=>n.name==='Prepare Events'),[envelope]).map(x=>x.json)));}
class FakeReceiver{
 constructor({transient=0,permanent=false,lostAck=false}={}){this.records=new Map();this.transient=transient;this.permanent=permanent;this.lostAck=lostAck;this.calls=0;}
 put(key,payload){
  this.calls++;
  if(this.permanent||this.transient-->0)throw new Error('SYNTHETIC_503');
  const existing=this.records.get(key),body=JSON.stringify(payload);
  if(existing&&existing!==body)throw new Error('IDEMPOTENCY_CONFLICT');
  const accepted=!existing;this.records.set(key,body);
  if(this.lostAck){this.lostAck=false;throw new Error('ACK_LOST_AFTER_COMMIT');}
  return {accepted,duplicate:!accepted};
 }
}
function replay(envelope,receiver,{main=exports()[0],dlq=new Map(),failDlq=false}={}){
 const events=prepare(envelope,main),delivery=main.nodes.find(n=>n.name==='Deliver Event');
 const result={accepted:0,duplicates:0,attempts:0,waitsMs:[],deadLetters:0,status:'complete',incidents:[]};
 for(const event of events){
  let delivered=false;
  for(let attempt=1;attempt<=delivery.maxTries;attempt++){
   result.attempts++;
   try{const r=receiver.put(event.idempotencyKey,event.payload);result.accepted+=Number(r.accepted);result.duplicates+=Number(r.duplicate);delivered=true;break;}
   catch(error){if(attempt<delivery.maxTries)result.waitsMs.push(delivery.waitBetweenTries);}
  }
  if(!delivered){
   const node=main.nodes.find(n=>n.name==='Build Dead Letter');
   const record=JSON.parse(JSON.stringify(runCode(node,[{error:'synthetic delivery error'}],{originals:[event]})[0].json));
   if(failDlq){result.incidents.push(buildIncident({execution:{id:'SYN-EXEC-1'},workflow:{id:main.id}}));result.status='dead-letter-failed';}
   else{dlq.set(record.dead_letter_key,record);result.deadLetters++;result.status='delivery-failed';result.incidents.push(buildIncident({execution:{id:'SYN-EXEC-1'},workflow:{id:main.id}}));}
   // Real Stop and Error may halt other items. Replay the whole envelope safely after recovery.
   break;
  }
 }
 return result;
}
function buildIncident(input){const node=exports()[1].nodes.find(n=>n.name==='Build Incident');return JSON.parse(JSON.stringify(runCode(node,[input])[0].json));}
module.exports={loadExports:exports,runCode,prepare,FakeReceiver,replay,buildIncident};