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

ServerEnvironment.test.ts

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