Created
March 17, 2021 03:01
-
-
Save cowboyd/3a706403c3abb088c85f32e1b93b860a to your computer and use it in GitHub Desktop.
potential supervisor in 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 { Task, Operation } from 'effection'; | |
interface SupervisorOptions { | |
maxConcurrency?: number; | |
dropMostRecent?: boolean; | |
} | |
const supervisorDefaults = { | |
maxConcurrency: 1, | |
dropMostRecent: true | |
}; | |
interface Runnable<T> { | |
run(scope: Task): T; | |
} | |
interface Call<T extends unknown[], R = void> { | |
(...args: T): R; | |
} | |
type Operator<T extends unknown[]> = Call<T, Operation<unknown>>; | |
export function createSupervisor(inputs: SupervisorOptions = {}): <T extends unknown[]>(create: Operator<T>) => Runnable<Call<T>> { | |
let options = { ...supervisorDefaults, ...inputs }; | |
return (operator) => { | |
return { | |
run(scope) { | |
let tasks = new Set<Task>(); | |
return (...args) => { | |
let i = 1; | |
for (let task of tasks) { | |
if (i >= options.maxConcurrency) { | |
task.halt(); | |
tasks.delete(task); | |
} | |
i++; | |
} | |
let task = scope.spawn(operator(...args)); | |
task.finally(() => tasks.delete(task)); | |
tasks.add(task); | |
}; | |
} | |
}; | |
}; | |
} | |
const restartable = createSupervisor({ maxConcurrency: 1}); | |
run(function*(scope: Task) { | |
let build = restartable((num: number) => function*() { | |
}).run(scope); | |
build(1); | |
}) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment