-
Notifications
You must be signed in to change notification settings - Fork 821
/
grakn.js
1841 lines (1812 loc) · 75.2 KB
/
grakn.js
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
import uuid from 'uuid/v4';
import {
__,
append,
ascend,
assoc,
chain,
concat,
descend,
dissoc,
equals,
filter,
find as Rfind,
flatten,
fromPairs,
groupBy,
head,
includes,
invertObj,
isEmpty,
isNil,
join,
last,
map,
mapObjIndexed,
mergeAll,
mergeRight,
pipe,
pluck,
prop,
sortWith,
split,
tail,
take,
toPairs,
uniq,
uniqBy
} from 'ramda';
import moment from 'moment';
import { cursorToOffset } from 'graphql-relay/lib/connection/arrayconnection';
import Grakn from 'grakn-client';
import { DatabaseError } from '../config/errors';
import conf, { logger } from '../config/conf';
import { buildPagination, fillTimeSeries, randomKey } from './utils';
import { isInversed, rolesMap } from './graknRoles';
import {
elAggregationCount,
elAggregationRelationsCount,
elBulk,
elDeleteInstanceIds,
elHistogramCount,
elLoadByGraknId,
elLoadById,
elLoadByStixId,
elPaginate,
elRemoveRelationConnection,
elUpdate,
forceNoCache,
INDEX_STIX_ENTITIES,
INDEX_STIX_OBSERVABLE,
INDEX_STIX_RELATIONS,
REL_INDEX_PREFIX
} from './elasticSearch';
// region global variables
const dateFormat = 'YYYY-MM-DDTHH:mm:ss';
const GraknString = 'String';
const GraknDate = 'Date';
export const TYPE_OPENCTI_INTERNAL = 'Internal';
export const TYPE_STIX_DOMAIN = 'Stix-Domain';
export const TYPE_STIX_DOMAIN_ENTITY = 'Stix-Domain-Entity';
export const TYPE_STIX_OBSERVABLE = 'Stix-Observable';
export const TYPE_STIX_RELATION = 'stix_relation';
export const TYPE_STIX_OBSERVABLE_RELATION = 'stix_observable_relation';
export const TYPE_RELATION_EMBEDDED = 'relation_embedded';
export const TYPE_STIX_RELATION_EMBEDDED = 'stix_relation_embedded';
const UNIMPACTED_ENTITIES_ROLE = ['tagging', 'marking', 'kill_chain_phase', 'creator'];
export const inferIndexFromConceptTypes = (types, parentType = null) => {
// Observable index
if (includes(TYPE_STIX_OBSERVABLE, types) || parentType === TYPE_STIX_OBSERVABLE) return INDEX_STIX_OBSERVABLE;
// Relation index
if (includes(TYPE_STIX_RELATION, types) || parentType === TYPE_STIX_RELATION) return INDEX_STIX_RELATIONS;
if (includes(TYPE_STIX_OBSERVABLE_RELATION, types) || parentType === TYPE_STIX_OBSERVABLE_RELATION)
return INDEX_STIX_RELATIONS;
if (includes(TYPE_STIX_RELATION_EMBEDDED, types) || parentType === TYPE_STIX_RELATION_EMBEDDED)
return INDEX_STIX_RELATIONS;
if (includes(TYPE_RELATION_EMBEDDED, types) || parentType === TYPE_RELATION_EMBEDDED) return INDEX_STIX_RELATIONS;
// Everything else in entities index
return INDEX_STIX_ENTITIES;
};
export const now = () => {
// eslint-disable-next-line prettier/prettier
return moment()
.utc()
.toISOString();
};
export const graknNow = () => {
// eslint-disable-next-line prettier/prettier
return moment()
.utc()
.format(dateFormat); // Format that accept grakn
};
export const prepareDate = date => {
// eslint-disable-next-line prettier/prettier
return moment(date)
.utc()
.format(dateFormat);
};
export const sinceNowInMinutes = lastModified => {
const utc = moment().utc();
const diff = utc.diff(moment(lastModified));
const duration = moment.duration(diff);
return Math.floor(duration.asMinutes());
};
export const yearFormat = date => moment(date).format('YYYY');
export const monthFormat = date => moment(date).format('YYYY-MM');
export const dayFormat = date => moment(date).format('YYYY-MM-DD');
export const escape = chars => {
const toEscape = chars && typeof chars === 'string';
if (toEscape) {
return chars
.replace(/\\/g, '\\\\')
.replace(/;/g, '\\;')
.replace(/,/g, '\\,');
}
return chars;
};
export const escapeString = s => (s ? s.replace(/\\/g, '\\\\').replace(/"/g, '\\"') : '');
// Attributes key that can contains multiple values.
export const multipleAttributes = ['stix_label', 'alias', 'grant', 'platform', 'required_permission'];
export const statsDateAttributes = ['created_at', 'first_seen', 'last_seen', 'published', 'valid_from', 'valid_until'];
export const readOnlyAttributes = ['observable_value'];
// endregion
// region client
const client = new Grakn(`${conf.get('grakn:hostname')}:${conf.get('grakn:port')}`);
let session = null;
// endregion
// region basic commands
const closeTx = async gTx => {
try {
if (gTx.tx.isOpen()) {
await gTx.tx.close();
}
} catch (err) {
logger.error('[GRAKN] CloseReadTx error > ', err);
}
};
const takeReadTx = async (retry = false) => {
if (session === null) {
session = await client.session('grakn');
}
try {
const tx = await session.transaction().read();
return { session, tx };
} catch (err) {
logger.error('[GRAKN] TakeReadTx error > ', err);
if (retry === true) {
logger.error('[GRAKN] TakeReadTx, retry failed, Grakn seems down, stopping...');
process.exit(1);
}
return takeReadTx(true);
}
};
export const executeRead = async executeFunction => {
const rTx = await takeReadTx();
try {
const result = await executeFunction(rTx);
await closeTx(rTx);
return result;
} catch (err) {
await closeTx(rTx);
logger.error('[GRAKN] executeRead error > ', err);
throw err;
}
};
const takeWriteTx = async (retry = false) => {
if (session === null) {
session = await client.session('grakn');
}
try {
const tx = await session.transaction().write();
return { session, tx };
} catch (err) {
logger.error('[GRAKN] TakeWriteTx error > ', err);
if (retry === true) {
logger.error('[GRAKN] TakeWriteTx, retry failed, Grakn seems down, stopping...');
process.exit(1);
}
return takeWriteTx(true);
}
};
const commitWriteTx = async wTx => {
try {
await wTx.tx.commit();
} catch (err) {
logger.error('[GRAKN] CommitWriteTx error > ', err);
if (err.code === 3) {
throw new DatabaseError({
data: { details: split('\n', err.details)[1] }
});
}
throw new DatabaseError({ data: { details: err.details } });
}
};
export const executeWrite = async executeFunction => {
const wTx = await takeWriteTx();
try {
const result = await executeFunction(wTx);
await commitWriteTx(wTx);
return result;
} catch (err) {
await closeTx(wTx);
logger.error('[GRAKN] executeWrite error > ', err);
throw err;
}
};
export const write = async query => {
const wTx = await takeWriteTx();
try {
await wTx.tx.query(query);
await commitWriteTx(wTx);
} catch (err) {
logger.error('[GRAKN] Write error > ', err);
} finally {
await closeTx(wTx);
}
};
export const graknIsAlive = async () => {
try {
// Just try to take a read transaction
await executeRead(() => {});
} catch (e) {
logger.error(`[GRAKN] Seems down`);
throw new Error('Grakn seems down');
}
};
export const getGraknVersion = async () => {
// It seems that Grakn server does not expose its version yet:
// https://github.com/graknlabs/client-nodejs/issues/47
return '1.5.9';
};
/**
* Recursive fetch of every types of a concept
* @param concept the element
* @param currentType the current type
* @param acc the recursive accumulator
* @returns {Promise<Array>}
*/
export const conceptTypes = async (concept, currentType = null, acc = []) => {
if (currentType === null) {
const conceptType = await concept.type();
const conceptLabel = await conceptType.label();
acc.push(conceptLabel);
return conceptTypes(concept, conceptType, acc);
}
const parentType = await currentType.sup();
if (parentType === null) return acc;
const conceptLabel = await parentType.label();
if (conceptLabel === 'entity' || conceptLabel === 'relation') return acc;
acc.push(conceptLabel);
return conceptTypes(concept, parentType, acc);
};
const getAliasInternalIdFilter = (query, alias) => {
const reg = new RegExp(`\\$${alias}[\\s]*has[\\s]*internal_id_key[\\s]*"([0-9a-z-_]+)"`, 'gi');
const keyVars = Array.from(query.matchAll(reg));
return keyVars.length > 0 ? last(head(keyVars)) : undefined;
};
const extractRelationAlias = (alias, role, relationType) => {
const variables = [];
if (alias !== 'from' && alias !== 'to') {
throw new Error('[GRAKN] Query cant have relation alias without roles (except for from/to)');
}
const resolveRightAlias = alias === 'from' ? 'to' : 'from';
const resolvedRelation = rolesMap[relationType];
if (resolvedRelation === undefined) {
throw new Error(`[GRAKN] Relation binding missing and rolesMap: ${relationType}`);
}
const bindingByAlias = invertObj(resolvedRelation);
const resolveRightRole = bindingByAlias[resolveRightAlias];
if (resolveRightRole === undefined) {
throw new Error(`[GRAKN] Role resolution error for alias: ${resolveRightAlias} - relation: ${relationType}`);
}
// Control the role specified in the query.
const resolveLeftRole = bindingByAlias[alias];
if (role !== resolveLeftRole) {
throw new Error(`[GRAKN] Incorrect role specified for alias: ${alias} - role: ${role} - relation: ${relationType}`);
}
variables.push({ role: resolveRightRole, alias: resolveRightAlias, forceNatural: false });
variables.push({ role, alias, forceNatural: false });
return variables;
};
/**
* Extract all vars from a grakn query
* @param query
*/
export const extractQueryVars = query => {
const vars = uniq(map(m => ({ alias: m.replace('$', '') }), query.match(/\$[a-z_]+/gi)));
const relationsVars = Array.from(query.matchAll(/\(([a-z_\-\s:$]+),([a-z_\-\s:$]+)\)[\s]*isa[\s]*([a-z_-]+)/g));
const roles = flatten(
map(r => {
const [, left, right, relationType] = r;
const [leftRole, leftAlias] = includes(':', left) ? left.trim().split(':') : [null, left];
const [rightRole, rightAlias] = includes(':', right) ? right.trim().split(':') : [null, right];
const lAlias = leftAlias.trim().replace('$', '');
const lKeyFilter = getAliasInternalIdFilter(query, lAlias);
const rAlias = rightAlias.trim().replace('$', '');
const rKeyFilter = getAliasInternalIdFilter(query, rAlias);
// If one filtering key is specified, just return the duo with no roles
if (lKeyFilter || rKeyFilter) {
return [
{ alias: lAlias, internalIdKey: lKeyFilter, forceNatural: false },
{ alias: rAlias, internalIdKey: rKeyFilter, forceNatural: false }
];
}
// If no filtering, roles must be fully specified or not specified.
// If missing left role
if (leftRole === null && rightRole !== null) {
return extractRelationAlias(rAlias, rightRole, relationType);
}
// If missing right role
if (leftRole !== null && rightRole === null) {
return extractRelationAlias(lAlias, leftRole, relationType);
}
// Else, we have both or nothing
const roleForRight = rightRole ? rightRole.trim() : undefined;
const roleForLeft = leftRole ? leftRole.trim() : undefined;
return [
{ role: roleForRight, alias: rAlias, forceNatural: roleForRight === undefined },
{ role: roleForLeft, alias: lAlias, forceNatural: roleForLeft === undefined }
];
}, relationsVars)
);
return map(v => {
const associatedRole = Rfind(r => r.alias === v.alias, roles);
return pipe(
assoc('role', associatedRole ? associatedRole.role : undefined),
assoc('internalIdKey', associatedRole ? associatedRole.internalIdKey : undefined)
)(v);
}, vars);
};
// endregion
// region Loader common
export const queryAttributeValues = async type => {
return executeRead(async rTx => {
const query = `match $x isa ${escape(type)}; get;`;
logger.debug(`[GRAKN - infer: false] queryAttributeValues > ${query}`);
const iterator = await rTx.tx.query(query);
const answers = await iterator.collect();
const result = await Promise.all(
answers.map(async answer => {
const attribute = answer.map().get('x');
const attributeType = await attribute.type();
const value = await attribute.value();
const attributeTypeLabel = await attributeType.label();
const replacedValue = value.replace(/\\"/g, '"').replace(/\\\\/g, '\\');
return {
node: {
id: attribute.id,
type: attributeTypeLabel,
value: replacedValue
}
};
})
);
return buildPagination(5000, 0, result, 5000);
});
};
export const attributeExists = async attributeLabel => {
return executeRead(async rTx => {
const checkQuery = `match $x sub ${attributeLabel}; get;`;
logger.debug(`[GRAKN - infer: false] attributeExists > ${checkQuery}`);
await rTx.tx.query(checkQuery);
return true;
}).catch(() => false);
};
export const queryAttributeValueById = async id => {
return executeRead(async rTx => {
const query = `match $x id ${escape(id)}; get;`;
logger.debug(`[GRAKN - infer: false] queryAttributeValueById > ${query}`);
const iterator = await rTx.tx.query(query);
const answer = await iterator.next();
const attribute = answer.map().get('x');
const attributeType = await attribute.type();
const value = await attribute.value();
const attributeTypeLabel = await attributeType.label();
const replacedValue = value.replace(/\\"/g, '"').replace(/\\\\/g, '\\');
return {
id: attribute.id,
type: attributeTypeLabel,
value: replacedValue
};
});
};
/**
* Load any grakn instance with internal grakn ID.
* @param query initial query
* @param concept the concept to get attributes from
* @param args
* @returns {Promise}
*/
const loadConcept = async (query, concept, args = {}) => {
const { id } = concept;
const { relationsMap = new Map(), noCache = false, infer = false } = args;
const conceptType = concept.baseType;
const types = await conceptTypes(concept);
const index = inferIndexFromConceptTypes(types);
// 01. Return the data in elastic if not explicitly asked in grakn
// Very useful for getting every entities through relation query.
if (infer === false && noCache === false && !forceNoCache()) {
const conceptFromCache = await elLoadByGraknId(id, relationsMap, [index]);
if (!conceptFromCache) {
logger.debug(`[GRAKN] Cache warning: ${id} should be available in cache`);
} else {
return conceptFromCache;
}
}
// 02. If not found continue the process.
logger.debug(`[GRAKN - infer: false] getAttributes > ${head(types)} ${id}`);
const attributesIterator = await concept.attributes();
const attributes = await attributesIterator.collect();
const attributesPromises = attributes.map(async attribute => {
const attributeType = await attribute.type();
const attributeLabel = await attributeType.label();
return {
dataType: await attributeType.dataType(),
label: attributeLabel,
value: await attribute.value()
};
});
return Promise.all(attributesPromises)
.then(attributesData => {
const transform = pipe(
map(attribute => {
let transformedVal = attribute.value;
const { dataType, label } = attribute;
if (dataType === GraknDate) {
transformedVal = moment(attribute.value)
.utc()
.toISOString();
} else if (dataType === GraknString) {
transformedVal = attribute.value.replace(/\\"/g, '"').replace(/\\\\/g, '\\');
}
return { [label]: transformedVal };
}), // Extract values
chain(toPairs), // Convert to pairs for grouping
groupBy(head), // Group by key
map(pluck(1)), // Remove grouping boilerplate
mapObjIndexed((num, key, obj) =>
// eslint-disable-next-line no-nested-ternary
Array.isArray(obj[key]) && !includes(key, multipleAttributes)
? head(obj[key])
: head(obj[key]) && head(obj[key]) !== ''
? obj[key]
: []
) // Remove extra list then contains only 1 element
)(attributesData);
return pipe(
assoc('id', transform.internal_id_key),
assoc('grakn_id', concept.id),
assoc('parent_types', types),
assoc('base_type', conceptType.toLowerCase()),
assoc('index_version', '1.0')
)(transform);
})
.then(async entityData => {
if (entityData.base_type !== 'relation') return entityData;
const isInferredPromise = concept.isInferred();
const rolePlayers = await concept.rolePlayersMap();
const roleEntries = Array.from(rolePlayers.entries());
const rolesPromises = Promise.all(
map(async roleItem => {
// eslint-disable-next-line prettier/prettier
const roleId = last(roleItem)
.values()
.next().value.id;
const conceptFromMap = relationsMap.get(roleId);
if (conceptFromMap) {
const { alias, forceNatural } = conceptFromMap;
// eslint-disable-next-line prettier/prettier
return head(roleItem)
.label()
.then(async roleLabel => {
// Alias when role are not specified need to be force the opencti natural direction.
let useAlias = alias;
// If role specified in the query, just use the grakn binding.
// If alias is filtering by an internal_id_key, just use the grakn binding.
// If not, retrieve the alias (from or to) inside the roles map.
if (forceNatural) {
const directedRole = rolesMap[head(types)];
if (directedRole === undefined) {
throw new Error(`Undefined directed roles for ${head(types)}, query: ${query}`);
}
useAlias = directedRole[roleLabel];
if (useAlias === undefined) {
throw new Error(`Cannot find directed role for ${roleLabel} in ${head(types)}, query: ${query}`);
}
}
return {
[useAlias]: null, // With be use lazily
[`${useAlias}Id`]: roleId,
[`${useAlias}Role`]: roleLabel,
[`${useAlias}Types`]: conceptFromMap.types
};
});
}
return {};
}, roleEntries)
);
// Wait for all promises before building the result
return Promise.all([isInferredPromise, rolesPromises]).then(([isInferred, roles]) => {
return pipe(
assoc('id', isInferred ? uuid() : entityData.id),
assoc('inferred', isInferred),
assoc('entity_type', entityData.entity_type || TYPE_RELATION_EMBEDDED),
assoc('relationship_type', head(types)),
mergeRight(mergeAll(roles))
)(entityData);
});
})
.then(relationData => {
// Then change the id if relation is inferred
if (relationData.inferred) {
const { fromId, fromRole, toId, toRole } = relationData;
const type = relationData.relationship_type;
const pattern = `{ $rel(${fromRole}: $from, ${toRole}: $to) isa ${type}; $from id ${fromId}; $to id ${toId}; };`;
return assoc('id', Buffer.from(pattern).toString('base64'), relationData);
}
return relationData;
});
};
// endregion
// region Loader list
export const getSingleValue = async (query, infer = false) => {
return executeRead(async rTx => {
logger.debug(`[GRAKN - infer: ${infer}] getSingleValue > ${query}`);
const iterator = await rTx.tx.query(query, { infer });
return iterator.next();
});
};
export const getSingleValueNumber = async (query, infer = false) => {
return getSingleValue(query, infer).then(data => data.number());
};
const findOpts = { infer: false, noCache: false };
export const find = async (query, entities, { uniqueKey, infer, noCache } = findOpts) => {
// Remove empty values from entities
const plainEntities = filter(e => !isEmpty(e) && !isNil(e), entities);
return executeRead(async rTx => {
const conceptQueryVars = extractQueryVars(query);
logger.debug(`[GRAKN - infer: ${infer}] Find > ${query}`);
const iterator = await rTx.tx.query(query, { infer });
// 01. Get every concepts to fetch (unique)
const answers = await iterator.collect();
if (answers.length === 0) return [];
// 02. Query concepts and rebind the data
const queryConcepts = await Promise.all(
map(async answer => {
// Create a map useful for relation roles binding
const queryVarsToConcepts = await Promise.all(
conceptQueryVars.map(async ({ alias, role, internalIdKey }) => {
const concept = answer.map().get(alias);
if (concept.baseType === 'ATTRIBUTE') return undefined; // If specific attributes are used for filtering, ordering, ...
const types = await conceptTypes(concept);
return { id: concept.id, data: { concept, alias, role, internalIdKey, types } };
})
);
const conceptsIndex = filter(e => e, queryVarsToConcepts);
const fetchingConceptsPairs = map(x => [x.id, x.data], conceptsIndex);
const relationsMap = new Map(fetchingConceptsPairs);
// Fetch every concepts of the answer
const requestedConcepts = filter(r => includes(r.data.alias, entities), conceptsIndex);
return map(t => {
const { concept } = t.data;
return { id: concept.id, concept, relationsMap };
}, requestedConcepts);
}, answers)
);
// 03. Fetch every unique concepts
const uniqConceptsLoading = pipe(
flatten,
uniqBy(e => e.id),
map(l => loadConcept(query, l.concept, { relationsMap: l.relationsMap, noCache, infer }))
)(queryConcepts);
const resolvedConcepts = await Promise.all(uniqConceptsLoading);
// 04. Create map from concepts
const conceptCache = new Map(map(c => [c.grakn_id, c], resolvedConcepts));
// 05. Bind all row to data entities
const result = answers.map(answer => {
const dataPerEntities = plainEntities.map(entity => {
const concept = answer.map().get(entity);
const conceptData = conceptCache.get(concept.id);
return [entity, conceptData];
});
return fromPairs(dataPerEntities);
});
// 06. Filter every relation in double
// Grakn can respond with twice the relations (browse in 2 directions)
const uniqFilter = uniqueKey || head(entities);
return uniqBy(u => u[uniqFilter].grakn_id, result);
});
};
// TODO Start - Refactor UI to be able to remove these 2 API
export const findWithConnectedRelations = async (query, key, extraRelKey = null, infer = false) => {
const dataFind = await find(query, [key, extraRelKey], { infer });
return map(t => ({ node: t[key], relation: t[extraRelKey] }), dataFind);
};
export const loadWithConnectedRelations = (query, key, relationKey = null, infer = false) => {
return findWithConnectedRelations(query, key, relationKey, infer).then(result => head(result));
};
const listElements = async (baseQuery, first, offset, orderBy, orderMode, connectedReference, inferred) => {
const countQuery = `${baseQuery} count;`;
const paginateQuery = `offset ${offset}; limit ${first};`;
const orderQuery = orderBy ? `sort $order ${orderMode};` : '';
const query = `${baseQuery} ${orderQuery} ${paginateQuery}`;
const countPromise = getSingleValueNumber(countQuery);
const instancesPromise = await findWithConnectedRelations(query, 'rel', connectedReference, inferred);
return Promise.all([instancesPromise, countPromise]).then(([instances, globalCount]) => {
return buildPagination(first, offset, instances, globalCount);
});
};
export const listEntities = async (entityTypes, searchFields, args) => {
// filters contains potential relations like, mitigates, tagged ...
const { first = 200, after, orderBy, orderMode = 'asc', withCache = true } = args;
const { parentType = null, search, filters } = args;
const offset = after ? cursorToOffset(after) : 0;
const isRelationOrderBy = orderBy && includes('.', orderBy);
// Define if Elastic can support this query.
// 01-2 Check the filters
const validFilters = filter(f => f && f.values.filter(n => n).length > 0, filters || []);
const unSupportedRelations =
filter(k => {
// If the relation must be forced in a specific direction, ES cant support it.
if (k.fromRole || k.toRole) return true;
const isRelationFilter = includes('.', k.key);
if (isRelationFilter) {
// ES only support internal_id reference
const [, field] = k.key.split('.');
if (field !== 'internal_id_key') return true;
}
return false;
}, validFilters).length > 0;
// 01-3 Check the ordering
const unsupportedOrdering = isRelationOrderBy && last(orderBy.split('.')) !== 'internal_id_key';
const supportedByCache = !unsupportedOrdering && !unSupportedRelations;
if (!forceNoCache() && withCache && supportedByCache) {
const index = inferIndexFromConceptTypes(entityTypes, parentType);
return elPaginate(index, assoc('types', entityTypes, args));
}
logger.debug(`[GRAKN] ListEntities on Grakn, supportedByCache: ${supportedByCache} - withCache: ${withCache}`);
// 02. If not go with standard Grakn
const relationsFields = [];
const attributesFields = [];
const attributesFilters = [];
// Handle order by field
if (isRelationOrderBy) {
const [relation, field] = orderBy.split('.');
const curatedRelation = relation.replace(REL_INDEX_PREFIX, '');
relationsFields.push(
`($elem, $${curatedRelation}) isa ${curatedRelation}; $${curatedRelation} has ${field} $order;`
);
} else if (orderBy) {
attributesFields.push(`$elem has ${orderBy} $order;`);
}
// Handle filters
if (validFilters && validFilters.length > 0) {
for (let index = 0; index < validFilters.length; index += 1) {
const filterKey = validFilters[index].key;
const filterValues = validFilters[index].values;
const isRelationFilter = includes('.', filterKey);
if (isRelationFilter) {
const [relation, field] = filterKey.split('.');
const curatedRelation = relation.replace(REL_INDEX_PREFIX, '');
const sourceRole = validFilters[index].fromRole ? `${validFilters[index].fromRole}:` : '';
const toRole = validFilters[index].toRole ? `${validFilters[index].toRole}:` : '';
const relId = `rel_${curatedRelation}`;
relationsFields.push(`$${relId} (${sourceRole}$elem, ${toRole}$${curatedRelation}) isa ${curatedRelation};`);
for (let valueIndex = 0; valueIndex < filterValues.length; valueIndex += 1) {
const val = filterValues[valueIndex];
// Apply filter on target.
// TODO @Julien Support more than only string filters
attributesFields.push(`$${curatedRelation} has ${field} "${val}";`);
}
} else {
for (let valueIndex = 0; valueIndex < filterValues.length; valueIndex += 1) {
const val = filterValues[valueIndex];
attributesFields.push(`$elem has ${filterKey} "${escapeString(val)}";`);
}
}
}
}
// Handle special case of search
if (search) {
for (let searchIndex = 0; searchIndex < searchFields.length; searchIndex += 1) {
const searchFieldName = searchFields[searchIndex];
attributesFields.push(`$elem has ${searchFieldName} $${searchFieldName};`);
}
const searchFilter = pipe(
map(e => `{ $${e} contains "${escapeString(search)}"; }`),
join(' or ')
)(searchFields);
attributesFilters.push(`${searchFilter};`);
}
// build the final query
const queryAttributesFields = join(' ', attributesFields);
const queryAttributesFilters = join(' ', attributesFilters);
const queryRelationsFields = join(' ', relationsFields);
const headType = entityTypes.length === 1 ? head(entityTypes) : 'entity';
const extraTypes =
entityTypes.length > 1
? pipe(
map(e => `{ $elem isa ${e}; }`),
join(' or '),
concat(__, ';')
)(entityTypes)
: '';
const baseQuery = `match $elem isa ${headType}; ${extraTypes} ${queryRelationsFields}
${queryAttributesFields} ${queryAttributesFilters} get;`;
return listElements(baseQuery, first, offset, orderBy, orderMode, null, false);
};
export const listRelations = async (relationType, relationFilter, args) => {
const searchFields = ['name', 'description'];
const { first = 200, after, orderBy, orderMode = 'asc', withCache = true, inferred = false } = args;
const { search, fromRole, fromId, toRole, toId, fromTypes = [], toTypes = [] } = args;
const { firstSeenStart, firstSeenStop, lastSeenStart, lastSeenStop, weights = [] } = args;
const offset = after ? cursorToOffset(after) : 0;
const isRelationOrderBy = orderBy && includes('.', orderBy);
// Handle relation type(s)
const relationToGet = relationType || 'stix_relation';
// 0 - Check if we can support the query by Elastic
const unsupportedOrdering = isRelationOrderBy && last(orderBy.split('.')) !== 'internal_id_key';
const supportedByCache = !unsupportedOrdering && !relationFilter && !inferred;
const useCache = !forceNoCache() && withCache && supportedByCache;
if (useCache) {
const filters = [];
const relationsMap = new Map();
if (fromId) {
filters.push({ key: 'connections.internal_id_key', values: [fromId] });
relationsMap.set(fromId, { alias: 'from', internalIdKey: fromId });
}
if (toId) {
filters.push({ key: 'connections.internal_id_key', values: [toId] });
relationsMap.set(toId, { alias: 'to', internalIdKey: toId });
}
if (fromTypes && fromTypes.length > 0) filters.push({ key: 'connections.types', values: fromTypes });
if (toTypes && toTypes.length > 0) filters.push({ key: 'connections.types', values: toTypes });
if (firstSeenStart) filters.push({ key: 'first_seen', values: [firstSeenStart], operator: 'gt' });
if (firstSeenStop) filters.push({ key: 'first_seen', values: [firstSeenStop], operator: 'lt' });
if (lastSeenStart) filters.push({ key: 'last_seen', values: [lastSeenStart], operator: 'gt' });
if (lastSeenStop) filters.push({ key: 'last_seen', values: [lastSeenStop], operator: 'lt' });
if (lastSeenStop) filters.push({ key: 'last_seen', values: [lastSeenStop], operator: 'lt' });
if (weights && weights.length > 0) filters.push({ key: 'weight', values: [weights] });
const paginateArgs = pipe(
assoc('types', [relationToGet]),
assoc('filters', filters),
assoc('relationsMap', relationsMap)
)(args);
return elPaginate(INDEX_STIX_RELATIONS, paginateArgs);
}
// 1- If not, use Grakn
// eslint-disable-next-line prettier/prettier
const queryFromTypes = fromTypes && fromTypes.length > 0 ?
pipe(map(e => `{ $from isa ${e}; }`), join(' or '), concat(__, ';'))(fromTypes) : '';
// eslint-disable-next-line prettier/prettier
const queryToTypes = toTypes && toTypes.length > 0 ?
pipe(map(e => `{ $to isa ${e}; }`), join(' or '), concat(__, ';'))(toTypes) : '';
// Search
const relationsFields = [];
const attributesFields = [];
const attributesFilters = [];
// Handle order by field
if (isRelationOrderBy) {
const [relation, field] = orderBy.split('.');
const curatedRelation = relation.replace(REL_INDEX_PREFIX, '');
relationsFields.push(
`($rel, $${curatedRelation}) isa ${curatedRelation}; $${curatedRelation} has ${field} $order;`
);
} else if (orderBy) {
attributesFields.push(`$rel has ${orderBy} $order;`);
}
// Handle every filters
if (search) {
for (let searchIndex = 0; searchIndex < searchFields.length; searchIndex += 1) {
const searchFieldName = searchFields[searchIndex];
attributesFields.push(`$to has ${searchFieldName} $${searchFieldName};`);
}
const searchFilter = pipe(
map(e => `{ $${e} contains "${escapeString(search)}"; }`),
join(' or ')
)(searchFields);
attributesFilters.push(`${searchFilter};`);
}
if (fromId) attributesFilters.push(`$from has internal_id_key "${escapeString(fromId)}";`);
if (toId) attributesFilters.push(`$to has internal_id_key "${escapeString(toId)}";`);
if (firstSeenStart || firstSeenStop) {
attributesFields.push(`$rel has first_seen $fs;`);
if (firstSeenStart) attributesFilters.push(`$fs > ${prepareDate(firstSeenStart)};`);
if (firstSeenStop) attributesFilters.push(`$fs < ${prepareDate(firstSeenStop)};`);
}
if (lastSeenStart || lastSeenStop) {
attributesFields.push(`$rel has last_seen $ls;`);
if (lastSeenStart) attributesFilters.push(`$ls > ${prepareDate(lastSeenStart)};`);
if (lastSeenStop) attributesFilters.push(`$ls < ${prepareDate(lastSeenStop)};`);
}
if (weights && weights.length > 0) {
attributesFields.push(`$rel has weight $weight;`);
// eslint-disable-next-line prettier/prettier
attributesFilters.push(pipe(map(e => `{ $weight == ${e}; }`), join(' or '), concat(__, ';'))(weights));
}
const relationRef = relationFilter ? 'relationRef' : null;
if (relationFilter) {
// eslint-disable-next-line no-shadow
const { relation, fromRole, toRole, id } = relationFilter;
const pEid = escapeString(id);
const relationQueryPart = `$${relationRef}(${fromRole}:$rel,${toRole}:$pointer) isa ${relation}; $pointer has internal_id_key "${pEid}";`;
relationsFields.push(relationQueryPart);
}
// Build the query
const queryAttributesFields = join(' ', attributesFields);
const queryAttributesFilters = join(' ', attributesFilters);
const queryRelationsFields = join(' ', relationsFields);
const relFrom = fromRole ? `${fromRole}:` : '';
const relTo = toRole ? `${toRole}:` : '';
const baseQuery = `match $rel(${relFrom}$from, ${relTo}$to) isa ${relationToGet};
${queryFromTypes} ${queryToTypes}
${queryRelationsFields} ${queryAttributesFields} ${queryAttributesFilters} get;`;
return listElements(baseQuery, first, offset, orderBy, orderMode, relationRef, inferred);
};
// endregion
// region Loader element
export const load = async (query, entities, { infer, noCache } = findOpts) => {
const data = await find(query, entities, { infer, noCache });
return head(data);
};
export const loadEntityById = async (id, args = {}) => {
const { noCache = false } = args;
if (!noCache && !forceNoCache()) {
// [ELASTIC] From cache
const fromCache = await elLoadById(id);
if (fromCache) return fromCache;
}
const query = `match $x isa entity; $x has internal_id_key "${escapeString(id)}"; get;`;
const element = await load(query, ['x'], { noCache });
return element ? element.x : null;
};
export const loadEntityByStixId = async id => {
if (!forceNoCache()) {
// [ELASTIC] From cache
const fromCache = await elLoadByStixId(id);
if (fromCache) return fromCache;
}
const query = `match $x isa entity; $x has stix_id_key "${escapeString(id)}"; get;`;
const element = await load(query, ['x']);
return element ? element.x : null;
};
export const loadEntityByGraknId = async (graknId, args = {}) => {
const { noCache = false } = args;
if (!noCache && !forceNoCache()) {
// [ELASTIC] From cache
const fromCache = await elLoadByGraknId(graknId);
if (fromCache) return fromCache;
}
const query = `match $x isa entity; $x id ${escapeString(graknId)}; get;`;
const element = await load(query, ['x']);
return element.x;
};
export const loadRelationById = async (id, args = {}) => {
const { noCache = false } = args;
if (!noCache && !forceNoCache()) {
// [ELASTIC] From cache
const fromCache = await elLoadById(id);
if (fromCache) return fromCache;
}
const eid = escapeString(id);
const query = `match $rel($from, $to) isa relation; $rel has internal_id_key "${eid}"; get;`;
const element = await load(query, ['rel']);
return element ? element.rel : null;
};
export const loadRelationByStixId = async id => {
if (!forceNoCache()) {
// [ELASTIC] From cache
const fromCache = await elLoadByStixId(id);
if (fromCache) return fromCache;
}
const eid = escapeString(id);
const query = `match $rel($from, $to) isa relation; $rel has stix_id_key "${eid}"; get;`;
const element = await load(query, ['rel']);
return element ? element.rel : null;
};
export const loadRelationByGraknId = async (graknId, args = {}) => {
const { noCache = false } = args;
if (!noCache && !forceNoCache()) {
// [ELASTIC] From cache
const fromCache = await elLoadByGraknId(graknId);
if (fromCache) return fromCache;
}
const eid = escapeString(graknId);
const query = `match $rel($from, $to) isa relation; $rel id ${eid}; get;`;
const element = await load(query, ['rel']);
return element ? element.rel : null;
};
export const loadByGraknId = async (graknId, args = {}) => {
// Could be entity or relation.
const { noCache = false } = args;
if (!noCache && !forceNoCache()) {
// [ELASTIC] From cache - Already support the diff between entity and relation.
const fromCache = await elLoadByGraknId(graknId);
if (fromCache) return fromCache;
}
const entity = await loadEntityByGraknId(graknId, { noCache: true });
if (entity.base_type === 'relation') {
return loadRelationByGraknId(graknId, { noCache: true });
}
return entity;
};
// endregion
// region Indexer
const prepareIndexing = async elements => {
return Promise.all(
map(async thing => {
if (thing.relationship_type) {
if (thing.fromRole === undefined || thing.toRole === undefined) {
throw new Error(
`[ELASTIC] Cant index relation ${thing.grakn_id} connections without from (${thing.fromId}) or to (${thing.toId})`
);
}
const connections = [];
const [from, to] = await Promise.all([elLoadByGraknId(thing.fromId), elLoadByGraknId(thing.toId)]);
connections.push({
grakn_id: thing.fromId,
internal_id_key: from.internal_id_key,
types: thing.fromTypes,
role: thing.fromRole
});
connections.push({
grakn_id: thing.toId,
internal_id_key: to.internal_id_key,
types: thing.toTypes,
role: thing.toRole
});
return pipe(
assoc('connections', connections),
// Dissoc from
dissoc('from'),
dissoc('fromId'),
dissoc('fromTypes'),
dissoc('fromRole'),
// Dissoc to
dissoc('to'),
dissoc('toId'),
dissoc('toTypes'),
dissoc('toRole')
)(thing);
}
return thing;
}, elements)
);
};
export const indexElements = async (elements, retry = 2) => {
// 00. Relations must be transformed before indexing.
const transformedElements = await prepareIndexing(elements);
// 01. Bulk the indexing of row elements
const body = transformedElements.flatMap(doc => [
{ index: { _index: inferIndexFromConceptTypes(doc.parent_types), _id: doc.grakn_id } },
doc
]);
await elBulk({ refresh: true, body });
// 02. If relation, generate impacts for from and to sides
const impactedEntities = pipe(
filter(e => e.relationship_type !== undefined),
map(e => {
const { fromRole, toRole } = e;
const relationshipType = e.relationship_type;
const impacts = [];
// We impact target entities of the relation only if not global entities like
// MarkingDefinition (marking) / KillChainPhase (kill_chain_phase) / Tag (tagging)
if (!includes(fromRole, UNIMPACTED_ENTITIES_ROLE)) impacts.push({ from: e.fromId, relationshipType, to: e.toId });
if (!includes(toRole, UNIMPACTED_ENTITIES_ROLE)) impacts.push({ from: e.toId, relationshipType, to: e.fromId });
return impacts;
}),
flatten,
groupBy(i => i.from)
)(elements);
const elementsToUpdate = await Promise.all(
// For each from, generate the