localgate 0.4.0 → 0.6.0
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/README.md +91 -19
- package/logic/cli/localgateBanner.ts +9 -8
- package/logic/cli/localgateCli.ts +158 -23
- package/logic/client/localgateProxyClient.ts +9 -1
- package/logic/config/localgateAliasStore.ts +187 -0
- package/logic/config/localgateConfigReport.ts +45 -0
- package/logic/config/localgateMachineConfig.ts +7 -0
- package/logic/config/localgateNames.ts +19 -0
- package/logic/proxy/localgateAliasRoute.ts +46 -0
- package/logic/proxy/localgateControlApi.ts +18 -0
- package/logic/proxy/localgateHealth.ts +53 -15
- package/logic/proxy/localgatePortProbe.ts +42 -0
- package/logic/proxy/localgateProxy.ts +34 -1
- package/logic/proxy/localgateProxyHost.ts +52 -6
- package/logic/proxy/localgateRegistry.ts +20 -8
- package/logic/proxy/localgateStartPage.ts +491 -0
- package/logic/proxy/localgateUrl.ts +43 -0
- package/logic/run/localgateEnvRewrite.ts +28 -6
- package/logic/run/localgateNodeBootstrap.mjs +29 -0
- package/logic/run/localgateNodeOptions.ts +15 -0
- package/logic/run/localgateProcessTree.ts +122 -31
- package/logic/run/localgateRunner.ts +215 -124
- package/logic/run/localgateRunnerControl.ts +151 -0
- package/logic/run/localgateShellCommand.ts +51 -0
- package/package.json +1 -1
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
import { closeSync, fsyncSync, mkdirSync, openSync, readFileSync, renameSync, writeSync } from "node:fs";
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import { dirname, join } from "node:path";
|
|
4
|
+
import { LocalgateMachineConfig } from "./localgateMachineConfig.ts";
|
|
5
|
+
|
|
6
|
+
export type LocalgatePersistedAlias =
|
|
7
|
+
{
|
|
8
|
+
name: string;
|
|
9
|
+
port: number;
|
|
10
|
+
// What ends whatever answers on that port, when the machine knows. An alias names a process localgate
|
|
11
|
+
// did not start - a container, a service - so there is nobody to ask; this line is the answer the
|
|
12
|
+
// machine's owner wrote down, and it is what lets an alias have a stop button at all.
|
|
13
|
+
stop: string | null;
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
// Records alias INTENT - the short name, the port, and optionally the command that stops what listens
|
|
17
|
+
// there. An alias is the one route with no process behind it, so a runner heartbeat cannot bring it back
|
|
18
|
+
// after a proxy restart and a file is its only possible owner of record. Names and mode are deliberately
|
|
19
|
+
// not stored: re-deriving them at restore time is what keeps a changed machine label or domain from
|
|
20
|
+
// resurrecting hostnames nobody uses any more.
|
|
21
|
+
//
|
|
22
|
+
// The CLI alias command is the only writer. The proxy reads it at boot to restore the routes, and the
|
|
23
|
+
// start page reads the stop commands as it renders, so an alias that gains one needs no proxy restart.
|
|
24
|
+
// A stop command is trusted because this file is the only way in: it never crosses the control API,
|
|
25
|
+
// where a form POST from a browser could plant one.
|
|
26
|
+
export class LocalgateAliasStore
|
|
27
|
+
{
|
|
28
|
+
private static readonly maxPortConst = 65_535;
|
|
29
|
+
private static readonly directoryModeConst = 0o700;
|
|
30
|
+
private static readonly fileModeConst = 0o600;
|
|
31
|
+
|
|
32
|
+
static filePath(): string
|
|
33
|
+
{
|
|
34
|
+
return join(homedir(), ".localgate", "aliases.json");
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
// The one port rule for an alias, so the command that writes an entry and the loader that reads it back
|
|
38
|
+
// cannot disagree about what is storable.
|
|
39
|
+
static isPort(value: number): boolean
|
|
40
|
+
{
|
|
41
|
+
return Number.isInteger(value) && value >= 1 && value <= LocalgateAliasStore.maxPortConst;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// Never throws. A hand-edited or half-written file must not take down a proxy boot that every dev
|
|
45
|
+
// server on the machine depends on, so a bad entry is dropped and the rest still load.
|
|
46
|
+
static load(filePath: string = LocalgateAliasStore.filePath()): LocalgatePersistedAlias[]
|
|
47
|
+
{
|
|
48
|
+
return LocalgateAliasStore.read(filePath, true);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
// The stop commands alone, by alias name, and without a word to stderr: the page asks for these on
|
|
52
|
+
// every render, and a file the boot already complained about must not complain again every five
|
|
53
|
+
// seconds.
|
|
54
|
+
static stopCommands(filePath: string = LocalgateAliasStore.filePath()): Map<string, string>
|
|
55
|
+
{
|
|
56
|
+
const commands = new Map<string, string>();
|
|
57
|
+
for (const alias of LocalgateAliasStore.read(filePath, false))
|
|
58
|
+
if (alias.stop) commands.set(alias.name, alias.stop);
|
|
59
|
+
return commands;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
private static read(filePath: string, report: boolean): LocalgatePersistedAlias[]
|
|
63
|
+
{
|
|
64
|
+
let raw: string;
|
|
65
|
+
try
|
|
66
|
+
{
|
|
67
|
+
raw = readFileSync(filePath, "utf8");
|
|
68
|
+
}
|
|
69
|
+
catch (error)
|
|
70
|
+
{
|
|
71
|
+
// A machine that never registered an alias is the ordinary case and says nothing. Anything else -
|
|
72
|
+
// no permission, a directory in the way - is worth a line, because it loses aliases that exist.
|
|
73
|
+
if (report && (error as NodeJS.ErrnoException).code != "ENOENT")
|
|
74
|
+
process.stderr.write(`localgate: ${filePath} could not be read, continuing without its aliases: ${String(error)}\n`);
|
|
75
|
+
return [];
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
let parsed: unknown;
|
|
79
|
+
try
|
|
80
|
+
{
|
|
81
|
+
parsed = JSON.parse(raw);
|
|
82
|
+
}
|
|
83
|
+
catch
|
|
84
|
+
{
|
|
85
|
+
// Left on disk on purpose: the next add or remove rewrites it, and until then the person can
|
|
86
|
+
// still see what they typed.
|
|
87
|
+
if (report) process.stderr.write(`localgate: ${filePath} is not valid JSON, ignoring the aliases in it\n`);
|
|
88
|
+
return [];
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
const entries = (parsed as { aliases?: unknown } | null)?.aliases;
|
|
92
|
+
if (!Array.isArray(entries))
|
|
93
|
+
{
|
|
94
|
+
if (report) process.stderr.write(`localgate: ${filePath} has no alias list, ignoring it\n`);
|
|
95
|
+
return [];
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
const aliases: LocalgatePersistedAlias[] = [];
|
|
99
|
+
for (const entry of entries)
|
|
100
|
+
{
|
|
101
|
+
const alias = LocalgateAliasStore.validated(entry, filePath, report);
|
|
102
|
+
if (alias) aliases.push(alias);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
return aliases;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
// Upsert by name, because re-running `localgate alias myapp 8002` moves an existing alias to a new
|
|
109
|
+
// port the same way the registry replaces the live route.
|
|
110
|
+
static add(alias: LocalgatePersistedAlias, filePath: string = LocalgateAliasStore.filePath()): void
|
|
111
|
+
{
|
|
112
|
+
const aliases = LocalgateAliasStore.load(filePath);
|
|
113
|
+
const previous = aliases.find(existing => existing.name == alias.name);
|
|
114
|
+
|
|
115
|
+
// Re-running `localgate alias myapp 8002` moves the port, and it must not silently drop a stop
|
|
116
|
+
// command written for that name. Passing one replaces it.
|
|
117
|
+
const kept = aliases.filter(existing => existing.name != alias.name);
|
|
118
|
+
kept.push({ ...alias, stop: alias.stop ?? previous?.stop ?? null });
|
|
119
|
+
LocalgateAliasStore.write(kept, filePath);
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
static remove(name: string, filePath: string = LocalgateAliasStore.filePath()): boolean
|
|
123
|
+
{
|
|
124
|
+
const aliases = LocalgateAliasStore.load(filePath);
|
|
125
|
+
const kept = aliases.filter(alias => alias.name != name);
|
|
126
|
+
if (kept.length == aliases.length) return false;
|
|
127
|
+
|
|
128
|
+
LocalgateAliasStore.write(kept, filePath);
|
|
129
|
+
return true;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
// Throws on a disk failure, unlike `load`: a caller that cannot write has to decide what to tell the
|
|
133
|
+
// user, and a silently dropped write is an alias that goes missing at the next boot.
|
|
134
|
+
private static write(aliases: LocalgatePersistedAlias[], filePath: string): void
|
|
135
|
+
{
|
|
136
|
+
// The file lists this machine's internal services, so it stays readable by its owner alone.
|
|
137
|
+
mkdirSync(dirname(filePath), { recursive: true, mode: LocalgateAliasStore.directoryModeConst });
|
|
138
|
+
|
|
139
|
+
// Write beside the file, flush it, then rename over the target. Losing every alias to a crash
|
|
140
|
+
// halfway through a write is the failure this file exists to prevent, and without the flush the
|
|
141
|
+
// rename can still publish an empty file after a power cut.
|
|
142
|
+
const temporary = `${filePath}.tmp`;
|
|
143
|
+
const handle = openSync(temporary, "w", LocalgateAliasStore.fileModeConst);
|
|
144
|
+
try
|
|
145
|
+
{
|
|
146
|
+
// An absent command is absent from the file rather than written as a null: people edit this file.
|
|
147
|
+
const written = aliases.map(alias => alias.stop ? alias : { name: alias.name, port: alias.port });
|
|
148
|
+
writeSync(handle, `${JSON.stringify({ aliases: written }, null, 2)}\n`);
|
|
149
|
+
fsyncSync(handle);
|
|
150
|
+
}
|
|
151
|
+
finally
|
|
152
|
+
{
|
|
153
|
+
closeSync(handle);
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
renameSync(temporary, filePath);
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
private static validated(entry: unknown, filePath: string, report: boolean): LocalgatePersistedAlias | null
|
|
160
|
+
{
|
|
161
|
+
const candidate = entry as { name?: unknown; port?: unknown; stop?: unknown } | null;
|
|
162
|
+
const name = candidate?.name;
|
|
163
|
+
const port = candidate?.port;
|
|
164
|
+
|
|
165
|
+
if (typeof name != "string" || !LocalgateMachineConfig.isLabel(name))
|
|
166
|
+
{
|
|
167
|
+
if (report) process.stderr.write(`localgate: ${filePath} holds an alias whose name is not a DNS label, skipping it\n`);
|
|
168
|
+
return null;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
if (typeof port != "number" || !LocalgateAliasStore.isPort(port))
|
|
172
|
+
{
|
|
173
|
+
if (report) process.stderr.write(`localgate: ${filePath} holds alias ${name} without a usable port, skipping it\n`);
|
|
174
|
+
return null;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
// A malformed stop command costs the button, not the alias: the name and the port are what make the
|
|
178
|
+
// route, and dropping those over a mistyped extra field would take a service off the machine.
|
|
179
|
+
const stop = typeof candidate?.stop == "string" && candidate.stop.trim().length > 0 ? candidate.stop : null;
|
|
180
|
+
// A written `null` says "none", which is exactly what this returns, so only a value that tried to be
|
|
181
|
+
// a command and failed is worth a word.
|
|
182
|
+
if (candidate?.stop != null && !stop && report)
|
|
183
|
+
process.stderr.write(`localgate: ${filePath} holds alias ${name} with an unusable "stop" command, ignoring that field\n`);
|
|
184
|
+
|
|
185
|
+
return { name, port, stop };
|
|
186
|
+
}
|
|
187
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { LocalgateAliasStore } from "./localgateAliasStore.ts";
|
|
2
|
+
import { LocalgateMachineConfig, type LocalgateMachineSettings } from "./localgateMachineConfig.ts";
|
|
3
|
+
import { LocalgateNames } from "./localgateNames.ts";
|
|
4
|
+
import { LocalgateProjectConfig, type LocalgateMode } from "./localgateProjectConfig.ts";
|
|
5
|
+
import { LocalgateUrl } from "../proxy/localgateUrl.ts";
|
|
6
|
+
|
|
7
|
+
export type LocalgateConfigReport =
|
|
8
|
+
{
|
|
9
|
+
machineFilePath: string;
|
|
10
|
+
machine: LocalgateMachineSettings | null;
|
|
11
|
+
proxyPort: number;
|
|
12
|
+
project: { name: string; mode: LocalgateMode; packageDirectory: string } | null;
|
|
13
|
+
names: { local: string; lan: string | null; public: string | null } | null;
|
|
14
|
+
aliases: { filePath: string; count: number };
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
// Localgate owns the naming and machine-config rules, so anything that needs them can read them from
|
|
18
|
+
// here instead of parsing ~/.localgate/config.json and re-deriving the names. Read-only by design:
|
|
19
|
+
// this reports what is configured, it never writes.
|
|
20
|
+
export class LocalgateConfigReporter
|
|
21
|
+
{
|
|
22
|
+
static build(directory: string | null): LocalgateConfigReport
|
|
23
|
+
{
|
|
24
|
+
const machine = LocalgateMachineConfig.load();
|
|
25
|
+
const report: LocalgateConfigReport = {
|
|
26
|
+
machineFilePath: LocalgateMachineConfig.filePath(),
|
|
27
|
+
machine,
|
|
28
|
+
proxyPort: LocalgateUrl.proxyPort(machine),
|
|
29
|
+
project: null,
|
|
30
|
+
names: null,
|
|
31
|
+
aliases: { filePath: LocalgateAliasStore.filePath(), count: LocalgateAliasStore.load().length }
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
if (directory === null) return report;
|
|
35
|
+
|
|
36
|
+
const project = LocalgateProjectConfig.load(directory);
|
|
37
|
+
report.project = { name: project.name, mode: project.mode, packageDirectory: project.packageDirectory };
|
|
38
|
+
report.names = {
|
|
39
|
+
local: LocalgateNames.local(project.name),
|
|
40
|
+
lan: machine ? LocalgateNames.lan(project.name, machine) : null,
|
|
41
|
+
public: machine ? LocalgateNames.publicName(project.name, machine) : null
|
|
42
|
+
};
|
|
43
|
+
return report;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
@@ -65,6 +65,13 @@ export class LocalgateMachineConfig
|
|
|
65
65
|
return `.${settings.label}.${settings.baseDomain}`;
|
|
66
66
|
}
|
|
67
67
|
|
|
68
|
+
// The alias store validates names against the same rule, and two copies of a DNS-label regex is how
|
|
69
|
+
// one of them ends up accepting a name the proxy will never serve.
|
|
70
|
+
static isLabel(value: string): boolean
|
|
71
|
+
{
|
|
72
|
+
return LocalgateMachineConfig.labelPatternConst.test(value);
|
|
73
|
+
}
|
|
74
|
+
|
|
68
75
|
private static optionalLabel(parsed: Record<string, unknown>, key: string, filePath: string): string | null
|
|
69
76
|
{
|
|
70
77
|
const value = parsed[key];
|
|
@@ -3,6 +3,11 @@ import type { LocalgateMode } from "./localgateProjectConfig.ts";
|
|
|
3
3
|
|
|
4
4
|
export class LocalgateNames
|
|
5
5
|
{
|
|
6
|
+
// The start page answers on this label instead of a route, on `.localhost` and on the machine's own
|
|
7
|
+
// domain. It is resolved before the route table, so a project or alias holding the same name would be
|
|
8
|
+
// registered, listed and never reached - refused at registration instead.
|
|
9
|
+
static readonly startNameConst = "start";
|
|
10
|
+
|
|
6
11
|
private static readonly dnsLabelMaxLengthConst = 63;
|
|
7
12
|
|
|
8
13
|
static local(projectName: string): string
|
|
@@ -25,6 +30,20 @@ export class LocalgateNames
|
|
|
25
30
|
return `${label}.${machine.baseDomain}`;
|
|
26
31
|
}
|
|
27
32
|
|
|
33
|
+
// The short name a person types, from any of the names a route answers to. Every layer needs it - the
|
|
34
|
+
// banner, the proxy's error pages, the CLI - and each one deriving it again is how they drift apart.
|
|
35
|
+
static shortName(hostname: string): string
|
|
36
|
+
{
|
|
37
|
+
return hostname.split(".")[0];
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// Takes the short name as well as any hostname built from it, because the name arrives as both: a
|
|
41
|
+
// project name from package.json, an alias argument, and a full hostname from `localgate list`.
|
|
42
|
+
static isReserved(name: string): boolean
|
|
43
|
+
{
|
|
44
|
+
return LocalgateNames.shortName(name) == LocalgateNames.startNameConst;
|
|
45
|
+
}
|
|
46
|
+
|
|
28
47
|
static routeNames(projectName: string, mode: LocalgateMode, machine: LocalgateMachineSettings | null): string[]
|
|
29
48
|
{
|
|
30
49
|
const local = LocalgateNames.local(projectName);
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { LocalgateNames } from "../config/localgateNames.ts";
|
|
2
|
+
import type { LocalgateMachineSettings } from "../config/localgateMachineConfig.ts";
|
|
3
|
+
import type { LocalgatePersistedAlias } from "../config/localgateAliasStore.ts";
|
|
4
|
+
import type { LocalgateMode } from "../config/localgateProjectConfig.ts";
|
|
5
|
+
import type { LocalgateRegistry, LocalgateRouteRegistration } from "./localgateRegistry.ts";
|
|
6
|
+
|
|
7
|
+
// One builder for the registration an alias produces, shared by the `alias` command and by the proxy's
|
|
8
|
+
// boot restore. Two copies of this literal is how a restored alias ends up subtly different from the one
|
|
9
|
+
// the person registered - a missing name, a different mode - in the half of the flow nobody watches.
|
|
10
|
+
export class LocalgateAliasRoute
|
|
11
|
+
{
|
|
12
|
+
static registration(name: string, port: number, machine: LocalgateMachineSettings | null): LocalgateRouteRegistration
|
|
13
|
+
{
|
|
14
|
+
const mode: LocalgateMode = machine ? "lan" : "local";
|
|
15
|
+
|
|
16
|
+
return {
|
|
17
|
+
names: LocalgateNames.routeNames(name, mode, machine),
|
|
18
|
+
port,
|
|
19
|
+
kind: "alias",
|
|
20
|
+
mode,
|
|
21
|
+
cwd: null,
|
|
22
|
+
command: null,
|
|
23
|
+
controlUrl: null,
|
|
24
|
+
runnerPid: null,
|
|
25
|
+
childPid: null,
|
|
26
|
+
debuggerAttached: false
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// Replays persisted intent into a fresh table. Kept out of the proxy host so the step that actually
|
|
31
|
+
// fixes a lost alias can be tested without binding a port.
|
|
32
|
+
static restore(registry: LocalgateRegistry, aliases: LocalgatePersistedAlias[],
|
|
33
|
+
machine: LocalgateMachineSettings | null, now: string): string[]
|
|
34
|
+
{
|
|
35
|
+
const restored: string[] = [];
|
|
36
|
+
for (const alias of aliases)
|
|
37
|
+
{
|
|
38
|
+
// The table is empty at boot, so nothing can collide; a name repeated in a hand-edited file
|
|
39
|
+
// replaces the earlier row, the same as re-running the alias command.
|
|
40
|
+
registry.register(LocalgateAliasRoute.registration(alias.name, alias.port, machine), now);
|
|
41
|
+
restored.push(`localgate: restored alias ${alias.name} -> 127.0.0.1:${alias.port}`);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
return restored;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
@@ -8,6 +8,8 @@ export class LocalgateControlApi
|
|
|
8
8
|
{
|
|
9
9
|
static readonly pathPrefixConst = "/__localgate/";
|
|
10
10
|
|
|
11
|
+
private static readonly maxPortConst = 65_535;
|
|
12
|
+
|
|
11
13
|
// onChange lets the proxy re-evaluate whether it still has a reason to run, since the registry itself
|
|
12
14
|
// is a plain table and emits nothing.
|
|
13
15
|
constructor(private readonly registry: LocalgateRegistry, private readonly onChange: () => void) {}
|
|
@@ -34,6 +36,7 @@ export class LocalgateControlApi
|
|
|
34
36
|
if (route == "routes" && method == "POST")
|
|
35
37
|
{
|
|
36
38
|
const registration = await LocalgateControlApi.readJson(request) as LocalgateRouteRegistration;
|
|
39
|
+
LocalgateControlApi.checkRegistration(registration);
|
|
37
40
|
const created = this.registry.register(registration, new Date().toISOString());
|
|
38
41
|
this.onChange();
|
|
39
42
|
return LocalgateControlApi.sendJson(response, 201, { route: created });
|
|
@@ -72,6 +75,21 @@ export class LocalgateControlApi
|
|
|
72
75
|
}
|
|
73
76
|
}
|
|
74
77
|
|
|
78
|
+
// The body is JSON from another process, so it is checked here rather than trusted through the cast.
|
|
79
|
+
// A port outside the dialable range ends the proxy on the first request to that route, and a kind
|
|
80
|
+
// nothing branches on reaches the throwing `else` of every message that switches on it.
|
|
81
|
+
private static checkRegistration(registration: LocalgateRouteRegistration): void
|
|
82
|
+
{
|
|
83
|
+
if (!Array.isArray(registration.names) || registration.names.length == 0)
|
|
84
|
+
throw new Error("a route needs at least one name");
|
|
85
|
+
|
|
86
|
+
if (!Number.isInteger(registration.port) || registration.port < 1 || registration.port > LocalgateControlApi.maxPortConst)
|
|
87
|
+
throw new Error(`port ${JSON.stringify(registration.port)} is not a port a route can point at`);
|
|
88
|
+
|
|
89
|
+
if (registration.kind != "app" && registration.kind != "alias")
|
|
90
|
+
throw new Error(`unknown route kind: ${JSON.stringify(registration.kind)}`);
|
|
91
|
+
}
|
|
92
|
+
|
|
75
93
|
private static async readJson(request: IncomingMessage): Promise<unknown>
|
|
76
94
|
{
|
|
77
95
|
const chunks: Buffer[] = [];
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { LocalgateNames } from "../config/localgateNames.ts";
|
|
1
2
|
import type { LocalgateRegistry, LocalgateRoute } from "./localgateRegistry.ts";
|
|
2
3
|
|
|
3
4
|
export type LocalgateRestartRequest = (route: LocalgateRoute) => Promise<void>;
|
|
@@ -31,6 +32,13 @@ export class LocalgateHealth
|
|
|
31
32
|
return LocalgateHealth.requestTimeoutMsConst;
|
|
32
33
|
}
|
|
33
34
|
|
|
35
|
+
// How long a refused connection still reads as "not bound yet" rather than "gone". Shared with the
|
|
36
|
+
// start page, which has to draw the same line when its own probe finds nothing on the port.
|
|
37
|
+
static startupGraceMs(): number
|
|
38
|
+
{
|
|
39
|
+
return LocalgateHealth.startupGraceMsConst;
|
|
40
|
+
}
|
|
41
|
+
|
|
34
42
|
noteSuccess(route: LocalgateRoute): void
|
|
35
43
|
{
|
|
36
44
|
this.failures.delete(route.id);
|
|
@@ -57,31 +65,61 @@ export class LocalgateHealth
|
|
|
57
65
|
this.registry.update(route.id, { state: withinGrace ? "starting" : "dead" });
|
|
58
66
|
}
|
|
59
67
|
|
|
68
|
+
// `localgate restart` refuses an alias, because there is no process localgate owns to restart, so the
|
|
69
|
+
// two kinds cannot share the closing advice.
|
|
60
70
|
unresponsiveMessage(route: LocalgateRoute): string
|
|
61
71
|
{
|
|
62
|
-
const
|
|
63
|
-
return [
|
|
72
|
+
const stalled = [
|
|
64
73
|
`localgate: ${route.names[0]} is not responding.`,
|
|
65
74
|
"",
|
|
66
|
-
`The
|
|
75
|
+
`The server accepted the connection but did not answer ${LocalgateHealth.failuresBeforeUnresponsiveConst} requests in a row`,
|
|
67
76
|
`(${LocalgateHealth.requestTimeoutMsConst / 1000} s each). It is wedged, or it is paused in a debugger.`,
|
|
68
|
-
"",
|
|
69
|
-
"Restart it with:",
|
|
70
|
-
` localgate restart ${route.names[0].split(".")[0]}`,
|
|
71
|
-
` (or run localgate restart in ${target})`,
|
|
72
77
|
""
|
|
73
|
-
]
|
|
78
|
+
];
|
|
79
|
+
|
|
80
|
+
if (route.kind == "app")
|
|
81
|
+
return [
|
|
82
|
+
...stalled,
|
|
83
|
+
"Restart it with:",
|
|
84
|
+
` localgate restart ${LocalgateNames.shortName(route.names[0])}`,
|
|
85
|
+
` (or run localgate restart in ${route.cwd ?? route.names[0]})`,
|
|
86
|
+
""
|
|
87
|
+
].join("\n");
|
|
88
|
+
else if (route.kind == "alias")
|
|
89
|
+
return [
|
|
90
|
+
...stalled,
|
|
91
|
+
`The alias points at 127.0.0.1:${route.port}, a process localgate does not own, so restart it`,
|
|
92
|
+
"yourself. Drop the alias with:",
|
|
93
|
+
` localgate alias --remove ${LocalgateNames.shortName(route.names[0])}`,
|
|
94
|
+
""
|
|
95
|
+
].join("\n");
|
|
96
|
+
else
|
|
97
|
+
throw new Error(`Unknown route kind: ${JSON.stringify(route.kind)}`);
|
|
74
98
|
}
|
|
75
99
|
|
|
100
|
+
// An alias points at a process localgate does not own, so neither half of the app advice applies to it:
|
|
101
|
+
// there is no editor to start it from, and `prune` deliberately leaves aliases alone.
|
|
76
102
|
deadMessage(route: LocalgateRoute): string
|
|
77
103
|
{
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
104
|
+
if (route.kind == "app")
|
|
105
|
+
return [
|
|
106
|
+
`localgate: nothing is listening for ${route.names[0]}.`,
|
|
107
|
+
"",
|
|
108
|
+
"The route is registered but its dev server is gone. Start it again from your editor,",
|
|
109
|
+
"or run localgate prune to drop the route.",
|
|
110
|
+
""
|
|
111
|
+
].join("\n");
|
|
112
|
+
else if (route.kind == "alias")
|
|
113
|
+
return [
|
|
114
|
+
`localgate: nothing is listening for ${route.names[0]}.`,
|
|
115
|
+
"",
|
|
116
|
+
`The alias points at 127.0.0.1:${route.port} and nothing answers there. Start whatever should`,
|
|
117
|
+
"listen on that port, or drop the alias with:",
|
|
118
|
+
` localgate alias --remove ${LocalgateNames.shortName(route.names[0])}`,
|
|
119
|
+
""
|
|
120
|
+
].join("\n");
|
|
121
|
+
else
|
|
122
|
+
throw new Error(`Unknown route kind: ${JSON.stringify(route.kind)}`);
|
|
85
123
|
}
|
|
86
124
|
|
|
87
125
|
startingMessage(route: LocalgateRoute): string
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { connect } from "node:net";
|
|
2
|
+
import type { LocalgateRoute } from "./localgateRegistry.ts";
|
|
3
|
+
|
|
4
|
+
// Whether anything is listening on a route's port, right now.
|
|
5
|
+
//
|
|
6
|
+
// The proxy's own health is learned from forwarded traffic, which costs nothing but says nothing at all
|
|
7
|
+
// about a route nobody has opened: a dev server that has been up for an hour and an alias whose
|
|
8
|
+
// container is down both sit at "starting" until someone visits them. A connection to loopback answers
|
|
9
|
+
// that question directly and costs a millisecond, so the start page asks it rather than repeating a
|
|
10
|
+
// guess back to the reader.
|
|
11
|
+
export class LocalgatePortProbe
|
|
12
|
+
{
|
|
13
|
+
// Loopback either accepts or refuses at once. The timeout is for the case in between - a port being
|
|
14
|
+
// dropped by a firewall rule - where the page must not wait on it.
|
|
15
|
+
private static readonly timeoutMsConst = 400;
|
|
16
|
+
|
|
17
|
+
static listening(port: number, timeoutMs: number = LocalgatePortProbe.timeoutMsConst): Promise<boolean>
|
|
18
|
+
{
|
|
19
|
+
return new Promise<boolean>(resolve =>
|
|
20
|
+
{
|
|
21
|
+
const socket = connect({ host: "127.0.0.1", port });
|
|
22
|
+
const settle = (answer: boolean) =>
|
|
23
|
+
{
|
|
24
|
+
socket.destroy();
|
|
25
|
+
resolve(answer);
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
socket.setTimeout(timeoutMs, () => settle(false));
|
|
29
|
+
socket.once("connect", () => settle(true));
|
|
30
|
+
socket.once("error", () => settle(false));
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// All of them at once, keyed by route id: a page that probed eight ports one after another would
|
|
35
|
+
// answer eight timeouts later in the worst case. It takes the two fields it dials with rather than the
|
|
36
|
+
// whole route, because that is all a port probe can honestly need.
|
|
37
|
+
static async listeningRoutes(routes: Pick<LocalgateRoute, "id" | "port">[]): Promise<Map<string, boolean>>
|
|
38
|
+
{
|
|
39
|
+
const answers = await Promise.all(routes.map(route => LocalgatePortProbe.listening(route.port)));
|
|
40
|
+
return new Map(routes.map((route, index) => [route.id, answers[index]!]));
|
|
41
|
+
}
|
|
42
|
+
}
|
|
@@ -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
|
{
|
|
@@ -127,6 +134,15 @@ export class LocalgateProxy
|
|
|
127
134
|
|
|
128
135
|
private forward(route: LocalgateRoute, request: IncomingMessage, response: ServerResponse): void
|
|
129
136
|
{
|
|
137
|
+
// A route pointing at the proxy's own port turns every listener into a bridge to the loopback one:
|
|
138
|
+
// the request comes back in as loopback, so a LAN caller reaches the control API, and any other path
|
|
139
|
+
// loops until the machine runs out of sockets. Refused here rather than at each registration point,
|
|
140
|
+
// because this is the one place every route is dialled from.
|
|
141
|
+
if (this.boundPorts().includes(route.port))
|
|
142
|
+
return LocalgateProxy.sendText(response, 502, `localgate: ${route.names[0]} points at localgate's own `
|
|
143
|
+
+ `port ${route.port}, which would only send the request back here. Point it at the port the `
|
|
144
|
+
+ "service actually listens on.\n");
|
|
145
|
+
|
|
130
146
|
const headers = { ...request.headers };
|
|
131
147
|
LocalgateHeaderRewrite.apply(request.url ?? "/", headers, request.headers.host ?? "", route.names[0]!);
|
|
132
148
|
|
|
@@ -156,8 +172,20 @@ export class LocalgateProxy
|
|
|
156
172
|
upstreamResponse.pipe(response);
|
|
157
173
|
});
|
|
158
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
|
+
|
|
159
183
|
upstream.once("error", (error: NodeJS.ErrnoException) =>
|
|
160
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
|
+
|
|
161
189
|
if (response.headersSent)
|
|
162
190
|
{
|
|
163
191
|
response.destroy();
|
|
@@ -228,6 +256,9 @@ export class LocalgateProxy
|
|
|
228
256
|
});
|
|
229
257
|
|
|
230
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());
|
|
231
262
|
upstream.end();
|
|
232
263
|
}
|
|
233
264
|
|
|
@@ -258,7 +289,9 @@ export class LocalgateProxy
|
|
|
258
289
|
lines.push(` ${route.names.join(" ")} -> 127.0.0.1:${route.port} [${route.state}]`);
|
|
259
290
|
}
|
|
260
291
|
|
|
261
|
-
|
|
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]!)}`, "");
|
|
262
295
|
return lines.join("\n");
|
|
263
296
|
}
|
|
264
297
|
|