forked from exi/rsyncCopyManager
-
Notifications
You must be signed in to change notification settings - Fork 0
/
serverQueue.js
92 lines (77 loc) · 2.32 KB
/
serverQueue.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
var events = require('events');
var util = require('util');
var Token = module.exports.Token = function(startFunction) {
events.EventEmitter.call(this);
this.start = startFunction;
};
util.inherits(Token, events.EventEmitter);
var Queue = module.exports.Queue = function(dependencies) {
var api = {};
var servers = {};
function notifyPositionChange(queue) {
queue.forEach(function(item, idx) {
item.token.emit('position-change', idx);
});
}
function cleanQueue(queue) {
var l = queue.length;
var change = false;
for (var i = 0; i < l ; i++) {
if (queue[i].finished === true) {
queue.splice(i, 1);
l--;
change = true;
}
}
if (change) {
notifyPositionChange(queue);
}
}
function runQueue(serverId) {
var server = servers[serverId];
var queue = server.queue;
if (queue.length > 0) {
var item = queue[0];
item.token.on('finished', function() {
queue.shift();
notifyPositionChange(queue);
runQueue(serverId);
});
item.token.start();
}
}
dependencies.eventBus.on('server-removed', function(serverId) {
console.log('server queue remove' + serverId);
if (servers.hasOwnProperty(serverId)) {
console.log('reallay server queue remove' + serverId);
servers[serverId].queue.forEach(function(item) {
item.token.emit('reject');
});
servers[serverId].queue = [];
}
});
function schedule(serverId) {
if (servers[serverId].queue.length === 1) {
runQueue(serverId);
}
}
api.queue = function(serverId, token) {
if (!servers.hasOwnProperty(serverId)) {
servers[serverId] = {
queue: []
};
}
var item = {
finished: false,
token: token
};
servers[serverId].queue.push(item);
token.on('finished', function() {
item.finished = true;
cleanQueue(servers[serverId]);
});
schedule(serverId);
notifyPositionChange(servers[serverId].queue);
};
return api;
};