Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
TypeScript agentic-aiagentsaiai-agentsaiagentsdeveloper-toolsfunction-callinggpt-4javascriptjsllmllmopsmcppythonremote-mcp-serverssetypescript
fix(cli): add atomic file replacement
jkomynoe79846e00acc
diff --git a/ts/packages/cli/src/utils/atomic-replace.ts b/ts/packages/cli/src/utils/atomic-replace.tsnew file mode 100644index 000000000..8ed236bde--- /dev/null+++ b/ts/packages/cli/src/utils/atomic-replace.ts@@ -0,0 +1,110 @@+import { FileSystem, Path } from '@effect/platform';+import { Data, Effect, Scope } from 'effect';++export class AtomicReplaceError extends Data.TaggedError('utils/AtomicReplaceError')<{+ readonly targetPath: string;+ readonly message: string;+ readonly cause: unknown;+}> {}++type AtomicReplaceFileOptions = {+ readonly sourcePath: string;+ readonly targetPath: string;+ readonly mode?: number;+};++type AtomicReplaceDirectoryOptions = {+ readonly sourcePath: string;+ readonly targetPath: string;+};++export const atomicReplaceFile = ({+ sourcePath,+ targetPath,+ mode,+}: AtomicReplaceFileOptions): Effect.Effect<+ void,+ AtomicReplaceError,+ FileSystem.FileSystem | Path.Path | Scope.Scope+> =>+ Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const stagingDirectory = yield* fs.makeTempDirectoryScoped({+ directory: path.dirname(targetPath),+ prefix: '.composio-atomic-replace-',+ });+ const stagedPath = path.join(stagingDirectory, path.basename(targetPath));++ yield* fs.copyFile(sourcePath, stagedPath);+ if (mode !== undefined) {+ yield* fs.chmod(stagedPath, mode);+ }+ yield* fs.rename(stagedPath, targetPath);+ }).pipe(+ Effect.mapError(+ cause =>+ new AtomicReplaceError({+ targetPath,+ message: `Failed to replace file at ${targetPath}`,+ cause,+ })+ )+ );++/**+ * Replaces a directory with a staged copy using two renames. The old directory+ * is restored when publishing the replacement fails, but an abrupt process+ * exit between the renames can leave the target temporarily absent.+ */+export const atomicReplaceDirectory = ({+ sourcePath,+ targetPath,+}: AtomicReplaceDirectoryOptions): Effect.Effect<+ void,+ AtomicReplaceError,+ FileSystem.FileSystem | Path.Path | Scope.Scope+> =>+ Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const stagingDirectory = yield* fs.makeTempDirectoryScoped({+ directory: path.dirname(targetPath),+ prefix: '.composio-atomic-replace-',+ });+ const targetName = path.basename(targetPath);+ const stagedPath = path.join(stagingDirectory, targetName);+ const asidePath = path.join(stagingDirectory, `${targetName}.aside`);++ yield* fs.copy(sourcePath, stagedPath);++ if (!(yield* fs.exists(targetPath))) {+ yield* fs.rename(stagedPath, targetPath);+ return;+ }++ yield* Effect.uninterruptible(+ Effect.gen(function* () {+ yield* fs.rename(targetPath, asidePath);+ yield* fs+ .rename(stagedPath, targetPath)+ .pipe(+ Effect.catchAll(cause =>+ fs+ .rename(asidePath, targetPath)+ .pipe(Effect.ignore, Effect.zipRight(Effect.fail(cause)))+ )+ );+ yield* fs.remove(asidePath, { recursive: true });+ })+ );+ }).pipe(+ Effect.mapError(+ cause =>+ new AtomicReplaceError({+ targetPath,+ message: `Failed to replace directory at ${targetPath}`,+ cause,+ })+ )+ );diff --git a/ts/packages/cli/test/src/utils/atomic-replace.test.ts b/ts/packages/cli/test/src/utils/atomic-replace.test.tsnew file mode 100644index 000000000..3bd4ee09c--- /dev/null+++ b/ts/packages/cli/test/src/utils/atomic-replace.test.ts@@ -0,0 +1,99 @@+import { FileSystem, Path } from '@effect/platform';+import { BunFileSystem, BunPath } from '@effect/platform-bun';+import { describe, expect, layer } from '@effect/vitest';+import { Effect, Layer, Option } from 'effect';+import {+ AtomicReplaceError,+ atomicReplaceDirectory,+ atomicReplaceFile,+} from 'src/utils/atomic-replace';++const TestPlatform = Layer.mergeAll(BunFileSystem.layer, BunPath.layer);++describe('atomic replace', () => {+ layer(TestPlatform)(it => {+ it.scoped('replaces an existing file without modifying its open inode', () =>+ Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const directory = yield* fs.makeTempDirectoryScoped();+ const sourcePath = path.join(directory, 'source');+ const targetPath = path.join(directory, 'target');+ yield* fs.writeFileString(sourcePath, 'new contents');+ yield* fs.writeFileString(targetPath, 'old contents');++ const before = yield* fs.stat(targetPath);+ const oldTarget = yield* fs.open(targetPath);+ yield* Effect.scoped(atomicReplaceFile({ sourcePath, targetPath }));+ const after = yield* fs.stat(targetPath);+ const openContents = yield* oldTarget.readAlloc(FileSystem.Size('old contents'.length));++ expect(yield* fs.readFileString(targetPath)).toBe('new contents');+ expect(after.dev).toBe(before.dev);+ expect(Option.getOrThrow(after.ino)).not.toBe(Option.getOrThrow(before.ino));+ expect(new TextDecoder().decode(Option.getOrThrow(openContents))).toBe('old contents');+ expect((yield* fs.readDirectory(directory)).sort()).toEqual(['source', 'target']);+ })+ );++ it.scoped('creates an executable target when mode is provided', () =>+ Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const directory = yield* fs.makeTempDirectoryScoped();+ const sourcePath = path.join(directory, 'source');+ const targetPath = path.join(directory, 'target');+ yield* fs.writeFileString(sourcePath, 'binary');++ yield* Effect.scoped(atomicReplaceFile({ sourcePath, targetPath, mode: 0o755 }));++ expect(yield* fs.readFileString(targetPath)).toBe('binary');+ expect((yield* fs.stat(targetPath)).mode & 0o777).toBe(0o755);+ expect((yield* fs.readDirectory(directory)).sort()).toEqual(['source', 'target']);+ })+ );++ it.scoped('preserves the target and cleans staging when the source is missing', () =>+ Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const directory = yield* fs.makeTempDirectoryScoped();+ const sourcePath = path.join(directory, 'missing');+ const targetPath = path.join(directory, 'target');+ yield* fs.writeFileString(targetPath, 'old contents');++ const error = yield* Effect.flip(+ Effect.scoped(atomicReplaceFile({ sourcePath, targetPath }))+ );++ expect(error).toBeInstanceOf(AtomicReplaceError);+ expect(error.targetPath).toBe(targetPath);+ expect(error.cause).toBeDefined();+ expect(yield* fs.readFileString(targetPath)).toBe('old contents');+ expect(yield* fs.readDirectory(directory)).toEqual(['target']);+ })+ );++ it.scoped('replaces an existing non-empty directory without leaving residue', () =>+ Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const directory = yield* fs.makeTempDirectoryScoped();+ const sourcePath = path.join(directory, 'source');+ const targetPath = path.join(directory, 'target');+ yield* fs.makeDirectory(path.join(sourcePath, 'nested'), { recursive: true });+ yield* fs.writeFileString(path.join(sourcePath, 'nested', 'new.txt'), 'new contents');+ yield* fs.makeDirectory(targetPath);+ yield* fs.writeFileString(path.join(targetPath, 'old.txt'), 'old contents');++ yield* Effect.scoped(atomicReplaceDirectory({ sourcePath, targetPath }));++ expect(yield* fs.readFileString(path.join(targetPath, 'nested', 'new.txt'))).toBe(+ 'new contents'+ );+ expect(yield* fs.exists(path.join(targetPath, 'old.txt'))).toBe(false);+ expect((yield* fs.readDirectory(directory)).sort()).toEqual(['source', 'target']);+ })+ );+ });+});