tricache 0.8.0 → 1.0.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.
Files changed (56) hide show
  1. package/README.md +10 -4
  2. package/dashboards/prometheus-scrape.yml +18 -0
  3. package/dist/{cache-service-5MZXFIGK.js → cache-service-26GCO3UU.js} +3 -3
  4. package/dist/{cache-service-CyLdpo77.d.ts → cache-service-pJ-nFcVj.d.ts} +44 -12
  5. package/dist/{chunk-XZL45ABR.js → chunk-2AJKEQMZ.js} +54 -1
  6. package/dist/{chunk-6PQ5MOWR.js → chunk-7SZSQS55.js} +571 -115
  7. package/dist/chunk-BQRURGGD.js +60 -0
  8. package/dist/chunk-IITRFWHY.js +196 -0
  9. package/dist/{chunk-LJ5QJB5O.js → chunk-UBWLPKTI.js} +127 -11
  10. package/dist/cli.cjs +767 -133
  11. package/dist/cli.js +24 -6
  12. package/dist/dashboard/index.d.ts +2 -2
  13. package/dist/drizzle/index.cjs +734 -132
  14. package/dist/drizzle/index.d.ts +2 -2
  15. package/dist/drizzle/index.js +1 -1
  16. package/dist/edge/index.cjs +163 -46
  17. package/dist/edge/index.d.ts +3 -3
  18. package/dist/edge/index.js +42 -14
  19. package/dist/hono/index.cjs +8093 -0
  20. package/dist/hono/index.d.ts +91 -0
  21. package/dist/hono/index.js +185 -0
  22. package/dist/{hono-DQRS1Xd7.d.ts → hono-DuNvciyq.d.ts} +6 -5
  23. package/dist/http/index.cjs +833 -170
  24. package/dist/http/index.d.ts +6 -30
  25. package/dist/http/index.js +9 -59
  26. package/dist/index.cjs +755 -130
  27. package/dist/index.d.ts +35 -6
  28. package/dist/index.js +16 -6
  29. package/dist/nestjs/index.cjs +725 -130
  30. package/dist/nestjs/index.d.ts +2 -2
  31. package/dist/nestjs/index.js +4 -4
  32. package/dist/next/index.cjs +725 -130
  33. package/dist/next/index.d.ts +2 -2
  34. package/dist/next/index.js +3 -3
  35. package/dist/prisma/index.d.ts +2 -2
  36. package/dist/serialize-worker.cjs +127 -9
  37. package/dist/serialize-worker.js +8 -4
  38. package/dist/{types-B6krw64X.d.ts → types-5HXqBfAf.d.ts} +74 -7
  39. package/dist/utils-CEsU_Z0s.d.ts +27 -0
  40. package/package.json +22 -9
  41. package/src/cache-service.ts +540 -68
  42. package/src/cli.ts +21 -4
  43. package/src/compression.ts +193 -15
  44. package/src/cross-region.ts +1 -1
  45. package/src/edge/cache.ts +38 -11
  46. package/src/edge/hono.ts +123 -42
  47. package/src/env.d.ts +13 -0
  48. package/src/hono/index.ts +316 -0
  49. package/src/http/index.ts +5 -0
  50. package/src/index.ts +9 -1
  51. package/src/ipc-telemetry.ts +29 -1
  52. package/src/serialize-worker.ts +6 -2
  53. package/src/types.ts +68 -5
  54. package/src/utils/tag-matcher.ts +90 -0
  55. package/dist/chunk-ZTSWCFYO.js +0 -135
  56. /package/dist/{chunk-QNU7B43J.js → chunk-VXFTFZ5N.js} +0 -0
