Proposal: Retry After Token Refresh
Preview of retryFailed() for @blac/async, replacing an app-wide token-refresh event that reloads every failed container.
Problem
A common way to recover from an expired token is an app-wide event:
- A session container refreshes the access token, then dispatches a
token-refreshedevent. - Every data container listens. If it is in an error state and remembers its last parameters, it reloads.
Each data container stores its last parameters just for this, and the retry works for keepAlive instances with no owners.
There are two kinds of refresh, and only one needs the library:
- On demand (
401→ refresh → retry). This belongs in the fetch layer, because every request needs it. A typical client already queues concurrent401s behind one refresh and retries each request once. The production codebase behind these proposals does this, so the earlier idea of aretryOnrecipe is dropped, andretryOnitself has been removed. A request that still fails after the refresh rejects like any other error. - Scheduled (a timer refreshes the token before it expires). Requests that failed in the meantime, for example while the device was offline or the old token was rejected, stay failed. Nothing retries them, which is what the event above is for.
invalidate(tag) reloads errored resources, but only those that declared a tag, and the caller must know the tags. So the event has no replacement for “a refresh just succeeded, reload everything that failed”.
Proposal
retryFailed(registry?) (new API)
import { retryFailed } from '@blac/async';
retryFailed(); // global registryretryFailed(registry); // a RegistryProvider scopeRe-runs every resource in the error state:
- An active resource reloads now.
- An inactive one (for example
keepAlivewith no owners) is marked stale and loads on its next activation. This is the same ruleinvalidatefollows. - Resources that are
idle,loadingorsuccessare untouched, and mutations are never retried, since replaying a side effect is unsafe.
It needs a per-registry set of every resource, next to the existing tag index in invalidate.ts. No tags are required. About 15 lines.
Use
// session container, after a successful refreshthis.emit({ ...this.state, accessToken, status: 'authenticated' });retryFailed();// scoped test or workspace subtreeretryFailed(registry);Before and after
Dispatching the refresh
this.emit({ ...this.state, refreshToken, status: 'authenticated', accessToken: newAccessToken, sessionExpired: false,});
eventBus.dispatch(new AppEvent(TOKEN_REFRESHED_EVENT));this.emit({ ...this.state, refreshToken, status: 'authenticated', accessToken: newAccessToken, sessionExpired: false,});
retryFailed();Receiving it: a base class for data containers
Abridged. This is the part every data container inherits.
export const TOKEN_REFRESHED_EVENT = 'token-refreshed';
protected lastParams: TParams | null = null;
readonly getData = (parameters: TParams): TData | null => { this.lastParams = parameters; // remembered only so the event can retry // ...};
_onEvent(event: AppEvent): void { if (sessionResetApplies(event, this._id)) { this.resetData(); return; } if ( event.type === TOKEN_REFRESHED_EVENT && this.getRequestError(DEFAULT_KEY) && this.lastParams ) { this.reloadData(this.lastParams); }}// nothing: a resource already knows how to reload itself,// because its function reads args from the containerdata = resource(this, 'data', (signal, args) => api.get(args, signal), { auto: true,});What goes away: the event constant, the _onEvent branch, lastParams (the resource reads host.args), and the cross-container event dispatch from the session container. The session-reset branch beside it is covered by clearWhere, which is already built.
Test
dataCubit._onEvent(new AppEvent(TOKEN_REFRESHED_EVENT));const cubit = withBlocState( DataCubit, { data: failure(new Error('401')) }, args,);retryFailed();await waitForState(cubit, (s) => s.data.status === 'success');The tests around the event become tests of the mapping in the app, not of the event plumbing.
Differences to review
- Inactive instances. Before, a keepAlive data container with an error reloaded on the event even with no owner. After, it loads on its next activation. That avoids a request nobody is waiting for, but the data is not warm when the screen returns.
- Ordering. The event was synchronous and fire-and-forget.
retryFailed()starts the reloads and returnsvoid, so callers do not wait either. - Per-call
onError. A reload throughretryFailedgoes through the sameonErrorpath, so a failure that persists is reported again. Decide whether a retry should report only when the error differs.
Library change
invalidate.ts: a per-registrySetof resources, filled and cleared next to the tag index.resource.ts: the entry exposesfailed().- Tests: active and inactive errored resources, scope isolation across registries, mutations untouched.
- Docs: a section in
guide/async-resources.md.
Effort: about 3 hours.
Open questions
- Name.
retryFailedvsreloadFailedvsinvalidate('*'). A wildcard tag avoids a new export, but makesinvalidate’s contract looser. - Mutations. Excluded by design. Is there a case where a failed mutation should replay after a refresh? The fetch layer already retries a request once after an on-demand refresh.