localgate 0.5.0 → 0.6.1

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.
@@ -1,18 +1,18 @@
1
1
  import { spawn, type ChildProcess } from "node:child_process";
2
- import { createServer, type Server } from "node:http";
3
2
  import { readFileSync } from "node:fs";
4
3
  import { createServer as createSocketServer } from "node:net";
5
4
  import { join } from "node:path";
6
- import { createInterface } from "node:readline/promises";
7
5
  import { LocalgateBanner } from "../cli/localgateBanner.ts";
8
6
  import { LocalgateProxyClient } from "../client/localgateProxyClient.ts";
9
7
  import { LocalgateMachineConfig, type LocalgateMachineSettings } from "../config/localgateMachineConfig.ts";
10
8
  import { LocalgateNames } from "../config/localgateNames.ts";
11
9
  import { LocalgateProjectConfig, type LocalgateProjectSettings } from "../config/localgateProjectConfig.ts";
12
- import type { LocalgateRoute } from "../proxy/localgateRegistry.ts";
13
- import { LocalgateUrl } from "../proxy/localgateUrl.ts";
10
+ import { LocalgateRouteConflictError } from "../proxy/localgateRegistry.ts";
11
+ import type { LocalgateRoute, LocalgateRouteRegistration } from "../proxy/localgateRegistry.ts";
14
12
  import { LocalgateEnvRewrite } from "./localgateEnvRewrite.ts";
15
- import { LocalgateProcessTree } from "./localgateProcessTree.ts";
13
+ import { LocalgateNodeOptions } from "./localgateNodeOptions.ts";
14
+ import { LocalgateProcessTree, type LocalgateKillOutcome } from "./localgateProcessTree.ts";
15
+ import { LocalgateRunnerControl } from "./localgateRunnerControl.ts";
16
16
 
17
17
  type LocalgateRunnerRuntime =
