Skip to content

Traffic records

One JSON body per DNP3 application fragment, as the DNP3 traffic schema, version 1, defines it, and the envelope that carries it. DNP3 traffic records is the guide; this is the reference.

py1815.traffic

DNP3 traffic records: one JSON body per application fragment, and its envelope.

An application that embeds the outstation or the master knows every fragment it sends and receives. This module describes each fragment as a JSON body that follows the DNP3 traffic schema, version 1 (:data:SCHEMA_ID), and wraps the body in a :class:~py1815.envelope.ProtocolMessage, so the application can publish its own traffic to consumers that also take captured DNP3 traffic. It builds the bodies from a :class:~py1815.observers.RequestRecord from the outstation, and from an exchange or an unsolicited response from the master.

The schema, not any one decoder's output, defines the body (D103). It ships with the package, and :func:load_schema returns it. A body describes the fragment in IEEE 1815 terms:

  • The link addresses, the application function code, the link layer's primary-message bit, which end sent the fragment, the application control's UNS bit, and a response's internal indications by name.
  • The IP address and port of each end of the connection, where known.
  • One entry per object header, with its qualifier, its range or count, and the octets of objects that are not points, such as a time write.
  • Every point the fragment carries, in wire order, with its point type, object group and variation, the index on the wire, its value, flag octet and time, and the fields of a control object.

The fragment is read by this module's own walk of the object headers, written from the object layouts of IEEE 1815-2012. An object the master's decoder also reads takes its layout from :data:py1815.decode.LAYOUTS, so both read its octets the same way. The walk reads requests and responses, every qualifier the standard defines, and the command objects a master sends and an outstation echoes. A fragment it cannot read to its end is described as rejected, with no objects and no points (:data:REJECTED_MALFORMED, :data:REJECTED_POINT_COUNT, :data:REJECTED_TOO_LARGE).

Copyright 2026 DER Security Corp. Licensed under the Apache License, Version 2.0.

Direction

Bases: StrEnum

Which end sent a fragment: the master sends requests, the outstation responses.

Source code in src/py1815/traffic.py
class Direction(StrEnum):
    """Which end sent a fragment: the master sends requests, the outstation responses."""

    REQUEST = "request"
    RESPONSE = "response"

load_schema

load_schema() -> dict[str, Any]

Return the JSON Schema the bodies follow, read from the copy in this package.

Source code in src/py1815/traffic.py
def load_schema() -> dict[str, Any]:
    """Return the JSON Schema the bodies follow, read from the copy in this package."""
    text = (resources.files("py1815") / "schemas" / _SCHEMA_FILE).read_text(encoding="utf-8")
    schema: dict[str, Any] = json.loads(text)
    return schema

fragment_body

fragment_body(
    fragment: bytes,
    *,
    direction: Direction | str,
    source: int,
    destination: int,
    sender: Endpoint | None = None,
    receiver: Endpoint | None = None,
) -> dict[str, Any]

Return the body for one application fragment, request or response.

Parameters:

Name Type Description Default
fragment bytes

The application fragment, from the application control octet to the last object.

required
direction Direction | str

"request" for a fragment the master sent, "response" for one the outstation sent, an unsolicited response included. A response is read with its internal indications.

required
source int

The link address of the station that sent the fragment.

required
destination int

The link address it was sent to.

required
sender Endpoint | None

The sender's end of the connection, for source_ip and source_port. Left out of the body when None.

None
receiver Endpoint | None

The receiver's end, for destination_ip and destination_port.

None

Raises:

Type Description
ValueError

If the fragment is shorter than a control octet and a function code, or direction names neither direction.

