1
0
Fork 0
mirror of synced 2024-09-28 23:31:43 +12:00
budibase/packages/server/src/threads/automation.js

219 lines
7.2 KiB
JavaScript
Raw Normal View History

require("./utils").threadSetup()
const env = require("../environment")
const actions = require("../automations/actions")
const automationUtils = require("../automations/automationUtils")
const AutomationEmitter = require("../events/AutomationEmitter")
const { processObject } = require("@budibase/string-templates")
const { DEFAULT_TENANT_ID } = require("@budibase/backend-core/constants")
const { DocumentTypes, isDevAppID } = require("../db/utils")
const { doInTenant } = require("@budibase/backend-core/tenancy")
2021-09-24 10:25:25 +12:00
const usage = require("../utilities/usageQuota")
const { definitions: triggerDefs } = require("../automations/triggerInfo")
const { doInAppContext, getAppDB } = require("@budibase/backend-core/context")
2021-09-14 22:28:39 +12:00
const FILTER_STEP_ID = actions.ACTION_DEFINITIONS.FILTER.stepId
2022-03-25 22:26:55 +13:00
const LOOP_STEP_ID = actions.ACTION_DEFINITIONS.LOOP.stepId
const CRON_STEP_ID = triggerDefs.CRON.stepId
const STOPPED_STATUS = { success: false, status: "STOPPED" }
2022-03-25 23:52:22 +13:00
const { cloneDeep } = require("lodash/fp")
2022-03-28 22:01:56 +13:00
const { loop } = require("svelte/internal")
/**
* The automation orchestrator is a class responsible for executing automations.
* It handles the context of the automation and makes sure each step gets the correct
* inputs and handles any outputs.
*/
class Orchestrator {
2021-05-19 08:03:26 +12:00
constructor(automation, triggerOutput = {}) {
this._metadata = triggerOutput.metadata
this._chainCount = this._metadata ? this._metadata.automationChainCount : 0
this._appId = triggerOutput.appId
this._app = null
const triggerStepId = automation.definition.trigger.stepId
triggerOutput = this.cleanupTriggerOutputs(triggerStepId, triggerOutput)
// remove from context
delete triggerOutput.appId
delete triggerOutput.metadata
// step zero is never used as the template string is zero indexed for customer facing
this._context = { steps: [{}], trigger: triggerOutput }
this._automation = automation
// create an emitter which has the chain count for this automation run in it, so it can block
// excessive chaining if required
this._emitter = new AutomationEmitter(this._chainCount + 1)
this.executionOutput = { trigger: {}, steps: [] }
// setup the execution output
const triggerId = automation.definition.trigger.id
this.updateExecutionOutput(triggerId, triggerStepId, null, triggerOutput)
}
cleanupTriggerOutputs(stepId, triggerOutput) {
if (stepId === CRON_STEP_ID) {
triggerOutput.timestamp = Date.now()
}
return triggerOutput
}
2021-09-14 22:28:39 +12:00
async getStepFunctionality(stepId) {
let step = await actions.getAction(stepId)
if (step == null) {
throw `Cannot find automation step by name ${stepId}`
}
return step
}
async getApp() {
if (this._app) {
return this._app
}
const db = getAppDB()
this._app = await db.get(DocumentTypes.APP_METADATA)
return this._app
}
updateExecutionOutput(id, stepId, inputs, outputs) {
const stepObj = { id, stepId, inputs, outputs }
// first entry is always the trigger (constructor)
if (this.executionOutput.steps.length === 0) {
this.executionOutput.trigger = stepObj
}
this.executionOutput.steps.push(stepObj)
}
async execute() {
let automation = this._automation
const app = await this.getApp()
let stopped = false
2022-03-25 22:26:55 +13:00
let loopStep
let stepCount = 0
let loopStepNumber
2022-03-28 22:01:56 +13:00
let loopSteps = []
for (let step of automation.definition.steps) {
2022-03-25 22:26:55 +13:00
stepCount++
if (step.stepId === LOOP_STEP_ID) {
loopStep = step
loopStepNumber = stepCount
continue
}
2022-03-28 22:01:56 +13:00
let iterations = loopStep ? loopStep.inputs.binding.split(",").length : 1
2022-03-25 22:26:55 +13:00
for (let index = 0; index < iterations; index++) {
2022-03-25 23:52:22 +13:00
let originalStepInput = cloneDeep(step.inputs)
2022-03-28 22:01:56 +13:00
/*
if (step.stepId === LOOP_STEP_ID && index >= loopStep.inputs.iterations) {
this.executionOutput.steps[loopStepNumber].outputs.status = "Loop Broken"
break
}
*/
2022-03-25 22:26:55 +13:00
// execution stopped, record state for that
if (stopped) {
this.updateExecutionOutput(step.id, step.stepId, {}, STOPPED_STATUS)
continue
}
2022-03-25 22:26:55 +13:00
// If it's a loop step, we need to manually add the bindings to the context
if (loopStep) {
this._context.steps[loopStepNumber] = {
currentItem: loopStep.inputs.binding.split(",")[index],
}
}
let stepFn = await this.getStepFunctionality(step.stepId)
2022-03-25 23:52:22 +13:00
let inputs = await processObject(originalStepInput, this._context)
inputs = automationUtils.cleanInputValues(inputs, step.schema.inputs)
2022-03-25 22:26:55 +13:00
try {
// appId is always passed
let tenantId = app.tenantId || DEFAULT_TENANT_ID
const outputs = await doInTenant(tenantId, () => {
return stepFn({
2022-03-25 23:52:22 +13:00
inputs: inputs,
2022-03-25 22:26:55 +13:00
appId: this._appId,
emitter: this._emitter,
context: this._context,
})
})
this._context.steps[stepCount] = outputs
// if filter causes us to stop execution don't break the loop, set a var
// so that we can finish iterating through the steps and record that it stopped
if (step.stepId === FILTER_STEP_ID && !outputs.success) {
stopped = true
this.updateExecutionOutput(step.id, step.stepId, step.inputs, {
...outputs,
...STOPPED_STATUS,
})
continue
}
2022-03-28 22:01:56 +13:00
if (loopStep) {
loopSteps.push({
id: step.id,
stepId: step.stepId,
inputs: step.inputs,
outputs,
})
} else {
this.updateExecutionOutput(
step.id,
step.stepId,
step.inputs,
outputs
)
}
2022-03-25 22:26:55 +13:00
} catch (err) {
console.error(`Automation error - ${step.stepId} - ${err}`)
return err
}
2022-03-28 22:01:56 +13:00
2022-03-25 22:26:55 +13:00
if (index === iterations - 1) {
loopStep = null
break
}
}
2022-03-28 22:01:56 +13:00
if (loopSteps) {
this.executionOutput.steps.splice(loopStepNumber, 0, {
id: step.id,
stepId: step.stepId,
outputs: {
success: true,
outputs: loopSteps,
iterations: iterations,
},
})
this._context.steps.splice(loopStepNumber, 0, {
id: step.id,
stepId: step.stepId,
steps: loopSteps,
iterations,
success: true,
})
loopSteps = null
}
}
// Increment quota for automation runs
if (!env.SELF_HOSTED && !isDevAppID(this._appId)) {
await usage.update(usage.Properties.AUTOMATION, 1)
2021-09-24 10:25:25 +12:00
}
2022-03-25 22:26:55 +13:00
// make that we don't loop the next step if we have already been looping (loop block only has one step)
return this.executionOutput
}
}
module.exports = (input, callback) => {
const appId = input.data.event.appId
doInAppContext(appId, () => {
const automationOrchestrator = new Orchestrator(
input.data.automation,
input.data.event
)
automationOrchestrator
.execute()
.then(response => {
callback(null, response)
})
.catch(err => {
callback(err)
})
})
2020-12-09 00:23:06 +13:00
}