tricache 0.7.1 → 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 (102) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +89 -1371
  3. package/dashboards/prometheus-scrape.yml +18 -0
  4. package/dashboards/tricache-alerts.yaml +54 -0
  5. package/dashboards/tricache-grafana.json +548 -0
  6. package/dist/cache-service-DVvroyqA.d.ts +886 -0
  7. package/dist/cache-service-KI5ACF3F.js +12 -0
  8. package/dist/chunk-7RV5ZVBB.js +1023 -0
  9. package/dist/chunk-BQRURGGD.js +60 -0
  10. package/dist/chunk-IITRFWHY.js +196 -0
  11. package/dist/{chunk-X5AXHPVD.js → chunk-LJ5QJB5O.js} +90 -5
  12. package/dist/{chunk-EUGYR7KR.js → chunk-PL5J3ZNT.js} +3184 -514
  13. package/dist/chunk-QNU7B43J.js +687 -0
  14. package/dist/chunk-UGD4VEPD.js +138 -0
  15. package/dist/chunk-XZL45ABR.js +108 -0
  16. package/dist/cli.cjs +3122 -495
  17. package/dist/cli.d.ts +1 -0
  18. package/dist/cli.js +121 -5
  19. package/dist/dashboard/index.cjs +1065 -0
  20. package/dist/dashboard/index.d.ts +183 -0
  21. package/dist/dashboard/index.js +22 -0
  22. package/dist/drizzle/index.cjs +2846 -494
  23. package/dist/drizzle/index.d.ts +3 -1
  24. package/dist/drizzle/index.js +1 -1
  25. package/dist/edge/index.cjs +1559 -0
  26. package/dist/edge/index.d.ts +127 -0
  27. package/dist/edge/index.js +1109 -0
  28. package/dist/hono/index.cjs +7760 -0
  29. package/dist/hono/index.d.ts +91 -0
  30. package/dist/hono/index.js +185 -0
  31. package/dist/hono-VA9A1m0I.d.ts +371 -0
  32. package/dist/http/index.cjs +3281 -587
  33. package/dist/http/index.d.ts +85 -23
  34. package/dist/http/index.js +176 -78
  35. package/dist/index.cjs +7212 -2505
  36. package/dist/index.d.ts +547 -30
  37. package/dist/index.js +104 -5
  38. package/dist/murmur3-CMGw9PbV.d.ts +98 -0
  39. package/dist/nestjs/index.cjs +2787 -487
  40. package/dist/nestjs/index.d.ts +3 -1
  41. package/dist/nestjs/index.js +6 -3
  42. package/dist/next/index.cjs +2804 -501
  43. package/dist/next/index.d.ts +4 -2
  44. package/dist/next/index.js +14 -10
  45. package/dist/prisma/index.d.ts +3 -1
  46. package/dist/serialize-worker.cjs +5 -4
  47. package/dist/serialize-worker.js +1 -1
  48. package/dist/{cache-service-D8tIXmzb.d.ts → types-B_QkVwJ7.d.ts} +622 -662
  49. package/dist/utils-CEsU_Z0s.d.ts +27 -0
  50. package/package.json +48 -10
  51. package/src/adapters/auto-pipeliner.ts +206 -0
  52. package/src/adapters/node-redis.ts +370 -0
  53. package/src/cache-service.ts +1619 -415
  54. package/src/cli.ts +137 -2
  55. package/src/codec.ts +72 -0
  56. package/src/cross-region.ts +245 -0
  57. package/src/dashboard/handler.ts +392 -0
  58. package/src/dashboard/html.ts +594 -0
  59. package/src/dashboard/index.ts +195 -0
  60. package/src/dashboard/types.ts +96 -0
  61. package/src/disk-tier.ts +449 -47
  62. package/src/drizzle/index.ts +86 -86
  63. package/src/edge/adapters/cloudflare-do.ts +130 -0
  64. package/src/edge/adapters/cloudflare-kv.ts +115 -0
  65. package/src/edge/adapters/upstash.ts +143 -0
  66. package/src/edge/cache.ts +797 -0
  67. package/src/edge/crypto.ts +182 -0
  68. package/src/edge/hono.ts +284 -0
  69. package/src/edge/index.ts +37 -0
  70. package/src/edge/types.ts +230 -0
  71. package/src/edge/utils/base64.ts +63 -0
  72. package/src/edge/utils/murmur3.ts +179 -0
  73. package/src/encryption.ts +127 -5
  74. package/src/hono/index.ts +316 -0
  75. package/src/http/express.ts +195 -0
  76. package/src/http/fastify.ts +260 -0
  77. package/src/http/index.ts +44 -258
  78. package/src/http/utils.ts +92 -0
  79. package/src/index.ts +149 -47
  80. package/src/ipc-telemetry.ts +509 -0
  81. package/src/latency-watchdog.ts +282 -0
  82. package/src/nestjs/decorators.ts +161 -161
  83. package/src/nestjs/index.ts +23 -23
  84. package/src/nestjs/tricache.module.ts +104 -104
  85. package/src/nestjs/tricache.store.ts +97 -97
  86. package/src/nestjs/types.ts +79 -79
  87. package/src/next/cache-handler.ts +12 -9
  88. package/src/next/index.ts +37 -37
  89. package/src/next/isr-handler.ts +105 -105
  90. package/src/next/types.ts +130 -130
  91. package/src/remote-snapshot.ts +153 -0
  92. package/src/serialize-worker.ts +120 -120
  93. package/src/sigv4-snapshot-adapter.ts +260 -0
  94. package/src/smart-memory-cache.ts +91 -8
  95. package/src/types.ts +315 -2
  96. package/src/utils/cgroup.ts +100 -0
  97. package/src/utils/tracing.ts +54 -0
  98. package/src/wasm/bloom-filter-wasm.ts +109 -102
  99. package/src/worker-pool.ts +299 -299
  100. package/src/wtiny-lfu.ts +624 -0
  101. package/dist/cache-service-5GATUYAK.js +0 -7
  102. package/dist/chunk-UBSR5UYA.js +0 -0
