feature: db selection in redis
[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, 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       db: CONFIG.REDIS.DB
31     })
32
33     this.client.on('error', err => {
34       logger.error('Error in Redis client.', { err })
35       process.exit(-1)
36     })
37
38     if (CONFIG.REDIS.AUTH) {
39       this.client.auth(CONFIG.REDIS.AUTH)
40     }
41
42     this.prefix = 'redis-' + CONFIG.WEBSERVER.HOST + '-'
43   }
44
45   async setResetPasswordVerificationString (userId: number) {
46     const generatedString = await generateRandomString(32)
47
48     await this.setValue(this.generateResetPasswordKey(userId), generatedString, USER_PASSWORD_RESET_LIFETIME)
49
50     return generatedString
51   }
52
53   async getResetPasswordLink (userId: number) {
54     return this.getValue(this.generateResetPasswordKey(userId))
55   }
56
57   setView (ip: string, videoUUID: string) {
58     return this.setValue(this.buildViewKey(ip, videoUUID), '1', VIDEO_VIEW_LIFETIME)
59   }
60
61   async isViewExists (ip: string, videoUUID: string) {
62     return this.exists(this.buildViewKey(ip, videoUUID))
63   }
64
65   async getCachedRoute (req: express.Request) {
66     const cached = await this.getObject(this.buildCachedRouteKey(req))
67
68     return cached as CachedRoute
69   }
70
71   setCachedRoute (req: express.Request, body: any, lifetime: number, contentType?: string, statusCode?: number) {
72     const cached: CachedRoute = {
73       body: body.toString(),
74       contentType,
75       statusCode: statusCode.toString()
76     }
77
78     return this.setObject(this.buildCachedRouteKey(req), cached, lifetime)
79   }
80
81   listJobs (jobsPrefix: string, state: string, mode: 'alpha', order: 'ASC' | 'DESC', offset: number, count: number) {
82     return new Promise<string[]>((res, rej) => {
83       this.client.sort(jobsPrefix + ':jobs:' + state, 'by', mode, order, 'LIMIT', offset.toString(), count.toString(), (err, values) => {
84         if (err) return rej(err)
85
86         return res(values)
87       })
88     })
89   }
90
91   private getValue (key: string) {
92     return new Promise<string>((res, rej) => {
93       this.client.get(this.prefix + key, (err, value) => {
94         if (err) return rej(err)
95
96         return res(value)
97       })
98     })
99   }
100
101   private setValue (key: string, value: string, expirationMilliseconds: number) {
102     return new Promise<void>((res, rej) => {
103       this.client.set(this.prefix + key, value, 'PX', expirationMilliseconds, (err, ok) => {
104         if (err) return rej(err)
105
106         if (ok !== 'OK') return rej(new Error('Redis set result is not OK.'))
107
108         return res()
109       })
110     })
111   }
112
113   private setObject (key: string, obj: { [ id: string ]: string }, expirationMilliseconds: number) {
114     return new Promise<void>((res, rej) => {
115       this.client.hmset(this.prefix + key, obj, (err, ok) => {
116         if (err) return rej(err)
117         if (!ok) return rej(new Error('Redis mset result is not OK.'))
118
119         this.client.pexpire(this.prefix + key, expirationMilliseconds, (err, ok) => {
120           if (err) return rej(err)
121           if (!ok) return rej(new Error('Redis expiration result is not OK.'))
122
123           return res()
124         })
125       })
126     })
127   }
128
129   private getObject (key: string) {
130     return new Promise<{ [ id: string ]: string }>((res, rej) => {
131       this.client.hgetall(this.prefix + key, (err, value) => {
132         if (err) return rej(err)
133
134         return res(value)
135       })
136     })
137   }
138
139   private exists (key: string) {
140     return new Promise<boolean>((res, rej) => {
141       this.client.exists(this.prefix + key, (err, existsNumber) => {
142         if (err) return rej(err)
143
144         return res(existsNumber === 1)
145       })
146     })
147   }
148
149   private generateResetPasswordKey (userId: number) {
150     return 'reset-password-' + userId
151   }
152
153   private buildViewKey (ip: string, videoUUID: string) {
154     return videoUUID + '-' + ip
155   }
156
157   private buildCachedRouteKey (req: express.Request) {
158     return req.method + '-' + req.originalUrl
159   }
160
161   static get Instance () {
162     return this.instance || (this.instance = new this())
163   }
164 }
165
166 // ---------------------------------------------------------------------------
167
168 export {
169   Redis
170 }