Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
| 1 | import { Data, Effect, FileSystem, Path, Predicate, Schedule, Scope } from 'effect'; |
| 2 | |
| 3 | export class AtomicReplaceError extends Data.TaggedError('utils/AtomicReplaceError')<{ |
| 4 | readonly targetPath: string; |
| 5 | readonly message: string; |
| 6 | readonly cause: unknown; |
| 7 | }> {} |
| 8 | |
| 9 | type AtomicReplaceFileOptions = { |
| 10 | readonly sourcePath: string; |
| 11 | readonly targetPath: string; |
| 12 | readonly mode?: number; |
| 13 | /** Move an in-use Windows executable aside before installing its replacement. */ |
| 14 | readonly backupPath?: string; |
| 15 | }; |
| 16 | |
| 17 | export const atomicReplaceFile = ({ |
| 18 | sourcePath, |
| 19 | targetPath, |
| 20 | mode, |
| 21 | backupPath, |
| 22 | }: AtomicReplaceFileOptions): Effect.Effect< |
| 23 | void, |
| 24 | AtomicReplaceError, |
| 25 | FileSystem.FileSystem | Path.Path | Scope.Scope |
| 26 | > => |
| 27 | Effect.gen(function* () { |
| 28 | const fs = yield* FileSystem.FileSystem; |
| 29 | const path = yield* Path.Path; |
| 30 | const stagingDirectory = yield* fs.makeTempDirectoryScoped({ |
| 31 | directory: path.dirname(targetPath), |
| 32 | prefix: '.composio-atomic-replace-', |
| 33 | }); |
| 34 | const stagedPath = path.join(stagingDirectory, path.basename(targetPath)); |
| 35 | |
| 36 | yield* fs.copyFile(sourcePath, stagedPath); |
| 37 | if (mode !== undefined) { |
| 38 | yield* fs.chmod(stagedPath, mode); |
| 39 | } |
| 40 | if (backupPath === undefined || !(yield* fs.exists(targetPath))) { |
| 41 | yield* fs.rename(stagedPath, targetPath); |
| 42 | return; |
| 43 | } |
| 44 | |
| 45 | // A loaded Windows executable cannot be overwritten. Keep its old image |
| 46 | // until the next upgrade, when the process using it has exited. |
| 47 | yield* fs.remove(backupPath, { force: true }); |
| 48 | yield* Effect.uninterruptible( |
| 49 | fs.rename(targetPath, backupPath).pipe( |
| 50 | // Windows can briefly lock the new executable after a preceding upgrade. |
| 51 | Effect.retry({ |
| 52 | times: 10, |
| 53 | schedule: Schedule.spaced('200 millis'), |
| 54 | while: error => Predicate.isTagged(error.reason, 'Busy'), |
| 55 | }), |
| 56 | Effect.andThen( |
| 57 | fs |
| 58 | .rename(stagedPath, targetPath) |
| 59 | .pipe( |
| 60 | Effect.catch(cause => |
| 61 | fs.rename(backupPath, targetPath).pipe(Effect.andThen(Effect.fail(cause))) |
| 62 | ) |
| 63 | ) |
| 64 | ) |
| 65 | ) |
| 66 | ); |
| 67 | }).pipe( |
| 68 | Effect.mapError( |
| 69 | cause => |
| 70 | new AtomicReplaceError({ |
| 71 | targetPath, |
| 72 | message: `Failed to replace file at ${targetPath}`, |
| 73 | cause, |
| 74 | }) |
| 75 | ) |
| 76 | ); |