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

config.ts

461 lines16.6 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(200)),
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 noBrowser: Config.boolean("T3CODE_NO_BROWSER").pipe(
110 Config.option,
111 Config.map(Option.getOrUndefined),
112 ),
113 bootstrapFd: Config.int("T3CODE_BOOTSTRAP_FD").pipe(
114 Config.option,
115 Config.map(Option.getOrUndefined),
116 ),
117 autoBootstrapProjectFromCwd: Config.boolean("T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD").pipe(
118 Config.option,
119 Config.map(Option.getOrUndefined),
120 ),
121 logWebSocketEvents: Config.boolean("T3CODE_LOG_WS_EVENTS").pipe(
122 Config.option,
123 Config.map(Option.getOrUndefined),
124 ),
125 tailscaleServeEnabled: Config.boolean("T3CODE_TAILSCALE_SERVE").pipe(
126 Config.option,
127 Config.map(Option.getOrUndefined),
128 ),
129 tailscaleServePort: Config.port("T3CODE_TAILSCALE_SERVE_PORT").pipe(
130 Config.option,
131 Config.map(Option.getOrUndefined),
132 ),
133});
134​
135export interface CliServerFlags {
136 readonly mode: Option.Option<ServerConfig.RuntimeMode>;
137 readonly port: Option.Option<number>;
138 readonly host: Option.Option<string>;
139 readonly baseDir: Option.Option<string>;
140 readonly cwd: Option.Option<string>;
141 readonly devUrl: Option.Option<URL>;
142 readonly noBrowser: Option.Option<boolean>;
143 readonly bootstrapFd: Option.Option<number>;
144 readonly autoBootstrapProjectFromCwd: Option.Option<boolean>;
145 readonly logWebSocketEvents: Option.Option<boolean>;
146 readonly tailscaleServeEnabled: Option.Option<boolean>;
147 readonly tailscaleServePort: Option.Option<number>;
149​
150export interface CliAuthLocationFlags {
151 readonly baseDir: Option.Option<string>;
152 readonly devUrl?: Option.Option<URL>;
154​
155export const sharedServerLocationFlags = {
156 baseDir: baseDirFlag,
157 devUrl: devUrlFlag,
158} as const;
159​
160export const projectLocationFlags = {
161 baseDir: baseDirFlag,
162} as const;
163​
164export const sharedServerCommandFlags = {
165 mode: modeFlag,
166 port: portFlag,
167 host: hostFlag,
168 baseDir: baseDirFlag,
169 cwd: Argument.string("cwd").pipe(
170 Argument.withDescription(
171 "Working directory for provider sessions (defaults to the current directory).",
172 ),
173 Argument.optional,
174 ),
175 devUrl: devUrlFlag,
176 noBrowser: noBrowserFlag,
177 bootstrapFd: bootstrapFdFlag,
178 autoBootstrapProjectFromCwd: autoBootstrapProjectFromCwdFlag,
179 logWebSocketEvents: logWebSocketEventsFlag,
180 tailscaleServeEnabled: tailscaleServeFlag,
181 tailscaleServePort: tailscaleServePortFlag,
182} as const;
183​
184export const authLocationFlags = sharedServerLocationFlags;
185​
186const resolveOptionPrecedence = <Value>(
187 ...values: ReadonlyArray<Option.Option<Value>>
188): Option.Option<Value> => Option.firstSomeOf(values);
189​
190const loadPersistedObservabilitySettings = Effect.fn(function* (settingsPath: string) {
191 const fs = yield* FileSystem.FileSystem;
192 const exists = yield* fs.exists(settingsPath).pipe(Effect.orElseSucceed(() => false));
193 if (!exists) {
194 return { otlpTracesUrl: undefined, otlpMetricsUrl: undefined };
195 }
196​
197 const raw = yield* fs.readFileString(settingsPath).pipe(Effect.orElseSucceed(() => ""));
198 return parsePersistedServerObservabilitySettings(raw);
199});
200​
201export const resolveServerConfig = (
202 flags: CliServerFlags,
203 cliLogLevel: Option.Option<LogLevel.LogLevel>,
204 options?: {
205 readonly startupPresentation?: ServerConfig.StartupPresentation;
206 readonly forceAutoBootstrapProjectFromCwd?: boolean;
207 },
208) =>
209 Effect.gen(function* () {
210 const { findAvailablePort } = yield* NetService.NetService;
211 const path = yield* Path.Path;
212 const fs = yield* FileSystem.FileSystem;
213 const env = yield* EnvServerConfig;
214 const normalizedFlags = {
215 mode: flags.mode ?? Option.none(),
216 port: flags.port ?? Option.none(),
217 host: flags.host ?? Option.none(),
218 baseDir: flags.baseDir ?? Option.none(),
219 cwd: flags.cwd ?? Option.none(),
220 devUrl: flags.devUrl ?? Option.none(),
221 noBrowser: flags.noBrowser ?? Option.none(),
222 bootstrapFd: flags.bootstrapFd ?? Option.none(),
223 autoBootstrapProjectFromCwd: flags.autoBootstrapProjectFromCwd ?? Option.none(),
224 logWebSocketEvents: flags.logWebSocketEvents ?? Option.none(),
225 tailscaleServeEnabled: flags.tailscaleServeEnabled ?? Option.none(),
226 tailscaleServePort: flags.tailscaleServePort ?? Option.none(),
227 } satisfies CliServerFlags;
228 const bootstrapFd = Option.getOrUndefined(normalizedFlags.bootstrapFd) ?? env.bootstrapFd;
229 const bootstrapEnvelope =
230 bootstrapFd !== undefined
231 ? yield* readBootstrapEnvelope(DesktopBackendBootstrap, bootstrapFd)
232 : Option.none();
233 const bootstrap = Option.getOrUndefined(bootstrapEnvelope);
234​
235 const mode: ServerConfig.RuntimeMode = Option.getOrElse(
236 resolveOptionPrecedence(
237 normalizedFlags.mode,
238 Option.fromUndefinedOr(env.mode),
239 Option.fromUndefinedOr(bootstrap?.mode),
240 ),
241 () => "web",
242 );
243​
244 const port = yield* Option.match(
245 resolveOptionPrecedence(
246 normalizedFlags.port,
247 Option.fromUndefinedOr(env.port),
248 Option.fromUndefinedOr(bootstrap?.port),
249 ),
250 {
251 onSome: (value) => Effect.succeed(value),
252 onNone: () => {
253 if (mode === "desktop") {
254 return Effect.succeed(ServerConfig.DEFAULT_PORT);
255 }
256 return findAvailablePort(ServerConfig.DEFAULT_PORT);
257 },
258 },
259 );
260 const devUrl = Option.getOrElse(
261 resolveOptionPrecedence(normalizedFlags.devUrl, Option.fromUndefinedOr(env.devUrl)),
262 () => undefined,
263 );
264 const explicitBaseDir = resolveOptionPrecedence(
265 normalizedFlags.baseDir,
266 Option.fromUndefinedOr(env.t3Home),
267 ).pipe(Option.filter((value) => value.trim().length > 0));
268 const baseDir = yield* resolveBaseDir(
269 Option.getOrUndefined(
270 resolveOptionPrecedence(explicitBaseDir, Option.fromUndefinedOr(bootstrap?.t3Home)),
271 ),
272 );
273 const rawCwd = Option.getOrElse(normalizedFlags.cwd, () => process.cwd());
274 const cwd = path.resolve(yield* expandHomePath(rawCwd.trim()));
275 yield* fs.makeDirectory(cwd, { recursive: true });
276 const derivedPaths = yield* ServerConfig.deriveServerPaths(baseDir, devUrl, {
277 baseDirIsExplicit: Option.isSome(explicitBaseDir),
278 });
279 yield* ServerConfig.ensureServerDirectories(derivedPaths);
280 const persistedObservabilitySettings = yield* loadPersistedObservabilitySettings(
281 derivedPaths.settingsPath,
282 );
283 const serverTracePath = env.traceFile ?? derivedPaths.serverTracePath;
284 yield* fs.makeDirectory(path.dirname(serverTracePath), { recursive: true });
285 const startupPresentation = options?.startupPresentation ?? "browser";
286 const isHeadlessStartup = startupPresentation === "headless";
287 const noBrowser = Option.getOrElse(
288 resolveOptionPrecedence(
289 isHeadlessStartup ? Option.some(true) : Option.none(),
290 normalizedFlags.noBrowser,
291 Option.fromUndefinedOr(env.noBrowser),
292 Option.fromUndefinedOr(bootstrap?.noBrowser),
293 ),
294 () => mode === "desktop",
295 );
296 const desktopBootstrapToken = bootstrap?.desktopBootstrapToken;
297 const autoBootstrapProjectFromCwd = Option.getOrElse(
298 resolveOptionPrecedence(
299 Option.fromUndefinedOr(options?.forceAutoBootstrapProjectFromCwd),
300 isHeadlessStartup ? Option.some(false) : Option.none(),
301 normalizedFlags.autoBootstrapProjectFromCwd,
302 Option.fromUndefinedOr(env.autoBootstrapProjectFromCwd),
303 ),
304 () => mode === "web",
305 );
306 const logWebSocketEvents = Option.getOrElse(
307 resolveOptionPrecedence(
308 normalizedFlags.logWebSocketEvents,
309 Option.fromUndefinedOr(env.logWebSocketEvents),
310 ),
311 () => Boolean(devUrl),
312 );
313 const tailscaleServeEnabled = Option.getOrElse(
314 resolveOptionPrecedence(
315 normalizedFlags.tailscaleServeEnabled,
316 Option.fromUndefinedOr(env.tailscaleServeEnabled),
317 Option.fromUndefinedOr(bootstrap?.tailscaleServeEnabled),
318 ),
319 () => false,
320 );
321 const tailscaleServePort = Option.getOrElse(
322 resolveOptionPrecedence(
323 normalizedFlags.tailscaleServePort,
324 Option.fromUndefinedOr(env.tailscaleServePort),
325 Option.fromUndefinedOr(bootstrap?.tailscaleServePort),
326 ),
327 () => 443,
328 );
329 const staticDir = devUrl ? undefined : yield* ServerConfig.resolveStaticDir();
330 const host = Option.getOrElse(
331 resolveOptionPrecedence(
332 normalizedFlags.host,
333 Option.fromUndefinedOr(env.host),
334 Option.fromUndefinedOr(bootstrap?.host),
335 ),
336 () => (mode === "desktop" ? "127.0.0.1" : undefined),
337 );
338 const logLevel = Option.getOrElse(cliLogLevel, () => env.logLevel);
339​
340 const config: ServerConfig.ServerConfig["Service"] = {
341 logLevel,
342 traceMinLevel: env.traceMinLevel,
343 traceTimingEnabled: env.traceTimingEnabled,
344 traceBatchWindowMs: env.traceBatchWindowMs,
345 traceMaxBytes: env.traceMaxBytes,
346 traceMaxFiles: env.traceMaxFiles,
347 otlpTracesUrl:
348 env.otlpTracesUrl ??
349 bootstrap?.otlpTracesUrl ??
350 persistedObservabilitySettings.otlpTracesUrl,
351 otlpMetricsUrl:
352 env.otlpMetricsUrl ??
353 bootstrap?.otlpMetricsUrl ??
354 persistedObservabilitySettings.otlpMetricsUrl,
355 otlpExportIntervalMs: env.otlpExportIntervalMs,
356 otlpServiceName: env.otlpServiceName,
357 mode,
358 port,
359 cwd,
360 baseDir,
361 ...derivedPaths,
362 serverTracePath,
363 host,
364 staticDir,
365 devUrl,
366 noBrowser,
367 startupPresentation,
368 desktopBootstrapToken,
369 autoBootstrapProjectFromCwd,
370 logWebSocketEvents,
371 tailscaleServeEnabled,
372 tailscaleServePort,
373 };
374​
375 return config;
376 });
377​
378export const resolveCliAuthConfig = (
379 flags: CliAuthLocationFlags,
380 cliLogLevel: Option.Option<LogLevel.LogLevel>,
381) =>
382 resolveServerConfig(
383 {
384 mode: Option.none(),
385 port: Option.none(),
386 host: Option.none(),
387 baseDir: flags.baseDir,
388 cwd: Option.none(),
389 devUrl: flags.devUrl ?? Option.none(),
390 noBrowser: Option.none(),
391 bootstrapFd: Option.none(),
392 autoBootstrapProjectFromCwd: Option.none(),
393 logWebSocketEvents: Option.none(),
394 tailscaleServeEnabled: Option.none(),
395 tailscaleServePort: Option.none(),
396 },
397 cliLogLevel,
398 );
399​
400const DurationShorthandPattern = /^(?<value>\d+)(?<unit>ms|s|m|h|d|w)$/i;
401​
402const parseDurationInput = (value: string): Duration.Duration | null => {
403 const trimmed = value.trim();
404 if (trimmed.length === 0) return null;
405​
406 const shorthand = DurationShorthandPattern.exec(trimmed);
407 const normalizedInput = shorthand?.groups
408 ? (() => {
409 const amountText = shorthand.groups.value;
410 const unitText = shorthand.groups.unit;
411 if (typeof amountText !== "string" || typeof unitText !== "string") {
412 return null;
413 }
414​
415 const amount = Number.parseInt(amountText, 10);
416 if (!Number.isFinite(amount)) return null;
417​
418 switch (unitText.toLowerCase()) {
419 case "ms":
420 return `${amount} millis`;
421 case "s":
422 return `${amount} seconds`;
423 case "m":
424 return `${amount} minutes`;
425 case "h":
426 return `${amount} hours`;
427 case "d":
428 return `${amount} days`;
429 case "w":
430 return `${amount} weeks`;
431 default:
432 return null;
433 }
434 })()
435 : (trimmed as Duration.Input);
436​
437 if (normalizedInput === null) return null;
438​
439 const decoded = Duration.fromInput(normalizedInput as Duration.Input);
440 return Option.isSome(decoded) ? decoded.value : null;
441};
442​
443export const DurationFromString = Schema.String.pipe(
444 Schema.decodeTo(
445 Schema.Duration,
446 SchemaTransformation.transformOrFail({
447 decode: (value) => {
448 const duration = parseDurationInput(value);
449 if (duration !== null) {
450 return Effect.succeed(duration);
451 }
452 return Effect.fail(
453 new SchemaIssue.InvalidValue(Option.some(value), {
454 message: "Invalid duration. Use values like 5m, 1h, 30d, or 15 minutes.",
455 }),
456 );
457 },
458 encode: (duration) => Effect.succeed(Duration.format(duration)),
459 }),
460 ),
461);