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