-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcacheStore.ts
More file actions
291 lines (253 loc) · 8.45 KB
/
Copy pathcacheStore.ts
File metadata and controls
291 lines (253 loc) · 8.45 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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
import { randomUUID } from 'node:crypto';
import { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
import path from 'node:path';
const fmtCacheFileName = 'cache.json';
const fmtCacheVersion = 2;
const fileEntryWidth = 4;
const contentHashOffset = 1;
const optionsIndexOffset = 2;
const stateOffset = 3;
const fmtCacheStates = ['clean', 'dirty', 'unsupported'] as const;
type FmtCacheState = (typeof fmtCacheStates)[number];
type FmtCacheStateId = 0 | 1 | 2;
const fmtCacheStateIds = {
clean: 0,
dirty: 1,
unsupported: 2,
} as const satisfies Record<FmtCacheState, FmtCacheStateId>;
type FmtCacheFileValue = string | number;
type FmtCacheEntry = readonly [
contentHash: string,
optionsHash: string,
state: FmtCacheState,
];
interface FmtCacheFile {
version: typeof fmtCacheVersion;
namespace: string;
options: string[];
/** Repeated tuples of file path, content hash, options index, and numeric state. */
files: FmtCacheFileValue[];
}
interface ParsedFmtCacheFile {
cache: FmtCacheFile;
fileOffsets: Map<string, number>;
optionsIndexes: Map<string, number>;
optionsUseCounts: number[];
}
interface FmtCacheStore {
get(filePath: string): FmtCacheEntry | undefined;
set(filePath: string, entry: FmtCacheEntry): void;
/** Persists changed entries and returns whether the cache file was replaced. */
save(): Promise<boolean>;
}
const createEmptyCache = (namespace: string): ParsedFmtCacheFile => ({
cache: {
version: fmtCacheVersion,
namespace,
options: [],
files: [],
},
fileOffsets: new Map(),
optionsIndexes: new Map(),
optionsUseCounts: [],
});
const parseCacheFile = (
content: string,
expectedNamespace: string,
): ParsedFmtCacheFile | undefined => {
let value: unknown;
try {
value = JSON.parse(content);
} catch {
return;
}
if (typeof value !== 'object' || value === null || Array.isArray(value)) {
return;
}
const cache = value as FmtCacheFile;
const { version, namespace, options, files } = cache;
if (
version !== fmtCacheVersion ||
namespace !== expectedNamespace ||
!Array.isArray(options) ||
!Array.isArray(files) ||
files.length % fileEntryWidth !== 0
) {
return;
}
const optionsIndexes = new Map<string, number>();
for (let index = 0; index < options.length; index++) {
optionsIndexes.set(options[index], index);
}
const fileOffsets = new Map<string, number>();
const optionsUseCounts = new Array<number>(options.length).fill(0);
for (let offset = 0; offset < files.length; offset += fileEntryWidth) {
const filePath = files[offset] as string;
const optionsIndex = files[offset + optionsIndexOffset] as number;
fileOffsets.set(filePath, offset);
optionsUseCounts[optionsIndex]++;
}
return {
cache,
fileOffsets,
optionsIndexes,
optionsUseCounts,
};
};
const serializeCache = (cache: FmtCacheFile): string =>
`${JSON.stringify(cache)}\n`;
const isFileNotFoundError = (error: unknown): error is NodeJS.ErrnoException =>
error instanceof Error && 'code' in error && error.code === 'ENOENT';
const getTemporaryPath = (filePath: string): string =>
path.join(
path.dirname(filePath),
`.${path.basename(filePath)}.${process.pid}.${randomUUID()}.tmp`,
);
class FmtCacheStoreImpl implements FmtCacheStore {
readonly #filePath: string;
readonly #cache: FmtCacheFile;
readonly #fileOffsets: Map<string, number>;
readonly #optionsIndexes: Map<string, number>;
readonly #optionsUseCounts: number[];
#savedContent: string | undefined;
#changed: boolean;
constructor(
filePath: string,
parsed: ParsedFmtCacheFile,
savedContent: string | undefined,
changed: boolean,
) {
this.#filePath = filePath;
this.#cache = parsed.cache;
this.#fileOffsets = parsed.fileOffsets;
this.#optionsIndexes = parsed.optionsIndexes;
this.#optionsUseCounts = parsed.optionsUseCounts;
this.#savedContent = savedContent;
this.#changed = changed;
}
get(filePath: string): FmtCacheEntry | undefined {
const offset = this.#fileOffsets.get(filePath);
if (offset === undefined) {
return;
}
const { files, options } = this.#cache;
const contentHash = files[offset + contentHashOffset] as string;
const optionsHash = options[files[offset + optionsIndexOffset] as number];
const state =
fmtCacheStates[files[offset + stateOffset] as FmtCacheStateId];
return [contentHash, optionsHash, state];
}
set(filePath: string, entry: FmtCacheEntry): void {
const { files, options } = this.#cache;
const [contentHash, optionsHash, state] = entry;
const stateId = fmtCacheStateIds[state];
const offset = this.#fileOffsets.get(filePath);
if (offset !== undefined) {
const currentOptionsIndex = files[offset + optionsIndexOffset] as number;
if (
files[offset + contentHashOffset] === contentHash &&
options[currentOptionsIndex] === optionsHash &&
files[offset + stateOffset] === stateId
) {
return;
}
const optionsIndex = this.#getOrCreateOptionsIndex(optionsHash);
if (currentOptionsIndex !== optionsIndex) {
this.#optionsUseCounts[currentOptionsIndex]--;
this.#optionsUseCounts[optionsIndex]++;
files[offset + optionsIndexOffset] = optionsIndex;
}
files[offset + contentHashOffset] = contentHash;
files[offset + stateOffset] = stateId;
} else {
const optionsIndex = this.#getOrCreateOptionsIndex(optionsHash);
const nextOffset = files.length;
files.push(filePath, contentHash, optionsIndex, stateId);
this.#fileOffsets.set(filePath, nextOffset);
this.#optionsUseCounts[optionsIndex]++;
}
this.#changed = true;
}
#getOrCreateOptionsIndex(optionsHash: string): number {
const current = this.#optionsIndexes.get(optionsHash);
if (current !== undefined) {
return current;
}
const index = this.#cache.options.length;
this.#cache.options.push(optionsHash);
this.#optionsIndexes.set(optionsHash, index);
this.#optionsUseCounts.push(0);
return index;
}
/** Removes unreferenced option hashes and remaps file entries to the compacted indexes. */
#compactUnusedOptions(): void {
if (!this.#optionsUseCounts.includes(0)) {
return;
}
const { files, options } = this.#cache;
const counts = this.#optionsUseCounts;
const remap = new Int32Array(options.length).fill(-1);
let nextIndex = 0;
this.#optionsIndexes.clear();
for (let index = 0; index < options.length; index++) {
const count = counts[index];
if (count > 0) {
const option = options[index];
remap[index] = nextIndex;
options[nextIndex] = option;
counts[nextIndex] = count;
this.#optionsIndexes.set(option, nextIndex);
nextIndex++;
}
}
options.length = nextIndex;
counts.length = nextIndex;
for (let offset = 0; offset < files.length; offset += fileEntryWidth) {
const index = files[offset + optionsIndexOffset] as number;
files[offset + optionsIndexOffset] = remap[index];
}
}
async save(): Promise<boolean> {
if (!this.#changed) {
return false;
}
this.#compactUnusedOptions();
const content = serializeCache(this.#cache);
if (content === this.#savedContent) {
this.#changed = false;
return false;
}
const temporaryPath = getTemporaryPath(this.#filePath);
try {
await mkdir(path.dirname(this.#filePath), { recursive: true });
await writeFile(temporaryPath, content);
await rename(temporaryPath, this.#filePath);
this.#savedContent = content;
this.#changed = false;
return true;
} catch {
return false;
} finally {
await rm(temporaryPath, { force: true }).catch(() => undefined);
}
}
}
const loadFmtCacheStore = async (
filePath: string,
namespace: string,
): Promise<FmtCacheStore> => {
const emptyCache = createEmptyCache(namespace);
try {
const content = await readFile(filePath, 'utf8');
const parsed = parseCacheFile(content, namespace);
if (!parsed) {
return new FmtCacheStoreImpl(filePath, emptyCache, undefined, true);
}
return new FmtCacheStoreImpl(filePath, parsed, content, false);
} catch (error) {
const missing = isFileNotFoundError(error);
return new FmtCacheStoreImpl(filePath, emptyCache, undefined, !missing);
}
};
export { fmtCacheFileName, fmtCacheVersion, loadFmtCacheStore };
export type { FmtCacheEntry, FmtCacheFile, FmtCacheState, FmtCacheStore };