18
18
  {
@@ -29,14 +29,17 @@ export class LocalgateRunner
29
29
  private static readonly logLinesKeptConst = 400;
30
30
  private static readonly heartbeatMsConst = 10_000;
31
31
  private static readonly takeoverTimeoutMsConst = 10_000;
32
+ private static readonly replacementTimeoutMsConst = 10_000;
33
+ private static readonly replacementPollMsConst = 50;
32
34
 
33
35
  private child: ChildProcess | null = null;
34
- private controlServer: Server | null = null;
36
+ private control: LocalgateRunnerControl | null = null;
35
37
  private route: LocalgateRoute | null = null;
36
38
  private runtime: LocalgateRunnerRuntime | null = null;
37
39
  private readonly logs: string[] = [];
38
40
  private stopping = false;
39
41
  private restarting = false;
42
+ private reportedLostRoute = false;
40
43
  private exitCode = 0;
41
44
 
42
45
  constructor(
@@ -78,11 +81,14 @@ export class LocalgateRunner
78
81
  const body = scripts[script] ?? "";
79
82
  if (!body.includes("next")) return command;
80
83
 
84
+ // pnpm forwards a separator to the script, where Next treats the following flags as positional arguments.
85
+ if (runner == "pnpm" || runner == "pnpm.cmd") return [...command, "-p", String(port)];
86
+
81
87
  return [...command, "--", "-p", String(port)];
82
88
  }
83
89
 
84
- // Shown before the question, and instead of it when there is no terminal to ask in: whoever is about
85
- // to lose their dev server should be able to recognise it from this alone.
90
+ // Shown before the takeover, and instead of it when there is no terminal: whoever is about to lose
91
+ // their dev server should be able to recognise it from this alone.
86
92
  static describeRunning(route: LocalgateRoute): string
87
93
  {
88
94
  const lines = [
@@ -111,6 +117,19 @@ export class LocalgateRunner
111
117
  return registered?.runnerPid == runnerPid && registered.controlUrl == route.controlUrl;
112
118
  }
113
119
 
120
+ // Whether the kill got far enough for a restart or a stop to be called done, and what to report when it
121
+ // did not. The kill used to be fire-and-forget, so a taskkill the system refused left the old dev server
122
+ // holding the port while `localgate restart` printed "restarted" and the browser went on being served
123
+ // the old build. A port that came free is the fact this trusts; the errors only say why it did not.
124
+ static killFailure(route: LocalgateRoute, pid: number, outcome: LocalgateKillOutcome,
125
+ action: "restarted" | "stopped"): string | null
126
+ {
127
+ if (outcome.released) return null;
128
+
129
+ return `${route.names[0]} still answers on 127.0.0.1:${route.port} after killing ${pid}`
130
+ + `${LocalgateProcessTree.describeErrors(outcome)} - it was not ${action}`;
131
+ }
132
+
114
133
  static async freePort(): Promise<number>
115
134
  {
116
135
  return new Promise<number>((resolve, reject) =>
@@ -138,14 +157,26 @@ export class LocalgateRunner
138
157
 
139
158
  const runtime = this.loadRuntime();
140
159
 
141
- const blocked = await this.clearPredecessor(runtime.project);
142
- if (blocked != 0) return blocked;
160
+ // Refused before the proxy is even asked for: the name belongs to localgate's own start page, so the
161
+ // registration would fail anyway, and here the message can name the file that decides it.
162
+ if (LocalgateNames.isReserved(runtime.project.name))
163
+ {
164
+ process.stderr.write(`localgate: "${LocalgateNames.startNameConst}" is reserved for localgate's start `
165
+ + `page, so this project cannot use it as a name. Set "localgate": { "name": "..." } in `
166
+ + `${runtime.project.packageDirectory}/package.json.\n`);
167
+ return 1;
168
+ }
169
+
170
+ // Before the check and not after it: the route table lives in the proxy, so asking what already
171
+ // runs while the proxy is down answers "nothing" about a machine full of dev servers.
172
+ await LocalgateProxyClient.ensureRunning();
173
+
174
+ if (!await this.clearPredecessor(runtime.project)) return 1;
143
175
 
144
176
  const port = await LocalgateRunner.freePort();
145
177
  const controlUrl = await this.startControlServer();
146
178
 
147
- await LocalgateProxyClient.ensureRunning();
148
- const route = await LocalgateProxyClient.register({
179
+ const route = await this.claim({
149
180
  names: runtime.names,
150
181
  port,
151
182
  kind: "app",
@@ -157,6 +188,13 @@ export class LocalgateRunner
157
188
  childPid: null,
158
189
  debuggerAttached: LocalgateRunner.debuggerAttached()
159
190
  });
191
+
192
+ if (!route)
193
+ {
194
+ await this.cleanup();
195
+ return 1;
196
+ }
197
+
160
198
  this.route = route;
161
199
  this.runtime = runtime;
162
200
 
@@ -176,53 +214,82 @@ export class LocalgateRunner
176
214
  // Starting a second dev server for one project used to fail twice over: the registry handed this
177
215
  // runner the name and left the old one holding its port unreachable, and the dev server itself then
178
216
  // refused because of its own lock. So the collision is settled here, before anything is claimed.
179
- // Returns 0 to go ahead, or the exit code to leave with.
180
- private async clearPredecessor(project: LocalgateProjectSettings): Promise<number>
217
+ // Returns whether the run may go ahead.
218
+ private async clearPredecessor(project: LocalgateProjectSettings): Promise<boolean>
181
219
  {
182
220
  // By name, because that is what the registry would take away, and by directory, because that is
183
221
  // what a dev server's own lock is keyed on.
184
222
  const existing = await LocalgateProxyClient.resolve({ name: project.name })
185
223
  ?? await LocalgateProxyClient.resolve({ directory: project.packageDirectory });
186
224
 
187
- if (!existing) return 0;
225
+ if (!existing) return true;
226
+ return this.settle(existing);
227
+ }
228
+
229
+ // The registration is the second place a collision shows up, and the one no check can prevent: the
230
+ // route table lives in the proxy, so between the check above and this claim another runner can take
231
+ // the name. A proxy that has just started is that race in practice - its table is empty, and the live
232
+ // runners refill it from their own heartbeats up to ten seconds later, so the check sees a free name
233
+ // that is not free. This used to end the process with a stack trace. It is now settled exactly like
234
+ // the collision the check finds, and the claim is made once more.
235
+ private async claim(registration: LocalgateRouteRegistration): Promise<LocalgateRoute | null>
236
+ {
237
+ try
238
+ {
239
+ return await LocalgateProxyClient.register(registration);
240
+ }
241
+ catch (error)
242
+ {
243
+ if (!(error instanceof LocalgateRouteConflictError)) throw error;
244
+ if (!await this.settle(error.existing)) return null;
245
+ }
246
+
247
+ try
248
+ {
249
+ return await LocalgateProxyClient.register(registration);
250
+ }
251
+ catch (error)
252
+ {
253
+ if (!(error instanceof LocalgateRouteConflictError)) throw error;
254
+ process.stderr.write(`localgate: ${error.existing.names[0]} was claimed by runner `
255
+ + `${error.existing.runnerPid ?? "?"} while this one was taking it over - run again\n`);
256
+ return null;
257
+ }
258
+ }
188
259
 
260
+ // What happens to whoever holds the name: an alias is not ours to take, a route whose runner is gone
261
+ // is cleared, and a live runner is stopped when this run has a terminal. That used to be a question,
262
+ // but starting the project again from a terminal is the editor's restart button, and in a compound
263
+ // launch the question waited in a terminal nobody looked at, leaving that project on its old build.
264
+ // Without a terminal the caller is an agent or a CI job, which must not end the developer's session
265
+ // by accident, so it gets the facts and needs --force.
266
+ private async settle(existing: LocalgateRoute): Promise<boolean>
267
+ {
189
268
  if (existing.kind == "alias")
190
269
  {
191
270
  process.stderr.write(`localgate: ${existing.names[0]} is an alias pointing at 127.0.0.1:${existing.port}, `
192
271
  + "so this project cannot claim that name.\n"
193
272
  + "Remove the alias, or give the project another name in package.json.\n");
194
- return 1;
273
+ return false;
195
274
  }
196
275
 
197
276
  if (!await LocalgateRunner.runnerAlive(existing))
198
277
  {
199
278
  await LocalgateRunner.reclaimAbandoned(existing);
200
- return 0;
279
+ return true;
201
280
  }
202
281
 
203
- if (!this.force)
204
- {
205
- process.stdout.write(LocalgateRunner.describeRunning(existing));
206
-
207
- // Asking without a terminal would block until somebody kills this process, so a non-interactive
208
- // caller gets the facts and a flag instead.
209
- if (process.stdin.isTTY !== true)
210
- {
211
- process.stderr.write("localgate: nothing to ask on, this is not a terminal. "
212
- + "Re-run with --force to take it over.\n");
213
- return 1;
214
- }
282
+ process.stdout.write(LocalgateRunner.describeRunning(existing));
215
283
 
216
- if (!await LocalgateRunner.askTakeover())
217
- {
218
- process.stdout.write("localgate: left it running. Reach it at "
219
- + `${LocalgateUrl.forName(existing.names[0], LocalgateProxyClient.proxyPort())}\n`);
220
- return 1;
221
- }
284
+ if (!this.force && process.stdin.isTTY !== true)
285
+ {
286
+ process.stderr.write("localgate: left it running, this is not a terminal. "
287
+ + "Re-run with --force to take it over.\n");
288
+ return false;
222
289
  }
223
290
 
224
291
  await this.stopPredecessor(existing);
225
- return 0;
292
+ return true;
226
293
  }
227
294
 
228
295
  // A runner that died without cleaning up leaves a row behind, and usually its dev server too: the
@@ -238,9 +305,10 @@ export class LocalgateRunner
238
305
  process.stdout.write(`localgate: ${route.names[0]} was left behind by a runner that is gone, `
239
306
  + `clearing 127.0.0.1:${route.port}\n`);
240
307
 
241
- if (!await LocalgateProcessTree.killPortHolder(route.port, LocalgateRunner.takeoverTimeoutMsConst))
242
- process.stderr.write(`localgate: 127.0.0.1:${route.port} is still held - `
243
- + "stop that process by hand, then run again\n");
308
+ const outcome = await LocalgateProcessTree.killPortHolder(route.port, LocalgateRunner.takeoverTimeoutMsConst);
309
+ if (!outcome.released)
310
+ process.stderr.write(`localgate: 127.0.0.1:${route.port} is still held`
311
+ + `${LocalgateProcessTree.describeErrors(outcome)} - stop that process by hand, then run again\n`);
244
312
  }
245
313
 
246
314
  await LocalgateProxyClient.deregister(route.id).catch(() => {});
@@ -255,26 +323,6 @@ export class LocalgateRunner
255
323
  .catch(() => false);
256
324
  }
257
325
 
258
- private static async askTakeover(): Promise<boolean>
259
- {
260
- const reader = createInterface({ input: process.stdin, output: process.stdout });
261
- reader.once("SIGINT", () =>
262
- {
263
- reader.close();
264
- process.exit(1);
265
- });
266
-
267
- try
268
- {
269
- const answer = await reader.question("Stop it and take over? [Y/n] ");
270
- return !/^n/i.test(answer.trim());
271
- }
272
- finally
273
- {
274
- reader.close();
275
- }
276
- }
277
-
278
326
  // The old runner's own stop endpoint is the good path: it kills its child tree, releases the port and
279
327
  // deregisters itself, so its terminal ends cleanly. Killing by pid is the fallback for a runner that
280
328
  // no longer answers, and the port has to actually come free either way.
@@ -297,11 +345,12 @@ export class LocalgateRunner
297
345
  if (pid === null)
298
346
  throw new Error(`${route.names[0]} did not stop and has no pid to kill - stop it by hand`);
299
347
 
300
- await LocalgateProcessTree.killTree(pid, route.port, LocalgateRunner.takeoverTimeoutMsConst);
348
+ const outcome = await LocalgateProcessTree.killTree(pid, route.port, LocalgateRunner.takeoverTimeoutMsConst);
301
349
  await LocalgateProxyClient.deregister(route.id).catch(() => {});
302
350
 
303
- if (await LocalgateProcessTree.isPortListening(route.port))
304
- throw new Error(`${route.names[0]} still holds 127.0.0.1:${route.port} - stop it by hand`);
351
+ if (!outcome.released)
352
+ throw new Error(`${route.names[0]} still holds 127.0.0.1:${route.port}`
353
+ + `${LocalgateProcessTree.describeErrors(outcome)} - stop it by hand`);
305
354
  }
306
355
 
307
356
  private spawnChild(port: number): Promise<void>
@@ -312,8 +361,12 @@ export class LocalgateRunner
312
361
  const scripts = LocalgateRunner.readScripts(runtime.project.packageDirectory);
313
362
  const command = LocalgateRunner.withPortFlag(this.command, scripts, port);
314
363
 
315
- const env = LocalgateEnvRewrite.apply(process.env, runtime.project.mode, runtime.machine,
316
- LocalgateProxyClient.proxyPort());
364
+ const env = LocalgateNodeOptions.apply(LocalgateEnvRewrite.apply(
365
+ process.env,
366
+ runtime.project.mode,
367
+ runtime.machine,
368
+ LocalgateProxyClient.proxyPort()
369
+ ));
317
370
  env.PORT = String(port);
318
371
 
319
372
  // One command string rather than a command plus an args array: `npm run dev` on Windows is a .cmd,
@@ -354,12 +407,17 @@ export class LocalgateRunner
354
407
  return;
355
408
  }
356
409
 
357
- this.exitCode = code ?? 0;
410
+ // A stop kills it on purpose too, and there the result of the run is the stop's, not the code a
411
+ // dev server leaves behind when it is killed.
412
+ if (!this.stopping) this.exitCode = code ?? 0;
358
413
  resolve();
359
414
  });
360
415
  });
