| 1 | // Copyright Jerome Benoit. 2021. All Rights Reserved. |
| 2 | |
| 3 | import fs from 'fs'; |
| 4 | |
| 5 | import lockfile from 'proper-lockfile'; |
| 6 | |
| 7 | import { FileType } from '../../types/FileType'; |
| 8 | import type { Statistics } from '../../types/Statistics'; |
| 9 | import FileUtils from '../../utils/FileUtils'; |
| 10 | import Utils from '../../utils/Utils'; |
| 11 | import { Storage } from './Storage'; |
| 12 | |
| 13 | export class JsonFileStorage extends Storage { |
| 14 | private fd: number | null = null; |
| 15 | |
| 16 | constructor(storageUri: string, logPrefix: string) { |
| 17 | super(storageUri, logPrefix); |
| 18 | this.dbName = this.storageUri.pathname; |
| 19 | } |
| 20 | |
| 21 | public storePerformanceStatistics(performanceStatistics: Statistics): void { |
| 22 | this.checkPerformanceRecordsFile(); |
| 23 | lockfile |
| 24 | .lock(this.dbName, { stale: 5000, retries: 3 }) |
| 25 | .then(async (release) => { |
| 26 | try { |
| 27 | const fileData = fs.readFileSync(this.dbName, 'utf8'); |
| 28 | const performanceRecords: Statistics[] = fileData |
| 29 | ? (JSON.parse(fileData) as Statistics[]) |
| 30 | : []; |
| 31 | performanceRecords.push(performanceStatistics); |
| 32 | fs.writeFileSync( |
| 33 | this.dbName, |
| 34 | Utils.JSONStringifyWithMapSupport(performanceRecords, 2), |
| 35 | 'utf8' |
| 36 | ); |
| 37 | } catch (error) { |
| 38 | FileUtils.handleFileException( |
| 39 | this.logPrefix, |
| 40 | FileType.PerformanceRecords, |
| 41 | this.dbName, |
| 42 | error as NodeJS.ErrnoException |
| 43 | ); |
| 44 | } |
| 45 | await release(); |
| 46 | }) |
| 47 | .catch(() => { |
| 48 | /* This is intentional */ |
| 49 | }); |
| 50 | } |
| 51 | |
| 52 | public open(): void { |
| 53 | try { |
| 54 | if (!this?.fd) { |
| 55 | this.fd = fs.openSync(this.dbName, 'a+'); |
| 56 | } |
| 57 | } catch (error) { |
| 58 | FileUtils.handleFileException( |
| 59 | this.logPrefix, |
| 60 | FileType.PerformanceRecords, |
| 61 | this.dbName, |
| 62 | error as NodeJS.ErrnoException |
| 63 | ); |
| 64 | } |
| 65 | } |
| 66 | |
| 67 | public close(): void { |
| 68 | try { |
| 69 | if (this?.fd) { |
| 70 | fs.closeSync(this.fd); |
| 71 | this.fd = null; |
| 72 | } |
| 73 | } catch (error) { |
| 74 | FileUtils.handleFileException( |
| 75 | this.logPrefix, |
| 76 | FileType.PerformanceRecords, |
| 77 | this.dbName, |
| 78 | error as NodeJS.ErrnoException |
| 79 | ); |
| 80 | } |
| 81 | } |
| 82 | |
| 83 | private checkPerformanceRecordsFile(): void { |
| 84 | if (!this?.fd) { |
| 85 | throw new Error( |
| 86 | `${this.logPrefix} Performance records '${this.dbName}' file descriptor not found` |
| 87 | ); |
| 88 | } |
| 89 | } |
| 90 | } |