592504a77c73ae104035da36f6415f4bf2986ffb
[e-mobility-charging-stations-simulator.git] / src / performance / storage / JsonFileStorage.ts
1 // Copyright Jerome Benoit. 2021-2024. All Rights Reserved.
2
3 import { closeSync, existsSync, mkdirSync, openSync, writeSync } from 'node:fs'
4 import { dirname } from 'node:path'
5
6 import { BaseError } from '../../exception/index.js'
7 import { FileType, MapStringifyFormat, type Statistics } from '../../types/index.js'
8 import { AsyncLock, AsyncLockType, handleFileException, JSONStringify } from '../../utils/index.js'
9 import { Storage } from './Storage.js'
10
11 export class JsonFileStorage extends Storage {
12 private fd?: number
13
14 constructor (storageUri: string, logPrefix: string) {
15 super(storageUri, logPrefix)
16 this.dbName = this.storageUri.pathname
17 }
18
19 public storePerformanceStatistics (performanceStatistics: Statistics): void {
20 this.setPerformanceStatistics(performanceStatistics)
21 this.checkPerformanceRecordsFile()
22 AsyncLock.runExclusive(AsyncLockType.performance, () => {
23 writeSync(
24 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
25 this.fd!,
26 JSONStringify([...this.getPerformanceStatistics()], 2, MapStringifyFormat.object),
27 0,
28 'utf8'
29 )
30 }).catch(error => {
31 handleFileException(
32 this.dbName,
33 FileType.PerformanceRecords,
34 error as NodeJS.ErrnoException,
35 this.logPrefix
36 )
37 })
38 }
39
40 public open (): void {
41 try {
42 if (this.fd == null) {
43 if (!existsSync(dirname(this.dbName))) {
44 mkdirSync(dirname(this.dbName), { recursive: true })
45 }
46 this.fd = openSync(this.dbName, 'w')
47 }
48 } catch (error) {
49 handleFileException(
50 this.dbName,
51 FileType.PerformanceRecords,
52 error as NodeJS.ErrnoException,
53 this.logPrefix
54 )
55 }
56 }
57
58 public close (): void {
59 this.clearPerformanceStatistics()
60 try {
61 if (this.fd != null) {
62 closeSync(this.fd)
63 delete this.fd
64 }
65 } catch (error) {
66 handleFileException(
67 this.dbName,
68 FileType.PerformanceRecords,
69 error as NodeJS.ErrnoException,
70 this.logPrefix
71 )
72 }
73 }
74
75 private checkPerformanceRecordsFile (): void {
76 if (this.fd == null) {
77 throw new BaseError(
78 `${this.logPrefix} Performance records '${this.dbName}' file descriptor not found`
79 )
80 }
81 }
82 }