tricache 1.0.0 → 1.0.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.
Files changed (43) hide show
  1. package/README.md +1 -1
  2. package/dist/{cache-service-pJ-nFcVj.d.ts → cache-service-CREOp7MM.d.ts} +29 -1
  3. package/dist/{cache-service-26GCO3UU.js → cache-service-MG7PN6MX.js} +1 -1
  4. package/dist/{chunk-VXFTFZ5N.js → chunk-3I5L7K6I.js} +17 -0
  5. package/dist/{chunk-7SZSQS55.js → chunk-JYQFQJNJ.js} +533 -295
  6. package/dist/cli.cjs +534 -296
  7. package/dist/cli.js +2 -2
  8. package/dist/dashboard/index.d.ts +2 -2
  9. package/dist/drizzle/index.cjs +533 -295
  10. package/dist/drizzle/index.d.ts +2 -2
  11. package/dist/drizzle/index.js +1 -1
  12. package/dist/edge/index.cjs +55 -32
  13. package/dist/edge/index.d.ts +3 -3
  14. package/dist/edge/index.js +55 -32
  15. package/dist/hono/index.cjs +533 -295
  16. package/dist/hono/index.d.ts +2 -2
  17. package/dist/hono/index.js +1 -1
  18. package/dist/{hono-DuNvciyq.d.ts → hono-DSV2ve66.d.ts} +8 -1
  19. package/dist/http/index.cjs +585 -316
  20. package/dist/http/index.d.ts +3 -3
  21. package/dist/http/index.js +55 -24
  22. package/dist/index.cjs +550 -295
  23. package/dist/index.d.ts +5 -4
  24. package/dist/index.js +2 -2
  25. package/dist/nestjs/index.cjs +533 -295
  26. package/dist/nestjs/index.d.ts +2 -2
  27. package/dist/nestjs/index.js +2 -2
  28. package/dist/next/index.cjs +535 -303
  29. package/dist/next/index.d.ts +2 -2
  30. package/dist/next/index.js +3 -9
  31. package/dist/prisma/index.d.ts +2 -2
  32. package/dist/{types-5HXqBfAf.d.ts → types-Dyip5wAl.d.ts} +2 -0
  33. package/package.json +1 -1
  34. package/src/adapters/node-redis.ts +19 -0
  35. package/src/cache-service.ts +599 -320
  36. package/src/cli.ts +1 -1
  37. package/src/edge/cache.ts +60 -35
  38. package/src/http/express.ts +55 -16
  39. package/src/http/fastify.ts +3 -7
  40. package/src/next/cache-handler.ts +1 -4
  41. package/src/next/isr-handler.ts +1 -4
  42. package/src/smart-memory-cache.ts +3 -2
  43. package/src/types.ts +2 -0
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 = '1.0.0';
63
+ let version = '1.0.1';
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;
package/src/edge/cache.ts CHANGED
@@ -58,6 +58,7 @@ export class EdgeCacheService {
58
58
  private readonly tagIndex = new Map<string, Set<string>>();
59
59
 
60
60
  // Tag version in-isolate cache with 800ms micro-TTL (prevents HTTP fetch amplification on L1 hits)
61
+ private static readonly MAX_TAG_VERSION_CACHE = 10_000;
61
62
  private readonly tagVersionCache = new Map<string, { version: number; expiresAt: number }>();
62
63
  private readonly tagVersionTtlMs = 800;
63
64
 
@@ -147,6 +148,22 @@ export class EdgeCacheService {
147
148
  };
148
149
  }
149
150
 
