tricache 1.0.1 → 1.0.2

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.
Files changed (96) hide show
  1. package/README.md +36 -28
  2. package/dist/{cache-service-CREOp7MM.d.ts → cache-service-B108FzER.d.ts} +36 -4
  3. package/dist/cache-service-CWI4jkS7.d.cts +963 -0
  4. package/dist/{cache-service-MG7PN6MX.js → cache-service-GYPZFB7O.js} +2 -2
  5. package/dist/{chunk-IITRFWHY.js → chunk-EUKB7RKP.js} +21 -4
  6. package/dist/{chunk-2AJKEQMZ.js → chunk-H4GFLQ26.js} +7 -4
  7. package/dist/{chunk-7RV5ZVBB.js → chunk-JNSLMK4Q.js} +111 -29
  8. package/dist/chunk-OYDU3SMI.js +89 -0
  9. package/dist/{chunk-3I5L7K6I.js → chunk-VNRDL5RA.js} +102 -140
  10. package/dist/{chunk-JYQFQJNJ.js → chunk-WYF7NOAT.js} +1443 -609
  11. package/dist/cli.cjs +1367 -625
  12. package/dist/cli.d.cts +12 -0
  13. package/dist/cli.js +27 -6
  14. package/dist/dashboard/index.cjs +111 -29
  15. package/dist/dashboard/index.d.cts +185 -0
  16. package/dist/dashboard/index.d.ts +5 -3
  17. package/dist/dashboard/index.js +1 -1
  18. package/dist/drizzle/index.cjs +1370 -624
  19. package/dist/drizzle/index.d.cts +46 -0
  20. package/dist/drizzle/index.d.ts +2 -2
  21. package/dist/drizzle/index.js +1 -1
  22. package/dist/edge/index.cjs +227 -123
  23. package/dist/edge/index.d.cts +127 -0
  24. package/dist/edge/index.d.ts +3 -3
  25. package/dist/edge/index.js +201 -117
  26. package/dist/hono/index.cjs +1418 -644
  27. package/dist/hono/index.d.cts +93 -0
  28. package/dist/hono/index.d.ts +7 -5
  29. package/dist/hono/index.js +16 -9
  30. package/dist/{hono-DSV2ve66.d.ts → hono-3rDMYVtY.d.ts} +16 -3
  31. package/dist/hono-C886ok3X.d.cts +391 -0
  32. package/dist/http/index.cjs +1514 -679
  33. package/dist/http/index.d.cts +103 -0
  34. package/dist/http/index.d.ts +13 -5
  35. package/dist/http/index.js +92 -43
  36. package/dist/index.cjs +1671 -790
  37. package/dist/index.d.cts +1006 -0
  38. package/dist/index.d.ts +39 -8
  39. package/dist/index.js +8 -8
  40. package/dist/murmur3-CMGw9PbV.d.cts +98 -0
  41. package/dist/nestjs/index.cjs +1454 -649
  42. package/dist/nestjs/index.d.cts +285 -0
  43. package/dist/nestjs/index.d.ts +103 -30
  44. package/dist/nestjs/index.js +115 -32
  45. package/dist/next/index.cjs +1512 -718
  46. package/dist/next/index.d.cts +232 -0
  47. package/dist/next/index.d.ts +33 -11
  48. package/dist/next/index.js +172 -99
  49. package/dist/prisma/index.cjs +11 -1
  50. package/dist/prisma/index.d.cts +62 -0
  51. package/dist/prisma/index.d.ts +2 -2
  52. package/dist/prisma/index.js +11 -1
  53. package/dist/serialize-worker.d.cts +2 -0
  54. package/dist/{types-Dyip5wAl.d.ts → types-BA4pz1A0.d.cts} +24 -9
  55. package/dist/types-BA4pz1A0.d.ts +1519 -0
  56. package/dist/{utils-CEsU_Z0s.d.ts → utils-Bvzn-rKS.d.cts} +3 -1
  57. package/dist/utils-Bvzn-rKS.d.ts +29 -0
  58. package/package.json +96 -36
  59. package/src/adapters/auto-pipeliner.ts +107 -24
  60. package/src/adapters/node-redis.ts +106 -27
  61. package/src/cache-service.ts +802 -502
  62. package/src/cli.ts +24 -6
  63. package/src/cross-region.ts +21 -3
  64. package/src/dashboard/handler.ts +26 -6
  65. package/src/dashboard/html.ts +35 -10
  66. package/src/dashboard/index.ts +35 -13
  67. package/src/dashboard/types.ts +3 -1
  68. package/src/disk-tier.ts +171 -65
  69. package/src/edge/cache.ts +145 -97
  70. package/src/edge/hono.ts +23 -6
  71. package/src/edge/types.ts +2 -0
  72. package/src/hono/index.ts +19 -9
  73. package/src/http/express.ts +62 -17
  74. package/src/http/fastify.ts +35 -21
  75. package/src/http/utils.ts +54 -20
  76. package/src/ipc-telemetry.ts +35 -9
  77. package/src/nestjs/decorators.ts +1 -1
  78. package/src/nestjs/index.ts +2 -0
  79. package/src/nestjs/keyv-adapter.ts +68 -0
  80. package/src/nestjs/tricache.module.ts +13 -11
  81. package/src/nestjs/tricache.store.ts +51 -20
  82. package/src/nestjs/types.ts +29 -15
  83. package/src/next/cache-handler.ts +131 -53
  84. package/src/next/index.ts +1 -0
  85. package/src/next/types.ts +21 -0
  86. package/src/prisma/index.ts +12 -1
  87. package/src/smart-memory-cache.ts +63 -26
  88. package/src/types.ts +25 -2
  89. package/src/utils/cgroup.ts +12 -0
  90. package/src/utils/deadline.ts +14 -0
  91. package/src/utils/diagnostics.ts +27 -0
  92. package/src/utils/redis-slot.ts +13 -0
  93. package/src/wasm/bloom-filter-wasm.ts +9 -4
  94. package/src/worker-pool.ts +17 -8
  95. package/src/wtiny-lfu.ts +20 -6
  96. package/dist/chunk-BQRURGGD.js +0 -60
