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

ServerEnvironment.test.ts

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