151
+ private _setTagVersionCache(tag: string, version: number, expiresAt: number): void {
152
+ if (this.tagVersionCache.size >= EdgeCacheService.MAX_TAG_VERSION_CACHE && !this.tagVersionCache.has(tag)) {
153
+ const now = Date.now();
154
+ for (const [k, v] of this.tagVersionCache) {
155
+ if (v.expiresAt <= now) {
156
+ this.tagVersionCache.delete(k);
157
+ }
158
+ }
159
+ if (this.tagVersionCache.size >= EdgeCacheService.MAX_TAG_VERSION_CACHE) {
160
+ const oldestKey = this.tagVersionCache.keys().next().value;
161
+ if (oldestKey !== undefined) this.tagVersionCache.delete(oldestKey);
162
+ }
163
+ }
164
+ this.tagVersionCache.set(tag, { version, expiresAt });
165
+ }
166
+
150
167
  private async _getTagVersion(tag: string): Promise<number> {
151
168
  const cached = this.tagVersionCache.get(tag);
152
169
  const now = Date.now();
@@ -168,7 +185,7 @@ export class EdgeCacheService {
168
185
  } else {
169
186
  version = cached?.version ?? 1;
170
187
  }
171
- this.tagVersionCache.set(tag, { version, expiresAt: now + this.tagVersionTtlMs });
188
+ this._setTagVersionCache(tag, version, now + this.tagVersionTtlMs);
172
189
  return version;
173
190
  }
174
191
 
@@ -195,7 +212,7 @@ export class EdgeCacheService {
195
212
  const t = missingTags[i];
196
213
  const v = remoteVersions[this.nk(t)] ?? remoteVersions[t] ?? 1;
197
214
  result[t] = v;
198
- this.tagVersionCache.set(t, { version: v, expiresAt: now + this.tagVersionTtlMs });
215
+ this._setTagVersionCache(t, v, now + this.tagVersionTtlMs);
199
216
  }
