From a3f6b6ce6dd6b3af53cb7781e1f5beba55d3864a Mon Sep 17 00:00:00 2001 From: Andreas Motl Date: Wed, 25 Sep 2024 04:38:19 +0200 Subject: [PATCH] MongoDB: Fix BSON decoder --- src/commons_codec/transform/mongodb.py | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/src/commons_codec/transform/mongodb.py b/src/commons_codec/transform/mongodb.py index d2fa01c..2b67f96 100644 --- a/src/commons_codec/transform/mongodb.py +++ b/src/commons_codec/transform/mongodb.py @@ -6,7 +6,7 @@ import datetime as dt import logging import typing as t -from functools import cached_property +from functools import lru_cache from typing import Iterable import bson @@ -25,6 +25,15 @@ logger = logging.getLogger(__name__) +@lru_cache() +def all_bson_types() -> t.Tuple[t.Type, ...]: + _types: t.List[t.Type] = [] + for _typ in bson._ENCODERS: + if hasattr(_typ, "_type_marker"): + _types.append(_typ) + return tuple(_types) + + @define class MongoDBCrateDBConverter: """ @@ -118,7 +127,7 @@ def decode_extended_json(self, value: t.Dict[str, t.Any]) -> t.Any: else: out = object_hook(value) - is_bson = isinstance(out, self.all_bson_types) + is_bson = isinstance(out, all_bson_types()) # Decode BSON types. if isinstance(out, bson.Binary) and out.subtype == bson.UUID_SUBTYPE: @@ -145,14 +154,6 @@ def decode_extended_json(self, value: t.Dict[str, t.Any]) -> t.Any: # Return others converted as-is. return out - @cached_property - def all_bson_types(self) -> t.Tuple[t.Type, ...]: - _types: t.List[t.Type] = [] - for _typ in bson._ENCODERS: - if hasattr(_typ, "_type_marker"): - _types.append(_typ) - return tuple(_types) - @staticmethod def convert_epoch(value: t.Any) -> float: if isinstance(value, int):