|
| 1 | +# |
| 2 | +# MIT License |
| 3 | +# |
| 4 | +# Copyright (c) 2020 Airbyte |
| 5 | +# |
| 6 | +# Permission is hereby granted, free of charge, to any person obtaining a copy |
| 7 | +# of this software and associated documentation files (the "Software"), to deal |
| 8 | +# in the Software without restriction, including without limitation the rights |
| 9 | +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell |
| 10 | +# copies of the Software, and to permit persons to whom the Software is |
| 11 | +# furnished to do so, subject to the following conditions: |
| 12 | +# |
| 13 | +# The above copyright notice and this permission notice shall be included in all |
| 14 | +# copies or substantial portions of the Software. |
| 15 | +# |
| 16 | +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
| 17 | +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
| 18 | +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
| 19 | +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
| 20 | +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
| 21 | +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE |
| 22 | +# SOFTWARE. |
| 23 | +# |
| 24 | +from distutils.util import strtobool |
| 25 | +from enum import Flag, auto |
| 26 | +from typing import Any, Callable, Dict |
| 27 | + |
| 28 | +from airbyte_cdk.logger import AirbyteLogger |
| 29 | +from jsonschema import Draft7Validator, validators |
| 30 | + |
| 31 | +logger = AirbyteLogger() |
| 32 | + |
| 33 | + |
| 34 | +class TransformConfig(Flag): |
| 35 | + """ |
| 36 | + TypeTransformer class config. Configs can be combined using bitwise or operator e.g. |
| 37 | + ``` |
| 38 | + TransformConfig.DefaultSchemaNormalization | TransformConfig.CustomSchemaNormalization |
| 39 | + ``` |
| 40 | + """ |
| 41 | + |
| 42 | + # No action taken, default behaviour. Cannot be combined with any other options. |
| 43 | + NoTransform = auto() |
| 44 | + # Applies default type casting with default_convert method which converts |
| 45 | + # values by applying simple type casting to specified jsonschema type. |
| 46 | + DefaultSchemaNormalization = auto() |
| 47 | + # Allow registering custom type transformation callback. Can be combined |
| 48 | + # with DefaultSchemaNormalization. In this case default type casting would |
| 49 | + # be applied before custom one. |
| 50 | + CustomSchemaNormalization = auto() |
| 51 | + |
| 52 | + |
| 53 | +class TypeTransformer: |
| 54 | + """ |
| 55 | + Class for transforming object before output. |
| 56 | + """ |
| 57 | + |
| 58 | + _custom_normalizer: Callable[[Any, Dict[str, Any]], Any] = None |
| 59 | + |
| 60 | + def __init__(self, config: TransformConfig): |
| 61 | + """ |
| 62 | + Initialize TypeTransformer instance. |
| 63 | + :param config Transform config that would be applied to object |
| 64 | + """ |
| 65 | + if TransformConfig.NoTransform in config and config != TransformConfig.NoTransform: |
| 66 | + raise Exception("NoTransform option cannot be combined with other flags.") |
| 67 | + self._config = config |
| 68 | + all_validators = { |
| 69 | + key: self.__get_normalizer(key, orig_validator) |
| 70 | + for key, orig_validator in Draft7Validator.VALIDATORS.items() |
| 71 | + # Do not validate field we do not transform for maximum performance. |
| 72 | + if key in ["type", "array", "$ref", "properties", "items"] |
| 73 | + } |
| 74 | + self._normalizer = validators.create(meta_schema=Draft7Validator.META_SCHEMA, validators=all_validators) |
| 75 | + |
| 76 | + def registerCustomTransform(self, normalization_callback: Callable[[Any, Dict[str, Any]], Any]) -> Callable: |
| 77 | + """ |
| 78 | + Register custom normalization callback. |
| 79 | + :param normalization_callback function to be used for value |
| 80 | + normalization. Takes original value and part type schema. Should return |
| 81 | + normalized value. See docs/connector-development/cdk-python/schemas.md |
| 82 | + for details. |
| 83 | + :return Same callbeck, this is usefull for using registerCustomTransform function as decorator. |
| 84 | + """ |
| 85 | + if TransformConfig.CustomSchemaNormalization not in self._config: |
| 86 | + raise Exception("Please set TransformConfig.CustomSchemaNormalization config before registering custom normalizer") |
| 87 | + self._custom_normalizer = normalization_callback |
| 88 | + return normalization_callback |
| 89 | + |
| 90 | + def __normalize(self, original_item: Any, subschema: Dict[str, Any]) -> Any: |
| 91 | + """ |
| 92 | + Applies different transform function to object's field according to config. |
| 93 | + :param original_item original value of field. |
| 94 | + :param subschema part of the jsonschema containing field type/format data. |
| 95 | + :return Final field value. |
| 96 | + """ |
| 97 | + if TransformConfig.DefaultSchemaNormalization in self._config: |
| 98 | + original_item = self.default_convert(original_item, subschema) |
| 99 | + |
| 100 | + if self._custom_normalizer: |
| 101 | + original_item = self._custom_normalizer(original_item, subschema) |
| 102 | + return original_item |
| 103 | + |
| 104 | + @staticmethod |
| 105 | + def default_convert(original_item: Any, subschema: Dict[str, Any]) -> Any: |
| 106 | + """ |
| 107 | + Default transform function that is used when TransformConfig.DefaultSchemaNormalization flag set. |
| 108 | + :param original_item original value of field. |
| 109 | + :param subschema part of the jsonschema containing field type/format data. |
| 110 | + :return transformed field value. |
| 111 | + """ |
| 112 | + target_type = subschema.get("type") |
| 113 | + if original_item is None and "null" in target_type: |
| 114 | + return None |
| 115 | + if isinstance(target_type, list): |
| 116 | + # jsonschema type could either be a single string or array of type |
| 117 | + # strings. In case if there is some disambigous and more than one |
| 118 | + # type (except null) do not do any conversion and return original |
| 119 | + # value. If type array has one type and null i.e. {"type": |
| 120 | + # ["integer", "null"]}, convert value to specified type. |
| 121 | + target_type = [t for t in target_type if t != "null"] |
| 122 | + if len(target_type) != 1: |
| 123 | + return original_item |
| 124 | + target_type = target_type[0] |
| 125 | + try: |
| 126 | + if target_type == "string": |
| 127 | + return str(original_item) |
| 128 | + elif target_type == "number": |
| 129 | + return float(original_item) |
| 130 | + elif target_type == "integer": |
| 131 | + return int(original_item) |
| 132 | + elif target_type == "boolean": |
| 133 | + if isinstance(original_item, str): |
| 134 | + return strtobool(original_item) == 1 |
| 135 | + return bool(original_item) |
| 136 | + except ValueError: |
| 137 | + return original_item |
| 138 | + return original_item |
| 139 | + |
| 140 | + def __get_normalizer(self, schema_key: str, original_validator: Callable): |
| 141 | + """ |
| 142 | + Traverse through object fields using native jsonschema validator and apply normalization function. |
| 143 | + :param schema_key related json schema key that currently being validated/normalized. |
| 144 | + :original_validator: native jsonschema validator callback. |
| 145 | + """ |
| 146 | + |
| 147 | + def normalizator(validator_instance: Callable, val: Any, instance: Any, schema: Dict[str, Any]): |
| 148 | + """ |
| 149 | + Jsonschema validator callable it uses for validating instance. We |
| 150 | + override default Draft7Validator to perform value transformation |
| 151 | + before validation take place. We do not take any action except |
| 152 | + logging warn if object does not conform to json schema, just using |
| 153 | + jsonschema algorithm to traverse through object fields. |
| 154 | + Look |
| 155 | + https://python-jsonschema.readthedocs.io/en/stable/creating/?highlight=validators.create#jsonschema.validators.create |
| 156 | + validators parameter for detailed description. |
| 157 | + : |
| 158 | + """ |
| 159 | + |
| 160 | + def resolve(subschema): |
| 161 | + if "$ref" in subschema: |
| 162 | + _, resolved = validator_instance.resolver.resolve(subschema["$ref"]) |
| 163 | + return resolved |
| 164 | + return subschema |
| 165 | + |
| 166 | + if schema_key == "type" and instance is not None: |
| 167 | + if "object" in val and isinstance(instance, dict): |
| 168 | + for k, subschema in schema.get("properties", {}).items(): |
| 169 | + if k in instance: |
| 170 | + subschema = resolve(subschema) |
| 171 | + instance[k] = self.__normalize(instance[k], subschema) |
| 172 | + elif "array" in val and isinstance(instance, list): |
| 173 | + subschema = schema.get("items", {}) |
| 174 | + subschema = resolve(subschema) |
| 175 | + for index, item in enumerate(instance): |
| 176 | + instance[index] = self.__normalize(item, subschema) |
| 177 | + # Running native jsonschema traverse algorithm after field normalization is done. |
| 178 | + yield from original_validator(validator_instance, val, instance, schema) |
| 179 | + |
| 180 | + return normalizator |
| 181 | + |
| 182 | + def transform(self, record: Dict[str, Any], schema: Dict[str, Any]): |
| 183 | + """ |
| 184 | + Normalize and validate according to config. |
| 185 | + :param record record instance for normalization/transformation. All modification are done by modifing existent object. |
| 186 | + :schema object's jsonschema for normalization. |
| 187 | + """ |
| 188 | + if TransformConfig.NoTransform in self._config: |
| 189 | + return |
| 190 | + normalizer = self._normalizer(schema) |
| 191 | + for e in normalizer.iter_errors(record): |
| 192 | + """ |
| 193 | + just calling normalizer.validate() would throw an exception on |
| 194 | + first validation occurences and stop processing rest of schema. |
| 195 | + """ |
| 196 | + logger.warn(e.message) |
0 commit comments