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

config.ts

509 lines18.3 KB

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