Add USE_WORKER_THREADS environment var

This commit is contained in:
Matt Low 2021-03-05 12:56:20 -07:00
parent 15b69c510c
commit 9ee76b10fa
3 changed files with 34 additions and 11 deletions

View File

@ -1,10 +1,5 @@
import { gql } from "../mods.js";
import {
solve,
generate,
GenerateArguments,
SolveArguments,
} from "../sudoku/index.js";
import { Sudoku, GenerateArguments, SolveArguments } from "../sudoku/index.js";
export const typeDefs = gql`
"""
@ -33,9 +28,16 @@ export const typeDefs = gql`
}
`;
interface SudokuFuncs {
solve(args: SolveArguments): Promise<Sudoku> | Sudoku;
generate(args: GenerateArguments): Promise<Sudoku> | Sudoku;
}
export const resolvers = {
Query: {
generate: (obj: any, args: GenerateArguments) => generate(args),
solve: (obj: any, args: SolveArguments) => solve(args),
generate: (obj: any, args: GenerateArguments, ctx: SudokuFuncs) =>
ctx.generate(args),
solve: (obj: any, args: SolveArguments, ctx: SudokuFuncs) =>
ctx.solve(args),
},
};

View File

@ -1,6 +1,13 @@
import { Application, bodyParser } from "./mods.js";
import { applyGraphQL } from "./graphql.js";
import { typeDefs, resolvers } from "./graphql/index.js";
import {
initializeWorkers,
solve,
generate,
solveSync,
generateSync,
} from "./sudoku/index.js";
import stoppable from "stoppable";
import cors from "@koa/cors";
@ -31,10 +38,25 @@ async function main() {
);
});
let sudokuFuncs: any;
if (process.env.USE_WORKER_THREADS) {
initializeWorkers();
sudokuFuncs = {
solve,
generate,
};
} else {
sudokuFuncs = {
solve: solveSync,
generate: generateSync,
};
}
applyGraphQL({
app,
typeDefs: typeDefs,
resolvers: resolvers,
context: () => sudokuFuncs,
});
runtime.server = stoppable(

View File

@ -49,13 +49,12 @@ function spawnWorker() {
);
}
function initialize() {
export function initializeWorkers() {
console.log(`Starting ${WORKERS} worker threads`);
for (let n = 0; n < WORKERS; n++) {
spawnWorker();
}
}
initialize();
function pickWorker() {
const proxy = available.pop();
@ -165,7 +164,7 @@ export function solveSync({
regionWidth,
regionHeight,
cells,
}: SolveArguments) {
}: SolveArguments): Sudoku {
const size = (regionWidth * regionHeight) ** 2;
if (size !== cells.length) {
throw new Error(