AnalyticsManager.js 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  1. const SessionManager = require('../Authentication/SessionManager')
  2. const UserAnalyticsIdCache = require('./UserAnalyticsIdCache')
  3. const Settings = require('@overleaf/settings')
  4. const Metrics = require('../../infrastructure/Metrics')
  5. const Queues = require('../../infrastructure/Queues')
  6. const uuid = require('uuid')
  7. const _ = require('lodash')
  8. const { expressify } = require('../../util/promises')
  9. const { logger } = require('logger-sharelatex')
  10. const analyticsEventsQueue = Queues.getAnalyticsEventsQueue()
  11. const analyticsEditingSessionsQueue = Queues.getAnalyticsEditingSessionsQueue()
  12. const analyticsUserPropertiesQueue = Queues.getAnalyticsUserPropertiesQueue()
  13. const ONE_MINUTE_MS = 60 * 1000
  14. function identifyUser(userId, analyticsId, isNewUser) {
  15. if (!userId || !analyticsId || userId.toString() === analyticsId.toString()) {
  16. return
  17. }
  18. if (_isAnalyticsDisabled() || _isSmokeTestUser(userId)) {
  19. return
  20. }
  21. Metrics.analyticsQueue.inc({ status: 'adding', event_type: 'identify' })
  22. analyticsEventsQueue
  23. .add(
  24. 'identify',
  25. { userId, analyticsId, isNewUser, createdAt: new Date() },
  26. { delay: ONE_MINUTE_MS }
  27. )
  28. .then(() => {
  29. Metrics.analyticsQueue.inc({ status: 'added', event_type: 'identify' })
  30. })
  31. .catch(() => {
  32. Metrics.analyticsQueue.inc({ status: 'error', event_type: 'identify' })
  33. })
  34. }
  35. async function recordEventForUser(userId, event, segmentation) {
  36. if (!userId) {
  37. return
  38. }
  39. if (_isAnalyticsDisabled() || _isSmokeTestUser(userId)) {
  40. return
  41. }
  42. const analyticsId = await UserAnalyticsIdCache.get(userId)
  43. if (analyticsId) {
  44. _recordEvent({ analyticsId, userId, event, segmentation, isLoggedIn: true })
  45. }
  46. }
  47. function recordEventForSession(session, event, segmentation) {
  48. const { analyticsId, userId } = getIdsFromSession(session)
  49. if (!analyticsId) {
  50. return
  51. }
  52. if (_isAnalyticsDisabled() || _isSmokeTestUser(userId)) {
  53. return
  54. }
  55. logger.info({
  56. analyticsId,
  57. userId,
  58. event,
  59. segmentation,
  60. isLoggedIn: !!userId,
  61. createdAt: new Date(),
  62. })
  63. _recordEvent({
  64. analyticsId,
  65. userId,
  66. event,
  67. segmentation,
  68. isLoggedIn: !!userId,
  69. createdAt: new Date(),
  70. })
  71. }
  72. async function setUserPropertyForUser(userId, propertyName, propertyValue) {
  73. if (_isAnalyticsDisabled() || _isSmokeTestUser(userId)) {
  74. return
  75. }
  76. _checkPropertyValue(propertyValue)
  77. const analyticsId = await UserAnalyticsIdCache.get(userId)
  78. if (analyticsId) {
  79. _setUserProperty({ analyticsId, propertyName, propertyValue })
  80. }
  81. }
  82. async function setUserPropertyForAnalyticsId(
  83. analyticsId,
  84. propertyName,
  85. propertyValue
  86. ) {
  87. if (_isAnalyticsDisabled()) {
  88. return
  89. }
  90. _checkPropertyValue(propertyValue)
  91. _setUserProperty({ analyticsId, propertyName, propertyValue })
  92. }
  93. async function setUserPropertyForSession(session, propertyName, propertyValue) {
  94. const { analyticsId, userId } = getIdsFromSession(session)
  95. if (_isAnalyticsDisabled() || _isSmokeTestUser(userId)) {
  96. return
  97. }
  98. _checkPropertyValue(propertyValue)
  99. if (analyticsId) {
  100. _setUserProperty({ analyticsId, propertyName, propertyValue })
  101. }
  102. }
  103. function updateEditingSession(userId, projectId, countryCode) {
  104. if (!userId) {
  105. return
  106. }
  107. if (_isAnalyticsDisabled() || _isSmokeTestUser(userId)) {
  108. return
  109. }
  110. Metrics.analyticsQueue.inc({
  111. status: 'adding',
  112. event_type: 'editing-session',
  113. })
  114. analyticsEditingSessionsQueue
  115. .add('editing-session', {
  116. userId,
  117. projectId,
  118. countryCode,
  119. createdAt: new Date(),
  120. })
  121. .then(() => {
  122. Metrics.analyticsQueue.inc({
  123. status: 'added',
  124. event_type: 'editing-session',
  125. })
  126. })
  127. .catch(() => {
  128. Metrics.analyticsQueue.inc({
  129. status: 'error',
  130. event_type: 'editing-session',
  131. })
  132. })
  133. }
  134. function _recordEvent(
  135. { analyticsId, userId, event, segmentation, isLoggedIn },
  136. { delay } = {}
  137. ) {
  138. Metrics.analyticsQueue.inc({ status: 'adding', event_type: 'event' })
  139. analyticsEventsQueue
  140. .add(
  141. 'event',
  142. {
  143. analyticsId,
  144. userId,
  145. event,
  146. segmentation,
  147. isLoggedIn,
  148. createdAt: new Date(),
  149. },
  150. { delay }
  151. )
  152. .then(() => {
  153. Metrics.analyticsQueue.inc({ status: 'added', event_type: 'event' })
  154. })
  155. .catch(() => {
  156. Metrics.analyticsQueue.inc({ status: 'error', event_type: 'event' })
  157. })
  158. }
  159. function _setUserProperty({ analyticsId, propertyName, propertyValue }) {
  160. Metrics.analyticsQueue.inc({
  161. status: 'adding',
  162. event_type: 'user-property',
  163. })
  164. analyticsUserPropertiesQueue
  165. .add('user-property', {
  166. analyticsId,
  167. propertyName,
  168. propertyValue,
  169. createdAt: new Date(),
  170. })
  171. .then(() => {
  172. Metrics.analyticsQueue.inc({
  173. status: 'added',
  174. event_type: 'user-property',
  175. })
  176. })
  177. .catch(() => {
  178. Metrics.analyticsQueue.inc({
  179. status: 'error',
  180. event_type: 'user-property',
  181. })
  182. })
  183. }
  184. function _isSmokeTestUser(userId) {
  185. const smokeTestUserId = Settings.smokeTest && Settings.smokeTest.userId
  186. return (
  187. smokeTestUserId != null &&
  188. userId != null &&
  189. userId.toString() === smokeTestUserId
  190. )
  191. }
  192. function _isAnalyticsDisabled() {
  193. return !(Settings.analytics && Settings.analytics.enabled)
  194. }
  195. function _checkPropertyValue(propertyValue) {
  196. if (propertyValue === undefined) {
  197. throw new Error(
  198. 'propertyValue cannot be undefined, use null to unset a property'
  199. )
  200. }
  201. }
  202. function getIdsFromSession(session) {
  203. const analyticsId = _.get(session, ['analyticsId'])
  204. const userId = SessionManager.getLoggedInUserId(session)
  205. return { analyticsId, userId }
  206. }
  207. async function analyticsIdMiddleware(req, res, next) {
  208. const session = req.session
  209. const sessionUser = SessionManager.getSessionUser(session)
  210. if (sessionUser) {
  211. // ensure `session.analyticsId` is set to the user's `analyticsId`, and fallback to their `userId` for pre-analyticsId users
  212. session.analyticsId = sessionUser.analyticsId || sessionUser.userId
  213. } else if (!session.analyticsId) {
  214. // generate an `analyticsId` if needed
  215. session.analyticsId = uuid.v4()
  216. }
  217. next()
  218. }
  219. module.exports = {
  220. identifyUser,
  221. recordEventForSession,
  222. recordEventForUser,
  223. setUserPropertyForUser,
  224. setUserPropertyForSession,
  225. setUserPropertyForAnalyticsId,
  226. updateEditingSession,
  227. getIdsFromSession,
  228. analyticsIdMiddleware: expressify(analyticsIdMiddleware),
  229. }