import os
import weakref
from collections.abc import Callable
from functools import partial
from importlib.metadata import version
from typing import Any
import cbor2
import numpy as np
from heros.exceptions import RemoteHEROError
from heros.helper import full_classname
from .inspect import is_hero_event, is_hero_method
ndarray_tag = 4242
hero_tag = 9000
unserializable_tag = 9001
unserializable_object_reference_tag = 9002
hero_event_tag = 9003
hero_method_tag = 9004
hero_exception_tag = 9005
cborv6 = int(version("cbor2")[0]) >= 6
[docs]
def is_builtin_class_instance(obj):
return obj.__class__.__module__ == "__builtin__"
[docs]
class ObjectStore:
"""
An object store to be used to keep week references to objects identified by a serializable identifier (int64).
"""
def __init__(self) -> None:
self._cache = {}
[docs]
def add(self, object: object) -> int:
"""
Add object to store and return it's identifier
Args:
object: object to store
Returns:
Identifier to retrieve the object from the store again
"""
identifier = id(object)
self._cache[identifier] = weakref.ref(object)
return identifier
[docs]
def get(self, identifier: int) -> object:
"""
Retrieve an object identified by :param:identifier from the store.
If the object does not exist any more, None is returned.
Args:
identifier: the identifier obtained when storing the object
Returns:
object corresponding to the identifier or None if the object does not exist any more
"""
if identifier not in self._cache:
return None
obj = self._cache[identifier]
if obj() is not None:
return obj()
else:
del self._cache[identifier]
return None
obj_store = ObjectStore()
[docs]
class UnserializableRemoteObject:
def __init__(self, type: str, id: int, representation: str):
self.type = type
self.representation = representation
self.id = id
[docs]
def __str__(self):
return f"Unserializable Remote Object ({self.type}): id {hex(self.id)}"
[docs]
def __repr__(self):
return self.__str__()
[docs]
def cbor_default_encoder(encoder, value, patches=None):
"""Handle custom types in serialization.
Args:
encoder: the CBOR encoder
value: the value to encode
patches: list that collects (32 byte placeholder, ndarray) pairs for the ndarrays
encoded in this run. Only used with cbor2 >= 6, see :py:func:`serialize`.
"""
from heros import LocalHERO, RemoteHERO
global obj_store # noqa:PLW0602
if type(value) is np.ndarray:
# encode ndarray
if not value.flags.c_contiguous:
value = np.ascontiguousarray(value)
encoder.encode_length(6, ndarray_tag) # cbor tag
encoder.encode_length(4, 3) # length of payload array (shape, dtype, data)
encoder.encode(value.shape) # first array entry: shape
encoder.encode(str(value.dtype).encode()) # second array entry: dtype
encoder.encode_length(2, value.nbytes) # length of data entry
if cborv6:
# write a unique placeholder into the stream and splice the buffer into the serialized data afterwards
# to avoid copy of the whole data.
if value.nbytes:
sentinel = os.urandom(32)
if patches is None:
# fall back to encoding a copy of the data for backwards compatibility
encoder.write(value.tobytes())
else:
patches.append((sentinel, value))
encoder.write(sentinel)
else:
encoder.fp.write(value.data) # pass memoryview directly to avoid copy of data
elif (type(value) is np.int32) or (type(value) is np.int64):
encoder.encode(int(value))
elif isinstance(value, (LocalHERO, RemoteHERO)):
# encode a HERO
encoder.encode(cbor2.CBORTag(hero_tag, [value._realm, value._name]))
elif is_hero_event(value):
# encode an event of a remote hero
# value.instance corresponds is the HERO instance
encoder.encode(cbor2.CBORTag(hero_event_tag, [value.instance, value.__name__]))
elif is_hero_method(value):
# encode a method of a remote hero
# value.__self__ corresponds is the HERO instance
encoder.encode(cbor2.CBORTag(hero_method_tag, [value.__self__, value.__name__]))
elif isinstance(value, BaseException):
# transparently pack the exception into a RemoteHEROError if it is not already
hero_error = value if isinstance(value, RemoteHEROError) else RemoteHEROError.from_exception(value)
encoder.encode(cbor2.CBORTag(hero_exception_tag, hero_error.serialize()))
elif type(value) is UnserializableRemoteObject:
# encode an reference on an remote object that cannot be serialized
encoder.encode(cbor2.CBORTag(unserializable_object_reference_tag, value.id))
else:
# for all object we cannot serialized, we hand out reference
identifier = obj_store.add(value)
encoder.encode(cbor2.CBORTag(unserializable_tag, [full_classname(value), identifier, str(value)]))
# cbor2 introduced a breaking API change with major version 6. We handle this by a thin wrapper.
if cborv6:
def cbor_tag_hook(tag, _immutable, *, make_remote: Callable[..., Any] | None = None):
"""
Decode the custom CBOR tags used by HEROS (cbor2 >=6 version).
Args:
tag: the tagged value to decode
make_remote: factory called as ``make_remote(name, realm=realm)`` to build a HERO from a HERO tag. Defaults to
:py:class:`heros.RemoteHERO`.
Returns:
The decoded object, or the unchanged tag if it is not a HEROS tag.
"""
return decode_tag(tag, make_remote)
else:
[docs]
def cbor_tag_hook(_decoder, tag, _shareable_index=None, *, make_remote: Callable[..., Any] | None = None):
"""
Decode the custom CBOR tags used by HEROS (cbor2 <6 version).
Args:
decoder: the CBOR decoder
tag: the tagged value to decode
shareable_index: index of a shareable value, passed in by cbor2
make_remote: factory called as ``make_remote(name, realm=realm)`` to build a HERO from a HERO tag. Defaults to
:py:class:`heros.RemoteHERO`.
Returns:
The decoded object, or the unchanged tag if it is not a HEROS tag.
"""
return decode_tag(tag, make_remote)
[docs]
def decode_tag(tag, make_remote: Callable[..., Any] | None = None):
if make_remote is None:
from heros import RemoteHERO
make_remote = RemoteHERO
global obj_store # noqa:PLW0602
if tag.tag == ndarray_tag:
# decode ndarray
shape, dtype, buffer = tag.value
return np.frombuffer(buffer, dtype=dtype).reshape(shape)
if tag.tag == hero_tag:
# decode a remote HERO
realm, name = tag.value
return make_remote(name, realm=realm)
if tag.tag == hero_event_tag:
# decode a remote HERO event
remote_hero, event_name = tag.value
return getattr(remote_hero, event_name)
if tag.tag == hero_method_tag:
# decode a remote HERO method
remote_hero, method_name = tag.value
return getattr(remote_hero, method_name)
if tag.tag == hero_exception_tag:
return RemoteHEROError.from_payload(tag.value)
if tag.tag == unserializable_tag:
# decode
t, i, s = tag.value
return UnserializableRemoteObject(t, i, s)
if tag.tag == unserializable_object_reference_tag:
obj = obj_store.get(tag.value)
return obj
return tag
[docs]
def _splice_ndarray_data(data, patches):
"""Replace the placeholder sentinels in serialized data with the raw ndarray buffers.
Args:
data: the serialized byte string containing placeholders
patches: list of (placeholder, ndarray) pairs collected during encoding
"""
pieces = []
pos = 0
for sentinel, value in patches:
header = _bytes_header(value.nbytes)
index = data.find(header + sentinel, pos)
if index < 0:
raise RuntimeError("failed to locate ndarray placeholder in serialized data")
pieces.append(data[pos : index + len(header)])
pieces.append(memoryview(value.data).cast("B"))
pos = index + len(header) + len(sentinel)
pieces.append(data[pos:])
return b"".join(pieces)
[docs]
def serialize(obj):
if cborv6:
patches = []
data = cbor2.dumps(obj, default=partial(cbor_default_encoder, patches=patches))
if patches:
data = _splice_ndarray_data(data, patches)
return data
return cbor2.dumps(obj, default=cbor_default_encoder)
[docs]
def deserialize(bytes, *, make_remote: Callable[..., Any] | None = None):
"""
Deserialize a CBOR byte string.
Args:
bytes: the byte string to deserialize
make_remote: factory used to build HEROs, see :py:func:`cbor_tag_hook`. Defaults to :py:class:`heros.RemoteHERO`.
Returns:
The deserialized object.
"""
hook = partial(cbor_tag_hook, make_remote=make_remote)
return cbor2.loads(bytes, tag_hook=hook)