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

ServerEnvironment.ts

188 lines6.2 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";
23​
24export class ServerEnvironmentIdPersistenceError extends Schema.TaggedErrorClass<ServerEnvironmentIdPersistenceError>()(
25 "ServerEnvironmentIdPersistenceError",
26 {
27 operation: Schema.Literals(["check", "read", "write"]),
28 environmentIdPath: Schema.String,
29 cause: Schema.Defect(),
30 },
31) {
32 override get message(): string {
33 return `Server environment ID ${this.operation} failed at '${this.environmentIdPath}'.`;
34 }
36​
37export class ServerEnvironment extends Context.Service<
38 ServerEnvironment,
39 {
40 readonly getEnvironmentId: Effect.Effect<EnvironmentId>;
41 readonly getDescriptor: Effect.Effect<ExecutionEnvironmentDescriptor>;
42 }
43>()("t3/environment/ServerEnvironment") {}
44​
45function platformOs(platform: NodeJS.Platform): ExecutionEnvironmentDescriptor["platform"]["os"] {
46 switch (platform) {
47 case "darwin":
48 return "darwin";
49 case "linux":
50 return "linux";
51 case "win32":
52 return "windows";
53 default:
54 return "unknown";
55 }
57​
58function platformArch(
59 architecture: NodeJS.Architecture,
60): ExecutionEnvironmentDescriptor["platform"]["arch"] {
61 switch (architecture) {
62 case "arm64":
63 return "arm64";
64 case "x64":
65 return "x64";
66 default:
67 return "other";
68 }
70​
71export const make = Effect.gen(function* () {
72 const fileSystem = yield* FileSystem.FileSystem;
73 const path = yield* Path.Path;
74 const serverConfig = yield* ServerConfig.ServerConfig;
75 const secrets = yield* ServerSecretStore.ServerSecretStore;
76 const crypto = yield* Crypto.Crypto;
77 const hostPlatform = yield* HostProcessPlatform;
78 const hostArchitecture = yield* HostProcessArchitecture;
79​
80 const readPersistedEnvironmentId = Effect.gen(function* () {
81 const exists = yield* fileSystem.exists(serverConfig.environmentIdPath).pipe(
82 Effect.mapError(
83 (cause) =>
84 new ServerEnvironmentIdPersistenceError({
85 operation: "check",
86 environmentIdPath: serverConfig.environmentIdPath,
87 cause,
88 }),
89 ),
90 );
91 if (!exists) {
92 return null;
93 }
94​
95 const raw = yield* fileSystem.readFileString(serverConfig.environmentIdPath).pipe(
96 Effect.map((value) => value.trim()),
97 Effect.mapError(
98 (cause) =>
99 new ServerEnvironmentIdPersistenceError({
100 operation: "read",
101 environmentIdPath: serverConfig.environmentIdPath,
102 cause,
103 }),
104 ),
105 );
106​
107 return raw.length > 0 ? raw : null;
108 });
109​
110 const persistEnvironmentId = (value: string) =>
111 fileSystem.writeFileString(serverConfig.environmentIdPath, `${value}\n`).pipe(
112 Effect.mapError(
113 (cause) =>
114 new ServerEnvironmentIdPersistenceError({
115 operation: "write",
116 environmentIdPath: serverConfig.environmentIdPath,
117 cause,
118 }),
119 ),
120 );
121​
122 const environmentIdRaw = yield* Effect.gen(function* () {
123 const persisted = yield* readPersistedEnvironmentId;
124 if (persisted) {
125 return persisted;
126 }
127​
128 const generated = yield* crypto.randomUUIDv4;
129 yield* persistEnvironmentId(generated);
130 return generated;
131 });
132​
133 const environmentId = EnvironmentId.make(environmentIdRaw);
134 const cwdBaseName = path.basename(serverConfig.cwd).trim();
135 const label = yield* resolveServerEnvironmentLabel({ cwdBaseName });
136 const launcher = yield* resolveServiceLauncherMode();
137 const serverSelfUpdate = resolveServerSelfUpdateCapability({
138 desktopManaged: serverConfig.mode === "desktop",
139 launcherManaged: launcher.managed,
140 });
141​
142 const descriptor: ExecutionEnvironmentDescriptor = {
143 environmentId,
144 label,
145 platform: {
146 os: platformOs(hostPlatform),
147 arch: platformArch(hostArchitecture),
148 },
149 serverVersion: packageJson.version,
150 capabilities: {
151 repositoryIdentity: true,
152 connectionProbe: true,
153 attachmentUploads: true,
154 fileAttachments: { maxUploadBytes: PROVIDER_SEND_TURN_MAX_FILE_BYTES },
155 pullRequests: true,
156 threadSettlement: true,
157 threadSnooze: true,
158 environmentThemes: true,
159 threadPinning: true,
160 threadPinReorder: true,
161 threadTitleRegeneration: true,
162 threadPullRequestLinking: true,
163 ...(serverSelfUpdate === null ? {} : { serverSelfUpdate }),
164 ...(serverSelfUpdate === "boot-service" ? { serverSelfUpdateProgress: true } : {}),
165 },
166 };
167​
168 return ServerEnvironment.of({
169 getEnvironmentId: Effect.succeed(environmentId),
170 // The publish opt-in and relay link change at runtime (`t3 connect
171 // publish`, the client settings toggle), so the capability is read per
172 // descriptor request rather than baked in at startup.
173 getDescriptor: readAgentActivityPublishingActive(secrets).pipe(
174 Effect.map((agentActivityPublishing) => ({
175 ...descriptor,
176 capabilities: { ...descriptor.capabilities, agentActivityPublishing },
177 })),
178 ),
179 });
180});
181​
182/**
183 * ServerEnvironment is acquired from persisted filesystem and host-process
184 * state. It intentionally has no fallback Layer.succeed value: callers must
185 * provide the external platform services, a ServerConfig, and the
186 * ServerSecretStore backing the descriptor's publishing capability.
187 */
188export const layer = Layer.effect(ServerEnvironment, make).pipe(Layer.provide(ProcessRunner.layer));