-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsession-store.ts
More file actions
356 lines (311 loc) · 12 KB
/
session-store.ts
File metadata and controls
356 lines (311 loc) · 12 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
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
import { Redis } from "ioredis";
import os from "node:os";
/* ------------------------------------------------------------------ */
/* Types */
/* ------------------------------------------------------------------ */
export interface UserContext {
userId: number;
consumerId: string;
orgId: string;
email: string;
}
export type ProxyMode = "actions";
/** Serialisable session metadata (no timers, no WebSocket handles). */
export interface SessionRecord {
id: string;
owner: UserContext;
apiKey: string;
upstreamSessionId: string;
upstreamCdpUrl: string;
mode: ProxyMode;
createdAtMs: number;
expiresAtMs: number;
idleTimeoutMs: number;
maxDurationMs: number;
connectedClients: number;
lastActivityMs: number;
/** Which replica owns the live WebSocket connections for this session. */
replicaId: string;
}
/* ------------------------------------------------------------------ */
/* Redis client */
/* ------------------------------------------------------------------ */
const REDIS_URL = process.env.REDIS_URL?.trim();
function createRedisClient(): Redis {
if (!REDIS_URL) {
throw new Error("REDIS_URL is required for multi-replica mode");
}
const client = new Redis(REDIS_URL, {
maxRetriesPerRequest: 3,
retryStrategy(times) {
return Math.min(times * 200, 3000);
},
lazyConnect: true,
});
client.on("error", (err) => {
console.error(`[session-store] redis error: ${err.message}`);
});
return client;
}
let redis: Redis | null = null;
export function getRedis(): Redis {
if (!redis) {
redis = createRedisClient();
}
return redis;
}
export async function connectRedis(): Promise<void> {
const r = getRedis();
await r.connect();
console.log("[session-store] redis connected");
}
export async function disconnectRedis(): Promise<void> {
if (redis) {
await redis.quit();
redis = null;
}
}
/* ------------------------------------------------------------------ */
/* Replica identity */
/* ------------------------------------------------------------------ */
export const REPLICA_ID =
process.env.RAILWAY_REPLICA_ID?.trim() ||
process.env.RAILWAY_DEPLOYMENT_ID?.trim() ||
os.hostname();
/* ------------------------------------------------------------------ */
/* Key helpers */
/* ------------------------------------------------------------------ */
const KEY = {
session: (id: string) => `proxy:session:${id}`,
orgSessions: (orgId: string) => `proxy:org:${orgId}:sessions`,
orgLimits: (orgId: string) => `proxy:org:${orgId}:limits`,
} as const;
/* ------------------------------------------------------------------ */
/* Serialisation */
/* ------------------------------------------------------------------ */
function serialise(session: SessionRecord): Record<string, string> {
return {
id: session.id,
owner: JSON.stringify(session.owner),
apiKey: session.apiKey,
upstreamSessionId: session.upstreamSessionId,
upstreamCdpUrl: session.upstreamCdpUrl,
mode: session.mode,
createdAtMs: String(session.createdAtMs),
expiresAtMs: String(session.expiresAtMs),
idleTimeoutMs: String(session.idleTimeoutMs),
maxDurationMs: String(session.maxDurationMs),
connectedClients: String(session.connectedClients),
lastActivityMs: String(session.lastActivityMs),
replicaId: session.replicaId,
};
}
function deserialise(hash: Record<string, string>): SessionRecord | null {
if (!hash || !hash.id) return null;
try {
return {
id: hash.id,
owner: JSON.parse(hash.owner) as UserContext,
apiKey: hash.apiKey,
upstreamSessionId: hash.upstreamSessionId,
upstreamCdpUrl: hash.upstreamCdpUrl,
mode: hash.mode as ProxyMode,
createdAtMs: Number(hash.createdAtMs),
expiresAtMs: Number(hash.expiresAtMs),
idleTimeoutMs: Number(hash.idleTimeoutMs),
maxDurationMs: Number(hash.maxDurationMs),
connectedClients: Number(hash.connectedClients),
lastActivityMs: Number(hash.lastActivityMs),
replicaId: hash.replicaId,
};
} catch {
return null;
}
}
/* ------------------------------------------------------------------ */
/* CRUD operations */
/* ------------------------------------------------------------------ */
/** Save a new session. Sets Redis TTL to maxDurationMs + 60s buffer. */
export async function saveSession(session: SessionRecord): Promise<void> {
const r = getRedis();
const key = KEY.session(session.id);
const ttlSec = Math.ceil(session.maxDurationMs / 1000) + 60;
const pipeline = r.pipeline();
pipeline.hset(key, serialise(session));
pipeline.expire(key, ttlSec);
pipeline.sadd(KEY.orgSessions(session.owner.orgId), session.id);
await pipeline.exec();
}
/** Get session by ID. Returns null if not found or expired in Redis. */
export async function getSession(sessionId: string): Promise<SessionRecord | null> {
const r = getRedis();
const hash = await r.hgetall(KEY.session(sessionId));
if (!hash || Object.keys(hash).length === 0) return null;
return deserialise(hash as Record<string, string>);
}
/** Delete session from Redis and remove from org set. */
export async function deleteSession(sessionId: string, orgId: string): Promise<void> {
const r = getRedis();
const pipeline = r.pipeline();
pipeline.del(KEY.session(sessionId));
pipeline.srem(KEY.orgSessions(orgId), sessionId);
await pipeline.exec();
}
/** Update specific fields on a session. */
export async function updateSession(
sessionId: string,
fields: Partial<Pick<SessionRecord, "connectedClients" | "lastActivityMs">>,
): Promise<void> {
const r = getRedis();
const updates: Record<string, string> = {};
if (fields.connectedClients !== undefined) updates.connectedClients = String(fields.connectedClients);
if (fields.lastActivityMs !== undefined) updates.lastActivityMs = String(fields.lastActivityMs);
if (Object.keys(updates).length > 0) {
await r.hset(KEY.session(sessionId), updates);
}
}
/** Check if this replica owns the session's WebSocket connections. */
export async function isOwnedByThisReplica(sessionId: string): Promise<boolean> {
const r = getRedis();
const rid = await r.hget(KEY.session(sessionId), "replicaId");
return rid === REPLICA_ID;
}
/** Get the replicaId that owns a session. */
export async function getSessionReplicaId(sessionId: string): Promise<string | null> {
const r = getRedis();
return r.hget(KEY.session(sessionId), "replicaId");
}
/* ------------------------------------------------------------------ */
/* Per-org queries */
/* ------------------------------------------------------------------ */
/** Count active sessions for an org. Cleans up expired entries. */
export async function countOrgSessions(orgId: string): Promise<number> {
const r = getRedis();
const sessionIds = await r.smembers(KEY.orgSessions(orgId));
if (sessionIds.length === 0) return 0;
// Verify each session still exists (TTL may have expired)
const pipeline = r.pipeline();
for (const sid of sessionIds) {
pipeline.exists(KEY.session(sid));
}
const results = await pipeline.exec();
if (!results) return 0;
const stale: string[] = [];
let count = 0;
for (let i = 0; i < results.length; i++) {
const [err, exists] = results[i];
if (!err && exists === 1) {
count++;
} else {
stale.push(sessionIds[i]);
}
}
// Clean up stale entries
if (stale.length > 0) {
await r.srem(KEY.orgSessions(orgId), ...stale);
}
return count;
}
/** List all session IDs for an org. */
export async function listOrgSessionIds(orgId: string): Promise<string[]> {
const r = getRedis();
return r.smembers(KEY.orgSessions(orgId));
}
/* ------------------------------------------------------------------ */
/* Per-org limits */
/* ------------------------------------------------------------------ */
export interface OrgLimits {
maxConcurrentSessions: number;
maxSessionCreatesPerHour: number;
}
const DEFAULT_ORG_LIMITS: OrgLimits = {
maxConcurrentSessions: 10,
maxSessionCreatesPerHour: 100,
};
export async function getOrgLimits(orgId: string): Promise<OrgLimits> {
const r = getRedis();
const raw = await r.hgetall(KEY.orgLimits(orgId));
if (!raw || Object.keys(raw).length === 0) return DEFAULT_ORG_LIMITS;
return {
maxConcurrentSessions: Number(raw.maxConcurrentSessions) || DEFAULT_ORG_LIMITS.maxConcurrentSessions,
maxSessionCreatesPerHour: Number(raw.maxSessionCreatesPerHour) || DEFAULT_ORG_LIMITS.maxSessionCreatesPerHour,
};
}
export async function setOrgLimits(orgId: string, limits: Partial<OrgLimits>): Promise<void> {
const r = getRedis();
const updates: Record<string, string> = {};
if (limits.maxConcurrentSessions !== undefined) updates.maxConcurrentSessions = String(limits.maxConcurrentSessions);
if (limits.maxSessionCreatesPerHour !== undefined) updates.maxSessionCreatesPerHour = String(limits.maxSessionCreatesPerHour);
if (Object.keys(updates).length > 0) {
await r.hset(KEY.orgLimits(orgId), updates);
}
}
/** Check concurrency limit. Returns true if allowed. */
export async function checkConcurrencyLimit(orgId: string): Promise<{ allowed: boolean; current: number; limit: number }> {
const [limits, current] = await Promise.all([
getOrgLimits(orgId),
countOrgSessions(orgId),
]);
return {
allowed: current < limits.maxConcurrentSessions,
current,
limit: limits.maxConcurrentSessions,
};
}
/** Check hourly rate limit. Returns true if allowed. Uses a sliding window counter. */
export async function checkRateLimit(orgId: string): Promise<{ allowed: boolean; current: number; limit: number }> {
const limits = await getOrgLimits(orgId);
const r = getRedis();
const rateKey = `proxy:org:${orgId}:rate:${Math.floor(Date.now() / 3_600_000)}`;
const current = await r.incr(rateKey);
if (current === 1) {
await r.expire(rateKey, 3600);
}
if (current > limits.maxSessionCreatesPerHour) {
return { allowed: false, current, limit: limits.maxSessionCreatesPerHour };
}
return { allowed: true, current, limit: limits.maxSessionCreatesPerHour };
}
/* ------------------------------------------------------------------ */
/* Stale session cleanup */
/* ------------------------------------------------------------------ */
/**
* On startup, find sessions that claim to be owned by this replica
* (from a previous instance) and return them for cleanup.
*/
export async function findStaleSessions(): Promise<SessionRecord[]> {
const r = getRedis();
const stale: SessionRecord[] = [];
// SCAN for all session keys
let cursor = "0";
do {
const [nextCursor, keys] = await r.scan(cursor, "MATCH", "proxy:session:*", "COUNT", 100);
cursor = nextCursor;
for (const key of keys) {
const rid = await r.hget(key, "replicaId");
if (rid === REPLICA_ID) {
const hash = await r.hgetall(key);
if (hash && Object.keys(hash).length > 0) {
const session = deserialise(hash as Record<string, string>);
if (session) stale.push(session);
}
}
}
} while (cursor !== "0");
return stale;
}
/* ------------------------------------------------------------------ */
/* Global stats */
/* ------------------------------------------------------------------ */
/** Count total active sessions across all replicas. */
export async function countAllSessions(): Promise<number> {
const r = getRedis();
let count = 0;
let cursor = "0";
do {
const [nextCursor, keys] = await r.scan(cursor, "MATCH", "proxy:session:*", "COUNT", 100);
cursor = nextCursor;
count += keys.length;
} while (cursor !== "0");
return count;
}