This repository has been archived by the owner on Dec 5, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
AsyncWriter.js
507 lines (432 loc) · 14.1 KB
/
AsyncWriter.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
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
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
/*
* Copyright 2011 eBay Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
function StringWriter(events) {
this.str = '';
this.events = events;
this.finished = false;
}
StringWriter.prototype = {
end: function() {
this.finished = true;
if (this.events) {
this.events.emit('finish');
}
},
write: function(str) {
this.str += str;
return this;
},
/**
* Converts the string buffer into a String.
*
* @returns {String} The built String
*/
toString: function() {
return this.str;
}
};
/**
* Simple wrapper that can be used to wrap a stream
* to reduce the number of write calls. In Node.js world,
* each stream.write() becomes a chunk. We can avoid overhead
* by reducing the number of chunks by buffering the output.
*/
function BufferedWriter(wrappedStream) {
this._buffer = '';
this._wrapped = wrappedStream;
}
BufferedWriter.prototype = {
write: function(str) {
this._buffer += str;
},
flush: function() {
if (this._buffer.length !== 0) {
this._wrapped.write(this._buffer);
this._buffer = '';
if (this._wrapped.flush) {
this._wrapped.flush();
}
}
},
end: function() {
this.flush();
if(!this._wrapped.isTTY) {
this._wrapped.end();
}
},
on: function(event, callback) {
return this._wrapped.on(event, callback);
},
once: function(event, callback) {
return this._wrapped.once(event, callback);
},
clear: function() {
this._buffer = '';
}
};
var EventEmitter = require('events').EventEmitter;
var includeStack = typeof process !== 'undefined' && process.env.NODE_ENV === 'development';
var voidWriter = {
write: function() {}
};
function Fragment(asyncWriter) {
this.asyncWriter = asyncWriter;
// The asyncWriter that this async fragment is associated with
this.writer = asyncWriter.writer;
// The original writer this fragment was associated with
this.finished = false;
// Used to keep track if this async fragment was ended
this.flushed = false;
// Set to true when the contents of this async fragment have been
// flushed to the original writer
this.next = null;
// A link to the next sibling async fragment (if any)
this.ready = true; // Will be set to true if this fragment is ready to be flushed
// (i.e. when there are no async fragments preceeding this fragment)
}
function flushNext(fragment, writer) {
var next = fragment.next;
if (next) {
next.ready = true;
// Since we have flushed the next fragment is ready
next.writer = next.asyncWriter.writer = writer;
// Update the next fragment to use the original writer
next.flush(); // Now flush the next fragment (if it is not finish then it will just do nothing)
}
}
function BufferedFragment(asyncWriter, buffer) {
Fragment.call(this, asyncWriter);
this.buffer = buffer;
}
BufferedFragment.prototype = {
flush: function () {
var writer = this.writer;
var bufferedString = this.buffer.toString();
if (bufferedString.length !== 0) {
writer.write(bufferedString);
}
this.flushed = true;
flushNext(this, writer);
}
};
function AsyncFragment(asyncWriter) {
Fragment.call(this, asyncWriter);
}
AsyncFragment.prototype = {
end: function () {
if (!this.finished) {
// Make sure end is only called once by the user
this.finished = true;
if (this.ready) {
// There are no nested asynchronous fragments that are
// remaining and we are ready to be flushed then let's do it!
this.flush();
}
}
},
flush: function () {
if (!this.finished) {
// Skipped Flushing since not finished
return;
}
this.flushed = true;
var writer = this.writer;
this.writer = this.asyncWriter.writer = voidWriter; // Prevent additional out-of-order writes
flushNext(this, writer);
}
};
function AsyncWriter(writer, global, async, buffer) {
this.data = {};
this.global = this.attributes /* legacy */ = (global || (global = {}));
this._af = this._prevAF = this._parentAF = null;
this._isSync = false;
this._last = null;
if (!global.events) {
// Use the underlying stream as the event emitter if available.
// Otherwise, create a new event emitter
global.events = writer && writer.on ? writer : new EventEmitter();
}
this._events = global.events;
if (async) {
this._async = async;
} else {
this._async = global.async || (global.async = {
remaining: 0,
ended: false,
last: 0,
finished: false
});
}
var stream;
if (!writer) {
writer = new StringWriter(this._events);
} else if (buffer) {
stream = writer;
writer = new BufferedWriter(writer);
}
this.stream = stream || writer;
this.writer = this._stream = writer;
}
AsyncWriter.DEFAULT_TIMEOUT = 10000;
AsyncWriter.prototype = {
constructor: AsyncWriter,
isAsyncWriter: AsyncWriter,
sync: function() {
this._isSync = true;
},
getAttributes: function () {
return this.global;
},
getAttribute: function (name) {
return this.global[name];
},
write: function (str) {
if (str != null) {
this.writer.write(str.toString());
}
return this;
},
getOutput: function () {
return this.writer.toString();
},
captureString: function (func, thisObj) {
var sb = new StringWriter();
this.swapWriter(sb, func, thisObj);
return sb.toString();
},
swapWriter: function (newWriter, func, thisObj) {
var oldWriter = this.writer;
this.writer = newWriter;
func.call(thisObj);
this.writer = oldWriter;
},
createNestedWriter: function (writer) {
var _this = this;
var child = new AsyncWriter(writer, _this.global);
// Keep a reference to the original stream. This was done because when
// rendering to a response stream we can get access to the request/response
// to figure out the locale and other information associated with the
// client. Without this we would have to rely on the request being
// passed around everywhere or rely on something like continuation-local-storage
// which has shown to be unreliable in some situations.
child._stream = _this._stream; // This is the original stream or the stream wrapped with a BufferedWriter
child.stream = _this.stream; // HACK: This is the user assigned stream and not the stream
// that was wrapped with a BufferedWriter.
return child;
},
beginAsync: function (options) {
if (this._isSync) {
throw new Error('beginAsync() not allowed when using renderSync()');
}
var ready = true;
// Create a new asyncWriter that the async fragment can write to.
// The new async asyncWriter will use the existing writer and
// the writer for the current asyncWriter (which will continue to be used)
// will be replaced with a string buffer writer
var asyncOut = this.createNestedWriter(this.writer);
var buffer = this.writer = new StringWriter();
var asyncFragment = new AsyncFragment(asyncOut);
var bufferedFragment = new BufferedFragment(this, buffer);
asyncFragment.next = bufferedFragment;
asyncOut._af = asyncFragment;
asyncOut._parentAF = asyncFragment;
var prevAsyncFragment = this._prevAF || this._parentAF;
// See if we are being buffered by a previous asynchronous
// fragment
if (prevAsyncFragment) {
// Splice in our two new fragments and add a link to the previous async fragment
// so that it can let us know when we are ready to be flushed
bufferedFragment.next = prevAsyncFragment.next;
prevAsyncFragment.next = asyncFragment;
if (!prevAsyncFragment.flushed) {
ready = false; // If we are preceeded by another async fragment then we aren't ready to be flushed
}
}
asyncFragment.ready = ready;
// Set the ready flag based on our earlier checks above
this._prevAF = bufferedFragment;
// Record the previous async fragment for linking purposes
asyncOut.handleBeginAsync(options, this);
return asyncOut;
},
handleBeginAsync: function(options, parent) {
var _this = this;
var async = _this._async;
var timeout;
var name;
async.remaining++;
if (options != null) {
if (typeof options === 'number') {
timeout = options;
} else {
timeout = options.timeout;
if (options.last === true) {
if (timeout == null) {
// Don't assign a timeout to last flush fragments
// unless it is explicitly given a timeout
timeout = 0;
}
async.last++;
}
name = options.name;
}
}
if (timeout == null) {
timeout = AsyncWriter.DEFAULT_TIMEOUT;
}
_this.stack = includeStack ? new Error().stack : null;
_this.name = name;
if (timeout > 0) {
_this._timeoutId = setTimeout(function() {
_this.error(new Error('Async fragment ' + (name ? '(' + name + ') ': '') + 'timed out after ' + timeout + 'ms'));
}, timeout);
}
this._events.emit('beginAsync', {
writer: this,
parentWriter: parent
});
},
on: function(event, callback) {
if (event === 'finish' && this.writer.finished) {
callback();
return this;
}
this._events.on(event, callback);
return this;
},
once: function(event, callback) {
if (event === 'finish' && this.writer.finished) {
callback();
return this;
}
this._events.once(event, callback);
return this;
},
onLast: function(callback) {
var lastArray = this._last;
if (!lastArray) {
lastArray = this._last = [];
var i = 0;
var next = function next() {
if (i === lastArray.length) {
return;
}
var _next = lastArray[i++];
_next(next);
};
this.once('last', function() {
next();
});
}
lastArray.push(callback);
},
emit: function(arg) {
var events = this._events;
switch(arguments.length) {
case 0:
events.emit();
break;
case 1:
events.emit(arg);
break;
default:
events.emit.apply(events, arguments);
break;
}
return this;
},
removeListener: function() {
var events = this._events;
events.removeListener.apply(events, arguments);
return this;
},
pipe: function(stream) {
this._stream.pipe(stream);
return this;
},
error: function(e) {
try {
var stack = this.stack;
var name = this.name;
e = new Error('Async fragment failed' + (name ? ' (' + name + ')': '') + '. Exception: ' + (e.stack || e) + (stack ? ('\nCreation stack trace: ' + stack) : ''));
this.emit('error', e);
} finally {
this.end();
}
},
end: function(data) {
if (data) {
this.write(data);
}
var asyncFragment = this._af;
if (asyncFragment) {
asyncFragment.end();
this.handleEnd(true);
} else {
this.handleEnd(false);
}
return this;
},
handleEnd: function(isAsync) {
var async = this._async;
if (async.finished) {
return;
}
var remaining;
if (isAsync) {
var timeoutId = this._timeoutId;
if (timeoutId) {
clearTimeout(timeoutId);
}
remaining = --async.remaining;
} else {
remaining = async.remaining;
async.ended = true;
}
if (async.ended) {
if (!async.lastFired && async.remaining - async.last === 0) {
async.lastFired = true;
async.last = 0;
this._events.emit('last');
}
if (remaining === 0) {
async.finished = true;
this._finish();
}
}
},
_finish: function() {
if (this._stream.end) {
this._stream.end();
} else {
this._events.emit('finish');
}
},
flush: function() {
if (!this._async.finished) {
var stream = this._stream;
if (stream && stream.flush) {
stream.flush();
}
}
}
};
AsyncWriter.prototype.w = AsyncWriter.prototype.write;
AsyncWriter.enableAsyncStackTrace = function() {
includeStack = true;
};
module.exports = AsyncWriter;