tricache 0.7.1 → 0.8.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.
- package/LICENSE +21 -21
- package/README.md +87 -1371
- package/dashboards/tricache-alerts.yaml +54 -0
- package/dashboards/tricache-grafana.json +548 -0
- package/dist/cache-service-5MZXFIGK.js +12 -0
- package/dist/cache-service-CyLdpo77.d.ts +871 -0
- package/dist/{chunk-EUGYR7KR.js → chunk-6PQ5MOWR.js} +2871 -490
- package/dist/chunk-7RV5ZVBB.js +1023 -0
- package/dist/{chunk-X5AXHPVD.js → chunk-LJ5QJB5O.js} +90 -5
- package/dist/chunk-QNU7B43J.js +687 -0
- package/dist/chunk-UGD4VEPD.js +138 -0
- package/dist/chunk-XZL45ABR.js +108 -0
- package/dist/chunk-ZTSWCFYO.js +135 -0
- package/dist/cli.cjs +2790 -471
- package/dist/cli.d.ts +1 -0
- package/dist/cli.js +103 -5
- package/dist/dashboard/index.cjs +1065 -0
- package/dist/dashboard/index.d.ts +183 -0
- package/dist/dashboard/index.js +22 -0
- package/dist/drizzle/index.cjs +2553 -470
- package/dist/drizzle/index.d.ts +3 -1
- package/dist/drizzle/index.js +1 -1
- package/dist/edge/index.cjs +1498 -0
- package/dist/edge/index.d.ts +127 -0
- package/dist/edge/index.js +1109 -0
- package/dist/hono-DQRS1Xd7.d.ts +370 -0
- package/dist/http/index.cjs +2926 -562
- package/dist/http/index.d.ts +109 -23
- package/dist/http/index.js +220 -72
- package/dist/index.cjs +6936 -2518
- package/dist/index.d.ts +547 -30
- package/dist/index.js +104 -5
- package/dist/murmur3-CMGw9PbV.d.ts +98 -0
- package/dist/nestjs/index.cjs +2494 -463
- package/dist/nestjs/index.d.ts +3 -1
- package/dist/nestjs/index.js +6 -3
- package/dist/next/index.cjs +2517 -483
- package/dist/next/index.d.ts +4 -2
- package/dist/next/index.js +14 -10
- package/dist/prisma/index.d.ts +3 -1
- package/dist/serialize-worker.cjs +5 -4
- package/dist/serialize-worker.js +1 -1
- package/dist/{cache-service-D8tIXmzb.d.ts → types-B6krw64X.d.ts} +596 -659
- package/package.json +34 -6
- package/src/adapters/auto-pipeliner.ts +206 -0
- package/src/adapters/node-redis.ts +370 -0
- package/src/cache-service.ts +1339 -402
- package/src/cli.ts +120 -2
- package/src/codec.ts +72 -0
- package/src/cross-region.ts +245 -0
- package/src/dashboard/handler.ts +392 -0
- package/src/dashboard/html.ts +594 -0
- package/src/dashboard/index.ts +195 -0
- package/src/dashboard/types.ts +96 -0
- package/src/disk-tier.ts +449 -47
- package/src/drizzle/index.ts +86 -86
- package/src/edge/adapters/cloudflare-do.ts +130 -0
- package/src/edge/adapters/cloudflare-kv.ts +115 -0
- package/src/edge/adapters/upstash.ts +143 -0
- package/src/edge/cache.ts +797 -0
- package/src/edge/crypto.ts +182 -0
- package/src/edge/hono.ts +203 -0
- package/src/edge/index.ts +37 -0
- package/src/edge/types.ts +230 -0
- package/src/edge/utils/base64.ts +63 -0
- package/src/edge/utils/murmur3.ts +179 -0
- package/src/encryption.ts +127 -5
- package/src/http/express.ts +195 -0
- package/src/http/fastify.ts +260 -0
- package/src/http/index.ts +39 -258
- package/src/http/utils.ts +92 -0
- package/src/index.ts +149 -47
- package/src/ipc-telemetry.ts +481 -0
- package/src/latency-watchdog.ts +282 -0
- package/src/nestjs/decorators.ts +161 -161
- package/src/nestjs/index.ts +23 -23
- package/src/nestjs/tricache.module.ts +104 -104
- package/src/nestjs/tricache.store.ts +97 -97
- package/src/nestjs/types.ts +79 -79
- package/src/next/cache-handler.ts +12 -9
- package/src/next/index.ts +37 -37
- package/src/next/isr-handler.ts +105 -105
- package/src/next/types.ts +130 -130
- package/src/remote-snapshot.ts +153 -0
- package/src/serialize-worker.ts +120 -120
- package/src/sigv4-snapshot-adapter.ts +260 -0
- package/src/smart-memory-cache.ts +91 -8
- package/src/types.ts +290 -2
- package/src/utils/cgroup.ts +100 -0
- package/src/utils/tracing.ts +54 -0
- package/src/wasm/bloom-filter-wasm.ts +109 -102
- package/src/worker-pool.ts +299 -299
- package/src/wtiny-lfu.ts +624 -0
- package/dist/cache-service-5GATUYAK.js +0 -7
- package/dist/chunk-UBSR5UYA.js +0 -0
package/src/cli.ts
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
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>]
|
|
@@ -9,6 +10,12 @@
|
|
|
9
10
|
|
|
10
11
|
import { parseArgs } from 'node:util';
|
|
11
12
|
import { CacheService } from './cache-service.js';
|
|
13
|
+
import {
|
|
14
|
+
IpcTelemetryClient,
|
|
15
|
+
resolveIpcSocketPath,
|
|
16
|
+
findActiveSockets,
|
|
17
|
+
renderTopDashboard,
|
|
18
|
+
} from './ipc-telemetry.js';
|
|
12
19
|
|
|
13
20
|
export async function runCli(args: string[] = process.argv.slice(2)): Promise<void> {
|
|
14
21
|
const options = {
|
|
@@ -17,6 +24,11 @@ export async function runCli(args: string[] = process.argv.slice(2)): Promise<vo
|
|
|
17
24
|
namespace: { type: 'string' as const, short: 'n' },
|
|
18
25
|
prefix: { type: 'string' as const },
|
|
19
26
|
disk: { type: 'string' as const, short: 'd' },
|
|
27
|
+
pid: { type: 'string' as const },
|
|
28
|
+
socket: { type: 'string' as const, short: 's' },
|
|
29
|
+
interval: { type: 'string' as const, short: 'i' },
|
|
30
|
+
once: { type: 'boolean' as const },
|
|
31
|
+
json: { type: 'boolean' as const },
|
|
20
32
|
help: { type: 'boolean' as const, short: 'h' },
|
|
21
33
|
version: { type: 'boolean' as const, short: 'v' },
|
|
22
34
|
};
|
|
@@ -43,8 +55,108 @@ export async function runCli(args: string[] = process.argv.slice(2)): Promise<vo
|
|
|
43
55
|
return;
|
|
44
56
|
}
|
|
45
57
|
|
|
58
|
+
// NOTE: console.log is INTENTIONAL across cli.ts — this file is the terminal CLI runner
|
|
59
|
+
// (bin/tricache.js). Output must go directly to process stdout without logger prefixes
|
|
60
|
+
// to support UNIX pipes, terminal formatting, and automated tooling.
|
|
46
61
|
if (values.version || command === 'version') {
|
|
47
|
-
console.log('tricache v0.
|
|
62
|
+
console.log('tricache v0.8.0');
|
|
63
|
+
return;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// Handle 'top' monitor command directly without constructing a local CacheService
|
|
67
|
+
if (command === 'top') {
|
|
68
|
+
let targetSocket = typeof values.socket === 'string' ? values.socket : undefined;
|
|
69
|
+
if (!targetSocket && typeof values.pid === 'string') {
|
|
70
|
+
targetSocket = resolveIpcSocketPath(values.pid);
|
|
71
|
+
}
|
|
72
|
+
if (!targetSocket) {
|
|
73
|
+
const active = await findActiveSockets();
|
|
74
|
+
if (active.length > 0) {
|
|
75
|
+
targetSocket = active[0];
|
|
76
|
+
} else {
|
|
77
|
+
targetSocket = resolveIpcSocketPath(process.pid);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
const client = new IpcTelemetryClient(targetSocket);
|
|
82
|
+
const intervalMs = typeof values.interval === 'string'
|
|
83
|
+
? Math.max(200, parseInt(values.interval, 10))
|
|
84
|
+
: 1000;
|
|
85
|
+
const isOnce = Boolean(values.once || !process.stdout.isTTY);
|
|
86
|
+
const asJson = Boolean(values.json);
|
|
87
|
+
|
|
88
|
+
if (isOnce) {
|
|
89
|
+
try {
|
|
90
|
+
const payload = await client.getMetrics();
|
|
91
|
+
if (asJson) {
|
|
92
|
+
console.log(JSON.stringify(payload, null, 2));
|
|
93
|
+
} else {
|
|
94
|
+
console.log(renderTopDashboard(payload));
|
|
95
|
+
}
|
|
96
|
+
return;
|
|
97
|
+
} catch (err) {
|
|
98
|
+
console.error(`Failed to connect to TriCache IPC at ${targetSocket}: ${(err as Error).message}`);
|
|
99
|
+
process.exit(1);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
// Interactive TTY mode: switch to alternate screen buffer and hide cursor
|
|
104
|
+
process.stdout.write('\x1b[?1049h\x1b[?25l');
|
|
105
|
+
|
|
106
|
+
let activeInterval: NodeJS.Timeout | null = null;
|
|
107
|
+
let cleaningUp = false;
|
|
108
|
+
|
|
109
|
+
const cleanup = () => {
|
|
110
|
+
if (cleaningUp) return;
|
|
111
|
+
cleaningUp = true;
|
|
112
|
+
if (activeInterval) clearInterval(activeInterval);
|
|
113
|
+
if (process.stdout.isTTY) {
|
|
114
|
+
process.stdout.write('\x1b[?25h\x1b[?1049l');
|
|
115
|
+
}
|
|
116
|
+
if (process.stdin.isTTY && typeof process.stdin.setRawMode === 'function') {
|
|
117
|
+
try {
|
|
118
|
+
process.stdin.setRawMode(false);
|
|
119
|
+
process.stdin.pause();
|
|
120
|
+
} catch {
|
|
121
|
+
// Ignore TTY reset errors
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
process.exit(0);
|
|
125
|
+
};
|
|
126
|
+
|
|
127
|
+
process.once('SIGINT', cleanup);
|
|
128
|
+
process.once('SIGTERM', cleanup);
|
|
129
|
+
|
|
130
|
+
if (process.stdin.isTTY && typeof process.stdin.setRawMode === 'function') {
|
|
131
|
+
try {
|
|
132
|
+
process.stdin.setRawMode(true);
|
|
133
|
+
process.stdin.resume();
|
|
134
|
+
process.stdin.setEncoding('utf8');
|
|
135
|
+
process.stdin.on('data', (key: string) => {
|
|
136
|
+
if (key === 'q' || key === 'Q' || key === '\u0003') {
|
|
137
|
+
cleanup();
|
|
138
|
+
}
|
|
139
|
+
});
|
|
140
|
+
} catch {
|
|
141
|
+
// Raw mode not supported
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
const tick = async () => {
|
|
146
|
+
try {
|
|
147
|
+
const payload = await client.getMetrics();
|
|
148
|
+
const screen = renderTopDashboard(payload);
|
|
149
|
+
process.stdout.write('\x1b[H' + screen + '\n Press "q" or Ctrl+C to exit\n');
|
|
150
|
+
} catch (err) {
|
|
151
|
+
process.stdout.write(`\x1b[HConnecting to ${targetSocket}...\nError: ${(err as Error).message}\n`);
|
|
152
|
+
}
|
|
153
|
+
};
|
|
154
|
+
|
|
155
|
+
await tick();
|
|
156
|
+
activeInterval = setInterval(tick, intervalMs);
|
|
157
|
+
|
|
158
|
+
// Keep process alive in interactive loop until exit
|
|
159
|
+
await new Promise<void>(() => {});
|
|
48
160
|
return;
|
|
49
161
|
}
|
|
50
162
|
|
|
@@ -127,15 +239,21 @@ Usage:
|
|
|
127
239
|
tricache <command> [options]
|
|
128
240
|
|
|
129
241
|
Commands:
|
|
242
|
+
top Live ASCII terminal dashboard monitoring an active TriCache process
|
|
130
243
|
inspect Display full dashboard including hit ratios, latencies, and hot keys (default)
|
|
131
244
|
ping Measure response latency across L1 (RAM), L1.5 (Disk), and L2 (Redis)
|
|
132
245
|
clear Flush all entries or keys matching a prefix
|
|
133
246
|
|
|
134
247
|
Options:
|
|
248
|
+
-s, --socket <path> IPC socket path or Windows named pipe
|
|
249
|
+
--pid <pid> Process ID of the target TriCache process to monitor
|
|
250
|
+
-i, --interval <ms> Refresh interval in milliseconds for top (default: 1000)
|
|
251
|
+
--once Output single snapshot and exit (non-interactive)
|
|
252
|
+
--json Format output as raw JSON
|
|
135
253
|
-r, --redis <host|url> Redis connection host or URL (e.g. localhost, redis://127.0.0.1:6379)
|
|
136
254
|
-p, --port <port> Redis port (default: 6379)
|
|
137
255
|
-n, --namespace <ns> Cache namespace
|
|
138
|
-
|
|
256
|
+
--prefix <prefix> Key prefix filter for clear command
|
|
139
257
|
-d, --disk <path> Custom disk cache directory path
|
|
140
258
|
-h, --help Show this help message
|
|
141
259
|
-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
|
+
}
|