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

ServerEnvironment.ts

269 lines9.6 KB

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