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

ServerEnvironment.test.ts

328 lines13.6 KB

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