fix: resolve race conditions when refreshing access token #203
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
What kind of change does this PR introduce?
This fixes a race condition that arises when there are overlapping calls to
GoTrueApi.refreshAccessToken
. It does so by keeping reference to the result ofthis._callRefreshToken
until it is settled and returning it to the concurrent calls.What is the current behavior?
Concurrent token refreshes inevitably result in unrecoverable failure:
access_token
and revokedrefresh_token
Currently library code doesn't trigger such conditions unless tokens are short lived and network latency is high. User code will trigger it if it calls
refreshSession()
naively (e.g. when handling a 401 "token expired" error from several parallel requests).Currently to avoid this problem user code must implement similar kind of batching that I did here. But even then there is no clean way to avoid racing against the auto refresh timer apart from disabling it (which also disables the token recovery from local storage).
What is the new behavior?
If
this._callRefreshToken
is invoked while an earlier request is in-flight they will be settled with the same promise. Once the promise is settled the reference to it is deleted, so that future calls will initiate fresh requests.This fix is intended to be fully compatible with existing code (including potential access to private properties) and allows user code to handle expired tokens more reliably.