43 lines
2.0 KiB
JavaScript
43 lines
2.0 KiB
JavaScript
'use strict';
|
|
const amqp = require('amqplib');
|
|
const telemetry = require('./telemetry');
|
|
const {readFileSync} = require('node:fs');
|
|
const queue = 'attachments.v1';
|
|
let pending;
|
|
async function open() {
|
|
const url = process.env.BROKER_URL || readFileSync(process.env.BROKER_URL_FILE || '/run/secrets/broker_url','utf8').trim();
|
|
const connection = await amqp.connect(url, {timeout: 5000,ca:require('./tls').ca,rejectUnauthorized:true});
|
|
connection.on('error', () => {});
|
|
const channel = await connection.createConfirmChannel();
|
|
channel.on('error', () => {});
|
|
await channel.assertQueue(queue, {durable: true});
|
|
return {connection, channel};
|
|
}
|
|
async function publisher() {
|
|
if (!pending) pending = open().then(value => {
|
|
value.connection.on('close', () => { pending = null; });
|
|
value.channel.on('close', () => { pending = null; });
|
|
return value;
|
|
}).catch(error => { pending = null; throw error; });
|
|
return pending;
|
|
}
|
|
function payload(job, attempt=1) {
|
|
return {schema_version:1,job_id:job.id,type:'attachment.process.v1',attachment_id:job.attachment_id,
|
|
pipeline_version:1,attempt,created_at:new Date(job.created_at).toISOString(),...telemetry.carrier()};
|
|
}
|
|
async function publish(job, attempt=1, channel) {
|
|
return telemetry.operation('attachments.publish',telemetry.SpanKind.PRODUCER,async () => {
|
|
channel = channel || (await publisher()).channel;
|
|
await new Promise((resolve,reject) => channel.sendToQueue(queue, Buffer.from(JSON.stringify(payload(job,attempt))),
|
|
{persistent:true,contentType:'application/json',messageId:job.id}, error => error ? reject(error) : resolve()));
|
|
}, {'messaging.system':'rabbitmq'});
|
|
}
|
|
async function ready() {
|
|
try { await (await publisher()).channel.checkQueue(queue); }
|
|
catch { throw Object.assign(new Error('Broker unavailable'),{status:503,code:'unavailable'}); }
|
|
}
|
|
async function close() {
|
|
if (pending) { const value=await pending; await value.connection.close(); }
|
|
}
|
|
module.exports = {open,publish,ready,queue,close};
|