@vltpkg/cache 0.0.0-0.1730239248325
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.
- package/LICENSE +15 -0
- package/README.md +69 -0
- package/dist/esm/index.d.ts +108 -0
- package/dist/esm/index.d.ts.map +1 -0
- package/dist/esm/index.js +270 -0
- package/dist/esm/index.js.map +1 -0
- package/dist/esm/package.json +3 -0
- package/package.json +65 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
Copyright (c) vlt technology, Inc.
|
|
2
|
+
|
|
3
|
+
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
|
|
4
|
+
|
|
5
|
+
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
|
|
6
|
+
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
|
|
7
|
+
Subject to the terms and conditions of this license, each copyright holder and contributor hereby grants to those receiving rights under this license a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except for failure to satisfy the conditions of this license) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer this software, where such license applies only to those patent claims, already acquired or hereafter acquired, licensable by such copyright holder or contributor that are necessarily infringed by:
|
|
8
|
+
|
|
9
|
+
(a) their Contribution(s) (the licensed copyrights of copyright holders and non-copyrightable additions of contributors, in source or binary form) alone; or
|
|
10
|
+
(b) combination of their Contribution(s) with the work of authorship to which such Contribution(s) was added by such copyright holder or contributor, if, at the time the Contribution is added, such addition causes such combination to be necessarily infringed. The patent license shall not apply to any other combinations which include the Contribution.
|
|
11
|
+
Except as expressly stated above, no rights or licenses from any copyright holder or contributor is granted under this license, whether expressly, by implication, estoppel or otherwise.
|
|
12
|
+
|
|
13
|
+
DISCLAIMER
|
|
14
|
+
|
|
15
|
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
package/README.md
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
# `@vltpkg/cache`
|
|
2
|
+
|
|
3
|
+
The filesystem cache for `@vlt/registry-client`, but also, a
|
|
4
|
+
general-purpose filesystem-backed
|
|
5
|
+
[LRUCache](http://npm.im/lru-cache).
|
|
6
|
+
|
|
7
|
+
This is very minimal on features, because it has a very narrow
|
|
8
|
+
use case, but if you want to have a persistently fs-backed LRU
|
|
9
|
+
memory cache of Buffers using strings as keys, then this is the
|
|
10
|
+
thing to use.
|
|
11
|
+
|
|
12
|
+
## USAGE
|
|
13
|
+
|
|
14
|
+
```js
|
|
15
|
+
import { Cache } from '@vltpkg/cache'
|
|
16
|
+
|
|
17
|
+
const numberOfItemsToKeepInMemory = 10_000
|
|
18
|
+
|
|
19
|
+
const cache = new Cache({
|
|
20
|
+
path: '/path/to/fs/cache/folder',
|
|
21
|
+
// the number of items to keep in memory
|
|
22
|
+
// on-disk folder will just keep everything
|
|
23
|
+
// see @vltpkg/cache-manager for handling that
|
|
24
|
+
max: 10_000,
|
|
25
|
+
})
|
|
26
|
+
|
|
27
|
+
// reading is always async, because it has to go to disk maybe
|
|
28
|
+
// this is a wrapper around an LRUCache#fetchMethod that reads
|
|
29
|
+
// from the file system
|
|
30
|
+
const someCachedValue = await cache.fetch(someKey)
|
|
31
|
+
|
|
32
|
+
// fetch by integrity, if available:
|
|
33
|
+
const integrity =
|
|
34
|
+
'sha512-6/mh1E2u2YgEsCHdY0Yx5oW+61gZU+1vXaoiHHrpKeuRNNgFvS+/jrwHiQhB5apAf5oB7UB7E19ol2R2LKH8hQ=='
|
|
35
|
+
const valueByInt = await cache.fetch('blah', {
|
|
36
|
+
context: { integrity },
|
|
37
|
+
})
|
|
38
|
+
|
|
39
|
+
// synchronous cache read, will only return a value if present in
|
|
40
|
+
// the memory cache. Does *not* fall back to the fs store.
|
|
41
|
+
const valueFromMemoryCache = cache.get(someKey)
|
|
42
|
+
|
|
43
|
+
// synchronous cache read, which does fall back to the fs store,
|
|
44
|
+
// using synchronous file I/O
|
|
45
|
+
const valueUsingSyncFileSystemOps = cache.fetchSync(someKey)
|
|
46
|
+
|
|
47
|
+
// set operations are atomically written to the fs cache in the
|
|
48
|
+
// background but are available immediately because they are
|
|
49
|
+
// added to the memory cache first
|
|
50
|
+
cache.set('some-key', Buffer.from('some-value'))
|
|
51
|
+
|
|
52
|
+
// set with integrity creates a hard-linked file at the content
|
|
53
|
+
// address, so that anyone fetching the same content by any other
|
|
54
|
+
// key will get the same result.
|
|
55
|
+
cache.set(someKey, someValue, { integrity })
|
|
56
|
+
await cache.promise() // once it's done writing...
|
|
57
|
+
// returns identical bits as someValue, because on-disk cache
|
|
58
|
+
// hard links to a file based on the integrity value.
|
|
59
|
+
const otherValue = await cache.fetch(otherKey, {
|
|
60
|
+
context: { integrity },
|
|
61
|
+
})
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
Note:
|
|
65
|
+
|
|
66
|
+
- The key type _must_ be a string. It gets `sha512` hashed to
|
|
67
|
+
determine the file on disk.
|
|
68
|
+
- The value must be a Buffer, so that it can be written to a
|
|
69
|
+
file and read from it without having to convert anything.
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
import { 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 declare class Cache extends LRUCache<string, Buffer, CacheFetchContext> {
|
|
29
|
+
#private;
|
|
30
|
+
[Symbol.toStringTag]: string;
|
|
31
|
+
onDiskWrite?: CacheOptions['onDiskWrite'];
|
|
32
|
+
onDiskDelete?: CacheOptions['onDiskDelete'];
|
|
33
|
+
/**
|
|
34
|
+
* ensure we get a different random key for every write,
|
|
35
|
+
* just in case the same file tries to write multiple times,
|
|
36
|
+
* it'll still be atomic.
|
|
37
|
+
*/
|
|
38
|
+
get random(): string;
|
|
39
|
+
/**
|
|
40
|
+
* A list of the actions currently happening in the background
|
|
41
|
+
*/
|
|
42
|
+
get pending(): Promise<boolean | undefined>[];
|
|
43
|
+
/**
|
|
44
|
+
* By default, cache up to 1000 items in memory.
|
|
45
|
+
* Disk cache is unbounded.
|
|
46
|
+
*/
|
|
47
|
+
static get defaultMax(): number;
|
|
48
|
+
constructor(options: CacheOptions);
|
|
49
|
+
/**
|
|
50
|
+
* Walk over all the items cached to disk (not just in memory).
|
|
51
|
+
* Useful for cleanup, pruning, etc.
|
|
52
|
+
*
|
|
53
|
+
* Implementation for `for await` to walk over entries.
|
|
54
|
+
*/
|
|
55
|
+
walk(): AsyncGenerator<[string, Buffer], void, unknown>;
|
|
56
|
+
[Symbol.asyncIterator](): AsyncGenerator<[
|
|
57
|
+
string,
|
|
58
|
+
Buffer
|
|
59
|
+
], void, void>;
|
|
60
|
+
/**
|
|
61
|
+
* Synchronous form of Cache.walk()
|
|
62
|
+
*/
|
|
63
|
+
walkSync(): Generator<[string, Buffer], void, unknown>;
|
|
64
|
+
[Symbol.iterator](): Generator<[string, Buffer], void>;
|
|
65
|
+
/**
|
|
66
|
+
* Pass `true` as second argument to delete not just from the in-memory
|
|
67
|
+
* cache, but the disk backing as well.
|
|
68
|
+
*/
|
|
69
|
+
delete(key: string, fromDisk?: boolean): boolean;
|
|
70
|
+
/**
|
|
71
|
+
* Sets an item in the memory cache (like `LRUCache.set`), and schedules a
|
|
72
|
+
* background operation to write it to disk.
|
|
73
|
+
*
|
|
74
|
+
* Use the {@link CacheOptions#onDiskWrite} method to know exactly when this
|
|
75
|
+
* happens, or `await cache.promise()` to defer until all pending actions are
|
|
76
|
+
* completed.
|
|
77
|
+
*
|
|
78
|
+
* The `noDiskWrite` option can be set to prevent it from writing back to the
|
|
79
|
+
* disk cache. This is almost never relevant for consumers, and is used
|
|
80
|
+
* internally to prevent the write at the end of `fetch()` from excessively
|
|
81
|
+
* writing over a file we just read from.
|
|
82
|
+
*/
|
|
83
|
+
set(key: string, val: Buffer, options?: LRUCache.SetOptions<string, Buffer, CacheFetchContext> & {
|
|
84
|
+
/** set to `true` to prevent writes to disk cache */
|
|
85
|
+
noDiskWrite?: boolean;
|
|
86
|
+
/** sha512 integrity string */
|
|
87
|
+
integrity?: Integrity;
|
|
88
|
+
}): this;
|
|
89
|
+
/**
|
|
90
|
+
* Resolves when there are no pending writes to the disk cache
|
|
91
|
+
*/
|
|
92
|
+
promise(): Promise<void>;
|
|
93
|
+
/**
|
|
94
|
+
* given a key, figure out the path on disk where it lives
|
|
95
|
+
*/
|
|
96
|
+
path(key: string): string;
|
|
97
|
+
/**
|
|
98
|
+
* given an SRI sha512 integrity string, get the path on disk that
|
|
99
|
+
* is hard-linked to the value.
|
|
100
|
+
*/
|
|
101
|
+
integrityPath(integrity?: Integrity): string | undefined;
|
|
102
|
+
/**
|
|
103
|
+
* Read synchronously from the fs cache storage if not already
|
|
104
|
+
* in memory.
|
|
105
|
+
*/
|
|
106
|
+
fetchSync(key: string, opts?: LRUCache.FetchOptions<string, Buffer, CacheFetchContext>): Buffer | undefined;
|
|
107
|
+
}
|
|
108
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,SAAS,EAAE,MAAM,eAAe,CAAA;AAYzC,OAAO,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAA;AAKpC,MAAM,MAAM,iBAAiB,GACzB;IACE,SAAS,CAAC,EAAE,SAAS,CAAA;CACtB,GACD,SAAS,CAAA;AAEb,MAAM,MAAM,YAAY,GAAG;KACxB,CAAC,IAAI,MAAM,QAAQ,CAAC,OAAO,CAC1B,MAAM,EACN,MAAM,EACN,iBAAiB,CAClB,CAAC,CAAC,EAAE,QAAQ,CAAC,OAAO,CAAC,MAAM,EAAE,MAAM,EAAE,iBAAiB,CAAC,CAAC,CAAC,CAAC;CAC5D,GAAG;IACF;;;OAGG;IACH,WAAW,CAAC,EAAE,SAAS,CAAA;IACvB;;OAEG;IACH,IAAI,EA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,EAAE,OAAO,CAAA;QACrB,8BAA8B;QAC9B,SAAS,CAAC,EAAE,SAAS,CAAA;KACtB;IAuBH;;OAEG;IACG,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;IAM9B;;OAEG;IACH,IAAI,CAAC,GAAG,EAAE,MAAM;IAGhB;;;OAGG;IACH,aAAa,CAAC,SAAS,CAAC,EAAE,SAAS;IAcnC;;;OAGG;IACH,SAAS,CACP,GAAG,EAAE,MAAM,EACX,IAAI,CAAC,EAAE,QAAQ,CAAC,YAAY,CAAC,MAAM,EAAE,MAAM,EAAE,iBAAiB,CAAC;CAwFlE"}
|
|
@@ -0,0 +1,270 @@
|
|
|
1
|
+
import { error } from '@vltpkg/error-cause';
|
|
2
|
+
import { XDG } from '@vltpkg/xdg';
|
|
3
|
+
import { createHash, randomBytes } from 'crypto';
|
|
4
|
+
import { opendirSync, readFileSync } from 'fs';
|
|
5
|
+
import { link, mkdir, opendir, readFile, rename, writeFile, } from 'fs/promises';
|
|
6
|
+
import { LRUCache } from 'lru-cache';
|
|
7
|
+
import { resolve } from 'node:path';
|
|
8
|
+
import { basename, dirname } from 'path';
|
|
9
|
+
import { rimraf } from 'rimraf';
|
|
10
|
+
const hash = (s) => createHash('sha512').update(s).digest('hex');
|
|
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
|
+
* ensure we get a different random key for every write,
|
|
21
|
+
* just in case the same file tries to write multiple times,
|
|
22
|
+
* it'll still be atomic.
|
|
23
|
+
*/
|
|
24
|
+
get random() {
|
|
25
|
+
return this.#random + '.' + String(this.#i++);
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* A list of the actions currently happening in the background
|
|
29
|
+
*/
|
|
30
|
+
get pending() {
|
|
31
|
+
return [...this.#pending];
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* By default, cache up to 1000 items in memory.
|
|
35
|
+
* Disk cache is unbounded.
|
|
36
|
+
*/
|
|
37
|
+
static get defaultMax() {
|
|
38
|
+
return 1000;
|
|
39
|
+
}
|
|
40
|
+
constructor(options) {
|
|
41
|
+
const { onDiskWrite, onDiskDelete, path = new XDG('vlt').cache(), fetchMethod: _, sizeCalculation = options.maxSize || options.maxEntrySize ?
|
|
42
|
+
(v, k) => v.length + k.length
|
|
43
|
+
: undefined, ...lruOpts } = options;
|
|
44
|
+
super({
|
|
45
|
+
max: Cache.defaultMax,
|
|
46
|
+
...lruOpts,
|
|
47
|
+
sizeCalculation,
|
|
48
|
+
fetchMethod: async (k, v, opts) => {
|
|
49
|
+
// do not write back to disk, since we just got it from there.
|
|
50
|
+
Object.assign(opts.options, {
|
|
51
|
+
noDiskWrite: true,
|
|
52
|
+
});
|
|
53
|
+
return this.#diskRead(k, v, opts.context?.integrity);
|
|
54
|
+
},
|
|
55
|
+
allowStaleOnFetchRejection: true,
|
|
56
|
+
allowStaleOnFetchAbort: true,
|
|
57
|
+
allowStale: true,
|
|
58
|
+
noDeleteOnStaleGet: true,
|
|
59
|
+
});
|
|
60
|
+
this.onDiskWrite = onDiskWrite;
|
|
61
|
+
this.onDiskDelete = onDiskDelete;
|
|
62
|
+
this.#path = path;
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Walk over all the items cached to disk (not just in memory).
|
|
66
|
+
* Useful for cleanup, pruning, etc.
|
|
67
|
+
*
|
|
68
|
+
* Implementation for `for await` to walk over entries.
|
|
69
|
+
*/
|
|
70
|
+
async *walk() {
|
|
71
|
+
const dir = await opendir(this.#path, { bufferSize: 1024 });
|
|
72
|
+
for await (const entry of dir) {
|
|
73
|
+
const f = resolve(this.#path, entry.name);
|
|
74
|
+
if (f.endsWith('.key')) {
|
|
75
|
+
const entry = await Promise.all([
|
|
76
|
+
readFile(resolve(this.#path, f), 'utf8'),
|
|
77
|
+
readFile(resolve(this.#path, f.substring(0, f.length - '.key'.length))),
|
|
78
|
+
]);
|
|
79
|
+
yield entry;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
[Symbol.asyncIterator]() {
|
|
84
|
+
return this.walk();
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* Synchronous form of Cache.walk()
|
|
88
|
+
*/
|
|
89
|
+
*walkSync() {
|
|
90
|
+
const dir = opendirSync(this.#path, { bufferSize: 1024 });
|
|
91
|
+
let entry = null;
|
|
92
|
+
while (null !== (entry = dir.readSync())) {
|
|
93
|
+
const f = resolve(this.#path, entry.name);
|
|
94
|
+
if (f.endsWith('.key')) {
|
|
95
|
+
const entry = [
|
|
96
|
+
readFileSync(resolve(this.#path, f), 'utf8'),
|
|
97
|
+
readFileSync(resolve(this.#path, f.substring(0, f.length - '.key'.length))),
|
|
98
|
+
];
|
|
99
|
+
yield entry;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
dir.closeSync();
|
|
103
|
+
}
|
|
104
|
+
[Symbol.iterator]() {
|
|
105
|
+
return this.walkSync();
|
|
106
|
+
}
|
|
107
|
+
#unpend(p, fn, ...args) {
|
|
108
|
+
this.#pending.delete(p);
|
|
109
|
+
if (fn)
|
|
110
|
+
fn(...args);
|
|
111
|
+
}
|
|
112
|
+
#pend(p) {
|
|
113
|
+
this.#pending.add(p);
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* Pass `true` as second argument to delete not just from the in-memory
|
|
117
|
+
* cache, but the disk backing as well.
|
|
118
|
+
*/
|
|
119
|
+
delete(key, fromDisk = false) {
|
|
120
|
+
const ret = super.delete(key);
|
|
121
|
+
if (fromDisk) {
|
|
122
|
+
const path = this.path(key);
|
|
123
|
+
const p = this.#diskDelete(path).then(deleted => this.#unpend(p, this.onDiskDelete, path, key, deleted));
|
|
124
|
+
this.#pend(p);
|
|
125
|
+
}
|
|
126
|
+
return ret;
|
|
127
|
+
}
|
|
128
|
+
/**
|
|
129
|
+
* Sets an item in the memory cache (like `LRUCache.set`), and schedules a
|
|
130
|
+
* background operation to write it to disk.
|
|
131
|
+
*
|
|
132
|
+
* Use the {@link CacheOptions#onDiskWrite} method to know exactly when this
|
|
133
|
+
* happens, or `await cache.promise()` to defer until all pending actions are
|
|
134
|
+
* completed.
|
|
135
|
+
*
|
|
136
|
+
* The `noDiskWrite` option can be set to prevent it from writing back to the
|
|
137
|
+
* disk cache. This is almost never relevant for consumers, and is used
|
|
138
|
+
* internally to prevent the write at the end of `fetch()` from excessively
|
|
139
|
+
* writing over a file we just read from.
|
|
140
|
+
*/
|
|
141
|
+
set(key, val, options) {
|
|
142
|
+
super.set(key, val, options);
|
|
143
|
+
const { noDiskWrite, integrity } = options ?? {};
|
|
144
|
+
// set/delete also used internally by LRUCache to manage async fetches
|
|
145
|
+
// only write when we're putting an actual value into the cache
|
|
146
|
+
if (Buffer.isBuffer(val) && !noDiskWrite) {
|
|
147
|
+
// best effort, already have it in memory
|
|
148
|
+
const path = this.path(key);
|
|
149
|
+
const p = this.#diskWrite(path, key, val, integrity)
|
|
150
|
+
/* c8 ignore next */
|
|
151
|
+
.catch(() => { })
|
|
152
|
+
.then(() => this.#unpend(p, this.onDiskWrite, path, key, val));
|
|
153
|
+
this.#pend(p);
|
|
154
|
+
}
|
|
155
|
+
return this;
|
|
156
|
+
}
|
|
157
|
+
/**
|
|
158
|
+
* Resolves when there are no pending writes to the disk cache
|
|
159
|
+
*/
|
|
160
|
+
async promise() {
|
|
161
|
+
if (this.pending.length)
|
|
162
|
+
await Promise.all(this.pending);
|
|
163
|
+
/* c8 ignore next - race condition */
|
|
164
|
+
if (this.#pending.size)
|
|
165
|
+
await this.promise();
|
|
166
|
+
}
|
|
167
|
+
/**
|
|
168
|
+
* given a key, figure out the path on disk where it lives
|
|
169
|
+
*/
|
|
170
|
+
path(key) {
|
|
171
|
+
return resolve(this.#path, hash(key));
|
|
172
|
+
}
|
|
173
|
+
/**
|
|
174
|
+
* given an SRI sha512 integrity string, get the path on disk that
|
|
175
|
+
* is hard-linked to the value.
|
|
176
|
+
*/
|
|
177
|
+
integrityPath(integrity) {
|
|
178
|
+
if (!integrity)
|
|
179
|
+
return undefined;
|
|
180
|
+
const m = /^sha512-([a-zA-Z0-9/+]{86}==)$/.exec(integrity);
|
|
181
|
+
const hash = m?.[1];
|
|
182
|
+
if (!hash) {
|
|
183
|
+
throw error('invalid integrity value', {
|
|
184
|
+
found: integrity,
|
|
185
|
+
wanted: /^sha512-([a-zA-Z0-9/+]{86}==)$/,
|
|
186
|
+
});
|
|
187
|
+
}
|
|
188
|
+
const base = Buffer.from(hash, 'base64').toString('hex');
|
|
189
|
+
return resolve(this.#path, base);
|
|
190
|
+
}
|
|
191
|
+
/**
|
|
192
|
+
* Read synchronously from the fs cache storage if not already
|
|
193
|
+
* in memory.
|
|
194
|
+
*/
|
|
195
|
+
fetchSync(key, opts) {
|
|
196
|
+
const v = this.get(key);
|
|
197
|
+
if (v)
|
|
198
|
+
return v;
|
|
199
|
+
const intFile = this.#maybeIntegrityPath(opts?.context?.integrity);
|
|
200
|
+
if (intFile) {
|
|
201
|
+
try {
|
|
202
|
+
const v = readFileSync(intFile);
|
|
203
|
+
this.set(key, v, { ...opts, noDiskWrite: true });
|
|
204
|
+
return v;
|
|
205
|
+
/* c8 ignore start */
|
|
206
|
+
}
|
|
207
|
+
catch { }
|
|
208
|
+
}
|
|
209
|
+
/* c8 ignore stop */
|
|
210
|
+
try {
|
|
211
|
+
const v = readFileSync(this.path(key));
|
|
212
|
+
// suppress the disk write, because we just read it from disk
|
|
213
|
+
this.set(key, v, { ...opts, noDiskWrite: true });
|
|
214
|
+
return v;
|
|
215
|
+
/* c8 ignore start */
|
|
216
|
+
}
|
|
217
|
+
catch { }
|
|
218
|
+
}
|
|
219
|
+
/* c8 ignore stop */
|
|
220
|
+
/**
|
|
221
|
+
* Delete path and path + '.key'
|
|
222
|
+
*/
|
|
223
|
+
async #diskDelete(path) {
|
|
224
|
+
return rimraf([path, path + '.key']);
|
|
225
|
+
}
|
|
226
|
+
#maybeIntegrityPath(i) {
|
|
227
|
+
try {
|
|
228
|
+
return this.integrityPath(i);
|
|
229
|
+
}
|
|
230
|
+
catch { }
|
|
231
|
+
}
|
|
232
|
+
async #diskWrite(path, key, val, integrity) {
|
|
233
|
+
const dir = dirname(path);
|
|
234
|
+
await mkdir(dir, { recursive: true });
|
|
235
|
+
const intFile = this.#maybeIntegrityPath(integrity);
|
|
236
|
+
const base = basename(path);
|
|
237
|
+
const keyFile = base + '.key';
|
|
238
|
+
const tmp = dir + '/.' + base + '.' + this.random;
|
|
239
|
+
const keyTmp = dir + '/.' + keyFile + '.' + this.random;
|
|
240
|
+
const writeData = intFile ?
|
|
241
|
+
// try to just link into the temp location, rather than write
|
|
242
|
+
// may fail with ENOENT or EEXIST, in which case, write normally
|
|
243
|
+
link(intFile, tmp).catch(() => writeFile(tmp, val))
|
|
244
|
+
// don't have it by integrity, write the new entry
|
|
245
|
+
: writeFile(tmp, val);
|
|
246
|
+
let p = Promise.all([
|
|
247
|
+
writeData.then(() => rename(tmp, path)),
|
|
248
|
+
writeFile(keyTmp, key).then(() => rename(keyTmp, path + '.key')),
|
|
249
|
+
]);
|
|
250
|
+
if (intFile) {
|
|
251
|
+
p = p.then(() => link(path, intFile));
|
|
252
|
+
}
|
|
253
|
+
return p;
|
|
254
|
+
}
|
|
255
|
+
async #diskRead(k, v, integrity) {
|
|
256
|
+
const intFile = this.#maybeIntegrityPath(integrity);
|
|
257
|
+
const file = this.path(k);
|
|
258
|
+
const p = intFile ?
|
|
259
|
+
readFile(intFile).catch(async () => {
|
|
260
|
+
// if we get the value, but not integrity, link to the
|
|
261
|
+
// integrity file so we get it next time.
|
|
262
|
+
const value = await readFile(file);
|
|
263
|
+
await link(file, intFile);
|
|
264
|
+
return value;
|
|
265
|
+
})
|
|
266
|
+
: readFile(file);
|
|
267
|
+
return p.catch(() => v);
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,qBAAqB,CAAA;AAE3C,OAAO,EAAE,GAAG,EAAE,MAAM,aAAa,CAAA;AACjC,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,QAAQ,CAAA;AAChD,OAAO,EAAU,WAAW,EAAE,YAAY,EAAE,MAAM,IAAI,CAAA;AACtD,OAAO,EACL,IAAI,EACJ,KAAK,EACL,OAAO,EACP,QAAQ,EACR,MAAM,EACN,SAAS,GACV,MAAM,aAAa,CAAA;AACpB,OAAO,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAA;AACpC,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAA;AACnC,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,MAAM,CAAA;AACxC,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAA;AAmC/B,MAAM,IAAI,GAAG,CAAC,CAAS,EAAE,EAAE,CACzB,UAAU,CAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAA;AAE9C,MAAM,OAAO,KAAM,SAAQ,QAI1B;IACC,KAAK,CAAS;IACd,CAAC,MAAM,CAAC,WAAW,CAAC,GAAG,qBAAqB,CAAA;IAC5C,OAAO,GAAW,WAAW,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAA;IAChD,EAAE,GAAG,CAAC,CAAA;IACN,QAAQ,GAAG,IAAI,GAAG,EAAgC,CAAA;IAClD,WAAW,CAA8B;IACzC,YAAY,CAA+B;IAE3C;;;;OAIG;IACH,IAAI,MAAM;QACR,OAAO,IA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AC,CAAC,CAAC,CAAA;IACzB,CAAC;CACF","sourcesContent":["import { error } from '@vltpkg/error-cause'\nimport { Integrity } from '@vltpkg/types'\nimport { XDG } from '@vltpkg/xdg'\nimport { createHash, randomBytes } from 'crypto'\nimport { Dirent, opendirSync, readFileSync } from 'fs'\nimport {\n link,\n mkdir,\n opendir,\n readFile,\n rename,\n writeFile,\n} from 'fs/promises'\nimport { LRUCache } from 'lru-cache'\nimport { resolve } from 'node:path'\nimport { basename, dirname } from 'path'\nimport { rimraf } from 'rimraf'\n\nexport type CacheFetchContext =\n | {\n integrity?: Integrity\n }\n | undefined\n\nexport type CacheOptions = {\n [k in keyof LRUCache.Options<\n string,\n Buffer,\n CacheFetchContext\n >]?: LRUCache.Options<string, Buffer, CacheFetchContext>[k]\n} & {\n /**\n * fetchMethod may not be provided, because this cache forces its own\n * read-from-disk as the fetchMethod\n */\n fetchMethod?: undefined\n /**\n * folder where items should be stored to disk\n */\n path: string\n /**\n * called whenever an item is written to disk.\n */\n onDiskWrite?: (path: string, key: string, data: Buffer) => any\n /**\n * called whenever an item is deleted with `cache.delete(key, true)`\n * Deletes of the in-memory data do not trigger this method.\n */\n onDiskDelete?: (path: string, key: string, deleted: boolean) => any\n}\n\nconst hash = (s: string) =>\n createHash('sha512').update(s).digest('hex')\n\nexport class Cache extends LRUCache<\n string,\n Buffer,\n CacheFetchContext\n> {\n #path: string;\n [Symbol.toStringTag] = '@vltpkg/cache.Cache'\n #random: string = randomBytes(6).toString('hex')\n #i = 0\n #pending = new Set<Promise<boolean | undefined>>()\n onDiskWrite?: CacheOptions['onDiskWrite']\n onDiskDelete?: CacheOptions['onDiskDelete']\n\n /**\n * ensure we get a different random key for every write,\n * just in case the same file tries to write multiple times,\n * it'll still be atomic.\n */\n get random(): string {\n return this.#random + '.' + String(this.#i++)\n }\n\n /**\n * A list of the actions currently happening in the background\n */\n get pending() {\n return [...this.#pending]\n }\n\n /**\n * By default, cache up to 1000 items in memory.\n * Disk cache is unbounded.\n */\n static get defaultMax() {\n return 1000\n }\n\n constructor(options: CacheOptions) {\n const {\n onDiskWrite,\n onDiskDelete,\n path = new XDG('vlt').cache(),\n fetchMethod: _,\n sizeCalculation = options.maxSize || options.maxEntrySize ?\n (v: Buffer, k: string) => v.length + k.length\n : undefined,\n ...lruOpts\n } = options\n\n super({\n max: Cache.defaultMax,\n ...lruOpts,\n sizeCalculation,\n fetchMethod: async (k, v, opts) => {\n // do not write back to disk, since we just got it from there.\n Object.assign(opts.options, {\n noDiskWrite: true,\n })\n return this.#diskRead(k, v, opts.context?.integrity)\n },\n allowStaleOnFetchRejection: true,\n allowStaleOnFetchAbort: true,\n allowStale: true,\n noDeleteOnStaleGet: true,\n })\n this.onDiskWrite = onDiskWrite\n this.onDiskDelete = onDiskDelete\n this.#path = path\n }\n\n /**\n * Walk over all the items cached to disk (not just in memory).\n * Useful for cleanup, pruning, etc.\n *\n * Implementation for `for await` to walk over entries.\n */\n async *walk() {\n const dir = await opendir(this.#path, { bufferSize: 1024 })\n for await (const entry of dir) {\n const f = resolve(this.#path, entry.name)\n if (f.endsWith('.key')) {\n const entry: [string, Buffer] = await Promise.all([\n readFile(resolve(this.#path, f), 'utf8'),\n readFile(\n resolve(\n this.#path,\n f.substring(0, f.length - '.key'.length),\n ),\n ),\n ])\n yield entry\n }\n }\n }\n\n [Symbol.asyncIterator](): AsyncGenerator<\n [string, Buffer],\n void,\n void\n > {\n return this.walk()\n }\n\n /**\n * Synchronous form of Cache.walk()\n */\n *walkSync() {\n const dir = opendirSync(this.#path, { bufferSize: 1024 })\n let entry: Dirent | null = null\n while (null !== (entry = dir.readSync())) {\n const f = resolve(this.#path, entry.name)\n if (f.endsWith('.key')) {\n const entry: [string, Buffer] = [\n readFileSync(resolve(this.#path, f), 'utf8'),\n readFileSync(\n resolve(\n this.#path,\n f.substring(0, f.length - '.key'.length),\n ),\n ),\n ]\n yield entry\n }\n }\n dir.closeSync()\n }\n [Symbol.iterator](): Generator<[string, Buffer], void> {\n return this.walkSync()\n }\n\n #unpend<F extends (...a: any[]) => any>(\n p: Promise<any>,\n fn: F | undefined,\n ...args: Parameters<F>\n ) {\n this.#pending.delete(p)\n if (fn) fn(...args)\n }\n\n #pend(p: Promise<any>) {\n this.#pending.add(p)\n }\n\n /**\n * Pass `true` as second argument to delete not just from the in-memory\n * cache, but the disk backing as well.\n */\n delete(key: string, fromDisk = false): boolean {\n const ret = super.delete(key)\n if (fromDisk) {\n const path = this.path(key)\n const p: Promise<void> = this.#diskDelete(path).then(deleted =>\n this.#unpend(p, this.onDiskDelete, path, key, deleted),\n )\n this.#pend(p)\n }\n return ret\n }\n\n /**\n * Sets an item in the memory cache (like `LRUCache.set`), and schedules a\n * background operation to write it to disk.\n *\n * Use the {@link CacheOptions#onDiskWrite} method to know exactly when this\n * happens, or `await cache.promise()` to defer until all pending actions are\n * completed.\n *\n * The `noDiskWrite` option can be set to prevent it from writing back to the\n * disk cache. This is almost never relevant for consumers, and is used\n * internally to prevent the write at the end of `fetch()` from excessively\n * writing over a file we just read from.\n */\n set(\n key: string,\n val: Buffer,\n options?: LRUCache.SetOptions<\n string,\n Buffer,\n CacheFetchContext\n > & {\n /** set to `true` to prevent writes to disk cache */\n noDiskWrite?: boolean\n /** sha512 integrity string */\n integrity?: Integrity\n },\n ) {\n super.set(key, val, options)\n const { noDiskWrite, integrity } = options ?? {}\n // set/delete also used internally by LRUCache to manage async fetches\n // only write when we're putting an actual value into the cache\n if (Buffer.isBuffer(val) && !noDiskWrite) {\n // best effort, already have it in memory\n const path = this.path(key)\n const p: Promise<void> = this.#diskWrite(\n path,\n key,\n val,\n integrity,\n )\n /* c8 ignore next */\n .catch(() => {})\n .then(() => this.#unpend(p, this.onDiskWrite, path, key, val))\n this.#pend(p)\n }\n return this\n }\n\n /**\n * Resolves when there are no pending writes to the disk cache\n */\n async promise(): Promise<void> {\n if (this.pending.length) await Promise.all(this.pending)\n /* c8 ignore next - race condition */\n if (this.#pending.size) await this.promise()\n }\n\n /**\n * given a key, figure out the path on disk where it lives\n */\n path(key: string) {\n return resolve(this.#path, hash(key))\n }\n /**\n * given an SRI sha512 integrity string, get the path on disk that\n * is hard-linked to the value.\n */\n integrityPath(integrity?: Integrity) {\n if (!integrity) return undefined\n const m = /^sha512-([a-zA-Z0-9/+]{86}==)$/.exec(integrity)\n const hash = m?.[1]\n if (!hash) {\n throw error('invalid integrity value', {\n found: integrity,\n wanted: /^sha512-([a-zA-Z0-9/+]{86}==)$/,\n })\n }\n const base = Buffer.from(hash, 'base64').toString('hex')\n return resolve(this.#path, base)\n }\n\n /**\n * Read synchronously from the fs cache storage if not already\n * in memory.\n */\n fetchSync(\n key: string,\n opts?: LRUCache.FetchOptions<string, Buffer, CacheFetchContext>,\n ) {\n const v = this.get(key)\n if (v) return v\n const intFile = this.#maybeIntegrityPath(opts?.context?.integrity)\n if (intFile) {\n try {\n const v = readFileSync(intFile)\n this.set(key, v, { ...opts, noDiskWrite: true })\n return v\n /* c8 ignore start */\n } catch {}\n }\n /* c8 ignore stop */\n try {\n const v = readFileSync(this.path(key))\n // suppress the disk write, because we just read it from disk\n this.set(key, v, { ...opts, noDiskWrite: true })\n return v\n /* c8 ignore start */\n } catch {}\n }\n /* c8 ignore stop */\n\n /**\n * Delete path and path + '.key'\n */\n async #diskDelete(path: string): Promise<boolean> {\n return rimraf([path, path + '.key'])\n }\n\n #maybeIntegrityPath(i?: Integrity) {\n try {\n return this.integrityPath(i)\n } catch {}\n }\n async #diskWrite(\n path: string,\n key: string,\n val: Buffer,\n integrity?: Integrity,\n ) {\n const dir = dirname(path)\n await mkdir(dir, { recursive: true })\n const intFile = this.#maybeIntegrityPath(integrity)\n const base = basename(path)\n const keyFile = base + '.key'\n const tmp = dir + '/.' + base + '.' + this.random\n const keyTmp = dir + '/.' + keyFile + '.' + this.random\n const writeData =\n intFile ?\n // try to just link into the temp location, rather than write\n // may fail with ENOENT or EEXIST, in which case, write normally\n link(intFile, tmp).catch(() => writeFile(tmp, val))\n // don't have it by integrity, write the new entry\n : writeFile(tmp, val)\n\n let p: Promise<any> = Promise.all([\n writeData.then(() => rename(tmp, path)),\n writeFile(keyTmp, key).then(() =>\n rename(keyTmp, path + '.key'),\n ),\n ])\n if (intFile) {\n p = p.then(() => link(path, intFile))\n }\n return p\n }\n\n async #diskRead(\n k: string,\n v: Buffer | undefined,\n integrity?: Integrity,\n ) {\n const intFile = this.#maybeIntegrityPath(integrity)\n const file = this.path(k)\n const p =\n intFile ?\n readFile(intFile).catch(async () => {\n // if we get the value, but not integrity, link to the\n // integrity file so we get it next time.\n const value = await readFile(file)\n await link(file, intFile)\n return value\n })\n : readFile(file)\n return p.catch(() => v)\n }\n}\n"]}
|
package/package.json
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@vltpkg/cache",
|
|
3
|
+
"description": "The filesystem cache for `@vlt/registry-client`",
|
|
4
|
+
"version": "0.0.0-0.1730239248325",
|
|
5
|
+
"tshy": {
|
|
6
|
+
"selfLink": false,
|
|
7
|
+
"dialects": [
|
|
8
|
+
"esm"
|
|
9
|
+
],
|
|
10
|
+
"exports": {
|
|
11
|
+
"./package.json": "./package.json",
|
|
12
|
+
".": "./src/index.ts"
|
|
13
|
+
}
|
|
14
|
+
},
|
|
15
|
+
"dependencies": {
|
|
16
|
+
"lru-cache": "^11.0.0",
|
|
17
|
+
"rimraf": "^6.0.1",
|
|
18
|
+
"@vltpkg/error-cause": "0.0.0-0.1730239248325",
|
|
19
|
+
"@vltpkg/types": "0.0.0-0.1730239248325",
|
|
20
|
+
"@vltpkg/xdg": "0.0.0-0.1730239248325"
|
|
21
|
+
},
|
|
22
|
+
"devDependencies": {
|
|
23
|
+
"@eslint/js": "^9.8.0",
|
|
24
|
+
"@types/eslint__js": "^8.42.3",
|
|
25
|
+
"@types/node": "^22.4.1",
|
|
26
|
+
"eslint": "^9.8.0",
|
|
27
|
+
"prettier": "^3.3.2",
|
|
28
|
+
"tap": "^21.0.1",
|
|
29
|
+
"tshy": "^3.0.2",
|
|
30
|
+
"typescript": "^5.5.4",
|
|
31
|
+
"typescript-eslint": "^8.0.1"
|
|
32
|
+
},
|
|
33
|
+
"license": "BSD-2-Clause-Patent",
|
|
34
|
+
"engines": {
|
|
35
|
+
"node": "20 || >=22"
|
|
36
|
+
},
|
|
37
|
+
"tap": {
|
|
38
|
+
"extends": "../../tap-config.yaml"
|
|
39
|
+
},
|
|
40
|
+
"prettier": "../../.prettierrc.js",
|
|
41
|
+
"module": "./dist/esm/index.js",
|
|
42
|
+
"type": "module",
|
|
43
|
+
"exports": {
|
|
44
|
+
"./package.json": "./package.json",
|
|
45
|
+
".": {
|
|
46
|
+
"import": {
|
|
47
|
+
"types": "./dist/esm/index.d.ts",
|
|
48
|
+
"default": "./dist/esm/index.js"
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
},
|
|
52
|
+
"files": [
|
|
53
|
+
"dist"
|
|
54
|
+
],
|
|
55
|
+
"scripts": {
|
|
56
|
+
"format": "prettier --write . --log-level warn --ignore-path ../../.prettierignore --cache",
|
|
57
|
+
"format:check": "prettier --check . --ignore-path ../../.prettierignore --cache",
|
|
58
|
+
"lint": "eslint . --fix",
|
|
59
|
+
"lint:check": "eslint .",
|
|
60
|
+
"presnap": "tshy",
|
|
61
|
+
"snap": "tap",
|
|
62
|
+
"pretest": "tshy",
|
|
63
|
+
"test": "tap"
|
|
64
|
+
}
|
|
65
|
+
}
|