Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

config.ts

543 lines19.3 KB

1import * as NetService from "@t3tools/shared/Net";
2import {
3 OtlpHeadersFromString,
4 OtlpProtocol,
5 type SignalExport,
6} from "@t3tools/shared/observability";
7import * as OtelEnvironment from "@t3tools/shared/otelEnvironment";
8import { parsePersistedServerObservabilitySettings } from "@t3tools/shared/serverSettings";
9import { DesktopBackendBootstrap, PortSchema } from "@t3tools/contracts";
10import * as Config from "effect/Config";
11import * as Duration from "effect/Duration";
12import * as Effect from "effect/Effect";
13import * as FileSystem from "effect/FileSystem";
14import * as LogLevel from "effect/LogLevel";
15import * as Option from "effect/Option";
16import * as Path from "effect/Path";
17import * as Redacted from "effect/Redacted";
18import * as Schema from "effect/Schema";
19import * as SchemaIssue from "effect/SchemaIssue";
20import * as SchemaTransformation from "effect/SchemaTransformation";
21import { Argument, Flag } from "effect/unstable/cli";
22​
23import { readBootstrapEnvelope } from "../bootstrap.ts";
24import * as ServerConfig from "../config.ts";
25import { expandHomePath, resolveBaseDir } from "../os-jank.ts";
26​
27const modeFlag = Flag.Literals("mode", ServerConfig.RuntimeMode.literals).pipe(
28 Flag.withDescription("Runtime mode. `desktop` keeps loopback defaults unless overridden."),
29 Flag.optional,
30);
31const portFlag = Flag.Int("port").pipe(
32 Flag.withSchema(PortSchema),
33 Flag.withDescription("Port for the HTTP/WebSocket server."),
34 Flag.optional,
35);
36const hostFlag = Flag.String("host").pipe(
37 Flag.withDescription("Host/interface to bind (for example 127.0.0.1, 0.0.0.0, or a Tailnet IP)."),
38 Flag.optional,
39);
40export const baseDirFlag = Flag.String("base-dir").pipe(
41 Flag.withDescription(
42 "Explicit T3 Code data directory; runtime state is stored under userdata (equivalent to T3CODE_HOME).",
43 ),
44 Flag.optional,
45);
46const devUrlFlag = Flag.String("dev-url").pipe(
47 Flag.withSchema(Schema.URLFromString),
48 Flag.withDescription("Dev web URL to proxy/redirect to (equivalent to VITE_DEV_SERVER_URL)."),
49 Flag.optional,
50);
51const noBrowserFlag = Flag.Boolean("no-browser").pipe(
52 Flag.withDescription("Disable automatic browser opening."),
53 Flag.optional,
54);
55const bootstrapFdFlag = Flag.Int("bootstrap-fd").pipe(
56 Flag.withSchema(Schema.Int),
57 Flag.withDescription("Read one-time bootstrap secrets from the given file descriptor."),
58 Flag.optional,
59);
60const autoBootstrapProjectFromCwdFlag = Flag.Boolean("auto-bootstrap-project-from-cwd").pipe(
61 Flag.withDescription(
62 "Create a project for the current working directory on startup when missing.",
63 ),
64 Flag.optional,
65);
66const logWebSocketEventsFlag = Flag.Boolean("log-websocket-events").pipe(
67 Flag.withDescription(
68 "Emit server-side logs for outbound WebSocket push traffic (equivalent to T3CODE_LOG_WS_EVENTS).",
69 ),
70 Flag.withAlias("log-ws-events"),
71 Flag.optional,
72);
73const tailscaleServeFlag = Flag.Boolean("tailscale-serve").pipe(
74 Flag.withDescription(
75 "Configure Tailscale Serve to expose this backend over HTTPS on the Tailnet.",
76 ),
77 Flag.optional,
78);
79const tailscaleServePortFlag = Flag.Int("tailscale-serve-port").pipe(
80 Flag.withSchema(PortSchema),
81 Flag.withDescription("HTTPS port for Tailscale Serve when --tailscale-serve is enabled."),
82 Flag.optional,
83);
84​
85const EnvServerConfig = Config.all({
86 logLevel: Config.LogLevel("T3CODE_LOG_LEVEL").pipe(Config.withDefault("Info")),
87 traceMinLevel: Config.LogLevel("T3CODE_TRACE_MIN_LEVEL").pipe(Config.withDefault("Info")),
88 traceTimingEnabled: Config.Boolean("T3CODE_TRACE_TIMING_ENABLED").pipe(Config.withDefault(true)),
89 traceFile: Config.String("T3CODE_TRACE_FILE").pipe(
90 Config.option,
91 Config.map(Option.getOrUndefined),
92 ),
93 traceMaxBytes: Config.Int("T3CODE_TRACE_MAX_BYTES").pipe(Config.withDefault(10 * 1024 * 1024)),
94 traceMaxFiles: Config.Int("T3CODE_TRACE_MAX_FILES").pipe(Config.withDefault(10)),
95 traceBatchWindowMs: Config.Int("T3CODE_TRACE_BATCH_WINDOW_MS").pipe(Config.withDefault(1_000)),
96 otlpTracesUrl: Config.String("T3CODE_OTLP_TRACES_URL").pipe(
97 Config.option,
98 Config.map(Option.getOrUndefined),
99 ),
100 otlpMetricsUrl: Config.String("T3CODE_OTLP_METRICS_URL").pipe(
101 Config.option,
102 Config.map(Option.getOrUndefined),
103 ),
104 otlpLogsUrl: Config.String("T3CODE_OTLP_LOGS_URL").pipe(
105 Config.option,
106 Config.map(Option.getOrUndefined),
107 ),
108 otlpExportIntervalMs: Config.Int("T3CODE_OTLP_EXPORT_INTERVAL_MS").pipe(
109 Config.withDefault(10_000),
110 ),
111 otlpHeaders: Config.schema(OtlpHeadersFromString, "T3CODE_OTLP_HEADERS").pipe(
112 Config.option,
113 Config.map(Option.getOrUndefined),
114 ),
115 otlpProtocol: Config.schema(OtlpProtocol, "T3CODE_OTLP_PROTOCOL").pipe(
116 Config.withDefault("http/json"),
117 ),
118 mode: Config.schema(ServerConfig.RuntimeMode, "T3CODE_MODE").pipe(
119 Config.option,
120 Config.map(Option.getOrUndefined),
121 ),
122 port: Config.Port("T3CODE_PORT").pipe(Config.option, Config.map(Option.getOrUndefined)),
123 host: Config.String("T3CODE_HOST").pipe(Config.option, Config.map(Option.getOrUndefined)),
124 t3Home: Config.String("T3CODE_HOME").pipe(Config.option, Config.map(Option.getOrUndefined)),
125 devUrl: Config.URL("VITE_DEV_SERVER_URL").pipe(Config.option, Config.map(Option.getOrUndefined)),
126 devAllowedOrigins: Config.String("T3CODE_DEV_ALLOWED_ORIGINS").pipe(
127 Config.withDefault(""),
128 Config.map((value) =>
129 value
130 .split(",")
131 .map((entry) => entry.trim())
132 .filter((entry) => entry.length > 0),
133 ),
134 ),
135 noBrowser: Config.Boolean("T3CODE_NO_BROWSER").pipe(
136 Config.option,
137 Config.map(Option.getOrUndefined),
138 ),
139 bootstrapFd: Config.Int("T3CODE_BOOTSTRAP_FD").pipe(
140 Config.option,
141 Config.map(Option.getOrUndefined),
142 ),
143 autoBootstrapProjectFromCwd: Config.Boolean("T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD").pipe(
144 Config.option,
145 Config.map(Option.getOrUndefined),
146 ),
147 logWebSocketEvents: Config.Boolean("T3CODE_LOG_WS_EVENTS").pipe(
148 Config.option,
149 Config.map(Option.getOrUndefined),
150 ),
151 tailscaleServeEnabled: Config.Boolean("T3CODE_TAILSCALE_SERVE").pipe(
152 Config.option,
153 Config.map(Option.getOrUndefined),
154 ),
155 tailscaleServePort: Config.Port("T3CODE_TAILSCALE_SERVE_PORT").pipe(
156 Config.option,
157 Config.map(Option.getOrUndefined),
158 ),
159});
160​
161const DevAuthTokenConfig = Config.Redacted("T3CODE_DEV_AUTH_TOKEN").pipe(
162 Config.map((token) => Redacted.make(Redacted.value(token).trim())),
163 Config.mapEffect((token) =>
164 Redacted.value(token).length === 0 || Redacted.value(token).length >= 32
165 ? Effect.succeed(token)
166 : Effect.fail(
167 new Config.ConfigError(
168 new Schema.SchemaError(
169 new SchemaIssue.InvalidValue({
170 message: "T3CODE_DEV_AUTH_TOKEN must contain at least 32 characters.",
171 }),
172 ),
173 ),
174 ),
175 ),
176 Config.option,
177 Config.map(Option.filter((token) => Redacted.value(token).length > 0)),
178 Config.map(Option.getOrUndefined),
179);
180​
181export interface CliServerFlags {
182 readonly mode: Option.Option<ServerConfig.RuntimeMode>;
183 readonly port: Option.Option<number>;
184 readonly host: Option.Option<string>;
185 readonly baseDir: Option.Option<string>;
186 readonly cwd: Option.Option<string>;
187 readonly devUrl: Option.Option<URL>;
188 readonly noBrowser: Option.Option<boolean>;
189 readonly bootstrapFd: Option.Option<number>;
190 readonly autoBootstrapProjectFromCwd: Option.Option<boolean>;
191 readonly logWebSocketEvents: Option.Option<boolean>;
192 readonly tailscaleServeEnabled: Option.Option<boolean>;
193 readonly tailscaleServePort: Option.Option<number>;
195​
196export interface CliAuthLocationFlags {
197 readonly baseDir: Option.Option<string>;
198 readonly devUrl?: Option.Option<URL>;
200​
201export const authLocationFlags = {
202 baseDir: baseDirFlag,
203 devUrl: devUrlFlag,
204} as const;
205​
206export const projectLocationFlags = {
207 baseDir: baseDirFlag,
208} as const;
209​
210export const sharedServerCommandFlags = {
211 mode: modeFlag,
212 port: portFlag,
213 host: hostFlag,
214 baseDir: baseDirFlag,
215 cwd: Argument.String("cwd").pipe(
216 Argument.withDescription(
217 "Working directory for provider sessions (defaults to the current directory).",
218 ),
219 Argument.optional,
220 ),
221 devUrl: devUrlFlag,
222 noBrowser: noBrowserFlag,
223 bootstrapFd: bootstrapFdFlag,
224 autoBootstrapProjectFromCwd: autoBootstrapProjectFromCwdFlag,
225 logWebSocketEvents: logWebSocketEventsFlag,
226 tailscaleServeEnabled: tailscaleServeFlag,
227 tailscaleServePort: tailscaleServePortFlag,
228} as const;
229​
230const resolveOptionPrecedence = <Value>(
231 ...values: ReadonlyArray<Option.Option<Value>>
232): Option.Option<Value> => Option.firstSomeOf(values);
233​
234const loadPersistedObservabilitySettings = Effect.fn(function* (settingsPath: string) {
235 const fs = yield* FileSystem.FileSystem;
236 const exists = yield* fs.exists(settingsPath).pipe(Effect.orElseSucceed(() => false));
237 if (!exists) {
238 return { otlpTracesUrl: undefined, otlpMetricsUrl: undefined, otlpLogsUrl: undefined };
239 }
240​
241 const raw = yield* fs.readFileString(settingsPath).pipe(Effect.orElseSucceed(() => ""));
242 return parsePersistedServerObservabilitySettings(raw);
243});
244​
245export const resolveServerConfig = (
246 flags: CliServerFlags,
247 cliLogLevel: Option.Option<LogLevel.LogLevel>,
248 options?: {
249 readonly startupPresentation?: ServerConfig.StartupPresentation;
250 readonly forceAutoBootstrapProjectFromCwd?: boolean;
251 },
252) =>
253 Effect.gen(function* () {
254 const { findAvailablePort } = yield* NetService.NetService;
255 const path = yield* Path.Path;
256 const fs = yield* FileSystem.FileSystem;
257 const env = yield* EnvServerConfig;
258 const normalizedFlags = {
259 mode: flags.mode ?? Option.none(),
260 port: flags.port ?? Option.none(),
261 host: flags.host ?? Option.none(),
262 baseDir: flags.baseDir ?? Option.none(),
263 cwd: flags.cwd ?? Option.none(),
264 devUrl: flags.devUrl ?? Option.none(),
265 noBrowser: flags.noBrowser ?? Option.none(),
266 bootstrapFd: flags.bootstrapFd ?? Option.none(),
267 autoBootstrapProjectFromCwd: flags.autoBootstrapProjectFromCwd ?? Option.none(),
268 logWebSocketEvents: flags.logWebSocketEvents ?? Option.none(),
269 tailscaleServeEnabled: flags.tailscaleServeEnabled ?? Option.none(),
270 tailscaleServePort: flags.tailscaleServePort ?? Option.none(),
271 } satisfies CliServerFlags;
272 const bootstrapFd = Option.getOrUndefined(normalizedFlags.bootstrapFd) ?? env.bootstrapFd;
273 const bootstrapEnvelope =
274 bootstrapFd !== undefined
275 ? yield* readBootstrapEnvelope(DesktopBackendBootstrap, bootstrapFd)
276 : Option.none();
277 const bootstrap = Option.getOrUndefined(bootstrapEnvelope);
278​
279 const mode: ServerConfig.RuntimeMode = Option.getOrElse(
280 resolveOptionPrecedence(
281 normalizedFlags.mode,
282 Option.fromUndefinedOr(env.mode),
283 Option.fromUndefinedOr(bootstrap?.mode),
284 ),
285 () => "web",
286 );
287​
288 const port = yield* Option.match(
289 resolveOptionPrecedence(
290 normalizedFlags.port,
291 Option.fromUndefinedOr(env.port),
292 Option.fromUndefinedOr(bootstrap?.port),
293 ),
294 {
295 onSome: (value) => Effect.succeed(value),
296 onNone: () => {
297 if (mode === "desktop") {
298 return Effect.succeed(ServerConfig.DEFAULT_PORT);
299 }
300 return findAvailablePort(ServerConfig.DEFAULT_PORT);
301 },
302 },
303 );
304 const devUrl = Option.getOrElse(
305 resolveOptionPrecedence(normalizedFlags.devUrl, Option.fromUndefinedOr(env.devUrl)),
306 () => undefined,
307 );
308 const devAuthToken =
309 mode === "web" && devUrl !== undefined ? yield* DevAuthTokenConfig : undefined;
310 const explicitBaseDir = resolveOptionPrecedence(
311 normalizedFlags.baseDir,
312 Option.fromUndefinedOr(env.t3Home),
313 ).pipe(Option.filter((value) => value.trim().length > 0));
314 const baseDir = yield* resolveBaseDir(
315 Option.getOrUndefined(
316 resolveOptionPrecedence(explicitBaseDir, Option.fromUndefinedOr(bootstrap?.t3Home)),
317 ),
318 );
319 const rawCwd = Option.getOrElse(normalizedFlags.cwd, () => process.cwd());
320 const cwd = path.resolve(yield* expandHomePath(rawCwd.trim()));
321 yield* fs.makeDirectory(cwd, { recursive: true });
322 const derivedPaths = yield* ServerConfig.deriveServerPaths(baseDir, devUrl, {
323 baseDirIsExplicit: Option.isSome(explicitBaseDir),
324 });
325 yield* ServerConfig.ensureServerDirectories(derivedPaths);
326 const persistedObservabilitySettings = yield* loadPersistedObservabilitySettings(
327 derivedPaths.settingsPath,
328 );
329 const serverTracePath = env.traceFile ?? derivedPaths.serverTracePath;
330 yield* fs.makeDirectory(path.dirname(serverTracePath), { recursive: true });
331 const startupPresentation = options?.startupPresentation ?? "browser";
332 const isHeadlessStartup = startupPresentation === "headless";
333 const noBrowser = Option.getOrElse(
334 resolveOptionPrecedence(
335 isHeadlessStartup ? Option.some(true) : Option.none(),
336 normalizedFlags.noBrowser,
337 Option.fromUndefinedOr(env.noBrowser),
338 Option.fromUndefinedOr(bootstrap?.noBrowser),
339 ),
340 () => mode === "desktop",
341 );
342 const desktopBootstrapToken = bootstrap?.desktopBootstrapToken;
343 const desktopTelemetryFd = bootstrap?.desktopTelemetryFd;
344 const desktopTelemetryControlFd = bootstrap?.desktopTelemetryControlFd;
345 const resourceMonitorPath = bootstrap?.resourceMonitorPath;
346 const autoBootstrapProjectFromCwd = Option.getOrElse(
347 resolveOptionPrecedence(
348 Option.fromUndefinedOr(options?.forceAutoBootstrapProjectFromCwd),
349 isHeadlessStartup ? Option.some(false) : Option.none(),
350 normalizedFlags.autoBootstrapProjectFromCwd,
351 Option.fromUndefinedOr(env.autoBootstrapProjectFromCwd),
352 ),
353 () => mode === "web",
354 );
355 const logWebSocketEvents = Option.getOrElse(
356 resolveOptionPrecedence(
357 normalizedFlags.logWebSocketEvents,
358 Option.fromUndefinedOr(env.logWebSocketEvents),
359 ),
360 () => Boolean(devUrl),
361 );
362 const tailscaleServeEnabled = Option.getOrElse(
363 resolveOptionPrecedence(
364 normalizedFlags.tailscaleServeEnabled,
365 Option.fromUndefinedOr(env.tailscaleServeEnabled),
366 Option.fromUndefinedOr(bootstrap?.tailscaleServeEnabled),
367 ),
368 () => false,
369 );
370 const tailscaleServePort = Option.getOrElse(
371 resolveOptionPrecedence(
372 normalizedFlags.tailscaleServePort,
373 Option.fromUndefinedOr(env.tailscaleServePort),
374 Option.fromUndefinedOr(bootstrap?.tailscaleServePort),
375 ),
376 () => 443,
377 );
378 const staticDir = devUrl ? undefined : yield* ServerConfig.resolveStaticDir();
379 const host = Option.getOrElse(
380 resolveOptionPrecedence(
381 normalizedFlags.host,
382 Option.fromUndefinedOr(env.host),
383 Option.fromUndefinedOr(bootstrap?.host),
384 ),
385 () => (mode === "desktop" ? "127.0.0.1" : undefined),
386 );
387 const logLevel = Option.getOrElse(cliLogLevel, () => env.logLevel);
388​
389 const otel = yield* OtelEnvironment.load;
390​
391 // T3 Code's own OTLP variables name no signal, so the one answer they give
392 // is the answer for all three.
393 const signalExport: SignalExport = {
394 protocol: env.otlpProtocol,
395 headers: env.otlpHeaders,
396 exportIntervalMs: env.otlpExportIntervalMs,
397 };
398 const traces = OtelEnvironment.resolveSignalEndpoint(
399 otel,
400 "traces",
401 { url: env.otlpTracesUrl, export: signalExport },
402 bootstrap?.otlpTracesUrl,
403 persistedObservabilitySettings.otlpTracesUrl,
404 );
405 const metrics = OtelEnvironment.resolveSignalEndpoint(
406 otel,
407 "metrics",
408 { url: env.otlpMetricsUrl, export: signalExport },
409 bootstrap?.otlpMetricsUrl,
410 persistedObservabilitySettings.otlpMetricsUrl,
411 );
412 const logs = OtelEnvironment.resolveSignalEndpoint(
413 otel,
414 "logs",
415 { url: env.otlpLogsUrl, export: signalExport },
416 bootstrap?.otlpLogsUrl,
417 persistedObservabilitySettings.otlpLogsUrl,
418 );
419​
420 const config: ServerConfig.ServerConfig["Service"] = {
421 logLevel,
422 traceMinLevel: env.traceMinLevel,
423 traceTimingEnabled: env.traceTimingEnabled,
424 traceBatchWindowMs: env.traceBatchWindowMs,
425 traceMaxBytes: env.traceMaxBytes,
426 traceMaxFiles: env.traceMaxFiles,
427 otlpTracesUrl: traces?.url,
428 otlpMetricsUrl: metrics?.url,
429 otlpLogsUrl: logs?.url,
430 otlpTracesExport: traces?.export ?? signalExport,
431 otlpMetricsExport: metrics?.export ?? signalExport,
432 otlpLogsExport: logs?.export ?? signalExport,
433 otelEnvironment: otel,
434 mode,
435 port,
436 cwd,
437 baseDir,
438 ...derivedPaths,
439 serverTracePath,
440 host,
441 staticDir,
442 devUrl,
443 ...(devAuthToken === undefined ? {} : { devAuthToken }),
444 devAllowedOrigins: env.devAllowedOrigins,
445 noBrowser,
446 startupPresentation,
447 desktopBootstrapToken,
448 desktopTelemetryFd,
449 desktopTelemetryControlFd,
450 resourceMonitorPath,
451 autoBootstrapProjectFromCwd,
452 logWebSocketEvents,
453 tailscaleServeEnabled,
454 tailscaleServePort,
455 };
456​
457 return config;
458 });
459​
460export const resolveCliAuthConfig = (
461 flags: CliAuthLocationFlags,
462 cliLogLevel: Option.Option<LogLevel.LogLevel>,
463) =>
464 resolveServerConfig(
465 {
466 mode: Option.none(),
467 port: Option.none(),
468 host: Option.none(),
469 baseDir: flags.baseDir,
470 cwd: Option.none(),
471 devUrl: flags.devUrl ?? Option.none(),
472 noBrowser: Option.none(),
473 bootstrapFd: Option.none(),
474 autoBootstrapProjectFromCwd: Option.none(),
475 logWebSocketEvents: Option.none(),
476 tailscaleServeEnabled: Option.none(),
477 tailscaleServePort: Option.none(),
478 },
479 cliLogLevel,
480 );
481​
482const DurationShorthandPattern = /^(?<value>\d+)(?<unit>ms|s|m|h|d|w)$/i;
483​
484const parseDurationInput = (value: string): Duration.Duration | null => {
485 const trimmed = value.trim();
486 if (trimmed.length === 0) return null;
487​
488 const shorthand = DurationShorthandPattern.exec(trimmed);
489 const normalizedInput = shorthand?.groups
490 ? (() => {
491 const amountText = shorthand.groups.value;
492 const unitText = shorthand.groups.unit;
493 if (typeof amountText !== "string" || typeof unitText !== "string") {
494 return null;
495 }
496​
497 const amount = Number.parseInt(amountText, 10);
498 if (!Number.isFinite(amount)) return null;
499​
500 switch (unitText.toLowerCase()) {
501 case "ms":
502 return `${amount} millis`;
503 case "s":
504 return `${amount} seconds`;
505 case "m":
506 return `${amount} minutes`;
507 case "h":
508 return `${amount} hours`;
509 case "d":
510 return `${amount} days`;
511 case "w":
512 return `${amount} weeks`;
513 default:
514 return null;
515 }
516 })()
517 : (trimmed as Duration.Input);
518​
519 if (normalizedInput === null) return null;
520​
521 const decoded = Duration.fromInput(normalizedInput as Duration.Input);
522 return Option.isSome(decoded) ? decoded.value : null;
523};
524​
525export const DurationFromString = Schema.String.pipe(
526 Schema.decodeTo(
527 Schema.Duration,
528 SchemaTransformation.transformEffect({
529 decode: (value) => {
530 const duration = parseDurationInput(value);
531 if (duration !== null) {
532 return Effect.succeed(duration);
533 }
534 return Effect.fail(
535 new SchemaIssue.InvalidValue({
536 message: "Invalid duration. Use values like 5m, 1h, 30d, or 15 minutes.",
537 }),
538 );
539 },
540 encode: (duration) => Effect.succeed(Duration.format(duration)),
541 }),
542 ),
543);