cedarkit-query 0.2.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- cedarkit_query/__init__.py +61 -0
- cedarkit_query/_json.py +124 -0
- cedarkit_query/errors.py +152 -0
- cedarkit_query/model.py +365 -0
- cedarkit_query/normalize.py +967 -0
- cedarkit_query/parameters.py +102 -0
- cedarkit_query/resources.py +268 -0
- cedarkit_query/schemas/catalog-v1.schema.json +369 -0
- cedarkit_query/schemas/common-v1.schema.json +3067 -0
- cedarkit_query/schemas/context-v1.schema.json +6 -0
- cedarkit_query/schemas/error-v1.schema.json +87 -0
- cedarkit_query/schemas/explanation-v1.schema.json +168 -0
- cedarkit_query/schemas/mappings-v1.schema.json +526 -0
- cedarkit_query/schemas/parameters-v1.schema.json +84 -0
- cedarkit_query/schemas/query-v1.schema.json +6 -0
- cedarkit_query/schemas/report-v1.schema.json +69 -0
- cedarkit_query/schemas/request-v1.schema.json +45 -0
- cedarkit_query/validation.py +202 -0
- cedarkit_query-0.2.1.dist-info/METADATA +41 -0
- cedarkit_query-0.2.1.dist-info/RECORD +23 -0
- cedarkit_query-0.2.1.dist-info/WHEEL +5 -0
- cedarkit_query-0.2.1.dist-info/licenses/LICENSE +202 -0
- cedarkit_query-0.2.1.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
"""CedarKit's single query/request and resource contracts. No business I/O."""
|
|
2
|
+
|
|
3
|
+
from .errors import CompletenessError, QueryError, SourceError
|
|
4
|
+
from .model import (
|
|
5
|
+
Catalog,
|
|
6
|
+
Context,
|
|
7
|
+
ErrorValue,
|
|
8
|
+
Mappings,
|
|
9
|
+
Parameters,
|
|
10
|
+
Query,
|
|
11
|
+
QueryExplanation,
|
|
12
|
+
QueryReport,
|
|
13
|
+
Request,
|
|
14
|
+
dump_value,
|
|
15
|
+
get_schema,
|
|
16
|
+
load_request,
|
|
17
|
+
load_value,
|
|
18
|
+
validate_value,
|
|
19
|
+
)
|
|
20
|
+
from .normalize import (
|
|
21
|
+
DEFAULT_MAX_EXPANSION,
|
|
22
|
+
combine_queries,
|
|
23
|
+
constrain_query,
|
|
24
|
+
expand_queries,
|
|
25
|
+
intersect_queries,
|
|
26
|
+
intersect_scopes,
|
|
27
|
+
normalize_query,
|
|
28
|
+
query_identity,
|
|
29
|
+
)
|
|
30
|
+
from .parameters import prepare_queries
|
|
31
|
+
from .resources import validate_resource_set
|
|
32
|
+
|
|
33
|
+
__all__ = [
|
|
34
|
+
"Query",
|
|
35
|
+
"Request",
|
|
36
|
+
"QueryReport",
|
|
37
|
+
"QueryExplanation",
|
|
38
|
+
"QueryError",
|
|
39
|
+
"CompletenessError",
|
|
40
|
+
"SourceError",
|
|
41
|
+
"ErrorValue",
|
|
42
|
+
"Catalog",
|
|
43
|
+
"Parameters",
|
|
44
|
+
"Mappings",
|
|
45
|
+
"validate_resource_set",
|
|
46
|
+
"Context",
|
|
47
|
+
"load_value",
|
|
48
|
+
"load_request",
|
|
49
|
+
"dump_value",
|
|
50
|
+
"get_schema",
|
|
51
|
+
"validate_value",
|
|
52
|
+
"normalize_query",
|
|
53
|
+
"prepare_queries",
|
|
54
|
+
"expand_queries",
|
|
55
|
+
"intersect_queries",
|
|
56
|
+
"intersect_scopes",
|
|
57
|
+
"constrain_query",
|
|
58
|
+
"combine_queries",
|
|
59
|
+
"query_identity",
|
|
60
|
+
"DEFAULT_MAX_EXPANSION",
|
|
61
|
+
]
|
cedarkit_query/_json.py
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
"""Strict JSON copying, immutable containers, and duplicate-safe text parsing."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import math
|
|
7
|
+
from collections.abc import Mapping
|
|
8
|
+
from types import MappingProxyType
|
|
9
|
+
|
|
10
|
+
import yaml
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def pointer(parts):
|
|
14
|
+
return "".join("/" + str(p).replace("~", "~0").replace("/", "~1") for p in parts)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def plain(value, path="", active=None):
|
|
18
|
+
from .model import ProtocolValue
|
|
19
|
+
|
|
20
|
+
if isinstance(value, ProtocolValue):
|
|
21
|
+
value = value.to_dict()
|
|
22
|
+
if value is None or type(value) in (str, bool, int):
|
|
23
|
+
return value
|
|
24
|
+
if type(value) is float and math.isfinite(value):
|
|
25
|
+
return value
|
|
26
|
+
if active is None:
|
|
27
|
+
active = set()
|
|
28
|
+
if isinstance(value, (Mapping, list, tuple)):
|
|
29
|
+
if id(value) in active:
|
|
30
|
+
raise ValueError(f"{path}: cyclic value")
|
|
31
|
+
active.add(id(value))
|
|
32
|
+
try:
|
|
33
|
+
if isinstance(value, Mapping):
|
|
34
|
+
if any(not isinstance(k, str) for k in value):
|
|
35
|
+
raise ValueError(f"{path}: object keys must be strings")
|
|
36
|
+
return {
|
|
37
|
+
k: plain(v, path + pointer([k]), active) for k, v in value.items()
|
|
38
|
+
}
|
|
39
|
+
return [plain(v, path + pointer([i]), active) for i, v in enumerate(value)]
|
|
40
|
+
finally:
|
|
41
|
+
active.remove(id(value))
|
|
42
|
+
raise ValueError(f"{path}: unsupported JSON value {type(value).__name__}")
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def freeze(value):
|
|
46
|
+
if isinstance(value, dict):
|
|
47
|
+
return MappingProxyType({k: freeze(v) for k, v in value.items()})
|
|
48
|
+
if isinstance(value, list):
|
|
49
|
+
return tuple(freeze(v) for v in value)
|
|
50
|
+
return value
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def thaw(value):
|
|
54
|
+
if isinstance(value, Mapping):
|
|
55
|
+
return {k: thaw(v) for k, v in value.items()}
|
|
56
|
+
if isinstance(value, tuple):
|
|
57
|
+
return [thaw(v) for v in value]
|
|
58
|
+
return value
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def canonical(value):
|
|
62
|
+
return json.dumps(
|
|
63
|
+
plain(value),
|
|
64
|
+
ensure_ascii=False,
|
|
65
|
+
allow_nan=False,
|
|
66
|
+
sort_keys=True,
|
|
67
|
+
separators=(",", ":"),
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _pairs(pairs):
|
|
72
|
+
result = {}
|
|
73
|
+
for key, value in pairs:
|
|
74
|
+
if key in result:
|
|
75
|
+
raise ValueError(f"duplicate JSON key: {key}")
|
|
76
|
+
result[key] = value
|
|
77
|
+
return result
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
class _Loader(yaml.SafeLoader):
|
|
81
|
+
pass
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
_Loader.yaml_implicit_resolvers = {
|
|
85
|
+
k: [(tag, regex) for tag, regex in values if tag != "tag:yaml.org,2002:timestamp"]
|
|
86
|
+
for k, values in yaml.SafeLoader.yaml_implicit_resolvers.items()
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _mapping(loader, node):
|
|
91
|
+
result = {}
|
|
92
|
+
for key_node, value_node in node.value:
|
|
93
|
+
key = loader.construct_object(key_node, deep=True)
|
|
94
|
+
if not isinstance(key, str):
|
|
95
|
+
raise ValueError("YAML object keys must be strings")
|
|
96
|
+
if key in result:
|
|
97
|
+
raise ValueError(f"duplicate YAML key: {key}")
|
|
98
|
+
result[key] = loader.construct_object(value_node, deep=True)
|
|
99
|
+
return result
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
_Loader.add_constructor(yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, _mapping)
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def parse(text, format=None):
|
|
106
|
+
selected = format or ("json" if text.lstrip().startswith(("{", "[")) else "yaml")
|
|
107
|
+
if selected == "json":
|
|
108
|
+
|
|
109
|
+
def nonfinite(token):
|
|
110
|
+
raise ValueError(f"non-finite JSON number: {token}")
|
|
111
|
+
|
|
112
|
+
return json.loads(text, object_pairs_hook=_pairs, parse_constant=nonfinite)
|
|
113
|
+
if selected == "yaml":
|
|
114
|
+
return yaml.load(text, Loader=_Loader)
|
|
115
|
+
raise ValueError(f"unsupported format: {selected}")
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def serialize(value, format="json"):
|
|
119
|
+
value = plain(value)
|
|
120
|
+
if format == "json":
|
|
121
|
+
return json.dumps(value, ensure_ascii=False, allow_nan=False, indent=2) + "\n"
|
|
122
|
+
if format == "yaml":
|
|
123
|
+
return yaml.safe_dump(value, allow_unicode=True, sort_keys=False)
|
|
124
|
+
raise ValueError(f"unsupported format: {format}")
|
cedarkit_query/errors.py
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
"""Public errors. No backend imports or conversion of arbitrary exceptions."""
|
|
2
|
+
|
|
3
|
+
import re
|
|
4
|
+
|
|
5
|
+
from ._json import freeze, plain, thaw
|
|
6
|
+
|
|
7
|
+
QUERY_CODES = frozenset(
|
|
8
|
+
{
|
|
9
|
+
"invalid_request",
|
|
10
|
+
"unsupported_version",
|
|
11
|
+
"invalid_config",
|
|
12
|
+
"invalid_query",
|
|
13
|
+
"constraint_conflict",
|
|
14
|
+
"unsupported",
|
|
15
|
+
"expansion_limit_exceeded",
|
|
16
|
+
"no_match",
|
|
17
|
+
"multiple_matches",
|
|
18
|
+
"missing_fields",
|
|
19
|
+
"completeness_undetermined",
|
|
20
|
+
"duplicate_field",
|
|
21
|
+
"incompatible_grid",
|
|
22
|
+
"multiple_variables",
|
|
23
|
+
}
|
|
24
|
+
)
|
|
25
|
+
SOURCE_CODES = frozenset(
|
|
26
|
+
{
|
|
27
|
+
"resource_not_found",
|
|
28
|
+
"permission_denied",
|
|
29
|
+
"authentication_failed",
|
|
30
|
+
"timeout",
|
|
31
|
+
"decode_failed",
|
|
32
|
+
"io_error",
|
|
33
|
+
"service_error",
|
|
34
|
+
"metadata_interpretation_failed",
|
|
35
|
+
"incomplete_response",
|
|
36
|
+
}
|
|
37
|
+
)
|
|
38
|
+
METADATA_REASONS = frozenset(
|
|
39
|
+
{
|
|
40
|
+
"missing_native_metadata",
|
|
41
|
+
"unmapped_native_value",
|
|
42
|
+
"invalid_vertical_metadata",
|
|
43
|
+
"inconsistent_native_metadata",
|
|
44
|
+
"fixed_definition_mismatch",
|
|
45
|
+
"invalid_time_metadata",
|
|
46
|
+
"invalid_member_metadata",
|
|
47
|
+
"invalid_statistics_metadata",
|
|
48
|
+
"unsupported_native_encoding",
|
|
49
|
+
}
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class _Error:
|
|
54
|
+
@property
|
|
55
|
+
def code(self):
|
|
56
|
+
return self._data["code"]
|
|
57
|
+
|
|
58
|
+
@property
|
|
59
|
+
def path(self):
|
|
60
|
+
return self._data["path"]
|
|
61
|
+
|
|
62
|
+
@property
|
|
63
|
+
def message(self):
|
|
64
|
+
return self._data["message"]
|
|
65
|
+
|
|
66
|
+
@property
|
|
67
|
+
def context(self):
|
|
68
|
+
return self._data["context"]
|
|
69
|
+
|
|
70
|
+
def _init(self, code, path, message, context):
|
|
71
|
+
if (
|
|
72
|
+
not isinstance(path, str)
|
|
73
|
+
or re.fullmatch(r"(?:/(?:[^~]|~[01])*)?", path) is None
|
|
74
|
+
):
|
|
75
|
+
raise ValueError("path must be a JSON Pointer")
|
|
76
|
+
if not isinstance(message, str) or not message.strip():
|
|
77
|
+
raise ValueError("message must be nonempty")
|
|
78
|
+
context = {} if context is None else plain(context)
|
|
79
|
+
if not isinstance(context, dict):
|
|
80
|
+
raise ValueError("context must be an object")
|
|
81
|
+
self._data = freeze(
|
|
82
|
+
{
|
|
83
|
+
"api_version": "cedarkit.error/v1",
|
|
84
|
+
"code": code,
|
|
85
|
+
"path": path,
|
|
86
|
+
"message": message,
|
|
87
|
+
"context": context,
|
|
88
|
+
}
|
|
89
|
+
)
|
|
90
|
+
super().__init__(f"{code} at {path or '/'}: {message}")
|
|
91
|
+
|
|
92
|
+
def to_dict(self):
|
|
93
|
+
return thaw(self._data)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
class QueryError(_Error, ValueError):
|
|
97
|
+
def __init__(self, code, path="", message="Query failed", context=None):
|
|
98
|
+
if code not in QUERY_CODES:
|
|
99
|
+
raise ValueError(f"unknown QueryError code: {code}")
|
|
100
|
+
if (
|
|
101
|
+
code in {"missing_fields", "completeness_undetermined"}
|
|
102
|
+
and type(self) is QueryError
|
|
103
|
+
):
|
|
104
|
+
raise ValueError(
|
|
105
|
+
"completeness codes require CompletenessError and a report"
|
|
106
|
+
)
|
|
107
|
+
self._init(code, path, message, context)
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
class SourceError(_Error, RuntimeError):
|
|
111
|
+
def __init__(self, code, path="", message="Source failed", context=None):
|
|
112
|
+
if code not in SOURCE_CODES:
|
|
113
|
+
raise ValueError(f"unknown SourceError code: {code}")
|
|
114
|
+
reason = (context or {}).get("reason")
|
|
115
|
+
if code == "metadata_interpretation_failed" and reason not in METADATA_REASONS:
|
|
116
|
+
raise ValueError("metadata interpretation requires a registered reason")
|
|
117
|
+
if code == "incomplete_response" and reason not in {
|
|
118
|
+
"response_truncated",
|
|
119
|
+
"pagination_incomplete",
|
|
120
|
+
}:
|
|
121
|
+
raise ValueError("incomplete response requires a registered reason")
|
|
122
|
+
self._init(code, path, message, context)
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
class CompletenessError(QueryError):
|
|
126
|
+
def __init__(
|
|
127
|
+
self,
|
|
128
|
+
code,
|
|
129
|
+
path="",
|
|
130
|
+
message="Completeness check failed",
|
|
131
|
+
*,
|
|
132
|
+
report,
|
|
133
|
+
context=None,
|
|
134
|
+
):
|
|
135
|
+
from .model import QueryReport
|
|
136
|
+
|
|
137
|
+
if code not in {"missing_fields", "completeness_undetermined"}:
|
|
138
|
+
raise ValueError("invalid CompletenessError code")
|
|
139
|
+
self._report = (
|
|
140
|
+
report if isinstance(report, QueryReport) else QueryReport(report)
|
|
141
|
+
)
|
|
142
|
+
status = self._report.overall["status"]
|
|
143
|
+
if status != ("missing" if code == "missing_fields" else "unchecked"):
|
|
144
|
+
raise ValueError("completeness code and report disagree")
|
|
145
|
+
super().__init__(code, path, message, context)
|
|
146
|
+
|
|
147
|
+
@property
|
|
148
|
+
def report(self):
|
|
149
|
+
return self._report
|
|
150
|
+
|
|
151
|
+
def to_dict(self):
|
|
152
|
+
return {**super().to_dict(), "report": self.report.to_dict()}
|
cedarkit_query/model.py
ADDED
|
@@ -0,0 +1,365 @@
|
|
|
1
|
+
"""Immutable declaration values and the single Python/JSON/YAML validation path."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Mapping
|
|
6
|
+
from functools import lru_cache
|
|
7
|
+
from importlib.resources import files
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import ClassVar
|
|
10
|
+
from yaml import YAMLError
|
|
11
|
+
import os
|
|
12
|
+
|
|
13
|
+
from jsonschema import Draft202012Validator, validators
|
|
14
|
+
from referencing import Registry, Resource
|
|
15
|
+
|
|
16
|
+
from ._json import freeze, parse, plain, pointer, serialize, thaw
|
|
17
|
+
from .errors import QueryError
|
|
18
|
+
|
|
19
|
+
KINDS = (
|
|
20
|
+
"common",
|
|
21
|
+
"query",
|
|
22
|
+
"context",
|
|
23
|
+
"request",
|
|
24
|
+
"report",
|
|
25
|
+
"explanation",
|
|
26
|
+
"error",
|
|
27
|
+
"catalog",
|
|
28
|
+
"parameters",
|
|
29
|
+
"mappings",
|
|
30
|
+
)
|
|
31
|
+
VERSIONS = {
|
|
32
|
+
"request": "cedarkit.request/v1",
|
|
33
|
+
"error": "cedarkit.error/v1",
|
|
34
|
+
"catalog": "cedarkit.catalog/v1",
|
|
35
|
+
"parameters": "cedarkit.parameters/v1",
|
|
36
|
+
"mappings": "cedarkit.mappings/v1",
|
|
37
|
+
}
|
|
38
|
+
StrictValidator = validators.extend(
|
|
39
|
+
Draft202012Validator,
|
|
40
|
+
type_checker=Draft202012Validator.TYPE_CHECKER.redefine(
|
|
41
|
+
"integer", lambda checker, value: type(value) is int
|
|
42
|
+
),
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def get_schema(kind):
|
|
47
|
+
if kind not in KINDS:
|
|
48
|
+
raise ValueError(f"unknown schema kind: {kind}")
|
|
49
|
+
import json
|
|
50
|
+
|
|
51
|
+
return json.loads(
|
|
52
|
+
files("cedarkit_query")
|
|
53
|
+
.joinpath("schemas", f"{kind}-v1.schema.json")
|
|
54
|
+
.read_text()
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
@lru_cache(maxsize=len(KINDS))
|
|
59
|
+
def _validator(kind):
|
|
60
|
+
schemas = [get_schema(k) for k in KINDS]
|
|
61
|
+
registry = Registry().with_resources(
|
|
62
|
+
(s["$id"], Resource.from_contents(s)) for s in schemas
|
|
63
|
+
)
|
|
64
|
+
return StrictValidator(get_schema(kind), registry=registry)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _best(error):
|
|
68
|
+
"""Prefer the matching discriminator/type branch of a oneOf diagnostic."""
|
|
69
|
+
if not error.context:
|
|
70
|
+
return error
|
|
71
|
+
groups = {}
|
|
72
|
+
for child in error.context:
|
|
73
|
+
groups.setdefault(child.schema_path[0], []).append(child)
|
|
74
|
+
|
|
75
|
+
def rank(children):
|
|
76
|
+
return (sum(e.validator in {"const", "type"} for e in children), len(children))
|
|
77
|
+
|
|
78
|
+
children = min(groups.values(), key=rank)
|
|
79
|
+
return min(
|
|
80
|
+
(_best(c) for c in children), key=lambda e: (-len(e.absolute_path), e.message)
|
|
81
|
+
)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def validate_value(value, kind):
|
|
85
|
+
"""Structure plus shared semantic validation; never loads referenced resources."""
|
|
86
|
+
if kind not in KINDS or kind == "common":
|
|
87
|
+
raise ValueError(f"not a value kind: {kind}")
|
|
88
|
+
code = (
|
|
89
|
+
"invalid_query"
|
|
90
|
+
if kind == "query"
|
|
91
|
+
else "invalid_request"
|
|
92
|
+
if kind == "request"
|
|
93
|
+
else "invalid_config"
|
|
94
|
+
)
|
|
95
|
+
try:
|
|
96
|
+
data = plain(value)
|
|
97
|
+
except ValueError as exc:
|
|
98
|
+
location, _, message = str(exc).partition(": ")
|
|
99
|
+
raise QueryError(
|
|
100
|
+
code, location if location.startswith("/") else "", message or str(exc)
|
|
101
|
+
) from exc
|
|
102
|
+
if isinstance(data, dict):
|
|
103
|
+
if (
|
|
104
|
+
kind in VERSIONS
|
|
105
|
+
and "api_version" in data
|
|
106
|
+
and isinstance(data["api_version"], str)
|
|
107
|
+
and data["api_version"] != VERSIONS[kind]
|
|
108
|
+
):
|
|
109
|
+
raise QueryError(
|
|
110
|
+
"unsupported_version", "/api_version", "unsupported format version"
|
|
111
|
+
)
|
|
112
|
+
if (
|
|
113
|
+
kind == "report"
|
|
114
|
+
and "schema_version" in data
|
|
115
|
+
and type(data["schema_version"]) is int
|
|
116
|
+
and data["schema_version"] != 1
|
|
117
|
+
):
|
|
118
|
+
raise QueryError(
|
|
119
|
+
"unsupported_version", "/schema_version", "unsupported report version"
|
|
120
|
+
)
|
|
121
|
+
error = next(_validator(kind).iter_errors(data), None)
|
|
122
|
+
if error is not None:
|
|
123
|
+
error = _best(error)
|
|
124
|
+
parts = list(error.absolute_path)
|
|
125
|
+
if error.validator == "required" and isinstance(error.instance, dict):
|
|
126
|
+
parts.append(
|
|
127
|
+
next(k for k in error.validator_value if k not in error.instance)
|
|
128
|
+
)
|
|
129
|
+
elif error.validator == "additionalProperties" and isinstance(
|
|
130
|
+
error.instance, dict
|
|
131
|
+
):
|
|
132
|
+
extras = set(error.instance) - set(error.schema.get("properties", {}))
|
|
133
|
+
if extras:
|
|
134
|
+
parts.append(sorted(extras)[0])
|
|
135
|
+
if kind == "request" and parts:
|
|
136
|
+
if parts[0] == "queries" and len(parts) > 1:
|
|
137
|
+
code = "invalid_query"
|
|
138
|
+
elif parts[0] in {"source", "context"}:
|
|
139
|
+
code = "invalid_config"
|
|
140
|
+
raise QueryError(code, pointer(parts), error.message)
|
|
141
|
+
from .validation import validate_semantics
|
|
142
|
+
|
|
143
|
+
validate_semantics(data, kind)
|
|
144
|
+
return data
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def validate_fragment(value, name, *, path="", code="invalid_config"):
|
|
148
|
+
"""Validate a shared schema fragment without resolving business references."""
|
|
149
|
+
try:
|
|
150
|
+
data = plain(value)
|
|
151
|
+
except ValueError as exc:
|
|
152
|
+
raise QueryError(code, path, str(exc)) from exc
|
|
153
|
+
validator = _validator("context").evolve(
|
|
154
|
+
schema={"$ref": "urn:cedarkit:query:common:v1#/$defs/" + name}
|
|
155
|
+
)
|
|
156
|
+
error = next(validator.iter_errors(data), None)
|
|
157
|
+
if error is not None:
|
|
158
|
+
error = _best(error)
|
|
159
|
+
raise QueryError(code, path + pointer(error.absolute_path), error.message)
|
|
160
|
+
return data
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
class ProtocolValue:
|
|
164
|
+
_value: Mapping
|
|
165
|
+
KIND: ClassVar[str] = ""
|
|
166
|
+
|
|
167
|
+
def __setattr__(self, name, value):
|
|
168
|
+
raise AttributeError("protocol values are immutable")
|
|
169
|
+
|
|
170
|
+
def __delattr__(self, name):
|
|
171
|
+
raise AttributeError("protocol values are immutable")
|
|
172
|
+
|
|
173
|
+
def __eq__(self, other):
|
|
174
|
+
return type(self) is type(other) and self._value == other._value
|
|
175
|
+
|
|
176
|
+
__hash__ = None
|
|
177
|
+
|
|
178
|
+
def __init__(self, value):
|
|
179
|
+
object.__setattr__(self, "_value", freeze(validate_value(value, self.KIND)))
|
|
180
|
+
|
|
181
|
+
def to_dict(self):
|
|
182
|
+
return thaw(self._value)
|
|
183
|
+
|
|
184
|
+
def __getattr__(self, name):
|
|
185
|
+
if name in self._value:
|
|
186
|
+
return self._value[name]
|
|
187
|
+
raise AttributeError(name)
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
_UNSET = object()
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
class Query(ProtocolValue):
|
|
194
|
+
KIND = "query"
|
|
195
|
+
|
|
196
|
+
def __init__(self, value=_UNSET, **conditions):
|
|
197
|
+
if value is not _UNSET and conditions:
|
|
198
|
+
raise QueryError(
|
|
199
|
+
"invalid_query",
|
|
200
|
+
"",
|
|
201
|
+
"use a Query mapping or keyword conditions, not both",
|
|
202
|
+
)
|
|
203
|
+
super().__init__(conditions if value is _UNSET else value)
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
class Request(ProtocolValue):
|
|
207
|
+
KIND = "request"
|
|
208
|
+
|
|
209
|
+
def __init__(self, value, *, base_dir=None):
|
|
210
|
+
data = validate_value(value, "request")
|
|
211
|
+
base = Path.cwd() if base_dir is None else Path(base_dir).absolute()
|
|
212
|
+
|
|
213
|
+
def absolute(path):
|
|
214
|
+
return os.path.abspath(base / path)
|
|
215
|
+
|
|
216
|
+
source = data["source"]
|
|
217
|
+
for key in ("path", "directory", "root", "config"):
|
|
218
|
+
if key in source:
|
|
219
|
+
source[key] = (
|
|
220
|
+
[absolute(p) for p in source[key]]
|
|
221
|
+
if isinstance(source[key], list)
|
|
222
|
+
else absolute(source[key])
|
|
223
|
+
)
|
|
224
|
+
context = data.get("context")
|
|
225
|
+
if isinstance(context, str):
|
|
226
|
+
data["context"] = absolute(context)
|
|
227
|
+
elif isinstance(context, dict):
|
|
228
|
+
data["context"] = Context.from_dict(context, base_dir=base).to_dict()
|
|
229
|
+
object.__setattr__(self, "_value", freeze(data))
|
|
230
|
+
|
|
231
|
+
@classmethod
|
|
232
|
+
def from_dict(cls, data, *, base_dir=None):
|
|
233
|
+
return cls(data, base_dir=base_dir)
|
|
234
|
+
|
|
235
|
+
@classmethod
|
|
236
|
+
def load(cls, path):
|
|
237
|
+
path = Path(path).absolute()
|
|
238
|
+
try:
|
|
239
|
+
data = parse(path.read_text(encoding="utf-8"), _format(path))
|
|
240
|
+
except (OSError, ValueError, YAMLError) as exc:
|
|
241
|
+
raise QueryError(
|
|
242
|
+
"invalid_request", "", "cannot load request", {"document": str(path)}
|
|
243
|
+
) from exc
|
|
244
|
+
return cls.from_dict(data, base_dir=path.parent)
|
|
245
|
+
|
|
246
|
+
@property
|
|
247
|
+
def queries(self):
|
|
248
|
+
return tuple(Query(q) for q in self._value["queries"])
|
|
249
|
+
|
|
250
|
+
@property
|
|
251
|
+
def context(self):
|
|
252
|
+
return self._value.get("context")
|
|
253
|
+
|
|
254
|
+
@property
|
|
255
|
+
def completeness(self):
|
|
256
|
+
return self._value.get("completeness")
|
|
257
|
+
|
|
258
|
+
def dump(self, path):
|
|
259
|
+
path = Path(path)
|
|
260
|
+
path.write_text(serialize(self, _format(path)), encoding="utf-8")
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
class QueryReport(ProtocolValue):
|
|
264
|
+
KIND = "report"
|
|
265
|
+
|
|
266
|
+
def to_json(self):
|
|
267
|
+
return serialize(self)
|
|
268
|
+
|
|
269
|
+
@classmethod
|
|
270
|
+
def from_json(cls, text):
|
|
271
|
+
return load_value(text, "report", format="json")
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
class QueryExplanation(ProtocolValue):
|
|
275
|
+
KIND = "explanation"
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
class ErrorValue(ProtocolValue):
|
|
279
|
+
KIND = "error"
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
class Catalog(ProtocolValue):
|
|
283
|
+
KIND = "catalog"
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
class Parameters(ProtocolValue):
|
|
287
|
+
KIND = "parameters"
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
class Mappings(ProtocolValue):
|
|
291
|
+
KIND = "mappings"
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
class Context(ProtocolValue):
|
|
295
|
+
KIND = "context"
|
|
296
|
+
|
|
297
|
+
def __init__(self, value, *, base_dir=None):
|
|
298
|
+
data = validate_value(value, "context")
|
|
299
|
+
base = Path.cwd() if base_dir is None else Path(base_dir).absolute()
|
|
300
|
+
refs = [data.get("catalog"), data.get("parameter_registry")]
|
|
301
|
+
refs.extend(data.get("mappings", {}).values())
|
|
302
|
+
for ref in refs:
|
|
303
|
+
if ref and "path" in ref:
|
|
304
|
+
ref["path"] = os.path.abspath(base / ref["path"])
|
|
305
|
+
object.__setattr__(self, "_value", freeze(data))
|
|
306
|
+
|
|
307
|
+
@classmethod
|
|
308
|
+
def from_dict(cls, data, *, base_dir=None):
|
|
309
|
+
return cls(data, base_dir=base_dir)
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
MODELS = {
|
|
313
|
+
model.KIND: model
|
|
314
|
+
for model in (
|
|
315
|
+
Query,
|
|
316
|
+
Request,
|
|
317
|
+
QueryReport,
|
|
318
|
+
QueryExplanation,
|
|
319
|
+
ErrorValue,
|
|
320
|
+
Catalog,
|
|
321
|
+
Parameters,
|
|
322
|
+
Mappings,
|
|
323
|
+
Context,
|
|
324
|
+
)
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
def _format(path):
|
|
329
|
+
suffix = path.suffix.lower()
|
|
330
|
+
if suffix not in {".yaml", ".yml", ".json"}:
|
|
331
|
+
raise ValueError("expected .yaml/.yml/.json")
|
|
332
|
+
return "json" if suffix == ".json" else "yaml"
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
def load_value(value, kind, *, format=None, base_dir=None):
|
|
336
|
+
if isinstance(value, str):
|
|
337
|
+
try:
|
|
338
|
+
value = parse(value, format)
|
|
339
|
+
except (ValueError, YAMLError) as exc:
|
|
340
|
+
raise QueryError(
|
|
341
|
+
"invalid_request"
|
|
342
|
+
if kind == "request"
|
|
343
|
+
else "invalid_query"
|
|
344
|
+
if kind == "query"
|
|
345
|
+
else "invalid_config",
|
|
346
|
+
"",
|
|
347
|
+
str(exc),
|
|
348
|
+
) from exc
|
|
349
|
+
elif format is not None:
|
|
350
|
+
raise ValueError("format is only valid for text input")
|
|
351
|
+
return (
|
|
352
|
+
MODELS[kind](value, base_dir=base_dir)
|
|
353
|
+
if kind in {"request", "context"}
|
|
354
|
+
else MODELS[kind](value)
|
|
355
|
+
)
|
|
356
|
+
|
|
357
|
+
|
|
358
|
+
def load_request(value, *, format=None, base_dir=None):
|
|
359
|
+
return load_value(value, "request", format=format, base_dir=base_dir)
|
|
360
|
+
|
|
361
|
+
|
|
362
|
+
def dump_value(value, *, format="json"):
|
|
363
|
+
if not isinstance(value, ProtocolValue):
|
|
364
|
+
raise TypeError("dump_value requires a validated value")
|
|
365
|
+
return serialize(value, format)
|