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

config.ts

301 lines11.9 KB

1import * as Context from "effect/Context";
2import * as Clock from "effect/Clock";
3import * as Effect from "effect/Effect";
4import * as FileSystem from "effect/FileSystem";
5import * as Layer from "effect/Layer";
6import * as LogLevel from "effect/LogLevel";
7import * as Path from "effect/Path";
8import type * as Redacted from "effect/Redacted";
9import * as Schema from "effect/Schema";
10​
11import type { OtlpEndpointSource } from "@t3tools/contracts";
12import { sweepStalePendingAttachments } from "./attachmentStore.ts";
13import { markNoCopyOnWrite } from "./noCopyOnWrite.ts";
14import {
15 DEFAULT_SIGNAL_EXPORT,
16 nodeProcessRuntimeAttributes,
17 processServiceInstanceId,
18 type SignalExport,
19} from "@t3tools/shared/observability";
20import * as OtelEnvironment from "@t3tools/shared/otelEnvironment";
21import { type ReleaseChannel, releaseResourceAttributes } from "@t3tools/shared/releaseResource";
22import packageJson from "../package.json" with { type: "json" };
23​
24// Official release workflows set this telemetry channel; other builds report dev.
25// Unlike __T3CODE_BUILD_CHANNEL__, this is not the sign-in page's latest/nightly channel.
26declare const __T3CODE_TELEMETRY_CHANNEL__: ReleaseChannel | undefined;
27export const telemetryChannel: ReleaseChannel =
28 typeof __T3CODE_TELEMETRY_CHANNEL__ === "undefined" ? "dev" : __T3CODE_TELEMETRY_CHANNEL__;
29​
30export const DEFAULT_PORT = 3773;
31​
32export const RuntimeMode = Schema.Literals(["web", "desktop"]);
33export type RuntimeMode = typeof RuntimeMode.Type;
34​
35export const StartupPresentation = Schema.Literals(["browser", "headless"]);
36export type StartupPresentation = typeof StartupPresentation.Type;
37​
38export interface ServerDerivedPaths {
39 readonly stateDir: string;
40 readonly dbPath: string;
41 readonly keybindingsConfigPath: string;
42 readonly settingsPath: string;
43 readonly environmentThemesDir: string;
44 readonly providerStatusCacheDir: string;
45 readonly worktreesDir: string;
46 /** Where workflow definition files live. In the home itself: they are the user's own code. */
47 readonly workflowsDir: string;
48 readonly worktreeCheckoutCacheDir: string;
49 readonly attachmentsDir: string;
50 readonly browserArtifactsDir: string;
51 readonly logsDir: string;
52 readonly serverTracePath: string;
53 readonly providerLogsDir: string;
54 readonly providerEventLogPath: string;
55 readonly terminalLogsDir: string;
56 readonly anonymousIdPath: string;
57 readonly environmentIdPath: string;
58 readonly serverRuntimeStatePath: string;
59 readonly secretsDir: string;
61​
62export interface DeriveServerPathsOptions {
63 readonly baseDirIsExplicit?: boolean;
65​
66export class ServerConfig extends Context.Service<
67 ServerConfig,
68 ServerDerivedPaths & {
69 readonly logLevel: LogLevel.LogLevel;
70 readonly traceMinLevel: LogLevel.LogLevel;
71 readonly traceTimingEnabled: boolean;
72 readonly traceBatchWindowMs: number;
73 readonly traceMaxBytes: number;
74 readonly traceMaxFiles: number;
75 readonly otlpTracesUrl: string | undefined;
76 readonly otlpMetricsUrl: string | undefined;
77 readonly otlpLogsUrl: string | undefined;
78 readonly otlpTracesExport: SignalExport;
79 readonly otlpMetricsExport: SignalExport;
80 readonly otlpLogsExport: SignalExport;
81 readonly otlpTracesSource?: OtlpEndpointSource;
82 readonly otlpTracesVariable?: string;
83 readonly otlpMetricsSource?: OtlpEndpointSource;
84 readonly otlpMetricsVariable?: string;
85 readonly otlpLogsSource?: OtlpEndpointSource;
86 readonly otlpLogsVariable?: string;
87 readonly otelEnvironment: OtelEnvironment.OtelEnvironment;
88 readonly mode: RuntimeMode;
89 readonly port: number;
90 readonly host: string | undefined;
91 /** Set when the host was defaulted to a private-network listener for the service. */
92 readonly privateNetworkOnly?: boolean | undefined;
93 readonly cwd: string;
94 readonly baseDir: string;
95 readonly staticDir: string | undefined;
96 readonly devUrl: URL | undefined;
97 readonly devAuthToken?: Redacted.Redacted<string> | undefined;
98 readonly devAllowedOrigins: ReadonlyArray<string>;
99 readonly noBrowser: boolean;
100 readonly startupPresentation: StartupPresentation;
101 readonly desktopBootstrapToken: string | undefined;
102 readonly desktopBootstrapSecret?: string | undefined;
103 readonly desktopReadinessSecret?: string | undefined;
104 readonly shellEnvironmentPrepared?: boolean | undefined;
105 readonly desktopTelemetryFd?: number | undefined;
106 readonly desktopTelemetryControlFd?: number | undefined;
107 readonly desktopAppUpdate?: boolean | undefined;
108 readonly desktopBrowserFd?: number | undefined;
109 readonly desktopBrowserControlFd?: number | undefined;
110 readonly resourceMonitorPath?: string | undefined;
111 readonly autoBootstrapProjectFromCwd: boolean;
112 readonly logWebSocketEvents: boolean;
113 readonly tailscaleServeEnabled: boolean;
114 readonly tailscaleServePort: number;
115 }
116>()("t3/config/ServerConfig") {
117 static readonly layerTest = (
118 cwd: string,
119 baseDirOrPrefix: string | { readonly prefix: string },
120 ) => layerTest(cwd, baseDirOrPrefix);
122​
123export const make = (config: ServerConfig["Service"]) => ServerConfig.of(config);
124​
125export const otlpResource = (
126 config: Pick<ServerConfig["Service"], "mode" | "otelEnvironment">,
127 hostName: string,
128) => ({
129 serviceName: "t3code-server",
130 serviceVersion: packageJson.version,
131 attributes: {
132 "service.namespace": "t3code",
133 "service.runtime": "t3-server",
134 "t3code.server.managed_by": config.mode === "desktop" ? "desktop" : "standalone",
135 "service.instance.id": processServiceInstanceId(config.otelEnvironment.resourceAttributes),
136 ...releaseResourceAttributes(telemetryChannel, config.otelEnvironment.resourceAttributes),
137 "host.name": config.otelEnvironment.resourceAttributes["host.name"] || hostName,
138 ...nodeProcessRuntimeAttributes(),
139 },
140});
141​
142export const layer = (config: ServerConfig["Service"]) => Layer.succeed(ServerConfig, make(config));
143​
144export const deriveServerPaths = Effect.fn(function* (
145 baseDir: ServerConfig["Service"]["baseDir"],
146 devUrl: ServerConfig["Service"]["devUrl"],
147 options: DeriveServerPathsOptions = {},
148): Effect.fn.Return<ServerDerivedPaths, never, Path.Path> {
149 const { join } = yield* Path.Path;
150 const stateDir = join(
151 baseDir,
152 devUrl !== undefined && !options.baseDirIsExplicit ? "dev" : "userdata",
153 );
154 const dbPath = join(stateDir, "statev2.sqlite");
155 const attachmentsDir = join(stateDir, "attachments");
156 const logsDir = join(stateDir, "logs");
157 const providerLogsDir = join(logsDir, "provider");
158 const providerStatusCacheDir = join(baseDir, "caches");
159 return {
160 stateDir,
161 dbPath,
162 keybindingsConfigPath: join(stateDir, "keybindings.json"),
163 settingsPath: join(stateDir, "settings.json"),
164 environmentThemesDir: join(stateDir, "themes"),
165 providerStatusCacheDir,
166 worktreesDir: join(baseDir, "worktrees"),
167 workflowsDir: join(baseDir, "workflows"),
168 worktreeCheckoutCacheDir: join(providerStatusCacheDir, "worktree-checkouts"),
169 attachmentsDir,
170 browserArtifactsDir: join(stateDir, "browser-artifacts"),
171 logsDir,
172 serverTracePath: join(logsDir, "server.trace.ndjson"),
173 providerLogsDir,
174 providerEventLogPath: join(providerLogsDir, "events.log"),
175 terminalLogsDir: join(logsDir, "terminals"),
176 anonymousIdPath: join(stateDir, "anonymous-id"),
177 environmentIdPath: join(stateDir, "environment-id"),
178 serverRuntimeStatePath: join(stateDir, "server-runtime.json"),
179 secretsDir: join(stateDir, "secrets"),
180 };
181});
182​
183export const ensureServerDirectories = Effect.fn(function* (derivedPaths: ServerDerivedPaths) {
184 const fs = yield* FileSystem.FileSystem;
185 const path = yield* Path.Path;
186​
187 yield* fs.makeDirectory(derivedPaths.stateDir, { recursive: true });
188 // Only before the database exists: a No_COW WAL beside an existing copy-on-write database
189 // could not be reflinked into one backup folder with it. When unsure, leave the folder as is.
190 if (!(yield* fs.exists(derivedPaths.dbPath).pipe(Effect.orElseSucceed(() => true)))) {
191 yield* Effect.promise(() => markNoCopyOnWrite(derivedPaths.stateDir));
192 }
193 yield* Effect.all(
194 [
195 fs.makeDirectory(derivedPaths.logsDir, { recursive: true }),
196 fs.makeDirectory(derivedPaths.providerLogsDir, { recursive: true }),
197 fs.makeDirectory(derivedPaths.terminalLogsDir, { recursive: true }),
198 fs.makeDirectory(derivedPaths.attachmentsDir, { recursive: true }),
199 fs.makeDirectory(derivedPaths.worktreesDir, { recursive: true }),
200 fs.makeDirectory(path.dirname(derivedPaths.keybindingsConfigPath), { recursive: true }),
201 fs.makeDirectory(path.dirname(derivedPaths.settingsPath), { recursive: true }),
202 fs.makeDirectory(derivedPaths.providerStatusCacheDir, { recursive: true }),
203 fs.makeDirectory(path.dirname(derivedPaths.anonymousIdPath), { recursive: true }),
204 fs.makeDirectory(path.dirname(derivedPaths.serverRuntimeStatePath), { recursive: true }),
205 ],
206 { concurrency: "unbounded" },
207 );
208 // Logs, traces and the database are written with the process umask; keep them owner-only.
209 yield* fs
210 .chmod(derivedPaths.stateDir, 0o700)
211 .pipe(
212 Effect.catch((cause) =>
213 Effect.logWarning("Could not restrict state directory permissions.", { cause }),
214 ),
215 );
216​
217 const swept = sweepStalePendingAttachments({
218 attachmentsDir: derivedPaths.attachmentsDir,
219 nowMs: yield* Clock.currentTimeMillis,
220 });
221 if (swept.deleted > 0) {
222 yield* Effect.logInfo("Removed expired attachment uploads.", { deleted: swept.deleted });
223 }
224});
225​
226const makeTest = Effect.fn("ServerConfig.makeTest")(function* (
227 cwd: string,
228 baseDirOrPrefix: string | { readonly prefix: string },
229) {
230 const devUrl = undefined;
231 const fs = yield* FileSystem.FileSystem;
232 const baseDir =
233 typeof baseDirOrPrefix === "string"
234 ? baseDirOrPrefix
235 : // macOS temp dirs live under the /var -> /private/var symlink; storage cleanup's
236 // symlink guards compare resolved paths, so generated test dirs must be real paths.
237 yield* fs.realPath(yield* fs.makeTempDirectoryScoped({ prefix: baseDirOrPrefix.prefix }));
238 const derivedPaths = yield* deriveServerPaths(baseDir, devUrl);
239 yield* ensureServerDirectories(derivedPaths);
240​
241 return ServerConfig.of({
242 logLevel: "Error",
243 traceMinLevel: "Info",
244 traceTimingEnabled: true,
245 traceBatchWindowMs: 200,
246 traceMaxBytes: 10 * 1024 * 1024,
247 traceMaxFiles: 10,
248 otlpTracesUrl: undefined,
249 otlpMetricsUrl: undefined,
250 otlpLogsUrl: undefined,
251 otlpTracesExport: DEFAULT_SIGNAL_EXPORT,
252 otlpMetricsExport: DEFAULT_SIGNAL_EXPORT,
253 otlpLogsExport: DEFAULT_SIGNAL_EXPORT,
254 otelEnvironment: OtelEnvironment.none,
255 cwd,
256 baseDir,
257 ...derivedPaths,
258 mode: "web",
259 autoBootstrapProjectFromCwd: false,
260 logWebSocketEvents: false,
261 tailscaleServeEnabled: false,
262 tailscaleServePort: 443,
263 port: 0,
264 host: undefined,
265 desktopBootstrapToken: undefined,
266 desktopTelemetryFd: undefined,
267 desktopTelemetryControlFd: undefined,
268 desktopBrowserFd: undefined,
269 desktopBrowserControlFd: undefined,
270 resourceMonitorPath: undefined,
271 staticDir: undefined,
272 devUrl,
273 devAllowedOrigins: [],
274 noBrowser: false,
275 startupPresentation: "browser",
276 });
277});
278​
279export const layerTest = (cwd: string, baseDirOrPrefix: string | { readonly prefix: string }) =>
280 Layer.effect(ServerConfig, makeTest(cwd, baseDirOrPrefix));
281​
282export const resolveStaticDir = Effect.fn(function* () {
283 const { join, resolve } = yield* Path.Path;
284 const { exists } = yield* FileSystem.FileSystem;
285 const bundledClient = resolve(join(import.meta.dirname, "client"));
286 const bundledStat = yield* exists(join(bundledClient, "index.html")).pipe(
287 Effect.orElseSucceed(() => false),
288 );
289 if (bundledStat) {
290 return bundledClient;
291 }
292​
293 const monorepoClient = resolve(join(import.meta.dirname, "../../web/dist"));
294 const monorepoStat = yield* exists(join(monorepoClient, "index.html")).pipe(
295 Effect.orElseSucceed(() => false),
296 );
297 if (monorepoStat) {
298 return monorepoClient;
299 }
300 return undefined;
301});