Last active
December 3, 2019 16:40
-
-
Save cowboyd/5c0c34b08592e8931604f5470e669958 to your computer and use it in GitHub Desktop.
Waiting for a port with effection
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
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