63 lines
2.3 KiB
TypeScript
63 lines
2.3 KiB
TypeScript
/**
|
|
* Marketing-Funnel Phase 3 (Phase 05 #80) — sequence step scheduler.
|
|
*
|
|
* BullMQ job handler for the `email-sequence.step` queue. The trigger
|
|
* handler (and the step engine itself) enqueues a delayed job with
|
|
* `{ runId, stepIndex, runAt }`. BullMQ wakes the worker at `runAt`
|
|
* and this handler invokes the pure {@link runStep} routine with the
|
|
* injected store + mail-sender + template renderer.
|
|
*
|
|
* Storage / mail / template surfaces are bound by the worker bootstrap
|
|
* in production; tests pass in-memory fakes.
|
|
*/
|
|
|
|
import { runStep, type StepRunnerDeps, type StepRunResult } from "@toolctrl/email-sequences";
|
|
|
|
export const EMAIL_SEQUENCE_QUEUE = "email-sequence.step" as const;
|
|
export const EMAIL_SEQUENCE_STEP_JOB_NAME = "run-email-sequence-step" as const;
|
|
|
|
export interface EmailSequenceStepJobData {
|
|
readonly runId: string;
|
|
readonly stepIndex: number;
|
|
/** ISO timestamp the job was scheduled for — for tracing only. */
|
|
readonly scheduledFor?: string;
|
|
}
|
|
|
|
export class EmailSequenceStepJobError extends Error {
|
|
override readonly name = "EmailSequenceStepJobError";
|
|
readonly code: "INVALID_PAYLOAD";
|
|
constructor(message: string, code: EmailSequenceStepJobError["code"]) {
|
|
super(message);
|
|
this.code = code;
|
|
}
|
|
}
|
|
|
|
export function parseEmailSequenceStepJob(data: unknown): EmailSequenceStepJobData {
|
|
if (!data || typeof data !== "object") {
|
|
throw new EmailSequenceStepJobError("scheduler job missing data envelope", "INVALID_PAYLOAD");
|
|
}
|
|
const e = data as Record<string, unknown>;
|
|
if (typeof e.runId !== "string" || e.runId.length === 0) {
|
|
throw new EmailSequenceStepJobError("scheduler job missing runId", "INVALID_PAYLOAD");
|
|
}
|
|
if (typeof e.stepIndex !== "number" || !Number.isInteger(e.stepIndex) || e.stepIndex < 0) {
|
|
throw new EmailSequenceStepJobError("scheduler job stepIndex invalid", "INVALID_PAYLOAD");
|
|
}
|
|
return {
|
|
runId: e.runId,
|
|
stepIndex: e.stepIndex,
|
|
scheduledFor: typeof e.scheduledFor === "string" ? e.scheduledFor : undefined,
|
|
};
|
|
}
|
|
|
|
export async function runEmailSequenceStepJob(
|
|
data: unknown,
|
|
deps: StepRunnerDeps
|
|
): Promise<StepRunResult> {
|
|
if (process.env.MARKETING_SEQUENCES_ENABLED !== "true") {
|
|
return { action: "cancelled", completed: true };
|
|
}
|
|
const job = parseEmailSequenceStepJob(data);
|
|
return runStep({ runId: job.runId, stepIndex: job.stepIndex }, deps);
|
|
}
|