diff --git a/common/src/zygote.ts b/common/src/zygote.ts index e0ad7004b..3bedcce8d 100644 --- a/common/src/zygote.ts +++ b/common/src/zygote.ts @@ -4,6 +4,41 @@ import os from 'os'; export type Zygote = () => PluginFork; +export function createService(options: ForkOptions, create: (t: Promise) => Promise): { + getResult: () => Promise, + terminate: () => void, +} { + let killed = false; + let currentResult: Promise; + let currentFork: ReturnType>; + + return { + getResult() { + if (killed) + throw new Error('service terminated'); + + if (currentResult) + return currentResult; + + currentFork = sdk.fork(options); + currentFork.worker.on('exit', () => currentResult = undefined); + currentResult = create(currentFork.result); + currentResult.catch(() => currentResult = undefined); + return currentResult; + }, + + terminate() { + if (killed) + return; + + killed = true; + currentFork.worker.terminate(); + currentFork = undefined; + currentResult = undefined; + } + } +} + export function createZygote(options?: ForkOptions): Zygote { let zygote = sdk.fork(options); function* next() {