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

config.test.ts

1,138 lines40.7 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";
6import * as NodePath from "node:path";
7​
8import { assert, expect, it } from "@effect/vitest";
9import * as ConfigProvider from "effect/ConfigProvider";
10import * as Effect from "effect/Effect";
11import * as FileSystem from "effect/FileSystem";
12import * as Layer from "effect/Layer";
13import * as Option from "effect/Option";
14import * as Path from "effect/Path";
15import * as Redacted from "effect/Redacted";
16import * as Result from "effect/Result";
17import * as Schema from "effect/Schema";
18​
19import {
20 DesktopBackendBootstrap,
21 type DesktopBackendBootstrap as DesktopBackendBootstrapValue,
22} from "@t3tools/contracts";
23import * as NetService from "@t3tools/shared/Net";
24import { DEFAULT_SIGNAL_EXPORT } from "@t3tools/shared/observability";
25import * as OtelEnvironment from "@t3tools/shared/otelEnvironment";
26import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
27import * as NodeServices from "@effect/platform-node/NodeServices";
28import * as HostProcess from "@t3tools/shared/HostProcess";
29import packageJson from "../../package.json" with { type: "json" };
30import { ServiceLauncherHostProcess } from "../cloud/serviceLauncherClient.ts";
31import {
32 SERVICE_LAUNCHER_CONTEXT_ENV,
33 SERVICE_LAUNCHER_PROTOCOL,
34} from "../cloud/serviceProtocol.ts";
35import { deriveServerPaths } from "../config.ts";
36import * as ProcessRunner from "../processRunner.ts";
37import { acquireServerOwnership } from "../serverOwnership.ts";
38import { resolveServerConfig } from "./config.ts";
39​
40const deriveExplicitServerPaths = (baseDir: string, devUrl: URL | undefined) =>
41 deriveServerPaths(baseDir, devUrl, { baseDirIsExplicit: true });
42​
43const minimalDesktopFlags = (baseDir: string) => ({
44 mode: Option.some("desktop" as const),
45 port: Option.some(4888),
46 host: Option.none<string>(),
47 baseDir: Option.some(baseDir),
48 cwd: Option.none<string>(),
49 devUrl: Option.none<URL>(),
50 noBrowser: Option.none<boolean>(),
51 bootstrapFd: Option.none<number>(),
52 autoBootstrapProjectFromCwd: Option.none<boolean>(),
53 logWebSocketEvents: Option.none<boolean>(),
54 tailscaleServeEnabled: Option.none<boolean>(),
55 tailscaleServePort: Option.none<number>(),
56 lan: Option.none<boolean>(),
57});
58​
59const encodeDesktopBootstrap = Schema.encodeEffect(Schema.fromJsonString(DesktopBackendBootstrap));
60const encodeUnknownJson = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown));
61​
62const makeDesktopBootstrap = (
63 overrides: Partial<DesktopBackendBootstrapValue> = {},
64): DesktopBackendBootstrapValue => ({
65 mode: "desktop",
66 noBrowser: true,
67 port: 4888,
68 t3Home: "/tmp/t3-bootstrap-home",
69 host: "127.0.0.1",
70 desktopBootstrapToken: "desktop-bootstrap-token",
71 tailscaleServeEnabled: false,
72 tailscaleServePort: 443,
73 ...overrides,
74});
75​
76const liveProcess = Effect.acquireRelease(
77 Effect.promise(async () => {
78 const child = NodeChildProcess.spawn(process.execPath, ["-e", "process.stdin.resume()"], {
79 stdio: ["pipe", "ignore", "ignore"],
80 });
81 await NodeEvents.EventEmitter.once(child, "spawn");
82 return child;
83 }),
84 (child) =>
85 Effect.promise(async () => {
86 const exited = NodeEvents.EventEmitter.once(child, "exit");
87 child.kill();
88 await exited;
89 }),
90);
91​
92it.layer(NodeServices.layer)("cli config resolution", (it) => {
93 const defaultObservabilityConfig = {
94 traceMinLevel: "Info",
95 traceTimingEnabled: true,
96 traceBatchWindowMs: 1_000,
97 traceMaxBytes: 10 * 1024 * 1024,
98 traceMaxFiles: 10,
99 otlpTracesUrl: undefined,
100 otlpMetricsUrl: undefined,
101 otlpLogsUrl: undefined,
102 otlpTracesExport: DEFAULT_SIGNAL_EXPORT,
103 otlpMetricsExport: DEFAULT_SIGNAL_EXPORT,
104 otlpLogsExport: DEFAULT_SIGNAL_EXPORT,
105 otelEnvironment: OtelEnvironment.none,
106 devAllowedOrigins: [],
107 } as const;
108​
109 const openBootstrapFd = Effect.fn(function* (payload: DesktopBackendBootstrapValue) {
110 const fs = yield* FileSystem.FileSystem;
111 const filePath = yield* fs.makeTempFileScoped({ prefix: "t3-bootstrap-", suffix: ".ndjson" });
112 const encoded = yield* encodeDesktopBootstrap(payload);
113 yield* fs.writeFileString(filePath, `${encoded}\n`);
114 return yield* Effect.acquireRelease(
115 Effect.sync(() => NodeFS.openSync(filePath, "r")),
116 // Windows cannot reopen the fd through /proc or /dev/fd, so the reader closes it.
117 (fd) =>
118 Effect.sync(() => {
119 try {
120 NodeFS.closeSync(fd);
121 } catch (error) {
122 if ((error as NodeJS.ErrnoException).code !== "EBADF") throw error;
123 }
124 }),
125 );
126 });
127​
128 it.effect("keeps stale records and supervised startup out of the manual launch preflight", () =>
129 Effect.gen(function* () {
130 const fs = yield* FileSystem.FileSystem;
131 const path = yield* Path.Path;
132 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-cli-preflight-" });
133 const child = yield* liveProcess;
134 assert(child.pid !== undefined);
135 for (const [name, pid, mode, rejectRunningServer] of [
136 ["stale", 2_147_483_647, "web", true],
137 ["own-pid", process.pid, "web", true],
138 ["desktop", child.pid, "desktop", true],
139 ["serve", child.pid, "web", false],
140 ] as const) {
141 const baseDir = path.join(root, name);
142 const stateDir = path.join(baseDir, "userdata");
143 yield* fs.makeDirectory(stateDir, { recursive: true });
144 yield* fs.writeFileString(
145 path.join(stateDir, "server-runtime.json"),
146 yield* encodeUnknownJson({
147 version: 1,
148 pid,
149 port: 3773,
150 origin: "http://127.0.0.1:3773",
151 startedAt: "2026-10-01T00:00:00.000Z",
152 }),
153 );
154 const cwd = path.join(root, `${name}-project`);
155 const configResult = yield* resolveServerConfig(
156 {
157 ...minimalWebFlags(baseDir),
158 mode: Option.some(mode),
159 port: Option.some(8788),
160 cwd: Option.some(cwd),
161 },
162 Option.none(),
163 { rejectRunningServer },
164 ).pipe(
165 Effect.provide(
166 Layer.merge(
167 NetService.layer,
168 ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} })),
169 ),
170 ),
171 Effect.result,
172 );
173 assert(Result.isSuccess(configResult));
174 expect(configResult.success.cwd).toBe(cwd);
175 expect(yield* fs.exists(cwd)).toBe(true);
176 }
177 }),
178 );
179​
180 const acquireOwnership = (baseDir: string) =>
181 acquireServerOwnership(NodePath.join(baseDir, "userdata", "server-runtime.json")).pipe(
182 Effect.provide(Layer.merge(ProcessRunner.layer, NodeCrypto.layer)),
183 Effect.provideService(HostProcess.HomeDirectory, baseDir),
184 Effect.provideService(HostProcess.Environment, {}),
185 );
186​
187 const resolveManualWebLaunch = (baseDir: string, cwd: string) =>
188 resolveServerConfig({ ...minimalWebFlags(baseDir), cwd: Option.some(cwd) }, Option.none(), {
189 rejectRunningServer: true,
190 }).pipe(
191 Effect.provide(
192 Layer.merge(NetService.layer, ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} }))),
193 ),
194 Effect.mapError(String),
195 Effect.result,
196 );
197​
198 it.effect("keeps leading spaces only in a relative startup directory", () =>
199 Effect.gen(function* () {
200 const fs = yield* FileSystem.FileSystem;
201 const path = yield* Path.Path;
202 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-cli-cwd-spaces-" });
203 const resolveCwd = (cwd: string) =>
204 resolveServerConfig({ ...minimalWebFlags(baseDir), cwd: Option.some(cwd) }, Option.none(), {
205 prepareDirectories: false,
206 }).pipe(
207 Effect.provide(
208 Layer.merge(
209 NetService.layer,
210 ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} })),
211 ),
212 ),
213 Effect.map((config) => config.cwd),
214 );
215 expect(yield* resolveCwd(" project ")).toBe(path.resolve(" project"));
216 const absolute = path.join(baseDir, "project");
217 expect(yield* resolveCwd(` ${absolute} `)).toBe(absolute);
218 }),
219 );
220​
221 it.effect("refuses a manual web launch while a lock-aware server owns the T3 home", () =>
222 Effect.gen(function* () {
223 const fs = yield* FileSystem.FileSystem;
224 const path = yield* Path.Path;
225 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-cli-preflight-live-" });
226 const child = yield* liveProcess;
227 assert(child.pid !== undefined);
228 const owner = yield* acquireOwnership(baseDir);
229 yield* owner.publish({
230 version: 1,
231 pid: child.pid,
232 port: 3773,
233 origin: "http://127.0.0.1:3773",
234 startedAt: "2026-10-01T00:00:00.000Z",
235 });
236 const cwd = path.join(baseDir, "project");
237 const result = yield* resolveManualWebLaunch(baseDir, cwd);
238 assert(Result.isFailure(result));
239 expect(result.failure).toContain("A T3 Code server is already running");
240 expect(result.failure).toContain(`pid ${child.pid}`);
241 expect(yield* fs.exists(cwd)).toBe(false);
242 }),
243 );
244​
245 it.effect("refuses a manual web launch when a pre-lock record belongs to a live process", () =>
246 Effect.gen(function* () {
247 const fs = yield* FileSystem.FileSystem;
248 const path = yield* Path.Path;
249 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-cli-preflight-legacy-" });
250 const child = yield* liveProcess;
251 assert(child.pid !== undefined);
252 const stateDir = path.join(baseDir, "userdata");
253 yield* fs.makeDirectory(stateDir, { recursive: true });
254 yield* fs.writeFileString(
255 path.join(stateDir, "server-runtime.json"),
256 yield* encodeUnknownJson({
257 version: 1,
258 pid: child.pid,
259 port: 3773,
260 origin: "http://127.0.0.1:3773",
261 startedAt: "2026-10-01T00:00:00.000Z",
262 }),
263 );
264 const cwd = path.join(baseDir, "project");
265 const result = yield* resolveManualWebLaunch(baseDir, cwd);
266 assert(Result.isFailure(result));
267 expect(result.failure).toContain(`pid ${child.pid}`);
268 expect(yield* fs.exists(cwd)).toBe(false);
269 }),
270 );
271​
272 it.effect(
273 "allows a manual web launch when a lock-aware record's PID was reused by an unrelated process",
274 () =>
275 Effect.gen(function* () {
276 const fs = yield* FileSystem.FileSystem;
277 const path = yield* Path.Path;
278 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-cli-preflight-reused-" });
279 const child = yield* liveProcess;
280 assert(child.pid !== undefined);
281 // The killed server's lock file stays behind, released.
282 yield* Effect.scoped(acquireOwnership(baseDir));
283 yield* fs.writeFileString(
284 path.join(baseDir, "userdata", "server-runtime.json"),
285 yield* encodeUnknownJson({
286 version: 1,
287 pid: child.pid,
288 ownerId: "4ec9f94a-0000-4000-8000-000000000000",
289 port: 3773,
290 origin: "http://127.0.0.1:3773",
291 startedAt: "2026-10-01T00:00:00.000Z",
292 }),
293 );
294 const cwd = path.join(baseDir, "project");
295 const result = yield* resolveManualWebLaunch(baseDir, cwd);
296 expect(result).toEqual(Result.succeed(expect.objectContaining({ cwd })));
297 }),
298 );
299​
300 it.effect("names the pair command for the refused server's home", () =>
301 Effect.gen(function* () {
302 const fs = yield* FileSystem.FileSystem;
303 const path = yield* Path.Path;
304 const child = yield* liveProcess;
305 assert(child.pid !== undefined);
306 for (const source of ["flag", "T3CODE_HOME", "default"] as const) {
307 const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-cli-preflight-pair-" });
308 const baseDir = source === "default" ? path.join(home, ".t3") : home;
309 const stateDir = path.join(baseDir, "userdata");
310 yield* fs.makeDirectory(stateDir, { recursive: true });
311 yield* fs.writeFileString(
312 path.join(stateDir, "server-runtime.json"),
313 yield* encodeUnknownJson({
314 version: 1,
315 pid: child.pid,
316 port: 3773,
317 origin: "http://127.0.0.1:3773",
318 startedAt: "2026-10-01T00:00:00.000Z",
319 }),
320 );
321 const error = yield* resolveServerConfig(
322 {
323 ...minimalWebFlags(baseDir),
324 baseDir: source === "flag" ? Option.some(baseDir) : Option.none(),
325 cwd: Option.some(path.join(home, "project")),
326 },
327 Option.none(),
328 { rejectRunningServer: true },
329 ).pipe(
330 Effect.provide(
331 Layer.merge(
332 NetService.layer,
333 ConfigProvider.layer(
334 ConfigProvider.fromEnv({
335 env: source === "T3CODE_HOME" ? { T3CODE_HOME: baseDir } : {},
336 }),
337 ),
338 ),
339 ),
340 Effect.provideService(HostProcess.HomeDirectory, home),
341 Effect.provideService(HostProcess.Platform, "linux"),
342 Effect.flip,
343 );
344 // A temp dir with spaces or backslashes is single-quoted for the shell.
345 const homePattern = baseDir.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
346 expect(String(error)).toMatch(
347 new RegExp(`pair --base-dir (${homePattern}|'${homePattern}')`),
348 );
349 }
350 }),
351 );
352​
353 it.effect("enables a trimmed reusable auth token only for web dev mode", () =>
354 Effect.gen(function* () {
355 const baseDir = yield* FileSystem.FileSystem.pipe(
356 Effect.flatMap((fs) => fs.makeTempDirectoryScoped({ prefix: "t3-cli-dev-auth-" })),
357 );
358 const flags = {
359 mode: Option.some("web" as const),
360 port: Option.some(8788),
361 host: Option.none<string>(),
362 baseDir: Option.some(baseDir),
363 cwd: Option.none<string>(),
364 devUrl: Option.some(new URL("http://127.0.0.1:5173")),
365 noBrowser: Option.none<boolean>(),
366 bootstrapFd: Option.none<number>(),
367 autoBootstrapProjectFromCwd: Option.none<boolean>(),
368 logWebSocketEvents: Option.none<boolean>(),
369 tailscaleServeEnabled: Option.none<boolean>(),
370 tailscaleServePort: Option.none<number>(),
371 lan: Option.none<boolean>(),
372 };
373 const layerConfig = ConfigProvider.layer(
374 ConfigProvider.fromEnv({
375 env: {
376 T3CODE_DEV_AUTH_TOKEN: " reusable-dev-auth-token-that-is-long-enough ",
377 },
378 }),
379 );
380 const web = yield* resolveServerConfig(flags, Option.none()).pipe(
381 Effect.provide(Layer.mergeAll(layerConfig, NetService.layer)),
382 );
383 const desktop = yield* resolveServerConfig(
384 { ...flags, mode: Option.some("desktop" as const) },
385 Option.none(),
386 ).pipe(Effect.provide(Layer.mergeAll(layerConfig, NetService.layer)));
387​
388 expect(web.devAuthToken).toBeDefined();
389 if (web.devAuthToken === undefined) {
390 return yield* Effect.die("Expected reusable dev auth token.");
391 }
392 expect(Redacted.value(web.devAuthToken)).toBe("reusable-dev-auth-token-that-is-long-enough");
393 expect(desktop.devAuthToken).toBeUndefined();
394 }),
395 );
396​
397 it.effect("does not expose an invalid reusable auth token", () =>
398 Effect.gen(function* () {
399 const secret = "short-secret";
400 const baseDir = yield* FileSystem.FileSystem.pipe(
401 Effect.flatMap((fs) => fs.makeTempDirectoryScoped({ prefix: "t3-cli-dev-auth-invalid-" })),
402 );
403 const flags = {
404 mode: Option.some("web" as const),
405 port: Option.some(8788),
406 host: Option.none<string>(),
407 baseDir: Option.some(baseDir),
408 cwd: Option.none<string>(),
409 devUrl: Option.some(new URL("http://127.0.0.1:5173")),
410 noBrowser: Option.none<boolean>(),
411 bootstrapFd: Option.none<number>(),
412 autoBootstrapProjectFromCwd: Option.none<boolean>(),
413 logWebSocketEvents: Option.none<boolean>(),
414 tailscaleServeEnabled: Option.none<boolean>(),
415 tailscaleServePort: Option.none<number>(),
416 lan: Option.none<boolean>(),
417 };
418 const layerConfig = ConfigProvider.layer(
419 ConfigProvider.fromEnv({ env: { T3CODE_DEV_AUTH_TOKEN: secret } }),
420 );
421 const error = yield* resolveServerConfig(flags, Option.none()).pipe(
422 Effect.provide(Layer.mergeAll(layerConfig, NetService.layer)),
423 Effect.flip,
424 );
425 const desktop = yield* resolveServerConfig(
426 { ...flags, mode: Option.some("desktop" as const) },
427 Option.none(),
428 ).pipe(Effect.provide(Layer.mergeAll(layerConfig, NetService.layer)));
429 const staticWeb = yield* resolveServerConfig(
430 { ...flags, devUrl: Option.none() },
431 Option.none(),
432 ).pipe(Effect.provide(Layer.mergeAll(layerConfig, NetService.layer)));
433​
434 expect(String(error)).not.toContain(secret);
435 const serialized = yield* encodeUnknownJson(error);
436 expect(serialized).not.toContain(secret);
437 expect(desktop.devAuthToken).toBeUndefined();
438 expect(staticWeb.devAuthToken).toBeUndefined();
439 }),
440 );
441​
442 it.effect("preserves explicit false CLI boolean flags over env and bootstrap values", () =>
443 Effect.gen(function* () {
444 const { join } = yield* Path.Path;
445 const baseDir = join(NodeOS.tmpdir(), "t3-cli-config-false-flags");
446 const fd = yield* openBootstrapFd(
447 makeDesktopBootstrap({
448 noBrowser: true,
449 tailscaleServeEnabled: false,
450 tailscaleServePort: 443,
451 }),
452 );
453 const derivedPaths = yield* deriveExplicitServerPaths(
454 baseDir,
455 new URL("http://127.0.0.1:4173"),
456 );
457​
458 const resolved = yield* resolveServerConfig(
459 {
460 mode: Option.some("web"),
461 port: Option.some(8788),
462 host: Option.some("127.0.0.1"),
463 baseDir: Option.some(baseDir),
464 cwd: Option.none(),
465 devUrl: Option.some(new URL("http://127.0.0.1:4173")),
466 noBrowser: Option.some(false),
467 bootstrapFd: Option.none(),
468 autoBootstrapProjectFromCwd: Option.some(false),
469 logWebSocketEvents: Option.some(false),
470 tailscaleServeEnabled: Option.none(),
471 tailscaleServePort: Option.none(),
472 lan: Option.none(),
473 },
474 Option.none(),
475 ).pipe(
476 Effect.provide(
477 Layer.mergeAll(
478 ConfigProvider.layer(
479 ConfigProvider.fromEnv({
480 env: {
481 T3CODE_BOOTSTRAP_FD: String(fd),
482 T3CODE_NO_BROWSER: "true",
483 T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "true",
484 T3CODE_LOG_WS_EVENTS: "true",
485 },
486 }),
487 ),
488 NetService.layer,
489 ),
490 ),
491 );
492​
493 expect(resolved).toEqual({
494 logLevel: "Info",
495 ...defaultObservabilityConfig,
496 mode: "web",
497 port: 8788,
498 cwd: process.cwd(),
499 baseDir,
500 ...derivedPaths,
501 host: "127.0.0.1",
502 staticDir: undefined,
503 devUrl: new URL("http://127.0.0.1:4173"),
504 noBrowser: false,
505 startupPresentation: "browser",
506 desktopBootstrapToken: "desktop-bootstrap-token",
507 autoBootstrapProjectFromCwd: false,
508 logWebSocketEvents: false,
509 tailscaleServeEnabled: false,
510 tailscaleServePort: 443,
511 });
512 }),
513 );
514​
515 it.effect("applies flag then env precedence over bootstrap envelope values", () =>
516 Effect.gen(function* () {
517 const { join } = yield* Path.Path;
518 const baseDir = join(NodeOS.tmpdir(), "t3-cli-config-env-wins");
519 const fd = yield* openBootstrapFd(
520 makeDesktopBootstrap({
521 port: 4888,
522 host: "127.0.0.2",
523 t3Home: "/tmp/t3-bootstrap-home",
524 noBrowser: false,
525 desktopBootstrapToken: "desktop-token",
526 tailscaleServeEnabled: false,
527 tailscaleServePort: 443,
528 }),
529 );
530 const derivedPaths = yield* deriveExplicitServerPaths(
531 baseDir,
532 new URL("http://127.0.0.1:4173"),
533 );
534​
535 const resolved = yield* resolveServerConfig(
536 {
537 mode: Option.none(),
538 port: Option.some(8788),
539 host: Option.some("127.0.0.1"),
540 baseDir: Option.none(),
541 cwd: Option.none(),
542 devUrl: Option.some(new URL("http://127.0.0.1:4173")),
543 noBrowser: Option.none(),
544 bootstrapFd: Option.none(),
545 autoBootstrapProjectFromCwd: Option.none(),
546 logWebSocketEvents: Option.none(),
547 tailscaleServeEnabled: Option.none(),
548 tailscaleServePort: Option.none(),
549 lan: Option.none(),
550 },
551 Option.some("Debug"),
552 ).pipe(
553 Effect.provide(
554 Layer.mergeAll(
555 ConfigProvider.layer(
556 ConfigProvider.fromEnv({
557 env: {
558 T3CODE_MODE: "web",
559 T3CODE_BOOTSTRAP_FD: String(fd),
560 T3CODE_HOME: baseDir,
561 T3CODE_NO_BROWSER: "true",
562 T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "true",
563 T3CODE_LOG_WS_EVENTS: "true",
564 },
565 }),
566 ),
567 NetService.layer,
568 ),
569 ),
570 );
571​
572 expect(resolved).toEqual({
573 logLevel: "Debug",
574 ...defaultObservabilityConfig,
575 mode: "web",
576 port: 8788,
577 cwd: process.cwd(),
578 baseDir,
579 ...derivedPaths,
580 host: "127.0.0.1",
581 staticDir: undefined,
582 devUrl: new URL("http://127.0.0.1:4173"),
583 noBrowser: true,
584 startupPresentation: "browser",
585 desktopBootstrapToken: "desktop-token",
586 autoBootstrapProjectFromCwd: true,
587 logWebSocketEvents: true,
588 tailscaleServeEnabled: false,
589 tailscaleServePort: 443,
590 });
591 }),
592 );
593​
594 it.effect("reports the desktop bootstrap as the source of endpoints it supplied", () =>
595 Effect.gen(function* () {
596 const fs = yield* FileSystem.FileSystem;
597 const baseDir = yield* fs.makeTempDirectoryScoped({
598 prefix: "t3-cli-config-otlp-bootstrap-",
599 });
600 const fd = yield* openBootstrapFd(
601 makeDesktopBootstrap({
602 otlpTracesUrl: "http://localhost:4318/v1/traces",
603 otlpMetricsUrl: "http://localhost:4318/v1/metrics",
604 otlpLogsUrl: "http://localhost:4318/v1/logs",
605 }),
606 );
607​
608 const resolved = yield* resolveServerConfig(
609 { ...minimalDesktopFlags(baseDir), bootstrapFd: Option.some(fd) },
610 Option.none(),
611 ).pipe(
612 Effect.provide(
613 Layer.mergeAll(
614 ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} })),
615 NetService.layer,
616 ),
617 ),
618 );
619​
620 expect(resolved).toMatchObject({
621 otlpTracesUrl: "http://localhost:4318/v1/traces",
622 otlpTracesSource: "bootstrap",
623 otlpMetricsSource: "bootstrap",
624 otlpLogsSource: "bootstrap",
625 });
626 }),
627 );
628​
629 it.effect("reports saved settings as the source of endpoints read from settings.json", () =>
630 Effect.gen(function* () {
631 const fs = yield* FileSystem.FileSystem;
632 const path = yield* Path.Path;
633 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-cli-config-otlp-settings-" });
634 const derivedPaths = yield* deriveExplicitServerPaths(baseDir, undefined);
635 yield* fs.makeDirectory(path.dirname(derivedPaths.settingsPath), { recursive: true });
636 yield* fs.writeFileString(
637 derivedPaths.settingsPath,
638 `${JSON.stringify({
639 observability: {
640 otlpTracesUrl: "http://localhost:4318/v1/traces",
641 otlpMetricsUrl: "http://localhost:4318/v1/metrics",
642 otlpLogsUrl: "http://localhost:4318/v1/logs",
643 },
644 })}\n`,
645 );
646​
647 const resolved = yield* resolveServerConfig(minimalDesktopFlags(baseDir), Option.none()).pipe(
648 Effect.provide(
649 Layer.mergeAll(
650 ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} })),
651 NetService.layer,
652 ),
653 ),
654 );
655​
656 expect(resolved).toMatchObject({
657 otlpTracesUrl: "http://localhost:4318/v1/traces",
658 otlpTracesSource: "settings",
659 otlpMetricsSource: "settings",
660 otlpLogsSource: "settings",
661 });
662 }),
663 );
664​
665 it.effect("zeroes an endpoint stored in Settings when the SDK is disabled", () =>
666 Effect.gen(function* () {
667 const fs = yield* FileSystem.FileSystem;
668 const path = yield* Path.Path;
669 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-cli-config-otel-off-" });
670 const derivedPaths = yield* deriveExplicitServerPaths(baseDir, undefined);
671 yield* fs.makeDirectory(path.dirname(derivedPaths.settingsPath), { recursive: true });
672 yield* fs.writeFileString(
673 derivedPaths.settingsPath,
674 `${JSON.stringify({
675 observability: {
676 otlpTracesUrl: "http://localhost:4318/v1/traces",
677 otlpMetricsUrl: "http://localhost:4318/v1/metrics",
678 otlpLogsUrl: "http://localhost:4318/v1/logs",
679 },
680 })}\n`,
681 );
682​
683 const resolved = yield* resolveServerConfig(
684 {
685 mode: Option.some("desktop"),
686 port: Option.some(4888),
687 host: Option.none(),
688 baseDir: Option.some(baseDir),
689 cwd: Option.none(),
690 devUrl: Option.none(),
691 noBrowser: Option.none(),
692 bootstrapFd: Option.none(),
693 autoBootstrapProjectFromCwd: Option.none(),
694 logWebSocketEvents: Option.none(),
695 tailscaleServeEnabled: Option.none(),
696 tailscaleServePort: Option.none(),
697 lan: Option.none(),
698 },
699 Option.none(),
700 ).pipe(
701 Effect.provide(
702 Layer.mergeAll(
703 ConfigProvider.layer(ConfigProvider.fromEnv({ env: { OTEL_SDK_DISABLED: "true" } })),
704 NetService.layer,
705 ),
706 ),
707 );
708​
709 expect(resolved.otlpTracesUrl).toBeUndefined();
710 expect(resolved.otlpMetricsUrl).toBeUndefined();
711 expect(resolved.otlpLogsUrl).toBeUndefined();
712 expect(resolved.otelEnvironment.disabled).toBe(true);
713 }),
714 );
715​
716 it.effect("lets T3CODE_OTEL_SDK_DISABLED=false override an ambient OTEL_SDK_DISABLED=true", () =>
717 Effect.gen(function* () {
718 const fs = yield* FileSystem.FileSystem;
719 const path = yield* Path.Path;
720 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-cli-config-otel-on-" });
721 const derivedPaths = yield* deriveExplicitServerPaths(baseDir, undefined);
722 yield* fs.makeDirectory(path.dirname(derivedPaths.settingsPath), { recursive: true });
723 yield* fs.writeFileString(
724 derivedPaths.settingsPath,
725 `${JSON.stringify({
726 observability: {
727 otlpTracesUrl: "http://localhost:4318/v1/traces",
728 },
729 })}\n`,
730 );
731​
732 const resolved = yield* resolveServerConfig(
733 {
734 mode: Option.some("desktop"),
735 port: Option.some(4888),
736 host: Option.none(),
737 baseDir: Option.some(baseDir),
738 cwd: Option.none(),
739 devUrl: Option.none(),
740 noBrowser: Option.none(),
741 bootstrapFd: Option.none(),
742 autoBootstrapProjectFromCwd: Option.none(),
743 logWebSocketEvents: Option.none(),
744 tailscaleServeEnabled: Option.none(),
745 tailscaleServePort: Option.none(),
746 lan: Option.none(),
747 },
748 Option.none(),
749 ).pipe(
750 Effect.provide(
751 Layer.mergeAll(
752 ConfigProvider.layer(
753 ConfigProvider.fromEnv({
754 env: { T3CODE_OTEL_SDK_DISABLED: "false", OTEL_SDK_DISABLED: "true" },
755 }),
756 ),
757 NetService.layer,
758 ),
759 ),
760 );
761​
762 expect(resolved.otelEnvironment.disabled).toBe(false);
763 expect(resolved.otlpTracesUrl).toBe("http://localhost:4318/v1/traces");
764 }),
765 );
766​
767 it.effect("forces noBrowser and disables auto-bootstrap for headless startup presentation", () =>
768 Effect.gen(function* () {
769 const { join } = yield* Path.Path;
770 const baseDir = join(NodeOS.tmpdir(), "t3-cli-config-headless-base");
771 const derivedPaths = yield* deriveExplicitServerPaths(baseDir, undefined);
772​
773 const resolved = yield* resolveServerConfig(
774 {
775 mode: Option.some("web"),
776 port: Option.some(3773),
777 host: Option.none(),
778 baseDir: Option.some(baseDir),
779 cwd: Option.none(),
780 devUrl: Option.none(),
781 noBrowser: Option.none(),
782 bootstrapFd: Option.none(),
783 autoBootstrapProjectFromCwd: Option.none(),
784 logWebSocketEvents: Option.none(),
785 tailscaleServeEnabled: Option.none(),
786 tailscaleServePort: Option.none(),
787 lan: Option.none(),
788 },
789 Option.none(),
790 {
791 startupPresentation: "headless",
792 },
793 ).pipe(
794 Effect.provide(
795 Layer.mergeAll(
796 ConfigProvider.layer(
797 ConfigProvider.fromEnv({
798 env: {
799 T3CODE_NO_BROWSER: "false",
800 T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "true",
801 },
802 }),
803 ),
804 NetService.layer,
805 ),
806 ),
807 );
808​
809 expect(resolved).toEqual({
810 logLevel: "Info",
811 ...defaultObservabilityConfig,
812 mode: "web",
813 port: 3773,
814 cwd: process.cwd(),
815 baseDir,
816 ...derivedPaths,
817 host: undefined,
818 staticDir: resolved.staticDir,
819 devUrl: undefined,
820 noBrowser: true,
821 startupPresentation: "headless",
822 desktopBootstrapToken: undefined,
823 autoBootstrapProjectFromCwd: false,
824 logWebSocketEvents: false,
825 tailscaleServeEnabled: false,
826 tailscaleServePort: 443,
827 });
828 }),
829 );
830​
831 it.effect("keeps whitespace-separated pairs and literal equals signs in OTLP headers", () =>
832 Effect.gen(function* () {
833 const { join } = yield* Path.Path;
834 const baseDir = join(NodeOS.tmpdir(), "t3-cli-config-otlp-headers-loose-base");
835​
836 const resolved = yield* resolveServerConfig(
837 {
838 mode: Option.some("web"),
839 port: Option.some(3773),
840 host: Option.none(),
841 baseDir: Option.some(baseDir),
842 cwd: Option.none(),
843 devUrl: Option.none(),
844 noBrowser: Option.none(),
845 bootstrapFd: Option.none(),
846 autoBootstrapProjectFromCwd: Option.none(),
847 logWebSocketEvents: Option.none(),
848 tailscaleServeEnabled: Option.none(),
849 tailscaleServePort: Option.none(),
850 lan: Option.none(),
851 },
852 Option.none(),
853 ).pipe(
854 Effect.provide(
855 Layer.mergeAll(
856 ConfigProvider.layer(
857 ConfigProvider.fromEnv({
858 env: {
859 T3CODE_OTLP_HEADERS: "authorization=Bearer abc==, x-tenant=t3",
860 T3CODE_OTLP_TRACES_URL: "http://collector.internal:4318",
861 },
862 }),
863 ),
864 NetService.layer,
865 ),
866 ),
867 );
868​
869 expect(resolved.otlpTracesExport.headers).toEqual({
870 authorization: "Bearer abc==",
871 "x-tenant": "t3",
872 });
873 expect(resolved.otlpTracesUrl).toBe("http://collector.internal:4318");
874 }),
875 );
876​
877 const minimalWebFlags = (baseDir: string) => ({
878 mode: Option.some("web" as const),
879 port: Option.some(3773),
880 host: Option.none<string>(),
881 baseDir: Option.some(baseDir),
882 cwd: Option.none<string>(),
883 devUrl: Option.none<URL>(),
884 noBrowser: Option.none<boolean>(),
885 bootstrapFd: Option.none<number>(),
886 autoBootstrapProjectFromCwd: Option.none<boolean>(),
887 logWebSocketEvents: Option.none<boolean>(),
888 tailscaleServeEnabled: Option.none<boolean>(),
889 tailscaleServePort: Option.none<number>(),
890 lan: Option.none<boolean>(),
891 });
892​
893 it.effect("uses the same unbracketed IPv6 wildcard for port selection and startup", () =>
894 Effect.gen(function* () {
895 const baseDir = yield* FileSystem.FileSystem.pipe(
896 Effect.flatMap((fs) => fs.makeTempDirectoryScoped({ prefix: "t3-cli-ipv6-host-" })),
897 );
898 const config = yield* resolveServerConfig(
899 { ...minimalWebFlags(baseDir), port: Option.none() },
900 Option.none(),
901 {
902 selectAutomaticPort: (_preferred, host) =>
903 Effect.succeed(host === "::" ? 50_123 : 50_124),
904 },
905 ).pipe(
906 Effect.provide(
907 Layer.merge(
908 NetService.layer,
909 ConfigProvider.layer(ConfigProvider.fromEnv({ env: { T3CODE_HOST: "[::]" } })),
910 ),
911 ),
912 );
913​
914 expect(config.host).toBe("::");
915 expect(config.port).toBe(50_123);
916 }),
917 );
918​
919 it.effect("uses the automatic port selector only when no port is configured", () =>
920 Effect.gen(function* () {
921 const baseDir = yield* FileSystem.FileSystem.pipe(
922 Effect.flatMap((fs) => fs.makeTempDirectoryScoped({ prefix: "t3-cli-auto-port-" })),
923 );
924 const selected: Array<readonly [number, string | undefined]> = [];
925 const selectAutomaticPort = (preferred: number, host: string | undefined) =>
926 Effect.sync(() => {
927 selected.push([preferred, host]);
928 return 50_123;
929 });
930 const resolvePort = (flags: {
931 readonly mode?: Option.Option<"web" | "desktop">;
932 readonly port: Option.Option<number>;
933 readonly host?: Option.Option<string>;
934 }) =>
935 resolveServerConfig({ ...minimalWebFlags(baseDir), ...flags }, Option.none(), {
936 selectAutomaticPort,
937 }).pipe(
938 Effect.map((config) => config.port),
939 Effect.provide(
940 Layer.merge(
941 NetService.layer,
942 ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} })),
943 ),
944 ),
945 );
946​
947 expect(yield* resolvePort({ port: Option.none() })).toBe(50_123);
948 expect(yield* resolvePort({ port: Option.none(), host: Option.some("100.64.0.7") })).toBe(
949 50_123,
950 );
951 expect(selected).toEqual([
952 [3773, undefined],
953 [3773, "100.64.0.7"],
954 ]);
955 expect(yield* resolvePort({ port: Option.some(8788) })).toBe(8788);
956 expect(
957 yield* resolvePort({ mode: Option.some("desktop" as const), port: Option.none() }),
958 ).toBe(3773);
959 expect(selected).toHaveLength(2);
960 }),
961 );
962​
963 it.effect(
964 "resolves each signal's endpoint through T3CODE_OTLP_*_URL, an OTEL endpoint, the bootstrap envelope, and persisted Settings, in that order",
965 () =>
966 Effect.gen(function* () {
967 const fs = yield* FileSystem.FileSystem;
968 const path = yield* Path.Path;
969 const baseDir = yield* fs.makeTempDirectoryScoped({
970 prefix: "t3-cli-config-otel-precedence-",
971 });
972 const derivedPaths = yield* deriveExplicitServerPaths(baseDir, undefined);
973 yield* fs.makeDirectory(path.dirname(derivedPaths.settingsPath), { recursive: true });
974 yield* fs.writeFileString(
975 derivedPaths.settingsPath,
976 `${JSON.stringify({ observability: { otlpLogsUrl: "http://settings:4318/v1/logs" } })}\n`,
977 );
978​
979 const fd = yield* openBootstrapFd(
980 makeDesktopBootstrap({
981 otlpMetricsUrl: "http://bootstrap:4318/v1/metrics",
982 otlpLogsUrl: "",
983 }),
984 );
985​
986 const resolved = yield* resolveServerConfig(
987 {
988 ...minimalWebFlags(baseDir),
989 mode: Option.some("desktop"),
990 port: Option.some(4888),
991 bootstrapFd: Option.some(fd),
992 },
993 Option.none(),
994 ).pipe(
995 Effect.provide(
996 Layer.mergeAll(
997 ConfigProvider.layer(
998 ConfigProvider.fromEnv({
999 env: {
1000 T3CODE_OTLP_TRACES_URL: "http://t3:4318/v1/traces",
1001 T3CODE_OTLP_HEADERS: "x-key=secret",
1002 OTEL_EXPORTER_OTLP_TRACES_ENDPOINT: "http://otel-traces:4318/custom",
1003 OTEL_EXPORTER_OTLP_METRICS_ENDPOINT: "http://otel-metrics:4318/custom",
1004 OTEL_EXPORTER_OTLP_HEADERS: "x-key=otel",
1005 },
1006 }),
1007 ),
1008 NetService.layer,
1009 ),
1010 ),
1011 );
1012​
1013 expect(resolved.otlpTracesUrl).toBe("http://t3:4318/v1/traces");
1014 expect(resolved.otlpTracesExport.headers).toEqual({ "x-key": "secret" });
1015 expect(resolved.otlpMetricsUrl).toBe("http://otel-metrics:4318/custom");
1016 expect(resolved.otlpMetricsExport).toEqual({
1017 ...DEFAULT_SIGNAL_EXPORT,
1018 protocol: "http/protobuf",
1019 headers: { "x-key": "otel" },
1020 });
1021 expect(resolved.otlpLogsUrl).toBe("http://settings:4318/v1/logs");
1022 expect(resolved.otlpLogsExport.headers).toEqual({ "x-key": "secret" });
1023 expect(resolved).toMatchObject({
1024 otlpTracesVariable: "T3CODE_OTLP_TRACES_URL",
1025 otlpMetricsVariable: "OTEL_EXPORTER_OTLP_METRICS_ENDPOINT",
1026 });
1027 expect(resolved.otlpLogsVariable).toBeUndefined();
1028 }),
1029 );
1030​
1031 it.effect(
1032 "exports nothing for a signal an OTEL endpoint claimed with a protocol or headers that do not read",
1033 () =>
1034 Effect.gen(function* () {
1035 const fs = yield* FileSystem.FileSystem;
1036 const path = yield* Path.Path;
1037 const baseDir = yield* fs.makeTempDirectoryScoped({
1038 prefix: "t3-cli-config-otel-off-",
1039 });
1040 const derivedPaths = yield* deriveExplicitServerPaths(baseDir, undefined);
1041 yield* fs.makeDirectory(path.dirname(derivedPaths.settingsPath), { recursive: true });
1042 yield* fs.writeFileString(
1043 derivedPaths.settingsPath,
1044 `${JSON.stringify({ observability: { otlpLogsUrl: "http://settings:4318/v1/logs" } })}\n`,
1045 );
1046​
1047 const fd = yield* openBootstrapFd(
1048 makeDesktopBootstrap({ otlpMetricsUrl: "http://bootstrap:4318/v1/metrics" }),
1049 );
1050​
1051 const resolved = yield* resolveServerConfig(
1053 ...minimalWebFlags(baseDir),
1054 mode: Option.some("desktop"),
1055 port: Option.some(4888),
1056 bootstrapFd: Option.some(fd),
1057 },
1058 Option.none(),
1059 ).pipe(
1060 Effect.provide(
1061 Layer.mergeAll(
1062 ConfigProvider.layer(
1063 ConfigProvider.fromEnv({
1064 env: {
1065 T3CODE_OTLP_TRACES_URL: "http://t3:4318/v1/traces",
1066 OTEL_EXPORTER_OTLP_ENDPOINT: "http://otel:4318",
1067 OTEL_EXPORTER_OTLP_HEADERS: "x-key=%zz",
1068 },
1069 }),
1070 ),
1071 NetService.layer,
1072 ),
1073 ),
1074 );
1075​
1076 expect(resolved.otlpTracesUrl).toBe("http://t3:4318/v1/traces");
1077 expect(resolved.otlpMetricsUrl).toBeUndefined();
1078 expect(resolved.otlpLogsUrl).toBeUndefined();
1079 }),
1080 );
1081​
1082 it.effect("listens on private networks per T3CODE_LAN, else under the service launcher", () =>
1083 Effect.gen(function* () {
1084 const { join } = yield* Path.Path;
1085 const baseDir = join(NodeOS.tmpdir(), "t3-cli-config-service-host");
1086 const resolveHost = (input: {
1087 readonly connected: boolean;
1088 readonly env?: Record<string, string>;
1089 }) =>
1090 resolveServerConfig(minimalWebFlags(baseDir), Option.none()).pipe(
1091 Effect.map(({ host, privateNetworkOnly }) => ({ host, privateNetworkOnly })),
1092 Effect.provide(
1093 Layer.mergeAll(
1094 ConfigProvider.layer(ConfigProvider.fromEnv({ env: input.env ?? {} })),
1095 NetService.layer,
1096 ),
1097 ),
1098 Effect.provideService(HostProcess.Environment, {
1099 [SERVICE_LAUNCHER_CONTEXT_ENV]: JSON.stringify({
1100 protocol: SERVICE_LAUNCHER_PROTOCOL,
1101 childVersion: packageJson.version,
1102 }),
1103 }),
1104 Effect.provideService(ServiceLauncherHostProcess, {
1105 connected: input.connected,
1106 send: () => false,
1107 on: () => undefined,
1108 off: () => undefined,
1109 }),
1110 );
1111​
1112 // A service installed before T3CODE_LAN existed.
1113 expect(yield* resolveHost({ connected: true })).toEqual({
1114 host: "0.0.0.0",
1115 privateNetworkOnly: true,
1116 });
1117 // `service.env` reaches the server as its environment.
1118 expect(yield* resolveHost({ connected: true, env: { T3CODE_HOST: "127.0.0.1" } })).toEqual({
1119 host: "127.0.0.1",
1120 privateNetworkOnly: undefined,
1121 });
1122 expect(yield* resolveHost({ connected: true, env: { T3CODE_LAN: "false" } })).toEqual({
1123 host: undefined,
1124 privateNetworkOnly: undefined,
1125 });
1126 expect(yield* resolveHost({ connected: false, env: { T3CODE_LAN: "true" } })).toEqual({
1127 host: "0.0.0.0",
1128 privateNetworkOnly: true,
1129 });
1130 // Without the launcher's IPC channel the context was inherited, e.g. by
1131 // `t3 serve` started from an agent inside the service.
1132 expect(yield* resolveHost({ connected: false })).toEqual({
1133 host: undefined,
1134 privateNetworkOnly: undefined,
1135 });
1136 }),
1137 );
1138});