File size: 18,014 Bytes
8dd52b2 e140d17 e4885de e140d17 8dd52b2 e140d17 8dd52b2 e140d17 8dd52b2 e140d17 8dd52b2 e140d17 8dd52b2 e140d17 8dd52b2 e140d17 8dd52b2 e140d17 8dd52b2 e140d17 98720a6 e140d17 8dd52b2 e140d17 98720a6 e140d17 b8dc207 e140d17 b8dc207 e140d17 b8dc207 e140d17 b8dc207 e140d17 b8dc207 e140d17 b8dc207 e140d17 b8dc207 e140d17 b8dc207 e140d17 b8dc207 e140d17 8dd52b2 e140d17 b8dc207 e140d17 98720a6 e140d17 8dd52b2 e140d17 8dd52b2 e140d17 8dd52b2 e140d17 8dd52b2 e140d17 8dd52b2 e140d17 8dd52b2 e140d17 8dd52b2 e140d17 8dd52b2 e140d17 8dd52b2 e140d17 8dd52b2 e140d17 8dd52b2 e140d17 8dd52b2 e140d17 8dd52b2 e140d17 8dd52b2 e140d17 8dd52b2 e140d17 b8dc207 e140d17 b8dc207 e140d17 b8dc207 e140d17 b8dc207 e140d17 b8dc207 e140d17 b8dc207 e140d17 b8dc207 e140d17 b8dc207 e140d17 b8dc207 e140d17 b8dc207 e140d17 b8dc207 e140d17 b8dc207 e140d17 b8dc207 e140d17 b8dc207 e140d17 b8dc207 e140d17 b8dc207 e140d17 b8dc207 59697b4 e140d17 b8dc207 e140d17 b8dc207 e140d17 b8dc207 e140d17 b8dc207 e140d17 b8dc207 e140d17 b8dc207 e140d17 b8dc207 e140d17 8dd52b2 e140d17 8dd52b2 e140d17 b8dc207 e140d17 b8dc207 e140d17 b8dc207 e140d17 b8dc207 e140d17 b8dc207 e140d17 b8dc207 e140d17 b8dc207 e140d17 b8dc207 59697b4 e140d17 | 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 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 | /* eslint-disable @typescript-eslint/no-explicit-any */
import { Job, Queue, Worker } from "bullmq";
import { and, eq, gte, isNull, lt, or, sql } from "drizzle-orm";
import type Redis from "ioredis";
import { db } from "@/db";
import {
automationWorkflows,
businesses,
emailLogs,
emailTemplates,
notifications,
users,
workflowExecutionLogs,
} from "@/db/schema";
import { interpolateTemplate, sendColdEmail } from "@/lib/email";
import { getRedis } from "@/lib/redis";
import { sendWhatsAppMessage } from "@/lib/whatsapp/client";
import type { ScraperSourceName } from "@/lib/scrapers/types";
interface EmailJobData {
userId: string;
businessId: string;
templateId: string;
accessToken: string;
}
interface ScrapingJobData {
userId: string;
jobId: string;
keywords: string[];
location: string;
targetBusinessType: string;
sources?: ScraperSourceName[];
}
interface WorkflowJobData {
workflowId: string;
userId: string;
businessId: string;
executionId: string;
}
interface QueueStats {
waiting: number;
active: number;
completed: number;
failed: number;
}
interface QueueWorkers {
emailWorker: Worker<EmailJobData>;
scrapingWorker: Worker<ScrapingJobData>;
workflowWorker: Worker<WorkflowJobData>;
}
let queueConnection: Redis | null = null;
let emailQueueInstance: Queue<EmailJobData> | null = null;
let scrapingQueueInstance: Queue<ScrapingJobData> | null = null;
let workflowQueueInstance: Queue<WorkflowJobData> | null = null;
let workerBundle: QueueWorkers | null = null;
function getQueueConnection(): Redis {
if (queueConnection) {
return queueConnection;
}
const connection = getRedis();
if (!connection) {
throw new Error("Redis/Valkey is required for queue operations.");
}
queueConnection = connection;
return connection;
}
function getEmailQueue() {
if (!emailQueueInstance) {
emailQueueInstance = new Queue<EmailJobData>("email-outreach", {
connection: getQueueConnection() as any,
});
}
return emailQueueInstance;
}
function getScrapingQueue() {
if (!scrapingQueueInstance) {
scrapingQueueInstance = new Queue<ScrapingJobData>("google-maps-scraping", {
connection: getQueueConnection() as any,
});
}
return scrapingQueueInstance;
}
function getWorkflowQueue() {
if (!workflowQueueInstance) {
workflowQueueInstance = new Queue<WorkflowJobData>("workflow-execution", {
connection: getQueueConnection() as any,
});
}
return workflowQueueInstance;
}
export async function queueEmail(data: EmailJobData) {
await getEmailQueue().add("send-email", data, {
attempts: 3,
backoff: {
type: "exponential",
delay: 2000,
},
});
}
export async function queueScraping(params: ScrapingJobData) {
await getScrapingQueue().add("scrape-google-maps", params, {
attempts: 3,
backoff: { type: "exponential", delay: 2000 },
removeOnComplete: { count: 100 },
removeOnFail: { count: 100 },
});
}
export async function queueWorkflowExecution(data: WorkflowJobData) {
await ensureWorkflowExecutionQueued(data);
}
async function ensureWorkflowExecutionQueued(data: WorkflowJobData) {
const queue = getWorkflowQueue();
const existingJob = await queue.getJob(data.executionId);
if (existingJob) {
return existingJob;
}
return queue.add("execute-workflow", data, {
jobId: data.executionId,
attempts: 3,
backoff: {
type: "exponential",
delay: 2000,
},
removeOnComplete: { count: 100 },
removeOnFail: { count: 200 },
});
}
async function processEmailJob(job: Job<EmailJobData>) {
const { userId, businessId, templateId, accessToken } = job.data;
try {
const [business] = await db
.select()
.from(businesses)
.where(eq(businesses.id, businessId))
.limit(1);
if (!business) {
throw new Error("Business not found");
}
const [template] = await db
.select()
.from(emailTemplates)
.where(eq(emailTemplates.id, templateId))
.limit(1);
if (!template) {
throw new Error("Template not found");
}
const startOfDay = new Date();
startOfDay.setHours(0, 0, 0, 0);
const endOfDay = new Date();
endOfDay.setHours(23, 59, 59, 999);
const [usage] = await db
.select({ count: sql<number>`count(*)` })
.from(emailLogs)
.where(
and(
eq(emailLogs.userId, userId),
eq(emailLogs.status, "sent"),
gte(emailLogs.sentAt, startOfDay),
lt(emailLogs.sentAt, endOfDay)
)
);
if (usage && usage.count >= 50) {
const now = new Date();
const tomorrow = new Date(now);
tomorrow.setDate(tomorrow.getDate() + 1);
tomorrow.setHours(0, 0, 0, 0);
const delay = tomorrow.getTime() - now.getTime() + 60000;
console.log(
`Daily email limit reached (${usage.count}/50). Delaying job ${job.id} by ${Math.round(
delay / 1000 / 60
)} minutes.`
);
await job.moveToDelayed(Date.now() + delay, job.token);
return { delayed: true, reason: "Daily limit reached" };
}
const sender = await db.query.users.findFirst({
where: eq(users.id, userId),
});
if (!sender) {
throw new Error("Sender not found");
}
const [logEntry] = await db
.insert(emailLogs)
.values({
userId,
businessId: business.id,
templateId: template.id,
subject: interpolateTemplate(template.subject, business, sender),
body: "",
status: "pending",
errorMessage: null,
sentAt: null,
})
.returning();
const trackingDomain = process.env.NEXT_PUBLIC_APP_URL || "http://localhost:3000";
const pixelUrl = `${trackingDomain}/api/tracking/open?id=${logEntry.id}`;
const trackingPixel =
`<img src="${pixelUrl}" alt="" width="1" height="1" style="display:none;" />`;
let finalBody = interpolateTemplate(template.body, business, sender);
finalBody = finalBody.replace(/href=["']([^"']+)["']/g, (_match, url) => {
const encodedUrl = encodeURIComponent(url);
const trackingUrl = `${trackingDomain}/api/tracking/click?id=${logEntry.id}&url=${encodedUrl}`;
return `href="${trackingUrl}"`;
});
finalBody += trackingPixel;
await db.update(emailLogs).set({ body: finalBody }).where(eq(emailLogs.id, logEntry.id));
const emailResult = await sendColdEmail(business, template, accessToken, sender);
const success = emailResult.success;
const error = emailResult.error;
await db
.update(emailLogs)
.set({
status: success ? "sent" : "failed",
errorMessage: error,
sentAt: success ? new Date() : null,
})
.where(eq(emailLogs.id, logEntry.id));
await db
.update(businesses)
.set({
emailSent: true,
emailSentAt: new Date(),
emailStatus: success ? "sent" : "failed",
updatedAt: new Date(),
})
.where(eq(businesses.id, business.id));
if (!success) {
throw new Error(error || "Failed to send email");
}
return { success: true, businessId };
} catch (error: unknown) {
const errorMessage = error instanceof Error ? error.message : String(error);
await db.insert(emailLogs).values({
userId,
businessId,
templateId,
subject: "Cold Outreach",
body: "Failed to send",
status: "failed",
errorMessage,
});
throw new Error(errorMessage);
}
}
async function processScrapingJob(job: Job<ScrapingJobData>) {
const { userId, jobId, keywords, location, sources = ["google-maps"] } = job.data;
console.log(`Starting scraping job ${job.id} for record ${jobId}`);
const { scrapingJobs } = await import("@/db/schema");
const { eq } = await import("drizzle-orm");
const { scrapeMultiSource } = await import("./scrapers");
try {
let [jobRecord] = await db
.select()
.from(scrapingJobs)
.where(eq(scrapingJobs.id, jobId))
.limit(1);
if (!jobRecord) {
throw new Error(`Job ${jobId} not found`);
}
await db.update(scrapingJobs).set({ status: "running" }).where(eq(scrapingJobs.id, jobId));
let totalFound = jobRecord.businessesFound || 0;
let loopCount = 0;
const maxLoops = 50;
while (true) {
loopCount += 1;
[jobRecord] = await db
.select()
.from(scrapingJobs)
.where(eq(scrapingJobs.id, jobId))
.limit(1);
if (!jobRecord) {
break;
}
if (jobRecord.status === "paused") {
await new Promise((resolve) => setTimeout(resolve, 5000));
continue;
}
if (jobRecord.status === "failed" || jobRecord.status === "completed") {
break;
}
const jitter = Math.floor(Math.random() * 5000);
await new Promise((resolve) => setTimeout(resolve, 2000 + jitter));
const results = await scrapeMultiSource(
{
keywords,
location,
limit: 20,
sources,
},
userId
);
if (results.length > 0) {
const businessesToInsert = results.map((business) => ({
...business,
userId,
category: business.category || "Unknown",
emailStatus: business.emailStatus || null,
}));
try {
await db.insert(businesses).values(businessesToInsert).onConflictDoNothing();
} catch (error: unknown) {
console.error(
"Failed to insert scraped businesses:",
error instanceof Error ? error.message : String(error)
);
await db.insert(businesses).values(businessesToInsert).catch((fallbackError: unknown) => {
console.error(
"Fallback insert failed:",
fallbackError instanceof Error ? fallbackError.message : String(fallbackError)
);
});
}
totalFound += results.length;
await db
.update(scrapingJobs)
.set({ businessesFound: totalFound })
.where(eq(scrapingJobs.id, jobId));
}
if (loopCount >= maxLoops) {
break;
}
await new Promise((resolve) => setTimeout(resolve, 1000));
}
await db
.update(scrapingJobs)
.set({
status: "completed",
businessesFound: totalFound,
completedAt: new Date(),
})
.where(eq(scrapingJobs.id, jobId));
return { success: true, count: totalFound };
} catch (error: unknown) {
const message = error instanceof Error ? error.message : String(error);
console.error(`Scraping job ${job.id} failed:`, message);
const { scrapingJobs } = await import("@/db/schema");
const { eq } = await import("drizzle-orm");
await db
.update(scrapingJobs)
.set({ status: "failed", completedAt: new Date() })
.where(eq(scrapingJobs.id, jobId));
throw new Error(message);
}
}
async function processWorkflowJob(job: Job<WorkflowJobData>) {
const { workflowId, userId, businessId, executionId } = job.data;
console.log(`Processing workflow job ${job.id} (execution ${executionId})`);
const { WorkflowExecutor } = await import("./workflow-executor");
try {
await db
.update(workflowExecutionLogs)
.set({
status: "running",
startedAt: new Date(),
updatedAt: new Date(),
})
.where(eq(workflowExecutionLogs.id, executionId));
const workflow = await db.query.automationWorkflows.findFirst({
where: eq(automationWorkflows.id, workflowId),
});
if (!workflow) {
throw new Error("Workflow not found");
}
const business = await db.query.businesses.findFirst({
where: eq(businesses.id, businessId),
});
if (!business) {
throw new Error("Business not found");
}
const executor = new WorkflowExecutor(workflow.nodes as any, workflow.edges as any, {
businessId: business.id,
businessData: business as any,
variables: {},
userId,
workflowId: workflow.id,
});
const result = await executor.execute();
const finalState = executor.getVariables();
await db
.update(workflowExecutionLogs)
.set({
status: result.success ? "success" : "failed",
logs: JSON.stringify(result.logs),
state: finalState,
completedAt: new Date(),
updatedAt: new Date(),
})
.where(eq(workflowExecutionLogs.id, executionId));
if (!result.success) {
throw new Error("Workflow execution logic returned failure");
}
await db
.update(automationWorkflows)
.set({
lastRunAt: new Date(),
executionCount: (workflow.executionCount || 0) + 1,
})
.where(eq(automationWorkflows.id, workflowId));
return { success: true };
} catch (error: unknown) {
const message = error instanceof Error ? error.message : String(error);
console.error(`Workflow job ${job.id} failed:`, message);
await db
.update(workflowExecutionLogs)
.set({
status: "failed",
error: message,
completedAt: new Date(),
updatedAt: new Date(),
})
.where(eq(workflowExecutionLogs.id, executionId));
throw new Error(message);
}
}
function attachCommonWorkerListeners<T>(worker: Worker<T>, label: string) {
worker.on("completed", (job) => {
console.log(`${label} job ${job.id} completed`);
});
worker.on("failed", (job, err) => {
console.error(`${label} job ${job?.id} failed:`, err.message);
});
}
async function attachWorkflowFailureListener(worker: Worker<WorkflowJobData>) {
worker.on("failed", async (job, err) => {
if (!job || job.attemptsMade < (job.opts.attempts ?? 0)) {
return;
}
await db.insert(notifications).values({
userId: job.data.userId,
title: "Workflow Failure",
message: `Workflow ${job.data.workflowId} failed after ${job.opts.attempts} attempts. Error: ${err.message}`,
level: "error",
category: "workflow",
});
try {
const user = await db.query.users.findFirst({
where: eq(users.id, job.data.userId),
});
if (user?.phone) {
await sendWhatsAppMessage({
to: user.phone,
text: `Critical alert: workflow ${job.data.executionId} failed. Error: ${err.message}`,
});
}
} catch (whatsAppError) {
console.error("Failed to send workflow WhatsApp alert:", whatsAppError);
}
});
}
function createWorkers(): QueueWorkers {
const connection = getQueueConnection();
const emailWorker = new Worker<EmailJobData>("email-outreach", processEmailJob, {
connection: connection as any,
});
const scrapingWorker = new Worker<ScrapingJobData>("google-maps-scraping", processScrapingJob, {
connection: connection as any,
concurrency: 5,
});
const workflowWorker = new Worker<WorkflowJobData>(
"workflow-execution",
processWorkflowJob,
{
connection: connection as any,
concurrency: 10,
}
);
attachCommonWorkerListeners(emailWorker, "Email");
attachCommonWorkerListeners(scrapingWorker, "Scraping");
attachCommonWorkerListeners(workflowWorker, "Workflow");
void attachWorkflowFailureListener(workflowWorker);
return {
emailWorker,
scrapingWorker,
workflowWorker,
};
}
async function recoverIncompleteWorkflowExecutions() {
const recoverableExecutions = await db.query.workflowExecutionLogs.findMany({
where: and(
or(
eq(workflowExecutionLogs.status, "pending"),
eq(workflowExecutionLogs.status, "running")
),
isNull(workflowExecutionLogs.completedAt)
),
columns: {
id: true,
workflowId: true,
userId: true,
businessId: true,
status: true,
},
});
if (recoverableExecutions.length === 0) {
return 0;
}
let recoveredCount = 0;
for (const execution of recoverableExecutions) {
if (!execution.businessId) {
continue;
}
await db
.update(workflowExecutionLogs)
.set({
status: "pending",
error: null,
updatedAt: new Date(),
})
.where(eq(workflowExecutionLogs.id, execution.id));
await ensureWorkflowExecutionQueued({
workflowId: execution.workflowId,
userId: execution.userId,
businessId: execution.businessId,
executionId: execution.id,
});
recoveredCount += 1;
}
console.log(`Recovered ${recoveredCount} incomplete workflow executions from Postgres.`);
return recoveredCount;
}
async function getQueueSnapshot(queue: Queue<any, any, string>): Promise<QueueStats> {
const [waiting, active, completed, failed] = await Promise.all([
queue.getWaitingCount(),
queue.getActiveCount(),
queue.getCompletedCount(),
queue.getFailedCount(),
]);
return {
waiting,
active,
completed,
failed,
};
}
export async function getQueueStats() {
try {
const [emailStats, scrapingStats, workflowStats] = await Promise.all([
getQueueSnapshot(getEmailQueue()),
getQueueSnapshot(getScrapingQueue()),
getQueueSnapshot(getWorkflowQueue()),
]);
return {
email: emailStats,
scraping: scrapingStats,
workflow: workflowStats,
};
} catch (error) {
if (error instanceof Error && error.message.includes("Redis/Valkey is required")) {
return {
email: { waiting: 0, active: 0, completed: 0, failed: 0 },
scraping: { waiting: 0, active: 0, completed: 0, failed: 0 },
workflow: { waiting: 0, active: 0, completed: 0, failed: 0 },
};
}
throw error;
}
}
export async function startWorker() {
if (process.env.START_QUEUE_WORKERS !== "true") {
throw new Error("Queue workers are disabled in this process.");
}
if (!workerBundle) {
workerBundle = createWorkers();
await recoverIncompleteWorkflowExecutions();
}
return workerBundle;
}
|