]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/lib/redis.ts
Convert followers/following in raw SQL queries
[github/Chocobozzz/PeerTube.git] / server / lib / redis.ts
CommitLineData
f4110e0a 1import { createClient, RedisClientOptions, RedisModules, RedisScripts } from 'redis'
e5d91a9b 2import { exists } from '@server/helpers/custom-validators/misc'
f1569117 3import { sha256 } from '@shared/extra-utils'
ecb4e35f
C
4import { logger } from '../helpers/logger'
5import { generateRandomString } from '../helpers/utils'
e5d91a9b 6import { CONFIG } from '../initializers/config'
a4101923 7import {
f1569117 8 AP_CLEANER,
a4101923 9 CONTACT_FORM_LIFETIME,
e5d91a9b
C
10 RESUMABLE_UPLOAD_SESSION_LIFETIME,
11 TRACKER_RATE_LIMITS,
a4101923 12 USER_EMAIL_VERIFY_LIFETIME,
45f1bd72 13 USER_PASSWORD_CREATE_LIFETIME,
e5d91a9b 14 USER_PASSWORD_RESET_LIFETIME,
e4bf7856 15 VIEW_LIFETIME,
e5d91a9b 16 WEBSERVER
74dc3bca 17} from '../initializers/constants'
4195cd2b 18
e5d91a9b 19// Only used for typings
b25fdc73 20// TODO: remove when https://github.com/microsoft/TypeScript/issues/37181 is fixed
f4110e0a 21const redisClientWrapperForType = () => createClient<{}, RedisScripts>()
ecb4e35f
C
22
23class Redis {
24
25 private static instance: Redis
26 private initialized = false
e5d91a9b
C
27 private connected = false
28 private client: ReturnType<typeof redisClientWrapperForType>
ecb4e35f
C
29 private prefix: string
30
a1587156
C
31 private constructor () {
32 }
ecb4e35f
C
33
34 init () {
35 // Already initialized
36 if (this.initialized === true) return
37 this.initialized = true
38
47f6409b 39 this.client = createClient(Redis.getRedisClientOptions())
ecb4e35f 40
8f5a1f36
C
41 logger.info('Connecting to redis...')
42
e5d91a9b 43 this.client.connect()
8f5a1f36
C
44 .then(() => {
45 logger.info('Connected to redis.')
46
47 this.connected = true
48 }).catch(err => {
e5d91a9b
C
49 logger.error('Cannot connect to redis', { err })
50 process.exit(-1)
51 })
52
6dd9de95 53 this.prefix = 'redis-' + WEBSERVER.HOST + '-'
ecb4e35f
C
54 }
55
47f6409b 56 static getRedisClientOptions () {
8f5a1f36
C
57 let config: RedisClientOptions<RedisModules, {}> = {
58 socket: {
59 connectTimeout: 20000 // Could be slow since node use sync call to compile PeerTube
60 }
61 }
62
63 if (CONFIG.REDIS.AUTH) {
64 config = { ...config, password: CONFIG.REDIS.AUTH }
65 }
66
67 if (CONFIG.REDIS.DB) {
68 config = { ...config, database: CONFIG.REDIS.DB }
69 }
70
71 if (CONFIG.REDIS.HOSTNAME && CONFIG.REDIS.PORT) {
72 config.socket = { ...config.socket, host: CONFIG.REDIS.HOSTNAME, port: CONFIG.REDIS.PORT }
73 } else {
74 config.socket = { ...config.socket, path: CONFIG.REDIS.SOCKET }
75 }
76
77 return config
19f7b248
RK
78 }
79
47f6409b
C
80 getClient () {
81 return this.client
82 }
83
84 getPrefix () {
85 return this.prefix
86 }
87
e5d91a9b
C
88 isConnected () {
89 return this.connected
90 }
91
a1587156 92 /* ************ Forgot password ************ */
6e46de09 93
ecb4e35f
C
94 async setResetPasswordVerificationString (userId: number) {
95 const generatedString = await generateRandomString(32)
96
97 await this.setValue(this.generateResetPasswordKey(userId), generatedString, USER_PASSWORD_RESET_LIFETIME)
98
45f1bd72
JL
99 return generatedString
100 }
101
102 async setCreatePasswordVerificationString (userId: number) {
103 const generatedString = await generateRandomString(32)
104
105 await this.setValue(this.generateResetPasswordKey(userId), generatedString, USER_PASSWORD_CREATE_LIFETIME)
106
ecb4e35f
C
107 return generatedString
108 }
109
e9c5f123
C
110 async removePasswordVerificationString (userId: number) {
111 return this.removeValue(this.generateResetPasswordKey(userId))
112 }
113
ecb4e35f
C
114 async getResetPasswordLink (userId: number) {
115 return this.getValue(this.generateResetPasswordKey(userId))
116 }
117
a1587156 118 /* ************ Email verification ************ */
6e46de09 119
d9eaee39
JM
120 async setVerifyEmailVerificationString (userId: number) {
121 const generatedString = await generateRandomString(32)
122
123 await this.setValue(this.generateVerifyEmailKey(userId), generatedString, USER_EMAIL_VERIFY_LIFETIME)
124
125 return generatedString
126 }
127
128 async getVerifyEmailLink (userId: number) {
129 return this.getValue(this.generateVerifyEmailKey(userId))
130 }
131
a1587156 132 /* ************ Contact form per IP ************ */
a4101923
C
133
134 async setContactFormIp (ip: string) {
135 return this.setValue(this.generateContactFormKey(ip), '1', CONTACT_FORM_LIFETIME)
136 }
137
0f6acda1 138 async doesContactFormIpExist (ip: string) {
a4101923
C
139 return this.exists(this.generateContactFormKey(ip))
140 }
141
a1587156 142 /* ************ Views per IP ************ */
6e46de09 143
51353d9a
C
144 setIPVideoView (ip: string, videoUUID: string) {
145 return this.setValue(this.generateIPViewKey(ip, videoUUID), '1', VIEW_LIFETIME.VIEW)
146 }
e4bf7856 147
0f6acda1 148 async doesVideoIPViewExist (ip: string, videoUUID: string) {
51353d9a
C
149 return this.exists(this.generateIPViewKey(ip, videoUUID))
150 }
151
db48de85
C
152 /* ************ Tracker IP block ************ */
153
154 setTrackerBlockIP (ip: string) {
155 return this.setValue(this.generateTrackerBlockIPKey(ip), '1', TRACKER_RATE_LIMITS.BLOCK_IP_LIFETIME)
156 }
157
158 async doesTrackerBlockIPExist (ip: string) {
159 return this.exists(this.generateTrackerBlockIPKey(ip))
160 }
161
51353d9a 162 /* ************ Video views stats ************ */
6e46de09 163
51353d9a
C
164 addVideoViewStats (videoId: number) {
165 const { videoKey, setKey } = this.generateVideoViewStatsKeys({ videoId })
6b616860
C
166
167 return Promise.all([
51353d9a
C
168 this.addToSet(setKey, videoId.toString()),
169 this.increment(videoKey)
6b616860
C
170 ])
171 }
172
51353d9a
C
173 async getVideoViewsStats (videoId: number, hour: number) {
174 const { videoKey } = this.generateVideoViewStatsKeys({ videoId, hour })
6b616860 175
51353d9a 176 const valueString = await this.getValue(videoKey)
6040f87d
C
177 const valueInt = parseInt(valueString, 10)
178
179 if (isNaN(valueInt)) {
51353d9a 180 logger.error('Cannot get videos views stats of video %d in hour %d: views number is NaN (%s).', videoId, hour, valueString)
6040f87d
C
181 return undefined
182 }
183
184 return valueInt
6b616860
C
185 }
186
51353d9a
C
187 async listVideosViewedForStats (hour: number) {
188 const { setKey } = this.generateVideoViewStatsKeys({ hour })
6b616860 189
51353d9a 190 const stringIds = await this.getSet(setKey)
6b616860
C
191 return stringIds.map(s => parseInt(s, 10))
192 }
193
51353d9a
C
194 deleteVideoViewsStats (videoId: number, hour: number) {
195 const { setKey, videoKey } = this.generateVideoViewStatsKeys({ videoId, hour })
196
197 return Promise.all([
198 this.deleteFromSet(setKey, videoId.toString()),
199 this.deleteKey(videoKey)
200 ])
201 }
202
203 /* ************ Local video views buffer ************ */
204
205 addLocalVideoView (videoId: number) {
206 const { videoKey, setKey } = this.generateLocalVideoViewsKeys(videoId)
6b616860
C
207
208 return Promise.all([
51353d9a
C
209 this.addToSet(setKey, videoId.toString()),
210 this.increment(videoKey)
211 ])
212 }
213
214 async getLocalVideoViews (videoId: number) {
215 const { videoKey } = this.generateLocalVideoViewsKeys(videoId)
216
217 const valueString = await this.getValue(videoKey)
218 const valueInt = parseInt(valueString, 10)
219
220 if (isNaN(valueInt)) {
221 logger.error('Cannot get videos views of video %d: views number is NaN (%s).', videoId, valueString)
222 return undefined
223 }
224
225 return valueInt
226 }
227
228 async listLocalVideosViewed () {
229 const { setKey } = this.generateLocalVideoViewsKeys()
230
231 const stringIds = await this.getSet(setKey)
232 return stringIds.map(s => parseInt(s, 10))
233 }
234
235 deleteLocalVideoViews (videoId: number) {
236 const { setKey, videoKey } = this.generateLocalVideoViewsKeys(videoId)
237
238 return Promise.all([
239 this.deleteFromSet(setKey, videoId.toString()),
240 this.deleteKey(videoKey)
6b616860
C
241 ])
242 }
243
b2111066
C
244 /* ************ Video viewers stats ************ */
245
246 getLocalVideoViewer (options: {
247 key?: string
248 // Or
249 ip?: string
250 videoId?: number
251 }) {
252 if (options.key) return this.getObject(options.key)
253
254 const { viewerKey } = this.generateLocalVideoViewerKeys(options.ip, options.videoId)
255
256 return this.getObject(viewerKey)
257 }
258
259 setLocalVideoViewer (ip: string, videoId: number, object: any) {
260 const { setKey, viewerKey } = this.generateLocalVideoViewerKeys(ip, videoId)
261
262 return Promise.all([
263 this.addToSet(setKey, viewerKey),
264 this.setObject(viewerKey, object)
265 ])
266 }
267
268 listLocalVideoViewerKeys () {
269 const { setKey } = this.generateLocalVideoViewerKeys()
270
271 return this.getSet(setKey)
272 }
273
274 deleteLocalVideoViewersKeys (key: string) {
275 const { setKey } = this.generateLocalVideoViewerKeys()
276
277 return Promise.all([
278 this.deleteFromSet(setKey, key),
279 this.deleteKey(key)
280 ])
281 }
282
276250f0
RK
283 /* ************ Resumable uploads final responses ************ */
284
285 setUploadSession (uploadId: string, response?: { video: { id: number, shortUUID: string, uuid: string } }) {
286 return this.setValue(
287 'resumable-upload-' + uploadId,
288 response
289 ? JSON.stringify(response)
290 : '',
291 RESUMABLE_UPLOAD_SESSION_LIFETIME
292 )
293 }
294
295 doesUploadSessionExist (uploadId: string) {
296 return this.exists('resumable-upload-' + uploadId)
297 }
298
299 async getUploadSession (uploadId: string) {
300 const value = await this.getValue('resumable-upload-' + uploadId)
301
302 return value
303 ? JSON.parse(value)
304 : ''
305 }
306
020d3d3d
C
307 deleteUploadSession (uploadId: string) {
308 return this.deleteKey('resumable-upload-' + uploadId)
309 }
310
f1569117
C
311 /* ************ AP ressource unavailability ************ */
312
313 async addAPUnavailability (url: string) {
314 const key = this.generateAPUnavailabilityKey(url)
315
316 const value = await this.increment(key)
317 await this.setExpiration(key, AP_CLEANER.PERIOD * 2)
318
319 return value
320 }
321
a1587156 322 /* ************ Keys generation ************ */
6e46de09 323
b2111066
C
324 private generateLocalVideoViewsKeys (videoId: number): { setKey: string, videoKey: string }
325 private generateLocalVideoViewsKeys (): { setKey: string }
326 private generateLocalVideoViewsKeys (videoId?: number) {
51353d9a 327 return { setKey: `local-video-views-buffer`, videoKey: `local-video-views-buffer-${videoId}` }
6b616860
C
328 }
329
b2111066
C
330 private generateLocalVideoViewerKeys (ip: string, videoId: number): { setKey: string, viewerKey: string }
331 private generateLocalVideoViewerKeys (): { setKey: string }
332 private generateLocalVideoViewerKeys (ip?: string, videoId?: number) {
333 return { setKey: `local-video-viewer-stats-keys`, viewerKey: `local-video-viewer-stats-${ip}-${videoId}` }
334 }
335
51353d9a
C
336 private generateVideoViewStatsKeys (options: { videoId?: number, hour?: number }) {
337 const hour = exists(options.hour)
338 ? options.hour
339 : new Date().getHours()
6b616860 340
51353d9a 341 return { setKey: `videos-view-h${hour}`, videoKey: `video-view-${options.videoId}-h${hour}` }
6b616860
C
342 }
343
6e46de09 344 private generateResetPasswordKey (userId: number) {
b40f0575
C
345 return 'reset-password-' + userId
346 }
347
6e46de09 348 private generateVerifyEmailKey (userId: number) {
d9eaee39
JM
349 return 'verify-email-' + userId
350 }
351
51353d9a 352 private generateIPViewKey (ip: string, videoUUID: string) {
a4101923
C
353 return `views-${videoUUID}-${ip}`
354 }
355
db48de85
C
356 private generateTrackerBlockIPKey (ip: string) {
357 return `tracker-block-ip-${ip}`
358 }
359
a4101923
C
360 private generateContactFormKey (ip: string) {
361 return 'contact-form-' + ip
b40f0575
C
362 }
363
f1569117
C
364 private generateAPUnavailabilityKey (url: string) {
365 return 'ap-unavailability-' + sha256(url)
366 }
367
a1587156 368 /* ************ Redis helpers ************ */
b40f0575 369
ecb4e35f 370 private getValue (key: string) {
e5d91a9b 371 return this.client.get(this.prefix + key)
ecb4e35f
C
372 }
373
6b616860 374 private getSet (key: string) {
e5d91a9b 375 return this.client.sMembers(this.prefix + key)
6b616860
C
376 }
377
378 private addToSet (key: string, value: string) {
e5d91a9b 379 return this.client.sAdd(this.prefix + key, value)
6b616860
C
380 }
381
382 private deleteFromSet (key: string, value: string) {
e5d91a9b 383 return this.client.sRem(this.prefix + key, value)
6b616860
C
384 }
385
386 private deleteKey (key: string) {
e5d91a9b 387 return this.client.del(this.prefix + key)
6e46de09
C
388 }
389
b2111066
C
390 private async getObject (key: string) {
391 const value = await this.getValue(key)
392 if (!value) return null
393
394 return JSON.parse(value)
395 }
396
397 private setObject (key: string, value: { [ id: string ]: number | string }) {
398 return this.setValue(key, JSON.stringify(value))
399 }
400
401 private async setValue (key: string, value: string, expirationMilliseconds?: number) {
402 const options = expirationMilliseconds
403 ? { PX: expirationMilliseconds }
404 : {}
405
406 const result = await this.client.set(this.prefix + key, value, options)
ecb4e35f 407
e5d91a9b 408 if (result !== 'OK') throw new Error('Redis set result is not OK.')
ecb4e35f
C
409 }
410
e9c5f123 411 private removeValue (key: string) {
e5d91a9b 412 return this.client.del(this.prefix + key)
4195cd2b
C
413 }
414
6b616860 415 private increment (key: string) {
e5d91a9b 416 return this.client.incr(this.prefix + key)
6b616860
C
417 }
418
c0d2eac3
C
419 private async exists (key: string) {
420 const result = await this.client.exists(this.prefix + key)
421
422 return result !== 0
b5c0e955
C
423 }
424
f1569117
C
425 private setExpiration (key: string, ms: number) {
426 return this.client.expire(this.prefix + key, ms / 1000)
427 }
428
ecb4e35f
C
429 static get Instance () {
430 return this.instance || (this.instance = new this())
431 }
432}
433
434// ---------------------------------------------------------------------------
435
436export {
437 Redis
438}