361
416
  }
362
417
 
418
+ // A restart is two facts, and answering before both are in is how a route came to report "restarted"
419
+ // while the old process went on serving: the old tree is gone with its port free, and a replacement
420
+ // child is running. Either one missing is a failed restart, and the caller is told which.
363
421
  private async restartChild(): Promise<void>
364
422
  {
365
423
  const child = this.child;
@@ -372,7 +430,56 @@ export class LocalgateRunner
372
430
  });
373
431
  this.runtime = runtime;
374
432
  this.restarting = true;
375
- await LocalgateProcessTree.killTree(child.pid, this.route.port);
433
+
434
+ const outcome = await LocalgateProcessTree.killTree(child.pid, this.route.port);
435
+ const failure = LocalgateRunner.killFailure(this.route, child.pid, outcome, "restarted");
436
+ if (failure !== null)
437
+ {
438
+ // Nothing died, so nothing will exit and nothing will respawn. The flag has to go back, or an exit
439
+ // this restart never caused would be taken for its replacement.
440
+ this.restarting = false;
441
+ throw new Error(failure);
442
+ }
443
+
444
+ if (!await this.waitForReplacement(child, LocalgateRunner.replacementTimeoutMsConst))
445
+ throw new Error(`${this.route.names[0]} released 127.0.0.1:${this.route.port} but started no `
446
+ + `replacement process within ${LocalgateRunner.replacementTimeoutMsConst / 1_000}s`);
447
+ }
448
+
449
+ // A stop is a request that can be refused, and that is the whole difference from the signal path: the
450
+ // kill runs first and what it achieved is the answer. Answering before it left a stop the system had
451
+ // turned down looking exactly like one that worked - the route gone, this runner gone, the old dev
452
+ // server still on its port, and `localgate stop` printing "stopped".
453
+ private async stopChild(): Promise<void>
454
+ {
455
+ const child = this.child;
456
+ if (!child?.pid || !this.route) return;
457
+
458
+ this.stopping = true;
459
+ const outcome = await LocalgateProcessTree.killTree(child.pid, this.route.port);
460
+ const failure = LocalgateRunner.killFailure(this.route, child.pid, outcome, "stopped");
461
+ if (failure === null) return;
462
+
463
+ // Nothing died, so this runner stays with what it could not kill: its route still points at the
464
+ // process that is serving, and that process still has an owner the next stop can ask. Exiting here
465
+ // would leave it holding the port with no route and nobody to end it but the operator, by hand.
466
+ this.stopping = false;
467
+ throw new Error(failure);
468
+ }
469
+
470
+ // The replacement is spawned by the old child's own exit handler, so the kill returning is not yet a
471
+ // restart. The flag is left alone here: a child still on its way out respawns after this gave up, and
472
+ // reporting a restart that did not finish in time is better than ending the runner on its next exit.
473
+ private async waitForReplacement(previous: ChildProcess, timeoutMs: number): Promise<boolean>
474
+ {
475
+ const deadline = Date.now() + timeoutMs;
476
+ for (;;)
477
+ {
478
+ const current = this.child;
479
+ if (current !== null && current !== previous) return true;
480
+ if (Date.now() >= deadline) return false;
481
+ await new Promise(resolve => setTimeout(resolve, LocalgateRunner.replacementPollMsConst));
482
+ }
376
483
  }
