Open History to see the last commit
1import * as Context from "effect/Context";
2import * as Clock from "effect/Clock";
3import * as Effect from "effect/Effect";
4import * as FileSystem from "effect/FileSystem";
5import * as Layer from "effect/Layer";
6import * as LogLevel from "effect/LogLevel";
7import * as Path from "effect/Path";
8import type * as Redacted from "effect/Redacted";
9import * as Schema from "effect/Schema";
10
11import { sweepStalePendingAttachments } from "./attachmentStore.ts";
12import { DEFAULT_SIGNAL_EXPORT, type SignalExport } from "@t3tools/shared/observability";
13import * as OtelEnvironment from "@t3tools/shared/otelEnvironment";
14import packageJson from "../package.json" with { type: "json" };
15
16export const DEFAULT_PORT = 3773;
17
18export const RuntimeMode = Schema.Literals(["web", "desktop"]);
19export type RuntimeMode = typeof RuntimeMode.Type;
20
21export const StartupPresentation = Schema.Literals(["browser", "headless"]);
22export type StartupPresentation = typeof StartupPresentation.Type;
23
24export interface ServerDerivedPaths {
25 readonly stateDir: string;
26 readonly dbPath: string;
27 readonly keybindingsConfigPath: string;
28 readonly settingsPath: string;
29 readonly environmentThemesDir: string;
30 readonly providerStatusCacheDir: string;
31 readonly worktreesDir: string;
32 readonly attachmentsDir: string;
33 readonly browserArtifactsDir: string;
34 readonly logsDir: string;
35 readonly serverTracePath: string;
36 readonly providerLogsDir: string;
37 readonly providerEventLogPath: string;
38 readonly terminalLogsDir: string;
39 readonly anonymousIdPath: string;
40 readonly environmentIdPath: string;
41 readonly serverRuntimeStatePath: string;
42 readonly secretsDir: string;
43}
44
45export interface DeriveServerPathsOptions {
46 readonly baseDirIsExplicit?: boolean;
47}
48
49export class ServerConfig extends Context.Service<
50 ServerConfig,
51 ServerDerivedPaths & {
52 readonly logLevel: LogLevel.LogLevel;
53 readonly traceMinLevel: LogLevel.LogLevel;
54 readonly traceTimingEnabled: boolean;
55 readonly traceBatchWindowMs: number;
56 readonly traceMaxBytes: number;
57 readonly traceMaxFiles: number;
58 readonly otlpTracesUrl: string | undefined;
59 readonly otlpMetricsUrl: string | undefined;
60 readonly otlpLogsUrl: string | undefined;
61 readonly otlpTracesExport: SignalExport;
62 readonly otlpMetricsExport: SignalExport;
63 readonly otlpLogsExport: SignalExport;
64 readonly otelEnvironment: OtelEnvironment.OtelEnvironment;
65 readonly mode: RuntimeMode;
66 readonly port: number;
67 readonly host: string | undefined;
68 readonly cwd: string;
69 readonly baseDir: string;
70 readonly staticDir: string | undefined;
71 readonly devUrl: URL | undefined;
72 readonly devAuthToken?: Redacted.Redacted<string> | undefined;
73 readonly devAllowedOrigins: ReadonlyArray<string>;
74 readonly noBrowser: boolean;
75 readonly startupPresentation: StartupPresentation;
76 readonly desktopBootstrapToken: string | undefined;
77 readonly desktopBootstrapSecret?: string | undefined;
78 readonly shellEnvironmentPrepared?: boolean | undefined;
79 readonly desktopTelemetryFd?: number | undefined;
80 readonly desktopTelemetryControlFd?: number | undefined;
81 readonly desktopBrowserFd?: number | undefined;
82 readonly desktopBrowserControlFd?: number | undefined;
83 readonly resourceMonitorPath?: string | undefined;
84 readonly autoBootstrapProjectFromCwd: boolean;
85 readonly logWebSocketEvents: boolean;
86 readonly tailscaleServeEnabled: boolean;
87 readonly tailscaleServePort: number;
88 }
89>()("t3/config/ServerConfig") {
90 static readonly layerTest = (
91 cwd: string,
92 baseDirOrPrefix: string | { readonly prefix: string },
93 ) => layerTest(cwd, baseDirOrPrefix);
94}
95
96export const make = (config: ServerConfig["Service"]) => ServerConfig.of(config);
97
98export const otlpResource = (
99 config: Pick<ServerConfig["Service"], "mode" | "otelEnvironment">,
100 hostName: string,
101) => ({
102 serviceName: "t3code-server",
103 serviceVersion: packageJson.version,
104 attributes: {
105 "service.namespace": "t3code",
106 "service.runtime": "t3-server",
107 "service.mode": config.mode,
108 "host.name": config.otelEnvironment.resourceAttributes["host.name"] || hostName,
109 },
110});
111
112export const layer = (config: ServerConfig["Service"]) => Layer.succeed(ServerConfig, make(config));
113
114export const deriveServerPaths = Effect.fn(function* (
115 baseDir: ServerConfig["Service"]["baseDir"],
116 devUrl: ServerConfig["Service"]["devUrl"],
117 options: DeriveServerPathsOptions = {},
118): Effect.fn.Return<ServerDerivedPaths, never, Path.Path> {
119 const { join } = yield* Path.Path;
120 const stateDir = join(
121 baseDir,
122 devUrl !== undefined && !options.baseDirIsExplicit ? "dev" : "userdata",
123 );
124 const dbPath = join(stateDir, "statev2.sqlite");
125 const attachmentsDir = join(stateDir, "attachments");
126 const logsDir = join(stateDir, "logs");
127 const providerLogsDir = join(logsDir, "provider");
128 const providerStatusCacheDir = join(baseDir, "caches");
129 return {
130 stateDir,
131 dbPath,
132 keybindingsConfigPath: join(stateDir, "keybindings.json"),
133 settingsPath: join(stateDir, "settings.json"),
134 environmentThemesDir: join(stateDir, "themes"),
135 providerStatusCacheDir,
136 worktreesDir: join(baseDir, "worktrees"),
137 attachmentsDir,
138 browserArtifactsDir: join(stateDir, "browser-artifacts"),
139 logsDir,
140 serverTracePath: join(logsDir, "server.trace.ndjson"),
141 providerLogsDir,
142 providerEventLogPath: join(providerLogsDir, "events.log"),
143 terminalLogsDir: join(logsDir, "terminals"),
144 anonymousIdPath: join(stateDir, "anonymous-id"),
145 environmentIdPath: join(stateDir, "environment-id"),
146 serverRuntimeStatePath: join(stateDir, "server-runtime.json"),
147 secretsDir: join(stateDir, "secrets"),
148 };
149});
150
151export const ensureServerDirectories = Effect.fn(function* (derivedPaths: ServerDerivedPaths) {
152 const fs = yield* FileSystem.FileSystem;
153 const path = yield* Path.Path;
154
155 yield* Effect.all(
156 [
157 fs.makeDirectory(derivedPaths.stateDir, { recursive: true }),
158 fs.makeDirectory(derivedPaths.logsDir, { recursive: true }),
159 fs.makeDirectory(derivedPaths.providerLogsDir, { recursive: true }),
160 fs.makeDirectory(derivedPaths.terminalLogsDir, { recursive: true }),
161 fs.makeDirectory(derivedPaths.attachmentsDir, { recursive: true }),
162 fs.makeDirectory(derivedPaths.worktreesDir, { recursive: true }),
163 fs.makeDirectory(path.dirname(derivedPaths.keybindingsConfigPath), { recursive: true }),
164 fs.makeDirectory(path.dirname(derivedPaths.settingsPath), { recursive: true }),
165 fs.makeDirectory(derivedPaths.providerStatusCacheDir, { recursive: true }),
166 fs.makeDirectory(path.dirname(derivedPaths.anonymousIdPath), { recursive: true }),
167 fs.makeDirectory(path.dirname(derivedPaths.serverRuntimeStatePath), { recursive: true }),
168 ],
169 { concurrency: "unbounded" },
170 );
171
172 const swept = sweepStalePendingAttachments({
173 attachmentsDir: derivedPaths.attachmentsDir,
174 nowMs: yield* Clock.currentTimeMillis,
175 });
176 if (swept.deleted > 0) {
177 yield* Effect.logInfo("Removed expired attachment uploads.", { deleted: swept.deleted });
178 }
179});
180
181const makeTest = Effect.fn("ServerConfig.makeTest")(function* (
182 cwd: string,
183 baseDirOrPrefix: string | { readonly prefix: string },
184) {
185 const devUrl = undefined;
186 const fs = yield* FileSystem.FileSystem;
187 const baseDir =
188 typeof baseDirOrPrefix === "string"
189 ? baseDirOrPrefix
190 : yield* fs.makeTempDirectoryScoped({ prefix: baseDirOrPrefix.prefix });
191 const derivedPaths = yield* deriveServerPaths(baseDir, devUrl);
192 yield* ensureServerDirectories(derivedPaths);
193
194 return ServerConfig.of({
195 logLevel: "Error",
196 traceMinLevel: "Info",
197 traceTimingEnabled: true,
198 traceBatchWindowMs: 200,
199 traceMaxBytes: 10 * 1024 * 1024,
200 traceMaxFiles: 10,
201 otlpTracesUrl: undefined,
202 otlpMetricsUrl: undefined,
203 otlpLogsUrl: undefined,
204 otlpTracesExport: DEFAULT_SIGNAL_EXPORT,
205 otlpMetricsExport: DEFAULT_SIGNAL_EXPORT,
206 otlpLogsExport: DEFAULT_SIGNAL_EXPORT,
207 otelEnvironment: OtelEnvironment.none,
208 cwd,
209 baseDir,
210 ...derivedPaths,
211 mode: "web",
212 autoBootstrapProjectFromCwd: false,
213 logWebSocketEvents: false,
214 tailscaleServeEnabled: false,
215 tailscaleServePort: 443,
216 port: 0,
217 host: undefined,
218 desktopBootstrapToken: undefined,
219 desktopTelemetryFd: undefined,
220 desktopTelemetryControlFd: undefined,
221 desktopBrowserFd: undefined,
222 desktopBrowserControlFd: 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});