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.
@@ -4,6 +4,7 @@ import { LocalgateControlApi } from "./localgateControlApi.ts";
4
4
  import { LocalgateHeaderRewrite } from "./localgateHeaderRewrite.ts";
5
5
  import { LocalgateHealth } from "./localgateHealth.ts";
6
6
  import type { LocalgateReach, LocalgateRegistry, LocalgateRoute } from "./localgateRegistry.ts";
7
+ import { LocalgateStartPage } from "./localgateStartPage.ts";
7
8
 
8
9
  export type LocalgateProxyOptions =
9
10
  {
@@ -27,6 +28,7 @@ export class LocalgateProxy
27
28
  private readonly registry: LocalgateRegistry,
28
29
  private readonly health: LocalgateHealth,
29
30
  private readonly controlApi: LocalgateControlApi,
31
+ private readonly startPage: LocalgateStartPage,
30
32
  private readonly options: LocalgateProxyOptions
31
33
  ) {}
32
34
 
@@ -115,6 +117,11 @@ export class LocalgateProxy
115
117
  if (loopback && LocalgateControlApi.handles(requestUrl))
116
118
  return this.controlApi.handle(request, response);
117
119
 
120
+ // Before the table, not after it: the start page has no route, and a route that took its name would
121
+ // shadow the page rather than the other way round. The registry refuses that name for this reason.
122
+ if (this.startPage.handles(request.headers.host ?? "", reachedFrom))
123
+ return this.startPage.handle(request, response, reachedFrom);
124
+
118
125
  const route = this.registry.byHostname(request.headers.host ?? "", reachedFrom);
119
126
  if (!route)
120
127
  {
@@ -165,8 +172,20 @@ export class LocalgateProxy
165
172
  upstreamResponse.pipe(response);
166
173
  });
167
174
 
175
+ // pipe() only unpipes when the browser goes away, it never ends the source. Without this an SSE
176
+ // stream or a long poll stays open on the dev server after a refresh, and the handler there never
177
+ // sees its request aborted. The same close covers a browser that leaves mid-upload or mid-wait.
178
+ response.once("close", () =>
179
+ {
180
+ if (!response.writableFinished) upstream.destroy();
181
+ });
182
+
168
183
  upstream.once("error", (error: NodeJS.ErrnoException) =>
169
184
  {
185
+ // The browser left and the close above tore the request down. That reset says nothing about the
186
+ // dev server, so it must not move the route to starting or dead.
187
+ if (response.destroyed) return;
188
+
170
189
  if (response.headersSent)
171
190
  {
172
191
  response.destroy();
@@ -237,6 +256,9 @@ export class LocalgateProxy
237
256
  });
238
257
 
239
258
  upstream.once("error", () => clientSocket.destroy());
259
+ // A browser that leaves before the dev server answers the handshake would otherwise leave the
260
+ // upgrade request, and the socket it later yields, open on the dev server with nobody to pipe to.
261
+ clientSocket.once("close", () => upstream.destroy());
240
262
  upstream.end();
241
263
  }
242
264
 
@@ -267,7 +289,9 @@ export class LocalgateProxy
267
289
  lines.push(` ${route.names.join(" ")} -> 127.0.0.1:${route.port} [${route.state}]`);
268
290
  }
269
291
 
270
- lines.push("");
292
+ // The port this request arrived on, not the configured one: the two differ when the proxy was asked
293
+ // for an ephemeral port, and a hint pointing at a port nothing listens on is worse than no hint.
294
+ lines.push("", `Every route, with its addresses: ${LocalgateStartPage.localUrl(this.boundPorts()[0]!)}`, "");
271
295
  return lines.join("\n");
272
296
  }
273
297
 
@@ -1,11 +1,15 @@
1
1
  import { LocalgateAliasStore } from "../config/localgateAliasStore.ts";
2
2
  import { LocalgateMachineConfig, type LocalgateMachineSettings } from "../config/localgateMachineConfig.ts";
3
+ import { LocalgateNames } from "../config/localgateNames.ts";
4
+ import { LocalgateRunnerControl } from "../run/localgateRunnerControl.ts";
5
+ import { LocalgateShellCommand } from "../run/localgateShellCommand.ts";
3
6
  import { LocalgateAliasRoute } from "./localgateAliasRoute.ts";
