@open-mercato/cache-provider-kit 0.0.0-stage → 0.11.1-develop.8665.1.2455b2503c
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/.turbo/turbo-build.log +2 -0
- package/build.mjs +10 -0
- package/dist/codec.js +75 -0
- package/dist/codec.js.map +7 -0
- package/dist/defaults.js +7 -0
- package/dist/defaults.js.map +7 -0
- package/dist/errors.js +13 -0
- package/dist/errors.js.map +7 -0
- package/dist/index.js +1 -0
- package/dist/index.js.map +7 -0
- package/dist/patterns.js +36 -0
- package/dist/patterns.js.map +7 -0
- package/dist/redisConnection.js +22 -0
- package/dist/redisConnection.js.map +7 -0
- package/package.json +33 -3
- package/src/codec.ts +94 -0
- package/src/defaults.ts +2 -0
- package/src/errors.ts +13 -0
- package/src/index.ts +107 -0
- package/src/patterns.ts +39 -0
- package/src/redisConnection.ts +58 -0
- package/tsconfig.json +10 -0
- package/watch.mjs +6 -0
- package/README.md +0 -3
package/build.mjs
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { dirname } from 'node:path'
|
|
2
|
+
import { fileURLToPath } from 'node:url'
|
|
3
|
+
import { buildPackage } from '../../scripts/build-package.mjs'
|
|
4
|
+
|
|
5
|
+
const packageDir = dirname(fileURLToPath(import.meta.url))
|
|
6
|
+
|
|
7
|
+
await buildPackage(packageDir, {
|
|
8
|
+
name: 'cache-provider-kit',
|
|
9
|
+
entryPoints: 'src/**/*.ts',
|
|
10
|
+
})
|
package/dist/codec.js
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import zlib from "node:zlib";
|
|
2
|
+
const DEFAULT_COMPRESSION_MIN_BYTES = 1024;
|
|
3
|
+
const MAX_DECOMPRESSED_BYTES = 64 * 1024 * 1024;
|
|
4
|
+
const ZSTD_LEVEL = 1;
|
|
5
|
+
const COMPRESSIONS = ["off", "zstd", "gzip"];
|
|
6
|
+
const warnedMessages = /* @__PURE__ */ new Set();
|
|
7
|
+
function warnOnce(message) {
|
|
8
|
+
if (warnedMessages.has(message)) return;
|
|
9
|
+
warnedMessages.add(message);
|
|
10
|
+
console.warn(message);
|
|
11
|
+
}
|
|
12
|
+
function isZstdAvailable() {
|
|
13
|
+
return typeof zlib.zstdCompressSync === "function" && typeof zlib.zstdDecompressSync === "function";
|
|
14
|
+
}
|
|
15
|
+
function parseCacheCompression(raw) {
|
|
16
|
+
const value = raw?.trim().toLowerCase();
|
|
17
|
+
if (!value) return "off";
|
|
18
|
+
if (COMPRESSIONS.includes(value)) return value;
|
|
19
|
+
warnOnce(`[cache] Unknown CACHE_COMPRESSION value "${raw}". Compression stays off.`);
|
|
20
|
+
return "off";
|
|
21
|
+
}
|
|
22
|
+
function parseCacheCompressionMinBytes(raw) {
|
|
23
|
+
if (!raw) return void 0;
|
|
24
|
+
const parsed = Number.parseInt(raw, 10);
|
|
25
|
+
return Number.isFinite(parsed) && parsed > 0 ? parsed : void 0;
|
|
26
|
+
}
|
|
27
|
+
function resolveCacheCodecConfig(options) {
|
|
28
|
+
const minBytes = options?.compressionMinBytes && options.compressionMinBytes > 0 ? options.compressionMinBytes : DEFAULT_COMPRESSION_MIN_BYTES;
|
|
29
|
+
let compression = options?.compression ?? "off";
|
|
30
|
+
if (compression === "zstd" && !isZstdAvailable()) {
|
|
31
|
+
warnOnce("[cache] zstd is not available in this Node.js runtime. Falling back to gzip cache compression.");
|
|
32
|
+
compression = "gzip";
|
|
33
|
+
}
|
|
34
|
+
return { compression, minBytes };
|
|
35
|
+
}
|
|
36
|
+
function compress(input, compression) {
|
|
37
|
+
if (compression === "zstd") {
|
|
38
|
+
return zlib.zstdCompressSync(input, { params: { [zlib.constants.ZSTD_c_compressionLevel]: ZSTD_LEVEL } });
|
|
39
|
+
}
|
|
40
|
+
return zlib.gzipSync(input);
|
|
41
|
+
}
|
|
42
|
+
function encodeCacheText(json, config) {
|
|
43
|
+
if (config.compression === "off") return json;
|
|
44
|
+
const size = Buffer.byteLength(json);
|
|
45
|
+
if (size < config.minBytes || size > MAX_DECOMPRESSED_BYTES) return json;
|
|
46
|
+
const compressed = compress(Buffer.from(json, "utf8"), config.compression);
|
|
47
|
+
return compressed.length < size ? compressed : json;
|
|
48
|
+
}
|
|
49
|
+
function isZstdFrame(raw) {
|
|
50
|
+
return raw.length >= 4 && raw[0] === 40 && raw[1] === 181 && raw[2] === 47 && raw[3] === 253;
|
|
51
|
+
}
|
|
52
|
+
function isGzipStream(raw) {
|
|
53
|
+
return raw.length >= 2 && raw[0] === 31 && raw[1] === 139;
|
|
54
|
+
}
|
|
55
|
+
function decodeCacheText(raw) {
|
|
56
|
+
if (typeof raw === "string") return raw;
|
|
57
|
+
if (isZstdFrame(raw)) {
|
|
58
|
+
return zlib.zstdDecompressSync(raw, { maxOutputLength: MAX_DECOMPRESSED_BYTES }).toString("utf8");
|
|
59
|
+
}
|
|
60
|
+
if (isGzipStream(raw)) {
|
|
61
|
+
return zlib.gunzipSync(raw, { maxOutputLength: MAX_DECOMPRESSED_BYTES }).toString("utf8");
|
|
62
|
+
}
|
|
63
|
+
return raw.toString("utf8");
|
|
64
|
+
}
|
|
65
|
+
export {
|
|
66
|
+
DEFAULT_COMPRESSION_MIN_BYTES,
|
|
67
|
+
MAX_DECOMPRESSED_BYTES,
|
|
68
|
+
decodeCacheText,
|
|
69
|
+
encodeCacheText,
|
|
70
|
+
isZstdAvailable,
|
|
71
|
+
parseCacheCompression,
|
|
72
|
+
parseCacheCompressionMinBytes,
|
|
73
|
+
resolveCacheCodecConfig
|
|
74
|
+
};
|
|
75
|
+
//# sourceMappingURL=codec.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/codec.ts"],
|
|
4
|
+
"sourcesContent": ["import zlib from 'node:zlib'\n\nexport type CacheCompression = 'off' | 'zstd' | 'gzip'\n\nexport type CacheCodecConfig = {\n compression: CacheCompression\n minBytes: number\n}\n\nexport type CacheCodecOptions = {\n compression?: CacheCompression\n compressionMinBytes?: number\n}\n\nexport const DEFAULT_COMPRESSION_MIN_BYTES = 1024\n\n/** Upper bound for one decompressed entry; larger JSON is never compressed, so no legitimate entry can hit it. */\nexport const MAX_DECOMPRESSED_BYTES = 64 * 1024 * 1024\n\nconst ZSTD_LEVEL = 1\nconst COMPRESSIONS: CacheCompression[] = ['off', 'zstd', 'gzip']\n\nconst warnedMessages = new Set<string>()\n\nfunction warnOnce(message: string): void {\n if (warnedMessages.has(message)) return\n warnedMessages.add(message)\n console.warn(message)\n}\n\nexport function isZstdAvailable(): boolean {\n return typeof zlib.zstdCompressSync === 'function' && typeof zlib.zstdDecompressSync === 'function'\n}\n\nexport function parseCacheCompression(raw: string | undefined): CacheCompression {\n const value = raw?.trim().toLowerCase()\n if (!value) return 'off'\n if (COMPRESSIONS.includes(value as CacheCompression)) return value as CacheCompression\n warnOnce(`[cache] Unknown CACHE_COMPRESSION value \"${raw}\". Compression stays off.`)\n return 'off'\n}\n\nexport function parseCacheCompressionMinBytes(raw: string | undefined): number | undefined {\n if (!raw) return undefined\n const parsed = Number.parseInt(raw, 10)\n return Number.isFinite(parsed) && parsed > 0 ? parsed : undefined\n}\n\nexport function resolveCacheCodecConfig(options?: CacheCodecOptions): CacheCodecConfig {\n const minBytes = options?.compressionMinBytes && options.compressionMinBytes > 0\n ? options.compressionMinBytes\n : DEFAULT_COMPRESSION_MIN_BYTES\n let compression = options?.compression ?? 'off'\n if (compression === 'zstd' && !isZstdAvailable()) {\n warnOnce('[cache] zstd is not available in this Node.js runtime. Falling back to gzip cache compression.')\n compression = 'gzip'\n }\n return { compression, minBytes }\n}\n\nfunction compress(input: Buffer, compression: Exclude<CacheCompression, 'off'>): Buffer {\n if (compression === 'zstd') {\n return zlib.zstdCompressSync(input, { params: { [zlib.constants.ZSTD_c_compressionLevel]: ZSTD_LEVEL } })\n }\n return zlib.gzipSync(input)\n}\n\nexport function encodeCacheText(json: string, config: CacheCodecConfig): string | Buffer {\n if (config.compression === 'off') return json\n const size = Buffer.byteLength(json)\n if (size < config.minBytes || size > MAX_DECOMPRESSED_BYTES) return json\n const compressed = compress(Buffer.from(json, 'utf8'), config.compression)\n return compressed.length < size ? compressed : json\n}\n\nfunction isZstdFrame(raw: Buffer): boolean {\n return raw.length >= 4 && raw[0] === 0x28 && raw[1] === 0xb5 && raw[2] === 0x2f && raw[3] === 0xfd\n}\n\nfunction isGzipStream(raw: Buffer): boolean {\n return raw.length >= 2 && raw[0] === 0x1f && raw[1] === 0x8b\n}\n\n/** Detects the format from the stored bytes, so entries stay readable whatever CACHE_COMPRESSION is set to now. */\nexport function decodeCacheText(raw: string | Buffer): string {\n if (typeof raw === 'string') return raw\n if (isZstdFrame(raw)) {\n return zlib.zstdDecompressSync(raw, { maxOutputLength: MAX_DECOMPRESSED_BYTES }).toString('utf8')\n }\n if (isGzipStream(raw)) {\n return zlib.gunzipSync(raw, { maxOutputLength: MAX_DECOMPRESSED_BYTES }).toString('utf8')\n }\n return raw.toString('utf8')\n}\n"],
|
|
5
|
+
"mappings": "AAAA,OAAO,UAAU;AAcV,MAAM,gCAAgC;AAGtC,MAAM,yBAAyB,KAAK,OAAO;AAElD,MAAM,aAAa;AACnB,MAAM,eAAmC,CAAC,OAAO,QAAQ,MAAM;AAE/D,MAAM,iBAAiB,oBAAI,IAAY;AAEvC,SAAS,SAAS,SAAuB;AACvC,MAAI,eAAe,IAAI,OAAO,EAAG;AACjC,iBAAe,IAAI,OAAO;AAC1B,UAAQ,KAAK,OAAO;AACtB;AAEO,SAAS,kBAA2B;AACzC,SAAO,OAAO,KAAK,qBAAqB,cAAc,OAAO,KAAK,uBAAuB;AAC3F;AAEO,SAAS,sBAAsB,KAA2C;AAC/E,QAAM,QAAQ,KAAK,KAAK,EAAE,YAAY;AACtC,MAAI,CAAC,MAAO,QAAO;AACnB,MAAI,aAAa,SAAS,KAAyB,EAAG,QAAO;AAC7D,WAAS,4CAA4C,GAAG,2BAA2B;AACnF,SAAO;AACT;AAEO,SAAS,8BAA8B,KAA6C;AACzF,MAAI,CAAC,IAAK,QAAO;AACjB,QAAM,SAAS,OAAO,SAAS,KAAK,EAAE;AACtC,SAAO,OAAO,SAAS,MAAM,KAAK,SAAS,IAAI,SAAS;AAC1D;AAEO,SAAS,wBAAwB,SAA+C;AACrF,QAAM,WAAW,SAAS,uBAAuB,QAAQ,sBAAsB,IAC3E,QAAQ,sBACR;AACJ,MAAI,cAAc,SAAS,eAAe;AAC1C,MAAI,gBAAgB,UAAU,CAAC,gBAAgB,GAAG;AAChD,aAAS,gGAAgG;AACzG,kBAAc;AAAA,EAChB;AACA,SAAO,EAAE,aAAa,SAAS;AACjC;AAEA,SAAS,SAAS,OAAe,aAAuD;AACtF,MAAI,gBAAgB,QAAQ;AAC1B,WAAO,KAAK,iBAAiB,OAAO,EAAE,QAAQ,EAAE,CAAC,KAAK,UAAU,uBAAuB,GAAG,WAAW,EAAE,CAAC;AAAA,EAC1G;AACA,SAAO,KAAK,SAAS,KAAK;AAC5B;AAEO,SAAS,gBAAgB,MAAc,QAA2C;AACvF,MAAI,OAAO,gBAAgB,MAAO,QAAO;AACzC,QAAM,OAAO,OAAO,WAAW,IAAI;AACnC,MAAI,OAAO,OAAO,YAAY,OAAO,uBAAwB,QAAO;AACpE,QAAM,aAAa,SAAS,OAAO,KAAK,MAAM,MAAM,GAAG,OAAO,WAAW;AACzE,SAAO,WAAW,SAAS,OAAO,aAAa;AACjD;AAEA,SAAS,YAAY,KAAsB;AACzC,SAAO,IAAI,UAAU,KAAK,IAAI,CAAC,MAAM,MAAQ,IAAI,CAAC,MAAM,OAAQ,IAAI,CAAC,MAAM,MAAQ,IAAI,CAAC,MAAM;AAChG;AAEA,SAAS,aAAa,KAAsB;AAC1C,SAAO,IAAI,UAAU,KAAK,IAAI,CAAC,MAAM,MAAQ,IAAI,CAAC,MAAM;AAC1D;AAGO,SAAS,gBAAgB,KAA8B;AAC5D,MAAI,OAAO,QAAQ,SAAU,QAAO;AACpC,MAAI,YAAY,GAAG,GAAG;AACpB,WAAO,KAAK,mBAAmB,KAAK,EAAE,iBAAiB,uBAAuB,CAAC,EAAE,SAAS,MAAM;AAAA,EAClG;AACA,MAAI,aAAa,GAAG,GAAG;AACrB,WAAO,KAAK,WAAW,KAAK,EAAE,iBAAiB,uBAAuB,CAAC,EAAE,SAAS,MAAM;AAAA,EAC1F;AACA,SAAO,IAAI,SAAS,MAAM;AAC5B;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
package/dist/defaults.js
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/defaults.ts"],
|
|
4
|
+
"sourcesContent": ["export const DEFAULT_SQLITE_CACHE_PATH = '.mercato/cache/cache.db'\nexport const DEFAULT_JSON_FILE_CACHE_PATH = '.mercato/cache/cache.json'\n"],
|
|
5
|
+
"mappings": "AAAO,MAAM,4BAA4B;AAClC,MAAM,+BAA+B;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
package/dist/errors.js
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
class CacheDependencyUnavailableError extends Error {
|
|
2
|
+
constructor(strategy, dependency, originalError) {
|
|
3
|
+
super(`Cache strategy "${strategy}" requires dependency "${dependency}" which is not available`);
|
|
4
|
+
this.name = "CacheDependencyUnavailableError";
|
|
5
|
+
this.strategy = strategy;
|
|
6
|
+
this.dependency = dependency;
|
|
7
|
+
this.originalError = originalError;
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
export {
|
|
11
|
+
CacheDependencyUnavailableError
|
|
12
|
+
};
|
|
13
|
+
//# sourceMappingURL=errors.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/errors.ts"],
|
|
4
|
+
"sourcesContent": ["export class CacheDependencyUnavailableError extends Error {\n public readonly strategy: string\n public readonly dependency: string\n public readonly originalError?: unknown\n\n constructor(strategy: string, dependency: string, originalError?: unknown) {\n super(`Cache strategy \"${strategy}\" requires dependency \"${dependency}\" which is not available`)\n this.name = 'CacheDependencyUnavailableError'\n this.strategy = strategy\n this.dependency = dependency\n this.originalError = originalError\n }\n}\n"],
|
|
5
|
+
"mappings": "AAAO,MAAM,wCAAwC,MAAM;AAAA,EAKzD,YAAY,UAAkB,YAAoB,eAAyB;AACzE,UAAM,mBAAmB,QAAQ,0BAA0B,UAAU,0BAA0B;AAC/F,SAAK,OAAO;AACZ,SAAK,WAAW;AAChB,SAAK,aAAa;AAClB,SAAK,gBAAgB;AAAA,EACvB;AACF;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
//# sourceMappingURL=index.js.map
|
package/dist/patterns.js
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
function matchCacheKeyPattern(key, pattern) {
|
|
2
|
+
let patternIndex = 0;
|
|
3
|
+
let keyIndex = 0;
|
|
4
|
+
let starIndex = -1;
|
|
5
|
+
let keyRetryIndex = 0;
|
|
6
|
+
while (keyIndex < key.length) {
|
|
7
|
+
const patternChar = pattern[patternIndex];
|
|
8
|
+
const keyChar = key[keyIndex];
|
|
9
|
+
if (patternChar === "*") {
|
|
10
|
+
starIndex = patternIndex;
|
|
11
|
+
keyRetryIndex = keyIndex;
|
|
12
|
+
patternIndex += 1;
|
|
13
|
+
continue;
|
|
14
|
+
}
|
|
15
|
+
if (patternChar === "?" || patternChar === keyChar) {
|
|
16
|
+
patternIndex += 1;
|
|
17
|
+
keyIndex += 1;
|
|
18
|
+
continue;
|
|
19
|
+
}
|
|
20
|
+
if (starIndex !== -1) {
|
|
21
|
+
patternIndex = starIndex + 1;
|
|
22
|
+
keyRetryIndex += 1;
|
|
23
|
+
keyIndex = keyRetryIndex;
|
|
24
|
+
continue;
|
|
25
|
+
}
|
|
26
|
+
return false;
|
|
27
|
+
}
|
|
28
|
+
while (pattern[patternIndex] === "*") {
|
|
29
|
+
patternIndex += 1;
|
|
30
|
+
}
|
|
31
|
+
return patternIndex === pattern.length;
|
|
32
|
+
}
|
|
33
|
+
export {
|
|
34
|
+
matchCacheKeyPattern
|
|
35
|
+
};
|
|
36
|
+
//# sourceMappingURL=patterns.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/patterns.ts"],
|
|
4
|
+
"sourcesContent": ["export function matchCacheKeyPattern(key: string, pattern: string): boolean {\n let patternIndex = 0\n let keyIndex = 0\n let starIndex = -1\n let keyRetryIndex = 0\n\n while (keyIndex < key.length) {\n const patternChar = pattern[patternIndex]\n const keyChar = key[keyIndex]\n\n if (patternChar === '*') {\n starIndex = patternIndex\n keyRetryIndex = keyIndex\n patternIndex += 1\n continue\n }\n\n if (patternChar === '?' || patternChar === keyChar) {\n patternIndex += 1\n keyIndex += 1\n continue\n }\n\n if (starIndex !== -1) {\n patternIndex = starIndex + 1\n keyRetryIndex += 1\n keyIndex = keyRetryIndex\n continue\n }\n\n return false\n }\n\n while (pattern[patternIndex] === '*') {\n patternIndex += 1\n }\n\n return patternIndex === pattern.length\n}\n"],
|
|
5
|
+
"mappings": "AAAO,SAAS,qBAAqB,KAAa,SAA0B;AAC1E,MAAI,eAAe;AACnB,MAAI,WAAW;AACf,MAAI,YAAY;AAChB,MAAI,gBAAgB;AAEpB,SAAO,WAAW,IAAI,QAAQ;AAC5B,UAAM,cAAc,QAAQ,YAAY;AACxC,UAAM,UAAU,IAAI,QAAQ;AAE5B,QAAI,gBAAgB,KAAK;AACvB,kBAAY;AACZ,sBAAgB;AAChB,sBAAgB;AAChB;AAAA,IACF;AAEA,QAAI,gBAAgB,OAAO,gBAAgB,SAAS;AAClD,sBAAgB;AAChB,kBAAY;AACZ;AAAA,IACF;AAEA,QAAI,cAAc,IAAI;AACpB,qBAAe,YAAY;AAC3B,uBAAiB;AACjB,iBAAW;AACX;AAAA,IACF;AAEA,WAAO;AAAA,EACT;AAEA,SAAO,QAAQ,YAAY,MAAM,KAAK;AACpC,oBAAgB;AAAA,EAClB;AAEA,SAAO,iBAAiB,QAAQ;AAClC;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
const REDIS_WIRE_PROTOCOL = 2;
|
|
2
|
+
function getRedisUrl(prefix) {
|
|
3
|
+
if (prefix) {
|
|
4
|
+
const prefixed = process.env[`${prefix}_REDIS_URL`];
|
|
5
|
+
if (prefixed) return prefixed;
|
|
6
|
+
}
|
|
7
|
+
return process.env.REDIS_URL || null;
|
|
8
|
+
}
|
|
9
|
+
function getRedisUrlOrThrow(prefix) {
|
|
10
|
+
const url = getRedisUrl(prefix);
|
|
11
|
+
if (url) return url;
|
|
12
|
+
const which = prefix ? `${prefix}_REDIS_URL or REDIS_URL` : "REDIS_URL";
|
|
13
|
+
throw new Error(
|
|
14
|
+
`Redis URL is not configured. Set ${which} in your environment to use a Redis-backed strategy.`
|
|
15
|
+
);
|
|
16
|
+
}
|
|
17
|
+
export {
|
|
18
|
+
REDIS_WIRE_PROTOCOL,
|
|
19
|
+
getRedisUrl,
|
|
20
|
+
getRedisUrlOrThrow
|
|
21
|
+
};
|
|
22
|
+
//# sourceMappingURL=redisConnection.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/redisConnection.ts"],
|
|
4
|
+
"sourcesContent": ["/**\n * Redis URL resolution and wire-protocol constant shared by the cache packages so\n * the stock Redis strategy does not depend on `@open-mercato/shared`, which\n * `@open-mercato/cache` does not (and cannot, without a cycle) declare.\n * `@open-mercato/shared/lib/redis/connection` re-exports these unchanged.\n */\n\n/**\n * RESP wire protocol version, mirroring ioredis' own `ProtocolVersion` union.\n * Declared locally because ioredis is an optional peer of the packages that\n * consume these options.\n */\nexport type RedisProtocolVersion = 2 | 3\n\n/**\n * Wire protocol every Redis client in the monorepo negotiates.\n *\n * ioredis 6 switched its default from RESP2 to RESP3. RESP3 changes the reply\n * shape of map-style commands and delivers pub/sub over push frames instead of\n * ordinary replies, which neither BullMQ nor rate-limiter-flexible declare\n * support for. Pinning the protocol keeps the client byte-compatible with the\n * ioredis 5 behaviour the rest of the stack was built and tested against.\n * Adopting RESP3 is a deliberate, separately testable change \u2014 not a side\n * effect of a version bump.\n */\nexport const REDIS_WIRE_PROTOCOL: RedisProtocolVersion = 2\n\n/**\n * Resolve a Redis URL from environment variables.\n *\n * Priority: <PREFIX>_REDIS_URL \u2192 REDIS_URL \u2192 null\n *\n * Returns null when no env var is set. Callers MUST NOT assume a\n * localhost default \u2014 silently connecting to localhost masks missing\n * configuration and stalls on platforms where nothing listens there\n * (e.g., WSL2 without a local Redis).\n */\nexport function getRedisUrl(prefix?: string): string | null {\n if (prefix) {\n const prefixed = process.env[`${prefix}_REDIS_URL`]\n if (prefixed) return prefixed\n }\n return process.env.REDIS_URL || null\n}\n\n/**\n * Like getRedisUrl, but throws a descriptive error when Redis is not\n * configured. Use from code paths that require Redis (e.g. BullMQ\n * async queue, Redis cache strategy, scheduler service).\n */\nexport function getRedisUrlOrThrow(prefix?: string): string {\n const url = getRedisUrl(prefix)\n if (url) return url\n const which = prefix ? `${prefix}_REDIS_URL or REDIS_URL` : 'REDIS_URL'\n throw new Error(\n `Redis URL is not configured. Set ${which} in your environment to use a Redis-backed strategy.`\n )\n}\n"],
|
|
5
|
+
"mappings": "AAyBO,MAAM,sBAA4C;AAYlD,SAAS,YAAY,QAAgC;AAC1D,MAAI,QAAQ;AACV,UAAM,WAAW,QAAQ,IAAI,GAAG,MAAM,YAAY;AAClD,QAAI,SAAU,QAAO;AAAA,EACvB;AACA,SAAO,QAAQ,IAAI,aAAa;AAClC;AAOO,SAAS,mBAAmB,QAAyB;AAC1D,QAAM,MAAM,YAAY,MAAM;AAC9B,MAAI,IAAK,QAAO;AAChB,QAAM,QAAQ,SAAS,GAAG,MAAM,4BAA4B;AAC5D,QAAM,IAAI;AAAA,IACR,oCAAoC,KAAK;AAAA,EAC3C;AACF;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,36 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@open-mercato/cache-provider-kit",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.11.1-develop.8665.1.2455b2503c",
|
|
4
|
+
"description": "Shared strategy types and storage helpers for Open Mercato cache",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"main": "./dist/index.js",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"types": "./src/index.ts",
|
|
11
|
+
"default": "./dist/index.js"
|
|
12
|
+
},
|
|
13
|
+
"./*": {
|
|
14
|
+
"types": "./src/*.ts",
|
|
15
|
+
"default": "./dist/*.js"
|
|
16
|
+
}
|
|
17
|
+
},
|
|
18
|
+
"scripts": {
|
|
19
|
+
"build": "node build.mjs",
|
|
20
|
+
"watch": "node watch.mjs",
|
|
21
|
+
"typecheck": "tsc --noEmit"
|
|
22
|
+
},
|
|
23
|
+
"devDependencies": {
|
|
24
|
+
"@types/node": "^26.4.0",
|
|
25
|
+
"typescript": "7.0.2"
|
|
26
|
+
},
|
|
27
|
+
"publishConfig": {
|
|
28
|
+
"access": "public"
|
|
29
|
+
},
|
|
30
|
+
"repository": {
|
|
31
|
+
"type": "git",
|
|
32
|
+
"url": "https://github.com/open-mercato/open-mercato",
|
|
33
|
+
"directory": "packages/cache-provider-kit"
|
|
34
|
+
},
|
|
35
|
+
"stableVersion": "0.11.0"
|
|
6
36
|
}
|
package/src/codec.ts
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import zlib from 'node:zlib'
|
|
2
|
+
|
|
3
|
+
export type CacheCompression = 'off' | 'zstd' | 'gzip'
|
|
4
|
+
|
|
5
|
+
export type CacheCodecConfig = {
|
|
6
|
+
compression: CacheCompression
|
|
7
|
+
minBytes: number
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export type CacheCodecOptions = {
|
|
11
|
+
compression?: CacheCompression
|
|
12
|
+
compressionMinBytes?: number
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export const DEFAULT_COMPRESSION_MIN_BYTES = 1024
|
|
16
|
+
|
|
17
|
+
/** Upper bound for one decompressed entry; larger JSON is never compressed, so no legitimate entry can hit it. */
|
|
18
|
+
export const MAX_DECOMPRESSED_BYTES = 64 * 1024 * 1024
|
|
19
|
+
|
|
20
|
+
const ZSTD_LEVEL = 1
|
|
21
|
+
const COMPRESSIONS: CacheCompression[] = ['off', 'zstd', 'gzip']
|
|
22
|
+
|
|
23
|
+
const warnedMessages = new Set<string>()
|
|
24
|
+
|
|
25
|
+
function warnOnce(message: string): void {
|
|
26
|
+
if (warnedMessages.has(message)) return
|
|
27
|
+
warnedMessages.add(message)
|
|
28
|
+
console.warn(message)
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function isZstdAvailable(): boolean {
|
|
32
|
+
return typeof zlib.zstdCompressSync === 'function' && typeof zlib.zstdDecompressSync === 'function'
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function parseCacheCompression(raw: string | undefined): CacheCompression {
|
|
36
|
+
const value = raw?.trim().toLowerCase()
|
|
37
|
+
if (!value) return 'off'
|
|
38
|
+
if (COMPRESSIONS.includes(value as CacheCompression)) return value as CacheCompression
|
|
39
|
+
warnOnce(`[cache] Unknown CACHE_COMPRESSION value "${raw}". Compression stays off.`)
|
|
40
|
+
return 'off'
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function parseCacheCompressionMinBytes(raw: string | undefined): number | undefined {
|
|
44
|
+
if (!raw) return undefined
|
|
45
|
+
const parsed = Number.parseInt(raw, 10)
|
|
46
|
+
return Number.isFinite(parsed) && parsed > 0 ? parsed : undefined
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export function resolveCacheCodecConfig(options?: CacheCodecOptions): CacheCodecConfig {
|
|
50
|
+
const minBytes = options?.compressionMinBytes && options.compressionMinBytes > 0
|
|
51
|
+
? options.compressionMinBytes
|
|
52
|
+
: DEFAULT_COMPRESSION_MIN_BYTES
|
|
53
|
+
let compression = options?.compression ?? 'off'
|
|
54
|
+
if (compression === 'zstd' && !isZstdAvailable()) {
|
|
55
|
+
warnOnce('[cache] zstd is not available in this Node.js runtime. Falling back to gzip cache compression.')
|
|
56
|
+
compression = 'gzip'
|
|
57
|
+
}
|
|
58
|
+
return { compression, minBytes }
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function compress(input: Buffer, compression: Exclude<CacheCompression, 'off'>): Buffer {
|
|
62
|
+
if (compression === 'zstd') {
|
|
63
|
+
return zlib.zstdCompressSync(input, { params: { [zlib.constants.ZSTD_c_compressionLevel]: ZSTD_LEVEL } })
|
|
64
|
+
}
|
|
65
|
+
return zlib.gzipSync(input)
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export function encodeCacheText(json: string, config: CacheCodecConfig): string | Buffer {
|
|
69
|
+
if (config.compression === 'off') return json
|
|
70
|
+
const size = Buffer.byteLength(json)
|
|
71
|
+
if (size < config.minBytes || size > MAX_DECOMPRESSED_BYTES) return json
|
|
72
|
+
const compressed = compress(Buffer.from(json, 'utf8'), config.compression)
|
|
73
|
+
return compressed.length < size ? compressed : json
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function isZstdFrame(raw: Buffer): boolean {
|
|
77
|
+
return raw.length >= 4 && raw[0] === 0x28 && raw[1] === 0xb5 && raw[2] === 0x2f && raw[3] === 0xfd
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function isGzipStream(raw: Buffer): boolean {
|
|
81
|
+
return raw.length >= 2 && raw[0] === 0x1f && raw[1] === 0x8b
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** Detects the format from the stored bytes, so entries stay readable whatever CACHE_COMPRESSION is set to now. */
|
|
85
|
+
export function decodeCacheText(raw: string | Buffer): string {
|
|
86
|
+
if (typeof raw === 'string') return raw
|
|
87
|
+
if (isZstdFrame(raw)) {
|
|
88
|
+
return zlib.zstdDecompressSync(raw, { maxOutputLength: MAX_DECOMPRESSED_BYTES }).toString('utf8')
|
|
89
|
+
}
|
|
90
|
+
if (isGzipStream(raw)) {
|
|
91
|
+
return zlib.gunzipSync(raw, { maxOutputLength: MAX_DECOMPRESSED_BYTES }).toString('utf8')
|
|
92
|
+
}
|
|
93
|
+
return raw.toString('utf8')
|
|
94
|
+
}
|
package/src/defaults.ts
ADDED
package/src/errors.ts
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
export class CacheDependencyUnavailableError extends Error {
|
|
2
|
+
public readonly strategy: string
|
|
3
|
+
public readonly dependency: string
|
|
4
|
+
public readonly originalError?: unknown
|
|
5
|
+
|
|
6
|
+
constructor(strategy: string, dependency: string, originalError?: unknown) {
|
|
7
|
+
super(`Cache strategy "${strategy}" requires dependency "${dependency}" which is not available`)
|
|
8
|
+
this.name = 'CacheDependencyUnavailableError'
|
|
9
|
+
this.strategy = strategy
|
|
10
|
+
this.dependency = dependency
|
|
11
|
+
this.originalError = originalError
|
|
12
|
+
}
|
|
13
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
export type CacheValue = unknown
|
|
2
|
+
|
|
3
|
+
export type CacheEntry = {
|
|
4
|
+
key: string
|
|
5
|
+
value: CacheValue
|
|
6
|
+
tags: string[]
|
|
7
|
+
expiresAt: number | null
|
|
8
|
+
/**
|
|
9
|
+
* Wall-clock creation time. Informational/diagnostic only — LRU recency and
|
|
10
|
+
* eviction rely purely on Map insertion order, not on this field.
|
|
11
|
+
*/
|
|
12
|
+
createdAt: number
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export type CacheOptions = {
|
|
16
|
+
ttl?: number // Time to live in milliseconds
|
|
17
|
+
tags?: string[] // Tags for invalidation
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export type CacheGetOptions = {
|
|
21
|
+
returnExpired?: boolean // Return expired values (default: false)
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export type CacheSetOptions = CacheOptions
|
|
25
|
+
|
|
26
|
+
export type CacheStrategy = {
|
|
27
|
+
/**
|
|
28
|
+
* Get a value from cache
|
|
29
|
+
* @param key - Cache key
|
|
30
|
+
* @param options - Get options
|
|
31
|
+
* @returns The cached value or null if not found or expired
|
|
32
|
+
*/
|
|
33
|
+
get(key: string, options?: CacheGetOptions): Promise<CacheValue | null>
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Set a value in cache
|
|
37
|
+
* @param key - Cache key
|
|
38
|
+
* @param value - Value to cache
|
|
39
|
+
* @param options - Cache options (ttl, tags)
|
|
40
|
+
*/
|
|
41
|
+
set(key: string, value: CacheValue, options?: CacheSetOptions): Promise<void>
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Check if a key exists in cache (and is not expired)
|
|
45
|
+
* @param key - Cache key
|
|
46
|
+
* @returns true if key exists and is not expired
|
|
47
|
+
*/
|
|
48
|
+
has(key: string): Promise<boolean>
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Delete a specific key from cache
|
|
52
|
+
* @param key - Cache key
|
|
53
|
+
* @returns true if key was deleted, false if not found
|
|
54
|
+
*/
|
|
55
|
+
delete(key: string): Promise<boolean>
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Delete all keys with specified tags
|
|
59
|
+
* @param tags - Tags to match (any key with ANY of these tags will be deleted)
|
|
60
|
+
* @returns Number of keys deleted
|
|
61
|
+
*/
|
|
62
|
+
deleteByTags(tags: string[]): Promise<number>
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Clear all cache entries
|
|
66
|
+
* @returns Number of keys deleted
|
|
67
|
+
*/
|
|
68
|
+
clear(): Promise<number>
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Get all keys matching a pattern
|
|
72
|
+
* @param pattern - Pattern to match (supports wildcards: * and ?)
|
|
73
|
+
* @returns Array of matching keys
|
|
74
|
+
*/
|
|
75
|
+
keys(pattern?: string): Promise<string[]>
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Get cache statistics
|
|
79
|
+
* @returns Statistics object
|
|
80
|
+
*/
|
|
81
|
+
stats(): Promise<{
|
|
82
|
+
size: number // Total number of entries
|
|
83
|
+
expired: number // Number of expired entries
|
|
84
|
+
// Optional process-global counters surfaced by bounded strategies (memory)
|
|
85
|
+
// so operators can tell whether the LRU cap / sweep is actively protecting
|
|
86
|
+
// the process. Strategies that do not track them omit these fields.
|
|
87
|
+
evictions?: number // Entries dropped by LRU eviction since process start
|
|
88
|
+
sweeps?: number // Amortized expired-entry sweep passes run since process start
|
|
89
|
+
lastSweepReclaimed?: number // Entries reclaimed by the most recent sweep pass
|
|
90
|
+
}>
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Verify the configured backend is reachable without activating a fallback.
|
|
94
|
+
*/
|
|
95
|
+
healthcheck?(): Promise<void>
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Clean up expired entries (optional, some strategies may auto-cleanup)
|
|
99
|
+
* @returns Number of entries removed
|
|
100
|
+
*/
|
|
101
|
+
cleanup?(): Promise<number>
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Close/disconnect the cache strategy
|
|
105
|
+
*/
|
|
106
|
+
close?(): Promise<void>
|
|
107
|
+
}
|
package/src/patterns.ts
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
export function matchCacheKeyPattern(key: string, pattern: string): boolean {
|
|
2
|
+
let patternIndex = 0
|
|
3
|
+
let keyIndex = 0
|
|
4
|
+
let starIndex = -1
|
|
5
|
+
let keyRetryIndex = 0
|
|
6
|
+
|
|
7
|
+
while (keyIndex < key.length) {
|
|
8
|
+
const patternChar = pattern[patternIndex]
|
|
9
|
+
const keyChar = key[keyIndex]
|
|
10
|
+
|
|
11
|
+
if (patternChar === '*') {
|
|
12
|
+
starIndex = patternIndex
|
|
13
|
+
keyRetryIndex = keyIndex
|
|
14
|
+
patternIndex += 1
|
|
15
|
+
continue
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
if (patternChar === '?' || patternChar === keyChar) {
|
|
19
|
+
patternIndex += 1
|
|
20
|
+
keyIndex += 1
|
|
21
|
+
continue
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
if (starIndex !== -1) {
|
|
25
|
+
patternIndex = starIndex + 1
|
|
26
|
+
keyRetryIndex += 1
|
|
27
|
+
keyIndex = keyRetryIndex
|
|
28
|
+
continue
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
return false
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
while (pattern[patternIndex] === '*') {
|
|
35
|
+
patternIndex += 1
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
return patternIndex === pattern.length
|
|
39
|
+
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Redis URL resolution and wire-protocol constant shared by the cache packages so
|
|
3
|
+
* the stock Redis strategy does not depend on `@open-mercato/shared`, which
|
|
4
|
+
* `@open-mercato/cache` does not (and cannot, without a cycle) declare.
|
|
5
|
+
* `@open-mercato/shared/lib/redis/connection` re-exports these unchanged.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* RESP wire protocol version, mirroring ioredis' own `ProtocolVersion` union.
|
|
10
|
+
* Declared locally because ioredis is an optional peer of the packages that
|
|
11
|
+
* consume these options.
|
|
12
|
+
*/
|
|
13
|
+
export type RedisProtocolVersion = 2 | 3
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Wire protocol every Redis client in the monorepo negotiates.
|
|
17
|
+
*
|
|
18
|
+
* ioredis 6 switched its default from RESP2 to RESP3. RESP3 changes the reply
|
|
19
|
+
* shape of map-style commands and delivers pub/sub over push frames instead of
|
|
20
|
+
* ordinary replies, which neither BullMQ nor rate-limiter-flexible declare
|
|
21
|
+
* support for. Pinning the protocol keeps the client byte-compatible with the
|
|
22
|
+
* ioredis 5 behaviour the rest of the stack was built and tested against.
|
|
23
|
+
* Adopting RESP3 is a deliberate, separately testable change — not a side
|
|
24
|
+
* effect of a version bump.
|
|
25
|
+
*/
|
|
26
|
+
export const REDIS_WIRE_PROTOCOL: RedisProtocolVersion = 2
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Resolve a Redis URL from environment variables.
|
|
30
|
+
*
|
|
31
|
+
* Priority: <PREFIX>_REDIS_URL → REDIS_URL → null
|
|
32
|
+
*
|
|
33
|
+
* Returns null when no env var is set. Callers MUST NOT assume a
|
|
34
|
+
* localhost default — silently connecting to localhost masks missing
|
|
35
|
+
* configuration and stalls on platforms where nothing listens there
|
|
36
|
+
* (e.g., WSL2 without a local Redis).
|
|
37
|
+
*/
|
|
38
|
+
export function getRedisUrl(prefix?: string): string | null {
|
|
39
|
+
if (prefix) {
|
|
40
|
+
const prefixed = process.env[`${prefix}_REDIS_URL`]
|
|
41
|
+
if (prefixed) return prefixed
|
|
42
|
+
}
|
|
43
|
+
return process.env.REDIS_URL || null
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Like getRedisUrl, but throws a descriptive error when Redis is not
|
|
48
|
+
* configured. Use from code paths that require Redis (e.g. BullMQ
|
|
49
|
+
* async queue, Redis cache strategy, scheduler service).
|
|
50
|
+
*/
|
|
51
|
+
export function getRedisUrlOrThrow(prefix?: string): string {
|
|
52
|
+
const url = getRedisUrl(prefix)
|
|
53
|
+
if (url) return url
|
|
54
|
+
const which = prefix ? `${prefix}_REDIS_URL or REDIS_URL` : 'REDIS_URL'
|
|
55
|
+
throw new Error(
|
|
56
|
+
`Redis URL is not configured. Set ${which} in your environment to use a Redis-backed strategy.`
|
|
57
|
+
)
|
|
58
|
+
}
|
package/tsconfig.json
ADDED
package/watch.mjs
ADDED
package/README.md
DELETED