forked from rinafcode/teachLink_backend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsession.service.ts
More file actions
300 lines (262 loc) · 7.97 KB
/
Copy pathsession.service.ts
File metadata and controls
300 lines (262 loc) · 7.97 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
import { Inject, Injectable, Logger, OnModuleDestroy } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import Redis from 'ioredis';
import { randomUUID } from 'crypto';
import { SESSION_REDIS_CLIENT } from './session.constants';
interface ISessionRecord {
sid: string;
userId: string;
metadata: Record<string, unknown>;
version: number;
createdAt: number;
updatedAt: number;
}
/**
* Provides session operations.
*/
@Injectable()
export class SessionService implements OnModuleDestroy {
private readonly logger = new Logger(SessionService.name);
private readonly sessionPrefix: string;
private readonly legacySessionPrefix: string;
private readonly sessionTtlSeconds: number;
private readonly lockTtlMs: number;
private readonly lockRetries: number;
private readonly lockRetryDelayMs: number;
constructor(
@Inject(SESSION_REDIS_CLIENT) private readonly redis: Redis,
private readonly configService: ConfigService,
) {
this.sessionPrefix = this.configService.get<string>('AUTH_SESSION_PREFIX') || 'auth:sess:';
this.legacySessionPrefix =
this.configService.get<string>('AUTH_SESSION_LEGACY_PREFIX') || 'session:';
this.sessionTtlSeconds = parseInt(
this.configService.get<string>('AUTH_SESSION_TTL_SECONDS') || '604800',
10,
);
this.lockTtlMs = parseInt(this.configService.get<string>('SESSION_LOCK_TTL_MS') || '5000', 10);
this.lockRetries = parseInt(
this.configService.get<string>('SESSION_LOCK_MAX_RETRIES') || '5',
10,
);
this.lockRetryDelayMs = parseInt(
this.configService.get<string>('SESSION_LOCK_RETRY_DELAY_MS') || '120',
10,
);
}
/**
* Executes on Module Destroy.
*/
async onModuleDestroy(): Promise<void> {
if (this.redis.status !== 'end') {
await this.redis.quit();
}
}
/**
* Creates session.
* @param userId The user identifier.
* @param metadata The data to process.
* @returns The resulting string value.
*/
async createSession(userId: string, metadata: Record<string, unknown> = {}): Promise<string> {
const sid = randomUUID();
const now = Date.now();
const session: ISessionRecord = {
sid,
userId,
metadata,
version: 1,
createdAt: now,
updatedAt: now,
};
await this.redis.set(
this.sessionKey(sid),
JSON.stringify(session),
'EX',
this.sessionTtlSeconds,
);
await this.addSessionToUserIndex(userId, sid);
return sid;
}
async getSession(sid: string): Promise<ISessionRecord | null> {
const data = await this.redis.get(this.sessionKey(sid));
if (!data) {
return this.migrateLegacySessionIfNeeded(sid);
}
try {
return JSON.parse(data) as ISessionRecord;
} catch {
this.logger.warn(`Invalid session payload for sid=${sid}`);
return null;
}
}
/**
* Executes touch Session.
* @param sid The sid.
* @param metadataPatch The data to process.
*/
async touchSession(sid: string, metadataPatch: Record<string, unknown> = {}): Promise<void> {
const session = await this.getSession(sid);
if (!session) {
return;
}
const nextSession: ISessionRecord = {
...session,
metadata: {
...session.metadata,
...metadataPatch,
},
updatedAt: Date.now(),
version: session.version + 1,
};
await this.redis
.multi()
.set(this.sessionKey(sid), JSON.stringify(nextSession))
.expire(this.sessionKey(sid), this.sessionTtlSeconds)
.exec();
}
/**
* Removes session.
* @param sid The sid.
*/
async removeSession(sid: string): Promise<void> {
const session = await this.getSession(sid);
await this.redis.del(this.sessionKey(sid));
if (session) {
await this.removeSessionFromUserIndex(session.userId, sid);
}
}
async deleteAllSessionsForUser(userId: string): Promise<number> {
const pattern = `${this.sessionPrefix}*`;
let cursor = '0';
let deletedCount = 0;
do {
const [nextCursor, keys] = await this.redis.scan(cursor, 'MATCH', pattern, 'COUNT', 100);
cursor = nextCursor;
for (const key of keys) {
const sessionData = await this.redis.get(key);
if (!sessionData) {
continue;
}
try {
const session = JSON.parse(sessionData) as ISessionRecord;
if (session.userId === userId) {
await this.redis.del(key);
await this.removeSessionFromUserIndex(userId, session.sid);
deletedCount += 1;
}
} catch {
this.logger.warn(`Invalid session payload for key=${key}`);
}
}
} while (cursor !== '0');
return deletedCount;
}
async addSessionToUserIndex(userId: string, sid: string): Promise<void> {
await this.redis.zadd(`user:sessions:${userId}`, Date.now(), sid);
}
async removeSessionFromUserIndex(userId: string, sid: string): Promise<void> {
await this.redis.zrem(`user:sessions:${userId}`, sid);
}
async getUserSessionIds(userId: string): Promise<string[]> {
return this.redis.zrange(`user:sessions:${userId}`, 0, -1);
}
/**
* Executes migrate Session.
* @param oldSid The old sid.
* @param newSid The new sid.
* @returns The resulting string value.
*/
async migrateSession(oldSid: string, newSid = randomUUID()): Promise<string> {
const existing = await this.getSession(oldSid);
if (!existing) {
return newSid;
}
const migrated: ISessionRecord = {
...existing,
sid: newSid,
updatedAt: Date.now(),
version: existing.version + 1,
};
await this.redis
.multi()
.set(this.sessionKey(newSid), JSON.stringify(migrated), 'EX', this.sessionTtlSeconds)
.del(this.sessionKey(oldSid))
.exec();
return newSid;
}
/**
* Executes with Lock.
* @param lockName The lock name.
* @param handler The handler.
* @returns The resulting t.
*/
async withLock<T>(lockName: string, handler: () => Promise<T>): Promise<T> {
const lockKey = `lock:${lockName}`;
const lockToken = randomUUID();
let locked = false;
for (let attempt = 0; attempt <= this.lockRetries; attempt += 1) {
const response = await this.redis.set(lockKey, lockToken, 'PX', this.lockTtlMs, 'NX');
if (response === 'OK') {
locked = true;
break;
}
if (attempt < this.lockRetries) {
await this.delay(this.lockRetryDelayMs);
}
}
if (!locked) {
throw new Error(`Could not acquire lock: ${lockName}`);
}
try {
return await handler();
} finally {
await this.releaseLock(lockKey, lockToken);
}
}
private async migrateLegacySessionIfNeeded(sid: string): Promise<ISessionRecord | null> {
const legacyKey = `${this.legacySessionPrefix}${sid}`;
const currentKey = this.sessionKey(sid);
if (legacyKey === currentKey) {
return null;
}
const legacyData = await this.redis.get(legacyKey);
if (!legacyData) {
return null;
}
const now = Date.now();
const migrated: ISessionRecord = {
sid,
userId: 'unknown',
metadata: {
source: 'legacy',
payload: legacyData,
},
version: 1,
createdAt: now,
updatedAt: now,
};
await this.redis
.multi()
.set(currentKey, JSON.stringify(migrated), 'EX', this.sessionTtlSeconds)
.del(legacyKey)
.exec();
this.logger.log(`Migrated legacy session sid=${sid} to prefix=${this.sessionPrefix}`);
return migrated;
}
private async releaseLock(lockKey: string, lockToken: string): Promise<void> {
const releaseScript = `
if redis.call('GET', KEYS[1]) == ARGV[1] then
return redis.call('DEL', KEYS[1])
end
return 0
`;
await this.redis.eval(releaseScript, 1, lockKey, lockToken);
}
private sessionKey(sid: string): string {
return `${this.sessionPrefix}${sid}`;
}
private async delay(ms: number): Promise<void> {
await new Promise((resolve) => setTimeout(resolve, ms));
}
}