Source code in src/py1815/traffic.py
def fragment_body(
    fragment: bytes,
    *,
    direction: Direction | str,
    source: int,
    destination: int,
    sender: Endpoint | None = None,
    receiver: Endpoint | None = None,
) -> dict[str, Any]:
    """Return the body for one application fragment, request or response.

    Args:
        fragment: The application fragment, from the application control octet
            to the last object.
        direction: ``"request"`` for a fragment the master sent,
            ``"response"`` for one the outstation sent, an unsolicited response
            included. A response is read with its internal indications.
        source: The link address of the station that sent the fragment.
        destination: The link address it was sent to.
        sender: The sender's end of the connection, for ``source_ip`` and
            ``source_port``. Left out of the body when None.
        receiver: The receiver's end, for ``destination_ip`` and
            ``destination_port``.

    Raises:
        ValueError: If the fragment is shorter than a control octet and a
            function code, or ``direction`` names neither direction.
    """
    direction = Direction(direction)
    if len(fragment) < 2:
        raise ValueError("a fragment holds at least an application control octet and a function")
    function = fragment[1]
    body: dict[str, Any] = {
        "schema": SCHEMA_VERSION,
        "source_address": source,
        "destination_address": destination,
        "function_code": function,
        "prm": _PRIMARY,
        "direction": direction.value,
        "unsolicited": bool(fragment[0] & UNS_MASK),
    }
    _put_endpoint(body, "source", sender)
    _put_endpoint(body, "destination", receiver)
    header = 2
    if direction is Direction.RESPONSE:
        if len(fragment) < 4:
            body.update(objects=[], points=[], apdu_rejected=REJECTED_MALFORMED)
            return body
        body["iin"] = _iin(fragment[2], fragment[3])
        header = 4
    walk = _Walk(bytes(fragment[header:]), direction=direction, function=function)
    try:
        walk.run()
    except _Rejected as rejected:
        # Values read from object data that cannot be trusted cannot be
        # trusted either, so a rejected fragment reports none.
        body.update(objects=[], points=[], apdu_rejected=rejected.reason)
        return body
    body["objects"] = walk.objects
    body["points"] = walk.points
    return body

record_bodies

record_bodies(
    record: RequestRecord,
    *,
    outstation: Endpoint | None = None,
) -> list[dict[str, Any]]

Return the bodies of one request record: the request, then the response.

An unsolicited response gives one body, and a request that was not answered gives the request alone. outstation is this outstation's end of the connection, for a record that does not carry one in local.

Source code in src/py1815/traffic.py
def record_bodies(
    record: RequestRecord, *, outstation: Endpoint | None = None
) -> list[dict[str, Any]]:
    """Return the bodies of one request record: the request, then the response.

    An unsolicited response gives one body, and a request that was not
    answered gives the request alone. ``outstation`` is this outstation's end
    of the connection, for a record that does not carry one in ``local``.
    """
    master_end = record.peer
    outstation_end = outstation or record.local
    if record.unsolicited:
        assert record.response is not None
        return [
            fragment_body(
                record.response,
                direction=Direction.RESPONSE,
                source=record.source,
                destination=record.destination,
                sender=outstation_end,
                receiver=master_end,
            )
        ]
    bodies = [
        fragment_body(
            record.request,
            direction=Direction.REQUEST,
            source=record.source,
            destination=record.destination,
            sender=master_end,
            receiver=outstation_end,
        )
    ]
    if record.response is not None:
        bodies.append(
            fragment_body(
                record.response,
                direction=Direction.RESPONSE,
                source=record.destination,
                destination=record.source,
                sender=outstation_end,
                receiver=master_end,
            )
        )
    return bodies

exchange_bodies

exchange_bodies(
    exchange: Exchange,
    *,
    master_address: int,
    outstation_address: int,
    master: Endpoint | None = None,
    outstation: Endpoint | None = None,
) -> list[dict[str, Any]]

Return the bodies of one master exchange: the request, then each response fragment.

master and outstation are the two ends of the master's connection. The request is described once, however many times it was sent again.

Source code in src/py1815/traffic.py
def exchange_bodies(
    exchange: Exchange,
    *,
    master_address: int,
    outstation_address: int,
    master: Endpoint | None = None,
    outstation: Endpoint | None = None,
) -> list[dict[str, Any]]:
    """Return the bodies of one master exchange: the request, then each response fragment.

    ``master`` and ``outstation`` are the two ends of the master's connection.
    The request is described once, however many times it was sent again.
    """
    destination = outstation_address if exchange.broadcast is None else int(exchange.broadcast)
    bodies = [
        fragment_body(
            exchange.request,
            direction=Direction.REQUEST,
            source=master_address,
            destination=destination,
            sender=master,
            receiver=outstation,
        )
    ]
    bodies.extend(
        fragment_body(
            _fragment(response),
            direction=Direction.RESPONSE,
            source=outstation_address,
            destination=master_address,
            sender=outstation,
            receiver=master,
        )
        for response in exchange.fragments
    )
    return bodies

unsolicited_body

unsolicited_body(
    unsolicited: Unsolicited,
    *,
    master_address: int,
    outstation_address: int,
    master: Endpoint | None = None,
    outstation: Endpoint | None = None,
) -> dict[str, Any]

Return the body of one unsolicited response the master received.

