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