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

config.test.ts

914 lines32.1 KB

1// @effect-diagnostics nodeBuiltinImport:off
2import * as NodeChildProcess from "node:child_process";
3import * as NodeEvents from "node:events";
4import * as NodeFS from "node:fs";
5import * as NodeOS from "node:os";
6​
7import { assert, expect, it } from "@effect/vitest";
8import * as ConfigProvider from "effect/ConfigProvider";
9import * as Effect from "effect/Effect";
10import * as FileSystem from "effect/FileSystem";
11import * as Layer from "effect/Layer";
12import * as Option from "effect/Option";
13import * as Path from "effect/Path";
14import * as Redacted from "effect/Redacted";
15import * as Result from "effect/Result";
16import * as Schema from "effect/Schema";
17​
18import {
19 DesktopBackendBootstrap,
20 type DesktopBackendBootstrap as DesktopBackendBootstrapValue,
21} from "@t3tools/contracts";
22import * as NetService from "@t3tools/shared/Net";
23import { DEFAULT_SIGNAL_EXPORT } from "@t3tools/shared/observability";
24import * as OtelEnvironment from "@t3tools/shared/otelEnvironment";
25import * as NodeServices from "@effect/platform-node/NodeServices";
26import * as HostProcess from "@t3tools/shared/HostProcess";
27import packageJson from "../../package.json" with { type: "json" };
28import { ServiceLauncherHostProcess } from "../cloud/serviceLauncherClient.ts";
29import {
30 SERVICE_LAUNCHER_CONTEXT_ENV,
31 SERVICE_LAUNCHER_PROTOCOL,
32} from "../cloud/serviceProtocol.ts";
33import { deriveServerPaths } from "../config.ts";
34import { resolveServerConfig } from "./config.ts";
35​
36const deriveExplicitServerPaths = (baseDir: string, devUrl: URL | undefined) =>
37 deriveServerPaths(baseDir, devUrl, { baseDirIsExplicit: true });
38​
39const minimalDesktopFlags = (baseDir: string) => ({
40 mode: Option.some("desktop" as const),
41 port: Option.some(4888),
42 host: Option.none<string>(),
43 baseDir: Option.some(baseDir),
44 cwd: Option.none<string>(),
45 devUrl: Option.none<URL>(),
46 noBrowser: Option.none<boolean>(),
47 bootstrapFd: Option.none<number>(),
48 autoBootstrapProjectFromCwd: Option.none<boolean>(),
49 logWebSocketEvents: Option.none<boolean>(),
50 tailscaleServeEnabled: Option.none<boolean>(),
51 tailscaleServePort: Option.none<number>(),
52});
53​
54const encodeDesktopBootstrap = Schema.encodeEffect(Schema.fromJsonString(DesktopBackendBootstrap));
55const encodeUnknownJson = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown));
56​
57const makeDesktopBootstrap = (
58 overrides: Partial<DesktopBackendBootstrapValue> = {},
59): DesktopBackendBootstrapValue => ({
60 mode: "desktop",
61 noBrowser: true,
62 port: 4888,
63 t3Home: "/tmp/t3-bootstrap-home",
64 host: "127.0.0.1",
65 desktopBootstrapToken: "desktop-bootstrap-token",
66 tailscaleServeEnabled: false,
67 tailscaleServePort: 443,
68 ...overrides,
69});
70​
71const liveProcess = Effect.acquireRelease(
72 Effect.promise(async () => {
73 const child = NodeChildProcess.spawn(process.execPath, ["-e", "process.stdin.resume()"], {
74 stdio: ["pipe", "ignore", "ignore"],
75 });
76 await NodeEvents.EventEmitter.once(child, "spawn");
77 return child;
78 }),
79 (child) =>
80 Effect.promise(async () => {
81 const exited = NodeEvents.EventEmitter.once(child, "exit");
82 child.kill();
83 await exited;
84 }),
85);
86​
87it.layer(NodeServices.layer)("cli config resolution", (it) => {
88 const defaultObservabilityConfig = {
89 traceMinLevel: "Info",
90 traceTimingEnabled: true,
91 traceBatchWindowMs: 1_000,
92 traceMaxBytes: 10 * 1024 * 1024,
93 traceMaxFiles: 10,
94 otlpTracesUrl: undefined,
95 otlpMetricsUrl: undefined,
96 otlpLogsUrl: undefined,
97 otlpTracesExport: DEFAULT_SIGNAL_EXPORT,
98 otlpMetricsExport: DEFAULT_SIGNAL_EXPORT,
99 otlpLogsExport: DEFAULT_SIGNAL_EXPORT,
100 otelEnvironment: OtelEnvironment.none,
101 devAllowedOrigins: [],
102 } as const;
103​
104 const openBootstrapFd = Effect.fn(function* (payload: DesktopBackendBootstrapValue) {
105 const fs = yield* FileSystem.FileSystem;
106 const filePath = yield* fs.makeTempFileScoped({ prefix: "t3-bootstrap-", suffix: ".ndjson" });
107 const encoded = yield* encodeDesktopBootstrap(payload);
108 yield* fs.writeFileString(filePath, `${encoded}\n`);
109 return yield* Effect.acquireRelease(
110 Effect.sync(() => NodeFS.openSync(filePath, "r")),
111 // Without a /proc or /dev/fd path to reopen, the reader consumes the fd
112 // itself (autoClose), so on Windows it is already closed here.
113 (fd) =>
114 Effect.sync(() => {
115 try {
116 NodeFS.closeSync(fd);
117 } catch (error) {
118 if ((error as NodeJS.ErrnoException).code !== "EBADF") throw error;
119 }
120 }),
121 );
122 });
123​
124 it.effect("keeps stale records and supervised startup out of the manual launch preflight", () =>
125 Effect.gen(function* () {
126 const fs = yield* FileSystem.FileSystem;
127 const path = yield* Path.Path;
128 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-cli-preflight-" });
129 const child = yield* liveProcess;
130 assert(child.pid !== undefined);
131 for (const [name, pid, mode, rejectRunningServer] of [
132 ["stale", 2_147_483_647, "web", true],
133 ["own-pid", process.pid, "web", true],
134 ["desktop", child.pid, "desktop", true],
135 ["serve", child.pid, "web", false],
136 ] as const) {
137 const baseDir = path.join(root, name);
138 const stateDir = path.join(baseDir, "userdata");
139 yield* fs.makeDirectory(stateDir, { recursive: true });
140 yield* fs.writeFileString(
141 path.join(stateDir, "server-runtime.json"),
142 yield* encodeUnknownJson({
143 version: 1,
144 pid,
145 port: 3773,
146 origin: "http://127.0.0.1:3773",
147 startedAt: "2026-10-01T00:00:00.000Z",
148 }),
149 );
150 const cwd = path.join(root, `${name}-project`);
151 const configResult = yield* resolveServerConfig(
152 {
153 ...minimalWebFlags(baseDir),
154 mode: Option.some(mode),
155 port: Option.some(8788),
156 cwd: Option.some(cwd),
157 },
158 Option.none(),
159 { rejectRunningServer },
160 ).pipe(
161 Effect.provide(
162 Layer.merge(
163 NetService.layer,
164 ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} })),
165 ),
166 ),
167 Effect.result,
168 );
169 assert(Result.isSuccess(configResult));
170 expect(configResult.success.cwd).toBe(cwd);
171 expect(yield* fs.exists(cwd)).toBe(true);
172 }
173 }),
174 );
175​
176 it.effect(
177 "refuses a manual web launch when a runtime record belongs to another live process",
178 () =>
179 Effect.gen(function* () {
180 const fs = yield* FileSystem.FileSystem;
181 const path = yield* Path.Path;
182 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-cli-preflight-live-" });
183 const child = yield* liveProcess;
184 assert(child.pid !== undefined);
185 const stateDir = path.join(baseDir, "userdata");
186 yield* fs.makeDirectory(stateDir, { recursive: true });
187 yield* fs.writeFileString(
188 path.join(stateDir, "server-runtime.json"),
189 yield* encodeUnknownJson({
190 version: 1,
191 pid: child.pid,
192 port: 3773,
193 origin: "http://127.0.0.1:3773",
194 startedAt: "2026-10-01T00:00:00.000Z",
195 }),
196 );
197 const cwd = path.join(baseDir, "project");
198 const error = yield* resolveServerConfig(
199 { ...minimalWebFlags(baseDir), cwd: Option.some(cwd) },
200 Option.none(),
201 { rejectRunningServer: true },
202 ).pipe(
203 Effect.provide(
204 Layer.merge(
205 NetService.layer,
206 ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} })),
207 ),
208 ),
209 Effect.flip,
210 );
211 expect(String(error)).toContain("A T3 Code server is already running");
212 expect(String(error)).toContain(`pid ${child.pid}`);
213 expect(yield* fs.exists(cwd)).toBe(false);
214 }),
215 );
216​
217 it.effect("enables a trimmed reusable auth token only for web dev mode", () =>
218 Effect.gen(function* () {
219 const baseDir = yield* FileSystem.FileSystem.pipe(
220 Effect.flatMap((fs) => fs.makeTempDirectoryScoped({ prefix: "t3-cli-dev-auth-" })),
221 );
222 const flags = {
223 mode: Option.some("web" as const),
224 port: Option.some(8788),
225 host: Option.none<string>(),
226 baseDir: Option.some(baseDir),
227 cwd: Option.none<string>(),
228 devUrl: Option.some(new URL("http://127.0.0.1:5173")),
229 noBrowser: Option.none<boolean>(),
230 bootstrapFd: Option.none<number>(),
231 autoBootstrapProjectFromCwd: Option.none<boolean>(),
232 logWebSocketEvents: Option.none<boolean>(),
233 tailscaleServeEnabled: Option.none<boolean>(),
234 tailscaleServePort: Option.none<number>(),
235 };
236 const layerConfig = ConfigProvider.layer(
237 ConfigProvider.fromEnv({
238 env: {
239 T3CODE_DEV_AUTH_TOKEN: " reusable-dev-auth-token-that-is-long-enough ",
240 },
241 }),
242 );
243 const web = yield* resolveServerConfig(flags, Option.none()).pipe(
244 Effect.provide(Layer.mergeAll(layerConfig, NetService.layer)),
245 );
246 const desktop = yield* resolveServerConfig(
247 { ...flags, mode: Option.some("desktop" as const) },
248 Option.none(),
249 ).pipe(Effect.provide(Layer.mergeAll(layerConfig, NetService.layer)));
250​
251 expect(web.devAuthToken).toBeDefined();
252 if (web.devAuthToken === undefined) {
253 return yield* Effect.die("Expected reusable dev auth token.");
254 }
255 expect(Redacted.value(web.devAuthToken)).toBe("reusable-dev-auth-token-that-is-long-enough");
256 expect(desktop.devAuthToken).toBeUndefined();
257 }),
258 );
259​
260 it.effect("does not expose an invalid reusable auth token", () =>
261 Effect.gen(function* () {
262 const secret = "short-secret";
263 const baseDir = yield* FileSystem.FileSystem.pipe(
264 Effect.flatMap((fs) => fs.makeTempDirectoryScoped({ prefix: "t3-cli-dev-auth-invalid-" })),
265 );
266 const flags = {
267 mode: Option.some("web" as const),
268 port: Option.some(8788),
269 host: Option.none<string>(),
270 baseDir: Option.some(baseDir),
271 cwd: Option.none<string>(),
272 devUrl: Option.some(new URL("http://127.0.0.1:5173")),
273 noBrowser: Option.none<boolean>(),
274 bootstrapFd: Option.none<number>(),
275 autoBootstrapProjectFromCwd: Option.none<boolean>(),
276 logWebSocketEvents: Option.none<boolean>(),
277 tailscaleServeEnabled: Option.none<boolean>(),
278 tailscaleServePort: Option.none<number>(),
279 };
280 const layerConfig = ConfigProvider.layer(
281 ConfigProvider.fromEnv({ env: { T3CODE_DEV_AUTH_TOKEN: secret } }),
282 );
283 const error = yield* resolveServerConfig(flags, Option.none()).pipe(
284 Effect.provide(Layer.mergeAll(layerConfig, NetService.layer)),
285 Effect.flip,
286 );
287 const desktop = yield* resolveServerConfig(
288 { ...flags, mode: Option.some("desktop" as const) },
289 Option.none(),
290 ).pipe(Effect.provide(Layer.mergeAll(layerConfig, NetService.layer)));
291 const staticWeb = yield* resolveServerConfig(
292 { ...flags, devUrl: Option.none() },
293 Option.none(),
294 ).pipe(Effect.provide(Layer.mergeAll(layerConfig, NetService.layer)));
295​
296 expect(String(error)).not.toContain(secret);
297 const serialized = yield* encodeUnknownJson(error);
298 expect(serialized).not.toContain(secret);
299 expect(desktop.devAuthToken).toBeUndefined();
300 expect(staticWeb.devAuthToken).toBeUndefined();
301 }),
302 );
303​
304 it.effect("preserves explicit false CLI boolean flags over env and bootstrap values", () =>
305 Effect.gen(function* () {
306 const { join } = yield* Path.Path;
307 const baseDir = join(NodeOS.tmpdir(), "t3-cli-config-false-flags");
308 const fd = yield* openBootstrapFd(
309 makeDesktopBootstrap({
310 noBrowser: true,
311 tailscaleServeEnabled: false,
312 tailscaleServePort: 443,
313 }),
314 );
315 const derivedPaths = yield* deriveExplicitServerPaths(
316 baseDir,
317 new URL("http://127.0.0.1:4173"),
318 );
319​
320 const resolved = yield* resolveServerConfig(
321 {
322 mode: Option.some("web"),
323 port: Option.some(8788),
324 host: Option.some("127.0.0.1"),
325 baseDir: Option.some(baseDir),
326 cwd: Option.none(),
327 devUrl: Option.some(new URL("http://127.0.0.1:4173")),
328 noBrowser: Option.some(false),
329 bootstrapFd: Option.none(),
330 autoBootstrapProjectFromCwd: Option.some(false),
331 logWebSocketEvents: Option.some(false),
332 tailscaleServeEnabled: Option.none(),
333 tailscaleServePort: Option.none(),
334 },
335 Option.none(),
336 ).pipe(
337 Effect.provide(
338 Layer.mergeAll(
339 ConfigProvider.layer(
340 ConfigProvider.fromEnv({
341 env: {
342 T3CODE_BOOTSTRAP_FD: String(fd),
343 T3CODE_NO_BROWSER: "true",
344 T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "true",
345 T3CODE_LOG_WS_EVENTS: "true",
346 },
347 }),
348 ),
349 NetService.layer,
350 ),
351 ),
352 );
353​
354 expect(resolved).toEqual({
355 logLevel: "Info",
356 ...defaultObservabilityConfig,
357 mode: "web",
358 port: 8788,
359 cwd: process.cwd(),
360 baseDir,
361 ...derivedPaths,
362 host: "127.0.0.1",
363 staticDir: undefined,
364 devUrl: new URL("http://127.0.0.1:4173"),
365 noBrowser: false,
366 startupPresentation: "browser",
367 desktopBootstrapToken: "desktop-bootstrap-token",
368 autoBootstrapProjectFromCwd: false,
369 logWebSocketEvents: false,
370 tailscaleServeEnabled: false,
371 tailscaleServePort: 443,
372 });
373 }),
374 );
375​
376 it.effect("applies flag then env precedence over bootstrap envelope values", () =>
377 Effect.gen(function* () {
378 const { join } = yield* Path.Path;
379 const baseDir = join(NodeOS.tmpdir(), "t3-cli-config-env-wins");
380 const fd = yield* openBootstrapFd(
381 makeDesktopBootstrap({
382 port: 4888,
383 host: "127.0.0.2",
384 t3Home: "/tmp/t3-bootstrap-home",
385 noBrowser: false,
386 desktopBootstrapToken: "desktop-token",
387 tailscaleServeEnabled: false,
388 tailscaleServePort: 443,
389 }),
390 );
391 const derivedPaths = yield* deriveExplicitServerPaths(
392 baseDir,
393 new URL("http://127.0.0.1:4173"),
394 );
395​
396 const resolved = yield* resolveServerConfig(
397 {
398 mode: Option.none(),
399 port: Option.some(8788),
400 host: Option.some("127.0.0.1"),
401 baseDir: Option.none(),
402 cwd: Option.none(),
403 devUrl: Option.some(new URL("http://127.0.0.1:4173")),
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 Option.some("Debug"),
412 ).pipe(
413 Effect.provide(
414 Layer.mergeAll(
415 ConfigProvider.layer(
416 ConfigProvider.fromEnv({
417 env: {
418 T3CODE_MODE: "web",
419 T3CODE_BOOTSTRAP_FD: String(fd),
420 T3CODE_HOME: baseDir,
421 T3CODE_NO_BROWSER: "true",
422 T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "true",
423 T3CODE_LOG_WS_EVENTS: "true",
424 },
425 }),
426 ),
427 NetService.layer,
428 ),
429 ),
430 );
431​
432 expect(resolved).toEqual({
433 logLevel: "Debug",
434 ...defaultObservabilityConfig,
435 mode: "web",
436 port: 8788,
437 cwd: process.cwd(),
438 baseDir,
439 ...derivedPaths,
440 host: "127.0.0.1",
441 staticDir: undefined,
442 devUrl: new URL("http://127.0.0.1:4173"),
443 noBrowser: true,
444 startupPresentation: "browser",
445 desktopBootstrapToken: "desktop-token",
446 autoBootstrapProjectFromCwd: true,
447 logWebSocketEvents: true,
448 tailscaleServeEnabled: false,
449 tailscaleServePort: 443,
450 });
451 }),
452 );
453​
454 it.effect("reports the desktop bootstrap as the source of endpoints it supplied", () =>
455 Effect.gen(function* () {
456 const fs = yield* FileSystem.FileSystem;
457 const baseDir = yield* fs.makeTempDirectoryScoped({
458 prefix: "t3-cli-config-otlp-bootstrap-",
459 });
460 const fd = yield* openBootstrapFd(
461 makeDesktopBootstrap({
462 otlpTracesUrl: "http://localhost:4318/v1/traces",
463 otlpMetricsUrl: "http://localhost:4318/v1/metrics",
464 otlpLogsUrl: "http://localhost:4318/v1/logs",
465 }),
466 );
467​
468 const resolved = yield* resolveServerConfig(
469 { ...minimalDesktopFlags(baseDir), bootstrapFd: Option.some(fd) },
470 Option.none(),
471 ).pipe(
472 Effect.provide(
473 Layer.mergeAll(
474 ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} })),
475 NetService.layer,
476 ),
477 ),
478 );
479​
480 expect(resolved).toMatchObject({
481 otlpTracesUrl: "http://localhost:4318/v1/traces",
482 otlpTracesSource: "bootstrap",
483 otlpMetricsSource: "bootstrap",
484 otlpLogsSource: "bootstrap",
485 });
486 }),
487 );
488​
489 it.effect("reports saved settings as the source of endpoints read from settings.json", () =>
490 Effect.gen(function* () {
491 const fs = yield* FileSystem.FileSystem;
492 const path = yield* Path.Path;
493 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-cli-config-otlp-settings-" });
494 const derivedPaths = yield* deriveExplicitServerPaths(baseDir, undefined);
495 yield* fs.makeDirectory(path.dirname(derivedPaths.settingsPath), { recursive: true });
496 yield* fs.writeFileString(
497 derivedPaths.settingsPath,
498 `${JSON.stringify({
499 observability: {
500 otlpTracesUrl: "http://localhost:4318/v1/traces",
501 otlpMetricsUrl: "http://localhost:4318/v1/metrics",
502 otlpLogsUrl: "http://localhost:4318/v1/logs",
503 },
504 })}\n`,
505 );
506​
507 const resolved = yield* resolveServerConfig(minimalDesktopFlags(baseDir), Option.none()).pipe(
508 Effect.provide(
509 Layer.mergeAll(
510 ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} })),
511 NetService.layer,
512 ),
513 ),
514 );
515​
516 expect(resolved).toMatchObject({
517 otlpTracesUrl: "http://localhost:4318/v1/traces",
518 otlpTracesSource: "settings",
519 otlpMetricsSource: "settings",
520 otlpLogsSource: "settings",
521 });
522 }),
523 );
524​
525 it.effect("zeroes an endpoint stored in Settings when the SDK is disabled", () =>
526 Effect.gen(function* () {
527 const fs = yield* FileSystem.FileSystem;
528 const path = yield* Path.Path;
529 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-cli-config-otel-off-" });
530 const derivedPaths = yield* deriveExplicitServerPaths(baseDir, undefined);
531 yield* fs.makeDirectory(path.dirname(derivedPaths.settingsPath), { recursive: true });
532 yield* fs.writeFileString(
533 derivedPaths.settingsPath,
534 `${JSON.stringify({
535 observability: {
536 otlpTracesUrl: "http://localhost:4318/v1/traces",
537 otlpMetricsUrl: "http://localhost:4318/v1/metrics",
538 otlpLogsUrl: "http://localhost:4318/v1/logs",
539 },
540 })}\n`,
541 );
542​
543 const resolved = yield* resolveServerConfig(
544 {
545 mode: Option.some("desktop"),
546 port: Option.some(4888),
547 host: Option.none(),
548 baseDir: Option.some(baseDir),
549 cwd: Option.none(),
550 devUrl: Option.none(),
551 noBrowser: Option.none(),
552 bootstrapFd: Option.none(),
553 autoBootstrapProjectFromCwd: Option.none(),
554 logWebSocketEvents: Option.none(),
555 tailscaleServeEnabled: Option.none(),
556 tailscaleServePort: Option.none(),
557 },
558 Option.none(),
559 ).pipe(
560 Effect.provide(
561 Layer.mergeAll(
562 ConfigProvider.layer(ConfigProvider.fromEnv({ env: { OTEL_SDK_DISABLED: "true" } })),
563 NetService.layer,
564 ),
565 ),
566 );
567​
568 expect(resolved.otlpTracesUrl).toBeUndefined();
569 expect(resolved.otlpMetricsUrl).toBeUndefined();
570 expect(resolved.otlpLogsUrl).toBeUndefined();
571 expect(resolved.otelEnvironment.disabled).toBe(true);
572 }),
573 );
574​
575 it.effect("lets T3CODE_OTEL_SDK_DISABLED=false override an ambient OTEL_SDK_DISABLED=true", () =>
576 Effect.gen(function* () {
577 const fs = yield* FileSystem.FileSystem;
578 const path = yield* Path.Path;
579 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-cli-config-otel-on-" });
580 const derivedPaths = yield* deriveExplicitServerPaths(baseDir, undefined);
581 yield* fs.makeDirectory(path.dirname(derivedPaths.settingsPath), { recursive: true });
582 yield* fs.writeFileString(
583 derivedPaths.settingsPath,
584 `${JSON.stringify({
585 observability: {
586 otlpTracesUrl: "http://localhost:4318/v1/traces",
587 },
588 })}\n`,
589 );
590​
591 const resolved = yield* resolveServerConfig(
592 {
593 mode: Option.some("desktop"),
594 port: Option.some(4888),
595 host: Option.none(),
596 baseDir: Option.some(baseDir),
597 cwd: Option.none(),
598 devUrl: Option.none(),
599 noBrowser: Option.none(),
600 bootstrapFd: Option.none(),
601 autoBootstrapProjectFromCwd: Option.none(),
602 logWebSocketEvents: Option.none(),
603 tailscaleServeEnabled: Option.none(),
604 tailscaleServePort: Option.none(),
605 },
606 Option.none(),
607 ).pipe(
608 Effect.provide(
609 Layer.mergeAll(
610 ConfigProvider.layer(
611 ConfigProvider.fromEnv({
612 env: { T3CODE_OTEL_SDK_DISABLED: "false", OTEL_SDK_DISABLED: "true" },
613 }),
614 ),
615 NetService.layer,
616 ),
617 ),
618 );
619​
620 expect(resolved.otelEnvironment.disabled).toBe(false);
621 expect(resolved.otlpTracesUrl).toBe("http://localhost:4318/v1/traces");
622 }),
623 );
624​
625 it.effect("forces noBrowser and disables auto-bootstrap for headless startup presentation", () =>
626 Effect.gen(function* () {
627 const { join } = yield* Path.Path;
628 const baseDir = join(NodeOS.tmpdir(), "t3-cli-config-headless-base");
629 const derivedPaths = yield* deriveExplicitServerPaths(baseDir, undefined);
630​
631 const resolved = yield* resolveServerConfig(
632 {
633 mode: Option.some("web"),
634 port: Option.some(3773),
635 host: Option.none(),
636 baseDir: Option.some(baseDir),
637 cwd: Option.none(),
638 devUrl: Option.none(),
639 noBrowser: Option.none(),
640 bootstrapFd: Option.none(),
641 autoBootstrapProjectFromCwd: Option.none(),
642 logWebSocketEvents: Option.none(),
643 tailscaleServeEnabled: Option.none(),
644 tailscaleServePort: Option.none(),
645 },
646 Option.none(),
647 {
648 startupPresentation: "headless",
649 },
650 ).pipe(
651 Effect.provide(
652 Layer.mergeAll(
653 ConfigProvider.layer(
654 ConfigProvider.fromEnv({
655 env: {
656 T3CODE_NO_BROWSER: "false",
657 T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "true",
658 },
659 }),
660 ),
661 NetService.layer,
662 ),
663 ),
664 );
665​
666 expect(resolved).toEqual({
667 logLevel: "Info",
668 ...defaultObservabilityConfig,
669 mode: "web",
670 port: 3773,
671 cwd: process.cwd(),
672 baseDir,
673 ...derivedPaths,
674 host: undefined,
675 staticDir: resolved.staticDir,
676 devUrl: undefined,
677 noBrowser: true,
678 startupPresentation: "headless",
679 desktopBootstrapToken: undefined,
680 autoBootstrapProjectFromCwd: false,
681 logWebSocketEvents: false,
682 tailscaleServeEnabled: false,
683 tailscaleServePort: 443,
684 });
685 }),
686 );
687​
688 it.effect("keeps whitespace-separated pairs and literal equals signs in OTLP headers", () =>
689 Effect.gen(function* () {
690 const { join } = yield* Path.Path;
691 const baseDir = join(NodeOS.tmpdir(), "t3-cli-config-otlp-headers-loose-base");
692​
693 const resolved = yield* resolveServerConfig(
694 {
695 mode: Option.some("web"),
696 port: Option.some(3773),
697 host: Option.none(),
698 baseDir: Option.some(baseDir),
699 cwd: Option.none(),
700 devUrl: Option.none(),
701 noBrowser: Option.none(),
702 bootstrapFd: Option.none(),
703 autoBootstrapProjectFromCwd: Option.none(),
704 logWebSocketEvents: Option.none(),
705 tailscaleServeEnabled: Option.none(),
706 tailscaleServePort: Option.none(),
707 },
708 Option.none(),
709 ).pipe(
710 Effect.provide(
711 Layer.mergeAll(
712 ConfigProvider.layer(
713 ConfigProvider.fromEnv({
714 env: {
715 T3CODE_OTLP_HEADERS: "authorization=Bearer abc==, x-tenant=t3",
716 T3CODE_OTLP_TRACES_URL: "http://collector.internal:4318",
717 },
718 }),
719 ),
720 NetService.layer,
721 ),
722 ),
723 );
724​
725 expect(resolved.otlpTracesExport.headers).toEqual({
726 authorization: "Bearer abc==",
727 "x-tenant": "t3",
728 });
729 expect(resolved.otlpTracesUrl).toBe("http://collector.internal:4318");
730 }),
731 );
732​
733 const minimalWebFlags = (baseDir: string) => ({
734 mode: Option.some("web" as const),
735 port: Option.some(3773),
736 host: Option.none<string>(),
737 baseDir: Option.some(baseDir),
738 cwd: Option.none<string>(),
739 devUrl: Option.none<URL>(),
740 noBrowser: Option.none<boolean>(),
741 bootstrapFd: Option.none<number>(),
742 autoBootstrapProjectFromCwd: Option.none<boolean>(),
743 logWebSocketEvents: Option.none<boolean>(),
744 tailscaleServeEnabled: Option.none<boolean>(),
745 tailscaleServePort: Option.none<number>(),
746 });
747​
748 it.effect(
749 "resolves each signal's endpoint through T3CODE_OTLP_*_URL, an OTEL endpoint, the bootstrap envelope, and persisted Settings, in that order",
750 () =>
751 Effect.gen(function* () {
752 const fs = yield* FileSystem.FileSystem;
753 const path = yield* Path.Path;
754 const baseDir = yield* fs.makeTempDirectoryScoped({
755 prefix: "t3-cli-config-otel-precedence-",
756 });
757 const derivedPaths = yield* deriveExplicitServerPaths(baseDir, undefined);
758 yield* fs.makeDirectory(path.dirname(derivedPaths.settingsPath), { recursive: true });
759 yield* fs.writeFileString(
760 derivedPaths.settingsPath,
761 `${JSON.stringify({ observability: { otlpLogsUrl: "http://settings:4318/v1/logs" } })}\n`,
762 );
763​
764 const fd = yield* openBootstrapFd(
765 makeDesktopBootstrap({
766 otlpMetricsUrl: "http://bootstrap:4318/v1/metrics",
767 otlpLogsUrl: "",
768 }),
769 );
770​
771 const resolved = yield* resolveServerConfig(
772 {
773 ...minimalWebFlags(baseDir),
774 mode: Option.some("desktop"),
775 port: Option.some(4888),
776 bootstrapFd: Option.some(fd),
777 },
778 Option.none(),
779 ).pipe(
780 Effect.provide(
781 Layer.mergeAll(
782 ConfigProvider.layer(
783 ConfigProvider.fromEnv({
784 env: {
785 T3CODE_OTLP_TRACES_URL: "http://t3:4318/v1/traces",
786 T3CODE_OTLP_HEADERS: "x-key=secret",
787 OTEL_EXPORTER_OTLP_TRACES_ENDPOINT: "http://otel-traces:4318/custom",
788 OTEL_EXPORTER_OTLP_METRICS_ENDPOINT: "http://otel-metrics:4318/custom",
789 OTEL_EXPORTER_OTLP_HEADERS: "x-key=otel",
790 },
791 }),
792 ),
793 NetService.layer,
794 ),
795 ),
796 );
797​
798 expect(resolved.otlpTracesUrl).toBe("http://t3:4318/v1/traces");
799 expect(resolved.otlpTracesExport.headers).toEqual({ "x-key": "secret" });
800 expect(resolved.otlpMetricsUrl).toBe("http://otel-metrics:4318/custom");
801 expect(resolved.otlpMetricsExport).toEqual({
802 ...DEFAULT_SIGNAL_EXPORT,
803 protocol: "http/protobuf",
804 headers: { "x-key": "otel" },
805 });
806 expect(resolved.otlpLogsUrl).toBe("http://settings:4318/v1/logs");
807 expect(resolved.otlpLogsExport.headers).toEqual({ "x-key": "secret" });
808 expect(resolved).toMatchObject({
809 otlpTracesVariable: "T3CODE_OTLP_TRACES_URL",
810 otlpMetricsVariable: "OTEL_EXPORTER_OTLP_METRICS_ENDPOINT",
811 });
812 expect(resolved.otlpLogsVariable).toBeUndefined();
813 }),
814 );
815​
816 it.effect(
817 "exports nothing for a signal an OTEL endpoint claimed with a protocol or headers that do not read",
818 () =>
819 Effect.gen(function* () {
820 const fs = yield* FileSystem.FileSystem;
821 const path = yield* Path.Path;
822 const baseDir = yield* fs.makeTempDirectoryScoped({
823 prefix: "t3-cli-config-otel-off-",
824 });
825 const derivedPaths = yield* deriveExplicitServerPaths(baseDir, undefined);
826 yield* fs.makeDirectory(path.dirname(derivedPaths.settingsPath), { recursive: true });
827 yield* fs.writeFileString(
828 derivedPaths.settingsPath,
829 `${JSON.stringify({ observability: { otlpLogsUrl: "http://settings:4318/v1/logs" } })}\n`,
830 );
831​
832 const fd = yield* openBootstrapFd(
833 makeDesktopBootstrap({ otlpMetricsUrl: "http://bootstrap:4318/v1/metrics" }),
834 );
835​
836 const resolved = yield* resolveServerConfig(
837 {
838 ...minimalWebFlags(baseDir),
839 mode: Option.some("desktop"),
840 port: Option.some(4888),
841 bootstrapFd: Option.some(fd),
842 },
843 Option.none(),
844 ).pipe(
845 Effect.provide(
846 Layer.mergeAll(
847 ConfigProvider.layer(
848 ConfigProvider.fromEnv({
849 env: {
850 T3CODE_OTLP_TRACES_URL: "http://t3:4318/v1/traces",
851 OTEL_EXPORTER_OTLP_ENDPOINT: "http://otel:4318",
852 OTEL_EXPORTER_OTLP_HEADERS: "x-key=%zz",
853 },
854 }),
855 ),
856 NetService.layer,
857 ),
858 ),
859 );
860​
861 expect(resolved.otlpTracesUrl).toBe("http://t3:4318/v1/traces");
862 expect(resolved.otlpMetricsUrl).toBeUndefined();
863 expect(resolved.otlpLogsUrl).toBeUndefined();
864 }),
865 );
866​
867 it.effect("listens on private networks only under the service launcher with no host set", () =>
868 Effect.gen(function* () {
869 const { join } = yield* Path.Path;
870 const baseDir = join(NodeOS.tmpdir(), "t3-cli-config-service-host");
871 const resolveHost = (input: {
872 readonly connected: boolean;
873 readonly env?: Record<string, string>;
874 }) =>
875 resolveServerConfig(minimalWebFlags(baseDir), Option.none()).pipe(
876 Effect.map(({ host, privateNetworkOnly }) => ({ host, privateNetworkOnly })),
877 Effect.provide(
878 Layer.mergeAll(
879 ConfigProvider.layer(ConfigProvider.fromEnv({ env: input.env ?? {} })),
880 NetService.layer,
881 ),
882 ),
883 Effect.provideService(HostProcess.Environment, {
884 [SERVICE_LAUNCHER_CONTEXT_ENV]: JSON.stringify({
885 protocol: SERVICE_LAUNCHER_PROTOCOL,
886 childVersion: packageJson.version,
887 }),
888 }),
889 Effect.provideService(ServiceLauncherHostProcess, {
890 connected: input.connected,
891 send: () => false,
892 on: () => undefined,
893 off: () => undefined,
894 }),
895 );
896​
897 expect(yield* resolveHost({ connected: true })).toEqual({
898 host: "0.0.0.0",
899 privateNetworkOnly: true,
900 });
901 // `service.env` reaches the server as its environment.
902 expect(yield* resolveHost({ connected: true, env: { T3CODE_HOST: "127.0.0.1" } })).toEqual({
903 host: "127.0.0.1",
904 privateNetworkOnly: undefined,
905 });
906 // Without the launcher's IPC channel the context was inherited, e.g. by
907 // `t3 serve` started from an agent inside the service.
908 expect(yield* resolveHost({ connected: false })).toEqual({
909 host: undefined,
910 privateNetworkOnly: undefined,
911 });
912 }),
913 );
914});