Source code in src/py1815/traffic.py
def unsolicited_body(
    unsolicited: Unsolicited,
    *,
    master_address: int,
    outstation_address: int,
    master: Endpoint | None = None,
    outstation: Endpoint | None = None,
) -> dict[str, Any]:
    """Return the body of one unsolicited response the master received."""
    return fragment_body(
        _fragment(unsolicited.response),
        direction=Direction.RESPONSE,
        source=outstation_address,
        destination=master_address,
        sender=outstation,
        receiver=master,
    )

envelope

envelope(
    body: dict[str, Any],
    *,
    outstation: Endpoint,
    at: float,
    forwarder_id: str = "",
    capture_origin: str = CAPTURE_ORIGIN_LIVE,
) -> ProtocolMessage

Return the envelope that carries one body.

The envelope names the outstation: source is its address and port and client_id its link address, the source address of a response and the destination address of a request. direction is upstream for every fragment, whichever end sent it.

Parameters:

Name Type Description Default
body dict[str, Any]

A body from :func:fragment_body or the functions built on it.

required
outstation Endpoint

The outstation's address and port.

required
at float

When the fragment was sent, in seconds since the Unix epoch.

required
forwarder_id str

Names the system publishing the message.

''
capture_origin str

Where the traffic was captured; "live" for traffic seen as it happened.

CAPTURE_ORIGIN_LIVE
Source code in src/py1815/traffic.py
def envelope(
    body: dict[str, Any],
    *,
    outstation: Endpoint,
    at: float,
    forwarder_id: str = "",
    capture_origin: str = CAPTURE_ORIGIN_LIVE,
) -> ProtocolMessage:
    """Return the envelope that carries one body.

    The envelope names the outstation: ``source`` is its address and port and
    ``client_id`` its link address, the source address of a response and the
    destination address of a request. ``direction`` is ``upstream`` for every
    fragment, whichever end sent it.

    Args:
        body: A body from :func:`fragment_body` or the functions built on it.
        outstation: The outstation's address and port.
        at: When the fragment was sent, in seconds since the Unix epoch.
        forwarder_id: Names the system publishing the message.
        capture_origin: Where the traffic was captured; ``"live"`` for
            traffic seen as it happened.
    """
    if body.get("direction") == Direction.RESPONSE:
        link_address = body.get("source_address")
    else:
        link_address = body.get("destination_address")
    return ProtocolMessage(
        protocol=Protocol.DNP3,
        direction=WireDirection.UPSTREAM,
        client_id=str(link_address if link_address is not None else 0),
        payload=body,
        source=NetworkEndpoint(ip=outstation.host, port=outstation.port),
        forwarder_id=forwarder_id,
        protocol_data=ProtocolMetadata(
            extra={
                CAPTURE_ORIGIN_KEY: capture_origin.strip() or CAPTURE_ORIGIN_LIVE,
                CLIENT_ID_SOURCE_KEY: "",
            }
        ),
        timestamp=datetime.fromtimestamp(at, UTC).isoformat(),
    )

record_messages

record_messages(
    record: RequestRecord,
    *,
    outstation: Endpoint | None = None,
    forwarder_id: str = "",
    capture_origin: str = CAPTURE_ORIGIN_LIVE,
) -> list[ProtocolMessage]

Return the envelopes of one request record, stamped with the record's time.

Raises:

Type Description
ValueError

If the record has no local address and no outstation is given.

Source code in src/py1815/traffic.py
def record_messages(
    record: RequestRecord,
    *,
    outstation: Endpoint | None = None,
    forwarder_id: str = "",
    capture_origin: str = CAPTURE_ORIGIN_LIVE,
) -> list[ProtocolMessage]:
    """Return the envelopes of one request record, stamped with the record's time.

    Raises:
        ValueError: If the record has no ``local`` address and no
            ``outstation`` is given.
    """
    endpoint = _known(outstation or record.local)
    return [
        envelope(
            body,
            outstation=endpoint,
            at=record.timestamp,
            forwarder_id=forwarder_id,
            capture_origin=capture_origin,
        )
        for body in record_bodies(record, outstation=endpoint)
    ]

exchange_messages

exchange_messages(
    exchange: Exchange,
    *,
    master_address: int,
    outstation_address: int,
    outstation: Endpoint,
    master: Endpoint | None = None,
    at: float | None = None,
    forwarder_id: str = "",
    capture_origin: str = CAPTURE_ORIGIN_LIVE,
) -> list[ProtocolMessage]

Return the envelopes of one master exchange.

