summaryrefslogtreecommitdiffstats
path: root/src/civetweb/src/third_party/duktape-1.5.2/examples/eventloop/ecma_eventloop.js
blob: bad4e4d90116d1b371865a5708e6408a02566275 (plain)
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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
/*
 *  Pure Ecmascript eventloop example.
 *
 *  Timer state handling is inefficient in this trivial example.  Timers are
 *  kept in an array sorted by their expiry time which works well for expiring
 *  timers, but has O(n) insertion performance.  A better implementation would
 *  use a heap or some other efficient structure for managing timers so that
 *  all operations (insert, remove, get nearest timer) have good performance.
 *
 *  https://developer.mozilla.org/en-US/docs/Web/JavaScript/Timers
 */

/*
 *  Event loop
 *
 *  Timers are sorted by 'target' property which indicates expiry time of
 *  the timer.  The timer expiring next is last in the array, so that
 *  removals happen at the end, and inserts for timers expiring in the
 *  near future displace as few elements in the array as possible.
 */

EventLoop = {
    // timers
    timers: [],         // active timers, sorted (nearest expiry last)
    expiring: null,     // set to timer being expired (needs special handling in clearTimeout/clearInterval)
    nextTimerId: 1,
    minimumDelay: 1,
    minimumWait: 1,
    maximumWait: 60000,
    maxExpirys: 10,

    // sockets
    socketListening: {},  // fd -> callback
    socketReading: {},    // fd -> callback
    socketConnecting: {}, // fd -> callback

    // misc
    exitRequested: false
};

EventLoop.dumpState = function() {
    print('TIMER STATE:');
    this.timers.forEach(function(t) {
        print('    ' + Duktape.enc('jx', t));
    });
    if (this.expiring) {
        print('    EXPIRING: ' + Duktape.enc('jx', this.expiring));
    }
}

// Get timer with lowest expiry time.  Since the active timers list is
// sorted, it's always the last timer.
EventLoop.getEarliestTimer = function() {
    var timers = this.timers;
    n = timers.length;
    return (n > 0 ? timers[n - 1] : null);
}

EventLoop.getEarliestWait = function() {
    var t = this.getEarliestTimer();
    return (t ? t.target - Date.now() : null);
}

EventLoop.insertTimer = function(timer) {
    var timers = this.timers;
    var i, n, t;

    /*
     *  Find 'i' such that we want to insert *after* timers[i] at index i+1.
     *  If no such timer, for-loop terminates with i-1, and we insert at -1+1=0.
     */

    n = timers.length;
    for (i = n - 1; i >= 0; i--) {
        t = timers[i];
        if (timer.target <= t.target) {
            // insert after 't', to index i+1
            break;
        }
    }

    timers.splice(i + 1 /*start*/, 0 /*deleteCount*/, timer);
}

// Remove timer/interval with a timer ID.  The timer/interval can reside
// either on the active list or it may be an expired timer (this.expiring)
// whose user callback we're running when this function gets called.
EventLoop.removeTimerById = function(timer_id) {
    var timers = this.timers;
    var i, n, t;

    t = this.expiring;
    if (t) {
        if (t.id === timer_id) {
            // Timer has expired and we're processing its callback.  User
            // callback has requested timer deletion.  Mark removed, so
            // that the timer is not reinserted back into the active list.
            // This is actually a common case because an interval may very
            // well cancel itself.
            t.removed = true;
            return;
        }
    }

    n = timers.length;
    for (i = 0; i < n; i++) {
        t = timers[i];
        if (t.id === timer_id) {
            // Timer on active list: mark removed (not really necessary, but
            // nice for dumping), and remove from active list.
            t.removed = true;
            this.timers.splice(i /*start*/, 1 /*deleteCount*/);
            return;
        }
    }

   // no such ID, ignore
}

