sync_group_subscription_memberships.mjs 8.1 KB

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