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
package/dist/next/index.js
CHANGED
|
@@ -1,10 +1,12 @@
|
|
|
1
1
|
import {
|
|
2
|
-
CacheService
|
|
3
|
-
|
|
2
|
+
CacheService,
|
|
3
|
+
WorkLimit,
|
|
4
|
+
positiveLimit
|
|
5
|
+
} from "../chunk-MB3DMVWN.js";
|
|
4
6
|
import {
|
|
5
7
|
consoleLogger
|
|
6
|
-
} from "../chunk-
|
|
7
|
-
import "../chunk-
|
|
8
|
+
} from "../chunk-EJXG7WO6.js";
|
|
9
|
+
import "../chunk-KV7KISK2.js";
|
|
8
10
|
|
|
9
11
|
// src/next/cache-handler.ts
|
|
10
12
|
var PRESET_CACHE_LIFE_PROFILES = {
|
|
@@ -38,18 +40,32 @@ function resolveCacheLife(profileOrName) {
|
|
|
38
40
|
}
|
|
39
41
|
return null;
|
|
40
42
|
}
|
|
41
|
-
async function drainStream(stream) {
|
|
43
|
+
async function drainStream(stream, maxBytes, reserveBytes) {
|
|
42
44
|
const reader = stream.getReader();
|
|
43
45
|
const chunks = [];
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
46
|
+
let size = 0;
|
|
47
|
+
try {
|
|
48
|
+
while (true) {
|
|
49
|
+
const { done, value } = await reader.read();
|
|
50
|
+
if (done) break;
|
|
51
|
+
if (value) {
|
|
52
|
+
size += value.byteLength;
|
|
53
|
+
if (size > maxBytes) throw new Error("RSC stream exceeds maxStreamBytes");
|
|
54
|
+
if (value.byteLength > 0) reserveBytes(value.byteLength);
|
|
55
|
+
chunks.push(Uint8Array.from(value));
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
return Buffer.concat(chunks);
|
|
59
|
+
} catch (error) {
|
|
60
|
+
void reader.cancel(error).catch(() => {
|
|
61
|
+
});
|
|
62
|
+
throw error;
|
|
63
|
+
} finally {
|
|
64
|
+
reader.releaseLock();
|
|
48
65
|
}
|
|
49
|
-
return Buffer.concat(chunks);
|
|
50
66
|
}
|
|
51
67
|
function createReadableStream(buffer) {
|
|
52
|
-
const uint8 =
|
|
68
|
+
const uint8 = Uint8Array.from(buffer);
|
|
53
69
|
return new ReadableStream({
|
|
54
70
|
start(controller) {
|
|
55
71
|
controller.enqueue(uint8);
|
|
@@ -57,11 +73,20 @@ function createReadableStream(buffer) {
|
|
|
57
73
|
}
|
|
58
74
|
});
|
|
59
75
|
}
|
|
60
|
-
var TriCacheHandler = class {
|
|
76
|
+
var TriCacheHandler = class _TriCacheHandler {
|
|
61
77
|
cache;
|
|
62
78
|
logger;
|
|
79
|
+
maxStreamBytes;
|
|
80
|
+
streamBudget;
|
|
81
|
+
static streamBudgets = /* @__PURE__ */ new WeakMap();
|
|
82
|
+
pendingSets = /* @__PURE__ */ new Map();
|
|
83
|
+
observedTags = /* @__PURE__ */ new Map();
|
|
63
84
|
constructor(options = {}) {
|
|
64
85
|
this.logger = options.logger ?? consoleLogger;
|
|
86
|
+
this.maxStreamBytes = positiveLimit(options.maxStreamBytes, 16 * 1024 * 1024, "maxStreamBytes");
|
|
87
|
+
const maxPendingStreamBytes = positiveLimit(options.maxPendingStreamBytes, 64 * 1024 * 1024, "maxPendingStreamBytes");
|
|
88
|
+
const maxConcurrentStreams = positiveLimit(options.maxConcurrentStreams, 16, "maxConcurrentStreams");
|
|
89
|
+
if (options.tagStrategy && options.tagStrategy !== "generational") throw new Error("Next.js cache handlers require tagStrategy: generational");
|
|
65
90
|
const isBuildPhase = options.isBuildPhase ?? (typeof process !== "undefined" && (process.env.NEXT_PHASE === "phase-production-build" || process.env.NEXT_PHASE === "phase-export"));
|
|
66
91
|
this.cache = CacheService.create({
|
|
67
92
|
...options,
|
|
@@ -70,35 +95,72 @@ var TriCacheHandler = class {
|
|
|
70
95
|
cloneStrategy: options.cloneStrategy ?? "none",
|
|
71
96
|
disableRedis: isBuildPhase ? true : options.disableRedis
|
|
72
97
|
});
|
|
98
|
+
const existing = _TriCacheHandler.streamBudgets.get(this.cache);
|
|
99
|
+
if (existing && (existing.bytes.maximum !== maxPendingStreamBytes || existing.streams.maximum !== maxConcurrentStreams)) {
|
|
100
|
+
throw new Error("Next handlers sharing one cache must use the same stream admission limits");
|
|
101
|
+
}
|
|
102
|
+
this.streamBudget = existing ?? {
|
|
103
|
+
bytes: new WorkLimit(maxPendingStreamBytes, "Next buffered stream bytes"),
|
|
104
|
+
streams: new WorkLimit(maxConcurrentStreams, "Next concurrent streams")
|
|
105
|
+
};
|
|
106
|
+
_TriCacheHandler.streamBudgets.set(this.cache, this.streamBudget);
|
|
73
107
|
}
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
108
|
+
async get(cacheKey, context) {
|
|
109
|
+
let pending = this.pendingSets.get(cacheKey);
|
|
110
|
+
while (pending) {
|
|
111
|
+
await pending.completion;
|
|
112
|
+
pending = this.pendingSets.get(cacheKey);
|
|
113
|
+
}
|
|
114
|
+
const native = Array.isArray(context);
|
|
115
|
+
const ctx = native ? { softTags: context } : context;
|
|
79
116
|
const stored = await this.cache.peek(cacheKey);
|
|
80
117
|
if (!stored || stored.data == null) {
|
|
81
118
|
return void 0;
|
|
82
119
|
}
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
120
|
+
const expire = stored.expire ?? stored.ttl;
|
|
121
|
+
if (!Number.isFinite(stored.timestamp) || !Number.isFinite(expire) || Date.now() >= stored.timestamp + expire * 1e3) return void 0;
|
|
122
|
+
const tags = [.../* @__PURE__ */ new Set([...stored.tags, ...ctx?.softTags ?? []])];
|
|
123
|
+
const versions = await Promise.all(tags.map((tag) => this.cache.getTagVersion(tag)));
|
|
124
|
+
const states = await this.cache.mget(tags.map((tag) => `_next_tag_state_:${tag}`));
|
|
125
|
+
let revalidate = stored.revalidate ?? stored.ttl;
|
|
126
|
+
for (let index = 0; index < tags.length; index++) {
|
|
127
|
+
const tag = tags[index];
|
|
128
|
+
const state = states[index];
|
|
129
|
+
const snapshot = stored.generations?.[tag] ?? stored.softTagVersions?.[tag];
|
|
130
|
+
if (state && (state.revalidatedAt > stored.timestamp || state.revalidatedAt === stored.timestamp && snapshot !== versions[index])) {
|
|
131
|
+
if (state.expiredAt !== void 0 && state.expiredAt <= Date.now()) return void 0;
|
|
132
|
+
revalidate = -1;
|
|
133
|
+
} else if (!state && versions[index] > 0) {
|
|
134
|
+
if (snapshot !== void 0 && versions[index] > snapshot) return void 0;
|
|
135
|
+
if (snapshot === void 0) {
|
|
136
|
+
const observed = this.observeTag(tag, versions[index]);
|
|
137
|
+
if (stored.timestamp <= observed) return void 0;
|
|
90
138
|
}
|
|
91
139
|
}
|
|
92
140
|
}
|
|
93
141
|
let val = stored.data;
|
|
94
|
-
if (stored.isStream
|
|
95
|
-
|
|
142
|
+
if (stored.isStream) {
|
|
143
|
+
let bytes;
|
|
144
|
+
if (stored.streamEncoding === "base64" && typeof val === "string") {
|
|
145
|
+
if (val.length > Math.ceil(this.maxStreamBytes / 3) * 4) return void 0;
|
|
146
|
+
bytes = Buffer.from(val, "base64");
|
|
147
|
+
} else if (Buffer.isBuffer(val) || val instanceof Uint8Array) bytes = val;
|
|
148
|
+
else if (val && typeof val === "object" && val.type === "Buffer" && Array.isArray(val.data)) {
|
|
149
|
+
bytes = Buffer.from(val.data);
|
|
150
|
+
} else return void 0;
|
|
151
|
+
if (bytes.length > this.maxStreamBytes) return void 0;
|
|
152
|
+
val = createReadableStream(bytes);
|
|
153
|
+
} else if (native) {
|
|
154
|
+
return void 0;
|
|
96
155
|
}
|
|
97
156
|
return {
|
|
98
157
|
value: val,
|
|
99
158
|
tags: stored.tags,
|
|
100
159
|
timestamp: stored.timestamp,
|
|
101
|
-
ttl: stored.ttl
|
|
160
|
+
ttl: stored.ttl,
|
|
161
|
+
stale: stored.stale ?? 300,
|
|
162
|
+
revalidate,
|
|
163
|
+
expire
|
|
102
164
|
};
|
|
103
165
|
}
|
|
104
166
|
/**
|
|
@@ -106,92 +168,123 @@ var TriCacheHandler = class {
|
|
|
106
168
|
* before storing. Catches mid-flight stream aborts to avoid crashing Next.js.
|
|
107
169
|
*/
|
|
108
170
|
async set(cacheKey, pendingEntry, ctx) {
|
|
109
|
-
const
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
);
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
171
|
+
const token = Symbol(cacheKey);
|
|
172
|
+
let finish;
|
|
173
|
+
const completion = new Promise((resolve) => {
|
|
174
|
+
finish = resolve;
|
|
175
|
+
});
|
|
176
|
+
this.pendingSets.set(cacheKey, { token, completion });
|
|
177
|
+
const byteReservation = this.streamBudget.bytes.reservation();
|
|
178
|
+
let releaseStream;
|
|
179
|
+
try {
|
|
180
|
+
const canCommit = this.cache.captureMutationFence(cacheKey);
|
|
181
|
+
const entry = await pendingEntry;
|
|
182
|
+
if (!entry || entry.value == null) return;
|
|
183
|
+
const tags = Array.from(/* @__PURE__ */ new Set([...entry.tags ?? [], ...ctx?.tags ?? []]));
|
|
184
|
+
const allTags = [.../* @__PURE__ */ new Set([...tags, ...ctx?.softTags ?? []])];
|
|
185
|
+
const initialVersions = Object.fromEntries(await Promise.all(allTags.map(async (tag) => [tag, await this.cache.getTagVersion(tag)])));
|
|
186
|
+
let dataToStore = entry.value;
|
|
187
|
+
const isStream = Boolean(
|
|
188
|
+
dataToStore && typeof dataToStore.getReader === "function"
|
|
189
|
+
);
|
|
190
|
+
if (isStream) {
|
|
191
|
+
try {
|
|
192
|
+
releaseStream = this.streamBudget.streams.acquire();
|
|
193
|
+
dataToStore = (await drainStream(
|
|
194
|
+
dataToStore,
|
|
195
|
+
this.maxStreamBytes,
|
|
196
|
+
(bytes) => byteReservation.grow(bytes)
|
|
197
|
+
)).toString("base64");
|
|
198
|
+
} catch (streamErr) {
|
|
199
|
+
const stream = entry.value;
|
|
200
|
+
if (!stream.locked) void stream.cancel(streamErr).catch(() => {
|
|
201
|
+
});
|
|
202
|
+
this.logger.debug("Next.js cacheHandler: stream drain failed mid-flight, skipping cache", {
|
|
203
|
+
cacheKey,
|
|
204
|
+
error: streamErr.message
|
|
205
|
+
});
|
|
206
|
+
return;
|
|
207
|
+
}
|
|
124
208
|
}
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
if (ctx
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
const
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
209
|
+
let ttl;
|
|
210
|
+
const resolvedLife = resolveCacheLife(ctx?.cacheLife);
|
|
211
|
+
if (resolvedLife) {
|
|
212
|
+
ttl = resolvedLife.ttl;
|
|
213
|
+
} else if (typeof entry.revalidate === "number") {
|
|
214
|
+
ttl = entry.revalidate;
|
|
215
|
+
} else if (typeof entry.ttl === "number") {
|
|
216
|
+
ttl = entry.ttl;
|
|
217
|
+
} else if (typeof ctx?.revalidate === "number") {
|
|
218
|
+
if (ctx.revalidate <= 0) return;
|
|
219
|
+
ttl = ctx.revalidate;
|
|
220
|
+
} else if (ctx?.revalidate === false) {
|
|
221
|
+
ttl = 31536e3;
|
|
222
|
+
} else {
|
|
223
|
+
ttl = 300;
|
|
224
|
+
}
|
|
225
|
+
const expire = entry.expire ?? (resolvedLife ? resolvedLife.ttl + resolvedLife.swr : ttl);
|
|
226
|
+
const timestamp = entry.timestamp ?? Date.now();
|
|
227
|
+
if (!Number.isFinite(expire) || expire <= 0 || !Number.isFinite(timestamp) || timestamp > Date.now() + (this.cache.options.clockSkewToleranceMs ?? 250)) return;
|
|
228
|
+
const remaining = timestamp + expire * 1e3 - Date.now();
|
|
229
|
+
if (remaining <= 0 || !canCommit() || this.pendingSets.get(cacheKey)?.token !== token) return;
|
|
230
|
+
const finalVersions = await Promise.all(allTags.map((tag) => this.cache.getTagVersion(tag)));
|
|
231
|
+
if (allTags.some((tag, index) => finalVersions[index] !== initialVersions[tag])) return;
|
|
232
|
+
const tagStates = await this.cache.mget(allTags.map((tag) => `_next_tag_state_:${tag}`));
|
|
233
|
+
if (tagStates.some((state) => state && state.revalidatedAt > timestamp)) return;
|
|
234
|
+
let softTagVersions;
|
|
235
|
+
if (ctx?.softTags && ctx.softTags.length > 0) {
|
|
236
|
+
const softTags = ctx.softTags;
|
|
237
|
+
const vers = await Promise.all(softTags.map((st) => this.cache.getTagVersion(st)));
|
|
238
|
+
softTagVersions = {};
|
|
239
|
+
for (let i = 0; i < softTags.length; i++) {
|
|
240
|
+
softTagVersions[softTags[i]] = vers[i];
|
|
241
|
+
}
|
|
148
242
|
}
|
|
243
|
+
const stored = {
|
|
244
|
+
data: dataToStore,
|
|
245
|
+
isStream,
|
|
246
|
+
tags,
|
|
247
|
+
timestamp,
|
|
248
|
+
ttl,
|
|
249
|
+
softTagVersions,
|
|
250
|
+
generations: initialVersions,
|
|
251
|
+
stale: entry.stale ?? (typeof ctx?.cacheLife === "string" ? PRESET_CACHE_LIFE_PROFILES[ctx.cacheLife]?.stale : typeof ctx?.cacheLife === "object" ? ctx.cacheLife.stale : void 0) ?? 300,
|
|
252
|
+
revalidate: ttl,
|
|
253
|
+
expire,
|
|
254
|
+
streamEncoding: isStream ? "base64" : void 0
|
|
255
|
+
};
|
|
256
|
+
if (!canCommit() || this.pendingSets.get(cacheKey)?.token !== token) return;
|
|
257
|
+
await this.cache.set(cacheKey, stored, remaining / 1e3, void 0, { tags: [] });
|
|
258
|
+
} finally {
|
|
259
|
+
byteReservation.release();
|
|
260
|
+
releaseStream?.();
|
|
261
|
+
finish();
|
|
262
|
+
if (this.pendingSets.get(cacheKey)?.token === token) this.pendingSets.delete(cacheKey);
|
|
149
263
|
}
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
}
|
|
158
|
-
|
|
264
|
+
}
|
|
265
|
+
observeTag(tag, version) {
|
|
266
|
+
const known = this.observedTags.get(tag);
|
|
267
|
+
if (known?.version === version) return known.observedAt;
|
|
268
|
+
if (this.observedTags.size >= 1e4) {
|
|
269
|
+
const oldest = this.observedTags.keys().next().value;
|
|
270
|
+
if (oldest !== void 0) this.observedTags.delete(oldest);
|
|
271
|
+
}
|
|
272
|
+
const observedAt = Date.now();
|
|
273
|
+
this.observedTags.set(tag, { version, observedAt });
|
|
274
|
+
return observedAt;
|
|
159
275
|
}
|
|
160
276
|
/**
|
|
161
|
-
*
|
|
162
|
-
* cached entry for the given tags, or 0 when nothing is tracked. Next.js
|
|
163
|
-
* uses this to decide whether a revalidation is due — a hardcoded 0 means
|
|
164
|
-
* "always expired", so this reads the real stored entries instead.
|
|
277
|
+
* Delegate soft-tag checking to get() using Next's Infinity sentinel.
|
|
165
278
|
*/
|
|
166
279
|
async getExpiration(tags) {
|
|
167
|
-
|
|
168
|
-
let maxExpiration = 0;
|
|
169
|
-
const tagSet = new Set(tags);
|
|
170
|
-
const l1 = this.cache.l1;
|
|
171
|
-
l1.scan((key, entry) => {
|
|
172
|
-
if (!entry.tagVersions) return;
|
|
173
|
-
for (const tag of Object.keys(entry.tagVersions)) {
|
|
174
|
-
if (!tagSet.has(tag)) continue;
|
|
175
|
-
const exp = entry.expiresAt ?? 0;
|
|
176
|
-
if (exp > maxExpiration) maxExpiration = exp;
|
|
177
|
-
return;
|
|
178
|
-
}
|
|
179
|
-
}, 0);
|
|
180
|
-
return maxExpiration;
|
|
181
|
-
} catch (err) {
|
|
182
|
-
this.logger.debug("Next.js cacheHandler getExpiration fail-soft", { error: err.message });
|
|
183
|
-
return 0;
|
|
184
|
-
}
|
|
280
|
+
return tags.length ? Infinity : 0;
|
|
185
281
|
}
|
|
186
282
|
/**
|
|
187
|
-
*
|
|
188
|
-
* in-memory tag-version cache so every subsequent read re-syncs versions
|
|
189
|
-
* from Redis. The previous implementation was an empty try/catch.
|
|
283
|
+
* Force subsequent tag reads to re-sync without forgetting monotonic versions.
|
|
190
284
|
*/
|
|
191
285
|
async refreshTags() {
|
|
192
286
|
try {
|
|
193
|
-
|
|
194
|
-
cache.tagVersions?.clear();
|
|
287
|
+
this.cache.refreshTagVersions();
|
|
195
288
|
} catch (err) {
|
|
196
289
|
this.logger.debug("Next.js cacheHandler refreshTags fail-soft catch", {
|
|
197
290
|
error: err.message
|
|
@@ -201,8 +294,15 @@ var TriCacheHandler = class {
|
|
|
201
294
|
/**
|
|
202
295
|
* Update or invalidate tags cluster-wide.
|
|
203
296
|
*/
|
|
204
|
-
async updateTags(tags) {
|
|
297
|
+
async updateTags(tags, durations) {
|
|
205
298
|
if (!tags || tags.length === 0) return;
|
|
299
|
+
const now = Date.now();
|
|
300
|
+
const delay = durations && durations.expire === void 0 ? void 0 : Math.max(0, durations?.expire ?? 0) * 1e3;
|
|
301
|
+
if (delay !== void 0 && !Number.isFinite(delay)) throw new Error("Tag expiry duration must be finite");
|
|
302
|
+
await Promise.all(tags.map((tag) => this.cache.set(`_next_tag_state_:${tag}`, {
|
|
303
|
+
revalidatedAt: now,
|
|
304
|
+
expiredAt: delay === void 0 ? void 0 : now + delay
|
|
305
|
+
}, 0, 3 /* HIGH */)));
|
|
206
306
|
await this.cache.invalidateTags(tags);
|
|
207
307
|
}
|
|
208
308
|
};
|
package/dist/prisma/index.cjs
CHANGED
|
@@ -35,6 +35,22 @@ __export(prisma_exports, {
|
|
|
35
35
|
});
|
|
36
36
|
module.exports = __toCommonJS(prisma_exports);
|
|
37
37
|
var import_crypto = __toESM(require("crypto"), 1);
|
|
38
|
+
|
|
39
|
+
// src/utils/query-key.ts
|
|
40
|
+
function deterministicStringify(val) {
|
|
41
|
+
if (val instanceof Date) return `date:${JSON.stringify(val.toISOString())}`;
|
|
42
|
+
if (typeof val === "bigint") return `bigint:${val}`;
|
|
43
|
+
if (val instanceof Uint8Array) return `binary:${Buffer.from(val.buffer, val.byteOffset, val.byteLength).toString("base64")}`;
|
|
44
|
+
if (val && typeof val === "object" && typeof val.toJSON === "function") {
|
|
45
|
+
return deterministicStringify(val.toJSON());
|
|
46
|
+
}
|
|
47
|
+
if (val === null || typeof val !== "object") return JSON.stringify(val) ?? "undefined";
|
|
48
|
+
if (Array.isArray(val)) return `[${val.map(deterministicStringify).join(",")}]`;
|
|
49
|
+
const obj = val;
|
|
50
|
+
return `{${Object.keys(obj).sort().map((key) => `${JSON.stringify(key)}:${deterministicStringify(obj[key])}`).join(",")}}`;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// src/prisma/index.ts
|
|
38
54
|
var READ_OPERATIONS = /* @__PURE__ */ new Set([
|
|
39
55
|
"findUnique",
|
|
40
56
|
"findUniqueOrThrow",
|
|
@@ -56,17 +72,6 @@ var MUTATION_OPERATIONS = /* @__PURE__ */ new Set([
|
|
|
56
72
|
"delete",
|
|
57
73
|
"deleteMany"
|
|
58
74
|
]);
|
|
59
|
-
function deterministicStringify(val) {
|
|
60
|
-
if (val === null || typeof val !== "object") {
|
|
61
|
-
return JSON.stringify(val);
|
|
62
|
-
}
|
|
63
|
-
if (Array.isArray(val)) {
|
|
64
|
-
return `[${val.map(deterministicStringify).join(",")}]`;
|
|
65
|
-
}
|
|
66
|
-
const obj = val;
|
|
67
|
-
const keys = Object.keys(obj).sort();
|
|
68
|
-
return `{${keys.map((k) => `${JSON.stringify(k)}:${deterministicStringify(obj[k])}`).join(",")}}`;
|
|
69
|
-
}
|
|
70
75
|
function generatePrismaCacheKey(model, operation, args) {
|
|
71
76
|
const normalized = deterministicStringify({ model, operation, args });
|
|
72
77
|
const hash = import_crypto.default.createHash("sha256").update(normalized, "utf8").digest("hex").slice(0, 32);
|
|
@@ -80,19 +85,25 @@ function withTriCache(options) {
|
|
|
80
85
|
$allModels: {
|
|
81
86
|
async $allOperations({ model, operation, args, query }) {
|
|
82
87
|
const modelTag = model.toLowerCase();
|
|
88
|
+
const queryArgs = args ?? {};
|
|
89
|
+
const cacheConfig = queryArgs.cache;
|
|
90
|
+
let cleanArgs = args;
|
|
91
|
+
if (args && Object.prototype.hasOwnProperty.call(args, "cache")) {
|
|
92
|
+
const { cache: _cacheOpt, ...rest } = args;
|
|
93
|
+
cleanArgs = rest;
|
|
94
|
+
}
|
|
83
95
|
if (autoInvalidate && MUTATION_OPERATIONS.has(operation)) {
|
|
84
|
-
const
|
|
85
|
-
const result = await query(cleanMutationArgs);
|
|
96
|
+
const result = await query(cleanArgs);
|
|
86
97
|
await cache.invalidateTag(modelTag);
|
|
87
98
|
return result;
|
|
88
99
|
}
|
|
89
100
|
if (READ_OPERATIONS.has(operation)) {
|
|
90
|
-
|
|
91
|
-
|
|
101
|
+
if (cacheConfig === false) {
|
|
102
|
+
return query(cleanArgs);
|
|
103
|
+
}
|
|
92
104
|
if (cacheConfig !== void 0 || autoCache) {
|
|
93
105
|
const opts = typeof cacheConfig === "object" && cacheConfig !== null ? cacheConfig : {};
|
|
94
|
-
const
|
|
95
|
-
const key = opts.key ?? generatePrismaCacheKey(model, operation, cleanArgs);
|
|
106
|
+
const key = opts.key ?? generatePrismaCacheKey(model, operation, cleanArgs ?? {});
|
|
96
107
|
const tags = [.../* @__PURE__ */ new Set([modelTag, ...opts.tags ?? []])];
|
|
97
108
|
return cache.wrap(
|
|
98
109
|
key,
|
|
@@ -110,7 +121,7 @@ function withTriCache(options) {
|
|
|
110
121
|
);
|
|
111
122
|
}
|
|
112
123
|
}
|
|
113
|
-
return query(
|
|
124
|
+
return query(cleanArgs);
|
|
114
125
|
}
|
|
115
126
|
}
|
|
116
127
|
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { C as CacheService } from '../cache-service-BV5T8-20.cjs';
|
|
2
|
+
import { W as WrapOptions } from '../types-F8vRWMrE.cjs';
|
|
3
|
+
import 'crypto';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* tricache/prisma — First-class Prisma Client extension for TriCache.
|
|
7
|
+
*
|
|
8
|
+
* Usage:
|
|
9
|
+
* import { PrismaClient } from '@prisma/client';
|
|
10
|
+
* import { withTriCache } from 'tricache/prisma';
|
|
11
|
+
*
|
|
12
|
+
* const prisma = new PrismaClient().$extends(
|
|
13
|
+
* withTriCache({
|
|
14
|
+
* cache,
|
|
15
|
+
* defaultTtl: 300,
|
|
16
|
+
* autoInvalidate: true, // Invalidate model tags on create/update/delete
|
|
17
|
+
* })
|
|
18
|
+
* );
|
|
19
|
+
*
|
|
20
|
+
* // Query with cache options:
|
|
21
|
+
* const users = await prisma.user.findMany({
|
|
22
|
+
* where: { active: true },
|
|
23
|
+
* cache: { ttl: 60, tags: ['users'], swr: 30 },
|
|
24
|
+
* });
|
|
25
|
+
*/
|
|
26
|
+
|
|
27
|
+
interface PrismaCacheQueryOptions extends WrapOptions {
|
|
28
|
+
/** Explicit cache key. Defaults to SHA-256 hash of (model + operation + args). */
|
|
29
|
+
key?: string;
|
|
30
|
+
/** Explicit tags for invalidation. Automatically includes `[model.toLowerCase()]`. */
|
|
31
|
+
tags?: string[];
|
|
32
|
+
}
|
|
33
|
+
interface PrismaTriCacheOptions {
|
|
34
|
+
/** TriCache instance to use for caching. */
|
|
35
|
+
cache: CacheService;
|
|
36
|
+
/** Default TTL in seconds for cached queries (default: 300 s). */
|
|
37
|
+
defaultTtl?: number;
|
|
38
|
+
/** Whether to automatically invalidate model tags on write operations (default: true). */
|
|
39
|
+
autoInvalidate?: boolean;
|
|
40
|
+
/** Automatically cache all read queries even if `cache` options are not provided (default: false). */
|
|
41
|
+
autoCache?: boolean;
|
|
42
|
+
}
|
|
43
|
+
/** Generate a deterministic SHA-256 hash key for a Prisma query. */
|
|
44
|
+
declare function generatePrismaCacheKey(model: string, operation: string, args: unknown): string;
|
|
45
|
+
/**
|
|
46
|
+
* Creates a Prisma Client Extension for TriCache.
|
|
47
|
+
*/
|
|
48
|
+
declare function withTriCache(options: PrismaTriCacheOptions): {
|
|
49
|
+
name: string;
|
|
50
|
+
query: {
|
|
51
|
+
$allModels: {
|
|
52
|
+
$allOperations({ model, operation, args, query }: {
|
|
53
|
+
model: string;
|
|
54
|
+
operation: string;
|
|
55
|
+
args: Record<string, unknown> | undefined;
|
|
56
|
+
query: (args: unknown) => Promise<unknown>;
|
|
57
|
+
}): Promise<unknown>;
|
|
58
|
+
};
|
|
59
|
+
};
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
export { type PrismaCacheQueryOptions, type PrismaTriCacheOptions, generatePrismaCacheKey, withTriCache };
|
package/dist/prisma/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { C as CacheService } from '../cache-service-
|
|
2
|
-
import { W as WrapOptions } from '../types-
|
|
1
|
+
import { C as CacheService } from '../cache-service-tpyrXvlH.js';
|
|
2
|
+
import { W as WrapOptions } from '../types-F8vRWMrE.js';
|
|
3
3
|
import 'crypto';
|
|
4
4
|
|
|
5
5
|
/**
|
package/dist/prisma/index.js
CHANGED
|
@@ -1,3 +1,7 @@
|
|
|
1
|
+
import {
|
|
2
|
+
deterministicStringify
|
|
3
|
+
} from "../chunk-S5N65I45.js";
|
|
4
|
+
|
|
1
5
|
// src/prisma/index.ts
|
|
2
6
|
import crypto from "crypto";
|
|
3
7
|
var READ_OPERATIONS = /* @__PURE__ */ new Set([
|
|
@@ -21,17 +25,6 @@ var MUTATION_OPERATIONS = /* @__PURE__ */ new Set([
|
|
|
21
25
|
"delete",
|
|
22
26
|
"deleteMany"
|
|
23
27
|
]);
|
|
24
|
-
function deterministicStringify(val) {
|
|
25
|
-
if (val === null || typeof val !== "object") {
|
|
26
|
-
return JSON.stringify(val);
|
|
27
|
-
}
|
|
28
|
-
if (Array.isArray(val)) {
|
|
29
|
-
return `[${val.map(deterministicStringify).join(",")}]`;
|
|
30
|
-
}
|
|
31
|
-
const obj = val;
|
|
32
|
-
const keys = Object.keys(obj).sort();
|
|
33
|
-
return `{${keys.map((k) => `${JSON.stringify(k)}:${deterministicStringify(obj[k])}`).join(",")}}`;
|
|
34
|
-
}
|
|
35
28
|
function generatePrismaCacheKey(model, operation, args) {
|
|
36
29
|
const normalized = deterministicStringify({ model, operation, args });
|
|
37
30
|
const hash = crypto.createHash("sha256").update(normalized, "utf8").digest("hex").slice(0, 32);
|
|
@@ -45,19 +38,25 @@ function withTriCache(options) {
|
|
|
45
38
|
$allModels: {
|
|
46
39
|
async $allOperations({ model, operation, args, query }) {
|
|
47
40
|
const modelTag = model.toLowerCase();
|
|
41
|
+
const queryArgs = args ?? {};
|
|
42
|
+
const cacheConfig = queryArgs.cache;
|
|
43
|
+
let cleanArgs = args;
|
|
44
|
+
if (args && Object.prototype.hasOwnProperty.call(args, "cache")) {
|
|
45
|
+
const { cache: _cacheOpt, ...rest } = args;
|
|
46
|
+
cleanArgs = rest;
|
|
47
|
+
}
|
|
48
48
|
if (autoInvalidate && MUTATION_OPERATIONS.has(operation)) {
|
|
49
|
-
const
|
|
50
|
-
const result = await query(cleanMutationArgs);
|
|
49
|
+
const result = await query(cleanArgs);
|
|
51
50
|
await cache.invalidateTag(modelTag);
|
|
52
51
|
return result;
|
|
53
52
|
}
|
|
54
53
|
if (READ_OPERATIONS.has(operation)) {
|
|
55
|
-
|
|
56
|
-
|
|
54
|
+
if (cacheConfig === false) {
|
|
55
|
+
return query(cleanArgs);
|
|
56
|
+
}
|
|
57
57
|
if (cacheConfig !== void 0 || autoCache) {
|
|
58
58
|
const opts = typeof cacheConfig === "object" && cacheConfig !== null ? cacheConfig : {};
|
|
59
|
-
const
|
|
60
|
-
const key = opts.key ?? generatePrismaCacheKey(model, operation, cleanArgs);
|
|
59
|
+
const key = opts.key ?? generatePrismaCacheKey(model, operation, cleanArgs ?? {});
|
|
61
60
|
const tags = [.../* @__PURE__ */ new Set([modelTag, ...opts.tags ?? []])];
|
|
62
61
|
return cache.wrap(
|
|
63
62
|
key,
|
|
@@ -75,7 +74,7 @@ function withTriCache(options) {
|
|
|
75
74
|
);
|
|
76
75
|
}
|
|
77
76
|
}
|
|
78
|
-
return query(
|
|
77
|
+
return query(cleanArgs);
|
|
79
78
|
}
|
|
80
79
|
}
|
|
81
80
|
}
|