tricache 0.8.0 → 0.9.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 (44) hide show
  1. package/README.md +4 -2
  2. package/dashboards/prometheus-scrape.yml +18 -0
  3. package/dist/{cache-service-CyLdpo77.d.ts → cache-service-DVvroyqA.d.ts} +16 -1
  4. package/dist/{cache-service-5MZXFIGK.js → cache-service-KI5ACF3F.js} +1 -1
  5. package/dist/chunk-BQRURGGD.js +60 -0
  6. package/dist/chunk-IITRFWHY.js +196 -0
  7. package/dist/{chunk-6PQ5MOWR.js → chunk-PL5J3ZNT.js} +370 -81
  8. package/dist/cli.cjs +392 -84
  9. package/dist/cli.js +22 -4
  10. package/dist/dashboard/index.d.ts +2 -2
  11. package/dist/drizzle/index.cjs +350 -81
  12. package/dist/drizzle/index.d.ts +2 -2
  13. package/dist/drizzle/index.js +1 -1
  14. package/dist/edge/index.cjs +99 -38
  15. package/dist/edge/index.d.ts +3 -3
  16. package/dist/edge/index.js +5 -5
  17. package/dist/hono/index.cjs +7760 -0
  18. package/dist/hono/index.d.ts +91 -0
  19. package/dist/hono/index.js +185 -0
  20. package/dist/{hono-DQRS1Xd7.d.ts → hono-VA9A1m0I.d.ts} +3 -2
  21. package/dist/http/index.cjs +449 -119
  22. package/dist/http/index.d.ts +6 -30
  23. package/dist/http/index.js +9 -59
  24. package/dist/index.cjs +370 -81
  25. package/dist/index.d.ts +3 -3
  26. package/dist/index.js +1 -1
  27. package/dist/nestjs/index.cjs +350 -81
  28. package/dist/nestjs/index.d.ts +2 -2
  29. package/dist/nestjs/index.js +1 -1
  30. package/dist/next/index.cjs +350 -81
  31. package/dist/next/index.d.ts +2 -2
  32. package/dist/next/index.js +1 -1
  33. package/dist/prisma/index.d.ts +2 -2
  34. package/dist/{types-B6krw64X.d.ts → types-B_QkVwJ7.d.ts} +23 -0
  35. package/dist/utils-CEsU_Z0s.d.ts +27 -0
  36. package/package.json +16 -6
  37. package/src/cache-service.ts +302 -35
  38. package/src/cli.ts +21 -4
  39. package/src/edge/hono.ts +123 -42
  40. package/src/hono/index.ts +316 -0
  41. package/src/http/index.ts +5 -0
  42. package/src/ipc-telemetry.ts +29 -1
  43. package/src/types.ts +25 -0
  44. package/dist/chunk-ZTSWCFYO.js +0 -135
package/src/cli.ts CHANGED
@@ -8,6 +8,7 @@
8
8
  * npx tricache clear [--redis redis://localhost:6379] [--namespace <ns>] [--prefix <prefix>]
9
9
  */
10
10
 
11
+ import { readFileSync } from 'node:fs';
11
12
  import { parseArgs } from 'node:util';
12
13
  import { CacheService } from './cache-service.js';
13
14
  import {
@@ -59,7 +60,14 @@ export async function runCli(args: string[] = process.argv.slice(2)): Promise<vo
59
60
  // (bin/tricache.js). Output must go directly to process stdout without logger prefixes
60
61
  // to support UNIX pipes, terminal formatting, and automated tooling.
61
62
  if (values.version || command === 'version') {
62
- console.log('tricache v0.8.0');
63
+ let version = '0.9.0';
64
+ try {
65
+ const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
66
+ if (pkg?.version) version = pkg.version;
67
+ } catch {
68
+ // fallback to default version
69
+ }
70
+ console.log(`tricache v${version}`);
63
71
  return;
64
72
  }
65
73
 
@@ -73,11 +81,20 @@ export async function runCli(args: string[] = process.argv.slice(2)): Promise<vo
73
81
  const active = await findActiveSockets();
74
82
  if (active.length > 0) {
75
83
  targetSocket = active[0];
76
- } else {
77
- targetSocket = resolveIpcSocketPath(process.pid);
78
84
  }
79
85
  }
80
86
 
87
+ if (!targetSocket) {
88
+ console.error('No active TriCache instances found to monitor.\n');
89
+ console.error('To use `tricache top`:');
90
+ console.error(' 1. Ensure your running application enables IPC telemetry:');
91
+ console.error(" const cache = new CacheService({ namespace: 'my-app', enableIpc: true, ... });\n");
92
+ console.error(' 2. If the application is already running, specify its PID or socket:');
93
+ console.error(' npx tricache top --pid <pid>');
94
+ console.error(' npx tricache top --socket <path>\n');
95
+ process.exit(1);
96
+ }
97
+
81
98
  const client = new IpcTelemetryClient(targetSocket);
82
99
  const intervalMs = typeof values.interval === 'string'
83
100
  ? Math.max(200, parseInt(values.interval, 10))
@@ -148,7 +165,7 @@ export async function runCli(args: string[] = process.argv.slice(2)): Promise<vo
148
165
  const screen = renderTopDashboard(payload);
149
166
  process.stdout.write('\x1b[H' + screen + '\n Press "q" or Ctrl+C to exit\n');
150
167
  } catch (err) {
151
- process.stdout.write(`\x1b[HConnecting to ${targetSocket}...\nError: ${(err as Error).message}\n`);
168
+ process.stdout.write(`\x1b[HConnecting to ${targetSocket}...\nError: ${(err as Error).message}\n\nWaiting for TriCache IPC server. Ensure the target process is running with enableIpc: true.\nPress "q" or Ctrl+C to exit\n`);
152
169
  }
