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