DocumentUpdaterController.js 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  1. /* eslint-disable
  2. camelcase,
  3. no-unused-vars,
  4. */
  5. // TODO: This file was created by bulk-decaffeinate.
  6. // Fix any style issues and re-enable lint.
  7. /*
  8. * decaffeinate suggestions:
  9. * DS101: Remove unnecessary use of Array.from
  10. * DS102: Remove unnecessary code created because of implicit returns
  11. * DS205: Consider reworking code to avoid use of IIFEs
  12. * DS207: Consider shorter variations of null checks
  13. * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
  14. */
  15. let DocumentUpdaterController
  16. const logger = require('logger-sharelatex')
  17. const settings = require('settings-sharelatex')
  18. const RedisClientManager = require('./RedisClientManager')
  19. const SafeJsonParse = require('./SafeJsonParse')
  20. const EventLogger = require('./EventLogger')
  21. const HealthCheckManager = require('./HealthCheckManager')
  22. const RoomManager = require('./RoomManager')
  23. const ChannelManager = require('./ChannelManager')
  24. const metrics = require('metrics-sharelatex')
  25. const MESSAGE_SIZE_LOG_LIMIT = 1024 * 1024 // 1Mb
  26. module.exports = DocumentUpdaterController = {
  27. // DocumentUpdaterController is responsible for updates that come via Redis
  28. // Pub/Sub from the document updater.
  29. rclientList: RedisClientManager.createClientList(settings.redis.pubsub),
  30. listenForUpdatesFromDocumentUpdater(io) {
  31. let i, rclient
  32. logger.log(
  33. { rclients: this.rclientList.length },
  34. 'listening for applied-ops events'
  35. )
  36. for (i = 0; i < this.rclientList.length; i++) {
  37. rclient = this.rclientList[i]
  38. rclient.subscribe('applied-ops')
  39. rclient.on('message', function (channel, message) {
  40. metrics.inc('rclient', 0.001) // global event rate metric
  41. if (settings.debugEvents > 0) {
  42. EventLogger.debugEvent(channel, message)
  43. }
  44. return DocumentUpdaterController._processMessageFromDocumentUpdater(
  45. io,
  46. channel,
  47. message
  48. )
  49. })
  50. }
  51. // create metrics for each redis instance only when we have multiple redis clients
  52. if (this.rclientList.length > 1) {
  53. for (i = 0; i < this.rclientList.length; i++) {
  54. rclient = this.rclientList[i]
  55. ;((
  56. i // per client event rate metric
  57. ) => rclient.on('message', () => metrics.inc(`rclient-${i}`, 0.001)))(i)
  58. }
  59. }
  60. return this.handleRoomUpdates(this.rclientList)
  61. },
  62. handleRoomUpdates(rclientSubList) {
  63. const roomEvents = RoomManager.eventSource()
  64. roomEvents.on('doc-active', function (doc_id) {
  65. const subscribePromises = Array.from(rclientSubList).map((rclient) =>
  66. ChannelManager.subscribe(rclient, 'applied-ops', doc_id)
  67. )
  68. return RoomManager.emitOnCompletion(
  69. subscribePromises,
  70. `doc-subscribed-${doc_id}`
  71. )
  72. })
  73. return roomEvents.on('doc-empty', (doc_id) =>
  74. Array.from(rclientSubList).map((rclient) =>
  75. ChannelManager.unsubscribe(rclient, 'applied-ops', doc_id)
  76. )
  77. )
  78. },
  79. _processMessageFromDocumentUpdater(io, channel, message) {
  80. return SafeJsonParse.parse(message, function (error, message) {
  81. if (error != null) {
  82. logger.error({ err: error, channel }, 'error parsing JSON')
  83. return
  84. }
  85. if (message.op != null) {
  86. if (message._id != null && settings.checkEventOrder) {
  87. const status = EventLogger.checkEventOrder(
  88. 'applied-ops',
  89. message._id,
  90. message
  91. )
  92. if (status === 'duplicate') {
  93. return // skip duplicate events
  94. }
  95. }
  96. return DocumentUpdaterController._applyUpdateFromDocumentUpdater(
  97. io,
  98. message.doc_id,
  99. message.op
  100. )
  101. } else if (message.error != null) {
  102. return DocumentUpdaterController._processErrorFromDocumentUpdater(
  103. io,
  104. message.doc_id,
  105. message.error,
  106. message
  107. )
  108. } else if (message.health_check != null) {
  109. logger.debug(
  110. { message },
  111. 'got health check message in applied ops channel'
  112. )
  113. return HealthCheckManager.check(channel, message.key)
  114. }
  115. })
  116. },
  117. _applyUpdateFromDocumentUpdater(io, doc_id, update) {
  118. let client
  119. const clientList = io.sockets.clients(doc_id)
  120. // avoid unnecessary work if no clients are connected
  121. if (clientList.length === 0) {
  122. return
  123. }
  124. // send updates to clients
  125. logger.log(
  126. {
  127. doc_id,
  128. version: update.v,
  129. source: update.meta != null ? update.meta.source : undefined,
  130. socketIoClients: (() => {
  131. const result = []
  132. for (client of Array.from(clientList)) {
  133. result.push(client.id)
  134. }
  135. return result
  136. })()
  137. },
  138. 'distributing updates to clients'
  139. )
  140. const seen = {}
  141. // send messages only to unique clients (due to duplicate entries in io.sockets.clients)
  142. for (client of Array.from(clientList)) {
  143. if (!seen[client.id]) {
  144. seen[client.id] = true
  145. if (client.publicId === update.meta.source) {
  146. logger.log(
  147. {
  148. doc_id,
  149. version: update.v,
  150. source: update.meta != null ? update.meta.source : undefined
  151. },
  152. 'distributing update to sender'
  153. )
  154. client.emit('otUpdateApplied', { v: update.v, doc: update.doc })
  155. } else if (!update.dup) {
  156. // Duplicate ops should just be sent back to sending client for acknowledgement
  157. logger.log(
  158. {
  159. doc_id,
  160. version: update.v,
  161. source: update.meta != null ? update.meta.source : undefined,
  162. client_id: client.id
  163. },
  164. 'distributing update to collaborator'
  165. )
  166. client.emit('otUpdateApplied', update)
  167. }
  168. }
  169. }
  170. if (Object.keys(seen).length < clientList.length) {
  171. metrics.inc('socket-io.duplicate-clients', 0.1)
  172. return logger.log(
  173. {
  174. doc_id,
  175. socketIoClients: (() => {
  176. const result1 = []
  177. for (client of Array.from(clientList)) {
  178. result1.push(client.id)
  179. }
  180. return result1
  181. })()
  182. },
  183. 'discarded duplicate clients'
  184. )
  185. }
  186. },
  187. _processErrorFromDocumentUpdater(io, doc_id, error, message) {
  188. return (() => {
  189. const result = []
  190. for (const client of Array.from(io.sockets.clients(doc_id))) {
  191. logger.warn(
  192. { err: error, doc_id, client_id: client.id },
  193. 'error from document updater, disconnecting client'
  194. )
  195. client.emit('otUpdateError', error, message)
  196. result.push(client.disconnect())
  197. }
  198. return result
  199. })()
  200. }
  201. }