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

DesktopApp.ts

244 lines9.2 KB

1import * as Cause from "effect/Cause";
2import * as Data from "effect/Data";
3import * as Effect from "effect/Effect";
4import * as Option from "effect/Option";
5import * as Ref from "effect/Ref";
6​
7import * as NetService from "@t3tools/shared/Net";
8import * as Crypto from "effect/Crypto";
9import * as ElectronApp from "../electron/ElectronApp.ts";
10import * as ElectronDialog from "../electron/ElectronDialog.ts";
11import * as ElectronProtocol from "../electron/ElectronProtocol.ts";
12import { installDesktopIpcHandlers } from "../ipc/DesktopIpcHandlers.ts";
13import * as DesktopAppIdentity from "./DesktopAppIdentity.ts";
14import * as DesktopCloudAuth from "./DesktopCloudAuth.ts";
15import * as DesktopApplicationMenu from "../window/DesktopApplicationMenu.ts";
16import * as DesktopBackendManager from "../backend/DesktopBackendManager.ts";
17import * as DesktopEnvironment from "./DesktopEnvironment.ts";
18import * as DesktopLifecycle from "./DesktopLifecycle.ts";
19import * as DesktopObservability from "./DesktopObservability.ts";
20import * as DesktopServerExposure from "../backend/DesktopServerExposure.ts";
21import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
22import * as DesktopShellEnvironment from "../shell/DesktopShellEnvironment.ts";
23import * as DesktopState from "./DesktopState.ts";
24import * as DesktopUpdates from "../updates/DesktopUpdates.ts";
25​
26const DEFAULT_DESKTOP_BACKEND_PORT = 3773;
27const MAX_TCP_PORT = 65_535;
28const DESKTOP_BACKEND_PORT_PROBE_HOSTS = ["127.0.0.1", "0.0.0.0", "::"] as const;
29​
30const makeDesktopRunId = Crypto.Crypto.pipe(
31 Effect.flatMap((crypto) => crypto.randomUUIDv4),
32 Effect.map((value) => value.replaceAll("-", "").slice(0, 12)),
33);
34​
35class DesktopBackendPortUnavailableError extends Data.TaggedError(
36 "DesktopBackendPortUnavailableError",
37)<{
38 readonly startPort: number;
39 readonly maxPort: number;
40 readonly hosts: readonly string[];
41}> {
42 override get message() {
43 return `No desktop backend port is available on hosts ${this.hosts.join(", ")} between ${this.startPort} and ${this.maxPort}.`;
44 }
46​
47class DesktopDevelopmentBackendPortRequiredError extends Data.TaggedError(
48 "DesktopDevelopmentBackendPortRequiredError",
49)<{}> {
50 override get message() {
51 return "T3CODE_PORT is required in desktop development.";
52 }
54​
55const { logInfo: logBootstrapInfo, logWarning: logBootstrapWarning } =
56 DesktopObservability.makeComponentLogger("desktop-bootstrap");
57​
58const { logInfo: logStartupInfo, logError: logStartupError } =
59 DesktopObservability.makeComponentLogger("desktop-startup");
60​
61const resolveDesktopBackendPort = Effect.fn("resolveDesktopBackendPort")(function* (
62 configuredPort: Option.Option<number>,
63) {
64 if (Option.isSome(configuredPort)) {
65 return {
66 port: configuredPort.value,
67 selectedByScan: false,
68 } as const;
69 }
70​
71 const net = yield* NetService.NetService;
72 for (let port = DEFAULT_DESKTOP_BACKEND_PORT; port <= MAX_TCP_PORT; port += 1) {
73 let availableOnEveryHost = true;
74​
75 for (const host of DESKTOP_BACKEND_PORT_PROBE_HOSTS) {
76 if (!(yield* net.canListenOnHost(port, host))) {
77 availableOnEveryHost = false;
78 break;
79 }
80 }
81​
82 if (availableOnEveryHost) {
83 return {
84 port,
85 selectedByScan: true,
86 } as const;
87 }
88 }
89​
90 return yield* new DesktopBackendPortUnavailableError({
91 startPort: DEFAULT_DESKTOP_BACKEND_PORT,
92 maxPort: MAX_TCP_PORT,
93 hosts: DESKTOP_BACKEND_PORT_PROBE_HOSTS,
94 });
95});
96​
97const handleFatalStartupError = Effect.fn("desktop.startup.handleFatalStartupError")(function* (
98 stage: string,
99 error: unknown,
100): Effect.fn.Return<
101 void,
102 never,
103 | DesktopLifecycle.DesktopShutdown
104 | DesktopState.DesktopState
105 | ElectronApp.ElectronApp
106 | ElectronDialog.ElectronDialog
107> {
108 const shutdown = yield* DesktopLifecycle.DesktopShutdown;
109 const state = yield* DesktopState.DesktopState;
110 const electronApp = yield* ElectronApp.ElectronApp;
111 const electronDialog = yield* ElectronDialog.ElectronDialog;
112 const message = error instanceof Error ? error.message : String(error);
113 const detail =
114 error instanceof Error && typeof error.stack === "string" ? `\n${error.stack}` : "";
115 yield* logStartupError("fatal startup error", {
116 stage,
117 message,
118 ...(detail.length > 0 ? { detail } : {}),
119 });
120 const wasQuitting = yield* Ref.getAndSet(state.quitting, true);
121 if (!wasQuitting) {
122 yield* electronDialog.showErrorBox(
123 "T3 Code failed to start",
124 `Stage: ${stage}\n${message}${detail}`,
125 );
126 }
127 yield* shutdown.request;
128 yield* electronApp.quit;
129});
130​
131const fatalStartupCause = <E>(stage: string, cause: Cause.Cause<E>) =>
132 handleFatalStartupError(stage, Cause.pretty(cause)).pipe(Effect.andThen(Effect.failCause(cause)));
133​
134const bootstrap = Effect.gen(function* () {
135 const backendManager = yield* DesktopBackendManager.DesktopBackendManager;
136 const state = yield* DesktopState.DesktopState;
137 const environment = yield* DesktopEnvironment.DesktopEnvironment;
138 const desktopSettings = yield* DesktopAppSettings.DesktopAppSettings;
139 const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
140 yield* logBootstrapInfo("bootstrap start");
141​
142 if (environment.isDevelopment && Option.isNone(environment.configuredBackendPort)) {
143 return yield* new DesktopDevelopmentBackendPortRequiredError();
144 }
145​
146 const backendPortSelection = yield* resolveDesktopBackendPort(environment.configuredBackendPort);
147 const backendPort = backendPortSelection.port;
148 yield* logBootstrapInfo(
149 backendPortSelection.selectedByScan
150 ? "selected backend port via sequential scan"
151 : "using configured backend port",
152 {
153 port: backendPort,
154 ...(backendPortSelection.selectedByScan ? { startPort: DEFAULT_DESKTOP_BACKEND_PORT } : {}),
155 },
156 );
157​
158 const settings = yield* desktopSettings.get;
159 if (settings.serverExposureMode !== environment.defaultDesktopSettings.serverExposureMode) {
160 yield* logBootstrapInfo("bootstrap restoring persisted server exposure mode", {
161 mode: settings.serverExposureMode,
162 });
163 }
164 const serverExposureState = yield* serverExposure.configureFromSettings({ port: backendPort });
165 const backendConfig = yield* serverExposure.backendConfig;
166 yield* logBootstrapInfo("bootstrap resolved backend endpoint", {
167 baseUrl: backendConfig.httpBaseUrl.href,
168 });
169 if (serverExposureState.endpointUrl) {
170 yield* logBootstrapInfo("bootstrap enabled network access", {
171 endpointUrl: serverExposureState.endpointUrl,
172 });
173 } else if (settings.serverExposureMode === "network-accessible") {
174 yield* logBootstrapWarning(
175 "bootstrap fell back to local-only because no advertised network host was available",
176 );
177 }
178​
179 yield* installDesktopIpcHandlers;
180 yield* logBootstrapInfo("bootstrap ipc handlers registered");
181​
182 if (!(yield* Ref.get(state.quitting))) {
183 yield* backendManager.start;
184 yield* logBootstrapInfo("bootstrap backend start requested");
185 }
186}).pipe(Effect.withSpan("desktop.bootstrap"));
187​
188const startup = Effect.gen(function* () {
189 const appIdentity = yield* DesktopAppIdentity.DesktopAppIdentity;
190 const applicationMenu = yield* DesktopApplicationMenu.DesktopApplicationMenu;
191 const electronApp = yield* ElectronApp.ElectronApp;
192 const electronProtocol = yield* ElectronProtocol.ElectronProtocol;
193 const lifecycle = yield* DesktopLifecycle.DesktopLifecycle;
194 const cloudAuth = yield* DesktopCloudAuth.DesktopCloudAuth;
195 const shellEnvironment = yield* DesktopShellEnvironment.DesktopShellEnvironment;
196 const desktopSettings = yield* DesktopAppSettings.DesktopAppSettings;
197 const updates = yield* DesktopUpdates.DesktopUpdates;
198 const environment = yield* DesktopEnvironment.DesktopEnvironment;
199​
200 yield* shellEnvironment.installIntoProcess;
201 const userDataPath = yield* appIdentity.resolveUserDataPath;
202 yield* electronApp.setPath("userData", userDataPath);
203 yield* logStartupInfo("runtime logging configured", { logDir: environment.logDir });
204 yield* desktopSettings.load;
205​
206 if (environment.platform === "linux") {
207 yield* electronApp.appendCommandLineSwitch("class", environment.linuxWmClass);
208 }
209​
210 yield* appIdentity.configure;
211 yield* lifecycle.register;
212 yield* cloudAuth.configure;
213​
214 yield* electronApp.whenReady.pipe(
215 Effect.withSpan("desktop.electron.whenReady"),
216 Effect.catchCause((cause) => fatalStartupCause("whenReady", cause)),
217 );
218 yield* logStartupInfo("app ready");
219 yield* appIdentity.configure;
220 yield* applicationMenu.configure;
221 yield* electronProtocol.registerDesktopFileProtocol;
222 yield* updates.configure;
223 yield* bootstrap.pipe(Effect.catchCause((cause) => fatalStartupCause("bootstrap", cause)));
224}).pipe(Effect.withSpan("desktop.startup"));
225​
226const scopedProgram = Effect.scoped(
227 Effect.gen(function* () {
228 const runId = yield* makeDesktopRunId;
229 yield* Effect.annotateLogsScoped({ scope: "desktop", runId });
230 yield* Effect.annotateCurrentSpan({ scope: "desktop", runId });
231​
232 const shutdown = yield* DesktopLifecycle.DesktopShutdown;
233 const backendManager = yield* DesktopBackendManager.DesktopBackendManager;
234​
235 yield* Effect.addFinalizer(() =>
236 backendManager.stop().pipe(Effect.ensuring(shutdown.markComplete)),
237 );
238​
239 yield* startup;
240 yield* shutdown.awaitRequest;
241 }),
242);
243​
244export const program = scopedProgram.pipe(Effect.withSpan("desktop.app"));