Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off
2import * as NodeFS from "node:fs";
3import * as NodeServices from "@effect/platform-node/NodeServices";
4import { it as effectIt } from "@effect/vitest";
5import * as Effect from "effect/Effect";
6import * as FileSystem from "effect/FileSystem";
7import * as Path from "effect/Path";
8import * as PlatformError from "effect/PlatformError";
9import * as Schema from "effect/Schema";
10import { expect, vi } from "vite-plus/test";
11
12import { makeAsyncRotatingFileSink, RotatingFileSink, RotatingFileSinkError } from "./logging.ts";
13
14vi.mock("node:fs", { spy: true });
15const { renameSync, rmSync } = await vi.importActual<typeof NodeFS>("node:fs");
16const modes = ["synchronous", "asynchronous"] as const;
17const isRotatingFileSinkError = Schema.is(RotatingFileSinkError);
18
19const openSink = Effect.fnUntraced(function* (
20 mode: (typeof modes)[number],
21 filePath: string,
22 maxBytes: number,
23 maxFiles: number,
24 deny: (source: string, target: string) => boolean = () => false,
25 { throwOnError = true, denyRemove = (_path: string) => false } = {},
26) {
27 const fs = yield* FileSystem.FileSystem;
28 const denied = (source: string) =>
29 PlatformError.systemError({
30 _tag: "PermissionDenied",
31 module: "FileSystem",
32 method: "rename",
33 pathOrDescriptor: source,
34 });
35 if (mode === "synchronous") {
36 const spy = vi.mocked(NodeFS.renameSync);
37 const removeSpy = vi.mocked(NodeFS.rmSync);
38 const run = <A>(action: () => A) => {
39 try {
40 spy.mockImplementation((source, target) => {
41 if (deny(String(source), String(target))) throw denied(String(source));
42 renameSync(source, target);
43 });
44 removeSpy.mockImplementation((path, options) => {
45 if (denyRemove(String(path))) throw denied(String(path));
46 rmSync(path, options);
47 });
48 return action();
49 } finally {
50 spy.mockReset();
51 removeSpy.mockReset();
52 }
53 };
54 const sink = run(() => new RotatingFileSink({ filePath, maxBytes, maxFiles, throwOnError }));
55 return {
56 write: (chunk: string) =>
57 Effect.try({
58 try: () => run(() => sink.write(chunk)),
59 catch: (cause) =>
60 isRotatingFileSinkError(cause)
61 ? cause
62 : new RotatingFileSinkError({ operation: "write", filePath, cause }),
63 }),
64 };
65 }
66 return yield* makeAsyncRotatingFileSink({ filePath, maxBytes, maxFiles }).pipe(
67 Effect.provideService(FileSystem.FileSystem, {
68 ...fs,
69 rename: (source, target) =>
70 deny(source, target) ? Effect.fail(denied(source)) : fs.rename(source, target),
71 remove: (name, options) =>
72 denyRemove(name) ? Effect.fail(denied(name)) : fs.remove(name, options),
73 }),
74 );
75});
76
77effectIt.layer(NodeServices.layer)("log rotation recovery", (it) => {
78 it.effect.each(
79 modes.flatMap((mode) => [
80 { mode, active: false, backup: false },
81 { mode, active: true, backup: true },
82 ]),
83 )(
84 "$mode sink recovers staged history with active=$active and backup=$backup",
85 ({ mode, active, backup }) =>
86 Effect.gen(function* () {
87 const fs = yield* FileSystem.FileSystem;
88 const path = yield* Path.Path;
89 const directory = yield* fs.makeTempDirectoryScoped();
90 const filePath = path.join(directory, "provider.log");
91 yield* fs.writeFileString(`${filePath}.rotating`, "staged");
92 if (active) yield* fs.writeFileString(filePath, "active");
93 if (backup) yield* fs.writeFileString(`${filePath}.1`, "backup");
94
95 const sink = yield* openSink(mode, filePath, 6, 3);
96 yield* sink.write("next");
97
98 expect(yield* fs.exists(`${filePath}.rotating`)).toBe(false);
99 expect(yield* fs.readFileString(filePath)).toBe("next");
100 expect(yield* fs.readFileString(`${filePath}.1`)).toBe(active ? "active" : "staged");
101 if (active) expect(yield* fs.readFileString(`${filePath}.2`)).toBe("staged");
102 if (backup) expect(yield* fs.readFileString(`${filePath}.3`)).toBe("backup");
103 }),
104 );
105
106 it.effect.each(
107 modes.flatMap((mode) => (["stage", "publish"] as const).map((phase) => ({ mode, phase }))),
108 )(
109 "$mode sink preserves every backup when $phase fails and writes after it clears",
110 ({ mode, phase }) =>
111 Effect.gen(function* () {
112 const fs = yield* FileSystem.FileSystem;
113 const path = yield* Path.Path;
114 const directory = yield* fs.makeTempDirectoryScoped();
115 const filePath = path.join(directory, "provider.log");
116 const history = [
117 [filePath, "active"],
118 [`${filePath}.1`, "previous"],
119 [`${filePath}.2`, "oldest"],
120 ] as const;
121 for (const [name, content] of history) yield* fs.writeFileString(name, content);
122 let denials = 0;
123 const sink = yield* openSink(
124 mode,
125 filePath,
126 6,
127 2,
128 (source, target) =>
129 (phase === "stage"
130 ? source === filePath
131 : source === `${filePath}.rotating` && target === `${filePath}.1`) && denials++ < 2,
132 );
133
134 for (const attempt of [1, 2]) {
135 const failed = yield* sink.write("next").pipe(Effect.flip);
136 expect(failed).toMatchObject({ operation: "rotate" });
137 expect(denials).toBe(attempt);
138 for (const [name, content] of history) {
139 expect(yield* fs.readFileString(name)).toBe(content);
140 }
141 }
142 yield* sink.write("next");
143 expect(yield* fs.readFileString(filePath)).toBe("next");
144 expect(yield* fs.readFileString(`${filePath}.1`)).toBe("active");
145 expect(yield* fs.readFileString(`${filePath}.2`)).toBe("previous");
146 expect((yield* fs.readDirectory(directory)).sort()).toEqual([
147 "provider.log",
148 "provider.log.1",
149 "provider.log.2",
150 ]);
151 }),
152 );
153
154 it.effect.each(modes)("%s sink retries blocked recovery before writing after reopen", (mode) =>
155 Effect.gen(function* () {
156 const fs = yield* FileSystem.FileSystem;
157 const path = yield* Path.Path;
158 const directory = yield* fs.makeTempDirectoryScoped();
159 const filePath = path.join(directory, "provider.log");
160 yield* fs.writeFileString(filePath, "active");
161 yield* fs.writeFileString(`${filePath}.1`, "previous");
162 yield* fs.writeFileString(`${filePath}.2`, "oldest");
163 let locked = true;
164 const deny = (source: string, target: string) =>
165 locked &&
166 target === `${filePath}.1` &&
167 (source === `${filePath}.rotating` || source === `${filePath}.2`);
168 const sink = yield* openSink(mode, filePath, 9, 2, deny);
169 expect(yield* sink.write("next").pipe(Effect.flip)).toMatchObject({ operation: "rotate" });
170
171 const reopened = yield* openSink(mode, filePath, 9, 2, deny);
172 expect(yield* reopened.write("ok").pipe(Effect.flip)).toMatchObject({ operation: "rotate" });
173 expect(yield* fs.exists(filePath)).toBe(false);
174 expect(yield* fs.readFileString(`${filePath}.rotating`)).toBe("active");
175 expect(yield* fs.readFileString(`${filePath}.2`)).toBe("previous");
176 expect(yield* fs.readFileString(`${filePath}.rotating.oldest`)).toBe("oldest");
177
178 locked = false;
179 yield* reopened.write("ok");
180 expect(yield* fs.readFileString(filePath)).toBe("activeok");
181 expect(yield* fs.readFileString(`${filePath}.1`)).toBe("previous");
182 expect(yield* fs.readFileString(`${filePath}.2`)).toBe("oldest");
183 expect((yield* fs.readDirectory(directory)).sort()).toEqual([
184 "provider.log",
185 "provider.log.1",
186 "provider.log.2",
187 ]);
188 }),
189 );
190
191 it.effect.each(modes.flatMap((mode) => [".oldest", ".json"].map((suffix) => ({ mode, suffix }))))(
192 "$mode sink appends while committed cleanup of $suffix is blocked",
193 ({ mode, suffix }) =>
194 Effect.gen(function* () {
195 const fs = yield* FileSystem.FileSystem;
196 const path = yield* Path.Path;
197 const directory = yield* fs.makeTempDirectoryScoped();
198 const filePath = path.join(directory, "provider.log");
199 const blockedPath = `${filePath}.rotating${suffix}`;
200 yield* fs.writeFileString(filePath, "active");
201 yield* fs.writeFileString(`${filePath}.1`, "previous");
202 let locked = true;
203 const options = { denyRemove: (name: string) => locked && name === blockedPath };
204 const sink = yield* openSink(mode, filePath, 6, 1, undefined, options);
205 yield* sink.write("first");
206 const reopened = yield* openSink(mode, filePath, 6, 1, undefined, options);
207 yield* reopened.write("second");
208 expect(yield* fs.readFileString(filePath)).toBe("firstsecond");
209 expect(yield* fs.readFileString(`${filePath}.1`)).toBe("active");
210 expect(yield* fs.exists(blockedPath)).toBe(true);
211
212 locked = false;
213 yield* reopened.write("third");
214 expect(yield* fs.readFileString(filePath)).toBe("third");
215 expect(yield* fs.readFileString(`${filePath}.1`)).toBe("firstsecond");
216 expect(yield* fs.exists(blockedPath)).toBe(false);
217 }),
218 );
219
220 it.effect("best-effort writes continue while rollback is blocked", () =>
221 Effect.gen(function* () {
222 const fs = yield* FileSystem.FileSystem;
223 const path = yield* Path.Path;
224 const directory = yield* fs.makeTempDirectoryScoped();
225 const filePath = path.join(directory, "provider.log");
226 yield* fs.writeFileString(filePath, "active");
227 yield* fs.writeFileString(`${filePath}.1`, "previous");
228 let locked = true;
229 const deny = (source: string, target: string) =>
230 locked &&
231 target === `${filePath}.1` &&
232 (source === `${filePath}.rotating` || source === `${filePath}.2`);
233 const options = { throwOnError: false };
234 const sink = yield* openSink("synchronous", filePath, 9, 2, deny, options);
235 yield* sink.write("next");
236 const reopened = yield* openSink("synchronous", filePath, 9, 2, deny, options);
237 yield* reopened.write("ok");
238 expect(yield* fs.readFileString(filePath)).toBe("nextok");
239 expect(yield* fs.readFileString(`${filePath}.rotating`)).toBe("active");
240
241 locked = false;
242 yield* reopened.write("yes");
243 expect(yield* fs.readFileString(filePath)).toBe("nextokyes");
244 expect(yield* fs.readFileString(`${filePath}.1`)).toBe("active");
245 expect(yield* fs.readFileString(`${filePath}.2`)).toBe("previous");
246 }),
247 );
248});