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

config.ts

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