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

config.ts

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