2020-09-11 19:47:22 +02:00
|
|
|
const mustache = require("mustache")
|
|
|
|
const actions = require("./actions")
|
|
|
|
const logic = require("./logic")
|
|
|
|
|
2020-09-16 15:00:04 +02:00
|
|
|
function recurseMustache(inputs, context) {
|
|
|
|
for (let key in Object.keys(inputs)) {
|
|
|
|
let val = inputs[key]
|
|
|
|
if (typeof val === "string") {
|
|
|
|
inputs[key] = mustache.render(val, { context })
|
|
|
|
}
|
|
|
|
// this covers objects and arrays
|
|
|
|
else if (typeof val === "object") {
|
|
|
|
inputs[key] = recurseMustache(inputs[key], context)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return inputs
|
|
|
|
}
|
|
|
|
|
2020-09-11 19:47:22 +02:00
|
|
|
/**
|
|
|
|
* The workflow orchestrator is a class responsible for executing workflows.
|
|
|
|
* It handles the context of the workflow and makes sure each step gets the correct
|
|
|
|
* inputs and handles any outputs.
|
|
|
|
*/
|
|
|
|
class Orchestrator {
|
2020-09-16 15:00:04 +02:00
|
|
|
constructor(workflow, triggerOutput) {
|
|
|
|
this._instanceId = triggerOutput.instanceId
|
|
|
|
// block zero is never used as the mustache is zero indexed for customer facing
|
2020-09-16 20:25:52 +02:00
|
|
|
this._context = { blocks: [{}], trigger: triggerOutput }
|
2020-09-11 19:47:22 +02:00
|
|
|
this._workflow = workflow
|
|
|
|
}
|
|
|
|
|
2020-09-16 15:00:04 +02:00
|
|
|
async getStepFunctionality(type, stepId) {
|
2020-09-11 19:47:22 +02:00
|
|
|
let step = null
|
|
|
|
if (type === "ACTION") {
|
|
|
|
step = await actions.getAction(stepId)
|
|
|
|
} else if (type === "LOGIC") {
|
|
|
|
step = logic.getLogic(stepId)
|
|
|
|
}
|
|
|
|
if (step == null) {
|
|
|
|
throw `Cannot find workflow step by name ${stepId}`
|
|
|
|
}
|
|
|
|
return step
|
|
|
|
}
|
|
|
|
|
2020-09-16 15:00:04 +02:00
|
|
|
async execute() {
|
2020-09-11 19:47:22 +02:00
|
|
|
let workflow = this._workflow
|
|
|
|
for (let block of workflow.definition.steps) {
|
2020-09-16 15:00:04 +02:00
|
|
|
let stepFn = await this.getStepFunctionality(block.type, block.stepId)
|
|
|
|
block.inputs = recurseMustache(block.inputs, this._context)
|
|
|
|
// instanceId is always passed
|
|
|
|
const outputs = await stepFn({
|
|
|
|
inputs: block.inputs,
|
|
|
|
instanceId: this._instanceId,
|
2020-09-11 19:47:22 +02:00
|
|
|
})
|
2020-09-16 15:00:04 +02:00
|
|
|
this._context.blocks.push(outputs)
|
2020-09-11 19:47:22 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-09-14 11:30:35 +02:00
|
|
|
// callback is required for worker-farm to state that the worker thread has completed
|
2020-09-11 19:47:22 +02:00
|
|
|
module.exports = async (job, cb = null) => {
|
|
|
|
try {
|
2020-09-16 15:00:04 +02:00
|
|
|
const workflowOrchestrator = new Orchestrator(
|
|
|
|
job.data.workflow,
|
|
|
|
job.data.event
|
|
|
|
)
|
|
|
|
await workflowOrchestrator.execute()
|
2020-09-11 19:47:22 +02:00
|
|
|
if (cb) {
|
|
|
|
cb()
|
|
|
|
}
|
|
|
|
} catch (err) {
|
|
|
|
if (cb) {
|
|
|
|
cb(err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|