at is when the exchange ended, now if not given. The responses are stamped with it, and the request with the time it was first sent.

Source code in src/py1815/traffic.py
def exchange_messages(
    exchange: Exchange,
    *,
    master_address: int,
    outstation_address: int,
    outstation: Endpoint,
    master: Endpoint | None = None,
    at: float | None = None,
    forwarder_id: str = "",
    capture_origin: str = CAPTURE_ORIGIN_LIVE,
) -> list[ProtocolMessage]:
    """Return the envelopes of one master exchange.

    ``at`` is when the exchange ended, now if not given. The responses are
    stamped with it, and the request with the time it was first sent.
    """
    ended = time.time() if at is None else at
    bodies = exchange_bodies(
        exchange,
        master_address=master_address,
        outstation_address=outstation_address,
        master=master,
        outstation=outstation,
    )
    return [
        envelope(
            body,
            outstation=outstation,
            at=ended - exchange.elapsed if number == 0 else ended,
            forwarder_id=forwarder_id,
            capture_origin=capture_origin,
        )
        for number, body in enumerate(bodies)
    ]

unsolicited_message

unsolicited_message(
    unsolicited: Unsolicited,
    *,
    master_address: int,
    outstation_address: int,
    outstation: Endpoint,
    master: Endpoint | None = None,
    at: float | None = None,
    forwarder_id: str = "",
    capture_origin: str = CAPTURE_ORIGIN_LIVE,
) -> ProtocolMessage

Return the envelope of one unsolicited response, stamped at or now.

Source code in src/py1815/traffic.py
def unsolicited_message(
    unsolicited: Unsolicited,
    *,
    master_address: int,
    outstation_address: int,
    outstation: Endpoint,
    master: Endpoint | None = None,
    at: float | None = None,
    forwarder_id: str = "",
    capture_origin: str = CAPTURE_ORIGIN_LIVE,
) -> ProtocolMessage:
    """Return the envelope of one unsolicited response, stamped ``at`` or now."""
    body = unsolicited_body(
        unsolicited,
        master_address=master_address,
        outstation_address=outstation_address,
        master=master,
        outstation=outstation,
    )
    return envelope(
        body,
        outstation=outstation,
        at=time.time() if at is None else at,
        forwarder_id=forwarder_id,
        capture_origin=capture_origin,
    )

py1815.envelope

The message envelope DNP3 traffic records are published in.

Each DNP3 application fragment, captured from the network or reported by one end of the association, is published as a :class:ProtocolMessage: an envelope that names the protocol, the device and the time, and carries the fragment's description as a JSON payload. :mod:py1815.traffic builds those payloads and envelopes from what the outstation and the master report, so an application can publish their traffic beside captured traffic without converting it. This module is the envelope alone. It knows nothing of DNP3 beyond the protocol's name, and nothing in the outstation or the master depends on it.

The envelope is a published contract shared with consumers that also ingest other protocols. It is copied here, not imported, so the library keeps no runtime dependency (D1). Its serialized form is the contract, as :meth:ProtocolMessage.to_dict emits it:

  • version, protocol, direction, timestamp, client_id, forwarder_id, payload, source, hash and is_valid are always present.
  • destination, protocol_data and validation_error appear only when set. An optional field is left out, not written as null: a consumer matches on presence, and adding a field is a compatible change.
  • timestamp is an ISO 8601 date and time with a UTC offset. A trailing Z is rewritten to +00:00 on construction. A date with no time, or a time with no offset, is refused: neither names one instant.
  • hash is a UUIDv3 over the protocol, the client id, the timestamp and the payload text, so a consumer can find a message published twice without asking the producer.

Copyright 2026 DER Security Corp. Licensed under the Apache License, Version 2.0.

WireDirection

Bases: StrEnum

Which way the message travelled, as the envelope carries it.

UPSTREAM is from the device toward a server, DOWNSTREAM the other way.

Source code in src/py1815/envelope.py
class WireDirection(StrEnum):
    """Which way the message travelled, as the envelope carries it.

    ``UPSTREAM`` is from the device toward a server, ``DOWNSTREAM`` the other
    way.
    """

    UPSTREAM = "upstream"
    DOWNSTREAM = "downstream"

Protocol

Bases: StrEnum

The application protocol a message was captured from.

