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

config.ts

477 lines17.2 KB

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