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
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* tricache — Remote Blob Storage Cold-Start Hydration
|
|
3
|
+
*
|
|
4
|
+
* Enables stateless containers (Kubernetes, AWS ECS/Fargate, Google Cloud Run, Fly.io)
|
|
5
|
+
* to persist and hydrate L1 cache snapshots from remote object storage (S3, GCS, R2, Azure, MinIO, or HTTP).
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
export interface IRemoteSnapshotAdapter {
|
|
9
|
+
/**
|
|
10
|
+
* Read the latest snapshot blob from remote storage.
|
|
11
|
+
* Returns null if no snapshot exists yet (e.g. 404 Not Found / first deploy).
|
|
12
|
+
*/
|
|
13
|
+
get(): Promise<Buffer | Uint8Array | null>;
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Write the snapshot blob to remote storage.
|
|
17
|
+
*/
|
|
18
|
+
put(data: Buffer): Promise<void>;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
import type { EnvelopeEncryptionOptions } from './encryption';
|
|
22
|
+
|
|
23
|
+
export interface RemoteSnapshotOptions {
|
|
24
|
+
/**
|
|
25
|
+
* Remote storage adapter implementation.
|
|
26
|
+
*/
|
|
27
|
+
adapter: IRemoteSnapshotAdapter;
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Maximum age in milliseconds of a remote snapshot before it is rejected as stale.
|
|
31
|
+
* Default: 2 hours (7,200,000 ms).
|
|
32
|
+
*/
|
|
33
|
+
maxAgeMs?: number;
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Whether to trigger an asynchronous remote snapshot upload during graceful shutdown (SIGTERM/SIGINT).
|
|
37
|
+
* Ensure your container orchestration allows sufficient termination grace period (e.g. >= 10s).
|
|
38
|
+
* Default: true.
|
|
39
|
+
*/
|
|
40
|
+
saveOnShutdown?: boolean;
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Optional periodic background upload interval in milliseconds.
|
|
44
|
+
* Ensures remote snapshots stay fresh even in the event of ungraceful container termination (SIGKILL / OOM / spot eviction).
|
|
45
|
+
* Default: undefined (disabled).
|
|
46
|
+
*/
|
|
47
|
+
intervalMs?: number;
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Optional asymmetric envelope encryption configuration.
|
|
51
|
+
* When configured, snapshot payloads are encrypted with an ephemeral AES-256 DEK wrapped by RSA-OAEP or KMS.
|
|
52
|
+
*/
|
|
53
|
+
envelope?: EnvelopeEncryptionOptions;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export interface HttpSnapshotAdapterOptions {
|
|
57
|
+
/**
|
|
58
|
+
* URL to fetch the snapshot from (e.g. S3 presigned GET URL or internal blob service).
|
|
59
|
+
*/
|
|
60
|
+
getUrl: string;
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* URL to upload the snapshot to via HTTP PUT. If omitted, defaults to `getUrl`.
|
|
64
|
+
*/
|
|
65
|
+
putUrl?: string;
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Optional HTTP headers (e.g. Authorization or custom metadata).
|
|
69
|
+
*/
|
|
70
|
+
headers?: Record<string, string>;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Creates an HTTP-based remote snapshot adapter using standard global `fetch()`.
|
|
75
|
+
* Ideal for S3/R2 presigned URLs, internal storage gateways, or serverless webhooks.
|
|
76
|
+
*/
|
|
77
|
+
export function createHttpSnapshotAdapter(options: HttpSnapshotAdapterOptions): IRemoteSnapshotAdapter {
|
|
78
|
+
const getUrl = options.getUrl;
|
|
79
|
+
const putUrl = options.putUrl ?? getUrl;
|
|
80
|
+
const headers = options.headers ?? {};
|
|
81
|
+
|
|
82
|
+
return {
|
|
83
|
+
async get(): Promise<Buffer | null> {
|
|
84
|
+
const res = await fetch(getUrl, {
|
|
85
|
+
method: 'GET',
|
|
86
|
+
headers,
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
if (res.status === 404) return null;
|
|
90
|
+
if (!res.ok) {
|
|
91
|
+
throw new Error(`HttpSnapshotAdapter: GET failed with status ${res.status} ${res.statusText}`);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
const ab = await res.arrayBuffer();
|
|
95
|
+
return Buffer.from(ab);
|
|
96
|
+
},
|
|
97
|
+
|
|
98
|
+
async put(data: Buffer): Promise<void> {
|
|
99
|
+
const res = await fetch(putUrl, {
|
|
100
|
+
method: 'PUT',
|
|
101
|
+
headers: {
|
|
102
|
+
'Content-Type': 'application/octet-stream',
|
|
103
|
+
...headers,
|
|
104
|
+
},
|
|
105
|
+
body: data as unknown as BodyInit,
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
if (!res.ok) {
|
|
109
|
+
throw new Error(`HttpSnapshotAdapter: PUT failed with status ${res.status} ${res.statusText}`);
|
|
110
|
+
}
|
|
111
|
+
},
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* Helper to define and type-check a custom remote snapshot adapter (e.g. AWS SDK v3, GCS, Azure Blob).
|
|
117
|
+
*/
|
|
118
|
+
export function createCustomSnapshotAdapter(adapter: IRemoteSnapshotAdapter): IRemoteSnapshotAdapter {
|
|
119
|
+
return adapter;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* In-memory snapshot adapter designed for unit testing, CI pipelines, and ephemeral mock environments.
|
|
124
|
+
*/
|
|
125
|
+
export function createMemorySnapshotAdapter(): IRemoteSnapshotAdapter & {
|
|
126
|
+
getBuffer(): Buffer | null;
|
|
127
|
+
clear(): void;
|
|
128
|
+
} {
|
|
129
|
+
let stored: Buffer | null = null;
|
|
130
|
+
|
|
131
|
+
return {
|
|
132
|
+
async get(): Promise<Buffer | null> {
|
|
133
|
+
return stored ? Buffer.from(stored) : null;
|
|
134
|
+
},
|
|
135
|
+
async put(data: Buffer): Promise<void> {
|
|
136
|
+
stored = Buffer.from(data);
|
|
137
|
+
},
|
|
138
|
+
getBuffer(): Buffer | null {
|
|
139
|
+
return stored;
|
|
140
|
+
},
|
|
141
|
+
clear(): void {
|
|
142
|
+
stored = null;
|
|
143
|
+
},
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
export {
|
|
148
|
+
SigV4SnapshotAdapter,
|
|
149
|
+
createSigV4SnapshotAdapter,
|
|
150
|
+
createS3SnapshotAdapter,
|
|
151
|
+
createR2SnapshotAdapter,
|
|
152
|
+
type SigV4SnapshotAdapterOptions,
|
|
153
|
+
} from './sigv4-snapshot-adapter.js';
|
package/src/serialize-worker.ts
CHANGED
|
@@ -1,120 +1,120 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* serialize-worker — worker-thread entry point for off-main-thread encryption/decryption/compression.
|
|
3
|
-
*
|
|
4
|
-
* Receives messages from WorkerPool:
|
|
5
|
-
* { id: number; type: 'encrypt'; payload: string }
|
|
6
|
-
* { id: number; type: 'decrypt'; payload: string }
|
|
7
|
-
*
|
|
8
|
-
* Posts back:
|
|
9
|
-
* { id: number; result: string } — on success
|
|
10
|
-
* { id: number; error: string } — on failure
|
|
11
|
-
*
|
|
12
|
-
* The encryption key and mode are received once via workerData at thread creation,
|
|
13
|
-
* so no key material travels with every per-message IPC call.
|
|
14
|
-
*/
|
|
15
|
-
|
|
16
|
-
import { parentPort, workerData } from 'worker_threads';
|
|
17
|
-
import { CacheEncryption } from './encryption.ts';
|
|
18
|
-
import type { EncryptionMode } from './encryption.ts';
|
|
19
|
-
import type { ILogger } from './types.ts';
|
|
20
|
-
import {
|
|
21
|
-
compressBuffer,
|
|
22
|
-
decompressBuffer,
|
|
23
|
-
PREFIX_COMPRESSED,
|
|
24
|
-
PREFIX_ENC_COMPRESSED,
|
|
25
|
-
type CompressionAlgorithm,
|
|
26
|
-
} from './compression.ts';
|
|
27
|
-
|
|
28
|
-
interface WorkerInit {
|
|
29
|
-
keyBase64: string;
|
|
30
|
-
mode: EncryptionMode;
|
|
31
|
-
prevKeyBase64: string | undefined;
|
|
32
|
-
prevMode: EncryptionMode | undefined;
|
|
33
|
-
compression?: CompressionAlgorithm;
|
|
34
|
-
compressionThresholdBytes?: number;
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
// Minimal no-op logger — worker thread does not log to avoid interleaved I/O.
|
|
38
|
-
const silentLogger: ILogger = {
|
|
39
|
-
debug: () => {},
|
|
40
|
-
info: () => {},
|
|
41
|
-
warn: () => {},
|
|
42
|
-
error: () => {},
|
|
43
|
-
};
|
|
44
|
-
|
|
45
|
-
const { keyBase64, mode, prevKeyBase64, prevMode, compression, compressionThresholdBytes } =
|
|
46
|
-
workerData as WorkerInit;
|
|
47
|
-
|
|
48
|
-
const enc = new CacheEncryption(
|
|
49
|
-
keyBase64 || undefined,
|
|
50
|
-
silentLogger,
|
|
51
|
-
mode,
|
|
52
|
-
prevKeyBase64 || undefined,
|
|
53
|
-
prevMode,
|
|
54
|
-
);
|
|
55
|
-
|
|
56
|
-
const cmpAlgo = compression ?? 'none';
|
|
57
|
-
const cmpThreshold = compressionThresholdBytes ?? 1024;
|
|
58
|
-
|
|
59
|
-
parentPort!.on(
|
|
60
|
-
'message',
|
|
61
|
-
({ id, type, payload }: { id: number; type: 'encrypt' | 'decrypt'; payload: string | Uint8Array }) => {
|
|
62
|
-
try {
|
|
63
|
-
const textPayload =
|
|
64
|
-
typeof payload === 'string'
|
|
65
|
-
? payload
|
|
66
|
-
: Buffer.from(payload.buffer, payload.byteOffset, payload.byteLength).toString('utf8');
|
|
67
|
-
|
|
68
|
-
if (type === 'encrypt') {
|
|
69
|
-
let result: string;
|
|
70
|
-
if (cmpAlgo !== 'none' && textPayload.length > cmpThreshold) {
|
|
71
|
-
const compressed = compressBuffer(Buffer.from(textPayload, 'utf8'), cmpAlgo);
|
|
72
|
-
if (enc.isEnabled) {
|
|
73
|
-
const encrypted = enc.encryptBuffer(compressed);
|
|
74
|
-
result = PREFIX_ENC_COMPRESSED + encrypted.toString('base64');
|
|
75
|
-
} else {
|
|
76
|
-
result = PREFIX_COMPRESSED + compressed.toString('base64');
|
|
77
|
-
}
|
|
78
|
-
} else {
|
|
79
|
-
result = enc.encrypt(textPayload);
|
|
80
|
-
}
|
|
81
|
-
|
|
82
|
-
if (result.length >= 131_072) {
|
|
83
|
-
const outBuf = Buffer.from(result, 'utf8');
|
|
84
|
-
const transferable = new ArrayBuffer(outBuf.byteLength);
|
|
85
|
-
new Uint8Array(transferable).set(outBuf);
|
|
86
|
-
const outputUint8 = new Uint8Array(transferable);
|
|
87
|
-
parentPort!.postMessage({ id, result: outputUint8, isTransfer: true }, [transferable]);
|
|
88
|
-
} else {
|
|
89
|
-
parentPort!.postMessage({ id, result });
|
|
90
|
-
}
|
|
91
|
-
} else {
|
|
92
|
-
let result: string;
|
|
93
|
-
if (textPayload.startsWith(PREFIX_ENC_COMPRESSED)) {
|
|
94
|
-
const rawBuf = Buffer.from(textPayload.slice(PREFIX_ENC_COMPRESSED.length), 'base64');
|
|
95
|
-
const decryptedBuf = enc.decryptBuffer(rawBuf);
|
|
96
|
-
const decompressed = decompressBuffer(decryptedBuf, cmpAlgo !== 'none' ? cmpAlgo : 'brotli');
|
|
97
|
-
result = decompressed.toString('utf8');
|
|
98
|
-
} else if (textPayload.startsWith(PREFIX_COMPRESSED)) {
|
|
99
|
-
const rawBuf = Buffer.from(textPayload.slice(PREFIX_COMPRESSED.length), 'base64');
|
|
100
|
-
const decompressed = decompressBuffer(rawBuf, cmpAlgo !== 'none' ? cmpAlgo : 'brotli');
|
|
101
|
-
result = decompressed.toString('utf8');
|
|
102
|
-
} else {
|
|
103
|
-
result = enc.decrypt(textPayload);
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
if (result.length >= 131_072) {
|
|
107
|
-
const outBuf = Buffer.from(result, 'utf8');
|
|
108
|
-
const transferable = new ArrayBuffer(outBuf.byteLength);
|
|
109
|
-
new Uint8Array(transferable).set(outBuf);
|
|
110
|
-
const outputUint8 = new Uint8Array(transferable);
|
|
111
|
-
parentPort!.postMessage({ id, result: outputUint8, isTransfer: true }, [transferable]);
|
|
112
|
-
} else {
|
|
113
|
-
parentPort!.postMessage({ id, result });
|
|
114
|
-
}
|
|
115
|
-
}
|
|
116
|
-
} catch (e) {
|
|
117
|
-
parentPort!.postMessage({ id, error: (e as Error).message });
|
|
118
|
-
}
|
|
119
|
-
},
|
|
120
|
-
);
|
|
1
|
+
/**
|
|
2
|
+
* serialize-worker — worker-thread entry point for off-main-thread encryption/decryption/compression.
|
|
3
|
+
*
|
|
4
|
+
* Receives messages from WorkerPool:
|
|
5
|
+
* { id: number; type: 'encrypt'; payload: string }
|
|
6
|
+
* { id: number; type: 'decrypt'; payload: string }
|
|
7
|
+
*
|
|
8
|
+
* Posts back:
|
|
9
|
+
* { id: number; result: string } — on success
|
|
10
|
+
* { id: number; error: string } — on failure
|
|
11
|
+
*
|
|
12
|
+
* The encryption key and mode are received once via workerData at thread creation,
|
|
13
|
+
* so no key material travels with every per-message IPC call.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import { parentPort, workerData } from 'worker_threads';
|
|
17
|
+
import { CacheEncryption } from './encryption.ts';
|
|
18
|
+
import type { EncryptionMode } from './encryption.ts';
|
|
19
|
+
import type { ILogger } from './types.ts';
|
|
20
|
+
import {
|
|
21
|
+
compressBuffer,
|
|
22
|
+
decompressBuffer,
|
|
23
|
+
PREFIX_COMPRESSED,
|
|
24
|
+
PREFIX_ENC_COMPRESSED,
|
|
25
|
+
type CompressionAlgorithm,
|
|
26
|
+
} from './compression.ts';
|
|
27
|
+
|
|
28
|
+
interface WorkerInit {
|
|
29
|
+
keyBase64: string;
|
|
30
|
+
mode: EncryptionMode;
|
|
31
|
+
prevKeyBase64: string | undefined;
|
|
32
|
+
prevMode: EncryptionMode | undefined;
|
|
33
|
+
compression?: CompressionAlgorithm;
|
|
34
|
+
compressionThresholdBytes?: number;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
// Minimal no-op logger — worker thread does not log to avoid interleaved I/O.
|
|
38
|
+
const silentLogger: ILogger = {
|
|
39
|
+
debug: () => {},
|
|
40
|
+
info: () => {},
|
|
41
|
+
warn: () => {},
|
|
42
|
+
error: () => {},
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
const { keyBase64, mode, prevKeyBase64, prevMode, compression, compressionThresholdBytes } =
|
|
46
|
+
workerData as WorkerInit;
|
|
47
|
+
|
|
48
|
+
const enc = new CacheEncryption(
|
|
49
|
+
keyBase64 || undefined,
|
|
50
|
+
silentLogger,
|
|
51
|
+
mode,
|
|
52
|
+
prevKeyBase64 || undefined,
|
|
53
|
+
prevMode,
|
|
54
|
+
);
|
|
55
|
+
|
|
56
|
+
const cmpAlgo = compression ?? 'none';
|
|
57
|
+
const cmpThreshold = compressionThresholdBytes ?? 1024;
|
|
58
|
+
|
|
59
|
+
parentPort!.on(
|
|
60
|
+
'message',
|
|
61
|
+
({ id, type, payload }: { id: number; type: 'encrypt' | 'decrypt'; payload: string | Uint8Array }) => {
|
|
62
|
+
try {
|
|
63
|
+
const textPayload =
|
|
64
|
+
typeof payload === 'string'
|
|
65
|
+
? payload
|
|
66
|
+
: Buffer.from(payload.buffer, payload.byteOffset, payload.byteLength).toString('utf8');
|
|
67
|
+
|
|
68
|
+
if (type === 'encrypt') {
|
|
69
|
+
let result: string;
|
|
70
|
+
if (cmpAlgo !== 'none' && textPayload.length > cmpThreshold) {
|
|
71
|
+
const compressed = compressBuffer(Buffer.from(textPayload, 'utf8'), cmpAlgo);
|
|
72
|
+
if (enc.isEnabled) {
|
|
73
|
+
const encrypted = enc.encryptBuffer(compressed);
|
|
74
|
+
result = PREFIX_ENC_COMPRESSED + encrypted.toString('base64');
|
|
75
|
+
} else {
|
|
76
|
+
result = PREFIX_COMPRESSED + compressed.toString('base64');
|
|
77
|
+
}
|
|
78
|
+
} else {
|
|
79
|
+
result = enc.encrypt(textPayload);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
if (result.length >= 131_072) {
|
|
83
|
+
const outBuf = Buffer.from(result, 'utf8');
|
|
84
|
+
const transferable = new ArrayBuffer(outBuf.byteLength);
|
|
85
|
+
new Uint8Array(transferable).set(outBuf);
|
|
86
|
+
const outputUint8 = new Uint8Array(transferable);
|
|
87
|
+
parentPort!.postMessage({ id, result: outputUint8, isTransfer: true }, [transferable]);
|
|
88
|
+
} else {
|
|
89
|
+
parentPort!.postMessage({ id, result });
|
|
90
|
+
}
|
|
91
|
+
} else {
|
|
92
|
+
let result: string;
|
|
93
|
+
if (textPayload.startsWith(PREFIX_ENC_COMPRESSED)) {
|
|
94
|
+
const rawBuf = Buffer.from(textPayload.slice(PREFIX_ENC_COMPRESSED.length), 'base64');
|
|
95
|
+
const decryptedBuf = enc.decryptBuffer(rawBuf);
|
|
96
|
+
const decompressed = decompressBuffer(decryptedBuf, cmpAlgo !== 'none' ? cmpAlgo : 'brotli');
|
|
97
|
+
result = decompressed.toString('utf8');
|
|
98
|
+
} else if (textPayload.startsWith(PREFIX_COMPRESSED)) {
|
|
99
|
+
const rawBuf = Buffer.from(textPayload.slice(PREFIX_COMPRESSED.length), 'base64');
|
|
100
|
+
const decompressed = decompressBuffer(rawBuf, cmpAlgo !== 'none' ? cmpAlgo : 'brotli');
|
|
101
|
+
result = decompressed.toString('utf8');
|
|
102
|
+
} else {
|
|
103
|
+
result = enc.decrypt(textPayload);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
if (result.length >= 131_072) {
|
|
107
|
+
const outBuf = Buffer.from(result, 'utf8');
|
|
108
|
+
const transferable = new ArrayBuffer(outBuf.byteLength);
|
|
109
|
+
new Uint8Array(transferable).set(outBuf);
|
|
110
|
+
const outputUint8 = new Uint8Array(transferable);
|
|
111
|
+
parentPort!.postMessage({ id, result: outputUint8, isTransfer: true }, [transferable]);
|
|
112
|
+
} else {
|
|
113
|
+
parentPort!.postMessage({ id, result });
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
} catch (e) {
|
|
117
|
+
parentPort!.postMessage({ id, error: (e as Error).message });
|
|
118
|
+
}
|
|
119
|
+
},
|
|
120
|
+
);
|
|
@@ -0,0 +1,260 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* tricache — Zero-Dependency AWS SigV4 Snapshot Adapter
|
|
3
|
+
*
|
|
4
|
+
* Provides a lightweight (~150 LOC) AWS SigV4 request signer built purely on the
|
|
5
|
+
* standard Web Crypto API (crypto.subtle) and global fetch.
|
|
6
|
+
*
|
|
7
|
+
* Allows stateless container pods (Kubernetes, AWS ECS, GCP Cloud Run) and Edge workers
|
|
8
|
+
* to persist and hydrate L1 snapshots directly to/from AWS S3, Cloudflare R2, MinIO,
|
|
9
|
+
* or custom S3-compatible object storage WITHOUT pulling in the 30MB @aws-sdk/client-s3.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import type { IRemoteSnapshotAdapter } from './remote-snapshot';
|
|
13
|
+
|
|
14
|
+
export interface SigV4SnapshotAdapterOptions {
|
|
15
|
+
/** S3 or Cloudflare R2 bucket name */
|
|
16
|
+
bucket: string;
|
|
17
|
+
/** Object key / filename for the snapshot (e.g. 'production-l1.snap') */
|
|
18
|
+
key: string;
|
|
19
|
+
/** AWS Region. Default: 'us-east-1' (use 'auto' for Cloudflare R2) */
|
|
20
|
+
region?: string;
|
|
21
|
+
/** Custom endpoint URL (e.g. 'https://<account_id>.r2.cloudflarestorage.com' or 'http://127.0.0.1:9000') */
|
|
22
|
+
endpoint?: string;
|
|
23
|
+
/** AWS Access Key ID. Defaults to process.env.AWS_ACCESS_KEY_ID */
|
|
24
|
+
accessKeyId?: string;
|
|
25
|
+
/** AWS Secret Access Key. Defaults to process.env.AWS_SECRET_ACCESS_KEY */
|
|
26
|
+
secretAccessKey?: string;
|
|
27
|
+
/** Optional AWS Session Token (for temporary IAM/STS credentials). Defaults to process.env.AWS_SESSION_TOKEN */
|
|
28
|
+
sessionToken?: string;
|
|
29
|
+
/** Force path-style URLs (e.g. https://endpoint/bucket/key). Default: true if endpoint is specified, false for AWS S3 */
|
|
30
|
+
forcePathStyle?: boolean;
|
|
31
|
+
/** Custom fetch implementation (defaults to globalThis.fetch) */
|
|
32
|
+
fetch?: typeof globalThis.fetch;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const EMPTY_STRING_SHA256 = 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855';
|
|
36
|
+
|
|
37
|
+
async function sha256Hex(data: ArrayBuffer | Uint8Array | string): Promise<string> {
|
|
38
|
+
const buf = typeof data === 'string' ? new TextEncoder().encode(data) : data;
|
|
39
|
+
const digest = await crypto.subtle.digest('SHA-256', buf as ArrayBuffer);
|
|
40
|
+
return Array.from(new Uint8Array(digest)).map(b => b.toString(16).padStart(2, '0')).join('');
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
async function hmac(key: CryptoKey | ArrayBuffer | Uint8Array, data: string): Promise<ArrayBuffer> {
|
|
44
|
+
let cryptoKey: CryptoKey;
|
|
45
|
+
if (key instanceof CryptoKey) {
|
|
46
|
+
cryptoKey = key;
|
|
47
|
+
} else {
|
|
48
|
+
const rawBuf: ArrayBuffer = key instanceof Uint8Array
|
|
49
|
+
? (key.buffer.slice(key.byteOffset, key.byteOffset + key.byteLength) as ArrayBuffer)
|
|
50
|
+
: (key as ArrayBuffer);
|
|
51
|
+
cryptoKey = await crypto.subtle.importKey(
|
|
52
|
+
'raw',
|
|
53
|
+
rawBuf,
|
|
54
|
+
{ name: 'HMAC', hash: 'SHA-256' },
|
|
55
|
+
false,
|
|
56
|
+
['sign'],
|
|
57
|
+
);
|
|
58
|
+
}
|
|
59
|
+
return await crypto.subtle.sign('HMAC', cryptoKey, new TextEncoder().encode(data));
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function encodeRfc3986(str: string): string {
|
|
63
|
+
return encodeURIComponent(str).replace(/[!'()*]/g, c => `%${c.charCodeAt(0).toString(16).toUpperCase()}`);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function encodePath(path: string): string {
|
|
67
|
+
return path.split('/').map(encodeRfc3986).join('/');
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export class SigV4SnapshotAdapter implements IRemoteSnapshotAdapter {
|
|
71
|
+
private readonly bucket: string;
|
|
72
|
+
private readonly key: string;
|
|
73
|
+
private readonly region: string;
|
|
74
|
+
private readonly endpoint?: string;
|
|
75
|
+
private readonly accessKeyId: string;
|
|
76
|
+
private readonly secretAccessKey: string;
|
|
77
|
+
private readonly sessionToken?: string;
|
|
78
|
+
private readonly forcePathStyle: boolean;
|
|
79
|
+
private readonly fetchImpl: typeof globalThis.fetch;
|
|
80
|
+
|
|
81
|
+
constructor(options: SigV4SnapshotAdapterOptions) {
|
|
82
|
+
this.bucket = options.bucket;
|
|
83
|
+
this.key = options.key.replace(/^\/+/, '');
|
|
84
|
+
this.region = options.region ?? (options.endpoint?.includes('r2.cloudflarestorage.com') ? 'auto' : 'us-east-1');
|
|
85
|
+
this.endpoint = options.endpoint;
|
|
86
|
+
|
|
87
|
+
const accessKey = options.accessKeyId ?? (typeof process !== 'undefined' ? process.env?.AWS_ACCESS_KEY_ID : undefined);
|
|
88
|
+
const secretKey = options.secretAccessKey ?? (typeof process !== 'undefined' ? process.env?.AWS_SECRET_ACCESS_KEY : undefined);
|
|
89
|
+
const token = options.sessionToken ?? (typeof process !== 'undefined' ? process.env?.AWS_SESSION_TOKEN : undefined);
|
|
90
|
+
|
|
91
|
+
if (!accessKey || !secretKey) {
|
|
92
|
+
throw new Error(
|
|
93
|
+
'SigV4SnapshotAdapter: AWS credentials missing. Provide accessKeyId and secretAccessKey or set AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY.',
|
|
94
|
+
);
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
this.accessKeyId = accessKey;
|
|
98
|
+
this.secretAccessKey = secretKey;
|
|
99
|
+
this.sessionToken = token;
|
|
100
|
+
this.forcePathStyle = options.forcePathStyle ?? Boolean(options.endpoint);
|
|
101
|
+
this.fetchImpl = options.fetch ?? globalThis.fetch;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
private _resolveTarget(): { url: URL; canonicalUri: string; host: string } {
|
|
105
|
+
const encodedKey = encodePath(this.key);
|
|
106
|
+
|
|
107
|
+
if (this.endpoint) {
|
|
108
|
+
const base = new URL(this.endpoint);
|
|
109
|
+
const basePath = base.pathname.replace(/\/+$/, '');
|
|
110
|
+
if (this.forcePathStyle) {
|
|
111
|
+
const canonicalUri = `${basePath}/${encodeRfc3986(this.bucket)}/${encodedKey}`;
|
|
112
|
+
const url = new URL(canonicalUri, base.origin);
|
|
113
|
+
return { url, canonicalUri, host: url.host };
|
|
114
|
+
} else {
|
|
115
|
+
const host = `${this.bucket}.${base.host}`;
|
|
116
|
+
const canonicalUri = `${basePath}/${encodedKey}`;
|
|
117
|
+
const url = new URL(canonicalUri, `${base.protocol}//${host}`);
|
|
118
|
+
return { url, canonicalUri, host };
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
if (this.forcePathStyle) {
|
|
123
|
+
const host = this.region === 'us-east-1' ? 's3.amazonaws.com' : `s3.${this.region}.amazonaws.com`;
|
|
124
|
+
const canonicalUri = `/${encodeRfc3986(this.bucket)}/${encodedKey}`;
|
|
125
|
+
const url = new URL(`https://${host}${canonicalUri}`);
|
|
126
|
+
return { url, canonicalUri, host };
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
const host = this.region === 'us-east-1'
|
|
130
|
+
? `${this.bucket}.s3.amazonaws.com`
|
|
131
|
+
: `${this.bucket}.s3.${this.region}.amazonaws.com`;
|
|
132
|
+
const canonicalUri = `/${encodedKey}`;
|
|
133
|
+
const url = new URL(`https://${host}${canonicalUri}`);
|
|
134
|
+
return { url, canonicalUri, host };
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
private async _buildHeaders(method: string, body?: Uint8Array): Promise<{ headers: Record<string, string>; url: URL }> {
|
|
138
|
+
const { url, canonicalUri, host } = this._resolveTarget();
|
|
139
|
+
const now = new Date();
|
|
140
|
+
const amzDate = now.toISOString().replace(/[:-]|\.\d{3}/g, '');
|
|
141
|
+
const dateStamp = amzDate.slice(0, 8);
|
|
142
|
+
const service = 's3';
|
|
143
|
+
|
|
144
|
+
const payloadHash = body ? await sha256Hex(body) : EMPTY_STRING_SHA256;
|
|
145
|
+
|
|
146
|
+
const headersToSign: Record<string, string> = {
|
|
147
|
+
host,
|
|
148
|
+
'x-amz-content-sha256': payloadHash,
|
|
149
|
+
'x-amz-date': amzDate,
|
|
150
|
+
};
|
|
151
|
+
|
|
152
|
+
if (this.sessionToken) {
|
|
153
|
+
headersToSign['x-amz-security-token'] = this.sessionToken;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
if (body) {
|
|
157
|
+
headersToSign['content-type'] = 'application/octet-stream';
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
const sortedHeaderKeys = Object.keys(headersToSign).sort();
|
|
161
|
+
const canonicalHeaders = sortedHeaderKeys.map(k => `${k}:${headersToSign[k]}\n`).join('');
|
|
162
|
+
const signedHeaders = sortedHeaderKeys.join(';');
|
|
163
|
+
|
|
164
|
+
const canonicalRequest = [
|
|
165
|
+
method,
|
|
166
|
+
canonicalUri,
|
|
167
|
+
'', // canonical query string
|
|
168
|
+
canonicalHeaders,
|
|
169
|
+
signedHeaders,
|
|
170
|
+
payloadHash,
|
|
171
|
+
].join('\n');
|
|
172
|
+
|
|
173
|
+
const credentialScope = `${dateStamp}/${this.region}/${service}/aws4_request`;
|
|
174
|
+
const stringToSign = [
|
|
175
|
+
'AWS4-HMAC-SHA256',
|
|
176
|
+
amzDate,
|
|
177
|
+
credentialScope,
|
|
178
|
+
await sha256Hex(canonicalRequest),
|
|
179
|
+
].join('\n');
|
|
180
|
+
|
|
181
|
+
// Chained HMAC key derivation
|
|
182
|
+
const kDate = await hmac(new TextEncoder().encode(`AWS4${this.secretAccessKey}`), dateStamp);
|
|
183
|
+
const kRegion = await hmac(kDate, this.region);
|
|
184
|
+
const kService = await hmac(kRegion, service);
|
|
185
|
+
const kSigning = await hmac(kService, 'aws4_request');
|
|
186
|
+
|
|
187
|
+
const signatureBytes = await hmac(kSigning, stringToSign);
|
|
188
|
+
const signature = Array.from(new Uint8Array(signatureBytes)).map(b => b.toString(16).padStart(2, '0')).join('');
|
|
189
|
+
|
|
190
|
+
const authHeader = `AWS4-HMAC-SHA256 Credential=${this.accessKeyId}/${credentialScope}, SignedHeaders=${signedHeaders}, Signature=${signature}`;
|
|
191
|
+
|
|
192
|
+
const finalHeaders: Record<string, string> = {
|
|
193
|
+
...headersToSign,
|
|
194
|
+
Authorization: authHeader,
|
|
195
|
+
};
|
|
196
|
+
|
|
197
|
+
return { headers: finalHeaders, url };
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
async get(): Promise<Buffer | null> {
|
|
201
|
+
const { headers, url } = await this._buildHeaders('GET');
|
|
202
|
+
|
|
203
|
+
const res = await this.fetchImpl(url.toString(), {
|
|
204
|
+
method: 'GET',
|
|
205
|
+
headers,
|
|
206
|
+
});
|
|
207
|
+
|
|
208
|
+
if (res.status === 404) return null;
|
|
209
|
+
if (!res.ok) {
|
|
210
|
+
const errBody = await res.text().catch(() => '');
|
|
211
|
+
throw new Error(`SigV4SnapshotAdapter: GET ${url.pathname} failed with status ${res.status} ${res.statusText}: ${errBody}`);
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
const ab = await res.arrayBuffer();
|
|
215
|
+
return Buffer.from(ab);
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
async put(data: Buffer): Promise<void> {
|
|
219
|
+
const { headers, url } = await this._buildHeaders('PUT', data);
|
|
220
|
+
|
|
221
|
+
const res = await this.fetchImpl(url.toString(), {
|
|
222
|
+
method: 'PUT',
|
|
223
|
+
headers,
|
|
224
|
+
body: data as unknown as BodyInit,
|
|
225
|
+
});
|
|
226
|
+
|
|
227
|
+
if (!res.ok) {
|
|
228
|
+
const errBody = await res.text().catch(() => '');
|
|
229
|
+
throw new Error(`SigV4SnapshotAdapter: PUT ${url.pathname} failed with status ${res.status} ${res.statusText}: ${errBody}`);
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/**
|
|
235
|
+
* Creates a zero-dependency AWS SigV4 snapshot adapter for AWS S3, Cloudflare R2, MinIO, or custom gateways.
|
|
236
|
+
*/
|
|
237
|
+
export function createSigV4SnapshotAdapter(options: SigV4SnapshotAdapterOptions): IRemoteSnapshotAdapter {
|
|
238
|
+
return new SigV4SnapshotAdapter(options);
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/**
|
|
242
|
+
* Ergonomic alias for AWS S3 snapshot storage.
|
|
243
|
+
*/
|
|
244
|
+
export function createS3SnapshotAdapter(options: SigV4SnapshotAdapterOptions): IRemoteSnapshotAdapter {
|
|
245
|
+
return createSigV4SnapshotAdapter(options);
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/**
|
|
249
|
+
* Ergonomic alias for Cloudflare R2 snapshot storage using SigV4 REST credentials.
|
|
250
|
+
*/
|
|
251
|
+
export function createR2SnapshotAdapter(
|
|
252
|
+
options: Omit<SigV4SnapshotAdapterOptions, 'region'> & { region?: string; accountId?: string },
|
|
253
|
+
): IRemoteSnapshotAdapter {
|
|
254
|
+
const endpoint = options.endpoint ?? (options.accountId ? `https://${options.accountId}.r2.cloudflarestorage.com` : undefined);
|
|
255
|
+
return createSigV4SnapshotAdapter({
|
|
256
|
+
...options,
|
|
257
|
+
endpoint,
|
|
258
|
+
region: options.region ?? 'auto',
|
|
259
|
+
});
|
|
260
|
+
}
|