@tafrahq/wt-tunnel-client 0.0.0-stage → 0.7.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.
Files changed (77) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +166 -2
  3. package/dist/bin.js +15 -0
  4. package/dist/bin.js.map +1 -0
  5. package/dist/cli-commands.js +27 -0
  6. package/dist/cli-commands.js.map +1 -0
  7. package/dist/cli-provision.js +25 -0
  8. package/dist/cli-provision.js.map +1 -0
  9. package/dist/cli-status.js +19 -0
  10. package/dist/cli-status.js.map +1 -0
  11. package/dist/cli-workspace.js +38 -0
  12. package/dist/cli-workspace.js.map +1 -0
  13. package/dist/cli-worktree.js +40 -0
  14. package/dist/cli-worktree.js.map +1 -0
  15. package/dist/cli.js +9 -0
  16. package/dist/cli.js.map +1 -0
  17. package/dist/config.js +70 -0
  18. package/dist/config.js.map +1 -0
  19. package/dist/domain.js +26 -0
  20. package/dist/domain.js.map +1 -0
  21. package/dist/errno.js +6 -0
  22. package/dist/errno.js.map +1 -0
  23. package/dist/errors.js +7 -0
  24. package/dist/errors.js.map +1 -0
  25. package/dist/exec.js +18 -0
  26. package/dist/exec.js.map +1 -0
  27. package/dist/files.js +18 -0
  28. package/dist/files.js.map +1 -0
  29. package/dist/frpc-binary.js +16 -0
  30. package/dist/frpc-binary.js.map +1 -0
  31. package/dist/frpc-config.js +47 -0
  32. package/dist/frpc-config.js.map +1 -0
  33. package/dist/packages/binaries/src/frp.js +45 -0
  34. package/dist/packages/binaries/src/frp.js.map +1 -0
  35. package/dist/packages/binaries/src/install.js +110 -0
  36. package/dist/packages/binaries/src/install.js.map +1 -0
  37. package/dist/packages/contract/src/index.js +12 -0
  38. package/dist/packages/contract/src/index.js.map +1 -0
  39. package/dist/ports.js +121 -0
  40. package/dist/ports.js.map +1 -0
  41. package/dist/processes.js +118 -0
  42. package/dist/processes.js.map +1 -0
  43. package/dist/provision-frpc.js +100 -0
  44. package/dist/provision-frpc.js.map +1 -0
  45. package/dist/provision-ports.js +75 -0
  46. package/dist/provision-ports.js.map +1 -0
  47. package/dist/provision.js +28 -0
  48. package/dist/provision.js.map +1 -0
  49. package/dist/state.js +53 -0
  50. package/dist/state.js.map +1 -0
  51. package/dist/worktree.js +25 -0
  52. package/dist/worktree.js.map +1 -0
  53. package/llms.txt +33 -0
  54. package/package.json +63 -3
  55. package/src/bin.ts +28 -0
  56. package/src/cli-commands.ts +40 -0
  57. package/src/cli-provision.ts +34 -0
  58. package/src/cli-status.ts +29 -0
  59. package/src/cli-workspace.ts +78 -0
  60. package/src/cli-worktree.ts +62 -0
  61. package/src/cli.ts +15 -0
  62. package/src/config.ts +101 -0
  63. package/src/domain.ts +51 -0
  64. package/src/errno.ts +5 -0
  65. package/src/errors.ts +13 -0
  66. package/src/exec.ts +18 -0
  67. package/src/files.ts +20 -0
  68. package/src/frpc-binary.ts +27 -0
  69. package/src/frpc-config.ts +69 -0
  70. package/src/ports.ts +177 -0
  71. package/src/processes.ts +163 -0
  72. package/src/provision-frpc.ts +152 -0
  73. package/src/provision-ports.ts +116 -0
  74. package/src/provision.ts +41 -0
  75. package/src/resource.ts +28 -0
  76. package/src/state.ts +87 -0
  77. package/src/worktree.ts +52 -0
