Skip to content

Commit

Permalink
Prevent fetching the user agent concurrently (#1205)
Browse files Browse the repository at this point in the history
  • Loading branch information
richardm-stripe authored Jul 28, 2021
1 parent 93ce450 commit 65176f1
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 13 deletions.
31 changes: 18 additions & 13 deletions lib/stripe.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,8 @@ Stripe.USER_AGENT = {
typescript: false,
};

Stripe.USER_AGENT_SERIALIZED = null;
/** @private */
Stripe._UNAME_CACHE = null;

const MAX_NETWORK_RETRY_DELAY_SEC = 2;
const INITIAL_NETWORK_RETRY_DELAY_SEC = 0.5;
Expand Down Expand Up @@ -102,7 +103,6 @@ function Stripe(key, config = {}) {
// serializing the user agent involves shelling out to the system,
// and given some users may instantiate the library many times without switching between TS and non-TS,
// we only want to incur the performance hit when that actually happens.
Stripe.USER_AGENT_SERIALIZED = null;
Stripe.USER_AGENT.typescript = typescript;
}

Expand Down Expand Up @@ -286,9 +286,6 @@ Stripe.prototype = {
return accum;
}, undefined);

// Kill the cached UA string because it may no longer be valid
Stripe.USER_AGENT_SERIALIZED = undefined;

this._appInfo = appInfo;
},

Expand Down Expand Up @@ -396,6 +393,20 @@ Stripe.prototype = {
return INITIAL_NETWORK_RETRY_DELAY_SEC;
},

/**
* @private
*/
getUname(cb) {
if (!Stripe._UNAME_CACHE) {
Stripe._UNAME_CACHE = new Promise((resolve) => {
utils.safeExec('uname -a', (err, uname) => {
resolve(uname);
});
});
}
Stripe._UNAME_CACHE.then((uname) => cb(uname));
},

/**
* @private
* Please open or upvote an issue at github.com/stripe/stripe-node
Expand All @@ -407,13 +418,7 @@ Stripe.prototype = {
* speed advantage.
*/
getClientUserAgent(cb) {
if (Stripe.USER_AGENT_SERIALIZED) {
return cb(Stripe.USER_AGENT_SERIALIZED);
}
this.getClientUserAgentSeeded(Stripe.USER_AGENT, (cua) => {
Stripe.USER_AGENT_SERIALIZED = cua;
cb(Stripe.USER_AGENT_SERIALIZED);
});
return this.getClientUserAgentSeeded(Stripe.USER_AGENT, cb);
},

/**
Expand All @@ -427,7 +432,7 @@ Stripe.prototype = {
* fetching a uname from the system.
*/
getClientUserAgentSeeded(seed, cb) {
utils.safeExec('uname -a', (err, uname) => {
this.getUname((uname) => {
const userAgent = {};
for (const field in seed) {
userAgent[field] = encodeURIComponent(seed[field]);
Expand Down
3 changes: 3 additions & 0 deletions test/stripe.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,9 @@ describe('Stripe Module', function() {

describe('uname', () => {
let origExec;
beforeEach(() => {
Stripe._UNAME_CACHE = null;
});
beforeEach(() => {
origExec = utils.safeExec;
});
Expand Down

0 comments on commit 65176f1

Please sign in to comment.