-
Notifications
You must be signed in to change notification settings - Fork 741
/
Copy pathactivity.sync.service.ts
290 lines (246 loc) · 8.55 KB
/
activity.sync.service.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
import { IDbActivitySyncData } from '../repo/activity.data'
import { ActivityRepository } from '../repo/activity.repo'
import { OpenSearchIndex } from '../types'
import { trimUtf8ToMaxByteLength } from '@crowd/common'
import { DbStore } from '@crowd/database'
import { Logger, getChildLogger, logExecutionTime } from '@crowd/logging'
import { IPagedSearchResponse, ISearchHit } from './opensearch.data'
import { OpenSearchService } from './opensearch.service'
export class ActivitySyncService {
private static MAX_BYTE_LENGTH = 25000
private log: Logger
private readonly activityRepo: ActivityRepository
constructor(
store: DbStore,
private readonly openSearchService: OpenSearchService,
parentLog: Logger,
) {
this.log = getChildLogger('activity-sync-service', parentLog)
this.activityRepo = new ActivityRepository(store, this.log)
}
public async getAllIndexedTenantIds(
pageSize = 500,
afterKey?: string,
): Promise<IPagedSearchResponse<string, string>> {
const include = ['uuid_tenantId']
const results = await this.openSearchService.search(
OpenSearchIndex.ACTIVITIES,
undefined,
{
uuid_tenantId_buckets: {
composite: {
size: pageSize,
sources: [
{
uuid_tenantId: {
terms: {
field: 'uuid_tenantId',
},
},
},
],
after: afterKey
? {
uuid_tenantId: afterKey,
}
: undefined,
},
},
},
undefined,
undefined,
undefined,
include,
)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const data = (results as any).uuid_tenantId_buckets
const newAfterKey = data.after_key?.uuid_tenantId
const ids = data.buckets.map((b) => b.key.uuid_tenantId)
return {
data: ids,
afterKey: newAfterKey,
}
}
public async cleanupActivityIndex(tenantId: string): Promise<void> {
this.log.warn({ tenantId }, 'Cleaning up activity index!')
const query = {
bool: {
filter: {
term: {
uuid_tenantId: tenantId,
},
},
},
}
const sort = [{ date_timestamp: 'asc' }]
const include = ['date_timestamp']
const pageSize = 500
let lastTimestamp: string
let results = (await this.openSearchService.search(
OpenSearchIndex.ACTIVITIES,
query,
undefined,
pageSize,
sort,
undefined,
include,
)) as ISearchHit<{ date_timestamp: string }>[]
let processed = 0
while (results.length > 0) {
// check every activity if they exists in the database and if not remove them from the index
const ids = results.map((r) => r._id)
const dbIds = await this.activityRepo.checkActivitiesExist(tenantId, ids)
const toRemove = ids.filter((id) => !dbIds.includes(id))
if (toRemove.length > 0) {
this.log.warn({ tenantId, toRemove }, 'Removing activities from index!')
for (const id of toRemove) {
await this.removeActivity(id)
}
}
processed += results.length
this.log.warn({ tenantId }, `Processed ${processed} activities while cleaning up tenant!`)
// use last joinedAt to get the next page
lastTimestamp = results[results.length - 1]._source.date_timestamp
results = (await this.openSearchService.search(
OpenSearchIndex.ACTIVITIES,
query,
undefined,
pageSize,
sort,
lastTimestamp,
include,
)) as ISearchHit<{ date_timestamp: string }>[]
}
this.log.warn({ tenantId }, `Processed total of ${processed} members while cleaning up tenant!`)
}
public async syncTenantActivities(tenantId: string, batchSize = 200): Promise<void> {
this.log.debug({ tenantId }, 'Syncing all tenant activities!')
let count = 0
const now = new Date()
const cutoffDate = now.toISOString()
await logExecutionTime(
async () => {
let activityIds = await this.activityRepo.getTenantActivitiesForSync(tenantId, batchSize)
while (activityIds.length > 0) {
count += await this.syncActivities(activityIds)
const diffInSeconds = (new Date().getTime() - now.getTime()) / 1000
this.log.info(
{ tenantId },
`Synced ${count} activities! Speed: ${Math.round(
count / diffInSeconds,
)} activities/second!`,
)
activityIds = await this.activityRepo.getTenantActivitiesForSync(
tenantId,
batchSize,
activityIds[activityIds.length - 1],
)
}
activityIds = await this.activityRepo.getRemainingTenantActivitiesForSync(
tenantId,
1,
batchSize,
cutoffDate,
)
while (activityIds.length > 0) {
count += await this.syncActivities(activityIds)
const diffInSeconds = (new Date().getTime() - now.getTime()) / 1000
this.log.info(
{ tenantId },
`Synced ${count} activities! Speed: ${Math.round(
count / diffInSeconds,
)} activities/second!`,
)
activityIds = await this.activityRepo.getRemainingTenantActivitiesForSync(
tenantId,
1,
batchSize,
cutoffDate,
)
}
},
this.log,
'sync-tenant-activities',
)
this.log.info({ tenantId }, `Synced total of ${count} activities!`)
}
public async syncOrganizationActivities(organizationId: string, batchSize = 200): Promise<void> {
this.log.debug({ organizationId }, 'Syncing all organization activities!')
let count = 0
const now = new Date()
await logExecutionTime(
async () => {
let activityIds = await this.activityRepo.getOrganizationActivitiesForSync(
organizationId,
batchSize,
)
while (activityIds.length > 0) {
count += await this.syncActivities(activityIds)
const diffInSeconds = (new Date().getTime() - now.getTime()) / 1000
this.log.info(
{ organizationId },
`Synced ${count} activities! Speed: ${Math.round(
count / diffInSeconds,
)} activities/second!`,
)
activityIds = await this.activityRepo.getOrganizationActivitiesForSync(
organizationId,
batchSize,
activityIds[activityIds.length - 1],
)
}
},
this.log,
'sync-organization-activities',
)
this.log.info({ organizationId }, `Synced total of ${count} activities!`)
}
public async removeActivity(activityId: string): Promise<void> {
this.log.debug({ activityId }, 'Removing activity from index!')
await this.openSearchService.removeFromIndex(activityId, OpenSearchIndex.ACTIVITIES)
}
public async syncActivities(activityIds: string[]): Promise<number> {
this.log.debug({ activityIds }, 'Syncing activities!')
const activities = await this.activityRepo.getActivityData(activityIds)
if (activities.length > 0) {
await this.openSearchService.bulkIndex(
OpenSearchIndex.ACTIVITIES,
activities.map((m) => {
return {
id: m.id,
body: ActivitySyncService.prefixData(m),
}
}),
)
}
return activities.length
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
public static prefixData(data: IDbActivitySyncData): any {
const p: Record<string, unknown> = {}
p.uuid_id = data.id
p.uuid_tenantId = data.tenantId
p.uuid_segmentId = data.segmentId
p.keyword_type = data.type
p.date_timestamp = new Date(data.timestamp).toISOString()
p.keyword_platform = data.platform
p.bool_isContribution = data.isContribution
p.int_score = data.score ?? 0
p.keyword_sourceId = data.sourceId
p.keyword_sourceParentId = data.sourceParentId
p.keyword_channel = data.channel
p.string_body = trimUtf8ToMaxByteLength(data.body, ActivitySyncService.MAX_BYTE_LENGTH)
p.string_title = data.title
p.string_url = data.url
p.int_sentiment = data.sentiment
p.keyword_importHash = data.importHash
p.uuid_memberId = data.memberId
p.uuid_conversationId = data.conversationId
p.uuid_parentId = data.parentId
p.string_username = data.username
p.uuid_objectMemberId = data.objectMemberId
p.string_objectMemberUsername = data.objectMemberUsername
p.uuid_organizationId = data.organizationId
return p
}
}