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

ServerEnvironment.test.ts

377 lines15.7 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 expect(descriptor.capabilities).toMatchObject({
122 settledWorktreeCleanup: true,
123 storageCleanupRun: true,
124 projectWorktreeCleanup: true,
125 worktreesDirectory: true,
126 threadAutoSettlementScope: true,
127 });
128 }
129 }),
130 );
131 it.effect.each([
132 { name: "missing", content: undefined },
133 { name: "empty", content: "" },
134 { name: "whitespace-only", content: " \t\n" },
135 ])("concurrent initializers recover a $name environment id file", ({ content }) =>
136 Effect.gen(function* () {
137 const fileSystem = yield* FileSystem.FileSystem;
138 const crypto = yield* Crypto.Crypto;
139 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
140 prefix: "t3-server-environment-concurrent-test-",
141 });
142 const serverConfig = yield* makeServerConfig(baseDir);
143 yield* fileSystem.makeDirectory(serverConfig.stateDir, { recursive: true });
144 if (content !== undefined) {
145 yield* fileSystem.writeFileString(serverConfig.environmentIdPath, content);
146 }
147 const bothGenerated = yield* Deferred.make<void>();
148 const bothReadEmpty = yield* Deferred.make<void>();
149 const firstInitialized = yield* Deferred.make<void>();
150 let remaining = 2;
151 let emptyReads = 0;
152 const readIdentity = Effect.gen(function* () {
153 const identity = yield* ServerEnvironment.ServerEnvironmentIdentity;
154 return yield* identity.getEnvironmentId;
155 }).pipe(
156 Effect.tap(() => Deferred.succeed(firstInitialized, undefined)),
157 Effect.provide(Layer.fresh(ServerEnvironment.layerIdentity)),
158 Effect.provideService(ServerConfig.ServerConfig, serverConfig),
159 Effect.provideService(FileSystem.FileSystem, {
160 ...fileSystem,
161 readFileString: (path) =>
162 fileSystem.readFileString(path).pipe(
163 Effect.tap(
164 Effect.fn(function* (value) {
165 if (path !== serverConfig.environmentIdPath || remaining > 0 || value.trim()) {
166 return;
167 }
168 if (++emptyReads === 2) {
169 yield* Deferred.succeed(bothReadEmpty, undefined);
170 yield* Deferred.await(firstInitialized);
171 } else {
172 yield* Deferred.await(bothReadEmpty);
173 }
174 }),
175 ),
176 ),
177 }),
178 Effect.provideService(Crypto.Crypto, {
179 ...crypto,
180 randomUUIDv4: (() =>
181 Effect.gen(function* () {
182 const id = yield* crypto.randomUUIDv4();
183 if (--remaining === 0) {
184 yield* Deferred.succeed(bothGenerated, undefined);
185 }
186 yield* Deferred.await(bothGenerated);
187 return id;
188 })) as Crypto.Crypto["randomUUIDv4"],
189 }),
190 );
191​
192 const [first, second] = yield* Effect.all([readIdentity, readIdentity], {
193 concurrency: "unbounded",
194 });
195 const persisted = yield* fileSystem.readFileString(serverConfig.environmentIdPath);
196​
197 expect(first).toBe(second);
198 expect(persisted.trim()).toBe(first);
199 }),
200 );
201​
202 it.effect("persists the environment id across service restarts", () =>
203 Effect.gen(function* () {
204 const fileSystem = yield* FileSystem.FileSystem;
205 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
206 prefix: "t3-server-environment-test-",
207 });
208​
209 const first = yield* Effect.gen(function* () {
210 const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
211 return yield* serverEnvironment.getDescriptor;
212 }).pipe(Effect.provide(layerServerEnvironment(baseDir)));
213 const second = yield* Effect.gen(function* () {
214 const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
215 return yield* serverEnvironment.getDescriptor;
216 }).pipe(Effect.provide(layerServerEnvironment(baseDir)));
217​
218 expect(first.environmentId).toBe(second.environmentId);
219 expect(first.orchestrationProtocolVersion).toBe(ORCHESTRATION_PROTOCOL_VERSION);
220 expect(second.capabilities.repositoryIdentity).toBe(true);
221 expect(second.capabilities.connectionProbe).toBe(true);
222 expect(second.capabilities.attachmentUploads).toBe(true);
223 expect(second.capabilities.fileAttachments).toEqual({ maxUploadBytes: 50 * 1024 * 1024 });
224 expect(second.capabilities.pullRequests).toBe(true);
225 expect(second.capabilities.requiredWorktreeBootstrap).toBe(true);
226 expect(second.capabilities.usagePriceOverrides).toBe(true);
227 expect(second.capabilities.threadActiveReorder).toBe(true);
228 expect(second.capabilities.threadTitleRegeneration).toBe(true);
229 expect(second.capabilities.threadPullRequests).toBe(true);
230 expect(second.capabilities.threadPullRequestLinking).toBe(true);
231 expect(second.capabilities.serverResolvedCommandContext).toBe(true);
232 expect(second.capabilities.projectProviderInstanceOverrides).toBe(true);
233 expect(second.capabilities.agentActivityPublishing).toBe(false);
234 }),
235 );
236​
237 it.effect("reports agent activity publishing from the current secret state", () =>
238 Effect.gen(function* () {
239 const fileSystem = yield* FileSystem.FileSystem;
240 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
241 prefix: "t3-server-environment-publish-test-",
242 });
243 const layerTest = Layer.mergeAll(
244 ServerEnvironment.layer.pipe(Layer.provide(ServerSecretStore.layer)),
245 ServerSecretStore.layer,
246 ).pipe(Layer.provide(ServerConfig.layerTest(process.cwd(), baseDir)));
247​
248 yield* Effect.gen(function* () {
249 const secrets = yield* ServerSecretStore.ServerSecretStore;
250 const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
251 const encode = (value: string) => new TextEncoder().encode(value);
252​
253 const unlinked = yield* serverEnvironment.getDescriptor;
254 expect(unlinked.capabilities.agentActivityPublishing).toBe(false);
255​
256 yield* secrets.set(PUBLISH_AGENT_ACTIVITY_SECRET, encode("true"));
257 const withoutLink = yield* serverEnvironment.getDescriptor;
258 expect(withoutLink.capabilities.agentActivityPublishing).toBe(false);
259​
260 yield* secrets.set(RELAY_URL_SECRET, encode(""));
261 yield* secrets.set(RELAY_ENVIRONMENT_CREDENTIAL_SECRET, encode("credential"));
262 const emptyUrl = yield* serverEnvironment.getDescriptor;
263 expect(emptyUrl.capabilities.agentActivityPublishing).toBe(false);
264​
265 yield* secrets.set(RELAY_URL_SECRET, encode("https://relay.example"));
266 const linked = yield* serverEnvironment.getDescriptor;
267 expect(linked.capabilities.agentActivityPublishing).toBe(true);
268​
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 expect(withFd.capabilities.serverUpdateThreadContinuation).toBeUndefined();
303​
304 const withoutFd = yield* describeWith({ mode: "desktop" });
305 expect(withoutFd.capabilities.serverSelfUpdate).toBe("desktop-managed");
306 expect(withoutFd.capabilities.desktopAppUpdate).toBeUndefined();
307 expect(withoutFd.capabilities.serverSelfUpdateProgress).toBeUndefined();
308 expect(withoutFd.capabilities.serverUpdateThreadContinuation).toBeUndefined();
309​
310 const web = yield* describeWith({ mode: "web", desktopTelemetryControlFd: 5 });
311 expect(web.capabilities.desktopAppUpdate).toBeUndefined();
312 }),
313 );
314​
315 it.effect("structures persisted environment id filesystem failures", () =>
316 Effect.gen(function* () {
317 const fileSystem = yield* FileSystem.FileSystem;
318 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
319 prefix: "t3-server-environment-error-test-",
320 });
321 const serverConfig = yield* makeServerConfig(baseDir);
322 const environmentIdPath = serverConfig.environmentIdPath;
323 const tempPath = `${environmentIdPath}.tmp`;
324 const methodByOperation = {
325 check: "exists",
326 read: "readFileString",
327 write: "writeFileString",
328 } as const;
329​
330 for (const operation of ["check", "read", "write"] as const) {
331 const writeAttempts: string[] = [];
332 const cause = PlatformError.systemError({
333 _tag: "PermissionDenied",
334 module: "FileSystem",
335 method: methodByOperation[operation],
336 description: "permission denied",
337 pathOrDescriptor: environmentIdPath,
338 });
339 const layerFailingFileSystem = FileSystem.layerNoop({
340 exists: () =>
341 operation === "check" ? Effect.fail(cause) : Effect.succeed(operation === "read"),
342 readFileString: () => Effect.fail(cause),
343 makeTempFileScoped: () => Effect.succeed(tempPath),
344 writeFileString: (path) => {
345 writeAttempts.push(path);
346 return Effect.fail(cause);
347 },
348 });
349​
350 const error = yield* Effect.gen(function* () {
351 const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
352 return yield* serverEnvironment.getDescriptor;
353 }).pipe(
354 Effect.provide(
355 ServerEnvironment.layer.pipe(
356 Layer.provide(layerEmptySecretStore),
357 Layer.provide(Layer.merge(ServerConfig.layer(serverConfig), layerFailingFileSystem)),
358 ),
359 ),
360 Effect.flip,
361 );
362​
363 expect(isServerEnvironmentIdPersistenceError(error)).toBe(true);
364 if (!isServerEnvironmentIdPersistenceError(error)) {
365 throw error;
366 }
367 expect(error.operation).toBe(operation);
368 expect(error.environmentIdPath).toBe(environmentIdPath);
369 expect(error.cause).toBe(cause);
370 expect(error.message).toBe(
371 `Server environment ID ${operation} failed at '${environmentIdPath}'.`,
372 );
373 expect(writeAttempts).toEqual(operation === "write" ? [tempPath] : []);
374 }
375 }),
376 );
377});