200
217
  } else {
201
218
  await Promise.all(missingTags.map(async t => {
@@ -491,6 +508,45 @@ export class EdgeCacheService {
491
508
  }
492
509
  }
493
510
 
511
+ /**
512
+ * Executes invalidation for a single already-resolved concrete tag without
513
+ * re-entering wildcard/cascade resolution.
514
+ */
515
+ private async _invalidateConcreteTag(tag: string): Promise<void> {
516
+ let newVer = 1;
517
+ if (this.remoteStorage) {
518
+ try {
519
+ if (typeof this.remoteStorage.incrementTagVersion === 'function') {
520
+ newVer = await this.remoteStorage.incrementTagVersion(this.nk(tag));
521
+ } else {
522
+ const key = this.nk(`tag_ver:${tag}`);
523
+ const current = await this._getTagVersion(tag);
524
+ newVer = Math.max(current + 1, Date.now());
525
+ await this.remoteStorage.set(key, String(newVer));
526
+ }
527
+ } catch {
528
+ const current = this.tagVersionCache.get(tag)?.version ?? 1;
529
+ newVer = current + 1;
530
+ }
531
+ } else {
532
+ const current = this.tagVersionCache.get(tag)?.version ?? 1;
533
+ newVer = current + 1;
534
+ }
535
+
536
+ // Update in-isolate version cache immediately (with 60s pin)
537
+ this._setTagVersionCache(tag, newVer, Date.now() + 60_000);
538
+
539
+ // Invalidate local L1 entries
540
+ const keys = this.tagIndex.get(tag);
541
+ if (keys) {
542
+ const keysArr = Array.from(keys);
543
+ for (const k of keysArr) {
544
+ this._deleteL1(k);
545
+ }
546
+ this.tagIndex.delete(tag);
547
+ }
548
+ }
549
+
494
550
  /**
495
551
  * Invalidates all cached entries associated with a tag.
496
552
  */
@@ -518,43 +574,12 @@ export class EdgeCacheService {
518
574
  }
519
575
  if (shouldCascade && !isPattern) matched.add(tag);
520
576
  for (const t of matched) {
521
- await this.invalidateTag(t);
577
+ await this._invalidateConcreteTag(t);
522
578
  }
523
579
  return;
524
580
  }
525
581
 
526
- let newVer = 1;
527
- if (this.remoteStorage) {
528
- try {
529
- if (typeof this.remoteStorage.incrementTagVersion === 'function') {
530
- newVer = await this.remoteStorage.incrementTagVersion(this.nk(tag));
531
- } else {
532
- const key = this.nk(`tag_ver:${tag}`);
533
- const current = await this._getTagVersion(tag);
534
- newVer = Math.max(current + 1, Date.now());
535
- await this.remoteStorage.set(key, String(newVer));
536
- }
537
- } catch {
538
- const current = this.tagVersionCache.get(tag)?.version ?? 1;
539
- newVer = current + 1;
540
- }
541
- } else {
542
- const current = this.tagVersionCache.get(tag)?.version ?? 1;
543
- newVer = current + 1;
544
- }
545
-
546
- // Update in-isolate version cache immediately (with 60s pin)
547
- this.tagVersionCache.set(tag, { version: newVer, expiresAt: Date.now() + 60_000 });
548
-
549
- // Invalidate local L1 entries
550
- const keys = this.tagIndex.get(tag);
551
- if (keys) {
552
- const keysArr = Array.from(keys);
553
- for (const k of keysArr) {
554
- this._deleteL1(k);
555
- }
556
- this.tagIndex.delete(tag);
557
- }
582
+ await this._invalidateConcreteTag(tag);
558
583
  } catch (err) {
559
584
  span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
560
585
  span.recordException?.(err);
@@ -84,14 +84,45 @@ export function createExpressMiddleware(options: ExpressCacheOptions = {}) {
84
84
 
85
85
  const resolvedTags = typeof tags === 'function' ? tags(req) : tags;
86
86
 
87
+ let respondedLocally = false;
88
+
87
89
  try {
88
90
  const cached = await activeCache.get<CachedHttpResponse>(
89
91
  key,
90
92
  async () => {
91
- return new Promise<CachedHttpResponse>((resolve) => {
92
- const origJson = res.json?.bind(res);
93
- const origSend = res.send?.bind(res);
94
- const origEnd = res.end?.bind(res);
93
+ return new Promise<CachedHttpResponse>((resolve, reject) => {
94
+ const rawJson = res.json;
95
+ const rawSend = res.send;
96
+ const rawEnd = res.end;
97
+ const origJson = rawJson?.bind(res);
98
+ const origSend = rawSend?.bind(res);
99
+ const origEnd = rawEnd?.bind(res);
100
+ let settled = false;
101
+
102
+ const cleanup = () => {
103
+ if (rawJson !== undefined) res.json = rawJson;
104
+ if (rawSend !== undefined) res.send = rawSend;
105
+ if (rawEnd !== undefined) res.end = rawEnd;
106
+ res.removeListener?.('close', onClose);
107
+ };
108
+
109
+ const settle = (response: CachedHttpResponse) => {
110
+ if (settled) return;
111
+ settled = true;
112
+ respondedLocally = true;
113
+ cleanup();
114
+ resolve(response);
115
+ };
116
+
117
+ const onClose = () => {
118
+ if (settled) return;
119
+ settled = true;
120
+ respondedLocally = true;
121
+ cleanup();
122
+ reject(new Error('Express response closed before completion'));
123
+ };
124
+
125
+ res.once?.('close', onClose);
95
126
 
96
127
  const getStatusCode = () => (res.statusCode ?? 200);
97
128
 
@@ -101,15 +132,15 @@ export function createExpressMiddleware(options: ExpressCacheOptions = {}) {
101
132
  const bodyEtag = etag ? generateETag(body) : undefined;
102
133
  const contentType = res.getHeader?.('content-type') || 'application/json; charset=utf-8';
103
134
 
104
- resolve({ body, contentType, etag: bodyEtag, status });
135
+ settle({ body, contentType, etag: bodyEtag, status });
105
136
 
106
- if (ifNoneMatch && bodyEtag && ifNoneMatch === bodyEtag) {
137
+ if (status >= 200 && status < 300 && ifNoneMatch && bodyEtag && ifNoneMatch === bodyEtag) {
107
138
  res.status?.(304);
108
139
  origEnd?.();
109
140
  return;
110
141
  }
111
142
 
112
- if (bodyEtag && res.setHeader) {
143
+ if (status >= 200 && status < 300 && bodyEtag && res.setHeader) {
113
144
  res.setHeader('ETag', bodyEtag);
114
145
  }
115
146
  return origJson(body);
@@ -122,15 +153,15 @@ export function createExpressMiddleware(options: ExpressCacheOptions = {}) {
122
153
  const bodyEtag = etag ? generateETag(body) : undefined;
123
154
  const contentType = res.getHeader?.('content-type') as string | undefined;
124
155
 
125
- resolve({ body, contentType, etag: bodyEtag, status });
156
+ settle({ body, contentType, etag: bodyEtag, status });
126
157
 
127
- if (ifNoneMatch && bodyEtag && ifNoneMatch === bodyEtag) {
158
+ if (status >= 200 && status < 300 && ifNoneMatch && bodyEtag && ifNoneMatch === bodyEtag) {
128
159
  res.status?.(304);
129
160
  origEnd?.();
130
161
  return;
131
162
  }
132
163
 
133
- if (bodyEtag && res.setHeader) {
164
+ if (status >= 200 && status < 300 && bodyEtag && res.setHeader) {
134
165
  res.setHeader('ETag', bodyEtag);
135
166
  }
136
167
  return origSend(body);
@@ -143,12 +174,20 @@ export function createExpressMiddleware(options: ExpressCacheOptions = {}) {
143
174
  const bodyEtag = etag && body != null ? generateETag(body) : undefined;
144
175
  const contentType = res.getHeader?.('content-type') as string | undefined;
145
176
 
146
- resolve({ body, contentType, etag: bodyEtag, status });
177
+ settle({ body, contentType, etag: bodyEtag, status });
147
178
  return origEnd(body as never);
148
179
  };
149
180
  }
150
181
 
151
- next();
182
+ try {
183
+ next();
184
+ } catch (err) {
185
+ if (!settled) {
186
+ settled = true;
187
+ cleanup();
188
+ reject(err);
189
+ }
190
+ }
152
191
  });
153
192
  },
154
193
  ttl,
@@ -156,13 +195,13 @@ export function createExpressMiddleware(options: ExpressCacheOptions = {}) {
156
195
  );
157
196
 
158
197
  // Status gate: only cache 2xx successful responses
159
- if (typeof cached.status === 'number' && (cached.status < 200 || cached.status >= 300)) {
198
+ const isNon2xx = typeof cached.status === 'number' && (cached.status < 200 || cached.status >= 300);
199
+ if (isNon2xx) {
160
200
  await activeCache.delete(key).catch(() => {});
161
- return;
162
201
  }
163
202
 
164
- if (!res.headersSent) {
165
- if (cached.etag) {
203
+ if (!respondedLocally && !res.headersSent) {
204
+ if (!isNon2xx && cached.etag) {
166
205
  if (res.setHeader) res.setHeader('ETag', cached.etag);
167
206
  if (ifNoneMatch === cached.etag) {
168
207
  return res.status(304).end();
@@ -71,12 +71,8 @@ export function createFastifyPlugin(options: FastifyCacheOptions = {}) {
71
71
  ? (req.headers['if-none-match'] || req.headers['If-None-Match'])
72
72
  : undefined;
73
73
 
74
- // Fast probe in cache
75
- const cached = await activeCache!.get<CachedFastifyResponse | null>(
76
- key,
77
- async () => null,
78
- 0
79
- );
74
+ // Fast probe in cache without writing null entries on misses
75
+ const cached = await activeCache!.peek<CachedFastifyResponse>(key);
80
76
 
81
77
  if (cached && typeof cached === 'object' && cached.body !== null) {
82
78
  if (cached.etag) {
@@ -140,7 +136,7 @@ export function createFastifyPlugin(options: FastifyCacheOptions = {}) {
140
136
 
141
137
  void activeCache!.set(key, entry, mergedOpts.ttl ?? ttl, undefined, {
142
138
  tags: req._tricacheTags,
143
- });
139
+ }).catch(() => {});
144
140
  }
145
141
 
146
142
  return payload;
@@ -111,10 +111,7 @@ export class TriCacheHandler {
111
111
  * and returns a fresh unlocked ReadableStream if the stored value was a stream.
112
112
  */
113
113
  async get(cacheKey: string, ctx?: CacheHandlerContext): Promise<CacheHandlerValue | undefined> {
114
- const stored = await this.cache.get<StoredNextCacheEntry | null>(
115
- cacheKey,
116
- async () => null,
117
- );
114
+ const stored = await this.cache.peek<StoredNextCacheEntry>(cacheKey);
118
115
 
119
116
  if (!stored || stored.data == null) {
120
117
  return undefined;
@@ -38,10 +38,7 @@ export class TriCacheISRHandler {
38
38
  return this.requestCache.get(key) ?? null;
39
39
  }
40
40
 
41
- const stored = await this.cache.get<IncrementalCacheEntry | null>(
42
- key,
43
- async () => null,
44
- );
41
+ const stored = await this.cache.peek<IncrementalCacheEntry>(key);
45
42
 
46
43
  if (stored) {
47
44
  this.requestCache.set(key, stored);
@@ -576,6 +576,7 @@ export class SmartMemoryCache {
576
576
  staleAt?: number,
577
577
  delta?: number,
578
578
  tagVersions?: Record<string, number>,
579
+ setAt?: number,
579
580
  ): void {
580
581
  // Single serialization pass — always msgpackr. Eliminates the prior JSON.stringify
581
582
  // "size probe" that was discarded for large payloads (the double-pass).
@@ -621,7 +622,7 @@ export class SmartMemoryCache {
621
622
  priority,
622
623
  ttlMs,
623
624
  delta,
624
- setAt: now,
625
+ setAt: setAt ?? now,
625
626
  tagVersions,
626
627
  });
627
628
  }
@@ -657,7 +658,7 @@ export class SmartMemoryCache {
657
658
  // buffer AND a potentially much-larger deserialized object simultaneously (double-heap).
658
659
  // For large entries, get() falls back to the unpack() path transparently.
659
660
  const liveValue = size <= LARGE_VALUE_BYTES ? data : undefined;
660
- this.cache.set(key, { data: packed, value: liveValue, isCompressed: true, expiresAt: now + ttlMs, staleAt, size, hits: 1, lastAccess: now, priority, ttlMs, delta, setAt: now, tagVersions });
661
+ this.cache.set(key, { data: packed, value: liveValue, isCompressed: true, expiresAt: now + ttlMs, staleAt, size, hits: 1, lastAccess: now, priority, ttlMs, delta, setAt: setAt ?? now, tagVersions });
661
662
  // Only add new keys to the bloom — overwrites already have their bits set.
662
663
  // Re-adding inflates the insertions counter, delaying trigger-2 phantom detection.
663
664
  if (!existingEntry) this.bloom.add(key);
package/src/types.ts CHANGED
@@ -1198,6 +1198,7 @@ export interface IRedisPipeline {
1198
1198
  sadd(key: string, ...members: string[]): this;
1199
1199
  smembers(key: string): this;
1200
1200
  hset(key: string, value: Record<string, string>): this;
1201
+ hgetall?(key: string): this;
1201
1202
  exec(): Promise<Array<[Error | null, any]> | null>;
1202
1203
  }
1203
1204
 
@@ -1221,6 +1222,7 @@ export interface IRedisDriver {
1221
1222
  scan?(cursor: string, ...args: (string | number)[]): Promise<[string, string[]]>;
1222
1223
  scanStream?(options?: { match?: string; count?: number }): any;
1223
1224
  hset?(key: string, value: Record<string, string>): Promise<unknown>;
1225
+ hgetall?(key: string): Promise<Record<string, string>>;
1224
1226
  publish?(channel: string, message: string): Promise<number>;
1225
1227
  subscribe?(...channels: string[]): Promise<unknown>;
1226
1228
  disconnect(): Promise<void> | void;