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
|
@@ -1,79 +1,97 @@
|
|
|
1
|
-
import type { CacheService } from '../
|
|
1
|
+
import type { CacheService } from '../cache-service.js';
|
|
2
|
+
import { INDEFINITE_TTL_SECONDS } from '../cache-service.js';
|
|
2
3
|
import type { NestCacheStore } from './types.js';
|
|
4
|
+
import { EventEmitter } from 'node:events';
|
|
3
5
|
|
|
4
6
|
/**
|
|
5
|
-
* TriCacheStore —
|
|
7
|
+
* TriCacheStore — Nest CACHE_MANAGER facade for CacheInterceptor and basic cache calls.
|
|
6
8
|
*
|
|
7
|
-
* Implements millisecond-based TTL semantics
|
|
8
|
-
* while dispatching to TriCache's three-tier engine with L1 memory, L1.5
|
|
9
|
+
* Implements millisecond-based TTL semantics for cache-manager v7's common API
|
|
10
|
+
* while dispatching to TriCache's three-tier engine with L1 memory, L1.5 disk spill,
|
|
9
11
|
* and L2 Redis/Valkey tiers.
|
|
10
12
|
*/
|
|
11
|
-
export class TriCacheStore implements NestCacheStore {
|
|
12
|
-
constructor(public readonly cache: CacheService) {}
|
|
13
|
+
export class TriCacheStore extends EventEmitter implements NestCacheStore {
|
|
14
|
+
constructor(public readonly cache: CacheService) { super(); }
|
|
13
15
|
|
|
14
16
|
/**
|
|
15
17
|
* Retrieve an item from the cache.
|
|
16
|
-
* Returns undefined on miss (matching cache-manager
|
|
18
|
+
* Returns undefined on miss (matching Keyv/cache-manager contract).
|
|
17
19
|
*/
|
|
18
|
-
async get<T>(key: string): Promise<T | undefined
|
|
20
|
+
async get<T>(key: string): Promise<T | undefined>;
|
|
21
|
+
async get<T>(key: string, options: { raw: true }): Promise<{ value: T; expires?: number } | undefined>;
|
|
22
|
+
async get<T>(key: string, options?: { raw?: boolean }): Promise<T | { value: T; expires?: number } | undefined> {
|
|
19
23
|
const val = await this.cache.peek<T>(key);
|
|
20
|
-
|
|
24
|
+
if (val === null) return undefined;
|
|
25
|
+
if (options?.raw) {
|
|
26
|
+
const remaining = this.cache.ttl(key);
|
|
27
|
+
return { value: val, expires: remaining === null ? undefined : Date.now() + remaining * 1000 };
|
|
28
|
+
}
|
|
29
|
+
return val;
|
|
21
30
|
}
|
|
22
31
|
|
|
23
32
|
/**
|
|
24
33
|
* Set an item in the cache.
|
|
25
34
|
* @param key - Cache key
|
|
26
35
|
* @param value - Cache value
|
|
27
|
-
* @param ttl - TTL in milliseconds
|
|
36
|
+
* @param ttl - TTL in milliseconds. Omitted uses the engine default (300 s);
|
|
37
|
+
* `0` means indefinite; positive values are converted to seconds.
|
|
28
38
|
*/
|
|
29
|
-
async set<T>(key: string, value: T, ttl?: number): Promise<
|
|
30
|
-
|
|
31
|
-
|
|
39
|
+
async set<T>(key: string, value: T, ttl?: number): Promise<T> {
|
|
40
|
+
await this.cache.set(key, value, this._ttlSeconds(ttl) ?? 300);
|
|
41
|
+
return value;
|
|
32
42
|
}
|
|
33
43
|
|
|
34
44
|
/**
|
|
35
45
|
* Remove an item from the cache.
|
|
36
46
|
*/
|
|
37
|
-
async del(key: string): Promise<
|
|
47
|
+
async del(key: string): Promise<boolean> {
|
|
38
48
|
await this.cache.delete(key);
|
|
49
|
+
return true;
|
|
39
50
|
}
|
|
40
51
|
|
|
41
52
|
/**
|
|
42
53
|
* Clear the entire cache namespace.
|
|
43
54
|
*/
|
|
44
|
-
async reset(): Promise<
|
|
55
|
+
async reset(): Promise<boolean> {
|
|
45
56
|
await this.cache.clear();
|
|
57
|
+
return true;
|
|
46
58
|
}
|
|
47
59
|
|
|
48
60
|
/**
|
|
49
|
-
* Batch get multiple items from the cache.
|
|
61
|
+
* Batch get multiple items from the cache. Accepts cache-manager 7's key array
|
|
62
|
+
* and the legacy cache-store variadic form.
|
|
50
63
|
*/
|
|
51
|
-
async mget<T>(
|
|
64
|
+
async mget<T>(keys: string[]): Promise<(T | undefined)[]>;
|
|
65
|
+
async mget<T>(...keys: string[]): Promise<(T | undefined)[]>;
|
|
66
|
+
async mget<T>(keysOrFirst: string[] | string = [], ...rest: string[]): Promise<(T | undefined)[]> {
|
|
67
|
+
const keys = Array.isArray(keysOrFirst) ? keysOrFirst : [keysOrFirst, ...rest];
|
|
52
68
|
if (keys.length === 0) return [];
|
|
53
|
-
return this.cache.mget<T>(keys
|
|
69
|
+
return this.cache.mget<T>(keys);
|
|
54
70
|
}
|
|
55
71
|
|
|
56
72
|
/**
|
|
57
73
|
* Batch set multiple entries with per-entry millisecond TTL.
|
|
58
74
|
*/
|
|
59
|
-
async mset(entries: Array<{ key: string; value: unknown; ttl?: number }>): Promise<
|
|
60
|
-
if (entries.length === 0) return;
|
|
75
|
+
async mset(entries: Array<{ key: string; value: unknown; ttl?: number }>): Promise<Array<{ key: string; value: unknown; ttl?: number }>> {
|
|
76
|
+
if (entries.length === 0) return [];
|
|
61
77
|
const batch: Record<string, { value: unknown; ttl?: number }> = {};
|
|
62
78
|
for (const e of entries) {
|
|
63
|
-
batch[e.key] = {
|
|
64
|
-
value: e.value,
|
|
65
|
-
ttl: typeof e.ttl === 'number' && e.ttl > 0 ? Math.round(e.ttl / 1000) : (e.ttl === 0 ? 0 : undefined),
|
|
66
|
-
};
|
|
79
|
+
batch[e.key] = { value: e.value, ttl: this._ttlSeconds(e.ttl) ?? 300 };
|
|
67
80
|
}
|
|
68
81
|
await this.cache.mset(batch);
|
|
82
|
+
return entries;
|
|
69
83
|
}
|
|
70
84
|
|
|
71
85
|
/**
|
|
72
86
|
* Batch delete multiple keys.
|
|
73
87
|
*/
|
|
74
|
-
async mdel(
|
|
75
|
-
|
|
88
|
+
async mdel(keys: string[]): Promise<boolean>;
|
|
89
|
+
async mdel(...keys: string[]): Promise<boolean>;
|
|
90
|
+
async mdel(keysOrFirst: string[] | string = [], ...rest: string[]): Promise<boolean> {
|
|
91
|
+
const keys = Array.isArray(keysOrFirst) ? keysOrFirst : [keysOrFirst, ...rest];
|
|
92
|
+
if (keys.length === 0) return true;
|
|
76
93
|
await this.cache.mdel(keys);
|
|
94
|
+
return true;
|
|
77
95
|
}
|
|
78
96
|
|
|
79
97
|
/**
|
|
@@ -94,4 +112,29 @@ export class TriCacheStore implements NestCacheStore {
|
|
|
94
112
|
const rem = this.cache.ttl(key);
|
|
95
113
|
return rem !== null ? rem * 1000 : undefined;
|
|
96
114
|
}
|
|
115
|
+
|
|
116
|
+
async wrap<T>(key: string, fetch: () => T | Promise<T>, ttl?: number, refreshThreshold?: number): Promise<T> {
|
|
117
|
+
const seconds = this._ttlSeconds(ttl);
|
|
118
|
+
const refreshAhead = ttl && refreshThreshold ? Math.max(0, Math.min(1, (ttl - refreshThreshold) / ttl)) : undefined;
|
|
119
|
+
return this.cache.wrap(key, async () => await fetch(), { ttl: seconds, refreshAhead });
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* Translate a cache-manager millisecond TTL into engine seconds using the same
|
|
124
|
+
* contract as `set()`: omitted keeps the engine default, `0` means indefinite,
|
|
125
|
+
* and positive values convert exactly (sub-second values round up).
|
|
126
|
+
*/
|
|
127
|
+
private _ttlSeconds(ttl: number | undefined): number | undefined {
|
|
128
|
+
if (ttl === undefined) return undefined;
|
|
129
|
+
if (typeof ttl !== 'number' || !Number.isFinite(ttl) || ttl < 0) {
|
|
130
|
+
throw new TypeError('TriCacheStore TTL must be a finite non-negative number of milliseconds');
|
|
131
|
+
}
|
|
132
|
+
if (ttl === 0) return INDEFINITE_TTL_SECONDS;
|
|
133
|
+
return Math.max(0.001, ttl / 1000);
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
cacheId(): string { return `tricache:${this.cache.options.namespace ?? 'default'}`; }
|
|
137
|
+
get stores(): unknown[] { return [this]; }
|
|
138
|
+
async clear(): Promise<boolean> { await this.reset(); return true; }
|
|
139
|
+
async disconnect(): Promise<undefined> { return undefined; }
|
|
97
140
|
}
|
package/src/nestjs/types.ts
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
import type { CacheOptions } from '../
|
|
1
|
+
import type { CacheOptions } from '../types.js';
|
|
2
2
|
|
|
3
3
|
export const TRICACHE_SERVICE = 'TRICACHE_SERVICE';
|
|
4
4
|
export const CACHE_MANAGER = 'CACHE_MANAGER';
|
|
5
5
|
|
|
6
|
-
export type InjectionToken = string | symbol | Function | Type<
|
|
6
|
+
export type InjectionToken = string | symbol | Function | Type<any>;
|
|
7
7
|
|
|
8
8
|
export interface Type<T = unknown> extends Function {
|
|
9
|
-
new (...args:
|
|
9
|
+
new (...args: any[]): T;
|
|
10
10
|
}
|
|
11
11
|
|
|
12
12
|
export interface ForwardReference<T = unknown> {
|
|
@@ -25,6 +25,8 @@ export interface ValueProvider<T = unknown> {
|
|
|
25
25
|
export interface ClassProvider<T = unknown> {
|
|
26
26
|
provide: InjectionToken;
|
|
27
27
|
useClass: Type<T>;
|
|
28
|
+
scope?: 0 | 1 | 2;
|
|
29
|
+
durable?: boolean;
|
|
28
30
|
}
|
|
29
31
|
|
|
30
32
|
export interface ExistingProvider {
|
|
@@ -35,7 +37,9 @@ export interface ExistingProvider {
|
|
|
35
37
|
export interface FactoryProvider<T = unknown> {
|
|
36
38
|
provide: InjectionToken;
|
|
37
39
|
useFactory: (...args: any[]) => T | Promise<T>;
|
|
38
|
-
inject?: Array<InjectionToken |
|
|
40
|
+
inject?: Array<InjectionToken | { token: InjectionToken; optional: boolean }>;
|
|
41
|
+
scope?: 0 | 1 | 2;
|
|
42
|
+
durable?: boolean;
|
|
39
43
|
}
|
|
40
44
|
|
|
41
45
|
export type Provider<T = unknown> =
|
|
@@ -46,10 +50,11 @@ export type Provider<T = unknown> =
|
|
|
46
50
|
| FactoryProvider<T>;
|
|
47
51
|
|
|
48
52
|
export interface DynamicModule {
|
|
49
|
-
module: Type<
|
|
53
|
+
module: Type<any>;
|
|
50
54
|
providers?: Provider[];
|
|
51
|
-
exports?: Array<DynamicModule |
|
|
52
|
-
imports?: Array<Type<
|
|
55
|
+
exports?: Array<DynamicModule | string | symbol | Provider | ForwardReference | Abstract<any> | Function>;
|
|
56
|
+
imports?: Array<Type<any> | DynamicModule | ForwardReference>;
|
|
57
|
+
controllers?: Type<any>[];
|
|
53
58
|
global?: boolean;
|
|
54
59
|
}
|
|
55
60
|
|
|
@@ -58,22 +63,31 @@ export interface TriCacheOptionsFactory {
|
|
|
58
63
|
}
|
|
59
64
|
|
|
60
65
|
export interface TriCacheAsyncOptions {
|
|
61
|
-
imports?: Array<Type<
|
|
62
|
-
useExisting?:
|
|
66
|
+
imports?: Array<Type<any> | DynamicModule | ForwardReference>;
|
|
67
|
+
useExisting?: InjectionToken;
|
|
63
68
|
useClass?: Type<TriCacheOptionsFactory>;
|
|
64
|
-
useFactory?: (...args:
|
|
65
|
-
inject?: Array<InjectionToken |
|
|
69
|
+
useFactory?: (...args: any[]) => Promise<CacheOptions> | CacheOptions;
|
|
70
|
+
inject?: Array<InjectionToken | { token: InjectionToken; optional: boolean }>;
|
|
66
71
|
extraProviders?: Provider[];
|
|
72
|
+
/** Whether to bind CACHE_MANAGER to TriCacheStore. Default: true. */
|
|
73
|
+
provideCacheManager?: boolean;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export interface TriCacheModuleOptions {
|
|
77
|
+
/** Set false when importing @nestjs/cache-manager CacheModule in the same application. Default: true. */
|
|
78
|
+
provideCacheManager?: boolean;
|
|
67
79
|
}
|
|
68
80
|
|
|
69
81
|
export interface NestCacheStore {
|
|
70
82
|
get<T>(key: string): Promise<T | undefined>;
|
|
71
|
-
set<T>(key: string, value: T, ttl?: number): Promise<
|
|
72
|
-
del(key: string): Promise<
|
|
73
|
-
reset(): Promise<
|
|
83
|
+
set<T>(key: string, value: T, ttl?: number): Promise<T>;
|
|
84
|
+
del(key: string): Promise<boolean>;
|
|
85
|
+
reset(): Promise<boolean>;
|
|
86
|
+
mget<T>(keys: string[]): Promise<(T | undefined)[]>;
|
|
74
87
|
mget<T>(...keys: string[]): Promise<(T | undefined)[]>;
|
|
75
|
-
mset(entries: Array<{ key: string; value: unknown; ttl?: number }>): Promise<
|
|
76
|
-
mdel(
|
|
88
|
+
mset(entries: Array<{ key: string; value: unknown; ttl?: number }>): Promise<Array<{ key: string; value: unknown; ttl?: number }>>;
|
|
89
|
+
mdel(keys: string[]): Promise<boolean>;
|
|
90
|
+
mdel(...keys: string[]): Promise<boolean>;
|
|
77
91
|
keys(pattern?: string): Promise<string[]>;
|
|
78
92
|
ttl(key: string): Promise<number | undefined>;
|
|
79
93
|
}
|
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
import { CacheService } from '../cache-service';
|
|
2
|
-
import { consoleLogger } from '../types';
|
|
2
|
+
import { CachePriority, consoleLogger } from '../types';
|
|
3
3
|
import type { ILogger } from '../types';
|
|
4
|
+
import { positiveLimit, WorkLimit } from '../utils/work-limits';
|
|
4
5
|
import type {
|
|
5
6
|
CacheHandlerValue,
|
|
7
|
+
NextCacheEntry,
|
|
6
8
|
StoredNextCacheEntry,
|
|
7
9
|
CacheHandlerContext,
|
|
8
10
|
NextCacheHandlerOptions,
|
|
@@ -55,22 +57,35 @@ export function resolveCacheLife(profileOrName?: CacheLifePreset | CacheLifeProf
|
|
|
55
57
|
/**
|
|
56
58
|
* Drain incoming web ReadableStream into a contiguous Node Buffer.
|
|
57
59
|
*/
|
|
58
|
-
async function drainStream(stream: ReadableStream<Uint8Array
|
|
60
|
+
async function drainStream(stream: ReadableStream<Uint8Array>, maxBytes: number, reserveBytes: (bytes: number) => void): Promise<Buffer> {
|
|
59
61
|
const reader = stream.getReader();
|
|
60
62
|
const chunks: Uint8Array[] = [];
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
63
|
+
let size = 0;
|
|
64
|
+
try {
|
|
65
|
+
while (true) {
|
|
66
|
+
const { done, value } = await reader.read();
|
|
67
|
+
if (done) break;
|
|
68
|
+
if (value) {
|
|
69
|
+
size += value.byteLength;
|
|
70
|
+
if (size > maxBytes) throw new Error('RSC stream exceeds maxStreamBytes');
|
|
71
|
+
if (value.byteLength > 0) reserveBytes(value.byteLength);
|
|
72
|
+
chunks.push(Uint8Array.from(value));
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
return Buffer.concat(chunks);
|
|
76
|
+
} catch (error) {
|
|
77
|
+
void reader.cancel(error).catch(() => {});
|
|
78
|
+
throw error;
|
|
79
|
+
} finally {
|
|
80
|
+
reader.releaseLock();
|
|
65
81
|
}
|
|
66
|
-
return Buffer.concat(chunks);
|
|
67
82
|
}
|
|
68
83
|
|
|
69
84
|
/**
|
|
70
85
|
* Construct a fresh, unlocked ReadableStream from a buffer.
|
|
71
86
|
*/
|
|
72
87
|
function createReadableStream(buffer: Buffer | Uint8Array): ReadableStream<Uint8Array> {
|
|
73
|
-
const uint8 =
|
|
88
|
+
const uint8 = Uint8Array.from(buffer);
|
|
74
89
|
return new ReadableStream<Uint8Array>({
|
|
75
90
|
start(controller) {
|
|
76
91
|
controller.enqueue(uint8);
|
|
@@ -87,9 +102,18 @@ function createReadableStream(buffer: Buffer | Uint8Array): ReadableStream<Uint8
|
|
|
87
102
|
export class TriCacheHandler {
|
|
88
103
|
protected readonly cache: CacheService;
|
|
89
104
|
protected readonly logger: ILogger;
|
|
105
|
+
private readonly maxStreamBytes: number;
|
|
106
|
+
private readonly streamBudget: { bytes: WorkLimit; streams: WorkLimit };
|
|
107
|
+
private static readonly streamBudgets = new WeakMap<CacheService, { bytes: WorkLimit; streams: WorkLimit }>();
|
|
108
|
+
private readonly pendingSets = new Map<string, { token: symbol; completion: Promise<void> }>();
|
|
109
|
+
private readonly observedTags = new Map<string, { version: number; observedAt: number }>();
|
|
90
110
|
|
|
91
111
|
constructor(options: NextCacheHandlerOptions = {}) {
|
|
92
112
|
this.logger = options.logger ?? consoleLogger;
|
|
113
|
+
this.maxStreamBytes = positiveLimit(options.maxStreamBytes, 16 * 1024 * 1024, 'maxStreamBytes');
|
|
114
|
+
const maxPendingStreamBytes = positiveLimit(options.maxPendingStreamBytes, 64 * 1024 * 1024, 'maxPendingStreamBytes');
|
|
115
|
+
const maxConcurrentStreams = positiveLimit(options.maxConcurrentStreams, 16, 'maxConcurrentStreams');
|
|
116
|
+
if (options.tagStrategy && options.tagStrategy !== 'generational') throw new Error('Next.js cache handlers require tagStrategy: generational');
|
|
93
117
|
|
|
94
118
|
const isBuildPhase =
|
|
95
119
|
options.isBuildPhase ??
|
|
@@ -104,34 +128,72 @@ export class TriCacheHandler {
|
|
|
104
128
|
cloneStrategy: options.cloneStrategy ?? 'none',
|
|
105
129
|
disableRedis: isBuildPhase ? true : options.disableRedis,
|
|
106
130
|
});
|
|
131
|
+
const existing = TriCacheHandler.streamBudgets.get(this.cache);
|
|
132
|
+
if (existing && (existing.bytes.maximum !== maxPendingStreamBytes || existing.streams.maximum !== maxConcurrentStreams)) {
|
|
133
|
+
throw new Error('Next handlers sharing one cache must use the same stream admission limits');
|
|
134
|
+
}
|
|
135
|
+
this.streamBudget = existing ?? { bytes: new WorkLimit(maxPendingStreamBytes, 'Next buffered stream bytes'),
|
|
136
|
+
streams: new WorkLimit(maxConcurrentStreams, 'Next concurrent streams') };
|
|
137
|
+
TriCacheHandler.streamBudgets.set(this.cache, this.streamBudget);
|
|
107
138
|
}
|
|
108
139
|
|
|
109
140
|
/**
|
|
110
141
|
* Get an entry from cache. Checks softTags against generational tag versions
|
|
111
142
|
* and returns a fresh unlocked ReadableStream if the stored value was a stream.
|
|
112
143
|
*/
|
|
113
|
-
async get(cacheKey: string,
|
|
144
|
+
async get(cacheKey: string, softTags: string[]): Promise<NextCacheEntry | undefined>;
|
|
145
|
+
async get(cacheKey: string, ctx?: CacheHandlerContext): Promise<CacheHandlerValue | undefined>;
|
|
146
|
+
async get(cacheKey: string, context?: CacheHandlerContext | string[]): Promise<CacheHandlerValue | undefined> {
|
|
147
|
+
let pending = this.pendingSets.get(cacheKey);
|
|
148
|
+
while (pending) {
|
|
149
|
+
await pending.completion;
|
|
150
|
+
pending = this.pendingSets.get(cacheKey);
|
|
151
|
+
}
|
|
152
|
+
const native = Array.isArray(context);
|
|
153
|
+
const ctx = native ? { softTags: context } : context;
|
|
114
154
|
const stored = await this.cache.peek<StoredNextCacheEntry>(cacheKey);
|
|
115
155
|
|
|
116
156
|
if (!stored || stored.data == null) {
|
|
117
157
|
return undefined;
|
|
118
158
|
}
|
|
119
159
|
|
|
120
|
-
|
|
121
|
-
if (
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
160
|
+
const expire = stored.expire ?? stored.ttl;
|
|
161
|
+
if (!Number.isFinite(stored.timestamp) || !Number.isFinite(expire) || Date.now() >= stored.timestamp + expire * 1000) return undefined;
|
|
162
|
+
const tags = [...new Set([...stored.tags, ...ctx?.softTags ?? []])];
|
|
163
|
+
const versions = await Promise.all(tags.map(tag => this.cache.getTagVersion(tag)));
|
|
164
|
+
const states = await this.cache.mget<{ revalidatedAt: number; expiredAt?: number }>(tags.map(tag => `_next_tag_state_:${tag}`));
|
|
165
|
+
let revalidate = stored.revalidate ?? stored.ttl;
|
|
166
|
+
for (let index = 0; index < tags.length; index++) {
|
|
167
|
+
const tag = tags[index];
|
|
168
|
+
const state = states[index];
|
|
169
|
+
const snapshot = stored.generations?.[tag] ?? stored.softTagVersions?.[tag];
|
|
170
|
+
if (state && (state.revalidatedAt > stored.timestamp || state.revalidatedAt === stored.timestamp && snapshot !== versions[index])) {
|
|
171
|
+
if (state.expiredAt !== undefined && state.expiredAt <= Date.now()) return undefined;
|
|
172
|
+
revalidate = -1; // Next.js serves stale and computes a replacement in the background.
|
|
173
|
+
} else if (!state && versions[index] > 0) {
|
|
174
|
+
if (snapshot !== undefined && versions[index] > snapshot) return undefined;
|
|
175
|
+
if (snapshot === undefined) {
|
|
176
|
+
const observed = this.observeTag(tag, versions[index]);
|
|
177
|
+
if (stored.timestamp <= observed) return undefined;
|
|
128
178
|
}
|
|
129
179
|
}
|
|
130
180
|
}
|
|
131
181
|
|
|
132
182
|
let val = stored.data;
|
|
133
|
-
if (stored.isStream
|
|
134
|
-
|
|
183
|
+
if (stored.isStream) {
|
|
184
|
+
let bytes: Uint8Array;
|
|
185
|
+
if (stored.streamEncoding === 'base64' && typeof val === 'string') {
|
|
186
|
+
if (val.length > Math.ceil(this.maxStreamBytes / 3) * 4) return undefined;
|
|
187
|
+
bytes = Buffer.from(val, 'base64');
|
|
188
|
+
}
|
|
189
|
+
else if (Buffer.isBuffer(val) || val instanceof Uint8Array) bytes = val;
|
|
190
|
+
else if (val && typeof val === 'object' && (val as { type?: unknown }).type === 'Buffer' && Array.isArray((val as { data?: unknown }).data)) {
|
|
191
|
+
bytes = Buffer.from((val as { data: number[] }).data);
|
|
192
|
+
} else return undefined;
|
|
193
|
+
if (bytes.length > this.maxStreamBytes) return undefined;
|
|
194
|
+
val = createReadableStream(bytes);
|
|
195
|
+
} else if (native) {
|
|
196
|
+
return undefined; // Legacy plain-object entries are not native RSC CacheEntry streams.
|
|
135
197
|
}
|
|
136
198
|
|
|
137
199
|
return {
|
|
@@ -139,6 +201,9 @@ export class TriCacheHandler {
|
|
|
139
201
|
tags: stored.tags,
|
|
140
202
|
timestamp: stored.timestamp,
|
|
141
203
|
ttl: stored.ttl,
|
|
204
|
+
stale: stored.stale ?? 300,
|
|
205
|
+
revalidate,
|
|
206
|
+
expire,
|
|
142
207
|
};
|
|
143
208
|
}
|
|
144
209
|
|
|
@@ -151,8 +216,19 @@ export class TriCacheHandler {
|
|
|
151
216
|
pendingEntry: Promise<CacheHandlerValue | null>,
|
|
152
217
|
ctx?: CacheHandlerContext,
|
|
153
218
|
): Promise<void> {
|
|
219
|
+
const token = Symbol(cacheKey);
|
|
220
|
+
let finish!: () => void;
|
|
221
|
+
const completion = new Promise<void>(resolve => { finish = resolve; });
|
|
222
|
+
this.pendingSets.set(cacheKey, { token, completion });
|
|
223
|
+
const byteReservation = this.streamBudget.bytes.reservation();
|
|
224
|
+
let releaseStream: (() => void) | undefined;
|
|
225
|
+
try {
|
|
226
|
+
const canCommit = this.cache.captureMutationFence(cacheKey);
|
|
154
227
|
const entry = await pendingEntry;
|
|
155
228
|
if (!entry || entry.value == null) return;
|
|
229
|
+
const tags = Array.from(new Set([...(entry.tags ?? []), ...(ctx?.tags ?? [])]));
|
|
230
|
+
const allTags = [...new Set([...tags, ...ctx?.softTags ?? []])];
|
|
231
|
+
const initialVersions = Object.fromEntries(await Promise.all(allTags.map(async tag => [tag, await this.cache.getTagVersion(tag)])));
|
|
156
232
|
|
|
157
233
|
let dataToStore = entry.value;
|
|
158
234
|
const isStream = Boolean(
|
|
@@ -162,8 +238,12 @@ export class TriCacheHandler {
|
|
|
162
238
|
|
|
163
239
|
if (isStream) {
|
|
164
240
|
try {
|
|
165
|
-
|
|
241
|
+
releaseStream = this.streamBudget.streams.acquire();
|
|
242
|
+
dataToStore = (await drainStream(dataToStore as ReadableStream<Uint8Array>, this.maxStreamBytes,
|
|
243
|
+
bytes => byteReservation.grow(bytes))).toString('base64');
|
|
166
244
|
} catch (streamErr) {
|
|
245
|
+
const stream = entry.value as ReadableStream<Uint8Array>;
|
|
246
|
+
if (!stream.locked) void stream.cancel(streamErr).catch(() => {});
|
|
167
247
|
this.logger.debug('Next.js cacheHandler: stream drain failed mid-flight, skipping cache', {
|
|
168
248
|
cacheKey,
|
|
169
249
|
error: (streamErr as Error).message,
|
|
@@ -176,6 +256,8 @@ export class TriCacheHandler {
|
|
|
176
256
|
const resolvedLife = resolveCacheLife(ctx?.cacheLife);
|
|
177
257
|
if (resolvedLife) {
|
|
178
258
|
ttl = resolvedLife.ttl;
|
|
259
|
+
} else if (typeof entry.revalidate === 'number') {
|
|
260
|
+
ttl = entry.revalidate;
|
|
179
261
|
} else if (typeof entry.ttl === 'number') {
|
|
180
262
|
ttl = entry.ttl;
|
|
181
263
|
} else if (typeof ctx?.revalidate === 'number') {
|
|
@@ -187,7 +269,15 @@ export class TriCacheHandler {
|
|
|
187
269
|
ttl = 300; // fallback default
|
|
188
270
|
}
|
|
189
271
|
|
|
190
|
-
const
|
|
272
|
+
const expire = entry.expire ?? (resolvedLife ? resolvedLife.ttl + resolvedLife.swr : ttl);
|
|
273
|
+
const timestamp = entry.timestamp ?? Date.now();
|
|
274
|
+
if (!Number.isFinite(expire) || expire <= 0 || !Number.isFinite(timestamp) || timestamp > Date.now() + (this.cache.options.clockSkewToleranceMs ?? 250)) return;
|
|
275
|
+
const remaining = timestamp + expire * 1000 - Date.now();
|
|
276
|
+
if (remaining <= 0 || !canCommit() || this.pendingSets.get(cacheKey)?.token !== token) return;
|
|
277
|
+
const finalVersions = await Promise.all(allTags.map(tag => this.cache.getTagVersion(tag)));
|
|
278
|
+
if (allTags.some((tag, index) => finalVersions[index] !== initialVersions[tag])) return;
|
|
279
|
+
const tagStates = await this.cache.mget<{ revalidatedAt: number }>(allTags.map(tag => `_next_tag_state_:${tag}`));
|
|
280
|
+
if (tagStates.some(state => state && state.revalidatedAt > timestamp)) return;
|
|
191
281
|
|
|
192
282
|
let softTagVersions: Record<string, number> | undefined;
|
|
193
283
|
if (ctx?.softTags && ctx.softTags.length > 0) {
|
|
@@ -203,52 +293,54 @@ export class TriCacheHandler {
|
|
|
203
293
|
data: dataToStore,
|
|
204
294
|
isStream,
|
|
205
295
|
tags,
|
|
206
|
-
timestamp
|
|
296
|
+
timestamp,
|
|
207
297
|
ttl,
|
|
208
298
|
softTagVersions,
|
|
299
|
+
generations: initialVersions,
|
|
300
|
+
stale: entry.stale ?? (typeof ctx?.cacheLife === 'string' ? PRESET_CACHE_LIFE_PROFILES[ctx.cacheLife as CacheLifePreset]?.stale : typeof ctx?.cacheLife === 'object' ? ctx.cacheLife.stale : undefined) ?? 300,
|
|
301
|
+
revalidate: ttl,
|
|
302
|
+
expire,
|
|
303
|
+
streamEncoding: isStream ? 'base64' : undefined,
|
|
209
304
|
};
|
|
210
305
|
|
|
211
|
-
|
|
306
|
+
if (!canCommit() || this.pendingSets.get(cacheKey)?.token !== token) return;
|
|
307
|
+
// Next owns delayed tag expiry. Eager engine tags would delete SWR entries
|
|
308
|
+
// before Next could return revalidate:-1 and schedule their replacement.
|
|
309
|
+
await this.cache.set(cacheKey, stored, remaining / 1000, undefined, { tags: [] });
|
|
310
|
+
} finally {
|
|
311
|
+
byteReservation.release();
|
|
312
|
+
releaseStream?.();
|
|
313
|
+
finish();
|
|
314
|
+
if (this.pendingSets.get(cacheKey)?.token === token) this.pendingSets.delete(cacheKey);
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
private observeTag(tag: string, version: number): number {
|
|
319
|
+
const known = this.observedTags.get(tag);
|
|
320
|
+
if (known?.version === version) return known.observedAt;
|
|
321
|
+
if (this.observedTags.size >= 10000) {
|
|
322
|
+
const oldest = this.observedTags.keys().next().value;
|
|
323
|
+
if (oldest !== undefined) this.observedTags.delete(oldest);
|
|
324
|
+
}
|
|
325
|
+
const observedAt = Date.now();
|
|
326
|
+
this.observedTags.set(tag, { version, observedAt });
|
|
327
|
+
return observedAt;
|
|
212
328
|
}
|
|
213
329
|
|
|
214
330
|
/**
|
|
215
|
-
*
|
|
216
|
-
* cached entry for the given tags, or 0 when nothing is tracked. Next.js
|
|
217
|
-
* uses this to decide whether a revalidation is due — a hardcoded 0 means
|
|
218
|
-
* "always expired", so this reads the real stored entries instead.
|
|
331
|
+
* Delegate soft-tag checking to get() using Next's Infinity sentinel.
|
|
219
332
|
*/
|
|
220
333
|
async getExpiration(tags: string[]): Promise<number> {
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
const tagSet = new Set(tags);
|
|
224
|
-
const l1 = (this.cache as unknown as { l1: { scan(fn: (key: string, entry: { expiresAt?: number; tagVersions?: Record<string, number> }) => void, prefixLen: number): void } }).l1;
|
|
225
|
-
l1.scan((key, entry) => {
|
|
226
|
-
if (!entry.tagVersions) return;
|
|
227
|
-
for (const tag of Object.keys(entry.tagVersions)) {
|
|
228
|
-
if (!tagSet.has(tag)) continue;
|
|
229
|
-
const exp = entry.expiresAt ?? 0;
|
|
230
|
-
if (exp > maxExpiration) maxExpiration = exp;
|
|
231
|
-
return;
|
|
232
|
-
}
|
|
233
|
-
}, 0);
|
|
234
|
-
return maxExpiration;
|
|
235
|
-
} catch (err) {
|
|
236
|
-
this.logger.debug('Next.js cacheHandler getExpiration fail-soft', { error: (err as Error).message });
|
|
237
|
-
return 0;
|
|
238
|
-
}
|
|
334
|
+
// This is the native contract's explicit delegation sentinel, not an entry expiry.
|
|
335
|
+
return tags.length ? Infinity : 0;
|
|
239
336
|
}
|
|
240
337
|
|
|
241
338
|
/**
|
|
242
|
-
*
|
|
243
|
-
* in-memory tag-version cache so every subsequent read re-syncs versions
|
|
244
|
-
* from Redis. The previous implementation was an empty try/catch.
|
|
339
|
+
* Force subsequent tag reads to re-sync without forgetting monotonic versions.
|
|
245
340
|
*/
|
|
246
341
|
async refreshTags(): Promise<void> {
|
|
247
342
|
try {
|
|
248
|
-
|
|
249
|
-
tagVersions?: Map<string, unknown>;
|
|
250
|
-
};
|
|
251
|
-
cache.tagVersions?.clear();
|
|
343
|
+
this.cache.refreshTagVersions();
|
|
252
344
|
} catch (err) {
|
|
253
345
|
this.logger.debug('Next.js cacheHandler refreshTags fail-soft catch', {
|
|
254
346
|
error: (err as Error).message,
|
|
@@ -259,8 +351,14 @@ export class TriCacheHandler {
|
|
|
259
351
|
/**
|
|
260
352
|
* Update or invalidate tags cluster-wide.
|
|
261
353
|
*/
|
|
262
|
-
async updateTags(tags: string[]): Promise<void> {
|
|
354
|
+
async updateTags(tags: string[], durations?: { expire?: number }): Promise<void> {
|
|
263
355
|
if (!tags || tags.length === 0) return;
|
|
356
|
+
const now = Date.now();
|
|
357
|
+
const delay = durations && durations.expire === undefined ? undefined : Math.max(0, durations?.expire ?? 0) * 1000;
|
|
358
|
+
if (delay !== undefined && !Number.isFinite(delay)) throw new Error('Tag expiry duration must be finite');
|
|
359
|
+
await Promise.all(tags.map(tag => this.cache.set(`_next_tag_state_:${tag}`, {
|
|
360
|
+
revalidatedAt: now, expiredAt: delay === undefined ? undefined : now + delay,
|
|
361
|
+
}, 0, CachePriority.HIGH)));
|
|
264
362
|
await this.cache.invalidateTags(tags);
|
|
265
363
|
}
|
|
266
364
|
}
|
package/src/next/index.ts
CHANGED
package/src/next/types.ts
CHANGED
|
@@ -20,6 +20,20 @@ export interface CacheHandlerValue {
|
|
|
20
20
|
* Remaining / configured TTL (seconds).
|
|
21
21
|
*/
|
|
22
22
|
ttl?: number;
|
|
23
|
+
/** Native Next.js CacheEntry timing fields, in seconds. */
|
|
24
|
+
stale?: number;
|
|
25
|
+
revalidate?: number;
|
|
26
|
+
expire?: number;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Complete native Next.js CacheEntry output, structurally checked against Next in tests. */
|
|
30
|
+
export interface NextCacheEntry {
|
|
31
|
+
value: ReadableStream<Uint8Array>;
|
|
32
|
+
tags: string[];
|
|
33
|
+
timestamp: number;
|
|
34
|
+
stale: number;
|
|
35
|
+
revalidate: number;
|
|
36
|
+
expire: number;
|
|
23
37
|
}
|
|
24
38
|
|
|
25
39
|
/**
|
|
@@ -38,6 +52,11 @@ export interface StoredNextCacheEntry {
|
|
|
38
52
|
ttl: number;
|
|
39
53
|
/** Captured soft tag versions at write time */
|
|
40
54
|
softTagVersions?: Record<string, number>;
|
|
55
|
+
generations?: Record<string, number>;
|
|
56
|
+
stale?: number;
|
|
57
|
+
revalidate?: number;
|
|
58
|
+
expire?: number;
|
|
59
|
+
streamEncoding?: 'base64';
|
|
41
60
|
}
|
|
42
61
|
|
|
43
62
|
export type CacheLifePreset =
|
|
@@ -79,6 +98,12 @@ export interface NextCacheHandlerOptions extends CacheOptions {
|
|
|
79
98
|
* or `process.env.NEXT_PHASE === 'phase-export'`.
|
|
80
99
|
*/
|
|
81
100
|
isBuildPhase?: boolean;
|
|
101
|
+
/** Maximum buffered RSC stream size. Default: 16 MiB. */
|
|
102
|
+
maxStreamBytes?: number;
|
|
103
|
+
/** Aggregate buffered input stream bytes per shared cache instance. Default: 64 MiB. Excludes encoded copies and caller-owned streams. */
|
|
104
|
+
maxPendingStreamBytes?: number;
|
|
105
|
+
/** Concurrent stream materializations per shared cache instance. Default: 16. Overflow skips caching and cancels that input stream. */
|
|
106
|
+
maxConcurrentStreams?: number;
|
|
82
107
|
}
|
|
83
108
|
|
|
84
109
|
/**
|