Skip to content

Commit f656fab

Browse files
authored
refactor(utilities): move the ContextVars shared across modules into pcapkit.utilities.contextvars (#2623)
- pcapkit/utilities/contextvars.py: a leaf module holding beholding, frame_depth, in_fragment and rebuilding, public and in __all__. It imports nothing from pcapkit. - Their private definitions leave corekit.checksum.internet, corekit.decorators and protocols.protocol with no re-export; every reader imports them from utilities.contextvars. Module-private ContextVars stay put. - tests/project/test_shared_contextvars_2616_unit.py fails on a ContextVar taken across modules from anywhere else, and on a shared one that is private, missing from __all__ or read by one module alone. - Docs: an API page in the utilities toctree, and a Context Variables section on utilities-or-corekit.rst.
1 parent 83f05f5 commit f656fab

19 files changed

Lines changed: 417 additions & 74 deletions

File tree

‎docs/source/contributing/conventions/index.rst‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,8 @@ House Conventions
2727
reference, rather than any code at all;
2828
* :ref:`test-coverage` -- what the test suite has to prove;
2929
* :ref:`utilities-or-corekit` -- which of :mod:`pcapkit.utilities` and
30-
:mod:`pcapkit.corekit` a support module belongs in;
30+
:mod:`pcapkit.corekit` a support module belongs in, and where a context
31+
variable lives;
3132
* :ref:`reassembly-integration` -- :mod:`pcapkit.foundation.reassembly` and what a
3233
new engine there needs from :mod:`pcapkit.toolkit` and
3334
:mod:`pcapkit.foundation.analysis`;

‎docs/source/contributing/conventions/utilities-or-corekit.rst‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,3 +53,25 @@ checks that. What needs IPv4 and IPv6 stays beside
5353
:class:`~pcapkit.protocols.misc.checksum.ip_pseudo.IP_Pseudo`. The package holds one
5454
module per checksum family, so a new family sits beside
5555
:mod:`~pcapkit.corekit.checksum.internet`.
56+
57+
Context Variables
58+
~~~~~~~~~~~~~~~~~
59+
60+
Where a :class:`~contextvars.ContextVar` lives depends on which modules use it.
61+
Settled by the owner on :issue:`2616`:
62+
63+
* **One that more than one module sets or reads lives in**
64+
:mod:`pcapkit.utilities.contextvars`, under a public name in its ``__all__``. No
65+
other module re-exports it, so every reader imports it from there.
66+
* **One that only its own module uses stays in that module**, private, as
67+
``_exthdr_rebuilt`` does in :mod:`pcapkit.protocols.internet.internet`.
68+
69+
A shared variable kept in one of the modules that use it makes the others import a
70+
private name from that module, and ties them to its place in the import graph. A
71+
module of bare declarations that imports nothing from :mod:`pcapkit` passes the
72+
``utilities`` question above, so any module may import it --
73+
:mod:`pcapkit.corekit.checksum` included, which must not reach
74+
:mod:`pcapkit.protocols`. :file:`tests/project/test_shared_contextvars_2616_unit.py`
75+
fails on a module that takes a context variable from anywhere else, by name or as an
76+
attribute of an imported module, and on a variable there that is private, missing
77+
from ``__all__``, or read by one module alone.
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
Shared Context Variables
2+
========================
3+
4+
.. module:: pcapkit.utilities.contextvars
5+
6+
:mod:`pcapkit.utilities.contextvars` holds the :class:`~contextvars.ContextVar`
7+
objects that more than one :mod:`pcapkit` module sets or reads, so that no module
8+
imports another's private state (:issue:`2616`). A context variable that only its
9+
own module uses stays there. This module imports nothing from :mod:`pcapkit`, so
10+
a module at any layer may import it; see :ref:`utilities-or-corekit`.
11+
12+
.. versionadded:: 1.6.0
13+
14+
.. autodata:: pcapkit.utilities.contextvars.beholding
15+
:no-value:
16+
17+
.. autodata:: pcapkit.utilities.contextvars.frame_depth
18+
:no-value:
19+
20+
.. autodata:: pcapkit.utilities.contextvars.in_fragment
21+
:no-value:
22+
23+
.. autodata:: pcapkit.utilities.contextvars.rebuilding
24+
:no-value:

‎docs/source/pcapkit/utilities/index.rst‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,8 @@ Module Utilities
77
:mod:`pcapkit.utilities` holds the cross-cutting services :mod:`pcapkit` is
88
built with: user-refined exceptions and warnings, logging, the tunable limits
99
of :mod:`~pcapkit.utilities.config`, a compatibility layer, timestamp
10-
conversion, and wrappers around third-party libraries. It imports nothing from
10+
conversion, the :mod:`context variables <pcapkit.utilities.contextvars>` its
11+
modules share, and wrappers around third-party libraries. It imports nothing from
1112
:mod:`pcapkit` outside itself; see :ref:`utilities-or-corekit`.
1213

1314
.. toctree::
@@ -19,6 +20,7 @@ conversion, and wrappers around third-party libraries. It imports nothing from
1920
config
2021
chardet
2122
datetime
23+
contextvars
2224

2325
Version Compatibility
2426
=====================

‎pcapkit/corekit/checksum/internet.py‎

Lines changed: 4 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -25,12 +25,12 @@
2525
2626
"""
2727
import contextlib
28-
import contextvars
2928
import enum
3029
import struct
3130
from typing import TYPE_CHECKING
3231

3332
from pcapkit.corekit.enum import EnumLookup
33+
from pcapkit.utilities.contextvars import in_fragment, rebuilding
3434
from pcapkit.utilities.exceptions import stacklevel
3535
from pcapkit.utilities.warnings import ChecksumWarning, warn
3636

@@ -43,18 +43,6 @@
4343
'fragment_payload',
4444
]
4545

46-
#: contextvars.ContextVar[bool]: Whether a payload is being rebuilt by
47-
#: :meth:`Protocol._make_payload
48-
#: <pcapkit.protocols.protocol.Protocol._make_payload>`, so that the layer
49-
#: it is rebuilt for parses the same octets again; see
50-
#: :data:`~pcapkit.utilities.config.FRAME_LAYER_LIMIT`. It lives here so that
51-
#: :func:`verify_checksum` reads it without importing :mod:`pcapkit.protocols`.
52-
_rebuilding = contextvars.ContextVar('_rebuilding', default=False)
53-
54-
#: contextvars.ContextVar[bool]: Whether the layer being parsed is the payload
55-
#: of an IP fragment, see :func:`fragment_payload`.
56-
_in_fragment = contextvars.ContextVar('_in_fragment', default=False)
57-
5846

5947
class ChecksumStatus(EnumLookup, enum.IntEnum):
6048
"""Outcome of verifying a checksum, as recorded in ``checksum_status``.
@@ -193,7 +181,7 @@ def verify_checksum(alias: 'str', data: 'bytes', field: 'bytes', *, length: 'Opt
193181
value = int.from_bytes(field, 'big')
194182
rest = total + (~value & 0xFFFF)
195183
expected = ~((rest & 0xFFFF) + (rest >> 16)) & 0xFFFF
196-
if not _rebuilding.get():
184+
if not rebuilding.get():
197185
warn(f'{alias}: checksum {value:#06x} is wrong; {expected:#06x} expected',
198186
ChecksumWarning, stacklevel=stacklevel())
199187
return ChecksumStatus.INVALID
@@ -212,8 +200,8 @@ def fragment_payload(fragment: 'bool') -> 'Iterator[None]':
212200
fragment: Whether the IP layer is a fragment; an atomic one is not.
213201
214202
"""
215-
token = _in_fragment.set(fragment)
203+
token = in_fragment.set(fragment)
216204
try:
217205
yield
218206
finally:
219-
_in_fragment.reset(token)
207+
in_fragment.reset(token)

‎pcapkit/corekit/decorators.py‎

Lines changed: 3 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -24,13 +24,13 @@
2424
decorators either.
2525
2626
"""
27-
import contextvars
2827
import functools
2928
import io
3029
import os
3130
import traceback
3231
from typing import TYPE_CHECKING, cast
3332

33+
from pcapkit.utilities.contextvars import beholding
3434
from pcapkit.utilities.exceptions import (CaughtByCaller, ProtocolError, StreamEOFError,
3535
StructError, stacklevel)
3636
from pcapkit.utilities.logging import DEVMODE, VERBOSE, get_logger
@@ -55,14 +55,6 @@
5555
#: :data:`pcapkit.utilities.logging.logger`.
5656
logger = get_logger(__name__)
5757

58-
#: contextvars.ContextVar[bool]: Whether a layer that raises is discarded by its
59-
#: caller, as :func:`beholder` replaces it and
60-
#: :func:`~pcapkit.toolkit.pypcapfile._default_extension_header` drops it, so
61-
#: that :meth:`Protocol._parse_next_layer
62-
#: <pcapkit.protocols.protocol.Protocol._parse_next_layer>` drops its warnings
63-
#: with it (:issue:`2308`).
64-
_beholding = contextvars.ContextVar('_beholding', default=False)
65-
6658

6759
def seekset(func: 'Callable[Concatenate[ProtocolBase, P], R_seekset]') -> 'Callable[P, R_seekset]':
6860
"""Read file from start then set back to original.
@@ -183,14 +175,14 @@ def behold(*args: 'P.args', **kwargs: 'P.kwargs') -> 'R_beholder':
183175

184176
try:
185177
# call method
186-
token = _beholding.set(True)
178+
token = beholding.set(True)
187179
try:
188180
# NOTE: The whole call is quiet for a ProtocolError, which the ``except`` below
189181
# records; the recovery runs after it, loud unless an outer block is active (#2588).
190182
with CaughtByCaller(ProtocolError):
191183
return func(*args, **kwargs)
192184
finally:
193-
_beholding.reset(token)
185+
beholding.reset(token)
194186
except Exception as exc:
195187
if isinstance(exc, StructError) and exc.eof: # pylint: disable=no-member
196188
from pcapkit.protocols.misc.null import NoPayload as protocol # isort: skip # pylint: disable=import-outside-toplevel

‎pcapkit/protocols/application/tls.py‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@
6767
from typing import TYPE_CHECKING, cast
6868

6969
from pcapkit.const.tls.content_type import ContentType as Enum_ContentType
70-
from pcapkit.corekit.decorators import _beholding, beholder
70+
from pcapkit.corekit.decorators import beholder
7171
from pcapkit.protocols.application.ssl import (_TLS_VERSION_MAJOR, _WIRE_CONTENT_TYPES, SSL,
7272
TLS13_VERSION)
7373
from pcapkit.protocols.application.sslv2 import SSLv2
@@ -76,6 +76,7 @@
7676
from pcapkit.protocols.data.application.sslv2 import SSLv2 as SSLv2_Data
7777
from pcapkit.protocols.data.application.tls import TLS as Data_TLS
7878
from pcapkit.protocols.schema.application.tls import TLS as Schema_TLS
79+
from pcapkit.utilities.contextvars import beholding
7980
from pcapkit.utilities.exceptions import ProtocolError
8081
from pcapkit.utilities.warnings import hold_warnings
8182

@@ -314,7 +315,7 @@ def unpack(self, length: 'Optional[int]' = None, *, chained: 'bool' = False, #
314315
parsed = self._read_sslv2_fallback(len(self) if length is None else length, **kwargs)
315316
fallback.discard = parsed is None
316317
if parsed is None:
317-
trial.discard = _beholding.get()
318+
trial.discard = beholding.get()
318319
raise
319320
return parsed
320321

‎pcapkit/protocols/internet/icmpv4.py‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -205,8 +205,9 @@ def read(self, length: 'Optional[int]' = None, *,
205205
# an IP fragment carries only part of one.
206206
if config.CHECKSUM_VERIFY:
207207
from pcapkit.corekit.checksum.internet import ( # isort: skip # pylint: disable=import-outside-toplevel
208-
ChecksumStatus, _in_fragment, verify_checksum)
209-
if _in_fragment.get():
208+
ChecksumStatus, verify_checksum)
209+
from pcapkit.utilities.contextvars import in_fragment # isort: skip # pylint: disable=import-outside-toplevel
210+
if in_fragment.get():
210211
status = ChecksumStatus.NO_PSEUDO_HEADER
211212
else:
212213
status = verify_checksum(self.alias, self._data, schema.checksum, length=length)

‎pcapkit/protocols/internet/internet.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,13 +18,13 @@
1818

1919
from pcapkit.const.ipv6.extension_header import ExtensionHeader as Enum_ExtensionHeader
2020
from pcapkit.const.reg.transtype import TransType as Enum_TransType
21-
from pcapkit.corekit.checksum.internet import _rebuilding
2221
from pcapkit.corekit.decorators import beholder
2322
from pcapkit.corekit.module import ModuleDescriptor
2423
from pcapkit.corekit.protochain import ProtoChain
2524
from pcapkit.protocols.protocol import _PT, _ST, ProtocolBase
2625
from pcapkit.protocols.schema.schema import keep_short_read, replay_short_read
2726
from pcapkit.utilities import config
27+
from pcapkit.utilities.contextvars import rebuilding
2828
from pcapkit.utilities.exceptions import stacklevel
2929
from pcapkit.utilities.warnings import ProtocolWarning, RegistryWarning, warn
3030

@@ -428,7 +428,7 @@ class registered for ``proto``. Paired with it, the keywords that
428428
# NOTE: Inside a payload being rebuilt, the layer it is rebuilt for
429429
# warns of the same octets once its own parse gets here, as for
430430
# :data:`~pcapkit.utilities.config.FRAME_LAYER_LIMIT`.
431-
if not _rebuilding.get():
431+
if not rebuilding.get():
432432
warn(message, ProtocolWarning, stacklevel=stacklevel())
433433
return Raw, {'error': message}
434434

‎pcapkit/protocols/internet/ipv4.py‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,6 @@
5656
from pcapkit.const.ipv4.tos_thr import ToSThroughput as Enum_ToSThroughput
5757
from pcapkit.const.ipv4.ts_flag import TSFlag as Enum_TSFlag
5858
from pcapkit.const.reg.transtype import TransType as Enum_TransType
59-
from pcapkit.corekit.checksum.internet import _rebuilding
6059
from pcapkit.corekit.fields.ipaddress import parse_ip_address
6160
from pcapkit.corekit.multidict import OrderedMultiDict
6261
from pcapkit.protocols.data.internet.ipv4 import EOOLOption as Data_EOOLOption
@@ -106,6 +105,7 @@
106105
from pcapkit.protocols.schema.internet.ipv4 import UnassignedOption as Schema_UnassignedOption
107106
from pcapkit.protocols.schema.schema import Schema
108107
from pcapkit.utilities import config
108+
from pcapkit.utilities.contextvars import rebuilding
109109
from pcapkit.utilities.exceptions import ProtocolError
110110
from pcapkit.utilities.warnings import ProtocolWarning, RegistryWarning, warn
111111

@@ -605,12 +605,12 @@ def make(self,
605605
from pcapkit.protocols.misc.checksum.ip_pseudo import IP_Pseudo # isort: skip # pylint: disable=import-outside-toplevel
606606

607607
# NOTE: The header is parsed back for a source route's destination,
608-
# quietly, as this layer parses it again (cf. _rebuilding).
609-
token = _rebuilding.set(True)
608+
# quietly, as this layer parses it again (cf. rebuilding).
609+
token = rebuilding.set(True)
610610
try:
611611
header = IPv4(schema.pack()[:ihl * 4])
612612
finally:
613-
_rebuilding.reset(token)
613+
rebuilding.reset(token)
614614
# NOTE: The payload puts its own length in the pseudo-header.
615615
pseudo = IP_Pseudo(ip=header, protocol=proto, upper_length=0)
616616
upper = cast('ProtocolBase', payload)

0 commit comments

Comments
 (0)