|
1 | | -import { existsSync, readFileSync, statSync, writeFileSync } from 'fs'; // eslint-disable-line no-restricted-imports -- files being checked |
2 | | -import { writeFile } from 'fs/promises'; |
| 1 | +import { existsSync, readFileSync, renameSync, statSync, writeFileSync } from 'fs'; // eslint-disable-line no-restricted-imports -- files being checked |
| 2 | +import { rename, writeFile } from 'fs/promises'; |
3 | 3 | import { join } from 'path'; |
4 | 4 | import { Logger } from 'pino'; |
5 | 5 | import { lock, LockOptions, lockSync } from 'proper-lockfile'; |
@@ -28,18 +28,15 @@ export class EncryptedFileStore implements DataStore { |
28 | 28 | this.telemetry = TelemetryService.instance.get(`FileStore.${name}`); |
29 | 29 |
|
30 | 30 | if (existsSync(this.file)) { |
| 31 | + const release = lockSync(this.file, LOCK_OPTIONS_SYNC); |
31 | 32 | try { |
32 | 33 | this.content = this.readFile(); |
33 | 34 | } catch (error) { |
34 | 35 | this.log.error(error, 'Failed to decrypt file store, recreating store'); |
35 | 36 | this.telemetry.count('filestore.recreate', 1); |
36 | | - |
37 | | - const release = lockSync(this.file, LOCK_OPTIONS_SYNC); |
38 | | - try { |
39 | | - this.saveSync(); |
40 | | - } finally { |
41 | | - release(); |
42 | | - } |
| 37 | + this.saveSync(); |
| 38 | + } finally { |
| 39 | + release(); |
43 | 40 | } |
44 | 41 | } else { |
45 | 42 | this.saveSync(); |
@@ -113,11 +110,15 @@ export class EncryptedFileStore implements DataStore { |
113 | 110 | } |
114 | 111 |
|
115 | 112 | private saveSync() { |
116 | | - writeFileSync(this.file, encrypt(this.KEY, JSON.stringify(this.content))); |
| 113 | + const tmp = `${this.file}.${process.pid}.tmp`; |
| 114 | + writeFileSync(tmp, encrypt(this.KEY, JSON.stringify(this.content))); |
| 115 | + renameSync(tmp, this.file); |
117 | 116 | } |
118 | 117 |
|
119 | 118 | private async save() { |
120 | | - await writeFile(this.file, encrypt(this.KEY, JSON.stringify(this.content))); |
| 119 | + const tmp = `${this.file}.${process.pid}.tmp`; |
| 120 | + await writeFile(tmp, encrypt(this.KEY, JSON.stringify(this.content))); |
| 121 | + await rename(tmp, this.file); |
121 | 122 | } |
122 | 123 | } |
123 | 124 |
|
|
0 commit comments