Skip to content

Commit 6819cb3

Browse files
committed
feat(foundation): declare _CODE_DESTINATIONS as a dunder on the enum registries themselves
Follow-up to #2392/#2343. _CODE_DESTINATIONS was a module-level dict mapping an enum registry type to the protocol class(es) owning the __proto__ dispatch registry keyed by that enum, so register_protocol_code could infer a destination from a bare enum member. Mirrors __proto_key__, which #2392 moved the opposite direction (destination -> enum) onto the destination classes themselves. Each of the 4 enum registry classes (EtherType, TransType, LinkType, PayloadProtocolIdentifier) now declares __proto_dest__, a tuple of ModuleDescriptor naming its destination class(es) lazily -- const sits below protocols in the dependency order, so a real class reference would make const import protocols; ModuleDescriptor (already used for __proto__ dispatch tables elsewhere) avoids that without inventing a parallel string-path scheme. _iter_code_targets reads the dunder off type(code) via getattr() and resolves each descriptor's .klass. getattr(), not vars(): verified aenum refuses to extend an enumeration that already has members, so none of these four registries can gain a subclass with its own registry -- the hazard __proto_key__'s vars() call guards against (Loopback/IPX owning a differently-keyed registry) is structurally impossible here. Where an enum registry is subclassed (AppType -> TCP/UDP/SCTP/DCCP) the base has no members and the parts share one key space, so inheriting the pairing is correct. const/reg/*.py and const/sctp/payload_protocol_identifier.py are regenerated, not hand-edited: the vendor crawlers (vendor/reg/*.py, vendor/sctp/payload_protocol_identifier.py) gain a PROTO_DEST class attribute, threaded through vendor/default.py's LINE template and context(); a throwaway script recovered each committed file's ENUM/MISS blocks and re-rendered through the unmodified template first, asserting byte-identity with the committed file, before re-rendering with PROTO_DEST to confirm the diff is purely the template's effect. Tests: tests/vendor/test_vendor_proto_dest_2392_unit.py (new) plus ProtoDestDeclarationTests in test_protocol_code_registration_unit.py and an update to test_dispatch_reachability_unit.py, which read the dunder instead of the deleted dict.
1 parent 027f7d5 commit 6819cb3

18 files changed

Lines changed: 633 additions & 45 deletions