4
7
  import { LocalgateUrl } from "./localgateUrl.ts";
5
8
  import { LocalgateControlApi } from "./localgateControlApi.ts";
6
9
  import { LocalgateHealth } from "./localgateHealth.ts";
7
10
  import { LocalgateProxy } from "./localgateProxy.ts";
8
11
  import { LocalgateRegistry, type LocalgateRoute } from "./localgateRegistry.ts";
12
+ import { LocalgateStartPage } from "./localgateStartPage.ts";
9
13
 
10
14
  // Boots the long-lived half of localgate. Started on demand by the first `run` or `alias`, and it exits
11
15
  // once the last route disappears, so nothing is installed and nothing runs when no dev server does.
@@ -18,12 +22,21 @@ export class LocalgateProxyHost
18
22
  const machine = LocalgateMachineConfig.load();
19
23
  const port = LocalgateUrl.proxyPort(machine);
20
24
  const registry = new LocalgateRegistry();
21
- const health = new LocalgateHealth(registry, machine?.autoRestart === true, LocalgateProxyHost.requestRestart);
25
+ const health = new LocalgateHealth(registry, machine?.autoRestart === true,
26
+ route => LocalgateProxyHost.request(route, "restart"));
22
27
 
23
28
  const proxy: LocalgateProxy = new LocalgateProxy(
24
29
  registry,
25
30
  health,
26
31
  new LocalgateControlApi(registry, () => proxy.checkIdle()),
32
+ // The configured port rather than the bound one, because the page writes addresses for a person to
33
+ // click, and those are the names and the port they would have typed themselves.
34
+ new LocalgateStartPage(registry, machine, port, {
35
+ // Read at each render rather than held from boot, so an alias that gains a stop command gets
36
+ // its button without restarting the proxy every dev server on this machine depends on.
37
+ aliasStopCommands: () => LocalgateAliasStore.stopCommands(),
38
+ stop: route => LocalgateProxyHost.stop(route)
39
+ }),
27
40
  {
28
41
  port,
29
42
  lanIp: machine?.lanIp ?? null,
@@ -40,7 +53,8 @@ export class LocalgateProxyHost
40
53
 
41
54
  await proxy.start();
42
55
  process.stdout.write(`localgate proxy listening on 127.0.0.1:${port}`
43
- + `${machine?.lanIp ? ` and ${machine.lanIp}:${port}` : ""}\n`);
56
+ + `${machine?.lanIp ? ` and ${machine.lanIp}:${port}` : ""}\n`
57
+ + `localgate: start page at ${LocalgateStartPage.localUrl(port)}\n`);
44
58
 
45
59
  for (const signal of ["SIGINT", "SIGTERM"] as const)
46
60
  process.on(signal, () => void proxy.stop().then(() => process.exit(0)));
@@ -54,11 +68,31 @@ export class LocalgateProxyHost
54
68
  for (const line of restored) process.stdout.write(`${line}\n`);
55
69
  }
56
70
 
57
- private static async requestRestart(route: LocalgateRoute): Promise<void>
71
+ // Two kinds of route, two ways to end one. An app has a runner, and only the runner can end the child
72
+ // tree, release the port and deregister its own route. An alias has nothing of ours behind it, so all
73
+ // that can be done is to run the line the machine's owner wrote for it.
74
+ static async stop(route: LocalgateRoute): Promise<void>
75
+ {
76
+ if (route.controlUrl) return LocalgateProxyHost.request(route, "stop");
77
+
78
+ const name = LocalgateNames.shortName(route.names[0]!);
79
+ const command = LocalgateAliasStore.stopCommands().get(name);
80
+ if (!command) throw new Error(`${name} is an alias with no stop command in ${LocalgateAliasStore.filePath()}`);
81
+
82
+ await LocalgateShellCommand.run(command);
83
+ }
84
+
85
+ // The proxy never kills anything itself: it asks the runner that owns the process, which is the only
86
+ // one that can end the child tree, release the port and deregister its own route.
87
+ private static async request(route: LocalgateRoute, action: "restart" | "stop"): Promise<void>
58
88
  {
59
89
  if (!route.controlUrl) throw new Error(`route ${route.names[0]} has no control endpoint`);
60
90
 
61
- const response = await fetch(`${route.controlUrl}/restart`, { method: "POST" });
62
- if (!response.ok) throw new Error(`control endpoint answered ${response.status}`);
91
+ const response = await fetch(`${route.controlUrl}/${action}`, { method: "POST" });
92
+ // With the reason the runner wrote, not the status alone: this message is what the start page shows
93
+ // its reader, and a bare `409` there sends them to a terminal to find out what the kill hit.
94
+ if (!response.ok)
95
+ throw new Error(`control endpoint answered ${response.status}`
96
+ + LocalgateRunnerControl.refusalDetail(await response.text().catch(() => "")));
63
97
  }
