import assert from 'assert'; import { heapStats } from 'bun:jsc'; import { z, ZodSchema } from 'zod'; import { OVERLAY_ENV } from '../env'; // – // Worker State // – export type WorkerState = { /** The ISO Date string representing when the Worker was created */ createdAt: string; /** The ISO Date string representing when the pending task began */ pendingTaskBeganAt?: string; /** The pending task, if any */ pendingTask?: TaskT; /** The number of tasks the Worker has aborted since it started */ tasksAborted: number; /** The number of tasks the Worker has begun since it started */ tasksBegun: number; /** The number of tasks the Worker has completed since it started */ tasksCompleted: number; }; // – // Work Function // – type WorkFn = ( transition: WorkContext ) => AsyncIterable>; // – // Task State Transitions // – type TaskStateTransitionAbort = { type: 'AbortTask'; task: TaskT; reason: unknown; }; type TaskStateTransitionBegin = { type: 'BeginTask'; task: TaskT }; type TaskStateTransitionComplete = { type: 'CompleteTask'; task: TaskT }; type TaskStateTransition = | TaskStateTransitionAbort | TaskStateTransitionBegin | TaskStateTransitionComplete; // – // Work Context // – type WorkContext = { validateTask(taskData: unknown): TaskT; // Task State Transitions abortTask(task: TaskT, reason: unknown): TaskStateTransitionAbort; beginTask(task: TaskT): TaskStateTransitionBegin; completeTask(task: TaskT): TaskStateTransitionComplete; }; // – // Worker Health Check // – type WorkerHealthCheck = { status: 'OK' | 'ERROR'; workerName: string; workerState: WorkerState; }; // – // Worker Health Check Group // – type WorkerHealthCheckGroup = { status: 'ALL-OK' | 'ERROR'; workers: Record>; runtimeState: Record; }; // – // Worker // – export class Worker< TaskSchemaT extends ZodSchema, TaskT extends z.infer > { promise: Promise; state: WorkerState; taskSchema: TaskSchemaT; workFn: WorkFn; static healthCheckGroup< TaskSchemaT extends ZodSchema, TaskT extends z.infer >( workers: Record> ): WorkerHealthCheckGroup { const runtimeState = { heapStats: heapStats() }; // Transform workers to Record const workerHealthCheckEntries = Object.entries(workers).map( ([key, worker]) => [key, worker.healthCheck()] as const ); const workerHealthChecks = Object.fromEntries(workerHealthCheckEntries); // If any worker's health check status isn't OK, use error status if (workerHealthCheckEntries.some(([, { status }]) => status !== 'OK')) { return { status: 'ERROR', workers: workerHealthChecks, runtimeState }; } // If no worker's health check status is not OK, all is ok return { status: 'ALL-OK', workers: workerHealthChecks, runtimeState }; } constructor(taskSchema: TaskSchemaT, workFn: WorkFn) { this.taskSchema = taskSchema; this.workFn = workFn; // Initialize worker state this.state = { createdAt: new Date().toISOString(), tasksAborted: 0, tasksBegun: 0, tasksCompleted: 0, }; // Run the worker this.promise = this.run(); } private async run() { const workContext: WorkContext = { validateTask: (taskData) => this.taskSchema.parse(taskData), abortTask: (task, reason) => ({ type: 'AbortTask', reason, task }), beginTask: (task) => ({ type: 'BeginTask', task }), completeTask: (task) => ({ type: 'CompleteTask', task }), }; for await (const taskStateTransition of this.workFn(workContext)) { // Assert the task state transition task is valid workContext.validateTask(taskStateTransition.task); // NOTE: Do not require a default case for switching over a discriminating key // eslint-disable-next-line default-case switch (taskStateTransition.type) { case 'BeginTask': assert( !this.state.pendingTask, 'Cannot begin task while there is a pending task. Did you forget to *yield* the previous context.abortTask or context.completeTask?' ); this.beginTask(taskStateTransition.task); break; case 'AbortTask': assert( taskStateTransition.task === this.state.pendingTask, 'Cannot abort a different task than the pending task' ); this.abortPendingTask(); break; case 'CompleteTask': assert( taskStateTransition.task === this.state.pendingTask, 'Cannot complete a different task than the pending task' ); this.completePendingTask(); break; } } } private setPendingTask(task: TaskT) { this.state.pendingTask = task; this.state.pendingTaskBeganAt = new Date().toISOString(); } private clearPendingTask() { this.state.pendingTask = undefined; this.state.pendingTaskBeganAt = undefined; } private beginTask(task: TaskT) { this.setPendingTask(task); this.state.tasksBegun += 1; } private abortPendingTask() { this.clearPendingTask(); this.state.tasksAborted += 1; } private completePendingTask() { this.clearPendingTask(); this.state.tasksCompleted += 1; } healthCheck(): WorkerHealthCheck { // The worker is running, so its status is OK return { status: 'OK', workerName: OVERLAY_ENV.OVERLAY_APP_NAME, workerState: this.state, }; } }