Source code in src/py1815/envelope.py
class Protocol(StrEnum):
    """The application protocol a message was captured from."""

    DNP3 = "dnp3"

    @classmethod
    def from_string(cls, value: str) -> Protocol:
        """Return the protocol named by a wire value, ignoring case.

        Raises:
            ValueError: If the value names no protocol this module knows.
        """
        normalized = value.lower().strip()
        for member in cls:
            if member.value == normalized:
                return member
        raise ValueError(f"unknown protocol: {value}")
from_string classmethod
from_string(value: str) -> Protocol

Return the protocol named by a wire value, ignoring case.

Raises:

Type Description
ValueError

If the value names no protocol this module knows.

Source code in src/py1815/envelope.py
@classmethod
def from_string(cls, value: str) -> Protocol:
    """Return the protocol named by a wire value, ignoring case.

    Raises:
        ValueError: If the value names no protocol this module knows.
    """
    normalized = value.lower().strip()
    for member in cls:
        if member.value == normalized:
            return member
    raise ValueError(f"unknown protocol: {value}")

PayloadEnvelope dataclass

A payload, with the content type and encoding a consumer reads it by.

Source code in src/py1815/envelope.py
@dataclass
class PayloadEnvelope:
    """A payload, with the content type and encoding a consumer reads it by."""

    JSON = "application/json"

    content_type: str
    data: str
    encoding: str = "utf-8"

    @classmethod
    def from_dict(cls, data: dict[str, Any]) -> PayloadEnvelope:
        """Wrap a dictionary as a JSON payload."""
        return cls(content_type=cls.JSON, data=json.dumps(data), encoding="utf-8")

    def to_dict(self) -> dict[str, Any] | None:
        """Return a JSON payload as a dictionary, or None when it is not one."""
        if self.content_type == self.JSON:
            result = json.loads(self.data)
            if isinstance(result, dict):
                return result
        return None

    def serialize(self) -> dict[str, str]:
        """Return the payload as the envelope carries it."""
        return {"content_type": self.content_type, "data": self.data, "encoding": self.encoding}

    @classmethod
    def deserialize(cls, data: dict[str, str]) -> PayloadEnvelope:
        """Rebuild a payload from :meth:`serialize`."""
        return cls(
            content_type=data["content_type"],
            data=data["data"],
            encoding=data.get("encoding", "utf-8"),
        )
from_dict classmethod
from_dict(data: dict[str, Any]) -> PayloadEnvelope

Wrap a dictionary as a JSON payload.

Source code in src/py1815/envelope.py
@classmethod
def from_dict(cls, data: dict[str, Any]) -> PayloadEnvelope:
    """Wrap a dictionary as a JSON payload."""
    return cls(content_type=cls.JSON, data=json.dumps(data), encoding="utf-8")
to_dict
to_dict() -> dict[str, Any] | None

Return a JSON payload as a dictionary, or None when it is not one.

Source code in src/py1815/envelope.py
def to_dict(self) -> dict[str, Any] | None:
    """Return a JSON payload as a dictionary, or None when it is not one."""
    if self.content_type == self.JSON:
        result = json.loads(self.data)
        if isinstance(result, dict):
            return result
    return None
serialize
serialize() -> dict[str, str]

Return the payload as the envelope carries it.

Source code in src/py1815/envelope.py
def serialize(self) -> dict[str, str]:
    """Return the payload as the envelope carries it."""
    return {"content_type": self.content_type, "data": self.data, "encoding": self.encoding}
deserialize classmethod
deserialize(data: dict[str, str]) -> PayloadEnvelope

Rebuild a payload from :meth:serialize.

Source code in src/py1815/envelope.py
@classmethod
def deserialize(cls, data: dict[str, str]) -> PayloadEnvelope:
    """Rebuild a payload from :meth:`serialize`."""
    return cls(
        content_type=data["content_type"],
        data=data["data"],
        encoding=data.get("encoding", "utf-8"),
    )

NetworkEndpoint dataclass

One end of the connection a message was seen on.

mac is part of the format. A producer that sees frames sets it; this library sees connections, and leaves it unset.

