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

config.ts

219 lines7.6 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 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;
47​
48export interface DeriveServerPathsOptions {
49 readonly baseDirIsExplicit?: boolean;
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 autoBootstrapProjectFromCwd: boolean;
80 readonly logWebSocketEvents: boolean;
81 readonly tailscaleServeEnabled: boolean;
82 readonly tailscaleServePort: number;
83 }
84>()("t3/config/ServerConfig") {
85 /** @deprecated Import and use `layerTest` from this module. */
86 static readonly layerTest = (
87 cwd: string,
88 baseDirOrPrefix: string | { readonly prefix: string },
89 ) => layerTest(cwd, baseDirOrPrefix);
91​
92export const make = (config: ServerConfig["Service"]) => ServerConfig.of(config);
93​
94export const layer = (config: ServerConfig["Service"]) => Layer.succeed(ServerConfig, make(config));
95​
96export const deriveServerPaths = Effect.fn(function* (
97 baseDir: ServerConfig["Service"]["baseDir"],
98 devUrl: ServerConfig["Service"]["devUrl"],
99 options: DeriveServerPathsOptions = {},
100): Effect.fn.Return<ServerDerivedPaths, never, Path.Path> {
101 const { join } = yield* Path.Path;
102 const stateDir = join(
103 baseDir,
104 devUrl !== undefined && !options.baseDirIsExplicit ? "dev" : "userdata",
105 );
106 const dbPath = join(stateDir, "state.sqlite");
107 const attachmentsDir = join(stateDir, "attachments");
108 const logsDir = join(stateDir, "logs");
109 const providerLogsDir = join(logsDir, "provider");
110 const providerStatusCacheDir = join(baseDir, "caches");
111 return {
112 stateDir,
113 dbPath,
114 keybindingsConfigPath: join(stateDir, "keybindings.json"),
115 settingsPath: join(stateDir, "settings.json"),
116 providerStatusCacheDir,
117 worktreesDir: join(baseDir, "worktrees"),
118 attachmentsDir,
119 logsDir,
120 serverLogPath: join(logsDir, "server.log"),
121 serverTracePath: join(logsDir, "server.trace.ndjson"),
122 providerLogsDir,
123 providerEventLogPath: join(providerLogsDir, "events.log"),
124 terminalLogsDir: join(logsDir, "terminals"),
125 anonymousIdPath: join(stateDir, "anonymous-id"),
126 environmentIdPath: join(stateDir, "environment-id"),
127 serverRuntimeStatePath: join(stateDir, "server-runtime.json"),
128 secretsDir: join(stateDir, "secrets"),
129 };
130});
131​
132export const ensureServerDirectories = Effect.fn(function* (derivedPaths: ServerDerivedPaths) {
133 const fs = yield* FileSystem.FileSystem;
134 const path = yield* Path.Path;
135​
136 yield* Effect.all(
137 [
138 fs.makeDirectory(derivedPaths.stateDir, { recursive: true }),
139 fs.makeDirectory(derivedPaths.logsDir, { recursive: true }),
140 fs.makeDirectory(derivedPaths.providerLogsDir, { recursive: true }),
141 fs.makeDirectory(derivedPaths.terminalLogsDir, { recursive: true }),
142 fs.makeDirectory(derivedPaths.attachmentsDir, { recursive: true }),
143 fs.makeDirectory(derivedPaths.worktreesDir, { recursive: true }),
144 fs.makeDirectory(path.dirname(derivedPaths.keybindingsConfigPath), { recursive: true }),
145 fs.makeDirectory(path.dirname(derivedPaths.settingsPath), { recursive: true }),
146 fs.makeDirectory(derivedPaths.providerStatusCacheDir, { recursive: true }),
147 fs.makeDirectory(path.dirname(derivedPaths.anonymousIdPath), { recursive: true }),
148 fs.makeDirectory(path.dirname(derivedPaths.serverRuntimeStatePath), { recursive: true }),
149 ],
150 { concurrency: "unbounded" },
151 );
152});
153​
154const makeTest = Effect.fn("ServerConfig.makeTest")(function* (
155 cwd: string,
156 baseDirOrPrefix: string | { readonly prefix: string },
157) {
158 const devUrl = undefined;
159 const fs = yield* FileSystem.FileSystem;
160 const baseDir =
161 typeof baseDirOrPrefix === "string"
162 ? baseDirOrPrefix
163 : yield* fs.makeTempDirectoryScoped({ prefix: baseDirOrPrefix.prefix });
164 const derivedPaths = yield* deriveServerPaths(baseDir, devUrl);
165 yield* ensureServerDirectories(derivedPaths);
166​
167 return ServerConfig.of({
168 logLevel: "Error",
169 traceMinLevel: "Info",
170 traceTimingEnabled: true,
171 traceBatchWindowMs: 200,
172 traceMaxBytes: 10 * 1024 * 1024,
173 traceMaxFiles: 10,
174 otlpTracesUrl: undefined,
175 otlpMetricsUrl: undefined,
176 otlpExportIntervalMs: 10_000,
177 otlpServiceName: "t3-server",
178 cwd,
179 baseDir,
180 ...derivedPaths,
181 mode: "web",
182 autoBootstrapProjectFromCwd: false,
183 logWebSocketEvents: false,
184 tailscaleServeEnabled: false,
185 tailscaleServePort: 443,
186 port: 0,
187 host: undefined,
188 desktopBootstrapToken: undefined,
189 staticDir: undefined,
190 devUrl,
191 devAllowedOrigins: [],
192 noBrowser: false,
193 startupPresentation: "browser",
194 });
195});
196​
197export const layerTest = (cwd: string, baseDirOrPrefix: string | { readonly prefix: string }) =>
198 Layer.effect(ServerConfig, makeTest(cwd, baseDirOrPrefix));
199​
200export const resolveStaticDir = Effect.fn(function* () {
201 const { join, resolve } = yield* Path.Path;
202 const { exists } = yield* FileSystem.FileSystem;
203 const bundledClient = resolve(join(import.meta.dirname, "client"));
204 const bundledStat = yield* exists(join(bundledClient, "index.html")).pipe(
205 Effect.orElseSucceed(() => false),
206 );
207 if (bundledStat) {
208 return bundledClient;
209 }
210​
211 const monorepoClient = resolve(join(import.meta.dirname, "../../web/dist"));
212 const monorepoStat = yield* exists(join(monorepoClient, "index.html")).pipe(
213 Effect.orElseSucceed(() => false),
214 );
215 if (monorepoStat) {
216 return monorepoClient;
217 }
218 return undefined;
219});