|
| 1 | +"""Wire-layer codec — decode HTTP request bodies to PyMEOS objects, encode |
| 2 | +PyMEOS results back to HTTP response payloads. |
| 3 | +
|
| 4 | +The catalog (``vendor/meos-api/meos-idl.json``, after the enrichment pass) |
| 5 | +labels each parameter and the result with one of the supported encodings: |
| 6 | +
|
| 7 | +- ``mfjson`` — Moving Features JSON (the OGC API – Moving Features |
| 8 | + standard wire format for temporal trajectories). |
| 9 | +- ``text`` — EWKT (Extended Well-Known Text), the human-readable form. |
| 10 | +- ``wkb`` — EWKB (Extended Well-Known Binary), the wire-compact form. |
| 11 | +
|
| 12 | +``Wire`` resolves a per-parameter or per-result *encoding name* to the |
| 13 | +right PyMEOS factory / serialiser. It does not pick the encoding: that |
| 14 | +decision is made by the catalog at generation time and surfaced via the |
| 15 | +``x-meos-{decode,encode}`` extensions on the OpenAPI spec. |
| 16 | +
|
| 17 | +The module is split so that the encoding/decoding logic is *resolver- |
| 18 | +agnostic*. Production runs against PyMEOS; the tests use a stub |
| 19 | +``WireCodec`` whose factory map is explicit. |
| 20 | +""" |
| 21 | + |
| 22 | +from __future__ import annotations |
| 23 | + |
| 24 | +from typing import Any, Callable |
| 25 | + |
| 26 | + |
| 27 | +# Canonical encoding names appearing on catalog `wire.params[].decode` |
| 28 | +# and `wire.result.encode` fields. |
| 29 | +ENCODING_MFJSON = "mfjson" |
| 30 | +ENCODING_TEXT = "text" |
| 31 | +ENCODING_WKB = "wkb" |
| 32 | +ENCODING_HEXWKB = "hexwkb" |
| 33 | + |
| 34 | + |
| 35 | +class WireCodec: |
| 36 | + """Codec keyed by encoding name (``mfjson``, ``text``, ``wkb``, …). |
| 37 | +
|
| 38 | + The decode map turns an inbound wire value (str / bytes) into a |
| 39 | + PyMEOS object. The encode map turns a PyMEOS object back into a |
| 40 | + wire value. Each map is keyed by the *encoding name* the catalog |
| 41 | + labels the parameter / result with. |
| 42 | +
|
| 43 | + Stub-mode construction supplies the maps explicitly. Production |
| 44 | + construction asks PyMEOS for the factories. |
| 45 | + """ |
| 46 | + |
| 47 | + def __init__( |
| 48 | + self, |
| 49 | + decoders: dict[str, Callable[[Any], Any]], |
| 50 | + encoders: dict[str, Callable[[Any], Any]], |
| 51 | + ) -> None: |
| 52 | + self._decoders = decoders |
| 53 | + self._encoders = encoders |
| 54 | + |
| 55 | + def decode(self, encoding: str, wire_value: Any) -> Any: |
| 56 | + """Apply the decoder for ``encoding`` to ``wire_value``.""" |
| 57 | + try: |
| 58 | + return self._decoders[encoding](wire_value) |
| 59 | + except KeyError: |
| 60 | + raise KeyError( |
| 61 | + f"WireCodec has no decoder for encoding `{encoding}`. " |
| 62 | + f"Known: {sorted(self._decoders)}" |
| 63 | + ) |
| 64 | + |
| 65 | + def encode(self, encoding: str, value: Any) -> Any: |
| 66 | + """Apply the encoder for ``encoding`` to ``value``.""" |
| 67 | + try: |
| 68 | + return self._encoders[encoding](value) |
| 69 | + except KeyError: |
| 70 | + raise KeyError( |
| 71 | + f"WireCodec has no encoder for encoding `{encoding}`. " |
| 72 | + f"Known: {sorted(self._encoders)}" |
| 73 | + ) |
| 74 | + |
| 75 | + def has_decoder(self, encoding: str) -> bool: |
| 76 | + return encoding in self._decoders |
| 77 | + |
| 78 | + def has_encoder(self, encoding: str) -> bool: |
| 79 | + return encoding in self._encoders |
| 80 | + |
| 81 | + |
| 82 | +def stub_codec( |
| 83 | + decoders: dict[str, Callable[[Any], Any]] | None = None, |
| 84 | + encoders: dict[str, Callable[[Any], Any]] | None = None, |
| 85 | +) -> WireCodec: |
| 86 | + """Build a stub WireCodec from explicit maps (for tests).""" |
| 87 | + return WireCodec( |
| 88 | + decoders=decoders or {}, |
| 89 | + encoders=encoders or {}, |
| 90 | + ) |
| 91 | + |
| 92 | + |
| 93 | +def pymeos_codec() -> WireCodec: |
| 94 | + """Build the production WireCodec that bridges to PyMEOS. |
| 95 | +
|
| 96 | + Lazy-imports PyMEOS the first time the codec is used. The decoders |
| 97 | + accept the PyMEOS factory entry points, and the encoders use the |
| 98 | + PyMEOS object's own ``__str__`` / serialisation methods. |
| 99 | +
|
| 100 | + The factory entry points are deliberately not type-specific (e.g., |
| 101 | + the catalog says ``decode = "temporal_in"`` and that's a single |
| 102 | + PyMEOS factory that dispatches on the input). When PyMEOS exposes |
| 103 | + more granular factories per temporal subtype, this map grows. |
| 104 | + """ |
| 105 | + try: |
| 106 | + import pymeos # noqa: WPS433 - lazy import on purpose |
| 107 | + except ImportError as e: |
| 108 | + raise ImportError( |
| 109 | + "pymeos is not installed. WireCodec.pymeos_codec() requires " |
| 110 | + "the `pymeos` package on the Python path." |
| 111 | + ) from e |
| 112 | + |
| 113 | + def _from_mfjson(s): |
| 114 | + # PyMEOS exposes Temporal.from_mfjson on the family root class. |
| 115 | + # The dispatch by base type happens inside PyMEOS. |
| 116 | + return pymeos.TPoint.from_mfjson(s) if isinstance(s, str) else s |
| 117 | + |
| 118 | + def _from_wkb(b): |
| 119 | + return pymeos.TPoint.from_wkb(b) |
| 120 | + |
| 121 | + def _from_hexwkb(s): |
| 122 | + return pymeos.TPoint.from_hexwkb(s) |
| 123 | + |
| 124 | + def _from_text(s): |
| 125 | + return pymeos.TPoint(s) # PyMEOS constructor accepts EWKT |
| 126 | + |
| 127 | + return WireCodec( |
| 128 | + decoders={ |
| 129 | + ENCODING_MFJSON: _from_mfjson, |
| 130 | + ENCODING_WKB: _from_wkb, |
| 131 | + ENCODING_HEXWKB: _from_hexwkb, |
| 132 | + ENCODING_TEXT: _from_text, |
| 133 | + }, |
| 134 | + encoders={ |
| 135 | + ENCODING_MFJSON: lambda obj: obj.as_mfjson() if hasattr(obj, "as_mfjson") else str(obj), |
| 136 | + ENCODING_WKB: lambda obj: obj.as_wkb() if hasattr(obj, "as_wkb") else bytes(str(obj), "utf-8"), |
| 137 | + ENCODING_HEXWKB: lambda obj: obj.as_hexwkb() if hasattr(obj, "as_hexwkb") else str(obj), |
| 138 | + ENCODING_TEXT: str, |
| 139 | + }, |
| 140 | + ) |
0 commit comments