RippleWorkers / src /scripts /worker.ts
damndeepesh
Initialize project with LavinMQ integration and Docker support
c7fbc2e
Raw History Blame Contribute Delete
2.41 kB
import { getChannel } from "@/lib/lavinmq";
import { publishPost } from "@/lib/instagram-publisher";
import dotenv from 'dotenv';
import path from 'path';
// Ensure env vars are loaded for standalone script
dotenv.config({ path: path.resolve(process.cwd(), '.env.local') });
const QUEUE_NAME = "publish_jobs";
async function startWorker() {
console.log("Starting LavinMQ Worker...");
try {
const channel = await getChannel();
await channel.assertQueue(QUEUE_NAME, { durable: true });
// Prefetch 1 means only process 1 message at a time per consumer
channel.prefetch(1);
console.log(`[*] Waiting for messages in ${QUEUE_NAME}. To exit press CTRL+C`);
channel.consume(QUEUE_NAME, async (msg) => {
if (msg !== null) {
const content = msg.content.toString();
console.log(`[Worker] Received job: ${content}`);
try {
const { postId } = JSON.parse(content);
if (!postId) {
throw new Error("Invalid message format: missing postId");
}
console.log(`[Worker] Publishing post ${postId}...`);
await publishPost(postId);
console.log(`[Worker] Successfully published post ${postId}`);
channel.ack(msg); // Acknowledge success
} catch (error: any) {
console.error(`[Worker] Job failed:`, error);
// Decide whether to nack (re-queue) or ack (discard)
// For now, let's nack with requeue=false if it's a permanent error,
// or true if transient. Simpler to just ack and log error to avoid infinite loops for bad data.
// Or typically, we might want a Dead Letter Queue.
// Let's re-queue only once or twice? Not implemented here.
// We'll ack it to remove from queue so it doesn't block, but allow manual retry via DB later.
// channel.nack(msg, false, false); // Reject, don't requeue
channel.ack(msg); // Ack to clear it for now
}
}
}, {
noAck: false // We will manually ack
});
} catch (error) {
console.error("Worker Error:", error);
}
}
startWorker();