@aws-blocks/core 0.1.3 → 0.1.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cdk/index.d.ts +1 -1
- package/dist/cdk/index.d.ts.map +1 -1
- package/dist/cdk/index.js +1 -1
- package/dist/client/index.d.ts +1 -1
- package/dist/client/index.d.ts.map +1 -1
- package/dist/client/index.js +1 -1
- package/dist/constants.d.ts +12 -0
- package/dist/constants.d.ts.map +1 -1
- package/dist/constants.js +12 -0
- package/dist/errors.d.ts +28 -0
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +27 -1
- package/dist/errors.test.d.ts +2 -0
- package/dist/errors.test.d.ts.map +1 -0
- package/dist/errors.test.js +47 -0
- package/dist/hosting.d.ts +22 -1
- package/dist/hosting.d.ts.map +1 -1
- package/dist/index.cdk.d.ts +1 -1
- package/dist/index.cdk.d.ts.map +1 -1
- package/dist/index.cdk.js +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/scripts/dev-server-config.test.d.ts +2 -0
- package/dist/scripts/dev-server-config.test.d.ts.map +1 -0
- package/dist/scripts/dev-server-config.test.js +37 -0
- package/dist/scripts/dev-server-supervisor.test.d.ts +2 -0
- package/dist/scripts/dev-server-supervisor.test.d.ts.map +1 -0
- package/dist/scripts/dev-server-supervisor.test.js +551 -0
- package/dist/scripts/dev-server.d.ts +92 -0
- package/dist/scripts/dev-server.d.ts.map +1 -1
- package/dist/scripts/dev-server.js +317 -34
- package/dist/scripts/index.d.ts +1 -0
- package/dist/scripts/index.d.ts.map +1 -1
- package/dist/scripts/index.js +1 -0
- package/dist/scripts/process-tree.d.ts +126 -0
- package/dist/scripts/process-tree.d.ts.map +1 -0
- package/dist/scripts/process-tree.js +198 -0
- package/dist/scripts/sandbox.d.ts.map +1 -1
- package/dist/scripts/sandbox.js +41 -3
- package/dist/scripts/stack-id.d.ts +12 -0
- package/dist/scripts/stack-id.d.ts.map +1 -0
- package/dist/scripts/stack-id.js +54 -0
- package/dist/scripts/stack-id.test.d.ts +2 -0
- package/dist/scripts/stack-id.test.d.ts.map +1 -0
- package/dist/scripts/stack-id.test.js +54 -0
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/package.json +1 -1
- package/src/cdk/index.ts +1 -1
- package/src/client/index.ts +1 -1
- package/src/constants.ts +13 -0
- package/src/errors.test.ts +55 -0
- package/src/errors.ts +32 -1
- package/src/hosting.ts +22 -1
- package/src/index.cdk.ts +1 -1
- package/src/index.ts +1 -1
- package/src/scripts/dev-server-config.test.ts +43 -0
- package/src/scripts/dev-server-supervisor.test.ts +621 -0
- package/src/scripts/dev-server.ts +364 -33
- package/src/scripts/index.ts +1 -0
- package/src/scripts/process-tree.ts +245 -0
- package/src/scripts/sandbox.ts +40 -3
- package/src/scripts/stack-id.test.ts +63 -0
- package/src/scripts/stack-id.ts +61 -0
- package/src/version.ts +1 -1
|
@@ -4,13 +4,13 @@
|
|
|
4
4
|
import { createServer, type IncomingMessage, type ServerResponse } from 'node:http';
|
|
5
5
|
import { pathToFileURL, URL } from 'node:url';
|
|
6
6
|
import { resolve, dirname, join } from 'node:path';
|
|
7
|
-
import {
|
|
7
|
+
import { writeFileSync, mkdirSync } from 'node:fs';
|
|
8
8
|
import { spawn, type ChildProcess } from 'node:child_process';
|
|
9
9
|
import { createConnection } from 'node:net';
|
|
10
10
|
import httpProxy from 'http-proxy';
|
|
11
11
|
import { writeClientCode } from './generate-client.js';
|
|
12
12
|
import { ApiError } from '../errors.js';
|
|
13
|
-
import { BLOCKS_RPC_PREFIX } from '../constants.js';
|
|
13
|
+
import { BLOCKS_RPC_PREFIX, BLOCKS_SANDBOX_PREFIX } from '../constants.js';
|
|
14
14
|
import { matchRoute, lockRouteRegistry } from '../raw-route.js';
|
|
15
15
|
import { registerBuiltinRoutes } from '../builtin-routes.js';
|
|
16
16
|
import {
|
|
@@ -22,6 +22,7 @@ import {
|
|
|
22
22
|
import { redactToJson } from '../redact.js';
|
|
23
23
|
import { buildAndSendEvent } from '../telemetry/client.js';
|
|
24
24
|
import { applyDevMigrations } from './external-migrations-step.js';
|
|
25
|
+
import { killFrontendTree, terminateProcessTree } from './process-tree.js';
|
|
25
26
|
|
|
26
27
|
function toBodyStream(text: string): ReadableStream<Uint8Array> | null {
|
|
27
28
|
if (!text) return null;
|
|
@@ -43,6 +44,35 @@ export function resolveDevCorsOrigin(origin: string): string {
|
|
|
43
44
|
return LOCALHOST_PATTERN.test(origin) ? origin : 'http://localhost:3000';
|
|
44
45
|
}
|
|
45
46
|
|
|
47
|
+
/** Shape of the client runtime config the browser fetches to discover the API URL. */
|
|
48
|
+
export interface BlocksRuntimeConfig {
|
|
49
|
+
apiUrl: string;
|
|
50
|
+
environment: 'local' | 'sandbox';
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Build the runtime config the browser fetches at `${BLOCKS_SANDBOX_PREFIX}/config.json`.
|
|
55
|
+
* In sandbox mode the browser still targets the localhost front door (the dev
|
|
56
|
+
* server proxies `/aws-blocks/api` to the deployed API), so the shape is the
|
|
57
|
+
* same in both modes — only `environment` differs.
|
|
58
|
+
*/
|
|
59
|
+
export function buildBlocksConfig(port: number, isSandbox: boolean): BlocksRuntimeConfig {
|
|
60
|
+
return {
|
|
61
|
+
apiUrl: `http://localhost:${port}${BLOCKS_RPC_PREFIX}`,
|
|
62
|
+
environment: isSandbox ? 'sandbox' : 'local',
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* True for the reserved runtime-config request the dev server answers itself
|
|
68
|
+
* (mirroring production, where CloudFront serves `${BLOCKS_SANDBOX_PREFIX}/*`
|
|
69
|
+
* statically) instead of proxying it to the framework dev server — which only
|
|
70
|
+
* serves its own static dir (Next.js `public/`, etc.) and would 404.
|
|
71
|
+
*/
|
|
72
|
+
export function isBlocksConfigRequest(method: string, pathname: string): boolean {
|
|
73
|
+
return method === 'GET' && pathname === `${BLOCKS_SANDBOX_PREFIX}/config.json`;
|
|
74
|
+
}
|
|
75
|
+
|
|
46
76
|
export interface DevServerOptions {
|
|
47
77
|
/** Customer-facing port. Default: 3000. */
|
|
48
78
|
port?: number;
|
|
@@ -90,6 +120,123 @@ async function waitForPort(port: number, maxAttempts = 60): Promise<void> {
|
|
|
90
120
|
throw new Error(`Frontend server on port ${port} did not start within ${maxAttempts * 500}ms`);
|
|
91
121
|
}
|
|
92
122
|
|
|
123
|
+
/** Bounded auto-respawn policy for the frontend dev server. */
|
|
124
|
+
export interface FrontendRespawnPolicy {
|
|
125
|
+
/** Max restarts allowed within `windowMs` before giving up (prevents hot loops). */
|
|
126
|
+
maxRestarts: number;
|
|
127
|
+
/** Sliding window (ms) over which restarts are counted. */
|
|
128
|
+
windowMs: number;
|
|
129
|
+
/** Base backoff (ms); doubles for each restart already in the window. */
|
|
130
|
+
backoffMs: number;
|
|
131
|
+
/** Upper bound (ms) on any single backoff delay. */
|
|
132
|
+
maxBackoffMs: number;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** Default frontend respawn budget: 5 restarts / 10s, 500ms→5s exponential backoff. */
|
|
136
|
+
export const DEFAULT_FRONTEND_RESPAWN_POLICY: FrontendRespawnPolicy = {
|
|
137
|
+
maxRestarts: 5,
|
|
138
|
+
windowMs: 10_000,
|
|
139
|
+
backoffMs: 500,
|
|
140
|
+
maxBackoffMs: 5_000,
|
|
141
|
+
};
|
|
142
|
+
|
|
143
|
+
/** Outcome of {@link evaluateFrontendRespawn}. */
|
|
144
|
+
export interface RespawnDecision {
|
|
145
|
+
/** Whether the frontend should be respawned now. */
|
|
146
|
+
restart: boolean;
|
|
147
|
+
/** Delay (ms) to wait before respawning when `restart` is true. */
|
|
148
|
+
delayMs: number;
|
|
149
|
+
/**
|
|
150
|
+
* Restart timestamps still inside the window — plus the new attempt when
|
|
151
|
+
* restarting. The caller persists this for the next decision.
|
|
152
|
+
*/
|
|
153
|
+
recent: number[];
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* Decide whether to auto-respawn the frontend dev server after an unexpected
|
|
158
|
+
* exit, given the timestamps of restarts not yet "forgiven".
|
|
159
|
+
*
|
|
160
|
+
* Semantics — the budget counts only *failing* restarts:
|
|
161
|
+
* - Timestamps older than `windowMs` are dropped from the sliding window.
|
|
162
|
+
* - If `maxRestarts` are still within the window, the budget is exhausted and
|
|
163
|
+
* the frontend is left down (no hot restart loop) — `restart: false`.
|
|
164
|
+
* - Otherwise `restart: true` with an exponential backoff (`backoffMs` doubled
|
|
165
|
+
* per in-window restart, capped at `maxBackoffMs`) and the new attempt
|
|
166
|
+
* appended to `recent`.
|
|
167
|
+
*
|
|
168
|
+
* This function is pure; the *meaning* of the budget is enforced by the caller,
|
|
169
|
+
* which **resets `recentRestarts` to `[]` once a respawn demonstrably succeeds**
|
|
170
|
+
* (the frontend port becomes bound — see `announceFrontendReady`). As a result
|
|
171
|
+
* only *consecutive failing* restarts accumulate toward `maxRestarts`: a
|
|
172
|
+
* frontend that legitimately restarts many times in a burst (e.g.
|
|
173
|
+
* editor-triggered Vite full reloads) refreshes its budget on each healthy bind
|
|
174
|
+
* and is never permanently left down — only a genuine crash loop that never
|
|
175
|
+
* rebinds the port trips the limit.
|
|
176
|
+
*/
|
|
177
|
+
export function evaluateFrontendRespawn(
|
|
178
|
+
recentRestarts: number[],
|
|
179
|
+
now: number,
|
|
180
|
+
policy: FrontendRespawnPolicy = DEFAULT_FRONTEND_RESPAWN_POLICY,
|
|
181
|
+
): RespawnDecision {
|
|
182
|
+
const recent = recentRestarts.filter((t) => now - t < policy.windowMs);
|
|
183
|
+
if (recent.length >= policy.maxRestarts) {
|
|
184
|
+
return { restart: false, delayMs: 0, recent };
|
|
185
|
+
}
|
|
186
|
+
const delayMs = Math.min(policy.backoffMs * 2 ** recent.length, policy.maxBackoffMs);
|
|
187
|
+
return { restart: true, delayMs, recent: [...recent, now] };
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/**
|
|
191
|
+
* Wait (bounded) for a TCP port to STOP accepting connections, i.e. for the
|
|
192
|
+
* listener to actually release the socket. Used after killing the frontend so a
|
|
193
|
+
* `tsx watch` relaunch can rebind `:3100` cleanly instead of racing the kernel's
|
|
194
|
+
* socket teardown and hitting `--strictPort` `EADDRINUSE`. Resolves as soon as
|
|
195
|
+
* the port is free, or once `timeoutMs` elapses (never rejects).
|
|
196
|
+
*/
|
|
197
|
+
export async function waitForPortFree(port: number, timeoutMs = 2000): Promise<void> {
|
|
198
|
+
const { setTimeout: sleep } = await import('node:timers/promises');
|
|
199
|
+
const deadline = Date.now() + timeoutMs;
|
|
200
|
+
while (Date.now() < deadline) {
|
|
201
|
+
const open = await new Promise<boolean>((resolve) => {
|
|
202
|
+
const socket = createConnection({ port, host: 'localhost' }, () => {
|
|
203
|
+
socket.destroy();
|
|
204
|
+
resolve(true);
|
|
205
|
+
});
|
|
206
|
+
socket.on('error', () => { socket.destroy(); resolve(false); });
|
|
207
|
+
socket.setTimeout(200, () => { socket.destroy(); resolve(false); });
|
|
208
|
+
});
|
|
209
|
+
if (!open) return;
|
|
210
|
+
await sleep(100);
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/**
|
|
215
|
+
* Decide whether a "frontend is listening" probe should be *credited* as a
|
|
216
|
+
* successful (re)spawn — and thus reset the restart budget.
|
|
217
|
+
*
|
|
218
|
+
* `waitForPort` only proves *something* is listening on `:3100`; it cannot tell
|
|
219
|
+
* our Vite apart from a foreign listener (a leftover Vite, or a second dev
|
|
220
|
+
* server). Crediting any listener would let a foreign process on `:3100` make
|
|
221
|
+
* every `--strictPort`-failing respawn look successful, neutralizing the
|
|
222
|
+
* `maxRestarts` cap and hot-looping forever. So we credit the probe only when
|
|
223
|
+
* **our** spawned child is still the live frontend process — same identity and
|
|
224
|
+
* not yet exited. A child that already exited (e.g. it lost the `--strictPort`
|
|
225
|
+
* bind race to the foreign listener) is no longer `current`, so it is not
|
|
226
|
+
* credited and its failed attempt still counts toward the budget.
|
|
227
|
+
*/
|
|
228
|
+
export function shouldCreditFrontendReady(
|
|
229
|
+
child: { exitCode: number | null; signalCode: NodeJS.Signals | null } | null,
|
|
230
|
+
current: unknown,
|
|
231
|
+
): boolean {
|
|
232
|
+
return (
|
|
233
|
+
!!child &&
|
|
234
|
+
child === current &&
|
|
235
|
+
child.exitCode === null &&
|
|
236
|
+
child.signalCode === null
|
|
237
|
+
);
|
|
238
|
+
}
|
|
239
|
+
|
|
93
240
|
export async function startDevServer(options: DevServerOptions) {
|
|
94
241
|
const {
|
|
95
242
|
port = 3000,
|
|
@@ -125,11 +272,9 @@ export async function startDevServer(options: DevServerOptions) {
|
|
|
125
272
|
// BLOCKS_API_URL server-side, so the request still reaches the deployed Lambda.
|
|
126
273
|
// This makes sandbox single-origin, matching `npm run dev` and the prod
|
|
127
274
|
// CloudFront proxy; `crossDomain` stays unnecessary.
|
|
275
|
+
const blocksConfig = buildBlocksConfig(port, isSandbox);
|
|
128
276
|
mkdirSync('.blocks-sandbox', { recursive: true });
|
|
129
|
-
writeFileSync('.blocks-sandbox/config.json', JSON.stringify(
|
|
130
|
-
apiUrl: `http://localhost:${port}${BLOCKS_RPC_PREFIX}`,
|
|
131
|
-
environment: isSandbox ? 'sandbox' : 'local',
|
|
132
|
-
}, null, 2));
|
|
277
|
+
writeFileSync('.blocks-sandbox/config.json', JSON.stringify(blocksConfig, null, 2));
|
|
133
278
|
|
|
134
279
|
// 1. Set up global collectors for plugin discovery
|
|
135
280
|
(globalThis as any).__BLOCKS_CLIENT_MIDDLEWARE__ = [];
|
|
@@ -173,6 +318,168 @@ export async function startDevServer(options: DevServerOptions) {
|
|
|
173
318
|
(res as ServerResponse).end('Frontend server unavailable');
|
|
174
319
|
});
|
|
175
320
|
|
|
321
|
+
// ── Frontend supervisor ─────────────────────────────────────────────────
|
|
322
|
+
// The frontend runs under `shell: true`, so the real dev server (Vite) is a
|
|
323
|
+
// grandchild of this process. We spawn it `detached` (its own process group)
|
|
324
|
+
// on POSIX so cleanup/restart can signal the *whole* tree and free the port;
|
|
325
|
+
// otherwise the orphaned grandchild keeps `:3100` and every `/` request 502s
|
|
326
|
+
// forever (the proxy target is hardcoded to `frontendPort`). We also bound-
|
|
327
|
+
// respawn it on unexpected death and suppress all of this during shutdown.
|
|
328
|
+
//
|
|
329
|
+
// ── POST-EXIT GROUP-KILL POLICY ─────────────────────────────────────────
|
|
330
|
+
// The exact bug this supervisor fixes is the shell *exiting* while the
|
|
331
|
+
// detached grandchild survives, orphaned, still holding `:3100`. Reaping that
|
|
332
|
+
// orphan REQUIRES a group kill (`process.kill(-pid, …)`) issued *after* the
|
|
333
|
+
// shell has already exited — so all three post-exit kill sites below agree:
|
|
334
|
+
// the respawn path, `terminateFrontend`, and the `process.on('exit')` net all
|
|
335
|
+
// group-kill rather than skip when the shell is already gone.
|
|
336
|
+
//
|
|
337
|
+
// Why this is safe against the classic `-pid` PID-reuse hazard:
|
|
338
|
+
// 1. A surviving grandchild keeps the process group non-empty, so POSIX
|
|
339
|
+
// keeps `pid` reserved as the group id — it cannot be recycled as a new
|
|
340
|
+
// process id while it is still a live group's id. Hence `-pid` is
|
|
341
|
+
// guaranteed to target *our* group precisely when it matters (an orphan
|
|
342
|
+
// is still alive in it).
|
|
343
|
+
// 2. We only ever issue the kill synchronously, the instant we observe the
|
|
344
|
+
// shell's exit — there is no intervening `await` that could let the group
|
|
345
|
+
// drain and the pid be recycled — so the residual window is minimal.
|
|
346
|
+
// Residual accepted risk: if the ENTIRE group is already gone *and* `pid` has
|
|
347
|
+
// since been recycled into a brand-new group leader, `-pid` could signal an
|
|
348
|
+
// unrelated group. This is an accepted best-effort trade-off — there is then
|
|
349
|
+
// nothing of ours left to reap, whereas skipping the kill would otherwise
|
|
350
|
+
// leave `:3100` wedged, which is the failure this PR exists to prevent.
|
|
351
|
+
//
|
|
352
|
+
// Where each post-exit kill site lands on this trade-off: the two sites *in
|
|
353
|
+
// this file* — the respawn reap (in the child's `exit` handler) and the
|
|
354
|
+
// `process.on('exit')` net — fire synchronously the instant we observe the
|
|
355
|
+
// exit, so they lean on point (2) above and stay unconditional. The third
|
|
356
|
+
// path, `terminateFrontend` → `terminateProcessTree` (process-tree.ts), can
|
|
357
|
+
// run outside that minimal synchronous window, so it additionally PROBES group
|
|
358
|
+
// liveness (POSIX signal 0) and skips the reap once the group has fully
|
|
359
|
+
// drained — see its "POST-EXIT GROUP-KILL (scoped)" comment.
|
|
360
|
+
const usePosixProcessGroups = process.platform !== 'win32';
|
|
361
|
+
let isShuttingDown = false;
|
|
362
|
+
let frontendRestarts: number[] = [];
|
|
363
|
+
let respawnTimer: ReturnType<typeof setTimeout> | null = null;
|
|
364
|
+
|
|
365
|
+
const announceFrontendReady = async (child: ChildProcess | null, suffix = ''): Promise<void> => {
|
|
366
|
+
try {
|
|
367
|
+
await waitForPort(frontendPort);
|
|
368
|
+
// Reset the restart budget only when OUR child is the one now bound to
|
|
369
|
+
// `:3100`. `waitForPort` is a liveness-only probe — it cannot tell our
|
|
370
|
+
// Vite from a foreign listener (a leftover Vite or a second dev server),
|
|
371
|
+
// and crediting a foreign listener would make every `--strictPort`-failing
|
|
372
|
+
// respawn look successful, neutralizing the `maxRestarts` cap and
|
|
373
|
+
// hot-looping forever (see {@link shouldCreditFrontendReady}). Only
|
|
374
|
+
// *consecutive failing* restarts should count toward the give-up
|
|
375
|
+
// threshold, so a frontend that legitimately restarts many times (e.g.
|
|
376
|
+
// editor-triggered Vite full reloads) still never gets left down.
|
|
377
|
+
if (shouldCreditFrontendReady(child, frontendProcess)) {
|
|
378
|
+
frontendRestarts = [];
|
|
379
|
+
}
|
|
380
|
+
console.log(`\n ➜ http://localhost:${port}/${suffix}\n`);
|
|
381
|
+
} catch (e) {
|
|
382
|
+
console.error(`⚠️ Frontend did not start: ${(e as Error).message}`);
|
|
383
|
+
console.log(`\n ➜ http://localhost:${port}/ (API only — frontend unavailable)\n`);
|
|
384
|
+
}
|
|
385
|
+
};
|
|
386
|
+
|
|
387
|
+
const spawnFrontend = (command: string): ChildProcess => {
|
|
388
|
+
const child = spawn(command, {
|
|
389
|
+
shell: true,
|
|
390
|
+
// Own process group on POSIX so we can reap the Vite grandchild too.
|
|
391
|
+
detached: usePosixProcessGroups,
|
|
392
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
393
|
+
env: { ...process.env, NODE_OPTIONS: '' },
|
|
394
|
+
});
|
|
395
|
+
frontendProcess = child;
|
|
396
|
+
|
|
397
|
+
// Suppress frontend output — only show errors.
|
|
398
|
+
child.stderr?.on('data', (d: Buffer) => {
|
|
399
|
+
const msg = d.toString();
|
|
400
|
+
if (!msg.includes('DeprecationWarning')) process.stderr.write(msg);
|
|
401
|
+
});
|
|
402
|
+
|
|
403
|
+
child.on('exit', (code, signal) => {
|
|
404
|
+
// Ignore exits from a process we've already replaced or torn down.
|
|
405
|
+
if (child !== frontendProcess) return;
|
|
406
|
+
frontendProcess = null;
|
|
407
|
+
if (isShuttingDown) return;
|
|
408
|
+
// Reap any orphaned grandchild left in this child's group so `:3100` is
|
|
409
|
+
// free before we respawn — otherwise `--strictPort` makes the new Vite
|
|
410
|
+
// exit on bind and we'd spin until the restart budget is gone. The shell
|
|
411
|
+
// has already exited here (we are inside its `exit` handler), so this is a
|
|
412
|
+
// post-exit group kill; it is issued synchronously in this handler and is
|
|
413
|
+
// safe against PID reuse — see POST-EXIT GROUP-KILL POLICY above.
|
|
414
|
+
killFrontendTree(child, 'SIGKILL');
|
|
415
|
+
|
|
416
|
+
const decision = evaluateFrontendRespawn(frontendRestarts, Date.now());
|
|
417
|
+
frontendRestarts = decision.recent;
|
|
418
|
+
const why = `code=${code ?? 'null'}, signal=${signal ?? 'null'}`;
|
|
419
|
+
if (!decision.restart) {
|
|
420
|
+
console.error(
|
|
421
|
+
`⚠️ Frontend dev server exited (${why}) and exceeded ` +
|
|
422
|
+
`${DEFAULT_FRONTEND_RESPAWN_POLICY.maxRestarts} restarts within ` +
|
|
423
|
+
`${DEFAULT_FRONTEND_RESPAWN_POLICY.windowMs / 1000}s — leaving it down. ` +
|
|
424
|
+
`Fix the error above, then restart \`npm run dev\`.`,
|
|
425
|
+
);
|
|
426
|
+
return;
|
|
427
|
+
}
|
|
428
|
+
console.error(`⚠️ Frontend dev server exited (${why}); restarting in ${decision.delayMs}ms…`);
|
|
429
|
+
respawnTimer = setTimeout(() => {
|
|
430
|
+
respawnTimer = null;
|
|
431
|
+
if (isShuttingDown) return;
|
|
432
|
+
// Before relaunching, wait (bounded) for `:3100` to actually free —
|
|
433
|
+
// mirroring the graceful `terminateFrontend` path. The synchronous
|
|
434
|
+
// post-exit SIGKILL above only *initiates* teardown of the orphaned
|
|
435
|
+
// group; the kernel can still hold the listening socket for a beat, and a
|
|
436
|
+
// relaunched `--strictPort` Vite would then hit `EADDRINUSE` and burn a
|
|
437
|
+
// restart-budget slot on a race that isn't a real crash. The budget was
|
|
438
|
+
// already debited above, so this never double-counts a restart; re-check
|
|
439
|
+
// `isShuttingDown` after the await, since a shutdown signal can land while
|
|
440
|
+
// we wait (`waitForPortFree` is bounded, so it can't deadlock shutdown).
|
|
441
|
+
void (async () => {
|
|
442
|
+
await waitForPortFree(frontendPort);
|
|
443
|
+
if (isShuttingDown) return;
|
|
444
|
+
const next = spawnFrontend(command);
|
|
445
|
+
await announceFrontendReady(next, ' (frontend restarted)');
|
|
446
|
+
})();
|
|
447
|
+
}, decision.delayMs);
|
|
448
|
+
// INTENTIONAL unref: the listening HTTP `server` (created below) owns this
|
|
449
|
+
// process's lifetime — the backoff timer must NOT, by itself, keep the
|
|
450
|
+
// event loop alive. Without unref a pending respawn timer would hold the
|
|
451
|
+
// process up during shutdown (or after the server has closed), delaying or
|
|
452
|
+
// blocking a clean exit. This never drops a legitimately-needed respawn:
|
|
453
|
+
// `cleanup` explicitly clears this timer, and both the timer body and the
|
|
454
|
+
// awaited relaunch re-check `isShuttingDown`. Do NOT remove the unref to
|
|
455
|
+
// "fix" a perceived missed restart — it would reintroduce that shutdown hang.
|
|
456
|
+
respawnTimer.unref?.();
|
|
457
|
+
});
|
|
458
|
+
|
|
459
|
+
return child;
|
|
460
|
+
};
|
|
461
|
+
|
|
462
|
+
/**
|
|
463
|
+
* Gracefully terminate the frontend tree and wait (bounded) for the port to
|
|
464
|
+
* actually free before this process exits, so a `tsx watch` relaunch can
|
|
465
|
+
* rebind `:3100` cleanly. SIGTERM the group, escalate to SIGKILL if it lingers
|
|
466
|
+
* (via the shared {@link terminateProcessTree}), then poll until `:3100` is
|
|
467
|
+
* released. tsx-watch gives us ~5s before it force-kills us, so this budget is
|
|
468
|
+
* safe. Crucially the port-free wait runs on *both* paths — including when the
|
|
469
|
+
* shell has already exited — so the post-exit branch no longer drops the
|
|
470
|
+
* "wait for the port to free" guarantee.
|
|
471
|
+
*/
|
|
472
|
+
const terminateFrontend = async (child: ChildProcess | null): Promise<void> => {
|
|
473
|
+
if (!child) return;
|
|
474
|
+
// SIGTERM→SIGKILL the whole tree, reaping the detached Vite grandchild even
|
|
475
|
+
// when the shell has already exited (post-exit group kill — see policy).
|
|
476
|
+
await terminateProcessTree(child, 1500);
|
|
477
|
+
// Then wait (bounded) for `:3100` to be released. The old post-exit branch
|
|
478
|
+
// returned right after SIGKILL with no port poll, so a relaunch could race
|
|
479
|
+
// the kernel's socket teardown and hit `--strictPort` `EADDRINUSE`.
|
|
480
|
+
await waitForPortFree(frontendPort);
|
|
481
|
+
};
|
|
482
|
+
|
|
176
483
|
// ── API Gateway proxy (sandbox mode) ───────────────────────────────────
|
|
177
484
|
// `changeOrigin: true` rewrites the outgoing `Host` to the execute-api target
|
|
178
485
|
// (required for API Gateway's TLS SNI / host-based routing). That would make
|
|
@@ -221,6 +528,21 @@ export async function startDevServer(options: DevServerOptions) {
|
|
|
221
528
|
return;
|
|
222
529
|
}
|
|
223
530
|
|
|
531
|
+
// ── Blocks runtime config ──────────────────────────────────────────
|
|
532
|
+
// Reserved path: serve it from the front door so it works for every
|
|
533
|
+
// framework (Next/Nuxt/Astro/SPA all proxy through this :3000 server),
|
|
534
|
+
// mirroring production where CloudFront serves `${BLOCKS_SANDBOX_PREFIX}/*`
|
|
535
|
+
// statically. Otherwise the request is proxied to the framework dev
|
|
536
|
+
// server, which can't serve this project-root file and 404s.
|
|
537
|
+
if (isBlocksConfigRequest(method, url.pathname)) {
|
|
538
|
+
res.writeHead(200, {
|
|
539
|
+
'Content-Type': 'application/json',
|
|
540
|
+
'Cache-Control': 'no-store',
|
|
541
|
+
});
|
|
542
|
+
res.end(JSON.stringify(blocksConfig));
|
|
543
|
+
return;
|
|
544
|
+
}
|
|
545
|
+
|
|
224
546
|
// ── API/RawRoute requests ──────────────────────────────────────────
|
|
225
547
|
if (isApiRequest(method, url.pathname)) {
|
|
226
548
|
if (isSandbox && apiProxy) {
|
|
@@ -277,35 +599,14 @@ export async function startDevServer(options: DevServerOptions) {
|
|
|
277
599
|
}
|
|
278
600
|
|
|
279
601
|
// ── Start listening ────────────────────────────────────────────────────
|
|
280
|
-
server.listen(port,
|
|
602
|
+
server.listen(port, async () => {
|
|
281
603
|
console.log(`AWS Blocks local server running on http://localhost:${port}`);
|
|
282
604
|
buildAndSendEvent({ command: 'dev', state: 'SUCCESS', duration: Date.now() - devStartTime });
|
|
283
605
|
|
|
284
606
|
// Spawn frontend dev server after Blocks server is ready
|
|
285
607
|
if (frontendCommand) {
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
stdio: ['ignore', 'pipe', 'pipe'],
|
|
289
|
-
env: { ...process.env, NODE_OPTIONS: '' },
|
|
290
|
-
});
|
|
291
|
-
// Suppress frontend output — only show errors
|
|
292
|
-
frontendProcess.stderr?.on('data', (d: Buffer) => {
|
|
293
|
-
const msg = d.toString();
|
|
294
|
-
if (!msg.includes('DeprecationWarning')) process.stderr.write(msg);
|
|
295
|
-
});
|
|
296
|
-
frontendProcess.on('exit', (code) => {
|
|
297
|
-
if (code !== 0 && code !== null) {
|
|
298
|
-
console.error(`⚠️ Frontend process exited with code ${code}`);
|
|
299
|
-
}
|
|
300
|
-
});
|
|
301
|
-
|
|
302
|
-
try {
|
|
303
|
-
await waitForPort(frontendPort);
|
|
304
|
-
console.log(`\n ➜ http://localhost:${port}/\n`);
|
|
305
|
-
} catch (e) {
|
|
306
|
-
console.error(`⚠️ Frontend did not start: ${(e as Error).message}`);
|
|
307
|
-
console.log(`\n ➜ http://localhost:${port}/ (API only — frontend unavailable)\n`);
|
|
308
|
-
}
|
|
608
|
+
const child = spawnFrontend(frontendCommand);
|
|
609
|
+
await announceFrontendReady(child);
|
|
309
610
|
} else {
|
|
310
611
|
console.log(`\n ➜ http://localhost:${port}/\n`);
|
|
311
612
|
}
|
|
@@ -317,9 +618,24 @@ export async function startDevServer(options: DevServerOptions) {
|
|
|
317
618
|
});
|
|
318
619
|
|
|
319
620
|
// ── Cleanup ────────────────────────────────────────────────────────────
|
|
621
|
+
const signals: NodeJS.Signals[] = ['SIGINT', 'SIGTERM', 'SIGHUP'];
|
|
622
|
+
let cleaningUp = false;
|
|
320
623
|
const cleanup = async () => {
|
|
624
|
+
if (cleaningUp) return; // idempotent — a second signal must not re-enter
|
|
625
|
+
cleaningUp = true;
|
|
626
|
+
isShuttingDown = true; // stop the supervisor from respawning the frontend
|
|
321
627
|
console.log('\nShutting down...');
|
|
322
|
-
|
|
628
|
+
|
|
629
|
+
if (respawnTimer) { clearTimeout(respawnTimer); respawnTimer = null; }
|
|
630
|
+
// Detach our own listeners so repeated signals can't pile up handlers.
|
|
631
|
+
for (const sig of signals) process.removeListener(sig, cleanup);
|
|
632
|
+
|
|
633
|
+
// Kill the frontend process *group* and wait for the port to free before
|
|
634
|
+
// we exit, so a tsx-watch restart can rebind `:3100` cleanly.
|
|
635
|
+
const child = frontendProcess;
|
|
636
|
+
frontendProcess = null;
|
|
637
|
+
await terminateFrontend(child);
|
|
638
|
+
|
|
323
639
|
if (typeof backend.__cleanup === 'function') {
|
|
324
640
|
try { await backend.__cleanup(); } catch {}
|
|
325
641
|
}
|
|
@@ -329,8 +645,23 @@ export async function startDevServer(options: DevServerOptions) {
|
|
|
329
645
|
setTimeout(() => process.exit(0), 2000).unref();
|
|
330
646
|
};
|
|
331
647
|
|
|
332
|
-
process.on(
|
|
333
|
-
|
|
648
|
+
for (const sig of signals) process.on(sig, cleanup);
|
|
649
|
+
|
|
650
|
+
// Last-resort safety net for paths that bypass `cleanup` (e.g. an uncaught
|
|
651
|
+
// exception terminating the process): synchronously reap the frontend tree so
|
|
652
|
+
// a `detached` Vite is never left orphaned on `:3100`. Reuses
|
|
653
|
+
// `killFrontendTree`, so unlike the old hand-rolled `process.kill(-pid)` it
|
|
654
|
+
// also reaps on Windows (via `taskkill`) instead of early-returning and
|
|
655
|
+
// leaking the Vite tree, and stays in lockstep with the other kill sites. Both
|
|
656
|
+
// the POSIX group kill and the Windows `taskkill` are synchronous, so this is
|
|
657
|
+
// legal in an `exit` handler; it reaps even when the shell has already exited
|
|
658
|
+
// (a surviving grandchild keeps the group alive) — see POST-EXIT GROUP-KILL
|
|
659
|
+
// POLICY above.
|
|
660
|
+
process.once('exit', () => {
|
|
661
|
+
const child = frontendProcess;
|
|
662
|
+
if (!child) return;
|
|
663
|
+
killFrontendTree(child, 'SIGKILL');
|
|
664
|
+
});
|
|
334
665
|
}
|
|
335
666
|
|
|
336
667
|
// ── Local API handler ────────────────────────────────────────────────────────
|
package/src/scripts/index.ts
CHANGED