Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x | import { prisma } from "@/lib/prisma";
import { logger } from "@/lib/logging";
import type { WorkflowTriggerType, MarketingWorkflow, Prisma } from "@prisma/client";
import type {
WorkflowDefinition,
WorkflowStepConfig,
WorkflowExecutionContext } from "./types";
import { executeStep } from "./step-executor";
const LOG_CATEGORY = "WORKFLOW_ENGINE";
/**
* Workflow Engine - Handles workflow execution and management
*/
export class WorkflowEngine {
/**
* Trigger workflows based on an event
*/
static async trigger(
triggerType: WorkflowTriggerType,
userId: number,
triggerData: Record<string, unknown> = {}
): Promise<number[]> {
try {
// Find active workflows for this trigger
const workflows = await prisma.marketingWorkflow.findMany({
where: {
trigger: triggerType,
isActive: true,
isDraft: false}});
if (workflows.length === 0) {
return [];
}
const executionIds: number[] = [];
// Start each workflow
for (const workflow of workflows) {
try {
const executionId = await this.startWorkflow(
workflow,
userId,
triggerData
);
if (executionId) {
executionIds.push(executionId);
}
} catch (error) {
logger.error(`Failed to start workflow ${workflow.id}`, error instanceof Error ? error : new Error(String(error)), { category: LOG_CATEGORY });
}
}
return executionIds;
} catch (error) {
logger.error("Error triggering workflows", error instanceof Error ? error : new Error(String(error)), { category: LOG_CATEGORY });
return [];
}
}
/**
* Start a specific workflow for a user
*/
static async startWorkflow(
workflow: MarketingWorkflow,
userId: number,
triggerData: Record<string, unknown> = {}
): Promise<number | null> {
try {
// Check if user is already in this workflow
const existingExecution = await prisma.workflowExecution.findFirst({
where: {
workflowId: workflow.id,
userId,
status: { in: ["RUNNING", "WAITING"] }}});
if (existingExecution) {
logger.info(`User ${userId} already in workflow ${workflow.id}`, { category: LOG_CATEGORY });
return null;
}
// Create execution record
const execution = await prisma.workflowExecution.create({
data: {
workflowId: workflow.id,
userId,
status: "RUNNING",
currentStep: 0,
triggerData: triggerData as Prisma.JsonObject,
stepData: {} as Prisma.JsonObject}});
// Process the first step
await this.processExecution(execution.id);
return execution.id;
} catch (error) {
logger.error("Error starting workflow", error instanceof Error ? error : new Error(String(error)), { category: LOG_CATEGORY });
return null;
}
}
/**
* Process a workflow execution (run current step)
*/
static async processExecution(executionId: number): Promise<void> {
try {
const execution = await prisma.workflowExecution.findUnique({
where: { id: executionId },
include: { workflow: true, user: true }});
if (!execution) {
logger.error(`Execution ${executionId} not found`, new Error("Execution not found"), { category: LOG_CATEGORY });
return;
}
if (execution.status !== "RUNNING" && execution.status !== "WAITING") {
return;
}
const definition = execution.workflow.steps as unknown as WorkflowDefinition;
if (!definition || !definition.steps) {
logger.error(`Invalid workflow definition for ${execution.workflowId}`, new Error("Invalid workflow definition"), { category: LOG_CATEGORY });
await this.failExecution(executionId, "Invalid workflow definition");
return;
}
// Find the current step
const currentStepIndex = execution.currentStep;
const steps = definition.steps;
if (currentStepIndex >= steps.length) {
// Workflow complete
await this.completeExecution(executionId);
return;
}
const currentStep = steps[currentStepIndex];
if (!currentStep) {
await this.completeExecution(executionId);
return;
}
// Build execution context
const context: WorkflowExecutionContext = {
userId: execution.userId,
executionId: execution.id,
workflowId: execution.workflowId,
triggerData: (execution.triggerData as Record<string, unknown>) || {},
stepData: (execution.stepData as Record<string, unknown>) || {},
variables: {}};
// Create step execution record
const stepExecution = await prisma.workflowExecutionStep.create({
data: {
executionId,
stepIndex: currentStepIndex,
stepType: currentStep.type,
status: "RUNNING",
inputData: currentStep.config as unknown as Prisma.JsonObject,
startedAt: new Date()}});
try {
// Execute the step
const result = await executeStep(currentStep, context);
// Update step execution
await prisma.workflowExecutionStep.update({
where: { id: stepExecution.id },
data: {
status: result.success ? "COMPLETED" : "FAILED",
outputData: (result.data as Prisma.JsonObject) || null,
errorMessage: result.error,
completedAt: new Date()}});
if (!result.success) {
await this.failExecution(executionId, result.error || "Step failed");
return;
}
// Handle waiting
if (result.shouldWait && result.waitUntil) {
const mergedStepData = {
...(execution.stepData as Record<string, unknown>),
...result.data};
await prisma.workflowExecution.update({
where: { id: executionId },
data: {
status: "WAITING",
nextRunAt: result.waitUntil,
stepData: mergedStepData as Prisma.JsonObject}});
return;
}
// Move to next step
const nextStepIndex = this.getNextStepIndex(
steps,
currentStepIndex,
result.nextStepId
);
if (nextStepIndex === -1 || currentStep.type === "END") {
// Workflow complete
await this.completeExecution(executionId);
} else {
// Continue to next step
const updatedStepData = {
...(execution.stepData as Record<string, unknown>),
...result.data};
await prisma.workflowExecution.update({
where: { id: executionId },
data: {
currentStep: nextStepIndex,
stepData: updatedStepData as Prisma.JsonObject}});
// Process next step immediately (for non-blocking steps)
await this.processExecution(executionId);
}
} catch (error) {
const errorMessage =
error instanceof Error ? error.message : "Unknown error";
await prisma.workflowExecutionStep.update({
where: { id: stepExecution.id },
data: {
status: "FAILED",
errorMessage,
completedAt: new Date()}});
await this.failExecution(executionId, errorMessage);
}
} catch (error) {
logger.error("Error processing execution", error instanceof Error ? error : new Error(String(error)), { category: LOG_CATEGORY });
}
}
/**
* Get the index of the next step
*/
private static getNextStepIndex(
steps: WorkflowStepConfig[],
currentIndex: number,
nextStepId?: string
): number {
if (nextStepId) {
// Find step by ID
const index = steps.findIndex((s) => s.id === nextStepId);
if (index !== -1) return index;
}
// Check connections on current step
const currentStep = steps[currentIndex];
if (currentStep.connections && currentStep.connections.length > 0) {
const nextId = currentStep.connections[0];
const index = steps.findIndex((s) => s.id === nextId);
if (index !== -1) return index;
}
// Default to next sequential step
return currentIndex + 1;
}
/**
* Complete a workflow execution
*/
private static async completeExecution(executionId: number): Promise<void> {
await prisma.workflowExecution.update({
where: { id: executionId },
data: {
status: "COMPLETED",
completedAt: new Date()}});
logger.info(`Execution ${executionId} completed`, { category: LOG_CATEGORY });
}
/**
* Fail a workflow execution
*/
private static async failExecution(
executionId: number,
error: string
): Promise<void> {
await prisma.workflowExecution.update({
where: { id: executionId },
data: {
status: "FAILED",
completedAt: new Date(),
errorMessage: error}});
logger.error(`Execution ${executionId} failed: ${error}`, new Error(error), { category: LOG_CATEGORY });
}
/**
* Cancel a workflow execution
*/
static async cancelExecution(executionId: number): Promise<void> {
await prisma.workflowExecution.update({
where: { id: executionId },
data: {
status: "CANCELLED",
completedAt: new Date()}});
logger.info(`Execution ${executionId} cancelled`, { category: LOG_CATEGORY });
}
/**
* Process waiting executions (called by cron job)
*/
static async processWaitingExecutions(): Promise<number> {
try {
const waitingExecutions = await prisma.workflowExecution.findMany({
where: {
status: "WAITING",
nextRunAt: {
lte: new Date()}},
take: 100, // Process in batches
});
for (const execution of waitingExecutions) {
// Mark as running
await prisma.workflowExecution.update({
where: { id: execution.id },
data: {
status: "RUNNING",
nextRunAt: null}});
// Process the execution
await this.processExecution(execution.id);
}
return waitingExecutions.length;
} catch (error) {
logger.error("Error processing waiting executions", error instanceof Error ? error : new Error(String(error)), { category: LOG_CATEGORY });
return 0;
}
}
/**
* Get workflow statistics
*/
static async getWorkflowStats(workflowId: number) {
const [total, completed, failed, active] = await Promise.all([
prisma.workflowExecution.count({ where: { workflowId } }),
prisma.workflowExecution.count({
where: { workflowId, status: "COMPLETED" }}),
prisma.workflowExecution.count({
where: { workflowId, status: "FAILED" }}),
prisma.workflowExecution.count({
where: { workflowId, status: { in: ["RUNNING", "WAITING"] } }}),
]);
const lastExecution = await prisma.workflowExecution.findFirst({
where: { workflowId },
orderBy: { startedAt: "desc" }});
return {
totalExecutions: total,
completedExecutions: completed,
failedExecutions: failed,
activeExecutions: active,
completionRate: total > 0 ? (completed / total) * 100 : 0,
lastExecutedAt: lastExecution?.startedAt || null};
}
}
export default WorkflowEngine;
|