@@ -0,0 +1,316 @@
1
+ /**
2
+ * tricache/hono — first-class Node.js Hono middleware on CacheService.
3
+ *
4
+ * This is the Node three-tier path (L1 RAM → L1.5 disk → L2 Redis), not the
5
+ * Web-Crypto edge helper exported from `tricache/edge` / `tricache/http`.
6
+ *
7
+ * Usage:
8
+ * import { Hono } from 'hono';
9
+ * import { cacheMiddleware } from 'tricache/hono';
10
+ *
11
+ * const app = new Hono();
12
+ * app.get('/api/posts', cacheMiddleware({ ttl: 300, tags: ['posts'] }), (c) => {
13
+ * return c.json({ data: '...' });
14
+ * });
15
+ */
16
+
17
+ import type { CacheService } from '../cache-service.js';
18
+ import type { WrapOptions } from '../types.js';
19
+ import {
20
+ buildDeterministicKey,
21
+ generateETag,
22
+ shouldSkipCache,
23
+ type KeyDerivationOptions,
24
+ } from '../http/utils.js';
25
+
26
+ /**
27
+ * Minimal Hono context surface used by the middleware.
28
+ * Compatible with `import('hono').Context` without taking a runtime dependency.
29
+ */
30
+ export interface HonoCacheContext {
31
+ req: {
32
+ method: string;
33
+ url: string;
34
+ header?: (name: string) => string | undefined;
35
+ headers?: Headers | Record<string, string | string[] | undefined>;
36
+ };
37
+ res?: {
38
+ status?: number;
39
+ headers?: { get(name: string): string | null | undefined };
40
+ clone?: () => { text: () => Promise<string> };
41
+ body?: unknown;
42
+ };
43
+ body: (data: unknown, status?: number, headers?: Record<string, string>) => unknown;
44
+ executionCtx?: unknown;
45
+ }
46
+
47
+ export type HonoNext = () => Promise<void>;
48
+ export type HonoMiddleware = (c: HonoCacheContext, next: HonoNext) => Promise<unknown>;
49
+
50
+ export interface HonoCacheOptions extends Omit<WrapOptions, 'tags'>, Omit<KeyDerivationOptions, 'keyGenerator'> {
51
+ /** TriCache instance. If omitted, lazily resolves the default singleton via CacheService.create(). */
52
+ cache?: CacheService;
53
+ /** Whether to generate and evaluate weak ETags. Default: true. */
54
+ etag?: boolean;
55
+ /** Custom cache key. Overrides default method + URL + sorted query derivation. */
56
+ keyGenerator?: (c: HonoCacheContext) => string;
57
+ /** Custom predicate to skip caching dynamically (e.g. authenticated sessions). */
58
+ skipCache?: (c: HonoCacheContext) => boolean;
59
+ /** Dynamic tags derivation from the Hono context. */
60
+ tags?: string[] | ((c: HonoCacheContext) => string[]);
61
+ }
62
+
63
+ export interface CachedHonoResponse {
64
+ body: string;
65
+ contentType?: string;
66
+ headers?: Record<string, string>;
67
+ etag?: string;
68
+ status: number;
69
+ }
70
+
71
+ function readRequestHeader(c: HonoCacheContext, name: string): string | undefined {
72
+ const headerFn = c.req.header;
73
+ if (typeof headerFn === 'function') {
74
+ const viaFn = headerFn(name) ?? headerFn(name.toLowerCase());
75
+ if (viaFn !== undefined && viaFn !== null && viaFn !== '') {
76
+ return viaFn;
77
+ }
78
+ }
79
+
80
+ const raw = c.req.headers;
81
+ if (!raw) return undefined;
82
+
83
+ if (typeof (raw as Headers).get === 'function') {
84
+ const viaGet = (raw as Headers).get(name);
85
+ if (viaGet) return viaGet;
86
+ }
87
+
88
+ const record = raw as Record<string, string | string[] | undefined>;
89
+ const val = record[name.toLowerCase()] ?? record[name];
90
+ if (val === undefined || val === null || val === '') return undefined;
91
+ return Array.isArray(val) ? val.join(',') : String(val);
92
+ }
93
+
94
+ function toRequestLike(c: HonoCacheContext, headerWhitelist?: string[]) {
95
+ const headers: Record<string, string | undefined> = {};
96
+ const cacheControl = readRequestHeader(c, 'cache-control');
97
+ const ifNoneMatch = readRequestHeader(c, 'if-none-match');
98
+
99
+ if (cacheControl) {
100
+ headers['cache-control'] = cacheControl;
101
+ headers['Cache-Control'] = cacheControl;
102
+ }
103
+ if (ifNoneMatch) {
104
+ headers['if-none-match'] = ifNoneMatch;
105
+ headers['If-None-Match'] = ifNoneMatch;
106
+ }
107
+
108
+ if (headerWhitelist) {
109
+ for (const h of headerWhitelist) {
110
+ headers[h.toLowerCase()] = readRequestHeader(c, h);
111
+ }
112
+ }
113
+
114
+ return {
115
+ method: (c.req.method || 'GET').toUpperCase(),
116
+ url: c.req.url || '/',
117
+ headers,
118
+ };
119
+ }
120
+
121
+ function isCacheableStatus(status: number): boolean {
122
+ // Only standard successful full responses (never 206 Partial Content or non-2xx)
123
+ return status >= 200 && status < 300 && status !== 206;
124
+ }
125
+
126
+ function hasNoStoreDirective(cacheControl: string | null | undefined): boolean {
127
+ if (!cacheControl) return false;
128
+ const lower = cacheControl.toLowerCase();
129
+ return lower.includes('no-store') || lower.includes('no-cache') || lower.includes('private');
130
+ }
131
+
132
+ function applyHonoCachedResponse(
133
+ c: HonoCacheContext,
134
+ cached: CachedHonoResponse,
135
+ ifNoneMatch: string | undefined,
136
+ ): unknown {
137
+ if (cached.etag && ifNoneMatch === cached.etag) {
138
+ const notModifiedHeaders: Record<string, string> = { ETag: cached.etag };
139
+ if (cached.headers?.['cache-control']) notModifiedHeaders['Cache-Control'] = cached.headers['cache-control'];
140
+ if (cached.headers?.['vary']) notModifiedHeaders['Vary'] = cached.headers['vary'];
141
+ const result = c.body(null, 304, notModifiedHeaders);
142
+ if (result != null) {
143
+ c.res = result as HonoCacheContext['res'];
144
+ }
145
+ return result;
146
+ }
147
+
148
+ const headers: Record<string, string> = { ...cached.headers };
149
+ if (cached.etag) headers['ETag'] = cached.etag;
150
+ if (cached.contentType) headers['Content-Type'] = cached.contentType;
151
+
152
+ const result = c.body(cached.body, cached.status ?? 200, headers);
153
+ if (result != null) {
154
+ c.res = result as HonoCacheContext['res'];
155
+ }
156
+ return result;
157
+ }
158
+
159
+ async function snapshotHonoResponse(
160
+ c: HonoCacheContext,
161
+ etag: boolean,
162
+ ): Promise<CachedHonoResponse> {
163
+ const res = c.res;
164
+ if (!res) {
165
+ return { body: '', status: 0 };
166
+ }
167
+
168
+ const contentType = res.headers?.get?.('content-type') || 'text/plain; charset=utf-8';
169
+ if (contentType.toLowerCase().includes('text/event-stream')) {
170
+ // Never buffer or cache Server-Sent Events / infinite streams
171
+ return { body: '', contentType, status: 0 };
172
+ }
173
+
174
+ const cacheControl = res.headers?.get?.('cache-control');
175
+ if (hasNoStoreDirective(cacheControl)) {
176
+ // Response explicitly forbids caching / shared caching
177
+ return { body: '', contentType, status: 0 };
178
+ }
179
+
180
+ const status = res.status ?? 200;
181
+ if (!isCacheableStatus(status)) {
182
+ return { body: '', contentType, status };
183
+ }
184
+
185
+ const clone = typeof res.clone === 'function' ? res.clone() : undefined;
186
+ const text = clone && typeof clone.text === 'function'
187
+ ? await clone.text()
188
+ : typeof res.body === 'string'
189
+ ? res.body
190
+ : '';
191
+
192
+ const bodyEtag = etag ? generateETag(text) : undefined;
193
+
194
+ const capturedHeaders: Record<string, string> = {};
195
+ if (res.headers && typeof (res.headers as any).forEach === 'function') {
196
+ (res.headers as any).forEach((value: string, name: string) => {
197
+ const lower = name.toLowerCase();
198
+ if (
199
+ lower !== 'content-length' &&
200
+ lower !== 'transfer-encoding' &&
201
+ lower !== 'connection' &&
202
+ lower !== 'etag' &&
203
+ lower !== 'content-type'
204
+ ) {
205
+ capturedHeaders[name] = value;
206
+ }
207
+ });
208
+ }
209
+
210
+ return {
211
+ body: text,
212
+ contentType,
213
+ headers: capturedHeaders,
214
+ etag: bodyEtag,
215
+ status,
216
+ };
217
+ }
218
+
219
+ class NonCacheableHonoResponseError extends Error {
220
+ readonly isNonCacheable = true;
221
+ constructor(readonly response: CachedHonoResponse) {
222
+ super(`Non-cacheable response: status=${response.status}`);
223
+ this.name = 'NonCacheableHonoResponseError';
224
+ }
225
+ }
226
+
227
+ /**
228
+ * Creates a Hono middleware that caches GET/HEAD responses through Node
229
+ * `CacheService`, with Express-aligned ttl/tags/SWR options, weak ETags, and
230
+ * RFC 7232 `If-None-Match` → `304 Not Modified`. Non-2xx, 206 Partial Content,
231
+ * private/no-store, and streaming SSE responses are never kept.
232
+ *
233
+ * @example
234
+ * import { Hono } from 'hono';
235
+ * import { CacheService } from 'tricache';
236
+ * import { cacheMiddleware } from 'tricache/hono';
237
+ *
238
+ * const app = new Hono();
239
+ * const cache = CacheService.create();
240
+ *
241
+ * app.get(
242
+ * '/api/posts',
243
+ * cacheMiddleware({ cache, ttl: 300, tags: ['posts'] }),
244
+ * (c) => c.json({ data: '...' }),
245
+ * );
246
+ */
247
+ export function cacheMiddleware(options: HonoCacheOptions = {}): HonoMiddleware {
248
+ const {
249
+ cache,
250
+ etag = true,
251
+ ttl = 300,
252
+ swr,
253
+ tags,
254
+ skipCache,
255
+ keyGenerator,
256
+ headerWhitelist,
257
+ } = options;
258
+
259
+ let resolvedCache = cache;
260
+
261
+ return async (c, next) => {
262
+ const method = (c.req.method || 'GET').toUpperCase();
263
+ if (method !== 'GET' && method !== 'HEAD') {
264
+ return await next();
265
+ }
266
+
267
+ const reqLike = toRequestLike(c, headerWhitelist);
268
+ if (shouldSkipCache(reqLike, skipCache ? () => skipCache(c) : undefined)) {
269
+ return await next();
270
+ }
271
+
272
+ if (!resolvedCache) {
273
+ const { CacheService } = await import('../cache-service.js');
274
+ resolvedCache = CacheService.create();
275
+ }
276
+ const activeCache = resolvedCache;
277
+
278
+ const key = keyGenerator
279
+ ? keyGenerator(c)
280
+ : buildDeterministicKey(reqLike, { headerWhitelist });
281
+
282
+ const ifNoneMatch = readRequestHeader(c, 'if-none-match');
283
+ const resolvedTags = typeof tags === 'function' ? tags(c) : tags;
284
+
285
+ let ranNext = false;
286
+ try {
287
+ const cached = await activeCache.get<CachedHonoResponse>(
288
+ key,
289
+ async () => {
290
+ ranNext = true;
291
+ await next();
292
+ const snapshot = await snapshotHonoResponse(c, etag);
293
+ if (!isCacheableStatus(snapshot.status)) {
294
+ throw new NonCacheableHonoResponseError(snapshot);
295
+ }
296
+ return snapshot;
297
+ },
298
+ ttl,
299
+ { swr, tags: resolvedTags },
300
+ );
301
+
302
+ return applyHonoCachedResponse(c, cached, ifNoneMatch);
303
+ } catch (err: unknown) {
304
+ if (err instanceof NonCacheableHonoResponseError) {
305
+ if (!ranNext) {
306
+ return await next();
307
+ }
308
+ return;
309
+ }
310
+ throw err;
311
+ }
312
+ };
313
+ }
314
+
315
+ /** Alias matching `createExpressMiddleware` / `createKoaMiddleware` naming. */
316
+ export const createHonoMiddleware = cacheMiddleware;
package/src/http/index.ts CHANGED
@@ -10,8 +10,13 @@
10
10
  * import { fastifyCachePlugin } from 'tricache/http';
