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

ServerEnvironment.test.ts

379 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: Effect.gen(function* () {
175 const id = yield* crypto.randomUUIDv4;
176 if (--remaining === 0) {
177 yield* Deferred.succeed(bothGenerated, undefined);
178 }
179 yield* Deferred.await(bothGenerated);
180 return id;
181 }),
182 }),
183 );
184​
185 const [first, second] = yield* Effect.all([readIdentity, readIdentity], {
186 concurrency: "unbounded",
187 });
188 const persisted = yield* fileSystem.readFileString(serverConfig.environmentIdPath);
189​
190 expect(first).toBe(second);
191 expect(persisted.trim()).toBe(first);
192 }),
193 );
194​
195 it.effect("persists the environment id across service restarts", () =>
196 Effect.gen(function* () {
197 const fileSystem = yield* FileSystem.FileSystem;
198 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
199 prefix: "t3-server-environment-test-",
200 });
201​
202 const first = yield* Effect.gen(function* () {
203 const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
204 return yield* serverEnvironment.getDescriptor;
205 }).pipe(Effect.provide(layerServerEnvironment(baseDir)));
206 const second = yield* Effect.gen(function* () {
207 const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
208 return yield* serverEnvironment.getDescriptor;
209 }).pipe(Effect.provide(layerServerEnvironment(baseDir)));
210​
211 expect(first.environmentId).toBe(second.environmentId);
212 expect(first.orchestrationProtocolVersion).toBe(ORCHESTRATION_PROTOCOL_VERSION);
213 expect(second.capabilities.repositoryIdentity).toBe(true);
214 expect(second.capabilities.connectionProbe).toBe(true);
215 expect(second.capabilities.attachmentUploads).toBe(true);
216 expect(second.capabilities.fileAttachments).toEqual({ maxUploadBytes: 50 * 1024 * 1024 });
217 expect(second.capabilities.pullRequests).toBe(true);
218 expect(second.capabilities.requiredWorktreeBootstrap).toBe(true);
219 expect(second.capabilities.usagePriceOverrides).toBe(true);
220 expect(second.capabilities.threadActiveReorder).toBe(true);
221 expect(second.capabilities.threadTitleRegeneration).toBe(true);
222 expect(second.capabilities.threadPullRequests).toBe(true);
223 expect(second.capabilities.threadPullRequestLinking).toBe(true);
224 expect(second.capabilities.serverResolvedCommandContext).toBe(true);
225 expect(second.capabilities.projectProviderInstanceOverrides).toBe(true);
226 expect(second.capabilities.agentActivityPublishing).toBe(false);
227 }),
228 );
229​
230 it.effect("reports agent activity publishing from the current secret state", () =>
231 Effect.gen(function* () {
232 const fileSystem = yield* FileSystem.FileSystem;
233 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
234 prefix: "t3-server-environment-publish-test-",
235 });
236 const layerTest = Layer.mergeAll(
237 ServerEnvironment.layer.pipe(Layer.provide(ServerSecretStore.layer)),
238 ServerSecretStore.layer,
239 ).pipe(Layer.provide(ServerConfig.layerTest(process.cwd(), baseDir)));
240​
241 yield* Effect.gen(function* () {
242 const secrets = yield* ServerSecretStore.ServerSecretStore;
243 const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
244 const encode = (value: string) => new TextEncoder().encode(value);
245​
246 const unlinked = yield* serverEnvironment.getDescriptor;
247 expect(unlinked.capabilities.agentActivityPublishing).toBe(false);
248​
249 // The opt-in alone is not enough: without relay link credentials no
250 // publish would leave this environment.
251 yield* secrets.set(PUBLISH_AGENT_ACTIVITY_SECRET, encode("true"));
252 const withoutLink = yield* serverEnvironment.getDescriptor;
253 expect(withoutLink.capabilities.agentActivityPublishing).toBe(false);
254​
255 // Empty credentials are as unconfigured as missing ones: the
256 // publisher's truthiness gate skips them, so the capability must not
257 // advertise publishing.
258 yield* secrets.set(RELAY_URL_SECRET, encode(""));
259 yield* secrets.set(RELAY_ENVIRONMENT_CREDENTIAL_SECRET, encode("credential"));
260 const emptyUrl = yield* serverEnvironment.getDescriptor;
261 expect(emptyUrl.capabilities.agentActivityPublishing).toBe(false);
262​
263 yield* secrets.set(RELAY_URL_SECRET, encode("https://relay.example"));
264 const linked = yield* serverEnvironment.getDescriptor;
265 expect(linked.capabilities.agentActivityPublishing).toBe(true);
266​
267 // The toggle changes at runtime, so the same service instance must
268 // reflect a flip without a restart.
269 yield* secrets.set(PUBLISH_AGENT_ACTIVITY_SECRET, encode("false"));
270 const disabled = yield* serverEnvironment.getDescriptor;
271 expect(disabled.capabilities.agentActivityPublishing).toBe(false);
272 }).pipe(Effect.provide(layerTest));
273 }),
274 );
275​
276 it.effect("advertises desktopAppUpdate only with desktop mode and the control fd", () =>
277 Effect.gen(function* () {
278 const fileSystem = yield* FileSystem.FileSystem;
279 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
280 prefix: "t3-server-environment-desktop-update-test-",
281 });
282 const serverConfig = yield* makeServerConfig(baseDir);
283 yield* fileSystem.makeDirectory(serverConfig.stateDir, { recursive: true });
284​
285 const describeWith = (overrides: Partial<ServerConfig.ServerConfig["Service"]>) =>
286 Effect.gen(function* () {
287 const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
288 return yield* serverEnvironment.getDescriptor;
289 }).pipe(
290 Effect.provide(
291 ServerEnvironment.layer.pipe(
292 Layer.provide(ServerSecretStore.layer),
293 Layer.provide(ServerConfig.layer({ ...serverConfig, ...overrides })),
294 ),
295 ),
296 );
297​
298 const withFd = yield* describeWith({ mode: "desktop", desktopTelemetryControlFd: 5 });
299 expect(withFd.capabilities.serverSelfUpdate).toBe("desktop-managed");
300 expect(withFd.capabilities.desktopAppUpdate).toBe(true);
301 expect(withFd.capabilities.serverSelfUpdateProgress).toBe(true);
302 // v2 recovery terminalizes running runs on restart, so continuation
303 // stays unadvertised until the v2 runtime carries the markers.
304 expect(withFd.capabilities.serverUpdateThreadContinuation).toBeUndefined();
305​
306 const withoutFd = yield* describeWith({ mode: "desktop" });
307 expect(withoutFd.capabilities.serverSelfUpdate).toBe("desktop-managed");
308 expect(withoutFd.capabilities.desktopAppUpdate).toBeUndefined();
309 expect(withoutFd.capabilities.serverSelfUpdateProgress).toBeUndefined();
310 expect(withoutFd.capabilities.serverUpdateThreadContinuation).toBeUndefined();
311​
312 const web = yield* describeWith({ mode: "web", desktopTelemetryControlFd: 5 });
313 expect(web.capabilities.desktopAppUpdate).toBeUndefined();
314 }),
315 );
316​
317 it.effect("structures persisted environment id filesystem failures", () =>
318 Effect.gen(function* () {
319 const fileSystem = yield* FileSystem.FileSystem;
320 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
321 prefix: "t3-server-environment-error-test-",
322 });
323 const serverConfig = yield* makeServerConfig(baseDir);
324 const environmentIdPath = serverConfig.environmentIdPath;
325 const tempPath = `${environmentIdPath}.tmp`;
326 const methodByOperation = {
327 check: "exists",
328 read: "readFileString",
329 write: "writeFileString",
330 } as const;
331​
332 for (const operation of ["check", "read", "write"] as const) {
333 const writeAttempts: string[] = [];
334 const cause = PlatformError.systemError({
335 _tag: "PermissionDenied",
336 module: "FileSystem",
337 method: methodByOperation[operation],
338 description: "permission denied",
339 pathOrDescriptor: environmentIdPath,
340 });
341 const layerFailingFileSystem = FileSystem.layerNoop({
342 exists: () =>
343 operation === "check" ? Effect.fail(cause) : Effect.succeed(operation === "read"),
344 readFileString: () => Effect.fail(cause),
345 makeTempFileScoped: () => Effect.succeed(tempPath),
346 writeFileString: (path) => {
347 writeAttempts.push(path);
348 return Effect.fail(cause);
349 },
350 });
351​
352 const error = yield* Effect.gen(function* () {
353 const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
354 return yield* serverEnvironment.getDescriptor;
355 }).pipe(
356 Effect.provide(
357 ServerEnvironment.layer.pipe(
358 Layer.provide(layerEmptySecretStore),
359 Layer.provide(Layer.merge(ServerConfig.layer(serverConfig), layerFailingFileSystem)),
360 ),
361 ),
362 Effect.flip,
363 );
364​
365 expect(isServerEnvironmentIdPersistenceError(error)).toBe(true);
366 if (!isServerEnvironmentIdPersistenceError(error)) {
367 throw error;
368 }
369 expect(error.operation).toBe(operation);
370 expect(error.environmentIdPath).toBe(environmentIdPath);
371 expect(error.cause).toBe(cause);
372 expect(error.message).toBe(
373 `Server environment ID ${operation} failed at '${environmentIdPath}'.`,
374 );
375 expect(writeAttempts).toEqual(operation === "write" ? [tempPath] : []);
376 }
377 }),
378 );
379});