Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: worker pooling #962

Open
wants to merge 22 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 11 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .ghjk/deno.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 0 additions & 10 deletions deno.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion src/typegate/engine/src/runtimes/wit_wire.rs
Original file line number Diff line number Diff line change
Expand Up @@ -405,7 +405,7 @@ pub fn op_wit_wire_destroy(
scope: &mut v8::HandleScope<'_>,
#[string] instance_id: String,
) {
debug!("destroying wit_wire instnace {instance_id}");
debug!("destroying wit_wire instance {instance_id}");
let ctx = {
let state = state.borrow();
let ctx = state.borrow::<Ctx>();
Expand Down
2 changes: 1 addition & 1 deletion src/typegate/src/runtimes/deno/deno.ts
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,7 @@ export class DenoRuntime extends Runtime {
}

async deinit(): Promise<void> {
// await this.workerManager.deinit();
this.workerManager.deinit();
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Consider awaiting worker manager deinitialization.

Not awaiting workerManager.deinit() could lead to resource leaks or race conditions during shutdown. Consider maintaining the async await to ensure proper cleanup.

Apply this diff to ensure proper resource cleanup:

-    this.workerManager.deinit();
+    await this.workerManager.deinit();

Committable suggestion skipped: line range outside the PR's diff.

}

materialize(
Expand Down
9 changes: 5 additions & 4 deletions src/typegate/src/runtimes/deno/worker_manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,21 +21,22 @@ export class WorkerManager
extends BaseWorkerManager<TaskSpec, DenoMessage, DenoEvent> {
constructor(private config: WorkerManagerConfig) {
super(
"deno runtime",
(taskId: TaskId) => {
return new DenoWorker(taskId, import.meta.resolve("./worker.ts"));
},
);
}

callFunction(
async callFunction(
name: string,
modulePath: string,
relativeModulePath: string,
args: unknown,
internalTCtx: TaskContext,
) {
const taskId = createTaskId(`${name}@${relativeModulePath}`);
this.createWorker(name, taskId, {
await this.delegateTask(name, taskId, {
modulePath,
functionName: name,
});
Expand All @@ -49,13 +50,13 @@ export class WorkerManager

return new Promise((resolve, reject) => {
const timeoutId = setTimeout(() => {
this.destroyWorker(name, taskId);
this.deallocateWorker(name, taskId);
reject(new Error(`${this.config.timeout_ms}ms timeout exceeded`));
}, this.config.timeout_ms);

const handler: (event: DenoEvent) => void = (event) => {
clearTimeout(timeoutId);
this.destroyWorker(name, taskId);
this.deallocateWorker(name, taskId);
switch (event.type) {
case "SUCCESS":
resolve(event.result);
Expand Down
5 changes: 3 additions & 2 deletions src/typegate/src/runtimes/patterns/worker_manager/deno.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,13 +43,14 @@ export class DenoWorker<M extends BaseMessage, E extends BaseDenoWorkerMessage>
await handlerFn(message.data as E);
};

this.#worker.onerror = /*async*/ (event) =>
handlerFn(
this.#worker.onerror = async (event) => {
await handlerFn(
{
type: "WORKER_ERROR",
event,
} as E,
);
};
}

send(msg: M) {
Expand Down
157 changes: 135 additions & 22 deletions src/typegate/src/runtimes/patterns/worker_manager/mod.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,12 @@
// SPDX-License-Identifier: MPL-2.0

import { getLogger } from "../../../log.ts";
import {
createSimpleWaitQueue,
PoolConfig,
WaitQueue,
WaitQueueWithTimeout,
} from "./pooling.ts";
import { BaseMessage, EventHandler, TaskId } from "./types.ts";

const logger = getLogger(import.meta, "WARN");
Expand All @@ -17,25 +23,53 @@ export abstract class BaseWorker<M extends BaseMessage, E extends BaseMessage> {
abstract get id(): TaskId;
}

type DeallocateOptions = {
destroy?: boolean;
/// defaults to `true`
/// recreate workers to replace destroyed ones if `.destroy` is `true`.
/// Set to `false` for deinit.
ensureMinWorkers?: boolean;
};

export class BaseWorkerManager<
T,
M extends BaseMessage,
E extends BaseMessage,
> {
#name: string;
#activeTasks: Map<TaskId, {
worker: BaseWorker<M, E>;
taskSpec: T;
}> = new Map();
#tasksByName: Map<string, Set<TaskId>> = new Map();
#startedAt: Map<TaskId, Date> = new Map();
#poolConfig: PoolConfig;
// TODO auto-remove idle workers after a certain time
#idleWorkers: BaseWorker<M, E>[] = [];
#waitQueue: WaitQueue<BaseWorker<M, E>>;
#nextWorkerId = 1;

#workerFactory: () => BaseWorker<M, E>;

#workerFactory: (taskId: TaskId) => BaseWorker<M, E>;
protected constructor(workerFactory: (taskId: TaskId) => BaseWorker<M, E>) {
this.#workerFactory = workerFactory;
get #workerCount() {
return this.#idleWorkers.length + this.#activeTasks.size;
}

get workerFactory() {
return this.#workerFactory;
protected constructor(
name: string,
workerFactory: (taskId: TaskId) => BaseWorker<M, E>,
config: PoolConfig = {},
) {
this.#name = name;
this.#workerFactory = () =>
workerFactory(`${this.#name} worker #${this.#nextWorkerId++}`);
this.#poolConfig = config;

if (config.waitTimeoutMs == null) { // no timeout
this.#waitQueue = createSimpleWaitQueue();
} else {
this.#waitQueue = new WaitQueueWithTimeout(config.waitTimeoutMs ?? 30000);
}
}

protected getActiveTaskNames() {
Expand Down Expand Up @@ -68,49 +102,85 @@ export class BaseWorkerManager<
return startedAt;
}

// allocate worker?
protected createWorker(name: string, taskId: TaskId, taskSpec: T) {
const worker = this.#workerFactory(taskId);
// TODO inline
this.addWorker(name, taskId, worker, taskSpec, new Date());
#nextWorker() {
const idleWorker = this.#idleWorkers.shift();
if (idleWorker) {
return Promise.resolve(idleWorker);
}
if (
this.#poolConfig.maxWorkers == null ||
this.#activeTasks.size < this.#poolConfig.maxWorkers
) {
return Promise.resolve(this.#workerFactory());
}
return this.#waitForWorker();
}

protected addWorker(
#waitForWorker() {
return new Promise<BaseWorker<M, E>>((resolve, reject) => {
this.#waitQueue.push(
(worker) => resolve(worker),
() =>
reject(
new Error("timeout while waiting for a worker to be available"),
),
);
});
}

protected async delegateTask(
name: string,
taskId: TaskId,
worker: BaseWorker<M, E>,
taskSpec: T,
startedAt: Date,
) {
): Promise<void> {
const worker = await this.#nextWorker();

if (!this.#tasksByName.has(name)) {
this.#tasksByName.set(name, new Set());
}

this.#tasksByName.get(name)!.add(taskId);
this.#activeTasks.set(taskId, { worker, taskSpec });
if (!this.#startedAt.has(taskId)) {
this.#startedAt.set(taskId, startedAt);
this.#startedAt.set(taskId, new Date());
}
}

protected destroyAllWorkers() {
for (const name of this.getActiveTaskNames()) {
this.destroyWorkersByName(name);
protected deallocateAllWorkers(options: DeallocateOptions = {}) {
const activeTaskNames = this.getActiveTaskNames();
if (activeTaskNames.length > 0) {
if (options.destroy) {
logger.warn(
`destroying workers for tasks ${
activeTaskNames.map((w) => `"${w}"`).join(", ")
}`,
);
}
for (const name of activeTaskNames) {
this.deallocateWorkersByName(name, options);
}
}
}

protected destroyWorkersByName(name: string) {
protected deallocateWorkersByName(
name: string,
options: DeallocateOptions = {},
) {
const taskIds = this.#tasksByName.get(name);
if (taskIds) {
for (const taskId of taskIds) {
this.destroyWorker(name, taskId);
this.deallocateWorker(name, taskId, options);
}
return true;
}
return false;
}

protected destroyWorker(name: string, taskId: TaskId) {
deallocateWorker(
name: string,
taskId: TaskId,
{ destroy = false, ensureMinWorkers = true }: DeallocateOptions = {},
) {
const task = this.#activeTasks.get(taskId);
if (this.#tasksByName.has(name)) {
if (!task) {
Expand All @@ -120,14 +190,41 @@ export class BaseWorkerManager<
return false;
}

task.worker.destroy();
this.#activeTasks.delete(taskId);
this.#tasksByName.get(name)!.delete(taskId);
// startedAt records are not deleted

if (destroy) {
task.worker.destroy();

const taskAdded = this.#waitQueue.shift(() => this.#workerFactory());
if (!taskAdded) { // no task from the queue
if (ensureMinWorkers) {
const { minWorkers } = this.#poolConfig;
if (minWorkers != null && this.#workerCount < minWorkers) {
this.#idleWorkers.push(this.#workerFactory());
}
}
}
} else {
const taskAdded = this.#waitQueue.shift(() => task.worker);
if (!taskAdded) { // worker has not been reassigned
const { maxWorkers } = this.#poolConfig;
// how?? xD
// We might add "urgent" tasks in the future;
// in this case the worker count might exceed `maxWorkers`.
if (maxWorkers != null && this.#workerCount >= maxWorkers) {
task.worker.destroy();
} else {
this.#idleWorkers.push(task.worker);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I feel like we should never exceed max but instead ensure it is big enough at start. Not sure how that would fit here but a design idea is to allocate as much as needed with a small room for newer tasks: allocate minAlloc, then if that is not enough and then task is urgent then allocate minAlloc+5, (minAlloc+5)+5, ..., min(minAlloc + 5 + 5 + ..., maxAlloc) etc. 5 is completely arbitrary btw.

}
}
}

return true;
}

logger.warn(`Task with name "${name}" does not exist`);
return false;
}

Expand All @@ -140,6 +237,22 @@ export class BaseWorkerManager<
worker.send(msg);
this.logMessage(taskId, msg);
}

deinit() {
this.deallocateAllWorkers({ destroy: true, ensureMinWorkers: false });
if (this.#idleWorkers.length > 0) {
logger.warn(
`destroying idle workers: ${
this.#idleWorkers.map((w) => `"${w.id}"`).join(", ")
}`,
);
for (const worker of this.#idleWorkers) {
worker.destroy();
}
this.#idleWorkers = [];
}
return Promise.resolve();
}
}

export function createTaskId(name: string) {
Expand Down
Loading
Loading