-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathindex.js
106 lines (91 loc) · 2.52 KB
/
index.js
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
var uuid = 0;
function stableSort(arr, compare) {
var wrapper = arr.map(function (item, idx) {
return { item: item, idx: idx };
});
wrapper.sort(function (a, b) {
return compare(a.item, b.item) || (a.idx - b.idx);
});
return wrapper.map(function (w) { return w.item });
}
function MemoryStore() {
this._queue = []; // Array of taskIds
this._tasks = {}; // Map of taskId => task
this._priorities = {}; // Map of taskId => priority
this._running = {}; // Map of lockId => taskIds
}
MemoryStore.prototype.connect = function (cb) {
cb(null, this._queue.length);
}
MemoryStore.prototype.getTask = function (taskId, cb) {
return cb(null, this._tasks[taskId]);
}
MemoryStore.prototype.deleteTask = function (taskId, cb) {
var self = this;
var hadTask = self._tasks[taskId];
delete self._tasks[taskId];
delete self._priorities[taskId];
if (hadTask) {
self._queue.splice(self._queue.indexOf(taskId), 1);
}
cb();
}
MemoryStore.prototype.putTask = function (taskId, task, priority, cb) {
var self = this;
var hadTask = self._tasks[taskId];
self._tasks[taskId] = task;
if (!hadTask) {
self._queue.push(taskId);
}
if (priority !== undefined) {
self._priorities[taskId] = priority;
self._queue = stableSort(self._queue, function (a, b) {
if (self._priorities[a] < self._priorities[b]) return 1;
if (self._priorities[a] > self._priorities[b]) return -1;
return 0;
})
}
cb();
}
MemoryStore.prototype.takeFirstN = function (n, cb) {
var self = this;
var lockId = uuid++;;
var taskIds = self._queue.splice(0, n);
var tasks = {};
taskIds.forEach(function (taskId) {
tasks[taskId] = self._tasks[taskId];
delete self._tasks[taskId];
})
if (taskIds.length > 0) {
self._running[lockId] = tasks;
}
cb(null, lockId);
}
MemoryStore.prototype.takeLastN = function (n, cb) {
var self = this;
var lockId = uuid++;
var taskIds = self._queue.splice(-n).reverse();
var tasks = {};
taskIds.forEach(function (taskId) {
tasks[taskId] = self._tasks[taskId];
delete self._tasks[taskId];
})
if (taskIds.length > 0) {
self._running[lockId] = tasks;
}
cb(null, lockId);
}
MemoryStore.prototype.getLock = function (lockId, cb) {
var self = this;
cb(null, self._running[lockId]);
}
MemoryStore.prototype.getRunningTasks = function (cb) {
var self = this;
cb(null, self._running);
}
MemoryStore.prototype.releaseLock = function (lockId, cb) {
var self = this;
delete self._running[lockId];
cb();
}
module.exports = MemoryStore;