Skip to content

Commit 0d31d4d

Browse files
committed
chore: clean up
1 parent 43738e8 commit 0d31d4d

File tree

1 file changed

+23
-8
lines changed

1 file changed

+23
-8
lines changed

packages/shield-controller/src/polling-with-policy.ts

Lines changed: 23 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -24,13 +24,12 @@ export class PollingWithCockatielPolicy {
2424
}
2525

2626
async start<ReturnType>(requestId: string, requestFn: RequestFn<ReturnType>) {
27-
this.abortPendingRequest(requestId);
28-
const abortController = this.addNewRequestEntry(requestId);
27+
const abortController = this.#addNewRequestEntry(requestId);
2928

3029
try {
3130
const result = await this.#policy.execute(
32-
async ({ signal: abortSignal }) => {
33-
return requestFn(abortSignal);
31+
async ({ signal }) => {
32+
return requestFn(signal);
3433
},
3534
abortController.signal,
3635
);
@@ -40,18 +39,34 @@ export class PollingWithCockatielPolicy {
4039
throw new Error('Request cancelled');
4140
}
4241
throw error;
42+
} finally {
43+
// Only cleanup if this abort controller is still active. If a new request with the same
44+
// requestId started while this one was running, it would have replaced with a new abort controller.
45+
// We must not delete the new request's controller when this older request finishes.
46+
if (abortController === this.#requestEntry.get(requestId)) {
47+
this.#cleanup(requestId);
48+
}
4349
}
4450
}
4551

46-
addNewRequestEntry(requestId: string) {
52+
abortPendingRequest(requestId: string) {
53+
const abortController = this.#requestEntry.get(requestId);
54+
abortController?.abort();
55+
this.#cleanup(requestId);
56+
}
57+
58+
#addNewRequestEntry(requestId: string) {
59+
// abort the previous request if it exists
60+
this.abortPendingRequest(requestId);
61+
62+
// create a new abort controller for the new request
4763
const abortController = new AbortController();
4864
this.#requestEntry.set(requestId, abortController);
4965
return abortController;
5066
}
5167

52-
abortPendingRequest(requestId: string) {
53-
const abortController = this.#requestEntry.get(requestId);
54-
abortController?.abort();
68+
#cleanup(requestId: string) {
69+
this.#requestEntry.delete(requestId);
5570
}
5671

5772
#shouldRetry(error: Error): boolean {

0 commit comments

Comments
 (0)