Source code in src/py1815/envelope.py
@dataclass
class NetworkEndpoint:
    """One end of the connection a message was seen on.

    ``mac`` is part of the format. A producer that sees frames sets it; this
    library sees connections, and leaves it unset.
    """

    ip: str
    port: int
    mac: str | None = None

    def __post_init__(self) -> None:
        """Accept a port given as a string, and write a MAC in one spelling.

        Raises:
            ValueError: If ``mac`` is set and is not six hex pairs.
        """
        if isinstance(self.port, str):
            self.port = int(self.port)
        if self.mac is not None:
            if not isinstance(self.mac, str) or not _MAC.match(self.mac):
                raise ValueError(
                    f"mac must be six hex pairs separated by ':' or '-', got {self.mac!r}"
                )
            self.mac = self.mac.lower().replace("-", ":")

    def to_dict(self) -> dict[str, Any]:
        """Return the endpoint as the envelope carries it, without an unset ``mac``."""
        result: dict[str, Any] = {"ip": self.ip, "port": self.port}
        if self.mac is not None:
            result["mac"] = self.mac
        return result

    @classmethod
    def from_dict(cls, data: dict[str, Any]) -> NetworkEndpoint:
        """Rebuild an endpoint from :meth:`to_dict`."""
        return cls(ip=data["ip"], port=data["port"], mac=data.get("mac"))
to_dict
to_dict() -> dict[str, Any]

Return the endpoint as the envelope carries it, without an unset mac.

Source code in src/py1815/envelope.py
def to_dict(self) -> dict[str, Any]:
    """Return the endpoint as the envelope carries it, without an unset ``mac``."""
    result: dict[str, Any] = {"ip": self.ip, "port": self.port}
    if self.mac is not None:
        result["mac"] = self.mac
    return result
from_dict classmethod
from_dict(data: dict[str, Any]) -> NetworkEndpoint

Rebuild an endpoint from :meth:to_dict.

Source code in src/py1815/envelope.py
@classmethod
def from_dict(cls, data: dict[str, Any]) -> NetworkEndpoint:
    """Rebuild an endpoint from :meth:`to_dict`."""
    return cls(ip=data["ip"], port=data["port"], mac=data.get("mac"))

ProtocolMetadata dataclass

Detail about a message beyond its payload.

The format names many fields for other protocols. None of them applies to DNP3, so this class models only extra, the format's free-form dictionary, and keeps any other key it reads in passthrough, so that a message read and written again keeps its shape.

Source code in src/py1815/envelope.py
@dataclass
class ProtocolMetadata:
    """Detail about a message beyond its payload.

    The format names many fields for other protocols. None of them applies to
    DNP3, so this class models only ``extra``, the format's free-form
    dictionary, and keeps any other key it reads in ``passthrough``, so that a
    message read and written again keeps its shape.
    """

    extra: dict[str, Any] = field(default_factory=dict)
    passthrough: dict[str, Any] = field(default_factory=dict)

    def to_dict(self) -> dict[str, Any]:
        """Return the metadata as the envelope carries it, without empty fields."""
        result: dict[str, Any] = dict(self.passthrough)
        if self.extra:
            result["extra"] = self.extra
        return result

    @classmethod
    def from_dict(cls, data: dict[str, Any]) -> ProtocolMetadata:
        """Rebuild metadata from :meth:`to_dict`.

        Raises:
            TypeError: If ``extra`` is present and is not a mapping.
        """
        extra = data.get("extra")
        if extra is not None and not isinstance(extra, dict):
            raise TypeError(f"protocol_data 'extra' must be a mapping, got {type(extra).__name__}")
        passthrough = {key: value for key, value in data.items() if key != "extra"}
        return cls(extra=dict(extra or {}), passthrough=passthrough)
to_dict
to_dict() -> dict[str, Any]

Return the metadata as the envelope carries it, without empty fields.

Source code in src/py1815/envelope.py
def to_dict(self) -> dict[str, Any]:
    """Return the metadata as the envelope carries it, without empty fields."""
    result: dict[str, Any] = dict(self.passthrough)
    if self.extra:
        result["extra"] = self.extra
    return result
from_dict classmethod
from_dict(data: dict[str, Any]) -> ProtocolMetadata

Rebuild metadata from :meth:to_dict.

Raises:

Type Description
TypeError

If extra is present and is not a mapping.

Source code in src/py1815/envelope.py
@classmethod
def from_dict(cls, data: dict[str, Any]) -> ProtocolMetadata:
    """Rebuild metadata from :meth:`to_dict`.

    Raises:
        TypeError: If ``extra`` is present and is not a mapping.
    """
    extra = data.get("extra")
    if extra is not None and not isinstance(extra, dict):
        raise TypeError(f"protocol_data 'extra' must be a mapping, got {type(extra).__name__}")
    passthrough = {key: value for key, value in data.items() if key != "extra"}
    return cls(extra=dict(extra or {}), passthrough=passthrough)

ProtocolMessage dataclass

One captured protocol message, ready to publish.

