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

ServerEnvironment.ts

276 lines9.7 KB

1import {
2 EnvironmentId,
3 PROVIDER_SEND_TURN_MAX_FILE_BYTES,
4 type ExecutionEnvironmentDescriptor,
5} from "@t3tools/contracts";
6import { HostProcessArchitecture, HostProcessPlatform } from "@t3tools/shared/hostProcess";
7import * as Context from "effect/Context";
8import * as Crypto from "effect/Crypto";
9import * as Effect from "effect/Effect";
10import * as FileSystem from "effect/FileSystem";
11import * as Layer from "effect/Layer";
12import * as Path from "effect/Path";
13import * as Schema from "effect/Schema";
14​
15import packageJson from "../../package.json" with { type: "json" };
16import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
17import { readAgentActivityPublishingActive } from "../cloud/config.ts";
18import { resolveServerSelfUpdateCapability } from "../cloud/selfUpdate.ts";
19import { resolveServiceLauncherMode } from "../cloud/serviceLauncherClient.ts";
20import * as ServerConfig from "../config.ts";
21import * as ProcessRunner from "../processRunner.ts";
22import { resolveServerEnvironmentLabel } from "./ServerEnvironmentLabel.ts";
23import { detectServerEnvironmentMachineKind } from "./ServerEnvironmentMachine.ts";
24​
25export class ServerEnvironmentIdPersistenceError extends Schema.TaggedError<ServerEnvironmentIdPersistenceError>()(
26 "ServerEnvironmentIdPersistenceError",
27 {
28 operation: Schema.Literals(["check", "read", "write", "initialize"]),
29 environmentIdPath: Schema.String,
30 cause: Schema.optional(Schema.Defect()),
31 },
32) {
33 override get message(): string {
34 if (this.operation === "initialize") {
35 return `Server environment ID file is missing or empty after initialization at '${this.environmentIdPath}'.`;
36 }
37 return `Server environment ID ${this.operation} failed at '${this.environmentIdPath}'.`;
38 }
40​
41export class ServerEnvironment extends Context.Service<
42 ServerEnvironment,
43 {
44 readonly getEnvironmentId: Effect.Effect<EnvironmentId>;
45 readonly getDescriptor: Effect.Effect<ExecutionEnvironmentDescriptor>;
46 }
47>()("t3/environment/ServerEnvironment") {}
48​
49export class ServerEnvironmentIdentity extends Context.Service<
50 ServerEnvironmentIdentity,
51 {
52 readonly getEnvironmentId: Effect.Effect<EnvironmentId>;
53 }
54>()("t3/environment/ServerEnvironment/ServerEnvironmentIdentity") {}
55​
56function platformOs(platform: NodeJS.Platform): ExecutionEnvironmentDescriptor["platform"]["os"] {
57 switch (platform) {
58 case "darwin":
59 return "darwin";
60 case "linux":
61 return "linux";
62 case "win32":
63 return "windows";
64 default:
65 return "unknown";
66 }
68​
69function platformArch(
70 architecture: NodeJS.Architecture,
71): ExecutionEnvironmentDescriptor["platform"]["arch"] {
72 switch (architecture) {
73 case "arm64":
74 return "arm64";
75 case "x64":
76 return "x64";
77 default:
78 return "other";
79 }
81​
82const makeIdentity = Effect.gen(function* () {
83 const fileSystem = yield* FileSystem.FileSystem;
84 const serverConfig = yield* ServerConfig.ServerConfig;
85 const crypto = yield* Crypto.Crypto;
86​
87 const readPersistedEnvironmentId = Effect.gen(function* () {
88 const exists = yield* fileSystem.exists(serverConfig.environmentIdPath).pipe(
89 Effect.mapError(
90 (cause) =>
91 new ServerEnvironmentIdPersistenceError({
92 operation: "check",
93 environmentIdPath: serverConfig.environmentIdPath,
94 cause,
95 }),
96 ),
97 );
98 if (!exists) {
99 return null;
100 }
101​
102 const raw = yield* fileSystem.readFileString(serverConfig.environmentIdPath).pipe(
103 Effect.map((value) => value.trim()),
104 Effect.mapError(
105 (cause) =>
106 new ServerEnvironmentIdPersistenceError({
107 operation: "read",
108 environmentIdPath: serverConfig.environmentIdPath,
109 cause,
110 }),
111 ),
112 );
113​
114 return raw.length > 0 ? raw : null;
115 });
116​
117 const persistEnvironmentId = Effect.fn("ServerEnvironmentIdentity.persistEnvironmentId")(
118 function* (value: string, mode: "create" | "recover") {
119 const destinationPath =
120 mode === "recover"
121 ? `${serverConfig.environmentIdPath}.recovery`
122 : serverConfig.environmentIdPath;
123 const tempPath = yield* fileSystem.makeTempFileScoped({
124 directory: serverConfig.stateDir,
125 prefix: ".environment-id-",
126 });
127 yield* fileSystem.writeFileString(tempPath, `${value}\n`);
128 // Publish the completed file without replacing an ID created by another process.
129 yield* fileSystem
130 .link(tempPath, destinationPath)
131 .pipe(
132 Effect.catch((cause) =>
133 cause.reason._tag === "AlreadyExists" ? Effect.void : Effect.fail(cause),
134 ),
135 );
136 if (mode === "recover") {
137 // Keep the recovery ID so delayed initializers also publish the same winner.
138 yield* fileSystem.remove(tempPath);
139 yield* fileSystem.copyFile(destinationPath, tempPath);
140 yield* fileSystem.rename(tempPath, serverConfig.environmentIdPath);
141 }
142 },
143 Effect.scoped,
144 Effect.mapError(
145 (cause) =>
146 new ServerEnvironmentIdPersistenceError({
147 operation: "write",
148 environmentIdPath: serverConfig.environmentIdPath,
149 cause,
150 }),
151 ),
152 );
153​
154 const environmentIdRaw = yield* Effect.gen(function* () {
155 const persisted = yield* readPersistedEnvironmentId;
156 if (persisted) {
157 return persisted;
158 }
159​
160 const generated = yield* crypto.randomUUIDv4;
161 yield* persistEnvironmentId(generated, "create");
162 let winner = yield* readPersistedEnvironmentId;
163 if (winner === null) {
164 yield* persistEnvironmentId(generated, "recover");
165 winner = yield* readPersistedEnvironmentId;
166 }
167 if (winner === null) {
168 return yield* new ServerEnvironmentIdPersistenceError({
169 operation: "initialize",
170 environmentIdPath: serverConfig.environmentIdPath,
171 });
172 }
173 return winner;
174 });
175​
176 const environmentId = EnvironmentId.make(environmentIdRaw);
177 return ServerEnvironmentIdentity.of({
178 getEnvironmentId: Effect.succeed(environmentId),
179 });
180});
181​
182/** @public Service construction is part of the canonical Effect module API. */
183export const make = Effect.gen(function* () {
184 const path = yield* Path.Path;
185 const serverConfig = yield* ServerConfig.ServerConfig;
186 const secrets = yield* ServerSecretStore.ServerSecretStore;
187 const identity = yield* ServerEnvironmentIdentity;
188 const hostPlatform = yield* HostProcessPlatform;
189 const hostArchitecture = yield* HostProcessArchitecture;
190 const environmentId = yield* identity.getEnvironmentId;
191 const cwdBaseName = path.basename(serverConfig.cwd).trim();
192 const label = yield* resolveServerEnvironmentLabel({ cwdBaseName });
193 const machine = yield* detectServerEnvironmentMachineKind();
194 const launcher = yield* resolveServiceLauncherMode();
195 const serverSelfUpdate = resolveServerSelfUpdateCapability({
196 desktopManaged: serverConfig.mode === "desktop",
197 launcherManaged: launcher.managed,
198 });
199 // Static is correct: the control fd is known at bootstrap, and the desktop
200 // app and its bundled server ship in one artifact, so a present fd means
201 // the app speaks the requestDesktopUpdate protocol. WSL backends never get
202 // the fd and correctly do not advertise.
203 const desktopAppUpdate =
204 serverSelfUpdate === "desktop-managed" && serverConfig.desktopTelemetryControlFd !== undefined;
205​
206 const descriptor: ExecutionEnvironmentDescriptor = {
207 environmentId,
208 label,
209 platform: {
210 os: platformOs(hostPlatform),
211 arch: platformArch(hostArchitecture),
212 ...(machine === null ? {} : { machine }),
213 },
214 serverVersion: packageJson.version,
215 capabilities: {
216 repositoryIdentity: true,
217 connectionProbe: true,
218 attachmentUploads: true,
219 questionAttachments: true,
220 fileAttachments: { maxUploadBytes: PROVIDER_SEND_TURN_MAX_FILE_BYTES },
221 pullRequests: true,
222 inlineMessageContext: true,
223 threadSettlement: true,
224 threadAutoSettlement: true,
225 threadRestartContinuation: true,
226 projectSettingsOverrides: true,
227 threadSnooze: true,
228 environmentThemes: true,
229 usageLimitSources: true,
230 usagePriceOverrides: true,
231 threadPinning: true,
232 threadPinReorder: true,
233 threadActiveReorder: true,
234 threadTitleRegeneration: true,
235 threadPullRequests: true,
236 pullRequestStackActions: true,
237 threadPullRequestLinking: true,
238 environmentIcon: true,
239 projectCloneTracking: true,
240 ...(serverSelfUpdate === null ? {} : { serverSelfUpdate }),
241 ...(serverSelfUpdate === "boot-service" || desktopAppUpdate
242 ? {
243 serverSelfUpdateProgress: true,
244 serverUpdateThreadContinuation: true,
245 }
246 : {}),
247 ...(desktopAppUpdate ? { desktopAppUpdate: true } : {}),
248 },
249 };
250​
251 return ServerEnvironment.of({
252 getEnvironmentId: Effect.succeed(environmentId),
253 // The publish opt-in and relay link change at runtime (`t3 connect
254 // publish`, the client settings toggle), so the capability is read per
255 // descriptor request rather than baked in at startup.
256 getDescriptor: readAgentActivityPublishingActive(secrets).pipe(
257 Effect.map((agentActivityPublishing) => ({
258 ...descriptor,
259 capabilities: { ...descriptor.capabilities, agentActivityPublishing },
260 })),
261 ),
262 });
263});
264​
265export const identityLayer = Layer.effect(ServerEnvironmentIdentity, makeIdentity);
266​
267/**
268 * ServerEnvironment is acquired from persisted filesystem and host-process
269 * state. It intentionally has no fallback Layer.succeed value: callers must
270 * provide the external platform services, a ServerConfig, and the
271 * ServerSecretStore backing the descriptor's publishing capability.
272 */
273export const layer = Layer.effect(ServerEnvironment, make).pipe(
274 Layer.provideMerge(identityLayer),
275 Layer.provide(ProcessRunner.layer),
276);