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