tricache 0.9.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 (47) hide show
  1. package/README.md +7 -3
  2. package/dist/{cache-service-KI5ACF3F.js → cache-service-26GCO3UU.js} +3 -3
  3. package/dist/{cache-service-DVvroyqA.d.ts → cache-service-pJ-nFcVj.d.ts} +29 -12
  4. package/dist/{chunk-XZL45ABR.js → chunk-2AJKEQMZ.js} +54 -1
  5. package/dist/{chunk-PL5J3ZNT.js → chunk-7SZSQS55.js} +201 -34
  6. package/dist/{chunk-LJ5QJB5O.js → chunk-UBWLPKTI.js} +127 -11
  7. package/dist/cli.cjs +376 -50
  8. package/dist/cli.js +4 -4
  9. package/dist/dashboard/index.d.ts +2 -2
  10. package/dist/drizzle/index.cjs +384 -51
  11. package/dist/drizzle/index.d.ts +2 -2
  12. package/dist/drizzle/index.js +1 -1
  13. package/dist/edge/index.cjs +64 -8
  14. package/dist/edge/index.d.ts +3 -3
  15. package/dist/edge/index.js +37 -9
  16. package/dist/hono/index.cjs +384 -51
  17. package/dist/hono/index.d.ts +2 -2
  18. package/dist/hono/index.js +1 -1
  19. package/dist/{hono-VA9A1m0I.d.ts → hono-DuNvciyq.d.ts} +4 -4
  20. package/dist/http/index.cjs +384 -51
  21. package/dist/http/index.d.ts +3 -3
  22. package/dist/http/index.js +8 -8
  23. package/dist/index.cjs +385 -49
  24. package/dist/index.d.ts +35 -6
  25. package/dist/index.js +16 -6
  26. package/dist/nestjs/index.cjs +375 -49
  27. package/dist/nestjs/index.d.ts +2 -2
  28. package/dist/nestjs/index.js +4 -4
  29. package/dist/next/index.cjs +375 -49
  30. package/dist/next/index.d.ts +2 -2
  31. package/dist/next/index.js +3 -3
  32. package/dist/prisma/index.d.ts +2 -2
  33. package/dist/serialize-worker.cjs +127 -9
  34. package/dist/serialize-worker.js +8 -4
  35. package/dist/{types-B_QkVwJ7.d.ts → types-5HXqBfAf.d.ts} +51 -7
  36. package/package.json +7 -4
  37. package/src/cache-service.ts +238 -33
  38. package/src/cli.ts +1 -1
  39. package/src/compression.ts +193 -15
  40. package/src/cross-region.ts +1 -1
  41. package/src/edge/cache.ts +38 -11
  42. package/src/env.d.ts +13 -0
  43. package/src/index.ts +9 -1
  44. package/src/serialize-worker.ts +6 -2
  45. package/src/types.ts +43 -5
  46. package/src/utils/tag-matcher.ts +90 -0
  47. /package/dist/{chunk-QNU7B43J.js → chunk-VXFTFZ5N.js} +0 -0
@@ -49,6 +49,7 @@ import {
49
49
  WTinyLfuStats,
50
50
  CachePresetType,
51
51
  CacheHealthStatus,
52
+ InvalidateTagOptions,
52
53
  } from './types';
53
54
  import { CacheEncryption, EnvelopeEncryption, type EncryptionMode } from './encryption';
54
55
  import { SmartMemoryCache } from './smart-memory-cache';
@@ -60,10 +61,18 @@ import { IpcTelemetryServer } from './ipc-telemetry.js';
60
61
  import {
61
62
  compressBuffer,
62
63
  decompressBuffer,
64
+ initZstd,
63
65
  PREFIX_COMPRESSED,
64
66
  PREFIX_ENC_COMPRESSED,
65
67
  type CompressionAlgorithm,
68
+ type CustomCompressor,
66
69
  } from './compression';
70
+ import {
71
+ isWildcardTag,
72
+ matchesTagPattern,
73
+ isChildTag,
74
+ expandHierarchicalTags,
75
+ } from './utils/tag-matcher.js';
67
76
 
68
77
  // ─── Lua scripts ─────────────────────────────────────────────────────────────
69
78
 
