-
Notifications
You must be signed in to change notification settings - Fork 781
/
Copy pathStripeResource.js
450 lines (374 loc) · 13 KB
/
StripeResource.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
'use strict';
const http = require('http');
const https = require('https');
const path = require('path');
const uuid = require('uuid/v4');
const utils = require('./utils');
const Error = require('./Error');
const defaultHttpAgent = new http.Agent({keepAlive: true});
const defaultHttpsAgent = new https.Agent({keepAlive: true});
// Provide extension mechanism for Stripe Resource Sub-Classes
StripeResource.extend = utils.protoExtend;
// Expose method-creator & prepared (basic) methods
StripeResource.method = require('./StripeMethod');
StripeResource.BASIC_METHODS = require('./StripeMethod.basic');
StripeResource.MAX_BUFFERED_REQUEST_METRICS = 100;
/**
* Encapsulates request logic for a Stripe Resource
*/
function StripeResource(stripe, deprecatedUrlData) {
this._stripe = stripe;
if (deprecatedUrlData) {
throw new Error(
'Support for curried url params was dropped in stripe-node v7.0.0. Instead, pass two ids.'
);
}
this.basePath = utils.makeURLInterpolator(
this.basePath || stripe.getApiField('basePath')
);
this.resourcePath = this.path;
this.path = utils.makeURLInterpolator(this.path);
if (this.includeBasic) {
this.includeBasic.forEach(function(methodName) {
this[methodName] = StripeResource.BASIC_METHODS[methodName];
}, this);
}
this.initialize(...arguments);
}
StripeResource.prototype = {
path: '',
// Methods that don't use the API's default '/v1' path can override it with this setting.
basePath: null,
initialize() {},
// Function to override the default data processor. This allows full control
// over how a StripeResource's request data will get converted into an HTTP
// body. This is useful for non-standard HTTP requests. The function should
// take method name, data, and headers as arguments.
requestDataProcessor: null,
// Function to add a validation checks before sending the request, errors should
// be thrown, and they will be passed to the callback/promise.
validateRequest: null,
createFullPath(commandPath, urlData) {
return path
.join(
this.basePath(urlData),
this.path(urlData),
typeof commandPath == 'function' ? commandPath(urlData) : commandPath
)
.replace(/\\/g, '/'); // ugly workaround for Windows
},
// Creates a relative resource path with symbols left in (unlike
// createFullPath which takes some data to replace them with). For example it
// might produce: /invoices/{id}
createResourcePathWithSymbols(pathWithSymbols) {
return `/${path
.join(this.resourcePath, pathWithSymbols || '')
.replace(/\\/g, '/')}`; // ugly workaround for Windows
},
// DEPRECATED: Here for backcompat in case users relied on this.
wrapTimeout: utils.callbackifyPromiseWithTimeout,
_timeoutHandler(timeout, req, callback) {
return () => {
const timeoutErr = new Error('ETIMEDOUT');
timeoutErr.code = 'ETIMEDOUT';
req._isAborted = true;
req.abort();
callback.call(
this,
new Error.StripeConnectionError({
message: `Request aborted due to timeout being reached (${timeout}ms)`,
detail: timeoutErr,
}),
null
);
};
},
_responseHandler(req, callback) {
return (res) => {
let response = '';
res.setEncoding('utf8');
res.on('data', (chunk) => {
response += chunk;
});
res.on('end', () => {
const headers = res.headers || {};
// NOTE: Stripe responds with lowercase header names/keys.
// For convenience, make Request-Id easily accessible on
// lastResponse.
res.requestId = headers['request-id'];
const requestDurationMs = Date.now() - req._requestStart;
const responseEvent = utils.removeEmpty({
api_version: headers['stripe-version'],
account: headers['stripe-account'],
idempotency_key: headers['idempotency-key'],
method: req._requestEvent.method,
path: req._requestEvent.path,
status: res.statusCode,
request_id: res.requestId,
elapsed: requestDurationMs,
});
this._stripe._emitter.emit('response', responseEvent);
try {
response = JSON.parse(response);
if (response.error) {
let err;
// Convert OAuth error responses into a standard format
// so that the rest of the error logic can be shared
if (typeof response.error === 'string') {
response.error = {
type: response.error,
message: response.error_description,
};
}
response.error.headers = headers;
response.error.statusCode = res.statusCode;
response.error.requestId = res.requestId;
if (res.statusCode === 401) {
err = new Error.StripeAuthenticationError(response.error);
} else if (res.statusCode === 403) {
err = new Error.StripePermissionError(response.error);
} else if (res.statusCode === 429) {
err = new Error.StripeRateLimitError(response.error);
} else {
err = Error.StripeError.generate(response.error);
}
return callback.call(this, err, null);
}
} catch (e) {
return callback.call(
this,
new Error.StripeAPIError({
message: 'Invalid JSON received from the Stripe API',
response,
exception: e,
requestId: headers['request-id'],
}),
null
);
}
this._recordRequestMetrics(res.requestId, requestDurationMs);
// Expose res object
Object.defineProperty(response, 'lastResponse', {
enumerable: false,
writable: false,
value: res,
});
callback.call(this, null, response);
});
};
},
_generateConnectionErrorMessage(requestRetries) {
return `An error occurred with our connection to Stripe.${
requestRetries > 0 ? ` Request was retried ${requestRetries} times.` : ''
}`;
},
_errorHandler(req, requestRetries, callback) {
return (error) => {
if (req._isAborted) {
// already handled
return;
}
callback.call(
this,
new Error.StripeConnectionError({
message: this._generateConnectionErrorMessage(requestRetries),
detail: error,
}),
null
);
};
},
_shouldRetry(res, numRetries) {
// Do not retry if we are out of retries.
if (numRetries >= this._stripe.getMaxNetworkRetries()) {
return false;
}
// Retry on connection error.
if (!res) {
return true;
}
// Retry on conflict and availability errors.
if (res.statusCode === 409 || res.statusCode === 503) {
return true;
}
// Retry on 5xx's, except POST's, which our idempotency framework
// would just replay as 500's again anyway.
if (res.statusCode >= 500 && res.req._requestEvent.method !== 'POST') {
return true;
}
return false;
},
_getSleepTimeInMS(numRetries) {
const initialNetworkRetryDelay = this._stripe.getInitialNetworkRetryDelay();
const maxNetworkRetryDelay = this._stripe.getMaxNetworkRetryDelay();
// Apply exponential backoff with initialNetworkRetryDelay on the
// number of numRetries so far as inputs. Do not allow the number to exceed
// maxNetworkRetryDelay.
let sleepSeconds = Math.min(
initialNetworkRetryDelay * Math.pow(numRetries - 1, 2),
maxNetworkRetryDelay
);
// Apply some jitter by randomizing the value in the range of
// (sleepSeconds / 2) to (sleepSeconds).
sleepSeconds *= 0.5 * (1 + Math.random());
// But never sleep less than the base sleep seconds.
sleepSeconds = Math.max(initialNetworkRetryDelay, sleepSeconds);
return sleepSeconds * 1000;
},
_defaultHeaders(auth, contentLength, apiVersion) {
let userAgentString = `Stripe/v1 NodeBindings/${this._stripe.getConstant(
'PACKAGE_VERSION'
)}`;
if (this._stripe._appInfo) {
userAgentString += ` ${this._stripe.getAppInfoAsString()}`;
}
const headers = {
// Use specified auth token or use default from this stripe instance:
Authorization: auth ? `Bearer ${auth}` : this._stripe.getApiField('auth'),
Accept: 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': contentLength,
'User-Agent': userAgentString,
};
if (apiVersion) {
headers['Stripe-Version'] = apiVersion;
}
return headers;
},
_addTelemetryHeader(headers) {
if (
this._stripe.getTelemetryEnabled() &&
this._stripe._prevRequestMetrics.length > 0
) {
const metrics = this._stripe._prevRequestMetrics.shift();
headers['X-Stripe-Client-Telemetry'] = JSON.stringify({
last_request_metrics: metrics,
});
}
},
_recordRequestMetrics(requestId, requestDurationMs) {
if (this._stripe.getTelemetryEnabled() && requestId) {
if (
this._stripe._prevRequestMetrics.length >
StripeResource.MAX_BUFFERED_REQUEST_METRICS
) {
utils.emitWarning(
'Request metrics buffer is full, dropping telemetry message.'
);
} else {
this._stripe._prevRequestMetrics.push({
request_id: requestId,
request_duration_ms: requestDurationMs,
});
}
}
},
_request(method, host, path, data, auth, options, callback) {
let requestData;
const makeRequest = (apiVersion, headers, numRetries) => {
const timeout = this._stripe.getApiField('timeout');
const isInsecureConnection =
this._stripe.getApiField('protocol') == 'http';
let agent = this._stripe.getApiField('agent');
if (agent == null) {
agent = isInsecureConnection ? defaultHttpAgent : defaultHttpsAgent;
}
const req = (isInsecureConnection ? http : https).request({
host: host || this._stripe.getApiField('host'),
port: this._stripe.getApiField('port'),
path,
method,
agent,
headers,
ciphers: 'DEFAULT:!aNULL:!eNULL:!LOW:!EXPORT:!SSLv2:!MD5',
});
// If this is a POST and we allow multiple retries, set a idempotency key if one is not
// already provided.
if (method === 'POST' && this._stripe.getMaxNetworkRetries() > 0) {
if (!headers.hasOwnProperty('Idempotency-Key')) {
headers['Idempotency-Key'] = uuid();
}
}
const requestEvent = utils.removeEmpty({
api_version: apiVersion,
account: headers['Stripe-Account'],
idempotency_key: headers['Idempotency-Key'],
method,
path,
});
const requestRetries = numRetries || 0;
req._requestEvent = requestEvent;
req._requestStart = Date.now();
this._stripe._emitter.emit('request', requestEvent);
req.setTimeout(timeout, this._timeoutHandler(timeout, req, callback));
req.on('response', (res) => {
if (this._shouldRetry(res, requestRetries)) {
return retryRequest(makeRequest, apiVersion, headers, requestRetries);
} else {
return this._responseHandler(req, callback)(res);
}
});
req.on('error', (error) => {
if (this._shouldRetry(null, requestRetries)) {
return retryRequest(makeRequest, apiVersion, headers, requestRetries);
} else {
return this._errorHandler(req, requestRetries, callback)(error);
}
});
req.on('socket', (socket) => {
if (socket.connecting) {
socket.on(isInsecureConnection ? 'connect' : 'secureConnect', () => {
// Send payload; we're safe:
req.write(requestData);
req.end();
});
} else {
// we're already connected
req.write(requestData);
req.end();
}
});
};
const makeRequestWithData = (error, data) => {
if (error) {
return callback(error);
}
const apiVersion = this._stripe.getApiField('version');
requestData = data;
const headers = this._defaultHeaders(
auth,
requestData.length,
apiVersion
);
this._stripe.getClientUserAgent((cua) => {
headers['X-Stripe-Client-User-Agent'] = cua;
if (options.headers) {
Object.assign(headers, options.headers);
}
this._addTelemetryHeader(headers);
makeRequest(apiVersion, headers);
});
};
if (this.requestDataProcessor) {
this.requestDataProcessor(
method,
data,
options.headers,
makeRequestWithData
);
} else {
makeRequestWithData(null, utils.stringifyRequestData(data || {}));
}
const retryRequest = (requestFn, apiVersion, headers, requestRetries) => {
requestRetries += 1;
return setTimeout(
requestFn,
this._getSleepTimeInMS(requestRetries),
apiVersion,
headers,
requestRetries
);
};
},
};
module.exports = StripeResource;