Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

second-server.ts

68 lines2.6 KB

1// A second T3 server for scenarios that need another machine: its own T3 home, the replay
2// agent, and a pairing token for Settings > Connections > Add environment.
3import * as NodeServices from "@effect/platform-node/NodeServices";
4import * as HostProcess from "@t3tools/shared/HostProcess";
5import * as NetService from "@t3tools/shared/Net";
6import * as Deferred from "effect/Deferred";
7import * as Effect from "effect/Effect";
8import * as Fiber from "effect/Fiber";
9import * as Path from "effect/Path";
10​
11import { APP_DIR, T3_HOME } from "../e2e.config.ts";
12import { prepareHome, start } from "./start-app.ts";
13​
14export const SECOND_HOME = `${T3_HOME}-second-environment`;
15​
16/** A second server on its own T3 home, running until interrupted. `--dev-url` admits the web
17 * origin through CORS and registers the replay agent; `paired` gets the Add environment input. */
18const runSecondServer = Effect.fn("scenario.secondServer")(function* (
19 devUrl: string,
20 paired: (target: { readonly host: string; readonly token: string }) => void,
21) {
22 const path = yield* Path.Path;
23 const node = yield* HostProcess.ExecutablePath;
24 const hostEnvironment = yield* HostProcess.Environment;
25 const port = yield* (yield* NetService.NetService).reserveLoopbackPort();
26 yield* prepareHome(SECOND_HOME);
27 const token = yield* Deferred.make<string>();
28 yield* start({
29 cwd: APP_DIR,
30 command: node,
31 args: [
32 "apps/server/src/bin.ts",
33 "serve",
34 "--host",
35 "127.0.0.1",
36 "--port",
37 String(port),
38 "--base-dir",
39 SECOND_HOME,
40 "--dev-url",
41 devUrl,
42 ],
43 env: {
44 PATH: `${path.join(SECOND_HOME, "bin")}:${hostEnvironment.PATH ?? ""}`,
45 HOME: hostEnvironment.HOME,
46 T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "0",
47 },
48 onLine: (line) => {
49 const value = /^Token:\s*(\S+)/.exec(line)?.[1];
50 return value === undefined ? Effect.void : Deferred.succeed(token, value).pipe(Effect.asVoid);
51 },
52 });
53 paired({ host: `http://127.0.0.1:${port}`, token: yield* Deferred.await(token) });
54 return yield* Effect.never;
55});
56​
57/** Starts the second server for the web app at `devUrl`. `ready` settles with its pairing input. */
58export function startSecondServer(devUrl: string) {
59 const pairing = Promise.withResolvers<{ readonly host: string; readonly token: string }>();
60 const server = Effect.runFork(
61 runSecondServer(devUrl, pairing.resolve).pipe(
62 Effect.scoped,
63 Effect.provide([NodeServices.layer, NetService.layer]),
64 ),
65 );
66 server.addObserver(() => pairing.reject(new Error("The second server stopped.")));
67 return { ready: pairing.promise, stop: () => Effect.runPromise(Fiber.interrupt(server)) };