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

config.ts

242 lines8.6 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 * as Schema from "effect/Schema";
17​
18import { sweepStalePendingAttachments } from "./attachmentStore.ts";
19​
20export const DEFAULT_PORT = 3773;
21​
22export const RuntimeMode = Schema.Literals(["web", "desktop"]);
23export type RuntimeMode = typeof RuntimeMode.Type;
24​
25export const StartupPresentation = Schema.Literals(["browser", "headless"]);
26export type StartupPresentation = typeof StartupPresentation.Type;
27​
28/**
29 * ServerDerivedPaths - Derived paths from the base directory.
30 */
31export interface ServerDerivedPaths {
32 readonly stateDir: string;
33 readonly dbPath: string;
34 readonly keybindingsConfigPath: string;
35 readonly settingsPath: string;
36 /** Palettes this machine publishes for clients to follow, one file per theme. */
37 readonly environmentThemesDir: string;
38 readonly providerStatusCacheDir: string;
39 readonly worktreesDir: string;
40 readonly attachmentsDir: string;
41 /** Screenshots the agent asks the collaborative browser to keep for the user. */
42 readonly browserArtifactsDir: string;
43 readonly logsDir: string;
44 readonly serverLogPath: string;
45 readonly serverTracePath: string;
46 readonly providerLogsDir: string;
47 readonly providerEventLogPath: string;
48 readonly terminalLogsDir: string;
49 readonly anonymousIdPath: string;
50 readonly environmentIdPath: string;
51 readonly serverRuntimeStatePath: string;
52 readonly secretsDir: string;
54​
55export interface DeriveServerPathsOptions {
56 readonly baseDirIsExplicit?: boolean;
58​
59/**
60 * ServerConfig - Service tag for server runtime configuration.
61 */
62export class ServerConfig extends Context.Service<
63 ServerConfig,
64 ServerDerivedPaths & {
65 readonly logLevel: LogLevel.LogLevel;
66 readonly traceMinLevel: LogLevel.LogLevel;
67 readonly traceTimingEnabled: boolean;
68 readonly traceBatchWindowMs: number;
69 readonly traceMaxBytes: number;
70 readonly traceMaxFiles: number;
71 readonly otlpTracesUrl: string | undefined;
72 readonly otlpMetricsUrl: string | undefined;
73 readonly otlpExportIntervalMs: number;
74 readonly otlpServiceName: string;
75 readonly mode: RuntimeMode;
76 readonly port: number;
77 readonly host: string | undefined;
78 readonly cwd: string;
79 readonly baseDir: string;
80 readonly staticDir: string | undefined;
81 readonly devUrl: URL | undefined;
82 readonly devAllowedOrigins: ReadonlyArray<string>;
83 readonly noBrowser: boolean;
84 readonly startupPresentation: StartupPresentation;
85 readonly desktopBootstrapToken: string | undefined;
86 readonly desktopTelemetryFd?: number | undefined;
87 readonly desktopTelemetryControlFd?: number | undefined;
88 readonly resourceMonitorPath?: string | undefined;
89 readonly autoBootstrapProjectFromCwd: boolean;
90 readonly logWebSocketEvents: boolean;
91 readonly tailscaleServeEnabled: boolean;
92 readonly tailscaleServePort: number;
93 }
94>()("t3/config/ServerConfig") {
95 /** @deprecated Import and use `layerTest` from this module. */
96 static readonly layerTest = (
97 cwd: string,
98 baseDirOrPrefix: string | { readonly prefix: string },
99 ) => layerTest(cwd, baseDirOrPrefix);
101​
102export const make = (config: ServerConfig["Service"]) => ServerConfig.of(config);
103​
104export const layer = (config: ServerConfig["Service"]) => Layer.succeed(ServerConfig, make(config));
105​
106export const deriveServerPaths = Effect.fn(function* (
107 baseDir: ServerConfig["Service"]["baseDir"],
108 devUrl: ServerConfig["Service"]["devUrl"],
109 options: DeriveServerPathsOptions = {},
110): Effect.fn.Return<ServerDerivedPaths, never, Path.Path> {
111 const { join } = yield* Path.Path;
112 const stateDir = join(
113 baseDir,
114 devUrl !== undefined && !options.baseDirIsExplicit ? "dev" : "userdata",
115 );
116 const dbPath = join(stateDir, "state.sqlite");
117 const attachmentsDir = join(stateDir, "attachments");
118 const logsDir = join(stateDir, "logs");
119 const providerLogsDir = join(logsDir, "provider");
120 const providerStatusCacheDir = join(baseDir, "caches");
121 return {
122 stateDir,
123 dbPath,
124 keybindingsConfigPath: join(stateDir, "keybindings.json"),
125 settingsPath: join(stateDir, "settings.json"),
126 environmentThemesDir: join(stateDir, "themes"),
127 providerStatusCacheDir,
128 worktreesDir: join(baseDir, "worktrees"),
129 attachmentsDir,
130 browserArtifactsDir: join(stateDir, "browser-artifacts"),
131 logsDir,
132 serverLogPath: join(logsDir, "server.log"),
133 serverTracePath: join(logsDir, "server.trace.ndjson"),
134 providerLogsDir,
135 providerEventLogPath: join(providerLogsDir, "events.log"),
136 terminalLogsDir: join(logsDir, "terminals"),
137 anonymousIdPath: join(stateDir, "anonymous-id"),
138 environmentIdPath: join(stateDir, "environment-id"),
139 serverRuntimeStatePath: join(stateDir, "server-runtime.json"),
140 secretsDir: join(stateDir, "secrets"),
141 };
142});
143​
144export const ensureServerDirectories = Effect.fn(function* (derivedPaths: ServerDerivedPaths) {
145 const fs = yield* FileSystem.FileSystem;
146 const path = yield* Path.Path;
147​
148 yield* Effect.all(
149 [
150 fs.makeDirectory(derivedPaths.stateDir, { recursive: true }),
151 fs.makeDirectory(derivedPaths.logsDir, { recursive: true }),
152 fs.makeDirectory(derivedPaths.providerLogsDir, { recursive: true }),
153 fs.makeDirectory(derivedPaths.terminalLogsDir, { recursive: true }),
154 fs.makeDirectory(derivedPaths.attachmentsDir, { recursive: true }),
155 fs.makeDirectory(derivedPaths.worktreesDir, { recursive: true }),
156 fs.makeDirectory(path.dirname(derivedPaths.keybindingsConfigPath), { recursive: true }),
157 fs.makeDirectory(path.dirname(derivedPaths.settingsPath), { recursive: true }),
158 fs.makeDirectory(derivedPaths.providerStatusCacheDir, { recursive: true }),
159 fs.makeDirectory(path.dirname(derivedPaths.anonymousIdPath), { recursive: true }),
160 fs.makeDirectory(path.dirname(derivedPaths.serverRuntimeStatePath), { recursive: true }),
161 ],
162 { concurrency: "unbounded" },
163 );
164​
165 const swept = sweepStalePendingAttachments({
166 attachmentsDir: derivedPaths.attachmentsDir,
167 nowMs: yield* Clock.currentTimeMillis,
168 });
169 if (swept.deleted > 0) {
170 yield* Effect.logInfo("Removed expired attachment uploads.", { deleted: swept.deleted });
171 }
172});
173​
174const makeTest = Effect.fn("ServerConfig.makeTest")(function* (
175 cwd: string,
176 baseDirOrPrefix: string | { readonly prefix: string },
177) {
178 const devUrl = undefined;
179 const fs = yield* FileSystem.FileSystem;
180 const baseDir =
181 typeof baseDirOrPrefix === "string"
182 ? baseDirOrPrefix
183 : yield* fs.makeTempDirectoryScoped({ prefix: baseDirOrPrefix.prefix });
184 const derivedPaths = yield* deriveServerPaths(baseDir, devUrl);
185 yield* ensureServerDirectories(derivedPaths);
186​
187 return ServerConfig.of({
188 logLevel: "Error",
189 traceMinLevel: "Info",
190 traceTimingEnabled: true,
191 traceBatchWindowMs: 200,
192 traceMaxBytes: 10 * 1024 * 1024,
193 traceMaxFiles: 10,
194 otlpTracesUrl: undefined,
195 otlpMetricsUrl: undefined,
196 otlpExportIntervalMs: 10_000,
197 otlpServiceName: "t3-server",
198 cwd,
199 baseDir,
200 ...derivedPaths,
201 mode: "web",
202 autoBootstrapProjectFromCwd: false,
203 logWebSocketEvents: false,
204 tailscaleServeEnabled: false,
205 tailscaleServePort: 443,
206 port: 0,
207 host: undefined,
208 desktopBootstrapToken: undefined,
209 desktopTelemetryFd: undefined,
210 desktopTelemetryControlFd: undefined,
211 resourceMonitorPath: undefined,
212 staticDir: undefined,
213 devUrl,
214 devAllowedOrigins: [],
215 noBrowser: false,
216 startupPresentation: "browser",
217 });
218});
219​
220export const layerTest = (cwd: string, baseDirOrPrefix: string | { readonly prefix: string }) =>
221 Layer.effect(ServerConfig, makeTest(cwd, baseDirOrPrefix));
222​
223export const resolveStaticDir = Effect.fn(function* () {
224 const { join, resolve } = yield* Path.Path;
225 const { exists } = yield* FileSystem.FileSystem;
226 const bundledClient = resolve(join(import.meta.dirname, "client"));
227 const bundledStat = yield* exists(join(bundledClient, "index.html")).pipe(
228 Effect.orElseSucceed(() => false),
229 );
230 if (bundledStat) {
231 return bundledClient;
232 }
233​
234 const monorepoClient = resolve(join(import.meta.dirname, "../../web/dist"));
235 const monorepoStat = yield* exists(join(monorepoClient, "index.html")).pipe(
236 Effect.orElseSucceed(() => false),
237 );
238 if (monorepoStat) {
239 return monorepoClient;
240 }
241 return undefined;
242});