-
Notifications
You must be signed in to change notification settings - Fork 5
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
refactor: more simplification and docs
- Loading branch information
1 parent
681b58b
commit f97282c
Showing
63 changed files
with
1,726 additions
and
578 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -2,5 +2,6 @@ | |
/coverage/ | ||
dist/ | ||
node_modules/ | ||
temp/ | ||
*.log | ||
*.tgz |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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": 85, | ||
"functions": 85, | ||
"lines": 85, | ||
"statements": 85 | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
} | ||
} | ||
} | ||
``` |
Oops, something went wrong.