File tree 2 files changed +42
-1
lines changed
2 files changed +42
-1
lines changed Original file line number Diff line number Diff line change @@ -187,6 +187,10 @@ export class GoogleAuth<T extends AuthClient = JSONClient> {
187
187
apiKey : string | null ;
188
188
189
189
cachedCredential : AnyAuthClient | T | null = null ;
190
+ /**
191
+ * A pending {@link AuthClient}. Used for concurrent {@link GoogleAuth.getClient} calls.
192
+ */
193
+ #pendingAuthClient: Promise < AnyAuthClient | T > | null = null ;
190
194
191
195
/**
192
196
* Scopes populated by the client library by default. We differentiate between
@@ -1007,7 +1011,22 @@ export class GoogleAuth<T extends AuthClient = JSONClient> {
1007
1011
async getClient ( ) : Promise < AnyAuthClient | T > {
1008
1012
if ( this . cachedCredential ) {
1009
1013
return this . cachedCredential ;
1010
- } else if ( this . jsonContent ) {
1014
+ }
1015
+
1016
+ // Use an existing auth client request, or cache a new one
1017
+ this . #pendingAuthClient =
1018
+ this . #pendingAuthClient || this . #determineClient( ) ;
1019
+
1020
+ try {
1021
+ return await this . #pendingAuthClient;
1022
+ } finally {
1023
+ // reset the pending auth client in case it is changed later
1024
+ this . #pendingAuthClient = null ;
1025
+ }
1026
+ }
1027
+
1028
+ async #determineClient( ) {
1029
+ if ( this . jsonContent ) {
1011
1030
return this . _cacheClientFromJSON ( this . jsonContent , this . clientOptions ) ;
1012
1031
} else if ( this . keyFilename ) {
1013
1032
const filePath = path . resolve ( this . keyFilename ) ;
Original file line number Diff line number Diff line change @@ -2617,6 +2617,28 @@ describe('googleauth', () => {
2617
2617
2618
2618
assert ( actualClient instanceof ExternalAccountAuthorizedUserClient ) ;
2619
2619
} ) ;
2620
+
2621
+ it ( 'should return the same instance for concurrent requests' , async ( ) => {
2622
+ // Set up a mock to return path to a valid credentials file.
2623
+ mockEnvVar (
2624
+ 'GOOGLE_APPLICATION_CREDENTIALS' ,
2625
+ './test/fixtures/external-account-authorized-user-cred.json'
2626
+ ) ;
2627
+ const auth = new GoogleAuth ( ) ;
2628
+
2629
+ let client : AuthClient | null = null ;
2630
+ const getClientCalls = await Promise . all ( [
2631
+ auth . getClient ( ) ,
2632
+ auth . getClient ( ) ,
2633
+ auth . getClient ( ) ,
2634
+ ] ) ;
2635
+
2636
+ for ( const resClient of getClientCalls ) {
2637
+ if ( ! client ) client = resClient ;
2638
+
2639
+ assert ( client === resClient ) ;
2640
+ }
2641
+ } ) ;
2620
2642
} ) ;
2621
2643
2622
2644
describe ( 'sign()' , ( ) => {
You can’t perform that action at this time.
0 commit comments