Skip to content

rename PromiseCanceller to AbortSignalListener #4282

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

Merged
merged 4 commits into from
Nov 6, 2024
Merged
Show file tree
Hide file tree
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
91 changes: 91 additions & 0 deletions src/execution/AbortSignalListener.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
import { promiseWithResolvers } from '../jsutils/promiseWithResolvers.js';

/**
* A AbortSignalListener object can be used to trigger multiple responses
* in response to a single AbortSignal.
*
* @internal
*/
export class AbortSignalListener {
abortSignal: AbortSignal;
abort: () => void;

private _onAborts: Set<() => void>;

constructor(abortSignal: AbortSignal) {
this.abortSignal = abortSignal;
this._onAborts = new Set<() => void>();
this.abort = () => {
for (const abort of this._onAborts) {
abort();
}
};

abortSignal.addEventListener('abort', this.abort);
}

add(onAbort: () => void): void {
this._onAborts.add(onAbort);
}

delete(onAbort: () => void): void {
this._onAborts.delete(onAbort);
}

disconnect(): void {
this.abortSignal.removeEventListener('abort', this.abort);
}
}

export function cancellablePromise<T>(
originalPromise: Promise<T>,
abortSignalListener: AbortSignalListener,
): Promise<T> {
const abortSignal = abortSignalListener.abortSignal;
if (abortSignal.aborted) {
// eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors
return Promise.reject(abortSignal.reason);
}

const { promise, resolve, reject } = promiseWithResolvers<T>();
const onAbort = () => reject(abortSignal.reason);
abortSignalListener.add(onAbort);
originalPromise.then(
(resolved) => {
abortSignalListener.delete(onAbort);
resolve(resolved);
},
(error: unknown) => {
abortSignalListener.delete(onAbort);
reject(error);
},
);

return promise;
}

export function cancellableIterable<T>(
iterable: AsyncIterable<T>,
abortSignalListener: AbortSignalListener,
): AsyncIterable<T> {
const iterator = iterable[Symbol.asyncIterator]();

const _next = iterator.next.bind(iterator);

if (iterator.return) {
const _return = iterator.return.bind(iterator);

return {
[Symbol.asyncIterator]: () => ({
next: () => cancellablePromise(_next(), abortSignalListener),
return: () => cancellablePromise(_return(), abortSignalListener),
}),
};
}

return {
[Symbol.asyncIterator]: () => ({
next: () => cancellablePromise(_next(), abortSignalListener),
}),
};
}
8 changes: 4 additions & 4 deletions src/execution/IncrementalPublisher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ import { pathToArray } from '../jsutils/Path.js';

import type { GraphQLError } from '../error/GraphQLError.js';

