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