64
98
  }
@@ -1,5 +1,7 @@
1
1
  import { isAbsolute, relative, resolve, sep } from "node:path";
2
+ import { LocalgateNames } from "../config/localgateNames.ts";
2
3
  import type { LocalgateMode } from "../config/localgateProjectConfig.ts";
4
+ import { LocalgateUrl } from "./localgateUrl.ts";
3
5
 
4
6
  export type LocalgateRouteKind = "app" | "alias";
5
7
 
@@ -70,6 +72,8 @@ export class LocalgateRegistry
70
72
  if (registration.names.length == 0)
71
73
  throw new Error("a route needs at least one name");
72
74
 
75
+ LocalgateRegistry.refuseReserved(registration.names);
76
+
73
77
  // Taking a name away from a live runner used to be silent, which left that runner holding its port
74
78
  // with no route pointing at it - unreachable, and invisible to stop/restart/status. A runner may
75
79
  // still re-register its own names, which is how the heartbeat recovers from a proxy restart.
@@ -119,7 +123,7 @@ export class LocalgateRegistry
119
123
  // `.localhost` name ends up answered on the LAN.
120
124
  byHostname(hostHeader: string, reachedFrom: LocalgateReach): LocalgateRoute | null
121
125
  {
122
- const host = LocalgateRegistry.hostnameOf(hostHeader);
126
+ const host = LocalgateUrl.hostnameOf(hostHeader);
123
127
  if (!host) return null;
124
128
 
125
129
  for (const route of this.routes.values())
@@ -175,6 +179,7 @@ export class LocalgateRegistry
175
179
  if (patch.names)
176
180
  {
177
181
  if (patch.names.length == 0) throw new Error("a route needs at least one name");
182
+ LocalgateRegistry.refuseReserved(patch.names);
178
183
  for (const name of patch.names)
179
184
  {
180
185
  const existing = this.findByName(name);
@@ -186,6 +191,17 @@ export class LocalgateRegistry
186
191
  return route;
187
192
  }
188
193
 
194
+ // The proxy resolves the start page before it looks in this table, so a route under that name would be
195
+ // registered, listed and never reached. Refused here rather than only in the commands, because the
196
+ // table is what every path ends at - the alias command, a runner claiming a name, a rename on restart.
197
+ private static refuseReserved(names: string[]): void
198
+ {
199
+ for (const name of names)
200
+ if (LocalgateNames.isReserved(name))
201
+ throw new Error(`"${LocalgateNames.startNameConst}" is reserved for localgate's start page, `
202
+ + `so ${name} cannot be registered`);
203
+ }
204
+
189
205
  private findByName(name: string): LocalgateRoute | null
190
206
  {
191
207
  for (const route of this.routes.values())
@@ -193,12 +209,6 @@ export class LocalgateRegistry
193
209
  return null;
194
210
  }
195
211
 
196
- private static hostnameOf(hostHeader: string): string | null
197
- {
198
- const host = hostHeader.trim().toLowerCase().split(":")[0];
199
- return host ? host : null;
200
- }
201
-
202
212
  // `.localhost` resolves to the loopback address of whoever looked it up, so off this machine it
203
213
  // names somebody else's computer. Serving it on the LAN listener would hand out every route,
204
214
  // including the local-mode ones whose whole point is that they never leave the machine.