@@ -501,11 +510,14 @@ export class CacheService {
501
510
  redisProtocol: 2 | 3 | undefined;
502
511
  useShardedPubSub: boolean;
503
512
  compression: CompressionAlgorithm;
513
+ customCompressor?: CustomCompressor;
504
514
  compressionThresholdBytes: number;
505
515
  strictSingleton: boolean;
506
516
  failClosed: boolean;
507
517
  tagStrategy: 'set' | 'generational';
508
518
  tagVersionTtlMs: number;
519
+ hierarchicalTags: boolean;
520
+ tagHierarchyDelimiter: string;
509
521
  cloneStrategy: 'none' | 'structuredClone';
510
522
  backplaneMode: 'pubsub' | 'stream';
511
523
  backplaneStreamMaxLen: number;
@@ -536,6 +548,7 @@ export class CacheService {
536
548
  };
537
549
  /** Pre-computed once — opts.namespace never changes after construction. */
538
550
  private readonly _namespace: string;
551
+ private readonly prefixLen: number;
539
552
  /** Pre-computed once — disableRedis and redisHost never change after construction. */
540
553
  private readonly _redisDisabled: boolean;
541
554
  private readonly watchdog: TierLatencyWatchdog;
@@ -765,12 +778,15 @@ export class CacheService {
765
778
  redisSentinel: options.redisSentinel,
766
779
  redisProtocol: options.redisProtocol,
767
780
  useShardedPubSub: options.useShardedPubSub ?? false,
768
- compression: options.compression ?? 'none',
781
+ compression: options.compression ?? 'zstd',
782
+ customCompressor: options.customCompressor,
769
783
  compressionThresholdBytes: options.compressionThresholdBytes ?? 1024,
770
784
  strictSingleton: options.strictSingleton ?? false,
771
785
  failClosed: options.failClosed ?? false,
772
786
  tagStrategy: options.tagStrategy ?? 'set',
773
787
  tagVersionTtlMs: options.tagVersionTtlMs ?? 5_000,
788
+ hierarchicalTags: options.hierarchicalTags ?? false,
789
+ tagHierarchyDelimiter: options.tagHierarchyDelimiter ?? ':',
774
790
  cloneStrategy: options.cloneStrategy ?? 'none',
775
791
  backplaneMode: options.backplaneMode ?? 'pubsub',
776
792
  backplaneStreamMaxLen: options.backplaneStreamMaxLen ?? 10_000,
@@ -854,6 +870,7 @@ export class CacheService {
854
870
  });
855
871
 
856
872
  this._namespace = ns;
873
+ this.prefixLen = ns ? ns.length + 1 : 0;
857
874
  // disableRedis takes unconditional precedence; otherwise, L2 is active when
858
875
  // at least one of host / cluster nodes / sentinel is configured.
859
876
  this._redisDisabled = this.opts.disableRedis
@@ -991,6 +1008,9 @@ export class CacheService {
991
1008
 
992
1009
  // Auto-warm from remote snapshot or L2 if configured; ready() waits for completion.
993
1010
  const startupPromises: Promise<void>[] = [];
1011
+ if (this.opts.compression === 'zstd') {
1012
+ startupPromises.push(initZstd().then(() => undefined));
1013
+ }
994
1014
  if (this.opts.remoteSnapshot) {
995
1015
  startupPromises.push(this.loadRemoteSnapshot().then(() => undefined));
996
1016
  }
@@ -1534,6 +1554,50 @@ export class CacheService {
1534
1554
  const tag = key;
1535
1555
  const ver = typeof tagVersion === 'number' ? tagVersion : ((this.tagVersions.get(tag)?.version ?? 0) + 1);
1536
1556
  this._setLocalTagVersion(tag, ver, performance.now());
1557
+ } else if (op === 'tag_pattern_incr') {
1558
+ const pattern = key;
1559
+ const now = performance.now();
1560
+ for (const [tag, info] of this.tagVersions) {
1561
+ if (matchesTagPattern(pattern, tag)) {
1562
+ this._setLocalTagVersion(tag, info.version + 1, now);
1563
+ }
1564
+ }
1565
+ this.l1.scan((k, entry) => {
1566
+ if (entry.tagVersions) {
1567
+ for (const tag of Object.keys(entry.tagVersions)) {
1568
+ if (matchesTagPattern(pattern, tag)) {
1569
+ this.l1.delete(k);
1570
+ this._bumpKeyMutation(k);
1571
+ break;
1572
+ }
1573
+ }
1574
+ }
1575
+ }, 0);
1576
+ } else if (op === 'tag_pattern_del') {
1577
+ const pattern = key;
1578
+ const matchedTagKeys: string[] = [];
1579
+ const prefix = this.nk('_tag_:');
1580
+ for (const [tagKey, members] of this.tagIndex) {
1581
+ const tag = tagKey.startsWith(prefix) ? tagKey.slice(prefix.length) : tagKey;
1582
+ if (matchesTagPattern(pattern, tag)) {
1583
+ matchedTagKeys.push(tagKey);
1584
+ for (const k of members) {
1585
+ this.l1.delete(k);
1586
+ this._bumpKeyMutation(k);
1587
+ this._pendingDiskDeletes.add(k);
1588
+ setImmediate(() => {
1589
+ try {
1590
+ if (!this._diskDisabled) this.disk.delete(k);
1591
+ } finally {
1592
+ this._pendingDiskDeletes.delete(k);
1593
+ }
1594
+ });
1595
+ }
1596
+ }
1597
+ }
1598
+ for (const tagKey of matchedTagKeys) {
1599
+ this.tagIndex.delete(tagKey);
1600
+ }
1537
1601
  }
1538
1602
  this.logger.debug('Backplane: invalidation applied', { op, key: key.slice(0, 60) });
1539
1603
  }
@@ -1548,7 +1612,7 @@ export class CacheService {
1548
1612
  Array.isArray(msg) ||
1549
1613
  typeof msg.src !== 'string' ||
1550
1614
  typeof msg.key !== 'string' ||
1551
- (msg.op !== 'del' && msg.op !== 'del-glob' && msg.op !== 'tag_incr')
1615
+ (msg.op !== 'del' && msg.op !== 'del-glob' && msg.op !== 'tag_incr' && msg.op !== 'tag_pattern_incr' && msg.op !== 'tag_pattern_del')
1552
1616
  ) {
1553
1617
  this.logger.warn('Backplane: rejected invalid pubsub message format', {
1554
1618
  raw: typeof message === 'string' ? message.slice(0, 100).replace(/[\r\n\t]/g, ' ') : String(message),
@@ -1567,7 +1631,7 @@ export class CacheService {
1567
1631
  }
1568
1632
 
1569
1633
  private async publishInvalidation(
1570
- op: 'del' | 'del-glob' | 'tag_incr',
1634
+ op: 'del' | 'del-glob' | 'tag_incr' | 'tag_pattern_incr' | 'tag_pattern_del',
1571
1635
  key: string,
1572
1636
  tagVersion?: number,
1573
1637
  isCrossRegionRelay = false,
@@ -1640,7 +1704,7 @@ export class CacheService {
1640
1704
  }
1641
1705
 
1642
1706
  private async _broadcastCrossRegion(
1643
- op: 'del' | 'del-glob' | 'tag_incr',
1707
+ op: 'del' | 'del-glob' | 'tag_incr' | 'tag_pattern_incr' | 'tag_pattern_del',
1644
1708
  key: string,
1645
1709
  tagVersion?: number,
1646
1710
  ): Promise<void> {
@@ -1767,12 +1831,12 @@ export class CacheService {
1767
1831
  * Offloads to worker thread if pool is active and payload exceeds threshold.
1768
1832
  */
1769
1833
  private async _serializeAndEncrypt(serialized: string): Promise<string> {
1770
- const isCompressed = this.opts.compression && this.opts.compression !== 'none' && serialized.length > this.opts.compressionThresholdBytes;
1771
- if (this._workerPool && (this.enc.isEnabled || isCompressed) && serialized.length > this.opts.workerThresholdBytes) {
1834
+ const isCompressed = (this.opts.customCompressor || (this.opts.compression && this.opts.compression !== 'none')) && serialized.length > this.opts.compressionThresholdBytes;
1835
+ if (this._workerPool && !this.opts.customCompressor && (this.enc.isEnabled || isCompressed) && serialized.length > this.opts.workerThresholdBytes) {
1772
1836
  return this._workerPool.encrypt(serialized);
1773
1837
  }
1774
1838
  if (isCompressed) {
1775
- const compressed = compressBuffer(Buffer.from(serialized, 'utf8'), this.opts.compression);
1839
+ const compressed = compressBuffer(Buffer.from(serialized, 'utf8'), this.opts.compression, this.opts.customCompressor);
1776
1840
  if (this.enc.isEnabled) {
1777
1841
  const encrypted = this.enc.encryptBuffer(compressed);
1778
1842
  return PREFIX_ENC_COMPRESSED + encrypted.toString('base64');
@@ -1788,16 +1852,16 @@ export class CacheService {
1788
1852
  */
1789
1853
  private async _decryptAndDeserialize<T>(raw: string): Promise<T> {
1790
1854
  let plain: string;
1791
- if (this._workerPool && raw.length > this.opts.workerThresholdBytes) {
1855
+ if (this._workerPool && !this.opts.customCompressor && raw.length > this.opts.workerThresholdBytes) {
1792
1856
  plain = await this._workerPool.decrypt(raw);
1793
1857
  } else if (raw.startsWith(PREFIX_ENC_COMPRESSED)) {
1794
1858
  const encBuf = Buffer.from(raw.slice(PREFIX_ENC_COMPRESSED.length), 'base64');
1795
1859
  const decBuf = this.enc.decryptBuffer(encBuf);
1796
- const decompressed = decompressBuffer(decBuf, this.opts.compression !== 'none' ? this.opts.compression : 'brotli');
1860
+ const decompressed = decompressBuffer(decBuf, this.opts.compression !== 'none' ? this.opts.compression : 'brotli', this.opts.customCompressor);
1797
1861
  plain = decompressed.toString('utf8');
1798
1862
  } else if (raw.startsWith(PREFIX_COMPRESSED)) {
1799
1863
  const cmpBuf = Buffer.from(raw.slice(PREFIX_COMPRESSED.length), 'base64');
1800
- const decompressed = decompressBuffer(cmpBuf, this.opts.compression !== 'none' ? this.opts.compression : 'brotli');
1864
+ const decompressed = decompressBuffer(cmpBuf, this.opts.compression !== 'none' ? this.opts.compression : 'brotli', this.opts.customCompressor);
1801
1865
  plain = decompressed.toString('utf8');
1802
1866
  } else if (raw.startsWith('enc:v1:') || this.enc.isEnabled) {
1803
1867
  plain = this.enc.decrypt(raw);
@@ -2257,7 +2321,9 @@ export class CacheService {
2257
2321
  const optRefreshAhead = opts.refreshAhead;
2258
2322
  const optXfetchBeta = opts.xfetchBeta;
2259
2323
  const optNotFoundTtl = opts.notFoundTtl;
2260
- const optTags = opts.tags;
2324
+ const optTags = opts.tags
2325
+ ? (this.opts.hierarchicalTags ? expandHierarchicalTags(opts.tags, this.opts.tagHierarchyDelimiter) : opts.tags)
2326
+ : undefined;
2261
2327
 
2262
2328
  // L1: in-memory (fastest path)
2263
2329
  const l1Hit = this.l1.get(k);
@@ -2797,15 +2863,19 @@ export class CacheService {
2797
2863
  this.counters.sets++;
2798
2864
 
2799
2865
  let activeTagVersions: Record<string, number> | undefined;
2800
- if (opts?.tags?.length) {
2866
+ const tagsToRegister = opts?.tags?.length
2867
+ ? (this.opts.hierarchicalTags ? expandHierarchicalTags(opts.tags, this.opts.tagHierarchyDelimiter) : opts.tags)
2868
+ : undefined;
2869
+
2870
+ if (tagsToRegister?.length) {
2801
2871
  if (this.opts.tagStrategy === 'generational') {
2802
- const vers = await Promise.all(opts.tags.map(tag => this._getTagVersion(tag)));
2872
+ const vers = await Promise.all(tagsToRegister.map(tag => this._getTagVersion(tag)));
2803
2873
  activeTagVersions = {};
2804
- for (let i = 0; i < opts.tags.length; i++) {
2805
- activeTagVersions[opts.tags[i]] = vers[i];
2874
+ for (let i = 0; i < tagsToRegister.length; i++) {
2875
+ activeTagVersions[tagsToRegister[i]] = vers[i];
2806
2876
  }
2807
2877
  } else {
2808
- await this._registerTags(k, opts.tags, ttlSeconds);
2878
+ await this._registerTags(k, tagsToRegister, ttlSeconds);
2809
2879
  }
2810
2880
  }
2811
2881
 
@@ -3350,7 +3420,7 @@ export class CacheService {
3350
3420
  */
3351
3421
  async mget<T>(
3352
3422
  keys: string[],
3353
- fetchFn: (missKeys: string[]) => Promise<Record<string, T>>,
3423
+ fetchFn?: (missKeys: string[]) => Promise<Record<string, T> | Map<string, T>>,
3354
3424
  ttl: number | ((key: string) => number) = 300,
3355
3425
  priority?: CachePriority,
3356
3426
  ): Promise<(T | undefined)[]> {
@@ -3461,16 +3531,24 @@ export class CacheService {
3461
3531
  }
3462
3532
 
3463
3533
  // ── Tier 3: fetchFn for whatever still missed ──
3464
- if (missKeys.length > 0) {
3534
+ if (missKeys.length > 0 && fetchFn) {
3465
3535
  this.counters.fetches++;
3466
3536
  const fetched = await fetchFn(missKeys);
3537
+ const isMap = fetched instanceof Map;
3467
3538
  const setPromises: Promise<void>[] = [];
3468
3539
  for (let j = 0; j < missKeys.length; j++) {
3469
- const v = fetched[missKeys[j]];
3540
+ const k = missKeys[j];
3541
+ const v = isMap ? (fetched as Map<string, T>).get(k) : (fetched as Record<string, T>)[k];
3470
3542
  result[missIndexes[j]] = v;
3471
- if (v !== undefined) {
3472
- const resolvedTtl = typeof ttl === 'function' ? ttl(missKeys[j]) : ttl;
3473
- setPromises.push(this.set(missKeys[j], v, resolvedTtl, priority));
3543
+ if (v !== undefined && v !== null) {
3544
+ const resolvedTtl = typeof ttl === 'function' ? ttl(k) : ttl;
3545
+ setPromises.push(this.set(k, v, resolvedTtl, priority));
3546
+ } else if (v == null && this.opts.notFoundTtl > 0) {
3547
+ // Negative caching: cache null/missing records with notFoundTtl to protect origin DB
3548
+ setPromises.push(this.set(k, null as unknown as T, this.opts.notFoundTtl, priority));
3549
+ } else if (v === null) {
3550
+ const resolvedTtl = typeof ttl === 'function' ? ttl(k) : ttl;
3551
+ setPromises.push(this.set(k, null as unknown as T, resolvedTtl, priority));
3474
3552
  }
3475
3553
  }
3476
3554
  if (setPromises.length > 0) {
@@ -3628,21 +3706,131 @@ export class CacheService {
3628
3706
  }
3629
3707
 
3630
3708
  /**
3631
- * Invalidate all keys associated with a tag.
3632
- * Deletes from L1, disk, and Redis (both the keyed values and the tag set).
3709
+ * Discovers all concrete tag names in the system that match `tag` either via
3710
+ * glob wildcards ('*' or '?') or parent-child hierarchy cascading.
3711
+ * Scans local in-memory indices (tagIndex, tagVersions, L1 entries) and Redis (if connected).
3712
+ */
3713
+ private async _resolveMatchingTags(tag: string, shouldCascade: boolean): Promise<Set<string>> {
3714
+ const isPattern = isWildcardTag(tag);
3715
+ const delim = this.opts.tagHierarchyDelimiter;
3716
+ const matched = new Set<string>();
3717
+
3718
+ const tagMatches = (t: string): boolean => {
3719
+ if (t === tag) return true;
3720
+ if (isPattern && matchesTagPattern(tag, t)) return true;
3721
+ if (shouldCascade && isChildTag(tag, t, delim)) return true;
3722
+ return false;
3723
+ };
3724
+
3725
+ if (shouldCascade && !isPattern) {
3726
+ matched.add(tag);
3727
+ }
3728
+
3729
+ // 1. Scan in-process tagIndex (set strategy)
3730
+ const tagPrefix = this.nk('_tag_:');
3731
+ for (const tagKey of this.tagIndex.keys()) {
3732
+ const t = tagKey.startsWith(tagPrefix) ? tagKey.slice(tagPrefix.length) : tagKey;
3733
+ if (tagMatches(t)) matched.add(t);
3734
+ }
3735
+
3736
+ // 2. Scan in-process tagVersions (generational strategy)
3737
+ for (const t of this.tagVersions.keys()) {
3738
+ if (tagMatches(t)) matched.add(t);
3739
+ }
3740
+
3741
+ // 3. Scan in-process L1 entries for any active tags
3742
+ this.l1.scan((_k, entry) => {
3743
+ if (entry.tagVersions) {
3744
+ for (const t of Object.keys(entry.tagVersions)) {
3745
+ if (tagMatches(t)) matched.add(t);
3746
+ }
3747
+ }
3748
+ }, 0);
3749
+
3750
+ // 4. Scan Redis if connected
3751
+ if (!this._redisDisabled) {
3752
+ try {
3753
+ const client = await this.getRedis();
3754
+ if (this.opts.tagStrategy === 'generational') {
3755
+ const redisPattern = isPattern
3756
+ ? this.nk(`tag_ver:${tag}`)
3757
+ : this.nk(`tag_ver:${tag}${delim}*`);
3758
+ const scannedKeys = await this._scanKeys(client, redisPattern);
3759
+ const pfx = this.nk('tag_ver:');
3760
+ for (const sk of scannedKeys) {
3761
+ const t = sk.startsWith(pfx) ? sk.slice(pfx.length) : sk;
3762
+ if (tagMatches(t)) matched.add(t);
3763
+ }
3764
+ } else {
3765
+ const redisPattern = isPattern
3766
+ ? this.nk(`_tag_:${tag}`)
3767
+ : this.nk(`_tag_:${tag}${delim}*`);
3768
+ const scannedKeys = await this._scanKeys(client, redisPattern);
3769
+ const pfx = this.nk('_tag_:');
3770
+ for (const sk of scannedKeys) {
3771
+ const t = sk.startsWith(pfx) ? sk.slice(pfx.length) : sk;
3772
+ if (tagMatches(t)) matched.add(t);
3773
+ }
3774
+ }
3775
+ } catch (err) {
3776
+ this.logger.debug('_resolveMatchingTags: Redis scan failed', { tag, error: (err as Error).message });
3777
+ }
3778
+ }
3779
+
3780
+ return matched;
3781
+ }
3782
+
3783
+ /**
3784
+ * Invalidate all keys associated with a tag, wildcard glob pattern, or hierarchical namespace.
3785
+ * Deletes from L1, disk, and Redis (both the keyed values and the tag metadata).
3786
+ *
3787
+ * @param tag Tag name or wildcard glob pattern (e.g. `'catalog'`, `'org:123:*'`, `'*:comments'`).
3788
+ * @param opts Optional invalidation options, including `{ cascade: true }` to invalidate child namespaces.
3633
3789
  *
3634
3790
  * @example
3635
3791
  * await cache.set('product:1', data, 60, undefined, { tags: ['catalog'] });
3636
3792
  * await cache.invalidateTag('catalog'); // clears product:1 and any other tagged entries
3793
+ *
3794
+ * @example
3795
+ * // Wildcard pattern invalidation
3796
+ * await cache.invalidateTag('org:123:*');
3797
+ *
3798
+ * @example
3799
+ * // Hierarchical tag cascading (clears 'org:123' and all child tags like 'org:123:dept:456')
3800
+ * await cache.invalidateTag('org:123', { cascade: true });
3637
3801
  */
3638
- async invalidateTag(tag: string): Promise<void> {
3802
+ async invalidateTag(tag: string, opts?: InvalidateTagOptions): Promise<void> {
3639
3803
  this._assertActive('invalidateTag');
3640
3804
  const span = this._startSpan('tricache.invalidate_tag');
3641
3805
  if (this.opts.tracer) {
3642
3806
  span.setAttribute('cache.tag', tag);
3643
3807
  span.setAttribute('cache.tag_strategy', this.opts.tagStrategy);
3808
+ if (opts?.cascade) span.setAttribute('cache.cascade', true);
3644
3809
  }
3645
3810
  try {
3811
+ const isPattern = isWildcardTag(tag);
3812
+ const shouldCascade = Boolean(opts?.cascade || this.opts.hierarchicalTags);
3813
+
3814
+ if (isPattern || shouldCascade) {
3815
+ const matchedTags = await this._resolveMatchingTags(tag, shouldCascade);
3816
+ const delim = this.opts.tagHierarchyDelimiter;
3817
+ const broadcastPattern = isPattern ? tag : `${tag}${delim}*`;
3818
+
3819
+ if (matchedTags.size > 0) {
3820
+ await this.invalidateTags(Array.from(matchedTags));
3821
+ }
3822
+
3823
+ // Broadcast wildcard invalidation across backplane and cross-region
3824
+ const op = this.opts.tagStrategy === 'generational' ? 'tag_pattern_incr' : 'tag_pattern_del';
3825
+ if (this.opts.awaitInvalidationBackplane) {
3826
+ await this.publishInvalidation(op, broadcastPattern, undefined, false, true);
3827
+ } else {
3828
+ void this.publishInvalidation(op, broadcastPattern, undefined, false, true);
3829
+ }
3830
+ return;
3831
+ }
3832
+
3833
+ // Fast-path: single discrete tag
3646
3834
  if (this.opts.tagStrategy === 'generational') {
3647
3835
  let newVer = 1;
3648
3836
  if (!this._redisDisabled) {
@@ -3710,20 +3898,37 @@ export class CacheService {
3710
3898
 
3711
3899
  /**
3712
3900
  * Invalidate all keys associated with any of the given tags in a single operation.
3713
- * Combines multiple `invalidateTag()` calls into one Redis pipeline round-trip,
3714
- * reducing latency when invalidating several related tags together.
3901
+ * Supports discrete tags, wildcard glob patterns, and hierarchical cascading.
3902
+ * Combines multiple tag invalidations into Redis pipeline round-trips.
3715
3903
  *
3716
- * Note: Redis pipelines are batched, not atomic. All L1/disk deletes happen
3717
- * synchronously before the Redis round-trip.
3904
+ * @param tags Array of tag names or wildcard patterns (e.g. `['case:acme', 'org:*']`).
3905
+ * @param opts Optional invalidation options, including `{ cascade: true }`.
3718
3906
  *
3719
3907
  * @example
3720
- * // Instead of three serial round-trips:
3721
- * await cache.invalidateTags(['case:acme', 'org:acme', 'ai-chat:acme']);
3908
+ * await cache.invalidateTags(['case:acme', 'org:acme', 'ai-chat:*']);
3722
3909
  */
3723
- async invalidateTags(tags: string[]): Promise<void> {
3910
+ async invalidateTags(tags: string[], opts?: InvalidateTagOptions): Promise<void> {
3724
3911
  this._assertActive('invalidateTags');
3725
3912
  if (tags.length === 0) return;
3726
- if (tags.length === 1) { await this.invalidateTag(tags[0]); return; }
3913
+
3914
+ const hasWildcards = tags.some(t => isWildcardTag(t));
3915
+ const shouldCascade = Boolean(opts?.cascade || this.opts.hierarchicalTags);
3916
+
3917
+ if (hasWildcards || shouldCascade) {
3918
+ const allResolvedTags = new Set<string>();
3919
+ for (const t of tags) {
3920
+ if (isWildcardTag(t) || shouldCascade) {
3921
+ const resolved = await this._resolveMatchingTags(t, shouldCascade);
3922
+ for (const rt of resolved) allResolvedTags.add(rt);
3923
+ } else {
3924
+ allResolvedTags.add(t);
3925
+ }
3926
+ }
3927
+ if (allResolvedTags.size === 0) return;
3928
+ tags = Array.from(allResolvedTags);
3929
+ }
3930
+
3931
+ if (tags.length === 1) { await this.invalidateTag(tags[0], opts); return; }
3727
3932
 
3728
3933
  if (this.opts.tagStrategy === 'generational') {
3729
3934
  const now = performance.now();
package/src/cli.ts CHANGED
@@ -60,7 +60,7 @@ export async function runCli(args: string[] = process.argv.slice(2)): Promise<vo
60
60
  // (bin/tricache.js). Output must go directly to process stdout without logger prefixes
61
61
  // to support UNIX pipes, terminal formatting, and automated tooling.
62
62
  if (values.version || command === 'version') {
63
- let version = '0.9.0';
63
+ let version = '1.0.0';
64
64
  try {
65
65
  const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
66
66
  if (pkg?.version) version = pkg.version;