377
484
 
378
485
  private absorb(chunk: Buffer, sink: NodeJS.WriteStream): void
@@ -388,60 +495,17 @@ export class LocalgateRunner
388
495
 
389
496
  private startControlServer(): Promise<string>
390
497
  {
391
- const server = createServer((request, response) =>
392
- {
393
- const url = new URL(request.url ?? "/", "http://127.0.0.1");
394
- const send = (status: number, payload: unknown) =>
395
- {
396
- const body = JSON.stringify(payload);
397
- response.writeHead(status, { "content-type": "application/json", "content-length": Buffer.byteLength(body) });
398
- response.end(body);
399
- };
400
-
401
- if (url.pathname == "/ping") return send(200, { ok: true, id: this.route?.id ?? null });
402
-
403
- if (url.pathname == "/logs")
404
- {
405
- const lines = Number.parseInt(url.searchParams.get("lines") ?? "80", 10);
406
- return send(200, { lines: this.logs.slice(-Math.max(1, lines)) });
407
- }
408
-
409
- if (url.pathname == "/restart" && request.method == "POST")
410
- {
411
- void this.restartChild().then(
412
- () => send(200, { ok: true }),
413
- (error: unknown) => send(409, { error: String(error) })
414
- );
415
- return;
416
- }
417
-
418
- if (url.pathname == "/stop" && request.method == "POST")
419
- {
420
- send(200, { ok: true });
421
- void this.shutdown(0);
422
- return;
423
- }
424
-
425
- return send(404, { error: `unknown ${request.method} ${url.pathname}` });
498
+ const control = new LocalgateRunnerControl({
499
+ routeId: () => this.route?.id ?? null,
500
+ logs: lines => this.logs.slice(-lines),
501
+ restart: () => this.restartChild(),
502
+ stop: () => this.stopChild(),
503
+ // The child is gone and its port is free, so what is left of the stop is this runner's own exit.
504
+ stopped: () => void this.end(0)
426
505
  });
427
506
 
428
- this.controlServer = server;
429
-
430
- // Loopback only: the restart channel must not be reachable from the LAN.
431
- return new Promise<string>((resolve, reject) =>
432
- {
433
- server.once("error", reject);
434
- server.listen(0, "127.0.0.1", () =>
435
- {
436
- const address = server.address();
437
- if (!address || typeof address == "string")
438
- {
439
- reject(new Error("control server has no port"));
440
- return;
441
- }
442
- resolve(`http://127.0.0.1:${address.port}`);
443
- });
444
- });
507
+ this.control = control;
508
+ return control.start();
445
509
  }
446
510
 
447
511
  // The proxy holds the route table in memory, so if it dies the route dies with it. Another runner may
@@ -477,10 +541,23 @@ export class LocalgateRunner
477
541
  childPid: this.child?.pid ?? null,
478
542
  debuggerAttached: this.route.debuggerAttached
479
543
  });
