Skip to content

Instantly share code, notes, and snippets.

@cowboyd
Last active December 3, 2019 16:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cowboyd/5c0c34b08592e8931604f5470e669958 to your computer and use it in GitHub Desktop.
Save cowboyd/5c0c34b08592e8931604f5470e669958 to your computer and use it in GitHub Desktop.
Waiting for a port with effection
import { fork, timeout, Sequence, Operation } from 'effection';
import { on } from '@effection/events';
import { createConnection } from 'net';
export function* waitConnect(host: string, port: number): Sequence {
loop: {
let socket = createConnection(port, host);
let monitor = fork(function*() {
let [error]: [Error] = yield on(socket, 'error');
throw error;
})
try {
yield on(socket, 'ready');
} catch (error) {
break loop;
} finally {
monitor.halt();
socket.destroy();
}
}
}
export function* waitPort(host: string, port: number, maxtime: number): Sequence {
yield timebox(maxtime, waitConnect(host, port));
}
// take any operation and timebox it to `duration`
export function* timebox(duration: number, operation: Operation): Sequence {
// timebox process will throw an exception after `duration` milliseconds
// thus aborting the parent operation (and all siblings).
let timebomb = fork(function* () {
yield timeout(duration);
throw new Error(`timeout of ${duration}ms exceeded`);
})
try {
return yield operation;
} finally {
timebomb.halt();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment