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

ServerEnvironment.test.ts

337 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 otlpServiceName: "t3-server",
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.each([
84 { name: "missing", content: undefined },
85 { name: "empty", content: "" },
86 { name: "whitespace-only", content: " \t\n" },
87 ])("concurrent initializers recover a $name environment id file", ({ content }) =>
88 Effect.gen(function* () {
89 const fileSystem = yield* FileSystem.FileSystem;
90 const crypto = yield* Crypto.Crypto;
91 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
92 prefix: "t3-server-environment-concurrent-test-",
93 });
94 const serverConfig = yield* makeServerConfig(baseDir);
95 yield* fileSystem.makeDirectory(serverConfig.stateDir, { recursive: true });
96 if (content !== undefined) {
97 yield* fileSystem.writeFileString(serverConfig.environmentIdPath, content);
98 }
99 const bothGenerated = yield* Deferred.make<void>();
100 const bothReadEmpty = yield* Deferred.make<void>();
101 const firstInitialized = yield* Deferred.make<void>();
102 let remaining = 2;
103 let emptyReads = 0;
104 const readIdentity = Effect.gen(function* () {
105 const identity = yield* ServerEnvironment.ServerEnvironmentIdentity;
106 return yield* identity.getEnvironmentId;
107 }).pipe(
108 Effect.tap(() => Deferred.succeed(firstInitialized, undefined)),
109 Effect.provide(Layer.fresh(ServerEnvironment.identityLayer)),
110 Effect.provideService(ServerConfig.ServerConfig, serverConfig),
111 Effect.provideService(FileSystem.FileSystem, {
112 ...fileSystem,
113 readFileString: (path) =>
114 fileSystem.readFileString(path).pipe(
115 Effect.tap(
116 Effect.fn(function* (value) {
117 if (path !== serverConfig.environmentIdPath || remaining > 0 || value.trim()) {
118 return;
119 }
120 // Both observe the empty file, but one repairs it after the other has finished.
121 if (++emptyReads === 2) {
122 yield* Deferred.succeed(bothReadEmpty, undefined);
123 yield* Deferred.await(firstInitialized);
124 } else {
125 yield* Deferred.await(bothReadEmpty);
126 }
127 }),
128 ),
129 ),
130 }),
131 Effect.provideService(Crypto.Crypto, {
132 ...crypto,
133 randomUUIDv4: Effect.gen(function* () {
134 const id = yield* crypto.randomUUIDv4;
135 if (--remaining === 0) {
136 yield* Deferred.succeed(bothGenerated, undefined);
137 }
138 yield* Deferred.await(bothGenerated);
139 return id;
140 }),
141 }),
142 );
143​
144 const [first, second] = yield* Effect.all([readIdentity, readIdentity], {
145 concurrency: "unbounded",
146 });
147 const persisted = yield* fileSystem.readFileString(serverConfig.environmentIdPath);
148​
149 expect(first).toBe(second);
150 expect(persisted.trim()).toBe(first);
151 }),
152 );
153​
154 it.effect("persists the environment id across service restarts", () =>
155 Effect.gen(function* () {
156 const fileSystem = yield* FileSystem.FileSystem;
157 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
158 prefix: "t3-server-environment-test-",
159 });
160​
161 const first = yield* Effect.gen(function* () {
162 const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
163 return yield* serverEnvironment.getDescriptor;
164 }).pipe(Effect.provide(makeServerEnvironmentLayer(baseDir)));
165 const second = yield* Effect.gen(function* () {
166 const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
167 return yield* serverEnvironment.getDescriptor;
168 }).pipe(Effect.provide(makeServerEnvironmentLayer(baseDir)));
169​
170 expect(first.environmentId).toBe(second.environmentId);
171 expect(first.orchestrationProtocolVersion).toBe(ORCHESTRATION_PROTOCOL_VERSION);
172 expect(second.capabilities.repositoryIdentity).toBe(true);
173 expect(second.capabilities.connectionProbe).toBe(true);
174 expect(second.capabilities.attachmentUploads).toBe(true);
175 expect(second.capabilities.fileAttachments).toEqual({ maxUploadBytes: 50 * 1024 * 1024 });
176 expect(second.capabilities.pullRequests).toBe(true);
177 expect(second.capabilities.requiredWorktreeBootstrap).toBe(true);
178 expect(second.capabilities.usagePriceOverrides).toBe(true);
179 expect(second.capabilities.threadActiveReorder).toBe(true);
180 expect(second.capabilities.threadTitleRegeneration).toBe(true);
181 expect(second.capabilities.threadPullRequests).toBe(true);
182 expect(second.capabilities.threadPullRequestLinking).toBe(true);
183 expect(second.capabilities.serverResolvedCommandContext).toBe(true);
184 expect(second.capabilities.agentActivityPublishing).toBe(false);
185 }),
186 );
187​
188 it.effect("reports agent activity publishing from the current secret state", () =>
189 Effect.gen(function* () {
190 const fileSystem = yield* FileSystem.FileSystem;
191 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
192 prefix: "t3-server-environment-publish-test-",
193 });
194 const testLayer = Layer.mergeAll(
195 ServerEnvironment.layer.pipe(Layer.provide(ServerSecretStore.layer)),
196 ServerSecretStore.layer,
197 ).pipe(Layer.provide(ServerConfig.layerTest(process.cwd(), baseDir)));
198​
199 yield* Effect.gen(function* () {
200 const secrets = yield* ServerSecretStore.ServerSecretStore;
201 const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
202 const encode = (value: string) => new TextEncoder().encode(value);
203​
204 const unlinked = yield* serverEnvironment.getDescriptor;
205 expect(unlinked.capabilities.agentActivityPublishing).toBe(false);
206​
207 // The opt-in alone is not enough: without relay link credentials no
208 // publish would leave this environment.
209 yield* secrets.set(PUBLISH_AGENT_ACTIVITY_SECRET, encode("true"));
210 const withoutLink = yield* serverEnvironment.getDescriptor;
211 expect(withoutLink.capabilities.agentActivityPublishing).toBe(false);
212​
213 // Empty credentials are as unconfigured as missing ones: the
214 // publisher's truthiness gate skips them, so the capability must not
215 // advertise publishing.
216 yield* secrets.set(RELAY_URL_SECRET, encode(""));
217 yield* secrets.set(RELAY_ENVIRONMENT_CREDENTIAL_SECRET, encode("credential"));
218 const emptyUrl = yield* serverEnvironment.getDescriptor;
219 expect(emptyUrl.capabilities.agentActivityPublishing).toBe(false);
220​
221 yield* secrets.set(RELAY_URL_SECRET, encode("https://relay.example"));
222 const linked = yield* serverEnvironment.getDescriptor;
223 expect(linked.capabilities.agentActivityPublishing).toBe(true);
224​
225 // The toggle changes at runtime, so the same service instance must
226 // reflect a flip without a restart.
227 yield* secrets.set(PUBLISH_AGENT_ACTIVITY_SECRET, encode("false"));
228 const disabled = yield* serverEnvironment.getDescriptor;
229 expect(disabled.capabilities.agentActivityPublishing).toBe(false);
230 }).pipe(Effect.provide(testLayer));
231 }),
232 );
233​
234 it.effect("advertises desktopAppUpdate only with desktop mode and the control fd", () =>
235 Effect.gen(function* () {
236 const fileSystem = yield* FileSystem.FileSystem;
237 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
238 prefix: "t3-server-environment-desktop-update-test-",
239 });
240 const serverConfig = yield* makeServerConfig(baseDir);
241 yield* fileSystem.makeDirectory(serverConfig.stateDir, { recursive: true });
242​
243 const describeWith = (overrides: Partial<ServerConfig.ServerConfig["Service"]>) =>
244 Effect.gen(function* () {
245 const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
246 return yield* serverEnvironment.getDescriptor;
247 }).pipe(
248 Effect.provide(
249 ServerEnvironment.layer.pipe(
250 Layer.provide(ServerSecretStore.layer),
251 Layer.provide(ServerConfig.layer({ ...serverConfig, ...overrides })),
252 ),
253 ),
254 );
255​
256 const withFd = yield* describeWith({ mode: "desktop", desktopTelemetryControlFd: 5 });
257 expect(withFd.capabilities.serverSelfUpdate).toBe("desktop-managed");
258 expect(withFd.capabilities.desktopAppUpdate).toBe(true);
259 expect(withFd.capabilities.serverSelfUpdateProgress).toBe(true);
260 // v2 recovery terminalizes running runs on restart, so continuation
261 // stays unadvertised until the v2 runtime carries the markers.
262 expect(withFd.capabilities.serverUpdateThreadContinuation).toBeUndefined();
263​
264 const withoutFd = yield* describeWith({ mode: "desktop" });
265 expect(withoutFd.capabilities.serverSelfUpdate).toBe("desktop-managed");
266 expect(withoutFd.capabilities.desktopAppUpdate).toBeUndefined();
267 expect(withoutFd.capabilities.serverSelfUpdateProgress).toBeUndefined();
268 expect(withoutFd.capabilities.serverUpdateThreadContinuation).toBeUndefined();
269​
270 const web = yield* describeWith({ mode: "web", desktopTelemetryControlFd: 5 });
271 expect(web.capabilities.desktopAppUpdate).toBeUndefined();
272 }),
273 );
274​
275 it.effect("structures persisted environment id filesystem failures", () =>
276 Effect.gen(function* () {
277 const fileSystem = yield* FileSystem.FileSystem;
278 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
279 prefix: "t3-server-environment-error-test-",
280 });
281 const serverConfig = yield* makeServerConfig(baseDir);
282 const environmentIdPath = serverConfig.environmentIdPath;
283 const tempPath = `${environmentIdPath}.tmp`;
284 const methodByOperation = {
285 check: "exists",
286 read: "readFileString",
287 write: "writeFileString",
288 } as const;
289​
290 for (const operation of ["check", "read", "write"] as const) {
291 const writeAttempts: string[] = [];
292 const cause = PlatformError.systemError({
293 _tag: "PermissionDenied",
294 module: "FileSystem",
295 method: methodByOperation[operation],
296 description: "permission denied",
297 pathOrDescriptor: environmentIdPath,
298 });
299 const failingFileSystemLayer = FileSystem.layerNoop({
300 exists: () =>
301 operation === "check" ? Effect.fail(cause) : Effect.succeed(operation === "read"),
302 readFileString: () => Effect.fail(cause),
303 makeTempFileScoped: () => Effect.succeed(tempPath),
304 writeFileString: (path) => {
305 writeAttempts.push(path);
306 return Effect.fail(cause);
307 },
308 });
309​
310 const error = yield* Effect.gen(function* () {
311 const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
312 return yield* serverEnvironment.getDescriptor;
313 }).pipe(
314 Effect.provide(
315 ServerEnvironment.layer.pipe(
316 Layer.provide(emptySecretStoreLayer),
317 Layer.provide(Layer.merge(ServerConfig.layer(serverConfig), failingFileSystemLayer)),
318 ),
319 ),
320 Effect.flip,
321 );
322​
323 expect(isServerEnvironmentIdPersistenceError(error)).toBe(true);
324 if (!isServerEnvironmentIdPersistenceError(error)) {
325 throw error;
326 }
327 expect(error.operation).toBe(operation);
328 expect(error.environmentIdPath).toBe(environmentIdPath);
329 expect(error.cause).toBe(cause);
330 expect(error.message).toBe(
331 `Server environment ID ${operation} failed at '${environmentIdPath}'.`,
332 );
333 expect(writeAttempts).toEqual(operation === "write" ? [tempPath] : []);
334 }
335 }),
336 );
337});