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