153
170
  };
154
171
 
package/src/edge/hono.ts CHANGED
@@ -22,6 +22,7 @@ export interface HonoEdgeCacheOptions {
22
22
  export interface CachedEdgeHttpResponse {
23
23
  body: string;
24
24
  contentType: string;
25
+ headers?: Record<string, string>;
25
26
  etag?: string;
26
27
  status: number;
27
28
  }
@@ -95,6 +96,14 @@ export function buildEdgeDeterministicKey(c: any, options?: { keyGenerator?: (c:
95
96
  return key;
96
97
  }
97
98
 
99
+ class NonCacheableEdgeResponseError extends Error {
100
+ readonly isNonCacheable = true;
101
+ constructor(readonly response: CachedEdgeHttpResponse) {
102
+ super(`Non-cacheable status: ${response.status}`);
103
+ this.name = 'NonCacheableEdgeResponseError';
104
+ }
105
+ }
106
+
98
107
  /**
99
108
  * Pure Web Standards Hono middleware for V8 Edge Isolates (Cloudflare Workers, Fastly, Vercel Edge).
100
109
  *
@@ -150,54 +159,126 @@ export function honoEdgeCache(options: HonoEdgeCacheOptions = {}) {
150
159
  const ifNoneMatch = c.req.header?.('if-none-match') || c.req.header?.('If-None-Match');
151
160
  const resolvedTags = typeof tags === 'function' ? tags(c) : tags;
152
161
 
153
- const cached = await cache.get(
154
- key,
155
- async () => {
156
- await next();
157
- const res = c.res;
158
- if (!res) {
159
- return null;
162
+ let ranNext = false;
163
+ try {
164
+ const cached = await cache.get(
165
+ key,
166
+ async () => {
167
+ ranNext = true;
168
+ await next();
169
+ const res = c.res;
170
+ if (!res) {
171
+ return null;
172
+ }
173
+
174
+ const contentType = res.headers?.get?.('content-type') || 'text/plain; charset=utf-8';
175
+ if (contentType.toLowerCase().includes('text/event-stream')) {
176
+ throw new NonCacheableEdgeResponseError({
177
+ body: '',
178
+ contentType,
179
+ status: 0,
180
+ });
181
+ }
182
+
183
+ const cc = res.headers?.get?.('cache-control');
184
+ if (cc) {
185
+ const lowerCc = cc.toLowerCase();
186
+ if (lowerCc.includes('no-store') || lowerCc.includes('no-cache') || lowerCc.includes('private')) {
187
+ throw new NonCacheableEdgeResponseError({
188
+ body: '',
189
+ contentType,
190
+ status: 0,
191
+ });
192
+ }
193
+ }
194
+
195
+ const statusCode = res.status ?? 200;
196
+ if (statusCode < 200 || statusCode >= 300 || statusCode === 206) {
197
+ throw new NonCacheableEdgeResponseError({
198
+ body: '',
199
+ contentType,
200
+ status: statusCode,
201
+ });
202
+ }
203
+
204
+ const clone = res.clone();
205
+ const text = await clone.text();
206
+ const bodyEtag = etag ? await computeEdgeETag(text) : undefined;
207
+
208
+ const capturedHeaders: Record<string, string> = {};
209
+ if (res.headers && typeof res.headers.forEach === 'function') {
210
+ res.headers.forEach((value: string, name: string) => {
211
+ const lower = name.toLowerCase();
212
+ if (
213
+ lower !== 'content-length' &&
214
+ lower !== 'transfer-encoding' &&
215
+ lower !== 'connection' &&
216
+ lower !== 'etag' &&
217
+ lower !== 'content-type'
218
+ ) {
219
+ capturedHeaders[name] = value;
220
+ }
221
+ });
222
+ }
223
+
224
+ const snapshot: CachedEdgeHttpResponse = {
225
+ body: text,
226
+ contentType,
227
+ headers: capturedHeaders,
228
+ etag: bodyEtag,
229
+ status: statusCode,
230
+ };
231
+
232
+ return snapshot;
233
+ },
234
+ ttl,
235
+ {
236
+ swr,
237
+ tags: resolvedTags,
238
+ ctx: c.executionCtx,
160
239
  }
240
+ );
161
241
 
162
- const clone = res.clone();
163
- const text = await clone.text();
164
- const statusCode = res.status ?? 200;
165
- const bodyEtag = etag ? await computeEdgeETag(text) : undefined;
166
- const contentType = res.headers.get('content-type') || 'text/plain; charset=utf-8';
167
-
168
- return {
169
- body: text,
170
- contentType,
171
- etag: bodyEtag,
172
- status: statusCode,
173
- };
174
- },
175
- ttl,
176
- {
177
- swr,
178
- tags: resolvedTags,
179
- ctx: c.executionCtx,
242
+ if (!cached) {
243
+ return;
180
244
  }
181
- );
182
245
 
183
- if (!cached) {
184
- return;
185
- }
246
+ if (cached.etag && ifNoneMatch === cached.etag) {
247
+ const notModifiedHeaders: Record<string, string> = { ETag: cached.etag };
248
+ if (cached.headers?.['cache-control']) notModifiedHeaders['Cache-Control'] = cached.headers['cache-control'];
249
+ if (cached.headers?.['vary']) notModifiedHeaders['Vary'] = cached.headers['vary'];
250
+ return applyEdgeResponse(c, null, 304, notModifiedHeaders);
251
+ }
186
252
 
187
- // Status gate: never cache error responses
188
- if (typeof cached.status === 'number' && (cached.status < 200 || cached.status >= 300)) {
189
- await cache.delete?.(key);
190
- return;
191
- }
253
+ const headers: Record<string, string> = { ...cached.headers };
254
+ if (cached.etag) headers['ETag'] = cached.etag;
255
+ if (cached.contentType) headers['Content-Type'] = cached.contentType;
192
256
 
193
- if (cached.etag && ifNoneMatch === cached.etag) {
194
- return c.body(null, 304, { ETag: cached.etag });
257
+ return applyEdgeResponse(c, cached.body, cached.status ?? 200, headers);
258
+ } catch (err: unknown) {
259
+ if (err instanceof NonCacheableEdgeResponseError) {
260
+ if (!ranNext) {
261
+ return await next();
262
+ }
263
+ return;
264
+ }
265
+ throw err;
195
266
  }
196
-
197
- const headers: Record<string, string> = {};
198
- if (cached.etag) headers['ETag'] = cached.etag;
199
- if (cached.contentType) headers['Content-Type'] = cached.contentType;
200
-
201
- return c.body(cached.body, cached.status ?? 200, headers);
202
267
  };
203
268
  }
269
+
270
+ /**
271
+ * Hono's `compose` ignores a middleware return value once `next()` has set
272
+ * `c.res` (`finalized === true`). Assigning `c.res` replaces the downstream
273
+ * body so weak ETags and 304s are visible on both cache miss and hit.
274
+ */
275
+ function applyEdgeResponse(
276
+ c: any,
277
+ body: string | null,
278
+ status: number,
279
+ headers: Record<string, string>,
280
+ ): Response {
281
+ const response = c.body(body, status, headers);
282
+ c.res = response;
283
+ return response;
284
+ }
@@ -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 {
@@ -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
 
package/src/types.ts CHANGED
@@ -675,6 +675,25 @@ export interface CacheOptions {
675
675
  */
676
676
  useShardedPubSub?: boolean;
677
677
 
678
+ /**
679
+ * If true, await backplane invalidation broadcasts during delete(), set(),
680
+ * clear(), and invalidateTag() operations rather than firing them in the background.
681
+ * Guarantees that remote cluster nodes receive the invalidation before the
682
+ * operation resolves to the caller.
683
+ *
684
+ * Default: `false` (asynchronous fire-and-forget for minimal caller latency).
685
+ */
686
+ awaitInvalidationBackplane?: boolean;
687
+
688
+ /**
689
+ * If `true`, `cache.lock()` operations fail closed (throw an Error) if Redis
690
+ * encounters a connection or runtime error during lock acquisition, preventing
691
+ * split-brain concurrent execution across multiple cluster nodes.
692
+ *
693
+ * Default: `false` (falls back to local in-process mutex with a debug log).
694
+ */
695
+ lockFailClosed?: boolean;
696
+
678
697
  // ── Multi-Region / Cross-Cluster Invalidation Relay ─────────────────────
679
698
  /**
680
699
  * Optional cross-region invalidation relay configuration for geo-distributed deployments.
@@ -1097,6 +1116,12 @@ export interface LockOptions {
1097
1116
  * Default: `100` ms.
1098
1117
  */
1099
1118
  retryInterval?: number;
1119
+ /**
1120
+ * If `true`, lock acquisition will throw an error immediately if Redis encounters a
1121
+ * connection or operational error rather than falling back to an in-process mutex.
1122
+ * Overrides `CacheOptions.lockFailClosed`.
1123
+ */
1124
+ failClosedOnRedisError?: boolean;
1100
1125
  }
1101
1126
 
1102
1127
  /**