request method
A function called when a request reaches this Link
Implementation
@override
Stream<Response> request(
Request request, [
NextLink? forward,
]) {
final next = forward!;
return Stream<Response>.multi((controller) {
StreamSubscription<Response>? forwardSub;
var cancelled = false;
var replaying = false;
Future<void> refreshAndReplay(
Object originalError,
StackTrace originalStack,
) async {
replaying = true;
try {
final refreshedToken = await _refresh();
if (cancelled) return;
// Reuse the token the shared refresh produced rather than calling getToken again:
// a caller that rotates tokens per call must not hand a second value to the replay.
final retried = _applyToken(request, headerKey, refreshedToken);
if (cancelled) return;
await for (final response in next(retried)) {
if (cancelled) break;
controller.add(response);
}
if (!cancelled) await controller.close();
} catch (_) {
// The replay itself failed. Surface the *original* error: it is the one the caller
// cares about, and a failure while refreshing must not mask it.
if (!cancelled) controller.addError(originalError, originalStack);
}
}
Future<void> run() async {
try {
final req = await _withToken(request, headerKey, getToken);
if (cancelled) return;
forwardSub = next(req).listen(
controller.add,
onError: (Object error, StackTrace stack) async {
// Not an auth failure, or the caller declined a refresh: surface it unchanged.
if (replaying || cancelled || onAuthError == null) {
if (!cancelled) controller.addError(error, stack);
return;
}
final refresh = await onAuthError!(error);
if (!refresh || cancelled || replaying) {
if (!cancelled) controller.addError(error, stack);
return;
}
refreshAndReplay(error, stack);
},
onDone: () {
if (!cancelled && !replaying) controller.close();
},
cancelOnError: true,
);
} catch (error, stack) {
// A synchronous throw from getToken/forward is not an auth failure to replay.
if (!cancelled) controller.addError(error, stack);
}
}
controller.onCancel = () async {
cancelled = true;
await forwardSub?.cancel();
};
run();
});
}