Code owners
Assign users and groups as approvers for specific file changes. Learn more.
redis.js 2.32 KiB
/*
*
* @copyright Copyright (c) OX Software GmbH, Germany <info@open-xchange.com>
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with OX App Suite. If not, see <https://www.gnu.org/licenses/agpl-3.0.txt>.
*
* Any use of the work other than as authorized under this license or copyright law is prohibited.
*
*/
import Redis from 'ioredis'
import logger from './logger.js'
const commonQueueOptions = { enableReadyCheck: false, maxRetriesPerRequest: null }
const hosts = (process.env.REDIS_HOSTS || '').split(',').map(host => {
const [hostname, port] = host.split(':')
return { host: hostname, port: Number(port) }
})
export function createClient (id, options = commonQueueOptions) {
options = {
username: process.env.REDIS_USERNAME,
db: Number(process.env.REDIS_DB),
password: process.env.REDIS_PASSWORD,
...options
}
if (process.env.REDIS_MODE === 'sentinel') {
options = {
sentinels: hosts,
name: process.env.REDIS_SENTINEL_MASTER_ID,
...options
}
} else if (process.env.REDIS_MODE === 'standalone') {
options = {
...hosts[0],
...options
}
}
const client = process.env.REDIS_MODE === 'cluster'
? new Redis.Cluster(hosts, { redisOptions: options })
: new Redis(options)
client.on('ready', () => logger.info(`[Redis] Connected ${id} to redis on ${process.env.REDIS_HOSTS}`))
client.on('error', (err) => logger.error(`[Redis] Connect error: ${err}`))
return client
}
export async function isReady () {
return new Promise(resolve => {
client.on('ready', () => resolve(true))
client.on('error', () => resolve(false))
}).catch(() => false)
}
export const client = createClient('common client', { maxRetriesPerRequest: 1 })
export function isEnabled () {
return !!process.env.REDIS_HOST
}