forked from amundsen-io/amundsen
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gremlin_proxy.py
1784 lines (1495 loc) · 80.2 KB
/
gremlin_proxy.py
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
# Copyright Contributors to the Amundsen project.
# SPDX-License-Identifier: Apache-2.0
import collections
import json
import logging
from abc import abstractmethod
from datetime import date, datetime, timedelta
from operator import attrgetter
from typing import (Any, Callable, Dict, Iterable, List, Mapping, Optional,
Sequence, Set, Tuple, Type, TypeVar, Union, no_type_check,
overload)
from urllib.parse import unquote
import gremlin_python
from amundsen_common.models.dashboard import DashboardSummary
from amundsen_common.models.lineage import Lineage
from amundsen_common.models.popular_table import PopularTable
from amundsen_common.models.table import (Application, Column,
ProgrammaticDescription, Reader,
Source, Stat, Table, Tag, Watermark)
from amundsen_common.models.user import User
from amundsen_gremlin.gremlin_model import (EdgeType, EdgeTypes, VertexType,
VertexTypes, WellKnownProperties)
from amundsen_gremlin.gremlin_shared import \
append_traversal as _append_traversal # TODO: rename the references
from amundsen_gremlin.gremlin_shared import (make_column_uri,
make_description_uri)
from amundsen_gremlin.neptune_bulk_loader.gremlin_model_converter import \
ensure_vertex_type
from amundsen_gremlin.script_translator import (
ScriptTranslator, ScriptTranslatorTargetJanusgraph)
from amundsen_gremlin.test_and_development_shard import get_shard
from gremlin_python.driver.client import Client
from gremlin_python.driver.driver_remote_connection import \
DriverRemoteConnection
from gremlin_python.driver.resultset import ResultSet
from gremlin_python.process.anonymous_traversal import traversal
from gremlin_python.process.graph_traversal import (GraphTraversal,
GraphTraversalSource, V,
__, bothV, coalesce,
constant, has, inE, inV,
outE, outV, select, unfold,
valueMap, values)
from gremlin_python.process.traversal import Cardinality
from gremlin_python.process.traversal import Column as MapColumn
from gremlin_python.process.traversal import (Direction, Order, P, T, TextP,
Traversal, gte, not_, within,
without)
from neptune_python_utils.gremlin_utils import ExtendedGraphSONSerializersV3d0
from overrides import overrides
from tornado import httpclient
from typing_extensions import Protocol # TODO: it's in typing 3.8
from metadata_service.entity.dashboard_detail import \
DashboardDetail as DashboardDetailEntity
from metadata_service.entity.description import Description
from metadata_service.entity.resource_type import ResourceType
from metadata_service.entity.tag_detail import TagDetail
from metadata_service.exception import NotFoundException
from metadata_service.proxy.statsd_utilities import timer_with_counter
from metadata_service.util import UserResourceRel
from .base_proxy import BaseProxy
from .shared import checkNotNone, retrying
# don't use statics.load_statics(globals()) it plays badly with mypy
__all__ = ['AbstractGremlinProxy', 'GenericGremlinProxy']
LOGGER = logging.getLogger(__name__)
PUBLISH_TAG_TIME_FORMAT: str = "%Y-%m-%d %H:%M"
AMUNDSEN_TIMESTAMP_KEY: str = 'amundsen_updated_timestamp'
def timestamp() -> datetime:
"""
mostly for mocking
See also https://docs.aws.amazon.com/neptune/latest/userguide/best-practices-gremlin-datetime-glv.html
and DateIO in gremlin python
"""
return datetime.now()
def is_reasonable_vertex_label(label: str) -> bool:
vertex_labels = set([each.value.label for each in VertexTypes])
return label in vertex_labels
def get_label_from(_entity_type_or_enum_or_str: Union[str, VertexTypes, EdgeTypes, VertexType, EdgeType]) -> str:
if isinstance(_entity_type_or_enum_or_str, str):
return _entity_type_or_enum_or_str
elif isinstance(_entity_type_or_enum_or_str, (VertexTypes, EdgeTypes)):
return _entity_type_or_enum_or_str.value.label
elif isinstance(_entity_type_or_enum_or_str, (VertexType, EdgeType)):
return _entity_type_or_enum_or_str.label
else:
raise RuntimeError(f'what the heck is label? {type(_entity_type_or_enum_or_str)} {_entity_type_or_enum_or_str}')
def get_cardinality_for(_entity_type_or_enum: Union[VertexTypes, EdgeTypes, VertexType, EdgeType],
name: str) -> Optional[Cardinality]:
_entity_type: Union[VertexType, EdgeType]
if isinstance(_entity_type_or_enum, (VertexTypes, EdgeTypes)):
_entity_type = _entity_type_or_enum.value
elif isinstance(_entity_type_or_enum, (VertexType, EdgeType)):
_entity_type = _entity_type_or_enum
else:
raise AssertionError(f'thing is not a VertexType(s) or EdgeType(s): {_entity_type_or_enum}')
properties = _entity_type.properties_as_map()
# TODO: this will expose missing properties
if name not in properties:
raise AssertionError(f'missing {name} property in {_entity_type_or_enum} {properties}')
maybe = properties[name].cardinality
if isinstance(_entity_type, VertexType):
return maybe.value if maybe is not None else Cardinality.single
elif isinstance(_entity_type, EdgeType):
return maybe.value if maybe is not None else None
else:
raise AssertionError(f'thing is not a VertexType(s) or EdgeType(s): {_entity_type_or_enum}')
class FromResultSet:
@classmethod
def generator(cls, result_set: ResultSet) -> Iterable[Any]:
for part in result_set:
for item in part:
yield item
@classmethod
def iterate(cls, result_set: ResultSet) -> None:
# haiku for consuming an interator
collections.deque(cls.generator(result_set), maxlen=0)
@classmethod
def next(cls, result_set: ResultSet) -> Any:
"""
really this is like first, but
"""
return next(iter(cls.generator(result_set)))
@classmethod
def toList(cls, result_set: ResultSet) -> List:
return list(cls.generator(result_set))
@classmethod
def toSet(cls, result_set: ResultSet) -> Set:
return set(cls.generator(result_set))
@classmethod
def getOptional(cls, result_set: ResultSet) -> Optional[Any]:
try:
return cls.getOnly(result_set)
except StopIteration:
return None
@classmethod
def getOnly(cls, result_set: ResultSet) -> Any:
i = iter(cls.generator(result_set))
value = next(i)
try:
next(i)
except StopIteration:
return value
raise RuntimeError('Expected one item, but there was more!')
TYPE = TypeVar('TYPE')
class ExecuteQuery(Protocol):
@overload # noqa: F811
def __call__(self, query: Traversal, get: Callable[[ResultSet], V]) -> V:
...
@overload # noqa: F811
def __call__(self, query: str, get: Callable[[ResultSet], V], *, # noqa: F811
bindings: Optional[Mapping[str, Any]] = None) -> V:
...
def __call__(self, query: Union[str, Traversal], get: Callable[[ResultSet], V], *, # noqa: F811
bindings: Optional[Mapping[str, Any]] = None) -> V:
...
class ClientQueryExecutor(ExecuteQuery):
def __init__(self, *, client: Client, traversal_translator: Callable[[Traversal], str]) -> None:
self.client = client
self.traversal_translator = traversal_translator
def __call__(self, query: Union[str, Traversal], get: Callable[[ResultSet], V], *, # noqa: F811
bindings: Optional[Mapping[str, Any]] = None) -> V:
if isinstance(query, Traversal):
if bindings is not None:
raise AssertionError(f'expected bindings to be none')
query_text = self.traversal_translator(query)
else:
query_text = query
if not isinstance(query_text, str):
raise AssertionError(f'expected str')
result_set = self.client.submit(query_text, bindings)
return get(result_set)
class RetryingClientQueryExecutor(ClientQueryExecutor):
def __init__(self, client: Client, traversal_translator: Callable[[Traversal], str],
is_retryable: Callable[[Exception], bool]) -> None:
ClientQueryExecutor.__init__(self, client=client, traversal_translator=traversal_translator)
self.is_retryable = is_retryable
def __enter__(self) -> Any:
return self
def __exit__(self, *args: Any, **kwargs: Any) -> None:
return self.client.close()
# TODO: ideally this would be __call__(*args: Any, **kwargs: Any) -> Any (and then this could be mixinable) but I
# can't get mypy to not think that conflicts
def __call__(self, query: Union[str, Traversal], get: Callable[[ResultSet], V], *,
bindings: Optional[Mapping[str, Any]] = None) -> V:
def callable() -> V:
return ClientQueryExecutor.__call__(self, query, get, bindings=bindings)
try:
return retrying(callable, is_retryable=self.is_retryable)
except Exception as e:
LOGGER.warning(f'got exception executing query={query}, get={get}, bindings={bindings}', exc_info=e)
raise
@no_type_check
def _safe_get_any(root, *keys):
"""
Helper method for getting value from nested dict, special for Gremlin valueMap things where properties can be lists
of one or 0.
:param root:
:param keys:
:return:
"""
current = root
for key in keys:
# first get the only element if it's a list/set
if isinstance(current, Sequence):
if len(current) > 1:
raise RuntimeError(f'{current} is not a singleton! root={root} keys={keys}')
elif len(current) == 0:
current = None
else:
current = current[0]
if not current:
return None
if not isinstance(current, Mapping):
raise RuntimeError(f'{current} is not a Mapping! root={root} keys={keys}')
current = current.get(key)
if not current:
return None
# don't dereference the list this usually is, we might want it or not
return current
@no_type_check
def _safe_get_list(root, *keys, transform: Optional[Callable] = None):
"""
Like _safe_get_any, but for gremlin where we get a list for a single property
"""
values = _safe_get_any(root, *keys)
# is List the only type? it seems so
if values is None:
return None
elif not isinstance(values, List):
raise RuntimeError(f'{values} is not a List! root={root} keys={keys}')
elif transform is None:
return sorted(values)
elif len(values) > 0 and type(values[0]) == datetime and transform == int:
# need to do something special for datetimes we are transforming into int's
return sorted([transform(value.timestamp()) for value in values])
else:
return sorted([transform(value) for value in values])
@no_type_check
def _safe_get(root, *keys, transform: Optional[Callable] = None, default: Any = None):
"""
Like _safe_get_any, but for gremlin where we get a list for a single property
"""
value = _safe_get_list(root, *keys, transform=transform)
if value is None or len(value) == 0:
return default
elif len(value) > 1:
raise RuntimeError(f'{value} is not a singleton! root={root} keys={keys}')
else:
return value[0]
def _properties_or_drop_if_changed_except(
*excludes: str, label: Union[VertexTypes, EdgeTypes, VertexType, EdgeType],
thing: Union[object, Dict[str, Any]], existing: Union[object, Dict[str, Any]]) -> GraphTraversal:
if isinstance(thing, Mapping):
_thing = thing
elif hasattr(thing, '__dict__'):
_thing = vars(thing)
else:
raise AssertionError(f'thing must be a dict or have __dict__: {type(thing)}')
if isinstance(existing, Mapping):
_existing = existing
elif hasattr(existing, '__dict__'):
_existing = vars(existing)
else:
raise AssertionError(f'existing must be a dict or have __dict__: {type(existing)}')
def p(name: str) -> Optional[GraphTraversal]:
return _property_or_drop_if_changed(name=name, value=_thing.get(name, None), existing=_existing.get(name, None),
cardinality=get_cardinality_for(label, name))
names = sorted(set(_thing.keys()).difference(set(excludes)))
traversals = [t for t in [p(name) for name in names] if t is not None]
return _append_traversal(__.start(), *traversals) if traversals else None
def _property_unchanged(*, value: Any, existing: Any, cardinality: Optional[Cardinality]) -> bool:
# this is the usual case: either an Edge property (no cardinality) or Vertex property with Cardinality.single
if existing is None:
return value is None
elif cardinality is None or cardinality == Cardinality.single:
return tuple(existing) == (value,)
elif cardinality in (Cardinality.set_, Cardinality.list_):
return value in tuple(existing)
else:
return False
def _property_or_drop_if_changed(*, name: str, value: Any, existing: Any, cardinality: Optional[Cardinality]) \
-> Optional[GraphTraversal]:
"""
You want to use _vertex_property or _edge_property.
"""
if _property_unchanged(value=value, existing=existing, cardinality=cardinality):
return None
elif value is None:
return __.sideEffect(__.properties(name).drop())
else:
# complicated: edges can't have cardinality supplied and are implied to be single
if cardinality is None:
return __.property(name, value)
else:
return __.property(cardinality, name, value)
def _properties_or_drop_except(label: Union[VertexTypes, EdgeTypes, VertexType, EdgeType],
thing: Union[object, Dict[str, Any]], *excludes: str) -> GraphTraversal:
if isinstance(thing, Mapping):
pass
elif hasattr(thing, '__dict__'):
thing = vars(thing)
else:
raise AssertionError(f'must be a dict or have __dict__: {type(thing)}')
g = __.start()
for name in set(thing.keys()).difference(set(excludes)):
g = _property_or_drop(g=g, name=name, value=thing.get(name, None), cardinality=get_cardinality_for(label, name))
return g
def _properties_or_drop_of(label: Union[VertexTypes, EdgeTypes, VertexType, EdgeType],
thing: Union[object, Dict[str, Any]], *includes: str) -> GraphTraversal:
if isinstance(thing, Mapping):
pass
elif hasattr(thing, '__dict__'):
thing = vars(thing)
else:
raise AssertionError(f'must be a dict or have __dict__: {type(thing)}')
g = __.start()
for name in includes:
g = _property_or_drop(g=g, name=name, value=thing.get(name, None), cardinality=get_cardinality_for(label, name))
return g
def _properties_except(thing: Union[object, Dict[str, Any]], *excludes: str) -> Mapping[str, Any]:
if isinstance(thing, Mapping):
pass
elif hasattr(thing, '__dict__'):
thing = vars(thing)
else:
raise AssertionError(f'must be a dict or have __dict__: {type(thing)}')
_excludes = set(excludes)
return dict([(k, v) for k, v in thing.items() if k not in _excludes])
def _properties_of(thing: Union[object, Dict[str, Any]], *includes: str) -> Mapping[str, Any]:
if isinstance(thing, Mapping):
pass
elif hasattr(thing, '__dict__'):
thing = vars(thing)
else:
raise AssertionError(f'must be a dict or have __dict__: {type(thing)}')
return dict([(k, thing.get(k, None)) for k in includes])
def _is_select_traversal(g: GraphTraversal) -> Optional[str]:
if not g.bytecode.source_instructions and len(g.bytecode.step_instructions) == 1 and \
len(g.bytecode.step_instructions[0]) == 2 and g.bytecode.step_instructions[0][0] == 'select':
return g.bytecode.step_instructions[0][1]
else:
return None
def _vertex_property(*, g: GraphTraversal, name: str, value: Any, cardinality: Optional[Cardinality] = None,
label: Optional[VertexTypes] = None) -> GraphTraversal:
if (cardinality is None) and (label is None):
raise AssertionError('must pass one of label or cardinality')
if cardinality is not None:
_cardinality = cardinality
elif label is not None:
_cardinality = get_cardinality_for(label, name)
else:
raise RuntimeError()
return _property_or_drop(g=g, name=name, value=value, cardinality=checkNotNone(_cardinality))
def _edge_property(*, g: GraphTraversal, name: str, value: Any) -> GraphTraversal:
return _property_or_drop(g=g, name=name, value=value, cardinality=None)
def _property_or_drop(*, g: GraphTraversal, name: str, value: Any, cardinality: Optional[Cardinality]) \
-> GraphTraversal:
"""
You want to use _vertex_property or _edge_property.
"""
if value is None:
return g.sideEffect(__.properties(name).drop())
else:
# complicated: edges can't have cardinality supplied and are implied to be single
p = __.property(name, value) if cardinality is None else __.property(cardinality, name, value)
return _append_traversal(g, p)
def _V(label: Union[str, VertexTypes, VertexType], key: Optional[Union[str, TextP]],
key_property_name: Optional[str] = None, g: Optional[Union[Traversal, GraphTraversalSource]] = None,
**properties: Any) -> GraphTraversal:
"""
Gets a vertex with the given label and key and returns the valueMap. If no such vertex exists, None is
returned. (If more than one exists, which would be super surprising, an exception is raised.)
"""
if g is None:
g = __.start()
properties = dict(properties or {})
if isinstance(key, str):
id = ensure_vertex_type(label).id(key=key)
g = g.V(id)
elif key is not None:
# let's support predicates on the key, but need to limit it to either the test_shard (or unsharded perhaps)
if key_property_name is None:
raise AssertionError('expected key_property_name')
g = g.V().has(get_label_from(label), key_property_name, key)
if get_shard():
properties.setdefault(WellKnownProperties.TestShard.value.name, get_shard())
else:
# let's support hasLabel, but need to limit it to either the test_shard (or unsharded perhaps)
g = g.V().hasLabel(get_label_from(label))
if get_shard():
properties.setdefault(WellKnownProperties.TestShard.value.name, get_shard())
# should we do this when using the V(id)? there are a couple or one case where we use it to filter so seems handy
if properties is not None:
for name, value in properties.items():
if value is not None:
# you can have value be a predicate, like within('foo','bar') or such
g = g.has(name, value)
else:
g = g.hasNot(name)
return g
def _has(*, g: Traversal, label: Union[None, str, VertexTypes, EdgeTypes, VertexType, EdgeType],
key: Optional[str], key_property_name: Optional[str] = 'key',
properties: Optional[Mapping[str, Any]] = None) -> GraphTraversal:
"""
Matches a vertex or edge with the given label and key
"""
if (label is None) and (key is None) and (properties is None):
raise AssertionError('at least label or key or properties must be present')
if label is not None:
_label = get_label_from(label)
if key is None:
g = g.hasLabel(_label)
else:
if key_property_name is None:
raise AssertionError('must supply key_property_name if supplying key')
# you can have key be a predicate, like within('foo','bar') or such
g = g.has(_label, key_property_name, key)
elif key is not None:
if key_property_name is None:
raise AssertionError('must supply key_property_name if supplying key')
g = g.has(key_property_name, key)
# don't usually need to blend in the shard for test isolation (since _has almost always is used at the end of a
# traversal rooted in one component)
if properties is not None:
for name, value in properties.items():
if value is not None:
# you can have value be a predicate, like within('foo','bar') or such
g = g.has(name, value)
else:
g = g.hasNot(name)
return g
def _upsert(*, executor: ExecuteQuery, execute: Callable[[ResultSet], TYPE] = FromResultSet.getOnly,
g: GraphTraversalSource, label: Union[VertexTypes, VertexType], key_property_name: str, key: str,
traversal_if_exists: Optional[Traversal] = None, traversal_if_add: Optional[Traversal] = None,
traversal: Optional[Traversal] = __.id(), **properties: Any) -> TYPE:
if not isinstance(label, (VertexTypes, VertexType)):
raise AssertionError(f'expected label to be a VertexType or VertexTypes: {label}')
if isinstance(label, VertexTypes):
id = label.value.id(key=key, **properties)
elif isinstance(label, VertexType):
id = label.id(key=key, **properties)
else:
raise AssertionError('wat') # appease mypy
if get_shard():
properties.setdefault(WellKnownProperties.TestShard.value.name, get_shard())
existing_node = executor(query=g.V(id).valueMap(True), get=FromResultSet.getOptional)
_label = get_label_from(label)
if existing_node is None:
add = __.addV(_label).property(T.id, id).property(Cardinality.single, key_property_name, key)
set_properties = _properties_or_drop_except(label, properties) if properties else None
g = _append_traversal(g, add, traversal_if_add, set_properties, traversal)
else:
# get existing vertex...
get = __.V(id)
set_properties = _properties_or_drop_if_changed_except(
label=label, thing=properties, existing=existing_node) if properties else None
g = _append_traversal(g, get, traversal_if_exists, set_properties, traversal)
# return the result
return executor(query=g, get=execute)
def _link(*, executor: ExecuteQuery, execute: Optional[Callable[[ResultSet], TYPE]] = None, # noqa: C901
g: GraphTraversalSource, edge_label: Union[EdgeTypes, EdgeType], key_property_name: Optional[str] = None,
vertex1_label: Optional[Union[str, VertexTypes]] = None, vertex1_key: Optional[str] = None,
vertex2_label: Optional[Union[str, VertexTypes]] = None, vertex2_key: Optional[str] = None,
vertex1_id: Optional[Any] = None, vertex2_id: Optional[Any] = None,
edge_properties: Dict[str, Any] = {}, traversal_if_exists: Optional[Traversal] = None,
traversal_if_add: Optional[Traversal] = None, traversal: Optional[Traversal] = None,
**properties: Any) -> Optional[TYPE]:
"""
Creates an edge from vertex 1 to vertex 2 with a given label, if such
an edge does not exist. It does not create vertex1 or vertex 2, so if
they don't exist, you will get some kind of error (usually an interation error).
:param edge_properties: A map of edge properties and values to be used for
edge idempotence. If an unexpired edge with these
properties and values exists, no edge will be created.
"""
if (vertex1_label is not None and vertex1_key is not None) == (vertex1_id is not None):
raise AssertionError(f'pass either vertex1_label and vertex1_key or vertex1_id, but not both')
if (vertex2_label is not None and vertex2_key is not None) == (vertex2_id is not None):
raise AssertionError(f'pass either vertex2_label and vertex2_key or vertex2_id, but not both')
# Return the raw id of a vertex
if vertex1_id is None:
if (key_property_name is None) or (vertex1_label is None):
raise AssertionError(f'expected both key_property_name and vertex1_label')
# we used to query to find this, but now that we're deterministically generating them we can do:
vertex1_id = ensure_vertex_type(vertex1_label).id(**{key_property_name: vertex1_key})
# but let's query to ensure it exists (which the previous pattern also ensured
executor(query=g.V(vertex1_id), get=FromResultSet.getOnly)
if vertex2_id is None:
if (key_property_name is None) or (vertex2_label is None):
raise AssertionError(f'expected both key_property_name and vertex2_label')
vertex2_id = ensure_vertex_type(vertex2_label).id(**{key_property_name: vertex2_key})
executor(query=g.V(vertex2_id), get=FromResultSet.getOnly)
if (vertex1_id is None) or (vertex2_id is None):
raise AssertionError(f'vertex1_label={vertex1_label}, vertex1_key={vertex1_key} \
or vertex2_label={vertex2_label}, vertex2_key={vertex2_key} either does not exist! \
vertex1_id={vertex1_id}, vertex2_id={vertex2_id}')
_label = get_label_from(edge_label)
edge_traversal = g.V(vertex1_id).outE(_label).where(__.inV().hasId(vertex2_id))
for key, value in edge_properties.items():
edge_traversal = edge_traversal.has(key, value)
edge_id = executor(query=edge_traversal.id(), get=FromResultSet.getOptional)
# If no link exists, create one!
if edge_id is None:
g = g.V(vertex1_id).as_('one').V(vertex2_id).addE(_label).from_('one').property('created', timestamp())
g = _append_traversal(g, traversal_if_add)
else:
# Just get the edge in case we need to add properties
g = _append_traversal(g.E(edge_id), traversal_if_exists)
if properties:
g = _append_traversal(g, _properties_or_drop_except(edge_label, properties))
# updated properties, etc.
if traversal is not None:
g = _append_traversal(g, traversal)
# return the result
return executor(query=g, get=execute if execute is not None else FromResultSet.getOnly)
def _expire_other_links( # noqa: C901
*, executor: ExecuteQuery, g: GraphTraversalSource,
edge_label: EdgeTypes, key_property_name: Optional[str] = None,
vertex1_label: Optional[Union[str, VertexTypes]] = None, vertex1_key: Optional[str] = None,
vertex2_label: Optional[Union[str, VertexTypes]] = None, vertex2_key: Optional[str] = None,
vertex1_id: Optional[Union[int, str, P]] = None, vertex2_id: Optional[Union[int, str, P]] = None,
edge_direction: Direction = Direction.OUT,
**properties: Any) -> None:
"""
Expires edges of a given label other than the ones connecting
vertex 1 and 2. If keys are not specified, will expire all edges between the two
vertex types
"""
if (vertex1_label is not None) == (vertex1_id is not None):
raise AssertionError('pass either vertex1_label and vertex1_key or vertex1_id, but not both')
if (vertex2_label is not None) == (vertex2_id is not None):
raise AssertionError('pass either vertex2_label and vertex2_key or vertex2_id, but not both')
# Return the raw id of a vertex
if vertex1_id is None:
if (key_property_name is None) or (vertex1_label is None):
raise AssertionError(f'expected both key_property_name and vertex1_label')
# we used to query to find this, but now that we're deterministically generating them we can do:
vertex1_id = ensure_vertex_type(vertex1_label).id(**{key_property_name: vertex1_key})
# but let's query to ensure it exists (which the previous pattern also ensured
executor(query=g.V(vertex1_id), get=FromResultSet.getOnly)
if vertex2_id is None and vertex2_key is not None:
# TODO support getting more than one here
if (key_property_name is None) or (vertex2_label is None):
raise AssertionError(f'expected both key_property_name and vertex2_label')
vertex2_id = ensure_vertex_type(vertex2_label).id(**{key_property_name: vertex2_key})
executor(query=g.V(vertex2_id), get=FromResultSet.getOnly)
if vertex1_id is not None:
g = g.V(vertex1_id)
else:
if vertex1_label is None:
raise AssertionError(f'expected vertex1_label')
g = g.V().hasLabel(get_label_from(vertex1_label))
# Traverse the edges from vertex 1
if edge_direction == Direction.OUT:
g = g.outE(get_label_from(edge_label))
else:
g = g.inE(get_label_from(edge_label))
g = g
# Find edges to vertexes with the label but an id that isn't vertex 2
_filter = __.inV() if edge_direction == Direction.OUT else __.outV()
if vertex2_id is None:
if vertex2_label is None:
raise AssertionError(f'expected vertex2_label')
g = g.filter(_filter)
elif isinstance(vertex2_id, (int, str)):
g = g.filter(_append_traversal(_filter, __.id().is_(P.neq(vertex2_id))))
elif isinstance(vertex2_id, P):
g = g.filter(_append_traversal(_filter, __.id().is_(not_(vertex2_id))))
g = g.drop()
executor(g, get=FromResultSet.iterate)
def _expire_link(*, executor: ExecuteQuery, g: GraphTraversalSource,
key_property_name: str, edge_label: Union[EdgeTypes, EdgeType],
vertex1_label: Optional[Union[str, VertexTypes, VertexType]] = None,
vertex1_key: Optional[Union[str, P]] = None,
vertex1_id: Optional[Union[int, str, P]] = None,
vertex2_label: Optional[Union[str, VertexTypes, VertexType]] = None,
vertex2_key: Optional[Union[str, P]] = None,
vertex2_id: Optional[Union[int, str, P]] = None) -> None:
"""
Expires link between two vertices. Refer to vertices either by supplying
label + key, or by providing the gremlin vertex ids directly
"""
if (vertex1_label is not None and vertex1_key is not None) == (vertex1_id is not None):
raise AssertionError(f'pass either vertex1_label and vertex1_key or vertex1_id, but not both')
if (vertex2_label is not None and vertex2_key is not None) == (vertex2_id is not None):
raise AssertionError(f'pass either vertex2_label and vertex2_key or vertex2_id, but not both')
# Return the raw ids of the vertices
if vertex1_id is None:
if (key_property_name is None) or (vertex1_label is None):
raise AssertionError(f'expected both key_property_name and vertex1_label')
# we used to query to find this, but now that we're deterministically generating them we can do:
vertex1_id = ensure_vertex_type(vertex1_label).id(**{key_property_name: vertex1_key})
# but let's query to ensure it exists (which the previous pattern also ensured
executor(query=g.V(vertex1_id), get=FromResultSet.getOnly)
if vertex2_id is None:
if (key_property_name is None) or (vertex2_label is None):
raise AssertionError(f'expected both key_property_name and vertex2_label')
# we used to query to find this, but now that we're deterministically generating them we can do:
vertex2_id = ensure_vertex_type(vertex2_label).id(**{key_property_name: vertex2_key})
# but let's query to ensure it exists (which the previous pattern also ensured
executor(query=g.V(vertex2_id), get=FromResultSet.getOnly)
if (vertex1_id is None) or (vertex2_id is None) or (vertex1_id == vertex2_id):
raise AssertionError(f'pass either vertex1_label and vertex1_key or vertex1_id, but not both')
g = g.V(vertex1_id)
g = g.bothE(get_label_from(edge_label)).where(bothV().hasId(vertex2_id))
g = g.drop()
executor(g, get=FromResultSet.iterate)
def _edges_between(*, g: Traversal, label: Union[None, str, EdgeTypes, EdgeType], vertex1: Traversal,
vertex2: Traversal, **properties: Any) -> GraphTraversal:
"""
get the edges from vertex1
"""
vertex1_alias = _is_select_traversal(vertex1)
if vertex1_alias is None:
vertex1_alias = 'one'
g = _append_traversal(g, vertex1).as_(vertex1_alias)
vertex2_alias = _is_select_traversal(vertex1)
g = _append_traversal(g, vertex2)
if (vertex1_alias is None) or (vertex1_alias == vertex2_alias):
raise AssertionError(f'vertex1_alias={vertex1_alias}, vertex2_alias={vertex2_alias}')
if label is not None:
g = g.bothE(get_label_from(label))
else:
g = g.bothE()
g = g.where(__.otherV().as_(vertex1_alias))
if 'expired' not in properties:
properties['expired'] = None
g = _has(g=g, properties=properties, label=None, key_property_name=None, key=None)
return g
def _edges_from(*, g: Union[GraphTraversalSource, GraphTraversal],
vertex1_label: Union[str, VertexTypes, VertexType], vertex1_key: str,
vertex1_properties: Optional[Mapping[str, Any]] = None,
vertex2_label: Optional[Union[str, VertexTypes, VertexType]], vertex2_key: Optional[str],
vertex2_properties: Optional[Mapping[str, Any]] = None,
edge_label: Optional[Union[str, EdgeTypes, EdgeType]],
**edge_properties: Any) -> GraphTraversal:
"""
get the edges from vertex1
"""
vertex1 = _V(g=__.start(), label=vertex1_label, key=vertex1_key, **(vertex1_properties or {}))
if vertex2_label is None and vertex2_key is None and not vertex2_properties:
vertex2 = None
else:
vertex2 = _has(g=__.start(), label=vertex2_label, key=vertex2_key, properties=vertex2_properties or {})
g = _append_traversal(g, vertex1)
if edge_label is not None:
g = g.outE(get_label_from(edge_label))
else:
g = g.outE()
if 'expired' not in edge_properties:
edge_properties['expired'] = None
g = _has(g=g, label=None, key=None, key_property_name=None, properties=edge_properties)
if vertex2 is not None:
g = g.where(_append_traversal(__.otherV(), vertex2))
return g
def _edges_to(*, g: Union[GraphTraversalSource, GraphTraversal],
vertex1_label: Union[str, VertexTypes, VertexType], vertex1_key: str,
vertex1_properties: Optional[Mapping[str, Any]] = None,
vertex2_label: Optional[Union[str, VertexTypes, VertexType]], vertex2_key: Optional[str],
vertex2_properties: Optional[Mapping[str, Any]] = None,
edge_label: Optional[Union[str, EdgeTypes, EdgeType]],
**edge_properties: Any) -> GraphTraversal:
"""
get the edges to vertex1
"""
vertex1 = _V(g=__.start(), label=vertex1_label, key=vertex1_key, **(vertex1_properties or {}))
if vertex2_label is None and vertex2_key is None and not vertex2_properties:
vertex2 = None
else:
vertex2 = _has(g=__.start(), label=vertex2_label, key=vertex2_key, properties=vertex2_properties or {})
g = _append_traversal(g, vertex1)
if edge_label is not None:
g = g.inE(get_label_from(edge_label))
else:
g = g.inE()
g = _has(g=g, label=None, key=None, key_property_name=None, properties=edge_properties)
if vertex2 is not None:
g = g.where(_append_traversal(__.otherV(), vertex2))
return g
def _parse_gremlin_server_error(exception: Exception) -> Dict[str, Any]:
if not isinstance(exception, gremlin_python.driver.protocol.GremlinServerError) or len(exception.args) != 1:
return {}
# this is like '444: {...json object...}'
return json.loads(exception.args[0][exception.args[0].index(': ') + 1:])
class AbstractGremlinProxy(BaseProxy):
"""
A proxy to a server using TinkerPop Gremlin (e.g. JanusGraph, AWS Neptune, Azure CosmosDB, NEO4J with the gremlin
plugin). There are some differences between them! The implementation here is intended to not rely on features of
any one of them very much.
:param key_property_name defaults to 'key', but some some servers don't allow key so their proxies will pick a different key property name (e.g. _key)
:param remote_connection a RemoteConnection e.g. `DriverRemoteConnection(url='wss://host:8182/gremlin')`
If you see:
gremlin_python.driver.protocol.GremlinServerError: 498: {"requestId":"80a1d05e-bcde-4f43-95c7-d48db3966c0a","code":"UnsupportedOperationException","detailedMessage:"com.amazon.neptune.storage.volcano.ast.CutoffNode cannot be cast to com.amazon.neptune.storage.volcano.ast.AbstractGroupNode"}
go look at https://stackoverflow.com/questions/58720484/gremlin-neptune-sort-edges-by-vertex-property
=== A short guide to writing queries that support the test sharding. ===
The round trip tests are not fast. To improve our experience, we are running tests in parallel, which means that
tests need to play nicely with each other. The simplest way to do this is start queries with some method that will
restrict the query to a subgraph for the test shard: _V, _upsert, _edges_to, _edges_from, _edges_between. What they
do is either get vertex id (which are specific to test shards), or sprinkle in a .property('shard', xxx) filter.
You will almost certainly not need to observe this in tests, but may need to in the proxy code/queries.
""" # noqa: E501
def __init__(self, *, key_property_name: str, driver_remote_connection_options: Mapping[str, Any] = {},
gremlin_client_options: Mapping[str, Any] = {}) -> None:
# these might vary from datastore type to another, but if you change these while talking to the same instance
# without migration, it will go poorly
self.key_property_name: str = key_property_name
self.driver_remote_connection_options = dict(driver_remote_connection_options or {})
self.gremlin_client_options = dict(gremlin_client_options or {})
self.gremlin_client_options.setdefault(
'traversal_source', self.driver_remote_connection_options.get('traversal_source', 'g'))
# set message_serializer in client creation
# override these since we need so little
self.gremlin_client_options.setdefault('pool_size', 1),
self.gremlin_client_options.setdefault('max_workers', 1),
# safe this for use in _submit
self.remote_connection: DriverRemoteConnection = DriverRemoteConnection(
url=self.possibly_signed_ws_client_request_or_url(),
**_properties_except(self.driver_remote_connection_options, 'url'))
self._g: GraphTraversalSource = traversal().withRemote(self.remote_connection)
def drop(self) -> None:
LOGGER.warning('DROPPING ALL NODES')
with self.query_executor() as executor:
executor(query=self.g.V().drop(), get=FromResultSet.iterate)
LOGGER.warning('COMPLETED DROP OF ALL NODES')
@property
def g(self) -> GraphTraversalSource:
"""
might not actually refer to g, but usually is so let's call it that here. no setter so we don't accidentally
self.g = somewhere
"""
return self._g
@classmethod
def get_is_retryable(cls, method_name: str) -> Callable[[Exception], bool]:
def is_retryable(exception: Exception) -> bool:
nonlocal method_name
return cls._is_retryable_exception(method_name=method_name, exception=exception)
return is_retryable
@classmethod
@abstractmethod
def script_translator(cls) -> Type[ScriptTranslator]:
pass
@abstractmethod
def possibly_signed_ws_client_request_or_url(self) -> Union[httpclient.HTTPRequest, str]:
pass
def client(self) -> Client:
gremlin_client_options = dict(self.gremlin_client_options)
gremlin_client_options.setdefault('message_serializer', ExtendedGraphSONSerializersV3d0())
gremlin_client_options['url'] = self.possibly_signed_ws_client_request_or_url()
return Client(**gremlin_client_options)
def query_executor(self, *, method_name: str = "nope") -> \
RetryingClientQueryExecutor:
return RetryingClientQueryExecutor(
client=self.client(), is_retryable=self.get_is_retryable(method_name),
traversal_translator=self.script_translator().translateT)
@classmethod
def _is_retryable_exception(cls, *, method_name: str, exception: Exception) -> bool:
"""
overridde this if you want to retry the exception for the given method_name
"""
return False
def _submit(self, *, command: str, bindings: Any = None) -> Any:
"""
Do not use this.
...except if you are doing graph management or other things not supported by Gremlin. For example, with
JanusGraph, you might:
>>> self._submit('''
graph.tx().rollback()
mgmt = graph.openManagement()
keyProperty = mgmt.getPropertyKey('_key')
vertexLabel = mgmt.getVertexLabel('Table')
mgmt.buildIndex('TableByKeyUnique', Vertex.class).addKey(keyProperty).indexOnly(vertexLabel).unique().buildCompositeIndex()
mgmt.commit()
''')
>>> self._submit('''
graph.openManagement().getGraphIndex('TableByKey')
''')
>>> self._submit('''
graph.openManagement().getGraphIndexes(Vertex.class)
''')
>>> self._submit('''
graph.openManagement().getGraphIndexes(Edge.class)
''')
""" # noqa: E501
# we use the client from the DriverRemoteConnection, which is sneaky. We could probably pull out parameters
# from the DriverRemoteConnection and construct a Client directly, but that feels even sneakier and more
# fragile.
return self.remote_connection._client.submit(message=command, bindings=bindings).all().result()
def is_healthy(self) -> None:
# throws if cluster unhealthy or can't connect. Neptune proxy overrides and uses status endpoint
self.query_executor()(query=self.g.V().limit(0).fold, get=FromResultSet.iterate)
def get_relationship(self, *, node_type1: str, node_key1: str, node_type2: str, node_key2: str) -> List[Any]:
"""
This method is largely meant for testing. It returns any relationships between
two nodes
See AbstractProxyTest
"""
g = self.g
g = _V(g=g, label=node_type1, key=node_key1).as_('v')
g = _V(g=g, label=node_type2, key=node_key2)
g = g.bothE()
# as creates an alias, BUT ALSO in filter, where, or some other predicate filters the traversal with the
# previously aliased value (which is what it does here)
g = g.where(__.otherV().as_('v'))
g = g.valueMap()
return self.query_executor()(query=g, get=FromResultSet.toList)
@timer_with_counter
@overrides
def get_user(self, *, id: str) -> Union[User, None]:
g = _V(g=self.g, label=VertexTypes.User, key=id).as_('user')
g = g.coalesce(outE(EdgeTypes.ManagedBy.value.label).inV().
hasLabel(VertexTypes.User.value.label).fold()).as_('managers')
g = g.select('user', 'managers').by(valueMap()).by(unfold().valueMap().fold())
results = self.query_executor()(query=g, get=FromResultSet.toList)
result = _safe_get(results)
if not result:
return result
user = self._convert_to_user(result['user'])
managers = _safe_get_list(result, 'managers')
user.manager_fullname = _safe_get(managers[0], 'full_name', default=None) if managers else None
return user
def _get_user(self, *, id: str, executor: ExecuteQuery) -> Union[User, None]:
g = _V(g=self.g, label=VertexTypes.User, key=id).as_('user')
g = g.coalesce(outE(EdgeTypes.ManagedBy.value.label).inV().
hasLabel(VertexTypes.User.value.label).fold()).as_('managers')