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

ServerEnvironment.test.ts

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