2022-06-20 23:29:21 +08:00
|
|
|
import path from 'path';
|
2024-05-08 16:20:31 +08:00
|
|
|
import { Op, Transactionable } from '@tachybase/database';
|
2024-05-31 18:26:25 +08:00
|
|
|
import { Logger, LoggerOptions } from '@tachybase/logger';
|
2024-05-08 16:20:31 +08:00
|
|
|
import Application, { Plugin, PluginOptions } from '@tachybase/server';
|
|
|
|
import { Registry } from '@tachybase/utils';
|
2022-06-20 23:29:21 +08:00
|
|
|
|
2024-05-31 18:26:25 +08:00
|
|
|
import LRUCache from 'lru-cache';
|
|
|
|
|
2022-06-20 23:29:21 +08:00
|
|
|
import initActions from './actions';
|
2022-10-27 13:00:16 +08:00
|
|
|
import { EXECUTION_STATUS } from './constants';
|
2024-05-31 18:26:25 +08:00
|
|
|
import { PluginActionTrigger } from './features/action-trigger/Plugin';
|
|
|
|
import { PluginAggregate } from './features/aggregate/Plugin';
|
2024-06-04 16:59:10 +08:00
|
|
|
import PluginWorkflowAPIRegularServer from './features/api-regular/plugin';
|
2024-05-31 18:26:25 +08:00
|
|
|
import { PluginDelay } from './features/delay/Plugin';
|
|
|
|
import { PluginDynamicCalculation } from './features/dynamic-calculation/Plugin';
|
2024-06-11 21:17:42 +08:00
|
|
|
import { PluginInterception } from './features/interception';
|
2024-05-31 20:27:27 +08:00
|
|
|
import PluginWorkflowJSParseServer from './features/js-parse/plugin';
|
2024-05-31 18:26:25 +08:00
|
|
|
import PluginWorkflowJSONParseServer from './features/json-parse/plugin';
|
|
|
|
import { PluginLoop } from './features/loop/Plugin';
|
|
|
|
import { PluginManual } from './features/manual/Plugin';
|
2024-06-14 00:56:39 +08:00
|
|
|
import { PluginOmniTrigger } from './features/omni-trigger';
|
2024-05-31 18:26:25 +08:00
|
|
|
import { PluginParallel } from './features/parallel/Plugin';
|
|
|
|
import { PluginRequest } from './features/request/Plugin';
|
2024-06-14 00:56:39 +08:00
|
|
|
import { PluginResponse } from './features/response';
|
2024-05-31 18:26:25 +08:00
|
|
|
import { PluginSql } from './features/sql/Plugin';
|
2024-06-18 13:43:11 +08:00
|
|
|
import { PluginTriggerInstruction } from './features/trigger-instruction/plugin';
|
2024-06-11 21:17:42 +08:00
|
|
|
import { PluginVariables } from './features/variables';
|
2023-08-24 17:47:45 +08:00
|
|
|
import initFunctions, { CustomFunction } from './functions';
|
2023-12-29 09:29:37 +08:00
|
|
|
import { Instruction, InstructionInterface } from './instructions';
|
2023-12-07 21:46:58 +08:00
|
|
|
import CalculationInstruction from './instructions/CalculationInstruction';
|
|
|
|
import ConditionInstruction from './instructions/ConditionInstruction';
|
|
|
|
import CreateInstruction from './instructions/CreateInstruction';
|
|
|
|
import DestroyInstruction from './instructions/DestroyInstruction';
|
2024-05-31 18:26:25 +08:00
|
|
|
import EndInstruction from './instructions/EndInstruction';
|
2023-12-07 21:46:58 +08:00
|
|
|
import QueryInstruction from './instructions/QueryInstruction';
|
|
|
|
import UpdateInstruction from './instructions/UpdateInstruction';
|
2024-05-31 18:26:25 +08:00
|
|
|
import Processor from './Processor';
|
|
|
|
import Trigger from './triggers';
|
|
|
|
import CollectionTrigger from './triggers/CollectionTrigger';
|
|
|
|
import ScheduleTrigger from './triggers/ScheduleTrigger';
|
2023-08-24 17:47:45 +08:00
|
|
|
import type { ExecutionModel, JobModel, WorkflowModel } from './types';
|
2023-07-07 17:59:46 +08:00
|
|
|
|
2023-12-20 10:13:08 +08:00
|
|
|
type ID = number | string;
|
|
|
|
|
2022-12-03 14:34:47 +08:00
|
|
|
type Pending = [ExecutionModel, JobModel?];
|
2023-04-10 21:00:29 +08:00
|
|
|
|
2023-12-20 10:13:08 +08:00
|
|
|
type CachedEvent = [WorkflowModel, any, { context?: any }];
|
2023-12-07 21:46:58 +08:00
|
|
|
|
2024-01-06 11:17:28 +08:00
|
|
|
export default class PluginWorkflowServer extends Plugin {
|
2023-12-29 09:29:37 +08:00
|
|
|
instructions: Registry<InstructionInterface> = new Registry();
|
2022-06-22 23:17:30 +08:00
|
|
|
triggers: Registry<Trigger> = new Registry();
|
2023-04-28 14:50:35 +08:00
|
|
|
functions: Registry<CustomFunction> = new Registry();
|
2024-03-29 09:09:12 +08:00
|
|
|
enabledCache: Map<number, WorkflowModel> = new Map();
|
2023-09-12 22:39:23 +08:00
|
|
|
|
|
|
|
private ready = false;
|
|
|
|
private executing: Promise<void> | null = null;
|
2023-04-10 21:00:29 +08:00
|
|
|
private pending: Pending[] = [];
|
2023-12-20 10:13:08 +08:00
|
|
|
private events: CachedEvent[] = [];
|
2024-01-03 09:59:33 +08:00
|
|
|
private eventsCount = 0;
|
2023-04-10 21:00:29 +08:00
|
|
|
|
|
|
|
private loggerCache: LRUCache<string, Logger>;
|
2024-01-03 09:59:33 +08:00
|
|
|
private meter = null;
|
2023-04-10 21:00:29 +08:00
|
|
|
|
2024-04-29 21:41:13 +08:00
|
|
|
constructor(app: Application, options?: PluginOptions) {
|
|
|
|
super(app, options);
|
2024-06-14 01:21:37 +08:00
|
|
|
this.addFeature(PluginSql);
|
|
|
|
this.addFeature(PluginRequest);
|
|
|
|
this.addFeature(PluginParallel);
|
|
|
|
this.addFeature(PluginManual);
|
|
|
|
this.addFeature(PluginLoop);
|
|
|
|
this.addFeature(PluginDynamicCalculation);
|
|
|
|
this.addFeature(PluginDelay);
|
|
|
|
this.addFeature(PluginAggregate);
|
|
|
|
this.addFeature(PluginActionTrigger);
|
|
|
|
this.addFeature(PluginWorkflowJSONParseServer);
|
|
|
|
this.addFeature(PluginWorkflowJSParseServer);
|
|
|
|
this.addFeature(PluginWorkflowAPIRegularServer);
|
|
|
|
this.addFeature(PluginInterception);
|
|
|
|
this.addFeature(PluginVariables);
|
|
|
|
this.addFeature(PluginResponse);
|
|
|
|
this.addFeature(PluginOmniTrigger);
|
2024-06-18 13:43:11 +08:00
|
|
|
this.addFeature(PluginTriggerInstruction);
|
2024-04-29 21:41:13 +08:00
|
|
|
}
|
|
|
|
|
2023-04-10 21:00:29 +08:00
|
|
|
getLogger(workflowId: ID): Logger {
|
|
|
|
const now = new Date();
|
|
|
|
const date = `${now.getFullYear()}-${`0${now.getMonth() + 1}`.slice(-2)}-${`0${now.getDate()}`.slice(-2)}`;
|
|
|
|
const key = `${date}-${workflowId}}`;
|
|
|
|
if (this.loggerCache.has(key)) {
|
|
|
|
return this.loggerCache.get(key);
|
|
|
|
}
|
|
|
|
|
2023-12-27 13:56:13 +08:00
|
|
|
const logger = this.createLogger({
|
|
|
|
dirname: path.join('workflows', date),
|
|
|
|
filename: `${workflowId}.log`,
|
|
|
|
transports: [...(process.env.NODE_ENV !== 'production' ? ['console'] : ['file'])],
|
2023-04-10 21:00:29 +08:00
|
|
|
} as LoggerOptions);
|
|
|
|
|
|
|
|
this.loggerCache.set(key, logger);
|
|
|
|
|
|
|
|
return logger;
|
|
|
|
}
|
2022-06-20 23:29:21 +08:00
|
|
|
|
2024-01-25 22:10:03 +08:00
|
|
|
isWorkflowSync(workflow: WorkflowModel) {
|
|
|
|
const trigger = this.triggers.get(workflow.type);
|
|
|
|
if (!trigger) {
|
|
|
|
throw new Error(`invalid trigger type ${workflow.type} of workflow ${workflow.id}`);
|
|
|
|
}
|
|
|
|
return trigger.sync ?? workflow.sync;
|
|
|
|
}
|
|
|
|
|
2024-03-29 09:09:12 +08:00
|
|
|
private onBeforeSave = async (instance: WorkflowModel, options) => {
|
2022-06-22 23:17:30 +08:00
|
|
|
const Model = <typeof WorkflowModel>instance.constructor;
|
|
|
|
|
|
|
|
if (instance.enabled) {
|
|
|
|
instance.set('current', true);
|
|
|
|
} else if (!instance.current) {
|
|
|
|
const count = await Model.count({
|
|
|
|
where: {
|
2023-02-13 09:57:03 +08:00
|
|
|
key: instance.key,
|
2022-06-22 23:17:30 +08:00
|
|
|
},
|
2023-02-13 09:57:03 +08:00
|
|
|
transaction: options.transaction,
|
2022-06-22 23:17:30 +08:00
|
|
|
});
|
|
|
|
if (!count) {
|
|
|
|
instance.set('current', true);
|
|
|
|
}
|
|
|
|
}
|
2022-06-20 23:29:21 +08:00
|
|
|
|
2022-06-22 23:17:30 +08:00
|
|
|
if (!instance.changed('enabled') || !instance.enabled) {
|
|
|
|
return;
|
2022-06-20 23:29:21 +08:00
|
|
|
}
|
2022-06-21 21:43:30 +08:00
|
|
|
|
2022-06-22 23:17:30 +08:00
|
|
|
const previous = await Model.findOne({
|
|
|
|
where: {
|
|
|
|
key: instance.key,
|
|
|
|
current: true,
|
|
|
|
id: {
|
2023-02-13 09:57:03 +08:00
|
|
|
[Op.ne]: instance.id,
|
|
|
|
},
|
2022-06-22 23:17:30 +08:00
|
|
|
},
|
2023-02-13 09:57:03 +08:00
|
|
|
transaction: options.transaction,
|
2022-06-21 21:43:30 +08:00
|
|
|
});
|
2022-06-20 23:29:21 +08:00
|
|
|
|
2022-06-22 23:17:30 +08:00
|
|
|
if (previous) {
|
|
|
|
// NOTE: set to `null` but not `false` will not violate the unique index
|
2023-02-13 09:57:03 +08:00
|
|
|
await previous.update(
|
|
|
|
{ enabled: false, current: null },
|
|
|
|
{
|
|
|
|
transaction: options.transaction,
|
|
|
|
hooks: false,
|
|
|
|
},
|
|
|
|
);
|
2022-06-22 23:17:30 +08:00
|
|
|
|
|
|
|
this.toggle(previous, false);
|
|
|
|
}
|
|
|
|
};
|
2022-06-20 23:29:21 +08:00
|
|
|
|
2023-12-27 13:55:48 +08:00
|
|
|
registerTrigger<T extends Trigger>(type: string, trigger: T | { new (p: Plugin): T }) {
|
|
|
|
if (typeof trigger === 'function') {
|
|
|
|
this.triggers.register(type, new trigger(this));
|
|
|
|
} else if (trigger) {
|
|
|
|
this.triggers.register(type, trigger);
|
|
|
|
} else {
|
|
|
|
throw new Error('invalid trigger type to register');
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-12-29 09:29:37 +08:00
|
|
|
registerInstruction(type: string, instruction: InstructionInterface | { new (p: Plugin): InstructionInterface }) {
|
2023-12-27 13:55:48 +08:00
|
|
|
if (typeof instruction === 'function') {
|
|
|
|
this.instructions.register(type, new instruction(this));
|
|
|
|
} else if (instruction) {
|
|
|
|
this.instructions.register(type, instruction);
|
|
|
|
} else {
|
|
|
|
throw new Error('invalid instruction type to register');
|
|
|
|
}
|
|
|
|
}
|
2023-12-07 21:46:58 +08:00
|
|
|
|
2023-12-27 13:55:48 +08:00
|
|
|
private initTriggers<T extends Trigger>(more: { [key: string]: T | { new (p: Plugin): T } } = {}) {
|
|
|
|
this.registerTrigger('collection', CollectionTrigger);
|
|
|
|
this.registerTrigger('schedule', ScheduleTrigger);
|
2023-12-07 21:46:58 +08:00
|
|
|
|
|
|
|
for (const [name, trigger] of Object.entries(more)) {
|
2023-12-27 13:55:48 +08:00
|
|
|
this.registerTrigger(name, trigger);
|
2023-12-07 21:46:58 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-12-27 13:55:48 +08:00
|
|
|
private initInstructions<T extends Instruction>(more: { [key: string]: T | { new (p: Plugin): T } } = {}) {
|
|
|
|
this.registerInstruction('calculation', CalculationInstruction);
|
|
|
|
this.registerInstruction('condition', ConditionInstruction);
|
2024-01-25 22:10:03 +08:00
|
|
|
this.registerInstruction('end', EndInstruction);
|
2023-12-27 13:55:48 +08:00
|
|
|
this.registerInstruction('create', CreateInstruction);
|
|
|
|
this.registerInstruction('destroy', DestroyInstruction);
|
|
|
|
this.registerInstruction('query', QueryInstruction);
|
|
|
|
this.registerInstruction('update', UpdateInstruction);
|
2023-12-07 21:46:58 +08:00
|
|
|
|
|
|
|
for (const [name, instruction] of Object.entries({ ...more })) {
|
2023-12-27 13:55:48 +08:00
|
|
|
this.registerInstruction(name, instruction);
|
2023-12-07 21:46:58 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-06-20 23:29:21 +08:00
|
|
|
async load() {
|
|
|
|
const { db, options } = this;
|
|
|
|
|
2023-02-20 11:52:06 +08:00
|
|
|
initActions(this);
|
2023-12-07 21:46:58 +08:00
|
|
|
this.initTriggers(options.triggers);
|
|
|
|
this.initInstructions(options.instructions);
|
2023-02-20 11:52:06 +08:00
|
|
|
initFunctions(this, options.functions);
|
|
|
|
|
2023-04-10 21:00:29 +08:00
|
|
|
this.loggerCache = new LRUCache({
|
|
|
|
max: 20,
|
|
|
|
updateAgeOnGet: true,
|
|
|
|
dispose(logger) {
|
|
|
|
(<Logger>logger).end();
|
2023-04-25 13:12:14 +08:00
|
|
|
},
|
2023-04-10 21:00:29 +08:00
|
|
|
});
|
|
|
|
|
2024-01-03 09:59:33 +08:00
|
|
|
this.meter = this.app.telemetry.metric.getMeter();
|
|
|
|
const counter = this.meter.createObservableGauge('workflow.events.counter');
|
|
|
|
counter.addCallback((result) => {
|
|
|
|
result.observe(this.eventsCount);
|
|
|
|
});
|
|
|
|
|
2023-01-09 07:35:48 +08:00
|
|
|
this.app.acl.registerSnippet({
|
|
|
|
name: `pm.${this.name}.workflows`,
|
|
|
|
actions: [
|
|
|
|
'workflows:*',
|
|
|
|
'workflows.nodes:*',
|
|
|
|
'executions:list',
|
|
|
|
'executions:get',
|
2024-02-02 10:32:27 +08:00
|
|
|
'executions:cancel',
|
2023-01-09 07:35:48 +08:00
|
|
|
'flow_nodes:update',
|
|
|
|
'flow_nodes:destroy',
|
|
|
|
],
|
|
|
|
});
|
|
|
|
|
2023-08-09 12:12:57 +08:00
|
|
|
this.app.acl.registerSnippet({
|
|
|
|
name: 'ui.*',
|
|
|
|
actions: ['workflows:list'],
|
|
|
|
});
|
|
|
|
|
|
|
|
this.app.acl.allow('workflows', ['trigger'], 'loggedIn');
|
2023-01-09 07:35:48 +08:00
|
|
|
|
2024-01-08 18:59:56 +08:00
|
|
|
await this.importCollections(path.resolve(__dirname, 'collections'));
|
2022-06-20 23:29:21 +08:00
|
|
|
|
2022-12-06 18:18:40 +08:00
|
|
|
this.db.addMigrations({
|
2023-09-12 22:39:23 +08:00
|
|
|
namespace: this.name,
|
2022-12-06 18:18:40 +08:00
|
|
|
directory: path.resolve(__dirname, 'migrations'),
|
|
|
|
context: {
|
|
|
|
plugin: this,
|
|
|
|
},
|
|
|
|
});
|
|
|
|
|
2022-06-22 23:17:30 +08:00
|
|
|
db.on('workflows.beforeSave', this.onBeforeSave);
|
2022-06-20 23:29:21 +08:00
|
|
|
db.on('workflows.afterSave', (model: WorkflowModel) => this.toggle(model));
|
|
|
|
db.on('workflows.afterDestroy', (model: WorkflowModel) => this.toggle(model, false));
|
|
|
|
|
|
|
|
// [Life Cycle]:
|
|
|
|
// * load all workflows in db
|
|
|
|
// * add all hooks for enabled workflows
|
|
|
|
// * add hooks for create/update[enabled]/delete workflow to add/remove specific hooks
|
|
|
|
this.app.on('beforeStart', async () => {
|
|
|
|
const collection = db.getCollection('workflows');
|
|
|
|
const workflows = await collection.repository.find({
|
|
|
|
filter: { enabled: true },
|
|
|
|
});
|
|
|
|
|
|
|
|
workflows.forEach((workflow: WorkflowModel) => {
|
|
|
|
this.toggle(workflow);
|
|
|
|
});
|
2023-06-23 23:21:19 +08:00
|
|
|
});
|
2022-12-02 15:58:13 +08:00
|
|
|
|
2023-06-23 23:21:19 +08:00
|
|
|
this.app.on('afterStart', () => {
|
2023-08-24 17:47:45 +08:00
|
|
|
this.app.setMaintainingMessage('check for not started executions');
|
2023-09-12 22:39:23 +08:00
|
|
|
this.ready = true;
|
2022-12-02 15:58:13 +08:00
|
|
|
// check for not started executions
|
2022-12-03 14:34:47 +08:00
|
|
|
this.dispatch();
|
2022-06-20 23:29:21 +08:00
|
|
|
});
|
2022-06-24 23:28:49 +08:00
|
|
|
|
|
|
|
this.app.on('beforeStop', async () => {
|
2024-02-02 10:32:27 +08:00
|
|
|
const repository = db.getRepository('workflows');
|
|
|
|
const workflows = await repository.find({
|
2022-06-24 23:28:49 +08:00
|
|
|
filter: { enabled: true },
|
|
|
|
});
|
|
|
|
|
|
|
|
workflows.forEach((workflow: WorkflowModel) => {
|
|
|
|
this.toggle(workflow, false);
|
|
|
|
});
|
2023-09-12 22:39:23 +08:00
|
|
|
|
|
|
|
this.ready = false;
|
2023-12-20 10:13:08 +08:00
|
|
|
if (this.events.length) {
|
|
|
|
await this.prepare();
|
|
|
|
}
|
2023-09-12 22:39:23 +08:00
|
|
|
if (this.executing) {
|
|
|
|
await this.executing;
|
|
|
|
}
|
2022-06-24 23:28:49 +08:00
|
|
|
});
|
2022-06-20 23:29:21 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
toggle(workflow: WorkflowModel, enable?: boolean) {
|
|
|
|
const type = workflow.get('type');
|
|
|
|
const trigger = this.triggers.get(type);
|
2023-12-25 23:59:45 +08:00
|
|
|
if (!trigger) {
|
|
|
|
this.getLogger(workflow.id).error(`trigger type ${workflow.type} of workflow ${workflow.id} is not implemented`);
|
|
|
|
return;
|
|
|
|
}
|
2024-01-27 22:46:19 +08:00
|
|
|
if (enable ?? workflow.get('enabled')) {
|
2022-06-20 23:29:21 +08:00
|
|
|
// NOTE: remove previous listener if config updated
|
|
|
|
const prev = workflow.previous();
|
|
|
|
if (prev.config) {
|
|
|
|
trigger.off({ ...workflow.get(), ...prev });
|
|
|
|
}
|
|
|
|
trigger.on(workflow);
|
2024-03-29 09:09:12 +08:00
|
|
|
this.enabledCache.set(workflow.id, workflow);
|
2022-06-20 23:29:21 +08:00
|
|
|
} else {
|
|
|
|
trigger.off(workflow);
|
2024-03-29 09:09:12 +08:00
|
|
|
this.enabledCache.delete(workflow.id);
|
2022-06-20 23:29:21 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-01-25 22:10:03 +08:00
|
|
|
public trigger(
|
|
|
|
workflow: WorkflowModel,
|
|
|
|
context: object,
|
2024-02-02 10:32:27 +08:00
|
|
|
options: { [key: string]: any } & Transactionable = {},
|
2024-01-25 22:10:03 +08:00
|
|
|
): void | Promise<Processor | null> {
|
2023-12-20 10:13:08 +08:00
|
|
|
const logger = this.getLogger(workflow.id);
|
|
|
|
if (!this.ready) {
|
|
|
|
logger.warn(`app is not ready, event of workflow ${workflow.id} will be ignored`);
|
2024-01-25 22:10:03 +08:00
|
|
|
logger.debug(`ignored event data:`, context);
|
2023-12-20 10:13:08 +08:00
|
|
|
return;
|
|
|
|
}
|
2022-06-20 23:29:21 +08:00
|
|
|
// `null` means not to trigger
|
2023-12-20 10:13:08 +08:00
|
|
|
if (context == null) {
|
|
|
|
logger.warn(`workflow ${workflow.id} event data context is null, event will be ignored`);
|
2022-12-03 14:34:47 +08:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2024-01-25 22:10:03 +08:00
|
|
|
if (this.isWorkflowSync(workflow)) {
|
|
|
|
return this.triggerSync(workflow, context, options);
|
|
|
|
}
|
|
|
|
|
2024-02-02 10:32:27 +08:00
|
|
|
const { transaction, ...rest } = options;
|
|
|
|
this.events.push([workflow, context, rest]);
|
2024-01-03 09:59:33 +08:00
|
|
|
this.eventsCount = this.events.length;
|
2022-12-03 14:34:47 +08:00
|
|
|
|
2023-12-20 10:13:08 +08:00
|
|
|
logger.info(`new event triggered, now events: ${this.events.length}`);
|
2024-03-29 09:09:12 +08:00
|
|
|
logger.debug(`event data:`, { context });
|
2023-01-08 00:56:43 +08:00
|
|
|
|
2022-12-03 14:34:47 +08:00
|
|
|
if (this.events.length > 1) {
|
|
|
|
return;
|
2022-06-20 23:29:21 +08:00
|
|
|
}
|
|
|
|
|
2022-12-03 14:34:47 +08:00
|
|
|
// NOTE: no await for quick return
|
|
|
|
setTimeout(this.prepare);
|
|
|
|
}
|
|
|
|
|
2024-01-25 22:10:03 +08:00
|
|
|
private async triggerSync(
|
|
|
|
workflow: WorkflowModel,
|
|
|
|
context: object,
|
2024-02-02 10:32:27 +08:00
|
|
|
options: { [key: string]: any } & Transactionable = {},
|
2024-01-25 22:10:03 +08:00
|
|
|
): Promise<Processor | null> {
|
|
|
|
let execution;
|
|
|
|
try {
|
|
|
|
execution = await this.createExecution(workflow, context, options);
|
|
|
|
} catch (err) {
|
|
|
|
this.getLogger(workflow.id).error(`creating execution failed: ${err.message}`, err);
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
|
|
|
|
try {
|
|
|
|
return this.process(execution, null, options);
|
|
|
|
} catch (err) {
|
|
|
|
this.getLogger(execution.workflowId).error(`execution (${execution.id}) error: ${err.message}`, err);
|
|
|
|
}
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
|
2023-08-24 17:47:45 +08:00
|
|
|
public async resume(job) {
|
|
|
|
if (!job.execution) {
|
|
|
|
job.execution = await job.getExecution();
|
|
|
|
}
|
2023-12-20 10:13:08 +08:00
|
|
|
this.getLogger(job.execution.workflowId).info(
|
|
|
|
`execution (${job.execution.id}) resuming from job (${job.id}) added to pending list`,
|
|
|
|
);
|
2023-08-24 17:47:45 +08:00
|
|
|
this.pending.push([job.execution, job]);
|
|
|
|
this.dispatch();
|
|
|
|
}
|
|
|
|
|
|
|
|
public createProcessor(execution: ExecutionModel, options = {}): Processor {
|
|
|
|
return new Processor(execution, { ...options, plugin: this });
|
|
|
|
}
|
|
|
|
|
2024-01-25 22:10:03 +08:00
|
|
|
private async createExecution(workflow: WorkflowModel, context, options): Promise<ExecutionModel | null> {
|
2024-01-27 22:46:19 +08:00
|
|
|
const { transaction = await this.db.sequelize.transaction() } = options;
|
|
|
|
const trigger = this.triggers.get(workflow.type);
|
|
|
|
const valid = await trigger.validateEvent(workflow, context, { ...options, transaction });
|
|
|
|
if (!valid) {
|
|
|
|
if (!options.transaction) {
|
|
|
|
await transaction.commit();
|
2022-06-20 23:29:21 +08:00
|
|
|
}
|
2024-01-27 22:46:19 +08:00
|
|
|
return null;
|
2022-06-20 23:29:21 +08:00
|
|
|
}
|
|
|
|
|
2024-01-25 22:10:03 +08:00
|
|
|
const execution = await workflow.createExecution(
|
|
|
|
{
|
|
|
|
context,
|
|
|
|
key: workflow.key,
|
|
|
|
status: EXECUTION_STATUS.QUEUEING,
|
|
|
|
},
|
|
|
|
{ transaction },
|
|
|
|
);
|
2024-01-03 09:59:33 +08:00
|
|
|
|
2024-01-25 22:10:03 +08:00
|
|
|
this.getLogger(workflow.id).info(`execution of workflow ${workflow.id} created as ${execution.id}`);
|
2023-12-20 10:13:08 +08:00
|
|
|
|
2024-01-25 22:10:03 +08:00
|
|
|
await workflow.increment(['executed', 'allExecuted'], { transaction });
|
|
|
|
// NOTE: https://sequelize.org/api/v6/class/src/model.js~model#instance-method-increment
|
|
|
|
if (this.db.options.dialect !== 'postgres') {
|
|
|
|
await workflow.reload({ transaction });
|
|
|
|
}
|
|
|
|
|
|
|
|
await (<typeof WorkflowModel>workflow.constructor).update(
|
|
|
|
{
|
|
|
|
allExecuted: workflow.allExecuted,
|
|
|
|
},
|
|
|
|
{
|
|
|
|
where: {
|
|
|
|
key: workflow.key,
|
2023-12-20 10:13:08 +08:00
|
|
|
},
|
2024-01-25 22:10:03 +08:00
|
|
|
transaction,
|
|
|
|
},
|
|
|
|
);
|
2023-01-08 00:56:43 +08:00
|
|
|
|
2024-01-25 22:10:03 +08:00
|
|
|
if (!options.transaction) {
|
|
|
|
await transaction.commit();
|
|
|
|
}
|
2023-01-08 00:56:43 +08:00
|
|
|
|
2024-01-25 22:10:03 +08:00
|
|
|
execution.workflow = workflow;
|
|
|
|
|
|
|
|
return execution;
|
2023-12-20 10:13:08 +08:00
|
|
|
}
|
2022-06-20 23:29:21 +08:00
|
|
|
|
2023-12-20 10:13:08 +08:00
|
|
|
private prepare = async () => {
|
2024-01-27 22:46:19 +08:00
|
|
|
if (this.executing && this.db.options.dialect === 'sqlite') {
|
|
|
|
await this.executing;
|
|
|
|
}
|
|
|
|
|
2023-12-20 10:13:08 +08:00
|
|
|
const event = this.events.shift();
|
2024-01-03 09:59:33 +08:00
|
|
|
this.eventsCount = this.events.length;
|
2023-12-20 10:13:08 +08:00
|
|
|
if (!event) {
|
|
|
|
this.getLogger('dispatcher').warn(`events queue is empty, no need to prepare`);
|
|
|
|
return;
|
2022-12-05 09:38:37 +08:00
|
|
|
}
|
|
|
|
|
2023-12-20 10:13:08 +08:00
|
|
|
const logger = this.getLogger(event[0].id);
|
|
|
|
logger.info(`preparing execution for event`);
|
|
|
|
|
|
|
|
try {
|
2024-01-25 22:10:03 +08:00
|
|
|
const execution = await this.createExecution(...event);
|
2024-01-03 09:59:33 +08:00
|
|
|
// NOTE: cache first execution for most cases
|
2024-01-27 22:46:19 +08:00
|
|
|
if (execution && !this.executing && !this.pending.length) {
|
2024-01-03 09:59:33 +08:00
|
|
|
this.pending.push([execution]);
|
|
|
|
}
|
2023-12-20 10:13:08 +08:00
|
|
|
} catch (err) {
|
|
|
|
logger.error(`failed to create execution: ${err.message}`, err);
|
|
|
|
// this.events.push(event); // NOTE: retry will cause infinite loop
|
|
|
|
}
|
2023-07-13 23:14:25 +08:00
|
|
|
|
2022-12-03 14:34:47 +08:00
|
|
|
if (this.events.length) {
|
|
|
|
await this.prepare();
|
|
|
|
} else {
|
|
|
|
this.dispatch();
|
|
|
|
}
|
2023-02-13 09:57:03 +08:00
|
|
|
};
|
2022-06-20 23:29:21 +08:00
|
|
|
|
2023-09-12 22:39:23 +08:00
|
|
|
private dispatch() {
|
2023-12-20 10:13:08 +08:00
|
|
|
if (!this.ready) {
|
|
|
|
this.getLogger('dispatcher').warn(`app is not ready, new dispatching will be ignored`);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (this.executing) {
|
|
|
|
this.getLogger('dispatcher').warn(`workflow executing is not finished, new dispatching will be ignored`);
|
2022-11-14 20:05:01 +08:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2024-01-27 22:46:19 +08:00
|
|
|
if (this.events.length) {
|
|
|
|
return this.prepare();
|
|
|
|
}
|
|
|
|
|
2023-09-12 22:39:23 +08:00
|
|
|
this.executing = (async () => {
|
|
|
|
let next: Pending | null = null;
|
|
|
|
// resuming has high priority
|
|
|
|
if (this.pending.length) {
|
|
|
|
next = this.pending.shift() as Pending;
|
|
|
|
this.getLogger(next[0].workflowId).info(`pending execution (${next[0].id}) ready to process`);
|
|
|
|
} else {
|
|
|
|
const execution = (await this.db.getRepository('executions').findOne({
|
|
|
|
filter: {
|
|
|
|
status: EXECUTION_STATUS.QUEUEING,
|
2023-12-25 17:44:07 +08:00
|
|
|
'workflow.enabled': true,
|
2023-10-12 18:12:15 +08:00
|
|
|
'workflow.id': {
|
|
|
|
[Op.not]: null,
|
|
|
|
},
|
2023-09-12 22:39:23 +08:00
|
|
|
},
|
|
|
|
appends: ['workflow'],
|
|
|
|
sort: 'createdAt',
|
|
|
|
})) as ExecutionModel;
|
2023-12-25 17:44:07 +08:00
|
|
|
if (execution) {
|
2023-09-12 22:39:23 +08:00
|
|
|
this.getLogger(execution.workflowId).info(`execution (${execution.id}) fetched from db`);
|
|
|
|
next = [execution];
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if (next) {
|
|
|
|
await this.process(...next);
|
2022-11-14 20:05:01 +08:00
|
|
|
}
|
2023-07-13 23:14:25 +08:00
|
|
|
|
2023-09-12 22:39:23 +08:00
|
|
|
this.executing = null;
|
2023-07-13 23:14:25 +08:00
|
|
|
|
2023-09-12 22:39:23 +08:00
|
|
|
if (next) {
|
|
|
|
this.dispatch();
|
|
|
|
}
|
|
|
|
})();
|
2022-12-03 14:34:47 +08:00
|
|
|
}
|
|
|
|
|
2024-02-02 21:11:08 +08:00
|
|
|
private async process(execution: ExecutionModel, job?: JobModel, options: Transactionable = {}): Promise<Processor> {
|
2023-02-20 11:52:06 +08:00
|
|
|
if (execution.status === EXECUTION_STATUS.QUEUEING) {
|
2024-02-02 21:11:08 +08:00
|
|
|
await execution.update({ status: EXECUTION_STATUS.STARTED }, { transaction: options.transaction });
|
2022-11-14 20:05:01 +08:00
|
|
|
}
|
2024-03-29 09:09:12 +08:00
|
|
|
const logger = this.getLogger(execution.workflowId);
|
2024-02-02 21:11:08 +08:00
|
|
|
const processor = this.createProcessor(execution, options);
|
2022-11-14 20:05:01 +08:00
|
|
|
|
2024-03-29 09:09:12 +08:00
|
|
|
logger.info(`execution (${execution.id}) ${job ? 'resuming' : 'starting'}...`);
|
|
|
|
|
|
|
|
// this.emit('beforeProcess', processor);
|
2022-11-14 20:05:01 +08:00
|
|
|
|
2023-01-08 00:56:43 +08:00
|
|
|
try {
|
|
|
|
await (job ? processor.resume(job) : processor.start());
|
2024-03-29 09:09:12 +08:00
|
|
|
logger.info(`execution (${execution.id}) finished with status: ${execution.status}`, { execution });
|
2023-08-10 16:18:07 +08:00
|
|
|
if (execution.status && execution.workflow.options?.deleteExecutionOnStatus?.includes(execution.status)) {
|
|
|
|
await execution.destroy();
|
|
|
|
}
|
2023-01-08 00:56:43 +08:00
|
|
|
} catch (err) {
|
2024-03-29 09:09:12 +08:00
|
|
|
logger.error(`execution (${execution.id}) error: ${err.message}`, err);
|
2023-01-08 00:56:43 +08:00
|
|
|
}
|
2024-01-25 22:10:03 +08:00
|
|
|
|
2024-03-29 09:09:12 +08:00
|
|
|
// this.emit('afterProcess', processor);
|
|
|
|
|
2024-01-25 22:10:03 +08:00
|
|
|
return processor;
|
2022-11-10 13:33:52 +08:00
|
|
|
}
|
2024-03-29 09:09:12 +08:00
|
|
|
|
|
|
|
useDataSourceTransaction(dataSourceName = 'main', transaction, create = false) {
|
|
|
|
// @ts-ignore
|
|
|
|
const { db } = this.app.dataSourceManager.dataSources.get(dataSourceName).collectionManager;
|
|
|
|
if (!db) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
if (db.sequelize === transaction?.sequelize) {
|
|
|
|
return transaction;
|
|
|
|
}
|
|
|
|
if (create) {
|
|
|
|
return db.sequelize.transaction();
|
|
|
|
}
|
|
|
|
}
|
2022-06-20 23:29:21 +08:00
|
|
|
}
|