1 // Copyright Joyent, Inc. and other Node contributors.
3 // Permission is hereby granted, free of charge, to any person obtaining a
4 // copy of this software and associated documentation files (the
5 // "Software"), to deal in the Software without restriction, including
6 // without limitation the rights to use, copy, modify, merge, publish,
7 // distribute, sublicense, and/or sell copies of the Software, and to permit
8 // persons to whom the Software is furnished to do so, subject to the
9 // following conditions:
11 // The above copyright notice and this permission notice shall be included
12 // in all copies or substantial portions of the Software.
14 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15 // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17 // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20 // USE OR OTHER DEALINGS IN THE SOFTWARE.
22 var Timer = process.binding('timer_wrap').Timer;
23 var L = require('_linklist');
24 var assert = require('assert').ok;
26 var kOnTimeout = Timer.kOnTimeout | 0;
28 // Timeout values > TIMEOUT_MAX are set to 1.
29 var TIMEOUT_MAX = 2147483647; // 2^31-1
31 var debug = require('util').debuglog('timer');
33 var tracing = require('tracing');
34 var asyncFlags = tracing._asyncFlags;
35 var runAsyncQueue = tracing._runAsyncQueue;
36 var loadAsyncQueue = tracing._loadAsyncQueue;
37 var unloadAsyncQueue = tracing._unloadAsyncQueue;
39 // Same as in AsyncListener in env.h
42 // Do a little housekeeping.
43 delete tracing._asyncFlags;
44 delete tracing._runAsyncQueue;
45 delete tracing._loadAsyncQueue;
46 delete tracing._unloadAsyncQueue;
51 // Because often many sockets will have the same idle timeout we will not
52 // use one timeout watcher per item. It is too much overhead. Instead
53 // we'll use a single watcher for all sockets with the same timeout value
54 // and a linked list. This technique is described in the libev manual:
55 // http://pod.tst.eu/http://cvs.schmorp.de/libev/ev.pod#Be_smart_about_timeouts
57 // Object containing all lists, timers
58 // key = time in milliseconds
62 // Make Timer as monomorphic as possible.
63 Timer.prototype._asyncQueue = undefined;
64 Timer.prototype._asyncData = undefined;
65 Timer.prototype._asyncFlags = 0;
67 // the main function - creates lists on demand and the watchers associated
69 function insert(item, msecs) {
70 item._idleStart = Timer.now();
71 item._idleTimeout = msecs;
73 if (msecs < 0) return;
87 list[kOnTimeout] = listOnTimeout;
91 assert(!L.isEmpty(list)); // list is not empty
94 function listOnTimeout() {
95 var msecs = this.msecs;
98 debug('timeout callback %d', msecs);
100 var now = Timer.now();
101 debug('now: %s', now);
103 var diff, first, hasQueue, threw;
104 while (first = L.peek(list)) {
105 diff = now - first._idleStart;
107 list.start(msecs - diff, 0);
108 debug('%d list wait because diff is %d', msecs, diff);
112 assert(first !== L.peek(list));
114 if (!first._onTimeout) continue;
116 // v0.4 compatibility: if the timer callback throws and the
117 // domain or uncaughtException handler ignore the exception,
118 // other timers that expire on this tick should still run.
120 // https://github.com/joyent/node/issues/2631
121 var domain = first.domain;
122 if (domain && domain._disposed)
125 hasQueue = !!first._asyncQueue;
129 loadAsyncQueue(first);
137 unloadAsyncQueue(first);
141 // We need to continue processing after domain error handling
142 // is complete, but not by using whatever domain was left over
143 // when the timeout threw its exception.
144 var oldDomain = process.domain;
145 process.domain = null;
146 process.nextTick(function() {
149 process.domain = oldDomain;
155 debug('%d list empty', msecs);
156 assert(L.isEmpty(list));
162 var unenroll = exports.unenroll = function(item) {
165 var list = lists[item._idleTimeout];
166 // if empty then stop the watcher
168 if (list && L.isEmpty(list)) {
169 debug('unenroll: list empty');
171 delete lists[item._idleTimeout];
173 // if active is called later, then we want to make sure not to insert again
174 item._idleTimeout = -1;
178 // Does not start the time, just sets up the members needed.
179 exports.enroll = function(item, msecs) {
180 // if this item was already in a list somewhere
181 // then we should unenroll it from that
182 if (item._idleNext) unenroll(item);
184 // Ensure that msecs fits into signed int32
185 if (msecs > 0x7fffffff) {
189 item._idleTimeout = msecs;
194 // call this whenever the item is active (not idle)
195 // it will reset its timeout.
196 exports.active = function(item) {
197 var msecs = item._idleTimeout;
199 var list = lists[msecs];
200 if (!list || L.isEmpty(list)) {
203 item._idleStart = Timer.now();
204 L.append(list, item);
207 // Whether or not a new TimerWrap needed to be created, this should run
208 // for each item. This way each "item" (i.e. timer) can properly have
209 // their own domain assigned.
210 if (asyncFlags[kHasListener] > 0)
220 exports.setTimeout = function(callback, after) {
223 after *= 1; // coalesce to number or NaN
225 if (!(after >= 1 && after <= TIMEOUT_MAX)) {
226 after = 1; // schedule on next tick, follows browser behaviour
229 timer = new Timeout(after);
231 if (arguments.length <= 2) {
232 timer._onTimeout = callback;
235 * Sometimes setTimeout is called with arguments, EG
237 * setTimeout(callback, 2000, "hello", "world")
239 * If that's the case we need to call the callback with
240 * those args. The overhead of an extra closure is not
241 * desired in the normal case.
243 var args = Array.prototype.slice.call(arguments, 2);
244 timer._onTimeout = function() {
245 callback.apply(timer, args);
249 if (process.domain) timer.domain = process.domain;
251 exports.active(timer);
257 exports.clearTimeout = function(timer) {
258 if (timer && (timer[kOnTimeout] || timer._onTimeout)) {
259 timer[kOnTimeout] = timer._onTimeout = null;
260 if (timer instanceof Timeout) {
261 timer.close(); // for after === 0
263 exports.unenroll(timer);
269 exports.setInterval = function(callback, repeat) {
270 repeat *= 1; // coalesce to number or NaN
272 if (!(repeat >= 1 && repeat <= TIMEOUT_MAX)) {
273 repeat = 1; // schedule on next tick, follows browser behaviour
276 var timer = new Timeout(repeat);
277 var args = Array.prototype.slice.call(arguments, 2);
278 timer._onTimeout = wrapper;
279 timer._repeat = true;
281 if (process.domain) timer.domain = process.domain;
282 exports.active(timer);
287 callback.apply(this, args);
288 // If callback called clearInterval().
289 if (timer._repeat === false) return;
290 // If timer is unref'd (or was - it's permanently removed from the list.)
292 this._handle.start(repeat, 0);
294 timer._idleTimeout = repeat;
295 exports.active(timer);
301 exports.clearInterval = function(timer) {
302 if (timer && timer._repeat) {
303 timer._repeat = false;
309 var Timeout = function(after) {
310 this._idleTimeout = after;
311 this._idlePrev = this;
312 this._idleNext = this;
313 this._idleStart = null;
314 this._onTimeout = null;
315 this._repeat = false;
318 Timeout.prototype.unref = function() {
320 var now = Timer.now();
321 if (!this._idleStart) this._idleStart = now;
322 var delay = this._idleStart + this._idleTimeout - now;
323 if (delay < 0) delay = 0;
324 exports.unenroll(this);
325 this._handle = new Timer();
326 this._handle[kOnTimeout] = this._onTimeout;
327 this._handle.start(delay, 0);
328 this._handle.domain = this.domain;
329 this._handle.unref();
331 this._handle.unref();
335 Timeout.prototype.ref = function() {
340 Timeout.prototype.close = function() {
341 this._onTimeout = null;
343 this._handle[kOnTimeout] = null;
344 this._handle.close();
346 exports.unenroll(this);
351 var immediateQueue = {};
352 L.init(immediateQueue);
355 function processImmediate() {
356 var queue = immediateQueue;
357 var domain, hasQueue, immediate;
360 L.init(immediateQueue);
362 while (L.isEmpty(queue) === false) {
363 immediate = L.shift(queue);
364 hasQueue = !!immediate._asyncQueue;
365 domain = immediate.domain;
368 loadAsyncQueue(immediate);
374 immediate._onImmediate();
378 if (!L.isEmpty(queue)) {
379 // Handle any remaining on next tick, assuming we're still
381 while (!L.isEmpty(immediateQueue)) {
382 L.append(queue, L.shift(immediateQueue));
384 immediateQueue = queue;
385 process.nextTick(processImmediate);
393 unloadAsyncQueue(immediate);
396 // Only round-trip to C++ land if we have to. Calling clearImmediate() on an
397 // immediate that's in |queue| is okay. Worst case is we make a superfluous
398 // call to NeedImmediateCallbackSetter().
399 if (L.isEmpty(immediateQueue)) {
400 process._needImmediateCallback = false;
405 function Immediate() { }
407 Immediate.prototype.domain = undefined;
408 Immediate.prototype._onImmediate = undefined;
409 Immediate.prototype._asyncQueue = undefined;
410 Immediate.prototype._asyncData = undefined;
411 Immediate.prototype._idleNext = undefined;
412 Immediate.prototype._idlePrev = undefined;
413 Immediate.prototype._asyncFlags = 0;
416 exports.setImmediate = function(callback) {
417 var immediate = new Immediate();
422 immediate._onImmediate = callback;
424 if (arguments.length > 1) {
426 for (index = 1; index < arguments.length; index++)
427 args.push(arguments[index]);
429 immediate._onImmediate = function() {
430 callback.apply(immediate, args);
434 if (!process._needImmediateCallback) {
435 process._needImmediateCallback = true;
436 process._immediateCallback = processImmediate;
439 // setImmediates are handled more like nextTicks.
440 if (asyncFlags[kHasListener] > 0)
441 runAsyncQueue(immediate);
443 immediate.domain = process.domain;
445 L.append(immediateQueue, immediate);
451 exports.clearImmediate = function(immediate) {
452 if (!immediate) return;
454 immediate._onImmediate = undefined;
458 if (L.isEmpty(immediateQueue)) {
459 process._needImmediateCallback = false;
464 // Internal APIs that need timeouts should use timers._unrefActive instead of
465 // timers.active as internal timeouts shouldn't hold the loop open
467 var unrefList, unrefTimer;
470 function unrefTimeout() {
471 var now = Timer.now();
473 debug('unrefTimer fired');
475 var diff, domain, first, hasQueue, threw;
476 while (first = L.peek(unrefList)) {
477 diff = now - first._idleStart;
479 if (diff < first._idleTimeout) {
480 diff = first._idleTimeout - diff;
481 unrefTimer.start(diff, 0);
482 unrefTimer.when = now + diff;
483 debug('unrefTimer rescheudling for later');
489 domain = first.domain;
491 if (!first._onTimeout) continue;
492 if (domain && domain._disposed) continue;
493 hasQueue = !!first._asyncQueue;
497 loadAsyncQueue(first);
498 if (domain) domain.enter();
500 debug('unreftimer firing timeout');
506 unloadAsyncQueue(first);
508 if (threw) process.nextTick(unrefTimeout);
512 debug('unrefList is empty');
513 unrefTimer.when = -1;
517 exports._unrefActive = function(item) {
518 var msecs = item._idleTimeout;
519 if (!msecs || msecs < 0) return;
525 debug('unrefList initialized');
529 debug('unrefTimer initialized');
530 unrefTimer = new Timer();
532 unrefTimer.when = -1;
533 unrefTimer[kOnTimeout] = unrefTimeout;
536 var now = Timer.now();
537 item._idleStart = now;
539 if (L.isEmpty(unrefList)) {
540 debug('unrefList empty');
541 L.append(unrefList, item);
543 unrefTimer.start(msecs, 0);
544 unrefTimer.when = now + msecs;
545 debug('unrefTimer scheduled');
549 var when = now + msecs;
551 debug('unrefList find where we can insert');
555 for (cur = unrefList._idlePrev; cur != unrefList; cur = cur._idlePrev) {
556 them = cur._idleStart + cur._idleTimeout;
559 debug('unrefList inserting into middle of list');
563 if (unrefTimer.when > when) {
564 debug('unrefTimer is scheduled to fire too late, reschedule');
565 unrefTimer.start(msecs, 0);
566 unrefTimer.when = when;
573 debug('unrefList append to end');
574 L.append(unrefList, item);