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

DesktopBackendConfiguration.ts

183 lines6.5 KB

1import { parsePersistedServerObservabilitySettings } from "@t3tools/shared/serverSettings";
2import * as Context from "effect/Context";
3import * as Crypto from "effect/Crypto";
4import * as Effect from "effect/Effect";
5import * as Encoding from "effect/Encoding";
6import * as FileSystem from "effect/FileSystem";
7import * as Layer from "effect/Layer";
8import * as Option from "effect/Option";
9import * as PlatformError from "effect/PlatformError";
10import * as Ref from "effect/Ref";
11import * as Schema from "effect/Schema";
12​
13import * as DesktopBackendManager from "./DesktopBackendManager.ts";
14import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
15import * as DesktopServerExposure from "./DesktopServerExposure.ts";
16​
17export class DesktopBackendObservabilitySettingsReadError extends Schema.TaggedErrorClass<DesktopBackendObservabilitySettingsReadError>()(
18 "DesktopBackendObservabilitySettingsReadError",
19 {
20 settingsPath: Schema.String,
21 cause: Schema.Defect(),
22 },
23) {
24 override get message(): string {
25 return `Failed to read persisted backend observability settings at ${this.settingsPath}.`;
26 }
28​
29export class DesktopBackendConfiguration extends Context.Service<
30 DesktopBackendConfiguration,
31 {
32 readonly resolve: Effect.Effect<
33 DesktopBackendManager.DesktopBackendStartConfig,
34 PlatformError.PlatformError
35 >;
36 }
37>()("@t3tools/desktop/backend/DesktopBackendConfiguration") {}
38​
39interface BackendObservabilitySettings {
40 readonly otlpTracesUrl: Option.Option<string>;
41 readonly otlpMetricsUrl: Option.Option<string>;
43​
44const emptyBackendObservabilitySettings: BackendObservabilitySettings = {
45 otlpTracesUrl: Option.none(),
46 otlpMetricsUrl: Option.none(),
47};
48​
49const DESKTOP_BACKEND_ENV_NAMES = [
50 "T3CODE_PORT",
51 "T3CODE_MODE",
52 "T3CODE_NO_BROWSER",
53 "T3CODE_HOST",
54 "T3CODE_DESKTOP_WS_URL",
55 "T3CODE_DESKTOP_LAN_ACCESS",
56 "T3CODE_DESKTOP_LAN_HOST",
57 "T3CODE_DESKTOP_HTTPS_ENDPOINTS",
58 "T3CODE_TAILSCALE_SERVE",
59 "T3CODE_TAILSCALE_SERVE_PORT",
60] as const;
61​
62const backendChildEnvPatch = (): Record<string, string | undefined> =>
63 Object.fromEntries(DESKTOP_BACKEND_ENV_NAMES.map((name) => [name, undefined]));
64​
65const logBackendObservabilitySettingsReadFailure = (
66 settingsPath: string,
67 cause: PlatformError.PlatformError,
68) => {
69 const error = new DesktopBackendObservabilitySettingsReadError({ settingsPath, cause });
70 return Effect.logWarning(error).pipe(
71 Effect.annotateLogs({
72 component: "desktop-backend-configuration",
73 error,
74 }),
75 );
76};
77​
78const readPersistedBackendObservabilitySettings = Effect.gen(function* () {
79 const fileSystem = yield* FileSystem.FileSystem;
80 const environment = yield* DesktopEnvironment.DesktopEnvironment;
81 const raw = yield* fileSystem.readFileString(environment.serverSettingsPath).pipe(
82 Effect.map(Option.some),
83 Effect.catchTags({
84 PlatformError: (cause) =>
85 cause.reason._tag === "NotFound"
86 ? Effect.succeed(Option.none())
87 : logBackendObservabilitySettingsReadFailure(environment.serverSettingsPath, cause).pipe(
88 Effect.as(Option.none()),
89 ),
90 }),
91 );
92 if (Option.isNone(raw)) {
93 return emptyBackendObservabilitySettings;
94 }
95​
96 const parsed = parsePersistedServerObservabilitySettings(raw.value);
97 return {
98 otlpTracesUrl: Option.fromNullishOr(parsed.otlpTracesUrl),
99 otlpMetricsUrl: Option.fromNullishOr(parsed.otlpMetricsUrl),
100 };
101});
102​
103const resolveBackendStartConfig = Effect.fn("desktop.backendConfiguration.resolveStartConfig")(
104 function* (input: {
105 readonly bootstrapToken: string;
106 readonly observabilitySettings: BackendObservabilitySettings;
107 }): Effect.fn.Return<
108 DesktopBackendManager.DesktopBackendStartConfig,
109 never,
110 DesktopEnvironment.DesktopEnvironment | DesktopServerExposure.DesktopServerExposure
111 > {
112 const environment = yield* DesktopEnvironment.DesktopEnvironment;
113 const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
114 const backendExposure = yield* serverExposure.backendConfig;
115​
116 return {
117 executablePath: process.execPath,
118 entryPath: environment.backendEntryPath,
119 cwd: environment.backendCwd,
120 env: {
121 ...backendChildEnvPatch(),
122 ELECTRON_RUN_AS_NODE: "1",
123 },
124 bootstrap: {
125 mode: "desktop",
126 noBrowser: true,
127 port: backendExposure.port,
128 t3Home: environment.baseDir,
129 host: backendExposure.bindHost,
130 desktopBootstrapToken: input.bootstrapToken,
131 tailscaleServeEnabled: backendExposure.tailscaleServeEnabled,
132 tailscaleServePort: backendExposure.tailscaleServePort,
133 ...Option.match(input.observabilitySettings.otlpTracesUrl, {
134 onNone: () => ({}),
135 onSome: (otlpTracesUrl) => ({ otlpTracesUrl }),
136 }),
137 ...Option.match(input.observabilitySettings.otlpMetricsUrl, {
138 onNone: () => ({}),
139 onSome: (otlpMetricsUrl) => ({ otlpMetricsUrl }),
140 }),
141 },
142 httpBaseUrl: backendExposure.httpBaseUrl,
143 captureOutput: true,
144 };
145 },
146);
147​
148export const make = Effect.gen(function* () {
149 const environment = yield* DesktopEnvironment.DesktopEnvironment;
150 const fileSystem = yield* FileSystem.FileSystem;
151 const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
152 const crypto = yield* Crypto.Crypto;
153 const tokenRef = yield* Ref.make(Option.none<string>());
154 const getOrCreateBootstrapToken = Effect.gen(function* () {
155 const existing = yield* Ref.get(tokenRef);
156 if (Option.isSome(existing)) {
157 return existing.value;
158 }
159​
160 const token = Encoding.encodeHex(yield* crypto.randomBytes(24));
161 yield* Ref.set(tokenRef, Option.some(token));
162 return token;
163 });
164​
165 return DesktopBackendConfiguration.of({
166 resolve: Effect.gen(function* () {
167 const bootstrapToken = yield* getOrCreateBootstrapToken;
168 const observabilitySettings = yield* readPersistedBackendObservabilitySettings.pipe(
169 Effect.provideService(FileSystem.FileSystem, fileSystem),
170 Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
171 );
172 return yield* resolveBackendStartConfig({
173 bootstrapToken,
174 observabilitySettings,
175 }).pipe(
176 Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
177 Effect.provideService(DesktopServerExposure.DesktopServerExposure, serverExposure),
178 );
179 }).pipe(Effect.withSpan("desktop.backendConfiguration.resolve")),
180 });
181});
182​
183export const layer = Layer.effect(DesktopBackendConfiguration, make);