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

ServerEnvironment.ts

92 lines2.7 KB

1import { EnvironmentId, type ExecutionEnvironmentDescriptor } from "@workbench/contracts";
2import { Effect, FileSystem, Layer, Path, Random } from "effect";
3​
4import { ServerConfig } from "../../config.ts";
5import { ServerEnvironment, type ServerEnvironmentShape } from "../Services/ServerEnvironment.ts";
6import packageJson from "../../../package.json" with { type: "json" };
7import { resolveServerEnvironmentLabel } from "./ServerEnvironmentLabel.ts";
8​
9function platformOs(): ExecutionEnvironmentDescriptor["platform"]["os"] {
10 switch (process.platform) {
11 case "darwin":
12 return "darwin";
13 case "linux":
14 return "linux";
15 case "win32":
16 return "windows";
17 default:
18 return "unknown";
19 }
21​
22function platformArch(): ExecutionEnvironmentDescriptor["platform"]["arch"] {
23 switch (process.arch) {
24 case "arm64":
25 return "arm64";
26 case "x64":
27 return "x64";
28 default:
29 return "other";
30 }
32​
33export const makeServerEnvironment = Effect.fn("makeServerEnvironment")(function* () {
34 const fileSystem = yield* FileSystem.FileSystem;
35 const path = yield* Path.Path;
36 const serverConfig = yield* ServerConfig;
37​
38 const readPersistedEnvironmentId = Effect.gen(function* () {
39 const exists = yield* fileSystem
40 .exists(serverConfig.environmentIdPath)
41 .pipe(Effect.orElseSucceed(() => false));
42 if (!exists) {
43 return null;
44 }
45​
46 const raw = yield* fileSystem
47 .readFileString(serverConfig.environmentIdPath)
48 .pipe(Effect.map((value) => value.trim()));
49​
50 return raw.length > 0 ? raw : null;
51 });
52​
53 const persistEnvironmentId = (value: string) =>
54 fileSystem.writeFileString(serverConfig.environmentIdPath, `${value}\n`);
55​
56 const environmentIdRaw = yield* Effect.gen(function* () {
57 const persisted = yield* readPersistedEnvironmentId;
58 if (persisted) {
59 return persisted;
60 }
61​
62 const generated = yield* Random.nextUUIDv4;
63 yield* persistEnvironmentId(generated);
64 return generated;
65 });
66​
67 const environmentId = EnvironmentId.make(environmentIdRaw);
68 const cwdBaseName = path.basename(serverConfig.cwd).trim();
69 const label = yield* resolveServerEnvironmentLabel({
70 cwdBaseName,
71 });
72​
73 const descriptor: ExecutionEnvironmentDescriptor = {
74 environmentId,
75 label,
76 platform: {
77 os: platformOs(),
78 arch: platformArch(),
79 },
80 serverVersion: packageJson.version,
81 capabilities: {
82 repositoryIdentity: true,
83 },
84 };
85​
86 return {
87 getEnvironmentId: Effect.succeed(environmentId),
88 getDescriptor: Effect.succeed(descriptor),
89 } satisfies ServerEnvironmentShape;
90});
91​
92export const ServerEnvironmentLive = Layer.effect(ServerEnvironment, makeServerEnvironment());