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