sync_group_subscription_memberships.mjs 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  1. import GoogleBigQueryHelper from './helpers/GoogleBigQueryHelper.mjs'
  2. import { Subscription } from '../../app/src/models/Subscription.js'
  3. import { waitForDb } from '../../app/src/infrastructure/mongodb.js'
  4. import AnalyticsManager from '../../app/src/Features/Analytics/AnalyticsManager.js'
  5. import { DeletedSubscription } from '../../app/src/models/DeletedSubscription.js'
  6. import minimist from 'minimist'
  7. import _ from 'lodash'
  8. import mongodb from 'mongodb-legacy'
  9. const { ObjectId } = mongodb
  10. let FETCH_LIMIT, COMMIT, VERBOSE
  11. async function main() {
  12. await waitForDb()
  13. console.log('## Syncing group subscription memberships...')
  14. const subscriptionsCount = await Subscription.countDocuments({
  15. groupPlan: true,
  16. })
  17. const deletedSubscriptionsCount = await DeletedSubscription.countDocuments({
  18. 'subscription.groupPlan': true,
  19. })
  20. console.log(
  21. `## Going to synchronize ${subscriptionsCount} subscriptions and ${deletedSubscriptionsCount} deleted subscriptions`
  22. )
  23. await checkActiveSubscriptions()
  24. await checkDeletedSubscriptions()
  25. }
  26. async function checkActiveSubscriptions() {
  27. let totalSubscriptionsChecked = 0
  28. let subscriptions
  29. const processedSubscriptionIds = new Set()
  30. do {
  31. subscriptions = await Subscription.find(
  32. { groupPlan: true },
  33. { recurlySubscription_id: 1, member_ids: 1 }
  34. )
  35. .sort('_id')
  36. .skip(totalSubscriptionsChecked)
  37. .limit(FETCH_LIMIT)
  38. .lean()
  39. if (subscriptions.length) {
  40. const groupIds = subscriptions.map(sub => sub._id)
  41. const bigQueryGroupMemberships =
  42. await fetchBigQueryMembershipStatuses(groupIds)
  43. const membershipsByGroupId = _.groupBy(
  44. bigQueryGroupMemberships,
  45. 'group_id'
  46. )
  47. for (const subscription of subscriptions) {
  48. const subscriptionId = subscription._id.toString()
  49. if (!processedSubscriptionIds.has(subscriptionId)) {
  50. await checkSubscriptionMemberships(
  51. subscription,
  52. membershipsByGroupId[subscriptionId] || []
  53. )
  54. processedSubscriptionIds.add(subscriptionId)
  55. }
  56. }
  57. totalSubscriptionsChecked += subscriptions.length
  58. }
  59. } while (subscriptions.length > 0)
  60. }
  61. async function checkDeletedSubscriptions() {
  62. let totalDeletedSubscriptionsChecked = 0
  63. let deletedSubscriptions
  64. const processedSubscriptionIds = new Set()
  65. do {
  66. deletedSubscriptions = (
  67. await DeletedSubscription.find(
  68. { 'subscription.groupPlan': true },
  69. { subscription: 1 }
  70. )
  71. .sort('deletedAt')
  72. .skip(totalDeletedSubscriptionsChecked)
  73. .limit(FETCH_LIMIT)
  74. ).map(sub => sub.toObject().subscription)
  75. if (deletedSubscriptions.length) {
  76. const groupIds = deletedSubscriptions.map(sub => sub._id.toString())
  77. const bigQueryGroupMemberships =
  78. await fetchBigQueryMembershipStatuses(groupIds)
  79. const membershipsByGroupId = _.groupBy(
  80. bigQueryGroupMemberships,
  81. 'group_id'
  82. )
  83. for (const deletedSubscription of deletedSubscriptions) {
  84. const subscriptionId = deletedSubscription._id.toString()
  85. if (!processedSubscriptionIds.has(subscriptionId)) {
  86. await checkDeletedSubscriptionMemberships(
  87. deletedSubscription,
  88. membershipsByGroupId[subscriptionId] || []
  89. )
  90. processedSubscriptionIds.add(subscriptionId)
  91. }
  92. }
  93. totalDeletedSubscriptionsChecked += deletedSubscriptions.length
  94. }
  95. } while (deletedSubscriptions.length > 0)
  96. }
  97. async function checkSubscriptionMemberships(subscription, membershipStatuses) {
  98. if (VERBOSE) {
  99. console.log(
  100. '\n###########################################################################################',
  101. '\n# Subscription (mongo): ',
  102. '\n# _id: \t\t\t\t',
  103. subscription._id.toString(),
  104. '\n# member_ids: \t\t\t',
  105. subscription.member_ids.map(_id => _id.toString()),
  106. '\n# recurlySubscription_id: \t',
  107. subscription.recurlySubscription_id
  108. )
  109. console.log('#\n# Membership statuses found in BigQuery: ')
  110. console.table(membershipStatuses)
  111. }
  112. // create missing `joined` events when membership status is missing
  113. for (const memberId of subscription.member_ids) {
  114. if (
  115. !_.find(membershipStatuses, {
  116. user_id: memberId.toString(),
  117. is_member: true,
  118. })
  119. ) {
  120. await sendCorrectiveEvent(
  121. memberId,
  122. 'group-subscription-joined',
  123. subscription
  124. )
  125. }
  126. }
  127. // create missing `left` events if user is not a member of the group anymore
  128. for (const { user_id: userId, is_member: isMember } of membershipStatuses) {
  129. if (
  130. isMember &&
  131. !subscription.member_ids.some(id => id.toString() === userId)
  132. ) {
  133. await sendCorrectiveEvent(userId, 'group-subscription-left', subscription)
  134. }
  135. }
  136. }
  137. async function checkDeletedSubscriptionMemberships(
  138. subscription,
  139. membershipStatuses
  140. ) {
  141. if (VERBOSE) {
  142. console.log(
  143. '\n###########################################################################################',
  144. '\n# Deleted subscription (mongo): ',
  145. '\n# _id: \t\t\t\t',
  146. subscription._id.toString(),
  147. '\n# member_ids: \t\t\t',
  148. subscription.member_ids.map(_id => _id.toString()),
  149. '\n# recurlySubscription_id: \t',
  150. subscription.recurlySubscription_id
  151. )
  152. console.log('#\n# Membership statuses found in BigQuery: ')
  153. console.table(membershipStatuses)
  154. }
  155. const updatedUserIds = new Set()
  156. // create missing `left` events if user was a member of the group in BQ and status is not up-to-date
  157. for (const memberId of subscription.member_ids.map(id => id.toString())) {
  158. if (
  159. _.find(membershipStatuses, {
  160. user_id: memberId,
  161. is_member: true,
  162. })
  163. ) {
  164. await sendCorrectiveEvent(
  165. memberId,
  166. 'group-subscription-left',
  167. subscription
  168. )
  169. updatedUserIds.add(memberId)
  170. }
  171. }
  172. // for cases where the user has been removed from the subscription before it was deleted and status is not up-to-date
  173. for (const { user_id: userId, is_member: isMember } of membershipStatuses) {
  174. if (isMember && !updatedUserIds.has(userId)) {
  175. await sendCorrectiveEvent(userId, 'group-subscription-left', subscription)
  176. updatedUserIds.add(userId)
  177. }
  178. }
  179. }
  180. async function sendCorrectiveEvent(userId, event, subscription) {
  181. if (!ObjectId.isValid(userId)) {
  182. console.warn(`Skipping '${event}' for user ${userId}: invalid user ID`)
  183. return
  184. }
  185. const segmentation = {
  186. groupId: subscription._id.toString(),
  187. subscriptionId: subscription.recurlySubscription_id,
  188. source: 'sync',
  189. }
  190. if (COMMIT) {
  191. console.log(
  192. `Sending event '${event}' for user ${userId} with segmentation: ${JSON.stringify(
  193. segmentation
  194. )}`
  195. )
  196. await AnalyticsManager.recordEventForUser(userId, event, segmentation)
  197. } else {
  198. console.log(
  199. `Dry run - would send event '${event}' for user ${userId} with segmentation: ${JSON.stringify(
  200. segmentation
  201. )}`
  202. )
  203. }
  204. }
  205. async function fetchBigQueryMembershipStatuses(groupIds) {
  206. const joinedGroupIds = groupIds.map(id => `"${id}"`).join(',')
  207. const query = `\
  208. WITH user_memberships AS (
  209. SELECT
  210. group_id,
  211. COALESCE(user_aliases.user_id, ugm.user_id) AS user_id,
  212. is_member,
  213. ugm.created_at
  214. FROM analytics.user_group_memberships ugm
  215. LEFT JOIN analytics.user_aliases ON ugm.user_id = user_aliases.analytics_id
  216. WHERE ugm.group_id IN (${joinedGroupIds})
  217. ),
  218. ordered_status AS (
  219. SELECT *,
  220. ROW_NUMBER() OVER(PARTITION BY group_id, user_id ORDER BY created_at DESC) AS row_number
  221. FROM user_memberships
  222. )
  223. SELECT group_id, user_id, is_member, created_at FROM ordered_status
  224. WHERE row_number = 1;
  225. `
  226. return GoogleBigQueryHelper.query(query)
  227. }
  228. const setup = () => {
  229. const argv = minimist(process.argv.slice(2))
  230. FETCH_LIMIT = argv.fetch ? argv.fetch : 100
  231. COMMIT = argv.commit !== undefined
  232. VERBOSE = argv.debug !== undefined
  233. if (!COMMIT) {
  234. console.warn('Doing dry run without --commit')
  235. }
  236. if (VERBOSE) {
  237. console.log('Running in verbose mode')
  238. }
  239. }
  240. setup()
  241. try {
  242. await main()
  243. console.error('Done.')
  244. process.exit(0)
  245. } catch (error) {
  246. console.error({ error })
  247. process.exit(1)
  248. }