@@ -0,0 +1,68 @@
1
+ import { EventEmitter } from 'node:events';
2
+ import type { CacheService } from '../cache-service.js';
3
+
4
+ /**
5
+ * Relative-millisecond storage adapter for Keyv 5 / cache-manager 7.
6
+ * Wrap it in Keyv before passing it to Nest's CacheModule. Unlike TriCacheStore,
7
+ * this is a storage adapter, not the injected cache-manager facade.
8
+ * The supplied engine remains caller-owned when Keyv disconnects.
9
+ */
10
+ export class TriCacheKeyvAdapter extends EventEmitter {
11
+ private _namespace?: string;
12
+
13
+ constructor(public readonly cache: CacheService) { super(); }
14
+
15
+ get namespace(): string | undefined { return this._namespace; }
16
+ set namespace(value: string | undefined) {
17
+ if (value && ['*', '?', '[', ']', '\\'].some(character => value.includes(character))) {
18
+ throw new Error('Keyv namespace must not contain glob characters');
19
+ }
20
+ this._namespace = value;
21
+ }
22
+
23
+ async get<T = unknown>(key: string): Promise<T | undefined> {
24
+ const value = await this.cache.peek<T>(key);
25
+ return value === null ? undefined : value;
26
+ }
27
+
28
+ async set(key: string, value: unknown, ttl?: number): Promise<boolean> {
29
+ if (ttl !== undefined && (!Number.isFinite(ttl) || ttl < 0)) throw new Error('Keyv TTL must be finite and non-negative');
30
+ const ttlSeconds = ttl === undefined ? 0 : ttl / 1000;
31
+ await this.cache.set(key, value, ttlSeconds);
32
+ return true;
33
+ }
34
+
35
+ async delete(key: string): Promise<boolean> {
36
+ const found = await this.has(key);
37
+ await this.cache.delete(key);
38
+ return found;
39
+ }
40
+
41
+ async clear(): Promise<void> {
42
+ await this.cache.clear(this._namespace ? `${this._namespace}:` : undefined);
43
+ }
44
+
45
+ async has(key: string): Promise<boolean> { return await this.cache.peek(key) !== null; }
46
+
47
+ async getMany<T = unknown>(keys: string[]): Promise<(T | undefined)[]> {
48
+ return this.cache.mget<T>(keys);
49
+ }
50
+
51
+ async deleteMany(keys: string[]): Promise<boolean> {
52
+ const found = await this.cache.mget(keys);
53
+ await this.cache.mdel(keys);
54
+ return found.every(value => value !== undefined && value !== null);
55
+ }
56
+
57
+ async setMany(entries: Array<{ key: string; value: unknown; ttl?: number }>): Promise<boolean[]> {
58
+ const results = await Promise.all(entries.map(entry => this.set(entry.key, entry.value, entry.ttl)));
59
+ return results;
60
+ }
61
+
62
+ async hasMany(keys: string[]): Promise<boolean[]> {
63
+ const values = await this.cache.mget(keys);
64
+ return values.map(value => value !== null && value !== undefined);
65
+ }
66
+
67
+ async disconnect(): Promise<void> { /* The caller owns and closes the shared engine. */ }
68
+ }
@@ -7,6 +7,7 @@ import {
7
7
  type Provider,
8
8
  type TriCacheAsyncOptions,
9
9
  type TriCacheOptionsFactory,
10
+ type TriCacheModuleOptions,
10
11
  } from './types.js';
