refactor(planning): run planner messages through a swappable job

Prefactoring for a single calculation lifecycle. The job that carries
planner messages becomes a parameter of the calculation entry point, and
a third implementation runs the worker's message handling on the calling
thread, so specs and non-browser callers can use the worker path without
a Worker.

- The worker's message handling moves into a handler with per-instance
  state; the worker entry binds it to its port.
- A passed job factory always takes the worker path, whatever the globals
  say, for the plan, date analyses and the checkpoint explanation.
- The lifecycle registers supersession for every job it starts, so jobs
  implemented outside the module yield to a newer calculation too.
- The in-process job lives in a module the default selection does not
  import: browsers still load the planner core only in the worker bundle.

No calculation path is deleted and no existing spec changes.

Refs #336

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
nessarandClaude Fable 5.2 committed 2026-11-10 19:54:41 +01:00
1 parent ea2feaf766
commit 62df01857c
7 files changed
+850 -134

No files matched your search

+241
View File
@@ -0,0 +1,241 @@
import { vi } from '../../testing/vitest-compat';
import { createInProcessCalculation, scriptedJobs } from '../../testing/planning-jobs';
import { startInProcessJob } from './leave-planner.in-process-job';
import {
createPlanningCalculation,
type PlanOutcome,
type PlanningStateSnapshot,
type WorkerJobFactory,
} from './leave-planner.service';
import { createOptimizationPresetRules } from './rule-service';
const request = { horizon: { start: '2024-01-01', end: '2025-01-01' }, balances: [], rules: [] };
const placement = {
date: '2024-01-05',
balanceId: 'cp',
type: 'cp' as const,
ruleIds: [],
supporting: false,
};
const plan = {
kind: 'Plan',
placements: [placement],
completedStages: [],
} as unknown as PlanOutcome;
const state = { marker: 'state' } as unknown as PlanningStateSnapshot;
const presets = createOptimizationPresetRules();
// Records every Worker and planning socket the default selection constructs.
const constructed: string[] = [];
class RecordingWorker {
onmessage = null;
onerror = null;
constructor() {
constructed.push('worker');
}
postMessage() {}
terminate() {}
}
class RecordingWebSocket {
constructor() {
constructed.push('socket');
}
send() {}
close() {}
}
beforeEach(() => vi.setSystemTime(new Date('2024-01-01T12:00:00Z')));
afterEach(() => {
constructed.length = 0;
vi.unstubAllGlobals();
vi.useRealTimers();
});
describe('calculation job factory', () => {
it.each([
['a window without Worker', {}],
['no window', { window: undefined }],
[
'a Worker and a planning socket',
{ Worker: RecordingWorker, WebSocket: RecordingWebSocket, PLANNING_BUILD: 'build' },
],
])('runs the worker path on a passed factory with %s', async (_, globals) => {
for (const [name, value] of Object.entries(globals)) vi.stubGlobal(name, value);
const { jobs, start } = scriptedJobs();
const calculation = createPlanningCalculation(request, start);
expect(jobs).toHaveLength(1);
expect(jobs[0].posts).toMatchObject([
{ type: 'plan', request: { horizon: request.horizon } },
]);
jobs[0].emit({ type: 'result', outcome: plan });
jobs[0].emit({ type: 'artifacts', artifacts: {} });
expect(await calculation.outcome).toMatchObject({ kind: 'Plan' });
expect(jobs[0].releases).toBe(1);
expect(constructed).toEqual([]);
});
it('keeps the default selection when no factory is passed', async () => {
vi.stubGlobal('Worker', RecordingWorker);
vi.stubGlobal('WebSocket', RecordingWebSocket);
vi.stubGlobal('PLANNING_BUILD', 'build');
createPlanningCalculation(request);
vi.stubGlobal('PLANNING_BUILD', undefined);
createPlanningCalculation(request);
expect(constructed).toEqual(['socket', 'worker']);
vi.stubGlobal('Worker', undefined);
expect(await createPlanningCalculation(request).outcome).toMatchObject({
kind: 'PlanningIncomplete',
reasons: [{ code: 'worker-unavailable' }],
});
});
it('completes a plan and a date analysis on the in-process job under the default test setup', async () => {
expect(typeof window).toBe('object');
expect(typeof Worker).toBe('undefined');
const calculation = createInProcessCalculation({
horizon: { start: '2024-01-01', end: '2024-01-10' },
balances: [{ id: 'cp', type: 'cp', quantity: 1, expiryDate: '2024-01-08' }],
rules: [presets[0]],
});
const outcome = await calculation.outcome;
if (outcome.kind !== 'Plan') throw new Error(`Expected a plan, got ${outcome.kind}`);
expect(outcome.placements).toHaveLength(1);
expect(await calculation.explanation).toMatchObject({ kind: 'PlanExplanation' });
expect(await calculation.timings).toEqual({ planningWorkMs: expect.any(Number) });
const analysis = await calculation.analyzeCounterfactual(outcome.placements[0]);
expect(analysis).toMatchObject({ kind: 'Counterfactual', calculationId: calculation.id });
});
it('posts a date analysis to the passed factory', async () => {
const { jobs, start } = scriptedJobs();
const calculation = createPlanningCalculation(request, start);
jobs[0].emit({ type: 'result', outcome: plan });
jobs[0].emit({ type: 'artifacts', artifacts: { finalState: state } });
const analysis = calculation.analyzeCounterfactual(placement);
await vi.waitFor(() => expect(jobs).toHaveLength(2));
expect(jobs[1].posts).toMatchObject([
{ type: 'counterfactual', request: calculation.snapshot, plan, placement, state },
]);
jobs[1].emit({
type: 'counterfactual-result',
analysis: {
kind: 'Counterfactual',
calculationId: 'job',
placement,
hypothetical: true,
baseline: { objectives: [] },
results: [],
},
});
expect(await analysis).toMatchObject({
kind: 'Counterfactual',
calculationId: calculation.id,
});
expect(jobs[1].releases).toBe(1);
});
it('posts the checkpoint explanation to the passed factory', async () => {
const { jobs, start } = scriptedJobs();
const calculation = createPlanningCalculation(request, start);
jobs[0].emit({ type: 'checkpoint', plan, state });
jobs[0].fail();
expect(await calculation.outcome).toMatchObject({
kind: 'PlanningIncomplete',
incumbent: { kind: 'Plan' },
reasons: [{ code: 'worker-error' }],
});
expect(jobs[0].releases).toBe(1);
expect(jobs[1].posts).toMatchObject([
{
type: 'explain-checkpoint',
request: calculation.snapshot,
plan,
state,
interruption: { code: 'worker-error' },
},
]);
jobs[1].emit({
type: 'explanation',
explanation: {
kind: 'IncompleteExplanation',
reason: { code: 'worker-error', message: 'The worker stopped.' },
completedStages: [],
uncompletedStages: [],
},
});
expect(await calculation.explanation).toMatchObject({ kind: 'IncompleteExplanation' });
expect(jobs[1].releases).toBe(1);
});
});
describe('supersession of jobs from a passed factory', () => {
it('stops a scripted plan with its checkpoint when a newer calculation starts', async () => {
const { jobs, start } = scriptedJobs();
const first = createPlanningCalculation(request, start);
jobs[0].emit({ type: 'checkpoint', plan, state });
createPlanningCalculation(request, start);
expect(await first.outcome).toMatchObject({
kind: 'PlanningIncomplete',
incumbent: { kind: 'Plan', placements: [placement] },
reasons: [{ code: 'stale-calculation' }],
});
expect(await first.explanationError).toMatchObject({ code: 'stale-calculation' });
expect(jobs[0].releases).toBe(1);
expect(jobs[1].releases).toBe(0);
});
it('stops a running in-process plan when a newer calculation starts', async () => {
const releases: number[] = [];
const counted: WorkerJobFactory = (onMessage, onError) => {
const job = startInProcessJob(onMessage, onError);
const index = releases.push(0) - 1;
return {
post: (message, onFailure) => job.post(message, onFailure),
release: () => {
releases[index]++;
job.release();
},
};
};
let started!: () => void;
const running = new Promise<void>((resolve) => (started = resolve));
const first = createPlanningCalculation({ ...request, progress: () => started() }, counted);
await running;
const latest = createPlanningCalculation(request, counted);
expect(await first.outcome).toMatchObject({
kind: 'PlanningIncomplete',
reasons: [{ code: 'stale-calculation' }],
});
expect(releases[0]).toBe(1);
expect(await latest.outcome).toMatchObject({ kind: 'Plan' });
await latest.timings;
expect(releases).toEqual([1, 1]);
});
it('stops a scripted date analysis when a newer calculation starts', async () => {
const { jobs, start } = scriptedJobs();
const calculation = createPlanningCalculation(request, start);
jobs[0].emit({ type: 'result', outcome: plan });
jobs[0].emit({ type: 'artifacts', artifacts: {} });
const analysis = calculation.analyzeCounterfactual(placement);
await vi.waitFor(() => expect(jobs).toHaveLength(2));
createPlanningCalculation(request, start);
expect(await analysis).toMatchObject({ kind: 'CounterfactualStale', placement });
expect(jobs[1].releases).toBe(1);
});
it('stops a scripted checkpoint explanation when a newer calculation starts', async () => {
const { jobs, start } = scriptedJobs();
const calculation = createPlanningCalculation(request, start);
jobs[0].emit({ type: 'checkpoint', plan, state });
jobs[0].fail();
expect(jobs[1].posts).toMatchObject([{ type: 'explain-checkpoint' }]);
createPlanningCalculation(request, start);
expect(await calculation.explanation).toBeUndefined();
expect(await calculation.explanationError).toEqual({
code: 'explanation-error',
message: 'Checkpoint explanation was superseded.',
});
expect(jobs[1].releases).toBe(1);
});
});
@@ -0,0 +1,356 @@
import { execFile } from 'node:child_process';
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
import { promisify } from 'node:util';
import { Worker as NodeWorker } from 'node:worker_threads';
import { startInProcessJob } from './leave-planner.in-process-job';
import { createPlannerMessageHandler } from './leave-planner.message-handler';
import type {
LeaveBalanceInput,
PlanOutcome,
PlanningRule,
PlanningSnapshot,
PlanningStateSnapshot,
WorkerJobFactory,
} from './leave-planner.service';
import {
PLANNING_JOBS,
type WorkerPlanningRequest,
type WorkerRequest,
type WorkerResponse,
} from './leave-planner.worker-messages';
import { createOptimizationPresetRules } from './rule-service';
const presets = createOptimizationPresetRules();
const CANCEL_STAGE = 'optimization:default-non-working-day-gain';
const snapshot = (
horizon: PlanningSnapshot['horizon'],
balances: LeaveBalanceInput[],
rules: PlanningRule[],
): PlanningSnapshot => ({
calculationDate: '2024-01-01',
horizon,
balances,
rules,
identities: {},
labels: {},
});
const completedRequest = snapshot(
{ start: '2024-01-01', end: '2024-03-01' },
[{ id: 'cp', type: 'cp', quantity: 3, expiryDate: '2024-02-15' }],
presets,
);
const conflictRequest = snapshot(
{ start: '2024-01-01', end: '2024-01-10' },
[{ id: 'cp', type: 'cp', quantity: 1, expiryDate: '2024-12-31' }],
[
{
id: 'two-days',
type: 'time_window',
force: 'obligation',
startDate: '2024-01-02',
endDate: '2024-01-03',
placeDays: 2,
placeType: 'cp',
},
],
);
const invalidRequest = snapshot({ start: '2024-02-01', end: '2024-01-01' }, [], []);
const cancelledRequest = snapshot(
{ start: '2024-01-01', end: '2025-01-01' },
[{ id: 'cp', type: 'cp', quantity: 3, expiryDate: '2024-12-31' }],
[
presets[0],
{
id: 'fixed',
type: 'time_window',
force: 'obligation',
startDate: '2024-01-02',
endDate: '2024-01-02',
placeDays: 1,
placeType: 'cp',
},
...presets.slice(1),
],
);
type JobRequest = Exclude<WorkerRequest, { type: 'cancel' }>;
// Runs one request in its own job until a terminal response, cancelling once a stage starts.
function respond(
start: WorkerJobFactory,
request: JobRequest,
cancelAt?: string,
): Promise<WorkerResponse[]> {
return new Promise((done, failed) => {
const responses: WorkerResponse[] = [];
const terminal: readonly string[] = PLANNING_JOBS[request.type].terminal;
const job = start(
(response) => {
responses.push(response);
if (response.type === 'progress' && response.stage === cancelAt)
job.post({ type: 'cancel' }, failed);
if (!terminal.includes(response.type)) return;
job.release();
done(responses);
},
() => failed(new Error('The job failed.')),
);
job.post(request, failed);
});
}
function planRequest(request: WorkerPlanningRequest): JobRequest {
return { type: 'plan', request };
}
// Heartbeats follow the clock, and so does the measured planning work.
function comparable(responses: WorkerResponse[]): WorkerResponse[] {
return responses
.filter(({ type }) => type !== 'heartbeat')
.map((response) =>
response.type === 'artifacts' && response.artifacts.timings
? {
...response,
artifacts: { ...response.artifacts, timings: { planningWorkMs: 0 } },
}
: response,
);
}
function find<T extends WorkerResponse['type']>(responses: WorkerResponse[], type: T) {
return responses.find((response) => response.type === type) as Extract<
WorkerResponse,
{ type: T }
>;
}
describe('in-process planning job', () => {
it('delivers responses in the order the worker handler posts them', async () => {
const posted: WorkerResponse[] = [];
await createPlannerMessageHandler((response) => posted.push(response))(
planRequest(completedRequest),
);
const delivered = await respond(startInProcessJob, planRequest(completedRequest));
expect(comparable(delivered)).toEqual(comparable(posted));
expect(delivered.map(({ type }) => type).slice(-3)).toEqual([
'result',
'explanation',
'artifacts',
]);
});
it('never delivers a response inside post', async () => {
let posting = false;
const deliveredWhilePosting: string[] = [];
const delivered: string[] = [];
const finished = new Promise<void>((done) => {
const job = startInProcessJob(
(response) => {
if (posting) deliveredWhilePosting.push(response.type);
delivered.push(response.type);
if (response.type === 'artifacts') done();
},
() => {},
);
// Invalid input is answered without awaiting, so a synchronous host would deliver here.
posting = true;
job.post(planRequest(invalidRequest), () => {});
posting = false;
});
await finished;
expect(deliveredWhilePosting).toEqual([]);
expect(delivered).toEqual(['heartbeat', 'result', 'artifacts']);
});
it('releases idempotently and silences every later response', async () => {
const delivered: string[] = [];
const job = startInProcessJob(
(response) => {
delivered.push(response.type);
if (response.type !== 'progress') return;
job.release();
job.release();
job.post(planRequest(invalidRequest), () => {});
},
() => {},
);
job.post(planRequest(completedRequest), () => {});
// A complete run of the same request outlasts the released one, which stops at its next pause.
await respond(startInProcessJob, planRequest(completedRequest));
expect(delivered).toEqual(['heartbeat', 'progress']);
});
it('runs two jobs at once without sharing the cancellation state', async () => {
const [cancelled, completed] = await Promise.all([
respond(startInProcessJob, planRequest(cancelledRequest), CANCEL_STAGE),
respond(startInProcessJob, planRequest(cancelledRequest)),
]);
expect(find(cancelled, 'result').outcome).toMatchObject({
kind: 'PlanningIncomplete',
reasons: [{ code: 'user-cancelled' }],
});
expect(find(completed, 'result').outcome).toMatchObject({
kind: 'Plan',
completedStages: expect.arrayContaining([CANCEL_STAGE]),
});
});
it.each([
[
'planner-error',
planRequest({
get horizon(): never {
throw new Error('The request cannot be read.');
},
}),
],
[
'counterfactual-error',
{
type: 'counterfactual',
request: completedRequest,
plan: undefined as unknown as PlanOutcome,
placement: {
date: '2024-01-05',
balanceId: 'cp',
type: 'cp',
ruleIds: [],
supporting: false,
},
} satisfies JobRequest,
],
] as [string, JobRequest][])(
'answers a fault with the worker’s %s response',
async (code, request) => {
const responses = await respond(startInProcessJob, request);
expect(responses.at(-1)).toMatchObject({
type: 'error',
code,
message: expect.any(String),
});
},
);
});
describe('in-process job against the real worker', () => {
let directory: string;
let bundle: string;
const threads = new Set<NodeWorker>();
beforeAll(async () => {
directory = mkdtempSync(join(tmpdir(), 'vac-optimizer-in-process-'));
bundle = join(directory, 'worker.mjs');
const entry = join(directory, 'entry.ts');
writeFileSync(
entry,
`import { parentPort, receiveMessageOnPort, workerData } from 'node:worker_threads';
const pause = new Int32Array(new SharedArrayBuffer(4));
globalThis.self = { postMessage: (message) => {
parentPort.postMessage(message);
// Hold the stage until the host's cancel arrives, so it lands where the in-process job's does.
if (message.type === 'progress' && message.stage === workerData.holdForCancelAtStage) {
let next;
for (let waits = 0; !(next = receiveMessageOnPort(parentPort)); waits++) {
if (waits > 5000) throw new Error('The host never sent the cancel request.');
Atomics.wait(pause, 0, 0, 1);
}
globalThis.self.onmessage({ data: next.message });
}
} };
await import(${JSON.stringify(resolve('src/app/services/leave-planner.worker.ts'))});
parentPort.on('message', (data) => globalThis.self.onmessage({ data }));
`,
);
await promisify(execFile)(process.execPath, [
'build',
entry,
'--target=node',
'--outfile',
bundle,
]);
});
afterAll(async () => {
await Promise.all([...threads].map((thread) => thread.terminate()));
rmSync(directory, { recursive: true, force: true });
});
const inWorkerThread =
(holdForCancelAtStage?: string): WorkerJobFactory =>
(onMessage, onError) => {
const thread = new NodeWorker(bundle, { workerData: { holdForCancelAtStage } });
threads.add(thread);
thread.on('message', onMessage);
thread.on('error', () => onError());
return {
post: (message) => thread.postMessage(message),
release: () => void thread.terminate(),
};
};
const bothWays = async (request: JobRequest, cancelAt?: string) => {
const inProcess = await respond(startInProcessJob, request, cancelAt);
const inWorker = await respond(inWorkerThread(cancelAt), request, cancelAt);
expect(comparable(inProcess)).toEqual(comparable(inWorker));
return inProcess;
};
it.each([
['a completed plan', completedRequest, undefined, { kind: 'Plan' }],
['a planning conflict', conflictRequest, undefined, { kind: 'PlanningConflict' }],
['invalid input', invalidRequest, undefined, { kind: 'InvalidInput' }],
[
'a cancel in the middle of a run',
cancelledRequest,
CANCEL_STAGE,
{
kind: 'PlanningIncomplete',
incumbent: { kind: 'Plan' },
reasons: [{ code: 'user-cancelled' }],
},
],
])('answers %s with the same responses', async (_, request, cancelAt, outcome) => {
const responses = await bothWays(planRequest(request), cancelAt);
expect(find(responses, 'result').outcome).toMatchObject(outcome);
});
it('answers a date analysis, a checkpoint explanation and a faulty analysis with the same responses', async () => {
const completed = await respond(startInProcessJob, planRequest(completedRequest));
const plan = find(completed, 'result').outcome as PlanOutcome;
const finalState = find(completed, 'artifacts').artifacts.finalState;
const checkpoint = find(completed, 'checkpoint');
expect(plan.placements.length).toBeGreaterThan(0);
expect(checkpoint.plan.completedStages).not.toContain('dates');
const analysis = await bothWays({
type: 'counterfactual',
request: completedRequest,
plan,
placement: plan.placements[0],
state: finalState,
});
expect(find(analysis, 'counterfactual-result').analysis.results.length).toBeGreaterThan(0);
const explanation = await bothWays({
type: 'explain-checkpoint',
request: completedRequest,
plan: checkpoint.plan,
state: checkpoint.state as PlanningStateSnapshot,
interruption: { code: 'worker-error', message: 'The worker stopped.' },
});
expect(find(explanation, 'explanation').explanation).toMatchObject({
kind: 'PlanExplanation',
incomplete: { reason: { code: 'worker-error' } },
});
const fault = await bothWays({
type: 'counterfactual',
request: completedRequest,
plan: undefined as unknown as PlanOutcome,
placement: plan.placements[0],
});
expect(find(fault, 'error')).toMatchObject({ code: 'counterfactual-error' });
});
});
@@ -0,0 +1,30 @@
import { createPlannerMessageHandler } from './leave-planner.message-handler';
import type { WorkerJobFactory } from './leave-planner.service';
/**
* Runs the planner worker's message handling on the calling thread, for tests and callers without
* a browser. The default job selection never imports it, so browsers load the planner core only in
* the worker bundle.
*/
export const startInProcessJob: WorkerJobFactory = (onMessage) => {
let released = false;
// Microtasks keep delivery in order and outside post, with no timer delay.
const handle = createPlannerMessageHandler((response) =>
queueMicrotask(() => {
if (!released) onMessage(response);
}),
);
return {
post(message) {
queueMicrotask(() => {
if (!released) void handle(message);
});
},
release() {
if (released) return;
released = true;
// Stops a running plan, as terminating a worker does.
void handle({ type: 'cancel' });
},
};
};
@@ -0,0 +1,102 @@
import type { PlanningOutcome } from './leave-planner.service';
import type { WorkerRequest, WorkerResponse } from './leave-planner.worker-messages';
import {
analyzeCounterfactualInternal,
calculatePlanningAsyncInternal,
explainIncompleteCheckpoint,
type PlanningArtifacts,
} from './leave-planner.core';
/** The planner worker's message handling, hosted by the worker entry or by an in-process job. */
export function createPlannerMessageHandler(
post: (response: WorkerResponse) => void,
): (request: WorkerRequest | undefined) => Promise<void> {
// Per handler, not per module: one process may host several jobs at once.
let activeCalculation: { cancelled: boolean } | undefined;
return async (request) => {
try {
if (request?.type === 'cancel') {
if (activeCalculation) activeCalculation.cancelled = true;
return;
}
if (request?.type === 'plan') {
const calculation = { cancelled: false };
activeCalculation = calculation;
let artifacts: PlanningArtifacts = {};
let outcomePosted = false;
let outcome: PlanningOutcome;
// The cooperative driver yields during preparation and search, even within one phase.
const heartbeat = () => post({ type: 'heartbeat' });
const heartbeatTimer = setInterval(heartbeat, 1000);
try {
heartbeat();
outcome = await calculatePlanningAsyncInternal(
{
...request.request,
progress: (stage: string) => post({ type: 'progress', stage }),
},
(plan, state) => post({ type: 'checkpoint', plan, state }),
(value) => (artifacts = value),
(value) => {
outcomePosted = true;
post({ type: 'result', outcome: value });
},
(explanation, explanationError, finalState) =>
post({
type: 'explanation',
explanation,
explanationError,
finalState,
}),
() => calculation.cancelled,
);
} catch (error) {
post({
type: 'error',
code: 'planner-error',
message: error instanceof Error ? error.message : String(error),
});
return;
} finally {
clearInterval(heartbeatTimer);
if (activeCalculation === calculation) activeCalculation = undefined;
}
if (!outcomePosted) post({ type: 'result', outcome });
post({ type: 'artifacts', artifacts });
return;
}
if (request?.type === 'explain-checkpoint') {
const result = explainIncompleteCheckpoint(
request.request,
request.plan,
request.state,
request.interruption,
);
post({ type: 'explanation', ...result });
return;
}
if (request?.type !== 'counterfactual') return;
try {
const analysis = analyzeCounterfactualInternal(
request.request,
request.plan,
request.placement,
request.state,
);
post({ type: 'counterfactual-result', analysis });
} catch (error) {
post({
type: 'error',
code: 'counterfactual-error',
message: error instanceof Error ? error.message : String(error),
});
}
} catch (error) {
post({
type: 'error',
code: 'worker-error',
message: error instanceof Error ? error.message : String(error),
});
}
};
}
+62 -22
View File
@@ -308,14 +308,38 @@ function interruptedOutcome(
const latestWorkerCancels = new Set<() => void>();
let latestCounterfactualCancel: (() => void) | undefined;
interface WorkerJob {
/** Carries one job's planner messages; implementations do transport only. */
export interface WorkerJob {
post(message: WorkerRequest, onFailure: (error: unknown) => void): void;
release(): void;
}
// Single owner of a worker's lifetime: creation, handlers, cancellation registration and an idempotent release.
function startLocalJob(
/** Starts a job, or throws when it cannot start. */
export type WorkerJobFactory = (
onMessage: (message: WorkerResponse) => void,
onError: (reason?: PlanningReason) => void,
) => WorkerJob;
// The lifecycle, not the job, registers supersession, so jobs from any factory yield to a newer calculation.
function startSupersedableJob(
startJob: WorkerJobFactory,
supersede: () => void,
onMessage: (message: WorkerResponse) => void,
onError: (reason?: PlanningReason) => void,
): WorkerJob {
const job = startJob(onMessage, onError);
latestWorkerCancels.add(supersede);
return {
post: (message, onFailure) => job.post(message, onFailure),
release() {
job.release();
latestWorkerCancels.delete(supersede);
},
};
}
// Single owner of a worker's lifetime: creation, handlers and an idempotent release.
function startLocalJob(
onMessage: (message: WorkerResponse) => void,
onError: () => void,
): WorkerJob {
@@ -329,7 +353,6 @@ function startLocalJob(
worker.onerror = () => {
onError();
};
latestWorkerCancels.add(supersede);
return {
post(message, onFailure) {
try {
@@ -344,7 +367,6 @@ function startLocalJob(
worker.onmessage = null;
worker.onerror = null;
worker.terminate();
latestWorkerCancels.delete(supersede);
},
};
}
@@ -377,7 +399,6 @@ function planningSocketUrl(build: string): string {
// One same-origin socket per job; falls back to a local worker, replaying the posts, until the server first answers.
function startRemoteJob(
build: string,
supersede: () => void,
onMessage: (message: WorkerResponse) => void,
onError: (reason?: PlanningReason) => void,
): WorkerJob {
@@ -385,7 +406,7 @@ function startRemoteJob(
try {
socket = new WebSocket(planningSocketUrl(build));
} catch {
return startLocalJob(supersede, onMessage, onError);
return startLocalJob(onMessage, onError);
}
type Post = { message: WorkerRequest; onFailure: (error: unknown) => void };
let released = false;
@@ -422,7 +443,7 @@ function startRemoteJob(
clearTimeout(connectTimer);
closeSocket();
try {
local = startLocalJob(supersede, onMessage, onError);
local = startLocalJob(onMessage, onError);
} catch {
ended = true;
onError();
@@ -466,7 +487,6 @@ function startRemoteJob(
// A close always follows an error event, and only the close carries the code.
socket.onclose = (event: CloseEvent) =>
lose(SERVER_FAULT_CLOSES.includes(event.code) ? undefined : CONNECTION_LOST);
latestWorkerCancels.add(supersede);
return {
post(message, onFailure) {
if (released || ended) return;
@@ -482,21 +502,19 @@ function startRemoteJob(
clearTimeout(connectTimer);
closeSocket();
local?.release();
latestWorkerCancels.delete(supersede);
},
};
}
function startWorkerJob(
supersede: () => void,
onMessage: (message: WorkerResponse) => void,
onError: (reason?: PlanningReason) => void,
): WorkerJob {
// Without a build identifier (development, tests) no server can match, so skip the socket.
const build = planningBuild();
return build === undefined || typeof WebSocket === 'undefined'
? startLocalJob(supersede, onMessage, onError)
: startRemoteJob(build, supersede, onMessage, onError);
? startLocalJob(onMessage, onError)
: startRemoteJob(build, onMessage, onError);
}
function cancelLatestWorkers(): void {
@@ -505,7 +523,7 @@ function cancelLatestWorkers(): void {
latestCounterfactualCancel = undefined;
}
function planInWorker(snapshot: TransportSnapshot): PlanningRun {
function planInWorker(snapshot: TransportSnapshot, startJob: WorkerJobFactory): PlanningRun {
let resolveOutcome!: (outcome: PlanningOutcome) => void;
let resolveExplanation!: (explanation: PlanningExplanation | undefined) => void;
let resolveExplanationError!: (error: PlanningReason | undefined) => void;
@@ -528,7 +546,8 @@ function planInWorker(snapshot: TransportSnapshot): PlanningRun {
});
let cancel: (() => void) | undefined;
try {
const job = startWorkerJob(
const job = startSupersedableJob(
startJob,
() => supersede(),
(message) => handleMessage(message),
(reason) =>
@@ -644,6 +663,7 @@ function planInWorker(snapshot: TransportSnapshot): PlanningRun {
if (!explanationSettled && checkpoint && checkpointState) {
finishArtifacts({ explanationError: reason, finalState: checkpointState }, false);
void explainCheckpointInWorker(
startJob,
publicSnapshot(snapshot),
checkpoint,
checkpointState,
@@ -769,6 +789,7 @@ async function runCounterfactual(
selection: CounterfactualSelection,
artifacts: Promise<PlanningArtifacts>,
isCurrent: () => boolean,
startJob: WorkerJobFactory | undefined,
): Promise<CounterfactualAnalysis | StaleCounterfactualAnalysis> {
const stale = (placement: LeavePlacement): StaleCounterfactualAnalysis => ({
kind: 'CounterfactualStale',
@@ -814,10 +835,11 @@ async function runCounterfactual(
if (!placement) throw new Error('The selected placement is not present in the calculation.');
const completedArtifacts = await artifacts;
if (context.id !== latestCalculationId || !isCurrent()) return stale(placement);
if (typeof window !== 'undefined' && typeof Worker !== 'undefined') {
if (startJob || (typeof window !== 'undefined' && typeof Worker !== 'undefined')) {
let result: CounterfactualAnalysis;
try {
result = await counterfactualInWorker(
startJob ?? startWorkerJob,
context.snapshot,
plan,
placement,
@@ -843,6 +865,7 @@ async function runCounterfactual(
}
function counterfactualInWorker(
startJob: WorkerJobFactory,
snapshot: PlanningSnapshot,
plan: PlanOutcome,
placement: LeavePlacement,
@@ -862,7 +885,8 @@ function counterfactualInWorker(
const cancel = () =>
finish(() => reject(new Error('Counterfactual analysis was superseded.')));
try {
job = startWorkerJob(
job = startSupersedableJob(
startJob,
cancel,
(message) => {
if (message.type === 'counterfactual-result' && message.analysis)
@@ -891,6 +915,7 @@ function counterfactualInWorker(
}
function explainCheckpointInWorker(
startJob: WorkerJobFactory,
snapshot: PlanningSnapshot,
plan: PlanOutcome,
state: PlanningStateSnapshot,
@@ -906,7 +931,8 @@ function explainCheckpointInWorker(
callback();
};
try {
job = startWorkerJob(
job = startSupersedableJob(
startJob,
() => finish(() => reject(new Error('Checkpoint explanation was superseded.'))),
(response) => {
if (response.type === 'explanation')
@@ -946,7 +972,15 @@ export interface PlanningCalculationContext {
) => Promise<CounterfactualAnalysis | StaleCounterfactualAnalysis>;
}
export function createPlanningCalculation(request: PlanningRequest): PlanningCalculationContext {
/**
* Starts a calculation whose plan, date analyses and checkpoint explanation run in jobs from
* `startJob`. A passed factory always takes the worker path, whatever the globals say; without one,
* the globals choose the path and the default job.
*/
export function createPlanningCalculation(
request: PlanningRequest,
startJob?: WorkerJobFactory,
): PlanningCalculationContext {
const calculationDate = planningDateInParis(new Date());
cancelLatestWorkers();
const transport = { ...snapshotRequest(request), calculationDate };
@@ -963,10 +997,12 @@ export function createPlanningCalculation(request: PlanningRequest): PlanningCal
artifacts: Promise.resolve({}),
timings: Promise.resolve({}),
};
} else if (startJob) {
run = planInWorker(transport, startJob);
} else {
if (typeof window !== 'undefined') {
if (typeof Worker !== 'undefined') {
run = planInWorker(transport);
run = planInWorker(transport, startWorkerJob);
} else {
let resolveArtifacts!: (artifacts: PlanningArtifacts) => void;
let resolveExplanation!: (explanation: PlanningExplanation | undefined) => void;
@@ -1157,12 +1193,16 @@ export function createPlanningCalculation(request: PlanningRequest): PlanningCal
selection,
run.artifacts,
() => sequence === counterfactualSequence,
startJob,
);
},
};
return context;
}
export async function planLeave(request: PlanningRequest): Promise<PlanningOutcome> {
return createPlanningCalculation(request).outcome;
export async function planLeave(
request: PlanningRequest,
startJob?: WorkerJobFactory,
): Promise<PlanningOutcome> {
return createPlanningCalculation(request, startJob).outcome;
}
+4 -112
View File
@@ -1,117 +1,9 @@
/// <reference lib="webworker" />
import type { PlanningOutcome } from './leave-planner.service';
import type { WorkerRequest, WorkerResponse } from './leave-planner.worker-messages';
import {
analyzeCounterfactualInternal,
calculatePlanningAsyncInternal,
explainIncompleteCheckpoint,
type PlanningArtifacts,
} from './leave-planner.core';
import type { WorkerRequest } from './leave-planner.worker-messages';
import { createPlannerMessageHandler } from './leave-planner.message-handler';
const worker = self as DedicatedWorkerGlobalScope;
let activeCalculation: { cancelled: boolean } | undefined;
const handle = createPlannerMessageHandler((response) => worker.postMessage(response));
worker.onmessage = async (event: MessageEvent<WorkerRequest>) => {
try {
if (event.data?.type === 'cancel') {
if (activeCalculation) activeCalculation.cancelled = true;
return;
}
if (event.data?.type === 'plan') {
const calculation = { cancelled: false };
activeCalculation = calculation;
let artifacts: PlanningArtifacts = {};
let outcomePosted = false;
let outcome: PlanningOutcome;
// The cooperative driver yields during preparation and search, even within one phase.
const heartbeat = () =>
worker.postMessage({ type: 'heartbeat' } satisfies WorkerResponse);
const heartbeatTimer = setInterval(heartbeat, 1000);
try {
heartbeat();
outcome = await calculatePlanningAsyncInternal(
{
...event.data.request,
progress: (stage: string) =>
worker.postMessage({
type: 'progress',
stage,
} satisfies WorkerResponse),
},
(plan, state) =>
worker.postMessage({
type: 'checkpoint',
plan,
state,
} satisfies WorkerResponse),
(value) => (artifacts = value),
(value) => {
outcomePosted = true;
worker.postMessage({
type: 'result',
outcome: value,
} satisfies WorkerResponse);
},
(explanation, explanationError, finalState) =>
worker.postMessage({
type: 'explanation',
explanation,
explanationError,
finalState,
} satisfies WorkerResponse),
() => calculation.cancelled,
);
} catch (error) {
worker.postMessage({
type: 'error',
code: 'planner-error',
message: error instanceof Error ? error.message : String(error),
} satisfies WorkerResponse);
return;
} finally {
clearInterval(heartbeatTimer);
if (activeCalculation === calculation) activeCalculation = undefined;
}
if (!outcomePosted)
worker.postMessage({ type: 'result', outcome } satisfies WorkerResponse);
worker.postMessage({ type: 'artifacts', artifacts } satisfies WorkerResponse);
return;
}
if (event.data?.type === 'explain-checkpoint') {
const result = explainIncompleteCheckpoint(
event.data.request,
event.data.plan,
event.data.state,
event.data.interruption,
);
worker.postMessage({ type: 'explanation', ...result } satisfies WorkerResponse);
return;
}
if (event.data?.type !== 'counterfactual') return;
try {
const analysis = analyzeCounterfactualInternal(
event.data.request,
event.data.plan,
event.data.placement,
event.data.state,
);
worker.postMessage({
type: 'counterfactual-result',
analysis,
} satisfies WorkerResponse);
} catch (error) {
worker.postMessage({
type: 'error',
code: 'counterfactual-error',
message: error instanceof Error ? error.message : String(error),
} satisfies WorkerResponse);
}
} catch (error) {
worker.postMessage({
type: 'error',
code: 'worker-error',
message: error instanceof Error ? error.message : String(error),
} satisfies WorkerResponse);
}
};
worker.onmessage = (event: MessageEvent<WorkerRequest>) => handle(event.data);
+55
View File
@@ -0,0 +1,55 @@
import { startInProcessJob } from '../app/services/leave-planner.in-process-job';
import {
createPlanningCalculation,
type PlanningCalculationContext,
type PlanningReason,
type PlanningRequest,
type WorkerJob,
type WorkerJobFactory,
} from '../app/services/leave-planner.service';
import type { WorkerRequest, WorkerResponse } from '../app/services/leave-planner.worker-messages';
/** A job a test drives by hand: it records posts and releases, and emits what the test scripts. */
export class ScriptedJob implements WorkerJob {
readonly posts: WorkerRequest[] = [];
releases = 0;
constructor(
private readonly onMessage: (message: WorkerResponse) => void,
private readonly onError: (reason?: PlanningReason) => void,
) {}
post(message: WorkerRequest): void {
this.posts.push(message);
}
release(): void {
this.releases++;
}
emit(response: WorkerResponse): void {
this.onMessage(response);
}
/** Fails the job as a crashed worker (no reason) or a lost connection does. */
fail(reason?: PlanningReason): void {
this.onError(reason);
}
}
/** A factory of scripted jobs and every job it started, in start order. */
export function scriptedJobs(): { start: WorkerJobFactory; jobs: ScriptedJob[] } {
const jobs: ScriptedJob[] = [];
return {
jobs,
start: (onMessage, onError) => {
const job = new ScriptedJob(onMessage, onError);
jobs.push(job);
return job;
},
};
}
export function createInProcessCalculation(request: PlanningRequest): PlanningCalculationContext {
return createPlanningCalculation(request, startInProcessJob);
}