11
11
  * await fastify.register(fastifyCachePlugin, { cache, ttl: 300 });
12
12
  *
13
+ * For Node Hono (CacheService, three-tier L1/L1.5/L2), use the dedicated entry:
14
+ * import { cacheMiddleware } from 'tricache/hono';
15
+ *
13
16
  * For Edge runtimes (Cloudflare Workers, Vercel Edge, Deno) and Hono, use:
14
17
  * import { honoEdgeCache } from 'tricache/edge';
18
+ *
19
+ * `honoCache` below remains the edge helper re-export for compatibility.
15
20
  */
16
21
 
17
22
  export {
package/src/index.ts CHANGED
@@ -36,7 +36,7 @@ export {
36
36
  export { DiskTier, resolveDefaultDiskDir } from './disk-tier';
37
37
  export { TierLatencyWatchdog, type LatencyWatchdogOptions, type LatencyWatchdogTelemetry } from './latency-watchdog';
38
38
  export { WasmBloomFilter } from './wasm/bloom-filter-wasm';
39
- export { type CompressionAlgorithm } from './compression';
39
+ export { type CompressionAlgorithm, type CustomCompressor, initZstd } from './compression';
40
40
  export { CacheCodec, defaultCodec, type CacheCodecOptions } from './codec';
41
41
  export {
42
42
  createHttpSnapshotAdapter,
@@ -114,6 +114,7 @@ export {
114
114
  type ICacheBatchObservableCallback,
115
115
  type ICacheMeter,
116
116
  type CacheHealthStatus,
117
+ type InvalidateTagOptions,
117
118
  } from './types';
118
119
 
119
120
  export {
@@ -122,6 +123,13 @@ export {
122
123
  type ParsedTraceParent,
123
124
  } from './utils/tracing';
124
125
 
126
+ export {
127
+ isWildcardTag,
128
+ matchesTagPattern,
129
+ isChildTag,
130
+ expandHierarchicalTags,
131
+ } from './utils/tag-matcher';
132
+
125
133
  export {
126
134
  tricacheDashboard,
127
135
  createNextDashboardHandlers,
@@ -355,8 +355,36 @@ export async function findActiveSockets(): Promise<string[]> {
355
355
  await client.ping(100);
356
356
  active.push(currentPipe);
357
357
  } catch {
358
- // Pipe not present or not active
358
+ // Pipe not present or not active on current PID
359
359
  }
360
+
361
+ try {
362
+ const { execFileSync } = await import('node:child_process');
363
+ const stdout = execFileSync(
364
+ 'powershell.exe',
365
+ ['-NoProfile', '-NonInteractive', '-Command', '[System.IO.Directory]::GetFiles("\\\\.\\pipe\\") | Where-Object { $_ -like "*tricache-*" }'],
366
+ { timeout: 1500, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] },
367
+ );
368
+ const candidates = stdout
369
+ .split(/\r?\n/)
370
+ .map((name) => name.trim())
371
+ .filter((name) => name.length > 0 && !active.includes(name));
372
+
373
+ await Promise.all(
374
+ candidates.map(async (pipePath) => {
375
+ const testClient = new IpcTelemetryClient(pipePath);
376
+ try {
377
+ await testClient.ping(100);
378
+ active.push(pipePath);
379
+ } catch {
380
+ // Stale or non-responsive pipe
381
+ }
382
+ }),
383
+ );
384
+ } catch {
385
+ // Ignore enumeration errors (e.g. timeout or restricted environment)
386
+ }
387
+
360
388
  return active;
361
389
  }
362
390
 
@@ -20,6 +20,7 @@ import type { ILogger } from './types.ts';
20
20
  import {
21
21
  compressBuffer,
22
22
  decompressBuffer,
23
+ initZstd,
23
24
  PREFIX_COMPRESSED,
24
25
  PREFIX_ENC_COMPRESSED,
25
26
  type CompressionAlgorithm,
@@ -53,13 +54,16 @@ const enc = new CacheEncryption(
53
54
  prevMode,
54
55
  );
55
56
 
56
- const cmpAlgo = compression ?? 'none';
57
+ const cmpAlgo = compression ?? 'zstd';
57
58
  const cmpThreshold = compressionThresholdBytes ?? 1024;
58
59
 
59
60
  parentPort!.on(
60
61
  'message',
61
- ({ id, type, payload }: { id: number; type: 'encrypt' | 'decrypt'; payload: string | Uint8Array }) => {
62
+ async ({ id, type, payload }: { id: number; type: 'encrypt' | 'decrypt'; payload: string | Uint8Array }) => {
62
63
  try {
64
+ if (cmpAlgo === 'zstd') {
65
+ await initZstd();
66
+ }
63
67
  const textPayload =
64
68
  typeof payload === 'string'
65
69
  ? payload
package/src/types.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import type { RemoteSnapshotOptions } from './remote-snapshot';
2
2
  import type { CrossRegionRelayOptions } from './cross-region';
3
+ import type { CompressionAlgorithm, CustomCompressor } from './compression';
3
4
 
4
5
  /**
5
6
  * tricache — shared types and interfaces
@@ -568,13 +569,22 @@ export interface CacheOptions {
568
569
 
569
570
  // ── Compression ──────────────────────────────────────────────────────────
570
571
  /**
571
- * Optional compression algorithm for L2 (Redis) strings and disk-tier binary blobs.
572
- * - `'brotli'` (default when enabled) — superior compression ratio for JSON / text payloads.
573
- * - `'gzip'` — faster compression / lower CPU overhead.
572
+ * Compression algorithm for L2 (Redis) strings and disk-tier binary blobs.
573
+ * - `'zstd'` (default) — Facebook Zstandard (via WebAssembly) for ultra-high throughput and ~96% ratio.
574
+ * - `'lz4'` — Ultra-fast compression/decompression for high-throughput, latency-critical workloads.
575
+ * - `'brotli'` — High compression ratio for JSON / text payloads.
576
+ * - `'gzip'` — Standard Deflate/Gzip compression.
574
577
  * - `'none'` — disable compression.
575
- * Default: `'none'` (uncompressed).
578
+ * Default: `'zstd'`.
576
579
  */
577
- compression?: 'brotli' | 'gzip' | 'none';
580
+ compression?: CompressionAlgorithm;
581
+
582
+ /**
583
+ * Custom compression engine plugin. When provided, overrides the built-in algorithms
584
+ * and delegates compression/decompression to this provider.
585
+ */
586
+ customCompressor?: CustomCompressor;
587
+
578
588
  /**
579
589
  * Minimum payload size in bytes before compression is applied.
580
590
  * Payloads smaller than this threshold remain uncompressed to avoid compression overhead.
@@ -675,6 +685,25 @@ export interface CacheOptions {
675
685
  */
676
686
  useShardedPubSub?: boolean;
677
687
 
688
+ /**
689
+ * If true, await backplane invalidation broadcasts during delete(), set(),
690
+ * clear(), and invalidateTag() operations rather than firing them in the background.
691
+ * Guarantees that remote cluster nodes receive the invalidation before the
692
+ * operation resolves to the caller.
693
+ *
694
+ * Default: `false` (asynchronous fire-and-forget for minimal caller latency).
695
+ */
696
+ awaitInvalidationBackplane?: boolean;
697
+
698
+ /**
699
+ * If `true`, `cache.lock()` operations fail closed (throw an Error) if Redis
700
+ * encounters a connection or runtime error during lock acquisition, preventing
701
+ * split-brain concurrent execution across multiple cluster nodes.
702
+ *
703
+ * Default: `false` (falls back to local in-process mutex with a debug log).
704
+ */
705
+ lockFailClosed?: boolean;
706
+
678
707
  // ── Multi-Region / Cross-Cluster Invalidation Relay ─────────────────────
679
708
  /**
680
709
  * Optional cross-region invalidation relay configuration for geo-distributed deployments.
@@ -1014,6 +1043,22 @@ export interface CacheOptions {
1014
1043
  */
1015
1044
  tagVersionTtlMs?: number;
1016
1045
 
1046
+ /**
1047
+ * Automatically expand hierarchical tags into their ancestor namespaces.
1048
+ * For example, tagging an entry with `'org:123:dept:456'` will also associate
1049
+ * it with `'org:123'` and `'org'`, allowing `invalidateTag('org:123')` or
1050
+ * `invalidateTag('org')` to automatically cascade down to this entry.
1051
+ *
1052
+ * Default: `false`.
1053
+ */
1054
+ hierarchicalTags?: boolean;
1055
+
1056
+ /**
1057
+ * The delimiter used for splitting hierarchical tags when `hierarchicalTags` is enabled.
1058
+ * Default: `':'`.
1059
+ */
1060
+ tagHierarchyDelimiter?: string;
1061
+
1017
1062
  /**
1018
1063
  * Read safety strategy for returned cached objects:
1019
1064
  * - `'none'` (default): Returns raw in-memory references for sub-microsecond performance (~350 ns).
@@ -1056,6 +1101,18 @@ export interface CacheOptions {
1056
1101
  meter?: ICacheMeter;
1057
1102
  }
1058
1103
 
1104
+ /**
1105
+ * Options for tag invalidation operations (`cache.invalidateTag()` and `cache.invalidateTags()`).
1106
+ */
1107
+ export interface InvalidateTagOptions {
1108
+ /**
1109
+ * When true, invalidates both the specified tag and any descendant child tags
1110
+ * in the hierarchy (e.g. invalidating 'org:123' also invalidates 'org:123:*').
1111
+ * Default: `false`.
1112
+ */
1113
+ cascade?: boolean;
1114
+ }
1115
+
1059
1116
  /**
1060
1117
  * Options for the ergonomic `cache.wrap(key, fetchFn, options)` method.
1061
1118
  */
@@ -1097,6 +1154,12 @@ export interface LockOptions {
1097
1154
  * Default: `100` ms.
1098
1155
  */
1099
1156
  retryInterval?: number;
1157
+ /**
1158
+ * If `true`, lock acquisition will throw an error immediately if Redis encounters a
1159
+ * connection or operational error rather than falling back to an in-process mutex.
1160
+ * Overrides `CacheOptions.lockFailClosed`.
1161
+ */
1162
+ failClosedOnRedisError?: boolean;
1100
1163
  }
1101
1164
 
1102
1165
  /**
@@ -0,0 +1,90 @@
1
+ /**
2
+ * Utilities for wildcard matching and hierarchical cascading of cache tags.
3
+ */
4
+
5
+ const globRegexCache = new Map<string, RegExp>();
6
+
7
+ /**
8
+ * Returns true if the given tag contains glob wildcard characters ('*' or '?').
9
+ */
10
+ export function isWildcardTag(tag: string): boolean {
11
+ return tag.includes('*') || tag.includes('?');
12
+ }
13
+
14
+ /**
15
+ * Matches a tag name against a pattern supporting '*' (0 or more chars) and '?' (single char).
16
+ * Optimized with fast-paths for exact match, universal wildcard, and single prefix/suffix wildcards.
17
+ */
18
+ export function matchesTagPattern(pattern: string, tag: string): boolean {
19
+ if (pattern === '*' || pattern === tag) return true;
20
+ if (!pattern.includes('*') && !pattern.includes('?')) return pattern === tag;
21
+
22
+ // Fast path: trailing single '*' (e.g. "org:123:*")
23
+ if (pattern.endsWith('*') && !pattern.slice(0, -1).includes('*') && !pattern.includes('?')) {
24
+ const prefix = pattern.slice(0, -1);
25
+ return tag.startsWith(prefix);
26
+ }
27
+
28
+ // Fast path: leading single '*' (e.g. "*:settings")
29
+ if (pattern.startsWith('*') && !pattern.slice(1).includes('*') && !pattern.includes('?')) {
30
+ const suffix = pattern.slice(1);
31
+ return tag.endsWith(suffix);
32
+ }
33
+
34
+ // General glob with bounded RegExp cache
35
+ let re = globRegexCache.get(pattern);
36
+ if (!re) {
37
+ if (globRegexCache.size >= 1000) globRegexCache.clear();
38
+ const escaped = pattern
39
+ .replace(/[.+^${}()|[\]\\]/g, '\\$&')
40
+ .replace(/\*/g, '.*')
41
+ .replace(/\?/g, '.');
42
+ re = new RegExp(`^${escaped}$`);
43
+ globRegexCache.set(pattern, re);
44
+ }
45
+ return re.test(tag);
46
+ }
47
+
48
+ /**
49
+ * Determines whether `candidateTag` is either identical to `parentTag`
50
+ * or a child descendant in the hierarchy separated by `delimiter`.
51
+ *
52
+ * Example:
53
+ * isChildTag('org:123', 'org:123', ':') -> true
54
+ * isChildTag('org:123', 'org:123:dept', ':') -> true
55
+ * isChildTag('org:123', 'org:1234', ':') -> false (must match delimiter boundary)
56
+ */
57
+ export function isChildTag(parentTag: string, candidateTag: string, delimiter = ':'): boolean {
58
+ if (candidateTag === parentTag) return true;
59
+ const prefix = parentTag.endsWith(delimiter) ? parentTag : `${parentTag}${delimiter}`;
60
+ return candidateTag.startsWith(prefix);
61
+ }
62
+
63
+ /**
64
+ * Expands hierarchical tags into all ancestor namespace levels.
65
+ *
66
+ * Example:
67
+ * expandHierarchicalTags(['org:123:dept:456', 'role:admin'], ':')
68
+ * => ['org', 'org:123', 'org:123:dept', 'org:123:dept:456', 'role', 'role:admin']
69
+ */
70
+ export function expandHierarchicalTags(tags: string[], delimiter = ':'): string[] {
71
+ if (!tags.length) return [];
72
+ const result = new Set<string>();
73
+
74
+ for (const tag of tags) {
75
+ if (!tag) continue;
76
+ const parts = tag.split(delimiter).filter(p => p.length > 0);
77
+ if (parts.length <= 1) {
78
+ result.add(tag);
79
+ continue;
80
+ }
81
+
82
+ let accumulated = '';
83
+ for (let i = 0; i < parts.length; i++) {
84
+ accumulated = i === 0 ? parts[i] : `${accumulated}${delimiter}${parts[i]}`;
85
+ result.add(accumulated);
86
+ }
87
+ }
88
+
89
+ return Array.from(result);
90
+ }