payload may be given as a dictionary, which is stored as a JSON payload. The hash is computed on construction unless one is given.

Source code in src/py1815/envelope.py
@dataclass
class ProtocolMessage:
    """One captured protocol message, ready to publish.

    ``payload`` may be given as a dictionary, which is stored as a JSON
    payload. The hash is computed on construction unless one is given.
    """

    protocol: Protocol
    direction: WireDirection
    client_id: str
    payload: PayloadEnvelope | dict[str, Any]
    source: NetworkEndpoint
    destination: NetworkEndpoint | None = None
    #: Names the system that produced or relayed the message, so a consumer
    #: that collects from several can tell them apart.
    forwarder_id: str = ""
    protocol_data: ProtocolMetadata = field(default_factory=ProtocolMetadata)
    timestamp: str = field(default_factory=lambda: datetime.now(UTC).isoformat())
    hash: str = ""
    is_valid: bool = True
    validation_error: str | None = None

    def __post_init__(self) -> None:
        """Normalize the fields given as plain values, check them, and compute the hash.

        Raises:
            ValueError: If ``client_id`` is empty, or ``timestamp`` is not an
                ISO 8601 date and time with a UTC offset.
        """
        if isinstance(self.protocol, str):
            self.protocol = Protocol.from_string(self.protocol)
        if isinstance(self.direction, str):
            self.direction = WireDirection(self.direction)
        if isinstance(self.payload, dict):
            self.payload = PayloadEnvelope.from_dict(self.payload)
        if self.timestamp.endswith("Z"):
            self.timestamp = self.timestamp[:-1] + "+00:00"
        _check_timestamp(self.timestamp)
        if not self.client_id or not self.client_id.strip():
            raise ValueError("client_id must be a non-empty string")
        self.forwarder_id = self.forwarder_id.strip()
        if not self.hash:
            self.hash = self._generate_hash()

    @property
    def body(self) -> dict[str, Any] | None:
        """Return the payload as a dictionary, or None when it is not JSON."""
        assert isinstance(self.payload, PayloadEnvelope)
        return self.payload.to_dict()

    def _generate_hash(self) -> str:
        """Return the deduplication key: a UUIDv3 over the identifying fields."""
        assert isinstance(self.payload, PayloadEnvelope)
        unique = f"{self.protocol.value}:{self.client_id}:{self.timestamp}:{self.payload.data}"
        return str(uuid.uuid3(uuid.NAMESPACE_DNS, unique))

    def to_dict(self) -> dict[str, Any]:
        """Return the message in its serialized form. The module docstring states the contract."""
        assert isinstance(self.payload, PayloadEnvelope)
        result: dict[str, Any] = {
            "version": _VERSION,
            "protocol": self.protocol.value,
            "direction": self.direction.value,
            "timestamp": self.timestamp,
            "client_id": self.client_id,
            "forwarder_id": self.forwarder_id,
            "payload": self.payload.serialize(),
            "source": self.source.to_dict(),
            "hash": self.hash,
            "is_valid": self.is_valid,
        }
        if self.destination is not None:
            result["destination"] = self.destination.to_dict()
        protocol_data = self.protocol_data.to_dict()
        if protocol_data:
            result["protocol_data"] = protocol_data
        if self.validation_error:
            result["validation_error"] = self.validation_error
        return result

    def to_json(self) -> str:
        """Return the serialized form as a JSON string."""
        return json.dumps(self.to_dict())

    @classmethod
    def from_dict(cls, data: dict[str, Any]) -> ProtocolMessage:
        """Rebuild a message from its serialized form.

        ``hash`` is taken as given and not computed again: it is the
        producer's key.

        Raises:
            KeyError: If a field the contract always carries is missing.
        """
        payload = data["payload"]
        if isinstance(payload, dict) and {"content_type", "data"} <= payload.keys():
            payload = PayloadEnvelope.deserialize(payload)
        destination = data.get("destination")
        protocol_data = data.get("protocol_data")
        return cls(
            protocol=Protocol.from_string(data["protocol"]),
            direction=WireDirection(data["direction"]),
            client_id=data["client_id"],
            payload=payload,
            source=NetworkEndpoint.from_dict(data["source"]),
            destination=NetworkEndpoint.from_dict(destination) if destination else None,
            forwarder_id=data.get("forwarder_id", ""),
            protocol_data=(
                ProtocolMetadata.from_dict(protocol_data) if protocol_data else ProtocolMetadata()
            ),
            timestamp=data["timestamp"],
            hash=data.get("hash", ""),
            is_valid=data.get("is_valid", True),
            validation_error=data.get("validation_error"),
        )

    @classmethod
    def from_json(cls, raw: str | bytes) -> ProtocolMessage:
        """Rebuild a message from :meth:`to_json`."""
        return cls.from_dict(json.loads(raw))
