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

config.ts

274 lines10.0 KB

1/**
2 * ServerConfig - Runtime configuration services.
3 *
4 * Defines process-level server configuration and networking helpers used by
5 * startup and runtime layers.
6 *
7 * @module ServerConfig
8 */
9import * as Context from "effect/Context";
10import * as Clock from "effect/Clock";
11import * as Effect from "effect/Effect";
12import * as FileSystem from "effect/FileSystem";
13import * as Layer from "effect/Layer";
14import * as LogLevel from "effect/LogLevel";
15import * as Path from "effect/Path";
16import type * as Redacted from "effect/Redacted";
17import * as Schema from "effect/Schema";
18​
19import { sweepStalePendingAttachments } from "./attachmentStore.ts";
20import { DEFAULT_SIGNAL_EXPORT, type SignalExport } from "@t3tools/shared/observability";
21import * as OtelEnvironment from "@t3tools/shared/otelEnvironment";
22​
23export const DEFAULT_PORT = 3773;
24​
25export const RuntimeMode = Schema.Literals(["web", "desktop"]);
26export type RuntimeMode = typeof RuntimeMode.Type;
27​
28export const StartupPresentation = Schema.Literals(["browser", "headless"]);
29export type StartupPresentation = typeof StartupPresentation.Type;
30​
31/**
32 * ServerDerivedPaths - Derived paths from the base directory.
33 */
34export interface ServerDerivedPaths {
35 readonly stateDir: string;
36 readonly dbPath: string;
37 readonly keybindingsConfigPath: string;
38 readonly settingsPath: string;
39 /** Palettes this machine publishes for clients to follow, one file per theme. */
40 readonly environmentThemesDir: string;
41 readonly providerStatusCacheDir: string;
42 readonly worktreesDir: string;
43 readonly attachmentsDir: string;
44 /** Screenshots the agent asks the collaborative browser to keep for the user. */
45 readonly browserArtifactsDir: string;
46 readonly logsDir: string;
47 readonly serverTracePath: string;
48 readonly providerLogsDir: string;
49 readonly providerEventLogPath: string;
50 readonly terminalLogsDir: string;
51 readonly anonymousIdPath: string;
52 readonly environmentIdPath: string;
53 readonly serverRuntimeStatePath: string;
54 readonly secretsDir: string;
56​
57export interface DeriveServerPathsOptions {
58 readonly baseDirIsExplicit?: boolean;
60​
61/**
62 * ServerConfig - Service tag for server runtime configuration.
63 */
64export class ServerConfig extends Context.Service<
65 ServerConfig,
66 ServerDerivedPaths & {
67 readonly logLevel: LogLevel.LogLevel;
68 readonly traceMinLevel: LogLevel.LogLevel;
69 readonly traceTimingEnabled: boolean;
70 readonly traceBatchWindowMs: number;
71 readonly traceMaxBytes: number;
72 readonly traceMaxFiles: number;
73 readonly otlpTracesUrl: string | undefined;
74 readonly otlpMetricsUrl: string | undefined;
75 readonly otlpLogsUrl: string | undefined;
76 /**
77 * How each signal is exported. Read instead of a process-wide setting so
78 * the wire format, credential, and schedule travel with the endpoint they
79 * were configured beside.
80 */
81 readonly otlpTracesExport: SignalExport;
82 readonly otlpMetricsExport: SignalExport;
83 readonly otlpLogsExport: SignalExport;
84 readonly otelEnvironment: OtelEnvironment.OtelEnvironment;
85 readonly mode: RuntimeMode;
86 readonly port: number;
87 readonly host: string | undefined;
88 readonly cwd: string;
89 readonly baseDir: string;
90 readonly staticDir: string | undefined;
91 readonly devUrl: URL | undefined;
92 readonly devAuthToken?: Redacted.Redacted<string> | undefined;
93 readonly devAllowedOrigins: ReadonlyArray<string>;
94 readonly noBrowser: boolean;
95 readonly startupPresentation: StartupPresentation;
96 readonly desktopBootstrapToken: string | undefined;
97 readonly desktopBootstrapSecret?: string | undefined;
98 readonly shellEnvironmentPrepared?: boolean | undefined;
99 readonly desktopTelemetryFd?: number | undefined;
100 readonly desktopTelemetryControlFd?: number | undefined;
101 readonly desktopBrowserFd?: number | undefined;
102 readonly desktopBrowserControlFd?: number | undefined;
103 readonly resourceMonitorPath?: string | undefined;
104 readonly autoBootstrapProjectFromCwd: boolean;
105 readonly logWebSocketEvents: boolean;
106 readonly tailscaleServeEnabled: boolean;
107 readonly tailscaleServePort: number;
108 }
109>()("t3/config/ServerConfig") {
110 /** @deprecated Import and use `layerTest` from this module. */
111 static readonly layerTest = (
112 cwd: string,
113 baseDirOrPrefix: string | { readonly prefix: string },
114 ) => layerTest(cwd, baseDirOrPrefix);
116​
117export const make = (config: ServerConfig["Service"]) => ServerConfig.of(config);
118​
119/**
120 * Resource attributes shared by every OTLP exporter, so traces, metrics, and
121 * logs report the same service identity to the collector.
122 */
123export const otlpResource = (config: ServerConfig["Service"]) => ({
124 serviceName: "t3code-server",
125 attributes: {
126 "service.namespace": "t3code",
127 "service.runtime": "t3-server",
128 "service.mode": config.mode,
129 },
130});
131​
132export const layer = (config: ServerConfig["Service"]) => Layer.succeed(ServerConfig, make(config));
133​
134export const deriveServerPaths = Effect.fn(function* (
135 baseDir: ServerConfig["Service"]["baseDir"],
136 devUrl: ServerConfig["Service"]["devUrl"],
137 options: DeriveServerPathsOptions = {},
138): Effect.fn.Return<ServerDerivedPaths, never, Path.Path> {
139 const { join } = yield* Path.Path;
140 const stateDir = join(
141 baseDir,
142 devUrl !== undefined && !options.baseDirIsExplicit ? "dev" : "userdata",
143 );
144 const dbPath = join(stateDir, "statev2.sqlite");
145 const attachmentsDir = join(stateDir, "attachments");
146 const logsDir = join(stateDir, "logs");
147 const providerLogsDir = join(logsDir, "provider");
148 const providerStatusCacheDir = join(baseDir, "caches");
149 return {
150 stateDir,
151 dbPath,
152 keybindingsConfigPath: join(stateDir, "keybindings.json"),
153 settingsPath: join(stateDir, "settings.json"),
154 environmentThemesDir: join(stateDir, "themes"),
155 providerStatusCacheDir,
156 worktreesDir: join(baseDir, "worktrees"),
157 attachmentsDir,
158 browserArtifactsDir: join(stateDir, "browser-artifacts"),
159 logsDir,
160 serverTracePath: join(logsDir, "server.trace.ndjson"),
161 providerLogsDir,
162 providerEventLogPath: join(providerLogsDir, "events.log"),
163 terminalLogsDir: join(logsDir, "terminals"),
164 anonymousIdPath: join(stateDir, "anonymous-id"),
165 environmentIdPath: join(stateDir, "environment-id"),
166 serverRuntimeStatePath: join(stateDir, "server-runtime.json"),
167 secretsDir: join(stateDir, "secrets"),
168 };
169});
170​
171export const ensureServerDirectories = Effect.fn(function* (derivedPaths: ServerDerivedPaths) {
172 const fs = yield* FileSystem.FileSystem;
173 const path = yield* Path.Path;
174​
175 yield* Effect.all(
176 [
177 fs.makeDirectory(derivedPaths.stateDir, { recursive: true }),
178 fs.makeDirectory(derivedPaths.logsDir, { recursive: true }),
179 fs.makeDirectory(derivedPaths.providerLogsDir, { recursive: true }),
180 fs.makeDirectory(derivedPaths.terminalLogsDir, { recursive: true }),
181 fs.makeDirectory(derivedPaths.attachmentsDir, { recursive: true }),
182 fs.makeDirectory(derivedPaths.worktreesDir, { recursive: true }),
183 fs.makeDirectory(path.dirname(derivedPaths.keybindingsConfigPath), { recursive: true }),
184 fs.makeDirectory(path.dirname(derivedPaths.settingsPath), { recursive: true }),
185 fs.makeDirectory(derivedPaths.providerStatusCacheDir, { recursive: true }),
186 fs.makeDirectory(path.dirname(derivedPaths.anonymousIdPath), { recursive: true }),
187 fs.makeDirectory(path.dirname(derivedPaths.serverRuntimeStatePath), { recursive: true }),
188 ],
189 { concurrency: "unbounded" },
190 );
191​
192 const swept = sweepStalePendingAttachments({
193 attachmentsDir: derivedPaths.attachmentsDir,
194 nowMs: yield* Clock.currentTimeMillis,
195 });
196 if (swept.deleted > 0) {
197 yield* Effect.logInfo("Removed expired attachment uploads.", { deleted: swept.deleted });
198 }
199});
200​
201const makeTest = Effect.fn("ServerConfig.makeTest")(function* (
202 cwd: string,
203 baseDirOrPrefix: string | { readonly prefix: string },
204) {
205 const devUrl = undefined;
206 const fs = yield* FileSystem.FileSystem;
207 const baseDir =
208 typeof baseDirOrPrefix === "string"
209 ? baseDirOrPrefix
210 : yield* fs.makeTempDirectoryScoped({ prefix: baseDirOrPrefix.prefix });
211 const derivedPaths = yield* deriveServerPaths(baseDir, devUrl);
212 yield* ensureServerDirectories(derivedPaths);
213​
214 return ServerConfig.of({
215 logLevel: "Error",
216 traceMinLevel: "Info",
217 traceTimingEnabled: true,
218 traceBatchWindowMs: 200,
219 traceMaxBytes: 10 * 1024 * 1024,
220 traceMaxFiles: 10,
221 otlpTracesUrl: undefined,
222 otlpMetricsUrl: undefined,
223 otlpLogsUrl: undefined,
224 otlpTracesExport: DEFAULT_SIGNAL_EXPORT,
225 otlpMetricsExport: DEFAULT_SIGNAL_EXPORT,
226 otlpLogsExport: DEFAULT_SIGNAL_EXPORT,
227 otelEnvironment: OtelEnvironment.none,
228 cwd,
229 baseDir,
230 ...derivedPaths,
231 mode: "web",
232 autoBootstrapProjectFromCwd: false,
233 logWebSocketEvents: false,
234 tailscaleServeEnabled: false,
235 tailscaleServePort: 443,
236 port: 0,
237 host: undefined,
238 desktopBootstrapToken: undefined,
239 desktopTelemetryFd: undefined,
240 desktopTelemetryControlFd: undefined,
241 desktopBrowserFd: undefined,
242 desktopBrowserControlFd: undefined,
243 resourceMonitorPath: undefined,
244 staticDir: undefined,
245 devUrl,
246 devAllowedOrigins: [],
247 noBrowser: false,
248 startupPresentation: "browser",
249 });
250});
251​
252export const layerTest = (cwd: string, baseDirOrPrefix: string | { readonly prefix: string }) =>
253 Layer.effect(ServerConfig, makeTest(cwd, baseDirOrPrefix));
254​
255export const resolveStaticDir = Effect.fn(function* () {
256 const { join, resolve } = yield* Path.Path;
257 const { exists } = yield* FileSystem.FileSystem;
258 const bundledClient = resolve(join(import.meta.dirname, "client"));
259 const bundledStat = yield* exists(join(bundledClient, "index.html")).pipe(
260 Effect.orElseSucceed(() => false),
261 );
262 if (bundledStat) {
263 return bundledClient;
264 }
265​
266 const monorepoClient = resolve(join(import.meta.dirname, "../../web/dist"));
267 const monorepoStat = yield* exists(join(monorepoClient, "index.html")).pipe(
268 Effect.orElseSucceed(() => false),
269 );
270 if (monorepoStat) {
271 return monorepoClient;
272 }
273 return undefined;
274});