index.js
7.14 KB
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
'use strict';
/*
* cls-bluebird
* Module entry point
*/
// Modules
var isBluebird = require('is-bluebird');
// Require Bluebird library
// Ignore errors if cannot be required
var Bluebird;
try {
Bluebird = require('bluebird');
} catch (err) {}
// Imports
var shimMethod = require('./shimMethod'),
shimOnCancel = require('./shimOnCancel'),
shimCall = require('./shimCall'),
shimUsing = require('./shimUsing'),
shimCoroutine = require('./shimCoroutine');
// Exports
/**
* Patch bluebird to run maintain CLS context for a specific namespace.
* If a Bluebird Promise constructor is provided, it is patched.
* If not provided, the version returned by `require('bluebird')` is used.
*
* @param {Object} ns - CLS namespace object
* @param {Function} [Promise] - Bluebird Promise constructor to patch (optional)
* @returns {Function} - Bluebird Promise constructor
* @throws {TypeError} - If `ns` or `Promise` are not of correct type
* @throws {Error} - If `Promise` not provided and cannot require `bluebird` module
*/
module.exports = function patchBluebird(ns, Promise) {
// Check namespace is valid
if (!ns || typeof ns !== 'object' || typeof ns.bind !== 'function' || typeof ns.run !== 'function') throw new TypeError('Must provide CLS namespace to patch Bluebird against');
// Check Promise implementation is some variation of Bluebird
// If none provided, use default Bluebird
if (!Promise) {
Promise = Bluebird;
if (!Promise) throw new Error('Could not require Bluebird');
} else if (!isBluebird.ctor(Promise)) {
throw new TypeError('Promise implementation provided must be Bluebird');
}
// Patch all methods to carry CLS context
var v3 = isBluebird.ctor.v3(Promise);
/*
* Core
*
* Not patched as always run callback synchronously:
* new Promise()
* Promise.try() / Promise.attempt()
*
* Not patched as do not take a callback:
* Promise.bind() / .bind()
* Promise.resolve() / Promise.fulfilled() / Promise.cast()
* Promise.reject() / Promise.rejected()
*
* Not patched as call another patched method synchronously
* .error() - calls .catch()
*
* Not patched as are wrappers:
* Promise.method()
*
* NB Due to bug in bluebird v2 https://github.com/petkaantonov/bluebird/issues/1153
* `Promise.join()` calls the callback synchronously if input is only values or
* resolved promises, but async if any promises are pending.
* So handler is sometimes bound to CLS context unnecessarily, but this does no harm
* beyond the very slight performance overhead of an extra `ns.bind()` call.
*/
shimProto('then', v3 ? [0, 1] : [0, 1, 2]);
shimProto('spread', v3 ? [0] : [0, 1]);
shimProto('finally', [0]);
Promise.prototype.lastly = Promise.prototype.finally;
shimStatic('join', [-1]);
if (!v3) {
// Only patched in bluebird v2.
// In bluebird v3 `.catch()` calls `.then()` immediately which binds callback.
shimProto('catch', [-1]);
Promise.prototype.caught = Promise.prototype.catch;
}
/*
* Synchronous inspection
*
* Not patched as do not take a callback:
* .isFulfilled()
* .isRejected()
* .isPending()
* .isCancelled()
* .isResolved()
* .value()
* .reason()
* .reflect()
*/
/*
* Collections
*
* Not patched as do not take a callback:
* Promise.all() / .all()
* Promise.props() / .props()
* Promise.any() / .any()
* Promise.some() / .some()
* Promise.race() / .race()
*/
shimBoth('map', [0]);
shimBoth('filter', [0]);
shimBoth('reduce', [0]);
shimBoth('each', [0]);
// In bluebird v2, there is no `Promise.mapSeries()`/`.mapSeries()` method
if (v3) shimBoth('mapSeries', [0]);
/*
* Resource management
*
* NB disposer callbacks are bound to context at time disposer created, not when utilized in `using()`
*/
shimUsing(Promise, ns, v3); // shims `Promise.using()`
shimProto('disposer', [0]);
/*
* Promisification
*
* Not patched as always run callback synchronously:
* Promise.fromCallback()
* Promise.fromNode()
*
* Not patched as they are wrappers:
* Promise.promisify()
* Promise.promisifyAll()
*/
shimProto('asCallback', [0]);
Promise.prototype.nodeify = Promise.prototype.asCallback;
/*
* Timers
*
* Not patched as do not take a callback:
* Promise.delay() / .delay()
* .timeout()
*/
/*
* Cancellation
*
* Not patched as does not take a callback:
* .cancel() / .break()
* .isCancellable()
* .cancellable() (bluebird v2 only)
* .uncancellable() (bluebird v2 only)
*
* NB In bluebird v3 `onCancel` handler will be called
* in CLS context of call to `onCancel()`.
*/
// Patch `Promise.prototype._resolveFromExecutor`
// in order to patch `onCancel` handler in `new Promise()`.
if (v3) shimOnCancel(Promise, ns);
/*
* Generators
*
* Not patched as does not take a callback:
* Promise.coroutine.addYieldHandler()
*
* NB `options.yieldHandler` will run in whatever CLS context is active at time of `yield`
*/
var addYieldHandler = Promise.coroutine.addYieldHandler;
shimCoroutine('coroutine', Promise, ns, v3); // shims `Promise.coroutine()`
Promise.coroutine.addYieldHandler = addYieldHandler;
/*
* Utility
*
* Not patched as do not take a callback:
* .get()
* .return() / .thenReturn()
* .throw() / .thenThrow()
* .catchReturn()
* .catchThrow()
* Promise.getNewLibraryCopy()
* Promise.noConflict()
* Promise.setScheduler()
*/
shimProto('tap', [0]);
if (v3) shimProto('tapCatch', [-1]);
shimCall(Promise, ns); // shims `.call()`
/*
* Configuration
*
* Not patched as do not take a callback:
* Promise.config()
* .suppressUnhandledRejections()
* Promise.longStackTraces()
* Promise.hasLongStackTraces()
*
* Not patched as meaningless to do so:
* Promise.onPossiblyUnhandledRejection()
* Promise.onUnhandledRejectionHandled()
*
* NB Error handlers will run with unknown CLS context.
* CLS context should not be relied upon to be the context at the time error was thrown.
* Catch errors with `.catch()` instead!
*/
shimProto('done', v3 ? [0, 1] : [0, 1, 2]);
/*
* Progression (bluebird v2 only)
*/
if (!v3) shimProto('progressed', [0]);
/*
* Undocumented
*
* Not patched as do not take a callback:
* Promise.is()
* Promise.settle() / .settle()
* Promise.defer() / Promise.pending()
* .toString()
* .toJSON()
*/
// `.fork()` does not exist in bluebird v3
if (!v3) shimProto('fork', [0, 1, 2]);
shimCoroutine('spawn', Promise, ns, v3); // shims `Promise.spawn()`
// Return patched Bluebird constructor
return Promise;
/*
* Patching functions
*/
function shimStatic(methodName, args) {
shimMethod(Promise, methodName, args, ns);
}
function shimProto(methodName, args) {
shimMethod(Promise.prototype, methodName, args, ns);
}
function shimBoth(methodName, args) {
shimProto(methodName, args);
shimStatic(methodName, args.map(function(arg) { return arg < 0 ? arg : arg + 1; }));
}
};