tricache 0.7.0 → 0.7.1
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/README.md +1428 -1428
- package/bin/tricache.js +8 -8
- package/dist/cache-service-5GATUYAK.js +7 -0
- package/dist/{cache-service-BblHuF3i.d.ts → cache-service-D8tIXmzb.d.ts} +23 -1
- package/dist/{chunk-3XQUQBOZ.js → chunk-EUGYR7KR.js} +87 -41
- package/dist/{chunk-PFB5FMEY.js → chunk-X5AXHPVD.js} +26 -15
- package/dist/cli.cjs +113 -56
- package/dist/cli.js +3 -3
- package/dist/drizzle/index.cjs +114 -57
- package/dist/drizzle/index.d.ts +1 -1
- package/dist/drizzle/index.js +1 -1
- package/dist/http/index.cjs +149 -64
- package/dist/http/index.d.ts +1 -1
- package/dist/http/index.js +38 -10
- package/dist/index.cjs +112 -55
- package/dist/index.d.ts +2 -2
- package/dist/index.js +2 -2
- package/dist/nestjs/index.cjs +112 -55
- package/dist/nestjs/index.d.ts +1 -1
- package/dist/nestjs/index.js +2 -2
- package/dist/next/index.cjs +143 -63
- package/dist/next/index.d.ts +10 -6
- package/dist/next/index.js +33 -10
- package/dist/prisma/index.cjs +2 -1
- package/dist/prisma/index.d.ts +1 -1
- package/dist/prisma/index.js +2 -1
- package/dist/serialize-worker.cjs +26 -15
- package/dist/serialize-worker.js +1 -1
- package/package.json +4 -2
- package/src/cache-service.ts +3294 -3226
- package/src/cli.ts +143 -143
- package/src/compression.ts +56 -63
- package/src/disk-tier.ts +821 -821
- package/src/encryption.ts +513 -493
- package/src/http/index.ts +265 -223
- package/src/next/cache-handler.ts +268 -244
- package/src/prisma/index.ts +154 -151
- package/src/smart-memory-cache.ts +1026 -1024
- package/src/types.ts +911 -902
- package/dist/cache-service-AJASH5FX.js +0 -7
package/src/cli.ts
CHANGED
|
@@ -1,143 +1,143 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* TriCache CLI — Developer & Troubleshooting Inspector
|
|
3
|
-
*
|
|
4
|
-
* Usage:
|
|
5
|
-
* npx tricache inspect [--redis redis://localhost:6379] [--namespace <ns>]
|
|
6
|
-
* npx tricache ping [--redis redis://localhost:6379]
|
|
7
|
-
* npx tricache clear [--redis redis://localhost:6379] [--namespace <ns>] [--prefix <prefix>]
|
|
8
|
-
*/
|
|
9
|
-
|
|
10
|
-
import { parseArgs } from 'node:util';
|
|
11
|
-
import { CacheService } from './cache-service.js';
|
|
12
|
-
|
|
13
|
-
export async function runCli(args: string[] = process.argv.slice(2)): Promise<void> {
|
|
14
|
-
const options = {
|
|
15
|
-
redis: { type: 'string' as const, short: 'r' },
|
|
16
|
-
port: { type: 'string' as const, short: 'p' },
|
|
17
|
-
namespace: { type: 'string' as const, short: 'n' },
|
|
18
|
-
prefix: { type: 'string' as const },
|
|
19
|
-
disk: { type: 'string' as const, short: 'd' },
|
|
20
|
-
help: { type: 'boolean' as const, short: 'h' },
|
|
21
|
-
version: { type: 'boolean' as const, short: 'v' },
|
|
22
|
-
};
|
|
23
|
-
|
|
24
|
-
let parsed;
|
|
25
|
-
try {
|
|
26
|
-
parsed = parseArgs({
|
|
27
|
-
args,
|
|
28
|
-
options,
|
|
29
|
-
allowPositionals: true,
|
|
30
|
-
strict: false,
|
|
31
|
-
});
|
|
32
|
-
} catch (err) {
|
|
33
|
-
console.error(`Error: ${(err as Error).message}\n`);
|
|
34
|
-
printHelp();
|
|
35
|
-
process.exit(1);
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
const { values, positionals } = parsed;
|
|
39
|
-
const command = positionals[0] || 'inspect';
|
|
40
|
-
|
|
41
|
-
if (values.help || command === 'help') {
|
|
42
|
-
printHelp();
|
|
43
|
-
return;
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
if (values.version || command === 'version') {
|
|
47
|
-
console.log('tricache v0.7.
|
|
48
|
-
return;
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
const redisStr = typeof values.redis === 'string' ? values.redis : undefined;
|
|
52
|
-
const redisHost = redisStr ? redisStr.replace(/^redis:\/\//, '').split(':')[0] : undefined;
|
|
53
|
-
const redisPort = typeof values.port === 'string'
|
|
54
|
-
? parseInt(values.port, 10)
|
|
55
|
-
: (redisStr && redisStr.includes(':') ? parseInt(redisStr.split(':')[1], 10) : 6379);
|
|
56
|
-
const namespace = typeof values.namespace === 'string' ? values.namespace : undefined;
|
|
57
|
-
const diskCacheDir = typeof values.disk === 'string' ? values.disk : undefined;
|
|
58
|
-
|
|
59
|
-
const cache = new CacheService({
|
|
60
|
-
redisHost,
|
|
61
|
-
redisPort,
|
|
62
|
-
namespace,
|
|
63
|
-
diskCacheDir,
|
|
64
|
-
disableRedis: !redisHost,
|
|
65
|
-
});
|
|
66
|
-
|
|
67
|
-
try {
|
|
68
|
-
if (command === 'inspect') {
|
|
69
|
-
const ping = await cache.ping();
|
|
70
|
-
const metrics = cache.metrics();
|
|
71
|
-
const stats = cache.stats();
|
|
72
|
-
const hot = cache.hotKeys(5);
|
|
73
|
-
|
|
74
|
-
const divPct = (n: number) => `${(n * 100).toFixed(1)}%`;
|
|
75
|
-
const l1MaxKB = Math.round((cache.options.l1MaxBytes ?? 200 * 1024 * 1024) / 1024);
|
|
76
|
-
|
|
77
|
-
console.log(`
|
|
78
|
-
┌──────────────────────────────────────────────────────────────┐
|
|
79
|
-
│ TriCache Engine Dashboard (Namespace: ${namespace || '(default)'})
|
|
80
|
-
├──────────────────────────────────────────────────────────────┤
|
|
81
|
-
│ Tiers Active: L1 (RAM) → L1.5 (NVMe Disk) → L2 (${redisHost ? 'Redis' : 'Disabled'})
|
|
82
|
-
│ Latencies: L1: ${ping.l1}ms | Disk: ${ping.disk}ms | L2: ${ping.l2 !== null ? `${ping.l2}ms` : 'N/A'}
|
|
83
|
-
│ L1 Entries: ${stats.l1.entries} (${stats.l1.sizeKB} KB / ${l1MaxKB} KB)
|
|
84
|
-
│ Disk Files: ${stats.disk.files} (${stats.disk.sizeKB} KB / ${stats.disk.maxKB} KB)
|
|
85
|
-
├──────────────────────────────────────────────────────────────┤
|
|
86
|
-
│ L1 Hit Ratio: ${divPct(metrics.gets.l1HitRate)} (${metrics.gets.l1Hits} hits)
|
|
87
|
-
│ L2 Hit Ratio: ${divPct(metrics.gets.l2HitRate)} (${metrics.gets.l2Hits} hits)
|
|
88
|
-
│ Disk Hit Ratio: ${divPct(metrics.gets.diskHitRate)} (${metrics.gets.diskHits} hits)
|
|
89
|
-
│ Stampedes Saved: ${metrics.gets.stampedePrevented} coalesced requests
|
|
90
|
-
├──────────────────────────────────────────────────────────────┤
|
|
91
|
-
│ 🔥 Top Hot Keys (Count-Min Sketch):`);
|
|
92
|
-
|
|
93
|
-
if (hot.length === 0) {
|
|
94
|
-
console.log('│ (no hot keys recorded yet)');
|
|
95
|
-
} else {
|
|
96
|
-
hot.forEach(({ key, hits, sizeBytes }, idx) => {
|
|
97
|
-
const size = sizeBytes > 1024 ? `${(sizeBytes / 1024).toFixed(1)} KB` : `${sizeBytes} B`;
|
|
98
|
-
console.log(`│ ${idx + 1}. ${key.padEnd(24)} (${hits} hits, ${size})`);
|
|
99
|
-
});
|
|
100
|
-
}
|
|
101
|
-
console.log('└──────────────────────────────────────────────────────────────┘\n');
|
|
102
|
-
} else if (command === 'ping') {
|
|
103
|
-
const ping = await cache.ping();
|
|
104
|
-
console.log(`TriCache Ping Results:`);
|
|
105
|
-
console.log(` • L1 RAM: ${ping.l1}ms`);
|
|
106
|
-
console.log(` • Disk: ${ping.disk}ms`);
|
|
107
|
-
console.log(` • L2 Redis:${ping.l2 !== null ? ` ${ping.l2}ms` : ' Disabled'}`);
|
|
108
|
-
} else if (command === 'clear') {
|
|
109
|
-
const prefix = typeof values.prefix === 'string' ? values.prefix : undefined;
|
|
110
|
-
await cache.clear(prefix);
|
|
111
|
-
console.log(`Cleared cache${prefix ? ` for prefix "${prefix}"` : ' (all entries)'} in namespace "${namespace || '(default)'}".`);
|
|
112
|
-
} else {
|
|
113
|
-
console.error(`Unknown command: ${command}\n`);
|
|
114
|
-
printHelp();
|
|
115
|
-
process.exit(1);
|
|
116
|
-
}
|
|
117
|
-
} finally {
|
|
118
|
-
await cache.destroy();
|
|
119
|
-
}
|
|
120
|
-
}
|
|
121
|
-
|
|
122
|
-
function printHelp(): void {
|
|
123
|
-
console.log(`
|
|
124
|
-
TriCache CLI — Developer & Troubleshooting Tool
|
|
125
|
-
|
|
126
|
-
Usage:
|
|
127
|
-
tricache <command> [options]
|
|
128
|
-
|
|
129
|
-
Commands:
|
|
130
|
-
inspect Display full dashboard including hit ratios, latencies, and hot keys (default)
|
|
131
|
-
ping Measure response latency across L1 (RAM), L1.5 (Disk), and L2 (Redis)
|
|
132
|
-
clear Flush all entries or keys matching a prefix
|
|
133
|
-
|
|
134
|
-
Options:
|
|
135
|
-
-r, --redis <host|url> Redis connection host or URL (e.g. localhost, redis://127.0.0.1:6379)
|
|
136
|
-
-p, --port <port> Redis port (default: 6379)
|
|
137
|
-
-n, --namespace <ns> Cache namespace
|
|
138
|
-
--prefix <prefix> Key prefix filter for clear command
|
|
139
|
-
-d, --disk <path> Custom disk cache directory path
|
|
140
|
-
-h, --help Show this help message
|
|
141
|
-
-v, --version Display version number
|
|
142
|
-
`);
|
|
143
|
-
}
|
|
1
|
+
/**
|
|
2
|
+
* TriCache CLI — Developer & Troubleshooting Inspector
|
|
3
|
+
*
|
|
4
|
+
* Usage:
|
|
5
|
+
* npx tricache inspect [--redis redis://localhost:6379] [--namespace <ns>]
|
|
6
|
+
* npx tricache ping [--redis redis://localhost:6379]
|
|
7
|
+
* npx tricache clear [--redis redis://localhost:6379] [--namespace <ns>] [--prefix <prefix>]
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { parseArgs } from 'node:util';
|
|
11
|
+
import { CacheService } from './cache-service.js';
|
|
12
|
+
|
|
13
|
+
export async function runCli(args: string[] = process.argv.slice(2)): Promise<void> {
|
|
14
|
+
const options = {
|
|
15
|
+
redis: { type: 'string' as const, short: 'r' },
|
|
16
|
+
port: { type: 'string' as const, short: 'p' },
|
|
17
|
+
namespace: { type: 'string' as const, short: 'n' },
|
|
18
|
+
prefix: { type: 'string' as const },
|
|
19
|
+
disk: { type: 'string' as const, short: 'd' },
|
|
20
|
+
help: { type: 'boolean' as const, short: 'h' },
|
|
21
|
+
version: { type: 'boolean' as const, short: 'v' },
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
let parsed;
|
|
25
|
+
try {
|
|
26
|
+
parsed = parseArgs({
|
|
27
|
+
args,
|
|
28
|
+
options,
|
|
29
|
+
allowPositionals: true,
|
|
30
|
+
strict: false,
|
|
31
|
+
});
|
|
32
|
+
} catch (err) {
|
|
33
|
+
console.error(`Error: ${(err as Error).message}\n`);
|
|
34
|
+
printHelp();
|
|
35
|
+
process.exit(1);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const { values, positionals } = parsed;
|
|
39
|
+
const command = positionals[0] || 'inspect';
|
|
40
|
+
|
|
41
|
+
if (values.help || command === 'help') {
|
|
42
|
+
printHelp();
|
|
43
|
+
return;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
if (values.version || command === 'version') {
|
|
47
|
+
console.log('tricache v0.7.1');
|
|
48
|
+
return;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
const redisStr = typeof values.redis === 'string' ? values.redis : undefined;
|
|
52
|
+
const redisHost = redisStr ? redisStr.replace(/^redis:\/\//, '').split(':')[0] : undefined;
|
|
53
|
+
const redisPort = typeof values.port === 'string'
|
|
54
|
+
? parseInt(values.port, 10)
|
|
55
|
+
: (redisStr && redisStr.includes(':') ? parseInt(redisStr.split(':')[1], 10) : 6379);
|
|
56
|
+
const namespace = typeof values.namespace === 'string' ? values.namespace : undefined;
|
|
57
|
+
const diskCacheDir = typeof values.disk === 'string' ? values.disk : undefined;
|
|
58
|
+
|
|
59
|
+
const cache = new CacheService({
|
|
60
|
+
redisHost,
|
|
61
|
+
redisPort,
|
|
62
|
+
namespace,
|
|
63
|
+
diskCacheDir,
|
|
64
|
+
disableRedis: !redisHost,
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
try {
|
|
68
|
+
if (command === 'inspect') {
|
|
69
|
+
const ping = await cache.ping();
|
|
70
|
+
const metrics = cache.metrics();
|
|
71
|
+
const stats = cache.stats();
|
|
72
|
+
const hot = cache.hotKeys(5);
|
|
73
|
+
|
|
74
|
+
const divPct = (n: number) => `${(n * 100).toFixed(1)}%`;
|
|
75
|
+
const l1MaxKB = Math.round((cache.options.l1MaxBytes ?? 200 * 1024 * 1024) / 1024);
|
|
76
|
+
|
|
77
|
+
console.log(`
|
|
78
|
+
┌──────────────────────────────────────────────────────────────┐
|
|
79
|
+
│ TriCache Engine Dashboard (Namespace: ${namespace || '(default)'})
|
|
80
|
+
├──────────────────────────────────────────────────────────────┤
|
|
81
|
+
│ Tiers Active: L1 (RAM) → L1.5 (NVMe Disk) → L2 (${redisHost ? 'Redis' : 'Disabled'})
|
|
82
|
+
│ Latencies: L1: ${ping.l1}ms | Disk: ${ping.disk}ms | L2: ${ping.l2 !== null ? `${ping.l2}ms` : 'N/A'}
|
|
83
|
+
│ L1 Entries: ${stats.l1.entries} (${stats.l1.sizeKB} KB / ${l1MaxKB} KB)
|
|
84
|
+
│ Disk Files: ${stats.disk.files} (${stats.disk.sizeKB} KB / ${stats.disk.maxKB} KB)
|
|
85
|
+
├──────────────────────────────────────────────────────────────┤
|
|
86
|
+
│ L1 Hit Ratio: ${divPct(metrics.gets.l1HitRate)} (${metrics.gets.l1Hits} hits)
|
|
87
|
+
│ L2 Hit Ratio: ${divPct(metrics.gets.l2HitRate)} (${metrics.gets.l2Hits} hits)
|
|
88
|
+
│ Disk Hit Ratio: ${divPct(metrics.gets.diskHitRate)} (${metrics.gets.diskHits} hits)
|
|
89
|
+
│ Stampedes Saved: ${metrics.gets.stampedePrevented} coalesced requests
|
|
90
|
+
├──────────────────────────────────────────────────────────────┤
|
|
91
|
+
│ 🔥 Top Hot Keys (Count-Min Sketch):`);
|
|
92
|
+
|
|
93
|
+
if (hot.length === 0) {
|
|
94
|
+
console.log('│ (no hot keys recorded yet)');
|
|
95
|
+
} else {
|
|
96
|
+
hot.forEach(({ key, hits, sizeBytes }, idx) => {
|
|
97
|
+
const size = sizeBytes > 1024 ? `${(sizeBytes / 1024).toFixed(1)} KB` : `${sizeBytes} B`;
|
|
98
|
+
console.log(`│ ${idx + 1}. ${key.padEnd(24)} (${hits} hits, ${size})`);
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
console.log('└──────────────────────────────────────────────────────────────┘\n');
|
|
102
|
+
} else if (command === 'ping') {
|
|
103
|
+
const ping = await cache.ping();
|
|
104
|
+
console.log(`TriCache Ping Results:`);
|
|
105
|
+
console.log(` • L1 RAM: ${ping.l1}ms`);
|
|
106
|
+
console.log(` • Disk: ${ping.disk}ms`);
|
|
107
|
+
console.log(` • L2 Redis:${ping.l2 !== null ? ` ${ping.l2}ms` : ' Disabled'}`);
|
|
108
|
+
} else if (command === 'clear') {
|
|
109
|
+
const prefix = typeof values.prefix === 'string' ? values.prefix : undefined;
|
|
110
|
+
await cache.clear(prefix);
|
|
111
|
+
console.log(`Cleared cache${prefix ? ` for prefix "${prefix}"` : ' (all entries)'} in namespace "${namespace || '(default)'}".`);
|
|
112
|
+
} else {
|
|
113
|
+
console.error(`Unknown command: ${command}\n`);
|
|
114
|
+
printHelp();
|
|
115
|
+
process.exit(1);
|
|
116
|
+
}
|
|
117
|
+
} finally {
|
|
118
|
+
await cache.destroy();
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function printHelp(): void {
|
|
123
|
+
console.log(`
|
|
124
|
+
TriCache CLI — Developer & Troubleshooting Tool
|
|
125
|
+
|
|
126
|
+
Usage:
|
|
127
|
+
tricache <command> [options]
|
|
128
|
+
|
|
129
|
+
Commands:
|
|
130
|
+
inspect Display full dashboard including hit ratios, latencies, and hot keys (default)
|
|
131
|
+
ping Measure response latency across L1 (RAM), L1.5 (Disk), and L2 (Redis)
|
|
132
|
+
clear Flush all entries or keys matching a prefix
|
|
133
|
+
|
|
134
|
+
Options:
|
|
135
|
+
-r, --redis <host|url> Redis connection host or URL (e.g. localhost, redis://127.0.0.1:6379)
|
|
136
|
+
-p, --port <port> Redis port (default: 6379)
|
|
137
|
+
-n, --namespace <ns> Cache namespace
|
|
138
|
+
--prefix <prefix> Key prefix filter for clear command
|
|
139
|
+
-d, --disk <path> Custom disk cache directory path
|
|
140
|
+
-h, --help Show this help message
|
|
141
|
+
-v, --version Display version number
|
|
142
|
+
`);
|
|
143
|
+
}
|
package/src/compression.ts
CHANGED
|
@@ -1,63 +1,56 @@
|
|
|
1
|
-
import zlib from 'zlib';
|
|
2
|
-
|
|
3
|
-
export type CompressionAlgorithm = 'brotli' | 'gzip' | 'none';
|
|
4
|
-
|
|
5
|
-
export const PREFIX_COMPRESSED = 'cmp:v1:';
|
|
6
|
-
export const PREFIX_ENC_COMPRESSED = 'ecp:v1:';
|
|
7
|
-
|
|
8
|
-
/** "TRC\x01" 4-byte marker prefix identifying compressed data */
|
|
9
|
-
const COMPRESSION_MAGIC = Buffer.from([0x54, 0x52, 0x43, 0x01]);
|
|
10
|
-
|
|
11
|
-
export function isCompressed(buf: Buffer): boolean {
|
|
12
|
-
return buf.length >= 4 && buf[0] === 0x54 && buf[1] === 0x52 && buf[2] === 0x43 && buf[3] === 0x01;
|
|
13
|
-
}
|
|
14
|
-
|
|
15
|
-
export function compressBuffer(buf: Buffer, algorithm: CompressionAlgorithm): Buffer {
|
|
16
|
-
if (algorithm === 'brotli') {
|
|
17
|
-
return zlib.brotliCompressSync(buf, {
|
|
18
|
-
params: {
|
|
19
|
-
[zlib.constants.BROTLI_PARAM_QUALITY]: 4, // Fast level 4 compression
|
|
20
|
-
},
|
|
21
|
-
});
|
|
22
|
-
}
|
|
23
|
-
if (algorithm === 'gzip') {
|
|
24
|
-
return zlib.gzipSync(buf, { level: 6 });
|
|
25
|
-
}
|
|
26
|
-
return buf;
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
export function decompressBuffer(buf: Buffer, algorithm: CompressionAlgorithm = 'brotli'): Buffer {
|
|
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
|
-
return
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
export function decompressWithHeader(buf: Buffer, algorithm: CompressionAlgorithm = 'brotli'): Buffer {
|
|
59
|
-
if (isCompressed(buf)) {
|
|
60
|
-
return decompressBuffer(buf.subarray(4), algorithm);
|
|
61
|
-
}
|
|
62
|
-
return buf;
|
|
63
|
-
}
|
|
1
|
+
import zlib from 'zlib';
|
|
2
|
+
|
|
3
|
+
export type CompressionAlgorithm = 'brotli' | 'gzip' | 'none';
|
|
4
|
+
|
|
5
|
+
export const PREFIX_COMPRESSED = 'cmp:v1:';
|
|
6
|
+
export const PREFIX_ENC_COMPRESSED = 'ecp:v1:';
|
|
7
|
+
|
|
8
|
+
/** "TRC\x01" 4-byte marker prefix identifying compressed data */
|
|
9
|
+
const COMPRESSION_MAGIC = Buffer.from([0x54, 0x52, 0x43, 0x01]);
|
|
10
|
+
|
|
11
|
+
export function isCompressed(buf: Buffer): boolean {
|
|
12
|
+
return buf.length >= 4 && buf[0] === 0x54 && buf[1] === 0x52 && buf[2] === 0x43 && buf[3] === 0x01;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export function compressBuffer(buf: Buffer, algorithm: CompressionAlgorithm): Buffer {
|
|
16
|
+
if (algorithm === 'brotli') {
|
|
17
|
+
return zlib.brotliCompressSync(buf, {
|
|
18
|
+
params: {
|
|
19
|
+
[zlib.constants.BROTLI_PARAM_QUALITY]: 4, // Fast level 4 compression
|
|
20
|
+
},
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
if (algorithm === 'gzip') {
|
|
24
|
+
return zlib.gzipSync(buf, { level: 6 });
|
|
25
|
+
}
|
|
26
|
+
return buf;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function decompressBuffer(buf: Buffer, algorithm: CompressionAlgorithm = 'brotli'): Buffer {
|
|
30
|
+
// Try the configured algorithm first, then the other one as recovery (covers
|
|
31
|
+
// entries written under a different compression setting). If BOTH fail, the
|
|
32
|
+
// payload is corrupt: THROW instead of returning the raw bytes. Returning raw
|
|
33
|
+
// surfaced corruption as garbage JSON.parse errors deep downstream; every
|
|
34
|
+
// call site maps a thrown error to a clean cache miss instead.
|
|
35
|
+
const tryBrotli = (): Buffer | null => { try { return zlib.brotliDecompressSync(buf); } catch { return null; } };
|
|
36
|
+
const tryGzip = (): Buffer | null => { try { return zlib.gunzipSync(buf); } catch { return null; } };
|
|
37
|
+
|
|
38
|
+
const result = algorithm === 'gzip' ? (tryGzip() ?? tryBrotli()) : (tryBrotli() ?? tryGzip());
|
|
39
|
+
if (result === null) {
|
|
40
|
+
throw new Error(`tricache: corrupt compressed payload (${buf.length} bytes, algorithm=${algorithm})`);
|
|
41
|
+
}
|
|
42
|
+
return result;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export function compressWithHeader(buf: Buffer, algorithm: CompressionAlgorithm): Buffer {
|
|
46
|
+
if (algorithm === 'none') return buf;
|
|
47
|
+
const compressed = compressBuffer(buf, algorithm);
|
|
48
|
+
return Buffer.concat([COMPRESSION_MAGIC, compressed]);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export function decompressWithHeader(buf: Buffer, algorithm: CompressionAlgorithm = 'brotli'): Buffer {
|
|
52
|
+
if (isCompressed(buf)) {
|
|
53
|
+
return decompressBuffer(buf.subarray(4), algorithm);
|
|
54
|
+
}
|
|
55
|
+
return buf;
|
|
56
|
+
}
|