|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | +"""Deferred Packet |
| 3 | +=================== |
| 4 | +
|
| 5 | +.. module:: pcapkit.corekit.packet |
| 6 | +
|
| 7 | +:mod:`pcapkit.corekit.packet` contains |
| 8 | +:class:`~pcapkit.corekit.packet.DeferredPacket`, the mixin that lets an |
| 9 | +:class:`~pcapkit.corekit.infoclass.Info` subclass hold its ``packet`` field as |
| 10 | +a placeholder and resolve it on first read. A reassembled datagram's ``packet`` |
| 11 | +is a second parse of its payload, and a traced flow's is a reassembly of its |
| 12 | +stream; most callers want neither, so both are postponed until somebody reads |
| 13 | +them. |
| 14 | +
|
| 15 | +A subclass keeps a three-part contract, which |
| 16 | +:meth:`DeferredPacket.__init_subclass__` checks at class creation: |
| 17 | +
|
| 18 | +* It is declared ``class X(DeferredPacket, Info)``, mixin first, so the methods |
| 19 | + here take precedence over :class:`~pcapkit.corekit.infoclass.Info`'s own. |
| 20 | +* It lists ``packet`` in its ``__additional__``. That is what makes the field |
| 21 | + lazy at all: :class:`~pcapkit.corekit.infoclass.Info` stores a field named |
| 22 | + there under a mangled key and maps it back on the way out, so ``packet`` |
| 23 | + never lands in :attr:`~object.__dict__` under its own name. Reading it |
| 24 | + therefore reaches :meth:`DeferredPacket.__getattr__`, where the placeholder |
| 25 | + can be resolved, while ``dict(x)``, :meth:`DeferredPacket.to_dict` and |
| 26 | + iteration still report the field as ``packet``. |
| 27 | +* It names its placeholder class in |
| 28 | + :attr:`~DeferredPacket.__deferred__`. A value of that class is called with no |
| 29 | + arguments to produce the real ``packet``; any other value already is one. |
| 30 | +
|
| 31 | +Resolution happens **at most once**: the result replaces the placeholder in |
| 32 | +:attr:`~object.__dict__`, so every later read returns that same object and the |
| 33 | +placeholder is never called again. |
| 34 | +
|
| 35 | +This module imports nothing from :mod:`pcapkit.foundation` or |
| 36 | +:mod:`pcapkit.protocols`. Each placeholder class stays with the subsystem that |
| 37 | +creates it, and only the subclass knows which one it holds. |
| 38 | +
|
| 39 | +""" |
| 40 | +from typing import TYPE_CHECKING |
| 41 | + |
| 42 | +from pcapkit.utilities.exceptions import InfoError |
| 43 | + |
| 44 | +if TYPE_CHECKING: |
| 45 | + from typing import Any, Callable, ClassVar, Type |
| 46 | + |
| 47 | +__all__ = ['DeferredPacket'] |
| 48 | + |
| 49 | + |
| 50 | +class DeferredPacket: |
| 51 | + """Resolves a deferred ``packet`` field on first read. |
| 52 | +
|
| 53 | + A mixin for :class:`~pcapkit.corekit.infoclass.Info` subclasses; see |
| 54 | + :mod:`pcapkit.corekit.packet` for the contract a subclass keeps. Reading |
| 55 | + ``packet`` -- as an attribute, as ``x['packet']``, or through |
| 56 | + :meth:`to_dict`, :func:`str` or :func:`repr` -- resolves a placeholder once |
| 57 | + and keeps the result. ``'packet' in x``, :func:`len` and iteration report the |
| 58 | + field by name without resolving it. |
| 59 | +
|
| 60 | + It is shared by |
| 61 | + :class:`pcapkit.foundation.reassembly.data.ip.Datagram`, |
| 62 | + :class:`pcapkit.foundation.reassembly.data.tcp.Datagram` and |
| 63 | + :class:`pcapkit.foundation.traceflow.data.tcp.Index`, which differ only in |
| 64 | + the placeholder class each names in :attr:`__deferred__` |
| 65 | + (:issue:`1516`). It is still importable from where it lived before: |
| 66 | + :mod:`pcapkit.foundation.reassembly.data`, |
| 67 | + :mod:`pcapkit.foundation.reassembly.data.data` and |
| 68 | + :mod:`pcapkit.foundation.traceflow.data.data`. |
| 69 | +
|
| 70 | + """ |
| 71 | + |
| 72 | + if TYPE_CHECKING: |
| 73 | + #: Placeholder class the ``packet`` field may hold, set by each subclass. |
| 74 | + #: A value of this class is resolved by calling it with no arguments; |
| 75 | + #: an instance of any other class, :data:`None` included, is not. |
| 76 | + __deferred__: 'ClassVar[Type[Callable[[], Any]]]' |
| 77 | + |
| 78 | + # NOTE: the ``super()`` calls below are suppressed for both checkers. They are |
| 79 | + # undefined *on this mixin*, which is what a mixin is -- the base arrives at |
| 80 | + # the point of use, where every subclass is declared |
| 81 | + # ``class X(DeferredPacket, Info)`` and :class:`~pcapkit.corekit.infoclass.Info` |
| 82 | + # supplies all three. Neither mypy nor pylint can see that from here, and |
| 83 | + # pylint calls it an *error* rather than a warning. |
| 84 | + |
| 85 | + def __init_subclass__(cls, /, *args: 'Any', **kwargs: 'Any') -> 'None': |
| 86 | + """Refuse a subclass that does not keep the contract. |
| 87 | +
|
| 88 | + Either omission would otherwise fail silently, and only on a read. |
| 89 | + Without ``packet`` in ``__additional__`` the field lands in |
| 90 | + :attr:`~object.__dict__` under its own name, :meth:`__getattr__` is never |
| 91 | + reached, and the placeholder itself comes back. Without |
| 92 | + :attr:`__deferred__`, :meth:`__analyse__` raises :exc:`AttributeError` |
| 93 | + from inside :meth:`__getattr__`, which ``getattr(x, 'packet', None)`` |
| 94 | + takes for a missing attribute and answers with :data:`None`. |
| 95 | +
|
| 96 | + Args: |
| 97 | + *args: Arbitrary positional arguments. |
| 98 | + **kwargs: Arbitrary keyword arguments in class definition. |
| 99 | +
|
| 100 | + Raises: |
| 101 | + InfoError: If ``cls`` does not list ``packet`` in its |
| 102 | + ``__additional__``, or does not name a class in its |
| 103 | + :attr:`__deferred__`. |
| 104 | +
|
| 105 | + """ |
| 106 | + super().__init_subclass__(*args, **kwargs) |
| 107 | + |
| 108 | + if 'packet' not in getattr(cls, '__additional__', ()): |
| 109 | + raise InfoError(f"{cls.__name__}: 'packet' is not listed in __additional__, " |
| 110 | + 'so reading it would never resolve the placeholder') |
| 111 | + if not isinstance(getattr(cls, '__deferred__', None), type): |
| 112 | + raise InfoError(f"{cls.__name__}: __deferred__ does not name the placeholder class " |
| 113 | + "that 'packet' may hold") |
| 114 | + |
| 115 | + def __analyse__(self) -> 'Any': |
| 116 | + """Resolve the ``packet`` field, at most once. |
| 117 | +
|
| 118 | + A placeholder, i.e. an instance of :attr:`__deferred__`, is called with |
| 119 | + no arguments and its result replaces it in :attr:`~object.__dict__`. Any |
| 120 | + other value is returned as it is. |
| 121 | +
|
| 122 | + Returns: |
| 123 | + The resolved ``packet``, which may be :data:`None` when the subclass |
| 124 | + stored that instead of a placeholder. |
| 125 | +
|
| 126 | + """ |
| 127 | + key = self.__map__.get('packet', 'packet') |
| 128 | + value = self.__dict__[key] |
| 129 | + if isinstance(value, self.__deferred__): |
| 130 | + value = value() |
| 131 | + self.__dict__[key] = value |
| 132 | + return value |
| 133 | + |
| 134 | + def __getattr__(self, name: 'str') -> 'Any': |
| 135 | + # NOTE: reached only for names absent from ``__dict__``, which ``packet`` |
| 136 | + # always is -- see ``__additional__`` in the module docstring. Everything |
| 137 | + # else has to raise, or a typo would silently answer with the resolved |
| 138 | + # ``packet``. |
| 139 | + if name != 'packet': |
| 140 | + raise AttributeError(f'{type(self).__name__!r} object has no attribute {name!r}') |
| 141 | + return self.__analyse__() |
| 142 | + |
| 143 | + def __getitem__(self, name: 'str') -> 'Any': |
| 144 | + if name == 'packet': |
| 145 | + return self.__analyse__() |
| 146 | + return super().__getitem__(name) # type: ignore[misc] # pylint: disable=no-member |
| 147 | + |
| 148 | + def __contains__(self, name: 'object') -> 'bool': |
| 149 | + # NOTE: ``Mapping.__contains__`` answers by fetching the value, which |
| 150 | + # would resolve the placeholder merely to decide that the field exists. |
| 151 | + # ``packet`` is a declared field, so it is always there. |
| 152 | + return name == 'packet' or super().__contains__(name) # type: ignore[misc] # pylint: disable=no-member |
| 153 | + |
| 154 | + def __str__(self) -> 'str': |
| 155 | + self.__analyse__() |
| 156 | + return super().__str__() |
| 157 | + |
| 158 | + def __repr__(self) -> 'str': |
| 159 | + self.__analyse__() |
| 160 | + return super().__repr__() |
| 161 | + |
| 162 | + def to_dict(self) -> 'dict[str, Any]': |
| 163 | + """Convert the instance into :obj:`dict`. |
| 164 | +
|
| 165 | + Returns: |
| 166 | + The fields, with ``packet`` resolved if it had not been read yet -- |
| 167 | + a :obj:`dict` holding the placeholder would leak an implementation |
| 168 | + detail into what is meant to be plain data. |
| 169 | +
|
| 170 | + """ |
| 171 | + self.__analyse__() |
| 172 | + return super().to_dict() # type: ignore[misc] # pylint: disable=no-member |
0 commit comments