test_blpop_failover.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. let listenInBackground, sendPings
  2. const redis = require('@overleaf/redis-wrapper')
  3. const rclient1 = redis.createClient({
  4. cluster: [
  5. {
  6. port: '7000',
  7. host: '127.0.0.1',
  8. },
  9. ],
  10. })
  11. const rclient2 = redis.createClient({
  12. cluster: [
  13. {
  14. port: '7000',
  15. host: '127.0.0.1',
  16. },
  17. ],
  18. })
  19. let counter = 0
  20. const sendPing = function (cb) {
  21. if (cb == null) {
  22. cb = function () {}
  23. }
  24. return rclient1.rpush('test-blpop', counter, error => {
  25. if (error != null) {
  26. console.error('[SENDING ERROR]', error.message)
  27. }
  28. if (error == null) {
  29. counter += 1
  30. }
  31. return cb()
  32. })
  33. }
  34. let previous = null
  35. const listenForPing = cb =>
  36. rclient2.blpop('test-blpop', 200, (error, result) => {
  37. if (error != null) {
  38. return cb(error)
  39. }
  40. let [, value] = Array.from(result)
  41. value = parseInt(value, 10)
  42. if (value % 10 === 0) {
  43. console.log('.')
  44. }
  45. if (previous != null && value !== previous + 1) {
  46. error = new Error(
  47. `Counter not in order. Got ${value}, expected ${previous + 1}`
  48. )
  49. }
  50. previous = value
  51. return cb(error, value)
  52. })
  53. const PING_DELAY = 100
  54. ;(sendPings = () => sendPing(() => setTimeout(sendPings, PING_DELAY)))()
  55. ;(listenInBackground = () =>
  56. listenForPing(error => {
  57. if (error) {
  58. console.error('[RECEIVING ERROR]', error.message)
  59. }
  60. return setTimeout(listenInBackground)
  61. }))()