@vltpkg/cache 1.0.0-rc.22 → 1.0.0-rc.24

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,102 @@
1
+ import type { Integrity } from '@vltpkg/types';
2
+ import { LRUCache } from 'lru-cache';
3
+ export type CacheFetchContext = {
4
+ integrity?: Integrity;
5
+ } | undefined;
6
+ export type CacheOptions = {
7
+ [k in keyof LRUCache.Options<string, Buffer, CacheFetchContext>]?: LRUCache.Options<string, Buffer, CacheFetchContext>[k];
8
+ } & {
9
+ /**
10
+ * fetchMethod may not be provided, because this cache forces its own
11
+ * read-from-disk as the fetchMethod
12
+ */
13
+ fetchMethod?: undefined;
14
+ /**
15
+ * folder where items should be stored to disk
16
+ */
17
+ path: string;
18
+ /**
19
+ * called whenever an item is written to disk.
20
+ */
21
+ onDiskWrite?: (path: string, key: string, data: Buffer) => any;
22
+ /**
23
+ * called whenever an item is deleted with `cache.delete(key, true)`
24
+ * Deletes of the in-memory data do not trigger this method.
25
+ */
26
+ onDiskDelete?: (path: string, key: string, deleted: boolean) => any;
27
+ };
28
+ export type BooleanOrVoid = boolean | void;
29
+ export declare class Cache extends LRUCache<string, Buffer, CacheFetchContext> {
30
+ #private;
31
+ [Symbol.toStringTag]: string;
32
+ onDiskWrite?: CacheOptions['onDiskWrite'];
33
+ onDiskDelete?: CacheOptions['onDiskDelete'];
34
+ /**
35
+ * A list of the actions currently happening in the background
36
+ */
37
+ get pending(): Promise<BooleanOrVoid>[];
38
+ /**
39
+ * By default, cache up to 1000 items in memory.
40
+ * Disk cache is unbounded.
41
+ */
42
+ static get defaultMax(): number;
43
+ constructor(options: CacheOptions);
44
+ /**
45
+ * Walk over all the items cached to disk (not just in memory).
46
+ * Useful for cleanup, pruning, etc.
47
+ *
48
+ * Implementation for `for await` to walk over entries.
49
+ */
50
+ walk(): AsyncGenerator<[string, Buffer<ArrayBufferLike>], void, unknown>;
51
+ [Symbol.asyncIterator](): AsyncGenerator<[
52
+ string,
53
+ Buffer
54
+ ], void, void>;
55
+ /**
56
+ * Synchronous form of Cache.walk()
57
+ */
58
+ walkSync(): Generator<[string, Buffer<ArrayBufferLike>], void, unknown>;
59
+ [Symbol.iterator](): Generator<[string, Buffer], void>;
60
+ /**
61
+ * Pass `true` as second argument to delete not just from the in-memory
62
+ * cache, but the disk backing as well.
63
+ */
64
+ delete(key: string, fromDisk?: boolean, integrity?: Integrity): boolean;
65
+ /**
66
+ * Sets an item in the memory cache (like `LRUCache.set`), and schedules a
67
+ * background operation to write it to disk.
68
+ *
69
+ * Use the {@link CacheOptions#onDiskWrite} method to know exactly when this
70
+ * happens, or `await cache.promise()` to defer until all pending actions are
71
+ * completed.
72
+ *
73
+ * The `noDiskWrite` option can be set to prevent it from writing back to the
74
+ * disk cache. This is almost never relevant for consumers, and is used
75
+ * internally to prevent the write at the end of `fetch()` from excessively
76
+ * writing over a file we just read from.
77
+ */
78
+ set(key: string, val: Buffer, options?: LRUCache.SetOptions<string, Buffer, CacheFetchContext> & {
79
+ /** set to `true` to prevent writes to disk cache */
80
+ noDiskWrite?: boolean;
81
+ /** sha512 integrity string */
82
+ integrity?: Integrity;
83
+ }): this;
84
+ /**
85
+ * Resolves when there are no pending writes to the disk cache
86
+ */
87
+ promise(): Promise<void>;
88
+ /**
89
+ * given a key, figure out the path on disk where it lives
90
+ */
91
+ path(key?: string): string;
92
+ /**
93
+ * given an SRI sha512 integrity string, get the path on disk that
94
+ * is hard-linked to the value.
95
+ */
96
+ integrityPath(integrity?: Integrity): string | undefined;
97
+ /**
98
+ * Read synchronously from the fs cache storage if not already
99
+ * in memory.
100
+ */
101
+ fetchSync(key: string, opts?: LRUCache.FetchOptions<string, Buffer, CacheFetchContext>): Buffer<ArrayBufferLike> | undefined;
102
+ }
package/dist/index.js ADDED
@@ -0,0 +1,307 @@
1
+ import { error } from '@vltpkg/error-cause';
2
+ import { createHash, randomBytes } from 'node:crypto';
3
+ import { opendirSync, readFileSync } from 'node:fs';
4
+ import { link, mkdir, opendir, readFile, rename, stat, writeFile, } from 'node:fs/promises';
5
+ import { LRUCache } from 'lru-cache';
6
+ import { resolve, dirname } from 'node:path';
7
+ import { rimraf } from 'rimraf';
8
+ const hash = (s) => createHash('sha512').update(s).digest('hex');
9
+ const FAILURE = null;
10
+ const success = (p) => p.then(result => result, () => FAILURE);
11
+ export class Cache extends LRUCache {
12
+ #path;
13
+ [Symbol.toStringTag] = '@vltpkg/cache.Cache';
14
+ #random = randomBytes(6).toString('hex');
15
+ #i = 0;
16
+ #pending = new Set();
17
+ onDiskWrite;
18
+ onDiskDelete;
19
+ /**
20
+ * A list of the actions currently happening in the background
21
+ */
22
+ get pending() {
23
+ return [...this.#pending];
24
+ }
25
+ /**
26
+ * By default, cache up to 1000 items in memory.
27
+ * Disk cache is unbounded.
28
+ */
29
+ static get defaultMax() {
30
+ return 10_000;
31
+ }
32
+ constructor(options) {
33
+ const { onDiskWrite, onDiskDelete, path, fetchMethod: _, sizeCalculation = options.maxSize || options.maxEntrySize ?
34
+ (v, k) => v.length + k.length
35
+ : undefined, ...lruOpts } = options;
36
+ super({
37
+ max: Cache.defaultMax,
38
+ ...lruOpts,
39
+ sizeCalculation,
40
+ fetchMethod: async (k, v, opts) => {
41
+ // do not write back to disk, since we just got it from there.
42
+ Object.assign(opts.options, {
43
+ noDiskWrite: true,
44
+ });
45
+ return this.#diskRead(k, v, opts.context?.integrity);
46
+ },
47
+ allowStaleOnFetchRejection: true,
48
+ allowStaleOnFetchAbort: true,
49
+ allowStale: true,
50
+ noDeleteOnStaleGet: true,
51
+ });
52
+ this.onDiskWrite = onDiskWrite;
53
+ this.onDiskDelete = onDiskDelete;
54
+ this.#path = path;
55
+ }
56
+ /**
57
+ * Walk over all the items cached to disk (not just in memory).
58
+ * Useful for cleanup, pruning, etc.
59
+ *
60
+ * Implementation for `for await` to walk over entries.
61
+ */
62
+ async *walk() {
63
+ const dir = await opendir(this.#path, { bufferSize: 1024 });
64
+ for await (const entry of dir) {
65
+ const f = resolve(this.#path, entry.name);
66
+ if (f.endsWith('.key')) {
67
+ const entry = await Promise.all([
68
+ readFile(resolve(this.#path, f), 'utf8'),
69
+ readFile(resolve(this.#path, f.substring(0, f.length - '.key'.length))),
70
+ ]);
71
+ yield entry;
72
+ }
73
+ }
74
+ }
75
+ [Symbol.asyncIterator]() {
76
+ return this.walk();
77
+ }
78
+ /**
79
+ * Synchronous form of Cache.walk()
80
+ */
81
+ *walkSync() {
82
+ const dir = opendirSync(this.#path, { bufferSize: 1024 });
83
+ let entry = null;
84
+ while (null !== (entry = dir.readSync())) {
85
+ const f = resolve(this.#path, entry.name);
86
+ if (f.endsWith('.key')) {
87
+ const entry = [
88
+ readFileSync(resolve(this.#path, f), 'utf8'),
89
+ readFileSync(resolve(this.#path, f.substring(0, f.length - '.key'.length))),
90
+ ];
91
+ yield entry;
92
+ }
93
+ }
94
+ dir.closeSync();
95
+ }
96
+ [Symbol.iterator]() {
97
+ return this.walkSync();
98
+ }
99
+ #unpend(p, fn, ...args) {
100
+ this.#pending.delete(p);
101
+ if (fn)
102
+ fn(...args);
103
+ }
104
+ #pend(p) {
105
+ this.#pending.add(p);
106
+ }
107
+ /**
108
+ * Pass `true` as second argument to delete not just from the in-memory
109
+ * cache, but the disk backing as well.
110
+ */
111
+ delete(key, fromDisk = false, integrity) {
112
+ const ret = super.delete(key);
113
+ if (fromDisk) {
114
+ const path = this.path(key);
115
+ const p = this.#diskDelete(path, integrity).then(deleted => this.#unpend(p, this.onDiskDelete, path, key, deleted));
116
+ this.#pend(p);
117
+ }
118
+ return ret;
119
+ }
120
+ /**
121
+ * Sets an item in the memory cache (like `LRUCache.set`), and schedules a
122
+ * background operation to write it to disk.
123
+ *
124
+ * Use the {@link CacheOptions#onDiskWrite} method to know exactly when this
125
+ * happens, or `await cache.promise()` to defer until all pending actions are
126
+ * completed.
127
+ *
128
+ * The `noDiskWrite` option can be set to prevent it from writing back to the
129
+ * disk cache. This is almost never relevant for consumers, and is used
130
+ * internally to prevent the write at the end of `fetch()` from excessively
131
+ * writing over a file we just read from.
132
+ */
133
+ set(key, val, options) {
134
+ super.set(key, val, options);
135
+ const { noDiskWrite, integrity } = options ?? {};
136
+ // set/delete also used internally by LRUCache to manage async fetches
137
+ // only write when we're putting an actual value into the cache
138
+ if (Buffer.isBuffer(val) && !noDiskWrite) {
139
+ // best effort, already have it in memory
140
+ const path = this.path(key);
141
+ const p = this.#diskWrite(path, key, val, integrity)
142
+ /* c8 ignore next */
143
+ .catch(() => { })
144
+ .then(() => this.#unpend(p, this.onDiskWrite, path, key, val));
145
+ this.#pend(p);
146
+ }
147
+ return this;
148
+ }
149
+ /**
150
+ * Resolves when there are no pending writes to the disk cache
151
+ */
152
+ async promise() {
153
+ if (this.pending.length)
154
+ await Promise.all(this.pending);
155
+ /* c8 ignore next - race condition */
156
+ if (this.#pending.size)
157
+ await this.promise();
158
+ }
159
+ /**
160
+ * given a key, figure out the path on disk where it lives
161
+ */
162
+ path(key) {
163
+ return key ? resolve(this.#path, hash(key)) : this.#path;
164
+ }
165
+ /**
166
+ * given an SRI sha512 integrity string, get the path on disk that
167
+ * is hard-linked to the value.
168
+ */
169
+ integrityPath(integrity) {
170
+ if (!integrity)
171
+ return undefined;
172
+ const m = /^sha512-([a-zA-Z0-9/+]{86}==)$/.exec(integrity);
173
+ const hash = m?.[1];
174
+ if (!hash) {
175
+ throw error('invalid integrity value', {
176
+ found: integrity,
177
+ wanted: /^sha512-([a-zA-Z0-9/+]{86}==)$/,
178
+ });
179
+ }
180
+ const base = Buffer.from(hash, 'base64').toString('hex');
181
+ return resolve(this.#path, base);
182
+ }
183
+ /**
184
+ * Read synchronously from the fs cache storage if not already
185
+ * in memory.
186
+ */
187
+ fetchSync(key, opts) {
188
+ const v = this.get(key);
189
+ if (v)
190
+ return v;
191
+ const intFile = this.#maybeIntegrityPath(opts?.context?.integrity);
192
+ if (intFile) {
193
+ try {
194
+ const v = readFileSync(intFile);
195
+ this.set(key, v, { ...opts, noDiskWrite: true });
196
+ return v;
197
+ /* c8 ignore start */
198
+ }
199
+ catch { }
200
+ }
201
+ /* c8 ignore stop */
202
+ try {
203
+ const v = readFileSync(this.path(key));
204
+ // suppress the disk write, because we just read it from disk
205
+ this.set(key, v, { ...opts, noDiskWrite: true });
206
+ return v;
207
+ /* c8 ignore start */
208
+ }
209
+ catch { }
210
+ }
211
+ /* c8 ignore stop */
212
+ /**
213
+ * Delete path and path + '.key'
214
+ */
215
+ async #diskDelete(path, integrity) {
216
+ const intPath = this.#maybeIntegrityPath(integrity);
217
+ const paths = [path, path + '.key'];
218
+ if (intPath)
219
+ paths.push(intPath);
220
+ return await rimraf(paths);
221
+ }
222
+ #maybeIntegrityPath(i) {
223
+ try {
224
+ return this.integrityPath(i);
225
+ }
226
+ catch { }
227
+ }
228
+ async #writeFileAtomic(file, data) {
229
+ // ensure we get a different random key for every write,
230
+ // just in case the same file tries to write multiple times,
231
+ // it'll still be atomic.
232
+ const tmp = `${file}.${this.#random}.${this.#i++}`;
233
+ await writeFile(tmp, data);
234
+ await rename(tmp, file);
235
+ }
236
+ async #linkAtomic(src, dest) {
237
+ const tmp = `${dest}.${this.#random}.${this.#i++}`;
238
+ await link(src, tmp);
239
+ await rename(tmp, dest);
240
+ }
241
+ async #diskWrite(valFile, key, val, integrity) {
242
+ const dir = dirname(valFile);
243
+ const intFile = this.#maybeIntegrityPath(integrity);
244
+ // Create the directory if it doesn't exist and save the promise
245
+ // to ensure any write file operations happen after the dir is created.
246
+ const mkdirP = mkdir(dir, { recursive: true });
247
+ // Helper to atomically write a file to the cache directory, waiting for the dir
248
+ // to be created first.
249
+ const writeCacheFile = (file, data) => mkdirP.then(() => this.#writeFileAtomic(file, data));
250
+ // Always write the key file as early as possible
251
+ const writeKeyP = writeCacheFile(`${valFile}.key`, key);
252
+ // Helper to wait for the operations we always want to run (write the key file)
253
+ // combined with any other operations passed in.
254
+ const finish = async (ops) => {
255
+ await Promise.all([writeKeyP, ...ops]);
256
+ };
257
+ if (!intFile) {
258
+ // No integrity provided, just write the value and key files
259
+ return finish([writeCacheFile(valFile, val)]);
260
+ }
261
+ // Now we know that we have been passed an integrity value
262
+ // that we should attempt to use...somehow.
263
+ const intStats = await success(stat(intFile));
264
+ if (!intStats) {
265
+ // Integrity file doesn't exist yet
266
+ // Write the value file and then link that to a new integrity file
267
+ return finish([
268
+ writeCacheFile(valFile, val).then(() => link(valFile, intFile)),
269
+ ]);
270
+ }
271
+ const valStats = await success(stat(valFile));
272
+ if (!valStats) {
273
+ // Value file doesn't exist but integrity does, we know they are the same
274
+ // because we trust the integrity file, so attempt to link and be done.
275
+ return finish([link(intFile, valFile)]);
276
+ }
277
+ // We now know that both the value and integrity files exist.
278
+ if (intStats.ino === valStats.ino &&
279
+ intStats.dev === valStats.dev) {
280
+ // Integrity and val file are already linked. If the are the same value
281
+ // then we can be done, otherwise we are probably unzipping and we should
282
+ // write the new integrity value and then link the value file to it.
283
+ return finish(val.length === valStats.size ?
284
+ []
285
+ : [
286
+ writeCacheFile(intFile, val).then(() => this.#linkAtomic(intFile, valFile)),
287
+ ]);
288
+ }
289
+ // By this point we know that the files are not linked, so
290
+ // we atomic link them because they should be the same entry.
291
+ return finish([this.#linkAtomic(intFile, valFile)]);
292
+ }
293
+ async #diskRead(k, v, integrity) {
294
+ const intFile = this.#maybeIntegrityPath(integrity);
295
+ const file = this.path(k);
296
+ const p = intFile ?
297
+ readFile(intFile).catch(async () => {
298
+ // if we get the value, but not integrity, link to the
299
+ // integrity file so we get it next time.
300
+ const value = await readFile(file);
301
+ await link(file, intFile);
302
+ return value;
303
+ })
304
+ : readFile(file);
305
+ return p.catch(() => v);
306
+ }
307
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@vltpkg/cache",
3
3
  "description": "The filesystem cache for `@vlt/registry-client`",
4
- "version": "1.0.0-rc.22",
4
+ "version": "1.0.0-rc.24",
5
5
  "repository": {
6
6
  "type": "git",
7
7
  "url": "git+https://github.com/vltpkg/vltpkg.git",
@@ -12,8 +12,8 @@
12
12
  "email": "support@vlt.sh"
13
13
  },
14
14
  "dependencies": {
15
- "@vltpkg/error-cause": "1.0.0-rc.22",
16
- "@vltpkg/types": "1.0.0-rc.22",
15
+ "@vltpkg/error-cause": "1.0.0-rc.24",
16
+ "@vltpkg/types": "1.0.0-rc.24",
17
17
  "lru-cache": "^11.2.4",
18
18
  "rimraf": "^6.1.2"
19
19
  },
@@ -46,13 +46,13 @@
46
46
  "extends": "../../tap-config.yaml"
47
47
  },
48
48
  "prettier": "../../.prettierrc.js",
49
- "module": "./src/index.ts",
49
+ "module": "./dist/index.js",
50
50
  "type": "module",
51
51
  "exports": {
52
52
  "./package.json": "./package.json",
53
53
  ".": {
54
54
  "import": {
55
- "default": "./src/index.ts"
55
+ "default": "./dist/index.js"
56
56
  }
57
57
  }
58
58
  },