-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathamqpConnector.js
More file actions
executable file
·80 lines (67 loc) · 2.6 KB
/
Copy pathamqpConnector.js
File metadata and controls
executable file
·80 lines (67 loc) · 2.6 KB
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
const amqplib = require('amqplib'),
createJobMessage = require('../../common/jobMessage').createJobMessage;
let conn = null;
let connPromise = null;
let channels = {};
let channelPromises = {};
async function getConnection() {
if (conn) return conn;
if (!connPromise) {
console.log("[AMQP] Creating new connection...");
connPromise = amqplib.connect(`amqp://${process.env.RABBIT_HOSTNAME}`, "heartbeat=60");
}
conn = await connPromise;
return conn;
}
async function initialize(queue_name) {
const connection = await getConnection();
if (channels[queue_name]) return;
if (!channelPromises[queue_name]) {
channelPromises[queue_name] = (async () => {
try {
console.log(`[AMQP] Creating channel for queue ${queue_name}`);
const ch = await connection.createChannel();
await ch.assertQueue(queue_name, { durable: false, expires: 6000000 });
channels[queue_name] = ch;
} catch (err) {
delete channelPromises[queue_name]; // retry logic
throw err;
}
})();
}
await channelPromises[queue_name];
}
function getQueueName(context) {
if ("executionModels" in context.appConfig) {
for (const taskType of context.appConfig.executionModels) {
if (taskType.name === context['name']) {
if ("queue" in taskType) {
return taskType.queue;
}
}
}
}
let namespace = process.env.HF_VAR_NAMESPACE || 'default'
return namespace + "." + context['name']
}
async function enqueueJobs(jobArr, taskIdArr, contextArr, customParams) {
let context = contextArr[0];
let queue_name = getQueueName(context);
try {
await initialize(queue_name);
let ch = channels[queue_name];
console.log(`jobArr: ${JSON.stringify(jobArr)}, taskIdArr: ${JSON.stringify(taskIdArr)}, contextArr: ${JSON.stringify(contextArr)}, customParams: ${JSON.stringify(customParams)}`);
let tasks = [];
for (let i = 0; i < jobArr.length; i++) {
let job = jobArr[i];
let taskId = taskIdArr[i];
let jobMessage = createJobMessage(job.ins, job.outs, contextArr[i], taskId);
await context.sendMsgToJob(JSON.stringify(jobMessage), taskId); // TODO remove
tasks.push({ "id": taskId, "message": jobMessage });
}
ch.sendToQueue(queue_name, Buffer.from(JSON.stringify({ 'tasks': tasks })));
} catch (error) {
console.log(error);
}
}
exports.enqueueJobs = enqueueJobs