feat(planning): calculate locally when client and server builds differ
`bun run build` now builds the browser and server bundles in one script that defines a fresh PLANNING_BUILD identifier for both. The client sends it when it opens a planning socket, and the server closes a socket from another build, or without one, with code 4409 before any message, so a tab opened before a deployment calculates with its own engine. Development and test runs have no identifier: the client skips the socket and calculates locally, and a server run from source accepts no planning sockets. Closes #325 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
e2a5a6f0e8
commit
63fc119297
9 files changed
+120
-19
No files matched your search
@@ -236,9 +236,11 @@ Open <http://localhost:4200>. The development server reloads when source files c
|
||||
| `bun run lint` | Run ESLint (`bun run lint:fix` applies its fixes). |
|
||||
| `bun run format:check` | Check Prettier formatting of the application, the CI scripts and the workflow (`bun run format` writes it). |
|
||||
| `bun run typecheck` | Type-check application and test code with `bun check`. It does not check Angular templates; only the build does. |
|
||||
| `bun run build` | Create the optimized browser bundle and the static server bundle in `dist/vac-optimizer/`. |
|
||||
| `bun run build` | Create the optimized browser bundle and the static server bundle in `dist/vac-optimizer/`, sharing one build id. |
|
||||
| `bun run serve` | Serve a completed production build on `PORT` (default 4000). |
|
||||
|
||||
Only `bun run build` output has a build identifier and plans on the server. Development and test runs (`ng serve`, `bun run watch`, `bun test`) have none and always calculate locally, and a server started from source (`bun src/server.ts`) accepts no planning sockets.
|
||||
|
||||
Project scripts run Node-shebang tools (`ng`, `eslint`, `prettier`) on Bun even when Node is installed: `bunfig.toml` sets `[run] bun = true`, which is the `--bun` flag for every `bun run`. Start them through the scripts above. A bare `bunx` or `bun x` uses Node when it is on `PATH`; for a one-off tool, use `bun --bun x <tool>`.
|
||||
|
||||
Angular compiles with TypeScript 6. `bun check` is Bun's TypeScript 7 checker for standalone type errors in application and test code. Neither replaces the other: only `bun run build` (Angular's compiler) checks templates, so a passing `typecheck` does not replace the production build. ESLint and Prettier stay until a stable Bun release ships its native linter and formatter ([bun-adoption](docs/bun-adoption.md#status)).
|
||||
@@ -258,7 +260,7 @@ 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 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), 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.
|
||||
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`. The client sends its build identifier in the `build` query parameter; the server closes a socket from a different build (or without one) with code 4409 before sending any message, so that tab calculates locally with its own engine. 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
|
||||
|
||||
|
||||
+1
-2
@@ -5,8 +5,7 @@
|
||||
"scripts": {
|
||||
"ng": "ng",
|
||||
"start": "bun scripts/generate-langs.js && ng serve",
|
||||
"build": "bun scripts/generate-langs.js && ng build",
|
||||
"postbuild": "bun build src/server.ts src/app/services/leave-planner.worker.ts --target=bun --outdir dist/vac-optimizer/server --entry-naming '[name].[ext]'",
|
||||
"build": "bun scripts/generate-langs.js && bun scripts/build.mjs",
|
||||
"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,23 @@
|
||||
// One script builds both bundles so they share one identifier: the server refuses clients of other builds.
|
||||
import { randomUUID } from 'node:crypto';
|
||||
|
||||
const define = JSON.stringify(randomUUID());
|
||||
const args = process.argv.slice(2).filter((arg, index) => index > 0 || arg !== '--');
|
||||
|
||||
// `ng build` empties its output path, so the server bundle has to come after it.
|
||||
const ng = Bun.spawn(
|
||||
['bun', 'run', 'ng', 'build', '--define', `PLANNING_BUILD=${define}`, ...args],
|
||||
{ stdio: ['inherit', 'inherit', 'inherit'] },
|
||||
);
|
||||
const code = await ng.exited;
|
||||
if (code !== 0) process.exit(code);
|
||||
|
||||
const result = await Bun.build({
|
||||
entrypoints: ['src/server.ts', 'src/app/services/leave-planner.worker.ts'],
|
||||
target: 'bun',
|
||||
outdir: 'dist/vac-optimizer/server',
|
||||
naming: '[name].[ext]',
|
||||
define: { PLANNING_BUILD: define },
|
||||
});
|
||||
for (const log of result.logs) console.log(log);
|
||||
if (!result.success) process.exit(1);
|
||||
@@ -96,6 +96,7 @@ describe('remote planning job', () => {
|
||||
FakeWorker.all = [];
|
||||
vi.useFakeTimers();
|
||||
vi.stubGlobal('window', {});
|
||||
vi.stubGlobal('PLANNING_BUILD', 'test-build');
|
||||
vi.stubGlobal('Worker', FakeWorker);
|
||||
vi.stubGlobal('WebSocket', FakeWebSocket);
|
||||
});
|
||||
@@ -108,7 +109,7 @@ describe('remote planning job', () => {
|
||||
const progress = vi.fn();
|
||||
const calculation = createPlanningCalculation({ ...request, progress });
|
||||
const [socket] = sockets();
|
||||
expect(socket.url).toBe('ws://localhost:3000/api/planning');
|
||||
expect(socket.url).toBe('ws://localhost:3000/api/planning?build=test-build');
|
||||
expect(socket.send).not.toHaveBeenCalled();
|
||||
socket.accept();
|
||||
expect(socket.sentTypes()).toEqual(['plan']);
|
||||
@@ -129,6 +130,16 @@ describe('remote planning job', () => {
|
||||
expect(sockets()).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('calculates locally without a socket when the build has no identifier', async () => {
|
||||
vi.stubGlobal('PLANNING_BUILD', undefined);
|
||||
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' });
|
||||
expect(sockets()).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('falls back to the local worker, replaying the plan and an early cancel', async () => {
|
||||
const calculation = createPlanningCalculation(request);
|
||||
const [socket] = sockets();
|
||||
|
||||
@@ -16,6 +16,7 @@ import type {
|
||||
PlanningStateSnapshot,
|
||||
StaleCounterfactualAnalysis,
|
||||
} from './leave-planner.core';
|
||||
import { planningBuild } from './planning-build';
|
||||
import { planningDateInParis } from './planning-date';
|
||||
import type { WorkerRequest, WorkerResponse } from './leave-planner.worker-messages';
|
||||
|
||||
@@ -360,21 +361,23 @@ function encodePlanningMessage(message: WorkerRequest): string {
|
||||
});
|
||||
}
|
||||
|
||||
function planningSocketUrl(): string {
|
||||
function planningSocketUrl(build: string): string {
|
||||
const url = new URL('/api/planning', location.href);
|
||||
url.searchParams.set('build', build);
|
||||
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(
|
||||
build: string,
|
||||
supersede: () => void,
|
||||
onMessage: (message: WorkerResponse) => void,
|
||||
onError: () => void,
|
||||
): WorkerJob {
|
||||
let socket: WebSocket;
|
||||
try {
|
||||
socket = new WebSocket(planningSocketUrl());
|
||||
socket = new WebSocket(planningSocketUrl(build));
|
||||
} catch {
|
||||
return startLocalJob(supersede, onMessage, onError);
|
||||
}
|
||||
@@ -482,9 +485,11 @@ function startWorkerJob(
|
||||
onMessage: (message: WorkerResponse) => void,
|
||||
onError: () => void,
|
||||
): WorkerJob {
|
||||
return typeof WebSocket === 'undefined'
|
||||
// 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(supersede, onMessage, onError);
|
||||
: startRemoteJob(build, supersede, onMessage, onError);
|
||||
}
|
||||
|
||||
function cancelLatestWorkers(): void {
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
declare const PLANNING_BUILD: string | undefined;
|
||||
|
||||
/** The identifier `bun run build` gives the client and server bundles of one build; undefined in development and test runs. */
|
||||
export function planningBuild(): string | undefined {
|
||||
return typeof PLANNING_BUILD === 'string' ? PLANNING_BUILD : undefined;
|
||||
}
|
||||
@@ -9,7 +9,7 @@ import {
|
||||
type PlanningOutcome,
|
||||
type PlanningRequest,
|
||||
} from './app/services/leave-planner.service';
|
||||
import { createServer } from './server';
|
||||
import { createServer, PLANNING_BUILD_MISMATCH } from './server';
|
||||
import { BunWebSocket, BunWorker } from './test-setup';
|
||||
import { vi } from './testing/vitest-compat';
|
||||
|
||||
@@ -18,6 +18,7 @@ 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 BUILD = 'equivalence-build';
|
||||
const scenarios = benchmarkScenarios();
|
||||
|
||||
let workdir: string;
|
||||
@@ -53,6 +54,7 @@ class RecordingWorker extends BunWorker {
|
||||
}
|
||||
|
||||
class RecordingWebSocket extends BunWebSocket {
|
||||
closeCode?: number;
|
||||
readonly received: Message[] = [];
|
||||
readonly sent: Message[] = [];
|
||||
|
||||
@@ -61,6 +63,7 @@ class RecordingWebSocket extends BunWebSocket {
|
||||
this.addEventListener('message', (event) =>
|
||||
this.received.push(JSON.parse(String(event.data))),
|
||||
);
|
||||
this.addEventListener('close', (event) => (this.closeCode = event.code));
|
||||
sockets.push(this);
|
||||
}
|
||||
|
||||
@@ -122,8 +125,13 @@ describe('server-side planning equivalence', () => {
|
||||
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 } });
|
||||
server = createServer({
|
||||
root: workdir,
|
||||
port: 0,
|
||||
planning: { worker: WORKER_URL, build: BUILD },
|
||||
});
|
||||
vi.stubGlobal('window', {});
|
||||
vi.stubGlobal('PLANNING_BUILD', BUILD);
|
||||
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'));
|
||||
@@ -158,6 +166,24 @@ describe('server-side planning equivalence', () => {
|
||||
60_000,
|
||||
);
|
||||
|
||||
it('calculates locally when the client was built differently from the server', async () => {
|
||||
vi.stubGlobal('PLANNING_BUILD', 'previous-build');
|
||||
try {
|
||||
const mismatched = await runRemote(scenarioRequest('typed obligations'));
|
||||
const [socket] = sockets.slice(-1);
|
||||
expect(socket.closeCode).toBe(PLANNING_BUILD_MISMATCH);
|
||||
expect(socket.received).toEqual([]);
|
||||
expect(mismatched.createdWorkers.filter((worker) => !worker.local)).toEqual([]);
|
||||
expect(mismatched.createdWorkers.filter((worker) => worker.local)).toHaveLength(1);
|
||||
|
||||
const local = await runLocal(scenarioRequest('typed obligations'));
|
||||
expect(mismatched.outcome).toEqual(local.outcome);
|
||||
expect(mismatched.explanation).toEqual(local.explanation);
|
||||
} finally {
|
||||
vi.stubGlobal('PLANNING_BUILD', BUILD);
|
||||
}
|
||||
}, 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);
|
||||
|
||||
+20
-3
@@ -4,7 +4,7 @@ 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 { createServer, PLANNING_BUILD_MISMATCH } from './server';
|
||||
import { BunWebSocket, BunWorker } from './test-setup';
|
||||
import { vi } from './testing/vitest-compat';
|
||||
|
||||
@@ -63,9 +63,10 @@ const PLAN = {
|
||||
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) {
|
||||
function planningSocket(base: URL, build: string | null = 'test-build') {
|
||||
const url = new URL('/api/planning', base);
|
||||
url.protocol = 'ws:';
|
||||
if (build !== null) url.searchParams.set('build', build);
|
||||
const socket = new BunWebSocket(url);
|
||||
const received: Message[] = [];
|
||||
const waiters: (() => void)[] = [];
|
||||
@@ -82,6 +83,7 @@ function planningSocket(base: URL) {
|
||||
});
|
||||
return {
|
||||
socket,
|
||||
received,
|
||||
opened,
|
||||
closed,
|
||||
send: (message: unknown) => socket.send(JSON.stringify(message)),
|
||||
@@ -134,7 +136,10 @@ beforeAll(() => {
|
||||
server = createServer({
|
||||
root,
|
||||
port: 0,
|
||||
planning: { worker: new URL('./app/services/leave-planner.worker.ts', import.meta.url) },
|
||||
planning: {
|
||||
worker: new URL('./app/services/leave-planner.worker.ts', import.meta.url),
|
||||
build: 'test-build',
|
||||
},
|
||||
});
|
||||
emptyServer = createServer({ root: join(workdir, 'empty'), port: 0 });
|
||||
});
|
||||
@@ -347,6 +352,18 @@ describe('planning socket', () => {
|
||||
expect((await client.closed).code).toBe(1003);
|
||||
}, 10_000);
|
||||
|
||||
it.each([
|
||||
['a different build', 'other-build'],
|
||||
['no build', null],
|
||||
])('closes with the mismatch code before any message for %s', async (_name, build) => {
|
||||
const before = workers.length;
|
||||
const client = planningSocket(server.url, build);
|
||||
client.socket.addEventListener('open', () => client.send({ type: 'plan', request: PLAN }));
|
||||
expect((await client.closed).code).toBe(PLANNING_BUILD_MISMATCH);
|
||||
expect(client.received).toEqual([]);
|
||||
expect(workers).toHaveLength(before);
|
||||
});
|
||||
|
||||
it('answers 426 to /api/planning without a WebSocket upgrade', async () => {
|
||||
const response = await fetch(new URL('/api/planning', server.url));
|
||||
|
||||
|
||||
+17
-5
@@ -1,6 +1,9 @@
|
||||
import { extname, join, resolve, sep } from 'node:path';
|
||||
import { planningBuild } from './app/services/planning-build';
|
||||
|
||||
const IMMUTABLE = 'public, max-age=31536000';
|
||||
/** Close code for a planning socket whose client was built differently from this server. */
|
||||
export const PLANNING_BUILD_MISMATCH = 4409;
|
||||
|
||||
/**
|
||||
* Fetch handler for a client-only Angular build in `root`: existing files are served as-is,
|
||||
@@ -52,7 +55,7 @@ export function createHandler(root: string) {
|
||||
}
|
||||
|
||||
type PlanningSocket = Bun.ServerWebSocket<PlanningSocketData>;
|
||||
type PlanningSocketData = { job?: PlanningJob };
|
||||
type PlanningSocketData = { build: string | null; job?: PlanningJob };
|
||||
|
||||
/**
|
||||
* One planning socket = one worker job. Client messages are buffered until the worker starts, so
|
||||
@@ -114,7 +117,7 @@ export function createServer({
|
||||
}: {
|
||||
root: string;
|
||||
port: number;
|
||||
planning?: { worker: string | URL };
|
||||
planning?: { worker: string | URL; build: string };
|
||||
}) {
|
||||
const handler = createHandler(root);
|
||||
const error = (error: Error) => {
|
||||
@@ -126,12 +129,17 @@ export function createServer({
|
||||
return Bun.serve<PlanningSocketData>({
|
||||
port,
|
||||
fetch(request, server) {
|
||||
if (new URL(request.url).pathname !== '/api/planning') return handler(request);
|
||||
if (server.upgrade(request, { data: {} })) return undefined;
|
||||
const url = new URL(request.url);
|
||||
if (url.pathname !== '/api/planning') return handler(request);
|
||||
if (server.upgrade(request, { data: { build: url.searchParams.get('build') } }))
|
||||
return undefined;
|
||||
return new Response('Upgrade Required', { status: 426 });
|
||||
},
|
||||
websocket: {
|
||||
open(ws) {
|
||||
// A client from another build runs its own engine; refuse before any worker starts.
|
||||
if (ws.data.build !== planning.build)
|
||||
return ws.close(PLANNING_BUILD_MISMATCH, 'Build mismatch');
|
||||
ws.data.job = new PlanningJob(ws, planning.worker);
|
||||
ws.data.job.start();
|
||||
},
|
||||
@@ -146,10 +154,14 @@ export function createServer({
|
||||
}
|
||||
|
||||
if (import.meta.main) {
|
||||
// A server run from source has no build identifier, so it accepts no planning sockets.
|
||||
const build = planningBuild();
|
||||
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') },
|
||||
planning: build
|
||||
? { worker: join(import.meta.dir, 'leave-planner.worker.js'), build }
|
||||
: undefined,
|
||||
});
|
||||
console.log(`Server listening on ${server.url}`);
|
||||
}
|
||||
Reference in new issue
Block a user