refactor(planning): share the planning socket's job table with the server
PLANNING_JOBS in leave-planner.worker-messages.ts now lists each job kind's follow-up messages and terminal responses, checked against WorkerRequest and WorkerResponse. The server reads it in place of its own TERMINAL_MESSAGES and cancel check, so a new job request type without an entry fails the typecheck instead of closing sockets with 1008. Refs #331 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
3044d507a2
commit
d018d5c1c3
3 files changed
+33
-20
No files matched your search
@@ -264,7 +264,7 @@ The server answers `GET` and `HEAD` only (other methods get 405), except at `/ap
|
||||
|
||||
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. Each client IP may hold five planning sockets at once. The IP is the `CF-Connecting-IP` header, or the address of the connection when the header is absent. The server closes a sixth socket from the same IP with code 4429 before sending any message, so that tab calculates locally with its own engine; closing a socket frees its place. The server also closes a socket whose incoming message exceeds about 1 MB (WebSocket code 1009, or an abnormal close) without running a calculation. The per-IP limit holds only if the origin accepts traffic from Cloudflare alone: anyone who can reach the origin directly can forge `CF-Connecting-IP` and bypass it.
|
||||
|
||||
At most `PLANNING_WORKERS` calculations run at once, each in its own worker; it defaults to half the CPU threads the container reports, which assumes two threads per core, so set it to the physical core count (throughput stops growing there). Other calculations wait in arrival order and the server sends a heartbeat every second so the client keeps waiting; no queue position is shown. A socket joins the line with its first message, so an idle open socket holds no worker. Closing the socket removes a waiting calculation. A waiting plan that its client cancels starts at once, even beyond `PLANNING_WORKERS`, and stops at its first yield with the worker's own cancelled outcome. A running calculation frees its place when it ends, fails or its socket closes. A client may send one job message and, for a plan, one `cancel`; any other text message before the job ends closes the socket with code 1008 (binary and invalid JSON get 1003 and 1007), and messages after it ends are ignored. Each calculation takes roughly 60 to 150 MB, and the production Compose file (`compose.prod.yml`) sets an 8 GB memory limit with no CPU limit.
|
||||
At most `PLANNING_WORKERS` calculations run at once, each in its own worker; it defaults to half the CPU threads the container reports, which assumes two threads per core, so set it to the physical core count (throughput stops growing there). Other calculations wait in arrival order and the server sends a heartbeat every second so the client keeps waiting; no queue position is shown. A socket joins the line with its first message, so an idle open socket holds no worker. Closing the socket removes a waiting calculation. A waiting plan that its client cancels starts at once, even beyond `PLANNING_WORKERS`, and stops at its first yield with the worker's own cancelled outcome. A running calculation frees its place when it ends, fails or its socket closes. A client may send one job message and, for a plan, one `cancel` (`PLANNING_JOBS` in `src/app/services/leave-planner.worker-messages.ts` lists each job's follow-ups and terminal responses); any other text message before the job ends closes the socket with code 1008 (binary and invalid JSON get 1003 and 1007), and messages after it ends are ignored. Each calculation takes roughly 60 to 150 MB, and the production Compose file (`compose.prod.yml`) sets an 8 GB memory limit with no CPU limit.
|
||||
|
||||
Behind a reverse proxy, forward WebSocket upgrades for `/api/planning`; on Nginx Proxy Manager, enable WebSocket support for the host.
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@ import type {
|
||||
} from './leave-planner.service';
|
||||
import type { PlanningArtifacts } from './leave-planner.core';
|
||||
|
||||
// Message contract shared by the planning coordinator and its worker; types only.
|
||||
// Message contract shared by the planning coordinator, its worker and the planning server.
|
||||
export type WorkerPlanningRequest = {
|
||||
calculationDate?: string;
|
||||
declaredDays?: unknown;
|
||||
@@ -58,3 +58,19 @@ export type WorkerResponse =
|
||||
}
|
||||
| { type: 'counterfactual-result'; analysis: CounterfactualAnalysis }
|
||||
| { type: 'error'; code?: string; message: string };
|
||||
|
||||
/**
|
||||
* What the planning server accepts on one socket: the first message names the job, then only its
|
||||
* follow-ups, each at most once, until one of its terminal responses ends it.
|
||||
*/
|
||||
export const PLANNING_JOBS = {
|
||||
plan: { followUps: ['cancel'], terminal: ['artifacts', 'error'] },
|
||||
'explain-checkpoint': { followUps: [], terminal: ['explanation', 'error'] },
|
||||
counterfactual: { followUps: [], terminal: ['counterfactual-result', 'error'] },
|
||||
} as const satisfies Record<
|
||||
Exclude<WorkerRequest['type'], 'cancel'>,
|
||||
{
|
||||
followUps: readonly WorkerRequest['type'][];
|
||||
terminal: readonly WorkerResponse['type'][];
|
||||
}
|
||||
>;
|
||||
+15
-18
@@ -1,5 +1,6 @@
|
||||
import { extname, join, resolve, sep } from 'node:path';
|
||||
import { planningBuild } from './app/services/planning-build';
|
||||
import { PLANNING_JOBS } from './app/services/leave-planner.worker-messages';
|
||||
|
||||
const IMMUTABLE = 'public, max-age=31536000';
|
||||
/** Close code for a planning socket whose client was built differently from this server. */
|
||||
@@ -67,12 +68,7 @@ type PlanningSocketData = {
|
||||
job?: PlanningJob;
|
||||
};
|
||||
|
||||
// What a planning socket may start with, and the worker messages that end each kind of job.
|
||||
const TERMINAL_MESSAGES: Record<string, readonly string[]> = {
|
||||
plan: ['artifacts', 'error'],
|
||||
'explain-checkpoint': ['explanation', 'error'],
|
||||
counterfactual: ['counterfactual-result', 'error'],
|
||||
};
|
||||
type PlanningJobKind = keyof typeof PLANNING_JOBS;
|
||||
const HEARTBEAT_MS = 1000;
|
||||
|
||||
/** At most `workers` jobs run; the others wait in arrival order. */
|
||||
@@ -115,13 +111,13 @@ class PlanningQueue {
|
||||
|
||||
/**
|
||||
* One planning socket = one worker job. Its first message fixes the kind and puts it in the
|
||||
* queue; a single allowed cancel is buffered until its worker starts. A job holds its slot only
|
||||
* queue; its allowed follow-ups are buffered until its worker starts. A job holds its slot only
|
||||
* while 'running', released exactly once by a terminal message, a failure or the socket closing.
|
||||
*/
|
||||
class PlanningJob {
|
||||
private state: 'idle' | 'waiting' | 'running' | 'done' = 'idle';
|
||||
private kind = '';
|
||||
private cancelled = false;
|
||||
private kind: PlanningJobKind = 'plan';
|
||||
private followUps: string[] = [];
|
||||
private worker?: Worker;
|
||||
private buffered: unknown[] = [];
|
||||
private heartbeat?: ReturnType<typeof setInterval>;
|
||||
@@ -154,7 +150,7 @@ class PlanningJob {
|
||||
if (this.state !== 'running') return;
|
||||
this.socket.send(JSON.stringify(event.data));
|
||||
// The client closes the socket; the core is free for the next job meanwhile.
|
||||
if (TERMINAL_MESSAGES[this.kind]?.includes(event.data?.type)) this.stop();
|
||||
if (PLANNING_JOBS[this.kind].terminal.includes(event.data?.type)) this.stop();
|
||||
});
|
||||
worker.addEventListener('error', () => this.fail(1011, 'Planner worker failed'));
|
||||
// A worker that exits on its own sends nothing else; stop() sets 'done' before terminating.
|
||||
@@ -176,20 +172,21 @@ class PlanningJob {
|
||||
const type = parsed?.type;
|
||||
if (this.state === 'done') return;
|
||||
if (this.state === 'idle') {
|
||||
if (typeof type !== 'string' || !Object.hasOwn(TERMINAL_MESSAGES, type))
|
||||
if (typeof type !== 'string' || !Object.hasOwn(PLANNING_JOBS, type))
|
||||
return this.fail(1008, 'Unknown first message');
|
||||
this.kind = type;
|
||||
this.kind = type as PlanningJobKind;
|
||||
this.followUps = [...PLANNING_JOBS[this.kind].followUps];
|
||||
this.buffered.push(parsed);
|
||||
return this.queue.submit(this);
|
||||
}
|
||||
// A client sends one job message and at most one cancel, and only for a plan: more would
|
||||
// start extra calculations or grow the buffer without bound.
|
||||
if (type !== 'cancel' || this.kind !== 'plan' || this.cancelled)
|
||||
return this.fail(1008, 'Unexpected message');
|
||||
this.cancelled = true;
|
||||
// Each follow-up at most once: more would start extra calculations or grow the buffer
|
||||
// without bound.
|
||||
const followUp = this.followUps.indexOf(type as string);
|
||||
if (followUp < 0) return this.fail(1008, 'Unexpected message');
|
||||
this.followUps.splice(followUp, 1);
|
||||
if (this.state === 'running') return this.worker?.postMessage(parsed);
|
||||
this.buffered.push(parsed);
|
||||
this.queue.promote(this);
|
||||
if (type === 'cancel') this.queue.promote(this);
|
||||
}
|
||||
|
||||
// Safe to call after the socket closed or the job ended.
|
||||
|
||||
Reference in new issue
Block a user