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

config.ts

475 lines17.0 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);
24const portFlag = Flag.integer("port").pipe(
25 Flag.withSchema(PortSchema),
26 Flag.withDescription("Port for the HTTP/WebSocket server."),
27 Flag.optional,
28);
29const 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);
39const 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);
44const noBrowserFlag = Flag.boolean("no-browser").pipe(
45 Flag.withDescription("Disable automatic browser opening."),
46 Flag.optional,
47);
48const 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);
53const 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);
59const 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);
66const 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 authLocationFlags = {
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​
193const resolveOptionPrecedence = <Value>(
194 ...values: ReadonlyArray<Option.Option<Value>>
195): Option.Option<Value> => Option.firstSomeOf(values);
196​
197const loadPersistedObservabilitySettings = Effect.fn(function* (settingsPath: string) {
198 const fs = yield* FileSystem.FileSystem;
199 const exists = yield* fs.exists(settingsPath).pipe(Effect.orElseSucceed(() => false));
200 if (!exists) {
201 return { otlpTracesUrl: undefined, otlpMetricsUrl: undefined };
202 }
203​
204 const raw = yield* fs.readFileString(settingsPath).pipe(Effect.orElseSucceed(() => ""));
205 return parsePersistedServerObservabilitySettings(raw);
206});
207​
208export const resolveServerConfig = (
209 flags: CliServerFlags,
210 cliLogLevel: Option.Option<LogLevel.LogLevel>,
211 options?: {
212 readonly startupPresentation?: ServerConfig.StartupPresentation;
213 readonly forceAutoBootstrapProjectFromCwd?: boolean;
214 },
215) =>
216 Effect.gen(function* () {
217 const { findAvailablePort } = yield* NetService.NetService;
218 const path = yield* Path.Path;
219 const fs = yield* FileSystem.FileSystem;
220 const env = yield* EnvServerConfig;
221 const normalizedFlags = {
222 mode: flags.mode ?? Option.none(),
223 port: flags.port ?? Option.none(),
224 host: flags.host ?? Option.none(),
225 baseDir: flags.baseDir ?? Option.none(),
226 cwd: flags.cwd ?? Option.none(),
227 devUrl: flags.devUrl ?? Option.none(),
228 noBrowser: flags.noBrowser ?? Option.none(),
229 bootstrapFd: flags.bootstrapFd ?? Option.none(),
230 autoBootstrapProjectFromCwd: flags.autoBootstrapProjectFromCwd ?? Option.none(),
231 logWebSocketEvents: flags.logWebSocketEvents ?? Option.none(),
232 tailscaleServeEnabled: flags.tailscaleServeEnabled ?? Option.none(),
233 tailscaleServePort: flags.tailscaleServePort ?? Option.none(),
234 } satisfies CliServerFlags;
235 const bootstrapFd = Option.getOrUndefined(normalizedFlags.bootstrapFd) ?? env.bootstrapFd;
236 const bootstrapEnvelope =
237 bootstrapFd !== undefined
238 ? yield* readBootstrapEnvelope(DesktopBackendBootstrap, bootstrapFd)
239 : Option.none();
240 const bootstrap = Option.getOrUndefined(bootstrapEnvelope);
241​
242 const mode: ServerConfig.RuntimeMode = Option.getOrElse(
243 resolveOptionPrecedence(
244 normalizedFlags.mode,
245 Option.fromUndefinedOr(env.mode),
246 Option.fromUndefinedOr(bootstrap?.mode),
247 ),
248 () => "web",
249 );
250​
251 const port = yield* Option.match(
252 resolveOptionPrecedence(
253 normalizedFlags.port,
254 Option.fromUndefinedOr(env.port),
255 Option.fromUndefinedOr(bootstrap?.port),
256 ),
257 {
258 onSome: (value) => Effect.succeed(value),
259 onNone: () => {
260 if (mode === "desktop") {
261 return Effect.succeed(ServerConfig.DEFAULT_PORT);
262 }
263 return findAvailablePort(ServerConfig.DEFAULT_PORT);
264 },
265 },
266 );
267 const devUrl = Option.getOrElse(
268 resolveOptionPrecedence(normalizedFlags.devUrl, Option.fromUndefinedOr(env.devUrl)),
269 () => undefined,
270 );
271 const explicitBaseDir = resolveOptionPrecedence(
272 normalizedFlags.baseDir,
273 Option.fromUndefinedOr(env.t3Home),
274 ).pipe(Option.filter((value) => value.trim().length > 0));
275 const baseDir = yield* resolveBaseDir(
276 Option.getOrUndefined(
277 resolveOptionPrecedence(explicitBaseDir, Option.fromUndefinedOr(bootstrap?.t3Home)),
278 ),
279 );
280 const rawCwd = Option.getOrElse(normalizedFlags.cwd, () => process.cwd());
281 const cwd = path.resolve(yield* expandHomePath(rawCwd.trim()));
282 yield* fs.makeDirectory(cwd, { recursive: true });
283 const derivedPaths = yield* ServerConfig.deriveServerPaths(baseDir, devUrl, {
284 baseDirIsExplicit: Option.isSome(explicitBaseDir),
285 });
286 yield* ServerConfig.ensureServerDirectories(derivedPaths);
287 const persistedObservabilitySettings = yield* loadPersistedObservabilitySettings(
288 derivedPaths.settingsPath,
289 );
290 const serverTracePath = env.traceFile ?? derivedPaths.serverTracePath;
291 yield* fs.makeDirectory(path.dirname(serverTracePath), { recursive: true });
292 const startupPresentation = options?.startupPresentation ?? "browser";
293 const isHeadlessStartup = startupPresentation === "headless";
294 const noBrowser = Option.getOrElse(
295 resolveOptionPrecedence(
296 isHeadlessStartup ? Option.some(true) : Option.none(),
297 normalizedFlags.noBrowser,
298 Option.fromUndefinedOr(env.noBrowser),
299 Option.fromUndefinedOr(bootstrap?.noBrowser),
300 ),
301 () => mode === "desktop",
302 );
303 const desktopBootstrapToken = bootstrap?.desktopBootstrapToken;
304 const desktopTelemetryFd = bootstrap?.desktopTelemetryFd;
305 const desktopTelemetryControlFd = bootstrap?.desktopTelemetryControlFd;
306 const resourceMonitorPath = bootstrap?.resourceMonitorPath;
307 const autoBootstrapProjectFromCwd = Option.getOrElse(
308 resolveOptionPrecedence(
309 Option.fromUndefinedOr(options?.forceAutoBootstrapProjectFromCwd),
310 isHeadlessStartup ? Option.some(false) : Option.none(),
311 normalizedFlags.autoBootstrapProjectFromCwd,
312 Option.fromUndefinedOr(env.autoBootstrapProjectFromCwd),
313 ),
314 () => mode === "web",
315 );
316 const logWebSocketEvents = Option.getOrElse(
317 resolveOptionPrecedence(
318 normalizedFlags.logWebSocketEvents,
319 Option.fromUndefinedOr(env.logWebSocketEvents),
320 ),
321 () => Boolean(devUrl),
322 );
323 const tailscaleServeEnabled = Option.getOrElse(
324 resolveOptionPrecedence(
325 normalizedFlags.tailscaleServeEnabled,
326 Option.fromUndefinedOr(env.tailscaleServeEnabled),
327 Option.fromUndefinedOr(bootstrap?.tailscaleServeEnabled),
328 ),
329 () => false,
330 );
331 const tailscaleServePort = Option.getOrElse(
332 resolveOptionPrecedence(
333 normalizedFlags.tailscaleServePort,
334 Option.fromUndefinedOr(env.tailscaleServePort),
335 Option.fromUndefinedOr(bootstrap?.tailscaleServePort),
336 ),
337 () => 443,
338 );
339 const staticDir = devUrl ? undefined : yield* ServerConfig.resolveStaticDir();
340 const host = Option.getOrElse(
341 resolveOptionPrecedence(
342 normalizedFlags.host,
343 Option.fromUndefinedOr(env.host),
344 Option.fromUndefinedOr(bootstrap?.host),
345 ),
346 () => (mode === "desktop" ? "127.0.0.1" : undefined),
347 );
348 const logLevel = Option.getOrElse(cliLogLevel, () => env.logLevel);
349​
350 const config: ServerConfig.ServerConfig["Service"] = {
351 logLevel,
352 traceMinLevel: env.traceMinLevel,
353 traceTimingEnabled: env.traceTimingEnabled,
354 traceBatchWindowMs: env.traceBatchWindowMs,
355 traceMaxBytes: env.traceMaxBytes,
356 traceMaxFiles: env.traceMaxFiles,
357 otlpTracesUrl:
358 env.otlpTracesUrl ??
359 bootstrap?.otlpTracesUrl ??
360 persistedObservabilitySettings.otlpTracesUrl,
361 otlpMetricsUrl:
362 env.otlpMetricsUrl ??
363 bootstrap?.otlpMetricsUrl ??
364 persistedObservabilitySettings.otlpMetricsUrl,
365 otlpExportIntervalMs: env.otlpExportIntervalMs,
366 otlpServiceName: env.otlpServiceName,
367 mode,
368 port,
369 cwd,
370 baseDir,
371 ...derivedPaths,
372 serverTracePath,
373 host,
374 staticDir,
375 devUrl,
376 devAllowedOrigins: env.devAllowedOrigins,
377 noBrowser,
378 startupPresentation,
379 desktopBootstrapToken,
380 desktopTelemetryFd,
381 desktopTelemetryControlFd,
382 resourceMonitorPath,
383 autoBootstrapProjectFromCwd,
384 logWebSocketEvents,
385 tailscaleServeEnabled,
386 tailscaleServePort,
387 };
388​
389 return config;
390 });
391​
392export const resolveCliAuthConfig = (
393 flags: CliAuthLocationFlags,
394 cliLogLevel: Option.Option<LogLevel.LogLevel>,
395) =>
396 resolveServerConfig(
397 {
398 mode: Option.none(),
399 port: Option.none(),
400 host: Option.none(),
401 baseDir: flags.baseDir,
402 cwd: Option.none(),
403 devUrl: flags.devUrl ?? Option.none(),
404 noBrowser: Option.none(),
405 bootstrapFd: Option.none(),
406 autoBootstrapProjectFromCwd: Option.none(),
407 logWebSocketEvents: Option.none(),
408 tailscaleServeEnabled: Option.none(),
409 tailscaleServePort: Option.none(),
410 },
411 cliLogLevel,
412 );
413​
414const DurationShorthandPattern = /^(?<value>\d+)(?<unit>ms|s|m|h|d|w)$/i;
415​
416const parseDurationInput = (value: string): Duration.Duration | null => {
417 const trimmed = value.trim();
418 if (trimmed.length === 0) return null;
419​
420 const shorthand = DurationShorthandPattern.exec(trimmed);
421 const normalizedInput = shorthand?.groups
422 ? (() => {
423 const amountText = shorthand.groups.value;
424 const unitText = shorthand.groups.unit;
425 if (typeof amountText !== "string" || typeof unitText !== "string") {
426 return null;
427 }
428​
429 const amount = Number.parseInt(amountText, 10);
430 if (!Number.isFinite(amount)) return null;
431​
432 switch (unitText.toLowerCase()) {
433 case "ms":
434 return `${amount} millis`;
435 case "s":
436 return `${amount} seconds`;
437 case "m":
438 return `${amount} minutes`;
439 case "h":
440 return `${amount} hours`;
441 case "d":
442 return `${amount} days`;
443 case "w":
444 return `${amount} weeks`;
445 default:
446 return null;
447 }
448 })()
449 : (trimmed as Duration.Input);
450​
451 if (normalizedInput === null) return null;
452​
453 const decoded = Duration.fromInput(normalizedInput as Duration.Input);
454 return Option.isSome(decoded) ? decoded.value : null;
455};
456​
457export const DurationFromString = Schema.String.pipe(
458 Schema.decodeTo(
459 Schema.Duration,
460 SchemaTransformation.transformOrFail({
461 decode: (value) => {
462 const duration = parseDurationInput(value);
463 if (duration !== null) {
464 return Effect.succeed(duration);
465 }
466 return Effect.fail(
467 new SchemaIssue.InvalidValue({
468 message: "Invalid duration. Use values like 5m, 1h, 30d, or 15 minutes.",
469 }),
470 );
471 },
472 encode: (duration) => Effect.succeed(Duration.format(duration)),
473 }),
474 ),
475);