import type { AbortSignalListener } from './AbortSignalListener.js';
import { IncrementalGraph } from './IncrementalGraph.js';
import type { PromiseCanceller } from './PromiseCanceller.js';
import type {
CancellableStreamRecord,
CompletedExecutionGroup,
Expand Down Expand Up @@ -44,7 +44,7 @@ export function buildIncrementalResponse(
}

interface IncrementalPublisherContext {
promiseCanceller: PromiseCanceller | undefined;
abortSignalListener: AbortSignalListener | undefined;
cancellableStreams: Set<CancellableStreamRecord> | undefined;
}

Expand Down Expand Up @@ -127,7 +127,7 @@ class IncrementalPublisher {
IteratorResult<SubsequentIncrementalExecutionResult, void>
> => {
if (isDone) {
this._context.promiseCanceller?.disconnect();
this._context.abortSignalListener?.disconnect();
await this._returnAsyncIteratorsIgnoringErrors();
return { value: undefined, done: true };
}
Expand Down Expand Up @@ -176,7 +176,7 @@ class IncrementalPublisher {

// TODO: add test for this case
/* c8 ignore next */
this._context.promiseCanceller?.disconnect();
this._context.abortSignalListener?.disconnect();
await this._returnAsyncIteratorsIgnoringErrors();
return { value: undefined, done: true };
};
Expand Down
76 changes: 0 additions & 76 deletions src/execution/PromiseCanceller.ts

This file was deleted.

170 changes: 170 additions & 0 deletions src/execution/__tests__/AbortSignalListener-test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
import { expect } from 'chai';
import { describe, it } from 'mocha';

import { expectPromise } from '../../__testUtils__/expectPromise.js';

import {
AbortSignalListener,
cancellableIterable,
cancellablePromise,
} from '../AbortSignalListener.js';

describe('AbortSignalListener', () => {
it('works to add a listener', () => {
const abortController = new AbortController();

const abortSignalListener = new AbortSignalListener(abortController.signal);

let called = false;
const onAbort = () => {
called = true;
};
abortSignalListener.add(onAbort);

abortController.abort();

expect(called).to.equal(true);
});

it('works to delete a listener', () => {
const abortController = new AbortController();

const abortSignalListener = new AbortSignalListener(abortController.signal);

let called = false;
/* c8 ignore next 3 */
const onAbort = () => {
called = true;
};
abortSignalListener.add(onAbort);
abortSignalListener.delete(onAbort);

abortController.abort();

expect(called).to.equal(false);
});

it('works to disconnect a listener from the abortSignal', () => {
const abortController = new AbortController();

const abortSignalListener = new AbortSignalListener(abortController.signal);

let called = false;
/* c8 ignore next 3 */
const onAbort = () => {
called = true;
};
abortSignalListener.add(onAbort);

abortSignalListener.disconnect();

abortController.abort();

expect(called).to.equal(false);
});
});

describe('cancellablePromise', () => {
it('works to cancel an already resolved promise', async () => {
const abortController = new AbortController();

const abortSignalListener = new AbortSignalListener(abortController.signal);

const promise = Promise.resolve(1);

const withCancellation = cancellablePromise(promise, abortSignalListener);

abortController.abort(new Error('Cancelled!'));

await expectPromise(withCancellation).toRejectWith('Cancelled!');
});

it('works to cancel an already resolved promise after abort signal triggered', async () => {
const abortController = new AbortController();
const abortSignalListener = new AbortSignalListener(abortController.signal);

abortController.abort(new Error('Cancelled!'));

const promise = Promise.resolve(1);

const withCancellation = cancellablePromise(promise, abortSignalListener);

await expectPromise(withCancellation).toRejectWith('Cancelled!');
});

it('works to cancel a hanging promise', async () => {
const abortController = new AbortController();
const abortSignalListener = new AbortSignalListener(abortController.signal);

const promise = new Promise(() => {
/* never resolves */
});

const withCancellation = cancellablePromise(promise, abortSignalListener);

abortController.abort(new Error('Cancelled!'));

await expectPromise(withCancellation).toRejectWith('Cancelled!');
});

it('works to cancel a hanging promise created after abort signal triggered', async () => {
const abortController = new AbortController();
const abortSignalListener = new AbortSignalListener(abortController.signal);

abortController.abort(new Error('Cancelled!'));

const promise = new Promise(() => {
/* never resolves */
});

const withCancellation = cancellablePromise(promise, abortSignalListener);

await expectPromise(withCancellation).toRejectWith('Cancelled!');
});
});

describe('cancellableAsyncIterable', () => {
it('works to abort a next call', async () => {
const abortController = new AbortController();
const abortSignalListener = new AbortSignalListener(abortController.signal);

const asyncIterable = {
[Symbol.asyncIterator]: () => ({
next: () => Promise.resolve({ value: 1, done: false }),
}),
};

const withCancellation = cancellableIterable(
asyncIterable,
abortSignalListener,
);

const nextPromise = withCancellation[Symbol.asyncIterator]().next();

abortController.abort(new Error('Cancelled!'));

await expectPromise(nextPromise).toRejectWith('Cancelled!');
});

it('works to abort a next call when already aborted', async () => {
const abortController = new AbortController();
const abortSignalListener = new AbortSignalListener(abortController.signal);

abortController.abort(new Error('Cancelled!'));

const asyncIterable = {
[Symbol.asyncIterator]: () => ({
next: () => Promise.resolve({ value: 1, done: false }),
}),
};

const withCancellation = cancellableIterable(
asyncIterable,
abortSignalListener,
);

const nextPromise = withCancellation[Symbol.asyncIterator]().next();

await expectPromise(nextPromise).toRejectWith('Cancelled!');
});
});
Loading
Loading