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