544
+ this.reportedLostRoute = false;
480
545
  process.stdout.write("localgate: proxy restarted, route re-registered\n");
481
546
  }
482
547
  catch (error)
483
548
  {
549
+ // Another runner serves this name now, so every following heartbeat fails the same way. Said
550
+ // once, because this prints into a terminal somebody is working in.
551
+ if (error instanceof LocalgateRouteConflictError)
552
+ {
553
+ if (this.reportedLostRoute) return;
554
+ this.reportedLostRoute = true;
555
+ process.stderr.write(`localgate: ${error.existing.names[0]} is served by runner `
556
+ + `${error.existing.runnerPid ?? "?"} now, so this runner has no route left. `
557
+ + "Stop it with Ctrl+C.\n");
558
+ return;
559
+ }
560
+
484
561
  process.stderr.write(`localgate: could not re-register the route: ${String(error)}\n`);
485
562
  }
486
563
  })();
@@ -496,15 +573,30 @@ export class LocalgateRunner
496
573
  process.on(signal, () => void this.shutdown(0));
497
574
  }
498
575
 
576
+ // Ctrl+C and the terminal going away, which is the operator leaving: the runner ends whatever the kill
577
+ // achieved, and a port that outlived the child is a line on the way out. `/stop` is the other way in,
578
+ // and it is the opposite - there somebody is waiting for the answer, so a refused kill is refused.
499
579
  private async shutdown(code: number): Promise<void>
