tricache 1.0.1 → 2.0.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/README.md +89 -93
- package/dashboards/tricache-alerts.yaml +80 -4
- package/dashboards/tricache-grafana.json +54 -1
- package/dashboards/tricache-inventory.rules.yml +21 -0
- package/dist/cache-service-BV5T8-20.d.cts +1064 -0
- package/dist/cache-service-UZXOQGEY.js +14 -0
- package/dist/{cache-service-CREOp7MM.d.ts → cache-service-tpyrXvlH.d.ts} +157 -24
- package/dist/{chunk-UBWLPKTI.js → chunk-EJXG7WO6.js} +152 -32
- package/dist/{chunk-IITRFWHY.js → chunk-EUKB7RKP.js} +21 -4
- package/dist/{chunk-7RV5ZVBB.js → chunk-JNSLMK4Q.js} +111 -29
- package/dist/{chunk-2AJKEQMZ.js → chunk-KV7KISK2.js} +54 -5
- package/dist/{chunk-JYQFQJNJ.js → chunk-MB3DMVWN.js} +3424 -1022
- package/dist/chunk-RBJRTGFK.js +94 -0
- package/dist/chunk-S5N65I45.js +17 -0
- package/dist/cli.cjs +3694 -1070
- package/dist/cli.d.cts +12 -0
- package/dist/cli.js +210 -14
- package/dist/dashboard/index.cjs +111 -29
- package/dist/dashboard/index.d.cts +185 -0
- package/dist/dashboard/index.d.ts +5 -3
- package/dist/dashboard/index.js +1 -1
- package/dist/drizzle/index.cjs +3578 -1068
- package/dist/drizzle/index.d.cts +46 -0
- package/dist/drizzle/index.d.ts +2 -2
- package/dist/drizzle/index.js +6 -2
- package/dist/edge/index.cjs +368 -162
- package/dist/edge/index.d.cts +134 -0
- package/dist/edge/index.d.ts +11 -4
- package/dist/edge/index.js +314 -155
- package/dist/hono/index.cjs +3614 -1087
- package/dist/hono/index.d.cts +93 -0
- package/dist/hono/index.d.ts +7 -5
- package/dist/hono/index.js +16 -9
- package/dist/hono-CMv2VdQ6.d.cts +404 -0
- package/dist/{hono-DSV2ve66.d.ts → hono-Dvq04kX9.d.ts} +33 -7
- package/dist/http/index.cjs +3712 -1124
- package/dist/http/index.d.cts +103 -0
- package/dist/http/index.d.ts +13 -5
- package/dist/http/index.js +92 -43
- package/dist/index.cjs +4067 -1252
- package/dist/index.d.cts +1071 -0
- package/dist/index.d.ts +123 -27
- package/dist/index.js +878 -21
- package/dist/{murmur3-CMGw9PbV.d.ts → murmur3-DF8BFRnu.d.cts} +1 -0
- package/dist/murmur3-DF8BFRnu.d.ts +99 -0
- package/dist/nestjs/index.cjs +3635 -1112
- package/dist/nestjs/index.d.cts +299 -0
- package/dist/nestjs/index.d.ts +120 -33
- package/dist/nestjs/index.js +132 -43
- package/dist/next/index.cjs +3704 -1175
- package/dist/next/index.d.cts +238 -0
- package/dist/next/index.d.ts +39 -11
- package/dist/next/index.js +202 -102
- package/dist/prisma/index.cjs +29 -18
- package/dist/prisma/index.d.cts +62 -0
- package/dist/prisma/index.d.ts +2 -2
- package/dist/prisma/index.js +17 -18
- package/dist/serialize-worker.cjs +162 -39
- package/dist/serialize-worker.d.cts +2 -0
- package/dist/serialize-worker.js +9 -7
- package/dist/{types-Dyip5wAl.d.ts → types-F8vRWMrE.d.cts} +186 -54
- package/dist/types-F8vRWMrE.d.ts +1636 -0
- package/dist/{utils-CEsU_Z0s.d.ts → utils-Bvzn-rKS.d.cts} +3 -1
- package/dist/utils-Bvzn-rKS.d.ts +29 -0
- package/package.json +116 -37
- package/src/adapters/auto-pipeliner.ts +150 -26
- package/src/adapters/node-redis.ts +106 -27
- package/src/cache-service.ts +2215 -793
- package/src/cli.ts +25 -14
- package/src/codec.ts +3 -3
- package/src/compression.ts +39 -16
- package/src/cross-region.ts +22 -4
- package/src/dashboard/handler.ts +26 -6
- package/src/dashboard/html.ts +35 -10
- package/src/dashboard/index.ts +35 -13
- package/src/dashboard/types.ts +3 -1
- package/src/disk-tier.ts +448 -102
- package/src/drizzle/index.ts +2 -1
- package/src/edge/adapters/cloudflare-do.ts +25 -10
- package/src/edge/adapters/cloudflare-kv.ts +12 -9
- package/src/edge/adapters/upstash.ts +27 -11
- package/src/edge/cache.ts +200 -110
- package/src/edge/hono.ts +23 -6
- package/src/edge/types.ts +17 -5
- package/src/encryption.ts +50 -18
- package/src/env.d.ts +1 -1
- package/src/errors.ts +12 -0
- package/src/hono/index.ts +19 -9
- package/src/http/express.ts +62 -17
- package/src/http/fastify.ts +35 -21
- package/src/http/utils.ts +60 -20
- package/src/index.ts +6 -0
- package/src/ipc-telemetry.ts +35 -9
- package/src/latency-watchdog.ts +5 -1
- package/src/nestjs/decorators.ts +11 -6
- package/src/nestjs/index.ts +2 -0
- package/src/nestjs/keyv-adapter.ts +68 -0
- package/src/nestjs/tricache.module.ts +15 -12
- package/src/nestjs/tricache.store.ts +69 -26
- package/src/nestjs/types.ts +30 -16
- package/src/next/cache-handler.ts +151 -53
- package/src/next/index.ts +1 -0
- package/src/next/types.ts +25 -0
- package/src/origin-capacity.ts +134 -0
- package/src/prisma/index.ts +17 -24
- package/src/remote-snapshot.ts +37 -27
- package/src/serialize-worker.ts +8 -5
- package/src/sigv4-snapshot-adapter.ts +37 -27
- package/src/smart-memory-cache.ts +121 -44
- package/src/types.ts +117 -37
- package/src/utils/cgroup.ts +12 -0
- package/src/utils/config-comparison.ts +29 -0
- package/src/utils/deadline.ts +14 -0
- package/src/utils/diagnostics.ts +27 -0
- package/src/utils/lz4-size.ts +74 -0
- package/src/utils/namespace-key.ts +48 -0
- package/src/utils/query-key.ts +13 -0
- package/src/utils/redis-slot.ts +13 -0
- package/src/utils/snapshot-transfer.ts +83 -0
- package/src/utils/work-limits.ts +73 -0
- package/src/utils/write-revision.ts +4 -0
- package/src/wasm/bloom-filter-wasm.ts +25 -5
- package/src/worker-pool.ts +44 -15
- package/src/wtiny-lfu.ts +82 -20
- package/dist/cache-service-MG7PN6MX.js +0 -12
- package/dist/chunk-3I5L7K6I.js +0 -704
- package/dist/chunk-BQRURGGD.js +0 -60
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
import { WorkLimit, positiveLimit } from './utils/work-limits.js';
|
|
2
|
+
|
|
3
|
+
export interface OriginCapacityOptions {
|
|
4
|
+
/** Per-process physical work budget. Batch fills reserve one slot per unique owned key. */
|
|
5
|
+
maxConcurrent: number;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
export interface OriginRunOptions {
|
|
9
|
+
signal?: AbortSignal;
|
|
10
|
+
/** Caller deadline in milliseconds; zero rejects before starting work. */
|
|
11
|
+
timeoutMs?: number;
|
|
12
|
+
/** Conservative work cost; defaults to one. No queue or implicit retry. */
|
|
13
|
+
weight?: number;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export interface OriginCapacityMetrics {
|
|
17
|
+
active: number;
|
|
18
|
+
capacity: number;
|
|
19
|
+
rejected: number;
|
|
20
|
+
started: number;
|
|
21
|
+
completed: number;
|
|
22
|
+
cancelled: number;
|
|
23
|
+
timedOut: number;
|
|
24
|
+
closed: boolean;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Share one instance across cache loaders and the direct-origin route for the same origin. */
|
|
28
|
+
export class OriginCapacityLimiter {
|
|
29
|
+
private readonly work: WorkLimit;
|
|
30
|
+
private readonly pending = new Set<(reason: unknown) => void>();
|
|
31
|
+
private closed = false;
|
|
32
|
+
private started = 0;
|
|
33
|
+
private completed = 0;
|
|
34
|
+
private cancelled = 0;
|
|
35
|
+
private timedOut = 0;
|
|
36
|
+
|
|
37
|
+
constructor(options: OriginCapacityOptions) {
|
|
38
|
+
this.work = new WorkLimit(positiveLimit(options?.maxConcurrent, 1024, 'maxConcurrent'), 'shared origin work');
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
async run<T>(origin: (signal: AbortSignal) => T | PromiseLike<T>, options: OriginRunOptions = {}): Promise<T> {
|
|
42
|
+
if (typeof origin !== 'function') throw new TypeError('Origin work must be a function');
|
|
43
|
+
const { signal, timeoutMs, weight = 1 } = options;
|
|
44
|
+
if (timeoutMs !== undefined && (!Number.isFinite(timeoutMs) || timeoutMs < 0 || timeoutMs > 2_147_483_647)) {
|
|
45
|
+
throw new RangeError('timeoutMs must be finite and between 0 and 2147483647');
|
|
46
|
+
}
|
|
47
|
+
if (this.closed) throw new Error('Origin capacity limiter is closed');
|
|
48
|
+
if (signal?.aborted) { this.cancelled++; throw signal.reason ?? new DOMException('Origin caller cancelled', 'AbortError'); }
|
|
49
|
+
if (timeoutMs === 0) { this.timedOut++; throw new DOMException('Origin request deadline exceeded', 'TimeoutError'); }
|
|
50
|
+
const release = this.work.acquire(weight);
|
|
51
|
+
const controller = new AbortController();
|
|
52
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
53
|
+
let abandon!: (reason: unknown) => void;
|
|
54
|
+
const cancelled = new Promise<never>((_resolve, reject) => {
|
|
55
|
+
abandon = reason => {
|
|
56
|
+
if (controller.signal.aborted) return;
|
|
57
|
+
// Reject the wait before signalling a cooperative origin that may settle synchronously.
|
|
58
|
+
reject(reason);
|
|
59
|
+
controller.abort(reason);
|
|
60
|
+
clearTimeout(timer);
|
|
61
|
+
signal?.removeEventListener('abort', onCallerAbort);
|
|
62
|
+
};
|
|
63
|
+
});
|
|
64
|
+
const onCallerAbort = () => {
|
|
65
|
+
if (controller.signal.aborted) return;
|
|
66
|
+
this.cancelled++;
|
|
67
|
+
abandon(signal?.reason ?? new DOMException('Origin caller cancelled', 'AbortError'));
|
|
68
|
+
};
|
|
69
|
+
const onClose = (reason: unknown) => {
|
|
70
|
+
if (controller.signal.aborted) return;
|
|
71
|
+
this.cancelled++;
|
|
72
|
+
abandon(reason);
|
|
73
|
+
};
|
|
74
|
+
this.pending.add(onClose);
|
|
75
|
+
signal?.addEventListener('abort', onCallerAbort, { once: true });
|
|
76
|
+
if (timeoutMs !== undefined) {
|
|
77
|
+
timer = setTimeout(() => {
|
|
78
|
+
if (controller.signal.aborted) return;
|
|
79
|
+
this.timedOut++;
|
|
80
|
+
abandon(new DOMException('Origin request deadline exceeded', 'TimeoutError'));
|
|
81
|
+
}, Math.ceil(timeoutMs));
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
this.started++;
|
|
85
|
+
let physical: Promise<T>;
|
|
86
|
+
try { physical = Promise.resolve(origin(controller.signal)); }
|
|
87
|
+
catch (error) { physical = Promise.reject(error); }
|
|
88
|
+
const finish = () => {
|
|
89
|
+
clearTimeout(timer);
|
|
90
|
+
signal?.removeEventListener('abort', onCallerAbort);
|
|
91
|
+
this.pending.delete(onClose);
|
|
92
|
+
release();
|
|
93
|
+
this.completed++;
|
|
94
|
+
};
|
|
95
|
+
// This handler remains attached after the caller abandons its wait. Only
|
|
96
|
+
// physical settlement releases capacity and observes a late rejection.
|
|
97
|
+
const settled = physical.then(value => { finish(); return value; }, error => { finish(); throw error; });
|
|
98
|
+
return Promise.race([settled, cancelled]);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** Reject new work and signal active origins. Ignored cancellation still occupies capacity. */
|
|
102
|
+
close(): void {
|
|
103
|
+
if (this.closed) return;
|
|
104
|
+
this.closed = true;
|
|
105
|
+
const reason = new DOMException('Origin capacity limiter is closed', 'AbortError');
|
|
106
|
+
for (const abort of this.pending) abort(reason);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
metrics(): OriginCapacityMetrics {
|
|
110
|
+
return { ...this.work.metrics(), started: this.started, completed: this.completed,
|
|
111
|
+
cancelled: this.cancelled, timedOut: this.timedOut, closed: this.closed };
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** Export once per shared origin budget, separately from per-namespace cache series. */
|
|
115
|
+
toPrometheusText(prefix = 'tricache_origin'): string {
|
|
116
|
+
if (!/^[a-zA-Z_:][a-zA-Z0-9_:]*$/.test(prefix)) throw new TypeError('Invalid Prometheus metric prefix');
|
|
117
|
+
const metrics = this.metrics();
|
|
118
|
+
const lines: string[] = [];
|
|
119
|
+
for (const [suffix, value, type, help] of [
|
|
120
|
+
['active', metrics.active, 'gauge', 'Reserved physical origin work slots'],
|
|
121
|
+
['capacity', metrics.capacity, 'gauge', 'Configured physical origin work capacity'],
|
|
122
|
+
['closed', metrics.closed ? 1 : 0, 'gauge', 'Origin budget is closed to new work'],
|
|
123
|
+
['rejections_total', metrics.rejected, 'counter', 'Origin admissions rejected at capacity'],
|
|
124
|
+
['started_total', metrics.started, 'counter', 'Physical origin invocations started'],
|
|
125
|
+
['completed_total', metrics.completed, 'counter', 'Physical origin invocations settled'],
|
|
126
|
+
['cancelled_total', metrics.cancelled, 'counter', 'Origin waits cancelled by callers or shutdown'],
|
|
127
|
+
['timeouts_total', metrics.timedOut, 'counter', 'Origin waits rejected by their deadline'],
|
|
128
|
+
] as const) {
|
|
129
|
+
const name = `${prefix}_${suffix}`;
|
|
130
|
+
lines.push(`# HELP ${name} ${help}`, `# TYPE ${name} ${type}`, `${name} ${value}`);
|
|
131
|
+
}
|
|
132
|
+
return lines.join('\n') + '\n';
|
|
133
|
+
}
|
|
134
|
+
}
|
package/src/prisma/index.ts
CHANGED
|
@@ -23,6 +23,7 @@
|
|
|
23
23
|
import type { CacheService } from '../cache-service.js';
|
|
24
24
|
import type { WrapOptions } from '../types.js';
|
|
25
25
|
import crypto from 'crypto';
|
|
26
|
+
import { deterministicStringify } from '../utils/query-key.js';
|
|
26
27
|
|
|
27
28
|
export interface PrismaCacheQueryOptions extends WrapOptions {
|
|
28
29
|
/** Explicit cache key. Defaults to SHA-256 hash of (model + operation + args). */
|
|
@@ -65,19 +66,6 @@ const MUTATION_OPERATIONS = new Set([
|
|
|
65
66
|
'deleteMany',
|
|
66
67
|
]);
|
|
67
68
|
|
|
68
|
-
/** Recursively sorts object keys for deterministic serialization of nested query filters */
|
|
69
|
-
function deterministicStringify(val: unknown): string {
|
|
70
|
-
if (val === null || typeof val !== 'object') {
|
|
71
|
-
return JSON.stringify(val);
|
|
72
|
-
}
|
|
73
|
-
if (Array.isArray(val)) {
|
|
74
|
-
return `[${val.map(deterministicStringify).join(',')}]`;
|
|
75
|
-
}
|
|
76
|
-
const obj = val as Record<string, unknown>;
|
|
77
|
-
const keys = Object.keys(obj).sort();
|
|
78
|
-
return `{${keys.map(k => `${JSON.stringify(k)}:${deterministicStringify(obj[k])}`).join(',')}}`;
|
|
79
|
-
}
|
|
80
|
-
|
|
81
69
|
/** Generate a deterministic SHA-256 hash key for a Prisma query. */
|
|
82
70
|
export function generatePrismaCacheKey(model: string, operation: string, args: unknown): string {
|
|
83
71
|
const normalized = deterministicStringify({ model, operation, args });
|
|
@@ -102,31 +90,36 @@ export function withTriCache(options: PrismaTriCacheOptions) {
|
|
|
102
90
|
query: (args: unknown) => Promise<unknown>;
|
|
103
91
|
}) {
|
|
104
92
|
const modelTag = model.toLowerCase();
|
|
93
|
+
const queryArgs = args ?? {};
|
|
94
|
+
const cacheConfig = (queryArgs as { cache?: PrismaCacheQueryOptions | boolean }).cache;
|
|
95
|
+
// `cache` is a TriCache-only pseudo-option. Remove it before every
|
|
96
|
+
// Prisma engine call, including pass-through reads and mutations when
|
|
97
|
+
// automatic invalidation/caching is disabled.
|
|
98
|
+
let cleanArgs: Record<string, unknown> | undefined = args;
|
|
99
|
+
if (args && Object.prototype.hasOwnProperty.call(args, 'cache')) {
|
|
100
|
+
const { cache: _cacheOpt, ...rest } = args;
|
|
101
|
+
cleanArgs = rest;
|
|
102
|
+
}
|
|
105
103
|
|
|
106
104
|
// Auto-invalidation on write operations
|
|
107
105
|
if (autoInvalidate && MUTATION_OPERATIONS.has(operation)) {
|
|
108
|
-
|
|
109
|
-
// but the mutation path forwarded it verbatim to the Prisma engine.
|
|
110
|
-
const { cache: _cacheOpt, ...cleanMutationArgs } = (args ?? {}) as Record<string, unknown>;
|
|
111
|
-
const result = await query(cleanMutationArgs);
|
|
106
|
+
const result = await query(cleanArgs);
|
|
112
107
|
await cache.invalidateTag(modelTag);
|
|
113
108
|
return result;
|
|
114
109
|
}
|
|
115
110
|
|
|
116
111
|
// Read operations
|
|
117
112
|
if (READ_OPERATIONS.has(operation)) {
|
|
118
|
-
|
|
119
|
-
|
|
113
|
+
if (cacheConfig === false) {
|
|
114
|
+
return query(cleanArgs);
|
|
115
|
+
}
|
|
120
116
|
|
|
121
117
|
if (cacheConfig !== undefined || autoCache) {
|
|
122
118
|
const opts: PrismaCacheQueryOptions = typeof cacheConfig === 'object' && cacheConfig !== null
|
|
123
119
|
? cacheConfig
|
|
124
120
|
: {};
|
|
125
121
|
|
|
126
|
-
|
|
127
|
-
const { cache: _c, ...cleanArgs } = queryArgs as Record<string, unknown>;
|
|
128
|
-
|
|
129
|
-
const key = opts.key ?? generatePrismaCacheKey(model, operation, cleanArgs);
|
|
122
|
+
const key = opts.key ?? generatePrismaCacheKey(model, operation, cleanArgs ?? {});
|
|
130
123
|
const tags = [...new Set([modelTag, ...(opts.tags ?? [])])];
|
|
131
124
|
|
|
132
125
|
return cache.wrap(
|
|
@@ -146,7 +139,7 @@ export function withTriCache(options: PrismaTriCacheOptions) {
|
|
|
146
139
|
}
|
|
147
140
|
}
|
|
148
141
|
|
|
149
|
-
return query(
|
|
142
|
+
return query(cleanArgs);
|
|
150
143
|
},
|
|
151
144
|
},
|
|
152
145
|
},
|
package/src/remote-snapshot.ts
CHANGED
|
@@ -5,17 +5,20 @@
|
|
|
5
5
|
* to persist and hydrate L1 cache snapshots from remote object storage (S3, GCS, R2, Azure, MinIO, or HTTP).
|
|
6
6
|
*/
|
|
7
7
|
|
|
8
|
+
import { discardSnapshotResponse, readSnapshotResponse, snapshotRequest, type SnapshotRequestOptions, type SnapshotTransferOptions } from './utils/snapshot-transfer.js';
|
|
9
|
+
export type { SnapshotRequestOptions, SnapshotTransferOptions } from './utils/snapshot-transfer.js';
|
|
10
|
+
|
|
8
11
|
export interface IRemoteSnapshotAdapter {
|
|
9
12
|
/**
|
|
10
13
|
* Read the latest snapshot blob from remote storage.
|
|
11
14
|
* Returns null if no snapshot exists yet (e.g. 404 Not Found / first deploy).
|
|
12
15
|
*/
|
|
13
|
-
get(): Promise<Buffer | Uint8Array | null>;
|
|
16
|
+
get(options?: SnapshotRequestOptions): Promise<Buffer | Uint8Array | null>;
|
|
14
17
|
|
|
15
18
|
/**
|
|
16
19
|
* Write the snapshot blob to remote storage.
|
|
17
20
|
*/
|
|
18
|
-
put(data: Buffer): Promise<void>;
|
|
21
|
+
put(data: Buffer, options?: SnapshotRequestOptions): Promise<void>;
|
|
19
22
|
}
|
|
20
23
|
|
|
21
24
|
import type { EnvelopeEncryptionOptions } from './encryption';
|
|
@@ -53,7 +56,7 @@ export interface RemoteSnapshotOptions {
|
|
|
53
56
|
envelope?: EnvelopeEncryptionOptions;
|
|
54
57
|
}
|
|
55
58
|
|
|
56
|
-
export interface HttpSnapshotAdapterOptions {
|
|
59
|
+
export interface HttpSnapshotAdapterOptions extends SnapshotTransferOptions {
|
|
57
60
|
/**
|
|
58
61
|
* URL to fetch the snapshot from (e.g. S3 presigned GET URL or internal blob service).
|
|
59
62
|
*/
|
|
@@ -80,34 +83,41 @@ export function createHttpSnapshotAdapter(options: HttpSnapshotAdapterOptions):
|
|
|
80
83
|
const headers = options.headers ?? {};
|
|
81
84
|
|
|
82
85
|
return {
|
|
83
|
-
async get(): Promise<Buffer | null> {
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
86
|
+
async get(request): Promise<Buffer | null> {
|
|
87
|
+
return snapshotRequest(options, request, async (signal, maxBytes) => {
|
|
88
|
+
const res = await fetch(getUrl, {
|
|
89
|
+
method: 'GET',
|
|
90
|
+
headers,
|
|
91
|
+
signal,
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
if (res.status === 404) { discardSnapshotResponse(res); return null; }
|
|
95
|
+
if (!res.ok) {
|
|
96
|
+
discardSnapshotResponse(res);
|
|
97
|
+
throw new Error(`HttpSnapshotAdapter: GET failed with status ${res.status} ${res.statusText}`);
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
return readSnapshotResponse(res, signal, maxBytes);
|
|
87
101
|
});
|
|
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
102
|
},
|
|
97
103
|
|
|
98
|
-
async put(data: Buffer): Promise<void> {
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
104
|
+
async put(data: Buffer, request): Promise<void> {
|
|
105
|
+
return snapshotRequest(options, request, async (signal) => {
|
|
106
|
+
const res = await fetch(putUrl, {
|
|
107
|
+
method: 'PUT',
|
|
108
|
+
headers: {
|
|
109
|
+
'Content-Type': 'application/octet-stream',
|
|
110
|
+
...headers,
|
|
111
|
+
},
|
|
112
|
+
body: data as unknown as BodyInit,
|
|
113
|
+
signal,
|
|
114
|
+
});
|
|
115
|
+
|
|
116
|
+
discardSnapshotResponse(res);
|
|
117
|
+
if (!res.ok) {
|
|
118
|
+
throw new Error(`HttpSnapshotAdapter: PUT failed with status ${res.status} ${res.statusText}`);
|
|
119
|
+
}
|
|
106
120
|
});
|
|
107
|
-
|
|
108
|
-
if (!res.ok) {
|
|
109
|
-
throw new Error(`HttpSnapshotAdapter: PUT failed with status ${res.status} ${res.statusText}`);
|
|
110
|
-
}
|
|
111
121
|
},
|
|
112
122
|
};
|
|
113
123
|
}
|
package/src/serialize-worker.ts
CHANGED
|
@@ -33,6 +33,7 @@ interface WorkerInit {
|
|
|
33
33
|
prevMode: EncryptionMode | undefined;
|
|
34
34
|
compression?: CompressionAlgorithm;
|
|
35
35
|
compressionThresholdBytes?: number;
|
|
36
|
+
allowLegacyPlaintextRead?: boolean;
|
|
36
37
|
}
|
|
37
38
|
|
|
38
39
|
// Minimal no-op logger — worker thread does not log to avoid interleaved I/O.
|
|
@@ -52,6 +53,7 @@ const enc = new CacheEncryption(
|
|
|
52
53
|
mode,
|
|
53
54
|
prevKeyBase64 || undefined,
|
|
54
55
|
prevMode,
|
|
56
|
+
{ allowLegacyPlaintextRead: (workerData as WorkerInit).allowLegacyPlaintextRead },
|
|
55
57
|
);
|
|
56
58
|
|
|
57
59
|
const cmpAlgo = compression ?? 'zstd';
|
|
@@ -59,7 +61,7 @@ const cmpThreshold = compressionThresholdBytes ?? 1024;
|
|
|
59
61
|
|
|
60
62
|
parentPort!.on(
|
|
61
63
|
'message',
|
|
62
|
-
async ({ id, type, payload }: { id: number; type: 'encrypt' | 'decrypt'; payload: string | Uint8Array }) => {
|
|
64
|
+
async ({ id, type, payload, context }: { id: number; type: 'encrypt' | 'decrypt'; payload: string | Uint8Array; context?: string }) => {
|
|
63
65
|
try {
|
|
64
66
|
if (cmpAlgo === 'zstd') {
|
|
65
67
|
await initZstd();
|
|
@@ -74,13 +76,13 @@ parentPort!.on(
|
|
|
74
76
|
if (cmpAlgo !== 'none' && textPayload.length > cmpThreshold) {
|
|
75
77
|
const compressed = compressBuffer(Buffer.from(textPayload, 'utf8'), cmpAlgo);
|
|
76
78
|
if (enc.isEnabled) {
|
|
77
|
-
const encrypted = enc.encryptBuffer(compressed);
|
|
79
|
+
const encrypted = enc.encryptBuffer(compressed, context);
|
|
78
80
|
result = PREFIX_ENC_COMPRESSED + encrypted.toString('base64');
|
|
79
81
|
} else {
|
|
80
82
|
result = PREFIX_COMPRESSED + compressed.toString('base64');
|
|
81
83
|
}
|
|
82
84
|
} else {
|
|
83
|
-
result = enc.encrypt(textPayload);
|
|
85
|
+
result = enc.encrypt(textPayload, context);
|
|
84
86
|
}
|
|
85
87
|
|
|
86
88
|
if (result.length >= 131_072) {
|
|
@@ -93,10 +95,11 @@ parentPort!.on(
|
|
|
93
95
|
parentPort!.postMessage({ id, result });
|
|
94
96
|
}
|
|
95
97
|
} else {
|
|
98
|
+
enc.assertReadPolicy(textPayload, context);
|
|
96
99
|
let result: string;
|
|
97
100
|
if (textPayload.startsWith(PREFIX_ENC_COMPRESSED)) {
|
|
98
101
|
const rawBuf = Buffer.from(textPayload.slice(PREFIX_ENC_COMPRESSED.length), 'base64');
|
|
99
|
-
const decryptedBuf = enc.decryptBuffer(rawBuf);
|
|
102
|
+
const decryptedBuf = enc.decryptBuffer(rawBuf, context);
|
|
100
103
|
const decompressed = decompressBuffer(decryptedBuf, cmpAlgo !== 'none' ? cmpAlgo : 'brotli');
|
|
101
104
|
result = decompressed.toString('utf8');
|
|
102
105
|
} else if (textPayload.startsWith(PREFIX_COMPRESSED)) {
|
|
@@ -104,7 +107,7 @@ parentPort!.on(
|
|
|
104
107
|
const decompressed = decompressBuffer(rawBuf, cmpAlgo !== 'none' ? cmpAlgo : 'brotli');
|
|
105
108
|
result = decompressed.toString('utf8');
|
|
106
109
|
} else {
|
|
107
|
-
result = enc.decrypt(textPayload);
|
|
110
|
+
result = enc.decrypt(textPayload, context);
|
|
108
111
|
}
|
|
109
112
|
|
|
110
113
|
if (result.length >= 131_072) {
|
|
@@ -10,8 +10,9 @@
|
|
|
10
10
|
*/
|
|
11
11
|
|
|
12
12
|
import type { IRemoteSnapshotAdapter } from './remote-snapshot';
|
|
13
|
+
import { discardSnapshotResponse, readSnapshotResponse, snapshotRequest, type SnapshotRequestOptions, type SnapshotTransferOptions } from './utils/snapshot-transfer.js';
|
|
13
14
|
|
|
14
|
-
export interface SigV4SnapshotAdapterOptions {
|
|
15
|
+
export interface SigV4SnapshotAdapterOptions extends SnapshotTransferOptions {
|
|
15
16
|
/** S3 or Cloudflare R2 bucket name */
|
|
16
17
|
bucket: string;
|
|
17
18
|
/** Object key / filename for the snapshot (e.g. 'production-l1.snap') */
|
|
@@ -77,8 +78,10 @@ export class SigV4SnapshotAdapter implements IRemoteSnapshotAdapter {
|
|
|
77
78
|
private readonly sessionToken?: string;
|
|
78
79
|
private readonly forcePathStyle: boolean;
|
|
79
80
|
private readonly fetchImpl: typeof globalThis.fetch;
|
|
81
|
+
private readonly transfer: SnapshotTransferOptions;
|
|
80
82
|
|
|
81
83
|
constructor(options: SigV4SnapshotAdapterOptions) {
|
|
84
|
+
this.transfer = { maxBytes: options.maxBytes, timeoutMs: options.timeoutMs };
|
|
82
85
|
this.bucket = options.bucket;
|
|
83
86
|
this.key = options.key.replace(/^\/+/, '');
|
|
84
87
|
this.region = options.region ?? (options.endpoint?.includes('r2.cloudflarestorage.com') ? 'auto' : 'us-east-1');
|
|
@@ -197,37 +200,44 @@ export class SigV4SnapshotAdapter implements IRemoteSnapshotAdapter {
|
|
|
197
200
|
return { headers: finalHeaders, url };
|
|
198
201
|
}
|
|
199
202
|
|
|
200
|
-
async get(): Promise<Buffer | null> {
|
|
201
|
-
|
|
203
|
+
async get(request?: SnapshotRequestOptions): Promise<Buffer | null> {
|
|
204
|
+
return snapshotRequest(this.transfer, request, async (signal, maxBytes) => {
|
|
205
|
+
const { headers, url } = await this._buildHeaders('GET');
|
|
206
|
+
signal.throwIfAborted();
|
|
207
|
+
|
|
208
|
+
const res = await this.fetchImpl(url.toString(), {
|
|
209
|
+
method: 'GET',
|
|
210
|
+
headers,
|
|
211
|
+
signal,
|
|
212
|
+
});
|
|
213
|
+
|
|
214
|
+
if (res.status === 404) { discardSnapshotResponse(res); return null; }
|
|
215
|
+
if (!res.ok) {
|
|
216
|
+
discardSnapshotResponse(res);
|
|
217
|
+
throw new Error(`SigV4SnapshotAdapter: GET ${url.pathname} failed with status ${res.status} ${res.statusText}`);
|
|
218
|
+
}
|
|
202
219
|
|
|
203
|
-
|
|
204
|
-
method: 'GET',
|
|
205
|
-
headers,
|
|
220
|
+
return readSnapshotResponse(res, signal, maxBytes);
|
|
206
221
|
});
|
|
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
222
|
}
|
|
217
223
|
|
|
218
|
-
async put(data: Buffer): Promise<void> {
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
224
|
+
async put(data: Buffer, request?: SnapshotRequestOptions): Promise<void> {
|
|
225
|
+
return snapshotRequest(this.transfer, request, async (signal) => {
|
|
226
|
+
const { headers, url } = await this._buildHeaders('PUT', data);
|
|
227
|
+
signal.throwIfAborted();
|
|
228
|
+
|
|
229
|
+
const res = await this.fetchImpl(url.toString(), {
|
|
230
|
+
method: 'PUT',
|
|
231
|
+
headers,
|
|
232
|
+
body: data as unknown as BodyInit,
|
|
233
|
+
signal,
|
|
234
|
+
});
|
|
235
|
+
|
|
236
|
+
discardSnapshotResponse(res);
|
|
237
|
+
if (!res.ok) {
|
|
238
|
+
throw new Error(`SigV4SnapshotAdapter: PUT ${url.pathname} failed with status ${res.status} ${res.statusText}`);
|
|
239
|
+
}
|
|
225
240
|
});
|
|
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
241
|
}
|
|
232
242
|
}
|
|
233
243
|
|