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

config.ts

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