-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathsearch-sync-domains.ts
More file actions
70 lines (62 loc) · 2.4 KB
/
search-sync-domains.ts
File metadata and controls
70 lines (62 loc) · 2.4 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
import { Domain, connectToDatabase } from '../models';
import { CommandOptions } from './ecs-client';
import { In } from 'typeorm';
import ESClient from './es-client';
import { chunk } from 'lodash';
import pRetry from 'p-retry';
/**
* Chunk sizes. These values are small during testing to facilitate testing.
*/
export const DOMAIN_CHUNK_SIZE = typeof jest === 'undefined' ? 50 : 10;
export const ORGANIZATION_CHUNK_SIZE = typeof jest === 'undefined' ? 50 : 10;
export const handler = async (organizationId?: string) => {
console.log('Running searchSync');
await connectToDatabase();
const client = new ESClient();
const qs = Domain.createQueryBuilder('domain')
.leftJoinAndSelect('domain.organization', 'organization')
.leftJoinAndSelect('domain.vulnerabilities', 'vulnerabilities')
.leftJoinAndSelect('domain.services', 'services')
.having('domain.syncedAt is null')
.orHaving('domain.updatedAt > domain.syncedAt')
.orHaving('organization.updatedAt > domain.syncedAt')
.orHaving(
'COUNT(CASE WHEN vulnerabilities.updatedAt > domain.syncedAt THEN 1 END) >= 1'
)
.orHaving(
'COUNT(CASE WHEN services.updatedAt > domain.syncedAt THEN 1 END) >= 1'
)
.groupBy('domain.id, organization.id, vulnerabilities.id, services.id')
.select(['domain.id']);
if (organizationId) {
// This parameter is used for testing only
qs.where('organization.id=:org', { org: organizationId });
}
qs.andWhere(
'(domain."isFceb" = true OR (domain."isFceb" = false AND domain."fromCidr" = true))'
);
const domainIds = (await qs.getMany()).map((e) => e.id);
console.log(`Got ${domainIds.length} domains.`);
if (domainIds.length) {
const domainIdChunks = chunk(domainIds, DOMAIN_CHUNK_SIZE);
for (const domainIdChunk of domainIdChunks) {
const domains = await Domain.find({
where: { id: In(domainIdChunk) },
relations: ['services', 'organization', 'vulnerabilities']
});
console.log(`Syncing ${domains.length} domains...`);
await pRetry(() => client.updateDomains(domains), {
retries: 3,
randomize: true
});
await Domain.createQueryBuilder('domain')
.update(Domain)
.set({ syncedAt: new Date(Date.now()) })
.where({ id: In(domains.map((e) => e.id)) })
.execute();
}
console.log('Domain sync complete.');
} else {
console.log('Not syncing any domains.');
}
};