DocumentUpdaterController.js 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  1. const logger = require('@overleaf/logger')
  2. const settings = require('@overleaf/settings')
  3. const RedisClientManager = require('./RedisClientManager')
  4. const SafeJsonParse = require('./SafeJsonParse')
  5. const EventLogger = require('./EventLogger')
  6. const HealthCheckManager = require('./HealthCheckManager')
  7. const RoomManager = require('./RoomManager')
  8. const ChannelManager = require('./ChannelManager')
  9. const metrics = require('@overleaf/metrics')
  10. let DocumentUpdaterController
  11. module.exports = DocumentUpdaterController = {
  12. // DocumentUpdaterController is responsible for updates that come via Redis
  13. // Pub/Sub from the document updater.
  14. rclientList: RedisClientManager.createClientList(settings.redis.pubsub),
  15. listenForUpdatesFromDocumentUpdater(io) {
  16. logger.debug(
  17. { rclients: this.rclientList.length },
  18. 'listening for applied-ops events'
  19. )
  20. for (const rclient of this.rclientList) {
  21. rclient.subscribe('applied-ops')
  22. rclient.on('message', function (channel, message) {
  23. metrics.inc('rclient', 0.001) // global event rate metric
  24. if (settings.debugEvents > 0) {
  25. EventLogger.debugEvent(channel, message)
  26. }
  27. DocumentUpdaterController._processMessageFromDocumentUpdater(
  28. io,
  29. channel,
  30. message
  31. )
  32. })
  33. }
  34. // create metrics for each redis instance only when we have multiple redis clients
  35. if (this.rclientList.length > 1) {
  36. this.rclientList.forEach((rclient, i) => {
  37. // per client event rate metric
  38. const metricName = `rclient-${i}`
  39. rclient.on('message', () => metrics.inc(metricName, 0.001))
  40. })
  41. }
  42. this.handleRoomUpdates(this.rclientList)
  43. },
  44. handleRoomUpdates(rclientSubList) {
  45. const roomEvents = RoomManager.eventSource()
  46. roomEvents.on('doc-active', function (docId) {
  47. const subscribePromises = rclientSubList.map(rclient =>
  48. ChannelManager.subscribe(rclient, 'applied-ops', docId)
  49. )
  50. RoomManager.emitOnCompletion(subscribePromises, `doc-subscribed-${docId}`)
  51. })
  52. roomEvents.on('doc-empty', docId =>
  53. rclientSubList.map(rclient =>
  54. ChannelManager.unsubscribe(rclient, 'applied-ops', docId)
  55. )
  56. )
  57. },
  58. _processMessageFromDocumentUpdater(io, channel, message) {
  59. SafeJsonParse.parse(message, function (error, message) {
  60. if (error) {
  61. logger.error({ err: error, channel }, 'error parsing JSON')
  62. return
  63. }
  64. if (message.op) {
  65. if (message._id && settings.checkEventOrder) {
  66. const status = EventLogger.checkEventOrder(
  67. 'applied-ops',
  68. message._id,
  69. message
  70. )
  71. if (status === 'duplicate') {
  72. return // skip duplicate events
  73. }
  74. }
  75. DocumentUpdaterController._applyUpdateFromDocumentUpdater(
  76. io,
  77. message.doc_id,
  78. message.op
  79. )
  80. } else if (message.error) {
  81. DocumentUpdaterController._processErrorFromDocumentUpdater(
  82. io,
  83. message.doc_id,
  84. message.error,
  85. message
  86. )
  87. } else if (message.health_check) {
  88. logger.debug(
  89. { message },
  90. 'got health check message in applied ops channel'
  91. )
  92. HealthCheckManager.check(channel, message.key)
  93. }
  94. })
  95. },
  96. _applyUpdateFromDocumentUpdater(io, docId, update) {
  97. let client
  98. const clientList = io.sockets.clients(docId)
  99. // avoid unnecessary work if no clients are connected
  100. if (clientList.length === 0) {
  101. return
  102. }
  103. // send updates to clients
  104. logger.debug(
  105. {
  106. docId,
  107. version: update.v,
  108. source: update.meta && update.meta.source,
  109. socketIoClients: clientList.map(client => client.id),
  110. },
  111. 'distributing updates to clients'
  112. )
  113. const seen = {}
  114. // send messages only to unique clients (due to duplicate entries in io.sockets.clients)
  115. for (client of clientList) {
  116. if (!seen[client.id]) {
  117. seen[client.id] = true
  118. if (client.publicId === update.meta.source) {
  119. logger.debug(
  120. {
  121. docId,
  122. version: update.v,
  123. source: update.meta.source,
  124. },
  125. 'distributing update to sender'
  126. )
  127. client.emit('otUpdateApplied', { v: update.v, doc: update.doc })
  128. } else if (!update.dup) {
  129. // Duplicate ops should just be sent back to sending client for acknowledgement
  130. logger.debug(
  131. {
  132. docId,
  133. version: update.v,
  134. source: update.meta.source,
  135. clientId: client.id,
  136. },
  137. 'distributing update to collaborator'
  138. )
  139. client.emit('otUpdateApplied', update)
  140. }
  141. }
  142. }
  143. if (Object.keys(seen).length < clientList.length) {
  144. metrics.inc('socket-io.duplicate-clients', 0.1)
  145. logger.debug(
  146. {
  147. docId,
  148. socketIoClients: clientList.map(client => client.id),
  149. },
  150. 'discarded duplicate clients'
  151. )
  152. }
  153. },
  154. _processErrorFromDocumentUpdater(io, docId, error, message) {
  155. for (const client of io.sockets.clients(docId)) {
  156. logger.warn(
  157. { err: error, docId, clientId: client.id },
  158. 'error from document updater, disconnecting client'
  159. )
  160. client.emit('otUpdateError', error, message)
  161. client.disconnect()
  162. }
  163. },
  164. }