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

ServerEnvironment.test.ts

336 lines14.1 KB

1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { ORCHESTRATION_PROTOCOL_VERSION } from "@t3tools/contracts";
3import { expect, it } from "@effect/vitest";
4import * as Crypto from "effect/Crypto";
5import * as Deferred from "effect/Deferred";
6import * as Effect from "effect/Effect";
7import * as FileSystem from "effect/FileSystem";
8import * as Layer from "effect/Layer";
9import * as PlatformError from "effect/PlatformError";
10import * as Schema from "effect/Schema";
11​
12import { DEFAULT_SIGNAL_EXPORT } from "@t3tools/shared/observability";
13import * as OtelEnvironment from "@t3tools/shared/otelEnvironment";
14​
15import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
16import {
17 PUBLISH_AGENT_ACTIVITY_SECRET,
18 RELAY_ENVIRONMENT_CREDENTIAL_SECRET,
19 RELAY_URL_SECRET,
20} from "../cloud/config.ts";
21import * as ServerConfig from "../config.ts";
22import * as ServerEnvironment from "./ServerEnvironment.ts";
23​
24const isServerEnvironmentIdPersistenceError = Schema.is(
25 ServerEnvironment.ServerEnvironmentIdPersistenceError,
26);
27​
28const makeServerEnvironmentLayer = (baseDir: string) =>
29 ServerEnvironment.layer.pipe(
30 Layer.provide(ServerSecretStore.layer),
31 Layer.provide(ServerConfig.layerTest(process.cwd(), baseDir)),
32 );
33​
34const emptySecretStoreLayer = Layer.succeed(
35 ServerSecretStore.ServerSecretStore,
36 ServerSecretStore.ServerSecretStore.of({
37 get: () => Effect.succeedNone,
38 set: () => Effect.void,
39 create: () => Effect.void,
40 getOrCreateRandom: () => Effect.succeed(new Uint8Array()),
41 remove: () => Effect.void,
42 }),
43);
44​
45const makeServerConfig = Effect.fn(function* (baseDir: string) {
46 const derivedPaths = yield* ServerConfig.deriveServerPaths(baseDir, undefined);
47​
48 return {
49 ...derivedPaths,
50 logLevel: "Error",
51 traceMinLevel: "Info",
52 traceTimingEnabled: true,
53 traceBatchWindowMs: 200,
54 traceMaxBytes: 10 * 1024 * 1024,
55 traceMaxFiles: 10,
56 otlpTracesUrl: undefined,
57 otlpMetricsUrl: undefined,
58 otlpLogsUrl: undefined,
59 otlpTracesExport: DEFAULT_SIGNAL_EXPORT,
60 otlpMetricsExport: DEFAULT_SIGNAL_EXPORT,
61 otlpLogsExport: DEFAULT_SIGNAL_EXPORT,
62 otelEnvironment: OtelEnvironment.none,
63 cwd: process.cwd(),
64 baseDir,
65 mode: "web",
66 autoBootstrapProjectFromCwd: false,
67 logWebSocketEvents: false,
68 tailscaleServeEnabled: false,
69 tailscaleServePort: 443,
70 port: 0,
71 host: undefined,
72 desktopBootstrapToken: undefined,
73 staticDir: undefined,
74 devUrl: undefined,
75 devAllowedOrigins: [],
76 noBrowser: false,
77 startupPresentation: "browser",
78 } satisfies ServerConfig.ServerConfig["Service"];
79});
80​
81it.layer(NodeServices.layer)("ServerEnvironmentLive", (it) => {
82 it.effect.each([
83 { name: "missing", content: undefined },
84 { name: "empty", content: "" },
85 { name: "whitespace-only", content: " \t\n" },
86 ])("concurrent initializers recover a $name environment id file", ({ content }) =>
87 Effect.gen(function* () {
88 const fileSystem = yield* FileSystem.FileSystem;
89 const crypto = yield* Crypto.Crypto;
90 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
91 prefix: "t3-server-environment-concurrent-test-",
92 });
93 const serverConfig = yield* makeServerConfig(baseDir);
94 yield* fileSystem.makeDirectory(serverConfig.stateDir, { recursive: true });
95 if (content !== undefined) {
96 yield* fileSystem.writeFileString(serverConfig.environmentIdPath, content);
97 }
98 const bothGenerated = yield* Deferred.make<void>();
99 const bothReadEmpty = yield* Deferred.make<void>();
100 const firstInitialized = yield* Deferred.make<void>();
101 let remaining = 2;
102 let emptyReads = 0;
103 const readIdentity = Effect.gen(function* () {
104 const identity = yield* ServerEnvironment.ServerEnvironmentIdentity;
105 return yield* identity.getEnvironmentId;
106 }).pipe(
107 Effect.tap(() => Deferred.succeed(firstInitialized, undefined)),
108 Effect.provide(Layer.fresh(ServerEnvironment.identityLayer)),
109 Effect.provideService(ServerConfig.ServerConfig, serverConfig),
110 Effect.provideService(FileSystem.FileSystem, {
111 ...fileSystem,
112 readFileString: (path) =>
113 fileSystem.readFileString(path).pipe(
114 Effect.tap(
115 Effect.fn(function* (value) {
116 if (path !== serverConfig.environmentIdPath || remaining > 0 || value.trim()) {
117 return;
118 }
119 // Both observe the empty file, but one repairs it after the other has finished.
120 if (++emptyReads === 2) {
121 yield* Deferred.succeed(bothReadEmpty, undefined);
122 yield* Deferred.await(firstInitialized);
123 } else {
124 yield* Deferred.await(bothReadEmpty);
125 }
126 }),
127 ),
128 ),
129 }),
130 Effect.provideService(Crypto.Crypto, {
131 ...crypto,
132 randomUUIDv4: Effect.gen(function* () {
133 const id = yield* crypto.randomUUIDv4;
134 if (--remaining === 0) {
135 yield* Deferred.succeed(bothGenerated, undefined);
136 }
137 yield* Deferred.await(bothGenerated);
138 return id;
139 }),
140 }),
141 );
142​
143 const [first, second] = yield* Effect.all([readIdentity, readIdentity], {
144 concurrency: "unbounded",
145 });
146 const persisted = yield* fileSystem.readFileString(serverConfig.environmentIdPath);
147​
148 expect(first).toBe(second);
149 expect(persisted.trim()).toBe(first);
150 }),
151 );
152​
153 it.effect("persists the environment id across service restarts", () =>
154 Effect.gen(function* () {
155 const fileSystem = yield* FileSystem.FileSystem;
156 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
157 prefix: "t3-server-environment-test-",
158 });
159​
160 const first = yield* Effect.gen(function* () {
161 const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
162 return yield* serverEnvironment.getDescriptor;
163 }).pipe(Effect.provide(makeServerEnvironmentLayer(baseDir)));
164 const second = yield* Effect.gen(function* () {
165 const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
166 return yield* serverEnvironment.getDescriptor;
167 }).pipe(Effect.provide(makeServerEnvironmentLayer(baseDir)));
168​
169 expect(first.environmentId).toBe(second.environmentId);
170 expect(first.orchestrationProtocolVersion).toBe(ORCHESTRATION_PROTOCOL_VERSION);
171 expect(second.capabilities.repositoryIdentity).toBe(true);
172 expect(second.capabilities.connectionProbe).toBe(true);
173 expect(second.capabilities.attachmentUploads).toBe(true);
174 expect(second.capabilities.fileAttachments).toEqual({ maxUploadBytes: 50 * 1024 * 1024 });
175 expect(second.capabilities.pullRequests).toBe(true);
176 expect(second.capabilities.requiredWorktreeBootstrap).toBe(true);
177 expect(second.capabilities.usagePriceOverrides).toBe(true);
178 expect(second.capabilities.threadActiveReorder).toBe(true);
179 expect(second.capabilities.threadTitleRegeneration).toBe(true);
180 expect(second.capabilities.threadPullRequests).toBe(true);
181 expect(second.capabilities.threadPullRequestLinking).toBe(true);
182 expect(second.capabilities.serverResolvedCommandContext).toBe(true);
183 expect(second.capabilities.agentActivityPublishing).toBe(false);
184 }),
185 );
186​
187 it.effect("reports agent activity publishing from the current secret state", () =>
188 Effect.gen(function* () {
189 const fileSystem = yield* FileSystem.FileSystem;
190 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
191 prefix: "t3-server-environment-publish-test-",
192 });
193 const testLayer = Layer.mergeAll(
194 ServerEnvironment.layer.pipe(Layer.provide(ServerSecretStore.layer)),
195 ServerSecretStore.layer,
196 ).pipe(Layer.provide(ServerConfig.layerTest(process.cwd(), baseDir)));
197​
198 yield* Effect.gen(function* () {
199 const secrets = yield* ServerSecretStore.ServerSecretStore;
200 const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
201 const encode = (value: string) => new TextEncoder().encode(value);
202​
203 const unlinked = yield* serverEnvironment.getDescriptor;
204 expect(unlinked.capabilities.agentActivityPublishing).toBe(false);
205​
206 // The opt-in alone is not enough: without relay link credentials no
207 // publish would leave this environment.
208 yield* secrets.set(PUBLISH_AGENT_ACTIVITY_SECRET, encode("true"));
209 const withoutLink = yield* serverEnvironment.getDescriptor;
210 expect(withoutLink.capabilities.agentActivityPublishing).toBe(false);
211​
212 // Empty credentials are as unconfigured as missing ones: the
213 // publisher's truthiness gate skips them, so the capability must not
214 // advertise publishing.
215 yield* secrets.set(RELAY_URL_SECRET, encode(""));
216 yield* secrets.set(RELAY_ENVIRONMENT_CREDENTIAL_SECRET, encode("credential"));
217 const emptyUrl = yield* serverEnvironment.getDescriptor;
218 expect(emptyUrl.capabilities.agentActivityPublishing).toBe(false);
219​
220 yield* secrets.set(RELAY_URL_SECRET, encode("https://relay.example"));
221 const linked = yield* serverEnvironment.getDescriptor;
222 expect(linked.capabilities.agentActivityPublishing).toBe(true);
223​
224 // The toggle changes at runtime, so the same service instance must
225 // reflect a flip without a restart.
226 yield* secrets.set(PUBLISH_AGENT_ACTIVITY_SECRET, encode("false"));
227 const disabled = yield* serverEnvironment.getDescriptor;
228 expect(disabled.capabilities.agentActivityPublishing).toBe(false);
229 }).pipe(Effect.provide(testLayer));
230 }),
231 );
232​
233 it.effect("advertises desktopAppUpdate only with desktop mode and the control fd", () =>
234 Effect.gen(function* () {
235 const fileSystem = yield* FileSystem.FileSystem;
236 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
237 prefix: "t3-server-environment-desktop-update-test-",
238 });
239 const serverConfig = yield* makeServerConfig(baseDir);
240 yield* fileSystem.makeDirectory(serverConfig.stateDir, { recursive: true });
241​
242 const describeWith = (overrides: Partial<ServerConfig.ServerConfig["Service"]>) =>
243 Effect.gen(function* () {
244 const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
245 return yield* serverEnvironment.getDescriptor;
246 }).pipe(
247 Effect.provide(
248 ServerEnvironment.layer.pipe(
249 Layer.provide(ServerSecretStore.layer),
250 Layer.provide(ServerConfig.layer({ ...serverConfig, ...overrides })),
251 ),
252 ),
253 );
254​
255 const withFd = yield* describeWith({ mode: "desktop", desktopTelemetryControlFd: 5 });
256 expect(withFd.capabilities.serverSelfUpdate).toBe("desktop-managed");
257 expect(withFd.capabilities.desktopAppUpdate).toBe(true);
258 expect(withFd.capabilities.serverSelfUpdateProgress).toBe(true);
259 // v2 recovery terminalizes running runs on restart, so continuation
260 // stays unadvertised until the v2 runtime carries the markers.
261 expect(withFd.capabilities.serverUpdateThreadContinuation).toBeUndefined();
262​
263 const withoutFd = yield* describeWith({ mode: "desktop" });
264 expect(withoutFd.capabilities.serverSelfUpdate).toBe("desktop-managed");
265 expect(withoutFd.capabilities.desktopAppUpdate).toBeUndefined();
266 expect(withoutFd.capabilities.serverSelfUpdateProgress).toBeUndefined();
267 expect(withoutFd.capabilities.serverUpdateThreadContinuation).toBeUndefined();
268​
269 const web = yield* describeWith({ mode: "web", desktopTelemetryControlFd: 5 });
270 expect(web.capabilities.desktopAppUpdate).toBeUndefined();
271 }),
272 );
273​
274 it.effect("structures persisted environment id filesystem failures", () =>
275 Effect.gen(function* () {
276 const fileSystem = yield* FileSystem.FileSystem;
277 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
278 prefix: "t3-server-environment-error-test-",
279 });
280 const serverConfig = yield* makeServerConfig(baseDir);
281 const environmentIdPath = serverConfig.environmentIdPath;
282 const tempPath = `${environmentIdPath}.tmp`;
283 const methodByOperation = {
284 check: "exists",
285 read: "readFileString",
286 write: "writeFileString",
287 } as const;
288​
289 for (const operation of ["check", "read", "write"] as const) {
290 const writeAttempts: string[] = [];
291 const cause = PlatformError.systemError({
292 _tag: "PermissionDenied",
293 module: "FileSystem",
294 method: methodByOperation[operation],
295 description: "permission denied",
296 pathOrDescriptor: environmentIdPath,
297 });
298 const failingFileSystemLayer = FileSystem.layerNoop({
299 exists: () =>
300 operation === "check" ? Effect.fail(cause) : Effect.succeed(operation === "read"),
301 readFileString: () => Effect.fail(cause),
302 makeTempFileScoped: () => Effect.succeed(tempPath),
303 writeFileString: (path) => {
304 writeAttempts.push(path);
305 return Effect.fail(cause);
306 },
307 });
308​
309 const error = yield* Effect.gen(function* () {
310 const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
311 return yield* serverEnvironment.getDescriptor;
312 }).pipe(
313 Effect.provide(
314 ServerEnvironment.layer.pipe(
315 Layer.provide(emptySecretStoreLayer),
316 Layer.provide(Layer.merge(ServerConfig.layer(serverConfig), failingFileSystemLayer)),
317 ),
318 ),
319 Effect.flip,
320 );
321​
322 expect(isServerEnvironmentIdPersistenceError(error)).toBe(true);
323 if (!isServerEnvironmentIdPersistenceError(error)) {
324 throw error;
325 }
326 expect(error.operation).toBe(operation);
327 expect(error.environmentIdPath).toBe(environmentIdPath);
328 expect(error.cause).toBe(cause);
329 expect(error.message).toBe(
330 `Server environment ID ${operation} failed at '${environmentIdPath}'.`,
331 );
332 expect(writeAttempts).toEqual(operation === "write" ? [tempPath] : []);
333 }
334 }),
335 );
336});