-
Notifications
You must be signed in to change notification settings - Fork 78
Expand file tree
/
Copy pathreferenceLaps.ts
More file actions
256 lines (235 loc) · 6.99 KB
/
Copy pathreferenceLaps.ts
File metadata and controls
256 lines (235 loc) · 6.99 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
import { ReferenceLap } from '@irdashies/types';
import { app } from 'electron';
import fs from 'node:fs';
import fsp from 'node:fs/promises';
import path from 'node:path';
import logger from '../logger';
import { readData, writeData } from './storage';
const dataPath = app.getPath('userData');
const filePath = path.join(dataPath, 'referenceLaps.json');
/**
* Debounce window for async writes. Multiple saveReferenceLap() calls inside
* this window collapse into a single write — addresses the 3×-per-fast-lap
* write storm identified in the PCC race performance log (51 save log lines
* for 17 distinct save events, one save per renderer).
*/
const WRITE_DEBOUNCE_MS = 250;
/**
* In-memory cache of all reference laps, lazy-loaded from disk on first
* access. Eliminates the per-call read+parse+revive cost that previously
* scanned the entire reference-lap database on every fetch and save.
*/
let cache: Map<string, ReferenceLap> | null = null;
/**
* Pending async write state. When a save is in flight or scheduled, additional
* saves update the cache (and reset the debounce timer) without scheduling a
* second write. On app shutdown, a sync flush picks up anything still pending.
*/
let writeTimer: NodeJS.Timeout | null = null;
let writeInFlight: Promise<void> | null = null;
/**
* One-time migration to clear old reference lap data.
* This should be removed in a future version.
*/
export const validateReferenceLapFile = () => {
const VERSION = '1.0.0';
const VERSION_KEY = 'version';
const isCurrent = readData<string>(VERSION_KEY, filePath) === VERSION;
if (!isCurrent) {
if (fs.existsSync(filePath)) {
try {
fs.unlinkSync(filePath);
logger.info('One-time cleanup of referenceLaps.json performed');
} catch (error) {
logger.error(
'Failed to delete referenceLaps.json during initialization:',
error
);
}
}
try {
writeData(VERSION_KEY, VERSION, filePath);
} catch (error) {
logger.error('Failed to persist version flag:', error);
}
}
};
/**
* Generates a unique composite key for storage.
*/
const generateKey = (
seriesId: number,
trackId: number,
classId: number
): string => {
return `${seriesId}_${trackId}_${classId}`;
};
/**
* JSON Reviver: Converts arrays back to Float32Arrays for specific keys
*/
const reviver = (key: string, value: unknown): unknown => {
if (
(key === 'pointPos' || key === 'times' || key === 'tangents') &&
Array.isArray(value)
) {
return new Float32Array(value);
}
return value;
};
/**
* JSON Replacer: Converts Float32Arrays to standard arrays for storage
*/
const replacer = (key: string, value: unknown): unknown => {
if (value instanceof Float32Array) {
return Array.from(value);
}
return value;
};
/**
* Lazy-load the file into the in-memory cache on first access. Synchronous
* by design — this runs once at startup, which is permitted by R6.1.
*/
const loadCache = (): Map<string, ReferenceLap> => {
if (cache) return cache;
try {
const data = fs.readFileSync(filePath, 'utf8');
const parsed = JSON.parse(data, reviver) as Record<string, ReferenceLap>;
cache = new Map(Object.entries(parsed));
} catch {
cache = new Map();
}
return cache;
};
const flushAsync = async (): Promise<void> => {
if (!cache) return;
try {
const obj = Object.fromEntries(cache);
const jsonString = JSON.stringify(obj, replacer, 2);
const entryCount = cache.size;
await fsp.writeFile(filePath, jsonString);
logger.info(
`[Main] Reference laps written to disk (${entryCount} entries)`
);
} catch (error) {
logger.error('Failed to write reference lap data:', error);
}
};
/**
* Synchronous flush for app shutdown — ensures any pending debounced write
* makes it to disk before the process exits.
*/
const flushSync = (): void => {
if (!cache) return;
if (writeTimer) {
clearTimeout(writeTimer);
writeTimer = null;
}
try {
const obj = Object.fromEntries(cache);
const jsonString = JSON.stringify(obj, replacer, 2);
fs.writeFileSync(filePath, jsonString);
} catch (error) {
logger.error('Failed to flush reference lap data on shutdown:', error);
}
};
/**
* Schedule a debounced async write. Multiple calls within WRITE_DEBOUNCE_MS
* collapse into a single write.
*/
const enqueueFlush = (): void => {
const previous = writeInFlight ?? Promise.resolve();
const tracked = previous
.catch(() => undefined)
.then(() => flushAsync())
.finally(() => {
if (writeInFlight === tracked) {
writeInFlight = null;
}
});
writeInFlight = tracked;
};
const scheduleWrite = (): void => {
if (writeTimer) {
clearTimeout(writeTimer);
}
writeTimer = setTimeout(() => {
writeTimer = null;
enqueueFlush();
}, WRITE_DEBOUNCE_MS);
};
/**
* Read all reference lap data from cache (lazy-loaded on first call).
* Returns a fresh plain-object copy to preserve the previous external
* contract for any caller that expects a mutable Record.
*/
export const readReferenceLaps = (): Record<string, ReferenceLap> => {
return Object.fromEntries(loadCache());
};
/**
* Replace the on-disk reference lap data. Updates the cache atomically and
* schedules a debounced async write.
*/
export const writeReferenceLaps = (data: Record<string, ReferenceLap>) => {
cache = new Map(Object.entries(data));
scheduleWrite();
};
/**
* Get reference lap for a specific combination. O(1) cache lookup.
*/
export const getReferenceLap = (
seriesId: number,
trackId: number,
classId: number
): ReferenceLap | null => {
const key = generateKey(seriesId, trackId, classId);
return loadCache().get(key) ?? null;
};
/**
* Save or update a reference lap for a specific combination. The cache is
* updated synchronously so subsequent reads observe the new value; the disk
* write is debounced so 3× per-renderer save bursts collapse to one write.
*/
export const saveReferenceLap = (
seriesId: number,
trackId: number,
classId: number,
lapData: ReferenceLap
) => {
const key = generateKey(seriesId, trackId, classId);
loadCache().set(key, lapData);
scheduleWrite();
};
/**
* Flush any pending write synchronously. Called on app shutdown to avoid
* losing the last save if the user closes the app within WRITE_DEBOUNCE_MS
* of setting a fast lap.
*/
export const flushReferenceLapsOnShutdown = (): void => {
flushSync();
};
/**
* Testing helper: await any in-flight write. Not exported in production
* use — only consumed by the spec to deterministically observe the
* debounced write completing.
*/
export const __awaitPendingWrite = async (): Promise<void> => {
if (writeTimer) {
clearTimeout(writeTimer);
writeTimer = null;
enqueueFlush();
}
while (writeInFlight) {
await writeInFlight;
}
};
/**
* Testing helper: reset module-level state so each spec starts clean.
*/
export const __resetForTests = (): void => {
cache = null;
if (writeTimer) {
clearTimeout(writeTimer);
writeTimer = null;
}
writeInFlight = null;
};