3039b49f2c372743b44c6766f0ba9568b0b3c77a
[platform/upstream/nodejs.git] / lib / timers.js
1 // Copyright Joyent, Inc. and other Node contributors.
2 //
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:
10 //
11 // The above copyright notice and this permission notice shall be included
12 // in all copies or substantial portions of the Software.
13 //
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.
21
22 var Timer = process.binding('timer_wrap').Timer;
23 var L = require('_linklist');
24 var assert = require('assert').ok;
25
26 var kOnTimeout = Timer.kOnTimeout | 0;
27
28 // Timeout values > TIMEOUT_MAX are set to 1.
29 var TIMEOUT_MAX = 2147483647; // 2^31-1
30
31 var debug = require('util').debuglog('timer');
32
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;
38
39 // Same as in AsyncListener in env.h
40 var kHasListener = 0;
41
42 // Do a little housekeeping.
43 delete tracing._asyncFlags;
44 delete tracing._runAsyncQueue;
45 delete tracing._loadAsyncQueue;
46 delete tracing._unloadAsyncQueue;
47
48
49 // IDLE TIMEOUTS
50 //
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
56
57 // Object containing all lists, timers
58 // key = time in milliseconds
59 // value = list
60 var lists = {};
61
62 // Make Timer as monomorphic as possible.
63 Timer.prototype._asyncQueue = undefined;
64 Timer.prototype._asyncData = undefined;
65 Timer.prototype._asyncFlags = 0;
66
67 // the main function - creates lists on demand and the watchers associated
68 // with them.
69 function insert(item, msecs) {
70   item._idleStart = Timer.now();
71   item._idleTimeout = msecs;
72
73   if (msecs < 0) return;
74
75   var list;
76
77   if (lists[msecs]) {
78     list = lists[msecs];
79   } else {
80     list = new Timer();
81     list.start(msecs, 0);
82
83     L.init(list);
84
85     lists[msecs] = list;
86     list.msecs = msecs;
87     list[kOnTimeout] = listOnTimeout;
88   }
89
90   L.append(list, item);
91   assert(!L.isEmpty(list)); // list is not empty
92 }
93
94 function listOnTimeout() {
95   var msecs = this.msecs;
96   var list = this;
97
98   debug('timeout callback %d', msecs);
99
100   var now = Timer.now();
101   debug('now: %s', now);
102
103   var diff, first, hasQueue, threw;
104   while (first = L.peek(list)) {
105     diff = now - first._idleStart;
106     if (diff < msecs) {
107       list.start(msecs - diff, 0);
108       debug('%d list wait because diff is %d', msecs, diff);
109       return;
110     } else {
111       L.remove(first);
112       assert(first !== L.peek(list));
113
114       if (!first._onTimeout) continue;
115
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.
119       //
120       // https://github.com/joyent/node/issues/2631
121       var domain = first.domain;
122       if (domain && domain._disposed)
123         continue;
124
125       hasQueue = !!first._asyncQueue;
126
127       try {
128         if (hasQueue)
129           loadAsyncQueue(first);
130         if (domain)
131           domain.enter();
132         threw = true;
133         first._onTimeout();
134         if (domain)
135           domain.exit();
136         if (hasQueue)
137           unloadAsyncQueue(first);
138         threw = false;
139       } finally {
140         if (threw) {
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() {
147             list[kOnTimeout]();
148           });
149           process.domain = oldDomain;
150         }
151       }
152     }
153   }
154
155   debug('%d list empty', msecs);
156   assert(L.isEmpty(list));
157   list.close();
158   delete lists[msecs];
159 }
160
161
162 var unenroll = exports.unenroll = function(item) {
163   L.remove(item);
164
165   var list = lists[item._idleTimeout];
166   // if empty then stop the watcher
167   debug('unenroll');
168   if (list && L.isEmpty(list)) {
169     debug('unenroll: list empty');
170     list.close();
171     delete lists[item._idleTimeout];
172   }
173   // if active is called later, then we want to make sure not to insert again
174   item._idleTimeout = -1;
175 };
176
177
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);
183
184   // Ensure that msecs fits into signed int32
185   if (msecs > 0x7fffffff) {
186     msecs = 0x7fffffff;
187   }
188
189   item._idleTimeout = msecs;
190   L.init(item);
191 };
192
193
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;
198   if (msecs >= 0) {
199     var list = lists[msecs];
200     if (!list || L.isEmpty(list)) {
201       insert(item, msecs);
202     } else {
203       item._idleStart = Timer.now();
204       L.append(list, item);
205     }
206   }
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)
211     runAsyncQueue(item);
212 };
213
214
215 /*
216  * DOM-style timers
217  */
218
219
220 exports.setTimeout = function(callback, after) {
221   var timer;
222
223   after *= 1; // coalesce to number or NaN
224
225   if (!(after >= 1 && after <= TIMEOUT_MAX)) {
226     after = 1; // schedule on next tick, follows browser behaviour
227   }
228
229   timer = new Timeout(after);
230
231   if (arguments.length <= 2) {
232     timer._onTimeout = callback;
233   } else {
234     /*
235      * Sometimes setTimeout is called with arguments, EG
236      *
237      *   setTimeout(callback, 2000, "hello", "world")
238      *
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.
242      */
243     var args = Array.prototype.slice.call(arguments, 2);
244     timer._onTimeout = function() {
245       callback.apply(timer, args);
246     }
247   }
248
249   if (process.domain) timer.domain = process.domain;
250
251   exports.active(timer);
252
253   return timer;
254 };
255
256
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
262     } else {
263       exports.unenroll(timer);
264     }
265   }
266 };
267
268
269 exports.setInterval = function(callback, repeat) {
270   repeat *= 1; // coalesce to number or NaN
271
272   if (!(repeat >= 1 && repeat <= TIMEOUT_MAX)) {
273     repeat = 1; // schedule on next tick, follows browser behaviour
274   }
275
276   var timer = new Timeout(repeat);
277   var args = Array.prototype.slice.call(arguments, 2);
278   timer._onTimeout = wrapper;
279   timer._repeat = true;
280
281   if (process.domain) timer.domain = process.domain;
282   exports.active(timer);
283
284   return timer;
285
286   function wrapper() {
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.)
291     if (this._handle) {
292       this._handle.start(repeat, 0);
293     } else {
294       timer._idleTimeout = repeat;
295       exports.active(timer);
296     }
297   }
298 };
299
300
301 exports.clearInterval = function(timer) {
302   if (timer && timer._repeat) {
303     timer._repeat = false;
304     clearTimeout(timer);
305   }
306 };
307
308
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;
316 };
317
318 Timeout.prototype.unref = function() {
319   if (!this._handle) {
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();
330   } else {
331     this._handle.unref();
332   }
333 };
334
335 Timeout.prototype.ref = function() {
336   if (this._handle)
337     this._handle.ref();
338 };
339
340 Timeout.prototype.close = function() {
341   this._onTimeout = null;
342   if (this._handle) {
343     this._handle[kOnTimeout] = null;
344     this._handle.close();
345   } else {
346     exports.unenroll(this);
347   }
348 };
349
350
351 var immediateQueue = {};
352 L.init(immediateQueue);
353
354
355 function processImmediate() {
356   var queue = immediateQueue;
357   var domain, hasQueue, immediate;
358
359   immediateQueue = {};
360   L.init(immediateQueue);
361
362   while (L.isEmpty(queue) === false) {
363     immediate = L.shift(queue);
364     hasQueue = !!immediate._asyncQueue;
365     domain = immediate.domain;
366
367     if (hasQueue)
368       loadAsyncQueue(immediate);
369     if (domain)
370       domain.enter();
371
372     var threw = true;
373     try {
374       immediate._onImmediate();
375       threw = false;
376     } finally {
377       if (threw) {
378         if (!L.isEmpty(queue)) {
379           // Handle any remaining on next tick, assuming we're still
380           // alive to do so.
381           while (!L.isEmpty(immediateQueue)) {
382             L.append(queue, L.shift(immediateQueue));
383           }
384           immediateQueue = queue;
385           process.nextTick(processImmediate);
386         }
387       }
388     }
389
390     if (domain)
391       domain.exit();
392     if (hasQueue)
393       unloadAsyncQueue(immediate);
394   }
395
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;
401   }
402 }
403
404
405 function Immediate() { }
406
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;
414
415
416 exports.setImmediate = function(callback) {
417   var immediate = new Immediate();
418   var args, index;
419
420   L.init(immediate);
421
422   immediate._onImmediate = callback;
423
424   if (arguments.length > 1) {
425     args = [];
426     for (index = 1; index < arguments.length; index++)
427       args.push(arguments[index]);
428
429     immediate._onImmediate = function() {
430       callback.apply(immediate, args);
431     };
432   }
433
434   if (!process._needImmediateCallback) {
435     process._needImmediateCallback = true;
436     process._immediateCallback = processImmediate;
437   }
438
439   // setImmediates are handled more like nextTicks.
440   if (asyncFlags[kHasListener] > 0)
441     runAsyncQueue(immediate);
442   if (process.domain)
443     immediate.domain = process.domain;
444
445   L.append(immediateQueue, immediate);
446
447   return immediate;
448 };
449
450
451 exports.clearImmediate = function(immediate) {
452   if (!immediate) return;
453
454   immediate._onImmediate = undefined;
455
456   L.remove(immediate);
457
458   if (L.isEmpty(immediateQueue)) {
459     process._needImmediateCallback = false;
460   }
461 };
462
463
464 // Internal APIs that need timeouts should use timers._unrefActive instead of
465 // timers.active as internal timeouts shouldn't hold the loop open
466
467 var unrefList, unrefTimer;
468
469
470 function unrefTimeout() {
471   var now = Timer.now();
472
473   debug('unrefTimer fired');
474
475   var diff, domain, first, hasQueue, threw;
476   while (first = L.peek(unrefList)) {
477     diff = now - first._idleStart;
478
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');
484       return;
485     }
486
487     L.remove(first);
488
489     domain = first.domain;
490
491     if (!first._onTimeout) continue;
492     if (domain && domain._disposed) continue;
493     hasQueue = !!first._asyncQueue;
494
495     try {
496       if (hasQueue)
497         loadAsyncQueue(first);
498       if (domain) domain.enter();
499       threw = true;
500       debug('unreftimer firing timeout');
501       first._onTimeout();
502       threw = false;
503       if (domain)
504         domain.exit();
505       if (hasQueue)
506         unloadAsyncQueue(first);
507     } finally {
508       if (threw) process.nextTick(unrefTimeout);
509     }
510   }
511
512   debug('unrefList is empty');
513   unrefTimer.when = -1;
514 }
515
516
517 exports._unrefActive = function(item) {
518   var msecs = item._idleTimeout;
519   if (!msecs || msecs < 0) return;
520   assert(msecs >= 0);
521
522   L.remove(item);
523
524   if (!unrefList) {
525     debug('unrefList initialized');
526     unrefList = {};
527     L.init(unrefList);
528
529     debug('unrefTimer initialized');
530     unrefTimer = new Timer();
531     unrefTimer.unref();
532     unrefTimer.when = -1;
533     unrefTimer[kOnTimeout] = unrefTimeout;
534   }
535
536   var now = Timer.now();
537   item._idleStart = now;
538
539   if (L.isEmpty(unrefList)) {
540     debug('unrefList empty');
541     L.append(unrefList, item);
542
543     unrefTimer.start(msecs, 0);
544     unrefTimer.when = now + msecs;
545     debug('unrefTimer scheduled');
546     return;
547   }
548
549   var when = now + msecs;
550
551   debug('unrefList find where we can insert');
552
553   var cur, them;
554
555   for (cur = unrefList._idlePrev; cur != unrefList; cur = cur._idlePrev) {
556     them = cur._idleStart + cur._idleTimeout;
557
558     if (when < them) {
559       debug('unrefList inserting into middle of list');
560
561       L.append(cur, item);
562
563       if (unrefTimer.when > when) {
564         debug('unrefTimer is scheduled to fire too late, reschedule');
565         unrefTimer.start(msecs, 0);
566         unrefTimer.when = when;
567       }
568
569       return;
570     }
571   }
572
573   debug('unrefList append to end');
574   L.append(unrefList, item);
575 };