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

ServerEnvironment.test.ts

325 lines13.4 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.agentActivityPublishing).toBe(false);
175 }),
176 );
177​
178 it.effect("reports agent activity publishing from the current secret state", () =>
179 Effect.gen(function* () {
180 const fileSystem = yield* FileSystem.FileSystem;
181 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
182 prefix: "t3-server-environment-publish-test-",
183 });
184 const testLayer = Layer.mergeAll(
185 ServerEnvironment.layer.pipe(Layer.provide(ServerSecretStore.layer)),
186 ServerSecretStore.layer,
187 ).pipe(Layer.provide(ServerConfig.layerTest(process.cwd(), baseDir)));
188​
189 yield* Effect.gen(function* () {
190 const secrets = yield* ServerSecretStore.ServerSecretStore;
191 const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
192 const encode = (value: string) => new TextEncoder().encode(value);
193​
194 const unlinked = yield* serverEnvironment.getDescriptor;
195 expect(unlinked.capabilities.agentActivityPublishing).toBe(false);
196​
197 // The opt-in alone is not enough: without relay link credentials no
198 // publish would leave this environment.
199 yield* secrets.set(PUBLISH_AGENT_ACTIVITY_SECRET, encode("true"));
200 const withoutLink = yield* serverEnvironment.getDescriptor;
201 expect(withoutLink.capabilities.agentActivityPublishing).toBe(false);
202​
203 // Empty credentials are as unconfigured as missing ones: the
204 // publisher's truthiness gate skips them, so the capability must not
205 // advertise publishing.
206 yield* secrets.set(RELAY_URL_SECRET, encode(""));
207 yield* secrets.set(RELAY_ENVIRONMENT_CREDENTIAL_SECRET, encode("credential"));
208 const emptyUrl = yield* serverEnvironment.getDescriptor;
209 expect(emptyUrl.capabilities.agentActivityPublishing).toBe(false);
210​
211 yield* secrets.set(RELAY_URL_SECRET, encode("https://relay.example"));
212 const linked = yield* serverEnvironment.getDescriptor;
213 expect(linked.capabilities.agentActivityPublishing).toBe(true);
214​
215 // The toggle changes at runtime, so the same service instance must
216 // reflect a flip without a restart.
217 yield* secrets.set(PUBLISH_AGENT_ACTIVITY_SECRET, encode("false"));
218 const disabled = yield* serverEnvironment.getDescriptor;
219 expect(disabled.capabilities.agentActivityPublishing).toBe(false);
220 }).pipe(Effect.provide(testLayer));
221 }),
222 );
223​
224 it.effect("advertises desktopAppUpdate only with desktop mode and the control fd", () =>
225 Effect.gen(function* () {
226 const fileSystem = yield* FileSystem.FileSystem;
227 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
228 prefix: "t3-server-environment-desktop-update-test-",
229 });
230 const serverConfig = yield* makeServerConfig(baseDir);
231 yield* fileSystem.makeDirectory(serverConfig.stateDir, { recursive: true });
232​
233 const describeWith = (overrides: Partial<ServerConfig.ServerConfig["Service"]>) =>
234 Effect.gen(function* () {
235 const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
236 return yield* serverEnvironment.getDescriptor;
237 }).pipe(
238 Effect.provide(
239 ServerEnvironment.layer.pipe(
240 Layer.provide(ServerSecretStore.layer),
241 Layer.provide(ServerConfig.layer({ ...serverConfig, ...overrides })),
242 ),
243 ),
244 );
245​
246 const withFd = yield* describeWith({ mode: "desktop", desktopTelemetryControlFd: 5 });
247 expect(withFd.capabilities.serverSelfUpdate).toBe("desktop-managed");
248 expect(withFd.capabilities.desktopAppUpdate).toBe(true);
249 expect(withFd.capabilities.serverSelfUpdateProgress).toBe(true);
250 expect(withFd.capabilities.serverUpdateThreadContinuation).toBe(true);
251​
252 const withoutFd = yield* describeWith({ mode: "desktop" });
253 expect(withoutFd.capabilities.serverSelfUpdate).toBe("desktop-managed");
254 expect(withoutFd.capabilities.desktopAppUpdate).toBeUndefined();
255 expect(withoutFd.capabilities.serverSelfUpdateProgress).toBeUndefined();
256 expect(withoutFd.capabilities.serverUpdateThreadContinuation).toBeUndefined();
257​
258 const web = yield* describeWith({ mode: "web", desktopTelemetryControlFd: 5 });
259 expect(web.capabilities.desktopAppUpdate).toBeUndefined();
260 }),
261 );
262​
263 it.effect("structures persisted environment id filesystem failures", () =>
264 Effect.gen(function* () {
265 const fileSystem = yield* FileSystem.FileSystem;
266 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
267 prefix: "t3-server-environment-error-test-",
268 });
269 const serverConfig = yield* makeServerConfig(baseDir);
270 const environmentIdPath = serverConfig.environmentIdPath;
271 const tempPath = `${environmentIdPath}.tmp`;
272 const methodByOperation = {
273 check: "exists",
274 read: "readFileString",
275 write: "writeFileString",
276 } as const;
277​
278 for (const operation of ["check", "read", "write"] as const) {
279 const writeAttempts: string[] = [];
280 const cause = PlatformError.systemError({
281 _tag: "PermissionDenied",
282 module: "FileSystem",
283 method: methodByOperation[operation],
284 description: "permission denied",
285 pathOrDescriptor: environmentIdPath,
286 });
287 const failingFileSystemLayer = FileSystem.layerNoop({
288 exists: () =>
289 operation === "check" ? Effect.fail(cause) : Effect.succeed(operation === "read"),
290 readFileString: () => Effect.fail(cause),
291 makeTempFileScoped: () => Effect.succeed(tempPath),
292 writeFileString: (path) => {
293 writeAttempts.push(path);
294 return Effect.fail(cause);
295 },
296 });
297​
298 const error = yield* Effect.gen(function* () {
299 const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
300 return yield* serverEnvironment.getDescriptor;
301 }).pipe(
302 Effect.provide(
303 ServerEnvironment.layer.pipe(
304 Layer.provide(emptySecretStoreLayer),
305 Layer.provide(Layer.merge(ServerConfig.layer(serverConfig), failingFileSystemLayer)),
306 ),
307 ),
308 Effect.flip,
309 );
310​
311 expect(isServerEnvironmentIdPersistenceError(error)).toBe(true);
312 if (!isServerEnvironmentIdPersistenceError(error)) {
313 throw error;
314 }
315 expect(error.operation).toBe(operation);
316 expect(error.environmentIdPath).toBe(environmentIdPath);
317 expect(error.cause).toBe(cause);
318 expect(error.message).toBe(
319 `Server environment ID ${operation} failed at '${environmentIdPath}'.`,
320 );
321 expect(writeAttempts).toEqual(operation === "write" ? [tempPath] : []);
322 }
323 }),
324 );
325});