From 9ee76b10fac4f1aeeec27b1576873d8c1057fd48 Mon Sep 17 00:00:00 2001 From: Matt Low Date: Fri, 5 Mar 2021 12:56:20 -0700 Subject: [PATCH] Add USE_WORKER_THREADS environment var --- src/graphql/sudoku.ts | 18 ++++++++++-------- src/main.ts | 22 ++++++++++++++++++++++ src/sudoku/index.ts | 5 ++--- 3 files changed, 34 insertions(+), 11 deletions(-) diff --git a/src/graphql/sudoku.ts b/src/graphql/sudoku.ts index 81f7373..3271699 100644 --- a/src/graphql/sudoku.ts +++ b/src/graphql/sudoku.ts @@ -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; + generate(args: GenerateArguments): Promise | 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), }, }; diff --git a/src/main.ts b/src/main.ts index 7d6ebc1..a8b122b 100644 --- a/src/main.ts +++ b/src/main.ts @@ -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( diff --git a/src/sudoku/index.ts b/src/sudoku/index.ts index 056c2f9..891094c 100644 --- a/src/sudoku/index.ts +++ b/src/sudoku/index.ts @@ -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(