tricache 0.7.0 → 0.8.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/LICENSE +21 -21
- package/README.md +144 -1428
- package/bin/tricache.js +8 -8
- package/dashboards/tricache-alerts.yaml +54 -0
- package/dashboards/tricache-grafana.json +548 -0
- package/dist/cache-service-5MZXFIGK.js +12 -0
- package/dist/cache-service-CyLdpo77.d.ts +871 -0
- package/dist/{chunk-3XQUQBOZ.js → chunk-6PQ5MOWR.js} +2950 -523
- package/dist/chunk-7RV5ZVBB.js +1023 -0
- package/dist/{chunk-PFB5FMEY.js → chunk-LJ5QJB5O.js} +116 -20
- package/dist/chunk-QNU7B43J.js +687 -0
- package/dist/chunk-UGD4VEPD.js +138 -0
- package/dist/chunk-XZL45ABR.js +108 -0
- package/dist/chunk-ZTSWCFYO.js +135 -0
- package/dist/cli.cjs +2894 -518
- package/dist/cli.d.ts +1 -0
- package/dist/cli.js +103 -5
- package/dist/dashboard/index.cjs +1065 -0
- package/dist/dashboard/index.d.ts +183 -0
- package/dist/dashboard/index.js +22 -0
- package/dist/drizzle/index.cjs +2648 -508
- package/dist/drizzle/index.d.ts +3 -1
- package/dist/drizzle/index.js +1 -1
- package/dist/edge/index.cjs +1498 -0
- package/dist/edge/index.d.ts +127 -0
- package/dist/edge/index.js +1109 -0
- package/dist/hono-DQRS1Xd7.d.ts +370 -0
- package/dist/http/index.cjs +3038 -589
- package/dist/http/index.d.ts +109 -23
- package/dist/http/index.js +238 -62
- package/dist/index.cjs +6962 -2487
- package/dist/index.d.ts +547 -30
- package/dist/index.js +104 -5
- package/dist/murmur3-CMGw9PbV.d.ts +98 -0
- package/dist/nestjs/index.cjs +2586 -498
- package/dist/nestjs/index.d.ts +3 -1
- package/dist/nestjs/index.js +6 -3
- package/dist/next/index.cjs +2633 -519
- package/dist/next/index.d.ts +13 -7
- package/dist/next/index.js +45 -18
- package/dist/prisma/index.cjs +2 -1
- package/dist/prisma/index.d.ts +3 -1
- package/dist/prisma/index.js +2 -1
- package/dist/serialize-worker.cjs +31 -19
- package/dist/serialize-worker.js +1 -1
- package/dist/{cache-service-BblHuF3i.d.ts → types-B6krw64X.d.ts} +605 -646
- package/package.json +37 -7
- package/src/adapters/auto-pipeliner.ts +206 -0
- package/src/adapters/node-redis.ts +370 -0
- package/src/cache-service.ts +4231 -3226
- package/src/cli.ts +261 -143
- package/src/codec.ts +72 -0
- package/src/compression.ts +56 -63
- package/src/cross-region.ts +245 -0
- package/src/dashboard/handler.ts +392 -0
- package/src/dashboard/html.ts +594 -0
- package/src/dashboard/index.ts +195 -0
- package/src/dashboard/types.ts +96 -0
- package/src/disk-tier.ts +1223 -821
- package/src/drizzle/index.ts +86 -86
- package/src/edge/adapters/cloudflare-do.ts +130 -0
- package/src/edge/adapters/cloudflare-kv.ts +115 -0
- package/src/edge/adapters/upstash.ts +143 -0
- package/src/edge/cache.ts +797 -0
- package/src/edge/crypto.ts +182 -0
- package/src/edge/hono.ts +203 -0
- package/src/edge/index.ts +37 -0
- package/src/edge/types.ts +230 -0
- package/src/edge/utils/base64.ts +63 -0
- package/src/edge/utils/murmur3.ts +179 -0
- package/src/encryption.ts +635 -493
- package/src/http/express.ts +195 -0
- package/src/http/fastify.ts +260 -0
- package/src/http/index.ts +46 -223
- package/src/http/utils.ts +92 -0
- package/src/index.ts +149 -47
- package/src/ipc-telemetry.ts +481 -0
- package/src/latency-watchdog.ts +282 -0
- package/src/nestjs/decorators.ts +161 -161
- package/src/nestjs/index.ts +23 -23
- package/src/nestjs/tricache.module.ts +104 -104
- package/src/nestjs/tricache.store.ts +97 -97
- package/src/nestjs/types.ts +79 -79
- package/src/next/cache-handler.ts +271 -244
- package/src/next/index.ts +37 -37
- package/src/next/isr-handler.ts +105 -105
- package/src/next/types.ts +130 -130
- package/src/prisma/index.ts +154 -151
- package/src/remote-snapshot.ts +153 -0
- package/src/serialize-worker.ts +120 -120
- package/src/sigv4-snapshot-adapter.ts +260 -0
- package/src/smart-memory-cache.ts +1109 -1024
- package/src/types.ts +1199 -902
- package/src/utils/cgroup.ts +100 -0
- package/src/utils/tracing.ts +54 -0
- package/src/wasm/bloom-filter-wasm.ts +109 -102
- package/src/worker-pool.ts +299 -299
- package/src/wtiny-lfu.ts +624 -0
- package/dist/cache-service-AJASH5FX.js +0 -7
- package/dist/chunk-UBSR5UYA.js +0 -0
package/src/drizzle/index.ts
CHANGED
|
@@ -1,86 +1,86 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* tricache/drizzle — First-class Drizzle ORM query caching wrapper for TriCache.
|
|
3
|
-
*
|
|
4
|
-
* Usage:
|
|
5
|
-
* import { withCache } from 'tricache/drizzle';
|
|
6
|
-
*
|
|
7
|
-
* const activeUsers = await withCache(
|
|
8
|
-
* db.select().from(users).where(eq(users.active, true)),
|
|
9
|
-
* { cache, ttl: 300, tags: ['users'] }
|
|
10
|
-
* );
|
|
11
|
-
*/
|
|
12
|
-
|
|
13
|
-
import type { CacheService } from '../cache-service.js';
|
|
14
|
-
import type { WrapOptions } from '../types.js';
|
|
15
|
-
import crypto from 'crypto';
|
|
16
|
-
|
|
17
|
-
export interface DrizzleCacheOptions extends WrapOptions {
|
|
18
|
-
/** TriCache instance to use. If omitted, uses process-level singleton `CacheService.create()`. */
|
|
19
|
-
cache?: CacheService;
|
|
20
|
-
/** Explicit cache key. If omitted, automatically derived from SHA-256 hash of `{ sql, params }`. */
|
|
21
|
-
key?: string;
|
|
22
|
-
}
|
|
23
|
-
|
|
24
|
-
export interface DrizzleExecutableQuery<T> {
|
|
25
|
-
toSQL(): { sql: string; params: unknown[] };
|
|
26
|
-
execute?(): Promise<T>;
|
|
27
|
-
then?: (onfulfilled?: (value: T) => unknown, onrejected?: (reason: unknown) => unknown) => Promise<unknown>;
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
/**
|
|
31
|
-
* Generate a deterministic SHA-256 hash key for a Drizzle query based on its compiled SQL and parameters.
|
|
32
|
-
*/
|
|
33
|
-
export function generateDrizzleCacheKey(sqlInfo: { sql: string; params: unknown[] }): string {
|
|
34
|
-
const normalized = JSON.stringify(sqlInfo);
|
|
35
|
-
const hash = crypto.createHash('sha256').update(normalized, 'utf8').digest('hex').slice(0, 32);
|
|
36
|
-
return `drizzle:${hash}`;
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
/**
|
|
40
|
-
* Wraps a Drizzle ORM query with TriCache caching.
|
|
41
|
-
*
|
|
42
|
-
* @param query Drizzle query builder or executable query instance.
|
|
43
|
-
* @param options Cache options including TTL, tags, SWR, priority, and optional key.
|
|
44
|
-
*/
|
|
45
|
-
export async function withCache<T>(
|
|
46
|
-
query: DrizzleExecutableQuery<T>,
|
|
47
|
-
options: DrizzleCacheOptions = {},
|
|
48
|
-
): Promise<T> {
|
|
49
|
-
const { cache, key, ttl = 300, swr, priority, tags, dependsOn, refreshAhead, xfetchBeta, notFoundTtl } = options;
|
|
50
|
-
|
|
51
|
-
let activeCache = cache;
|
|
52
|
-
if (!activeCache) {
|
|
53
|
-
const { CacheService } = await import('../cache-service.js');
|
|
54
|
-
activeCache = CacheService.create();
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
let cacheKey = key;
|
|
58
|
-
if (!cacheKey) {
|
|
59
|
-
if (typeof query.toSQL === 'function') {
|
|
60
|
-
const sqlInfo = query.toSQL();
|
|
61
|
-
cacheKey = generateDrizzleCacheKey(sqlInfo);
|
|
62
|
-
} else {
|
|
63
|
-
throw new Error('tricache/drizzle: query must provide a .toSQL() method or an explicit key option.');
|
|
64
|
-
}
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
const executeFn = async (): Promise<T> => {
|
|
68
|
-
if (typeof query.execute === 'function') {
|
|
69
|
-
return await query.execute();
|
|
70
|
-
} else if (typeof query.then === 'function') {
|
|
71
|
-
return await (query as unknown as Promise<T>);
|
|
72
|
-
}
|
|
73
|
-
throw new Error('tricache/drizzle: query is neither executable via .execute() nor thenable.');
|
|
74
|
-
};
|
|
75
|
-
|
|
76
|
-
return activeCache.wrap(cacheKey, executeFn, {
|
|
77
|
-
ttl,
|
|
78
|
-
swr,
|
|
79
|
-
priority,
|
|
80
|
-
tags,
|
|
81
|
-
dependsOn,
|
|
82
|
-
refreshAhead,
|
|
83
|
-
xfetchBeta,
|
|
84
|
-
notFoundTtl,
|
|
85
|
-
});
|
|
86
|
-
}
|
|
1
|
+
/**
|
|
2
|
+
* tricache/drizzle — First-class Drizzle ORM query caching wrapper for TriCache.
|
|
3
|
+
*
|
|
4
|
+
* Usage:
|
|
5
|
+
* import { withCache } from 'tricache/drizzle';
|
|
6
|
+
*
|
|
7
|
+
* const activeUsers = await withCache(
|
|
8
|
+
* db.select().from(users).where(eq(users.active, true)),
|
|
9
|
+
* { cache, ttl: 300, tags: ['users'] }
|
|
10
|
+
* );
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import type { CacheService } from '../cache-service.js';
|
|
14
|
+
import type { WrapOptions } from '../types.js';
|
|
15
|
+
import crypto from 'crypto';
|
|
16
|
+
|
|
17
|
+
export interface DrizzleCacheOptions extends WrapOptions {
|
|
18
|
+
/** TriCache instance to use. If omitted, uses process-level singleton `CacheService.create()`. */
|
|
19
|
+
cache?: CacheService;
|
|
20
|
+
/** Explicit cache key. If omitted, automatically derived from SHA-256 hash of `{ sql, params }`. */
|
|
21
|
+
key?: string;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export interface DrizzleExecutableQuery<T> {
|
|
25
|
+
toSQL(): { sql: string; params: unknown[] };
|
|
26
|
+
execute?(): Promise<T>;
|
|
27
|
+
then?: (onfulfilled?: (value: T) => unknown, onrejected?: (reason: unknown) => unknown) => Promise<unknown>;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Generate a deterministic SHA-256 hash key for a Drizzle query based on its compiled SQL and parameters.
|
|
32
|
+
*/
|
|
33
|
+
export function generateDrizzleCacheKey(sqlInfo: { sql: string; params: unknown[] }): string {
|
|
34
|
+
const normalized = JSON.stringify(sqlInfo);
|
|
35
|
+
const hash = crypto.createHash('sha256').update(normalized, 'utf8').digest('hex').slice(0, 32);
|
|
36
|
+
return `drizzle:${hash}`;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Wraps a Drizzle ORM query with TriCache caching.
|
|
41
|
+
*
|
|
42
|
+
* @param query Drizzle query builder or executable query instance.
|
|
43
|
+
* @param options Cache options including TTL, tags, SWR, priority, and optional key.
|
|
44
|
+
*/
|
|
45
|
+
export async function withCache<T>(
|
|
46
|
+
query: DrizzleExecutableQuery<T>,
|
|
47
|
+
options: DrizzleCacheOptions = {},
|
|
48
|
+
): Promise<T> {
|
|
49
|
+
const { cache, key, ttl = 300, swr, priority, tags, dependsOn, refreshAhead, xfetchBeta, notFoundTtl } = options;
|
|
50
|
+
|
|
51
|
+
let activeCache = cache;
|
|
52
|
+
if (!activeCache) {
|
|
53
|
+
const { CacheService } = await import('../cache-service.js');
|
|
54
|
+
activeCache = CacheService.create();
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
let cacheKey = key;
|
|
58
|
+
if (!cacheKey) {
|
|
59
|
+
if (typeof query.toSQL === 'function') {
|
|
60
|
+
const sqlInfo = query.toSQL();
|
|
61
|
+
cacheKey = generateDrizzleCacheKey(sqlInfo);
|
|
62
|
+
} else {
|
|
63
|
+
throw new Error('tricache/drizzle: query must provide a .toSQL() method or an explicit key option.');
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
const executeFn = async (): Promise<T> => {
|
|
68
|
+
if (typeof query.execute === 'function') {
|
|
69
|
+
return await query.execute();
|
|
70
|
+
} else if (typeof query.then === 'function') {
|
|
71
|
+
return await (query as unknown as Promise<T>);
|
|
72
|
+
}
|
|
73
|
+
throw new Error('tricache/drizzle: query is neither executable via .execute() nor thenable.');
|
|
74
|
+
};
|
|
75
|
+
|
|
76
|
+
return activeCache.wrap(cacheKey, executeFn, {
|
|
77
|
+
ttl,
|
|
78
|
+
swr,
|
|
79
|
+
priority,
|
|
80
|
+
tags,
|
|
81
|
+
dependsOn,
|
|
82
|
+
refreshAhead,
|
|
83
|
+
xfetchBeta,
|
|
84
|
+
notFoundTtl,
|
|
85
|
+
});
|
|
86
|
+
}
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
import type { IEdgeRemoteStorage, CloudflareDOStorage } from '../types';
|
|
2
|
+
|
|
3
|
+
interface DOEntry {
|
|
4
|
+
val: string;
|
|
5
|
+
exp: number; // 0 = no expiration
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Storage adapter for Cloudflare Durable Objects transactional storage (`state.storage`).
|
|
10
|
+
* Enables strongly-consistent edge caching and coordination across edge isolates.
|
|
11
|
+
*/
|
|
12
|
+
export class CloudflareDOStorageAdapter implements IEdgeRemoteStorage {
|
|
13
|
+
private readonly storage: CloudflareDOStorage;
|
|
14
|
+
|
|
15
|
+
constructor(storage: CloudflareDOStorage) {
|
|
16
|
+
if (!storage) {
|
|
17
|
+
throw new Error('CloudflareDOStorageAdapter: DurableObjectStorage instance is required.');
|
|
18
|
+
}
|
|
19
|
+
this.storage = storage;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
async get(key: string): Promise<string | null> {
|
|
23
|
+
const entry = await this.storage.get<DOEntry | string>(key);
|
|
24
|
+
if (entry === undefined || entry === null) return null;
|
|
25
|
+
|
|
26
|
+
if (typeof entry === 'object' && 'val' in entry && 'exp' in entry) {
|
|
27
|
+
if (entry.exp > 0 && Date.now() >= entry.exp) {
|
|
28
|
+
void this.storage.delete(key).catch(() => {});
|
|
29
|
+
return null;
|
|
30
|
+
}
|
|
31
|
+
return entry.val;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
return String(entry);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
async set(key: string, value: string, ttlSeconds?: number): Promise<void> {
|
|
38
|
+
const exp = typeof ttlSeconds === 'number' && ttlSeconds > 0
|
|
39
|
+
? Date.now() + Math.round(ttlSeconds * 1000)
|
|
40
|
+
: 0;
|
|
41
|
+
|
|
42
|
+
const entry: DOEntry = { val: value, exp };
|
|
43
|
+
await this.storage.put(key, entry);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
async delete(key: string): Promise<void> {
|
|
47
|
+
await this.storage.delete(key);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
async mget(keys: string[]): Promise<(string | null)[]> {
|
|
51
|
+
if (keys.length === 0) return [];
|
|
52
|
+
const map = await this.storage.get<DOEntry | string>(keys);
|
|
53
|
+
const now = Date.now();
|
|
54
|
+
const result: (string | null)[] = [];
|
|
55
|
+
|
|
56
|
+
for (const k of keys) {
|
|
57
|
+
const entry = map.get(k);
|
|
58
|
+
if (entry === undefined || entry === null) {
|
|
59
|
+
result.push(null);
|
|
60
|
+
} else if (typeof entry === 'object' && 'val' in entry && 'exp' in entry) {
|
|
61
|
+
if (entry.exp > 0 && now >= entry.exp) {
|
|
62
|
+
void this.storage.delete(k).catch(() => {});
|
|
63
|
+
result.push(null);
|
|
64
|
+
} else {
|
|
65
|
+
result.push(entry.val);
|
|
66
|
+
}
|
|
67
|
+
} else {
|
|
68
|
+
result.push(String(entry));
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
return result;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
async mset(entries: Record<string, string>, ttlSeconds?: number): Promise<void> {
|
|
76
|
+
const exp = typeof ttlSeconds === 'number' && ttlSeconds > 0
|
|
77
|
+
? Date.now() + Math.round(ttlSeconds * 1000)
|
|
78
|
+
: 0;
|
|
79
|
+
|
|
80
|
+
const record: Record<string, DOEntry> = {};
|
|
81
|
+
for (const [k, v] of Object.entries(entries)) {
|
|
82
|
+
record[k] = { val: v, exp };
|
|
83
|
+
}
|
|
84
|
+
await this.storage.put(record);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
async clear(prefix?: string): Promise<void> {
|
|
88
|
+
if (!this.storage.list) return;
|
|
89
|
+
|
|
90
|
+
const map = await this.storage.list({ prefix });
|
|
91
|
+
const keysToDelete = Array.from(map.keys());
|
|
92
|
+
if (keysToDelete.length > 0) {
|
|
93
|
+
await this.storage.delete(keysToDelete);
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
async incrementTagVersion(tag: string): Promise<number> {
|
|
98
|
+
const key = `tag_ver:${tag}`;
|
|
99
|
+
const raw = await this.storage.get<DOEntry>(key);
|
|
100
|
+
const prev = (raw && typeof raw === 'object' && 'val' in raw)
|
|
101
|
+
? parseInt(raw.val, 10) || 0
|
|
102
|
+
: (typeof raw === 'string' ? parseInt(raw, 10) || 0 : 0);
|
|
103
|
+
const nextVer = prev + 1;
|
|
104
|
+
await this.storage.put(key, { val: String(nextVer), exp: 0 });
|
|
105
|
+
return nextVer;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
async getTagVersion(tag: string): Promise<number> {
|
|
109
|
+
const raw = await this.storage.get<DOEntry>(`tag_ver:${tag}`);
|
|
110
|
+
if (raw && typeof raw === 'object' && 'val' in raw) {
|
|
111
|
+
return parseInt(raw.val, 10) || 1;
|
|
112
|
+
}
|
|
113
|
+
return typeof raw === 'string' ? parseInt(raw, 10) || 1 : 1;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
async batchGetTagVersions(tags: string[]): Promise<Record<string, number>> {
|
|
117
|
+
const keys = tags.map(t => `tag_ver:${t}`);
|
|
118
|
+
const map = await this.storage.get<DOEntry>(keys);
|
|
119
|
+
const result: Record<string, number> = {};
|
|
120
|
+
for (const tag of tags) {
|
|
121
|
+
const entry = map.get(`tag_ver:${tag}`);
|
|
122
|
+
if (entry && typeof entry === 'object' && 'val' in entry) {
|
|
123
|
+
result[tag] = parseInt(entry.val, 10) || 1;
|
|
124
|
+
} else {
|
|
125
|
+
result[tag] = typeof entry === 'string' ? parseInt(entry, 10) || 1 : 1;
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
return result;
|
|
129
|
+
}
|
|
130
|
+
}
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import type { IEdgeRemoteStorage, CloudflareKVNamespace } from '../types';
|
|
2
|
+
|
|
3
|
+
interface SubMinuteEnvelope {
|
|
4
|
+
exp: number;
|
|
5
|
+
val: string;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
const MIN_CF_KV_TTL = 60; // Cloudflare KV requires expirationTtl >= 60s
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Storage adapter for Cloudflare Workers KV.
|
|
12
|
+
*
|
|
13
|
+
* Mitigates Cloudflare KV's strict 60-second TTL floor by wrapping sub-minute
|
|
14
|
+
* TTLs in a lightweight timestamp envelope and validating expiry on read.
|
|
15
|
+
*/
|
|
16
|
+
export class CloudflareKVAdapter implements IEdgeRemoteStorage {
|
|
17
|
+
private readonly kv: CloudflareKVNamespace;
|
|
18
|
+
|
|
19
|
+
constructor(kv: CloudflareKVNamespace) {
|
|
20
|
+
if (!kv) {
|
|
21
|
+
throw new Error('CloudflareKVAdapter: KVNamespace instance is required.');
|
|
22
|
+
}
|
|
23
|
+
this.kv = kv;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
async get(key: string): Promise<string | null> {
|
|
27
|
+
const raw = await this.kv.get(key, { type: 'text' });
|
|
28
|
+
if (raw === null) return null;
|
|
29
|
+
|
|
30
|
+
// Check if entry was wrapped in a sub-minute logical envelope
|
|
31
|
+
if (raw.startsWith('{"exp":') && raw.includes('"val":')) {
|
|
32
|
+
try {
|
|
33
|
+
const parsed = JSON.parse(raw) as SubMinuteEnvelope;
|
|
34
|
+
if (typeof parsed.exp === 'number' && typeof parsed.val === 'string') {
|
|
35
|
+
if (Date.now() >= parsed.exp) {
|
|
36
|
+
// Expired logically — eagerly clean up and return null
|
|
37
|
+
void this.kv.delete(key).catch(() => {});
|
|
38
|
+
return null;
|
|
39
|
+
}
|
|
40
|
+
return parsed.val;
|
|
41
|
+
}
|
|
42
|
+
} catch {
|
|
43
|
+
// Fallback to returning raw if parsing fails
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
return raw;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
async set(key: string, value: string, ttlSeconds?: number): Promise<void> {
|
|
51
|
+
if (typeof ttlSeconds === 'number' && ttlSeconds > 0) {
|
|
52
|
+
if (ttlSeconds < MIN_CF_KV_TTL) {
|
|
53
|
+
// Sub-minute TTL: store expiration timestamp envelope and clamp KV TTL to minimum 60s
|
|
54
|
+
const envelope: SubMinuteEnvelope = {
|
|
55
|
+
exp: Date.now() + Math.round(ttlSeconds * 1000),
|
|
56
|
+
val: value,
|
|
57
|
+
};
|
|
58
|
+
await this.kv.put(key, JSON.stringify(envelope), { expirationTtl: MIN_CF_KV_TTL });
|
|
59
|
+
} else {
|
|
60
|
+
await this.kv.put(key, value, { expirationTtl: Math.round(ttlSeconds) });
|
|
61
|
+
}
|
|
62
|
+
} else {
|
|
63
|
+
await this.kv.put(key, value);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
async delete(key: string): Promise<void> {
|
|
68
|
+
await this.kv.delete(key);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
async mget(keys: string[]): Promise<(string | null)[]> {
|
|
72
|
+
return Promise.all(keys.map(k => this.get(k)));
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
async mset(entries: Record<string, string>, ttlSeconds?: number): Promise<void> {
|
|
76
|
+
const keys = Object.keys(entries);
|
|
77
|
+
await Promise.all(keys.map(k => this.set(k, entries[k], ttlSeconds)));
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
async clear(prefix?: string): Promise<void> {
|
|
81
|
+
if (!this.kv.list) return;
|
|
82
|
+
|
|
83
|
+
let cursor: string | undefined;
|
|
84
|
+
do {
|
|
85
|
+
const res = await this.kv.list({ prefix, cursor });
|
|
86
|
+
if (res.keys.length > 0) {
|
|
87
|
+
await Promise.all(res.keys.map(item => this.kv.delete(item.name)));
|
|
88
|
+
}
|
|
89
|
+
cursor = res.list_complete ? undefined : res.cursor;
|
|
90
|
+
} while (cursor);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
async incrementTagVersion(tag: string): Promise<number> {
|
|
94
|
+
const key = `tag_ver:${tag}`;
|
|
95
|
+
const raw = await this.kv.get(key);
|
|
96
|
+
const prev = raw ? parseInt(raw, 10) || 0 : 0;
|
|
97
|
+
const nextVer = Math.max(prev + 1, Date.now());
|
|
98
|
+
await this.kv.put(key, String(nextVer));
|
|
99
|
+
return nextVer;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
async getTagVersion(tag: string): Promise<number> {
|
|
103
|
+
const raw = await this.kv.get(`tag_ver:${tag}`);
|
|
104
|
+
return raw ? parseInt(raw, 10) || 1 : 1;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
async batchGetTagVersions(tags: string[]): Promise<Record<string, number>> {
|
|
108
|
+
const vers = await Promise.all(tags.map(t => this.getTagVersion(t)));
|
|
109
|
+
const res: Record<string, number> = {};
|
|
110
|
+
for (let i = 0; i < tags.length; i++) {
|
|
111
|
+
res[tags[i]] = vers[i];
|
|
112
|
+
}
|
|
113
|
+
return res;
|
|
114
|
+
}
|
|
115
|
+
}
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
import type { IEdgeRemoteStorage, UpstashRedisOptions } from '../types';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* High-performance HTTP-based Redis driver for Upstash.
|
|
5
|
+
* Compatible with pure V8 Edge Isolates (Cloudflare Workers, Vercel Edge, Fastly Compute).
|
|
6
|
+
*
|
|
7
|
+
* Communicates over HTTPS REST with zero native socket dependencies.
|
|
8
|
+
*/
|
|
9
|
+
export class UpstashRedisAdapter implements IEdgeRemoteStorage {
|
|
10
|
+
private readonly baseUrl: string;
|
|
11
|
+
private readonly token: string;
|
|
12
|
+
private readonly customFetch: typeof globalThis.fetch;
|
|
13
|
+
|
|
14
|
+
constructor(options: UpstashRedisOptions) {
|
|
15
|
+
if (!options?.url || !options?.token) {
|
|
16
|
+
throw new Error('UpstashRedisAdapter: url and token are required.');
|
|
17
|
+
}
|
|
18
|
+
this.baseUrl = options.url.replace(/\/+$/, '');
|
|
19
|
+
this.token = options.token;
|
|
20
|
+
this.customFetch = options.fetch ?? globalThis.fetch.bind(globalThis);
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
private async _executeCommand<T = unknown>(command: unknown[]): Promise<T> {
|
|
24
|
+
const res = await this.customFetch(this.baseUrl, {
|
|
25
|
+
method: 'POST',
|
|
26
|
+
headers: {
|
|
27
|
+
Authorization: `Bearer ${this.token}`,
|
|
28
|
+
'Content-Type': 'application/json',
|
|
29
|
+
},
|
|
30
|
+
body: JSON.stringify(command),
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
if (!res.ok) {
|
|
34
|
+
const text = await res.text().catch(() => '');
|
|
35
|
+
throw new Error(`Upstash HTTP error (${res.status} ${res.statusText}): ${text}`);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const json = (await res.json()) as { result?: T; error?: string };
|
|
39
|
+
if (json.error) {
|
|
40
|
+
throw new Error(`Upstash Redis command error: ${json.error}`);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
return json.result as T;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
private async _executePipeline<T = unknown>(commands: unknown[][]): Promise<T[]> {
|
|
47
|
+
const res = await this.customFetch(`${this.baseUrl}/pipeline`, {
|
|
48
|
+
method: 'POST',
|
|
49
|
+
headers: {
|
|
50
|
+
Authorization: `Bearer ${this.token}`,
|
|
51
|
+
'Content-Type': 'application/json',
|
|
52
|
+
},
|
|
53
|
+
body: JSON.stringify(commands),
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
if (!res.ok) {
|
|
57
|
+
const text = await res.text().catch(() => '');
|
|
58
|
+
throw new Error(`Upstash Pipeline error (${res.status} ${res.statusText}): ${text}`);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
const json = (await res.json()) as Array<{ result?: T; error?: string }>;
|
|
62
|
+
return json.map(item => {
|
|
63
|
+
if (item.error) {
|
|
64
|
+
throw new Error(`Upstash Redis pipeline item error: ${item.error}`);
|
|
65
|
+
}
|
|
66
|
+
return item.result as T;
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
async get(key: string): Promise<string | null> {
|
|
71
|
+
const res = await this._executeCommand<string | null>(['GET', key]);
|
|
72
|
+
return res ?? null;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
async set(key: string, value: string, ttlSeconds?: number): Promise<void> {
|
|
76
|
+
if (typeof ttlSeconds === 'number' && ttlSeconds > 0) {
|
|
77
|
+
await this._executeCommand(['SET', key, value, 'EX', Math.round(ttlSeconds)]);
|
|
78
|
+
} else {
|
|
79
|
+
await this._executeCommand(['SET', key, value]);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
async delete(key: string): Promise<void> {
|
|
84
|
+
await this._executeCommand(['DEL', key]);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
async mget(keys: string[]): Promise<(string | null)[]> {
|
|
88
|
+
if (keys.length === 0) return [];
|
|
89
|
+
const res = await this._executeCommand<(string | null)[]>(['MGET', ...keys]);
|
|
90
|
+
return Array.isArray(res) ? res : [];
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
async mset(entries: Record<string, string>, ttlSeconds?: number): Promise<void> {
|
|
94
|
+
const keys = Object.keys(entries);
|
|
95
|
+
if (keys.length === 0) return;
|
|
96
|
+
|
|
97
|
+
if (typeof ttlSeconds === 'number' && ttlSeconds > 0) {
|
|
98
|
+
const roundedTtl = Math.round(ttlSeconds);
|
|
99
|
+
const commands = keys.map(k => ['SET', k, entries[k], 'EX', roundedTtl]);
|
|
100
|
+
await this._executePipeline(commands);
|
|
101
|
+
} else {
|
|
102
|
+
const args: string[] = [];
|
|
103
|
+
for (const k of keys) {
|
|
104
|
+
args.push(k, entries[k]);
|
|
105
|
+
}
|
|
106
|
+
await this._executeCommand(['MSET', ...args]);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
async clear(prefix?: string): Promise<void> {
|
|
111
|
+
if (prefix) {
|
|
112
|
+
const pattern = prefix.endsWith('*') ? prefix : `${prefix}*`;
|
|
113
|
+
const keys = await this._executeCommand<string[]>(['KEYS', pattern]);
|
|
114
|
+
if (Array.isArray(keys) && keys.length > 0) {
|
|
115
|
+
await this._executeCommand(['DEL', ...keys]);
|
|
116
|
+
}
|
|
117
|
+
} else {
|
|
118
|
+
await this._executeCommand(['FLUSHDB']);
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
async incrementTagVersion(tag: string): Promise<number> {
|
|
123
|
+
const res = await this._executeCommand<number>(['INCR', `tag_ver:${tag}`]);
|
|
124
|
+
return typeof res === 'number' ? res : 1;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
async getTagVersion(tag: string): Promise<number> {
|
|
128
|
+
const res = await this._executeCommand<string | null>(['GET', `tag_ver:${tag}`]);
|
|
129
|
+
return res ? parseInt(res, 10) || 1 : 1;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
async batchGetTagVersions(tags: string[]): Promise<Record<string, number>> {
|
|
133
|
+
if (tags.length === 0) return {};
|
|
134
|
+
const keys = tags.map(t => `tag_ver:${t}`);
|
|
135
|
+
const res = await this.mget(keys);
|
|
136
|
+
const result: Record<string, number> = {};
|
|
137
|
+
for (let i = 0; i < tags.length; i++) {
|
|
138
|
+
const raw = res[i];
|
|
139
|
+
result[tags[i]] = raw ? parseInt(raw, 10) || 1 : 1;
|
|
140
|
+
}
|
|
141
|
+
return result;
|
|
142
|
+
}
|
|
143
|
+
}
|