budibase/packages/server/src/threads/automation.ts

439 lines
14 KiB
TypeScript
Raw Normal View History

import { threadSetup } from "./utils"
threadSetup()
import { isRecurring } from "../automations/utils"
import { default as actions } from "../automations/actions"
import { default as automationUtils } from "../automations/automationUtils"
import { default as AutomationEmitter } from "../events/AutomationEmitter"
import { generateAutomationMetadataID } from "../db/utils"
import { definitions as triggerDefs } from "../automations/triggerInfo"
import { AutomationErrors, MAX_AUTOMATION_RECURRING_ERRORS } from "../constants"
import { storeLog } from "../automations/logging"
import { Automation, AutomationStep, AutomationStatus } from "@budibase/types"
import {
LoopStep,
LoopStepTypes,
LoopInput,
AutomationEvent,
TriggerOutput,
AutomationContext,
AutomationMetadata,
} from "../definitions/automations"
const { doInAppContext, getAppDB } = require("@budibase/backend-core/context")
const { logAlertWithInfo } = require("@budibase/backend-core/logging")
const { processObject } = require("@budibase/string-templates")
2021-09-14 12:28:39 +02:00
const FILTER_STEP_ID = actions.ACTION_DEFINITIONS.FILTER.stepId
2022-03-25 10:26:55 +01:00
const LOOP_STEP_ID = actions.ACTION_DEFINITIONS.LOOP.stepId
const CRON_STEP_ID = triggerDefs.CRON.stepId
const STOPPED_STATUS = { success: true, status: AutomationStatus.STOPPED }
2022-03-25 11:52:22 +01:00
const { cloneDeep } = require("lodash/fp")
2022-04-12 10:13:01 +02:00
const env = require("../environment")
function typecastForLooping(loopStep: LoopStep, input: LoopInput) {
if (!input || !input.binding) {
return null
}
try {
switch (loopStep.inputs.option) {
case LoopStepTypes.ARRAY:
if (typeof input.binding === "string") {
return JSON.parse(input.binding)
}
break
case LoopStepTypes.STRING:
if (Array.isArray(input.binding)) {
return input.binding.join(",")
}
break
}
} catch (err) {
throw new Error("Unable to cast to correct type")
}
return input.binding
}
function getLoopIterations(loopStep: LoopStep, input: LoopInput) {
const binding = typecastForLooping(loopStep, input)
if (!loopStep || !binding) {
return 1
}
return Array.isArray(binding)
? binding.length
: automationUtils.stringSplit(binding).length
}
/**
* 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 {
_chainCount: number
_appId: string
_automation: Automation
_emitter: any
_context: AutomationContext
executionOutput: AutomationContext
constructor(automation: Automation, triggerOutput: TriggerOutput) {
const metadata = triggerOutput.metadata
this._chainCount = metadata ? metadata.automationChainCount : 0
this._appId = triggerOutput.appId as string
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: string, triggerOutput: TriggerOutput) {
if (stepId === CRON_STEP_ID) {
triggerOutput.timestamp = Date.now()
}
return triggerOutput
}
async getStepFunctionality(stepId: string) {
2021-09-14 12:28:39 +02:00
let step = await actions.getAction(stepId)
if (step == null) {
throw `Cannot find automation step by name ${stepId}`
}
return step
}
async getMetadata(): Promise<AutomationMetadata> {
const metadataId = generateAutomationMetadataID(this._automation._id)
const db = getAppDB()
let metadata: AutomationMetadata
try {
metadata = await db.get(metadataId)
} catch (err) {
metadata = {
_id: metadataId,
errorCount: 0,
}
}
return metadata
}
async checkIfShouldStop(metadata: AutomationMetadata): Promise<boolean> {
if (!metadata.errorCount) {
return false
}
const automation = this._automation
const trigger = automation.definition.trigger
if (metadata.errorCount >= MAX_AUTOMATION_RECURRING_ERRORS) {
// TODO: need to disable the recurring here
this.updateExecutionOutput(trigger.id, trigger.stepId, {}, STOPPED_STATUS)
await storeLog(automation, this.executionOutput)
return true
}
return false
}
async updateMetadata(metadata: AutomationMetadata) {
const output = this.executionOutput,
automation = this._automation
if (!output || !isRecurring(automation)) {
return
}
const count = metadata.errorCount
const isError = output.status === AutomationStatus.ERROR
// nothing to do in this scenario, escape
if (!count && !isError) {
return
}
if (isError) {
metadata.errorCount = count ? count + 1 : 1
} else {
metadata.errorCount = 0
}
const db = getAppDB()
try {
await db.put(metadata)
} catch (err) {
logAlertWithInfo(
"Failed to write automation metadata",
db.name,
automation._id,
err
)
}
}
updateExecutionOutput(id: string, stepId: string, inputs: any, outputs: any) {
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)
}
updateContextAndOutput(
loopStepNumber: number | undefined,
step: AutomationStep,
output: any,
result: { success: boolean; status: string }
) {
if (!loopStepNumber) {
throw new Error("No loop step number provided.")
}
2022-04-12 00:10:29 +02:00
this.executionOutput.steps.splice(loopStepNumber, 0, {
id: step.id,
stepId: step.stepId,
outputs: {
...output,
success: result.success,
status: result.status,
},
inputs: step.inputs,
})
this._context.steps.splice(loopStepNumber, 0, {
...output,
success: result.success,
status: result.status,
})
}
async execute() {
let automation = this._automation
let stopped = false
let loopStep: AutomationStep | undefined = undefined
2022-03-25 10:26:55 +01:00
let stepCount = 0
let loopStepNumber: any = undefined
let loopSteps: LoopStep[] | undefined = []
let metadata
// check if this is a recurring automation,
if (isRecurring(automation)) {
metadata = await this.getMetadata()
const shouldStop = await this.checkIfShouldStop(metadata)
if (shouldStop) {
return
}
}
for (let step of automation.definition.steps) {
2022-03-25 10:26:55 +01:00
stepCount++
let input,
iterations = 1,
iterationCount = 0
2022-03-25 10:26:55 +01:00
if (step.stepId === LOOP_STEP_ID) {
loopStep = step
loopStepNumber = stepCount
continue
}
2022-03-25 10:26:55 +01:00
2022-04-11 11:26:59 +02:00
if (loopStep) {
2022-05-04 12:55:26 +02:00
input = await processObject(loopStep.inputs, this._context)
iterations = getLoopIterations(loopStep as LoopStep, input)
2022-04-11 11:26:59 +02:00
}
2022-03-25 10:26:55 +01:00
for (let index = 0; index < iterations; index++) {
2022-03-25 11:52:22 +01:00
let originalStepInput = cloneDeep(step.inputs)
2022-03-28 11:01:56 +02:00
2022-04-11 11:26:59 +02:00
// Handle if the user has set a max iteration count or if it reaches the max limit set by us
if (loopStep && input.binding) {
2022-04-11 11:26:59 +02:00
let newInput = await processObject(
loopStep.inputs,
cloneDeep(this._context)
)
2022-04-12 00:10:29 +02:00
let tempOutput = { items: loopSteps, iterations: iterationCount }
try {
newInput.binding = typecastForLooping(
loopStep as LoopStep,
newInput
)
} catch (err) {
2022-04-12 00:10:29 +02:00
this.updateContextAndOutput(loopStepNumber, step, tempOutput, {
status: AutomationErrors.INCORRECT_TYPE,
2022-04-12 00:10:29 +02:00
success: false,
2022-04-11 11:26:59 +02:00
})
loopSteps = undefined
loopStep = undefined
2022-04-11 11:26:59 +02:00
break
}
2022-05-04 12:55:26 +02:00
let item
if (
typeof loopStep.inputs.binding === "string" &&
loopStep.inputs.option === "String"
) {
item = automationUtils.stringSplit(newInput.binding)
} else {
item = loopStep.inputs.binding
}
2022-05-04 11:24:28 +02:00
this._context.steps[loopStepNumber] = {
2022-05-04 12:55:26 +02:00
currentItem: item[index],
2022-05-04 11:24:28 +02:00
}
2022-04-11 11:26:59 +02:00
// The "Loop" binding in the front end is "fake", so replace it here so the context can understand it
2022-04-12 00:10:29 +02:00
// Pretty hacky because we need to account for the row object
for (let [key, value] of Object.entries(originalStepInput)) {
if (typeof value === "object") {
for (let [innerKey, innerValue] of Object.entries(
originalStepInput[key]
)) {
if (typeof innerValue === "string") {
originalStepInput[key][innerKey] =
automationUtils.substituteLoopStep(
innerValue,
`steps.${loopStepNumber}`
)
}
2022-04-11 11:26:59 +02:00
}
} else {
if (typeof value === "string") {
originalStepInput[key] = automationUtils.substituteLoopStep(
value,
`steps.${loopStepNumber}`
)
}
2022-04-11 11:26:59 +02:00
}
}
2022-04-12 10:13:01 +02:00
if (
2022-06-23 17:08:25 +02:00
index === env.AUTOMATION_MAX_ITERATION ||
2022-05-19 17:38:16 +02:00
index === parseInt(loopStep.inputs.iterations)
2022-04-12 10:13:01 +02:00
) {
2022-04-12 00:10:29 +02:00
this.updateContextAndOutput(loopStepNumber, step, tempOutput, {
status: AutomationErrors.MAX_ITERATIONS,
2022-04-11 11:26:59 +02:00
success: true,
})
loopSteps = undefined
loopStep = undefined
2022-04-11 11:26:59 +02:00
break
}
let isFailure = false
const currentItem = this._context.steps[loopStepNumber]?.currentItem
if (currentItem && typeof currentItem === "object") {
isFailure = Object.keys(currentItem).some(value => {
return currentItem[value] === loopStep?.inputs.failure
})
} else {
isFailure = currentItem && currentItem === loopStep.inputs.failure
}
if (isFailure) {
2022-04-12 00:10:29 +02:00
this.updateContextAndOutput(loopStepNumber, step, tempOutput, {
status: AutomationErrors.FAILURE_CONDITION,
2022-04-12 00:10:29 +02:00
success: false,
2022-04-11 11:26:59 +02:00
})
loopSteps = undefined
loopStep = undefined
2022-04-11 11:26:59 +02:00
break
}
2022-03-28 11:01:56 +02:00
}
2022-04-11 11:26:59 +02:00
2022-03-25 10:26:55 +01:00
// execution stopped, record state for that
if (stopped) {
this.updateExecutionOutput(step.id, step.stepId, {}, STOPPED_STATUS)
continue
}
2022-03-25 10:26:55 +01:00
// If it's a loop step, we need to manually add the bindings to the context
let stepFn = await this.getStepFunctionality(step.stepId)
2022-03-25 11:52:22 +01:00
let inputs = await processObject(originalStepInput, this._context)
inputs = automationUtils.cleanInputValues(inputs, step.schema.inputs)
2022-03-25 10:26:55 +01:00
try {
// appId is always passed
const outputs = await stepFn({
inputs: inputs,
appId: this._appId,
emitter: this._emitter,
context: this._context,
2022-03-25 10:26:55 +01:00
})
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.result) {
2022-03-25 10:26:55 +01:00
stopped = true
this.updateExecutionOutput(step.id, step.stepId, step.inputs, {
...outputs,
...STOPPED_STATUS,
})
continue
}
2022-03-29 11:29:51 +02:00
if (loopStep && loopSteps) {
loopSteps.push(outputs)
2022-03-28 11:01:56 +02:00
} else {
this.updateExecutionOutput(
step.id,
step.stepId,
step.inputs,
outputs
)
}
2022-03-25 10:26:55 +01:00
} catch (err) {
console.error(`Automation error - ${step.stepId} - ${err}`)
return err
}
2022-04-11 11:26:59 +02:00
if (loopStep) {
iterationCount++
if (index === iterations - 1) {
loopStep = undefined
2022-04-11 11:26:59 +02:00
this._context.steps.splice(loopStepNumber, 1)
break
}
2022-03-25 10:26:55 +01:00
}
}
2022-03-29 11:29:51 +02:00
if (loopSteps && loopSteps.length) {
2022-04-11 11:26:59 +02:00
let tempOutput = {
success: true,
items: loopSteps,
iterations: iterationCount,
}
this.executionOutput.steps.splice(loopStepNumber + 1, 0, {
id: step.id,
stepId: step.stepId,
2022-03-29 11:29:51 +02:00
outputs: tempOutput,
inputs: step.inputs,
2022-03-28 11:01:56 +02:00
})
2022-04-11 11:26:59 +02:00
this._context.steps.splice(loopStepNumber, 0, tempOutput)
loopSteps = undefined
2022-03-28 11:01:56 +02:00
}
}
2022-04-11 11:26:59 +02:00
// store the logs for the automation run
await storeLog(this._automation, this.executionOutput)
if (isRecurring(automation) && metadata) {
await this.updateMetadata(metadata)
}
return this.executionOutput
}
}
export default (
input: AutomationEvent,
callback: (error: any, response?: any) => void
) => {
const appId = input.data.event.appId
doInAppContext(appId, async () => {
const automationOrchestrator = new Orchestrator(
input.data.automation,
input.data.event
)
try {
const response = await automationOrchestrator.execute()
callback(null, response)
} catch (err) {
callback(err)
}
})
2020-12-08 12:23:06 +01:00
}