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