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

config.test.ts

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