forked from uber/tchannel-node
-
Notifications
You must be signed in to change notification settings - Fork 0
/
time_heap.js
304 lines (255 loc) · 8.17 KB
/
time_heap.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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
// Copyright (c) 2020 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
'use strict';
var setImmediate = require('timers').setImmediate;
var DRAIN_LOOP_MAX_DURATION = 100; // ms
module.exports = TimeHeap;
var globalTimers = {
setTimeout: require('timers').setTimeout,
clearTimeout: require('timers').clearTimeout,
now: Date.now
};
/* A specialized min-time heap
*
* new TimeHeap({
* timer: {now, setTimeout, clearTimeout},
* minTimeout: Number | (now) -> Number
* })
*
* The items on the heap must have two properties:
* - item.timeout is ms timeout, relative to heap add time
* - item.onTimeout is a callback which gets called once the item has expired;
* the callback is passed the current time in ms.
*
* Overview:
* - timeHeap.array is an array of TimeHeapElement objects
*
* - timeHeap.lastTime is the timestamp (ms) that all times in the heap are
* relative to
*
* - timeHeap.timer is the currently pending timer object or null
*
* - timeHeap.expired are any items pending having their .onTimeout called; this
* call is defered until next tick after a drain to avoid any heap
* interactions/changes while draining (if the callback adds something else
* to the heap)
*
* The primary public API is:
* timeHeap.update(item, ?now)
*
* Note the method is is intentionally not named something simple like "add" or
* "append" since it does a bit more:
* - pop any expired times, and defer a call to their .onTimeout
* - push the new item and its expiration time onto the heap
* - set a timer if there is none or the newly added item is the next to expire
*
* TODO: shrink array if end is << array.length/2 (trigger in pop and/or a
* sweep on an interval)
*/
function TimeHeap(options) {
var self = this;
options = options || {};
self.timers = options.timers || globalTimers;
self.minTimeout = options.minTimeout || null;
self.array = [];
self.expired = [];
self.lastTime = self.timers.now();
self.timer = null;
self.end = 0;
self.lastRun = 0;
self.drainUntil = 0;
self.scheduledDrain = null;
self.boundDrainExpired = boundDrainExpired;
function boundDrainExpired() {
var now = self.scheduledDrain;
self.scheduledDrain = null;
self.drainExpired(now);
}
}
TimeHeap.prototype.clear = function clear() {
var self = this;
self.timers.clearTimeout(self.timer);
self.array = [];
self.expired = [];
self.timer = null;
self.lastTime = self.timers.now();
self.end = 0;
};
TimeHeap.prototype.getNextTimeout = function getNextTimeout(now) {
var self = this;
var timeout = self.array[0].expireTime - now;
if (typeof self.minTimeout === 'function') {
timeout = Math.max(self.minTimeout(now), timeout);
} else if (typeof self.minTimeout === 'number') {
timeout = Math.max(self.minTimeout, timeout);
}
return timeout;
};
TimeHeap.prototype.update = function update(item, now) {
var self = this;
if (now === undefined) {
now = self.timers.now();
}
self.scheduleDrainExpired(now);
var time = now + item.timeout;
var i = self.push(item, time);
// update timer if none, or the newly added item is the new root
if (!self.timer || i === 0) {
self.setNextTimer(now);
}
return self.array[i];
};
TimeHeap.prototype.scheduleDrainExpired =
function scheduleDrainExpired(now) {
var self = this;
if (self.scheduledDrain) {
return;
}
self.scheduledDrain = now;
setImmediate(self.boundDrainExpired);
};
TimeHeap.prototype.setNextTimer = function setNextTimer(now) {
var self = this;
if (self.timer) {
self.timers.clearTimeout(self.timer);
}
var timeout = self.getNextTimeout(now);
self.timer = self.timers.setTimeout(onTimeout, timeout);
function onTimeout() {
var now2 = self.timers.now();
self.onTimeout(now2);
}
};
TimeHeap.prototype.onTimeout = function onTimeout(now) {
var self = this;
self.timer = null;
self.lastRun = now;
self.drainExpired(now);
if (self.end) {
self.setNextTimer(now);
}
};
TimeHeap.prototype.drainExpired = function drainExpired(now) {
var self = this;
if (now < self.drainUntil) {
return;
}
self.drainUntil = now + DRAIN_LOOP_MAX_DURATION;
while (self.end && self.array[0].expireTime <= now) {
var item = self.pop();
if (item) {
self.expired.push(item);
}
}
if (self.expired.length) {
// callExpiredTimeouts can re-enter drainExpired by calling popOutReq,
// which in turn calls update, and then back to drainExpired.
// The drainUntil shorts this recursive loop.
// The solution uses a timer instead of a flag to ensure that drain
// resumes even if an exception halts the loop prematurely without
// incurring the cost of try/finally.
self.callExpiredTimeouts(now);
}
self.drainUntil = 0;
};
TimeHeap.prototype.callExpiredTimeouts = function callExpiredTimeouts(now) {
var self = this;
while (self.expired.length) {
var item = self.expired.shift();
item.onTimeout(now);
}
};
TimeHeap.prototype.push = function push(item, expireTime) {
var self = this;
var i = self.end;
if (i >= self.array.length) {
i = self.array.length;
self.array.push(new TimeHeapElement());
}
var el = self.array[i];
el.expireTime = expireTime;
el.item = item;
self.end = i + 1;
return self.siftup(i);
};
TimeHeap.prototype.pop = function pop() {
var self = this;
if (!self.end) {
return null;
}
var el = self.array[0];
self.end--;
self.swap(0, self.end);
self.siftdown(0);
var item = el.item;
el.expireTime = 0;
el.item = null;
return item;
};
TimeHeap.prototype.siftdown = function siftdown(i) {
var self = this;
for (;;) {
var left = (2 * i) + 1;
var right = left + 1;
if (left < self.end &&
self.array[left].expireTime < self.array[i].expireTime) {
if (right < self.end &&
self.array[right].expireTime < self.array[left].expireTime) {
self.swap(i, right);
i = right;
} else {
self.swap(i, left);
i = left;
}
} else if (right < self.end &&
self.array[right].expireTime < self.array[i].expireTime) {
self.swap(i, right);
i = right;
} else {
return i;
}
}
};
TimeHeap.prototype.siftup = function siftup(i) {
var self = this;
while (i > 0) {
var par = Math.floor((i - 1) / 2);
if (self.array[i].expireTime < self.array[par].expireTime) {
self.swap(i, par);
i = par;
} else {
break;
}
}
return i;
};
TimeHeap.prototype.swap = function swap(i, j) {
var self = this;
var tmp = self.array[i];
self.array[i] = self.array[j];
self.array[j] = tmp;
};
function TimeHeapElement() {
this.expireTime = 0;
this.item = null;
}
TimeHeapElement.prototype.cancel = function cancel() {
this.item = null;
};