@open-mercato/cache 0.9.1-develop.7575.1.8480826a9b → 0.10.0

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.
@@ -46,16 +46,22 @@ describe('Cache Service', () => {
46
46
  })
47
47
 
48
48
  it('should respect defaultTtl option', async () => {
49
+ const initialTime = 1_000_000
50
+ const now = jest.spyOn(Date, 'now').mockReturnValue(initialTime)
49
51
  const cache = createCacheService({
50
52
  strategy: 'memory',
51
53
  defaultTtl: 100
52
54
  })
53
-
54
- await cache.set('test', 'value') // Should use default TTL
55
- expect(await cache.get('test')).toBe('value')
56
-
57
- await new Promise((resolve) => setTimeout(resolve, 150))
58
- expect(await cache.get('test')).toBeNull()
55
+
56
+ try {
57
+ await cache.set('test', 'value') // Should use default TTL
58
+ expect(await cache.get('test')).toBe('value')
59
+
60
+ now.mockReturnValue(initialTime + 101)
61
+ expect(await cache.get('test')).toBeNull()
62
+ } finally {
63
+ now.mockRestore()
64
+ }
59
65
  })
60
66
 
61
67
  it('should keep file-backed cache defaults under .mercato', async () => {
@@ -392,3 +398,57 @@ describe('Cache Service stats() counter gating', () => {
392
398
  expect(stats.lastSweepReclaimed).toBe(3)
393
399
  })
394
400
  })
401
+
402
+ describe('Cache Service compression resolution (CACHE_COMPRESSION)', () => {
403
+ afterEach(() => {
404
+ delete process.env.CACHE_COMPRESSION
405
+ delete process.env.CACHE_COMPRESSION_MIN_BYTES
406
+ jest.restoreAllMocks()
407
+ })
408
+
409
+ const captureSqliteOptions = () => {
410
+ const spy = jest.spyOn(sqliteStrategyModule, 'createSqliteStrategy')
411
+ spy.mockImplementation((_path, options) => {
412
+ return memoryStrategyModule.createMemoryStrategy({ defaultTtl: options?.defaultTtl })
413
+ })
414
+ return spy
415
+ }
416
+
417
+ it('passes the env compression settings to persistent strategies', () => {
418
+ process.env.CACHE_COMPRESSION = 'zstd'
419
+ process.env.CACHE_COMPRESSION_MIN_BYTES = '2048'
420
+ const spy = captureSqliteOptions()
421
+
422
+ createCacheService({ strategy: 'sqlite' })
423
+
424
+ expect(spy.mock.calls[0][1]).toMatchObject({ compression: 'zstd', compressionMinBytes: 2048 })
425
+ })
426
+
427
+ it('lets explicit options override the env', () => {
428
+ process.env.CACHE_COMPRESSION = 'zstd'
429
+ const spy = captureSqliteOptions()
430
+
431
+ createCacheService({ strategy: 'sqlite', compression: 'gzip', compressionMinBytes: 512 })
432
+
433
+ expect(spy.mock.calls[0][1]).toMatchObject({ compression: 'gzip', compressionMinBytes: 512 })
434
+ })
435
+
436
+ it('keeps compression off for an unknown env value and warns', () => {
437
+ process.env.CACHE_COMPRESSION = 'lz4-service-test'
438
+ const warn = jest.spyOn(console, 'warn').mockImplementation(() => {})
439
+ const spy = captureSqliteOptions()
440
+
441
+ createCacheService({ strategy: 'sqlite' })
442
+
443
+ expect(spy.mock.calls[0][1]).toMatchObject({ compression: 'off' })
444
+ expect(warn).toHaveBeenCalledWith(expect.stringContaining('lz4-service-test'))
445
+ })
446
+
447
+ it('defaults to off with no env and no options', () => {
448
+ const spy = captureSqliteOptions()
449
+
450
+ createCacheService({ strategy: 'sqlite' })
451
+
452
+ expect(spy.mock.calls[0][1]).toMatchObject({ compression: 'off', compressionMinBytes: undefined })
453
+ })
454
+ })
@@ -3,7 +3,7 @@ import os from 'node:os'
3
3
  import path from 'node:path'
