-
Notifications
You must be signed in to change notification settings - Fork 732
Expand file tree
/
Copy pathintegrationService.ts
More file actions
2701 lines (2339 loc) · 86.9 KB
/
integrationService.ts
File metadata and controls
2701 lines (2339 loc) · 86.9 KB
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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* eslint-disable no-promise-executor-return */
import { createAppAuth } from '@octokit/auth-app'
import { request } from '@octokit/request'
import axios, { AxiosRequestConfig, AxiosResponse } from 'axios'
import lodash from 'lodash'
import moment from 'moment'
import { Transaction } from 'sequelize'
import { EDITION, Error400, Error404, Error542 } from '@crowd/common'
import { getGithubInstallationToken } from '@crowd/common_services'
import {
ICreateInsightsProject,
deleteMissingSegmentRepositories,
deleteSegmentRepositories,
upsertSegmentRepositories,
} from '@crowd/data-access-layer/src/collections'
import { syncRepositoriesToGitV2 } from '@crowd/data-access-layer/src/integrations'
import {
NangoIntegration,
connectNangoIntegration,
createNangoConnection,
deleteNangoConnection,
setNangoMetadata,
startNangoSync,
} from '@crowd/nango'
import { RedisCache } from '@crowd/redis'
import { WorkflowIdReusePolicy } from '@crowd/temporal'
import { CodePlatform, Edition, PlatformType } from '@crowd/types'
import { IRepositoryOptions } from '@/database/repositories/IRepositoryOptions'
import GithubInstallationsRepository from '@/database/repositories/githubInstallationsRepository'
import GitlabReposRepository from '@/database/repositories/gitlabReposRepository'
import IntegrationProgressRepository from '@/database/repositories/integrationProgressRepository'
import SegmentRepository from '@/database/repositories/segmentRepository'
import { IntegrationProgress, Repos } from '@/serverless/integrations/types/regularTypes'
import {
fetchAllGitlabGroups,
fetchGitlabGroupProjects,
fetchGitlabUserProjects,
} from '@/serverless/integrations/usecases/gitlab/getProjects'
import { removeGitlabWebhooks } from '@/serverless/integrations/usecases/gitlab/removeWebhooks'
import { setupGitlabWebhooks } from '@/serverless/integrations/usecases/gitlab/setupWebhooks'
import { getUserSubscriptions } from '@/serverless/integrations/usecases/groupsio/getUserSubscriptions'
import {
GroupsioGetToken,
GroupsioIntegrationData,
GroupsioVerifyGroup,
} from '@/serverless/integrations/usecases/groupsio/types'
import { DISCORD_CONFIG, GITHUB_CONFIG, GITLAB_CONFIG, IS_TEST_ENV, KUBE_MODE } from '../conf/index'
import GitReposRepository from '../database/repositories/gitReposRepository'
import GithubReposRepository from '../database/repositories/githubReposRepository'
import IntegrationRepository from '../database/repositories/integrationRepository'
import SequelizeRepository from '../database/repositories/sequelizeRepository'
import telemetryTrack from '../segment/telemetryTrack'
import track from '../segment/track'
import { ILinkedInOrganization } from '../serverless/integrations/types/linkedinTypes'
import { getInstalledRepositories } from '../serverless/integrations/usecases/github/rest/getInstalledRepositories'
import {
GitHubStats,
getGitHubRemoteStats,
} from '../serverless/integrations/usecases/github/rest/getRemoteStats'
import { getOrganizations } from '../serverless/integrations/usecases/linkedin/getOrganizations'
import getToken from '../serverless/integrations/usecases/nango/getToken'
import { getIntegrationRunWorkerEmitter } from '../serverless/utils/queueService'
import { ConfluenceIntegrationData } from '../types/confluenceTypes'
import { JiraIntegrationData } from '../types/jiraTypes'
import { encryptData } from '../utils/crypto'
import { IServiceOptions } from './IServiceOptions'
import { CollectionService } from './collectionService'
const discordToken = DISCORD_CONFIG.token || DISCORD_CONFIG.token2
export default class IntegrationService {
options: IServiceOptions
constructor(options) {
this.options = options
}
async createOrUpdate(data, transaction: Transaction, options?: IRepositoryOptions) {
try {
const record = await IntegrationRepository.findByPlatform(data.platform, {
...(options || this.options),
transaction,
})
const updatedRecord = await this.update(record.id, data, transaction, options)
if (!IS_TEST_ENV) {
track(
'Integration Updated',
{
id: data.id,
platform: data.platform,
status: data.status,
},
{ ...this.options },
)
}
return updatedRecord
} catch (error) {
this.options.log.error(error)
if (error.code === 404) {
const record = await this.create(data, transaction, options)
if (!IS_TEST_ENV) {
track(
'Integration Created',
{
id: data.id,
platform: data.platform,
status: data.status,
},
{ ...this.options },
)
telemetryTrack(
'Integration created',
{
id: record.id,
createdAt: record.createdAt,
platform: record.platform,
},
this.options,
)
}
return record
}
throw error
}
}
/**
* Find all active integrations for a tenant
* @returns The active integrations for a tenant
*/
async getAllActiveIntegrations() {
return IntegrationRepository.findAndCountAll({ filter: { status: 'done' } }, this.options)
}
async findByPlatform(platform) {
return IntegrationRepository.findByPlatform(platform, this.options)
}
async findAllByPlatform(platform) {
return IntegrationRepository.findAllByPlatform(platform, this.options)
}
static isCodePlatform(value: string): value is CodePlatform {
return [
PlatformType.GITHUB,
PlatformType.GITHUB_NANGO,
PlatformType.GITLAB,
PlatformType.GIT,
PlatformType.GERRIT,
].includes(value as PlatformType)
}
async create(data, transaction?: any, options?: IRepositoryOptions) {
try {
const txOptions = {
...(options || this.options),
transaction,
}
const integration = await IntegrationRepository.create(data, txOptions)
const collectionService = new CollectionService(txOptions)
const [insightsProject] = await collectionService.findInsightsProjectsBySegmentId(
integration.segmentId,
)
if (!insightsProject) {
this.options.log.info(
`The segmentId: ${integration.segmentId} does not have any InsightsProject related`,
)
return integration
}
const { segmentId, id: insightsProjectId } = insightsProject
const { platform } = data
const repositories = IntegrationService.isCodePlatform(platform)
? await this.syncSegmentRepositories({
insightsProjectId,
integrationId: integration.id,
segmentId,
txOptions,
})
: insightsProject.repositories || []
await this.updateInsightsProject({
insightsProjectId,
isFirstUpdate: true,
platform,
repositories,
segmentId,
transaction,
})
return integration
} catch (error) {
SequelizeRepository.handleUniqueFieldError(error, this.options.language, 'integration')
throw error
}
}
async update(id, data, transaction?: any, options?: IRepositoryOptions) {
try {
const txOptions = {
...(options || this.options),
transaction,
}
const integration = await IntegrationRepository.update(id, data, txOptions)
const collectionService = new CollectionService(txOptions)
const [insightsProject] = await collectionService.findInsightsProjectsBySegmentId(
integration.segmentId,
)
let repositories = []
const { platform } = data
if (insightsProject) {
const { segmentId, id: insightsProjectId } = insightsProject
repositories = IntegrationService.isCodePlatform(platform)
? await this.syncSegmentRepositories({
insightsProjectId,
integrationId: integration.id,
segmentId,
txOptions,
})
: insightsProject.repositories || []
await this.updateInsightsProject({
insightsProjectId,
platform,
repositories,
segmentId,
transaction,
})
} else {
const currentRepositories = await collectionService.findRepositoriesForSegment(
integration.segmentId,
)
repositories = Object.values(currentRepositories).flatMap((repos) =>
repos.map((repo) => repo.url),
)
}
if (IntegrationService.isCodePlatform(platform) && platform !== PlatformType.GIT) {
await this.gitConnectOrUpdate(
{
remotes: repositories.map((url) => ({ url, forkedFrom: null })),
},
txOptions,
)
}
return integration
} catch (err) {
this.options.log.error(err)
SequelizeRepository.handleUniqueFieldError(err, this.options.language, 'integration')
throw err
}
}
private async updateInsightsProject({
insightsProjectId,
isFirstUpdate = false,
platform,
segmentId,
transaction,
repositories,
}: {
insightsProjectId: string
isFirstUpdate?: boolean
platform: PlatformType
segmentId: string
transaction: Transaction
repositories: string[]
}) {
const collectionService = new CollectionService({ ...this.options, transaction })
const data: Partial<ICreateInsightsProject> = {}
const { widgets } = await collectionService.findSegmentsWidgetsById(segmentId)
data.widgets = widgets
data.repositories = repositories
if (
(platform === PlatformType.GITHUB || platform === PlatformType.GITHUB_NANGO) &&
isFirstUpdate
) {
const githubInsights = await collectionService.findGithubInsightsForSegment(segmentId)
if (githubInsights) {
this.options.log.info(`Static Insights found: ${JSON.stringify(githubInsights)}`)
await this.options.temporal.workflow.start('automaticCategorization', {
taskQueue: 'categorization',
workflowId: `categorization/${segmentId}`,
workflowIdReusePolicy:
WorkflowIdReusePolicy.WORKFLOW_ID_REUSE_POLICY_TERMINATE_IF_RUNNING,
retry: {
maximumAttempts: 10,
},
args: [
{
description: githubInsights.description,
github: githubInsights.github,
topics: githubInsights.topics,
website: githubInsights.website,
segmentId,
},
],
})
data.description = githubInsights.description
data.github = githubInsights.github
data.keywords = githubInsights.topics
data.logoUrl = githubInsights.logoUrl
data.name = githubInsights.name
data.twitter = githubInsights.twitter
data.website = githubInsights.website
}
}
this.options.log.info(`Insight Project updated: ${insightsProjectId}`)
await collectionService.updateInsightsProject(insightsProjectId, data)
}
async destroyAll(ids) {
const toRemoveRepo = new Set<string>()
let segmentId
const transaction = await SequelizeRepository.createTransaction(this.options)
try {
for (const id of ids) {
let integration
try {
integration = await this.findById(id)
if (integration.segmentId) {
segmentId = integration.segmentId
}
} catch (err) {
throw new Error404()
}
// remove github remotes from git integration
if (
integration.platform === PlatformType.GITHUB ||
integration.platform === PlatformType.GITLAB ||
integration.platform === PlatformType.GITHUB_NANGO
) {
let shouldUpdateGit: boolean
const mapping =
integration.platform === PlatformType.GITHUB ||
integration.platform === PlatformType.GITHUB_NANGO
? await this.getGithubRepos(id)
: await this.getGitlabRepos(id)
const repos: Record<string, string[]> = mapping.reduce((acc, { url, segment }) => {
if (!acc[segment.id]) {
acc[segment.id] = []
}
acc[segment.id].push(url)
return acc
}, {})
for (const [segmentId, urls] of Object.entries(repos)) {
urls.forEach((url) => toRemoveRepo.add(url))
const segmentOptions: IRepositoryOptions = {
...this.options,
currentSegments: [
{
...this.options.currentSegments[0],
id: segmentId as string,
},
],
}
try {
await IntegrationRepository.findByPlatform(PlatformType.GIT, segmentOptions)
shouldUpdateGit = true
} catch (err) {
shouldUpdateGit = false
}
if (shouldUpdateGit) {
const gitInfo = await this.gitGetRemotes(segmentOptions)
const gitRemotes = gitInfo[segmentId].remotes
const remainingRemotes = gitRemotes.filter((remote) => !urls.includes(remote))
if (remainingRemotes.length === 0) {
// If no remotes left, delete the Git integration entirely
const gitIntegration = await IntegrationRepository.findByPlatform(
PlatformType.GIT,
segmentOptions,
)
// Soft delete git.repositories for git-integration V2
await GitReposRepository.delete(gitIntegration.id, {
...this.options,
transaction,
})
// Then delete the git integration
await IntegrationRepository.destroy(gitIntegration.id, {
...this.options,
transaction,
})
} else {
// Update with remaining remotes
await this.gitConnectOrUpdate(
{
remotes: remainingRemotes.map((url: string) => ({ url, forkedFrom: null })),
},
segmentOptions,
)
}
}
}
if (
integration.platform === PlatformType.GITHUB ||
integration.platform === PlatformType.GITHUB_NANGO
) {
// soft delete github repos
await GithubReposRepository.delete(integration.id, {
...this.options,
transaction,
})
// Also soft delete from git.repositories for git-integration V2
try {
// Find the Git integration ID for this segment
const gitIntegration = await IntegrationRepository.findByPlatform(PlatformType.GIT, {
...this.options,
currentSegments: [{ id: integration.segmentId } as any],
transaction,
})
if (gitIntegration) {
await GitReposRepository.delete(gitIntegration.id, {
...this.options,
transaction,
})
}
} catch (err) {
this.options.log.info(
'No Git integration found for segment, skipping git.repositories cleanup',
)
}
}
}
if (integration.platform === PlatformType.GITLAB) {
if (integration.settings.webhooks) {
await removeGitlabWebhooks(
integration.token,
integration.settings.webhooks.map((hook) => hook.projectId),
integration.settings.webhooks.map((hook) => hook.hookId),
)
}
// soft delete gitlab repos
await GitlabReposRepository.delete(integration.id, {
...this.options,
transaction,
})
}
await IntegrationRepository.destroy(id, {
...this.options,
transaction,
})
}
const collectionService = new CollectionService({ ...this.options, transaction })
const qx = SequelizeRepository.getQueryExecutor(this.options)
let insightsProject = null
let widgets = []
if (segmentId) {
const [project] = await collectionService.findInsightsProjectsBySegmentId(segmentId)
insightsProject = project
const widgetsResult = await collectionService.findSegmentsWidgetsById(segmentId)
widgets = widgetsResult.widgets
await deleteSegmentRepositories(qx, {
segmentId,
})
}
const insightsRepo = insightsProject?.repositories ?? []
const filteredRepos = insightsRepo.filter((repo) => !toRemoveRepo.has(repo))
// remove duplicates
const repositories = [...new Set<string>(filteredRepos)]
if (insightsProject) {
await collectionService.updateInsightsProject(insightsProject.id, { widgets, repositories })
}
await SequelizeRepository.commitTransaction(transaction)
} catch (error) {
await SequelizeRepository.rollbackTransaction(transaction)
throw error
}
}
async findById(id) {
const record = await IntegrationRepository.findById(id, this.options)
if (record) {
const segmentRepository = new SegmentRepository(this.options)
const segment = await segmentRepository.findById(record.segmentId)
return {
...record,
segment,
}
}
return record
}
async findAllAutocomplete(search, limit) {
return IntegrationRepository.findAllAutocomplete(search, limit, this.options)
}
async findAndCountAll(args) {
return IntegrationRepository.findAndCountAll(args, this.options)
}
/**
* Retrieves global integrations for the specified tenant.
*
* @param {any} args - Additional arguments that define search criteria or constraints.
* @return {Promise<any>} A promise that resolves to the list of global integrations matching the criteria.
*/
async findGlobalIntegrations(args: any) {
return IntegrationRepository.findGlobalIntegrations(args, this.options)
}
/**
* Fetches the global count of integration statuses for a given tenant.
*
* @param {Object} args - Additional arguments to refine the query.
* @return {Promise<number>} A promise that resolves to the count of global integration statuses.
*/
async findGlobalIntegrationsStatusCount(args: any) {
return IntegrationRepository.findGlobalIntegrationsStatusCount(args, this.options)
}
async query(data) {
const advancedFilter = data.filter
const orderBy = data.orderBy
const limit = data.limit
const offset = data.offset
return IntegrationRepository.findAndCountAll(
{ advancedFilter, orderBy, limit, offset },
this.options,
)
}
async import(data, importHash) {
const transaction = await SequelizeRepository.createTransaction(this.options)
try {
if (!importHash) {
throw new Error400(this.options.language, 'importer.errors.importHashRequired')
}
if (await this._isImportHashExistent(importHash)) {
throw new Error400(this.options.language, 'importer.errors.importHashExistent')
}
const dataToCreate = {
...data,
importHash,
}
const result = this.create(dataToCreate, transaction)
await SequelizeRepository.commitTransaction(transaction)
return await result
} catch (err) {
await SequelizeRepository.rollbackTransaction(transaction)
throw err
}
}
async _isImportHashExistent(importHash) {
const count = await IntegrationRepository.count(
{
importHash,
},
this.options,
)
return count > 0
}
/**
* Returns installation access token for a Github App installation
* @param installId Install id of the Github app
* @returns Installation authentication token
*/
static async getInstallToken(installId) {
let privateKey = GITHUB_CONFIG.privateKey
if (KUBE_MODE) {
privateKey = Buffer.from(privateKey, 'base64').toString('ascii')
}
const auth = createAppAuth({
appId: GITHUB_CONFIG.appId,
privateKey,
clientId: GITHUB_CONFIG.clientId,
clientSecret: GITHUB_CONFIG.clientSecret,
})
// Retrieve installation access token
const installationAuthentication = await auth({
type: 'installation',
installationId: installId,
})
return installationAuthentication.token
}
static extractOwner(repos, options) {
const owners = lodash.countBy(repos, 'owner')
if (Object.keys(owners).length === 1) {
return Object.keys(owners)[0]
}
options.log.warn('Multiple owners found in GitHub repos!', owners)
// return the owner with the most repos
return lodash.maxBy(Object.keys(owners), (owner) => owners[owner])
}
async connectGithub(code, installId, setupAction = 'install') {
if (setupAction === 'request') {
return this.createOrUpdate(
{
platform: PlatformType.GITHUB,
status: 'waiting-approval',
},
await SequelizeRepository.createTransaction(this.options),
)
}
const GITHUB_AUTH_ACCESSTOKEN_URL = 'https://github.com/login/oauth/access_token'
const CLIENT_ID = GITHUB_CONFIG.clientId
const CLIENT_SECRET = GITHUB_CONFIG.clientSecret
const tokenResponse = await axios({
method: 'post',
url: GITHUB_AUTH_ACCESSTOKEN_URL,
data: {
client_id: CLIENT_ID,
client_secret: CLIENT_SECRET,
code,
},
})
let token = tokenResponse.data
token = token.slice(token.search('=') + 1, token.search('&'))
try {
const requestWithAuth = request.defaults({
headers: {
authorization: `token ${token}`,
},
})
await requestWithAuth('GET /user')
} catch {
throw new Error542(
`Invalid token for GitHub integration. Code: ${code}, setupAction: ${setupAction}. Token: ${token}`,
)
}
const installToken = await IntegrationService.getInstallToken(installId)
const repos = await getInstalledRepositories(installToken)
const githubOwner = IntegrationService.extractOwner(repos, this.options)
let orgAvatar
try {
const response = await request('GET /users/{user}', {
user: githubOwner,
})
orgAvatar = response.data.avatar_url
} catch (err) {
this.options.log.warn(err, 'Error while fetching GitHub user!')
}
const integration = await this.createOrUpdateGithubIntegration(
{
platform: PlatformType.GITHUB,
token,
settings: { updateMemberAttributes: true, orgAvatar },
integrationIdentifier: installId,
status: 'mapping',
},
repos,
)
return integration
}
async connectGithubInstallation(installId: string) {
const installToken = await IntegrationService.getInstallToken(installId)
const repos = await getInstalledRepositories(installToken)
const githubOwner = IntegrationService.extractOwner(repos, this.options)
let orgAvatar
try {
const response = await request('GET /users/{user}', {
user: githubOwner,
})
orgAvatar = response.data.avatar_url
} catch (err) {
this.options.log.warn(err, 'Error while fetching GitHub user!')
}
const integration = await this.createOrUpdateGithubIntegration(
{
platform: PlatformType.GITHUB,
token: installToken,
settings: { updateMemberAttributes: true, orgAvatar },
integrationIdentifier: installId,
status: 'mapping',
},
repos,
)
return integration
}
async getGithubInstallations() {
return GithubInstallationsRepository.getInstallations(this.options)
}
/**
* Creates or updates a GitHub integration, handling large repos data
* @param integrationData The integration data to create or update
* @param repos The repositories data
*/
private async createOrUpdateGithubIntegration(integrationData, repos: Repos) {
let integration
const transaction = await SequelizeRepository.createTransaction(this.options)
try {
// Get the first repo's owner since we know all repos are from same installation
const orgName = repos[0]?.owner
// Create initial integration with org structure but empty repos
const initialOrg = {
name: orgName,
logo: integrationData.settings.orgAvatar,
url: `https://github.com/${orgName}`,
fullSync: true,
updatedAt: new Date().toISOString(),
repos: [],
}
integration = await this.createOrUpdate(
{
...integrationData,
settings: {
...integrationData.settings,
orgs: [initialOrg],
},
},
transaction,
)
await SequelizeRepository.commitTransaction(transaction)
// Transform repos into the new format
const transformedRepos = repos.map((repo) => ({
name: repo.name,
url: repo.url,
updatedAt: repo.createdAt || new Date().toISOString(),
forkedFrom: repo.forkedFrom || null,
}))
// Add repos in chunks
const chunkSize = 100 // Process 100 repos at a time
for (let i = 0; i < transformedRepos.length; i += chunkSize) {
const reposChunk = transformedRepos.slice(i, i + chunkSize)
await this.appendGitHubReposToOrg(integration.id, reposChunk)
}
return integration
} catch (err) {
await SequelizeRepository.rollbackTransaction(transaction)
throw err
}
}
private async appendGitHubReposToOrg(integrationId: string, repos: any[]) {
const transaction = await SequelizeRepository.createTransaction(this.options)
const sequelize = SequelizeRepository.getSequelize(this.options)
try {
// Append repos to the first (and only) org's repos array
const query = `
UPDATE integrations
SET settings = jsonb_set(
settings,
'{orgs,0,repos}',
COALESCE(settings->'orgs'->0->'repos', '[]'::jsonb) || ?::jsonb
)
WHERE id = ?
`
const values = [JSON.stringify(repos), integrationId]
await sequelize.query(query, {
replacements: values,
transaction,
})
await SequelizeRepository.commitTransaction(transaction)
} catch (error) {
await SequelizeRepository.rollbackTransaction(transaction)
throw error
}
}
async githubNangoConnect(settings, mapping, integrationId?: string) {
const existingTransaction = SequelizeRepository.getTransaction(this.options)
const transaction =
existingTransaction || (await SequelizeRepository.createTransaction(this.options))
const txOptions = {
...this.options,
transaction,
}
const txService = new IntegrationService(txOptions)
try {
let integration
if (!integrationId) {
// create new integration
integration = await txService.createOrUpdate(
{
platform: PlatformType.GITHUB_NANGO,
settings,
status: 'done',
},
transaction,
)
// create github mapping - this also creates git integration
await txService.mapGithubRepos(integration.id, mapping, false)
} else {
// update existing integration
integration = await txService.findById(integrationId)
// create github mapping - this also creates git integration
await txService.mapGithubRepos(integrationId, mapping, false)
integration = await txService.createOrUpdate(
{
id: integrationId,
platform: PlatformType.GITHUB_NANGO,
settings: {
...settings,
...(integration.settings.cursors
? {
cursors: integration.settings.cursors,
}
: {}),
...(integration.settings.nangoMapping
? {
nangoMapping: integration.settings.nangoMapping,
}
: {}),
},
},
transaction,
)
}
if (!existingTransaction) {
await SequelizeRepository.commitTransaction(transaction)
}
await this.options.temporal.workflow.start('syncGithubIntegration', {
taskQueue: 'nango',
workflowId: `github-nango-sync/${integration.id}`,
workflowIdReusePolicy: WorkflowIdReusePolicy.WORKFLOW_ID_REUSE_POLICY_ALLOW_DUPLICATE,
retry: {
maximumAttempts: 10,
},
args: [{ integrationIds: [integration.id] }],
})
return await this.findById(integration.id)
} catch (err) {
this.options.log.error(err, 'Error while creating or updating GitHub integration!')
if (!existingTransaction) {
await SequelizeRepository.rollbackTransaction(transaction)
}
throw err
}
}
async mapGithubRepos(integrationId, mapping, fireOnboarding = true) {
this.options.log.info(`Mapping GitHub repos for integration ${integrationId}!`)
const transaction = await SequelizeRepository.createTransaction(this.options)
const txOptions = {
...this.options,
transaction,
}
try {
this.options.log.info(`Updating GitHub repos mapping for integration ${integrationId}!`)
await GithubReposRepository.updateMapping(integrationId, mapping, txOptions)
// add the repos to the git integration
const repos: Record<string, string[]> = Object.entries(mapping).reduce(
(acc, [url, segmentId]) => {
if (!acc[segmentId as string]) {
acc[segmentId as string] = []
}
acc[segmentId as string].push(url)
return acc
},
{},
)
const qx = SequelizeRepository.getQueryExecutor(txOptions)
const collectionService = new CollectionService(txOptions)
for (const [segmentId, repositories] of Object.entries(repos)) {
this.options.log.info(`Finding insights project for segment ${segmentId}!`)
const [insightsProject] = await collectionService.findInsightsProjectsBySegmentId(segmentId)
if (insightsProject) {
this.options.log.info(`Upserting segment repositories for segment ${segmentId}!`)
await upsertSegmentRepositories(qx, {
insightsProjectId: insightsProject.id,
repositories,
segmentId,
})
await deleteMissingSegmentRepositories(qx, {
repositories,
segmentId,
})
}
}
// Get integration settings to access forkedFrom data from all orgs
const integration = await IntegrationRepository.findById(integrationId, txOptions)
const allReposInSettings = integration.settings?.orgs?.flatMap((org) => org.repos || []) || []
for (const [segmentId, urls] of Object.entries(repos)) {
let isGitintegrationConfigured
const segmentOptions: IRepositoryOptions = {
...txOptions,
currentSegments: [
{
...this.options.currentSegments[0],
id: segmentId as string,
},
],
}
try {
this.options.log.info(`Finding Git integration for segment ${segmentId}!`)
await IntegrationRepository.findByPlatform(PlatformType.GIT, segmentOptions)
isGitintegrationConfigured = true
} catch (err) {
isGitintegrationConfigured = false
}
if (isGitintegrationConfigured) {
this.options.log.info(`Finding Git integration for segment ${segmentId}!`)
const gitInfo = await this.gitGetRemotes(segmentOptions)
const gitRemotes = gitInfo[segmentId as string].remotes
const allUrls = Array.from(new Set([...gitRemotes, ...urls]))
this.options.log.info(`Updating Git integration for segment ${segmentId}!`)
await this.gitConnectOrUpdate(
{
remotes: allUrls.map((url) => {
const repoInSettings = allReposInSettings.find((r) => r.url === url)
return { url, forkedFrom: repoInSettings?.forkedFrom || null }