-
Notifications
You must be signed in to change notification settings - Fork 6
/
Queue.ts
97 lines (78 loc) · 2.33 KB
/
Queue.ts
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
import { Job } from "./models/Job";
import { config } from "../configs/config";
import DB from "./DB";
import { CredentialManager } from "./SSHCredentialGuard";
import { promisify } from "util";
const redis = require("redis");
class Queue {
private name;
private redis = {
push: null,
shift: null,
peak: null,
length: null,
};
private isConnected = false;
private db = new DB();
private credentialManager = new CredentialManager();
constructor(name: string) {
this.name = name;
}
async push(item: Job) {
await this.connect();
await this.redis.push([this.name, item.id]);
}
async shift(): Promise<Job> {
await this.connect();
var jobId = await this.redis.shift(this.name);
return this.getJobById(jobId);
}
async isEmpty(): Promise<boolean> {
await this.connect();
return (await this.redis.length(this.name)) === 0;
}
async peak(): Promise<Job> {
await this.connect();
if (await this.isEmpty()) return undefined;
var jobId = await this.redis.peak(this.name, 0, 0);
return this.getJobById(jobId);
}
async length(): Promise<number> {
await this.connect();
return await this.redis.length(this.name);
}
private async connect() {
if (!this.isConnected) {
var client = new redis.createClient({
host: config.redis.host,
port: config.redis.port,
});
if (config.redis.password != null && config.redis.password != undefined) {
var redisAuth = promisify(client.auth).bind(client);
await redisAuth(config.redis.password);
}
this.redis.push = promisify(client.rpush).bind(client);
this.redis.shift = promisify(client.lpop).bind(client);
this.redis.peak = promisify(client.lrange).bind(client);
this.redis.length = promisify(client.llen).bind(client);
this.isConnected = true;
}
}
private async getJobById(id: string): Promise<Job> {
var connection = await this.db.connect();
var jobRepo = connection.getRepository(Job);
var job = await jobRepo.findOne(id, {
relations: [
"remoteExecutableFolder",
"remoteDataFolder",
"remoteResultFolder",
],
});
if (!job) return null;
if (job.credentialId) {
job.credential = await this.credentialManager.get(job.credentialId);
}
return job;
}
}
export default Queue;