@@ -0,0 +1,163 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { open, rm, writeFile } from 'node:fs/promises';
3
+ import { join } from 'node:path';
4
+
5
+ import { Effect } from 'effect';
6
+
7
+ import { errorCode } from './errno.ts';
8
+ import { WtTunnelError } from './errors.ts';
9
+ import { execFileText } from './exec.ts';
10
+ import { readTextIfExists } from './files.ts';
11
+
12
+ /** Signal 0 checks that a process exists without touching it. */
13
+ const probeSignal = 0;
14
+ const firstPid = 1;
15
+ const logTailLines = 15;
16
+ /** How long a fresh process must survive before it counts as started. */
17
+ const startupGrace = '1500 millis';
18
+ const stopPollInterval = '100 millis';
19
+ const stopPolls = 50;
20
+
21
+ interface ProcessSpec {
22
+ readonly args: readonly string[];
23
+ readonly command: string;
24
+ readonly env?: Readonly<Record<string, string>>;
25
+ readonly name: 'frpc';
26
+ }
27
+
28
+ type ProcessName = ProcessSpec['name'];
29
+
30
+ type ProcessStatus =
31
+ | { readonly _tag: 'running'; readonly pid: number }
32
+ | { readonly _tag: 'stopped' }
33
+ | { readonly _tag: 'stale'; readonly pid: number };
34
+
35
+ const pidFile = (stateDir: string, name: ProcessName) => join(stateDir, `${name}.pid`);
36
+ const processLogFile = (stateDir: string, name: ProcessName) => join(stateDir, `${name}.log`);
37
+
38
+ const alive = (pid: number) => {
39
+ try {
40
+ process.kill(pid, probeSignal);
41
+ return true;
42
+ } catch (error) {
43
+ return errorCode(error) === 'EPERM';
44
+ }
45
+ };
46
+
47
+ /**
48
+ * A pid file can outlive its process and the pid can be reused, so a pid only counts as ours while
49
+ * its argv still mentions this worktree's state dir.
50
+ */
51
+ const ownedBy = (pid: number, stateDir: string) =>
52
+ execFileText('ps', ['-o', 'args=', '-p', String(pid)]).pipe(
53
+ Effect.map((args) => args.includes(stateDir)),
54
+ Effect.orElseSucceed(() => false),
55
+ );
56
+
57
+ const processStatus = (stateDir: string, name: ProcessName): Effect.Effect<ProcessStatus> =>
58
+ Effect.gen(function* readPidFile() {
59
+ const text = yield* Effect.promise(() => readTextIfExists(pidFile(stateDir, name)));
60
+ if (text === undefined) {
61
+ return { _tag: 'stopped' };
62
+ }
63
+ const pid = Number(text.trim());
64
+ if (Number.isInteger(pid) && pid >= firstPid && alive(pid) && (yield* ownedBy(pid, stateDir))) {
65
+ return { _tag: 'running', pid };
66
+ }
67
+ return { _tag: 'stale', pid };
68
+ });
69
+
70
+ const tail = (file: string) =>
71
+ Effect.promise(() => readTextIfExists(file)).pipe(
72
+ Effect.map((text) => (text ?? '').trimEnd().split('\n').slice(-logTailLines).join('\n')),
73
+ );
74
+
75
+ const failedToStart = (name: ProcessName) => (cause: unknown) =>
76
+ new WtTunnelError({ message: `Failed to start ${name}: ${String(cause)}` });
77
+
78
+ /** Spawn failures throw synchronously, as Node reports a missing command. */
79
+ const spawnDetached = (spec: ProcessSpec, logFd: number) => {
80
+ const child = spawn(spec.command, [...spec.args], {
81
+ detached: true,
82
+ env: { ...process.env, ...spec.env },
83
+ stdio: ['ignore', logFd, logFd],
84
+ });
85
+ child.unref();
86
+ if (child.pid === undefined) {
87
+ throw new Error(`could not spawn ${spec.command}`);
88
+ }
89
+ return child.pid;
90
+ };
91
+
92
+ /**
93
+ * Starts the process with its output appended to `log`. The child holds its own copy of the log
94
+ * descriptor, so ours is closed without waiting.
95
+ */
96
+ const spawnLogging = (spec: ProcessSpec, log: string) =>
97
+ Effect.gen(function* openLogThenSpawn() {
98
+ const handle = yield* Effect.tryPromise({
99
+ catch: failedToStart(spec.name),
100
+ try: () => open(log, 'a'),
101
+ });
102
+ return yield* Effect.try({
103
+ catch: failedToStart(spec.name),
104
+ try: () => spawnDetached(spec, handle.fd),
105
+ }).pipe(
106
+ Effect.ensuring(
107
+ Effect.sync(() => {
108
+ void handle.close();
109
+ }),
110
+ ),
111
+ );
112
+ });
113
+
114
+ /** Fails with the log's last lines when the process dies within the startup grace period. */
115
+ const survivesStartup = (stateDir: string, name: ProcessName, pid: number) =>
116
+ Effect.gen(function* waitThenCheck() {
117
+ yield* Effect.sleep(startupGrace);
118
+ if (!alive(pid)) {
119
+ yield* Effect.promise(() => rm(pidFile(stateDir, name), { force: true }));
120
+ const log = processLogFile(stateDir, name);
121
+ yield* new WtTunnelError({
122
+ message: `${name} exited right after starting. Last log lines (${log}):\n${yield* tail(log)}`,
123
+ });
124
+ }
125
+ });
126
+
127
+ const startProcess = (stateDir: string, spec: ProcessSpec) =>
128
+ Effect.gen(function* spawnUnlessRunning() {
129
+ const current = yield* processStatus(stateDir, spec.name);
130
+ if (current._tag === 'running') {
131
+ return current.pid;
132
+ }
133
+ const log = processLogFile(stateDir, spec.name);
134
+ const pid = yield* spawnLogging(spec, log);
135
+ yield* Effect.promise(() => writeFile(pidFile(stateDir, spec.name), `${pid}\n`));
136
+ yield* survivesStartup(stateDir, spec.name, pid);
137
+ return pid;
138
+ });
139
+
140
+ /** SIGTERM, then SIGKILL if the process is still alive after the polls. */
141
+ const terminate = (pid: number) =>
142
+ Effect.gen(function* termThenKill() {
143
+ process.kill(pid, 'SIGTERM');
144
+ for (let poll = 0; poll < stopPolls && alive(pid); poll++) {
145
+ yield* Effect.sleep(stopPollInterval);
146
+ }
147
+ if (alive(pid)) {
148
+ process.kill(pid, 'SIGKILL');
149
+ }
150
+ });
151
+
152
+ const stopProcess = (stateDir: string, name: ProcessName) =>
153
+ Effect.gen(function* terminateAndForget() {
154
+ const current = yield* processStatus(stateDir, name);
155
+ if (current._tag === 'running') {
156
+ yield* terminate(current.pid);
157
+ }
158
+ yield* Effect.promise(() => rm(pidFile(stateDir, name), { force: true }));
159
+ return current;
160
+ });
161
+
162
+ export { processLogFile, processStatus, startProcess, stopProcess };
163
+ export type { ProcessName, ProcessSpec };
@@ -0,0 +1,152 @@
1
+ import { rm, stat, writeFile } from 'node:fs/promises';
2
+
3
+ import { Effect } from 'effect';
4
+
5
+ import { WtTunnelError } from './errors.ts';
6
+ import { readTextIfExists } from './files.ts';
7
+ import { frpcBinary } from './frpc-binary.ts';
8
+ import { renderFrpcConfig, serverToken, tokenEnvironment } from './frpc-config.ts';
9
+ import { processLogFile, processStatus, startProcess, stopProcess } from './processes.ts';
10
+ import { routedApps } from './provision-ports.ts';
11
+ import type { RoutedApp } from './provision-ports.ts';
12
+ import type { Resource } from './resource.ts';
13
+
14
+ /**
15
+ * The token first, so a missing one fails before the download. `up` runs this before it creates
16
+ * anything, so a missing prerequisite changes nothing.
17
+ */
18
+ const frpcLaunch = Effect.gen(function* tokenThenBinary() {
19
+ const token = yield* serverToken;
20
+ const binary = yield* frpcBinary;
21
+ return { binary, token };
22
+ });
23
+
24
+ const confirmPolls = 75;
25
+ const confirmPollInterval = '200 millis';
26
+
27
+ type ProxyOutcome =
28
+ | { readonly _tag: 'pending' }
29
+ | { readonly _tag: 'rejected'; readonly reason: string }
30
+ | { readonly _tag: 'started' };
31
+
32
+ /** Frpc logs one line per proxy once the server has answered its registration. */
33
+ const proxyOutcome = (lines: readonly string[], app: string): ProxyOutcome => {
34
+ if (lines.some((line) => line.includes(`[${app}] start proxy success`))) {
35
+ return { _tag: 'started' };
36
+ }
37
+ const marker = `[${app}] start error: `;
38
+ const line = lines.find((candidate) => candidate.includes(marker));
39
+ return line === undefined
40
+ ? { _tag: 'pending' }
41
+ : { _tag: 'rejected', reason: line.slice(line.indexOf(marker) + marker.length) };
42
+ };
43
+
44
+ const logSize = (file: string) =>
45
+ Effect.promise(async () => {
46
+ try {
47
+ const info = await stat(file);
48
+ return info.size;
49
+ } catch {
50
+ return 0;
51
+ }
52
+ });
53
+
54
+ /** The log lines written since `offset`: what this frpc instance has said so far. */
55
+ const linesSince = (file: string, offset: number) =>
56
+ Effect.promise(() => readTextIfExists(file)).pipe(
57
+ Effect.map((text) =>
58
+ Buffer.from(text ?? '')
59
+ .subarray(offset)
60
+ .toString('utf8')
61
+ .split('\n'),
62
+ ),
63
+ );
64
+
65
+ /** Frps's reason when another frpc already serves the host. */
66
+ const hostTaken = 'router config conflict';
67
+
68
+ const rejectedMessage = (rejected: readonly (readonly [RoutedApp, string])[]) =>
69
+ [
70
+ 'The tunnel server refused these hosts:',
71
+ ...rejected.map(
72
+ ([{ hostname }, reason]) =>
73
+ ` ${hostname}: ${reason === hostTaken ? 'another worktree already serves it' : reason}`,
74
+ ),
75
+ ].join('\n');
76
+
77
+ /** One look at the log: true once every proxy started, a failure once any was refused. */
78
+ const proxiesStarted = (stateDir: string, apps: readonly RoutedApp[], offset: number) =>
79
+ Effect.gen(function* readOutcomes() {
80
+ const lines = yield* linesSince(processLogFile(stateDir, 'frpc'), offset);
81
+ const outcomes = apps.map((app) => [app, proxyOutcome(lines, app.app)] as const);
82
+ const rejected = outcomes.flatMap(([app, outcome]) =>
83
+ outcome._tag === 'rejected' ? [[app, outcome.reason] as const] : [],
84
+ );
85
+ if (rejected.length > 0) {
86
+ yield* stopProcess(stateDir, 'frpc');
87
+ return yield* new WtTunnelError({ message: rejectedMessage(rejected) });
88
+ }
89
+ return outcomes.every(([, outcome]) => outcome._tag === 'started');
90
+ });
91
+
92
+ /**
93
+ * Starting frpc only proves it logged in; the server can still refuse a proxy, for example when
94
+ * another worktree already serves that host. Waits until every proxy has an answer.
95
+ */
96
+ const confirmProxies = (stateDir: string, apps: readonly RoutedApp[], offset: number) =>
97
+ Effect.gen(function* pollLog() {
98
+ const log = processLogFile(stateDir, 'frpc');
99
+ for (let poll = 0; poll < confirmPolls; poll++) {
100
+ if (yield* proxiesStarted(stateDir, apps, offset)) {
101
+ return yield* Effect.void;
102
+ }
103
+ if ((yield* processStatus(stateDir, 'frpc'))._tag !== 'running') {
104
+ return yield* new WtTunnelError({
105
+ message: `frpc stopped before the server accepted its hosts. See ${log}`,
106
+ });
107
+ }
108
+ yield* Effect.sleep(confirmPollInterval);
109
+ }
110
+ return yield* new WtTunnelError({
111
+ message: `The tunnel server did not confirm every host in time. See ${log}`,
112
+ });
113
+ });
114
+
115
+ /** A running frpc read its config at start, so a changed config means a restart. */
116
+ const writeConfig = (stateDir: string, file: string, wanted: string) =>
117
+ Effect.gen(function* replaceIfChanged() {
118
+ if ((yield* Effect.promise(() => readTextIfExists(file))) !== wanted) {
119
+ yield* stopProcess(stateDir, 'frpc');
120
+ yield* Effect.promise(() => writeFile(file, wanted));
121
+ }
122
+ });
123
+
124
+ /** One frpc per worktree, with one HTTP proxy per routed app. */
125
+ const frpc: Resource = {
126
+ ensure: (context, state) =>
127
+ Effect.gen(function* writeConfigThenStart() {
128
+ const { binary, token } = yield* frpcLaunch;
129
+ const { stateDir, frpcConfigFile } = context.worktree;
130
+ const apps = routedApps(context, state.ports);
131
+ yield* writeConfig(
132
+ stateDir,
133
+ frpcConfigFile,
134
+ renderFrpcConfig(context.config.server, context.worktree, apps),
135
+ );
136
+ if ((yield* processStatus(stateDir, 'frpc'))._tag !== 'running') {
137
+ const offset = yield* logSize(processLogFile(stateDir, 'frpc'));
138
+ const spec = { args: ['-c', frpcConfigFile], command: binary, name: 'frpc' } as const;
139
+ yield* startProcess(stateDir, { ...spec, env: tokenEnvironment(token) });
140
+ yield* confirmProxies(stateDir, apps, offset);
141
+ }
142
+ return state;
143
+ }),
144
+ name: 'frpc',
145
+ remove: ({ worktree }, state) =>
146
+ stopProcess(worktree.stateDir, 'frpc').pipe(
147
+ Effect.andThen(Effect.promise(() => rm(worktree.frpcConfigFile, { force: true }))),
148
+ Effect.as(state),
149
+ ),
150
+ };
151
+
152
+ export { frpc, frpcLaunch };
@@ -0,0 +1,116 @@
1
+ import { writeFile } from 'node:fs/promises';
2
+
3
+ import type { Hostname } from '@tafrahq/wt-tunnel-contract';
4
+ import { Console, Effect, Record } from 'effect';
5
+
6
+ import { hostnameFor, worktreeZone } from './domain.ts';
7
+ import type { AppLabel, Port } from './domain.ts';
8
+ import { WtTunnelError } from './errors.ts';
9
+ import { allocate, claim, release, reservationsDir } from './ports.ts';
10
+ import type { ProvisionContext, Resource } from './resource.ts';
11
+ import type { WorktreeState } from './state.ts';
12
+
13
+ type PortsByApp = Record.ReadonlyRecord<AppLabel, Port>;
14
+
15
+ interface PortRequest {
16
+ readonly app: AppLabel;
17
+ readonly dir: string;
18
+ readonly owner: string;
19
+ /** Ports already given to other apps of this worktree. */
20
+ readonly used: readonly number[];
21
+ }
22
+
23
+ const claimPinned = (request: PortRequest, pinned: Port) =>
24
+ Effect.gen(function* failIfTaken() {
25
+ const result = yield* claim(request.dir, pinned, request.owner);
26
+ if (result._tag === 'taken') {
27
+ return yield* new WtTunnelError({
28
+ message: `Port ${pinned} for ${request.app} is reserved by the worktree at ${result.owner}`,
29
+ });
30
+ }
31
+ return pinned;
32
+ });
33
+
34
+ /** The saved port while this worktree still holds it, else a newly allocated one. */
35
+ const keepOrAllocate = (request: PortRequest, saved: Port | undefined) =>
36
+ Effect.gen(function* reuseSavedPort() {
37
+ if (saved !== undefined && !request.used.includes(saved)) {
38
+ const result = yield* claim(request.dir, saved, request.owner);
39
+ if (result._tag !== 'taken') {
40
+ return saved;
41
+ }
42
+ yield* Console.log(
43
+ ` port ${saved} for ${request.app} now belongs to ${result.owner}; picking a new one`,
44
+ );
45
+ }
46
+ return yield* allocate(request.dir, request.owner, request.used);
47
+ });
48
+
49
+ const reservePorts = (context: ProvisionContext, state: WorktreeState, dir: string) =>
50
+ Effect.gen(function* reserveEachApp() {
51
+ const assigned = new Map<AppLabel, Port>();
52
+ for (const [app, { port: pinned }] of Record.toEntries(context.config.apps)) {
53
+ const request = { app, dir, owner: context.worktree.dir, used: [...assigned.values()] };
54
+ const port =
55
+ pinned === undefined
56
+ ? yield* keepOrAllocate(request, state.ports[app])
57
+ : yield* claimPinned(request, pinned);
58
+ assigned.set(app, port);
59
+ }
60
+ return Object.fromEntries(assigned);
61
+ });
62
+
63
+ const envFileContents = (context: ProvisionContext, ports: PortsByApp) => {
64
+ const lines = Record.collect(
65
+ context.config.apps,
66
+ (app, { portEnv }) => `${portEnv}=${ports[app]}`,
67
+ );
68
+ const host = worktreeZone(context.worktree.name, context.config.domain);
69
+ return `${[...lines, `WT_TUNNEL_HOST=${host}`].join('\n')}\n`;
70
+ };
71
+
72
+ /** The app labelled `root` is served at the bare `<worktree>.<domain>`; others get a label in front. */
73
+ const rootAppLabel = 'root';
74
+
75
+ const appHostname = (context: ProvisionContext, app: AppLabel): Hostname =>
76
+ app === rootAppLabel
77
+ ? worktreeZone(context.worktree.name, context.config.domain)
78
+ : hostnameFor(app, context.worktree.name, context.config.domain);
79
+
80
+ interface RoutedApp {
81
+ readonly app: AppLabel;
82
+ readonly hostname: Hostname;
83
+ readonly port: Port;
84
+ }
85
+
86
+ /** The apps with a route and a reserved port, each with the host name it is served at. */
87
+ const routedApps = (context: ProvisionContext, ports: PortsByApp): readonly RoutedApp[] =>
88
+ Record.collect(context.config.apps, (app, { route }): readonly RoutedApp[] => {
89
+ const port = ports[app];
90
+ return route === false || port === undefined
91
+ ? []
92
+ : [{ app, hostname: appHostname(context, app), port }];
93
+ }).flat();
94
+
95
+ /**
96
+ * Ports are reserved per user in files (see ports.ts), so a stopped worktree keeps its ports and no
97
+ * other worktree can be handed them.
98
+ */
99
+ const ports: Resource = {
100
+ ensure: (context, state) =>
101
+ Effect.gen(function* reserveAndWriteEnv() {
102
+ const dir = reservationsDir();
103
+ const assigned = yield* reservePorts(context, state, dir);
104
+ yield* release(dir, context.worktree.dir, Object.values(assigned));
105
+ yield* Effect.promise(() =>
106
+ writeFile(context.worktree.envFile, envFileContents(context, assigned)),
107
+ );
108
+ return { ...state, ports: assigned };
109
+ }),
110
+ name: 'ports',
111
+ remove: (context, state) =>
112
+ release(reservationsDir(), context.worktree.dir).pipe(Effect.as({ ...state, ports: {} })),
113
+ };
114
+
115
+ export { ports, routedApps };
116
+ export type { RoutedApp };
@@ -0,0 +1,41 @@
1
+ import { Console, Effect } from 'effect';
2
+
3
+ import { frpc } from './provision-frpc.ts';
4
+ import { ports } from './provision-ports.ts';
5
+ import type { ProvisionContext, Resource } from './resource.ts';
6
+ import { writeState } from './state.ts';
7
+ import type { WorktreeState } from './state.ts';
8
+
9
+ /** What a worktree is made of, in creation order. */
10
+ const worktreeResources: readonly Resource[] = [ports, frpc];
11
+
12
+ interface Pass {
13
+ readonly verb: 'ensure' | 'remove';
14
+ readonly order: readonly Resource[];
15
+ }
16
+
17
+ /** Applies one step per resource, saving the state after each so a crash loses no progress. */
18
+ const applyPass = (context: ProvisionContext, initial: WorktreeState, pass: Pass) =>
19
+ Effect.gen(function* stepThroughResources() {
20
+ let state = initial;
21
+ for (const resource of pass.order) {
22
+ yield* Console.log(` ${pass.verb} ${resource.name}`);
23
+ state = yield* resource[pass.verb](context, state);
24
+ yield* writeState(context.worktree.stateFile, state);
25
+ }
26
+ return state;
27
+ });
28
+
29
+ const ensureAll = (
30
+ context: ProvisionContext,
31
+ initial: WorktreeState,
32
+ list: readonly Resource[] = worktreeResources,
33
+ ) => applyPass(context, initial, { order: list, verb: 'ensure' });
34
+
35
+ const removeAll = (
36
+ context: ProvisionContext,
37
+ initial: WorktreeState,
38
+ list: readonly Resource[] = worktreeResources,
39
+ ) => applyPass(context, initial, { order: list.toReversed(), verb: 'remove' });
40
+
41
+ export { ensureAll, removeAll, worktreeResources };
@@ -0,0 +1,28 @@
1
+ import type { Effect } from 'effect';
2
+
3
+ import type { WtTunnelConfig } from './config.ts';
4
+ import type { WtTunnelError } from './errors.ts';
5
+ import type { WorktreeState } from './state.ts';
6
+ import type { Worktree } from './worktree.ts';
7
+
8
+ interface ProvisionContext {
9
+ readonly config: WtTunnelConfig;
10
+ readonly worktree: Worktree;
11
+ }
12
+
13
+ type Step = (
14
+ context: ProvisionContext,
15
+ state: WorktreeState,
16
+ ) => Effect.Effect<WorktreeState, WtTunnelError>;
17
+
18
+ /**
19
+ * Each resource is found again by a deterministic name, never only by what state remembers, so a
20
+ * rerun after a crash or a lost state file converges.
21
+ */
22
+ interface Resource {
23
+ readonly ensure: Step;
24
+ readonly name: string;
25
+ readonly remove: Step;
26
+ }
27
+
28
+ export type { ProvisionContext, Resource };
package/src/state.ts ADDED
@@ -0,0 +1,87 @@
1
+ import { dirname } from 'node:path';
2
+
3
+ import { Hostname } from '@tafrahq/wt-tunnel-contract';
4
+ import { Effect, FileSystem, Schema } from 'effect';
5
+
6
+ import { AppLabel, Port, ProjectName, WorktreeName } from './domain.ts';
7
+ import { WtTunnelError } from './errors.ts';
8
+ import type { Worktree } from './worktree.ts';
9
+
10
+ const stateVersion = 4;
11
+ const jsonIndent = 2;
12
+
13
+ const WorktreeState = Schema.Struct({
14
+ domain: Hostname,
15
+ ports: Schema.Record(AppLabel, Port),
16
+ project: ProjectName,
17
+ version: Schema.Literal(stateVersion),
18
+ worktree: WorktreeName,
19
+ });
20
+ type WorktreeState = typeof WorktreeState.Type;
21
+
22
+ const StateJson = Schema.fromJsonString(WorktreeState);
23
+
24
+ const initialState = (
25
+ project: ProjectName,
26
+ worktree: WorktreeName,
27
+ domain: Hostname,
28
+ ): WorktreeState => ({
29
+ domain,
30
+ ports: {},
31
+ project,
32
+ version: stateVersion,
33
+ worktree,
34
+ });
35
+
36
+ const VersionJson = Schema.fromJsonString(Schema.Struct({ version: Schema.Unknown }));
37
+
38
+ /** Names the version mismatch when that is the problem, since the schema error would not. */
39
+ const invalidState = (file: string, text: string, schemaMessage: string) => {
40
+ const found = Schema.decodeUnknownOption(VersionJson)(text);
41
+ const version = found._tag === 'Some' ? found.value.version : undefined;
42
+ if (version !== undefined && version !== stateVersion) {
43
+ return new WtTunnelError({
44
+ message: `${file} was written by an older wt-tunnel-client (state version ${JSON.stringify(version)}, this one reads ${stateVersion}). Stop the processes named by the pid files in ${dirname(file)}, delete that directory, and run wt-tunnel-client worktree add again.`,
45
+ });
46
+ }
47
+ return new WtTunnelError({ message: `${file} is not valid state: ${schemaMessage}` });
48
+ };
49
+
50
+ const decodeState = (file: string, text: string) =>
51
+ Schema.decodeUnknownEffect(StateJson)(text).pipe(
52
+ Effect.mapError((schemaError) => invalidState(file, text, schemaError.message)),
53
+ );
54
+
55
+ const readState = (file: string) =>
56
+ Effect.gen(function* readIfPresent() {
57
+ const fs = yield* FileSystem.FileSystem;
58
+ const exists = yield* fs.exists(file);
59
+ return exists ? yield* decodeState(file, yield* fs.readFileString(file)) : undefined;
60
+ });
61
+
62
+ /** The saved state when it is for the same names (a rerun), else a fresh one; other names fail. */
63
+ const startingState = (worktree: Worktree, domain: Hostname) =>
64
+ Effect.gen(function* readOrCreate() {
65
+ const existing = yield* readState(worktree.stateFile);
66
+ if (existing === undefined) {
67
+ return initialState(worktree.project, worktree.name, domain);
68
+ }
69
+ if (existing.project !== worktree.project || existing.worktree !== worktree.name) {
70
+ return yield* new WtTunnelError({
71
+ message: `${worktree.dir} is already provisioned as ${existing.project} ${existing.worktree}. Run \`wt-tunnel-client worktree remove\` first.`,
72
+ });
73
+ }
74
+ return existing;
75
+ });
76
+
77
+ const writeState = (file: string, state: WorktreeState) =>
78
+ Effect.gen(function* writeAtomically() {
79
+ const fs = yield* FileSystem.FileSystem;
80
+ const encoded = yield* Schema.encodeEffect(WorktreeState)(state).pipe(Effect.orDie);
81
+ const temp = `${file}.${process.pid}.tmp`;
82
+ yield* fs.writeFileString(temp, `${JSON.stringify(encoded, undefined, jsonIndent)}\n`);
83
+ yield* fs.rename(temp, file);
84
+ });
85
+
86
+ export { initialState, readState, startingState, writeState };
87
+ export type { WorktreeState };
@@ -0,0 +1,52 @@
1
+ import { join } from 'node:path';
2
+
3
+ import { Effect, Schema } from 'effect';
4
+
5
+ import { ProjectName, WorktreeName } from './domain.ts';
6
+ import { WtTunnelError } from './errors.ts';
7
+
8
+ /** The directory being served (the worktree root) and the names it was provisioned under. */
9
+ interface Worktree {
10
+ readonly dir: string;
11
+ readonly envFile: string;
12
+ readonly frpcConfigFile: string;
13
+ readonly name: WorktreeName;
14
+ readonly project: ProjectName;
15
+ readonly stateDir: string;
16
+ readonly stateFile: string;
17
+ }
18
+
19
+ const stateDirOf = (root: string) => join(root, '.wt-tunnel');
20
+
21
+ const stateFileOf = (root: string) => join(stateDirOf(root), 'state.json');
22
+
23
+ const invalidName = (kind: string, value: string) =>
24
+ new WtTunnelError({
25
+ message: `"${value}" is not a valid ${kind} name. Use lowercase letters, digits and interior hyphens, at most 63 characters (a DNS label).`,
26
+ });
27
+
28
+ const parseProjectName = (value: string) =>
29
+ Schema.decodeUnknownEffect(ProjectName)(value).pipe(
30
+ Effect.mapError(() => invalidName('project', value)),
31
+ );
32
+
33
+ const parseWorktreeName = (value: string) =>
34
+ Schema.decodeUnknownEffect(WorktreeName)(value).pipe(
35
+ Effect.mapError(() => invalidName('worktree', value)),
36
+ );
37
+
38
+ const worktreeAt = (root: string, project: ProjectName, name: WorktreeName): Worktree => {
39
+ const stateDir = stateDirOf(root);
40
+ return {
41
+ dir: root,
42
+ envFile: join(stateDir, 'env'),
43
+ frpcConfigFile: join(stateDir, 'frpc.toml'),
44
+ name,
45
+ project,
46
+ stateDir,
47
+ stateFile: stateFileOf(root),
48
+ };
49
+ };
50
+
51
+ export { parseProjectName, parseWorktreeName, stateFileOf, worktreeAt };
52
+ export type { Worktree };