AnalyticsManager.js 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  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 crypto = require('crypto')
  7. const _ = require('lodash')
  8. const { expressify } = require('@overleaf/promise-utils')
  9. const logger = require('@overleaf/logger')
  10. const analyticsEventsQueue = Queues.getQueue('analytics-events')
  11. const analyticsEditingSessionsQueue = Queues.getQueue(
  12. 'analytics-editing-sessions'
  13. )
  14. const analyticsUserPropertiesQueue = Queues.getQueue(
  15. 'analytics-user-properties'
  16. )
  17. const ONE_MINUTE_MS = 60 * 1000
  18. const UUID_REGEXP = /^[\w]{8}(-[\w]{4}){3}-[\w]{12}$/
  19. function identifyUser(userId, analyticsId, isNewUser) {
  20. if (!userId || !analyticsId || !analyticsId.toString().match(UUID_REGEXP)) {
  21. return
  22. }
  23. if (_isAnalyticsDisabled() || _isSmokeTestUser(userId)) {
  24. return
  25. }
  26. Metrics.analyticsQueue.inc({ status: 'adding', event_type: 'identify' })
  27. Queues.createScheduledJob(
  28. 'analytics-events',
  29. {
  30. name: 'identify',
  31. data: { userId, analyticsId, isNewUser, createdAt: new Date() },
  32. },
  33. ONE_MINUTE_MS
  34. )
  35. .then(() => {
  36. Metrics.analyticsQueue.inc({ status: 'added', event_type: 'identify' })
  37. })
  38. .catch(() => {
  39. Metrics.analyticsQueue.inc({ status: 'error', event_type: 'identify' })
  40. })
  41. }
  42. async function recordEventForUser(userId, event, segmentation) {
  43. if (!userId) {
  44. return
  45. }
  46. if (_isAnalyticsDisabled() || _isSmokeTestUser(userId)) {
  47. return
  48. }
  49. const analyticsId = await UserAnalyticsIdCache.get(userId)
  50. if (analyticsId) {
  51. _recordEvent({ analyticsId, userId, event, segmentation, isLoggedIn: true })
  52. }
  53. }
  54. function recordEventForSession(session, event, segmentation) {
  55. const { analyticsId, userId } = getIdsFromSession(session)
  56. if (!analyticsId) {
  57. return
  58. }
  59. if (_isAnalyticsDisabled() || _isSmokeTestUser(userId)) {
  60. return
  61. }
  62. _recordEvent({
  63. analyticsId,
  64. userId,
  65. event,
  66. segmentation,
  67. isLoggedIn: !!userId,
  68. createdAt: new Date(),
  69. })
  70. }
  71. async function setUserPropertyForUser(userId, propertyName, propertyValue) {
  72. if (_isAnalyticsDisabled() || _isSmokeTestUser(userId)) {
  73. return
  74. }
  75. _checkPropertyValue(propertyValue)
  76. const analyticsId = await UserAnalyticsIdCache.get(userId)
  77. if (analyticsId) {
  78. await _setUserProperty({ analyticsId, propertyName, propertyValue })
  79. }
  80. }
  81. async function setUserPropertyForAnalyticsId(
  82. analyticsId,
  83. propertyName,
  84. propertyValue
  85. ) {
  86. if (_isAnalyticsDisabled()) {
  87. return
  88. }
  89. _checkPropertyValue(propertyValue)
  90. await _setUserProperty({ analyticsId, propertyName, propertyValue })
  91. }
  92. async function setUserPropertyForSession(session, propertyName, propertyValue) {
  93. const { analyticsId, userId } = getIdsFromSession(session)
  94. if (_isAnalyticsDisabled() || _isSmokeTestUser(userId)) {
  95. return
  96. }
  97. _checkPropertyValue(propertyValue)
  98. if (analyticsId) {
  99. await _setUserProperty({ analyticsId, propertyName, propertyValue })
  100. }
  101. }
  102. function updateEditingSession(userId, projectId, countryCode, segmentation) {
  103. if (!userId) {
  104. return
  105. }
  106. if (_isAnalyticsDisabled() || _isSmokeTestUser(userId)) {
  107. return
  108. }
  109. if (!_isSegmentationValid(segmentation)) {
  110. logger.info(
  111. { userId, projectId, segmentation },
  112. 'rejecting analytics editing session due to bad segmentation'
  113. )
  114. return
  115. }
  116. Metrics.analyticsQueue.inc({
  117. status: 'adding',
  118. event_type: 'editing-session',
  119. })
  120. analyticsEditingSessionsQueue
  121. .add('editing-session', {
  122. userId,
  123. projectId,
  124. countryCode,
  125. segmentation,
  126. createdAt: new Date(),
  127. })
  128. .then(() => {
  129. Metrics.analyticsQueue.inc({
  130. status: 'added',
  131. event_type: 'editing-session',
  132. })
  133. })
  134. .catch(() => {
  135. Metrics.analyticsQueue.inc({
  136. status: 'error',
  137. event_type: 'editing-session',
  138. })
  139. })
  140. }
  141. function _recordEvent(
  142. { analyticsId, userId, event, segmentation, isLoggedIn },
  143. { delay } = {}
  144. ) {
  145. if (!_isAttributeValid(event)) {
  146. logger.info(
  147. { analyticsId, event, segmentation },
  148. 'rejecting analytics event due to bad event name'
  149. )
  150. return
  151. }
  152. if (!_isSegmentationValid(segmentation)) {
  153. logger.info(
  154. { analyticsId, event, segmentation },
  155. 'rejecting analytics event due to bad segmentation'
  156. )
  157. return
  158. }
  159. logger.debug(
  160. {
  161. analyticsId,
  162. userId,
  163. event,
  164. segmentation,
  165. isLoggedIn: !!userId,
  166. createdAt: new Date(),
  167. },
  168. 'queueing analytics event'
  169. )
  170. Metrics.analyticsQueue.inc({ status: 'adding', event_type: 'event' })
  171. analyticsEventsQueue
  172. .add(
  173. 'event',
  174. {
  175. analyticsId,
  176. userId,
  177. event,
  178. segmentation,
  179. isLoggedIn,
  180. createdAt: new Date(),
  181. },
  182. { delay }
  183. )
  184. .then(() => {
  185. Metrics.analyticsQueue.inc({ status: 'added', event_type: 'event' })
  186. })
  187. .catch(() => {
  188. Metrics.analyticsQueue.inc({ status: 'error', event_type: 'event' })
  189. })
  190. }
  191. async function _setUserProperty({ analyticsId, propertyName, propertyValue }) {
  192. if (!_isAttributeValid(propertyName)) {
  193. logger.info(
  194. { analyticsId, propertyName, propertyValue },
  195. 'rejecting analytics user property due to bad name'
  196. )
  197. return
  198. }
  199. if (!_isAttributeValueValid(propertyValue)) {
  200. logger.info(
  201. { analyticsId, propertyName, propertyValue },
  202. 'rejecting analytics user property due to bad value'
  203. )
  204. return
  205. }
  206. Metrics.analyticsQueue.inc({
  207. status: 'adding',
  208. event_type: 'user-property',
  209. })
  210. await analyticsUserPropertiesQueue
  211. .add('user-property', {
  212. analyticsId,
  213. propertyName,
  214. propertyValue,
  215. createdAt: new Date(),
  216. })
  217. .then(() => {
  218. Metrics.analyticsQueue.inc({
  219. status: 'added',
  220. event_type: 'user-property',
  221. })
  222. })
  223. .catch(() => {
  224. Metrics.analyticsQueue.inc({
  225. status: 'error',
  226. event_type: 'user-property',
  227. })
  228. })
  229. }
  230. function _isSmokeTestUser(userId) {
  231. const smokeTestUserId = Settings.smokeTest && Settings.smokeTest.userId
  232. return (
  233. smokeTestUserId != null &&
  234. userId != null &&
  235. userId.toString() === smokeTestUserId
  236. )
  237. }
  238. function _isAnalyticsDisabled() {
  239. return !(Settings.analytics && Settings.analytics.enabled)
  240. }
  241. function _checkPropertyValue(propertyValue) {
  242. if (propertyValue === undefined) {
  243. throw new Error(
  244. 'propertyValue cannot be undefined, use null to unset a property'
  245. )
  246. }
  247. }
  248. function _isAttributeValid(attribute) {
  249. return !attribute || /^[a-zA-Z0-9-_.:;,/]+$/.test(attribute)
  250. }
  251. function _isAttributeValueValid(attributeValue) {
  252. return _isAttributeValid(attributeValue) || attributeValue instanceof Date
  253. }
  254. function _isSegmentationValueValid(attributeValue) {
  255. // spaces and %-escaped values are allowed for segmentation values
  256. return !attributeValue || /^[a-zA-Z0-9-_.:;,/ %]+$/.test(attributeValue)
  257. }
  258. function _isSegmentationValid(segmentation) {
  259. if (!segmentation) {
  260. return true
  261. }
  262. const hasAnyInvalidKey = [...Object.keys(segmentation)].some(
  263. key => !_isAttributeValid(key)
  264. )
  265. const hasAnyInvalidValue = [...Object.values(segmentation)].some(
  266. value => !_isSegmentationValueValid(value)
  267. )
  268. return !hasAnyInvalidKey && !hasAnyInvalidValue
  269. }
  270. function getIdsFromSession(session) {
  271. const analyticsId = _.get(session, ['analyticsId'])
  272. const userId = SessionManager.getLoggedInUserId(session)
  273. return { analyticsId, userId }
  274. }
  275. async function analyticsIdMiddleware(req, res, next) {
  276. const session = req.session
  277. const sessionUser = SessionManager.getSessionUser(session)
  278. if (sessionUser) {
  279. session.analyticsId = await UserAnalyticsIdCache.get(sessionUser._id)
  280. } else if (!session.analyticsId) {
  281. // generate an `analyticsId` if needed
  282. session.analyticsId = crypto.randomUUID()
  283. }
  284. next()
  285. }
  286. module.exports = {
  287. identifyUser,
  288. recordEventForSession,
  289. recordEventForUser,
  290. setUserPropertyForUser,
  291. setUserPropertyForSession,
  292. setUserPropertyForAnalyticsId,
  293. updateEditingSession,
  294. getIdsFromSession,
  295. analyticsIdMiddleware: expressify(analyticsIdMiddleware),
  296. }