package/src/cli.ts CHANGED
@@ -2,13 +2,21 @@
2
2
  * TriCache CLI — Developer & Troubleshooting Inspector
3
3
  *
4
4
  * Usage:
5
+ * npx tricache top [--socket <path>] [--pid <pid>] [--interval <ms>] [--once]
5
6
  * npx tricache inspect [--redis redis://localhost:6379] [--namespace <ns>]
6
7
  * npx tricache ping [--redis redis://localhost:6379]
7
8
  * npx tricache clear [--redis redis://localhost:6379] [--namespace <ns>] [--prefix <prefix>]
8
9
  */
9
10
 
11
+ import { readFileSync } from 'node:fs';
10
12
  import { parseArgs } from 'node:util';
11
13
  import { CacheService } from './cache-service.js';
14
+ import {
15
+ IpcTelemetryClient,
16
+ resolveIpcSocketPath,
17
+ findActiveSockets,
18
+ renderTopDashboard,
19
+ } from './ipc-telemetry.js';
12
20
 
13
21
  export async function runCli(args: string[] = process.argv.slice(2)): Promise<void> {
14
22
  const options = {
@@ -17,6 +25,11 @@ export async function runCli(args: string[] = process.argv.slice(2)): Promise<vo
17
25
  namespace: { type: 'string' as const, short: 'n' },
18
26
  prefix: { type: 'string' as const },
19
27
  disk: { type: 'string' as const, short: 'd' },
28
+ pid: { type: 'string' as const },
29
+ socket: { type: 'string' as const, short: 's' },
30
+ interval: { type: 'string' as const, short: 'i' },
31
+ once: { type: 'boolean' as const },
32
+ json: { type: 'boolean' as const },
20
33
  help: { type: 'boolean' as const, short: 'h' },
21
34
  version: { type: 'boolean' as const, short: 'v' },
22
35
  };
@@ -43,8 +56,124 @@ export async function runCli(args: string[] = process.argv.slice(2)): Promise<vo
43
56
  return;
44
57
  }
45
58
 
59
+ // NOTE: console.log is INTENTIONAL across cli.ts — this file is the terminal CLI runner
60
+ // (bin/tricache.js). Output must go directly to process stdout without logger prefixes
61
+ // to support UNIX pipes, terminal formatting, and automated tooling.
46
62
  if (values.version || command === 'version') {
47
- console.log('tricache v0.7.1');
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}`);
71
+ return;
72
+ }
73
+
74
+ // Handle 'top' monitor command directly without constructing a local CacheService
75
+ if (command === 'top') {
76
+ let targetSocket = typeof values.socket === 'string' ? values.socket : undefined;
77
+ if (!targetSocket && typeof values.pid === 'string') {
78
+ targetSocket = resolveIpcSocketPath(values.pid);
79
+ }
80
+ if (!targetSocket) {
81
+ const active = await findActiveSockets();
82
+ if (active.length > 0) {
83
+ targetSocket = active[0];
84
+ }
85
+ }
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
+
98
+ const client = new IpcTelemetryClient(targetSocket);
99
+ const intervalMs = typeof values.interval === 'string'
100
+ ? Math.max(200, parseInt(values.interval, 10))
101
+ : 1000;
102
+ const isOnce = Boolean(values.once || !process.stdout.isTTY);
103
+ const asJson = Boolean(values.json);
104
+
105
+ if (isOnce) {
106
+ try {
107
+ const payload = await client.getMetrics();
108
+ if (asJson) {
109
+ console.log(JSON.stringify(payload, null, 2));
110
+ } else {
111
+ console.log(renderTopDashboard(payload));
112
+ }
113
+ return;
114
+ } catch (err) {
115
+ console.error(`Failed to connect to TriCache IPC at ${targetSocket}: ${(err as Error).message}`);
116
+ process.exit(1);
117
+ }
118
+ }
119
+
120
+ // Interactive TTY mode: switch to alternate screen buffer and hide cursor
121
+ process.stdout.write('\x1b[?1049h\x1b[?25l');
122
+
123
+ let activeInterval: NodeJS.Timeout | null = null;
124
+ let cleaningUp = false;
125
+
126
+ const cleanup = () => {
127
+ if (cleaningUp) return;
128
+ cleaningUp = true;
129
+ if (activeInterval) clearInterval(activeInterval);
130
+ if (process.stdout.isTTY) {
131
+ process.stdout.write('\x1b[?25h\x1b[?1049l');
132
+ }
133
+ if (process.stdin.isTTY && typeof process.stdin.setRawMode === 'function') {
134
+ try {
135
+ process.stdin.setRawMode(false);
136
+ process.stdin.pause();
137
+ } catch {
138
+ // Ignore TTY reset errors
139
+ }
140
+ }
141
+ process.exit(0);
142
+ };
143
+
144
+ process.once('SIGINT', cleanup);
145
+ process.once('SIGTERM', cleanup);
146
+
147
+ if (process.stdin.isTTY && typeof process.stdin.setRawMode === 'function') {
148
+ try {
149
+ process.stdin.setRawMode(true);
150
+ process.stdin.resume();
151
+ process.stdin.setEncoding('utf8');
152
+ process.stdin.on('data', (key: string) => {
153
+ if (key === 'q' || key === 'Q' || key === '\u0003') {
154
+ cleanup();
155
+ }
156
+ });
157
+ } catch {
158
+ // Raw mode not supported
159
+ }
160
+ }
161
+
162
+ const tick = async () => {
163
+ try {
164
+ const payload = await client.getMetrics();
165
+ const screen = renderTopDashboard(payload);
166
+ process.stdout.write('\x1b[H' + screen + '\n Press "q" or Ctrl+C to exit\n');
167
+ } catch (err) {
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`);
169
+ }
170
+ };
171
+
172
+ await tick();
173
+ activeInterval = setInterval(tick, intervalMs);
174
+
175
+ // Keep process alive in interactive loop until exit
176
+ await new Promise<void>(() => {});
48
177
  return;
