|
| 1 | +from collections import ( |
| 2 | + defaultdict, |
| 3 | +) |
| 4 | +from functools import ( |
| 5 | + partial, |
| 6 | +) |
| 7 | +from itertools import ( |
| 8 | + chain, |
| 9 | +) |
| 10 | +import json |
1 | 11 | import logging |
2 | 12 | from typing import ( |
3 | 13 | Protocol, |
4 | 14 | Self, |
5 | 15 | TypedDict, |
| 16 | + cast, |
| 17 | + get_args, |
6 | 18 | ) |
7 | 19 |
|
8 | 20 | import attr |
9 | 21 | from chalice import ( |
10 | 22 | ForbiddenError, |
11 | 23 | ) |
| 24 | +from more_itertools import ( |
| 25 | + one, |
| 26 | + only, |
| 27 | +) |
12 | 28 |
|
13 | 29 | from azul import ( |
14 | 30 | CatalogName, |
| 31 | + R, |
15 | 32 | mutable_furl, |
16 | 33 | ) |
17 | 34 | from azul.json import ( |
|
25 | 42 | FlatJSON, |
26 | 43 | JSON, |
27 | 44 | PrimitiveJSON, |
| 45 | + reify, |
28 | 46 | ) |
29 | 47 |
|
30 | 48 | log = logging.getLogger(__name__) |
|
55 | 73 |
|
56 | 74 | type FiltersJSON = dict[FieldName, FilterJSON] |
57 | 75 |
|
| 76 | +_filter_operators = FilterJSON.__optional_keys__ |
| 77 | +_simple_filter_value_types = reify(PrimitiveJSON) |
| 78 | +_dict_filter_value_types = reify(get_args(FlatJSON.__value__)[1]) |
| 79 | +assert _simple_filter_value_types == _dict_filter_value_types |
| 80 | +_filter_range_end_types = reify(FilterRangeEnd) |
| 81 | + |
| 82 | + |
| 83 | +def parse_filters(raw_filters: str | None) -> FiltersJSON: |
| 84 | + """ |
| 85 | + Deserialize, validate and normalize the given string form of the `filters` |
| 86 | + request parameter. The aim of normalization is to eliminate any |
| 87 | + insignificant differences so that serializing the value returned from calls |
| 88 | + to this method with semantically equivalent and valid arguments yields |
| 89 | + exactly the same JSON string. Two valid arguments are considered |
| 90 | + semantically equivalent if they match the same subset of all possible |
| 91 | + documents. |
| 92 | +
|
| 93 | + >>> parse_filters(None) |
| 94 | + {} |
| 95 | +
|
| 96 | + >>> parse_filters('{}') |
| 97 | + {} |
| 98 | +
|
| 99 | + >>> parse_filters('{"x":{"is":[null]}}') |
| 100 | + {'x': {'is': [None]}} |
| 101 | +
|
| 102 | + Values are sorted. |
| 103 | +
|
| 104 | + >>> parse_filters('{"x":{"is":[2,1,null]}}') |
| 105 | + {'x': {'is': [None, 1, 2]}} |
| 106 | +
|
| 107 | + The entries in value dictionaries are sorted by key. |
| 108 | +
|
| 109 | + >>> parse_filters('{"x":{"is":[{"b":2,"a":1}]}}') |
| 110 | + {'x': {'is': [{'a': 1, 'b': 2}]}} |
| 111 | +
|
| 112 | + Value dictionaries are sorted by their values, in order of the key. If two |
| 113 | + dictionaries have equal values at the first key, the value at the second key |
| 114 | + is used as a tie breaker and so on. |
| 115 | +
|
| 116 | + >>> parse_filters('{"x":{"is":[{"b":2,"a":1},{"a":0,"b":3},{"b":null,"a":1}]}}') |
| 117 | + {'x': {'is': [{'a': 0, 'b': 3}, {'a': 1, 'b': None}, {'a': 1, 'b': 2}]}} |
| 118 | +
|
| 119 | + Ranges are sorted by start and end value. |
| 120 | +
|
| 121 | + >>> parse_filters('{"x":{"within":[[3,4],[1,2],[1,1]]}}') |
| 122 | + {'x': {'within': [[1, 1], [1, 2], [3, 4]]}} |
| 123 | +
|
| 124 | + Overall, filters are sorted by field name. |
| 125 | +
|
| 126 | + >>> parse_filters('{"y":{"within":[[1,2]]},"x":{"is":[4, 3]}}') |
| 127 | + {'x': {'is': [3, 4]}, 'y': {'within': [[1, 2]]}} |
| 128 | +
|
| 129 | + >>> parse_filters('[]') |
| 130 | + Traceback (most recent call last): |
| 131 | + ... |
| 132 | + AssertionError: R('Filters must be an object') |
| 133 | +
|
| 134 | + >>> parse_filters('{"":42}') |
| 135 | + Traceback (most recent call last): |
| 136 | + ... |
| 137 | + AssertionError: R('Empty field name') |
| 138 | +
|
| 139 | + >>> parse_filters('{"x":42}') |
| 140 | + Traceback (most recent call last): |
| 141 | + ... |
| 142 | + AssertionError: R('Filter must be an object', 'x') |
| 143 | +
|
| 144 | + >>> parse_filters('{"x":{}}') |
| 145 | + Traceback (most recent call last): |
| 146 | + ... |
| 147 | + AssertionError: R('Need exactly one filter per field', 'x') |
| 148 | +
|
| 149 | + >>> parse_filters('{"x":{"is":[1],"contains":[1]}}') |
| 150 | + Traceback (most recent call last): |
| 151 | + ... |
| 152 | + AssertionError: R('Need exactly one filter per field', 'x') |
| 153 | +
|
| 154 | + >>> parse_filters('{"x":{"foo":[2]}}') |
| 155 | + Traceback (most recent call last): |
| 156 | + ... |
| 157 | + AssertionError: R('Invalid operator', 'x', 'foo') |
| 158 | +
|
| 159 | + >>> parse_filters('{"x":{"is":[]}}') |
| 160 | + Traceback (most recent call last): |
| 161 | + ... |
| 162 | + AssertionError: R('Need at least one value', 'x') |
| 163 | +
|
| 164 | + >>> parse_filters('{"x":{"is":[1,1]}}') |
| 165 | + Traceback (most recent call last): |
| 166 | + ... |
| 167 | + AssertionError: R('Duplicate values', 'x') |
| 168 | +
|
| 169 | + >>> parse_filters('{"x":{"within":[1]}}') |
| 170 | + Traceback (most recent call last): |
| 171 | + ... |
| 172 | + AssertionError: R('Value does not match operator', 'x', <class 'int'>, 'within') |
| 173 | +
|
| 174 | + >>> parse_filters('{"x":{"is":[42,4.1]}}') |
| 175 | + Traceback (most recent call last): |
| 176 | + ... |
| 177 | + AssertionError: R('Inconsistent value types', 'x') |
| 178 | +
|
| 179 | + >>> parse_filters('{"x":{"within":[[1]]}}') |
| 180 | + Traceback (most recent call last): |
| 181 | + ... |
| 182 | + AssertionError: R('Range must be list of length 2', 'x') |
| 183 | +
|
| 184 | + >>> parse_filters('{"x":{"within":[[2,1]]}}') |
| 185 | + Traceback (most recent call last): |
| 186 | + ... |
| 187 | + AssertionError: R('Range is inverted', 'x') |
| 188 | +
|
| 189 | + >>> parse_filters('{"x":{"within":[[1,2],["",""]]}}') |
| 190 | + Traceback (most recent call last): |
| 191 | + ... |
| 192 | + AssertionError: R('Inconsistent range ends', 'x') |
| 193 | +
|
| 194 | + >>> parse_filters('{"x":{"within":[[1,1.1],[2,2.2]]}}') |
| 195 | + Traceback (most recent call last): |
| 196 | + ... |
| 197 | + AssertionError: R('Inconsistent range ends', 'x') |
| 198 | +
|
| 199 | + >>> parse_filters('{"x":{"within":[[false,true]]}}') |
| 200 | + Traceback (most recent call last): |
| 201 | + ... |
| 202 | + AssertionError: R('Invalid range end', 'x') |
| 203 | +
|
| 204 | + >>> parse_filters('{"x":{"within":[{}]}}') |
| 205 | + Traceback (most recent call last): |
| 206 | + ... |
| 207 | + AssertionError: R('Value does not match operator', 'x', <class 'dict'>, 'within') |
| 208 | +
|
| 209 | + >>> parse_filters('{"x":{"within":[[1,2],[1,2]]}}') |
| 210 | + Traceback (most recent call last): |
| 211 | + ... |
| 212 | + AssertionError: R('Duplicate ranges', 'x') |
| 213 | +
|
| 214 | + >>> parse_filters('{"x":{"is":[{}]}}') |
| 215 | + Traceback (most recent call last): |
| 216 | + ... |
| 217 | + AssertionError: R('Empty object', 'x') |
| 218 | +
|
| 219 | + >>> parse_filters('{"x":{"is":[{"":1}]}}') |
| 220 | + Traceback (most recent call last): |
| 221 | + ... |
| 222 | + AssertionError: R('Empty property name', 'x') |
| 223 | +
|
| 224 | + >>> parse_filters('{"x":{"is":[{"y":1},{"z":2}]}}') |
| 225 | + Traceback (most recent call last): |
| 226 | + ... |
| 227 | + AssertionError: R('Inconsistent property names', 'x') |
| 228 | +
|
| 229 | + >>> parse_filters('{"x":{"is":[{"y":1,"z":[]}]}}') |
| 230 | + Traceback (most recent call last): |
| 231 | + ... |
| 232 | + AssertionError: R('Invalid property value', 'x') |
| 233 | +
|
| 234 | + >>> parse_filters('{"x":{"is":[{"y":1,"z":2},{"y":"","z":3}]}}') |
| 235 | + Traceback (most recent call last): |
| 236 | + ... |
| 237 | + AssertionError: R('Inconsistent property values', 'x') |
| 238 | +
|
| 239 | + >>> parse_filters('{"x":{"is":[{"a":1,"b":2},{"b":2,"a":1}]}}') |
| 240 | + Traceback (most recent call last): |
| 241 | + ... |
| 242 | + AssertionError: R('Duplicate objects', 'x') |
| 243 | + """ |
| 244 | + if raw_filters is None: |
| 245 | + return {} |
| 246 | + else: |
| 247 | + filters = json.loads(raw_filters) |
| 248 | + assert type(filters) is dict, R('Filters must be an object') |
| 249 | + for field, filter in filters.items(): |
| 250 | + assert len(field) > 0, R('Empty field name') |
| 251 | + assert type(filter) is dict, R('Filter must be an object', field) |
| 252 | + assert len(filter) == 1, R('Need exactly one filter per field', field) |
| 253 | + operator, values = one(filter.items()) |
| 254 | + assert operator in _filter_operators, R('Invalid operator', field, operator) |
| 255 | + assert len(values) > 0, R('Need at least one value', field) |
| 256 | + num_value_types = set(map(type, values)) |
| 257 | + num_value_types.discard(type(None)) |
| 258 | + assert len(num_value_types) < 2, R('Inconsistent value types', field) |
| 259 | + value_type = only(num_value_types) |
| 260 | + mismatch = R('Value does not match operator', field, value_type, operator) |
| 261 | + if value_type is None: |
| 262 | + assert operator in {'is'}, mismatch |
| 263 | + elif value_type in _simple_filter_value_types: |
| 264 | + assert operator in {'is', 'contains'}, mismatch |
| 265 | + assert len(set(values)) == len(values), R('Duplicate values', field) |
| 266 | + elif value_type is list: |
| 267 | + assert operator in {'contains', 'within', 'intersects'}, mismatch |
| 268 | + for range in values: |
| 269 | + assert len(range) == 2, R('Range must be list of length 2', field) |
| 270 | + assert range[0] <= range[1], R('Range is inverted', field) |
| 271 | + assert len(set(map(tuple, values))) == len(values), R('Duplicate ranges', field) |
| 272 | + end_types = set(chain.from_iterable(map(partial(map, type), values))) |
| 273 | + assert len(end_types) == 1, R('Inconsistent range ends', field) |
| 274 | + end_type = one(end_types) |
| 275 | + assert end_type in _filter_range_end_types, R('Invalid range end', field) |
| 276 | + elif value_type is dict: |
| 277 | + assert operator == 'is', mismatch |
| 278 | + key_sets = set(map(frozenset, map(dict.keys, values))) |
| 279 | + assert len(key_sets) == 1, R('Inconsistent property names', field) |
| 280 | + keys = one(key_sets) |
| 281 | + assert len(keys) > 0, R('Empty object', field) |
| 282 | + assert '' not in keys, R('Empty property name', field) |
| 283 | + value_types_by_key = defaultdict(set) |
| 284 | + for value in values: |
| 285 | + for k, v in value.items(): |
| 286 | + assert type(v) in _dict_filter_value_types, R('Invalid property value', field) |
| 287 | + if v is not None: |
| 288 | + value_types_by_key[k].add(type(v)) |
| 289 | + num_value_types = set(map(len, value_types_by_key.values())) |
| 290 | + assert num_value_types == {1}, R('Inconsistent property values', field) |
| 291 | + # Sort each value dictionary in place by key (and value, but key |
| 292 | + # is already unique). This makes sorting the values and checking |
| 293 | + # their uniqueness easier. |
| 294 | + for value in values: |
| 295 | + sorted_value = dict(sorted(value.items())) |
| 296 | + value.clear() |
| 297 | + value.update(sorted_value) |
| 298 | + unique_values = set(map(tuple, map(dict.items, values))) |
| 299 | + assert len(unique_values) == len(values), R('Duplicate objects', field) |
| 300 | + else: |
| 301 | + assert False, R('Invalid value', field) |
| 302 | + |
| 303 | + def key(v): |
| 304 | + if v is None: |
| 305 | + return False, v |
| 306 | + elif type(v) is dict: |
| 307 | + # The entries in the dict are alteady sorted by key, the |
| 308 | + # values are primitive so we just need to handle None values |
| 309 | + # and "freeze" the iterable of entries. |
| 310 | + return True, tuple((k, key(v)) for k, v in v.items()) |
| 311 | + else: |
| 312 | + return True, v |
| 313 | + |
| 314 | + values.sort(key=key) |
| 315 | + |
| 316 | + filters = {k: v for k, v in sorted(filters.items())} |
| 317 | + |
| 318 | + return cast(FiltersJSON, filters) |
| 319 | + |
58 | 320 |
|
59 | 321 | @attr.s(auto_attribs=True, kw_only=True, frozen=True) |
60 | 322 | class Filters: |
|
0 commit comments