Add redis cache to feed route
[oweals/peertube.git] / server / lib / redis.ts
1 import * as express from 'express'
2 import { createClient, RedisClient } from 'redis'
3 import { logger } from '../helpers/logger'
4 import { generateRandomString } from '../helpers/utils'
5 import { CONFIG, FEEDS, USER_PASSWORD_RESET_LIFETIME, VIDEO_VIEW_LIFETIME } from '../initializers'
6
7 type CachedRoute = {
8   body: string,
9   contentType?: string
10   statusCode?: string
11 }
12
13 class Redis {
14
15   private static instance: Redis
16   private initialized = false
17   private client: RedisClient
18   private prefix: string
19
20   private constructor () {}
21
22   init () {
23     // Already initialized
24     if (this.initialized === true) return
25     this.initialized = true
26
27     this.client = createClient({
28       host: CONFIG.REDIS.HOSTNAME,
29       port: CONFIG.REDIS.PORT
30     })
31
32     this.client.on('error', err => {
33       logger.error('Error in Redis client.', { err })
34       process.exit(-1)
35     })
36
37     if (CONFIG.REDIS.AUTH) {
38       this.client.auth(CONFIG.REDIS.AUTH)
39     }
40
41     this.prefix = 'redis-' + CONFIG.WEBSERVER.HOST + '-'
42   }
43
44   async setResetPasswordVerificationString (userId: number) {
45     const generatedString = await generateRandomString(32)
46
47     await this.setValue(this.generateResetPasswordKey(userId), generatedString, USER_PASSWORD_RESET_LIFETIME)
48
49     return generatedString
50   }
51
52   async getResetPasswordLink (userId: number) {
53     return this.getValue(this.generateResetPasswordKey(userId))
54   }
55
56   setView (ip: string, videoUUID: string) {
57     return this.setValue(this.buildViewKey(ip, videoUUID), '1', VIDEO_VIEW_LIFETIME)
58   }
59
60   async isViewExists (ip: string, videoUUID: string) {
61     return this.exists(this.buildViewKey(ip, videoUUID))
62   }
63
64   async getCachedRoute (req: express.Request) {
65     const cached = await this.getObject(this.buildCachedRouteKey(req))
66
67     return cached as CachedRoute
68   }
69
70   setCachedRoute (req: express.Request, body: any, contentType?: string, statusCode?: number) {
71     const cached: CachedRoute = {
72       body: body.toString(),
73       contentType,
74       statusCode: statusCode.toString()
75     }
76
77     return this.setObject(this.buildCachedRouteKey(req), cached, FEEDS.CACHE_LIFETIME)
78   }
79
80   listJobs (jobsPrefix: string, state: string, mode: 'alpha', order: 'ASC' | 'DESC', offset: number, count: number) {
81     return new Promise<string[]>((res, rej) => {
82       this.client.sort(jobsPrefix + ':jobs:' + state, 'by', mode, order, 'LIMIT', offset.toString(), count.toString(), (err, values) => {
83         if (err) return rej(err)
84
85         return res(values)
86       })
87     })
88   }
89
90   private getValue (key: string) {
91     return new Promise<string>((res, rej) => {
92       this.client.get(this.prefix + key, (err, value) => {
93         if (err) return rej(err)
94
95         return res(value)
96       })
97     })
98   }
99
100   private setValue (key: string, value: string, expirationMilliseconds: number) {
101     return new Promise<void>((res, rej) => {
102       this.client.set(this.prefix + key, value, 'PX', expirationMilliseconds, (err, ok) => {
103         if (err) return rej(err)
104
105         if (ok !== 'OK') return rej(new Error('Redis set result is not OK.'))
106
107         return res()
108       })
109     })
110   }
111
112   private setObject (key: string, obj: { [ id: string ]: string }, expirationMilliseconds: number) {
113     return new Promise<void>((res, rej) => {
114       this.client.hmset(this.prefix + key, obj, (err, ok) => {
115         if (err) return rej(err)
116         if (!ok) return rej(new Error('Redis mset result is not OK.'))
117
118         this.client.pexpire(this.prefix + key, expirationMilliseconds, (err, ok) => {
119           if (err) return rej(err)
120           if (!ok) return rej(new Error('Redis expiration result is not OK.'))
121
122           return res()
123         })
124       })
125     })
126   }
127
128   private getObject (key: string) {
129     return new Promise<{ [ id: string ]: string }>((res, rej) => {
130       this.client.hgetall(this.prefix + key, (err, value) => {
131         if (err) return rej(err)
132
133         return res(value)
134       })
135     })
136   }
137
138   private exists (key: string) {
139     return new Promise<boolean>((res, rej) => {
140       this.client.exists(this.prefix + key, (err, existsNumber) => {
141         if (err) return rej(err)
142
143         return res(existsNumber === 1)
144       })
145     })
146   }
147
148   private generateResetPasswordKey (userId: number) {
149     return 'reset-password-' + userId
150   }
151
152   private buildViewKey (ip: string, videoUUID: string) {
153     return videoUUID + '-' + ip
154   }
155
156   private buildCachedRouteKey (req: express.Request) {
157     return req.method + '-' + req.originalUrl
158   }
159
160   static get Instance () {
161     return this.instance || (this.instance = new this())
162   }
163 }
164
165 // ---------------------------------------------------------------------------
166
167 export {
168   Redis
169 }