4
4
  import { createSqliteStrategy } from '../strategies/sqlite'
5
5
 
6
- type CacheEntry = { value: string; expires_at: number | null; created_at: number }
6
+ type CacheEntry = { value: string | Buffer; expires_at: number | null; created_at: number }
7
7
 
8
8
  class MockSqliteDatabase {
9
9
  static instances: MockSqliteDatabase[] = []
@@ -90,7 +90,7 @@ class MockSqliteDatabase {
90
90
  if (sql.startsWith('INSERT OR REPLACE INTO cache_entries')) {
91
91
  const [key, value, expiresAt, createdAt] = args
92
92
  this.entries.set(String(key), {
93
- value: String(value),
93
+ value: Buffer.isBuffer(value) ? value : String(value),
94
94
  expires_at: expiresAt === null ? null : Number(expiresAt),
95
95
  created_at: Number(createdAt),
96
96
  })
@@ -161,3 +161,54 @@ describe('SQLite Cache Strategy', () => {
161
161
  await cache.close?.()
162
162
  })
163
163
  })
164
+
165
+ describe('SQLite Cache Strategy value compression (better-sqlite3)', () => {
166
+ const largeValue = {
167
+ items: Array.from({ length: 100 }, (_, index) => ({ id: `row-${index}`, name: `Contact ${index}`, status: 'active' })),
168
+ }
169
+ let tempDir: string
170
+ let dbPath: string
171
+
172
+ beforeEach(() => {
173
+ tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'open-mercato-cache-compression-'))
174
+ dbPath = path.join(tempDir, 'cache.db')
175
+ })
176
+
177
+ afterEach(() => {
178
+ fs.rmSync(tempDir, { recursive: true, force: true })
179
+ })
180
+
181
+ function storedTypes(): Record<string, string> {
182
+ const Database = require('better-sqlite3') as typeof import('better-sqlite3')
183
+ const db = new Database(dbPath, { readonly: true })
184
+ try {
185
+ const rows = db.prepare('SELECT key, typeof(value) AS type FROM cache_entries').all() as { key: string; type: string }[]
186
+ return Object.fromEntries(rows.map((row) => [row.key, row.type]))
187
+ } finally {
188
+ db.close()
189
+ }
190
+ }
191
+
192
+ it.each(['zstd', 'gzip'] as const)('stores large %s entries as BLOBs next to legacy TEXT rows', async (compression) => {
193
+ const legacy = createSqliteStrategy(dbPath, { compression: 'off' })
194
+ await legacy.set('legacy', largeValue, { tags: ['customers'] })
195
+ await legacy.close?.()
196
+
197
+ const cache = createSqliteStrategy(dbPath, { compression })
198
+ await cache.set('compressed', largeValue, { tags: ['customers'] })
199
+ await cache.set('small', { id: 1 }, { tags: ['customers'] })
200
+
201
+ expect(await cache.get('legacy')).toEqual(largeValue)
202
+ expect(await cache.get('compressed')).toEqual(largeValue)
203
+ expect(await cache.get('small')).toEqual({ id: 1 })
204
+ await cache.close?.()
205
+
206
+ expect(storedTypes()).toEqual({ legacy: 'text', compressed: 'blob', small: 'text' })
207
+
208
+ const off = createSqliteStrategy(dbPath, { compression: 'off' })
209
+ expect(await off.get('compressed')).toEqual(largeValue)
210
+ expect(await off.deleteByTags(['customers'])).toBe(3)
211
+ expect(await off.get('compressed')).toBeNull()
212
+ await off.close?.()
213
+ })
214
+ })
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/service.ts CHANGED
@@ -7,6 +7,8 @@ import { getCurrentCacheTenant } from './tenantContext'
7
7
  import { createHash } from 'node:crypto'
