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

ServerEnvironment.test.ts

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