Skip to content

Supercharge your AI agents with data from the web and beyond. Building the library for superintelligence. 🔥

feat(nuq): RabbitMQ support for job finish events and waiting (#2230)

Gergő Móricz6c20801c16d6
diff --git a/apps/api/package.json b/apps/api/package.json
index 8959da558..b9e77e4fb 100644
--- a/apps/api/package.json
+++ b/apps/api/package.json
@@ -37,6 +37,7 @@
"license": "ISC",
"devDependencies": {
"@jest/globals": "^29.7.0",
+ "@types/amqplib": "^0.10.7",
"@types/body-parser": "^1.19.2",
"@types/cors": "^2.8.13",
"@types/escape-html": "^1.0.4",
@@ -89,6 +90,7 @@
"@types/ws": "^8.5.12",
"ai": "^4.3.4",
"ajv": "^8.16.0",
+ "amqplib": "^0.10.9",
"async-mutex": "^0.5.0",
"axios": "^1.12.2",
"body-parser": "^1.20.3",
diff --git a/apps/api/pnpm-lock.yaml b/apps/api/pnpm-lock.yaml
index 0d9a70151..00bd861c2 100644
--- a/apps/api/pnpm-lock.yaml
+++ b/apps/api/pnpm-lock.yaml
@@ -96,6 +96,9 @@ importers:
ajv:
specifier: ^8.16.0
version: 8.16.0
+ amqplib:
+ specifier: ^0.10.9
+ version: 0.10.9
async-mutex:
specifier: ^0.5.0
version: 0.5.0
@@ -241,6 +244,9 @@ importers:
'@jest/globals':
specifier: ^29.7.0
version: 29.7.0
+ '@types/amqplib':
+ specifier: ^0.10.7
+ version: 0.10.7
'@types/body-parser':
specifier: ^1.19.2
version: 1.19.5
@@ -3155,6 +3161,9 @@ packages:
resolution: {integrity: sha512-VyyPYFlOMNylG45GoAe0xDoLwWuowvf92F9kySqzYh8vmYm7D2u4iUJKa1tOUpS70Ku13ASrOkS4ScXFsTaCNQ==}
+ '@types/[email protected]':
+ resolution: {integrity: sha512-IVj3avf9AQd2nXCx0PGk/OYq7VmHiyNxWFSb5HhU9ATh+i+gHWvVcljFTcTWQ/dyHJCTrzCixde+r/asL2ErDA==}
+
resolution: {integrity: sha512-soT/c2gYBnT5ygwiHPmd9a1bftj462NWVk2tKCc1PYHSIacB2UwbTS2zYG4jzag1mRDuzg/OjtxQjQ2NKRB6Rw==}
@@ -3517,6 +3526,10 @@ packages:
resolution: {integrity: sha512-F0twR8U1ZU67JIEtekUcLkXkoO5mMMmgGD8sK/xUFzJ805jxHQl92hImFAqqXMyMYjSPOyUPAwHYhB72g5sTXw==}
+ resolution: {integrity: sha512-jwSftI4QjS3mizvnSnOrPGYiUnm1vI2OP1iXeOUz5pb74Ua0nbf6nPyyTzuiCLEE3fMpaJORXh2K/TQ08H5xGA==}
+ engines: {node: '>=10'}
+
resolution: {integrity: sha512-gKXj5ALrKWQLsYG9jlTRmR/xKluxHV+Z9QEwNIgCfM1/uwPMCuzVVnh5mwTd+OuBZcwSIMbqssNWRm1lE51QaQ==}
engines: {node: '>=8'}
@@ -3717,6 +3730,9 @@ packages:
resolution: {integrity: sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==}
+ resolution: {integrity: sha512-EMetuGFz5SLsT0QTnXzINh4Ksr+oo4i+UGTXEshiGCQWnsgSs7ZhJ8fzlwQ+OzEMs0MpDAMr1hxnblp5a4vcHg==}
+
resolution: {integrity: sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA==}
@@ -10715,6 +10731,10 @@ snapshots:
tslib: 2.8.1
optional: true
+ '@types/[email protected]':
+ dependencies:
+ '@types/node': 20.14.1
+
'@types/[email protected]': {}
@@ -11582,6 +11602,11 @@ snapshots:
require-from-string: 2.0.2
uri-js: 4.4.1
+ dependencies:
+ buffer-more-ints: 1.0.0
+ url-parse: 1.5.10
+
dependencies:
type-fest: 0.21.3
@@ -11813,6 +11838,8 @@ snapshots:
+
dependencies:
base64-js: 1.5.1
diff --git a/apps/api/src/controllers/v0/scrape.ts b/apps/api/src/controllers/v0/scrape.ts
index 94dd1ba30..2229295b9 100644
--- a/apps/api/src/controllers/v0/scrape.ts
+++ b/apps/api/src/controllers/v0/scrape.ts
@@ -82,6 +82,8 @@ async function scrapeHelper(
},
jobId,
await getJobPriority({ team_id, basePriority: 10 }),
+ false,
+ true,
);
let doc;
diff --git a/apps/api/src/controllers/v0/search.ts b/apps/api/src/controllers/v0/search.ts
index 60a66d703..812fdc08b 100644
--- a/apps/api/src/controllers/v0/search.ts
+++ b/apps/api/src/controllers/v0/search.ts
@@ -125,7 +125,7 @@ async function searchHelper(
// TODO: addScrapeJobs
for (const job of jobDatas) {
- await addScrapeJob(job.data, job.jobId, jobPriority);
+ await addScrapeJob(job.data, job.jobId, jobPriority, false, true);
}
const docs = (
diff --git a/apps/api/src/controllers/v1/scrape.ts b/apps/api/src/controllers/v1/scrape.ts
index 155b7da39..7f8faac27 100644
--- a/apps/api/src/controllers/v1/scrape.ts
+++ b/apps/api/src/controllers/v1/scrape.ts
@@ -104,6 +104,7 @@ export async function scrapeController(
jobId,
jobPriority,
isDirectToBullMQ,
+ true,
);
logger.info(
"Added scrape job now" + (bullJob ? "" : " (to concurrency queue)"),
diff --git a/apps/api/src/controllers/v1/search.ts b/apps/api/src/controllers/v1/search.ts
index 1b1db0239..b4daccab5 100644
--- a/apps/api/src/controllers/v1/search.ts
+++ b/apps/api/src/controllers/v1/search.ts
@@ -142,6 +142,7 @@ async function scrapeSearchResult(
jobId,
jobPriority,
directToBullMQ,
+ true,
);
const doc: Document = await waitForJob(
diff --git a/apps/api/src/controllers/v1/x402-search.ts b/apps/api/src/controllers/v1/x402-search.ts
index 10292e230..fc90e8f97 100644
--- a/apps/api/src/controllers/v1/x402-search.ts
+++ b/apps/api/src/controllers/v1/x402-search.ts
@@ -95,6 +95,7 @@ async function scrapeX402SearchResult(
basePriority: 10,
}),
directToBullMQ,
+ true,
);
const doc: Document = await waitForJob(
diff --git a/apps/api/src/controllers/v2/scrape.ts b/apps/api/src/controllers/v2/scrape.ts
index 48d662c0a..f56cc1f40 100644
--- a/apps/api/src/controllers/v2/scrape.ts
+++ b/apps/api/src/controllers/v2/scrape.ts
@@ -148,6 +148,7 @@ export async function scrapeController(
jobId,
jobPriority,
isDirectToBullMQ,
+ true,
);
setSpanAttributes(enqueueSpan, {
diff --git a/apps/api/src/controllers/v2/search.ts b/apps/api/src/controllers/v2/search.ts
index a71be2009..7893338fd 100644
--- a/apps/api/src/controllers/v2/search.ts
+++ b/apps/api/src/controllers/v2/search.ts
@@ -99,6 +99,7 @@ async function startScrapeJob(
jobId,
jobPriority,
directToBullMQ,
+ true,
);
return jobId;
diff --git a/apps/api/src/controllers/v2/x402-search.ts b/apps/api/src/controllers/v2/x402-search.ts
index 52081a8e3..7dd76719b 100644
--- a/apps/api/src/controllers/v2/x402-search.ts
+++ b/apps/api/src/controllers/v2/x402-search.ts
@@ -97,6 +97,7 @@ async function startX420ScrapeJob(
jobId,
jobPriority,
directToBullMQ,
+ true,
);
return jobId;
diff --git a/apps/api/src/lib/concurrency-limit.ts b/apps/api/src/lib/concurrency-limit.ts
index e8bbb122c..f09b34c1a 100644
--- a/apps/api/src/lib/concurrency-limit.ts
+++ b/apps/api/src/lib/concurrency-limit.ts
@@ -62,6 +62,7 @@ type ConcurrencyLimitedJob = {
id: string;
data: any;
priority: number;
+ listenable: boolean;
};
export async function cleanOldConcurrencyLimitedJobs(
@@ -346,6 +347,7 @@ export async function concurrentJobDone(job: NuQJob<any>) {
concurrencyLimitHit: true,
},
nextJob.job.priority,
+ nextJob.job.listenable,
);
}
}
diff --git a/apps/api/src/lib/extract/document-scraper.ts b/apps/api/src/lib/extract/document-scraper.ts
index e81582e0e..ffc99e567 100644
--- a/apps/api/src/lib/extract/document-scraper.ts
+++ b/apps/api/src/lib/extract/document-scraper.ts
@@ -71,6 +71,8 @@ export async function scrapeDocument(
},
jobId,
jobPriority,
+ false,
+ true,
);
const doc = await waitForJob(jobId, timeout, false, logger);
diff --git a/apps/api/src/lib/extract/fire-0/document-scraper-f0.ts b/apps/api/src/lib/extract/fire-0/document-scraper-f0.ts
index a1acbc8ec..7a23c5737 100644
--- a/apps/api/src/lib/extract/fire-0/document-scraper-f0.ts
+++ b/apps/api/src/lib/extract/fire-0/document-scraper-f0.ts
@@ -70,6 +70,8 @@ export async function scrapeDocument_F0(
},
jobId,
jobPriority,
+ false,
+ true,
);
const doc = await waitForJob(jobId, timeout, false, logger);
diff --git a/apps/api/src/services/queue-jobs.ts b/apps/api/src/services/queue-jobs.ts
index 194252f70..885be5005 100644
--- a/apps/api/src/services/queue-jobs.ts
+++ b/apps/api/src/services/queue-jobs.ts
@@ -41,6 +41,7 @@ async function _addScrapeJobToConcurrencyQueue(
webScraperOptions: any,
jobId: string,
priority: number = 0,
+ listenable: boolean = false,
) {
await pushConcurrencyLimitedJob(
webScraperOptions.team_id,
@@ -48,6 +49,7 @@ async function _addScrapeJobToConcurrencyQueue(
id: jobId,
data: webScraperOptions,
priority,
+ listenable,
},
webScraperOptions.crawl_id
? Infinity
@@ -59,6 +61,7 @@ export async function _addScrapeJobToBullMQ(
webScraperOptions: ScrapeJobData,
jobId: string,
priority: number = 0,
+ listenable: boolean = false,
): Promise<NuQJob<ScrapeJobData>> {
if (webScraperOptions.mode === "single_urls") {
abTestJob(webScraperOptions);
@@ -83,7 +86,7 @@ export async function _addScrapeJobToBullMQ(
}
}
- return await scrapeQueue.addJob(jobId, webScraperOptions, priority);
+ return await scrapeQueue.addJob(jobId, webScraperOptions, priority, listenable);
}
async function addScrapeJobRaw(
@@ -91,6 +94,7 @@ async function addScrapeJobRaw(
jobId: string,
priority: number = 0,
directToBullMQ: boolean = false,
+ listenable: boolean = false,
): Promise<NuQJob<ScrapeJobData> | null> {
let concurrencyLimited: "yes" | "yes-crawl" | "no" | null = null;
let currentActiveConcurrency = 0;
@@ -177,10 +181,10 @@ async function addScrapeJobRaw(
webScraperOptions.concurrencyLimited = true;
- await _addScrapeJobToConcurrencyQueue(webScraperOptions, jobId);
+ await _addScrapeJobToConcurrencyQueue(webScraperOptions, jobId, priority, listenable);
return null;
} else {
- return await _addScrapeJobToBullMQ(webScraperOptions, jobId, priority);
+ return await _addScrapeJobToBullMQ(webScraperOptions, jobId, priority, listenable);
}
}
@@ -189,6 +193,7 @@ export async function addScrapeJob(
jobId: string = uuidv4(),
priority: number = 0,
directToBullMQ: boolean = false,
+ listenable: boolean = false,
): Promise<NuQJob<ScrapeJobData> | null> {
// Capture trace context to propagate to worker
const traceContext = serializeTraceContext();
@@ -202,6 +207,7 @@ export async function addScrapeJob(
jobId,
priority,
directToBullMQ,
+ listenable,
);
}
@@ -210,6 +216,7 @@ export async function addScrapeJobs(
jobId: string;
data: ScrapeJobData;
priority: number;
+ listenable?: boolean;
}[],
) {
if (jobs.length === 0) return true;
@@ -223,6 +230,7 @@ export async function addScrapeJobs(
jobId: string;
data: ScrapeJobData;
priority: number;
+ listenable?: boolean;
}[]
>();
@@ -239,12 +247,14 @@ export async function addScrapeJobs(
data: ScrapeJobData;
jobId: string;
priority: number;
+ listenable?: boolean;
}[] = [];
let jobsPotentiallyInCQ: {
data: ScrapeJobData;
jobId: string;
priority: number;
+ listenable?: boolean;
}[] = [];
// == Select jobs by crawl ID ==
@@ -254,6 +264,7 @@ export async function addScrapeJobs(
data: ScrapeJobData;
jobId: string;
priority: number;
+ listenable?: boolean;
}[]
>();
@@ -261,6 +272,7 @@ export async function addScrapeJobs(
data: ScrapeJobData;
jobId: string;
priority: number;
+ listenable?: boolean;
}[] = [];
for (const job of teamJobs) {
@@ -363,6 +375,7 @@ export async function addScrapeJobs(
{ ...job.data, traceContext },
job.jobId,
job.priority,
+ job.listenable,
);
}),
);
@@ -373,6 +386,7 @@ export async function addScrapeJobs(
{ ...job.data, traceContext },
job.jobId,
job.priority,
+ job.listenable,
);
}),
);
diff --git a/apps/api/src/services/worker/nuq.ts b/apps/api/src/services/worker/nuq.ts
index 4365a39e1..28e24f701 100644
--- a/apps/api/src/services/worker/nuq.ts
+++ b/apps/api/src/services/worker/nuq.ts
@@ -3,6 +3,7 @@ import { logger } from "../../lib/logger";
import { Client, Pool } from "pg";
import { type ScrapeJobData } from "../../types";
import { withSpan, setSpanAttributes } from "../../lib/otel-tracer";
+import amqp from "amqplib";
// === Basics
@@ -23,10 +24,13 @@ export type NuQJob<Data = any, ReturnValue = any> = {
priority: number;
data: Data;
finishedAt?: Date;
+ listenChannelId?: string;
returnvalue?: ReturnValue;
failedReason?: string;
};
+const listenChannelId = process.env.NUQ_POD_NAME ?? "main";
+
// === Queue
class NuQ<JobData = any, JobReturnValue = any> {
@@ -34,53 +38,119 @@ class NuQ<JobData = any, JobReturnValue = any> {
// === Listener
- private listener: Client | null = null;
+ private listener: {
+ type: "postgres";
+ client: Client;
+ } | {
+ type: "rabbitmq";
+ connection: amqp.ChannelModel;
+ channel: amqp.Channel;
+ queue: string;
+ } | null = null;
private listens: {
[key: string]: ((status: "completed" | "failed") => void)[];
} = {};
private shuttingDown = false;
- async startListener() {
+ private async startListener() {
if (this.listener || this.shuttingDown) return;
- this.listener = new Client({
- connectionString:
- process.env.NUQ_DATABASE_URL_LISTEN ?? process.env.NUQ_DATABASE_URL, // will always be a direct connection
- application_name: "nuq_listener",
- });
+ if (process.env.NUQ_RABBITMQ_URL) {
+ const connection = await amqp.connect(process.env.NUQ_RABBITMQ_URL);
+ const channel = await connection.createChannel();
+ const queue = await channel.assertQueue(this.queueName + ".listen." + listenChannelId, {
+ exclusive: true,
+ autoDelete: true,
+ durable: false,
+ });
- this.listener.on("notification", msg => {
- const tok = (msg.payload ?? "unknown|unknown").split("|");
- if (tok[0] in this.listens) {
- this.listens[tok[0]].forEach(listener =>
- listener(tok[1] as "completed" | "failed"),
- );
- delete this.listens[tok[0]];
- }
- });
+ this.listener = {
+ type: "rabbitmq",
+ connection,
+ channel,
+ queue: queue.queue,
+ };
+
+ await this.listener.channel.consume(this.listener.queue, (msg => {
+ if (msg === null) {
+ logger.info("NuQ listener channel closed", { module: "nuq/rabbitmq" });
+ this.listener = null;
+
+ setTimeout(
+ (() => {
+ this.startListener().catch(err =>
+ logger.error("Error in NuQ listener reconnect", {
+ err,
+ module: "nuq/rabbitmq",
+ }),
+ );
+ }).bind(this),
+ 250,
+ );
+ return;
+ }
- this.listener.on("error", err =>
- logger.error("Error in NuQ listener", { err, module: "nuq" }),
- );
+ logger.info("NuQ job received", { module: "nuq/rabbitmq", jobId: msg.properties.correlationId, status: msg.content.toString() });
- this.listener.on("end", () => {
- logger.info("NuQ listener disconnected", { module: "nuq" });
- this.listener = null;
- setTimeout(
- (() => {
- this.startListener().catch(err =>
- logger.error("Error in NuQ listener reconnect", {
- err,
- module: "nuq",
- }),
+ const jobId = msg.properties.correlationId as string;
+ const status = msg.content.toString() as "completed" | "failed";
+
+ if (jobId in this.listens) {
+ this.listens[jobId].forEach(listener =>
+ listener(status),
);
- }).bind(this),
- 250,
+ }
+ delete this.listens[jobId];
+
+ if (this.listener && this.listener.type === "rabbitmq") {
+ this.listener.channel.ack(msg);
+ }
+ }).bind(this), {
+ noAck: false,
+ });
+ } else {
+ this.listener = {
+ type: "postgres",
+ client: new Client({
+ connectionString:
+ process.env.NUQ_DATABASE_URL_LISTEN ?? process.env.NUQ_DATABASE_URL, // will always be a direct connection
+ application_name: "nuq_listener",
+ }),
+ };
+
+ this.listener.client.on("notification", msg => {
+ const tok = (msg.payload ?? "unknown|unknown").split("|");
+ if (tok[0] in this.listens) {
+ this.listens[tok[0]].forEach(listener =>
+ listener(tok[1] as "completed" | "failed"),
+ );
+ delete this.listens[tok[0]];
+ }
+ });
+
+ this.listener.client.on("error", err =>
+ logger.error("Error in NuQ listener", { err, module: "nuq" }),
);
- });
- await this.listener.connect();
- await this.listener.query(`LISTEN "${this.queueName}";`);
+ this.listener.client.on("end", () => {
+ logger.info("NuQ listener disconnected", { module: "nuq" });
+ this.listener = null;
+ setTimeout(
+ (() => {
+ this.startListener().catch(err =>
+ logger.error("Error in NuQ listener reconnect", {
+ err,
+ module: "nuq",
+ }),
+ );
+ }).bind(this),
+ 250,
+ );
+ });
+
+ await this.listener.client.connect();
+ await this.listener.client.query(`LISTEN "${this.queueName}";`);
+ }
(async () => {
const backedUpJobs = (
@@ -95,7 +165,7 @@ class NuQ<JobData = any, JobReturnValue = any> {
})();
}
- async addListener(
+ private async addListener(
id: string,
listener: (status: "completed" | "failed") => void,
) {
@@ -105,7 +175,7 @@ class NuQ<JobData = any, JobReturnValue = any> {
else this.listens[id].push(listener);
}
- async removeListener(
+ private async removeListener(
id: string,
listener: (status: "completed" | "failed") => void,
) {
@@ -115,6 +185,42 @@ class NuQ<JobData = any, JobReturnValue = any> {
}
}
+ // === Sender
+
+ private sender: {
+ type: "rabbitmq";
+ connection: amqp.ChannelModel;
+ channel: amqp.Channel;
+ } | null = null;
+
+ private async startSender() {
+ if (this.sender || this.shuttingDown) return;
+
+ if (process.env.NUQ_RABBITMQ_URL) {
+ const connection = await amqp.connect(process.env.NUQ_RABBITMQ_URL);
+ const channel = await connection.createChannel();
+
+ this.sender = {
+ type: "rabbitmq",
+ connection,
+ channel,
+ };
+ }
+ }
+
+ private async sendJob(id: string, status: "completed" | "failed", listenChannelId: string, _logger: Logger = logger) {
+ await this.startSender();
+
+ if (this.sender) {
+ await this.sender.channel.sendToQueue(this.queueName + ".listen." + listenChannelId, Buffer.from(status, "utf8"), {
+ correlationId: id,
+ });
+ _logger.info("NuQ job sent", { module: "nuq/rabbitmq" });
+ } else {
+ _logger.warn("NuQ sender not started", { module: "nuq/rabbitmq" });
+ }
+ }
+
// === Job management
private readonly jobReturning = [
@@ -124,6 +230,7 @@ class NuQ<JobData = any, JobReturnValue = any> {
"priority",
"data",
"finished_at",
+ "listen_channel_id",
"returnvalue",
"failedreason",
];
@@ -137,6 +244,7 @@ class NuQ<JobData = any, JobReturnValue = any> {
priority: row.priority,
data: row.data,
finishedAt: row.finished_at ? new Date(row.finished_at) : undefined,
+ listenChannelId: row.listen_channel_id ?? undefined,
returnvalue: row.returnvalue ?? undefined,
failedReason: row.failedreason ?? undefined,
};
@@ -314,6 +422,7 @@ class NuQ<JobData = any, JobReturnValue = any> {
id: string,
data: JobData,
priority: number = 0,
+ listenable: boolean = false,
): Promise<NuQJob<JobData, JobReturnValue>> {
return withSpan("nuq.addJob", async span => {
setSpanAttributes(span, {
@@ -321,6 +430,7 @@ class NuQ<JobData = any, JobReturnValue = any> {
"nuq.job_id": id,
"nuq.priority": priority,
"nuq.zero_data_retention": (data as any)?.zeroDataRetention ?? false,
+ "nuq.listenable": listenable,
});
const start = Date.now();
@@ -328,8 +438,8 @@ class NuQ<JobData = any, JobReturnValue = any> {
const result = this.rowToJob(
(
await nuqPool.query(
- `INSERT INTO ${this.queueName} (id, data, priority) VALUES ($1, $2, $3) RETURNING ${this.jobReturning.join(", ")};`,
- [id, data, priority],
+ `INSERT INTO ${this.queueName} (id, data, priority, listen_channel_id) VALUES ($1, $2, $3, $4) RETURNING ${this.jobReturning.join(", ")};`,
+ [id, data, priority, listenable ? listenChannelId : null],
)
).rows[0],
)!;
@@ -356,7 +466,7 @@ class NuQ<JobData = any, JobReturnValue = any> {
}
private readonly nuqWaitMode =
- process.env.NUQ_WAIT_MODE === "listen"
+ process.env.NUQ_WAIT_MODE === "listen" || process.env.NUQ_RABBITMQ_URL
? ("listen" as const)
: ("poll" as const);
@@ -532,22 +642,27 @@ class NuQ<JobData = any, JobReturnValue = any> {
const start = Date.now();
try {
- const result =
- (
- await nuqPool.query(
- `
- WITH updated AS (UPDATE ${this.queueName} SET status = 'completed'::nuq.job_status, lock = null, locked_at = null, finished_at = now(), returnvalue = $3 WHERE id = $1 AND lock = $2 RETURNING id)
- SELECT pg_notify('${this.queueName}', (id::text || '|completed')) FROM updated;
- `,
- [id, lock, returnvalue],
- )
- ).rowCount !== 0;
+ const result = await nuqPool.query(
+ `UPDATE ${this.queueName} SET status = 'completed'::nuq.job_status, lock = null, locked_at = null, finished_at = now(), returnvalue = $3 WHERE id = $1 AND lock = $2 RETURNING id, listen_channel_id;`,
+ [id, lock, returnvalue],
+ );
+
+ const success = result.rowCount !== 0;
+ if (success) {
+ const job = result.rows[0];
+ if (this.nuqWaitMode === "listen" && !process.env.NUQ_RABBITMQ_URL) {
+ await nuqPool.query(`SELECT pg_notify('${this.queueName}', $1);`, [job.id + "|completed"]);
+ } else if (process.env.NUQ_RABBITMQ_URL && job.listen_channel_id) {
+ await this.sendJob(job.id, "completed", job.listen_channel_id, _logger);
+ }
+ }
+
setSpanAttributes(span, {
- "nuq.job_finished": result,
+ "nuq.job_finished": success,
});
- return result;
+ return success;
} finally {
const duration = Date.now() - start;
setSpanAttributes(span, {
@@ -578,22 +693,26 @@ class NuQ<JobData = any, JobReturnValue = any> {
const start = Date.now();
try {
- const result =
- (
- await nuqPool.query(
- `
- WITH updated AS (UPDATE ${this.queueName} SET status = 'failed'::nuq.job_status, lock = null, locked_at = null, finished_at = now(), failedreason = $3 WHERE id = $1 AND lock = $2 RETURNING id)
- SELECT pg_notify('${this.queueName}', (id::text || '|failed')) FROM updated;
- `,
- [id, lock, failedReason],
- )
- ).rowCount !== 0;
+ const result = await nuqPool.query(`UPDATE ${this.queueName} SET status = 'failed'::nuq.job_status, lock = null, locked_at = null, finished_at = now(), failedreason = $3 WHERE id = $1 AND lock = $2 RETURNING id`,
+ [id, lock, failedReason],
+ );
+
+ const success = result.rowCount !== 0;
+
+ if (success) {
+ const job = result.rows[0];
+ if (this.nuqWaitMode === "listen" && !process.env.NUQ_RABBITMQ_URL) {
+ await nuqPool.query(`SELECT pg_notify('${this.queueName}', $1);`, [job.id + "|failed"]);
+ } else if (process.env.NUQ_RABBITMQ_URL && job.listen_channel_id) {
+ await this.sendJob(job.id, "failed", job.listen_channel_id, _logger);
+ }
+ }
setSpanAttributes(span, {
- "nuq.job_failed": result,
+ "nuq.job_failed": success,
});
- return result;
+ return success;
} finally {
const duration = Date.now() - start;
setSpanAttributes(span, {
@@ -631,8 +750,20 @@ class NuQ<JobData = any, JobReturnValue = any> {
const nl = this.listener;
this.listener = null;
this.listens = {};
- await nl.query(`UNLISTEN "${this.queueName}";`);
- await nl.end();
+ if (nl.type === "postgres") {
+ await nl.client.query(`UNLISTEN "${this.queueName}";`);
+ await nl.client.end();
+ } else {
+ await nl.channel.cancel(nl.queue);
+ await nl.channel.close();
+ await nl.connection.close();
+ }
+ }
+ if (this.sender) {
+ const ns = this.sender;
+ this.sender = null;
+ await ns.channel.close();
+ await ns.connection.close();
}
}
}
diff --git a/apps/nuq-postgres/nuq.sql b/apps/nuq-postgres/nuq.sql
index 96977fe3f..f22a6b83a 100644
--- a/apps/nuq-postgres/nuq.sql
+++ b/apps/nuq-postgres/nuq.sql
@@ -19,6 +19,7 @@ CREATE TABLE IF NOT EXISTS nuq.queue_scrape (
locked_at timestamp with time zone,
stalls integer,
finished_at timestamp with time zone,
+ listen_channel_id text, -- for listenable jobs over rabbitmq
returnvalue jsonb, -- only for selfhost
failedreason text, -- only for selfhost
CONSTRAINT queue_scrape_pkey PRIMARY KEY (id)