/
model.py
1664 lines (1428 loc) · 64.6 KB
/
model.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
from __future__ import annotations
import copy
import json
import re
import sys
import textwrap
from abc import ABC, abstractmethod
from datetime import datetime, timezone, date
from functools import lru_cache
from json import JSONDecodeError
from typing import (
Union,
Any,
Optional,
Callable,
Type,
Sequence,
Dict,
List,
Set,
cast,
Tuple,
Iterable,
TypeVar,
Iterator,
)
import yaml
from attrs import define, frozen
from dateutil.parser import parse
from jsons import set_deserializer, set_serializer
from networkx import MultiDiGraph
from parsy import regex, string, Parser
from resotocore.compat import remove_suffix
from resotocore.model.transform_kind_convert import converters
from resotocore.model.typed_model import from_js, to_js
from resotocore.types import Json, JsonElement, ValidationResult, ValidationFn, EdgeType
from resotocore.util import if_set, utc, duration, first
from resotolib.core.model_check import check_overlap_for
from resotolib.durations import duration_parser, DurationRe
from resotolib.parse_util import make_parser, variable_dp_backtick, dot_dp
from resotolib.utils import is_env_var_string
T = TypeVar("T")
AvailableEdgeTypes: List[EdgeType] = ["default", "delete"]
def check_type_fn(t: type, type_name: str) -> ValidationFn:
def check_type(x: Any) -> ValidationResult:
if isinstance(x, t):
return None
else:
raise AttributeError(f"Expected type {type_name} but got {type(x).__name__}")
return check_type
def check_fn(x: Optional[Any], func: Callable[[Any, Any], Optional[Any]], message: str) -> Optional[ValidationFn]:
def check_single(value: Any) -> ValidationResult:
if func(x, value):
return None
else:
raise AttributeError(f">{value}< {message}")
return None if x is None else check_single
def validate_fn(*fns: Optional[ValidationFn]) -> ValidationFn:
defined = list(filter(lambda x: x is not None, fns))
def always_valid(_: Any) -> ValidationResult:
return None
def check_defined(value: Any) -> ValidationResult:
for fn in defined:
res = fn(value) # type: ignore
if res is not None:
return res
return None
return check_defined if defined else always_valid
@define(order=True, hash=True, frozen=True)
class SyntheticProperty:
path: List[str]
"""
A synthetic property does not exist in the underlying data model.
It is defined by a function on an existing other property.
Example: age is a duration defined on ctime which is a datetime.
the function is age=now-ctime.
"""
@define(order=True, hash=True, eq=True)
class Property:
name: str
kind: str
required: bool = False
synthetic: Optional[SyntheticProperty] = None
description: Optional[str] = None
metadata: Optional[Json] = None
def __attrs_post_init__(self) -> None:
assert self.synthetic is None or not self.required, "Synthetic properties can not be required!"
def resolve(self, model: Dict[str, Kind]) -> Kind:
return Property.parse_kind(self.kind, model)
def meta(self, name: str, clazz: Type[T]) -> Optional[T]:
meta = self.metadata
# noinspection PyUnboundLocalVariable
return v if meta is not None and (v := meta.get(name)) is not None and isinstance(v, clazz) else None
def meta_get(self, name: str, clazz: Type[T], default: T) -> T:
return self.meta(name, clazz) or default
@staticmethod
def parse_kind(name: str, model: Dict[str, Kind]) -> Kind:
def kind_by_name(kind_name: str) -> Kind:
if kind_name not in model:
raise AttributeError(f"Property kind is not known: {kind_name}. Have you registered it?")
return model[kind_name]
simple_kind_parser = regex("[A-Za-z][A-Za-z0-9_.]*").map(kind_by_name)
bracket_parser = string("[]")
dict_string_parser = string("dictionary[")
comma_parser = regex("\\s*,\\s*")
bracket_r = string("]")
@make_parser
def array_parser() -> Parser:
inner = yield dictionary_parser | simple_kind_parser
brackets = yield bracket_parser.times(1, cast(int, float("inf")))
return ArrayKind.mk_array(inner, len(brackets))
@make_parser
def dictionary_parser() -> Parser:
yield dict_string_parser
key_kind = cast(Kind, (yield simple_kind_parser))
yield comma_parser
value_kind = yield array_parser | dictionary_parser | simple_kind_parser
yield bracket_r
return DictionaryKind(key_kind, value_kind)
return (array_parser | dictionary_parser | simple_kind_parser).parse(name) # type: ignore
@staticmethod
def any_prop() -> Property:
return Property("any", "any")
# Split a variable path into its path parts.
# foo.bla -> [foo, bla]
# foo.`bla.bar` -> [foo, bla.bar]
prop_path_parser = (regex("[^`.]+") | variable_dp_backtick).sep_by(dot_dp)
array_index_re = re.compile(r"\[(\d+|\*)]")
class PropertyPath:
@staticmethod
def from_path(path: str) -> PropertyPath:
# remove index accesses from the path (e.g. [23] -> "[]", [*] -> "[]")
no_index = array_index_re.sub("[]", path)
return PropertyPath(prop_path_parser.parse(no_index), no_index)
def __init__(self, path: Sequence[Optional[str]], str_rep: Optional[str] = None):
self.path = path
self.path_str = str_rep if str_rep else ".".join(a if a else "" for a in self.path)
@property
def root(self) -> bool:
return not bool(self.path)
def child(self, part: Optional[str]) -> PropertyPath:
update = list(self.path)
update.append(part)
return PropertyPath(update)
@property
def last_part(self) -> Optional[str]:
return self.path[-1] if self.path else None
def same_as(self, other: PropertyPath) -> bool:
"""
Checks if the given path is the same this path.
Note: the path may include "holes" marked as None.
The holes mean positions that have to be ignored.
[A,B,C] same_as [A,None,C] same_as [A,None,None] same_as [None,None,None]
"""
if len(other.path) == len(self.path):
for left, right in zip(self.path, other.path):
if left is not None and right is not None and left != right:
return False
return True
else:
return False
def __repr__(self) -> str:
return self.path_str
def __eq__(self, other: Any) -> bool:
return isinstance(other, PropertyPath) and other.path_str == self.path_str
def __hash__(self) -> int:
return hash(self.path_str)
EmptyPath = PropertyPath([], "")
@define(order=True, hash=True, frozen=True)
class ResolvedProperty:
# The path of the resolved property in a complex kind
path: PropertyPath
# The metadata of the property (name etc.)
prop: Property
# the resolved kind of this property
kind: Kind
@property
def simple_kind(self) -> SimpleKind:
return self.kind if isinstance(self.kind, SimpleKind) else AnyKind()
class Kind(ABC):
def __init__(self, fqn: str):
self.fqn = fqn
def __eq__(self, other: object) -> bool:
return self.__dict__ == other.__dict__ if isinstance(other, Kind) else False
def __hash__(self) -> int:
return hash(self.fqn)
def coerce(self, value: JsonElement, **kwargs: bool) -> JsonElement:
coerced = self.coerce_if_required(value, **kwargs)
return coerced or value
@abstractmethod
def coerce_if_required(self, value: JsonElement, **kwargs: bool) -> Optional[JsonElement]:
"""
Coerces the given value to this kind.
- if obj is already correct: return None
- if obj can not be coerced: return None
- if obj can be coerced: return the value
"""
@abstractmethod
def check_valid(self, obj: JsonElement, **kwargs: bool) -> ValidationResult:
"""
Validate given object against definition:
- if obj is valid: return None
- if obj is not valid and can be coerced: return the coerced value.
- if obj is not valid and can not be coerced: raise an exception
"""
@staticmethod
def to_json(obj: Kind, **kwargs: Any) -> Json:
return obj.as_json(**kwargs)
@abstractmethod
def as_json(self, **kwargs: bool) -> Json:
pass
def resolve(self, model: Dict[str, Kind]) -> None:
pass
def kind_hierarchy(self) -> Set[str]:
return {self.fqn}
def package(self) -> Optional[str]:
return self.fqn.rsplit(".", 1)[0] if "." in self.fqn else None
# noinspection PyUnusedLocal
@staticmethod
def from_json(js: Json, _: type = object, **kwargs: object) -> Kind:
if "inner" in js:
inner = Kind.from_json(js["inner"])
return ArrayKind(inner)
elif "fqn" in js and "runtime_kind" in js and js["runtime_kind"] in simple_kind_to_type:
fqn = js["fqn"]
rk = js["runtime_kind"]
if "source_fqn" in js and "converter" in js and "reverse_order" in js:
return TransformKind(fqn, rk, js["source_fqn"], js["converter"], js["reverse_order"])
elif rk == "string":
minimum = js.get("min_length")
maximum = js.get("max_length")
p = js.get("pattern")
e = js.get("enum")
return StringKind(fqn, minimum, maximum, p, e)
elif rk in ("int32", "int64", "float", "double"):
minimum = js.get("minimum")
maximum = js.get("maximum")
e = js.get("enum")
return NumberKind(fqn, rk, minimum, maximum, e)
elif rk == "datetime":
return DateTimeKind(fqn)
elif rk == "date":
return DateKind(fqn)
elif rk == "duration":
return DurationKind(fqn)
elif rk == "boolean":
return BooleanKind(fqn)
else:
raise TypeError(f"Unhandled runtime kind: {rk}")
elif js.get("fqn") == "any" and js.get("runtime_kind") == "any":
return AnyKind()
elif "fqn" in js and ("properties" in js or "bases" in js):
props = list(map(lambda p: from_js(p, Property), js.get("properties", [])))
bases: List[str] = js.get("bases", [])
allow_unknown_props = js.get("allow_unknown_props", False)
successor_kinds = js.get("successor_kinds")
aggregate_root = js.get("aggregate_root", True)
metadata = js.get("metadata")
return ComplexKind(
fqn=js["fqn"],
bases=bases,
properties=props,
allow_unknown_props=allow_unknown_props,
successor_kinds=successor_kinds,
aggregate_root=aggregate_root,
metadata=metadata,
)
else:
raise JSONDecodeError("Given type can not be read.", json.dumps(js), 0)
def sort_json(self, js: Json) -> Json:
"""
Sort the given json element according to the kind definition.
A model which define properties in a specific order, the json object also uses the same order.
This will walk the complete json structure.
"""
if isinstance(js, dict) and isinstance(self, ComplexKind):
prop_order = {rp.name: idx for idx, rp in enumerate(self.all_props())}
sub = {
k: self.property_kind_of(k, AnyKind()).sort_json(v) if isinstance(v, dict) else v for k, v in js.items()
}
# a property which is unknown is moved to the end with no specific order
return dict(sorted(sub.items(), key=lambda k: prop_order.get(k[0], sys.maxsize)))
elif isinstance(js, dict):
# noinspection PyTypeChecker
return dict(sorted(js.items()))
else:
return js
def nested_complex_kinds(self) -> List[ComplexKind]:
if isinstance(self, ComplexKind):
return [self]
elif isinstance(self, ArrayKind):
return self.inner.nested_complex_kinds()
elif isinstance(self, DictionaryKind):
return self.key_kind.nested_complex_kinds() + self.value_kind.nested_complex_kinds()
else:
return []
def should_skip_env_var_str(obj: Any, kwargs: Dict[str, bool]) -> bool:
return kwargs.get("config_context", False) and is_env_var_string(obj)
simple_kind_to_type: Dict[str, Type[Union[str, int, float, bool]]] = {
"string": str,
"int32": int,
"int64": int,
"float": float,
"double": float,
"boolean": bool,
"date": str,
"datetime": str,
"duration": str,
}
class SimpleKind(Kind, ABC):
def __init__(self, fqn: str, runtime_kind: str, reverse_order: bool = False):
super().__init__(fqn)
self.runtime_kind = runtime_kind
self.reverse_order = reverse_order
def coerce_if_required(self, value: JsonElement, **kwargs: bool) -> Optional[JsonElement]:
"""
Take a user defined value and transform it into a machine queryable value.
Example:
- "10s" as string -> "10s"
- "10s" as boolean -> false
- "10s" as duration -> "10s"
- "10s" as date -> now + 10 seconds (depending on local time)
:param value: the value from the user
:return: the coerced value from the system
"""
return None
def as_json(self, **kwargs: bool) -> Json:
return {"fqn": self.fqn, "runtime_kind": self.runtime_kind}
class AnyKind(SimpleKind):
def __init__(self) -> None:
super().__init__("any", "any")
def __new__(cls) -> AnyKind:
if cls.__singleton is None:
cls.__singleton = super(AnyKind, cls).__new__(cls)
return cls.__singleton
def check_valid(self, obj: JsonElement, **kwargs: bool) -> ValidationResult:
return None
__singleton: Optional[AnyKind] = None
class StringKind(SimpleKind):
def __init__(
self,
fqn: str,
min_length: Optional[int] = None,
max_length: Optional[int] = None,
pattern: Optional[str] = None,
enum: Optional[Set[str]] = None,
):
super().__init__(fqn, "string")
self.min_length = min_length
self.max_length = max_length
self.pattern = pattern
self.pattern_compiled = if_set(pattern, re.compile)
self.enum = enum
self.valid_fn = validate_fn(
check_type_fn(str, "string"),
check_fn(
self.pattern_compiled,
lambda p, obj: p.fullmatch(obj) is not None,
f"does not conform to regex: {self.pattern}",
),
check_fn(self.enum, lambda x, obj: obj in x, f"should be one of: {self.enum}"),
check_fn(self.min_length, lambda x, obj: len(obj) >= x, f"does not have minimal length: {self.min_length}"),
check_fn(self.max_length, lambda x, obj: len(obj) <= x, f"is too long! Allowed: {self.max_length}"),
)
def check_valid(self, obj: JsonElement, **kwargs: bool) -> ValidationResult:
if obj is None:
return None
elif should_skip_env_var_str(obj, kwargs):
return None
elif isinstance(obj, str):
return self.valid_fn(obj)
coerced = self.coerce_if_required(obj, **kwargs)
if coerced is not None:
self.valid_fn(coerced)
return coerced
else:
raise AttributeError(f"Expected type {self.runtime_kind} but got {type(obj).__name__}")
def coerce_if_required(self, value: JsonElement, **kwargs: bool) -> Optional[str]:
if value is None:
return value
if isinstance(value, str):
return None
else:
return json.dumps(value)
def as_json(self, **kwargs: bool) -> Json:
js = super().as_json(**kwargs)
if self.pattern:
js["pattern"] = self.pattern
if self.enum:
js["enum"] = self.enum
if self.min_length:
js["min_length"] = self.min_length
if self.max_length:
js["max_length"] = self.max_length
return js
class NumberKind(SimpleKind):
def __init__(
self,
fqn: str,
runtime_kind: str,
minimum: Union[None, float, int] = None,
maximum: Union[None, float, int] = None,
enum: Optional[Set[Union[float, int]]] = None,
):
super().__init__(fqn, runtime_kind)
self.minimum = minimum
self.maximum = maximum
self.enum = enum
self.valid_fn = validate_fn(
check_type_fn(int, "int") if runtime_kind == "int" else self.check_float,
check_fn(self.enum, lambda x, obj: obj in x, f"should be one of: {self.enum}"),
check_fn(self.minimum, lambda x, obj: obj >= x, f"should be greater or equals than: {self.minimum}"),
check_fn(self.maximum, lambda x, obj: obj <= x, f"should be smaller or equals than: {self.maximum}"),
)
@staticmethod
def check_float(obj: Any) -> ValidationResult:
if isinstance(obj, (int, float)):
return None
else:
raise AttributeError(f"Expected number but got {obj}")
def check_valid(self, obj: JsonElement, **kwargs: bool) -> ValidationResult:
if obj is None:
return None
elif should_skip_env_var_str(obj, kwargs):
return None
elif isinstance(obj, (int, float)):
return self.valid_fn(obj)
coerced = self.coerce_if_required(obj, **kwargs)
if coerced is not None:
self.valid_fn(coerced)
return coerced
else:
raise AttributeError(f"Expected type {self.runtime_kind} but got {type(obj).__name__}")
def coerce_if_required(self, value: JsonElement, **kwargs: bool) -> Optional[Union[int, float]]:
if value is None:
return value
elif isinstance(value, (int, float)):
return None
else:
try:
return int(value) if self.runtime_kind in ("int32", "int64") else float(value) # type: ignore
except ValueError:
return None
def as_json(self, **kwargs: bool) -> Json:
js = super().as_json(**kwargs)
if self.enum:
js["enum"] = self.enum
if self.minimum:
js["minimum"] = self.minimum
if self.maximum:
js["maximum"] = self.maximum
return js
class BooleanKind(SimpleKind):
def __init__(self, fqn: str):
super().__init__(fqn, "boolean")
self.valid_fn = check_type_fn(bool, "boolean")
def check_valid(self, obj: JsonElement, **kwargs: bool) -> ValidationResult:
if obj is True or obj is False or obj is None:
return None
elif should_skip_env_var_str(obj, kwargs):
return None
coerced = self.coerce_if_required(obj, **kwargs)
if coerced is not None:
return coerced
else:
raise AttributeError(f"Expected type boolean but got {type(obj).__name__}")
def coerce_if_required(self, value: JsonElement, **kwargs: bool) -> Optional[bool]:
if value is None:
return value
elif isinstance(value, bool):
return None
elif isinstance(value, str) and value.lower() in ("true", "yes", "on"):
return True
elif isinstance(value, str) and value.lower() in ("false", "no", "off"):
return False
else:
return None
class DurationKind(SimpleKind):
def __init__(self, fqn: str):
super().__init__(fqn, "duration")
self.valid_fn = validate_fn(check_type_fn(str, "duration"), self.check_duration)
def check_duration(self, v: Any) -> None:
if not DurationRe.fullmatch(v):
raise AttributeError(f"Wrong format for duration: {v}. Examples: 1yr, 3mo, 3d4h3min1s, 3days and 2hours")
def check_valid(self, obj: JsonElement, **kwargs: bool) -> ValidationResult:
if should_skip_env_var_str(obj, kwargs):
return None
return self.valid_fn(obj)
def coerce_if_required(self, value: Any, **kwargs: bool) -> Optional[str]:
try:
return f"{int(duration_parser.parse(value))}s" if kwargs.get("normalize", True) else None
except Exception:
return None
class DateTimeKind(SimpleKind):
Format = "%Y-%m-%dT%H:%M:%SZ"
DateTimeRe = re.compile("\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z")
def __init__(self, fqn: str):
super().__init__(fqn, "datetime")
self.valid_fn = validate_fn(check_type_fn(str, "datetime"), self.check_datetime)
@staticmethod
def parse_datetime(date_string: str) -> Optional[datetime]:
try:
return datetime.strptime(date_string, DateTimeKind.Format)
except ValueError:
return None
@staticmethod
def check_datetime(obj: Any) -> ValidationResult:
def parse_datetime() -> str:
parsed = datetime.fromisoformat(str(obj))
utc_parsed = datetime.fromtimestamp(parsed.timestamp(), tz=timezone.utc)
return utc_parsed.strftime(DateTimeKind.Format)
return None if DateTimeKind.DateTimeRe.fullmatch(obj) else parse_datetime()
def check_valid(self, obj: JsonElement, **kwargs: bool) -> ValidationResult:
if should_skip_env_var_str(obj, kwargs):
return None
return self.valid_fn(obj)
def coerce_if_required(self, value: JsonElement, **kwargs: bool) -> Optional[str]:
try:
if value is None:
return value
elif not isinstance(value, str):
return None
elif self.DateTimeRe.fullmatch(value):
return None
elif DurationRe.fullmatch(value):
return self.from_duration(value)
else:
return self.from_datetime(value)
except Exception:
return None
@staticmethod
def from_datetime(value: str) -> str:
try:
dt = datetime.fromisoformat(value)
except Exception:
dt = parse(value)
if (
not dt.tzinfo
or dt.tzinfo.utcoffset(None) is None
or dt.tzinfo.utcoffset(None).total_seconds() != 0 # type: ignore
):
dt = dt.astimezone(timezone.utc)
return dt.strftime(DateTimeKind.Format)
@staticmethod
def from_duration(value: str, now: datetime = utc()) -> str:
# in case of duration, compute the timestamp as: now + duration
delta = duration(value)
instant = now + delta
return instant.strftime(DateTimeKind.Format)
class DateKind(SimpleKind):
Format = "%Y-%m-%d"
DateRe = re.compile("\\d{4}-\\d{2}-\\d{2}")
def __init__(self, fqn: str):
super().__init__(fqn, "date")
self.valid_fn = validate_fn(check_type_fn(str, "date"), self.check_date)
@staticmethod
def check_date(obj: Any) -> ValidationResult:
return None if DateKind.DateRe.fullmatch(obj) else date.fromisoformat(obj)
def check_valid(self, obj: JsonElement, **kwargs: bool) -> ValidationResult:
if should_skip_env_var_str(obj, kwargs):
return None
return self.valid_fn(obj)
def coerce_if_required(self, value: JsonElement, **kwargs: bool) -> Optional[str]:
try:
if value is None:
return value
elif not isinstance(value, str):
return None
elif DurationRe.fullmatch(value):
# in case of duration, compute the timestamp as: today + duration
delta = duration(value)
at = date.today() + delta
return at.isoformat()
else:
return parse(value).date().strftime(DateKind.Format)
except Exception:
return None
class TransformKind(SimpleKind):
"""
Transform kinds can be used to derive attributes in a complex kind from other attributes.
It is important, that the transformed attribute does not exist in the original complex kind!
It is a SimpleKind, since it can be queried directly as if it would be available as part of the json.
A transformed kind takes a source value of kind source_kind and transforms it using a function
into the destination kind.
:param fqn: the fully qualified name of this kind.
:param source_fqn: the underlying runtime kind.
:param destination_fqn: the destination kind that is used in the data store.
:param converter: name of converter. See transform_kind_convert.py for a dict of possible converter names.
"""
def __init__(self, fqn: str, source_fqn: str, destination_fqn: str, converter: str, reverse_order: bool):
# note: source_fqn and runtime_kind are considered the same.
# the synthetic property does not introduce a new type, but translates types.
super().__init__(fqn, source_fqn, reverse_order)
self.destination_fqn: str = destination_fqn
self.source_kind: Optional[SimpleKind] = None
self.destination_kind: Optional[SimpleKind] = None
self.converter = converter
self.source_to_destination, self.destination_to_source = converters[converter]
def coerce_if_required(self, value: JsonElement, **kwargs: bool) -> Optional[JsonElement]:
if value is None:
return None
elif self.source_kind:
coerced_source = self.source_kind.coerce(value)
real = self.source_to_destination(coerced_source) # type: ignore
return real
else:
return None
def transform(self, value: Any) -> Any:
if value is None:
return None
elif self.destination_kind:
real_coerced = self.destination_kind.coerce(value)
synth = self.destination_to_source(real_coerced) # type: ignore
return synth
else:
raise AttributeError(f"Synthetic kind is not resolved: {self.fqn}")
def check_valid(self, obj: JsonElement, **kwargs: bool) -> ValidationResult:
# this function is called during import for supplied values.
# synthetic values are never supplied
raise AttributeError(f"TransformKind {self.fqn} is not allowed to be supplied.")
def resolve(self, model: Dict[str, Kind]) -> None:
source = model.get(self.runtime_kind)
destination = model.get(self.destination_fqn)
if source and destination and isinstance(source, SimpleKind) and isinstance(destination, SimpleKind):
source.resolve(model)
destination.resolve(model)
self.source_kind = source
self.destination_kind = destination
else:
raise AttributeError(f"Underlying kind not known: {self.destination_fqn}")
def as_json(self, **kwargs: bool) -> Json:
return {
"fqn": self.fqn,
"runtime_kind": self.runtime_kind,
"source_fqn": self.destination_fqn,
"converter": self.converter,
"reverse_order": self.reverse_order,
}
class ArrayKind(Kind):
def __init__(self, inner: Kind):
super().__init__(f"{inner.fqn}[]")
self.inner = inner
def as_json(self, **kwargs: bool) -> Json:
return {"fqn": self.fqn, "inner": self.inner.as_json(**kwargs)}
def resolve(self, model: Dict[str, Kind]) -> None:
self.inner.resolve(model)
def check_valid(self, obj: JsonElement, **kwargs: bool) -> ValidationResult:
if isinstance(obj, dict):
# list is expected, but object found
raise AttributeError("Expected property is a json object not an array!")
coerced = self.coerce_if_required(obj, **kwargs)
for elem in coerced or obj: # type: ignore
self.inner.check_valid(elem, **kwargs)
return coerced
def coerce_if_required(self, value: JsonElement, **kwargs: bool) -> Optional[List[JsonElement]]:
has_coerced = False
if value is None:
return None
elif isinstance(value, dict):
return None
elif not isinstance(value, list):
# in case of simple type, we can make it an array
value = [value]
has_coerced = True
def check(item: Any) -> ValidationResult:
nonlocal has_coerced
res = self.inner.coerce_if_required(item, **kwargs)
if res is None:
return item
else:
has_coerced = True
return res
mapped = [check(elem) for elem in value]
return mapped if has_coerced else None
@staticmethod
def mk_array(kind: Kind, depth: int) -> Kind:
return kind if depth == 0 else ArrayKind(ArrayKind.mk_array(kind, depth - 1))
class DictionaryKind(Kind):
def __init__(self, key_kind: Kind, value_kind: Kind):
super().__init__(f"dictionary[{key_kind.fqn}, {value_kind.fqn}]")
self.key_kind = key_kind
self.value_kind = value_kind
def as_json(self, **kwargs: bool) -> Json:
return {
"fqn": self.fqn,
"key_kind": self.key_kind.as_json(**kwargs),
"value_kind": self.value_kind.as_json(**kwargs),
}
def check_valid(self, obj: JsonElement, **kwargs: bool) -> ValidationResult:
if isinstance(obj, dict):
coerced = self.coerce_if_required(obj, **kwargs)
for prop, value in (coerced or obj).items():
part = "key"
try:
self.key_kind.check_valid(prop, **kwargs)
part = "value"
self.value_kind.check_valid(value, **kwargs)
except Exception as at:
raise AttributeError(f"{part} of {self.fqn} is not valid: {at}") from at
return coerced
else:
raise AttributeError(f"dictionary requires a json object, but got this: {obj}")
def coerce_if_required(self, value: JsonElement, **kwargs: bool) -> Optional[Json]:
if isinstance(value, dict):
coerced: Json = {}
has_coerced = False
for p, v in value.items():
ck = self.key_kind.coerce_if_required(p, **kwargs)
cv = self.value_kind.coerce_if_required(v, **kwargs)
coerced[ck or p] = cv or v # type: ignore
if ck is not None or cv is not None:
has_coerced = True
return coerced if has_coerced else None
else:
return None
def resolve(self, model: Dict[str, Kind]) -> None:
self.key_kind.resolve(model)
self.value_kind.resolve(model)
class ComplexKind(Kind):
def __init__(
self,
fqn: str,
bases: List[str],
properties: List[Property],
allow_unknown_props: bool = False,
# EdgeType -> possible list of successor kinds
successor_kinds: Optional[Dict[EdgeType, List[str]]] = None,
aggregate_root: bool = True,
metadata: Optional[Json] = None,
):
super().__init__(fqn)
self.bases = bases
self.properties = properties
self.allow_unknown_props = allow_unknown_props
self.successor_kinds = successor_kinds or {}
self.aggregate_root = aggregate_root
self.metadata = metadata or {}
self._predecessor_kinds: Dict[EdgeType, List[str]] = {}
self.__prop_by_name = {prop.name: prop for prop in properties}
self.__resolved = False
self.__resolved_kinds: Dict[str, Tuple[Property, Kind]] = {}
self.__resolved_bases: Dict[str, ComplexKind] = {}
self.__all_props: List[Property] = list(self.properties)
self.__resolved_hierarchy: Set[str] = {fqn}
self.__property_by_path: List[ResolvedProperty] = []
self.__synthetic_props: List[ResolvedProperty] = []
def as_json(self, **kwargs: bool) -> Json:
result: Json = {"fqn": self.fqn, "aggregate_root": self.aggregate_root}
if kwargs.get("with_metadata", True):
result["metadata"] = self.metadata
if kwargs.get("with_properties", True):
result["allow_unknown_props"] = self.allow_unknown_props
result["properties"] = [to_js(prop) for prop in self.properties]
if kwargs.get("with_relatives", True):
result["bases"] = self.bases
result["successor_kinds"] = self.successor_kinds
return result
def copy(
self,
*,
bases: Optional[List[str]] = None,
properties: Optional[List[Property]] = None,
successor_kinds: Optional[Dict[EdgeType, List[str]]] = None,
predecessor_kinds: Optional[Dict[EdgeType, List[str]]] = None,
metadata: Optional[Json] = None,
) -> ComplexKind:
result = copy.copy(self)
result.bases = bases or self.bases
result.properties = properties or self.properties
result.successor_kinds = successor_kinds or self.successor_kinds
result._predecessor_kinds = predecessor_kinds or self._predecessor_kinds
result.metadata = metadata or self.metadata
return result
def resolve(self, model: Dict[str, Kind]) -> None:
if not self.__resolved:
self.__resolved = True
# resolve properties
for prop in self.properties:
kind = prop.resolve(model)
kind.resolve(model)
self.__resolved_kinds[prop.name] = (prop, kind)
# make sure all successor kinds can be resolved
for names in self.successor_kinds.values():
for name in names or []:
if name not in model:
raise AttributeError(f"{name} is not a known kind")
# resolve the hierarchy
if not self.is_root():
for base_name in self.bases:
base: Kind = model[base_name]
base.resolve(model)
if isinstance(base, ComplexKind):
self.__resolved_bases[base_name] = base
self.__resolved_kinds.update(base.__resolved_kinds)
self.__all_props = base.__all_props + self.__all_props
self.__prop_by_name = {prop.name: prop for prop in self.__all_props}
self.__resolved_hierarchy.update(base.__resolved_hierarchy)
# property path -> kind
self.__property_by_path = ComplexKind.resolve_properties(self, model)
self.__synthetic_props = [p for p in self.__property_by_path if p.prop.synthetic]
# resolve predecessor kinds
self._predecessor_kinds = {
edge_type: [
kind.fqn
for kind in model.values()
if isinstance(kind, ComplexKind) and self.fqn in kind.successor_kinds.get(edge_type, [])
]
for edge_type in AvailableEdgeTypes
}
def __eq__(self, other: Any) -> bool:
if isinstance(other, ComplexKind):
return (
self.fqn == other.fqn
and self.properties == other.properties
and self.bases == other.bases
and self.allow_unknown_props == other.allow_unknown_props
and self.successor_kinds == other.successor_kinds
and self.aggregate_root == other.aggregate_root
and self.metadata == other.metadata
)
else:
return False
def __contains__(self, name: str) -> bool:
return name in self.__prop_by_name
def __getitem__(self, name: str) -> Property:
return self.__prop_by_name[name]
def property_kind_of(self, name: str, or_else: Kind) -> Kind:
maybe = self.__resolved_kinds.get(name)
return maybe[1] if maybe else or_else
def property_with_kind_of(self, name: str) -> Optional[Tuple[Property, Kind]]:
return self.__resolved_kinds.get(name)
def property_with_kinds(self) -> Iterable[Tuple[Property, Kind]]:
return self.__resolved_kinds.values()
def is_root(self) -> bool:
return not self.bases or (len(self.bases) == 1 and self.bases[0] == self.fqn)
def kind_hierarchy(self) -> Set[str]:
return self.__resolved_hierarchy
def resolved_properties(self) -> List[ResolvedProperty]:
return self.__property_by_path
def resolved_bases(self) -> Dict[str, ComplexKind]:
return self.__resolved_bases
def all_props(self) -> List[Property]:
return self.__all_props