11
12
 
12
13
  /**
@@ -23,18 +24,18 @@ export class TriCacheModule {
23
24
  /**
24
25
  * Register TriCache module synchronously with static configuration options.
25
26
  */
26
- static register(options: CacheOptions = {}): DynamicModule {
27
+ static register(options: CacheOptions = {}, moduleOptions: TriCacheModuleOptions = {}): DynamicModule {
27
28
  const cache = CacheService.create(options);
28
- const store = new TriCacheStore(cache);
29
+ const provideCacheManager = moduleOptions.provideCacheManager ?? true;
29
30
 
30
31
  return {
31
32
  module: TriCacheModule,
32
33
  global: true,
33
34
  providers: [
34
35
  { provide: TRICACHE_SERVICE, useValue: cache },
35
- { provide: CACHE_MANAGER, useValue: store },
36
+ ...(provideCacheManager ? [{ provide: CACHE_MANAGER, useValue: new TriCacheStore(cache) }] : []),
36
37
  ],
37
- exports: [TRICACHE_SERVICE, CACHE_MANAGER],
38
+ exports: [TRICACHE_SERVICE, ...(provideCacheManager ? [CACHE_MANAGER] : [])],
38
39
  };
39
40
  }
40
41
 
@@ -43,6 +44,7 @@ export class TriCacheModule {
43
44
  */
44
45
  static registerAsync(asyncOptions: TriCacheAsyncOptions): DynamicModule {
45
46
  const asyncProviders = this.createAsyncProviders(asyncOptions);
47
+ const provideCacheManager = asyncOptions.provideCacheManager ?? true;
46
48
 
47
49
  return {
48
50
  module: TriCacheModule,
@@ -50,14 +52,14 @@ export class TriCacheModule {
50
52
  imports: asyncOptions.imports || [],
51
53
  providers: [
52
54
  ...asyncProviders,
53
- {
55
+ ...(provideCacheManager ? [{
54
56
  provide: CACHE_MANAGER,
55
- useFactory: (cache: any) => new TriCacheStore(cache as CacheService),
57
+ useFactory: (cache: CacheService) => new TriCacheStore(cache),
56
58
  inject: [TRICACHE_SERVICE],
57
- },
59
+ }] : []),
58
60
  ...(asyncOptions.extraProviders || []),
59
61
  ],
60
- exports: [TRICACHE_SERVICE, CACHE_MANAGER],
62
+ exports: [TRICACHE_SERVICE, ...(provideCacheManager ? [CACHE_MANAGER] : [])],
61
63
  };
62
64
  }
63
65
 
@@ -83,7 +85,7 @@ export class TriCacheModule {
83
85
  if (options.useFactory) {
84
86
  return {
85
87
  provide: TRICACHE_SERVICE,
86
- useFactory: async (...args: any[]) => {
88
+ useFactory: async (...args: unknown[]) => {
87
89
  const cacheOptions = await options.useFactory!(...args);
88
90
  return CacheService.create(cacheOptions);
89
91
  },
@@ -94,8 +96,8 @@ export class TriCacheModule {
94
96
  const injectToken = options.useExisting || options.useClass!;
95
97
  return {
96
98
  provide: TRICACHE_SERVICE,
97
- useFactory: async (optionsFactory: any) => {
98
- const cacheOptions = await (optionsFactory as TriCacheOptionsFactory).createTriCacheOptions();
99
+ useFactory: async (optionsFactory: TriCacheOptionsFactory) => {
100
+ const cacheOptions = await optionsFactory.createTriCacheOptions();
99
101
  return CacheService.create(cacheOptions);
100
102
  },
101
103
  inject: [injectToken],
@@ -1,23 +1,31 @@
1
1
  import type { CacheService } from '../index.js';
2
2
  import type { NestCacheStore } from './types.js';
3
+ import { EventEmitter } from 'node:events';
3
4
 
4
5
  /**
5
- * TriCacheStore — drop-in CacheStore conforming to @nestjs/cache-manager and cache-manager v5/v6.
6
+ * TriCacheStore — Nest CACHE_MANAGER facade for CacheInterceptor and basic cache calls.
6
7
  *
7
- * Implements millisecond-based TTL semantics expected by cache-manager v5/v6
8
- * while dispatching to TriCache's three-tier engine with L1 memory, L1.5 NVMe disk spill,
8
+ * Implements millisecond-based TTL semantics for cache-manager v7's common API
9
+ * while dispatching to TriCache's three-tier engine with L1 memory, L1.5 disk spill,
9
10
  * and L2 Redis/Valkey tiers.
10
11
  */
11
- export class TriCacheStore implements NestCacheStore {
12
- constructor(public readonly cache: CacheService) {}
12
+ export class TriCacheStore extends EventEmitter implements NestCacheStore {
13
+ constructor(public readonly cache: CacheService) { super(); }
13
14
 
14
15
  /**
15
16
  * Retrieve an item from the cache.
16
- * Returns undefined on miss (matching cache-manager v5/v6 contract).
17
+ * Returns undefined on miss (matching Keyv/cache-manager contract).
17
18
  */
18
- async get<T>(key: string): Promise<T | undefined> {
19
+ async get<T>(key: string): Promise<T | undefined>;
20
+ async get<T>(key: string, options: { raw: true }): Promise<{ value: T; expires?: number } | undefined>;
21
+ async get<T>(key: string, options?: { raw?: boolean }): Promise<T | { value: T; expires?: number } | undefined> {
19
22
  const val = await this.cache.peek<T>(key);
20
- return val !== null ? val : undefined;
23
+ if (val === null) return undefined;
24
+ if (options?.raw) {
25
+ const remaining = this.cache.ttl(key);
26
+ return { value: val, expires: remaining === null ? undefined : Date.now() + remaining * 1000 };
27
+ }
28
+ return val;
21
29
  }
22
30
 
23
31
  /**
@@ -26,54 +34,66 @@ export class TriCacheStore implements NestCacheStore {
26
34
  * @param value - Cache value
27
35
  * @param ttl - TTL in milliseconds (0 = indefinite / default engine TTL)
28
36
  */
29
- async set<T>(key: string, value: T, ttl?: number): Promise<void> {
30
- const ttlSeconds = typeof ttl === 'number' && ttl > 0 ? Math.round(ttl / 1000) : (ttl === 0 ? 0 : undefined);
37
+ async set<T>(key: string, value: T, ttl?: number): Promise<T> {
38
+ const ttlSeconds = typeof ttl === 'number' && ttl > 0 ? ttl / 1000 : (ttl === 0 ? 0 : undefined);
31
39
  await this.cache.set(key, value, ttlSeconds);
40
+ return value;
32
41
  }
33
42
 
34
43
  /**
35
44
  * Remove an item from the cache.
36
45
  */
37
- async del(key: string): Promise<void> {
46
+ async del(key: string): Promise<boolean> {
38
47
  await this.cache.delete(key);
48
+ return true;
39
49
  }
40
50
 
41
51
  /**
42
52
  * Clear the entire cache namespace.
43
53
  */
44
- async reset(): Promise<void> {
54
+ async reset(): Promise<boolean> {
45
55
  await this.cache.clear();
56
+ return true;
46
57
  }
47
58
 
48
59
  /**
49
- * Batch get multiple items from the cache.
60
+ * Batch get multiple items from the cache. Accepts cache-manager 7's key array
61
+ * and the legacy cache-store variadic form.
50
62
  */
51
- async mget<T>(...keys: string[]): Promise<(T | undefined)[]> {
63
+ async mget<T>(keys: string[]): Promise<(T | undefined)[]>;
64
+ async mget<T>(...keys: string[]): Promise<(T | undefined)[]>;
65
+ async mget<T>(keysOrFirst: string[] | string = [], ...rest: string[]): Promise<(T | undefined)[]> {
66
+ const keys = Array.isArray(keysOrFirst) ? keysOrFirst : [keysOrFirst, ...rest];
52
67
  if (keys.length === 0) return [];
53
- return this.cache.mget<T>(keys, async () => ({}));
68
+ return this.cache.mget<T>(keys);
54
69
  }
55
70
 
56
71
  /**
57
72
  * Batch set multiple entries with per-entry millisecond TTL.
58
73
  */
59
- async mset(entries: Array<{ key: string; value: unknown; ttl?: number }>): Promise<void> {
60
- if (entries.length === 0) return;
74
+ async mset(entries: Array<{ key: string; value: unknown; ttl?: number }>): Promise<Array<{ key: string; value: unknown; ttl?: number }>> {
75
+ if (entries.length === 0) return [];
61
76
  const batch: Record<string, { value: unknown; ttl?: number }> = {};
62
77
  for (const e of entries) {
63
78
  batch[e.key] = {
64
79
  value: e.value,
65
- ttl: typeof e.ttl === 'number' && e.ttl > 0 ? Math.round(e.ttl / 1000) : (e.ttl === 0 ? 0 : undefined),
80
+ ttl: typeof e.ttl === 'number' && e.ttl > 0 ? e.ttl / 1000 : (e.ttl === 0 ? 0 : undefined),
66
81
  };
67
82
  }
68
83
  await this.cache.mset(batch);
84
+ return entries;
69
85
  }
70
86
 
71
87
  /**
72
88
  * Batch delete multiple keys.
73
89
  */
74
- async mdel(...keys: string[]): Promise<void> {
75
- if (keys.length === 0) return;
90
+ async mdel(keys: string[]): Promise<boolean>;
91
+ async mdel(...keys: string[]): Promise<boolean>;
92
+ async mdel(keysOrFirst: string[] | string = [], ...rest: string[]): Promise<boolean> {
93
+ const keys = Array.isArray(keysOrFirst) ? keysOrFirst : [keysOrFirst, ...rest];
94
+ if (keys.length === 0) return true;
76
95
  await this.cache.mdel(keys);
96
+ return true;
77
97
  }
78
98
 
79
99
  /**
@@ -94,4 +114,15 @@ export class TriCacheStore implements NestCacheStore {
94
114
  const rem = this.cache.ttl(key);
95
115
  return rem !== null ? rem * 1000 : undefined;
96
116
  }
117
+
118
+ async wrap<T>(key: string, fetch: () => T | Promise<T>, ttl?: number, refreshThreshold?: number): Promise<T> {
119
+ const seconds = ttl === undefined ? 0 : ttl / 1000;
120
+ const refreshAhead = ttl && refreshThreshold ? Math.max(0, Math.min(1, (ttl - refreshThreshold) / ttl)) : undefined;
121
+ return this.cache.wrap(key, async () => await fetch(), { ttl: seconds, refreshAhead });
122
+ }
123
+
124
+ cacheId(): string { return `tricache:${this.cache.options.namespace ?? 'default'}`; }
125
+ get stores(): unknown[] { return [this]; }
126
+ async clear(): Promise<boolean> { await this.reset(); return true; }
127
+ async disconnect(): Promise<undefined> { return undefined; }
97
128
  }
@@ -3,10 +3,10 @@ import type { CacheOptions } from '../index.js';
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<unknown>;
6
+ export type InjectionToken = string | symbol | Function | Type<any>;
7
7
 
8
8
  export interface Type<T = unknown> extends Function {
9
- new (...args: unknown[]): T;
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 | any>;
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<unknown>;
53
+ module: Type<any>;
50
54
  providers?: Provider[];
51
- exports?: Array<DynamicModule | Promise<DynamicModule> | string | symbol | Provider | Function | unknown>;
52
- imports?: Array<Type<unknown> | DynamicModule | Promise<DynamicModule> | ForwardReference>;
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<unknown> | DynamicModule | Promise<DynamicModule> | ForwardReference>;
62
- useExisting?: Type<TriCacheOptionsFactory>;
66
+ imports?: Array<Type<any> | DynamicModule | ForwardReference>;
67
+ useExisting?: InjectionToken;
63
68
  useClass?: Type<TriCacheOptionsFactory>;
64
- useFactory?: (...args: unknown[]) => Promise<CacheOptions> | CacheOptions;
65
- inject?: Array<InjectionToken | unknown>;
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<void>;
72
- del(key: string): Promise<void>;
73
- reset(): Promise<void>;
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<void>;
76
- mdel(...keys: string[]): Promise<void>;
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,9 @@
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
4
  import type {
5
5
  CacheHandlerValue,
6
+ NextCacheEntry,
6
7
  StoredNextCacheEntry,
7
8
  CacheHandlerContext,
8
9
  NextCacheHandlerOptions,
@@ -55,22 +56,34 @@ export function resolveCacheLife(profileOrName?: CacheLifePreset | CacheLifeProf
55
56
  /**
56
57
  * Drain incoming web ReadableStream into a contiguous Node Buffer.
57
58
  */
58
- async function drainStream(stream: ReadableStream<Uint8Array>): Promise<Buffer> {
59
+ async function drainStream(stream: ReadableStream<Uint8Array>, maxBytes: number): Promise<Buffer> {
59
60
  const reader = stream.getReader();
60
61
  const chunks: Uint8Array[] = [];
61
- while (true) {
62
- const { done, value } = await reader.read();
63
- if (done) break;
64
- if (value) chunks.push(value);
62
+ let size = 0;
63
+ try {
64
+ while (true) {
65
+ const { done, value } = await reader.read();
66
+ if (done) break;
67
+ if (value) {
68
+ size += value.byteLength;
69
+ if (size > maxBytes) throw new Error('RSC stream exceeds maxStreamBytes');
70
+ chunks.push(Uint8Array.from(value));
71
+ }
72
+ }
73
+ return Buffer.concat(chunks);
74
+ } catch (error) {
75
+ void reader.cancel(error).catch(() => {});
76
+ throw error;
77
+ } finally {
78
+ reader.releaseLock();
65
79
  }
66
- return Buffer.concat(chunks);
67
80
  }
68
81
 
69
82
  /**
70
83
  * Construct a fresh, unlocked ReadableStream from a buffer.
71
84
  */
72
85
  function createReadableStream(buffer: Buffer | Uint8Array): ReadableStream<Uint8Array> {
73
- const uint8 = buffer instanceof Uint8Array ? buffer : new Uint8Array(buffer);
86
+ const uint8 = Uint8Array.from(buffer);
74
87
  return new ReadableStream<Uint8Array>({
75
88
  start(controller) {
76
89
  controller.enqueue(uint8);
@@ -87,9 +100,15 @@ function createReadableStream(buffer: Buffer | Uint8Array): ReadableStream<Uint8
87
100
  export class TriCacheHandler {
88
101
  protected readonly cache: CacheService;
89
102
  protected readonly logger: ILogger;
103
+ private readonly maxStreamBytes: number;
104
+ private readonly pendingSets = new Map<string, { token: symbol; completion: Promise<void> }>();
105
+ private readonly observedTags = new Map<string, { version: number; observedAt: number }>();
90
106
 
91
107
  constructor(options: NextCacheHandlerOptions = {}) {
92
108
  this.logger = options.logger ?? consoleLogger;
109
+ this.maxStreamBytes = options.maxStreamBytes ?? 16 * 1024 * 1024;
110
+ if (!Number.isFinite(this.maxStreamBytes) || this.maxStreamBytes <= 0) throw new Error('maxStreamBytes must be finite and positive');
111
+ if (options.tagStrategy && options.tagStrategy !== 'generational') throw new Error('Next.js cache handlers require tagStrategy: generational');
93
112
 
94
113
  const isBuildPhase =
95
114
  options.isBuildPhase ??
@@ -110,28 +129,59 @@ export class TriCacheHandler {
110
129
  * Get an entry from cache. Checks softTags against generational tag versions
111
130
  * and returns a fresh unlocked ReadableStream if the stored value was a stream.
112
131
  */
113
- async get(cacheKey: string, ctx?: CacheHandlerContext): Promise<CacheHandlerValue | undefined> {
132
+ async get(cacheKey: string, softTags: string[]): Promise<NextCacheEntry | undefined>;
133
+ async get(cacheKey: string, ctx?: CacheHandlerContext): Promise<CacheHandlerValue | undefined>;
134
+ async get(cacheKey: string, context?: CacheHandlerContext | string[]): Promise<CacheHandlerValue | undefined> {
135
+ let pending = this.pendingSets.get(cacheKey);
136
+ while (pending) {
137
+ await pending.completion;
138
+ pending = this.pendingSets.get(cacheKey);
139
+ }
140
+ const native = Array.isArray(context);
141
+ const ctx = native ? { softTags: context } : context;
114
142
  const stored = await this.cache.peek<StoredNextCacheEntry>(cacheKey);
115
143
 
116
144
  if (!stored || stored.data == null) {
117
145
  return undefined;
118
146
  }
119
147
 
120
- // Check softTags at read time (e.g. Next.js 16 layout / page boundaries)
121
- if (ctx?.softTags && ctx.softTags.length > 0) {
122
- const softTags = ctx.softTags;
123
- const currentVers = await Promise.all(softTags.map(st => this.cache.getTagVersion(st)));
124
- for (let i = 0; i < softTags.length; i++) {
125
- const storedSoftVer = stored.softTagVersions?.[softTags[i]] ?? 0;
126
- if (currentVers[i] > storedSoftVer) {
127
- return undefined;
148
+ const expire = stored.expire ?? stored.ttl;
149
+ if (!Number.isFinite(stored.timestamp) || !Number.isFinite(expire) || Date.now() >= stored.timestamp + expire * 1000) return undefined;
150
+ const tags = [...new Set([...stored.tags, ...ctx?.softTags ?? []])];
151
+ const versions = await Promise.all(tags.map(tag => this.cache.getTagVersion(tag)));
152
+ const states = await this.cache.mget<{ revalidatedAt: number; expiredAt?: number }>(tags.map(tag => `_next_tag_state_:${tag}`));
153
+ let revalidate = stored.revalidate ?? stored.ttl;
154
+ for (let index = 0; index < tags.length; index++) {
155
+ const tag = tags[index];
156
+ const state = states[index];
157
+ const snapshot = stored.generations?.[tag] ?? stored.softTagVersions?.[tag];
158
+ if (state && (state.revalidatedAt > stored.timestamp || state.revalidatedAt === stored.timestamp && snapshot !== versions[index])) {
159
+ if (state.expiredAt !== undefined && state.expiredAt <= Date.now()) return undefined;
160
+ revalidate = -1; // Next.js serves stale and computes a replacement in the background.
161
+ } else if (!state && versions[index] > 0) {
162
+ if (snapshot !== undefined && versions[index] > snapshot) return undefined;
163
+ if (snapshot === undefined) {
164
+ const observed = this.observeTag(tag, versions[index]);
165
+ if (stored.timestamp <= observed) return undefined;
128
166
  }
129
167
  }
130
168
  }
131
169
 
132
170
  let val = stored.data;
133
- if (stored.isStream && (Buffer.isBuffer(val) || val instanceof Uint8Array)) {
134
- val = createReadableStream(val);
171
+ if (stored.isStream) {
172
+ let bytes: Uint8Array;
173
+ if (stored.streamEncoding === 'base64' && typeof val === 'string') {
174
+ if (val.length > Math.ceil(this.maxStreamBytes / 3) * 4) return undefined;
175
+ bytes = Buffer.from(val, 'base64');
176
+ }
177
+ else if (Buffer.isBuffer(val) || val instanceof Uint8Array) bytes = val;
178
+ else if (val && typeof val === 'object' && (val as { type?: unknown }).type === 'Buffer' && Array.isArray((val as { data?: unknown }).data)) {
179
+ bytes = Buffer.from((val as { data: number[] }).data);
180
+ } else return undefined;
181
+ if (bytes.length > this.maxStreamBytes) return undefined;
182
+ val = createReadableStream(bytes);
183
+ } else if (native) {
184
+ return undefined; // Legacy plain-object entries are not native RSC CacheEntry streams.
135
185
  }
136
186
 
137
187
  return {
@@ -139,6 +189,9 @@ export class TriCacheHandler {
139
189
  tags: stored.tags,
140
190
  timestamp: stored.timestamp,
141
191
  ttl: stored.ttl,
192
+ stale: stored.stale ?? 300,
193
+ revalidate,
194
+ expire,
142
195
  };
143
196
  }
144
197
 
@@ -151,8 +204,17 @@ export class TriCacheHandler {
151
204
  pendingEntry: Promise<CacheHandlerValue | null>,
152
205
  ctx?: CacheHandlerContext,
153
206
  ): Promise<void> {
207
+ const token = Symbol(cacheKey);
208
+ let finish!: () => void;
209
+ const completion = new Promise<void>(resolve => { finish = resolve; });
210
+ this.pendingSets.set(cacheKey, { token, completion });
211
+ try {
212
+ const canCommit = this.cache.captureMutationFence(cacheKey);
154
213
  const entry = await pendingEntry;
155
214
  if (!entry || entry.value == null) return;
215
+ const tags = Array.from(new Set([...(entry.tags ?? []), ...(ctx?.tags ?? [])]));
216
+ const allTags = [...new Set([...tags, ...ctx?.softTags ?? []])];
217
+ const initialVersions = Object.fromEntries(await Promise.all(allTags.map(async tag => [tag, await this.cache.getTagVersion(tag)])));
156
218
 
157
219
  let dataToStore = entry.value;
158
220
  const isStream = Boolean(
@@ -162,7 +224,7 @@ export class TriCacheHandler {
162
224
 
163
225
  if (isStream) {
164
226
  try {
165
- dataToStore = await drainStream(dataToStore as ReadableStream<Uint8Array>);
227
+ dataToStore = (await drainStream(dataToStore as ReadableStream<Uint8Array>, this.maxStreamBytes)).toString('base64');
166
228
  } catch (streamErr) {
167
229
  this.logger.debug('Next.js cacheHandler: stream drain failed mid-flight, skipping cache', {
168
230
  cacheKey,
@@ -176,6 +238,8 @@ export class TriCacheHandler {
176
238
  const resolvedLife = resolveCacheLife(ctx?.cacheLife);
177
239
  if (resolvedLife) {
178
240
  ttl = resolvedLife.ttl;
241
+ } else if (typeof entry.revalidate === 'number') {
242
+ ttl = entry.revalidate;
179
243
  } else if (typeof entry.ttl === 'number') {
180
244
  ttl = entry.ttl;
181
245
  } else if (typeof ctx?.revalidate === 'number') {
@@ -187,7 +251,15 @@ export class TriCacheHandler {
187
251
  ttl = 300; // fallback default
188
252
  }
189
253
 
190
- const tags = Array.from(new Set([...(entry.tags ?? []), ...(ctx?.tags ?? [])]));
254
+ const expire = entry.expire ?? (resolvedLife ? resolvedLife.ttl + resolvedLife.swr : ttl);
255
+ const timestamp = entry.timestamp ?? Date.now();
256
+ if (!Number.isFinite(expire) || expire <= 0 || !Number.isFinite(timestamp) || timestamp > Date.now() + (this.cache.options.clockSkewToleranceMs ?? 250)) return;
257
+ const remaining = timestamp + expire * 1000 - Date.now();
258
+ if (remaining <= 0 || !canCommit() || this.pendingSets.get(cacheKey)?.token !== token) return;
259
+ const finalVersions = await Promise.all(allTags.map(tag => this.cache.getTagVersion(tag)));
260
+ if (allTags.some((tag, index) => finalVersions[index] !== initialVersions[tag])) return;
261
+ const tagStates = await this.cache.mget<{ revalidatedAt: number }>(allTags.map(tag => `_next_tag_state_:${tag}`));
262
+ if (tagStates.some(state => state && state.revalidatedAt > timestamp)) return;
191
263
 
192
264
  let softTagVersions: Record<string, number> | undefined;
193
265
  if (ctx?.softTags && ctx.softTags.length > 0) {
@@ -203,52 +275,52 @@ export class TriCacheHandler {
203
275
  data: dataToStore,
204
276
  isStream,
205
277
  tags,
206
- timestamp: entry.timestamp ?? Date.now(),
278
+ timestamp,
207
279
  ttl,
208
280
  softTagVersions,
281
+ generations: initialVersions,
282
+ 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,
283
+ revalidate: ttl,
284
+ expire,
285
+ streamEncoding: isStream ? 'base64' : undefined,
209
286
  };
210
287
 
211
- await this.cache.set(cacheKey, stored, ttl, undefined, tags.length > 0 ? { tags } : undefined);
288
+ if (!canCommit() || this.pendingSets.get(cacheKey)?.token !== token) return;
289
+ // Next owns delayed tag expiry. Eager engine tags would delete SWR entries
290
+ // before Next could return revalidate:-1 and schedule their replacement.
291
+ await this.cache.set(cacheKey, stored, remaining / 1000, undefined, { tags: [] });
292
+ } finally {
293
+ finish();
294
+ if (this.pendingSets.get(cacheKey)?.token === token) this.pendingSets.delete(cacheKey);
295
+ }
296
+ }
297
+
298
+ private observeTag(tag: string, version: number): number {
299
+ const known = this.observedTags.get(tag);
300
+ if (known?.version === version) return known.observedAt;
301
+ if (this.observedTags.size >= 10000) {
302
+ const oldest = this.observedTags.keys().next().value;
303
+ if (oldest !== undefined) this.observedTags.delete(oldest);
304
+ }
305
+ const observedAt = Date.now();
306
+ this.observedTags.set(tag, { version, observedAt });
307
+ return observedAt;
212
308
  }
213
309
 
214
310
  /**
215
- * Returns the expiration timestamp (ms since epoch) of the most relevant
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.
311
+ * Delegate soft-tag checking to get() using Next's Infinity sentinel.
219
312
  */
220
313
  async getExpiration(tags: string[]): Promise<number> {
221
- try {
222
- let maxExpiration = 0;
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
- }
314
+ // This is the native contract's explicit delegation sentinel, not an entry expiry.
315
+ return tags.length ? Infinity : 0;
239
316
  }
240
317
 
241
318
  /**
242
- * Reconcile local generational tag knowledge against shared state: drops the
243
- * in-memory tag-version cache so every subsequent read re-syncs versions
244
- * from Redis. The previous implementation was an empty try/catch.
319
+ * Force subsequent tag reads to re-sync without forgetting monotonic versions.
245
320
  */
246
321
  async refreshTags(): Promise<void> {
247
322
  try {
248
- const cache = this.cache as unknown as {
249
- tagVersions?: Map<string, unknown>;
250
- };
251
- cache.tagVersions?.clear();
323
+ this.cache.refreshTagVersions();
252
324
  } catch (err) {
253
325
  this.logger.debug('Next.js cacheHandler refreshTags fail-soft catch', {
254
326
  error: (err as Error).message,
@@ -259,8 +331,14 @@ export class TriCacheHandler {
259
331
  /**
260
332
  * Update or invalidate tags cluster-wide.
261
333
  */
262
- async updateTags(tags: string[]): Promise<void> {
334
+ async updateTags(tags: string[], durations?: { expire?: number }): Promise<void> {
263
335
  if (!tags || tags.length === 0) return;
336
+ const now = Date.now();
337
+ const delay = durations && durations.expire === undefined ? undefined : Math.max(0, durations?.expire ?? 0) * 1000;
338
+ if (delay !== undefined && !Number.isFinite(delay)) throw new Error('Tag expiry duration must be finite');
339
+ await Promise.all(tags.map(tag => this.cache.set(`_next_tag_state_:${tag}`, {
340
+ revalidatedAt: now, expiredAt: delay === undefined ? undefined : now + delay,
341
+ }, 0, CachePriority.HIGH)));
264
342
  await this.cache.invalidateTags(tags);
265
343
  }
266
344
  }