|
| 1 | +"""Avro codec support for the Durable Workflow Python SDK. |
| 2 | +
|
| 3 | +The Durable Workflow server uses an Avro generic-wrapper format on the |
| 4 | +wire when the ``payload_codec`` tag is ``"avro"``. The wire layout is: |
| 5 | +
|
| 6 | + base64( 0x00 || avro_binary( record{ json: string, version: int } ) ) |
| 7 | +
|
| 8 | +The ``json`` field carries ``json.dumps(value)``; ``version`` is currently |
| 9 | +``1``. A ``0x01`` prefix is reserved for typed-schema payloads — those |
| 10 | +are not yet encodeable/decodeable from this SDK because typed schemas |
| 11 | +require a schema registry that is out of scope for the first Avro release. |
| 12 | +
|
| 13 | +The ``avro`` third-party package is an *optional* runtime dependency. |
| 14 | +Install it with:: |
| 15 | +
|
| 16 | + pip install 'durable-workflow[avro]' |
| 17 | +
|
| 18 | +If the extra is not installed, calling :func:`encode` or :func:`decode` |
| 19 | +raises :class:`AvroNotInstalledError` with the install hint. |
| 20 | +""" |
| 21 | +from __future__ import annotations |
| 22 | + |
| 23 | +import base64 |
| 24 | +import io |
| 25 | +import json |
| 26 | +from typing import Any |
| 27 | + |
| 28 | +from .errors import AvroNotInstalledError |
| 29 | + |
| 30 | +WRAPPER_SCHEMA_JSON = ( |
| 31 | + '{"type":"record","name":"Payload","namespace":"durable_workflow",' |
| 32 | + '"fields":[{"name":"json","type":"string"},' |
| 33 | + '{"name":"version","type":"int","default":1}]}' |
| 34 | +) |
| 35 | +WRAPPER_VERSION = 1 |
| 36 | +_PREFIX_GENERIC_WRAPPER = b"\x00" |
| 37 | +_PREFIX_TYPED_SCHEMA = b"\x01" |
| 38 | + |
| 39 | + |
| 40 | +def _load_avro_schema() -> Any: |
| 41 | + try: |
| 42 | + import avro.schema |
| 43 | + except ImportError as exc: |
| 44 | + raise AvroNotInstalledError( |
| 45 | + "The 'avro' package is required to encode/decode payloads with the 'avro' " |
| 46 | + "codec. Install with: pip install 'durable-workflow[avro]'" |
| 47 | + ) from exc |
| 48 | + |
| 49 | + return avro.schema.parse(WRAPPER_SCHEMA_JSON) |
| 50 | + |
| 51 | + |
| 52 | +def encode(value: Any) -> str: |
| 53 | + """Encode a Python value as an Avro generic-wrapper payload blob. |
| 54 | +
|
| 55 | + Returns a base64 string the server accepts under ``payload_codec="avro"``. |
| 56 | + """ |
| 57 | + try: |
| 58 | + import avro.io |
| 59 | + except ImportError as exc: |
| 60 | + raise AvroNotInstalledError( |
| 61 | + "The 'avro' package is required to encode payloads with the 'avro' " |
| 62 | + "codec. Install with: pip install 'durable-workflow[avro]'" |
| 63 | + ) from exc |
| 64 | + |
| 65 | + schema = _load_avro_schema() |
| 66 | + buf = io.BytesIO() |
| 67 | + encoder = avro.io.BinaryEncoder(buf) |
| 68 | + writer = avro.io.DatumWriter(schema) |
| 69 | + writer.write( |
| 70 | + { |
| 71 | + "json": json.dumps(value, separators=(",", ":"), ensure_ascii=False), |
| 72 | + "version": WRAPPER_VERSION, |
| 73 | + }, |
| 74 | + encoder, |
| 75 | + ) |
| 76 | + return base64.b64encode(_PREFIX_GENERIC_WRAPPER + buf.getvalue()).decode("ascii") |
| 77 | + |
| 78 | + |
| 79 | +def decode(blob: str) -> Any: |
| 80 | + """Decode an Avro ``payload_codec="avro"`` blob into a Python value. |
| 81 | +
|
| 82 | + Accepts the server's generic-wrapper format (prefix ``0x00``). Typed |
| 83 | + schemas (prefix ``0x01``) raise :class:`ValueError` because the SDK |
| 84 | + has no schema registry. |
| 85 | + """ |
| 86 | + try: |
| 87 | + import avro.io |
| 88 | + except ImportError as exc: |
| 89 | + raise AvroNotInstalledError( |
| 90 | + "The 'avro' package is required to decode payloads with the 'avro' " |
| 91 | + "codec. Install with: pip install 'durable-workflow[avro]'" |
| 92 | + ) from exc |
| 93 | + |
| 94 | + try: |
| 95 | + raw = base64.b64decode(blob, validate=True) |
| 96 | + except (ValueError, TypeError) as exc: |
| 97 | + _diagnose_ingress(blob, exc) |
| 98 | + |
| 99 | + if not raw: |
| 100 | + raise ValueError("Avro payload is empty after base64 decode.") |
| 101 | + |
| 102 | + prefix = raw[:1] |
| 103 | + if prefix == _PREFIX_TYPED_SCHEMA: |
| 104 | + raise ValueError( |
| 105 | + "Typed Avro payload (prefix 0x01) received without a schema context. " |
| 106 | + "This SDK currently supports only the generic wrapper (prefix 0x00); " |
| 107 | + "typed schemas are not yet implemented." |
| 108 | + ) |
| 109 | + if prefix != _PREFIX_GENERIC_WRAPPER: |
| 110 | + raise ValueError( |
| 111 | + f"Unknown Avro payload prefix: 0x{prefix.hex()} " |
| 112 | + f"(expected 0x00 generic wrapper or 0x01 typed schema). " |
| 113 | + f"These bytes were not produced by a Durable Workflow Avro serializer." |
| 114 | + ) |
| 115 | + |
| 116 | + schema = _load_avro_schema() |
| 117 | + reader = avro.io.DatumReader(schema) |
| 118 | + decoder = avro.io.BinaryDecoder(io.BytesIO(raw[1:])) |
| 119 | + try: |
| 120 | + record = reader.read(decoder) |
| 121 | + except Exception as exc: |
| 122 | + raise ValueError(f"Avro generic-wrapper decode failed: {exc}") from exc |
| 123 | + |
| 124 | + if not isinstance(record, dict) or "json" not in record: |
| 125 | + raise ValueError( |
| 126 | + "Avro generic-wrapper payload did not decode to a {json, version} record." |
| 127 | + ) |
| 128 | + |
| 129 | + try: |
| 130 | + return json.loads(record["json"]) |
| 131 | + except (TypeError, json.JSONDecodeError) as exc: |
| 132 | + raise ValueError(f"Avro generic-wrapper 'json' field is not valid JSON: {exc}") from exc |
| 133 | + |
| 134 | + |
| 135 | +def _diagnose_ingress(blob: str, cause: Exception) -> None: |
| 136 | + """Re-raise an ingress base64 failure with a typed remediation hint.""" |
| 137 | + stripped = blob.lstrip() if isinstance(blob, str) else "" |
| 138 | + looks_like_json = stripped[:1] in {"{", "[", '"', "-", "t", "f", "n"} or ( |
| 139 | + stripped[:1].isdigit() if stripped else False |
| 140 | + ) |
| 141 | + if looks_like_json: |
| 142 | + raise ValueError( |
| 143 | + "Payload bytes look like JSON, not base64-encoded Avro. The producer " |
| 144 | + "appears to have JSON-encoded the payload but tagged it with codec " |
| 145 | + '"avro". Either change the codec tag to "json", or re-encode the ' |
| 146 | + 'payload with the Avro serializer before tagging it "avro".' |
| 147 | + ) from cause |
| 148 | + |
| 149 | + raise ValueError( |
| 150 | + "Failed to base64-decode Avro payload bytes. Avro payloads on the wire " |
| 151 | + "must be base64-encoded bytes whose first byte is 0x00 (generic wrapper) " |
| 152 | + "or 0x01 (typed schema). Re-encode the payload, or change the codec tag " |
| 153 | + "if the producer used a different codec." |
| 154 | + ) from cause |
0 commit comments