Spaces:
Sleeping
Sleeping
File size: 5,275 Bytes
097eaf0 | 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 | import amqp from "amqplib";
import { config } from "../../config";
import { logger as _logger } from "../../lib/logger";
const logger = _logger.child({ module: "indexer-queue" });
const INDEX_EXCHANGE = "index.jobs";
const LINKS_QUEUE_NAME = "index.jobs.links";
const LINKS_RK = "job.links";
const CONNECT_TIMEOUT = 5000;
const DRAIN_TIMEOUT = 30000;
type IndexWorkerMessage = {
id: string;
type: "links";
discovery_url: string;
urls: string[];
};
class IndexerQueue {
private connection: amqp.ChannelModel | null = null;
private publishChannel: amqp.Channel | null = null;
private connectPromise: Promise<void> | null = null;
private closing: boolean = false;
private noop: boolean | null = null;
async connect(): Promise<void> {
if (this.connectPromise) return this.connectPromise;
if (this.closing) return;
if (this.noop) return;
if (this.connection && this.publishChannel) return;
this.connectPromise = this._establishConnection();
try {
await this.connectPromise;
} finally {
this.connectPromise = null;
}
}
private async _establishConnection(): Promise<void> {
if (!config.INDEXER_RABBITMQ_URL) {
logger.debug("Indexer disabled via config");
this.noop = true;
return;
}
try {
logger.info("Connecting to index RabbitMQ");
this.connection = await amqp.connect(config.INDEXER_RABBITMQ_URL);
this.publishChannel = await this.connection.createChannel();
// NOTE: this queue is already created by another service
await this.publishChannel.checkQueue(LINKS_QUEUE_NAME);
this._registerConnectionEvents();
logger.info("Connected to index RabbitMQ");
} catch (err) {
this.connection = null;
this.publishChannel = null;
throw err;
}
}
private _registerConnectionEvents() {
if (this.noop) return;
if (!this.connection || !this.publishChannel) return;
this.connection.on("close", () => {
if (this.closing) return;
logger.warn("Index RabbitMQ connection closed", {
module: "index-queue",
});
this.cleanup();
setTimeout(
() =>
this.connect().catch(err =>
logger.error("Reconnection failed", {
err,
}),
),
CONNECT_TIMEOUT,
);
});
this.connection.on("error", err => {
logger.error("Index RabbitMQ connection error", {
err,
});
});
this.publishChannel.on("error", err => {
logger.error("Index RabbitMQ channel error", {
err,
});
});
}
async sendToWorker(message: IndexWorkerMessage): Promise<void> {
await this.connect();
if (this.noop) return;
if (!this.publishChannel) throw new Error("Channel not available");
const payload = {
id: message.id,
} as any;
if (message.type === "links") {
payload.urls = message.urls;
payload.discovery_url = message.discovery_url;
}
const buffer = Buffer.from(JSON.stringify(payload));
const canSendMore = this.publishChannel.publish(
INDEX_EXCHANGE,
LINKS_RK,
buffer,
{
persistent: true,
contentType: "application/json",
messageId: message.id,
},
);
if (!canSendMore) {
logger.warn("Index message buffer full, waiting for drain");
await this.waitForDrain();
}
}
private async waitForDrain(): Promise<void> {
if (this.noop) return;
return new Promise((resolve, reject) => {
if (!this.publishChannel) {
return reject(new Error("Channel not available"));
}
const listeners: Record<string, any> = {};
const cleanup = () => {
if (!this.publishChannel) return;
this.publishChannel.removeListener("drain", listeners.drain);
this.publishChannel.removeListener("error", listeners.error);
this.publishChannel.removeListener("close", listeners.close);
clearTimeout(listeners.timeout);
};
listeners.drain = () => {
cleanup();
resolve();
};
listeners.error = (err: Error) => {
cleanup();
reject(err);
};
listeners.close = () => {
cleanup();
reject(new Error("Channel closed during drain"));
};
listeners.timeout = setTimeout(() => {
cleanup();
reject(new Error(`Drain timeout after ${DRAIN_TIMEOUT}ms`));
}, DRAIN_TIMEOUT);
this.publishChannel.on("drain", listeners.drain);
this.publishChannel.on("error", listeners.error);
this.publishChannel.on("close", listeners.close);
});
}
async close(): Promise<void> {
if (this.noop) return;
this.closing = true;
try {
await this.publishChannel?.close();
await this.connection?.close();
} catch (err) {
logger.warn("Error while closing RabbitMQ connection", { err });
} finally {
this.cleanup();
logger.info("Indexer RabbitMQ closed");
}
}
private cleanup() {
this.connection = null;
this.publishChannel = null;
this.connectPromise = null;
}
}
export const indexerQueue = new IndexerQueue();
export async function shutdownIndexerQueue(): Promise<void> {
await indexerQueue.close();
}
|