File size: 2,406 Bytes
c7fbc2e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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

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();