feat(planning): calculate plans on the server over a WebSocket
Each worker job (a plan, an incomplete-checkpoint explanation or a counterfactual analysis) opens one same-origin socket at /api/planning that carries the existing worker protocol as JSON. The Bun server runs the unchanged planner worker in a Bun Worker per socket and terminates it when the socket closes. The production build ships the worker as its own entry point next to server.js. On the client the socket is a second worker job, so liveness, cancellation, checkpoints, explanations and supersession are unchanged. Until the server first answers, a socket that fails, does not open within 5 seconds or is closed falls back to a local worker and replays the messages posted so far. A connection lost afterwards gives an incomplete calculation with the retained plan, without a retry. Request dates go out as Europe/Paris dates, as the core reads a Date. Closes #320 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
dbc612336b
commit
e2a5a6f0e8
9 files changed
+1041
-26
No files matched your search
@@ -17,14 +17,24 @@ The planner answers these questions:
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
Host["Bun static server<br/>client assets"] -. serves .-> UI
|
||||
subgraph Server
|
||||
Host["Bun static server<br/>client assets + planning sockets"]
|
||||
ServerWorker["Leave-planner Bun Worker"]
|
||||
ServerCore["Resumable planner core"]
|
||||
ServerHolidays["date-holidays<br/>French public calendar"]
|
||||
|
||||
Host -- "one worker per socket" --> ServerWorker
|
||||
ServerWorker --> ServerCore
|
||||
ServerCore --> ServerHolidays
|
||||
end
|
||||
|
||||
subgraph Browser
|
||||
UI["Angular standalone components"]
|
||||
State["Signals + localStorage<br/>settings, balances, rules"]
|
||||
Duration["Indicative duration<br/>session-local calibration"]
|
||||
Facade["Planning calculation context<br/>immutable snapshot + async artifacts"]
|
||||
Worker["Leave-planner Web Worker"]
|
||||
Socket["Planning socket<br/>same-origin WebSocket"]
|
||||
Worker["Leave-planner Web Worker<br/>local fallback"]
|
||||
Core["Resumable planner core"]
|
||||
Holidays["date-holidays<br/>French public calendar"]
|
||||
|
||||
@@ -33,26 +43,31 @@ flowchart LR
|
||||
Duration -- "estimated wait" --> UI
|
||||
UI -- "rendered-calendar timing" --> Duration
|
||||
UI -- "Calculate / Cancel" --> Facade
|
||||
Facade -- "request / cancellation" --> Worker
|
||||
Facade -- "request / cancellation" --> Socket
|
||||
Socket -- "/api/planning" --> ServerWorker
|
||||
Facade -. "no socket or no early server message" .-> Worker
|
||||
Worker --> Core
|
||||
Core --> Holidays
|
||||
Worker -- "heartbeats, progress, checkpoints, outcome" --> Facade
|
||||
Worker -- "after outcome: stable explanation + final state" --> Facade
|
||||
Socket -- "heartbeats, progress, checkpoints, outcome" --> Facade
|
||||
Socket -- "after outcome: stable explanation + final state" --> Facade
|
||||
Worker -- "same messages as the socket" --> Facade
|
||||
Facade --> UI
|
||||
end
|
||||
|
||||
Host -. serves .-> UI
|
||||
```
|
||||
|
||||
Leave calculation stays in the browser. The production Bun process serves the generated client-only Angular application; it does not participate in planning. Browser calculations run cooperatively in a dedicated worker. The resumable core is emitted as a separate worker/lazy chunk and retains a synchronous adapter for direct core callers. The original decision trace and historical analysis were removed in issue #76; immutable checkpoints and final state remain available for cancellation recovery and displayed-placement alternatives.
|
||||
Leave calculation runs on the server by default, for every device, so the wait does not depend on the device. The production Bun process serves the generated client-only Angular application and accepts one planning WebSocket per worker job (a plan, an incomplete-checkpoint explanation or a counterfactual analysis) at `/api/planning`; each socket runs the planner worker in a Bun Worker. If the socket cannot open, does not open within about 5 seconds, or closes before sending any message, the browser starts its own Web Worker without notice and replays the messages posted so far, including an early Cancel. Under `ng serve`, which has no backend, calculations therefore run locally. The resumable core is emitted as a separate worker/lazy chunk and retains a synchronous adapter for direct core callers. The original decision trace and historical analysis were removed in issue #76; immutable checkpoints and final state remain available for cancellation recovery and displayed-placement alternatives.
|
||||
|
||||
### Main execution path
|
||||
|
||||
1. `PlanningDurationService` reads the pending horizon, balances, and ordered rules to estimate the wait without running the planner.
|
||||
2. On startup or an explicit Calculate action, `CalendarYear` submits those inputs through `CalendarService`, which opens one immutable planning calculation context.
|
||||
3. `leave-planner.service.ts` copies the request into a canonical transport shape and starts the worker.
|
||||
4. `leave-planner.worker.ts` runs the framework-free core, sends progress and valid checkpoints, publishes the outcome first, then delivers its stable explanation and final state.
|
||||
3. `leave-planner.service.ts` copies the request into a canonical transport shape, including the Europe/Paris calendar date it fixes, and starts a worker job. The job opens the planning socket at `/api/planning`, or starts the local Web Worker on fallback.
|
||||
4. `leave-planner.worker.ts` runs the framework-free core in the server's Bun Worker (or in the browser fallback), sends progress and valid checkpoints, publishes the outcome first, then delivers its stable explanation and final state.
|
||||
5. `CalendarYear` ignores stale calculations, renders the selected dates, reports remaining balances or errors, and records successful request-to-rendered-calendar timing for duration refinement.
|
||||
|
||||
Calculations run until all objectives complete or the user cancels; there is no automatic elapsed-time cutoff. During preparation and optimization, Cancel interrupts the worker cooperatively and preserves its best jointly valid candidate as a cancelled, incomplete calculation. A cancellation before a valid candidate reports no plan. The final calendar is delivered before the stable explanation, whose later arrival or failure cannot change the retained plan. Worker heartbeats distinguish responsive long phases from a worker that stops responding. See [the cancellation mechanism and checks](docs/planner-cancellation.md).
|
||||
Calculations run until all objectives complete or the user cancels; there is no automatic elapsed-time cutoff. During preparation and optimization, Cancel interrupts the worker cooperatively and preserves its best jointly valid candidate as a cancelled, incomplete calculation. A cancellation before a valid candidate reports no plan. The final calendar is delivered before the stable explanation, whose later arrival or failure cannot change the retained plan. Worker heartbeats distinguish responsive long phases from a worker that stops responding. A connection lost after the first server message gives an incomplete calculation with the best valid plan already received, without an automatic retry; the person can calculate again. See [the cancellation mechanism and checks](docs/planner-cancellation.md).
|
||||
|
||||
Technical callers may explicitly supply `deadlineMs`, a finite non-negative planning-work budget of any size. Omission means no deadline; the calendar and benchmark never supply one. This opt-in budget starts after calendar preparation and excludes observer callbacks and post-outcome explanation work. Expiry returns `PlanningIncomplete` with the latest valid checkpoint, if any, rather than a conflict. It is independent of worker liveness monitoring.
|
||||
|
||||
@@ -159,12 +174,12 @@ Incomplete outcomes explain the retained plan and unfinished phases; conflicts i
|
||||
- Angular Material and CDK
|
||||
- Signals for UI state and local storage for settings, edited leave balances, and rules
|
||||
- TypeScript 6
|
||||
- Web Workers for planner isolation
|
||||
- Bun Workers on the server and Web Workers in the browser for planner isolation; the Web Worker is the local fallback
|
||||
- `date-holidays` for the French public calendar
|
||||
- Bun for dependency management and project scripts
|
||||
- `bun test` with jsdom and Angular TestBed (JIT)
|
||||
- ESLint and Prettier, run by Bun, and `bun check` for standalone type checking
|
||||
- Client-only Angular build served by a small `Bun.serve` static server (`src/server.ts`)
|
||||
- Client-only Angular build served by a small `Bun.serve` static server (`src/server.ts`), which also accepts planning WebSockets at `/api/planning`
|
||||
- Gitea repository hosting and a multi-stage Docker image
|
||||
|
||||
The `/benchmark` route and planner core are lazy-loaded, so the normal application does not execute the benchmark or bundle the planner core into its main entry point.
|
||||
@@ -181,7 +196,7 @@ src/app/
|
||||
├── components/ # Calendar, inputs, rules, and settings UI
|
||||
├── services/
|
||||
│ ├── leave-planner.service.ts # Canonical async planning boundary
|
||||
│ ├── leave-planner.worker.ts # Browser worker adapter
|
||||
│ ├── leave-planner.worker.ts # Worker entry: server Bun Worker and browser fallback
|
||||
│ ├── leave-planner.core.ts # Framework-free planning algorithm
|
||||
│ ├── calendar-service.ts # Calendar projection and UI integration
|
||||
│ ├── calendar-settings-service.ts # Persisted horizon and week-number settings
|
||||
@@ -241,9 +256,9 @@ docker build -t vac-optimizer .
|
||||
docker run --rm -p 4000:4000 vac-optimizer
|
||||
```
|
||||
|
||||
The image builds the Angular application and the server bundle with Bun alone (no Node), then runs `dist/vac-optimizer/server/server.js` with Bun. The bundle has no runtime dependencies, so the production stage only copies `dist/` and installs nothing. Set `PORT` to override the default port `4000`; the health check requests `/`.
|
||||
The image builds the Angular application and the server bundle with Bun alone (no Node), then runs `dist/vac-optimizer/server/server.js` with Bun. The server bundle also includes `leave-planner.worker.js` next to `server.js`, which the server starts for each planning socket. The bundle has no runtime dependencies, so the production stage only copies `dist/` and installs nothing. Set `PORT` to override the default port `4000`; the health check requests `/`.
|
||||
|
||||
The server answers `GET` and `HEAD` only (other methods get 405). It serves files from `dist/vac-optimizer/browser` with `Cache-Control: public, max-age=31536000` (content-hashed assets), and returns `index.html` with `Cache-Control: no-cache` for `/index.html` and for every extension-less path, so direct navigation to client routes such as `/benchmark` works. A missing path with a file extension is a 404 rather than HTML, malformed or escaping paths are a 400, and unexpected failures are logged and answered with a plain 500.
|
||||
The server answers `GET` and `HEAD` only (other methods get 405), except at `/api/planning`: a WebSocket upgrade there opens a planning socket, and any other request there gets `426 Upgrade Required`. Behind a reverse proxy, forward WebSocket upgrades for `/api/planning`; on Nginx Proxy Manager, enable WebSocket support for the host. The server serves files from `dist/vac-optimizer/browser` with `Cache-Control: public, max-age=31536000` (content-hashed assets), and returns `index.html` with `Cache-Control: no-cache` for `/index.html` and for every extension-less path, so direct navigation to client routes such as `/benchmark` works. A missing path with a file extension is a 404 rather than HTML, malformed or escaping paths are a 400, and unexpected failures are logged and answered with a plain 500.
|
||||
|
||||
## Continuous integration
|
||||
|
||||
@@ -296,8 +311,9 @@ Run `bun scripts/ci-policy.test.mjs` and `bun scripts/ci-image.test.mjs` locally
|
||||
|
||||
- [CONTEXT.md](CONTEXT.md) defines the project vocabulary and planner semantics.
|
||||
- [ADR 0001](docs/adr/0001-ordered-heuristic-optimization.md) records the ordered heuristic decision.
|
||||
- [ADR 0002](docs/adr/0002-personal-client-side-planner-for-now.md) records the client-side scope.
|
||||
- [ADR 0002](docs/adr/0002-personal-client-side-planner-for-now.md) records the original client-side scope, superseded by ADR 0011.
|
||||
- [ADR 0003](docs/adr/0003-constraint-first-lexicographic-planning.md) records the constraint-first planner architecture.
|
||||
- [ADR 0004](docs/adr/0004-stable-explanation-original-trace-counterfactual.md) separates the outcome, stable explanation and displayed-placement hypothetical analysis.
|
||||
- [ADR 0005](docs/adr/0005-saved-planning-inputs-before-random-defaults.md) records saved-input restoration and random fallback behavior.
|
||||
- [ADR 0006](docs/adr/0006-user-selected-horizons-and-cancellable-calculations.md) records fixed saved horizons, cancellation, duration estimation, and the removal of the automatic deadline.
|
||||
- [ADR 0011](docs/adr/0011-server-side-planning-for-every-device.md) records server-side planning for every device with a local fallback.
|
||||
@@ -220,7 +220,9 @@ Issue #76 removes all trace timing, status and candidate-count columns, along wi
|
||||
tree until a human records it here.
|
||||
|
||||
The browser page uses the same `createPlanningCalculation(request)` context as
|
||||
the calendar and adds no solver or backend dependency. It omits `deadlineMs`.
|
||||
the calendar, so it measures the path the app uses: a server calculation over
|
||||
the planning WebSocket, with the local engine as fallback. It omits `deadlineMs`.
|
||||
The `bun test` protocol and its budget specs keep running against the local engine.
|
||||
Explanation delivery is independent of the outcome and cannot replace a valid plan.
|
||||
|
||||
`planning_ms` is the observed latency until the outcome is usable. `planning_work_ms` excludes observer callbacks and post-outcome explanation work. `wall_ms` includes preparation, outcome and explanation delivery. `max_ui_delay_ms` covers this entire interval; there is no decision recording, trace materialization or trace transfer.
|
||||
|
||||
+1
-1
@@ -6,7 +6,7 @@
|
||||
"ng": "ng",
|
||||
"start": "bun scripts/generate-langs.js && ng serve",
|
||||
"build": "bun scripts/generate-langs.js && ng build",
|
||||
"postbuild": "bun build src/server.ts --target=bun --outfile dist/vac-optimizer/server/server.js",
|
||||
"postbuild": "bun build src/server.ts src/app/services/leave-planner.worker.ts --target=bun --outdir dist/vac-optimizer/server --entry-naming '[name].[ext]'",
|
||||
"watch": "bun scripts/generate-langs.js && ng build --watch --configuration development",
|
||||
"test": "bun scripts/generate-langs.js && bun test --isolate",
|
||||
"serve": "bun dist/vac-optimizer/server/server.js",
|
||||
|
||||
@@ -0,0 +1,316 @@
|
||||
import { vi } from '../../testing/vitest-compat';
|
||||
import {
|
||||
createPlanningCalculation,
|
||||
type LeavePlacement,
|
||||
type PlanningCalculationContext,
|
||||
type PlanningRequest,
|
||||
} from './leave-planner.service';
|
||||
|
||||
const request = { horizon: { start: '2024-01-01', end: '2025-01-01' }, balances: [], rules: [] };
|
||||
const plan = {
|
||||
kind: 'Plan',
|
||||
placements: [{ date: '2024-01-05', balanceId: 'cp' } as unknown as LeavePlacement],
|
||||
completedStages: [],
|
||||
};
|
||||
const state = { marker: 'state' };
|
||||
const flush = () => vi.advanceTimersByTimeAsync(0);
|
||||
|
||||
type Sent = { type: string; request: { horizon: { start: string } } };
|
||||
|
||||
class FakeWebSocket {
|
||||
static all: FakeWebSocket[] = [];
|
||||
static constructThrows = false;
|
||||
static readonly CONNECTING = 0;
|
||||
static readonly OPEN = 1;
|
||||
static readonly CLOSING = 2;
|
||||
static readonly CLOSED = 3;
|
||||
readyState = FakeWebSocket.CONNECTING;
|
||||
url: string;
|
||||
send = vi.fn();
|
||||
close = vi.fn();
|
||||
onopen: (() => void) | null = null;
|
||||
onmessage: ((event: { data: unknown }) => void) | null = null;
|
||||
onerror: (() => void) | null = null;
|
||||
onclose: ((event: { code: number }) => void) | null = null;
|
||||
constructor(url: string) {
|
||||
if (FakeWebSocket.constructThrows) throw new Error('no socket');
|
||||
this.url = url;
|
||||
FakeWebSocket.all.push(this);
|
||||
}
|
||||
accept() {
|
||||
this.readyState = FakeWebSocket.OPEN;
|
||||
this.onopen?.();
|
||||
}
|
||||
emit(data: unknown) {
|
||||
this.onmessage?.({ data: JSON.stringify(data) });
|
||||
}
|
||||
drop(code: number) {
|
||||
this.readyState = FakeWebSocket.CLOSED;
|
||||
this.onclose?.({ code });
|
||||
}
|
||||
fail() {
|
||||
this.onerror?.();
|
||||
this.drop(1006);
|
||||
}
|
||||
sent(): Sent[] {
|
||||
return this.send.mock.calls.map(([data]) => JSON.parse(data as string) as Sent);
|
||||
}
|
||||
sentTypes(): string[] {
|
||||
return this.sent().map((message) => message.type);
|
||||
}
|
||||
}
|
||||
|
||||
class FakeWorker {
|
||||
static all: FakeWorker[] = [];
|
||||
onmessage: ((event: MessageEvent) => void) | null = null;
|
||||
onerror: (() => void) | null = null;
|
||||
terminate = vi.fn();
|
||||
postMessage = vi.fn();
|
||||
constructor() {
|
||||
FakeWorker.all.push(this);
|
||||
}
|
||||
emit(data: unknown) {
|
||||
this.onmessage?.({ data } as MessageEvent);
|
||||
}
|
||||
postedTypes(): string[] {
|
||||
return this.postMessage.mock.calls.map(([message]) => (message as { type: string }).type);
|
||||
}
|
||||
}
|
||||
|
||||
const sockets = () => FakeWebSocket.all;
|
||||
const finish = (target: { emit(data: unknown): void }, outcome: unknown = plan) => {
|
||||
target.emit({ type: 'result', outcome });
|
||||
target.emit({ type: 'artifacts', artifacts: {} });
|
||||
};
|
||||
const cancelled = {
|
||||
kind: 'PlanningIncomplete',
|
||||
incumbent: plan,
|
||||
completedStages: [],
|
||||
reasons: [{ code: 'user-cancelled', message: 'cancelled' }],
|
||||
};
|
||||
|
||||
describe('remote planning job', () => {
|
||||
beforeEach(() => {
|
||||
FakeWebSocket.all = [];
|
||||
FakeWebSocket.constructThrows = false;
|
||||
FakeWorker.all = [];
|
||||
vi.useFakeTimers();
|
||||
vi.stubGlobal('window', {});
|
||||
vi.stubGlobal('Worker', FakeWorker);
|
||||
vi.stubGlobal('WebSocket', FakeWebSocket);
|
||||
});
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
it('runs a plan over the socket by default', async () => {
|
||||
const progress = vi.fn();
|
||||
const calculation = createPlanningCalculation({ ...request, progress });
|
||||
const [socket] = sockets();
|
||||
expect(socket.url).toBe('ws://localhost:3000/api/planning');
|
||||
expect(socket.send).not.toHaveBeenCalled();
|
||||
socket.accept();
|
||||
expect(socket.sentTypes()).toEqual(['plan']);
|
||||
expect(FakeWorker.all).toHaveLength(0);
|
||||
socket.emit({ type: 'heartbeat' });
|
||||
socket.emit({ type: 'progress', stage: 'optimization' });
|
||||
socket.emit({ type: 'checkpoint', plan, state });
|
||||
socket.emit({ type: 'result', outcome: plan });
|
||||
expect(socket.close).not.toHaveBeenCalled();
|
||||
socket.emit({ type: 'artifacts', artifacts: {} });
|
||||
expect(await calculation.outcome).toMatchObject({ kind: 'Plan' });
|
||||
expect(progress).toHaveBeenCalledExactlyOnceWith('optimization');
|
||||
expect(socket.close).toHaveBeenCalledOnce();
|
||||
expect(socket.onmessage).toBeNull();
|
||||
socket.emit({ type: 'progress', stage: 'late' });
|
||||
socket.fail();
|
||||
expect(progress).toHaveBeenCalledOnce();
|
||||
expect(sockets()).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('falls back to the local worker, replaying the plan and an early cancel', async () => {
|
||||
const calculation = createPlanningCalculation(request);
|
||||
const [socket] = sockets();
|
||||
calculation.cancel();
|
||||
socket.fail();
|
||||
const [worker] = FakeWorker.all;
|
||||
expect(socket.close).toHaveBeenCalledOnce();
|
||||
expect(worker.postedTypes()).toEqual(['plan', 'cancel']);
|
||||
finish(worker, cancelled);
|
||||
expect(await calculation.outcome).toMatchObject({
|
||||
kind: 'PlanningIncomplete',
|
||||
incumbent: plan,
|
||||
reasons: [{ code: 'user-cancelled' }],
|
||||
});
|
||||
expect(worker.terminate).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('falls back to the local worker when the connection does not open in time', async () => {
|
||||
const calculation = createPlanningCalculation(request);
|
||||
const [socket] = sockets();
|
||||
await vi.advanceTimersByTimeAsync(4999);
|
||||
expect(FakeWorker.all).toHaveLength(0);
|
||||
await vi.advanceTimersByTimeAsync(1);
|
||||
expect(socket.close).toHaveBeenCalledOnce();
|
||||
expect(socket.send).not.toHaveBeenCalled();
|
||||
expect(FakeWorker.all).toHaveLength(1);
|
||||
expect(FakeWorker.all[0].postedTypes()).toEqual(['plan']);
|
||||
finish(FakeWorker.all[0]);
|
||||
expect(await calculation.outcome).toMatchObject({ kind: 'Plan' });
|
||||
});
|
||||
|
||||
it.each([4409, 4429, 1000])(
|
||||
'falls back to the local worker when the server closes with %i before any message',
|
||||
async (code) => {
|
||||
const calculation = createPlanningCalculation(request);
|
||||
const [socket] = sockets();
|
||||
socket.accept();
|
||||
calculation.cancel();
|
||||
expect(socket.sentTypes()).toEqual(['plan', 'cancel']);
|
||||
socket.drop(code);
|
||||
const [worker] = FakeWorker.all;
|
||||
expect(worker.postedTypes()).toEqual(['plan', 'cancel']);
|
||||
finish(worker, cancelled);
|
||||
expect(await calculation.outcome).toMatchObject({ kind: 'PlanningIncomplete' });
|
||||
},
|
||||
);
|
||||
|
||||
it('falls back to the local worker when the first message is not JSON', async () => {
|
||||
const calculation = createPlanningCalculation(request);
|
||||
const [socket] = sockets();
|
||||
socket.accept();
|
||||
socket.onmessage?.({ data: 'not json' });
|
||||
expect(socket.close).toHaveBeenCalledOnce();
|
||||
expect(FakeWorker.all[0].postedTypes()).toEqual(['plan']);
|
||||
finish(FakeWorker.all[0]);
|
||||
expect(await calculation.outcome).toMatchObject({ kind: 'Plan' });
|
||||
});
|
||||
|
||||
it('uses the local worker immediately when the socket cannot be constructed', async () => {
|
||||
FakeWebSocket.constructThrows = true;
|
||||
const calculation = createPlanningCalculation(request);
|
||||
expect(sockets()).toHaveLength(0);
|
||||
expect(FakeWorker.all[0].postedTypes()).toEqual(['plan']);
|
||||
finish(FakeWorker.all[0]);
|
||||
expect(await calculation.outcome).toMatchObject({ kind: 'Plan' });
|
||||
});
|
||||
|
||||
it('keeps the checkpoint plan when the connection is lost after the first message', async () => {
|
||||
const calculation = createPlanningCalculation(request);
|
||||
const [socket] = sockets();
|
||||
socket.accept();
|
||||
socket.emit({ type: 'heartbeat' });
|
||||
socket.emit({ type: 'checkpoint', plan, state });
|
||||
socket.drop(1006);
|
||||
expect(await calculation.outcome).toMatchObject({
|
||||
kind: 'PlanningIncomplete',
|
||||
incumbent: plan,
|
||||
reasons: [{ code: 'worker-error' }],
|
||||
});
|
||||
expect(FakeWorker.all).toHaveLength(0);
|
||||
const sentTypes = sockets().flatMap((candidate) => candidate.sentTypes());
|
||||
expect(sentTypes.filter((type) => type === 'plan')).toHaveLength(1);
|
||||
expect(socket.sentTypes()).toEqual(['plan']);
|
||||
});
|
||||
|
||||
it('reports a lost connection once and ignores later events', async () => {
|
||||
const progress = vi.fn();
|
||||
const calculation = createPlanningCalculation({ ...request, progress });
|
||||
const [socket] = sockets();
|
||||
socket.accept();
|
||||
socket.emit({ type: 'heartbeat' });
|
||||
socket.fail();
|
||||
const outcome = await calculation.outcome;
|
||||
socket.emit({ type: 'progress', stage: 'late' });
|
||||
socket.drop(1006);
|
||||
expect(progress).not.toHaveBeenCalled();
|
||||
expect(await calculation.outcome).toBe(outcome);
|
||||
expect(sockets()).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('cancels over the socket and resolves with the cancelled outcome', async () => {
|
||||
const calculation = createPlanningCalculation(request);
|
||||
const [socket] = sockets();
|
||||
socket.accept();
|
||||
socket.emit({ type: 'heartbeat' });
|
||||
calculation.cancel();
|
||||
expect(socket.sent().at(-1)).toEqual({ type: 'cancel' });
|
||||
finish(socket, cancelled);
|
||||
expect(await calculation.outcome).toMatchObject({
|
||||
kind: 'PlanningIncomplete',
|
||||
incumbent: plan,
|
||||
reasons: [{ code: 'user-cancelled' }],
|
||||
});
|
||||
expect(socket.close).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('closes the first socket when a newer calculation supersedes it', async () => {
|
||||
const first = createPlanningCalculation(request);
|
||||
const second = createPlanningCalculation(request);
|
||||
const [firstSocket, secondSocket] = sockets();
|
||||
expect(firstSocket.close).toHaveBeenCalledOnce();
|
||||
expect(secondSocket.close).not.toHaveBeenCalled();
|
||||
expect(await first.outcome).toMatchObject({
|
||||
kind: 'PlanningIncomplete',
|
||||
reasons: [{ code: 'stale-calculation' }],
|
||||
});
|
||||
secondSocket.accept();
|
||||
finish(secondSocket);
|
||||
expect(await second.outcome).toMatchObject({ kind: 'Plan' });
|
||||
});
|
||||
|
||||
it('runs counterfactual analysis on its own socket', async () => {
|
||||
const calculation = createPlanningCalculation(request);
|
||||
const [planSocket] = sockets();
|
||||
planSocket.accept();
|
||||
finish(planSocket);
|
||||
await calculation.timings;
|
||||
const analysis = (calculation as PlanningCalculationContext).analyzeCounterfactual(
|
||||
plan.placements[0],
|
||||
);
|
||||
await flush();
|
||||
const socket = sockets()[1];
|
||||
socket.accept();
|
||||
expect(socket.sentTypes()).toEqual(['counterfactual']);
|
||||
socket.emit({ type: 'counterfactual-result', analysis: { results: [] } });
|
||||
expect(await analysis).toMatchObject({ results: [] });
|
||||
expect(socket.close).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('runs the checkpoint explanation on its own socket after a lost connection', async () => {
|
||||
const calculation = createPlanningCalculation(request);
|
||||
const [planSocket] = sockets();
|
||||
planSocket.accept();
|
||||
planSocket.emit({ type: 'checkpoint', plan, state });
|
||||
planSocket.drop(1006);
|
||||
const socket = sockets()[1];
|
||||
socket.accept();
|
||||
expect(socket.sentTypes()).toEqual(['explain-checkpoint']);
|
||||
socket.emit({ type: 'explanation', explanation: { kind: 'IncompleteExplanation' } });
|
||||
expect(await calculation.explanation).toMatchObject({ kind: 'IncompleteExplanation' });
|
||||
expect(socket.close).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('sends Date values as Paris calendar dates', () => {
|
||||
createPlanningCalculation({
|
||||
...request,
|
||||
horizon: { start: new Date('2023-12-31T23:30:00Z'), end: '2025-01-01' },
|
||||
} as unknown as PlanningRequest);
|
||||
const [socket] = sockets();
|
||||
socket.accept();
|
||||
expect(socket.sent()[0].request.horizon.start).toBe('2024-01-01');
|
||||
});
|
||||
|
||||
it('is not tripped by the liveness timer while heartbeats keep arriving', async () => {
|
||||
const calculation = createPlanningCalculation(request);
|
||||
const [socket] = sockets();
|
||||
socket.accept();
|
||||
for (let second = 0; second < 35; second++) {
|
||||
socket.emit({ type: 'heartbeat' });
|
||||
await vi.advanceTimersByTimeAsync(1000);
|
||||
}
|
||||
finish(socket);
|
||||
expect(await calculation.outcome).toMatchObject({ kind: 'Plan' });
|
||||
});
|
||||
});
|
||||
@@ -313,7 +313,7 @@ interface WorkerJob {
|
||||
}
|
||||
|
||||
// Single owner of a worker's lifetime: creation, handlers, cancellation registration and an idempotent release.
|
||||
function startWorkerJob(
|
||||
function startLocalJob(
|
||||
supersede: () => void,
|
||||
onMessage: (message: WorkerResponse) => void,
|
||||
onError: () => void,
|
||||
@@ -348,6 +348,145 @@ function startWorkerJob(
|
||||
};
|
||||
}
|
||||
|
||||
const PLANNING_CONNECT_TIMEOUT_MS = 5_000;
|
||||
|
||||
// Dates go out as Paris calendar dates: the core reads the leading date of the ISO string, which is UTC.
|
||||
function encodePlanningMessage(message: WorkerRequest): string {
|
||||
return JSON.stringify(message, function (this: Record<string, unknown>, key, value: unknown) {
|
||||
const original = this[key];
|
||||
return original instanceof Date && !Number.isNaN(original.getTime())
|
||||
? planningDateInParis(original)
|
||||
: value;
|
||||
});
|
||||
}
|
||||
|
||||
function planningSocketUrl(): string {
|
||||
const url = new URL('/api/planning', location.href);
|
||||
url.protocol = url.protocol === 'https:' ? 'wss:' : 'ws:';
|
||||
return url.href;
|
||||
}
|
||||
|
||||
// One same-origin socket per job; falls back to a local worker, replaying the posts, until the server first answers.
|
||||
function startRemoteJob(
|
||||
supersede: () => void,
|
||||
onMessage: (message: WorkerResponse) => void,
|
||||
onError: () => void,
|
||||
): WorkerJob {
|
||||
let socket: WebSocket;
|
||||
try {
|
||||
socket = new WebSocket(planningSocketUrl());
|
||||
} catch {
|
||||
return startLocalJob(supersede, onMessage, onError);
|
||||
}
|
||||
type Post = { message: WorkerRequest; onFailure: (error: unknown) => void };
|
||||
let released = false;
|
||||
let ended = false;
|
||||
let opened = false;
|
||||
let heard = false;
|
||||
let local: WorkerJob | undefined;
|
||||
let queue: Post[] = [];
|
||||
let log: Post[] = [];
|
||||
const detach = () => {
|
||||
socket.onopen = null;
|
||||
socket.onmessage = null;
|
||||
socket.onerror = null;
|
||||
socket.onclose = null;
|
||||
};
|
||||
const closeSocket = () => {
|
||||
detach();
|
||||
try {
|
||||
socket.close();
|
||||
} catch {
|
||||
// Nothing left to release.
|
||||
}
|
||||
};
|
||||
const send = ({ message, onFailure }: Post) => {
|
||||
try {
|
||||
socket.send(encodePlanningMessage(message));
|
||||
} catch (error) {
|
||||
onFailure(error);
|
||||
}
|
||||
};
|
||||
const connectTimer = setTimeout(() => fallBack(), PLANNING_CONNECT_TIMEOUT_MS);
|
||||
const fallBack = () => {
|
||||
if (released || ended || local) return;
|
||||
clearTimeout(connectTimer);
|
||||
closeSocket();
|
||||
try {
|
||||
local = startLocalJob(supersede, onMessage, onError);
|
||||
} catch {
|
||||
ended = true;
|
||||
onError();
|
||||
return;
|
||||
}
|
||||
const replay = log;
|
||||
log = [];
|
||||
queue = [];
|
||||
for (const { message, onFailure } of replay) local.post(message, onFailure);
|
||||
};
|
||||
const lose = () => {
|
||||
if (!heard) return fallBack();
|
||||
if (released || ended) return;
|
||||
ended = true;
|
||||
closeSocket();
|
||||
onError();
|
||||
};
|
||||
socket.onopen = () => {
|
||||
clearTimeout(connectTimer);
|
||||
opened = true;
|
||||
const buffered = queue;
|
||||
queue = [];
|
||||
for (const post of buffered) send(post);
|
||||
};
|
||||
socket.onmessage = (event: MessageEvent) => {
|
||||
if (released || ended) return;
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = typeof event.data === 'string' ? JSON.parse(event.data) : undefined;
|
||||
} catch {
|
||||
parsed = undefined;
|
||||
}
|
||||
if (typeof parsed !== 'object' || parsed === null) return lose();
|
||||
if (!heard) {
|
||||
heard = true;
|
||||
clearTimeout(connectTimer);
|
||||
log = [];
|
||||
}
|
||||
onMessage(parsed as WorkerResponse);
|
||||
};
|
||||
socket.onerror = lose;
|
||||
socket.onclose = lose;
|
||||
latestWorkerCancels.add(supersede);
|
||||
return {
|
||||
post(message, onFailure) {
|
||||
if (released || ended) return;
|
||||
if (local) return local.post(message, onFailure);
|
||||
const post = { message, onFailure };
|
||||
if (!heard) log.push(post);
|
||||
if (opened) send(post);
|
||||
else queue.push(post);
|
||||
},
|
||||
release() {
|
||||
if (released) return;
|
||||
released = true;
|
||||
clearTimeout(connectTimer);
|
||||
closeSocket();
|
||||
local?.release();
|
||||
latestWorkerCancels.delete(supersede);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function startWorkerJob(
|
||||
supersede: () => void,
|
||||
onMessage: (message: WorkerResponse) => void,
|
||||
onError: () => void,
|
||||
): WorkerJob {
|
||||
return typeof WebSocket === 'undefined'
|
||||
? startLocalJob(supersede, onMessage, onError)
|
||||
: startRemoteJob(supersede, onMessage, onError);
|
||||
}
|
||||
|
||||
function cancelLatestWorkers(): void {
|
||||
for (const cancel of [...latestWorkerCancels]) cancel();
|
||||
latestWorkerCancels.clear();
|
||||
|
||||
@@ -0,0 +1,261 @@
|
||||
import { afterAll, beforeAll, describe, expect, it } from 'bun:test';
|
||||
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { benchmarkScenarios } from './app/benchmark/leave-planner-benchmark';
|
||||
import {
|
||||
createPlanningCalculation,
|
||||
type PlanningCalculationContext,
|
||||
type PlanningOutcome,
|
||||
type PlanningRequest,
|
||||
} from './app/services/leave-planner.service';
|
||||
import { createServer } from './server';
|
||||
import { BunWebSocket, BunWorker } from './test-setup';
|
||||
import { vi } from './testing/vitest-compat';
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
type Message = { type: string; [key: string]: any };
|
||||
|
||||
const WORKER_URL = new URL('./app/services/leave-planner.worker.ts', import.meta.url);
|
||||
const CALCULATION_DATE = '2024-01-01';
|
||||
const scenarios = benchmarkScenarios();
|
||||
|
||||
let workdir: string;
|
||||
let server: ReturnType<typeof createServer>;
|
||||
const workers: RecordingWorker[] = [];
|
||||
const sockets: RecordingWebSocket[] = [];
|
||||
|
||||
// Every worker of the process: the server's planner workers and, in local runs, the client's.
|
||||
class RecordingWorker extends BunWorker {
|
||||
// The client's local worker is the only one created with module options.
|
||||
readonly local: boolean;
|
||||
terminated = false;
|
||||
readonly received: Message[] = [];
|
||||
readonly posted: Message[] = [];
|
||||
|
||||
constructor(url: string | URL, options?: WorkerOptions) {
|
||||
super(url, options);
|
||||
this.local = options?.type === 'module';
|
||||
this.addEventListener('message', (event) => this.received.push(event.data));
|
||||
workers.push(this);
|
||||
}
|
||||
|
||||
override postMessage(message: unknown, ...rest: unknown[]) {
|
||||
this.posted.push(message as Message);
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
(super.postMessage as any)(message, ...rest);
|
||||
}
|
||||
|
||||
override terminate() {
|
||||
this.terminated = true;
|
||||
return super.terminate();
|
||||
}
|
||||
}
|
||||
|
||||
class RecordingWebSocket extends BunWebSocket {
|
||||
readonly received: Message[] = [];
|
||||
readonly sent: Message[] = [];
|
||||
|
||||
constructor(url: string | URL) {
|
||||
super(url);
|
||||
this.addEventListener('message', (event) =>
|
||||
this.received.push(JSON.parse(String(event.data))),
|
||||
);
|
||||
sockets.push(this);
|
||||
}
|
||||
|
||||
override send(data: string) {
|
||||
this.sent.push(JSON.parse(data));
|
||||
super.send(data);
|
||||
}
|
||||
}
|
||||
|
||||
function scenarioRequest(name: string): PlanningRequest {
|
||||
const scenario = scenarios.find((candidate) => candidate.name === name);
|
||||
if (!scenario) throw new Error(`Unknown scenario ${name}`);
|
||||
return structuredClone(scenario.request);
|
||||
}
|
||||
|
||||
const sentTypes = (socket: RecordingWebSocket) => socket.sent.map((message) => message.type);
|
||||
const hasReceived = (socket: RecordingWebSocket | undefined, type: string) =>
|
||||
socket?.received.some((message) => message.type === type) ?? false;
|
||||
|
||||
async function settle(calculation: PlanningCalculationContext) {
|
||||
const outcome = await calculation.outcome;
|
||||
const explanation = await calculation.explanation;
|
||||
await calculation.timings;
|
||||
return { outcome, explanation };
|
||||
}
|
||||
|
||||
async function runRemote(request: PlanningRequest) {
|
||||
vi.stubGlobal('WebSocket', RecordingWebSocket);
|
||||
const firstSocket = sockets.length;
|
||||
const firstWorker = workers.length;
|
||||
const calculation = createPlanningCalculation(request);
|
||||
const settled = await settle(calculation);
|
||||
const socket = sockets
|
||||
.slice(firstSocket)
|
||||
.find((candidate) => sentTypes(candidate).includes('plan'));
|
||||
return { calculation, ...settled, socket, createdWorkers: workers.slice(firstWorker) };
|
||||
}
|
||||
|
||||
async function runLocal(request: PlanningRequest) {
|
||||
vi.stubGlobal('WebSocket', undefined);
|
||||
const firstSocket = sockets.length;
|
||||
const firstWorker = workers.length;
|
||||
const calculation = createPlanningCalculation(request);
|
||||
const settled = await settle(calculation);
|
||||
const worker = workers.slice(firstWorker).find((candidate) => candidate.local);
|
||||
return { calculation, ...settled, worker, createdSockets: sockets.slice(firstSocket) };
|
||||
}
|
||||
|
||||
const finalStateOf = (messages: Message[] = []) =>
|
||||
messages.find((message) => message.type === 'artifacts')?.['artifacts'].finalState;
|
||||
|
||||
function placementOf(outcome: PlanningOutcome) {
|
||||
if (outcome.kind !== 'Plan') throw new Error(`Unexpected ${outcome.kind}`);
|
||||
return outcome.placements[0];
|
||||
}
|
||||
|
||||
describe('server-side planning equivalence', () => {
|
||||
beforeAll(() => {
|
||||
workdir = mkdtempSync(join(tmpdir(), 'server-planning-'));
|
||||
writeFileSync(join(workdir, 'index.html'), '<!doctype html><title>fixture app</title>');
|
||||
vi.stubGlobal('Worker', RecordingWorker);
|
||||
server = createServer({ root: workdir, port: 0, planning: { worker: WORKER_URL } });
|
||||
vi.stubGlobal('window', {});
|
||||
vi.stubGlobal('location', new URL(server.url));
|
||||
// The server clock stays real: only the client's date may decide.
|
||||
vi.setSystemTime(new Date('2024-01-01T12:00:00Z'));
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
vi.useRealTimers();
|
||||
vi.unstubAllGlobals();
|
||||
await server?.stop(true);
|
||||
rmSync(workdir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it.each(scenarios.map((scenario) => scenario.name))(
|
||||
'plans %s on the server exactly as in a local worker',
|
||||
async (name) => {
|
||||
const remote = await runRemote(scenarioRequest(name));
|
||||
const local = await runLocal(scenarioRequest(name));
|
||||
|
||||
expect(hasReceived(remote.socket, 'result')).toBe(true);
|
||||
expect(remote.createdWorkers.filter((worker) => worker.local)).toEqual([]);
|
||||
expect(local.createdSockets).toEqual([]);
|
||||
expect(local.worker).toBeDefined();
|
||||
|
||||
expect(remote.outcome).toEqual(local.outcome);
|
||||
expect(remote.explanation).toEqual(local.explanation);
|
||||
const remoteState = finalStateOf(remote.socket?.received);
|
||||
// A conflict explains nothing, so it ends without a final state on both sides.
|
||||
if (remote.outcome.kind !== 'PlanningConflict') expect(remoteState).toBeDefined();
|
||||
expect(remoteState).toEqual(finalStateOf(local.worker?.received));
|
||||
expect(remote.outcome).toMatchObject({ calculationDate: CALCULATION_DATE });
|
||||
},
|
||||
60_000,
|
||||
);
|
||||
|
||||
it('analyses a placement over its own socket like a local worker', async () => {
|
||||
const remote = await runRemote(scenarioRequest('typed obligations'));
|
||||
const placement = placementOf(remote.outcome);
|
||||
expect(placement).toBeDefined();
|
||||
|
||||
const firstSocket = sockets.length;
|
||||
const analysis = await remote.calculation.analyzeCounterfactual(placement);
|
||||
const analysisSockets = sockets.slice(firstSocket);
|
||||
expect(analysisSockets).toHaveLength(1);
|
||||
expect(sentTypes(analysisSockets[0])).toEqual(['counterfactual']);
|
||||
expect(hasReceived(analysisSockets[0], 'counterfactual-result')).toBe(true);
|
||||
|
||||
// A newer calculation makes older analyses stale, so the local one runs last.
|
||||
const local = await runLocal(scenarioRequest('typed obligations'));
|
||||
const localAnalysis = await local.calculation.analyzeCounterfactual(
|
||||
placementOf(local.outcome),
|
||||
);
|
||||
|
||||
expect(analysis).toMatchObject({ calculationId: remote.calculation.id });
|
||||
expect({ ...analysis, calculationId: undefined }).toEqual({
|
||||
...localAnalysis,
|
||||
calculationId: undefined,
|
||||
});
|
||||
}, 60_000);
|
||||
|
||||
it('cancels a server calculation and terminates its worker', async () => {
|
||||
vi.stubGlobal('WebSocket', RecordingWebSocket);
|
||||
const firstSocket = sockets.length;
|
||||
const firstWorker = workers.length;
|
||||
const calculation = createPlanningCalculation(scenarioRequest('loaded year'));
|
||||
const planSocket = () =>
|
||||
sockets.slice(firstSocket).find((candidate) => sentTypes(candidate).includes('plan'));
|
||||
await vi.waitFor(() => expect(hasReceived(planSocket(), 'checkpoint')).toBe(true), {
|
||||
timeout: 30_000,
|
||||
});
|
||||
calculation.cancel();
|
||||
|
||||
const outcome = await calculation.outcome;
|
||||
expect(outcome).toMatchObject({
|
||||
kind: 'PlanningIncomplete',
|
||||
incumbent: expect.anything(),
|
||||
reasons: [{ code: 'user-cancelled' }],
|
||||
});
|
||||
const explanation = await calculation.explanation;
|
||||
expect(['PlanExplanation', 'IncompleteExplanation']).toContain(explanation?.kind);
|
||||
expect(explanation).toMatchObject({
|
||||
incomplete: expect.anything(),
|
||||
});
|
||||
|
||||
const serverWorkers = workers.slice(firstWorker).filter((worker) => !worker.local);
|
||||
expect(serverWorkers).toHaveLength(1);
|
||||
await vi.waitFor(() => expect(serverWorkers[0].terminated).toBe(true), { timeout: 10_000 });
|
||||
}, 60_000);
|
||||
|
||||
it('reports a lost connection with its last checkpoint and never retries', async () => {
|
||||
vi.stubGlobal('WebSocket', RecordingWebSocket);
|
||||
const firstSocket = sockets.length;
|
||||
const firstWorker = workers.length;
|
||||
const calculation = createPlanningCalculation(scenarioRequest('loaded year'));
|
||||
const planSocket = () =>
|
||||
sockets.slice(firstSocket).find((candidate) => sentTypes(candidate).includes('plan'));
|
||||
await vi.waitFor(() => expect(hasReceived(planSocket(), 'checkpoint')).toBe(true), {
|
||||
timeout: 30_000,
|
||||
});
|
||||
const socket = planSocket()!;
|
||||
socket.close();
|
||||
|
||||
const outcome = await calculation.outcome;
|
||||
expect(outcome).toMatchObject({
|
||||
kind: 'PlanningIncomplete',
|
||||
reasons: [{ code: 'worker-error' }],
|
||||
});
|
||||
// Closing detaches the client, so no checkpoint arrives after the one it last saw.
|
||||
const checkpoint = socket.received
|
||||
.filter((message) => message.type === 'checkpoint')
|
||||
.at(-1);
|
||||
expect(outcome.kind === 'PlanningIncomplete' ? outcome.incumbent : undefined).toEqual(
|
||||
checkpoint?.['plan'],
|
||||
);
|
||||
|
||||
expect(await calculation.explanation).toBeDefined();
|
||||
const explainSockets = sockets
|
||||
.slice(firstSocket)
|
||||
.filter((candidate) => sentTypes(candidate).includes('explain-checkpoint'));
|
||||
expect(explainSockets).toHaveLength(1);
|
||||
expect(explainSockets[0]).not.toBe(socket);
|
||||
|
||||
const created = workers.slice(firstWorker).filter((worker) => !worker.local);
|
||||
await vi.waitFor(() => expect(created.every((worker) => worker.terminated)).toBe(true), {
|
||||
timeout: 10_000,
|
||||
});
|
||||
const plansSent = sockets
|
||||
.slice(firstSocket)
|
||||
.flatMap((candidate) => candidate.sent.filter((message) => message.type === 'plan'));
|
||||
const plansRun = created.flatMap((worker) =>
|
||||
worker.posted.filter((message) => message.type === 'plan'),
|
||||
);
|
||||
expect(plansSent).toHaveLength(1);
|
||||
expect(plansRun).toHaveLength(1);
|
||||
}, 60_000);
|
||||
});
|
||||
+193
-1
@@ -3,7 +3,10 @@ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
|
||||
import { connect } from 'node:net';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { calculatePlanningAsyncInternal } from './app/services/leave-planner.core';
|
||||
import { createServer } from './server';
|
||||
import { BunWebSocket, BunWorker } from './test-setup';
|
||||
import { vi } from './testing/vitest-compat';
|
||||
|
||||
const INDEX = '<!doctype html><title>fixture app</title>';
|
||||
const SECRET = 'top-secret-outside-the-root';
|
||||
@@ -13,6 +16,96 @@ const IMMUTABLE = 'public, max-age=31536000';
|
||||
let workdir: string;
|
||||
let server: ReturnType<typeof createServer>;
|
||||
let emptyServer: ReturnType<typeof createServer>;
|
||||
const workers: CountingWorker[] = [];
|
||||
|
||||
// Records each server worker so a test can tell whether its own was terminated.
|
||||
class CountingWorker extends BunWorker {
|
||||
terminated = false;
|
||||
|
||||
constructor(...args: ConstructorParameters<typeof Worker>) {
|
||||
super(...args);
|
||||
workers.push(this);
|
||||
}
|
||||
|
||||
override terminate() {
|
||||
this.terminated = true;
|
||||
return super.terminate();
|
||||
}
|
||||
}
|
||||
|
||||
const PLAN = {
|
||||
calculationDate: '2024-01-01',
|
||||
horizon: { start: '2024-01-01', end: '2024-03-31' },
|
||||
balances: [
|
||||
{
|
||||
id: 'cp',
|
||||
type: 'cp',
|
||||
quantity: 3,
|
||||
availableFrom: '2024-01-01',
|
||||
expiryDate: '2024-12-31',
|
||||
},
|
||||
],
|
||||
// An exact window makes the plan hold placements, which the counterfactual job needs.
|
||||
rules: [
|
||||
{
|
||||
id: 'cp-window',
|
||||
type: 'time_window',
|
||||
force: 'obligation',
|
||||
startDate: '2024-03-01',
|
||||
endDate: '2024-03-05',
|
||||
placeDays: 2,
|
||||
placeType: 'cp',
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
type Message = { type: string; [key: string]: any };
|
||||
|
||||
// A planning client; `until` resolves with every message up to the first one of that type.
|
||||
function planningSocket(base: URL) {
|
||||
const url = new URL('/api/planning', base);
|
||||
url.protocol = 'ws:';
|
||||
const socket = new BunWebSocket(url);
|
||||
const received: Message[] = [];
|
||||
const waiters: (() => void)[] = [];
|
||||
const closed = new Promise<{ code: number }>((resolve) =>
|
||||
socket.addEventListener('close', (event) => resolve({ code: event.code })),
|
||||
);
|
||||
const opened = new Promise<void>((resolve, reject) => {
|
||||
socket.addEventListener('open', () => resolve());
|
||||
socket.addEventListener('error', () => reject(new Error('socket error')));
|
||||
});
|
||||
socket.addEventListener('message', (event) => {
|
||||
received.push(JSON.parse(String(event.data)));
|
||||
waiters.splice(0).forEach((wake) => wake());
|
||||
});
|
||||
return {
|
||||
socket,
|
||||
opened,
|
||||
closed,
|
||||
send: (message: unknown) => socket.send(JSON.stringify(message)),
|
||||
async until(type: string): Promise<Message[]> {
|
||||
await opened;
|
||||
for (;;) {
|
||||
const failure = received.find((message) => message.type === 'error');
|
||||
if (failure) throw new Error(`Worker reported: ${failure['message']}`);
|
||||
if (received.some((message) => message.type === type)) break;
|
||||
await new Promise<void>((wake) => waiters.push(wake));
|
||||
}
|
||||
return received.slice(0, received.findIndex((message) => message.type === type) + 1);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function runPlan() {
|
||||
const client = planningSocket(server.url);
|
||||
await client.opened;
|
||||
client.send({ type: 'plan', request: PLAN });
|
||||
const messages = await client.until('artifacts');
|
||||
client.socket.close();
|
||||
return messages;
|
||||
}
|
||||
|
||||
// fetch() normalizes dot segments, so traversal needs an unnormalized request line.
|
||||
function rawGet(port: number, target: string): Promise<{ status: number; text: string }> {
|
||||
@@ -37,7 +130,12 @@ beforeAll(() => {
|
||||
writeFileSync(join(root, 'assets', 'data.json'), '{"nested":true}');
|
||||
writeFileSync(join(workdir, 'secret.txt'), SECRET);
|
||||
mkdirSync(join(workdir, 'empty'));
|
||||
server = createServer({ root, port: 0 });
|
||||
vi.stubGlobal('Worker', CountingWorker);
|
||||
server = createServer({
|
||||
root,
|
||||
port: 0,
|
||||
planning: { worker: new URL('./app/services/leave-planner.worker.ts', import.meta.url) },
|
||||
});
|
||||
emptyServer = createServer({ root: join(workdir, 'empty'), port: 0 });
|
||||
});
|
||||
|
||||
@@ -45,6 +143,7 @@ afterAll(async () => {
|
||||
await server.stop(true);
|
||||
await emptyServer.stop(true);
|
||||
rmSync(workdir, { recursive: true, force: true });
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
describe('direct navigation', () => {
|
||||
@@ -172,3 +271,96 @@ describe('errors', () => {
|
||||
expect((await fetch(new URL('/missing.js', emptyServer.url))).status).toBe(404);
|
||||
});
|
||||
});
|
||||
|
||||
describe('planning socket', () => {
|
||||
it('relays a plan as the worker produces it, with the in-process outcome', async () => {
|
||||
const messages = await runPlan();
|
||||
const types = messages.map((message) => message.type);
|
||||
const expected = await calculatePlanningAsyncInternal(PLAN);
|
||||
|
||||
for (const type of ['heartbeat', 'progress', 'checkpoint', 'result', 'explanation'])
|
||||
expect(types).toContain(type);
|
||||
expect(types.at(-1)).toBe('artifacts');
|
||||
expect(messages.find((message) => message.type === 'result')?.['outcome']).toEqual(
|
||||
expected,
|
||||
);
|
||||
}, 10_000);
|
||||
|
||||
it('cancels a running plan on a cancel message', async () => {
|
||||
const client = planningSocket(server.url);
|
||||
await client.opened;
|
||||
client.send({ type: 'plan', request: PLAN });
|
||||
client.send({ type: 'cancel' });
|
||||
const { outcome } = (await client.until('result')).at(-1)!;
|
||||
client.socket.close();
|
||||
|
||||
expect(outcome.kind).toBe('PlanningIncomplete');
|
||||
expect(outcome.reasons.map((reason: { code: string }) => reason.code)).toContain(
|
||||
'user-cancelled',
|
||||
);
|
||||
}, 10_000);
|
||||
|
||||
it('answers a counterfactual job on its own socket', async () => {
|
||||
const messages = await runPlan();
|
||||
const { outcome } = messages.find((message) => message.type === 'result')!;
|
||||
const { artifacts } = messages.find((message) => message.type === 'artifacts')!;
|
||||
const client = planningSocket(server.url);
|
||||
await client.opened;
|
||||
client.send({
|
||||
type: 'counterfactual',
|
||||
request: { ...PLAN, identities: {}, labels: {} },
|
||||
plan: outcome,
|
||||
placement: outcome.placements[0],
|
||||
state: artifacts.finalState,
|
||||
});
|
||||
const reply = (await client.until('counterfactual-result')).at(-1)!;
|
||||
client.socket.close();
|
||||
|
||||
expect(reply['analysis']).toBeDefined();
|
||||
}, 10_000);
|
||||
|
||||
it('terminates the worker when the client closes the socket', async () => {
|
||||
const before = workers.length;
|
||||
const client = planningSocket(server.url);
|
||||
await client.opened;
|
||||
client.send({ type: 'plan', request: PLAN });
|
||||
client.socket.close();
|
||||
|
||||
await vi.waitFor(() => expect(workers[before]?.terminated).toBe(true), { timeout: 5000 });
|
||||
}, 10_000);
|
||||
|
||||
it('closes with 1007 and terminates the worker on invalid JSON', async () => {
|
||||
const before = workers.length;
|
||||
const client = planningSocket(server.url);
|
||||
await client.opened;
|
||||
client.socket.send('{not json');
|
||||
|
||||
expect((await client.closed).code).toBe(1007);
|
||||
await vi.waitFor(() => expect(workers[before]?.terminated).toBe(true), { timeout: 5000 });
|
||||
}, 10_000);
|
||||
|
||||
it('closes with 1003 on a binary message', async () => {
|
||||
const client = planningSocket(server.url);
|
||||
await client.opened;
|
||||
client.socket.send(new Uint8Array([1, 2, 3]));
|
||||
|
||||
expect((await client.closed).code).toBe(1003);
|
||||
}, 10_000);
|
||||
|
||||
it('answers 426 to /api/planning without a WebSocket upgrade', async () => {
|
||||
const response = await fetch(new URL('/api/planning', server.url));
|
||||
|
||||
expect(response.status).toBe(426);
|
||||
expect(response.headers.get('content-type')).toStartWith('text/plain');
|
||||
expect(await response.text()).toBe('Upgrade Required');
|
||||
});
|
||||
|
||||
it('serves /api/planning as the application shell when planning is off', async () => {
|
||||
const plain = createServer({ root: join(workdir, 'browser'), port: 0 });
|
||||
const response = await fetch(new URL('/api/planning', plain.url));
|
||||
await plain.stop(true);
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(await response.text()).toBe(INDEX);
|
||||
});
|
||||
});
|
||||
+90
-6
@@ -51,14 +51,97 @@ export function createHandler(root: string) {
|
||||
};
|
||||
}
|
||||
|
||||
export function createServer({ root, port }: { root: string; port: number }) {
|
||||
return Bun.serve({
|
||||
type PlanningSocket = Bun.ServerWebSocket<PlanningSocketData>;
|
||||
type PlanningSocketData = { job?: PlanningJob };
|
||||
|
||||
/**
|
||||
* One planning socket = one worker job. Client messages are buffered until the worker starts, so
|
||||
* a later queue can start it after `open` without losing a message.
|
||||
*/
|
||||
class PlanningJob {
|
||||
private worker?: Worker;
|
||||
private buffered: unknown[] = [];
|
||||
private stopped = false;
|
||||
|
||||
constructor(
|
||||
private readonly socket: PlanningSocket,
|
||||
private readonly entry: string | URL,
|
||||
) {}
|
||||
|
||||
start() {
|
||||
if (this.stopped || this.worker) return;
|
||||
// Global looked up at call time so tests can substitute it.
|
||||
const worker = new Worker(this.entry);
|
||||
this.worker = worker;
|
||||
worker.addEventListener('message', (event) => {
|
||||
if (!this.stopped) this.socket.send(JSON.stringify(event.data));
|
||||
});
|
||||
worker.addEventListener('error', () => this.fail(1011, 'Planner worker failed'));
|
||||
for (const message of this.buffered.splice(0)) worker.postMessage(message);
|
||||
}
|
||||
|
||||
receive(message: string | Buffer) {
|
||||
if (typeof message !== 'string')
|
||||
return this.fail(1003, 'Binary messages are not supported');
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = JSON.parse(message);
|
||||
} catch {
|
||||
return this.fail(1007, 'Invalid JSON');
|
||||
}
|
||||
if (this.worker) this.worker.postMessage(parsed);
|
||||
else this.buffered.push(parsed);
|
||||
}
|
||||
|
||||
// Safe to call after the socket closed: the worker is already gone.
|
||||
stop() {
|
||||
this.stopped = true;
|
||||
this.buffered = [];
|
||||
this.worker?.terminate();
|
||||
this.worker = undefined;
|
||||
}
|
||||
|
||||
private fail(code: number, reason: string) {
|
||||
this.stop();
|
||||
this.socket.close(code, reason);
|
||||
}
|
||||
}
|
||||
|
||||
export function createServer({
|
||||
root,
|
||||
port,
|
||||
planning,
|
||||
}: {
|
||||
root: string;
|
||||
port: number;
|
||||
planning?: { worker: string | URL };
|
||||
}) {
|
||||
const handler = createHandler(root);
|
||||
const error = (error: Error) => {
|
||||
console.error(error);
|
||||
return new Response('Internal Server Error', { status: 500 });
|
||||
};
|
||||
if (!planning) return Bun.serve({ port, fetch: handler, error });
|
||||
|
||||
return Bun.serve<PlanningSocketData>({
|
||||
port,
|
||||
fetch: createHandler(root),
|
||||
error(error) {
|
||||
console.error(error);
|
||||
return new Response('Internal Server Error', { status: 500 });
|
||||
fetch(request, server) {
|
||||
if (new URL(request.url).pathname !== '/api/planning') return handler(request);
|
||||
if (server.upgrade(request, { data: {} })) return undefined;
|
||||
return new Response('Upgrade Required', { status: 426 });
|
||||
},
|
||||
websocket: {
|
||||
open(ws) {
|
||||
ws.data.job = new PlanningJob(ws, planning.worker);
|
||||
ws.data.job.start();
|
||||
},
|
||||
message: (ws, message) => ws.data.job?.receive(message),
|
||||
close(ws) {
|
||||
ws.data.job?.stop();
|
||||
ws.data.job = undefined;
|
||||
},
|
||||
},
|
||||
error,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -66,6 +149,7 @@ if (import.meta.main) {
|
||||
const server = createServer({
|
||||
root: join(import.meta.dir, '../browser'),
|
||||
port: Number(process.env['PORT'] || 4000),
|
||||
planning: { worker: join(import.meta.dir, 'leave-planner.worker.js') },
|
||||
});
|
||||
console.log(`Server listening on ${server.url}`);
|
||||
}
|
||||
+6
-1
@@ -108,9 +108,14 @@ getTestBed().configureTestingModule({ providers: [provideZonelessChangeDetection
|
||||
bt.beforeEach(ɵgetCleanupHook(false));
|
||||
bt.afterEach(ɵgetCleanupHook(true));
|
||||
|
||||
// Bun has a native Worker; the app must see none, as under jsdom.
|
||||
// Bun has a native Worker and WebSocket; the app must see neither, as under jsdom.
|
||||
// Specs that run the real server or planner worker stub these back in.
|
||||
export const BunWorker: typeof Worker = (globalThis as any).Worker;
|
||||
export const BunWebSocket: typeof WebSocket = (globalThis as any).WebSocket;
|
||||
delete (globalThis as any).Worker;
|
||||
delete (globalThis as any).WebSocket;
|
||||
vi.stubGlobal('Worker', undefined);
|
||||
vi.stubGlobal('WebSocket', undefined);
|
||||
Object.defineProperty(window, 'matchMedia', {
|
||||
writable: true,
|
||||
value: vi.fn().mockImplementation((query: string) => ({
|
||||
|
||||
Reference in new issue
Block a user