Skip to content

Commit

Permalink
Iterate
Browse files Browse the repository at this point in the history
Signed-off-by: Michael Telatynski <7t3chguy@gmail.com>
  • Loading branch information
t3chguy committed Feb 27, 2025
1 parent 0e689d0 commit a614183
Showing 1 changed file with 14 additions and 1 deletion.
15 changes: 14 additions & 1 deletion src/http-api/fetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,12 @@ export class FetchHttpApi<O extends IHttpOpts> {
return this.requestOtherUrl(method, fullUri, body, opts);
}

/**
* Promise used to block authenticated requests during a token refresh to avoid repeated expected errors.
* @private
*/
private tokenRefreshPromise?: Promise<unknown>;

/**
* Perform an authorised request to the homeserver.
* @param method - The HTTP method e.g. "GET".
Expand Down Expand Up @@ -163,21 +169,28 @@ export class FetchHttpApi<O extends IHttpOpts> {
}

try {
// Await any ongoing token refresh
await this.tokenRefreshPromise;
const response = await this.request<T>(method, path, queryParams, body, opts);
return response;
} catch (error) {
const err = error as MatrixError;

if (err.errcode === "M_UNKNOWN_TOKEN" && !opts.doNotAttemptTokenRefresh) {
const shouldRetry = await this.tryRefreshToken();
const tokenRefreshPromise = this.tryRefreshToken();
this.tokenRefreshPromise = Promise.allSettled([tokenRefreshPromise]);
const shouldRetry = await tokenRefreshPromise;
// if we got a new token retry the request
if (shouldRetry) {
return this.authedRequest(method, path, queryParams, body, {
...paramOpts,
doNotAttemptTokenRefresh: true,
});
}

throw err;
}

// otherwise continue with error handling
if (err.errcode == "M_UNKNOWN_TOKEN" && !opts?.inhibitLogoutEmit) {
this.eventEmitter.emit(HttpApiEvent.SessionLoggedOut, err);
Expand Down

0 comments on commit a614183

Please sign in to comment.