ConnectedUsersManager.js 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. const async = require('async')
  2. const Settings = require('@overleaf/settings')
  3. const logger = require('@overleaf/logger')
  4. const redis = require('@overleaf/redis-wrapper')
  5. const OError = require('@overleaf/o-error')
  6. const Metrics = require('@overleaf/metrics')
  7. const rclient = redis.createClient(Settings.redis.realtime)
  8. const Keys = Settings.redis.realtime.key_schema
  9. const ONE_HOUR_IN_S = 60 * 60
  10. const ONE_DAY_IN_S = ONE_HOUR_IN_S * 24
  11. const FOUR_DAYS_IN_S = ONE_DAY_IN_S * 4
  12. const USER_TIMEOUT_IN_S = ONE_HOUR_IN_S / 4
  13. const REFRESH_TIMEOUT_IN_S = 10 // only show clients which have responded to a refresh request in the last 10 seconds
  14. function recordProjectNotEmptySinceMetric(res, status) {
  15. const diff = Date.now() / 1000 - parseInt(res, 10)
  16. const BUCKETS = [
  17. 0,
  18. ONE_HOUR_IN_S,
  19. 2 * ONE_HOUR_IN_S,
  20. ONE_DAY_IN_S,
  21. 2 * ONE_DAY_IN_S,
  22. 7 * ONE_DAY_IN_S,
  23. 30 * ONE_DAY_IN_S,
  24. ]
  25. Metrics.histogram('project_not_empty_since', diff, BUCKETS, { status })
  26. }
  27. module.exports = {
  28. countConnectedClients(projectId, callback) {
  29. rclient.scard(Keys.clientsInProject({ project_id: projectId }), callback)
  30. },
  31. // Use the same method for when a user connects, and when a user sends a cursor
  32. // update. This way we don't care if the connected_user key has expired when
  33. // we receive a cursor update.
  34. updateUserPosition(projectId, clientId, user, cursorData, callback) {
  35. logger.debug({ projectId, clientId }, 'marking user as joined or connected')
  36. const multi = rclient.multi()
  37. multi.sadd(Keys.clientsInProject({ project_id: projectId }), clientId)
  38. multi.scard(Keys.clientsInProject({ project_id: projectId }))
  39. multi.expire(
  40. Keys.clientsInProject({ project_id: projectId }),
  41. FOUR_DAYS_IN_S
  42. )
  43. multi.hset(
  44. Keys.connectedUser({ project_id: projectId, client_id: clientId }),
  45. 'last_updated_at',
  46. Date.now()
  47. )
  48. multi.hset(
  49. Keys.connectedUser({ project_id: projectId, client_id: clientId }),
  50. 'user_id',
  51. user._id
  52. )
  53. multi.hset(
  54. Keys.connectedUser({ project_id: projectId, client_id: clientId }),
  55. 'first_name',
  56. user.first_name || ''
  57. )
  58. multi.hset(
  59. Keys.connectedUser({ project_id: projectId, client_id: clientId }),
  60. 'last_name',
  61. user.last_name || ''
  62. )
  63. multi.hset(
  64. Keys.connectedUser({ project_id: projectId, client_id: clientId }),
  65. 'email',
  66. user.email || ''
  67. )
  68. if (cursorData) {
  69. multi.hset(
  70. Keys.connectedUser({ project_id: projectId, client_id: clientId }),
  71. 'cursorData',
  72. JSON.stringify(cursorData)
  73. )
  74. }
  75. multi.expire(
  76. Keys.connectedUser({ project_id: projectId, client_id: clientId }),
  77. USER_TIMEOUT_IN_S
  78. )
  79. multi.exec(function (err, res) {
  80. if (err) {
  81. err = new OError('problem marking user as connected').withCause(err)
  82. }
  83. const [, nConnectedClients] = res
  84. Metrics.inc('editing_session_mode', 1, {
  85. method: cursorData ? 'update' : 'connect',
  86. status: nConnectedClients === 1 ? 'single' : 'multi',
  87. })
  88. callback(err)
  89. })
  90. },
  91. refreshClient(projectId, clientId) {
  92. logger.debug({ projectId, clientId }, 'refreshing connected client')
  93. const multi = rclient.multi()
  94. multi.hset(
  95. Keys.connectedUser({ project_id: projectId, client_id: clientId }),
  96. 'last_updated_at',
  97. Date.now()
  98. )
  99. multi.expire(
  100. Keys.connectedUser({ project_id: projectId, client_id: clientId }),
  101. USER_TIMEOUT_IN_S
  102. )
  103. multi.exec(function (err) {
  104. if (err) {
  105. logger.err(
  106. { err, projectId, clientId },
  107. 'problem refreshing connected client'
  108. )
  109. }
  110. })
  111. },
  112. markUserAsDisconnected(projectId, clientId, callback) {
  113. logger.debug({ projectId, clientId }, 'marking user as disconnected')
  114. const multi = rclient.multi()
  115. multi.srem(Keys.clientsInProject({ project_id: projectId }), clientId)
  116. multi.scard(Keys.clientsInProject({ project_id: projectId }))
  117. multi.expire(
  118. Keys.clientsInProject({ project_id: projectId }),
  119. FOUR_DAYS_IN_S
  120. )
  121. multi.del(
  122. Keys.connectedUser({ project_id: projectId, client_id: clientId })
  123. )
  124. multi.exec(function (err, res) {
  125. if (err) {
  126. err = new OError('problem marking user as disconnected').withCause(err)
  127. }
  128. const [, nConnectedClients] = res
  129. const status =
  130. nConnectedClients === 0
  131. ? 'empty'
  132. : nConnectedClients === 1
  133. ? 'single'
  134. : 'multi'
  135. Metrics.inc('editing_session_mode', 1, {
  136. method: 'disconnect',
  137. status,
  138. })
  139. if (status === 'empty') {
  140. rclient.getdel(Keys.projectNotEmptySince({ projectId }), (err, res) => {
  141. if (err) {
  142. logger.warn(
  143. { err, projectId },
  144. 'could not collect projectNotEmptySince'
  145. )
  146. } else if (res) {
  147. recordProjectNotEmptySinceMetric(res, status)
  148. }
  149. })
  150. } else {
  151. // Only populate projectNotEmptySince when more clients remain connected.
  152. const nowInSeconds = Math.ceil(Date.now() / 1000).toString()
  153. // We can go back to SET GET after upgrading to redis 7.0+
  154. const multi = rclient.multi()
  155. multi.get(Keys.projectNotEmptySince({ projectId }))
  156. multi.set(
  157. Keys.projectNotEmptySince({ projectId }),
  158. nowInSeconds,
  159. 'NX',
  160. 'EX',
  161. 31 * ONE_DAY_IN_S
  162. )
  163. multi.exec((err, res) => {
  164. if (err) {
  165. logger.warn(
  166. { err, projectId },
  167. 'could not get/set projectNotEmptySince'
  168. )
  169. } else if (res[0]) {
  170. recordProjectNotEmptySinceMetric(res[0], status)
  171. }
  172. })
  173. }
  174. callback(err)
  175. })
  176. },
  177. _getConnectedUser(projectId, clientId, callback) {
  178. rclient.hgetall(
  179. Keys.connectedUser({ project_id: projectId, client_id: clientId }),
  180. function (err, result) {
  181. if (err) {
  182. err = new OError('problem fetching connected user details', {
  183. other_client_id: clientId,
  184. }).withCause(err)
  185. return callback(err)
  186. }
  187. if (!(result && result.user_id)) {
  188. result = {
  189. connected: false,
  190. client_id: clientId,
  191. }
  192. } else {
  193. result.connected = true
  194. result.client_id = clientId
  195. result.client_age =
  196. (Date.now() - parseInt(result.last_updated_at, 10)) / 1000
  197. if (result.cursorData) {
  198. try {
  199. result.cursorData = JSON.parse(result.cursorData)
  200. } catch (e) {
  201. OError.tag(e, 'error parsing cursorData JSON', {
  202. other_client_id: clientId,
  203. cursorData: result.cursorData,
  204. })
  205. return callback(e)
  206. }
  207. }
  208. }
  209. callback(err, result)
  210. }
  211. )
  212. },
  213. getConnectedUsers(projectId, callback) {
  214. const self = this
  215. rclient.smembers(
  216. Keys.clientsInProject({ project_id: projectId }),
  217. function (err, results) {
  218. if (err) {
  219. err = new OError('problem getting clients in project').withCause(err)
  220. return callback(err)
  221. }
  222. const jobs = results.map(
  223. clientId => cb => self._getConnectedUser(projectId, clientId, cb)
  224. )
  225. async.series(jobs, function (err, users) {
  226. if (err) {
  227. OError.tag(err, 'problem getting connected users')
  228. return callback(err)
  229. }
  230. users = users.filter(
  231. user =>
  232. user && user.connected && user.client_age < REFRESH_TIMEOUT_IN_S
  233. )
  234. callback(null, users)
  235. })
  236. }
  237. )
  238. },
  239. }