1
+import { FileSystem, Path } from '@effect/platform';
2
+import * as PlatformError from '@effect/platform/Error';
3
+import { BunFileSystem, BunPath } from '@effect/platform-bun';
4
+import { describe, expect, layer } from '@effect/vitest';
5
+import { Deferred, Effect, Fiber, Layer } from 'effect';
6
+import { atomicWritePrivateFileString, ensurePrivateFileMode } from 'src/utils/atomic-write';
7
+
8
+const TestPlatform = Layer.mergeAll(BunFileSystem.layer, BunPath.layer);
9
+
10
+const failChmod = (fs: FileSystem.FileSystem, onAttempt: () => void): FileSystem.FileSystem =>
11
+ new Proxy(fs, {
12
+ get(target, property, receiver) {
13
+ if (property !== 'chmod') {
14
+ return Reflect.get(target, property, receiver);
15
+ }
16
+
17
+ return (path: string) => {
18
+ onAttempt();
19
+ return Effect.fail(
20
+ new PlatformError.SystemError({
21
+ reason: 'PermissionDenied',
22
+ module: 'FileSystem',
23
+ method: 'chmod',
24
+ pathOrDescriptor: path,
25
+ })
26
+ );
27
+ };
28
+ },
29
+ });
30
+
31
+const collideWithTmpWrites = (
32
+ fs: FileSystem.FileSystem,
33
+ maxCollisions: number,
34
+ onCollision: (path: string) => void
35
+): FileSystem.FileSystem => {
36
+ let collisions = 0;
37
+
38
+ return new Proxy(fs, {
39
+ get(target, property, receiver) {
40
+ if (property !== 'writeFileString') {
41
+ return Reflect.get(target, property, receiver);
42
+ }
43
+
44
+ return (path: string, contents: string, options?: FileSystem.WriteFileOptions) => {
45
+ if (collisions >= maxCollisions || !path.includes('.composio-tmp.')) {
46
+ return target.writeFileString(path, contents, options);
47
+ }
48
+
49
+ collisions += 1;
50
+ onCollision(path);
51
+ return target
52
+ .writeFileString(path, 'pre-existing contents')
53
+ .pipe(Effect.andThen(target.writeFileString(path, contents, options)));
54
+ };
55
+ },
56
+ });
57
+};
58
+
59
+const delayAfterTmpWrite = (
60
+ fs: FileSystem.FileSystem,
61
+ onStaged: Effect.Effect<void>,
62
+ release: Effect.Effect<void>
63
+): FileSystem.FileSystem =>
64
+ new Proxy(fs, {
65
+ get(target, property, receiver) {
66
+ if (property !== 'writeFileString') {
67
+ return Reflect.get(target, property, receiver);
68
+ }
69
+
70
+ return (path: string, contents: string, options?: FileSystem.WriteFileOptions) =>
71
+ target.writeFileString(path, contents, options).pipe(
72
+ Effect.tap(() => onStaged),
73
+ Effect.andThen(release)
74
+ );
75
+ },
76
+ });
77
+
78
+const failAfterTmpWrite = (fs: FileSystem.FileSystem): FileSystem.FileSystem =>
79
+ new Proxy(fs, {
80
+ get(target, property, receiver) {
81
+ if (property !== 'writeFileString') {
82
+ return Reflect.get(target, property, receiver);
83
+ }
84
+
85
+ return (path: string, contents: string, options?: FileSystem.WriteFileOptions) => {
86
+ if (!path.includes('.composio-tmp.')) {
87
+ return target.writeFileString(path, contents, options);
88
+ }
89
+
90
+ return target.writeFileString(path, contents, options).pipe(
91
+ Effect.andThen(
92
+ Effect.fail(
93
+ new PlatformError.SystemError({
94
+ reason: 'PermissionDenied',
95
+ module: 'FileSystem',
96
+ method: 'writeFileString',
97
+ pathOrDescriptor: path,
98
+ })
99
+ )
100
+ )
101
+ );
102
+ };
103
+ },
104
+ });
105
+
106
+describe('atomicWritePrivateFileString', () => {
107
+ layer(TestPlatform)(it => {
108
+ it.scoped('retries an exclusive random staging path without touching a collision', () =>
109
+ Effect.gen(function* () {
110
+ const fs = yield* FileSystem.FileSystem;
111
+ const path = yield* Path.Path;
112
+ const directory = yield* fs.makeTempDirectoryScoped();
113
+ const target = path.join(directory, 'credentials.json');
114
+ let collisionPath: string | undefined;
115
+ const collidingFs = collideWithTmpWrites(fs, 1, collidedPath => {
116
+ collisionPath = collidedPath;
117
+ });
118
+
119
+ yield* atomicWritePrivateFileString({
120
+ fs: collidingFs,
121
+ target,
122
+ contents: '{"api_key":"valid"}\n',
123
+ });
124
+
125
+ expect(collisionPath).toBeDefined();
126
+ expect(yield* fs.readFileString(collisionPath!, 'utf8')).toBe('pre-existing contents');
127
+ expect(yield* fs.readFileString(target, 'utf8')).toBe('{"api_key":"valid"}\n');
128
+ expect((yield* fs.stat(target)).mode & 0o777).toBe(0o600);
129
+ })
130
+ );
131
+
132
+ it.scoped('stops after bounded collisions without deleting foreign files', () =>
133
+ Effect.gen(function* () {
134
+ const fs = yield* FileSystem.FileSystem;
135
+ const path = yield* Path.Path;
136
+ const directory = yield* fs.makeTempDirectoryScoped();
137
+ const target = path.join(directory, 'credentials.json');
138
+ const collisionPaths: string[] = [];
139
+ const collidingFs = collideWithTmpWrites(fs, Number.POSITIVE_INFINITY, collisionPath => {
140
+ collisionPaths.push(collisionPath);
141
+ });
142
+
143
+ const error = yield* atomicWritePrivateFileString({
144
+ fs: collidingFs,
145
+ target,
146
+ contents: '{"api_key":"valid"}\n',
147
+ }).pipe(Effect.flip);
148
+
149
+ expect(error).toMatchObject({ _tag: 'SystemError', reason: 'AlreadyExists' });
150
+ expect(collisionPaths).toHaveLength(5);
151
+ expect(new Set(collisionPaths)).toHaveLength(5);
152
+ expect(yield* fs.exists(target)).toBe(false);
153
+ for (const collisionPath of collisionPaths) {
154
+ expect(yield* fs.readFileString(collisionPath, 'utf8')).toBe('pre-existing contents');
155
+ }
156
+ })
157
+ );
158
+
159
+ it.scoped('cleans staging before honoring interruption', () =>
160
+ Effect.gen(function* () {
161
+ const fs = yield* FileSystem.FileSystem;
162
+ const path = yield* Path.Path;
163
+ const directory = yield* fs.makeTempDirectoryScoped();
164
+ const target = path.join(directory, 'credentials.json');
165
+ yield* fs.writeFileString(target, '{"api_key":"old"}\n');
166
+ yield* fs.chmod(target, 0o600);
167
+ const staged = yield* Deferred.make<void>();
168
+ const release = yield* Deferred.make<void>();
169
+ const delayedFs = delayAfterTmpWrite(
170
+ fs,
171
+ Deferred.succeed(staged, undefined),
172
+ Deferred.await(release)
173
+ );
174
+ const fiber = yield* atomicWritePrivateFileString({
175
+ fs: delayedFs,
176
+ target,
177
+ contents: '{"api_key":"valid"}\n',
178
+ }).pipe(Effect.fork);
179
+
180
+ yield* Deferred.await(staged);
181
+ const interruptFiber = yield* Fiber.interrupt(fiber).pipe(Effect.fork);
182
+ yield* Effect.yieldNow();
183
+ yield* Deferred.succeed(release, undefined);
184
+ yield* Fiber.join(interruptFiber);
185
+
186
+ expect(yield* fs.readFileString(target, 'utf8')).toBe('{"api_key":"old"}\n');
187
+ expect((yield* fs.stat(target)).mode & 0o777).toBe(0o600);
188
+ expect(
189
+ (yield* fs.readDirectory(directory)).filter(name => name.includes('.composio-tmp.'))
190
+ ).toEqual([]);
191
+ })
192
+ );
193
+
194
+ it.scoped('cleans a partially written staging file on non-collision failure', () =>
195
+ Effect.gen(function* () {
196
+ const fs = yield* FileSystem.FileSystem;
197
+ const path = yield* Path.Path;
198
+ const directory = yield* fs.makeTempDirectoryScoped();
199
+ const target = path.join(directory, 'credentials.json');
200
+ yield* fs.writeFileString(target, '{"api_key":"old"}\n');
201
+ yield* fs.chmod(target, 0o600);
202
+
203
+ const error = yield* atomicWritePrivateFileString({
204
+ fs: failAfterTmpWrite(fs),
205
+ target,
206
+ contents: '{"api_key":"new"}\n',
207
+ }).pipe(Effect.flip);
208
+
209
+ expect(error).toMatchObject({ _tag: 'SystemError', reason: 'PermissionDenied' });
210
+ expect(yield* fs.readFileString(target, 'utf8')).toBe('{"api_key":"old"}\n');
211
+ expect(
212
+ (yield* fs.readDirectory(directory)).filter(name => name.includes('.composio-tmp.'))
213
+ ).toEqual([]);
214
+ })
215
+ );
216
+ });
217
+});
218
+
219
+describe('ensurePrivateFileMode', () => {
220
+ layer(TestPlatform)(it => {
221
+ it.scoped('keeps valid contents readable when chmod fails', () =>
222
+ Effect.gen(function* () {
223
+ const fs = yield* FileSystem.FileSystem;
224
+ const path = yield* Path.Path;
225
+ const directory = yield* fs.makeTempDirectoryScoped();
226
+ const target = path.join(directory, 'credentials.json');
227
+ const contents = '{"api_key":"valid"}\n';
228
+ yield* fs.writeFileString(target, contents);
229
+ yield* fs.chmod(target, 0o644);
230
+
231
+ let chmodAttempts = 0;
232
+ const failingFs = failChmod(fs, () => {
233
+ chmodAttempts += 1;
234
+ });
235
+ const readContents = yield* ensurePrivateFileMode({ fs: failingFs, target }).pipe(
236
+ Effect.andThen(failingFs.readFileString(target, 'utf8'))
237
+ );
238
+
239
+ expect(chmodAttempts).toBe(1);
240
+ expect(readContents).toBe(contents);
241
+ expect((yield* fs.stat(target)).mode & 0o777).toBe(0o644);
242
+ })
243
+ );
244
+
245
+ it.scoped('does not call chmod for an already-private file', () =>
246
+ Effect.gen(function* () {
247
+ const fs = yield* FileSystem.FileSystem;
248
+ const path = yield* Path.Path;
249
+ const directory = yield* fs.makeTempDirectoryScoped();
250
+ const target = path.join(directory, 'credentials.json');
251
+ yield* fs.writeFileString(target, '{"api_key":"valid"}\n');
252
+ yield* fs.chmod(target, 0o600);
253
+
254
+ let chmodAttempts = 0;
255
+ const failingFs = failChmod(fs, () => {
256
+ chmodAttempts += 1;
257
+ });
258
+ yield* ensurePrivateFileMode({ fs: failingFs, target });
259
+
260
+ expect(chmodAttempts).toBe(0);
261
+ })
262
+ );
263
+ });
264
+});