-
Notifications
You must be signed in to change notification settings - Fork 118
Expand file tree
/
Copy pathdb.py
More file actions
2313 lines (2075 loc) · 82.3 KB
/
db.py
File metadata and controls
2313 lines (2075 loc) · 82.3 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
from sqlalchemy import CheckConstraint
import networkx as nx
import uuid
import neo4j
import os
import logging
import re
import yaml
from pprint import pprint
from collections import Counter
from itertools import permutations
from typing import Any, Dict, List, Optional, Tuple, cast
from neomodel.exceptions import (
DoesNotExist,
FeatureNotSupported,
NodeClassAlreadyDefined,
)
from flask import json as flask_json
from sqlalchemy.orm import aliased
from flask_sqlalchemy.model import DefaultMeta
from sqlalchemy import func, delete
from neomodel import (
config,
StructuredNode,
StringProperty,
UniqueIdProperty,
Relationship,
RelationshipTo,
RelationshipFrom,
ArrayProperty,
StructuredRel,
db,
)
from application.database import inmemory_graph
from application.utils import redis
from application.defs import cre_defs
from application.utils import file
from application.utils.gap_analysis import (
get_path_score,
make_resources_key,
make_subresources_key,
)
from .. import sqla # type: ignore
logging.basicConfig()
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
BaseModel: DefaultMeta = sqla.Model
def generate_uuid():
return str(uuid.uuid4())
class Node(BaseModel): # type: ignore
__tablename__ = "node"
id = sqla.Column(sqla.String, primary_key=True, default=generate_uuid)
# ASVS or standard name, what are we linking to
name = sqla.Column(sqla.String)
# which part of <name> are we linking to
section = sqla.Column(sqla.String, nullable=True)
# which subpart of <name> are we linking to
subsection = sqla.Column(sqla.String)
# coma separated tags
tags = sqla.Column(sqla.String)
version = sqla.Column(sqla.String)
description = sqla.Column(sqla.String)
ntype = sqla.Column(sqla.String)
section_id = sqla.Column(sqla.String, nullable=True)
# some external link to where this is, usually a URL with an anchor
link = sqla.Column(sqla.String, default="")
__table_args__ = (
sqla.UniqueConstraint(
name,
section,
subsection,
version,
section_id,
name="uq_node",
),
)
class CRE(BaseModel): # type: ignore
__tablename__ = "cre"
id = sqla.Column(sqla.String, primary_key=True, default=generate_uuid)
external_id = sqla.Column(sqla.String, default="")
description = sqla.Column(sqla.String, default="")
name = sqla.Column(sqla.String)
tags = sqla.Column(sqla.String, default="") # coma separated tags
__table_args__ = (
sqla.UniqueConstraint(name, external_id, name="unique_cre_fields"),
)
class InternalLinks(BaseModel): # type: ignore
# model cre-groups linking cres
__tablename__ = "cre_links"
type = sqla.Column(sqla.String)
group = sqla.Column(
sqla.String,
sqla.ForeignKey("cre.id", onupdate="CASCADE", ondelete="CASCADE"),
primary_key=True,
)
cre = sqla.Column(
sqla.String,
sqla.ForeignKey("cre.id", onupdate="CASCADE", ondelete="CASCADE"),
primary_key=True,
)
__table_args__ = (
sqla.UniqueConstraint(
group,
cre,
name="uq_pair",
),
sqla.CheckConstraint("type != 'PartOf'", name="No 'PartOf' links"),
)
class Links(BaseModel): # type: ignore
__tablename__ = "cre_node_links"
type = sqla.Column(sqla.String)
cre = sqla.Column(
sqla.String,
sqla.ForeignKey("cre.id", onupdate="CASCADE", ondelete="CASCADE"),
primary_key=True,
)
node = sqla.Column(
sqla.String,
sqla.ForeignKey("node.id", onupdate="CASCADE", ondelete="CASCADE"),
primary_key=True,
)
__table_args__ = (
sqla.UniqueConstraint(
cre,
node,
name="uq_pair",
),
)
class Embeddings(BaseModel): # type: ignore
__tablename__ = "embeddings"
embeddings = sqla.Column(sqla.String)
doc_type = sqla.Column(sqla.String)
cre_id = sqla.Column(
sqla.String,
sqla.ForeignKey("cre.id", onupdate="CASCADE", ondelete="CASCADE"),
default="",
)
node_id = sqla.Column(
sqla.String,
sqla.ForeignKey("node.id", onupdate="CASCADE", ondelete="CASCADE"),
default="",
)
embeddings_url = sqla.Column(sqla.String, default="")
embeddings_content = sqla.Column(sqla.String, default="")
__table_args__ = (
sqla.PrimaryKeyConstraint(
embeddings,
doc_type,
cre_id,
node_id,
name="uq_entry",
),
)
class GapAnalysisResults(BaseModel):
__tablename__ = "gap_analysis_results"
cache_key = sqla.Column(sqla.String, primary_key=True)
ga_object = sqla.Column(sqla.String)
__table_args__ = (sqla.UniqueConstraint(cache_key, name="unique_cache_key_field"),)
class RelatedRel(StructuredRel):
pass
class ContainsRel(StructuredRel):
pass
class AutoLinkedToRel(StructuredRel):
pass
class LinkedToRel(StructuredRel):
pass
class SameRel(StructuredRel):
pass
class NeoDocument(StructuredNode):
document_id = UniqueIdProperty()
name = StringProperty(required=True)
description = StringProperty(required=True)
tags = ArrayProperty(StringProperty())
doctype = StringProperty(required=True)
related = Relationship("NeoDocument", "RELATED", model=RelatedRel)
@classmethod
def to_cre_def(self, node, parse_links=True):
raise Exception(f"Shouldn't be parsing a NeoDocument")
@classmethod
def get_links(self, links_dict):
links = []
for key in links_dict:
links.extend(
[
cre_defs.Link(c.to_cre_def(c, parse_links=False), key)
for c in links_dict[key]
]
)
return links
class NeoNode(NeoDocument):
doctype = StringProperty()
version = StringProperty(required=True)
hyperlink = StringProperty()
@classmethod
def to_cre_def(self, node, parse_links=True):
raise Exception(f"Shouldn't be parsing a NeoNode")
class NeoStandard(NeoNode):
section = StringProperty()
subsection = StringProperty()
section_id = StringProperty()
@classmethod
def to_cre_def(self, node, parse_links=True) -> cre_defs.Standard:
return cre_defs.Standard(
name=node.name,
description=node.description,
tags=node.tags,
hyperlink=node.hyperlink,
version=node.version,
section=node.section,
sectionID=node.section_id,
subsection=node.subsection,
links=(
self.get_links(
{
"Related": node.related,
}
)
if parse_links
else []
),
)
class NeoTool(NeoStandard):
tooltype = StringProperty(required=True)
@classmethod
def to_cre_def(self, node, parse_links=True) -> cre_defs.Tool:
return cre_defs.Tool(
tooltype=node.tooltype,
name=node.name,
description=node.description,
tags=node.tags,
hyperlink=node.hyperlink,
version=node.version,
section=node.section,
sectionID=node.section_id,
subsection=node.subsection,
links=(
self.get_links(
{
"Related": node.related,
}
)
if parse_links
else []
),
)
class NeoCode(NeoNode):
@classmethod
def to_cre_def(self, node, parse_links=True) -> cre_defs.Code:
return cre_defs.Code(
name=node.name,
description=node.description,
tags=node.tags,
hyperlink=node.hyperlink,
version=node.version,
links=(
self.get_links(
{
"Related": node.related,
}
)
if parse_links
else []
),
)
class NeoCRE(NeoDocument): # type: ignore
external_id = StringProperty()
contains = RelationshipTo("NeoCRE", "CONTAINS", model=ContainsRel)
contained_in = RelationshipFrom("NeoCRE", "CONTAINS", model=ContainsRel)
linked = RelationshipTo("NeoStandard", "LINKED_TO", model=LinkedToRel)
auto_linked_to = RelationshipTo(
"NeoStandard", "AUTOMATICALLY_LINKED_TO", model=AutoLinkedToRel
)
@classmethod
def to_cre_def(self, node, parse_links=True) -> cre_defs.CRE:
return cre_defs.CRE(
name=node.name,
id=node.external_id,
description=node.description,
tags=node.tags,
links=(
self.get_links(
{
"Contains": [*node.contains, *node.contained_in],
"Linked To": node.linked,
"Same as": node.same_as,
"Related": node.related,
"Automatically linked to": node.auto_linked_to,
}
)
if parse_links
else []
),
)
class NEO_DB:
__instance = None
driver = None
connected = False
@classmethod
def instance(self):
if self.__instance is None:
self.__instance = self.__new__(self)
config.DATABASE_URL = (
os.getenv("NEO4J_URL") or "neo4j://neo4j:password@localhost:7687"
)
return self.__instance
def __init__(sel):
raise ValueError("NEO_DB is a singleton, please call instance() instead")
@classmethod
def populate_DB(self, session):
for il in session.query(InternalLinks).all():
group = session.query(CRE).filter(CRE.id == il.group).first()
if not group:
logger.error(f"CRE {il.group} does not exist?")
self.add_cre(group)
cre = session.query(CRE).filter(CRE.id == il.cre).first()
if not cre:
logger.error(f"CRE {il.cre} does not exist?")
self.add_cre(cre)
self.link_CRE_to_CRE(il.group, il.cre, il.type)
for lnk in session.query(Links).all():
node = session.query(Node).filter(Node.id == lnk.node).first()
if not node:
logger.error(f"Node {lnk.node} does not exist?")
continue
self.add_dbnode(node)
cre = session.query(CRE).filter(CRE.id == lnk.cre).first()
self.add_cre(cre)
self.link_CRE_to_Node(lnk.cre, lnk.node, lnk.type)
@classmethod
def add_cre(self, dbcre: CRE):
document = NeoCRE.nodes.first_or_none(document_id=dbcre.id)
if not document:
return NeoCRE(
name=dbcre.name,
doctype=cre_defs.Credoctypes.CRE.value, # dbcre.ntype,
document_id=dbcre.id,
description=dbcre.description,
links=[], # dbcre.links,
tags=[dbcre.tags] if isinstance(dbcre.tags, str) else dbcre.tags,
external_id=dbcre.external_id,
).save()
document.name = dbcre.name
document.doctype = (cre_defs.Credoctypes.CRE.value,)
document.document_id = dbcre.id
document.description = dbcre.description or ""
document.tags = [dbcre.tags] if isinstance(dbcre.tags, str) else dbcre.tags
document.metadata = {}
document.external_id = dbcre.external_id or ""
return document.save()
def __create_dbnode(dbnode: Node):
if dbnode.ntype == "Standard":
return NeoStandard(
name=dbnode.name,
doctype=dbnode.ntype,
document_id=dbnode.id,
description=dbnode.description or "",
tags=[dbnode.tags] if isinstance(dbnode.tags, str) else dbnode.tags,
metadata={},
version=dbnode.version or "",
section=dbnode.section,
section_id=dbnode.section_id, # dbnode.sectionID,
subsection=dbnode.subsection or "",
tooltype="", # dbnode.tooltype,
).save()
elif dbnode.ntype == "Code":
return NeoCode(
name=dbnode.name,
doctype=dbnode.ntype,
document_id=dbnode.id,
description=dbnode.description,
links=[], # dbnode.links,
tags=([dbnode.tags] if isinstance(dbnode.tags, str) else dbnode.tags),
metadata="{}", # dbnode.metadata,
hyperlink="", # dbnode.hyperlink or "",
version=dbnode.version or "",
).save()
elif dbnode.ntype == "Tool":
ttype = [tag for tag in dbnode.tags if tag in cre_defs.ToolTypes]
if ttype:
ttype = ttype[0]
else:
ttype = cre_defs.ToolTypes.Unknown
return NeoTool(
tooltype=ttype,
name=dbnode.name,
doctype=dbnode.ntype,
document_id=dbnode.id,
description=dbnode.description,
links=[], # dbnode.links,
tags=([dbnode.tags] if isinstance(dbnode.tags, str) else dbnode.tags),
metadata="{}", # dbnode.metadata,
hyperlink="", # dbnode.hyperlink or "",
version=dbnode.version or "",
).save()
def __update_dbnode(dbnode: Node):
existing = NeoNode.nodes.first_or_none(document_id=dbnode.id)
if dbnode.ntype == "Standard":
existing.name = dbnode.name
existing.doctype = dbnode.ntype
existing.document_id = dbnode.id
existing.description = dbnode.description or ""
existing.tags = (
[dbnode.tags] if isinstance(dbnode.tags, str) else dbnode.tags
)
existing.metadata = {}
existing.version = dbnode.version or ""
existing.section = dbnode.section
existing.section_id = dbnode.section_id # dbnode.sectionID
existing.subsection = dbnode.subsection or ""
existing.tooltype = "" # dbnode.tooltype
return existing.save()
elif dbnode.ntype == "Code":
existing.name = dbnode.name
existing.doctype = dbnode.ntype
existing.document_id = dbnode.id
existing.description = dbnode.description
existing.links = [] # dbnode.links
existing.tags = (
[dbnode.tags] if isinstance(dbnode.tags, str) else dbnode.tags
)
existing.metadata = "{}" # dbnode.metadata,
existing.hyperlink = "" # dbnode.hyperlink or "",
existing.version = dbnode.version or ""
return existing.save()
elif dbnode.ntype == "Tool":
existing.name = dbnode.name
existing.doctype = dbnode.ntype
existing.document_id = dbnode.id
existing.description = dbnode.description
existing.links = [] # dbnode.links
existing.tags = (
[dbnode.tags] if isinstance(dbnode.tags, str) else dbnode.tags
)
ttype = [tag for tag in dbnode.tags if tag in cre_defs.ToolTypes]
if ttype:
ttype = ttype[0]
else:
ttype = cre_defs.ToolTypes.Unknown
existing.tooltype = ttype
existing.metadata = "{}" # dbnode.metadata,
existing.hyperlink = "" # dbnode.hyperlink or "",
existing.version = dbnode.version or ""
return existing.save()
else:
raise Exception(f"Unknown DB type: {dbnode.ntype}")
@classmethod
@db.transaction
def add_dbnode(self, dbnode: Node):
document = NeoNode.nodes.first_or_none(document_id=dbnode.id)
if document:
return self.__update_dbnode(dbnode)
return self.__create_dbnode(dbnode)
@classmethod
def link_CRE_to_CRE(self, id1, id2, link_type):
cre1 = NeoCRE.nodes.get(document_id=id1)
cre2 = NeoCRE.nodes.get(document_id=id2)
if link_type == cre_defs.LinkTypes.Contains.value:
cre1.contains.connect(cre2)
return
if link_type == cre_defs.LinkTypes.Related.value:
cre1.related.connect(cre2)
return
if link_type == cre_defs.LinkTypes.PartOf.value:
cre2.contains.connect(cre1)
return
raise Exception(f"Unknown relation type {link_type}")
@classmethod
def link_CRE_to_Node(self, CRE_id, node_id, link_type):
cre = NeoCRE.nodes.first_or_none(document_id=CRE_id)
node = NeoNode.nodes.first_or_none(document_id=node_id)
if not node:
return
if link_type == cre_defs.LinkTypes.AutomaticallyLinkedTo.value:
cre.auto_linked_to.connect(node)
return
elif link_type == cre_defs.LinkTypes.LinkedTo.value:
cre.linked.connect(node)
return
raise Exception(f"Unknown relation type {link_type} for Nodes to CREs")
@classmethod
def gap_analysis(self, name_1, name_2):
"""
Gap analysis with feature toggle support.
Toggle between original exhaustive traversal (default) and
optimized tiered pruning (opt-in via GAP_ANALYSIS_OPTIMIZED env var).
"""
from application.config import Config
if Config.GAP_ANALYSIS_OPTIMIZED:
logger.info(
f"Gap Analysis: Using OPTIMIZED tiered pruning for {name_1}>>{name_2}"
)
return self._gap_analysis_optimized(name_1, name_2)
else:
logger.info(
f"Gap Analysis: Using ORIGINAL exhaustive traversal for {name_1}>>{name_2}"
)
return self._gap_analysis_original(name_1, name_2)
@classmethod
def _gap_analysis_optimized(self, name_1, name_2):
"""
OPTIMIZED: Tiered Pruning Strategy with Early Exit
Tier 1: Strong links only (LINKED_TO, SAME, AUTOMATICALLY_LINKED_TO)
Tier 2: Add hierarchical (CONTAINS) if Tier 1 empty
Tier 3: Fallback to wildcard if both tiers empty
"""
logger.info(
f"Performing OPTIMIZED GraphDB queries for gap analysis {name_1}>>{name_2}"
)
base_standard = NeoStandard.nodes.filter(name=name_1)
denylist = ["Cross-cutting concerns"]
# Tier 1: Strong Links (LINKED_TO, SAME, AUTOMATICALLY_LINKED_TO)
path_records, _ = db.cypher_query(
"""
MATCH (BaseStandard:NeoStandard {name: $name1})
MATCH (CompareStandard:NeoStandard {name: $name2})
MATCH p = allShortestPaths((BaseStandard)-[:(LINKED_TO|AUTOMATICALLY_LINKED_TO|SAME)*..20]-(CompareStandard))
WITH p
WHERE length(p) > 1 AND ALL(n in NODES(p) WHERE (n:NeoCRE or n = BaseStandard or n = CompareStandard) AND NOT n.name in $denylist)
RETURN p
""",
{"name1": name_1, "name2": name_2, "denylist": denylist},
resolve_objects=True,
)
# If strict strong links found, return early (Pruning)
if path_records and len(path_records) > 0:
logger.info(
f"Gap Analysis: Tier 1 (Strong) found {len(path_records)} paths. Pruning remainder."
)
return self._format_gap_analysis_response(base_standard, path_records)
# Tier 2: Medium Links (Add CONTAINS to the mix)
path_records, _ = db.cypher_query(
"""
MATCH (BaseStandard:NeoStandard {name: $name1})
MATCH (CompareStandard:NeoStandard {name: $name2})
MATCH p = allShortestPaths((BaseStandard)-[:(LINKED_TO|AUTOMATICALLY_LINKED_TO|SAME|CONTAINS)*..20]-(CompareStandard))
WITH p
WHERE length(p) > 1 AND ALL(n in NODES(p) WHERE (n:NeoCRE or n = BaseStandard or n = CompareStandard) AND NOT n.name in $denylist)
RETURN p
""",
{"name1": name_1, "name2": name_2, "denylist": denylist},
resolve_objects=True,
)
if path_records and len(path_records) > 0:
logger.info(
f"Gap Analysis: Tier 2 (Medium) found {len(path_records)} paths. Pruning remainder."
)
return self._format_gap_analysis_response(base_standard, path_records)
# Tier 3: Weak/All Links (Wildcard - The original expensive query)
logger.info(
"Gap Analysis: Tiers 1 & 2 empty. Executing Tier 3 (Wildcard search)."
)
path_records_all, _ = db.cypher_query(
"""
MATCH (BaseStandard:NeoStandard {name: $name1})
MATCH (CompareStandard:NeoStandard {name: $name2})
MATCH p = allShortestPaths((BaseStandard)-[*..20]-(CompareStandard))
WITH p
WHERE length(p) > 1 AND ALL (n in NODES(p) where (n:NeoCRE or n = BaseStandard or n = CompareStandard) AND NOT n.name in $denylist)
RETURN p
""",
{"name1": name_1, "name2": name_2, "denylist": denylist},
resolve_objects=True,
)
return self._format_gap_analysis_response(base_standard, path_records_all)
@classmethod
def _gap_analysis_original(self, name_1, name_2):
"""
ORIGINAL: Exhaustive traversal (always runs both queries)
This is the safe default - maintains backward compatibility.
"""
logger.info(
f"Performing ORIGINAL GraphDB queries for gap analysis {name_1}>>{name_2}"
)
base_standard = NeoStandard.nodes.filter(name=name_1)
denylist = ["Cross-cutting concerns"]
from datetime import datetime
# Query 1: Wildcard (all relationships)
path_records_all, _ = db.cypher_query(
"""
MATCH (BaseStandard:NeoStandard {name: $name1})
MATCH (CompareStandard:NeoStandard {name: $name2})
MATCH p = allShortestPaths((BaseStandard)-[*..20]-(CompareStandard))
WITH p
WHERE length(p) > 1 AND ALL (n in NODES(p) where (n:NeoCRE or n = BaseStandard or n = CompareStandard) AND NOT n.name in $denylist)
RETURN p
""",
{"name1": name_1, "name2": name_2, "denylist": denylist},
resolve_objects=True,
)
# Query 2: Filtered (LINKED_TO, AUTOMATICALLY_LINKED_TO, CONTAINS)
path_records, _ = db.cypher_query(
"""
MATCH (BaseStandard:NeoStandard {name: $name1})
MATCH (CompareStandard:NeoStandard {name: $name2})
MATCH p = allShortestPaths((BaseStandard)-[:(LINKED_TO|AUTOMATICALLY_LINKED_TO|CONTAINS)*..20]-(CompareStandard))
WITH p
WHERE length(p) > 1 AND ALL(n in NODES(p) WHERE (n:NeoCRE or n = BaseStandard or n = CompareStandard) AND NOT n.name in $denylist)
RETURN p
""",
{"name1": name_1, "name2": name_2, "denylist": denylist},
resolve_objects=True,
)
# Combine results (original behavior)
def format_segment(seg: StructuredRel, nodes):
relation_map = {
RelatedRel: "RELATED",
ContainsRel: "CONTAINS",
LinkedToRel: "LINKED_TO",
AutoLinkedToRel: "AUTOMATICALLY_LINKED_TO",
}
start_node = [
node for node in nodes if node.element_id == seg._start_node_element_id
][0]
end_node = [
node for node in nodes if node.element_id == seg._end_node_element_id
][0]
return {
"start": NEO_DB.parse_node_no_links(start_node),
"end": NEO_DB.parse_node_no_links(end_node),
"relationship": relation_map[type(seg)],
}
def format_path_record(rec):
return {
"start": NEO_DB.parse_node_no_links(rec.start_node),
"end": NEO_DB.parse_node_no_links(rec.end_node),
"path": [format_segment(seg, rec.nodes) for seg in rec.relationships],
}
return [NEO_DB.parse_node_no_links(rec) for rec in base_standard], [
format_path_record(rec[0]) for rec in (path_records + path_records_all)
]
def gap_analysis(self, name_1, name_2):
logger.info(f"Performing GraphDB queries for gap analysis {name_1}>>{name_2}")
base_standard = NeoStandard.nodes.filter(name=name_1)
denylist = ["Cross-cutting concerns"]
from datetime import datetime
# Tier 1: Strong Links (LINKED_TO, SAME, AUTOMATICALLY_LINKED_TO)
path_records, _ = db.cypher_query(
"""
MATCH (BaseStandard:NeoStandard {name: $name1})
MATCH (CompareStandard:NeoStandard {name: $name2})
MATCH p = allShortestPaths((BaseStandard)-[:(LINKED_TO|AUTOMATICALLY_LINKED_TO|SAME)*..20]-(CompareStandard))
WITH p
WHERE length(p) > 1 AND ALL(n in NODES(p) WHERE (n:NeoCRE or n = BaseStandard or n = CompareStandard) AND NOT n.name in $denylist)
RETURN p
""",
{"name1": name_1, "name2": name_2, "denylist": denylist},
resolve_objects=True,
)
# If strict strong links found, return early (Pruning)
if path_records and len(path_records) > 0:
logger.info(
f"Gap Analysis: Tier 1 (Strong) found {len(path_records)} paths. Pruning remainder."
)
# Helper to format and return
return self._format_gap_analysis_response(base_standard, path_records)
# Tier 2: Medium Links (Add CONTAINS to the mix)
path_records, _ = db.cypher_query(
"""
MATCH (BaseStandard:NeoStandard {name: $name1})
MATCH (CompareStandard:NeoStandard {name: $name2})
MATCH p = allShortestPaths((BaseStandard)-[:(LINKED_TO|AUTOMATICALLY_LINKED_TO|SAME|CONTAINS)*..20]-(CompareStandard))
WITH p
WHERE length(p) > 1 AND ALL(n in NODES(p) WHERE (n:NeoCRE or n = BaseStandard or n = CompareStandard) AND NOT n.name in $denylist)
RETURN p
""",
{"name1": name_1, "name2": name_2, "denylist": denylist},
resolve_objects=True,
)
if path_records and len(path_records) > 0:
logger.info(
f"Gap Analysis: Tier 2 (Medium) found {len(path_records)} paths. Pruning remainder."
)
return self._format_gap_analysis_response(base_standard, path_records)
# Tier 3: Weak/All Links (Wildcard - The original expensive query)
logger.info(
"Gap Analysis: Tiers 1 & 2 empty. Executing Tier 3 (Wildcard search)."
)
path_records_all, _ = db.cypher_query(
"""
MATCH (BaseStandard:NeoStandard {name: $name1})
MATCH (CompareStandard:NeoStandard {name: $name2})
MATCH p = allShortestPaths((BaseStandard)-[*..20]-(CompareStandard))
WITH p
WHERE length(p) > 1 AND ALL (n in NODES(p) where (n:NeoCRE or n = BaseStandard or n = CompareStandard) AND NOT n.name in $denylist)
RETURN p
""",
{"name1": name_1, "name2": name_2, "denylist": denylist},
resolve_objects=True,
)
return self._format_gap_analysis_response(base_standard, path_records_all)
@classmethod
def _format_gap_analysis_response(self, base_standard, path_records):
def format_segment(seg: StructuredRel, nodes):
relation_map = {
RelatedRel: "RELATED",
ContainsRel: "CONTAINS",
LinkedToRel: "LINKED_TO",
AutoLinkedToRel: "AUTOMATICALLY_LINKED_TO",
SameRel: "SAME",
}
start_node = [
node for node in nodes if node.element_id == seg._start_node_element_id
][0]
end_node = [
node for node in nodes if node.element_id == seg._end_node_element_id
][0]
# Default to RELATED if relation unknown (though mostly governed by class type)
rtype = relation_map.get(type(seg), "RELATED")
return {
"start": NEO_DB.parse_node_no_links(start_node),
"end": NEO_DB.parse_node_no_links(end_node),
"relationship": rtype,
}
def format_path_record(rec):
return {
"start": NEO_DB.parse_node_no_links(rec.start_node),
"end": NEO_DB.parse_node_no_links(rec.end_node),
"path": [format_segment(seg, rec.nodes) for seg in rec.relationships],
}
return [NEO_DB.parse_node_no_links(rec) for rec in base_standard], [
format_path_record(rec[0]) for rec in path_records
]
@classmethod
def standards(self) -> List[str]:
results = []
for x in db.cypher_query("""MATCH (n:NeoTool) RETURN DISTINCT n.name""")[0]:
results.extend(x)
for x in db.cypher_query("""MATCH (n:NeoStandard) RETURN DISTINCT n.name""")[0]:
results.extend(x)
return list(set(results))
@classmethod
def everything(self) -> List[str]:
try:
return [NEO_DB.parse_node(rec) for rec in NeoDocument.nodes.all()]
except neo4j.exceptions.ServiceUnavailable:
logger.error("Neo4j DB offline")
return None
@staticmethod
def parse_node(node: NeoDocument) -> cre_defs.Document:
return node.to_cre_def(node)
@staticmethod
def parse_node_no_links(node: NeoDocument) -> cre_defs.Document:
return node.to_cre_def(node, parse_links=False)
class Node_collection:
graph: inmemory_graph.CRE_Graph = None
neo_db: NEO_DB = None
session = sqla.session
def __init__(self) -> None:
if not os.environ.get("NO_LOAD_GRAPH_DB"):
self.neo_db = NEO_DB.instance()
self.session = sqla.session
def with_graph(self) -> "Node_collection":
if self.graph is not None:
logger.debug("CRE graph already loaded, skipping reload")
return self
logger.info("Loading CRE graph in memory, memory-heavy operation!")
self.graph = inmemory_graph.CRE_Graph()
graph_singleton = inmemory_graph.Singleton_Graph_Storage.instance()
self.graph.with_graph(
graph=graph_singleton,
graph_data=self.__get_all_nodes_and_cres(cres_only=True),
)
logger.info("Successfully loaded CRE graph in memory")
return self
def __get_external_links(self) -> List[Tuple[CRE, Node, str]]:
external_links: List[Tuple[CRE, Node, str]] = []
all_links = self.session.query(Links).all()
for link in all_links:
cre = self.session.query(CRE).filter(CRE.id == link.cre).first()
node: Node = self.session.query(Node).filter(Node.id == link.node).first()
external_links.append((cre, node, link.type))
return external_links
def __get_internal_links(self) -> List[Tuple[CRE, CRE, str]]:
internal_links = []
all_internal_links = self.session.query(InternalLinks).all()
for il in all_internal_links:
group = self.session.query(CRE).filter(CRE.id == il.group).first()
cre = self.session.query(CRE).filter(CRE.id == il.cre).first()
internal_links.append((group, cre, il.type))
return internal_links
def __get_unlinked_nodes(self) -> List[Node]:
linked_nodes = (
self.session.query(Node.id).join(Links).filter(Node.id == Links.node)
)
nodes: List[Node] = (
self.session.query(Node).filter(Node.id.notin_(linked_nodes)).all()
)
return nodes
def __get_unlinked_cres(self) -> List[CRE]:
internally_linked_cres = self.session.query(CRE.id).join(
InternalLinks,
sqla.or_(InternalLinks.group == CRE.id, InternalLinks.cre == CRE.id),
)
externally_linked_cres = (
self.session.query(CRE.id).join(Links).filter(Links.cre == CRE.id)
)
cres = (
self.session.query(CRE)
.filter(
CRE.id.notin_(internally_linked_cres),
CRE.id.notin_(externally_linked_cres),
)
.all()
)
return cres
def __get_all_nodes_and_cres(
self, cres_only: bool = False
) -> List[cre_defs.Document]:
result = []
nodes = []
cres = []
if not cres_only:
node_ids = self.session.query(Node.id).all()
for nid in node_ids:
result.extend(self.get_nodes(db_id=nid[0]))
cre_ids = self.session.query(CRE.id).all()
for cid in cre_ids:
result.append(self.get_cre_by_db_id(cid[0]))
return result
@classmethod
def object_select(cls, node: Node, skip_attributes: List = []) -> List[Node]:
if not node:
return []
qu = Node.query.filter()
for vk, v in vars(node).items():
if vk not in skip_attributes and hasattr(Node, vk):
if v:
attr = getattr(Node, vk)
qu = qu.filter(attr == v)
else:
logger.debug(f"{vk} not in Node")
return qu.all()
def get_node_names(
self, ntype: str = cre_defs.Standard.__name__
) -> List[Tuple[str, str]]:
q = self.session.query(Node.ntype, Node.name).distinct().all()
if q:
return [i for i in q]
return []
def get_max_internal_connections(self) -> int:
q = self.session.query(InternalLinks).all()
grp_count = Counter([x.group for x in q]) or {0: 0}
cre_count = Counter([x.cre for x in q]) or {0: 0}
return max([max(cre_count.values()), max(grp_count.values())])
def find_cres_of_cre(self, cre: CRE) -> Optional[List[CRE]]:
"""returns the higher level CREs of the cre or none
if no higher level cres link to it"""
cre_id = self.session.query(CRE.id).filter(CRE.name == cre.name).first()
links = (
self.session.query(InternalLinks).filter(InternalLinks.cre == cre_id).all()
)
if links:
result = []
for link in links:
result.append(
self.session.query(CRE).filter(CRE.id == link.group).first()
)
return result
return None
def find_cres_of_node(self, node: cre_defs.Node) -> Optional[List[CRE]]:
"""returns the CREs that link to this node or none
if none link to it"""