-
Notifications
You must be signed in to change notification settings - Fork 55
Expand file tree
/
Copy pathcache-handler.ts
More file actions
267 lines (228 loc) · 6.74 KB
/
Copy pathcache-handler.ts
File metadata and controls
267 lines (228 loc) · 6.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
import { createClient } from "redis";
import type { RedisClientType } from "redis";
interface CacheEntry {
value: any;
lastModified: number;
tags: string[];
}
const DEFAULT_TTL = 84600; // 24 hours
const CACHE_KEY_PREFIX = "basechat:";
const TAG_INDEX_PREFIX = "basechat:tags:";
/**
* Builds a tenant-user tag for cache invalidation purposes
*/
export function buildTenantUserTag(userId: string, slug: string): string {
return `tenant:${slug}:user:${userId}`;
}
/**
* Builds a tenant tag for cache invalidation purposes
*/
export function buildTenantTag(slug: string): string {
return `tenant:${slug}`;
}
/**
* Builds tags array with tenant-wide and user-specific tags
*/
export function buildTags(userId: string, slug: string): string[] {
return [
buildTenantUserTag(userId, slug), // User-specific
buildTenantTag(slug), // Tenant-wide
];
}
export default class CacheHandler {
private redisClient: RedisClientType | null = null;
private isConnected: boolean = false;
private connectionPromise: Promise<boolean> | null = null;
constructor() {
// lazily initialize Redis
const redisUrl = process.env.REDIS_URL;
if (!redisUrl) {
console.warn("REDIS_URL environment variable not set. Cache will be disabled.");
return;
}
try {
this.redisClient = createClient({
url: redisUrl,
socket: {
reconnectStrategy: (retries) => {
// Fail fast - don't retry indefinitely
if (retries > 3) {
console.warn("Redis reconnection attempts exceeded, disabling cache");
return false;
}
return Math.min(retries * 100, 3000);
},
},
});
// Set up error handler
this.redisClient.on("error", (err: any) => {
console.error("Redis client error:", err);
this.isConnected = false;
});
this.redisClient.on("connect", () => {
this.isConnected = true;
});
this.redisClient.on("disconnect", () => {
console.log("Redis client disconnected");
this.isConnected = false;
});
} catch (error) {
console.error("Failed to create Redis client:", error);
this.redisClient = null;
}
}
private async ensureConnected(): Promise<boolean> {
if (!this.redisClient) {
return false;
}
if (this.isConnected) {
return true;
}
// If connection is already in progress, wait for it
if (this.connectionPromise) {
return this.connectionPromise;
}
// Start new connection attempt
this.connectionPromise = (async () => {
try {
await this.redisClient!.connect();
this.isConnected = true;
return true;
} catch (error) {
console.error("Failed to connect to Redis:", error);
this.isConnected = false;
return false;
} finally {
this.connectionPromise = null;
}
})();
return this.connectionPromise;
}
/**
* Gets the Redis key for a tag index
*/
private getTagIndexKey(tag: string): string {
return `${TAG_INDEX_PREFIX}${tag}`;
}
/**
* Get a value from cache by key
*/
async get(key: string): Promise<CacheEntry | undefined> {
const prefixedKey = `${CACHE_KEY_PREFIX}${key}`;
try {
const connected = await this.ensureConnected();
if (!connected) {
console.warn("Redis unavailable in get()");
return undefined;
}
const data = await this.redisClient!.get(prefixedKey);
if (!data) {
return undefined;
}
const parsed: CacheEntry = JSON.parse(data);
return parsed;
} catch (error) {
console.warn("Error getting cache key:", error);
return undefined;
}
}
/**
* Set a value in cache with tags
*/
async set(key: string, data: any, ctx: any): Promise<void> {
const prefixedKey = `${CACHE_KEY_PREFIX}${key}`;
const fixedCtx = {
...ctx,
tags: Array.isArray(ctx.tags) ? ctx.tags : [ctx.tags],
};
const fixedData = {
...data,
revalidate: typeof data.revalidate === "number" ? data.revalidate : DEFAULT_TTL,
};
try {
const connected = await this.ensureConnected();
if (!connected) {
console.warn("Redis unavailable in set()");
return undefined;
}
// Create the cache entry
const cacheEntry: CacheEntry = {
value: fixedData,
lastModified: Date.now(),
tags: fixedCtx.tags,
};
// Serialize the entry
const serialized = JSON.stringify(cacheEntry);
// Store the cache entry
await this.redisClient!.set(prefixedKey, serialized, {
expiration: {
type: "EX",
value: fixedData.revalidate,
},
});
// Update tag indices - add this cache key to each tag's set
// Using a pipeline for efficiency (though not strictly atomic)
const multi = this.redisClient!.multi();
for (const tag of fixedCtx.tags) {
const tagIndexKey = this.getTagIndexKey(tag);
multi.sAdd(tagIndexKey, prefixedKey);
multi.expire(tagIndexKey, fixedData.revalidate);
}
await multi.exec();
} catch (error) {
console.warn("Error setting cache key:", error);
return undefined;
}
}
/**
* Revalidate (invalidate) cache entries by tag(s)
*/
async revalidateTag(tags: string | string[]): Promise<void> {
try {
const connected = await this.ensureConnected();
if (!connected) {
console.warn("Redis unavailable in revalidateTag()");
return undefined;
}
const tagArray = Array.isArray(tags) ? tags : [tags];
for (const tag of tagArray) {
const tagIndexKey = this.getTagIndexKey(tag);
// Get all cache keys associated with this tag
const cacheKeys = await this.redisClient!.sMembers(tagIndexKey);
if (cacheKeys.length === 0) {
continue;
}
// Delete all cache entries and the tag index
const multi = this.redisClient!.multi();
for (const cacheKey of cacheKeys) {
multi.del(cacheKey);
}
// Delete the tag index itself
multi.del(tagIndexKey);
await multi.exec();
}
} catch (error) {
console.warn("Error revalidating tags:", error);
return undefined;
}
}
/**
* Reset per-request cache (not needed for Redis-backed cache)
*/
resetRequestCache(): void {
// No-op: we don't maintain per-request cache
}
/**
* Gracefully disconnect from Redis
*/
async disconnect(): Promise<void> {
if (this.redisClient && this.isConnected) {
try {
await this.redisClient.quit();
this.isConnected = false;
} catch (error) {
console.warn("Error disconnecting from Redis:", error);
}
}
}
}