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

Add cancellation token package #2

Merged
merged 4 commits into from
May 24, 2017
Merged
Show file tree
Hide file tree
Changes from 3 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
4 changes: 4 additions & 0 deletions packages/cancellation-token/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
/node_modules/
*.js
*.js.map
*.d.ts
44 changes: 44 additions & 0 deletions packages/cancellation-token/__tests__/Token.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import {Token} from "../lib/Token";
import {TokenSource} from "../lib/TokenSource";

describe('Token', () => {
it('should not be cancellable if no source provided at construction', () => {
const token = new Token();

expect(token.canBeCancelled).toBe(false);
expect(token.isCancellationRequested).toBe(false);
});

it('should defer cancellation queries to parent token source', () => {
const source = {isCancellationRequested: true};
const token = new Token(<TokenSource>source);

expect(token.isCancellationRequested).toBe(true);
source.isCancellationRequested = false;
expect(token.isCancellationRequested).toBe(false);
});

it(
'should register cancellation handlers when onCancellationRequested called',
() => {
const source = new TokenSource();
source.registerCancellationHandler = jest.fn();
const token = new Token(source);

const cb = () => {};
token.onCancellationRequested(cb);
expect(source.registerCancellationHandler).toHaveBeenCalledWith(cb);
}
);

it(
'should throw if cancellation requested and throwIfCancellationRequested called',
() => {
const token = new Token(<TokenSource>{isCancellationRequested: true});

expect(() => {
token.throwIfCancellationRequested('PANIC PANIC PANIC');
}).toThrow('PANIC PANIC PANIC');
}
);
});
61 changes: 61 additions & 0 deletions packages/cancellation-token/__tests__/TokenSource.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import {Token} from "../lib/Token";
import {TokenSource} from "../lib/TokenSource";

jest.useFakeTimers();

describe('TokenSource', () => {
it('should return a new token on each property access', () => {
const source = new TokenSource();
const token = source.getToken();
expect(token).toBeInstanceOf(Token);
expect(source.getToken()).not.toBe(token);
});

it(
'should report that cancellation was requested after cancel called',
() => {
const source = new TokenSource();
expect(source.isCancellationRequested).toBe(false);
source.cancel();
expect(source.isCancellationRequested).toBe(true);
}
);

it('should invoke registered cancellation handlers on cancellation', () => {
const source = new TokenSource();
const cb = jest.fn();
source.registerCancellationHandler(cb);
expect(cb).not.toHaveBeenCalled();
source.cancel();
jest.runAllTimers();
expect(cb).toHaveBeenCalled();
});

it(
'should not invoke registered handlers if silent cancellation requested',
() => {
const source = new TokenSource();
const cb = jest.fn();
source.registerCancellationHandler(cb);
expect(cb).not.toHaveBeenCalled();
source.cancel(false);
jest.runAllTimers();
expect(cb).not.toHaveBeenCalled();
}
);

it(
'should invoke cancellation handlers immediately if cancellation already requested',
() => {
const timeoutMock = <any>setTimeout;

const source = new TokenSource();
const cb = jest.fn();
source.cancel(false);
source.registerCancellationHandler(cb);
expect(timeoutMock).toHaveBeenCalledWith(cb, 0);
jest.runAllTimers();
expect(cb).toHaveBeenCalled();
}
);
});
2 changes: 2 additions & 0 deletions packages/cancellation-token/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export * from "./lib/Token";
export * from "./lib/TokenSource";
55 changes: 55 additions & 0 deletions packages/cancellation-token/lib/Token.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import {TokenSource} from './TokenSource';

/**
* @see {TokenSource}
*
* Holders of a Token object may query if the associated operation has been
* cancelled, register cancellation handlers, and conditionally throw an Error
* if the operation has already been cancelled.
*/
export class Token {
/**
* Whether the associated operation may be cancelled at some point in the
* future.
*/
public readonly canBeCancelled: boolean;
Copy link
Contributor

Choose a reason for hiding this comment

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

Optional: I actually liked cancellable, but it doesn't really matter.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Agreed.


/**
* Creates a new Token linked to a provided TokenSource. If no source is
* provided, the Token cannot be cancelled.
*/
constructor(private readonly source?: TokenSource) {
this.canBeCancelled = Boolean(source);
}

/**
* Whether the associated operation has already been cancelled.
*/
get isCancellationRequested(): boolean {
if (this.source) {
return this.source.isCancellationRequested;
}

return false;
}

/**
* Registers a handler to be invoked when cancellation is requested. If
* cancellation has already been requested, the handler will be invoked on
* the next tick of the event loop.
*/
onCancellationRequested(cb: () => void): void {
if (this.source) {
this.source.registerCancellationHandler(cb);
}
}

/**
* Throws an error if the associated operation has already been cancelled.
*/
throwIfCancellationRequested(reason?: string): void {
if (this.isCancellationRequested) {
throw new Error(`Operation cancelled${reason ? `: ${reason}` : ''}`);
}
}
}
61 changes: 61 additions & 0 deletions packages/cancellation-token/lib/TokenSource.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import {Token} from "./Token";

/**
* The AWS SDK uses a TokenSource/Token model to allow for cooperative
* cancellation of asynchronous operations. When initiating such an operation,
* the caller can create a TokenSource and then provide linked tokens to
* subtasks. This allows a single source to signal to multiple consumers that a
* cancellation has been requested without dictating how that cancellation
* should be handled.
*
* Holders of a TokenSource object may create new tokens, register cancellation
* handlers, or declare an operation cancelled (thereby invoking any registered
* handlers).
*/
export class TokenSource {
private _cancellationRequested: boolean = false;
private _invokeAfterCancellation: Array<() => void> = [];

/**
* Whether the operation associated with this TokenSource has been
* cancelled.
*/
get isCancellationRequested(): boolean {
return this._cancellationRequested;
}

/**
* Declares the operation associated with this TokenSource to be cancelled
* and invokes any registered cancellation handlers. The latter may be
* skipped if so desired.
*/
cancel(invokeRegisteredActions: boolean = true): void {
this._cancellationRequested = true;

if (invokeRegisteredActions) {
while (this._invokeAfterCancellation.length > 0) {
let action = this._invokeAfterCancellation.shift();
if (action) {
setTimeout(action, 0);
}
}
}
}

getToken(): Token {
Copy link
Contributor

Choose a reason for hiding this comment

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

Minor: The docs for token should be moved here as well.

return new Token(this);
}

/**
* Adds a handler to be invoked when cancellation of the associated
* operation has been requested. If cancellation has already been requested,
* the handler will be invoked on the next tick of the event loop.
*/
registerCancellationHandler(handler: () => void): void {
if (this._cancellationRequested) {
setTimeout(handler, 0);
} else {
this._invokeAfterCancellation.push(handler);
}
}
}
19 changes: 19 additions & 0 deletions packages/cancellation-token/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"name": "@aws/cancellation-token",
"version": "0.0.1",
"private": true,
"description": "A simple cancellation token library",
"main": "index.js",
"scripts": {
"prepublishOnly": "tsc",
"pretest": "tsc",
"test": "jest"
},
"author": "[email protected]",
"license": "UNLICENSED",
"devDependencies": {
"@types/jest": "^19.2.2",
"jest": "^19.0.2",
"typescript": "^2.3"
}
}
10 changes: 10 additions & 0 deletions packages/cancellation-token/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"compilerOptions": {
"module": "commonjs",
"target": "es5",
"strict": true,
"sourceMap": true,
"declaration": true,
"stripInternal": true
}
}