Files

197 lines
6.9 KiB
TypeScript

/**
* Sequence-execution engine.
*
* Two entry points:
* - `startSequenceRun()` — called by the trigger worker. Materialises
* an EmailSequenceRun row + a pending Step-0 delivery + schedules
* the first step.
* - `advanceSequenceRun()` — called by the step-runner after a step
* completes. Materialises the next step's delivery row + schedules
* it; flips the run to `completed` when no more steps remain.
*
* Storage + queue are injected so the engine stays testable.
*/
import type { SequenceDefinition, SequenceStep, SequenceTriggerContext } from "./types.js";
import { parseSequenceSteps } from "./types.js";
import { evaluateAllConditions } from "./conditions.js";
export type SequenceRunStatus = "pending" | "running" | "completed" | "cancelled" | "unsubscribed" | "failed";
export type StepDeliveryStatus = "pending" | "sent" | "skipped" | "bounced" | "failed";
export interface SequenceRunRow {
readonly id: string;
readonly sequenceId: string;
readonly leadId: string | null;
readonly tenantId: string | null;
readonly triggerEventId: string | null;
readonly status: SequenceRunStatus;
readonly startedAt: Date;
readonly completedAt: Date | null;
readonly stepStateJson: Readonly<Record<string, unknown>> | null;
}
export interface StepDeliveryRow {
readonly id: string;
readonly runId: string;
readonly stepIndex: number;
readonly status: StepDeliveryStatus;
readonly scheduledAt: Date;
}
/**
* Storage surface required by the engine. Implementations wrap Prisma
* (in the worker) or in-memory fakes (in tests).
*/
export interface SequenceEngineStore {
createRun(input: {
sequenceId: string;
leadId: string | null;
tenantId: string | null;
triggerEventId: string | null;
}): Promise<SequenceRunRow>;
/** Idempotent — returns the existing run if `(sequenceId,triggerEventId)` already exists. */
findRunByTrigger(sequenceId: string, triggerEventId: string): Promise<SequenceRunRow | null>;
updateRunStatus(runId: string, status: SequenceRunStatus, completedAt?: Date | null): Promise<void>;
createDelivery(input: { runId: string; stepIndex: number; scheduledAt: Date }): Promise<StepDeliveryRow>;
}
/**
* Queue surface — `scheduleStep` enqueues a delayed job that wakes up
* at `runAt` and invokes the step-runner.
*/
export interface SequenceEngineQueue {
scheduleStep(args: { runId: string; stepIndex: number; runAt: Date }): Promise<void>;
}
export interface SequenceEngineLogger {
info?: (record: Record<string, unknown>, message?: string) => void;
warn?: (record: Record<string, unknown>, message?: string) => void;
error: (record: Record<string, unknown>, message?: string) => void;
}
export interface SequenceEngineDeps {
readonly store: SequenceEngineStore;
readonly queue: SequenceEngineQueue;
readonly logger?: SequenceEngineLogger;
readonly now?: () => Date;
}
export interface StartSequenceRunArgs {
readonly sequence: SequenceDefinition;
readonly trigger: SequenceTriggerContext;
}
export interface StartSequenceRunResult {
readonly run: SequenceRunRow;
readonly firstDelivery: StepDeliveryRow | null;
readonly scheduled: boolean;
/** True when an existing run was returned instead of inserting a duplicate. */
readonly alreadyExisted: boolean;
}
/**
* Resolve the steps array, applying sequence-level enable + condition
* gating before producing the first delivery row.
*/
export async function startSequenceRun(
args: StartSequenceRunArgs,
deps: SequenceEngineDeps
): Promise<StartSequenceRunResult> {
const { sequence, trigger } = args;
if (!sequence.isEnabled) {
return emptyResult();
}
if (!evaluateAllConditions(trigger.payload, sequence.conditions)) {
deps.logger?.info?.(
{ op: "sequence.skipped.sequence_conditions", sequenceId: sequence.id },
"sequence-level conditions not met"
);
return emptyResult();
}
const steps = parseSequenceSteps(sequence.steps as unknown);
if (steps.length === 0) {
return emptyResult();
}
if (trigger.triggerEventId) {
const existing = await deps.store.findRunByTrigger(sequence.id, trigger.triggerEventId);
if (existing) {
return { run: existing, firstDelivery: null, scheduled: false, alreadyExisted: true };
}
}
const run = await deps.store.createRun({
sequenceId: sequence.id,
leadId: trigger.leadId ?? null,
tenantId: trigger.tenantId ?? null,
triggerEventId: trigger.triggerEventId ?? null,
});
const firstStep = steps[0]!;
const now = (deps.now ?? (() => new Date()))();
const scheduledAt = new Date(now.getTime() + firstStep.delayHours * 60 * 60 * 1000);
const delivery = await deps.store.createDelivery({
runId: run.id,
stepIndex: firstStep.stepIndex,
scheduledAt,
});
await deps.queue.scheduleStep({ runId: run.id, stepIndex: firstStep.stepIndex, runAt: scheduledAt });
deps.logger?.info?.(
{ op: "sequence.run.started", sequenceId: sequence.id, runId: run.id, stepIndex: firstStep.stepIndex },
"sequence run started"
);
return { run, firstDelivery: delivery, scheduled: true, alreadyExisted: false };
}
function emptyResult(): StartSequenceRunResult {
const placeholder: SequenceRunRow = {
id: "",
sequenceId: "",
leadId: null,
tenantId: null,
triggerEventId: null,
status: "cancelled",
startedAt: new Date(0),
completedAt: null,
stepStateJson: null,
};
return { run: placeholder, firstDelivery: null, scheduled: false, alreadyExisted: false };
}
export interface AdvanceArgs {
readonly run: SequenceRunRow;
readonly steps: readonly SequenceStep[];
readonly previousStepIndex: number;
}
export interface AdvanceResult {
readonly nextDelivery: StepDeliveryRow | null;
readonly scheduledAt: Date | null;
readonly completed: boolean;
}
/**
* After a step finishes (sent, skipped or bounced) move to the next.
* Marks the run completed when no further step exists.
*/
export async function advanceSequenceRun(args: AdvanceArgs, deps: SequenceEngineDeps): Promise<AdvanceResult> {
const { run, steps, previousStepIndex } = args;
const sorted = [...steps].sort((a, b) => a.stepIndex - b.stepIndex);
const nextIdx = sorted.findIndex((s) => s.stepIndex > previousStepIndex);
if (nextIdx === -1) {
await deps.store.updateRunStatus(run.id, "completed", (deps.now ?? (() => new Date()))());
deps.logger?.info?.({ op: "sequence.run.completed", runId: run.id }, "sequence run completed");
return { nextDelivery: null, scheduledAt: null, completed: true };
}
const nextStep = sorted[nextIdx]!;
const now = (deps.now ?? (() => new Date()))();
const scheduledAt = new Date(now.getTime() + nextStep.delayHours * 60 * 60 * 1000);
const delivery = await deps.store.createDelivery({
runId: run.id,
stepIndex: nextStep.stepIndex,
scheduledAt,
});
await deps.queue.scheduleStep({ runId: run.id, stepIndex: nextStep.stepIndex, runAt: scheduledAt });
return { nextDelivery: delivery, scheduledAt, completed: false };
}