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

ServerEnvironment.test.ts

205 lines8.1 KB

1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { expect, it } from "@effect/vitest";
3import * as Effect from "effect/Effect";
4import * as FileSystem from "effect/FileSystem";
5import * as Layer from "effect/Layer";
6import * as Option from "effect/Option";
7import * as PlatformError from "effect/PlatformError";
8import * as Schema from "effect/Schema";
9​
10import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
11import {
12 PUBLISH_AGENT_ACTIVITY_SECRET,
13 RELAY_ENVIRONMENT_CREDENTIAL_SECRET,
14 RELAY_URL_SECRET,
15} from "../cloud/config.ts";
16import * as ServerConfig from "../config.ts";
17import * as ServerEnvironment from "./ServerEnvironment.ts";
18​
19const isServerEnvironmentIdPersistenceError = Schema.is(
20 ServerEnvironment.ServerEnvironmentIdPersistenceError,
21);
22​
23const makeServerEnvironmentLayer = (baseDir: string) =>
24 ServerEnvironment.layer.pipe(
25 Layer.provide(ServerSecretStore.layer),
26 Layer.provide(ServerConfig.layerTest(process.cwd(), baseDir)),
27 );
28​
29const emptySecretStoreLayer = Layer.succeed(
30 ServerSecretStore.ServerSecretStore,
31 ServerSecretStore.ServerSecretStore.of({
32 get: () => Effect.succeed(Option.none()),
33 set: () => Effect.void,
34 create: () => Effect.void,
35 getOrCreateRandom: () => Effect.succeed(new Uint8Array()),
36 remove: () => Effect.void,
37 }),
38);
39​
40const makeServerConfig = Effect.fn(function* (baseDir: string) {
41 const derivedPaths = yield* ServerConfig.deriveServerPaths(baseDir, undefined);
42​
43 return {
44 ...derivedPaths,
45 logLevel: "Error",
46 traceMinLevel: "Info",
47 traceTimingEnabled: true,
48 traceBatchWindowMs: 200,
49 traceMaxBytes: 10 * 1024 * 1024,
50 traceMaxFiles: 10,
51 otlpTracesUrl: undefined,
52 otlpMetricsUrl: undefined,
53 otlpExportIntervalMs: 10_000,
54 otlpServiceName: "t3-server",
55 cwd: process.cwd(),
56 baseDir,
57 mode: "web",
58 autoBootstrapProjectFromCwd: false,
59 logWebSocketEvents: false,
60 tailscaleServeEnabled: false,
61 tailscaleServePort: 443,
62 port: 0,
63 host: undefined,
64 desktopBootstrapToken: undefined,
65 staticDir: undefined,
66 devUrl: undefined,
67 devAllowedOrigins: [],
68 noBrowser: false,
69 startupPresentation: "browser",
70 } satisfies ServerConfig.ServerConfig["Service"];
71});
72​
73it.layer(NodeServices.layer)("ServerEnvironmentLive", (it) => {
74 it.effect("persists the environment id across service restarts", () =>
75 Effect.gen(function* () {
76 const fileSystem = yield* FileSystem.FileSystem;
77 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
78 prefix: "t3-server-environment-test-",
79 });
80​
81 const first = yield* Effect.gen(function* () {
82 const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
83 return yield* serverEnvironment.getDescriptor;
84 }).pipe(Effect.provide(makeServerEnvironmentLayer(baseDir)));
85 const second = yield* Effect.gen(function* () {
86 const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
87 return yield* serverEnvironment.getDescriptor;
88 }).pipe(Effect.provide(makeServerEnvironmentLayer(baseDir)));
89​
90 expect(first.environmentId).toBe(second.environmentId);
91 expect(second.capabilities.repositoryIdentity).toBe(true);
92 expect(second.capabilities.connectionProbe).toBe(true);
93 expect(second.capabilities.pullRequests).toBe(true);
94 expect(second.capabilities.threadTitleRegeneration).toBe(true);
95 expect(second.capabilities.agentActivityPublishing).toBe(false);
96 }),
97 );
98​
99 it.effect("reports agent activity publishing from the current secret state", () =>
100 Effect.gen(function* () {
101 const fileSystem = yield* FileSystem.FileSystem;
102 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
103 prefix: "t3-server-environment-publish-test-",
104 });
105 const testLayer = Layer.mergeAll(
106 ServerEnvironment.layer.pipe(Layer.provide(ServerSecretStore.layer)),
107 ServerSecretStore.layer,
108 ).pipe(Layer.provide(ServerConfig.layerTest(process.cwd(), baseDir)));
109​
110 yield* Effect.gen(function* () {
111 const secrets = yield* ServerSecretStore.ServerSecretStore;
112 const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
113 const encode = (value: string) => new TextEncoder().encode(value);
114​
115 const unlinked = yield* serverEnvironment.getDescriptor;
116 expect(unlinked.capabilities.agentActivityPublishing).toBe(false);
117​
118 // The opt-in alone is not enough: without relay link credentials no
119 // publish would leave this environment.
120 yield* secrets.set(PUBLISH_AGENT_ACTIVITY_SECRET, encode("true"));
121 const withoutLink = yield* serverEnvironment.getDescriptor;
122 expect(withoutLink.capabilities.agentActivityPublishing).toBe(false);
123​
124 // Empty credentials are as unconfigured as missing ones: the
125 // publisher's truthiness gate skips them, so the capability must not
126 // advertise publishing.
127 yield* secrets.set(RELAY_URL_SECRET, encode(""));
128 yield* secrets.set(RELAY_ENVIRONMENT_CREDENTIAL_SECRET, encode("credential"));
129 const emptyUrl = yield* serverEnvironment.getDescriptor;
130 expect(emptyUrl.capabilities.agentActivityPublishing).toBe(false);
131​
132 yield* secrets.set(RELAY_URL_SECRET, encode("https://relay.example"));
133 const linked = yield* serverEnvironment.getDescriptor;
134 expect(linked.capabilities.agentActivityPublishing).toBe(true);
135​
136 // The toggle changes at runtime, so the same service instance must
137 // reflect a flip without a restart.
138 yield* secrets.set(PUBLISH_AGENT_ACTIVITY_SECRET, encode("false"));
139 const disabled = yield* serverEnvironment.getDescriptor;
140 expect(disabled.capabilities.agentActivityPublishing).toBe(false);
141 }).pipe(Effect.provide(testLayer));
142 }),
143 );
144​
145 it.effect("structures persisted environment id filesystem failures", () =>
146 Effect.gen(function* () {
147 const fileSystem = yield* FileSystem.FileSystem;
148 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
149 prefix: "t3-server-environment-error-test-",
150 });
151 const serverConfig = yield* makeServerConfig(baseDir);
152 const environmentIdPath = serverConfig.environmentIdPath;
153 const methodByOperation = {
154 check: "exists",
155 read: "readFileString",
156 write: "writeFileString",
157 } as const;
158​
159 for (const operation of ["check", "read", "write"] as const) {
160 const writeAttempts: string[] = [];
161 const cause = PlatformError.systemError({
162 _tag: "PermissionDenied",
163 module: "FileSystem",
164 method: methodByOperation[operation],
165 description: "permission denied",
166 pathOrDescriptor: environmentIdPath,
167 });
168 const failingFileSystemLayer = FileSystem.layerNoop({
169 exists: () =>
170 operation === "check" ? Effect.fail(cause) : Effect.succeed(operation === "read"),
171 readFileString: () => Effect.fail(cause),
172 writeFileString: (path) => {
173 writeAttempts.push(path);
174 return Effect.fail(cause);
175 },
176 });
177​
178 const error = yield* Effect.gen(function* () {
179 const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
180 return yield* serverEnvironment.getDescriptor;
181 }).pipe(
182 Effect.provide(
183 ServerEnvironment.layer.pipe(
184 Layer.provide(emptySecretStoreLayer),
185 Layer.provide(Layer.merge(ServerConfig.layer(serverConfig), failingFileSystemLayer)),
186 ),
187 ),
188 Effect.flip,
189 );
190​
191 expect(isServerEnvironmentIdPersistenceError(error)).toBe(true);
192 if (!isServerEnvironmentIdPersistenceError(error)) {
193 throw error;
194 }
195 expect(error.operation).toBe(operation);
196 expect(error.environmentIdPath).toBe(environmentIdPath);
197 expect(error.cause).toBe(cause);
198 expect(error.message).toBe(
199 `Server environment ID ${operation} failed at '${environmentIdPath}'.`,
200 );
201 expect(writeAttempts).toEqual(operation === "write" ? [environmentIdPath] : []);
202 }
203 }),
204 );
205});