EventLoop.processTimers = function() {
    var now = Date.now();
    var timers = this.timers;
    var sanity = this.maxExpirys;
    var n, t;

    /*
     *  Here we must be careful with mutations: user callback may add and
     *  delete an arbitrary number of timers.
     *
     *  Current solution is simple: check whether the timer at the end of
     *  the list has expired.  If not, we're done.  If it has expired,
     *  remove it from the active list, record it in this.expiring, and call
     *  the user callback.  If user code deletes the this.expiring timer,
     *  there is special handling which just marks the timer deleted so
     *  it won't get inserted back into the active list.
     *
     *  This process is repeated at most maxExpirys times to ensure we don't
     *  get stuck forever; user code could in principle add more and more
     *  already expired timers.
     */

    while (sanity-- > 0) {
        // If exit requested, don't call any more callbacks.  This allows
        // a callback to do cleanups and request exit, and can be sure that
        // no more callbacks are processed.

        if (this.exitRequested) {
            //print('exit requested, exit');
            break;
        }

        // Timers to expire?

        n = timers.length;
        if (n <= 0) {
            break;
        }
        t = timers[n - 1];
        if (now <= t.target) {
            // Timer has not expired, and no other timer could have expired
            // either because the list is sorted.
            break;
        }
        timers.pop();

        // Remove the timer from the active list and process it.  The user
        // callback may add new timers which is not a problem.  The callback
        // may also delete timers which is not a problem unless the timer
        // being deleted is the timer whose callback we're running; this is
        // why the timer is recorded in this.expiring so that clearTimeout()
        // and clearInterval() can detect this situation.

        if (t.oneshot) {
            t.removed = true;  // flag for removal
        } else {
            t.target = now + t.delay;
        }
        this.expiring = t;
        try {
            t.cb();
        } catch (e) {
            print('timer callback failed, ignored: ' + e);
        }
        this.expiring = null;

        // If the timer was one-shot, it's marked 'removed'.  If the user callback
        // requested deletion for the timer, it's also marked 'removed'.  If the
        // timer is an interval (and is not marked removed), insert it back into
        // the timer list.

        if (!t.removed) {
            // Reinsert interval timer to correct sorted position.  The timer
            // must be an interval timer because one-shot timers are marked
            // 'removed' above.
            this.insertTimer(t);
        }
    }
}

EventLoop.run = function() {
    var wait;
    var POLLIN = Poll.POLLIN;
    var POLLOUT = Poll.POLLOUT;
    var poll_set;
    var poll_count;
    var fd;
    var t, rev;
    var rc;
    var acc_res;

    for (;;) {
        /*
         *  Process expired timers.
         */

        this.processTimers();
        //this.dumpState();

        /*
         *  Exit check (may be requested by a user callback)
         */

        if (this.exitRequested) {
            //print('exit requested, exit');
            break;
        }

        /*
         *  Create poll socket list.  This is a very naive approach.
         *  On Linux, one could use e.g. epoll() and manage socket lists
         *  incrementally.
         */

        poll_set = {};
        poll_count = 0;
        for (fd in this.socketListening) {
            poll_set[fd] = { events: POLLIN, revents: 0 };
            poll_count++;
        }
        for (fd in this.socketReading) {
            poll_set[fd] = { events: POLLIN, revents: 0 };
            poll_count++;
        }
        for (fd in this.socketConnecting) {
            poll_set[fd] = { events: POLLOUT, revents: 0 };
            poll_count++;
        }
        //print(new Date(), 'poll_set IN:', Duktape.enc('jx', poll_set));

        /*
         *  Wait timeout for timer closest to expiry.  Since the poll
         *  timeout is relative, get this as close to poll() as possible.
         */

        wait = this.getEarliestWait();
        if (wait === null) {
            if (poll_count === 0) {
                print('no active timers and no sockets to poll, exit');
                break;
            } else {
                wait = this.maximumWait;
            }
        } else {
            wait = Math.min(this.maximumWait, Math.max(this.minimumWait, wait));
        }

        /*
         *  Do the actual poll.
         */

        try {
            Poll.poll(poll_set, wait);
        } catch (e) {
            // Eat errors silently.  When resizing curses window an EINTR
            // happens now.
        }

        /*
         *  Process all sockets so that nothing is left unhandled for the
         *  next round.
         */

        //print(new Date(), 'poll_set OUT:', Duktape.enc('jx', poll_set));
        for (fd in poll_set) {
            t = poll_set[fd];
            rev = t.revents;

            if (rev & POLLIN) {
                cb = this.socketReading[fd];
                if (cb) {
                    data = Socket.read(fd);  // no size control now
                    //print('READ', Duktape.enc('jx', data));
                    if (data.length === 0) {
                        //print('zero read for fd ' + fd + ', closing forcibly');
                        rc = Socket.close(fd);  // ignore result
                        delete this.socketListening[fd];
                        delete this.socketReading[fd];
                    } else {
                        cb(fd, data);
                    }
                } else {
                    cb = this.socketListening[fd];
                    if (cb) {
                        acc_res = Socket.accept(fd);
                        //print('ACCEPT:', Duktape.enc('jx', acc_res));
                        cb(acc_res.fd, acc_res.addr, acc_res.port);
                    } else {
                        //print('UNKNOWN');
                    }
                }
            }

            if (rev & POLLOUT) {
                cb = this.socketConnecting[fd];
                if (cb) {
                    delete this.socketConnecting[fd];
                    cb(fd);
                } else {
                    //print('UNKNOWN POLLOUT');
                }
            }

            if ((rev & ~(POLLIN | POLLOUT)) !== 0) {
                //print('revents ' + t.revents + ' for fd ' + fd + ', closing forcibly');
                rc = Socket.close(fd);  // ignore result
                delete this.socketListening[fd];
                delete this.socketReading[fd];
            }
        }
    }
}