49
178
  }
50
179
 
@@ -127,15 +256,21 @@ Usage:
127
256
  tricache <command> [options]
128
257
 
129
258
  Commands:
259
+ top Live ASCII terminal dashboard monitoring an active TriCache process
130
260
  inspect Display full dashboard including hit ratios, latencies, and hot keys (default)
131
261
  ping Measure response latency across L1 (RAM), L1.5 (Disk), and L2 (Redis)
132
262
  clear Flush all entries or keys matching a prefix
133
263
 
134
264
  Options:
265
+ -s, --socket <path> IPC socket path or Windows named pipe
266
+ --pid <pid> Process ID of the target TriCache process to monitor
267
+ -i, --interval <ms> Refresh interval in milliseconds for top (default: 1000)
268
+ --once Output single snapshot and exit (non-interactive)
269
+ --json Format output as raw JSON
135
270
  -r, --redis <host|url> Redis connection host or URL (e.g. localhost, redis://127.0.0.1:6379)
136
271
  -p, --port <port> Redis port (default: 6379)
137
272
  -n, --namespace <ns> Cache namespace
138
- --prefix <prefix> Key prefix filter for clear command
273
+ --prefix <prefix> Key prefix filter for clear command
139
274
  -d, --disk <path> Custom disk cache directory path
140
275
  -h, --help Show this help message
141
276
  -v, --version Display version number
package/src/codec.ts ADDED
@@ -0,0 +1,72 @@
1
+ import { Packr, type Options as MsgpackrOptions } from 'msgpackr';
2
+
3
+ /**
4
+ * Configuration options for the TriCache binary codec.
5
+ */
6
+ export interface CacheCodecOptions {
7
+ /**
8
+ * When true (default), objects with a toJSON() method will have toJSON() invoked.
9
+ * When false (msgpackr 2.1.0+), the object's own internal properties are serialized directly,
10
+ * avoiding accidental HTTP response projections on durable cached state.
11
+ */
12
+ useToJSON?: boolean;
13
+ /**
14
+ * Enable msgpackr record structure extension (default: true).
15
+ * Generates compact record definitions that yield 30-50% smaller encodings for repeated object shapes.
16
+ */
17
+ useRecords?: boolean;
18
+ /**
19
+ * Enable serialization of additional built-in types (Map, Set, TypedArray, Error, RegExp).
20
+ * Default: true.
21
+ */
22
+ moreTypes?: boolean;
23
+ /**
24
+ * Decode MessagePack maps as plain JavaScript objects.
25
+ * Default: true (ensures plain JS objects and standard maps decode to plain objects).
26
+ */
27
+ mapsAsObjects?: boolean;
28
+ }
29
+
30
+ /**
31
+ * CacheCodec wraps msgpackr's Packr/Unpackr to provide unified, high-performance binary
32
+ * serialization across L1 in-memory buffers, L1.5 disk spill, and cold-start snapshots.
33
+ */
34
+ export class CacheCodec {
35
+ private readonly packr: Packr;
36
+
37
+ constructor(options?: CacheCodecOptions) {
38
+ const packrOptions: MsgpackrOptions = {
39
+ useToJSON: options?.useToJSON ?? true,
40
+ useRecords: options?.useRecords ?? true,
41
+ moreTypes: options?.moreTypes ?? true,
42
+ mapsAsObjects: options?.mapsAsObjects ?? true,
43
+ };
44
+ this.packr = new Packr(packrOptions);
45
+ }
46
+
47
+ /**
48
+ * Serializes a JavaScript value to a binary MessagePack Buffer.
49
+ */
50
+ encode(data: unknown): Buffer {
51
+ const packed = this.packr.pack(data);
52
+ return Buffer.isBuffer(packed)
53
+ ? packed
54
+ : Buffer.from((packed as Uint8Array).buffer, (packed as Uint8Array).byteOffset, (packed as Uint8Array).byteLength);
55
+ }
56
+
57
+ /**
58
+ * Deserializes a binary MessagePack Buffer or Uint8Array back to a JavaScript value.
59
+ */
60
+ decode<T = unknown>(data: Buffer | Uint8Array): T {
61
+ return this.packr.unpack(data) as T;
62
+ }
63
+ }
64
+
65
+ /**
66
+ * Default singleton codec configured for high-speed packing, record deduplication, and rich types.
67
+ */
68
+ export const defaultCodec = new CacheCodec({
69
+ useToJSON: true,
70
+ useRecords: true,
71
+ moreTypes: true,
72
+ });
@@ -0,0 +1,245 @@
1
+ /**
2
+ * tricache — Multi-Cluster / Geo-Distributed Cross-Region Invalidation Relay
3
+ *
4
+ * Enables multi-region architectures (e.g. us-east-1 + eu-central-1) with independent
5
+ * Redis clusters to synchronize invalidations across regions without expensive
6
+ * active-active Redis Enterprise licenses.
7
+ */
8
+
9
+ export interface CrossRegionInvalidationEvent {
10
+ /** Unique ID of this invalidation event (UUIDv4) */
11
+ id: string;
12
+ /** Region where the invalidation originated, e.g. 'us-east-1' */
13
+ originRegion: string;
14
+ /** Instance ID that initiated the invalidation */
15
+ originInstanceId: string;
16
+ /** Invalidation operation */
17
+ op: 'del' | 'del-glob' | 'tag_incr';
18
+ /** Cache key or tag name */
19
+ key: string;
20
+ /** New tag version for generational tag invalidation */
21
+ tagVersion?: number;
22
+ /** Timestamp when the event was created */
23
+ timestamp: number;
24
+ /** Optional namespace of the origin cache */
25
+ namespace?: string;
26
+ /** Optional W3C traceparent header for distributed context propagation */
27
+ traceparent?: string;
28
+ }
29
+
30
+ export interface ICrossRegionRelay {
31
+ /**
32
+ * Broadcasts an invalidation event across regions (via HTTP mesh, SNS, SQS, EventBridge, or custom bus).
33
+ */
34
+ broadcast(event: CrossRegionInvalidationEvent): Promise<void>;
35
+ }
36
+
37
+ export interface CrossRegionRelayOptions {
38
+ /**
39
+ * Region identifier for this instance, e.g. 'us-east-1' or 'eu-central-1'.
40
+ */
41
+ currentRegion: string;
42
+
43
+ /**
44
+ * Cross-region relay implementation.
45
+ */
46
+ relay: ICrossRegionRelay;
47
+
48
+ /**
49
+ * Optional shared secret or bearer token for authenticating HTTP webhook mesh calls.
50
+ */
51
+ authSecret?: string;
52
+
53
+ /**
54
+ * Max entries stored in the deduplication cache for preventing invalidation loop echoes.
55
+ * Default: 10,000.
56
+ */
57
+ dedupCacheSize?: number;
58
+
59
+ /**
60
+ * Whether writes via `set()` should also broadcast cross-region.
61
+ * Default: `false` (only explicit invalidations `delete()`, `deletePattern()`,
62
+ * and `invalidateTag()` broadcast cross-region, avoiding inter-region thrashing
63
+ * when independent caches populate from local databases).
64
+ */
65
+ broadcastOnSet?: boolean;
66
+ }
67
+
68
+ export interface HttpMeshRelayOptions {
69
+ /**
70
+ * Array of peer regional webhook endpoints (e.g. ['https://eu.internal.api/cache/invalidation']).
71
+ */
72
+ peerUrls: string[];
73
+
74
+ /**
75
+ * Optional authentication secret sent in the `Authorization: Bearer <secret>` header.
76
+ */
77
+ authSecret?: string;
78
+
79
+ /**
80
+ * Request timeout in milliseconds for each peer. Default: 3000 ms.
81
+ */
82
+ timeoutMs?: number;
83
+
84
+ /**
85
+ * Optional fetch implementation (defaults to globalThis.fetch).
86
+ */
87
+ fetchFn?: typeof fetch;
88
+ }
89
+
90
+ /**
91
+ * Creates an HTTP-based peer mesh relay using native Node 22 `fetch()`.
92
+ * Broadcasts events concurrently to all configured peer URLs.
93
+ */
94
+ export function createHttpMeshRelay(options: HttpMeshRelayOptions): ICrossRegionRelay {
95
+ const peerUrls = options.peerUrls;
96
+ const timeoutMs = options.timeoutMs ?? 3000;
97
+ const fetcher = options.fetchFn ?? globalThis.fetch;
98
+ const headers: Record<string, string> = {
99
+ 'Content-Type': 'application/json',
100
+ };
101
+
102
+ if (options.authSecret) {
103
+ headers['Authorization'] = `Bearer ${options.authSecret}`;
104
+ headers['X-TriCache-Auth'] = options.authSecret;
105
+ }
106
+
107
+ return {
108
+ async broadcast(event: CrossRegionInvalidationEvent): Promise<void> {
109
+ if (!peerUrls.length) return;
110
+
111
+ const body = JSON.stringify(event);
112
+ await Promise.allSettled(
113
+ peerUrls.map(async (url) => {
114
+ const res = await fetcher(url, {
115
+ method: 'POST',
116
+ headers,
117
+ body,
118
+ signal: AbortSignal.timeout(timeoutMs),
119
+ });
120
+ if (!res.ok) {
121
+ throw new Error(`HttpMeshRelay: peer ${url} returned HTTP ${res.status} ${res.statusText}`);
122
+ }
123
+ }),
124
+ );
125
+ },
126
+ };
127
+ }
128
+
129
+ /**
130
+ * Type-checking helper for custom cross-region relays (AWS SNS/SQS, EventBridge, Kafka, NATS).
131
+ */
132
+ export function createCustomCrossRegionRelay(relay: ICrossRegionRelay): ICrossRegionRelay {
133
+ return relay;
134
+ }
135
+
136
+ /**
137
+ * In-memory cross-region mesh bus designed for unit testing and multi-region simulations.
138
+ */
139
+ export function createMemoryCrossRegionRelay(): ICrossRegionRelay & {
140
+ register(region: string, handler: (event: CrossRegionInvalidationEvent) => Promise<unknown> | unknown): () => void;
141
+ getBroadcastCount(): number;
142
+ clear(): void;
143
+ } {
144
+ const handlers = new Map<string, Set<(event: CrossRegionInvalidationEvent) => Promise<unknown> | unknown>>();
145
+ let broadcastCount = 0;
146
+
147
+ return {
148
+ async broadcast(event: CrossRegionInvalidationEvent): Promise<void> {
149
+ broadcastCount++;
150
+ const promises: Promise<unknown>[] = [];
151
+ for (const [region, set] of handlers.entries()) {
152
+ // Only deliver to handlers in DIFFERENT regions
153
+ if (region !== event.originRegion) {
154
+ for (const fn of set) {
155
+ promises.push(Promise.resolve(fn(event)));
156
+ }
157
+ }
158
+ }
159
+ await Promise.allSettled(promises);
160
+ },
161
+
162
+ register(region: string, handler: (event: CrossRegionInvalidationEvent) => Promise<unknown> | unknown): () => void {
163
+ if (!handlers.has(region)) {
164
+ handlers.set(region, new Set());
165
+ }
166
+ handlers.get(region)!.add(handler);
167
+ return () => {
168
+ handlers.get(region)?.delete(handler);
169
+ };
170
+ },
171
+
172
+ getBroadcastCount(): number {
173
+ return broadcastCount;
174
+ },
175
+
176
+ clear(): void {
177
+ handlers.clear();
178
+ broadcastCount = 0;
179
+ },
180
+ };
181
+ }
182
+
183
+ export interface WebhookRequestLike {
184
+ headers: Record<string, string | string[] | undefined>;
185
+ body: unknown;
186
+ }
187
+
188
+ export interface WebhookResponseLike {
189
+ status: number;
190
+ body: { ok: boolean; message?: string };
191
+ }
192
+
193
+ /**
194
+ * Creates a generic webhook handler to receive incoming cross-region invalidation requests.
195
+ * Compatible with Express, Fastify, Next.js route handlers, or Node's `http.createServer`.
196
+ */
197
+ export function createCrossRegionWebhookHandler(
198
+ cache: { receiveCrossRegionInvalidation(event: CrossRegionInvalidationEvent): Promise<boolean> | boolean },
199
+ options: { authSecret?: string } = {},
200
+ ) {
201
+ return async function handleCrossRegionWebhook(req: WebhookRequestLike): Promise<WebhookResponseLike> {
202
+ if (options.authSecret) {
203
+ const authHeader = req.headers['authorization'] ?? req.headers['Authorization'];
204
+ const customHeader = req.headers['x-tricache-auth'] ?? req.headers['X-TriCache-Auth'];
205
+
206
+ const bearer = typeof authHeader === 'string' && authHeader.startsWith('Bearer ')
207
+ ? authHeader.slice(7).trim()
208
+ : authHeader;
209
+
210
+ const provided = (typeof customHeader === 'string' ? customHeader : bearer);
211
+
212
+ if (!provided || provided !== options.authSecret) {
213
+ return {
214
+ status: 401,
215
+ body: { ok: false, message: 'Unauthorized: invalid or missing auth secret' },
216
+ };
217
+ }
218
+ }
219
+
220
+ try {
221
+ let event: CrossRegionInvalidationEvent;
222
+ if (typeof req.body === 'string') {
223
+ event = JSON.parse(req.body) as CrossRegionInvalidationEvent;
224
+ } else if (req.body && typeof req.body === 'object') {
225
+ event = req.body as CrossRegionInvalidationEvent;
226
+ } else {
227
+ return {
228
+ status: 400,
229
+ body: { ok: false, message: 'Invalid payload: body must be JSON object' },
230
+ };
231
+ }
232
+
233
+ const accepted = await cache.receiveCrossRegionInvalidation(event);
234
+ return {
235
+ status: 200,
236
+ body: { ok: true, message: accepted ? 'Invalidation applied' : 'Invalidation ignored (deduplicated or self)' },
237
+ };
238
+ } catch (err) {
239
+ return {
240
+ status: 400,
241
+ body: { ok: false, message: (err as Error).message },
242
+ };
243
+ }
244
+ };
245
+ }