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