RedisWrapper.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. const Settings = require('@overleaf/settings')
  2. const redis = require('@overleaf/redis-wrapper')
  3. const { addConnectionDrainer } = require('./GracefulShutdown')
  4. /**
  5. * A per-feature interface to Redis, looks up the feature in `settings.redis`
  6. * and returns an appropriate client. Necessary because we don't want to
  7. * migrate web over to redis-cluster all at once.
  8. *
  9. * @param feature - one of 'websessions' | 'ratelimiter' | ...
  10. */
  11. function client(feature) {
  12. const redisFeatureSettings = Settings.redis[feature] || Settings.redis.web
  13. const client = redis.createClient(redisFeatureSettings)
  14. addConnectionDrainer(`redis ${feature}`, async () => {
  15. await client.disconnect()
  16. })
  17. return client
  18. }
  19. async function cleanupTestRedis() {
  20. const rclient = client()
  21. ensureTestRedis(rclient)
  22. await rclient.flushall()
  23. }
  24. function ensureTestRedis(rclient) {
  25. const host = rclient.options.host
  26. const env = process.env.NODE_ENV
  27. if (host !== 'redis_test' || env !== 'test') {
  28. throw new Error(
  29. `Refusing to clear Redis instance '${host}' in environment '${env}'`
  30. )
  31. }
  32. }
  33. module.exports = { client, cleanupTestRedis }