Skip to content

Commit

Permalink
refactor: more simplification and docs
Browse files Browse the repository at this point in the history
  • Loading branch information
krisselden committed Jun 17, 2020
1 parent 681b58b commit 7c0b0ae
Show file tree
Hide file tree
Showing 63 changed files with 1,726 additions and 578 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,6 @@
/coverage/
dist/
node_modules/
temp/
*.log
*.tgz
8 changes: 4 additions & 4 deletions .nycrc.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"per-file": false,
"branches": 95,
"functions": 95,
"lines": 95,
"statements": 95
"branches": 90,
"functions": 90,
"lines": 90,
"statements": 90
}
73 changes: 3 additions & 70 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,73 +2,6 @@
[![Build Status](https://travis-ci.org/krisselden/race-cancellation.svg?branch=master)](https://travis-ci.org/krisselden/race-cancellation)
[![Coverage Status](https://coveralls.io/repos/github/krisselden/race-cancellation/badge.svg?branch=master)](https://coveralls.io/github/krisselden/race-cancellation?branch=master)

This is a library with utils to implement a cancellable async function
with a pattern that solves a number of issues with cancellation of promises.

The pattern is a cancellable async function takes a function that will build
the cancellation race on demand.

## Constraints

- Composable
- Cancellation concerns can be composed easily
- Lazy
- Should not create the Promise<never> until it is raced or it will create meaningless unhandledRejections
- Should be able to avoid invoking the raced task if it is already cancelled
- Should be able to avoid invoking the cancellation task if the parent cancellation already won

## RaceCancellation Interface

```ts
export type Race = <T>(task: Promise<T> | Task<T>) => Promise<T>;
export type Task<T> = () => Promise<T>;
export type CancellableTask<T> = (raceCancel: Race) => Promise<T>;
```

Since race cancellation is a function it can lazily create the Promise<never> to
avoid unhandledRejection. It can also avoid creating the Promise<never> if the task invoke fails.

Since it can take a function to invoke to produce the task,
it can avoid starting the task if it is already cancelled and can avoid creating the Promise<never>
if the task fails on invoke.

This also allows the combined race cancellations to be lazy.
For example, if we are already cancelled because we are disconnected
we don't need to start a timeout.

## Examples of Cancellable Async Functions

```js
import * as fs from "fs";

async function pollFile(path, interval, raceCancel) {
while (!fs.existsSync(path)) {
await sleep(interval, raceCancel);
}
}

async function sleep(ms, raceCancel) {
let id;
try {
const createTimeout = () =>
new Promise<void>(resolve => {
id = setTimeout(() => {
resolve();
id = undefined;
}, ms);
})
// if cancellation has happened race cancel can return
// a rejected promise without invoking createTimeout
// otherwise createTimeout is called and raced against
// a new Promise<never> created from the cancellation Promise,
// cancellationPromise.then(throwCancellationError)
return await raceCancel(createTimeout);
} finally {
if (id !== undefined) {
// cleanup timeout so node will exit right away if
// our script is done.
clearTimeout(id);
}
}
}
```
- [README](./race-cancellation/README.md)
- [API Docs](./race-cancellation/docs/race-cancellation.md)
- [Example](./examples/ctrl-c.js)
56 changes: 34 additions & 22 deletions examples/ctrl-c.js
Original file line number Diff line number Diff line change
@@ -1,49 +1,61 @@
import { cancellableRace, disposablePromise } from "race-cancellation";
import { cancellablePromise, withCancel } from "race-cancellation";

const [raceCancellation, cancel] = cancellableRace();

process.on("SIGINT", cancel);
// Graceful exit on SIGINT

void main();

/**
* Run a cancellable async function with cancel on SIGINT.
*
* @template T
* @param {import("race-cancellation").CancellableAsyncFn<T>} cancellableAsync
*/
function withCancelOnSigint(cancellableAsync) {
return withCancel(cancellableAsync, (resolve) => {
process.on("SIGINT", resolve);
return () => process.off("SIGINT", resolve);
});
}

process.stdout.setNoDelay(true);

/**
* Cancellable async main with graceful termination on cancel.
*/
async function main() {
console.log("main started");
try {
const result = await myAsyncTask((step, total) => {
console.log(`main progress: ${step} of ${total}`);
const result = await withCancelOnSigint(async (raceCancel) => {
for (let i = 0; i < 8; i++) {
process.stdout.write(`waiting on step ${i + 1} of 8 …`);
await doRealAsyncStep(raceCancel);
process.stdout.write(` done.\n`);
}
return "some result";
});
console.log(`main done: ${result}`);
} catch (e) {
console.error("%o", e);
// let node exit naturally
process.exitCode = 1;
} finally {
// do cleanup, like remove tmp files
console.log("main finalized");
// do cancellable async cleanup
await withCancelOnSigint(async (raceCancel) => {
process.stdout.write(`cleaning up …`);
await doRealAsyncStep(raceCancel);
process.stdout.write(` done.\n`);
});
}
}

/**
* @param {(i: number, t: number) => void} progress
* @param {import("race-cancellation").RaceCancelFn} raceCancel
*/
async function myAsyncTask(progress) {
for (let i = 0; i < 8; i++) {
await doRealAsyncStep();
progress(i + 1, 8);
}
return "some result";
}

async function doRealAsyncStep() {
// `disposablePromise` is helper for real async to
// ensure cleanup on cancellation
await disposablePromise((resolve) => {
function doRealAsyncStep(raceCancel) {
return cancellablePromise((resolve) => {
const id = setTimeout(resolve, 1000);
return () => {
clearTimeout(id);
};
}, raceCancellation);
}, raceCancel);
}
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
"examples"
],
"scripts": {
"docs": "yarn workspace race-cancellation docs",
"lint": "npm-run-all lint:*",
"lint:eslint": "eslint .",
"lint:examples": "tsc -p examples --noEmit",
Expand Down
2 changes: 1 addition & 1 deletion LICENSE → race-cancellation/LICENSE
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
BSD 2-CLAUSE LICENSE

Copyright 2019 Kris Selden. All Rights Reserved.
Copyright 2019-2020 Kris Selden. All Rights Reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

Expand Down
75 changes: 75 additions & 0 deletions race-cancellation/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
# race-cancellation
[![Build Status](https://travis-ci.org/krisselden/race-cancellation.svg?branch=master)](https://travis-ci.org/krisselden/race-cancellation)
[![Coverage Status](https://coveralls.io/repos/github/krisselden/race-cancellation/badge.svg?branch=master)](https://coveralls.io/github/krisselden/race-cancellation?branch=master)

[API Docs](./docs/race-cancellation.md)

This is a library with utils to implement a cancellable async function
with a pattern that solves a number of issues with cancellation of promises.

The pattern is a cancellable async function takes a function that will build
the cancellation race lazily.

## Design Constraints

- Composable
- Cancellation concerns can be composed easily
- Lazy
- Should not create the Promise<never> until it is raced or it will create meaningless unhandledRejections
- Should be able to avoid invoking the raced async function if it is already cancelled
- Should be able to avoid invoking the cancellation task if the outer scope cancellation already won
- Adaptable
- Should be easy to adapt other promise cancellation patterns

## RaceCancellation Interface

```ts
export type AsyncFn<T> = () => Promise<T>;
export type RaceCancelFn = <T>(asyncFnOrPromise: AsyncFn<T> | PromiseLike<T>) => Promise<T>;
export type CancellableAsyncFn<T> = (raceCancel: RaceCancelFn) => Promise<T>;
```

Since race cancellation is a function it can lazily create the Promise<never> to
avoid unhandledRejection.

Since it can take a function to invoke to produce the task,
it can avoid starting the task if it is already cancelled and can avoid creating the Promise<never>
if the task fails on invoke.

This also allows the combined race cancellations to be lazy.
For example, if we are already cancelled because we are disconnected
we don't need to start a timeout.

## Examples of Cancellable Async Functions

```js
import * as fs from "fs";

async function pollFile(path, interval, raceCancel) {
while (!fs.existsSync(path)) {
await sleep(interval, raceCancel);
}
}

async function sleep(ms, raceCancel) {
let id;
try {
const createTimeout = () =>
new Promise<void>(resolve => {
id = setTimeout(resolve, ms);
});
// if cancellation has happened race cancel can return
// a rejected promise without invoking createTimeout
// otherwise createTimeout is called and raced against
// a new Promise<never> created from the cancellation Promise,
// cancellationPromise.then(throwCancellationError)
return await raceCancel(createTimeout);
} finally {
if (id !== undefined) {
// cleanup timeout so node will exit right away if
// our script is done.
clearTimeout(id);
}
}
}
```

0 comments on commit 7c0b0ae

Please sign in to comment.