Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
freebsd
GitHub Repository: freebsd/phabricator
Path: blob/master/webroot/rsrc/externals/javelin/lib/Router.js
12242 views
1
/**
2
* @provides javelin-router
3
* @requires javelin-install
4
* javelin-util
5
* @javelin
6
*/
7
8
/**
9
* Route requests. Primarily, this class provides a quality-of-service
10
* priority queue so large numbers of background loading tasks don't block
11
* interactive requests.
12
*/
13
JX.install('Router', {
14
15
construct: function() {
16
this._queue = [];
17
},
18
19
events: ['queue', 'start', 'done'],
20
21
members: {
22
_queue: null,
23
_active: 0,
24
_limit: 5,
25
26
queue: function(routable) {
27
this._queue.push(routable);
28
29
this.invoke('queue', routable);
30
this._update();
31
},
32
33
getRoutableByKey: function(key) {
34
for (var ii = 0; ii < this._queue.length; ii++) {
35
if (this._queue[ii].getKey() == key) {
36
return this._queue[ii];
37
}
38
}
39
return null;
40
},
41
42
/**
43
* Start new requests if we have slots free for them.
44
*/
45
_update: function() {
46
var active = this._active;
47
var limit = this._limit;
48
49
if (active >= limit) {
50
// If we're already at the request limit, we can't add any more
51
// requests.
52
return;
53
}
54
55
// If we only have one free slot, we reserve it for a request with
56
// at least priority 1000.
57
var minimum;
58
if ((active + 1) == limit) {
59
minimum = 1000;
60
} else {
61
minimum = 0;
62
}
63
64
var idx = this._getNextRoutable(minimum);
65
if (idx === null) {
66
return;
67
}
68
69
var routable = this._queue[idx];
70
this._queue.splice(idx, 1);
71
72
73
routable.listen('done', JX.bind(this, this._done, routable));
74
75
this._active++;
76
routable.start();
77
this.invoke('start', routable);
78
79
this._update();
80
},
81
82
_done: function(routable) {
83
this._active--;
84
this.invoke('done', routable);
85
86
this._update();
87
},
88
89
_getNextRoutable: function(minimum) {
90
var best = (minimum - 1);
91
92
var routable = null;
93
for (var ii = 0; ii < this._queue.length; ii++) {
94
var priority = this._queue[ii].getPriority();
95
if (priority > best) {
96
best = priority;
97
routable = ii;
98
}
99
}
100
101
return routable;
102
}
103
104
},
105
106
statics: {
107
_instance: null,
108
getInstance: function() {
109
if (!JX.Router._instance) {
110
JX.Router._instance = new JX.Router();
111
}
112
return JX.Router._instance;
113
}
114
}
115
});
116
117