‎CHANGELOG.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -188,7 +188,7 @@ Preceded by `1.5.0a1` (2026-09-15), `1.5.0b1` to `1.5.0b3` (all 2026-09-19) and
188188
- the Mobility Header registry, completed ([#383](https://github.com/JarryShaw/PyPCAPKit/pull/383), [#437](https://github.com/JarryShaw/PyPCAPKit/pull/437)): the [RFC 5568](https://datatracker.ietf.org/doc/html/rfc5568) fast-handover messages and options, then every registered message data type, every registered option (with nested sub-option registries for the flow identification, access network identifier, quality-of-service and LMA-controlled MAG parameter families) and every CGA extension. The CGA Parameters option, the only option that can carry a CGA extension on the wire, was the last to come off the generic handler, which is what let the CGA extensions round-trip end to end.
189189
- dispatch entries for dissectors that existed but were reachable from no registry ([#436](https://github.com/JarryShaw/PyPCAPKit/pull/436)): FTP-DATA on TCP 20, HTTP/1 on TCP 8080, HTTP on UDP 8080, `L2TPv2` on UDP 1701 and OSPF at `TransType` 89. `VLAN` became an abstract base with `C_Tag` (802.1Q) and `S_Tag` (802.1ad) as concrete subclasses, so a Q-in-Q frame no longer collapses into one opaque `Raw`; `L2TP` likewise became a base, with `L2TPv2` carrying the [RFC 2661](https://datatracker.ietf.org/doc/html/rfc2661) implementation.
190190
- `Protocol`/`ProtocolBase` gain a `code=` class keyword for the next-layer dispatch registries (`Link.__proto__`, `Internet.__proto__`, `TCP.__proto__`, `UDP.__proto__`, `SCTP.__proto__`, `Frame.__proto__`, `PCAPNG.__proto__`), the opt-in treatment [#514](https://github.com/JarryShaw/PyPCAPKit/issues/514) gave `Engine`, `Reassembly`, `TraceFlow` and `Dumper` above, extended to the one family that needed a registration key invented. Omitting `code` leaves a subclass unregistered, as before; the built-in tables are still filled by literal assignment in each layer module, so nothing the library ships moves. `code` accepts a bare enum member, whose *type* infers the destination (`EtherType` means `Link`, `TransType` means `Internet`, `PayloadProtocolIdentifier` means `SCTP`, and `LinkType` means *both* `Frame` **and** `PCAPNG`, mirroring `register_linktype`), or a `{destination: key}` mapping, required for a raw `int` such as a port number, which cannot say which transport it belongs to. Either form may appear in an iterable, so one declaration can register a class into several registries (e.g. a `L2TP` subclass reachable by IP protocol number and by a UDP port), and the mapping form is accepted even where inference would work. Inference refuses rather than guesses: an enum member whose type names no known destination raises `RegistryError`, and an unrecognised class keyword raises `UnsupportedCall`, matching the other registrar families. Backed by `pcapkit.foundation.registry.protocols.register_protocol_code()`, also callable directly for a class that declined at definition time. It was written up as the mechanism [#548](https://github.com/JarryShaw/PyPCAPKit/issues/548) needs; [#548](https://github.com/JarryShaw/PyPCAPKit/issues/548) turned out to need a missing class instead (115 is [RFC 3931](https://datatracker.ietf.org/doc/html/rfc3931) L2TPv3 over IP, not [RFC 2661](https://datatracker.ietf.org/doc/html/rfc2661); see the corresponding **Fixed** entry below), so its worked example names `L2TPv3` ([#570](https://github.com/JarryShaw/PyPCAPKit/pull/570)).
191-
- `tests/protocols/test_dispatch_reachability_unit.py`, the coverage [#548](https://github.com/JarryShaw/PyPCAPKit/issues/548) asked for: every `ProtocolBase` descendant whose `__index__` returns an enum member must be reachable under that code in the registry its enum *type* designates, read from the same `_CODE_DESTINATIONS` table backing `code=` so the two cannot drift. It walks the classes rather than the registry entries, so it catches a class nothing registered, the shape in which `OSPF` once shipped ([#548](https://github.com/JarryShaw/PyPCAPKit/issues/548)).
191+
- `tests/protocols/test_dispatch_reachability_unit.py`, the coverage [#548](https://github.com/JarryShaw/PyPCAPKit/issues/548) asked for: every `ProtocolBase` descendant whose `__index__` returns an enum member must be reachable under that code in the registry its enum *type* designates, read from the same `__proto_dest__` declaration backing `code=` so the two cannot drift. It walks the classes rather than the registry entries, so it catches a class nothing registered, the shape in which `OSPF` once shipped ([#548](https://github.com/JarryShaw/PyPCAPKit/issues/548)).
192192
- `tests/protocols/transport/test_tcp_mptcp_join_flag_ordering_unit.py`, covering all three MP_JOIN layouts through the *public* constructor, the construct-pack-parse cycle for each, the stale-flags case that rules out a zero-valued default, the statement order, and controls for the parse path and the flag-independent options. The old cases bypassed the public path, so full coverage coexisted with a broken one. The stale `tcp-mptcp/MP_JOIN` entry is deleted from `EXPECTED_FAILURES` ([#587](https://github.com/JarryShaw/PyPCAPKit/issues/587)).
193193
- `tests/protocols/test_option_generator_tcp_base_unit.py`, asserting that every `TCP_BASE` key is a parameter `TCP.make()` declares (derived from `inspect.signature`) and that the built segment carries the stated header in both data model and packed octets ([#602](https://github.com/JarryShaw/PyPCAPKit/issues/602)).
194194
- ILNP nonce sizing coverage in `tests/protocols/internet/test_ipv6_extension_unit.py`, a test per protocol, asserting the declared length, the exact packed octets and the construct-pack-parse cycle over a spread of nonces, most with a bit length that is *not* a multiple of eight, where floor division and the ceiling disagree ([#601](https://github.com/JarryShaw/PyPCAPKit/issues/601)).

‎docs/source/changelog/1.5.0.rst‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1303,7 +1303,7 @@ Added
13031303
* ``tests/protocols/test_dispatch_reachability_unit.py``, the coverage :issue:`548`
13041304
asked for: every :class:`.ProtocolBase` descendant whose ``__index__`` returns an enum
13051305
member must be reachable under that code in the registry its enum *type*
1306-
designates, read from the same ``_CODE_DESTINATIONS`` table backing ``code=`` so
1306+
designates, read from the same ``__proto_dest__`` declaration backing ``code=`` so
13071307
the two cannot drift. It walks the classes rather than the registry entries, so it
13081308
catches a class nothing registered, the shape in which
13091309
:class:`~pcapkit.protocols.application.ospf.OSPF` once shipped (:issue:`548`).

‎docs/source/pcapkit/const/reg.rst‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ which is automatically generated from :class:`pcapkit.vendor.reg.linktype.LinkTy
3030
:members:
3131
:undoc-members:
3232
:show-inheritance:
33+
:special-members: __proto_dest__
3334

3435
Ethertype IEEE 802 Numbers
3536
==========================
@@ -43,6 +44,7 @@ which is automatically generated from :class:`pcapkit.vendor.reg.ethertype.Ether
4344
:members:
4445
:undoc-members:
4546
:show-inheritance:
47+
:special-members: __proto_dest__
4648

4749
Transport Layer Protocol Numbers
4850
================================
@@ -56,6 +58,7 @@ which is automatically generated from :class:`pcapkit.vendor.reg.transtype.Trans
5658
:members:
5759
:undoc-members:
5860
:show-inheritance:
61+
:special-members: __proto_dest__
5962

6063
Application Layer Protocol Numbers
6164
==================================

‎docs/source/pcapkit/const/sctp.rst‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,7 @@ which is automatically generated from :class:`pcapkit.vendor.sctp.payload_protoc
7070
:members:
7171
:undoc-members:
7272
:show-inheritance:
73+
:special-members: __proto_dest__
7374

7475
.. rubric:: Footnotes
7576

‎docs/source/pcapkit/vendor/default.rst‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ only, which is the base class for all vendor crawlers.
1616
:no-value:
1717
.. autoattribute:: LINK
1818
:no-value:
19+
.. autoattribute:: PROTO_DEST
1920

2021
.. automethod:: count
2122
.. automethod:: process
@@ -76,7 +77,7 @@ Internal Definitions
7677
:no-members:
7778
:show-inheritance:
7879

79-
.. function:: LINE(NAME, DOCS, FLAG, ENUM, MISS, MODL)
80+
.. function:: LINE(NAME, DOCS, FLAG, ENUM, MISS, MODL, DEST=())
8081

8182
Default constant template of enumeration registry from IANA CSV.
8283

@@ -86,8 +87,16 @@ Internal Definitions
8687
:param str ENUM: enumeration data (class attributes)
8788
:param str MISS: missing value handler (default value)
8889
:param str MODL: module name of the constant enumeration class
90+
:param DEST: the crawler's :attr:`~pcapkit.vendor.default.Vendor.PROTO_DEST`,
91+
rendered as the class's ``__proto_dest__``; nothing is rendered when it is
92+
empty, which is the case for every registry that keys no ``__proto__``
93+
:type DEST: tuple[~pcapkit.corekit.module.ModuleDescriptor, ...]
8994
:rtype: str
9095

96+
.. autodata:: pcapkit.vendor.default.PROTO_DEST_IMPORT
97+
98+
.. autofunction:: pcapkit.vendor.default.render_proto_dest
99+
91100
.. autofunction:: pcapkit.vendor.default.get_proxies
92101

93102
.. autofunction:: pcapkit.vendor.default.stdin_is_interactive

‎pcapkit/const/reg/ethertype.py‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
from aenum import IntEnum
1616

1717
from pcapkit.corekit.enum import EnumRegistry
18+
from pcapkit.corekit.module import ModuleDescriptor
1819
from pcapkit.utilities.exceptions import EnumValueError
1920

2021
if TYPE_CHECKING:
@@ -26,6 +27,17 @@
2627
class EtherType(EnumRegistry, IntEnum):
2728
"""[EtherType] Ethertype IEEE 802 Numbers"""
2829

30+
#: Protocol class(es) owning the ``__proto__`` dispatch registry keyed by
31+
#: this enumeration, read by
32+
#: :func:`~pcapkit.foundation.registry.protocols.register_protocol_code`
33+
#: to resolve a bare member of it into its destination(s). The classes are
34+
#: named as lazy :class:`~pcapkit.corekit.module.ModuleDescriptor`
35+
#: references rather than imported, because :mod:`pcapkit.const` sits below
36+
#: :mod:`pcapkit.protocols` and importing one from here would be circular.
37+
__proto_dest__ = (
38+
ModuleDescriptor('pcapkit.protocols.link.link', 'Link'),
39+
)
40+
2941
#: Formerly XEROX PUP. Invalid as an Ethertype since 1983. Use 0x0A00. [Boggs,
3042
#: D., J. Shoch, E. Taft, and R. Metcalfe, "PUP: An Internetwork Architecture",
3143
#: XEROX Palo Alto Research Center, CSL-79-10, July 1979; also in IEEE

‎pcapkit/const/reg/linktype.py‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
from aenum import IntEnum
1616

1717
from pcapkit.corekit.enum import EnumRegistry
18+
from pcapkit.corekit.module import ModuleDescriptor
1819
from pcapkit.utilities.exceptions import EnumValueError
1920

2021
if TYPE_CHECKING:
@@ -26,6 +27,18 @@
2627
class LinkType(EnumRegistry, IntEnum):
2728
"""[LinkType] Link-Layer Header Type Values"""
2829

30+
#: Protocol class(es) owning the ``__proto__`` dispatch registry keyed by
31+
#: this enumeration, read by
32+
#: :func:`~pcapkit.foundation.registry.protocols.register_protocol_code`
33+
#: to resolve a bare member of it into its destination(s). The classes are
34+
#: named as lazy :class:`~pcapkit.corekit.module.ModuleDescriptor`
35+
#: references rather than imported, because :mod:`pcapkit.const` sits below
36+
#: :mod:`pcapkit.protocols` and importing one from here would be circular.
37+
__proto_dest__ = (
38+
ModuleDescriptor('pcapkit.protocols.misc.pcap.frame', 'Frame'),
39+
ModuleDescriptor('pcapkit.protocols.misc.pcapng', 'PCAPNG'),
40+
)
41+
2942
#: [``DLT_NULL``] BSD loopback encapsulation.
3043
NULL = 0
3144

‎pcapkit/const/reg/transtype.py‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
from aenum import IntEnum
1616

1717
from pcapkit.corekit.enum import EnumRegistry
18+
from pcapkit.corekit.module import ModuleDescriptor
1819
from pcapkit.utilities.exceptions import EnumValueError
1920

2021
if TYPE_CHECKING:
@@ -26,6 +27,17 @@
2627
class TransType(EnumRegistry, IntEnum):
2728
"""[TransType] Transport Layer Protocol Numbers"""
2829

30+
#: Protocol class(es) owning the ``__proto__`` dispatch registry keyed by
31+
#: this enumeration, read by
32+
#: :func:`~pcapkit.foundation.registry.protocols.register_protocol_code`
33+
#: to resolve a bare member of it into its destination(s). The classes are
34+
#: named as lazy :class:`~pcapkit.corekit.module.ModuleDescriptor`
35+
#: references rather than imported, because :mod:`pcapkit.const` sits below
36+
#: :mod:`pcapkit.protocols` and importing one from here would be circular.
37+
__proto_dest__ = (
38+
ModuleDescriptor('pcapkit.protocols.internet.internet', 'Internet'),
39+
)
40+
2941
#: IPv6 Hop-by-Hop Option [:rfc:`8200`]
3042
HOPOPT = 0
3143

‎pcapkit/const/sctp/payload_protocol_identifier.py‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
from aenum import IntEnum
1616

1717
from pcapkit.corekit.enum import EnumRegistry
18+
from pcapkit.corekit.module import ModuleDescriptor
1819
from pcapkit.utilities.exceptions import EnumValueError
1920

2021
if TYPE_CHECKING:
@@ -26,6 +27,17 @@
2627
class PayloadProtocolIdentifier(EnumRegistry, IntEnum):
2728
"""[PayloadProtocolIdentifier] SCTP Payload Protocol Identifiers"""
2829

30+
#: Protocol class(es) owning the ``__proto__`` dispatch registry keyed by
31+
#: this enumeration, read by
32+
#: :func:`~pcapkit.foundation.registry.protocols.register_protocol_code`
33+
#: to resolve a bare member of it into its destination(s). The classes are
34+
#: named as lazy :class:`~pcapkit.corekit.module.ModuleDescriptor`
35+
#: references rather than imported, because :mod:`pcapkit.const` sits below
36+
#: :mod:`pcapkit.protocols` and importing one from here would be circular.
37+
__proto_dest__ = (
38+
ModuleDescriptor('pcapkit.protocols.transport.sctp', 'SCTP'),
39+
)
40+
2941
#: Reserved by SCTP [:rfc:`9260`]
3042
Reserved_by_SCTP = 0
3143

‎pcapkit/foundation/registry/protocols.py‎

Lines changed: 19 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -88,7 +88,6 @@
8888
from pcapkit.const.reg.transtype import TransType
8989
from pcapkit.const.sctp.payload_protocol_identifier import \
9090
PayloadProtocolIdentifier as SCTP_PayloadProtocolIdentifier
91-
from pcapkit.corekit.enum import EnumRegistry
9291
from pcapkit.corekit.sentinels import NullType
9392
from pcapkit.protocols.application.httpv2 import FrameConstructor as HTTP_FrameConstructor
9493
from pcapkit.protocols.application.httpv2 import FrameParser as HTTP_FrameParser
@@ -405,25 +404,6 @@ def _register_name(protocol: 'Type[ProtocolBase]', *targets: 'tuple[type, Any]')
405404
_CODE_LEASES[target] = lease
406405

407406

408-
#: Destination classes for each enum type a ``code=`` key can carry.
409-
#:
410-
#: Maps an enum type to the class(es) owning the
411-
#: :attr:`ProtocolBase.__proto__ <pcapkit.protocols.protocol.ProtocolBase.__proto__>`
412-
#: dispatch registry keyed by that enum type -- the "registry-of-registries" that
413-
#: lets ``code=`` infer a destination from a key's own type, per :issue:`514`. It
414-
#: is the same targeting :func:`register_ethertype`, :func:`register_transtype`,
415-
#: :func:`register_linktype` and :func:`register_sctp` hard-code by hand, in one
416-
#: table so :func:`register_protocol_code` can consult it. :class:`~pcapkit.const.reg.linktype.LinkType` naming
417-
#: more than one class is deliberate, not ambiguous -- :func:`register_linktype`
418-
#: already fans out to each of them.
419-
_CODE_DESTINATIONS: 'dict[Type[EnumRegistry], tuple[Type[ProtocolBase], ...]]' = {
420-
Enum_EtherType: (Link,),
421-
Enum_TransType: (Internet,),
422-
Enum_PayloadProtocolIdentifier: (SCTP,),
423-
Enum_LinkType: (Frame, PCAPNG),
424-
}
425-
426-
427407
def _iter_code_targets(code: 'Any') -> 'Iterator[tuple[Type[ProtocolBase], Any]]':
428408
"""Flatten a ``code=`` argument into ``(destination, key)`` pairs.
429409
@@ -445,13 +425,23 @@ def _iter_code_targets(code: 'Any') -> 'Iterator[tuple[Type[ProtocolBase], Any]]
445425
return
446426

447427
if isinstance(code, (enum.Enum, aenum.Enum)):
448-
destinations = _CODE_DESTINATIONS.get(cast('Type[EnumRegistry]', type(code)))
449-
if destinations is None:
428+
# NOTE: read with ``getattr``, not out of the type's own ``vars()`` as
429+
# the ``__proto_key__`` check in ``register_protocol_code`` does. That
430+
# read is deliberately non-inheriting because a protocol subclass can
431+
# own a registry keyed by something other than its parent's -- Loopback
432+
# does. No enum registry can be in that position: declaring a
433+
# destination means having members, and aenum refuses to extend an
434+
# enumeration with members, so none of these registries has a subclass
435+
# and none can gain one. Where an enum registry is subclassed it is a
436+
# memberless base partitioned by transport protocol (AppType), whose
437+
# parts share one key space and would rightly share one destination.
438+
destinations = getattr(type(code), '__proto_dest__', None)
439+
if not destinations:
450440
raise RegistryError(
451441
f'no destination registry is known for enum type {type(code).__name__!r} '
452442
f'(key {code!r}); pass an explicit destination, e.g. code={{SomeClass: {code!r}}}')
453-
for destination in destinations:
454-
yield destination, code
443+
for descriptor in destinations:
444+
yield descriptor.klass, code
455445
return
456446

457447
if isinstance(code, (str, bytes)):
@@ -479,8 +469,9 @@ def register_protocol_code(protocol: 'Type[ProtocolBase]', code: 'Any') -> 'None
479469
``code`` is normalised into a flat sequence of targets, where each item
480470
is either:
481471
482-
* an enum member, whose *type* is looked up in a small table mapping
483-
enum type to the class(es) owning the matching ``__proto__`` --
472+
* an enum member, whose *type* names the class(es) owning the matching
473+
``__proto__`` in its
474+
:attr:`__proto_dest__ <pcapkit.const.reg.ethertype.EtherType.__proto_dest__>` --
484475
:class:`~pcapkit.const.reg.ethertype.EtherType` to
485476
:class:`~pcapkit.protocols.link.link.Link`,
486477
:class:`~pcapkit.const.reg.transtype.TransType` to
@@ -527,7 +518,8 @@ def register_protocol_code(protocol: 'Type[ProtocolBase]', code: 'Any') -> 'None
527518
Raises:
528519
RegistryError: If a bare :class:`int` (or any other non-enum,
529520
non-mapping value) is given without an explicit destination, or if
530-
an enum member's type names no known destination registry --
521+
an enum member's type declares no
522+
:attr:`__proto_dest__ <pcapkit.const.reg.ethertype.EtherType.__proto_dest__>` --
531523
inference refuses rather than guesses; or if a key is not of the
532524
type its destination's registry is keyed by, as its typed registrar
533525
would reject it, e.g. ``{Frame: TransType.ICMP}``. What a registry is

0 commit comments

Comments
 (0)