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

ServerEnvironment.ts

180 lines6.0 KB

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