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

ServerEnvironment.ts

266 lines9.3 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.TaggedErrorClass<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​
182export const make = Effect.gen(function* () {
183 const path = yield* Path.Path;
184 const serverConfig = yield* ServerConfig.ServerConfig;
185 const secrets = yield* ServerSecretStore.ServerSecretStore;
186 const identity = yield* ServerEnvironmentIdentity;
187 const hostPlatform = yield* HostProcessPlatform;
188 const hostArchitecture = yield* HostProcessArchitecture;
189 const environmentId = yield* identity.getEnvironmentId;
190 const cwdBaseName = path.basename(serverConfig.cwd).trim();
191 const label = yield* resolveServerEnvironmentLabel({ cwdBaseName });
192 const machine = yield* detectServerEnvironmentMachineKind();
193 const launcher = yield* resolveServiceLauncherMode();
194 const serverSelfUpdate = resolveServerSelfUpdateCapability({
195 desktopManaged: serverConfig.mode === "desktop",
196 launcherManaged: launcher.managed,
197 });
198 // Static is correct: the control fd is known at bootstrap, and the desktop
199 // app and its bundled server ship in one artifact, so a present fd means
200 // the app speaks the requestDesktopUpdate protocol. WSL backends never get
201 // the fd and correctly do not advertise.
202 const desktopAppUpdate =
203 serverSelfUpdate === "desktop-managed" && serverConfig.desktopTelemetryControlFd !== undefined;
204​
205 const descriptor: ExecutionEnvironmentDescriptor = {
206 environmentId,
207 label,
208 platform: {
209 os: platformOs(hostPlatform),
210 arch: platformArch(hostArchitecture),
211 ...(machine === null ? {} : { machine }),
212 },
213 serverVersion: packageJson.version,
214 capabilities: {
215 repositoryIdentity: true,
216 connectionProbe: true,
217 attachmentUploads: true,
218 fileAttachments: { maxUploadBytes: PROVIDER_SEND_TURN_MAX_FILE_BYTES },
219 pullRequests: true,
220 threadSettlement: true,
221 threadAutoSettlement: true,
222 threadSnooze: true,
223 environmentThemes: true,
224 usageLimitSources: true,
225 threadPinning: true,
226 threadPinReorder: true,
227 threadTitleRegeneration: true,
228 threadPullRequestLinking: true,
229 environmentIcon: true,
230 ...(serverSelfUpdate === null ? {} : { serverSelfUpdate }),
231 ...(serverSelfUpdate === "boot-service" || desktopAppUpdate
232 ? {
233 serverSelfUpdateProgress: true,
234 serverUpdateThreadContinuation: true,
235 }
236 : {}),
237 ...(desktopAppUpdate ? { desktopAppUpdate: true } : {}),
238 },
239 };
240​
241 return ServerEnvironment.of({
242 getEnvironmentId: Effect.succeed(environmentId),
243 // The publish opt-in and relay link change at runtime (`t3 connect
244 // publish`, the client settings toggle), so the capability is read per
245 // descriptor request rather than baked in at startup.
246 getDescriptor: readAgentActivityPublishingActive(secrets).pipe(
247 Effect.map((agentActivityPublishing) => ({
248 ...descriptor,
249 capabilities: { ...descriptor.capabilities, agentActivityPublishing },
250 })),
251 ),
252 });
253});
254​
255export const identityLayer = Layer.effect(ServerEnvironmentIdentity, makeIdentity);
256​
257/**
258 * ServerEnvironment is acquired from persisted filesystem and host-process
259 * state. It intentionally has no fallback Layer.succeed value: callers must
260 * provide the external platform services, a ServerConfig, and the
261 * ServerSecretStore backing the descriptor's publishing capability.
262 */
263export const layer = Layer.effect(ServerEnvironment, make).pipe(
264 Layer.provideMerge(identityLayer),
265 Layer.provide(ProcessRunner.layer),
266);