body property
body: dict[str, Any] | None

Return the payload as a dictionary, or None when it is not JSON.

to_dict
to_dict() -> dict[str, Any]

Return the message in its serialized form. The module docstring states the contract.

Source code in src/py1815/envelope.py
def to_dict(self) -> dict[str, Any]:
    """Return the message in its serialized form. The module docstring states the contract."""
    assert isinstance(self.payload, PayloadEnvelope)
    result: dict[str, Any] = {
        "version": _VERSION,
        "protocol": self.protocol.value,
        "direction": self.direction.value,
        "timestamp": self.timestamp,
        "client_id": self.client_id,
        "forwarder_id": self.forwarder_id,
        "payload": self.payload.serialize(),
        "source": self.source.to_dict(),
        "hash": self.hash,
        "is_valid": self.is_valid,
    }
    if self.destination is not None:
        result["destination"] = self.destination.to_dict()
    protocol_data = self.protocol_data.to_dict()
    if protocol_data:
        result["protocol_data"] = protocol_data
    if self.validation_error:
        result["validation_error"] = self.validation_error
    return result
to_json
to_json() -> str

Return the serialized form as a JSON string.

Source code in src/py1815/envelope.py
def to_json(self) -> str:
    """Return the serialized form as a JSON string."""
    return json.dumps(self.to_dict())
from_dict classmethod
from_dict(data: dict[str, Any]) -> ProtocolMessage

Rebuild a message from its serialized form.

hash is taken as given and not computed again: it is the producer's key.

Raises:

Type Description
KeyError

If a field the contract always carries is missing.

Source code in src/py1815/envelope.py
@classmethod
def from_dict(cls, data: dict[str, Any]) -> ProtocolMessage:
    """Rebuild a message from its serialized form.

    ``hash`` is taken as given and not computed again: it is the
    producer's key.

    Raises:
        KeyError: If a field the contract always carries is missing.
    """
    payload = data["payload"]
    if isinstance(payload, dict) and {"content_type", "data"} <= payload.keys():
        payload = PayloadEnvelope.deserialize(payload)
    destination = data.get("destination")
    protocol_data = data.get("protocol_data")
    return cls(
        protocol=Protocol.from_string(data["protocol"]),
        direction=WireDirection(data["direction"]),
        client_id=data["client_id"],
        payload=payload,
        source=NetworkEndpoint.from_dict(data["source"]),
        destination=NetworkEndpoint.from_dict(destination) if destination else None,
        forwarder_id=data.get("forwarder_id", ""),
        protocol_data=(
            ProtocolMetadata.from_dict(protocol_data) if protocol_data else ProtocolMetadata()
        ),
        timestamp=data["timestamp"],
        hash=data.get("hash", ""),
        is_valid=data.get("is_valid", True),
        validation_error=data.get("validation_error"),
    )
from_json classmethod
from_json(raw: str | bytes) -> ProtocolMessage

Rebuild a message from :meth:to_json.

Source code in src/py1815/envelope.py
@classmethod
def from_json(cls, raw: str | bytes) -> ProtocolMessage:
    """Rebuild a message from :meth:`to_json`."""
    return cls.from_dict(json.loads(raw))

wire_version

wire_version() -> str

Return the value for the envelope's version field.

Consumers accept a bare semantic version or "2.0" and reject anything else, so the installed version is not passed through as it is. A development build carries a suffix such as 0.4.0.dev1, and a source tree that was never installed has no version. The release segment is used when there is one, and "2.0" otherwise.

Source code in src/py1815/envelope.py
def wire_version() -> str:
    """Return the value for the envelope's ``version`` field.

    Consumers accept a bare semantic version or ``"2.0"`` and reject anything
    else, so the installed version is not passed through as it is. A
    development build carries a suffix such as ``0.4.0.dev1``, and a source
    tree that was never installed has no version. The release segment is used
    when there is one, and ``"2.0"`` otherwise.
    """
    try:
        installed = importlib.metadata.version("py1815")
    except importlib.metadata.PackageNotFoundError:
        return WIRE_FORMAT_VERSION
    release = _RELEASE.match(installed)
    return release.group(0) if release else WIRE_FORMAT_VERSION