-
Notifications
You must be signed in to change notification settings - Fork 731
chore: backfill email-domain member organization dates (CM-1107) #4064
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 14 commits
Commits
Show all changes
27 commits
Select commit
Hold shift + click to select a range
d997511
feat: infer memberOrganization stint dates from work-email activities
skwowet 057464d
fix: resolve pr comments from ai bots
skwowet 0af601c
fix: update redis member ID retrieval method and cleanup logic
skwowet 34354a5
Update services/apps/data_sink_worker/src/service/member.service.ts
skwowet f74aef1
fix: resolve pr comments from ai bots
skwowet 68a79fc
refactor: extract source rank logic into a separate func for clarity …
skwowet 9553e2c
refactor: streamline email domain extraction logic in ActivityService
skwowet e0a9860
chore: backfill email-domain member organization dates
skwowet 8a9f500
chore: enable debugger logs in prod
skwowet d7a18df
chore: add logging for member organization stint inference job start
skwowet 15bd7ec
fix: debugger and info logs
skwowet 8914f41
chore: remove unused constant and add TODO for applying stint changes…
skwowet 498f0c1
feat: apply overrides in member organization stint changes job
skwowet f834a6b
Merge branch 'improve/CM-1105' into script/CM-1107
skwowet 4fead74
fix: resolve pr review comments
skwowet 0f3d3a2
fix: redis key pruning script
skwowet 21e42bf
chore: rm redis key clean up script
skwowet 0adfab9
fix: lua script edge case
skwowet 0c51d12
Merge branch 'improve/CM-1105' into script/CM-1107
skwowet 086253c
fix: resolve pr review comments
skwowet bdce7d1
fix: set organization source to UI for manual edits in member organiz…
skwowet 3de432b
Merge branch 'improve/CM-1105' into script/CM-1107
skwowet c2f76de
Merge branch 'main' into improve/CM-1105
skwowet 4a4434a
Merge branch 'improve/CM-1105' into script/CM-1107
skwowet afc5734
chore: rm debugger env
skwowet 96e5871
Merge branch 'improve/CM-1105' into script/CM-1107
skwowet c9fac03
Merge branch 'main' into script/CM-1107
skwowet File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
156 changes: 156 additions & 0 deletions
156
backend/src/bin/scripts/backfill-email-domain-member-organization-dates.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,156 @@ | ||
| import commandLineArgs from 'command-line-args' | ||
|
|
||
| import { inferMemberOrganizationStintChanges } from '@crowd/common_services' | ||
| import { | ||
| createMemberOrganization, | ||
| fetchEmailDomainMemberOrganizationActivityDates, | ||
| fetchEmailDomainMemberOrganizationsWithoutDates, | ||
| fetchMemberOrganizationsBySource, | ||
| pgpQx, | ||
| updateMemberOrganization, | ||
| } from '@crowd/data-access-layer' | ||
| import { getDbConnection } from '@crowd/data-access-layer/src/database' | ||
| import { chunkArray } from '@crowd/data-access-layer/src/old/apps/merge_suggestions_worker/utils' | ||
| import { getServiceLogger } from '@crowd/logging' | ||
| import { getRedisClient } from '@crowd/redis' | ||
| import { OrganizationSource } from '@crowd/types' | ||
|
|
||
| import { DB_CONFIG, REDIS_CONFIG } from '@/conf' | ||
|
|
||
| const log = getServiceLogger() | ||
|
|
||
| const options = [ | ||
| { | ||
| name: 'testRun', | ||
| alias: 't', | ||
| type: Boolean, | ||
| description: 'Run in test mode (limit to 1 batch and 10 members).', | ||
| }, | ||
| { | ||
| name: 'afterMemberId', | ||
| alias: 'a', | ||
| type: String, | ||
| description: 'The member ID to start processing after.', | ||
| }, | ||
| { | ||
| name: 'batchSize', | ||
| alias: 'b', | ||
| type: Number, | ||
| description: 'The number of members to fetch in each batch.', | ||
| }, | ||
| { | ||
| name: 'help', | ||
| alias: 'h', | ||
| type: Boolean, | ||
| description: 'Print this usage guide.', | ||
| }, | ||
| ] | ||
|
|
||
| const parameters = commandLineArgs(options) | ||
|
|
||
| setImmediate(async () => { | ||
| const testRun = parameters.testRun ?? false | ||
| const BATCH_SIZE = parameters.batchSize ?? (testRun ? 10 : 500) | ||
| let afterMemberId = parameters.afterMemberId ?? undefined | ||
|
|
||
| const db = await getDbConnection({ | ||
| host: DB_CONFIG.writeHost, | ||
| port: DB_CONFIG.port, | ||
| database: DB_CONFIG.database, | ||
| user: DB_CONFIG.username, | ||
| password: DB_CONFIG.password, | ||
| }) | ||
|
|
||
| const qx = pgpQx(db) | ||
| const redis = await getRedisClient(REDIS_CONFIG, true) | ||
|
|
||
| log.info({ testRun, BATCH_SIZE, afterMemberId }, 'Running script with the following parameters!') | ||
|
|
||
| let hasMore = true | ||
|
|
||
| while (hasMore) { | ||
| const memberIds = await fetchEmailDomainMemberOrganizationsWithoutDates( | ||
| qx, | ||
| BATCH_SIZE, | ||
| afterMemberId, | ||
| ) | ||
|
|
||
| if (memberIds.length > 0) { | ||
| for (const chunk of chunkArray(memberIds, 50)) { | ||
| await Promise.all( | ||
| chunk.map(async (memberId) => { | ||
| if (testRun) { | ||
| log.info({ memberId }, 'Processing member!') | ||
| } | ||
|
|
||
| try { | ||
| const [existingMemberOrganizations, activityDates] = await Promise.all([ | ||
| fetchMemberOrganizationsBySource(qx, memberId, OrganizationSource.EMAIL_DOMAIN), | ||
| fetchEmailDomainMemberOrganizationActivityDates(qx, memberId), | ||
| ]) | ||
|
|
||
| const changes = inferMemberOrganizationStintChanges( | ||
| memberId, | ||
| existingMemberOrganizations, | ||
| activityDates, | ||
| ) | ||
|
|
||
| if (testRun) { | ||
| log.info( | ||
| { existingMemberOrganizations, activityDates, changes }, | ||
| 'Previewing changes for member.', | ||
| ) | ||
| } | ||
|
|
||
| if (changes.length > 0) { | ||
| await qx.tx(async (tx) => { | ||
| for (const change of changes) { | ||
| if (change.type === 'insert') { | ||
| await createMemberOrganization(tx, memberId, { | ||
| organizationId: change.organizationId, | ||
| dateStart: change.dateStart, | ||
| dateEnd: change.dateEnd, | ||
| source: OrganizationSource.EMAIL_DOMAIN, | ||
| }) | ||
| } else if (change.type === 'update') { | ||
| await updateMemberOrganization(tx, memberId, change.id, { | ||
| dateStart: change.dateStart, | ||
| dateEnd: change.dateEnd, | ||
| }) | ||
| } | ||
|
|
||
| if (testRun) { | ||
| log.info( | ||
| { memberId, orgId: change.organizationId, type: change.type }, | ||
| 'Member organization updated.', | ||
| ) | ||
| } | ||
| } | ||
| }) | ||
| await redis.sAdd('recalculate-member-affiliations', [memberId]) | ||
| } else if (testRun) { | ||
| log.info({ memberId }, 'No changes found for member!') | ||
| } | ||
| } catch (err) { | ||
| log.error({ memberId, err }, 'Failed to process for member!') | ||
| throw err | ||
| } | ||
| }), | ||
| ) | ||
| } | ||
|
|
||
| const lastMemberId = memberIds[memberIds.length - 1] | ||
| afterMemberId = lastMemberId | ||
|
|
||
| log.info({ lastMemberId, count: memberIds.length }, 'Batch processed!') | ||
|
|
||
| if (testRun || memberIds.length < BATCH_SIZE) { | ||
| hasMore = false | ||
| } | ||
| } else { | ||
| hasMore = false | ||
| } | ||
| } | ||
|
|
||
| process.exit(0) | ||
| }) | ||
3 changes: 3 additions & 0 deletions
3
.../src/database/migrations/V1776931245__member-organizations-email-domain-partial-index.sql
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,3 @@ | ||
| CREATE INDEX CONCURRENTLY IF NOT EXISTS "ix_memberOrganizations_memberId_emailDomain" | ||
| ON "memberOrganizations" ("memberId") | ||
| WHERE "source" = 'email-domain' AND "deletedAt" IS NULL; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
141 changes: 141 additions & 0 deletions
141
services/apps/cron_service/src/jobs/inferMemberOrganizationStintChanges.job.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,141 @@ | ||
| import CronTime from 'cron-time-generator' | ||
|
|
||
| import { | ||
| MEMBER_ORG_STINT_CHANGES_DATES_PREFIX, | ||
| MEMBER_ORG_STINT_CHANGES_QUEUE, | ||
| inferMemberOrganizationStintChanges, | ||
| } from '@crowd/common_services' | ||
| import { | ||
| QueryExecutor, | ||
| changeMemberOrganizationAffiliationOverrides, | ||
| checkOrganizationAffiliationPolicy, | ||
| createMemberOrganization, | ||
| fetchMemberOrganizationsBySource, | ||
| updateMemberOrganization, | ||
| } from '@crowd/data-access-layer' | ||
| import { WRITE_DB_CONFIG, getDbConnection } from '@crowd/data-access-layer/src/database' | ||
| import { pgpQx } from '@crowd/data-access-layer/src/queryExecutor' | ||
| import { REDIS_CONFIG, getRedisClient } from '@crowd/redis' | ||
| import { MemberOrgStintChange, OrganizationSource } from '@crowd/types' | ||
|
|
||
| import { IJobDefinition } from '../types' | ||
|
|
||
| const job: IJobDefinition = { | ||
| name: 'infer-member-organization-stint-changes', | ||
| cronTime: CronTime.every(5).minutes(), | ||
| timeout: 10 * 60, | ||
| process: async (ctx) => { | ||
| const redis = await getRedisClient(REDIS_CONFIG()) | ||
| const db = await getDbConnection(WRITE_DB_CONFIG()) | ||
| const qx = pgpQx(db) | ||
|
|
||
| ctx.log.info('Starting member organization stint inference job.') | ||
|
|
||
| const memberIds = await redis.sRandMemberCount(MEMBER_ORG_STINT_CHANGES_QUEUE, 500) | ||
| if (!memberIds?.length) return | ||
|
|
||
| ctx.log.info({ count: memberIds.length }, 'Processing members from queue.') | ||
|
|
||
| let processed = 0 | ||
|
|
||
| for (const memberId of memberIds) { | ||
| try { | ||
| const datesKey = `${MEMBER_ORG_STINT_CHANGES_DATES_PREFIX}:${memberId}` | ||
| const hash = await redis.hGetAll(datesKey) | ||
|
|
||
| if (!hash || Object.keys(hash).length === 0) { | ||
| await redis.sRem(MEMBER_ORG_STINT_CHANGES_QUEUE, memberId) | ||
| continue | ||
| } | ||
|
|
||
| const { activityDates, orgIds } = parseMemberActivityHash(hash) | ||
|
|
||
| if (activityDates.length > 0) { | ||
| const existingOrgs = await fetchMemberOrganizationsBySource( | ||
| qx, | ||
| memberId, | ||
| OrganizationSource.EMAIL_DOMAIN, | ||
| ) | ||
|
|
||
| const changes = inferMemberOrganizationStintChanges(memberId, existingOrgs, activityDates) | ||
|
|
||
| if (changes.length > 0) { | ||
| ctx.log.debug({ memberId, changes }, 'Stint changes identified.') | ||
| await applyStintChanges(qx, changes) | ||
| } | ||
| } | ||
|
|
||
| // Remove only the fields we actually read | ||
| await redis | ||
| .multi() | ||
| .hDel(datesKey, orgIds) | ||
| .sRem(MEMBER_ORG_STINT_CHANGES_QUEUE, memberId) | ||
| .exec() | ||
|
|
||
| processed++ | ||
| } catch (err) { | ||
| ctx.log.error(err, { memberId }, 'Failed to process member stint inference.') | ||
| } | ||
| } | ||
|
|
||
| ctx.log.info({ processed }, 'Batch complete.') | ||
| }, | ||
| } | ||
|
|
||
| /** | ||
| * Parses the Redis hash into a clean, typed list of activity dates. | ||
| */ | ||
| function parseMemberActivityHash(hash: Record<string, string>) { | ||
| const orgIds = Object.keys(hash) | ||
| const activityDates = orgIds.flatMap((organizationId) => { | ||
| try { | ||
| const dates = JSON.parse(hash[organizationId]) | ||
| return Array.isArray(dates) | ||
| ? dates | ||
| .filter((d): d is string => typeof d === 'string') | ||
| .map((date) => ({ organizationId, date })) | ||
| : [] | ||
| } catch { | ||
| return [] | ||
| } | ||
| }) | ||
| return { activityDates, orgIds } | ||
| } | ||
|
|
||
| /** | ||
| * Applies the stint changes to the database. | ||
| */ | ||
| async function applyStintChanges(qx: QueryExecutor, changes: MemberOrgStintChange[]) { | ||
| for (const change of changes) { | ||
| if (change.type === 'insert') { | ||
| const memberOrganizationId = await createMemberOrganization(qx, change.memberId, { | ||
| organizationId: change.organizationId, | ||
| dateStart: change.dateStart, | ||
| dateEnd: change.dateEnd, | ||
| source: OrganizationSource.EMAIL_DOMAIN, | ||
| }) | ||
|
|
||
| const isAffiliationBlocked = await checkOrganizationAffiliationPolicy( | ||
| qx, | ||
| change.organizationId, | ||
| ) | ||
|
|
||
| if (memberOrganizationId && isAffiliationBlocked) { | ||
| await changeMemberOrganizationAffiliationOverrides(qx, [ | ||
| { | ||
| memberId: change.memberId, | ||
| memberOrganizationId, | ||
| allowAffiliation: false, | ||
| }, | ||
| ]) | ||
| } | ||
| } else { | ||
| await updateMemberOrganization(qx, change.memberId, change.id, { | ||
| dateStart: change.dateStart, | ||
| dateEnd: change.dateEnd, | ||
| }) | ||
| } | ||
| } | ||
| } | ||
|
|
||
| export default job |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.