Skip to content

fix: Resolve race condition in AbortController handling during tab visibility changes #94

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 14 additions & 2 deletions src/fetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,19 @@ export function fetchEventSource(input: RequestInfo, {
const fetch = inputFetch ?? window.fetch;
const onopen = inputOnOpen ?? defaultOnOpen;
async function create() {
curRequestController = new AbortController();
// Store the AbortController instance in function scope to prevent race conditions
// This ensures that when error handling occurs, we check the abort status
// of the correct controller instance that was associated with this specific request,
// rather than potentially checking a new controller created by a subsequent request.
//
// Race condition example:
// 1. Request A starts with Controller A
// 2. Tab becomes hidden -> Controller A is aborted
// 3. Tab becomes visible -> Request B starts with Controller B
// 4. Request A's error handler executes
// Without this fix, it would check Controller B's status instead of A's
const currentController = new AbortController();
curRequestController = currentController;
try {
const response = await fetch(input, {
...rest,
Expand All @@ -126,7 +138,7 @@ export function fetchEventSource(input: RequestInfo, {
dispose();
resolve();
} catch (err) {
if (!curRequestController.signal.aborted) {
if (!currentController.signal.aborted) {
// if we haven't aborted the request ourselves:
try {
// check if we need to retry:
Expand Down