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 type { OtlpEndpointSource } from "@t3tools/contracts";
12import { sweepStalePendingAttachments } from "./attachmentStore.ts";
13import { DEFAULT_SIGNAL_EXPORT, type SignalExport } from "@t3tools/shared/observability";
14import * as OtelEnvironment from "@t3tools/shared/otelEnvironment";
15import packageJson from "../package.json" with { type: "json" };
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
25export interface ServerDerivedPaths {
26 readonly stateDir: string;
27 readonly dbPath: string;
28 readonly keybindingsConfigPath: string;
29 readonly settingsPath: string;
30 readonly environmentThemesDir: string;
31 readonly providerStatusCacheDir: string;
32 readonly worktreesDir: string;
33 readonly attachmentsDir: string;
34 readonly browserArtifactsDir: string;
35 readonly logsDir: string;
36 readonly serverTracePath: string;
37 readonly providerLogsDir: string;
38 readonly providerEventLogPath: string;
39 readonly terminalLogsDir: string;
40 readonly anonymousIdPath: string;
41 readonly environmentIdPath: string;
42 readonly serverRuntimeStatePath: string;
43 readonly secretsDir: string;
44}
45
46export interface DeriveServerPathsOptions {
47 readonly baseDirIsExplicit?: boolean;
48}
49
50export class ServerConfig extends Context.Service<
51 ServerConfig,
52 ServerDerivedPaths & {
53 readonly logLevel: LogLevel.LogLevel;
54 readonly traceMinLevel: LogLevel.LogLevel;
55 readonly traceTimingEnabled: boolean;
56 readonly traceBatchWindowMs: number;
57 readonly traceMaxBytes: number;
58 readonly traceMaxFiles: number;
59 readonly otlpTracesUrl: string | undefined;
60 readonly otlpMetricsUrl: string | undefined;
61 readonly otlpLogsUrl: string | undefined;
62 readonly otlpTracesExport: SignalExport;
63 readonly otlpMetricsExport: SignalExport;
64 readonly otlpLogsExport: SignalExport;
65 readonly otlpTracesSource?: OtlpEndpointSource;
66 readonly otlpTracesVariable?: string;
67 readonly otlpMetricsSource?: OtlpEndpointSource;
68 readonly otlpMetricsVariable?: string;
69 readonly otlpLogsSource?: OtlpEndpointSource;
70 readonly otlpLogsVariable?: string;
71 readonly otelEnvironment: OtelEnvironment.OtelEnvironment;
72 readonly mode: RuntimeMode;
73 readonly port: number;
74 readonly host: string | undefined;
75 /** Set when the host was defaulted to a private-network listener for the service. */
76 readonly privateNetworkOnly?: boolean | undefined;
77 readonly cwd: string;
78 readonly baseDir: string;
79 readonly staticDir: string | undefined;
80 readonly devUrl: URL | undefined;
81 readonly devAuthToken?: Redacted.Redacted<string> | undefined;
82 readonly devAllowedOrigins: ReadonlyArray<string>;
83 readonly noBrowser: boolean;
84 readonly startupPresentation: StartupPresentation;
85 readonly desktopBootstrapToken: string | undefined;
86 readonly desktopBootstrapSecret?: string | undefined;
87 readonly shellEnvironmentPrepared?: boolean | undefined;
88 readonly desktopTelemetryFd?: number | undefined;
89 readonly desktopTelemetryControlFd?: number | undefined;
90 readonly desktopBrowserFd?: number | undefined;
91 readonly desktopBrowserControlFd?: number | undefined;
92 readonly resourceMonitorPath?: string | undefined;
93 readonly autoBootstrapProjectFromCwd: boolean;
94 readonly logWebSocketEvents: boolean;
95 readonly tailscaleServeEnabled: boolean;
96 readonly tailscaleServePort: number;
97 }
98>()("t3/config/ServerConfig") {
99 static readonly layerTest = (
100 cwd: string,
101 baseDirOrPrefix: string | { readonly prefix: string },
102 ) => layerTest(cwd, baseDirOrPrefix);
103}
104
105export const make = (config: ServerConfig["Service"]) => ServerConfig.of(config);
106
107export const otlpResource = (
108 config: Pick<ServerConfig["Service"], "mode" | "otelEnvironment">,
109 hostName: string,
110) => ({
111 serviceName: "t3code-server",
112 serviceVersion: packageJson.version,
113 attributes: {
114 "service.namespace": "t3code",
115 "service.runtime": "t3-server",
116 "t3code.server.managed_by": config.mode === "desktop" ? "desktop" : "standalone",
117 "host.name": config.otelEnvironment.resourceAttributes["host.name"] || hostName,
118 },
119});
120
121export const layer = (config: ServerConfig["Service"]) => Layer.succeed(ServerConfig, make(config));
122
123export const deriveServerPaths = Effect.fn(function* (
124 baseDir: ServerConfig["Service"]["baseDir"],
125 devUrl: ServerConfig["Service"]["devUrl"],
126 options: DeriveServerPathsOptions = {},
127): Effect.fn.Return<ServerDerivedPaths, never, Path.Path> {
128 const { join } = yield* Path.Path;
129 const stateDir = join(
130 baseDir,
131 devUrl !== undefined && !options.baseDirIsExplicit ? "dev" : "userdata",
132 );
133 const dbPath = join(stateDir, "statev2.sqlite");
134 const attachmentsDir = join(stateDir, "attachments");
135 const logsDir = join(stateDir, "logs");
136 const providerLogsDir = join(logsDir, "provider");
137 const providerStatusCacheDir = join(baseDir, "caches");
138 return {
139 stateDir,
140 dbPath,
141 keybindingsConfigPath: join(stateDir, "keybindings.json"),
142 settingsPath: join(stateDir, "settings.json"),
143 environmentThemesDir: join(stateDir, "themes"),
144 providerStatusCacheDir,
145 worktreesDir: join(baseDir, "worktrees"),
146 attachmentsDir,
147 browserArtifactsDir: join(stateDir, "browser-artifacts"),
148 logsDir,
149 serverTracePath: join(logsDir, "server.trace.ndjson"),
150 providerLogsDir,
151 providerEventLogPath: join(providerLogsDir, "events.log"),
152 terminalLogsDir: join(logsDir, "terminals"),
153 anonymousIdPath: join(stateDir, "anonymous-id"),
154 environmentIdPath: join(stateDir, "environment-id"),
155 serverRuntimeStatePath: join(stateDir, "server-runtime.json"),
156 secretsDir: join(stateDir, "secrets"),
157 };
158});
159
160export const ensureServerDirectories = Effect.fn(function* (derivedPaths: ServerDerivedPaths) {
161 const fs = yield* FileSystem.FileSystem;
162 const path = yield* Path.Path;
163
164 yield* Effect.all(
165 [
166 fs.makeDirectory(derivedPaths.stateDir, { recursive: true }),
167 fs.makeDirectory(derivedPaths.logsDir, { recursive: true }),
168 fs.makeDirectory(derivedPaths.providerLogsDir, { recursive: true }),
169 fs.makeDirectory(derivedPaths.terminalLogsDir, { recursive: true }),
170 fs.makeDirectory(derivedPaths.attachmentsDir, { recursive: true }),
171 fs.makeDirectory(derivedPaths.worktreesDir, { recursive: true }),
172 fs.makeDirectory(path.dirname(derivedPaths.keybindingsConfigPath), { recursive: true }),
173 fs.makeDirectory(path.dirname(derivedPaths.settingsPath), { recursive: true }),
174 fs.makeDirectory(derivedPaths.providerStatusCacheDir, { recursive: true }),
175 fs.makeDirectory(path.dirname(derivedPaths.anonymousIdPath), { recursive: true }),
176 fs.makeDirectory(path.dirname(derivedPaths.serverRuntimeStatePath), { recursive: true }),
177 ],
178 { concurrency: "unbounded" },
179 );
180
181 const swept = sweepStalePendingAttachments({
182 attachmentsDir: derivedPaths.attachmentsDir,
183 nowMs: yield* Clock.currentTimeMillis,
184 });
185 if (swept.deleted > 0) {
186 yield* Effect.logInfo("Removed expired attachment uploads.", { deleted: swept.deleted });
187 }
188});
189
190const makeTest = Effect.fn("ServerConfig.makeTest")(function* (
191 cwd: string,
192 baseDirOrPrefix: string | { readonly prefix: string },
193) {
194 const devUrl = undefined;
195 const fs = yield* FileSystem.FileSystem;
196 const baseDir =
197 typeof baseDirOrPrefix === "string"
198 ? baseDirOrPrefix
199 : // macOS temp dirs live under the /var -> /private/var symlink; storage cleanup's
200 // symlink guards compare resolved paths, so generated test dirs must be real paths.
201 yield* fs.realPath(yield* fs.makeTempDirectoryScoped({ prefix: baseDirOrPrefix.prefix }));
202 const derivedPaths = yield* deriveServerPaths(baseDir, devUrl);
203 yield* ensureServerDirectories(derivedPaths);
204
205 return ServerConfig.of({
206 logLevel: "Error",
207 traceMinLevel: "Info",
208 traceTimingEnabled: true,
209 traceBatchWindowMs: 200,
210 traceMaxBytes: 10 * 1024 * 1024,
211 traceMaxFiles: 10,
212 otlpTracesUrl: undefined,
213 otlpMetricsUrl: undefined,
214 otlpLogsUrl: undefined,
215 otlpTracesExport: DEFAULT_SIGNAL_EXPORT,
216 otlpMetricsExport: DEFAULT_SIGNAL_EXPORT,
217 otlpLogsExport: DEFAULT_SIGNAL_EXPORT,
218 otelEnvironment: OtelEnvironment.none,
219 cwd,
220 baseDir,
221 ...derivedPaths,
222 mode: "web",
223 autoBootstrapProjectFromCwd: false,
224 logWebSocketEvents: false,
225 tailscaleServeEnabled: false,
226 tailscaleServePort: 443,
227 port: 0,
228 host: undefined,
229 desktopBootstrapToken: undefined,
230 desktopTelemetryFd: undefined,
231 desktopTelemetryControlFd: undefined,
232 desktopBrowserFd: undefined,
233 desktopBrowserControlFd: undefined,
234 resourceMonitorPath: undefined,
235 staticDir: undefined,
236 devUrl,
237 devAllowedOrigins: [],
238 noBrowser: false,
239 startupPresentation: "browser",
240 });
241});
242
243export const layerTest = (cwd: string, baseDirOrPrefix: string | { readonly prefix: string }) =>
244 Layer.effect(ServerConfig, makeTest(cwd, baseDirOrPrefix));
245
246export const resolveStaticDir = Effect.fn(function* () {
247 const { join, resolve } = yield* Path.Path;
248 const { exists } = yield* FileSystem.FileSystem;
249 const bundledClient = resolve(join(import.meta.dirname, "client"));
250 const bundledStat = yield* exists(join(bundledClient, "index.html")).pipe(
251 Effect.orElseSucceed(() => false),
252 );
253 if (bundledStat) {
254 return bundledClient;
255 }
256
257 const monorepoClient = resolve(join(import.meta.dirname, "../../web/dist"));
258 const monorepoStat = yield* exists(join(monorepoClient, "index.html")).pipe(
259 Effect.orElseSucceed(() => false),
260 );
261 if (monorepoStat) {
262 return monorepoClient;
263 }
264 return undefined;
265});