EventLoop.requestExit = function() {
    this.exitRequested = true;
}

EventLoop.server = function(address, port, cb_accepted) {
    var fd = Socket.createServerSocket(address, port);
    this.socketListening[fd] = cb_accepted;
}

EventLoop.connect = function(address, port, cb_connected) {
    var fd = Socket.connect(address, port);
    this.socketConnecting[fd] = cb_connected;
}

EventLoop.close = function(fd) {
    delete this.socketReading[fd];
    delete this.socketListening[fd];
}

EventLoop.setReader = function(fd, cb_read) {
    this.socketReading[fd] = cb_read;
}

EventLoop.write = function(fd, data) {
    // This simple example doesn't have support for write blocking / draining
    var rc = Socket.write(fd, Duktape.Buffer(data));
}

/*
 *  Timer API
 *
 *  These interface with the singleton EventLoop.
 */

function setTimeout(func, delay) {
    var cb_func;
    var bind_args;
    var timer_id;
    var evloop = EventLoop;

    if (typeof delay !== 'number') {
        throw new TypeError('delay is not a number');
    }
    delay = Math.max(evloop.minimumDelay, delay);

    if (typeof func === 'string') {
        // Legacy case: callback is a string.
        cb_func = eval.bind(this, func);
    } else if (typeof func !== 'function') {
        throw new TypeError('callback is not a function/string');
    } else if (arguments.length > 2) {
        // Special case: callback arguments are provided.
        bind_args = Array.prototype.slice.call(arguments, 2);  // [ arg1, arg2, ... ]
        bind_args.unshift(this);  // [ global(this), arg1, arg2, ... ]
        cb_func = func.bind.apply(func, bind_args);
    } else {
        // Normal case: callback given as a function without arguments.
        cb_func = func;
    }

    timer_id = evloop.nextTimerId++;

    evloop.insertTimer({
        id: timer_id,
        oneshot: true,
        cb: cb_func,
        delay: delay,
        target: Date.now() + delay
    });

    return timer_id;
}

function clearTimeout(timer_id) {
    var evloop = EventLoop;

    if (typeof timer_id !== 'number') {
        throw new TypeError('timer ID is not a number');
    }
    evloop.removeTimerById(timer_id);
}

function setInterval(func, delay) {
    var cb_func;
    var bind_args;
    var timer_id;
    var evloop = EventLoop;

    if (typeof delay !== 'number') {
        throw new TypeError('delay is not a number');
    }
    delay = Math.max(evloop.minimumDelay, delay);

    if (typeof func === 'string') {
        // Legacy case: callback is a string.
        cb_func = eval.bind(this, func);
    } else if (typeof func !== 'function') {
        throw new TypeError('callback is not a function/string');
    } else if (arguments.length > 2) {
        // Special case: callback arguments are provided.
        bind_args = Array.prototype.slice.call(arguments, 2);  // [ arg1, arg2, ... ]
        bind_args.unshift(this);  // [ global(this), arg1, arg2, ... ]
        cb_func = func.bind.apply(func, bind_args);
    } else {
        // Normal case: callback given as a function without arguments.
        cb_func = func;
    }

    timer_id = evloop.nextTimerId++;

    evloop.insertTimer({
        id: timer_id,
        oneshot: false,
        cb: cb_func,
        delay: delay,
        target: Date.now() + delay
    });

    return timer_id;
}

function clearInterval(timer_id) {
    var evloop = EventLoop;

    if (typeof timer_id !== 'number') {
        throw new TypeError('timer ID is not a number');
    }
    evloop.removeTimerById(timer_id);
}

/* custom call */
function requestEventLoopExit() {
    EventLoop.requestExit();
}