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

ServerEnvironment.test.ts

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