Skip to content

Commit fb41229

Browse files
fix(server): atomically initialize environment identity
1 parent 3b74b69 commit fb41229

2 files changed

Lines changed: 80 additions & 13 deletions

File tree

‎apps/server/src/environment/ServerEnvironment.test.ts‎

Lines changed: 45 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
import * as NodeServices from "@effect/platform-node/NodeServices";
22
import { expect, it } from "@effect/vitest";
3+
import * as Crypto from "effect/Crypto";
4+
import * as Deferred from "effect/Deferred";
35
import * as Effect from "effect/Effect";
46
import * as FileSystem from "effect/FileSystem";
57
import * as Layer from "effect/Layer";
@@ -71,6 +73,46 @@ const makeServerConfig = Effect.fn(function* (baseDir: string) {
7173
});
7274

7375
it.layer(NodeServices.layer)("ServerEnvironmentLive", (it) => {
76+
it.effect("concurrent initializers use the same persisted environment id", () =>
77+
Effect.gen(function* () {
78+
const fileSystem = yield* FileSystem.FileSystem;
79+
const crypto = yield* Crypto.Crypto;
80+
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
81+
prefix: "t3-server-environment-concurrent-test-",
82+
});
83+
const serverConfig = yield* makeServerConfig(baseDir);
84+
yield* fileSystem.makeDirectory(serverConfig.stateDir, { recursive: true });
85+
const bothGenerated = yield* Deferred.make<void>();
86+
let remaining = 2;
87+
const readIdentity = Effect.gen(function* () {
88+
const identity = yield* ServerEnvironment.ServerEnvironmentIdentity;
89+
return yield* identity.getEnvironmentId;
90+
}).pipe(
91+
Effect.provide(Layer.fresh(ServerEnvironment.identityLayer)),
92+
Effect.provideService(ServerConfig.ServerConfig, serverConfig),
93+
Effect.provideService(Crypto.Crypto, {
94+
...crypto,
95+
randomUUIDv4: Effect.gen(function* () {
96+
const id = yield* crypto.randomUUIDv4;
97+
if (--remaining === 0) {
98+
yield* Deferred.succeed(bothGenerated, undefined);
99+
}
100+
yield* Deferred.await(bothGenerated);
101+
return id;
102+
}),
103+
}),
104+
);
105+
106+
const [first, second] = yield* Effect.all([readIdentity, readIdentity], {
107+
concurrency: "unbounded",
108+
});
109+
const persisted = yield* fileSystem.readFileString(serverConfig.environmentIdPath);
110+
111+
expect(first).toBe(second);
112+
expect(persisted.trim()).toBe(first);
113+
}),
114+
);
115+
74116
it.effect("persists the environment id across service restarts", () =>
75117
Effect.gen(function* () {
76118
const fileSystem = yield* FileSystem.FileSystem;
@@ -153,6 +195,7 @@ it.layer(NodeServices.layer)("ServerEnvironmentLive", (it) => {
153195
});
154196
const serverConfig = yield* makeServerConfig(baseDir);
155197
const environmentIdPath = serverConfig.environmentIdPath;
198+
const tempPath = `${environmentIdPath}.tmp`;
156199
const methodByOperation = {
157200
check: "exists",
158201
read: "readFileString",
@@ -172,6 +215,7 @@ it.layer(NodeServices.layer)("ServerEnvironmentLive", (it) => {
172215
exists: () =>
173216
operation === "check" ? Effect.fail(cause) : Effect.succeed(operation === "read"),
174217
readFileString: () => Effect.fail(cause),
218+
makeTempFileScoped: () => Effect.succeed(tempPath),
175219
writeFileString: (path) => {
176220
writeAttempts.push(path);
177221
return Effect.fail(cause);
@@ -201,7 +245,7 @@ it.layer(NodeServices.layer)("ServerEnvironmentLive", (it) => {
201245
expect(error.message).toBe(
202246
`Server environment ID ${operation} failed at '${environmentIdPath}'.`,
203247
);
204-
expect(writeAttempts).toEqual(operation === "write" ? [environmentIdPath] : []);
248+
expect(writeAttempts).toEqual(operation === "write" ? [tempPath] : []);
205249
}
206250
}),
207251
);

‎apps/server/src/environment/ServerEnvironment.ts‎

Lines changed: 35 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -110,17 +110,32 @@ const makeIdentity = Effect.gen(function* () {
110110
return raw.length > 0 ? raw : null;
111111
});
112112

113-
const persistEnvironmentId = (value: string) =>
114-
fileSystem.writeFileString(serverConfig.environmentIdPath, `${value}\n`).pipe(
115-
Effect.mapError(
116-
(cause) =>
117-
new ServerEnvironmentIdPersistenceError({
118-
operation: "write",
119-
environmentIdPath: serverConfig.environmentIdPath,
120-
cause,
121-
}),
122-
),
123-
);
113+
const persistEnvironmentId = Effect.fn("ServerEnvironmentIdentity.persistEnvironmentId")(
114+
function* (value: string) {
115+
const tempPath = yield* fileSystem.makeTempFileScoped({
116+
directory: serverConfig.stateDir,
117+
prefix: ".environment-id-",
118+
});
119+
yield* fileSystem.writeFileString(tempPath, `${value}\n`);
120+
// Publish the completed file without replacing an ID created by another process.
121+
yield* fileSystem
122+
.link(tempPath, serverConfig.environmentIdPath)
123+
.pipe(
124+
Effect.catch((cause) =>
125+
cause.reason._tag === "AlreadyExists" ? Effect.void : Effect.fail(cause),
126+
),
127+
);
128+
},
129+
Effect.scoped,
130+
Effect.mapError(
131+
(cause) =>
132+
new ServerEnvironmentIdPersistenceError({
133+
operation: "write",
134+
environmentIdPath: serverConfig.environmentIdPath,
135+
cause,
136+
}),
137+
),
138+
);
124139

125140
const environmentIdRaw = yield* Effect.gen(function* () {
126141
const persisted = yield* readPersistedEnvironmentId;
@@ -130,7 +145,15 @@ const makeIdentity = Effect.gen(function* () {
130145

131146
const generated = yield* crypto.randomUUIDv4;
132147
yield* persistEnvironmentId(generated);
133-
return generated;
148+
const winner = yield* readPersistedEnvironmentId;
149+
if (winner === null) {
150+
return yield* new ServerEnvironmentIdPersistenceError({
151+
operation: "read",
152+
environmentIdPath: serverConfig.environmentIdPath,
153+
cause: new Error("Environment ID file is missing or empty after initialization."),
154+
});
155+
}
156+
return winner;
134157
});
135158

136159
const environmentId = EnvironmentId.make(environmentIdRaw);

0 commit comments

Comments
 (0)