tricache 0.6.7 → 0.7.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +1 -1
- package/README.md +1428 -970
- package/bin/tricache.js +8 -0
- package/dist/cache-service-5GATUYAK.js +7 -0
- package/dist/cache-service-D8tIXmzb.d.ts +1498 -0
- package/dist/chunk-EUGYR7KR.js +4629 -0
- package/dist/chunk-UBSR5UYA.js +0 -0
- package/dist/{chunk-FKY5R3CE.js → chunk-X5AXHPVD.js} +139 -6
- package/dist/cli.cjs +5238 -0
- package/dist/cli.d.ts +11 -0
- package/dist/cli.js +130 -0
- package/dist/drizzle/index.cjs +5218 -0
- package/dist/drizzle/index.d.ts +44 -0
- package/dist/drizzle/index.js +46 -0
- package/dist/http/index.cjs +5374 -0
- package/dist/http/index.d.ts +33 -0
- package/dist/http/index.js +200 -0
- package/dist/index.cjs +1245 -209
- package/dist/index.d.ts +15 -1230
- package/dist/index.js +11 -3705
- package/dist/nestjs/index.cjs +5362 -0
- package/dist/nestjs/index.d.ts +210 -0
- package/dist/nestjs/index.js +250 -0
- package/dist/next/index.cjs +5407 -0
- package/dist/next/index.d.ts +208 -0
- package/dist/next/index.js +297 -0
- package/dist/prisma/index.cjs +123 -0
- package/dist/prisma/index.d.ts +60 -0
- package/dist/prisma/index.js +87 -0
- package/dist/serialize-worker.cjs +190 -15
- package/dist/serialize-worker.js +63 -12
- package/package.json +71 -21
- package/src/cache-service.ts +3294 -2429
- package/src/cli.ts +143 -0
- package/src/compression.ts +56 -0
- package/src/disk-tier.ts +821 -757
- package/src/drizzle/index.ts +86 -0
- package/src/encryption.ts +513 -442
- package/src/http/index.ts +265 -0
- package/src/index.ts +7 -0
- package/src/nestjs/decorators.ts +161 -0
- package/src/nestjs/index.ts +23 -0
- package/src/nestjs/tricache.module.ts +104 -0
- package/src/nestjs/tricache.store.ts +97 -0
- package/src/nestjs/types.ts +79 -0
- package/src/next/cache-handler.ts +268 -0
- package/src/next/index.ts +37 -0
- package/src/next/isr-handler.ts +105 -0
- package/src/next/types.ts +130 -0
- package/src/prisma/index.ts +154 -0
- package/src/serialize-worker.ts +77 -13
- package/src/smart-memory-cache.ts +1026 -1010
- package/src/types.ts +911 -732
- package/src/wasm/bloom-filter-wasm.ts +3 -2
- package/src/worker-pool.ts +156 -42
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* tricache/prisma — First-class Prisma Client extension for TriCache.
|
|
3
|
+
*
|
|
4
|
+
* Usage:
|
|
5
|
+
* import { PrismaClient } from '@prisma/client';
|
|
6
|
+
* import { withTriCache } from 'tricache/prisma';
|
|
7
|
+
*
|
|
8
|
+
* const prisma = new PrismaClient().$extends(
|
|
9
|
+
* withTriCache({
|
|
10
|
+
* cache,
|
|
11
|
+
* defaultTtl: 300,
|
|
12
|
+
* autoInvalidate: true, // Invalidate model tags on create/update/delete
|
|
13
|
+
* })
|
|
14
|
+
* );
|
|
15
|
+
*
|
|
16
|
+
* // Query with cache options:
|
|
17
|
+
* const users = await prisma.user.findMany({
|
|
18
|
+
* where: { active: true },
|
|
19
|
+
* cache: { ttl: 60, tags: ['users'], swr: 30 },
|
|
20
|
+
* });
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
import type { CacheService } from '../cache-service.js';
|
|
24
|
+
import type { WrapOptions } from '../types.js';
|
|
25
|
+
import crypto from 'crypto';
|
|
26
|
+
|
|
27
|
+
export 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
|
+
|
|
34
|
+
export interface PrismaTriCacheOptions {
|
|
35
|
+
/** TriCache instance to use for caching. */
|
|
36
|
+
cache: CacheService;
|
|
37
|
+
/** Default TTL in seconds for cached queries (default: 300 s). */
|
|
38
|
+
defaultTtl?: number;
|
|
39
|
+
/** Whether to automatically invalidate model tags on write operations (default: true). */
|
|
40
|
+
autoInvalidate?: boolean;
|
|
41
|
+
/** Automatically cache all read queries even if `cache` options are not provided (default: false). */
|
|
42
|
+
autoCache?: boolean;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const READ_OPERATIONS = new Set([
|
|
46
|
+
'findUnique',
|
|
47
|
+
'findUniqueOrThrow',
|
|
48
|
+
'findFirst',
|
|
49
|
+
'findFirstOrThrow',
|
|
50
|
+
'findMany',
|
|
51
|
+
'count',
|
|
52
|
+
'aggregate',
|
|
53
|
+
'groupBy',
|
|
54
|
+
]);
|
|
55
|
+
|
|
56
|
+
const MUTATION_OPERATIONS = new Set([
|
|
57
|
+
'create',
|
|
58
|
+
'createMany',
|
|
59
|
+
'createManyAndReturn',
|
|
60
|
+
'update',
|
|
61
|
+
'updateMany',
|
|
62
|
+
'updateManyAndReturn',
|
|
63
|
+
'upsert',
|
|
64
|
+
'delete',
|
|
65
|
+
'deleteMany',
|
|
66
|
+
]);
|
|
67
|
+
|
|
68
|
+
/** Recursively sorts object keys for deterministic serialization of nested query filters */
|
|
69
|
+
function deterministicStringify(val: unknown): string {
|
|
70
|
+
if (val === null || typeof val !== 'object') {
|
|
71
|
+
return JSON.stringify(val);
|
|
72
|
+
}
|
|
73
|
+
if (Array.isArray(val)) {
|
|
74
|
+
return `[${val.map(deterministicStringify).join(',')}]`;
|
|
75
|
+
}
|
|
76
|
+
const obj = val as Record<string, unknown>;
|
|
77
|
+
const keys = Object.keys(obj).sort();
|
|
78
|
+
return `{${keys.map(k => `${JSON.stringify(k)}:${deterministicStringify(obj[k])}`).join(',')}}`;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** Generate a deterministic SHA-256 hash key for a Prisma query. */
|
|
82
|
+
export function generatePrismaCacheKey(model: string, operation: string, args: unknown): string {
|
|
83
|
+
const normalized = deterministicStringify({ model, operation, args });
|
|
84
|
+
const hash = crypto.createHash('sha256').update(normalized, 'utf8').digest('hex').slice(0, 32);
|
|
85
|
+
return `prisma:${model.toLowerCase()}:${operation}:${hash}`;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Creates a Prisma Client Extension for TriCache.
|
|
90
|
+
*/
|
|
91
|
+
export function withTriCache(options: PrismaTriCacheOptions) {
|
|
92
|
+
const { cache, defaultTtl = 300, autoInvalidate = true, autoCache = false } = options;
|
|
93
|
+
|
|
94
|
+
return {
|
|
95
|
+
name: 'tricache-prisma-extension',
|
|
96
|
+
query: {
|
|
97
|
+
$allModels: {
|
|
98
|
+
async $allOperations({ model, operation, args, query }: {
|
|
99
|
+
model: string;
|
|
100
|
+
operation: string;
|
|
101
|
+
args: Record<string, unknown> | undefined;
|
|
102
|
+
query: (args: unknown) => Promise<unknown>;
|
|
103
|
+
}) {
|
|
104
|
+
const modelTag = model.toLowerCase();
|
|
105
|
+
|
|
106
|
+
// Auto-invalidation on write operations
|
|
107
|
+
if (autoInvalidate && MUTATION_OPERATIONS.has(operation)) {
|
|
108
|
+
// Strip the cache pseudo-option here too — the read path removes it,
|
|
109
|
+
// but the mutation path forwarded it verbatim to the Prisma engine.
|
|
110
|
+
const { cache: _cacheOpt, ...cleanMutationArgs } = (args ?? {}) as Record<string, unknown>;
|
|
111
|
+
const result = await query(cleanMutationArgs);
|
|
112
|
+
await cache.invalidateTag(modelTag);
|
|
113
|
+
return result;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
// Read operations
|
|
117
|
+
if (READ_OPERATIONS.has(operation)) {
|
|
118
|
+
const queryArgs = args ?? {};
|
|
119
|
+
const cacheConfig = (queryArgs as { cache?: PrismaCacheQueryOptions | boolean }).cache;
|
|
120
|
+
|
|
121
|
+
if (cacheConfig !== undefined || autoCache) {
|
|
122
|
+
const opts: PrismaCacheQueryOptions = typeof cacheConfig === 'object' && cacheConfig !== null
|
|
123
|
+
? cacheConfig
|
|
124
|
+
: {};
|
|
125
|
+
|
|
126
|
+
// Clone args without the `cache` property to pass clean args to Prisma query engine
|
|
127
|
+
const { cache: _c, ...cleanArgs } = queryArgs as Record<string, unknown>;
|
|
128
|
+
|
|
129
|
+
const key = opts.key ?? generatePrismaCacheKey(model, operation, cleanArgs);
|
|
130
|
+
const tags = [...new Set([modelTag, ...(opts.tags ?? [])])];
|
|
131
|
+
|
|
132
|
+
return cache.wrap(
|
|
133
|
+
key,
|
|
134
|
+
() => query(cleanArgs),
|
|
135
|
+
{
|
|
136
|
+
ttl: opts.ttl ?? defaultTtl,
|
|
137
|
+
swr: opts.swr,
|
|
138
|
+
priority: opts.priority,
|
|
139
|
+
tags,
|
|
140
|
+
dependsOn: opts.dependsOn,
|
|
141
|
+
refreshAhead: opts.refreshAhead,
|
|
142
|
+
xfetchBeta: opts.xfetchBeta,
|
|
143
|
+
notFoundTtl: opts.notFoundTtl,
|
|
144
|
+
},
|
|
145
|
+
);
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
return query(args);
|
|
150
|
+
},
|
|
151
|
+
},
|
|
152
|
+
},
|
|
153
|
+
};
|
|
154
|
+
}
|
package/src/serialize-worker.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* serialize-worker — worker-thread entry point for off-main-thread encryption/decryption.
|
|
2
|
+
* serialize-worker — worker-thread entry point for off-main-thread encryption/decryption/compression.
|
|
3
3
|
*
|
|
4
4
|
* Receives messages from WorkerPool:
|
|
5
5
|
* { id: number; type: 'encrypt'; payload: string }
|
|
@@ -17,12 +17,21 @@ import { parentPort, workerData } from 'worker_threads';
|
|
|
17
17
|
import { CacheEncryption } from './encryption.ts';
|
|
18
18
|
import type { EncryptionMode } from './encryption.ts';
|
|
19
19
|
import type { ILogger } from './types.ts';
|
|
20
|
+
import {
|
|
21
|
+
compressBuffer,
|
|
22
|
+
decompressBuffer,
|
|
23
|
+
PREFIX_COMPRESSED,
|
|
24
|
+
PREFIX_ENC_COMPRESSED,
|
|
25
|
+
type CompressionAlgorithm,
|
|
26
|
+
} from './compression.ts';
|
|
20
27
|
|
|
21
28
|
interface WorkerInit {
|
|
22
29
|
keyBase64: string;
|
|
23
30
|
mode: EncryptionMode;
|
|
24
31
|
prevKeyBase64: string | undefined;
|
|
25
32
|
prevMode: EncryptionMode | undefined;
|
|
33
|
+
compression?: CompressionAlgorithm;
|
|
34
|
+
compressionThresholdBytes?: number;
|
|
26
35
|
}
|
|
27
36
|
|
|
28
37
|
// Minimal no-op logger — worker thread does not log to avoid interleaved I/O.
|
|
@@ -33,24 +42,79 @@ const silentLogger: ILogger = {
|
|
|
33
42
|
error: () => {},
|
|
34
43
|
};
|
|
35
44
|
|
|
36
|
-
const { keyBase64, mode, prevKeyBase64, prevMode } =
|
|
45
|
+
const { keyBase64, mode, prevKeyBase64, prevMode, compression, compressionThresholdBytes } =
|
|
46
|
+
workerData as WorkerInit;
|
|
37
47
|
|
|
38
48
|
const enc = new CacheEncryption(
|
|
39
|
-
keyBase64
|
|
49
|
+
keyBase64 || undefined,
|
|
40
50
|
silentLogger,
|
|
41
51
|
mode,
|
|
42
52
|
prevKeyBase64 || undefined,
|
|
43
53
|
prevMode,
|
|
44
54
|
);
|
|
45
55
|
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
56
|
+
const cmpAlgo = compression ?? 'none';
|
|
57
|
+
const cmpThreshold = compressionThresholdBytes ?? 1024;
|
|
58
|
+
|
|
59
|
+
parentPort!.on(
|
|
60
|
+
'message',
|
|
61
|
+
({ id, type, payload }: { id: number; type: 'encrypt' | 'decrypt'; payload: string | Uint8Array }) => {
|
|
62
|
+
try {
|
|
63
|
+
const textPayload =
|
|
64
|
+
typeof payload === 'string'
|
|
65
|
+
? payload
|
|
66
|
+
: Buffer.from(payload.buffer, payload.byteOffset, payload.byteLength).toString('utf8');
|
|
67
|
+
|
|
68
|
+
if (type === 'encrypt') {
|
|
69
|
+
let result: string;
|
|
70
|
+
if (cmpAlgo !== 'none' && textPayload.length > cmpThreshold) {
|
|
71
|
+
const compressed = compressBuffer(Buffer.from(textPayload, 'utf8'), cmpAlgo);
|
|
72
|
+
if (enc.isEnabled) {
|
|
73
|
+
const encrypted = enc.encryptBuffer(compressed);
|
|
74
|
+
result = PREFIX_ENC_COMPRESSED + encrypted.toString('base64');
|
|
75
|
+
} else {
|
|
76
|
+
result = PREFIX_COMPRESSED + compressed.toString('base64');
|
|
77
|
+
}
|
|
78
|
+
} else {
|
|
79
|
+
result = enc.encrypt(textPayload);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
if (result.length >= 131_072) {
|
|
83
|
+
const outBuf = Buffer.from(result, 'utf8');
|
|
84
|
+
const transferable = new ArrayBuffer(outBuf.byteLength);
|
|
85
|
+
new Uint8Array(transferable).set(outBuf);
|
|
86
|
+
const outputUint8 = new Uint8Array(transferable);
|
|
87
|
+
parentPort!.postMessage({ id, result: outputUint8, isTransfer: true }, [transferable]);
|
|
88
|
+
} else {
|
|
89
|
+
parentPort!.postMessage({ id, result });
|
|
90
|
+
}
|
|
91
|
+
} else {
|
|
92
|
+
let result: string;
|
|
93
|
+
if (textPayload.startsWith(PREFIX_ENC_COMPRESSED)) {
|
|
94
|
+
const rawBuf = Buffer.from(textPayload.slice(PREFIX_ENC_COMPRESSED.length), 'base64');
|
|
95
|
+
const decryptedBuf = enc.decryptBuffer(rawBuf);
|
|
96
|
+
const decompressed = decompressBuffer(decryptedBuf, cmpAlgo !== 'none' ? cmpAlgo : 'brotli');
|
|
97
|
+
result = decompressed.toString('utf8');
|
|
98
|
+
} else if (textPayload.startsWith(PREFIX_COMPRESSED)) {
|
|
99
|
+
const rawBuf = Buffer.from(textPayload.slice(PREFIX_COMPRESSED.length), 'base64');
|
|
100
|
+
const decompressed = decompressBuffer(rawBuf, cmpAlgo !== 'none' ? cmpAlgo : 'brotli');
|
|
101
|
+
result = decompressed.toString('utf8');
|
|
102
|
+
} else {
|
|
103
|
+
result = enc.decrypt(textPayload);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
if (result.length >= 131_072) {
|
|
107
|
+
const outBuf = Buffer.from(result, 'utf8');
|
|
108
|
+
const transferable = new ArrayBuffer(outBuf.byteLength);
|
|
109
|
+
new Uint8Array(transferable).set(outBuf);
|
|
110
|
+
const outputUint8 = new Uint8Array(transferable);
|
|
111
|
+
parentPort!.postMessage({ id, result: outputUint8, isTransfer: true }, [transferable]);
|
|
112
|
+
} else {
|
|
113
|
+
parentPort!.postMessage({ id, result });
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
} catch (e) {
|
|
117
|
+
parentPort!.postMessage({ id, error: (e as Error).message });
|
|
52
118
|
}
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
}
|
|
56
|
-
});
|
|
119
|
+
},
|
|
120
|
+
);
|