import decimal import json import logging import re from collections import defaultdict from copy import deepcopy from io import BytesIO from typing import Dict, List, Optional, Set, Tuple, Union, cast from fastavro import repository, validate from fastavro.schema import load_schema from confluent_kafka.schema_registry.confluent.type.variant_utils import Variant from confluent_kafka.schema_registry.serde import ( VALIDATION_RULES_PROP, FieldTransform, FieldType, RuleConditionError, RuleContext, ValidationRule, ValidationRuleError, ValidationRuleExecutor, evaluate_validation_rule, parse_validation_rules, ) from .schema_registry_client import RuleKind, Schema # The Avro `variant` logical type: a record {metadata: bytes, value: bytes} carrying a # Spark/Parquet Variant. A field with this logical type decodes to / encodes from a Variant, # so serde consumers and CEL rules see a first-class Variant rather than raw bytes. fastavro # keys logical handlers by "-" = "record-variant"; this is the Python # counterpart of Java's io.confluent.avro.type.VariantConversion. def _variant_from_avro(data, writer_schema, reader_schema=None): # noqa: ARG001 return Variant(bytes(data["value"]), bytes(data["metadata"])) def _variant_to_avro(data, schema): # noqa: ARG001 if isinstance(data, Variant): # standalone_value_bytes, not .value: a navigated sub-variant's own value starts at # its position, and .value is the whole shared buffer. return {"metadata": data.metadata, "value": data.standalone_value_bytes()} return data try: from fastavro import read as _fastavro_read from fastavro import write as _fastavro_write _fastavro_read.LOGICAL_READERS["record-variant"] = _variant_from_avro _fastavro_write.LOGICAL_WRITERS["record-variant"] = _variant_to_avro except Exception: # pragma: no cover - guards against a fastavro API shape change pass __all__ = [ 'AvroMessage', 'AvroSchema', '_schema_loads', 'LocalSchemaRepository', 'parse_schema_with_repo', 'transform', '_transform_field', 'validate_message', 'get_type', '_disjoint', '_resolve_union', '_collapse_schema', 'get_inline_tags', '_get_inline_tags_recursively', '_implied_namespace', ] AVRO_TYPE = "AVRO" AvroMessage = Union[ None, # 'null' Avro type str, # 'string' and 'enum' float, # 'float' and 'double' int, # 'int' and 'long' decimal.Decimal, # 'fixed' bool, # 'boolean' bytes, # 'bytes' list, # 'array' dict, # 'map' and 'record' tuple, # wrapped union type ] AvroSchema = Union[str, list, dict] log = logging.getLogger(__name__) class _ContextStringIO(BytesIO): """ Wrapper to allow use of StringIO via 'with' constructs. """ def __enter__(self): return self def __exit__(self, *args): self.close() return False def _schema_loads(schema_str: str) -> Schema: """ Instantiate a Schema instance from a declaration string. Args: schema_str (str): Avro Schema declaration. .. _Schema declaration: https://avro.apache.org/docs/current/spec.html#schemas Returns: Schema: A Schema instance. """ schema_str = schema_str.strip() # canonical form primitive declarations are not supported if schema_str[0] != "{" and schema_str[0] != "[": schema_str = '{"type":' + schema_str + '}' return Schema(schema_str, schema_type='AVRO') class LocalSchemaRepository(repository.AbstractSchemaRepository): def __init__(self, schemas): self.schemas = schemas def load(self, subject): return self.schemas.get(subject) def parse_schema_with_repo(schema_str: str, named_schemas: Dict[str, AvroSchema]) -> AvroSchema: copy = deepcopy(named_schemas) copy["$root"] = json.loads(schema_str) repo = LocalSchemaRepository(copy) return load_schema("$root", repo=repo) def transform( ctx: RuleContext, schema: AvroSchema, message: AvroMessage, field_transform: FieldTransform ) -> AvroMessage: # Only the schema being absent stops the walk. A `None` *value* is the null branch of a # `["null", T]` union and has to reach the rule: the reference binds it as CEL null so a # rule can guard with `value == null`, and returning early here skipped the rule entirely - # indistinguishable, to the caller, from a rule that ran and passed. if schema is None: return message field_ctx = ctx.current_field() if field_ctx is not None: field_ctx.field_type = get_type(schema) if isinstance(schema, list): subschema, submessage = _resolve_union(schema, message) if subschema is None: return message submessage = transform(ctx, subschema, submessage, field_transform) # The branch a transformed value belongs to follows from the value, not from the branch # it arrived on - the reference keeps no branch at all and resolves it from the datum. # Keep the notation while its branch still accepts the result, so two same-shaped # records are never swapped; drop it otherwise and let fastavro resolve, since # ("null", x) would be written as null with x silently dropped. if isinstance(message, tuple) and len(message) == 2 and _branch_accepts(subschema, submessage): return (message[0], submessage) return submessage elif isinstance(schema, dict): schema_type = schema.get("type") if schema_type == 'array': if not isinstance(message, list): log.warning("Incompatible message type for array schema") return message return [transform(ctx, schema["items"], item, field_transform) for item in message] elif schema_type == 'map': if not isinstance(message, dict): log.warning("Incompatible message type for map schema") return message return {key: transform(ctx, schema["values"], value, field_transform) for key, value in message.items()} elif schema_type == 'record': # A null record has no fields to walk. Guarded before the isinstance check below # so a legitimate null does not log an "incompatible message type" warning; the # reference guards the record case, and only the record case, the same way. if message is None: return message if not isinstance(message, dict): log.warning("Incompatible message type for record schema") return message fields = schema["fields"] for field in fields: if field["name"] not in message: continue _transform_field(ctx, schema, field, message, field_transform) return message if field_ctx is not None: rule_tags = ctx.rule.tags if not rule_tags or not _disjoint(set(rule_tags), field_ctx.tags): return field_transform(ctx, field_ctx, message) return message def _transform_field(ctx: RuleContext, schema: dict, field: dict, message: dict, field_transform: FieldTransform): field_type = field["type"] name = field["name"] full_name = schema["name"] + "." + name try: ctx.enter_field(message, full_name, name, get_type(field_type), None) value = message[name] new_value = transform(ctx, field_type, value, field_transform) if ctx.rule.kind == RuleKind.CONDITION: if new_value is False: raise RuleConditionError(ctx.rule) else: message[name] = new_value finally: ctx.exit_field() def validate_message( executor: Optional[ValidationRuleExecutor], schema: Optional[AvroSchema], message: AvroMessage, fail_fast: bool = False, ) -> List[ValidationRuleError]: """ Walk ``message`` against ``schema``, evaluating every inline ``confluent:rules`` CHECK constraint encountered and collecting all failures. Read-only — the message is not modified. Two kinds of rules are evaluated: - Record-level (``confluent:rules`` on a record schema) — ``this`` is the record. - Field-level (``confluent:rules`` on a record's field) — ``this`` is the field value. Honors the skip-on-null contract: a field that is absent or null does not have its rules invoked. Failures (rules evaluating to False, returning a non-empty string, or raising during evaluation) are appended with their dotted-path location (e.g. ``addr.zip``, ``tags[3]``, ``scores["foo"]``). The walk continues after each failure so callers see the full set rather than only the first, unless ``fail_fast`` is set. """ violations: List[ValidationRuleError] = [] if executor is None or schema is None or message is None: return violations _validate_message(executor, schema, message, "", fail_fast, violations) return violations def _validate_message( executor: ValidationRuleExecutor, schema: AvroSchema, message: AvroMessage, path: str, fail_fast: bool, out: List[ValidationRuleError], ): """ Mirrors :func:`transform`'s dispatch shape: each call takes a (schema, message) pair and dispatches on the schema type. """ if schema is None: return if isinstance(schema, list): if message is None: return subschema, submessage = _resolve_union(schema, message) if subschema is None or subschema == 'null': return _validate_message(executor, subschema, submessage, path, fail_fast, out) return if isinstance(schema, dict): schema_type = schema.get("type") if schema_type == 'array': if not isinstance(message, list): log.warning("Incompatible message type for array schema") return for i, item in enumerate(message): _validate_message(executor, schema["items"], item, f"{path}[{i}]", fail_fast, out) if fail_fast and out: return return elif schema_type == 'map': if not isinstance(message, dict): log.warning("Incompatible message type for map schema") return for key, value in message.items(): _validate_message(executor, schema["values"], value, f'{path}["{key}"]', fail_fast, out) if fail_fast and out: return return elif schema_type == 'record': if not isinstance(message, dict): log.warning("Incompatible message type for record schema") return # Record-level rules: this = the record value. for rule in _read_validation_rules(schema): evaluate_validation_rule(executor, rule, schema, message, path, out) if fail_fast and out: return for field in schema["fields"]: name = field["name"] field_schema = field["type"] child_path = name if not path else f"{path}.{name}" value = message.get(name) # Skip-on-null: an absent or null field value does not invoke the # executor. The recursion below still runs but no-ops for None. if value is not None: for rule in _read_validation_rules(field): evaluate_validation_rule(executor, rule, field_schema, value, child_path, out) if fail_fast and out: return _validate_message(executor, field_schema, value, child_path, fail_fast, out) if fail_fast and out: return return # primitive leaf — field-level rules were evaluated by the parent record case def _read_validation_rules(source: dict) -> List[ValidationRule]: """ Read the ``confluent:rules`` property off a record schema or a field. fastavro preserves unknown schema properties, so both are plain dicts. """ return parse_validation_rules(source.get(VALIDATION_RULES_PROP)) def get_type(schema: AvroSchema) -> FieldType: if isinstance(schema, list): return FieldType.COMBINED elif isinstance(schema, dict): schema_type = schema.get("type") else: # string schemas; this could be either a named schema or a primitive type schema_type = schema if schema_type == 'record': return FieldType.RECORD elif schema_type == 'enum': return FieldType.ENUM elif schema_type == 'array': return FieldType.ARRAY elif schema_type == 'map': return FieldType.MAP elif schema_type == 'union': return FieldType.COMBINED elif schema_type == 'fixed': return FieldType.FIXED elif schema_type == 'string': return FieldType.STRING elif schema_type == 'bytes': return FieldType.BYTES elif schema_type == 'int': return FieldType.INT elif schema_type == 'long': return FieldType.LONG elif schema_type == 'float': return FieldType.FLOAT elif schema_type == 'double': return FieldType.DOUBLE elif schema_type == 'boolean': return FieldType.BOOLEAN elif schema_type == 'null': return FieldType.NULL else: return FieldType.NULL def _disjoint(tags1: Set[str], tags2: Set[str]) -> bool: for tag in tags1: if tag in tags2: return False return True def _union_branch_matches(subschema: AvroSchema, branch_name: str, exact: bool) -> bool: """ Whether ``branch_name``, taken from a wrapped or typed union value, names ``subschema``. The value carries the branch's fullname, while the subschema may carry only its simple name with the namespace inherited from an enclosing record — which is not visible here. So match on the fullname first, and only then fall back to comparing simple names. The fallback is only for a subschema whose namespace is inherited, and so absent here. A subschema that declares its own namespace has a fullname that the exact pass already decided; comparing its simple name as well would let a value naming another namespace match it, picking a branch the value does not name. For the same reason the exact pass matches the fullname alone: a namespaced record is named ``namespace.name``, so its bare name names it no more than it names a same-named record in another namespace. """ if isinstance(subschema, str): return exact and branch_name == subschema if not isinstance(subschema, dict): return False name = subschema.get("name") if name is None: return False if exact: namespace = subschema.get("namespace") # namespace.name when a namespace is declared, else the name as written - which may # already be a fullname (Avro allows "a.Rec" in the name field itself). fullname = f"{namespace}.{name}" if namespace else name return branch_name == fullname return '.' not in name and not subschema.get("namespace") and branch_name.rsplit('.', 1)[-1] == name def _branch_accepts(subschema: AvroSchema, message: AvroMessage) -> bool: """Whether ``subschema`` can hold ``message``, by the same test ``_resolve_union`` uses.""" try: validate(message, _collapse_schema(deepcopy(subschema))) return True except: # noqa: E722 return False def _resolve_union(schema: AvroSchema, message: AvroMessage) -> Tuple[Optional[AvroSchema], AvroMessage]: is_wrapped_union = isinstance(message, tuple) and len(message) == 2 is_typed_union = isinstance(message, dict) and '-type' in message if is_wrapped_union or is_typed_union: if is_wrapped_union: tuple_message = cast(tuple, message) branch_name, payload = tuple_message[0], tuple_message[1] else: dict_message = cast(dict, message) branch_name, payload = dict_message['-type'], dict_message # Exact fullname matches win; only if none matched do simple names decide, so a # union holding the same simple name in two namespaces still resolves correctly. for exact in (True, False): for subschema in schema: if _union_branch_matches(subschema, branch_name, exact): return (subschema, payload) return (None, message) for subschema in schema: try: validate(message, _collapse_schema(deepcopy(subschema))) return (subschema, message) except: # noqa: E722 continue return (None, message) def _collapse_schema(schema: AvroSchema, encountered_references=None) -> AvroSchema: """ Collapses a schema to conform to the Avro specification if it has been previously expanded. Recursively replaces record, fixed, or enum definitions with their name when they have been already defined. Mutates the incoming schema. Args: schema: An (expanded) Avro schema encountered_references: A list of encountered references (used in the recursion) Returns: AvroSchema: A collapsed Avro schema. """ if encountered_references is None: encountered_references = [] if isinstance(schema, str): return schema elif isinstance(schema, list): return [_collapse_schema(subschema, encountered_references) for subschema in schema] elif isinstance(schema, dict): schema_type = schema.get("type") if schema_type == 'array': schema["items"] = _collapse_schema(schema['items'], encountered_references) return schema elif schema_type == 'map': schema["values"] = _collapse_schema(schema["values"], encountered_references) return schema elif schema_type == "record": name = schema.get("name") namespace = schema.get("namespace") full_name = name if namespace is None or (name is not None and '.' in name) else f"{namespace}.{name}" if full_name in encountered_references: return schema["name"] encountered_references.append(full_name) if schema.get("aliases") is not None: for alias in schema["aliases"]: full_alias = alias if namespace is None or '.' in alias else f"{namespace}.{alias}" encountered_references.append(full_alias) schema["fields"] = _collapse_schema(schema["fields"], encountered_references) return schema elif schema_type == "fixed" or schema_type == "enum": if schema["name"] in encountered_references: return schema["name"] encountered_references.append(schema["name"]) if schema.get("aliases") is not None: for alias in schema["aliases"]: encountered_references.append(alias) return schema schema["type"] = _collapse_schema(schema["type"], encountered_references) return schema return schema def get_inline_tags(schema: AvroSchema) -> Dict[str, Set[str]]: inline_tags: Dict[str, Set[str]] = defaultdict(set) _get_inline_tags_recursively('', '', schema, inline_tags) return inline_tags def _get_inline_tags_recursively(ns: str, name: str, schema: Optional[AvroSchema], tags: Dict[str, Set[str]]): if schema is None: return if isinstance(schema, list): for subschema in schema: _get_inline_tags_recursively(ns, name, subschema, tags) elif not isinstance(schema, dict): # string schemas; this could be either a named schema or a primitive type return else: schema_type = schema.get("type") if schema_type == 'array': _get_inline_tags_recursively(ns, name, schema.get("items"), tags) elif schema_type == 'map': _get_inline_tags_recursively(ns, name, schema.get("values"), tags) elif schema_type == 'record': record_name = schema.get("name") record_ns: str if record_name is not None and '.' in record_name: # A name containing a dot is already a fullname; Avro ignores any # namespace attribute for it. record_ns = _implied_namespace(record_name) or '' else: namespace_attr = schema.get("namespace") if namespace_attr is not None: record_ns = namespace_attr else: record_ns = _implied_namespace(name) or ns # The namespace is a prefix to prepend, not a prefix to test for: a record # named 'foobar' in namespace 'foo' is 'foo.foobar', not 'foobar'. if record_name is not None and record_ns != '': record_name = f"{record_ns}.{record_name}" fields = schema["fields"] for field in fields: field_tags = field.get("confluent:tags") field_name = field.get("name") field_type = field.get("type") # Ensure all required fields are present before building tag key if field_tags is not None and field_name is not None and record_name is not None: tags[record_name + '.' + field_name].update(field_tags) if field_type is not None and record_name is not None: _get_inline_tags_recursively(record_ns, record_name, field_type, tags) def _implied_namespace(name: str) -> Optional[str]: match = re.match(r"^(.*)\.[^.]+$", name) return match.group(1) if match else None