Skip to content
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

[Core] Make AbortController/AbortSignal work in the browser with fetch #6045

Closed
wants to merge 4 commits into from
Closed
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
22 changes: 16 additions & 6 deletions sdk/core/abort-controller/src/AbortController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ export class AbortError extends Error {
*/
export class AbortController {
private _signal: AbortSignal;

private _innerController?: InstanceType<typeof window.AbortController>;
/**
* @param {AbortSignalLike[]} [parentSignals] The AbortSignals that will signal aborted on the AbortSignal associated with this controller.
* @constructor
Expand All @@ -69,7 +69,13 @@ export class AbortController {
*/
constructor(...parentSignals: AbortSignalLike[]);
constructor(parentSignals?: any) {
this._signal = new AbortSignal();
if (typeof window !== "undefined" && typeof window.AbortController === "function") {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we check self instead of window in case we're running inside a webworker?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think you're right... we need to abstract out these platform checks in a better way. We're checking window in a lot of places outside of this library.

this._innerController = new window.AbortController();
this._signal = this._innerController.signal;
} else {
this._innerController = undefined;
this._signal = new AbortSignal();
}

if (!parentSignals) {
return;
Expand Down Expand Up @@ -111,7 +117,11 @@ export class AbortController {
* @memberof AbortController
*/
abort() {
abortSignal(this._signal);
if (this._innerController) {
this._innerController.abort();
} else {
abortSignal(this._signal);
}
}

/**
Expand All @@ -122,12 +132,12 @@ export class AbortController {
* @returns {AbortSignal}
*/
public static timeout(ms: number): AbortSignal {
const signal = new AbortSignal();
const timer = setTimeout(abortSignal, ms, signal);
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), ms);
// Prevent the active Timer from keeping the Node.js event loop active.
if (typeof timer.unref === "function") {
timer.unref();
}
return signal;
return controller.signal;
}
}
18 changes: 12 additions & 6 deletions sdk/core/abort-controller/src/AbortSignal.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
/// <reference path="./shims-public.d.ts" />

import { AbortController } from "./AbortController";

type AbortEventListener = (this: AbortSignalLike, ev?: any) => any;

const listenersMap = new WeakMap<AbortSignal, AbortEventListener[]>();
Expand Down Expand Up @@ -76,15 +79,16 @@ export class AbortSignal implements AbortSignalLike {
* @memberof AbortSignal
*/
public static get none(): AbortSignal {
return new AbortSignal();
const controller = new AbortController();
return controller.signal;
}

/**
* onabort event listener.
*
* @memberof AbortSignal
*/
public onabort: ((ev?: Event) => any) | null = null;
public onabort: ((ev: Event) => any) | null = null;

/**
* Added new "abort" event listener, only support "abort" event.
Expand Down Expand Up @@ -131,10 +135,12 @@ export class AbortSignal implements AbortSignalLike {
}

/**
* Dispatches a synthetic event to the AbortSignal.
*/
* Dispatches a synthetic event to the AbortSignal.
*/
dispatchEvent(event: Event): boolean {
throw new Error("This is a stub dispatchEvent implementation that should not be used. It only exists for type-checking purposes.")
throw new Error(
"This is a stub dispatchEvent implementation that should not be used. It only exists for type-checking purposes."
);
}
}

Expand All @@ -154,7 +160,7 @@ export function abortSignal(signal: AbortSignal) {
}

if (signal.onabort) {
signal.onabort.call(signal);
signal.onabort.call(signal, { type: "abort" } as any);
}

const listeners = listenersMap.get(signal)!;
Expand Down
28 changes: 25 additions & 3 deletions sdk/core/abort-controller/test/aborter.spec.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
/// <reference lib="dom" />

import * as assert from "assert";
import { AbortController, AbortSignal, AbortError } from "../src/aborter";

Expand Down Expand Up @@ -179,7 +181,7 @@ describe("AbortController", () => {
assert.equal(s, "parent1");
});

it("should call abort() on child signals that were created before parent abort() call", async function() {
it("should call abort() on child signals that were created before parent abort() call", async () => {
const parentController = new AbortController();
const parentSignal = parentController.signal;

Expand Down Expand Up @@ -276,7 +278,7 @@ describe("AbortController", () => {
assert.equal(true, values.includes("child"));
});

it("should call abort() on deeply nested child signals that were created before parent abort() call", async function() {
it("should call abort() on deeply nested child signals that were created before parent abort() call", async () => {
const parentController = new AbortController();
const parentSignal = parentController.signal;

Expand Down Expand Up @@ -307,7 +309,7 @@ describe("AbortController", () => {
assert.equal(true, values.includes("child2"));
});

it("should not call abort() on parent signals when child calls abort()", async function() {
it("should not call abort() on parent signals when child calls abort()", async () => {
const parentController = new AbortController();
const parentSignal = parentController.signal;

Expand Down Expand Up @@ -348,3 +350,23 @@ describe("AbortController", () => {
assert.equal(true, values.includes("child2"));
});
});

if (typeof window !== "undefined" && typeof window.fetch !== "undefined") {
describe("fetch integration", () => {
it("works", async () => {
const parentController = new AbortController();
const parentSignal = parentController.signal;
parentController.abort();

let error;
try {
await fetch("example.com", {
signal: parentSignal
});
} catch (e) {
error = e;
}
assert.equal(error.name, "AbortError");
});
});
}
1 change: 0 additions & 1 deletion sdk/servicebus/service-bus/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@
"main": "./dist/index.js",
"module": "dist-esm/src/index.js",
"browser": {
"./dist/index.js": "./browser/service-bus.js",
"./dist-esm/test/utils/aadUtils.js": "./dist-esm/test/utils/aadUtils.browser.js",
"./dist-esm/src/util/crypto.js": "./dist-esm/src/util/crypto.browser.js",
"buffer": "buffer",
Expand Down
2 changes: 1 addition & 1 deletion sdk/servicebus/service-bus/review/service-bus.api.md
Original file line number Diff line number Diff line change
Expand Up @@ -156,8 +156,8 @@ export interface OnMessage {
// @public
export class QueueClient implements Client {
close(): Promise<void>;
createReceiver(receiveMode: ReceiveMode, sessionOptions: SessionReceiverOptions): SessionReceiver;
createReceiver(receiveMode: ReceiveMode): Receiver;
createReceiver(receiveMode: ReceiveMode, sessionOptions: SessionReceiverOptions): SessionReceiver;
createSender(): Sender;
readonly entityPath: string;
static getDeadLetterQueuePath(queueName: string): string;
Expand Down
3 changes: 1 addition & 2 deletions sdk/servicebus/service-bus/rollup.base.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -141,8 +141,7 @@ export function browserConfig({ test = false, production = false } = {}) {

nodeResolve({
mainFields: ["module", "browser"],
preferBuiltins: false,
dedupe: ["buffer"]
preferBuiltins: false
}),
cjs({
namedExports: { events: ["EventEmitter"], long: ["ZERO"] }
Expand Down
9 changes: 1 addition & 8 deletions sdk/servicebus/service-bus/rollup.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,6 @@ import * as base from "./rollup.base.config";

const inputs = [];

if (!process.env.ONLY_BROWSER) {
inputs.push(base.nodeConfig());
}

if (!process.env.ONLY_NODE) {
inputs.push(base.browserConfig());
inputs.push(base.browserConfig({ production: true }));
}
inputs.push(base.browserConfig());

export default inputs;