8
8
  import { CacheDependencyUnavailableError } from './errors'
9
9
  import { matchCacheKeyPattern } from './patterns'
10
+ import { parseCacheCompression, parseCacheCompressionMinBytes } from './codec'
11
+ import type { CacheCodecOptions } from './codec'
10
12
 
11
13
  function normalizeTenantKey(raw: string | null | undefined): string {
12
14
  const value = typeof raw === 'string' ? raw.trim() : ''
@@ -260,7 +262,12 @@ function createConfiguredTenantAwareStrategy(options?: CacheServiceOptions): Ten
260
262
  const parsedEnvMaxEntries = envMaxEntries ? Number.parseInt(envMaxEntries, 10) : undefined
261
263
  const maxEntries = options?.maxEntries ?? (typeof parsedEnvMaxEntries === 'number' && Number.isFinite(parsedEnvMaxEntries) ? parsedEnvMaxEntries : undefined)
262
264
 
263
- const baseStrategy = createStrategyForType(strategyType, options, defaultTtl, maxEntries)
265
+ const codecOptions: CacheCodecOptions = {
266
+ compression: options?.compression ?? parseCacheCompression(process.env.CACHE_COMPRESSION),
267
+ compressionMinBytes: options?.compressionMinBytes ?? parseCacheCompressionMinBytes(process.env.CACHE_COMPRESSION_MIN_BYTES),
268
+ }
269
+
270
+ const baseStrategy = createStrategyForType(strategyType, options, defaultTtl, maxEntries, codecOptions)
264
271
  const resilientStrategy = withDependencyFallback(baseStrategy, strategyType, defaultTtl, maxEntries)
265
272
  const reportsBoundedCounters = strategyType === 'memory'
266
273
 
@@ -276,6 +283,8 @@ function createConfiguredTenantAwareStrategy(options?: CacheServiceOptions): Ten
276
283
  * - CACHE_REDIS_URL: Redis connection URL (for redis strategy)
277
284
  * - CACHE_SQLITE_PATH: SQLite database file path (for sqlite strategy)
278
285
  * - CACHE_JSON_FILE_PATH: JSON file path (for jsonfile strategy)
286
+ * - CACHE_COMPRESSION: 'off' | 'zstd' | 'gzip' value compression for redis/sqlite (default: 'off')
287
+ * - CACHE_COMPRESSION_MIN_BYTES: smallest serialized entry that gets compressed (default: 1024)
279
288
  *
280
289
  * @example
281
290
  * const cache = createCacheService({ strategy: 'memory', defaultTtl: 60000 })
@@ -373,12 +382,12 @@ export class CacheService implements CacheStrategy {
373
382
  }
374
383
  }
375
384
 
376
- function createStrategyForType(strategyType: CacheStrategyName, options?: CacheServiceOptions, defaultTtl?: number, maxEntries?: number): CacheStrategy {
385
+ function createStrategyForType(strategyType: CacheStrategyName, options?: CacheServiceOptions, defaultTtl?: number, maxEntries?: number, codecOptions?: CacheCodecOptions): CacheStrategy {
377
386
  switch (strategyType) {
378
387
  case 'redis':
379
- return createRedisStrategy(options?.redisUrl, { defaultTtl })
388
+ return createRedisStrategy(options?.redisUrl, { defaultTtl, ...codecOptions })
380
389
  case 'sqlite':
381
- return createSqliteStrategy(options?.sqlitePath, { defaultTtl })
390
+ return createSqliteStrategy(options?.sqlitePath, { defaultTtl, ...codecOptions })
382
391
  case 'jsonfile':
383
392
  return createJsonFileStrategy(options?.jsonFilePath, { defaultTtl })
384
393
  case 'memory':