500
580
  {
501
581
  if (this.stopping) return;
502
582
  this.stopping = true;
503
- this.exitCode = code;
504
583
 
505
584
  const child = this.child;
506
- if (child?.pid && this.route) await LocalgateProcessTree.killTree(child.pid, this.route.port);
585
+ if (child?.pid && this.route)
586
+ {
587
+ const outcome = await LocalgateProcessTree.killTree(child.pid, this.route.port);
588
+ if (!outcome.released)
589
+ process.stderr.write(`localgate: 127.0.0.1:${this.route.port} is still held after stopping `
590
+ + `${child.pid}${LocalgateProcessTree.describeErrors(outcome)}\n`);
591
+ }
592
+
593
+ await this.end(code);
594
+ }
507
595
 
596
+ // Everything left once the child is dealt with: the route, the control server and this process.
597
+ private async end(code: number): Promise<void>
598
+ {
599
+ this.exitCode = code;
508
600
  await this.cleanup();
509
601
  process.exit(code);
510
602
  }
@@ -518,11 +610,10 @@ export class LocalgateRunner
518
610
  this.runtime = null;
519
611
  }
520
612
 
521
- if (this.controlServer)
613
+ if (this.control)
522
614
  {
523
- this.controlServer.closeAllConnections();
524
- await new Promise<void>(resolve => this.controlServer!.close(() => resolve()));
525
- this.controlServer = null;
615
+ await this.control.close();
616
+ this.control = null;
526
617
  }
