@5minds/processcube_engine
Version:
The ProcessCube Engine. Stores and executes BPMNs.
259 lines • 13.6 kB
JavaScript
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.StartTimerEventHandler = void 0;
const inversify_1 = require("inversify");
const processcube_engine_sdk_1 = require("@5minds/processcube_engine_sdk");
const index_1 = require("../../../Contracts/index");
const index_2 = require("../../../Tools/DatabaseAdaptersSequelize/index");
const EventAggregator_1 = __importDefault(require("../../../Tools/EventAggregator"));
const EventMiddlewareHandler_1 = require("../../../Tools/EventMiddlewareHandler");
const TimerFacade_1 = require("../../Facades/TimerFacade");
const ProcessInstance_1 = require("../../ProcessInstance");
const FlowNodeHandlerFactory_1 = require("../FlowNodeHandlerFactory");
const EventHandler_1 = require("./EventHandler");
let StartTimerEventHandler = class StartTimerEventHandler extends EventHandler_1.EventHandler {
timerFacade;
timerSubscription;
eventName;
constructor(eventMiddlewareHandler, flowNodeHandlerFactory, flowNodeInstanceDatabaseAdapter, timerFacade, startEventModel, processInstance) {
super(eventMiddlewareHandler, flowNodeHandlerFactory, flowNodeInstanceDatabaseAdapter, startEventModel, processInstance, 'timer_start_event_handler');
this.timerFacade = timerFacade;
}
get startEvent() {
return this.flowNode;
}
async beforeExecute(resolveFunction, rejectFunction) {
await super.beforeExecute(resolveFunction, rejectFunction);
this.processToken = this.processInstance.getInitialPayload() ?? {};
}
async persistOnSuspend() {
await super.persistOnSuspend({
eventName: this.getEvaluatedEventName(),
triggerValue: this.startEvent.triggerValueInToken,
triggeredByFlowNodeInstanceId: this.triggeredByFlowNodeInstanceId,
});
}
async persistOnTerminate() {
await super.persistOnTerminate({
type: index_1.FlowNodeInstanceDataTypes.catchEvent,
eventName: this.getEvaluatedEventName(),
triggerValue: this.startEvent.triggerValueInToken,
triggeredByFlowNodeInstanceId: this.triggeredByFlowNodeInstanceId,
});
this.publishStartEventFinishedNotification();
}
async persistOnError(error) {
await super.persistOnError(error, {
type: index_1.FlowNodeInstanceDataTypes.catchEvent,
eventName: this.getEvaluatedEventName(),
triggerValue: this.startEvent.triggerValueInToken,
triggeredByFlowNodeInstanceId: this.triggeredByFlowNodeInstanceId,
});
this.publishStartEventFinishedNotification();
}
async persistOnExit() {
await super.persistOnExit({
type: index_1.FlowNodeInstanceDataTypes.catchEvent,
eventName: this.getEvaluatedEventName(),
triggerValue: this.startEvent.triggerValueInToken,
triggeredByFlowNodeInstanceId: this.triggeredByFlowNodeInstanceId,
});
this.publishStartEventFinishedNotification();
}
async startExecution() {
this.logger.debug(`Executing TimerStartEvent instance.`);
return this.executeHandler();
}
async resumeAfterSuspend(flowNodeInstance) {
const handlerPromise = new Promise(async (resolve, reject) => {
try {
this.onInterruptedCallback = () => {
this.timerFacade.cancelTimerSubscription(this.timerSubscription);
reject();
};
this.eventName = flowNodeInstance.eventName || (await this.executeTimerExpressionIfNeeded());
const newTokenPayload = await new Promise(async (timerResolve) => {
this.waitForTimerToElapse(timerResolve);
});
this.processToken = newTokenPayload;
const nextFlowNodeInfo = this.processInstance.getProcessModelFacade().getNextFlowNodesFor(this.startEvent);
return resolve(nextFlowNodeInfo);
}
catch (error) {
return reject(error);
}
});
return handlerPromise;
}
async executeHandler() {
const handlerPromise = new Promise(async (resolve, reject) => {
try {
this.onInterruptedCallback = () => {
this.timerFacade.cancelTimerSubscription(this.timerSubscription);
reject();
};
this.sendProcessStartedMessage();
this.validateTimer();
// Cyclic TimerStartEvents are started automatically through the Cronjob Service.
// All other Timer types are started through this handler, since they cannot be scheduled.
if (this.startEvent.timerEventDefinition != undefined) {
this.eventName = await this.executeTimerExpressionIfNeeded();
if (this.startEvent.timerEventDefinition.timerType !== processcube_engine_sdk_1.Model.Events.TimerType.timeCycle) {
const newTokenPayload = await this.suspendAndWaitForTimerToElapse();
this.processToken = newTokenPayload;
}
}
const nextFlowNodeInfo = this.processInstance.getProcessModelFacade().getNextFlowNodesFor(this.startEvent);
return resolve(nextFlowNodeInfo);
}
catch (error) {
return reject(error);
}
});
return handlerPromise;
}
sendProcessStartedMessage() {
const processStartedMessage = {
correlationId: this.processInstance.getCorrelationId(),
processDefinitionId: this.processInstance.getProcessDefinitionId(),
processModelId: this.processInstance.getProcessModelId(),
embeddedProcessModelId: this.processInstance.getEmbeddedProcessModelId(),
processModelName: this.processInstance.getProcessModelName(),
processInstanceId: this.processInstance.getProcessInstanceId(),
parentProcessInstanceId: this.processInstance.getParentProcessInstance()?.getProcessInstanceId(),
flowNodeId: this.startEvent.id,
flowNodeName: this.startEvent.name,
flowNodeInstanceId: this.flowNodeInstanceId,
processInstanceOwner: this.processInstance.getOwner(),
currentToken: this.processToken,
eventType: this.flowNode.eventType,
eventName: this.startEvent.timerEventDefinition?.value,
};
EventAggregator_1.default.publish(index_1.eventAggregatorSettings.messagePaths.processStarted, processStartedMessage);
const processStartedBaseName = index_1.eventAggregatorSettings.messagePaths.processInstanceWithIdStarted;
const processModelIdParam = index_1.eventAggregatorSettings.messageParams.processModelId;
const processWithIdStartedMessage = processStartedBaseName.replace(processModelIdParam, this.processInstance.getProcessModelId());
EventAggregator_1.default.publish(processWithIdStartedMessage, processStartedMessage);
}
async suspendAndWaitForTimerToElapse() {
return new Promise(async (resolve, reject) => {
try {
this.logger.debug('Initializing Timer');
await this.waitForTimerToElapse(resolve);
this.logger.debug('Suspending Start event until timer expires');
await this.persistOnSuspend();
}
catch (error) {
reject(error);
}
});
}
async waitForTimerToElapse(resolveFunc) {
const timerElapsed = () => {
this.logger.debug('Timer has expired, continuing execution');
this.timerFacade.cancelTimerSubscription(this.timerSubscription);
resolveFunc(this.processToken);
};
this.timerSubscription = this.timerFacade.initializeTimer(this.startEvent.id, this.startEvent.timerEventDefinition.timerType, this.eventName, timerElapsed, this.startEvent);
const triggerTimerImmediatelyEvent = index_1.eventAggregatorSettings.messagePaths.triggerTimerEvent.replace(index_1.eventAggregatorSettings.messageParams.flowNodeInstanceId, this.flowNodeInstanceId);
EventAggregator_1.default.subscribeOnce(triggerTimerImmediatelyEvent, () => {
this.timerFacade.triggerTimerImmediately(this.timerSubscription, this.startEvent.timerEventDefinition.timerType);
});
}
async executeTimerExpressionIfNeeded() {
const timerExpression = this.startEvent.timerEventDefinition.value;
const isConstantTimerExpression = !timerExpression ||
!this.processInstance
.getProcessTokenService()
.getAvailableParametersForExpressions()
.some((param) => timerExpression.includes(param));
if (isConstantTimerExpression) {
return timerExpression;
}
try {
return this.processInstance.executeRuntimeExpression({
expression: timerExpression,
currentFlowNode: this.startEvent,
currentToken: this.processToken,
previousFlowNode: this.processInstance.getProcessModelFacade().getPreviousFlowNodesFor(this.startEvent)?.pop(),
allowNonObjectResults: true,
});
}
catch (err) {
err.additionalInformation = {
processInstanceId: this.processInstance.getProcessInstanceId(),
correlationId: this.processInstance.getCorrelationId(),
};
this.logger.error(err);
throw err;
}
}
validateTimer() {
if (!this.startEvent.timerEventDefinition.timerType || !this.startEvent.timerEventDefinition.value) {
const errorToThrow = new processcube_engine_sdk_1.BadRequestError('Start Timer Event does not have a type or definition assigned.', 'process');
errorToThrow.additionalInformation = {
flowNodeInstanceId: this.flowNodeInstanceId,
flowNodeId: this.startEvent.id,
flowNodeName: this.startEvent.name,
processInstanceId: this.processInstance.getProcessInstanceId(),
processModelId: this.processInstance.getProcessModelId(),
embeddedProcessModelId: this.processInstance.getEmbeddedProcessModelId(),
correlationId: this.processInstance.getCorrelationId(),
};
throw errorToThrow;
}
}
getEvaluatedEventName() {
if (!this.eventName) {
return;
}
if (typeof this.eventName?.toISOString === 'function') {
return this.eventName.toISOString();
}
if (typeof this.eventName != 'string') {
return JSON.stringify(this.eventName);
}
return this.eventName;
}
publishStartEventFinishedNotification() {
const message = {
correlationId: this.processInstance.getCorrelationId(),
processDefinitionId: this.processInstance.getProcessDefinitionId(),
processModelId: this.processInstance.getProcessModelId(),
embeddedProcessModelId: this.processInstance.getEmbeddedProcessModelId(),
processModelName: this.processInstance.getProcessModelName(),
processInstanceId: this.processInstance.getProcessInstanceId(),
parentProcessInstanceId: this.processInstance.getParentProcessInstance()?.getProcessInstanceId(),
flowNodeId: this.flowNode.id,
flowNodeName: this.flowNode.name,
flowNodeInstanceId: this.flowNodeInstanceId,
processInstanceOwner: this.processInstance.getOwner(),
currentToken: this.processToken,
previousFlowNodeInstanceId: this.previousFlowNodeInstanceId,
eventType: this.flowNode.eventType,
eventName: this.startEvent.timerEventDefinition?.value,
};
EventAggregator_1.default.publish(index_1.eventAggregatorSettings.messagePaths.startEventFinished, message);
}
};
exports.StartTimerEventHandler = StartTimerEventHandler;
exports.StartTimerEventHandler = StartTimerEventHandler = __decorate([
(0, inversify_1.injectable)(),
__metadata("design:paramtypes", [EventMiddlewareHandler_1.EventMiddlewareHandler,
FlowNodeHandlerFactory_1.FlowNodeHandlerFactory,
index_2.FlowNodeInstanceDatabaseAdapter,
TimerFacade_1.TimerFacade, Object, ProcessInstance_1.ProcessInstance])
], StartTimerEventHandler);
//# sourceMappingURL=StartTimerEventHandler.js.map