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