527
618
  }
528
619
 
@@ -0,0 +1,151 @@
1
+ import { createServer, type IncomingMessage, type Server, type ServerResponse } from "node:http";
2
+
3
+ // What the endpoint may ask of the runner that owns the dev process. `restart` and `stop` both resolve
4
+ // only once the work is done and reject with the reason it is not, because the answer is the only thing
5
+ // the caller ever sees: a `200` written before the kill is how `localgate stop` came to print "stopped"
6
+ // for a process the system had refused to end.
7
+ export type LocalgateRunnerControlHandler =
8
+ {
9
+ routeId(): string | null;
10
+ logs(lines: number): string[];
11
+ restart(): Promise<void>;
12
+ stop(): Promise<void>;
13
+ // Runs once the stop's answer has left this server, and not inside `stop` itself: ending the runner
14
+ // closes this server, and a socket cut before the answer left it would report a transport failure for
15
+ // a stop that worked.
16
+ stopped(): void;
17
+ };
18
+
19
+ // The runner's own endpoint, on loopback and nowhere else: how `localgate restart`, `localgate stop`,
20
+ // `localgate logs` and the start page's stop button reach the process that owns the dev server.
21
+ export class LocalgateRunnerControl
22
+ {
23
+ private static readonly defaultLogLinesConst = 80;
24
+
25
+ private readonly handler: LocalgateRunnerControlHandler;
26
+ private server: Server | null;
27
+ // The stop answer a caller is waiting for, from the request until it has left the socket. Closing the
28
+ // server destroys that socket, so the close waits for it.
29
+ private answering: Promise<void> | null;
30
+
31
+ constructor(handler: LocalgateRunnerControlHandler)
32
+ {
33
+ this.handler = handler;
34
+ this.server = null;
35
+ this.answering = null;
36
+ }
37
+
38
+ // Loopback only: the control channel must not be reachable from the LAN.
39
+ start(): Promise<string>
40
+ {
41
+ const server = createServer((request, response) => this.dispatch(request, response));
42
+ this.server = server;
43
+
44
+ return new Promise<string>((resolve, reject) =>
45
+ {
46
+ server.once("error", reject);
47
+ server.listen(0, "127.0.0.1", () =>
48
+ {
49
+ const address = server.address();
50
+ if (!address || typeof address == "string")
51
+ {
52
+ reject(new Error("control server has no port"));
53
+ return;
54
+ }
55
+ resolve(`http://127.0.0.1:${address.port}`);
56
+ });
57
+ });
58
+ }
59
+
60
+ // What a refused control call says, as the tail of a sentence that has already named the status code:
61
+ // the reason the runner wrote, or nothing when it wrote nothing. It is the reading half of `refusal`
62
+ // below, and it lives here so the shape of that body has one owner - `localgate restart`, `localgate
63
+ // stop` and the start page's stop button all report the same refusal, and the page has no terminal to
64
+ // send its reader to for the rest of it.
65
+ static refusalDetail(body: string): string
66
+ {
67
+ const text = body.trim();
68
+ if (text.length == 0) return "";
69
+
70
+ try
71
+ {
72
+ const parsed: unknown = JSON.parse(text);
73
+ if (typeof parsed == "object" && parsed !== null && "error" in parsed && typeof parsed.error == "string")
74
+ return `: ${parsed.error}`;
75
+ }
76
+ catch
77
+ {
78
+ // Not JSON, so the body is whatever the runner wrote and is reported as it stands.
79
+ }
80
+
81
+ return `: ${text}`;
82
+ }
83
+
84
+ async close(): Promise<void>
85
+ {
86
+ const server = this.server;
87
+ if (!server) return;
88
+
89
+ this.server = null;
90
+ if (this.answering) await this.answering;
91
+
92
+ server.closeAllConnections();
93
+ await new Promise<void>(resolve => server.close(() => resolve()));
94
+ }
95
+
96
+ private dispatch(request: IncomingMessage, response: ServerResponse): void
97
+ {
98
+ const url = new URL(request.url ?? "/", "http://127.0.0.1");
99
+ const send = (status: number, payload: unknown) =>
100
+ {
101
+ const body = JSON.stringify(payload);
102
+ response.writeHead(status, { "content-type": "application/json", "content-length": Buffer.byteLength(body) });
103
+ response.end(body);
104
+ };
105
+
106
+ if (url.pathname == "/ping") return send(200, { ok: true, id: this.handler.routeId() });
107
+
108
+ if (url.pathname == "/logs")
109
+ {
110
+ const requested = url.searchParams.get("lines") ?? String(LocalgateRunnerControl.defaultLogLinesConst);
111
+ return send(200, { lines: this.handler.logs(Math.max(1, Number.parseInt(requested, 10))) });
112
+ }
113
+
114
+ if (url.pathname == "/restart" && request.method == "POST")
115
+ {
116
+ void this.handler.restart().then(
117
+ () => send(200, { ok: true }),
118
+ (error: unknown) => send(409, LocalgateRunnerControl.refusal(error))
119
+ );
120
+ return;
121
+ }
122
+
123
+ if (url.pathname == "/stop" && request.method == "POST")
124
+ {
125
+ // From here on the runner's exit has to wait for this answer. The kill below ends the child, the
126
+ // runner ends with it, and closing this server on the way out would cut the socket the caller is
127
+ // still waiting on - a stop that worked, reported as a broken connection.
128
+ const answered = new Promise<void>(resolve => response.once("close", () => resolve()));
129
+ this.answering = answered;
130
+
131
+ void this.handler.stop().then(
132
+ () =>
133
+ {
134
+ send(200, { ok: true });
135
+ void answered.then(() => this.handler.stopped());
136
+ },
137
+ (error: unknown) => send(409, LocalgateRunnerControl.refusal(error))
138
+ );
139
+ return;
140
+ }
141
+
142
+ return send(404, LocalgateRunnerControl.refusal(`unknown ${request.method} ${url.pathname}`));
143
+ }
144
+
145
+ // Everything this endpoint refuses says why in the same field, because that reason is the only account
146
+ // of what happened: a kill the system turned down, a port still held, a verb this runner does not know.
147
+ private static refusal(error: unknown): { error: string }
148
+ {
149
+ return { error: String(error) };
150
+ }
151
+ }