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

ServerEnvironment.ts

164 lines5.2 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 { resolveServerSelfUpdateCapability } from "../cloud/selfUpdate.ts";
13import * as ServerConfig from "../config.ts";
14import * as ProcessRunner from "../processRunner.ts";
15import { resolveServerEnvironmentLabel } from "./ServerEnvironmentLabel.ts";
16​
17export class ServerEnvironmentIdPersistenceError extends Schema.TaggedErrorClass<ServerEnvironmentIdPersistenceError>()(
18 "ServerEnvironmentIdPersistenceError",
19 {
20 operation: Schema.Literals(["check", "read", "write"]),
21 environmentIdPath: Schema.String,
22 cause: Schema.Defect(),
23 },
24) {
25 override get message(): string {
26 return `Server environment ID ${this.operation} failed at '${this.environmentIdPath}'.`;
27 }
29​
30export class ServerEnvironment extends Context.Service<
31 ServerEnvironment,
32 {
33 readonly getEnvironmentId: Effect.Effect<EnvironmentId>;
34 readonly getDescriptor: Effect.Effect<ExecutionEnvironmentDescriptor>;
35 }
36>()("t3/environment/ServerEnvironment") {}
37​
38function platformOs(platform: NodeJS.Platform): ExecutionEnvironmentDescriptor["platform"]["os"] {
39 switch (platform) {
40 case "darwin":
41 return "darwin";
42 case "linux":
43 return "linux";
44 case "win32":
45 return "windows";
46 default:
47 return "unknown";
48 }
50​
51function platformArch(
52 architecture: NodeJS.Architecture,
53): ExecutionEnvironmentDescriptor["platform"]["arch"] {
54 switch (architecture) {
55 case "arm64":
56 return "arm64";
57 case "x64":
58 return "x64";
59 default:
60 return "other";
61 }
63​
64export const make = Effect.gen(function* () {
65 const fileSystem = yield* FileSystem.FileSystem;
66 const path = yield* Path.Path;
67 const serverConfig = yield* ServerConfig.ServerConfig;
68 const crypto = yield* Crypto.Crypto;
69 const hostPlatform = yield* HostProcessPlatform;
70 const hostArchitecture = yield* HostProcessArchitecture;
71​
72 const readPersistedEnvironmentId = Effect.gen(function* () {
73 const exists = yield* fileSystem.exists(serverConfig.environmentIdPath).pipe(
74 Effect.mapError(
75 (cause) =>
76 new ServerEnvironmentIdPersistenceError({
77 operation: "check",
78 environmentIdPath: serverConfig.environmentIdPath,
79 cause,
80 }),
81 ),
82 );
83 if (!exists) {
84 return null;
85 }
86​
87 const raw = yield* fileSystem.readFileString(serverConfig.environmentIdPath).pipe(
88 Effect.map((value) => value.trim()),
89 Effect.mapError(
90 (cause) =>
91 new ServerEnvironmentIdPersistenceError({
92 operation: "read",
93 environmentIdPath: serverConfig.environmentIdPath,
94 cause,
95 }),
96 ),
97 );
98​
99 return raw.length > 0 ? raw : null;
100 });
101​
102 const persistEnvironmentId = (value: string) =>
103 fileSystem.writeFileString(serverConfig.environmentIdPath, `${value}\n`).pipe(
104 Effect.mapError(
105 (cause) =>
106 new ServerEnvironmentIdPersistenceError({
107 operation: "write",
108 environmentIdPath: serverConfig.environmentIdPath,
109 cause,
110 }),
111 ),
112 );
113​
114 const environmentIdRaw = yield* Effect.gen(function* () {
115 const persisted = yield* readPersistedEnvironmentId;
116 if (persisted) {
117 return persisted;
118 }
119​
120 const generated = yield* crypto.randomUUIDv4;
121 yield* persistEnvironmentId(generated);
122 return generated;
123 });
124​
125 const environmentId = EnvironmentId.make(environmentIdRaw);
126 const cwdBaseName = path.basename(serverConfig.cwd).trim();
127 const label = yield* resolveServerEnvironmentLabel({ cwdBaseName });
128 const serverSelfUpdate = yield* resolveServerSelfUpdateCapability({
129 desktopManaged: serverConfig.mode === "desktop",
130 });
131​
132 const descriptor: ExecutionEnvironmentDescriptor = {
133 environmentId,
134 label,
135 platform: {
136 os: platformOs(hostPlatform),
137 arch: platformArch(hostArchitecture),
138 },
139 serverVersion: packageJson.version,
140 capabilities: {
141 repositoryIdentity: true,
142 connectionProbe: true,
143 threadSettlement: true,
144 threadSnooze: true,
145 threadTitleRegeneration: true,
146 ...(serverSelfUpdate === null ? {} : { serverSelfUpdate }),
147 ...(serverSelfUpdate === "boot-service" || serverSelfUpdate === "respawn"
148 ? { serverSelfUpdateProgress: true }
149 : {}),
150 },
151 };
152​
153 return ServerEnvironment.of({
154 getEnvironmentId: Effect.succeed(environmentId),
155 getDescriptor: Effect.succeed(descriptor),
156 });
157});
158​
159/**
160 * ServerEnvironment is acquired from persisted filesystem and host-process
161 * state. It intentionally has no fallback Layer.succeed value: callers must
162 * provide the external platform services and a ServerConfig.
163 */
164export const layer = Layer.effect(ServerEnvironment, make).pipe(Layer.provide(ProcessRunner.layer));