Skip to content

Observers

Records of the client's exchanges, connections, anomalies, device reads and writes, and audit trail, for an embedding application.

py20305.observers

Structured records of what the client does on the wire, for the host application.

The client logs what happens to its exchanges and connections. A log line is for a person. A host application that keeps a record of every exchange, that passes the client's connections to a monitoring system, or that watches for protocol anomalies needs the same facts as fields. This module defines those records and the type of the callable that receives each one.

  • :class:ExchangeRecord is one HTTP exchange: a request the client sent and the response it received, a request that received no response, or a notification the server POSTed to the client's listener.
  • :class:ConnectionEvent is one thing that happened to a connection: the client connected, failed to connect or lost a connection, or the listener accepted or refused a notification request.
  • :class:ProtocolAnomaly is one body the client could not use, one response with a status it did not expect, or one notification it dropped.
  • :class:DeviceRecord is one read from or write to a device through a connector.
  • :class:AuditRecord is one event lifecycle, loss-of-communications or late dispatch record of the control audit trail.

Every observer is optional and off by default. Attach the protocol observers with :class:Observers (CsipClient.attach_observers), the device observer through :class:~py20305.connectors.device_telemetry.DeviceTelemetryEmitter, and the audit observer with CsipClient.audit.attach_observer.

Stability. These records are a public contract:

  • Every record carries record_version, currently :data:RECORD_VERSION.
  • Fields are only added. A field is removed only after one minor release in which reading it raises a :class:DeprecationWarning, and only in the next major release. record_version is raised when a field is removed or its meaning changes.
  • Records are frozen dataclasses with keyword-only fields. Build them by keyword, and read them by name, so an added field breaks nothing.

An observer is called on the event loop, or for a device record on whatever thread called the connector, and must return quickly. Hand records to :class:QueuedObserver to process them on a background thread. An observer that raises does not affect the exchange: :class:ObserverGuard catches the exception, counts it and logs it.

Endpoint dataclass

An address and port at one end of a connection.

Source code in src/py20305/observers.py
@dataclass(frozen=True)
class Endpoint:
    """An address and port at one end of a connection."""

    host: str
    port: int

    @classmethod
    def of(cls, name: Any) -> Endpoint | None:
        """Return the endpoint of a socket name, or None when the name holds none.

        ``name`` is what ``getpeername`` or ``getsockname`` returns: a tuple
        whose first two items are the address and the port.
        """
        if isinstance(name, tuple) and len(name) >= 2:
            try:
                return cls(str(name[0]), int(name[1]))
            except (TypeError, ValueError):
                return None
        return None

    def __str__(self) -> str:
        host = f"[{self.host}]" if ":" in self.host else self.host
        return f"{host}:{self.port}"
of classmethod
of(name: Any) -> Endpoint | None

Return the endpoint of a socket name, or None when the name holds none.

name is what getpeername or getsockname returns: a tuple whose first two items are the address and the port.

Source code in src/py20305/observers.py
@classmethod
def of(cls, name: Any) -> Endpoint | None:
    """Return the endpoint of a socket name, or None when the name holds none.

    ``name`` is what ``getpeername`` or ``getsockname`` returns: a tuple
    whose first two items are the address and the port.
    """
    if isinstance(name, tuple) and len(name) >= 2:
        try:
            return cls(str(name[0]), int(name[1]))
        except (TypeError, ValueError):
            return None
    return None

ExchangeDirection

Bases: StrEnum

Which end started an exchange.

Source code in src/py20305/observers.py
class ExchangeDirection(StrEnum):
    """Which end started an exchange."""

    #: The client sent the request to the server.
    CLIENT_REQUEST = "client_request"
    #: The server POSTed a notification to the client's listener.
    NOTIFICATION = "notification"

ErrorKind

Bases: StrEnum

Why an exchange received no response, or a connection failed. The values are stable.

Source code in src/py20305/observers.py
class ErrorKind(StrEnum):
    """Why an exchange received no response, or a connection failed. The values are stable."""

    #: The TCP connection could not be made.
    CONNECT = "connect"
    #: The TLS handshake or the certificate check failed.
    TLS = "tls"
    #: No answer arrived in time.
    TIMEOUT = "timeout"
    #: The connection closed before the response was complete.
    DISCONNECTED = "disconnected"
    #: The request URL is not valid.
    INVALID_URL = "invalid_url"
    #: Another failure.
    OTHER = "other"

ExchangeRecord dataclass

One HTTP exchange.

A request the client sent is reported once per attempt, retries included, with the response it received or, when none arrived, with error_kind and error. A notification is reported once, with the response the listener sent back.

Attributes:

Name Type Description
record_version int

The record shape version.

exchange_id str

A unique identifier of this exchange. It correlates the request with its response, and anomalies with the exchange.

direction ExchangeDirection

Which end started the exchange.

method str

The HTTP method.

url str

The full request URL. For a notification, the URL the listener received the request on.

path str

The path and query of the request.

request_headers Headers

The request headers, with the redacted ones replaced.

request_body bytes | None

The request body exactly as sent, or None when the request had no body or body capture is off.

status int | None

The response status, or None when no response arrived.

response_headers Headers

The response headers, with the redacted ones replaced.

response_body bytes | None

The response body after content decoding (aiohttp decompresses gzip and deflate), so it can differ from the bytes on the wire when the server compresses. None when there was no response, it had no body, or body capture is off.

sent_at float

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

received_at float | None

When the response arrived, in seconds since the Unix epoch, or None.

sent_monotonic float

time.monotonic() when the request was sent.

received_monotonic float | None

time.monotonic() when the response arrived, or None.

duration float | None

Seconds from sending the request to receiving the response, or to the failure. None when unknown.

attempt int

The attempt number within one logical request, from 1.

error_kind ErrorKind | None

Why the attempt failed, or None. Set when no response arrived, and when a transport failure such as a truncated body or a reset ended the exchange after the status was received.

error str | None

The failure, in a few words, or None.

local Endpoint | None

This end of the connection, or None when unknown.

remote Endpoint | None

The other end of the connection, or None when unknown.

server_host str

The IEEE 2030.5 server's host name as configured.

tls_version str | None

The negotiated TLS version, or None.

tls_cipher str | None

The negotiated cipher suite, or None.

server_cert_sha256 str | None

The SHA-256 fingerprint of the certificate the peer presented, as lowercase hex: the server's for a client request, the notifying server's client certificate for a notification. None when there was none or it could not be read.

client_lfdi str | None

The LFDI of this client's certificate, or None.

client_sfdi int | None

The SFDI of this client's certificate, or None.

device_lfdi str | None

The LFDI of the device the exchange concerns, when the client can attribute it, or None.

end_device_href str | None

The href of that device's EndDevice, or None.

resource_type str | None

The IEEE 2030.5 element of the body, such as DERControlList, or None.

request_valid bool | None

Whether the request body passed schema validation, or None when it was not checked.

request_validation_error str | None

The first validation error, or None.

response_valid bool | None

Whether the response body passed schema validation, or None when it was not checked.

response_validation_error str | None

The first validation error, or None.

Source code in src/py20305/observers.py
@dataclass(frozen=True, kw_only=True)
class ExchangeRecord:
    """One HTTP exchange.

    A request the client sent is reported once per attempt, retries included,
    with the response it received or, when none arrived, with ``error_kind``
    and ``error``. A notification is reported once, with the response the
    listener sent back.

    Attributes:
        record_version: The record shape version.
        exchange_id: A unique identifier of this exchange. It correlates the
            request with its response, and anomalies with the exchange.
        direction: Which end started the exchange.
        method: The HTTP method.
        url: The full request URL. For a notification, the URL the listener
            received the request on.
        path: The path and query of the request.
        request_headers: The request headers, with the redacted ones replaced.
        request_body: The request body exactly as sent, or None when the
            request had no body or body capture is off.
        status: The response status, or None when no response arrived.
        response_headers: The response headers, with the redacted ones replaced.
        response_body: The response body after content decoding (aiohttp
            decompresses gzip and deflate), so it can differ from the bytes on
            the wire when the server compresses. None when there was no
            response, it had no body, or body capture is off.
        sent_at: When the request was sent, in seconds since the Unix epoch.
        received_at: When the response arrived, in seconds since the Unix
            epoch, or None.
        sent_monotonic: ``time.monotonic()`` when the request was sent.
        received_monotonic: ``time.monotonic()`` when the response arrived, or
            None.
        duration: Seconds from sending the request to receiving the response,
            or to the failure. None when unknown.
        attempt: The attempt number within one logical request, from 1.
        error_kind: Why the attempt failed, or None. Set when no response
            arrived, and when a transport failure such as a truncated body
            or a reset ended the exchange after the status was received.
        error: The failure, in a few words, or None.
        local: This end of the connection, or None when unknown.
        remote: The other end of the connection, or None when unknown.
        server_host: The IEEE 2030.5 server's host name as configured.
        tls_version: The negotiated TLS version, or None.
        tls_cipher: The negotiated cipher suite, or None.
        server_cert_sha256: The SHA-256 fingerprint of the certificate the peer
            presented, as lowercase hex: the server's for a client request,
            the notifying server's client certificate for a notification. None
            when there was none or it could not be read.
        client_lfdi: The LFDI of this client's certificate, or None.
        client_sfdi: The SFDI of this client's certificate, or None.
        device_lfdi: The LFDI of the device the exchange concerns, when the
            client can attribute it, or None.
        end_device_href: The href of that device's EndDevice, or None.
        resource_type: The IEEE 2030.5 element of the body, such as
            ``DERControlList``, or None.
        request_valid: Whether the request body passed schema validation, or
            None when it was not checked.
        request_validation_error: The first validation error, or None.
        response_valid: Whether the response body passed schema validation,
            or None when it was not checked.
        response_validation_error: The first validation error, or None.
    """

    record_version: int = RECORD_VERSION
    exchange_id: str
    direction: ExchangeDirection
    method: str
    url: str
    path: str
    request_headers: Headers = ()
    request_body: bytes | None = None
    status: int | None = None
    response_headers: Headers = ()
    response_body: bytes | None = None
    sent_at: float
    received_at: float | None = None
    sent_monotonic: float
    received_monotonic: float | None = None
    duration: float | None = None
    attempt: int = 1
    error_kind: ErrorKind | None = None
    error: str | None = None
    local: Endpoint | None = None
    remote: Endpoint | None = None
    server_host: str = ""
    tls_version: str | None = None
    tls_cipher: str | None = None
    server_cert_sha256: str | None = None
    client_lfdi: str | None = None
    client_sfdi: int | None = None
    device_lfdi: str | None = None
    end_device_href: str | None = None
    resource_type: str | None = None
    request_valid: bool | None = None
    request_validation_error: str | None = None
    response_valid: bool | None = None
    response_validation_error: str | None = None

ConnectionRole

Bases: StrEnum

Which part of the client reported a connection event.

Source code in src/py20305/observers.py
class ConnectionRole(StrEnum):
    """Which part of the client reported a connection event."""

    #: The client's connection to the IEEE 2030.5 server.
    CLIENT = "client"
    #: The notification listener, which the server connects to.
    LISTENER = "listener"

ConnectionDirection

Bases: StrEnum

Which end opened the connection, seen from the client.

Source code in src/py20305/observers.py
class ConnectionDirection(StrEnum):
    """Which end opened the connection, seen from the client."""

    #: The remote end opened it. Every connection the listener reports.
    INBOUND = "inbound"
    #: The client opened it. Every connection the client reports.
    OUTBOUND = "outbound"

ConnectionTransport

Bases: StrEnum

What the connection is carried over.

Source code in src/py20305/observers.py
class ConnectionTransport(StrEnum):
    """What the connection is carried over."""

    TCP = "tcp"
    TLS = "tls"

ConnectionOutcome

Bases: StrEnum

What happened to a connection. The values are stable.

Source code in src/py20305/observers.py
class ConnectionOutcome(StrEnum):
    """What happened to a connection. The values are stable."""

    #: The client made the connection, and the TLS handshake and the IEEE
    #: 2030.5 certificate profile check passed.
    CONNECTED = "connected"
    #: The client could not make the connection: the TCP connection, the TLS
    #: handshake or the certificate check failed.
    FAILED = "failed"
    #: The client lost a connection while an exchange was in progress.
    LOST = "lost"
    #: The listener received a notification request and admitted it.
    ACCEPTED = "accepted"
    #: The listener received a notification request and refused it.
    REFUSED = "refused"

ConnectionEvent dataclass

One thing that happened to one connection.

Attributes:

Name Type Description
record_version int

The record shape version.

role ConnectionRole

The part of the client that reports the event.

direction ConnectionDirection

Which end opened the connection.

outcome ConnectionOutcome

What happened.

transport ConnectionTransport

TCP, or TLS over TCP.

remote Endpoint | None

The other end. For a failed attempt, the host and port tried.

local Endpoint | None

This end, or None when no socket was made.

server_host str

The IEEE 2030.5 server's host name as configured, for the client role. Empty for the listener.

reason str

Why, in a few words, for every outcome except CONNECTED and ACCEPTED. It holds no secret.

error_kind ErrorKind | None

The kind of failure, for FAILED and LOST.

status int | None

The HTTP status the listener answered a refused request with.

tls_version str | None

The negotiated TLS version, or None.

tls_cipher str | None

The negotiated cipher suite, or None.

peer_cert_sha256 str | None

The SHA-256 fingerprint of the certificate the peer presented, as lowercase hex, or None.

timestamp float

When the event was reported, in seconds since the Unix epoch.

Source code in src/py20305/observers.py
@dataclass(frozen=True, kw_only=True)
class ConnectionEvent:
    """One thing that happened to one connection.

    Attributes:
        record_version: The record shape version.
        role: The part of the client that reports the event.
        direction: Which end opened the connection.
        outcome: What happened.
        transport: TCP, or TLS over TCP.
        remote: The other end. For a failed attempt, the host and port tried.
        local: This end, or None when no socket was made.
        server_host: The IEEE 2030.5 server's host name as configured, for the
            client role. Empty for the listener.
        reason: Why, in a few words, for every outcome except ``CONNECTED`` and
            ``ACCEPTED``. It holds no secret.
        error_kind: The kind of failure, for ``FAILED`` and ``LOST``.
        status: The HTTP status the listener answered a refused request with.
        tls_version: The negotiated TLS version, or None.
        tls_cipher: The negotiated cipher suite, or None.
        peer_cert_sha256: The SHA-256 fingerprint of the certificate the peer
            presented, as lowercase hex, or None.
        timestamp: When the event was reported, in seconds since the Unix
            epoch.
    """

    record_version: int = RECORD_VERSION
    role: ConnectionRole
    direction: ConnectionDirection
    outcome: ConnectionOutcome
    transport: ConnectionTransport
    remote: Endpoint | None
    local: Endpoint | None = None
    server_host: str = ""
    reason: str = ""
    error_kind: ErrorKind | None = None
    status: int | None = None
    tls_version: str | None = None
    tls_cipher: str | None = None
    peer_cert_sha256: str | None = None
    timestamp: float = field(default_factory=time.time)

AnomalyCode

Bases: StrEnum

What the client could not use or did not expect. The values are stable.

Source code in src/py20305/observers.py
class AnomalyCode(StrEnum):
    """What the client could not use or did not expect. The values are stable."""

    #: A body that is not well-formed XML or not the element expected.
    UNPARSEABLE_BODY = "unparseable_body"
    #: A body that failed schema validation. It was still used.
    INVALID_BODY = "invalid_body"
    #: A response status the client did not expect for the request.
    UNEXPECTED_STATUS = "unexpected_status"
    #: A notification request whose body could not be read.
    UNREADABLE_NOTIFICATION = "unreadable_notification"
    #: A notification the listener refused: no client certificate, or a
    #: body that failed its checks.
    REJECTED_NOTIFICATION = "rejected_notification"
    #: A notification the listener accepted and did not act on, while a
    #: loss-of-communications simulation runs.
    DROPPED_NOTIFICATION = "dropped_notification"

AnomalySeverity

Bases: StrEnum

How much an anomaly says about the peer, from least to most.

Source code in src/py20305/observers.py
class AnomalySeverity(StrEnum):
    """How much an anomaly says about the peer, from least to most."""

    #: Expected in normal operation, and recorded for completeness.
    INFO = "info"
    #: Explained by a server's ordinary behavior as easily as by a fault.
    LOW = "low"
    #: A malformed body or an unexpected answer: a defective or
    #: misconfigured peer, or one probing the client.
    MEDIUM = "medium"

ProtocolAnomaly dataclass

One body the client could not use, unexpected status, or dropped notification.

Attributes:

Name Type Description
record_version int

The record shape version.

code AnomalyCode

What happened.

severity AnomalySeverity

How much it says about the peer. Always SEVERITY[code].

message str

What happened, in a few words.

exchange_id str | None

The :class:ExchangeRecord the anomaly belongs to, or None when no exchange record was made.

method str | None

The HTTP method of the exchange, or None.

path str | None

The path of the exchange, or None.

status int | None

The response status, or None.

peer Endpoint | None

The other end of the connection, when known.

timestamp float

When the anomaly was reported, in seconds since the Unix epoch.

Source code in src/py20305/observers.py
@dataclass(frozen=True, kw_only=True)
class ProtocolAnomaly:
    """One body the client could not use, unexpected status, or dropped notification.

    Attributes:
        record_version: The record shape version.
        code: What happened.
        severity: How much it says about the peer. Always ``SEVERITY[code]``.
        message: What happened, in a few words.
        exchange_id: The :class:`ExchangeRecord` the anomaly belongs to, or
            None when no exchange record was made.
        method: The HTTP method of the exchange, or None.
        path: The path of the exchange, or None.
        status: The response status, or None.
        peer: The other end of the connection, when known.
        timestamp: When the anomaly was reported, in seconds since the Unix
            epoch.
    """

    record_version: int = RECORD_VERSION
    code: AnomalyCode
    severity: AnomalySeverity
    message: str
    exchange_id: str | None = None
    method: str | None = None
    path: str | None = None
    status: int | None = None
    peer: Endpoint | None = None
    timestamp: float = field(default_factory=time.time)

    @classmethod
    def of(cls, code: AnomalyCode, message: str, **fields: Any) -> ProtocolAnomaly:
        """Return an anomaly with the severity its code is reported with."""
        return cls(code=code, severity=SEVERITY[code], message=message, **fields)
of classmethod
of(code: AnomalyCode, message: str, **fields: Any) -> ProtocolAnomaly

Return an anomaly with the severity its code is reported with.

Source code in src/py20305/observers.py
@classmethod
def of(cls, code: AnomalyCode, message: str, **fields: Any) -> ProtocolAnomaly:
    """Return an anomaly with the severity its code is reported with."""
    return cls(code=code, severity=SEVERITY[code], message=message, **fields)

DeviceOperation

Bases: StrEnum

What a device record reports.

Source code in src/py20305/observers.py
class DeviceOperation(StrEnum):
    """What a device record reports."""

    READ = "read"
    WRITE = "write"

DeviceOutcome

Bases: StrEnum

How a device read or write ended.

Source code in src/py20305/observers.py
class DeviceOutcome(StrEnum):
    """How a device read or write ended."""

    #: The read or write completed.
    OK = "ok"
    #: The connector raised.
    FAILED = "failed"
    #: The write was not sent, because the command authority refused it.
    REFUSED = "refused"

DeviceRecord dataclass

One read from or write to a device through its connector.

Attributes:

Name Type Description
record_version int

The record shape version.

operation DeviceOperation

Read or write.

device str

The identifier the client knows the device by.

lfdi str | None

The device's LFDI, when known.

resource str

For a read, what was read: monitoring, nameplate, configuration, status or availability. For a write, the control written, in the same vocabulary the management API uses.

values Mapping[str, Any]

For a read, the values read. For a write, the parameters written.

outcome DeviceOutcome

How it ended.

error str | None

The failure, cut to :data:MAX_ERROR_CHARS, or None.

error_type str | None

The failure's exception class name, or None.

origin str | None

Who issued a write, such as ieee2030_5, or None.

applied_mrid str | None

The mRID of the control written, as uppercase hex.

cause_mrid str | None

The mRID of the event whose lifecycle produced the write, as uppercase hex.

protocol str

What the connector speaks to the device, as the connector declares it (modbus, generic, ...).

endpoint str | None

The connector's device address, such as host:port or rtu:/dev/ttyUSB0, or None.

timestamp float

When the record was made, in seconds since the Unix epoch.

Source code in src/py20305/observers.py
@dataclass(frozen=True, kw_only=True)
class DeviceRecord:
    """One read from or write to a device through its connector.

    Attributes:
        record_version: The record shape version.
        operation: Read or write.
        device: The identifier the client knows the device by.
        lfdi: The device's LFDI, when known.
        resource: For a read, what was read: ``monitoring``, ``nameplate``,
            ``configuration``, ``status`` or ``availability``. For a write,
            the control written, in the same vocabulary the management API
            uses.
        values: For a read, the values read. For a write, the parameters
            written.
        outcome: How it ended.
        error: The failure, cut to :data:`MAX_ERROR_CHARS`, or None.
        error_type: The failure's exception class name, or None.
        origin: Who issued a write, such as ``ieee2030_5``, or None.
        applied_mrid: The mRID of the control written, as uppercase hex.
        cause_mrid: The mRID of the event whose lifecycle produced the write,
            as uppercase hex.
        protocol: What the connector speaks to the device, as the connector
            declares it (``modbus``, ``generic``, ...).
        endpoint: The connector's device address, such as ``host:port`` or
            ``rtu:/dev/ttyUSB0``, or None.
        timestamp: When the record was made, in seconds since the Unix epoch.
    """

    record_version: int = RECORD_VERSION
    operation: DeviceOperation
    device: str
    lfdi: str | None = None
    resource: str
    values: Mapping[str, Any] = field(default_factory=lambda: MappingProxyType({}))
    outcome: DeviceOutcome = DeviceOutcome.OK
    error: str | None = None
    error_type: str | None = None
    origin: str | None = None
    applied_mrid: str | None = None
    cause_mrid: str | None = None
    protocol: str = "generic"
    endpoint: str | None = None
    timestamp: float = field(default_factory=time.time)

AuditRecord dataclass

One record of the control audit trail.

Attributes:

Name Type Description
record_version int

The record shape version.

kind str

der_event, comms_loss or late_dispatch.

data Mapping[str, Any]

The record's fields, the same document the operations history stores. See the audit trail section of the observers guide.

Source code in src/py20305/observers.py
@dataclass(frozen=True, kw_only=True)
class AuditRecord:
    """One record of the control audit trail.

    Attributes:
        record_version: The record shape version.
        kind: ``der_event``, ``comms_loss`` or ``late_dispatch``.
        data: The record's fields, the same document the operations history
            stores. See the audit trail section of the observers guide.
    """

    record_version: int = RECORD_VERSION
    kind: str
    data: Mapping[str, Any]

Observers dataclass

The protocol observers of one client, and how exchanges are captured.

Attributes:

Name Type Description
exchange ExchangeObserver | None

Receives each :class:ExchangeRecord, or None.

connection ConnectionObserver | None

Receives each :class:ConnectionEvent, or None.

anomaly AnomalyObserver | None

Receives each :class:ProtocolAnomaly, or None.

capture_bodies bool

Put request and response bodies in exchange records. Off, request_body and response_body are None.

redacted_headers frozenset[str]

Header names whose values are replaced by :data:REDACTED in exchange records. Compared without regard to case.

validate bool

Validate each body against the schemas and report the result in the exchange record. Runs only with an exchange or anomaly observer attached.

schema_dir Path | None

Directory holding the schema files to validate with; the packaged schemas fill in any it lacks.

Source code in src/py20305/observers.py
@dataclass(frozen=True, kw_only=True)
class Observers:
    """The protocol observers of one client, and how exchanges are captured.

    Attributes:
        exchange: Receives each :class:`ExchangeRecord`, or None.
        connection: Receives each :class:`ConnectionEvent`, or None.
        anomaly: Receives each :class:`ProtocolAnomaly`, or None.
        capture_bodies: Put request and response bodies in exchange records.
            Off, ``request_body`` and ``response_body`` are None.
        redacted_headers: Header names whose values are replaced by
            :data:`REDACTED` in exchange records. Compared without regard to
            case.
        validate: Validate each body against the schemas and report the
            result in the exchange record. Runs only with an exchange or
            anomaly observer attached.
        schema_dir: Directory holding the schema files to validate with; the
            packaged schemas fill in any it lacks.
    """

    exchange: ExchangeObserver | None = None
    connection: ConnectionObserver | None = None
    anomaly: AnomalyObserver | None = None
    capture_bodies: bool = True
    redacted_headers: frozenset[str] = DEFAULT_REDACTED_HEADERS
    validate: bool = True
    schema_dir: Path | None = None

    @property
    def any(self) -> bool:
        """Whether any observer is attached."""
        return any(o is not None for o in (self.exchange, self.connection, self.anomaly))
any property
any: bool

Whether any observer is attached.

ObserverGuard

Call an observer and keep its exceptions from reaching the caller.

Each exception is counted in :attr:failures. The first exception of an observer is logged with its traceback. Later exceptions of the same observer are logged at DEBUG, so an observer that fails on every record does not fill the log. A different observer starts over.

Source code in src/py20305/observers.py
class ObserverGuard:
    """Call an observer and keep its exceptions from reaching the caller.

    Each exception is counted in :attr:`failures`. The first exception of an
    observer is logged with its traceback. Later exceptions of the same
    observer are logged at DEBUG, so an observer that fails on every record
    does not fill the log. A different observer starts over.
    """

    def __init__(self, what: str) -> None:
        """Make a guard for the observer named ``what`` in log records."""
        self._what = what
        self._failed: object | None = None
        #: How many times the guarded observers raised.
        self.failures = 0

    def deliver(self, observer: Callable[[_Record], None] | None, record: _Record) -> None:
        """Call ``observer`` with ``record``, unless there is no observer."""
        if observer is None:
            return
        try:
            observer(record)
        except Exception:  # pylint: disable=broad-exception-caught
            # The observer belongs to the host application. Its failure says
            # nothing about the exchange, which goes on.
            self.failures += 1
            if self._failed is observer:
                logger.debug("the %s failed again", self._what, exc_info=True)
            else:
                self._failed = observer
                logger.exception("the %s failed; further failures are logged at DEBUG", self._what)
deliver
deliver(observer: Callable[[_Record], None] | None, record: _Record) -> None

Call observer with record, unless there is no observer.

Source code in src/py20305/observers.py
def deliver(self, observer: Callable[[_Record], None] | None, record: _Record) -> None:
    """Call ``observer`` with ``record``, unless there is no observer."""
    if observer is None:
        return
    try:
        observer(record)
    except Exception:  # pylint: disable=broad-exception-caught
        # The observer belongs to the host application. Its failure says
        # nothing about the exchange, which goes on.
        self.failures += 1
        if self._failed is observer:
            logger.debug("the %s failed again", self._what, exc_info=True)
        else:
            self._failed = observer
            logger.exception("the %s failed; further failures are logged at DEBUG", self._what)

QueuedObserver

Bases: Generic[_Record]

Hand records to another observer on a background thread, through a bounded queue.

Calling an instance puts the record on the queue and returns at once. A record that arrives while the queue is full is dropped and counted in :attr:dropped. The target runs on one daemon thread, in the order the records arrived; its exceptions are counted in :attr:failures and never reach the caller.

Call :meth:close to deliver what is queued and stop the thread.

Source code in src/py20305/observers.py
class QueuedObserver(Generic[_Record]):
    """Hand records to another observer on a background thread, through a bounded queue.

    Calling an instance puts the record on the queue and returns at once. A
    record that arrives while the queue is full is dropped and counted in
    :attr:`dropped`. The target runs on one daemon thread, in the order the
    records arrived; its exceptions are counted in :attr:`failures` and never
    reach the caller.

    Call :meth:`close` to deliver what is queued and stop the thread.
    """

    _STOP = object()
    #: Seconds between checks for room in a full queue while closing.
    _CLOSE_POLL = 0.05

    def __init__(
        self, target: Callable[[_Record], None], *, maxsize: int = 10_000, name: str = "observer"
    ) -> None:
        """Start the thread that delivers to ``target``.

        Args:
            target: Receives each record.
            maxsize: Most records held; at least 1.
            name: Names the thread and the log records.
        """
        if maxsize < 1:
            raise ValueError("maxsize must be at least 1")
        self._target = target
        self._queue: queue.Queue[object] = queue.Queue(maxsize=maxsize)
        self._guard = ObserverGuard(name)
        # Guards ``_closed``, ``dropped`` and the check-and-put in ``__call__``,
        # so a record offered while the observer closes is queued or counted.
        self._lock = threading.Lock()
        self._closed = False
        # Set when close() gave up waiting: the thread then stops after the
        # record it is delivering and counts the rest as dropped.
        self._abandon = threading.Event()
        #: How many records were dropped because the queue was full, closed or abandoned.
        self.dropped = 0
        self._thread = threading.Thread(target=self._run, name=name, daemon=True)
        self._thread.start()

    @property
    def failures(self) -> int:
        """How many times the target raised."""
        return self._guard.failures

    @property
    def pending(self) -> int:
        """How many records wait to be delivered."""
        return self._queue.qsize()

    def __call__(self, record: _Record) -> None:
        """Queue ``record`` for delivery, or drop and count it when the queue is full."""
        with self._lock:
            if self._closed:
                self.dropped += 1
                return
            try:
                self._queue.put_nowait(record)
            except queue.Full:
                self.dropped += 1

    def close(self, timeout: float | None = 5.0) -> None:
        """Deliver the queued records, then stop the thread.

        Records that arrive after this call are dropped and counted. Waits up
        to ``timeout`` seconds in total for the thread; None waits until it
        finishes. When the wait ends with the thread still busy, for example
        because the target is stuck, the thread stops after the record it is
        delivering and counts the records still queued in :attr:`dropped`.
        """
        with self._lock:
            if self._closed:
                return
            self._closed = True
        deadline = None if timeout is None else time.monotonic() + timeout
        if not self._put_stop(deadline):
            self._abandon.set()
            return
        self._thread.join(None if deadline is None else max(0.0, deadline - time.monotonic()))
        if self._thread.is_alive():
            self._abandon.set()

    def _put_stop(self, deadline: float | None) -> bool:
        """Queue the stop marker, waiting for room until ``deadline``; return whether it fit."""
        while self._thread.is_alive():
            wait = self._CLOSE_POLL
            if deadline is not None:
                wait = min(wait, deadline - time.monotonic())
                if wait <= 0:
                    return False
            try:
                self._queue.put(self._STOP, timeout=wait)
            except queue.Full:
                continue
            return True
        return True

    def _run(self) -> None:
        while not self._abandon.is_set():
            record = self._queue.get()
            if record is self._STOP:
                return
            self._guard.deliver(self._target, record)  # type: ignore[arg-type]
        self._discard_queued()

    def _discard_queued(self) -> None:
        """Remove every queued record and count it as dropped."""
        while True:
            try:
                record = self._queue.get_nowait()
            except queue.Empty:
                return
            if record is not self._STOP:
                with self._lock:
                    self.dropped += 1
failures property
failures: int

How many times the target raised.

pending property
pending: int

How many records wait to be delivered.

close
close(timeout: float | None = 5.0) -> None

Deliver the queued records, then stop the thread.

Records that arrive after this call are dropped and counted. Waits up to timeout seconds in total for the thread; None waits until it finishes. When the wait ends with the thread still busy, for example because the target is stuck, the thread stops after the record it is delivering and counts the records still queued in :attr:dropped.

Source code in src/py20305/observers.py
def close(self, timeout: float | None = 5.0) -> None:
    """Deliver the queued records, then stop the thread.

    Records that arrive after this call are dropped and counted. Waits up
    to ``timeout`` seconds in total for the thread; None waits until it
    finishes. When the wait ends with the thread still busy, for example
    because the target is stuck, the thread stops after the record it is
    delivering and counts the records still queued in :attr:`dropped`.
    """
    with self._lock:
        if self._closed:
            return
        self._closed = True
    deadline = None if timeout is None else time.monotonic() + timeout
    if not self._put_stop(deadline):
        self._abandon.set()
        return
    self._thread.join(None if deadline is None else max(0.0, deadline - time.monotonic()))
    if self._thread.is_alive():
        self._abandon.set()

redact_headers

redact_headers(headers: Iterable[tuple[str, str]], redacted: Iterable[str] = DEFAULT_REDACTED_HEADERS) -> Headers

Return headers with the value of each header named in redacted replaced.

Names are compared without regard to case. Order and repeated headers are kept.

Source code in src/py20305/observers.py
def redact_headers(
    headers: Iterable[tuple[str, str]], redacted: Iterable[str] = DEFAULT_REDACTED_HEADERS
) -> Headers:
    """Return ``headers`` with the value of each header named in ``redacted`` replaced.

    Names are compared without regard to case. Order and repeated headers are
    kept.
    """
    names = {name.lower() for name in redacted}
    return tuple(
        (str(name), REDACTED if str(name).lower() in names else str(value))
        for name, value in headers
    )

py20305.connectors.device_telemetry

Southbound device telemetry: what this client reads from and writes to a DER.

The exchange observer reports the client's IEEE 2030.5 traffic with the server. The southbound half, the traffic between this client and the devices it controls through connectors, is reported here, so a monitoring system sees the commands the client issued to the equipment beside the ones it received.

A curtailment that arrives over IEEE 2030.5 and a curtailment that reaches the inverter are different facts, and the gap between them is where a compromised or misbehaving client shows up.

:class:DeviceTelemetryEmitter hands one :class:~py20305.observers.DeviceRecord per read and per write to a device observer. The reading source, the telemetry managers and the control dispatcher share one emitter.

DeviceTelemetryEmitter

Reports southbound device reads and writes to a device observer.

One instance per client, shared by the reading source and the control dispatcher, the two places every southbound read and write passes through.

Nothing here may raise into the data path: the observer's exceptions are caught and counted, and a record that cannot be built is counted in :attr:emit_failures.

Source code in src/py20305/connectors/device_telemetry.py
class DeviceTelemetryEmitter:
    """Reports southbound device reads and writes to a device observer.

    One instance per client, shared by the reading source and the control
    dispatcher, the two places every southbound read and write passes through.

    Nothing here may raise into the data path: the observer's exceptions are
    caught and counted, and a record that cannot be built is counted in
    :attr:`emit_failures`.
    """

    def __init__(self, observer: DeviceObserver | None = None) -> None:
        """Create an emitter that reports to ``observer``; None reports nothing."""
        self._observer = observer
        self._guard = ObserverGuard("device observer")
        #: Records that could not be built.
        self.emit_failures = 0

    @property
    def enabled(self) -> bool:
        """Whether device reads are reported."""
        return self._observer is not None

    @property
    def writes_enabled(self) -> bool:
        """Whether device writes are reported."""
        return self._observer is not None

    @property
    def observer_failures(self) -> int:
        """How many times the device observer raised."""
        return self._guard.failures

    def attach_observer(self, observer: DeviceObserver | None) -> None:
        """Report to ``observer`` from now on, or stop with None."""
        self._observer = observer

    def record_read(
        self,
        device: str,
        values: dict[str, Any],
        *,
        connector: object = None,
        lfdi: str | None = None,
        resource: str = "monitoring",
    ) -> None:
        """Report one set of values read from a device.

        Args:
            device: Device identifier the client knows it by.
            values: The values read, as the connector returned them.
            connector: The connector the read went through.
            lfdi: The device's LFDI when one is known.
            resource: What was read: ``monitoring``, ``nameplate``,
                ``configuration``, ``status`` or ``availability``.
        """
        if not values or self._observer is None:
            # An empty record would be indistinguishable from a device
            # reporting all zero, which is a real reading.
            return
        self._emit(
            operation=DeviceOperation.READ,
            device=device,
            resource=resource,
            values=values,
            connector=connector,
            lfdi=lfdi,
        )

    def record_write(
        self,
        device: str,
        control: str,
        params: dict[str, Any],
        *,
        connector: object = None,
        lfdi: str | None = None,
        error: str | None = None,
        error_type: str | None = None,
        origin: str | None = None,
        applied_mrid: bytes | None = None,
        cause_mrid: bytes | None = None,
    ) -> None:
        """Report one control written to a device, or refused or failed.

        Args:
            device: Device identifier the client knows it by.
            control: Control name, in the same vocabulary the management API
                uses.
            params: The parameters written.
            connector: The connector the write went through.
            lfdi: The device's LFDI when one is known.
            error: The failure reason, when the write was refused or failed.
            error_type: The failure's exception class name, or ``refused``
                when the command authority refused the write.
            origin: Who issued the write, e.g. ``"ieee2030_5"``.
            applied_mrid: The mRID of the control written, when it was a
                DERControl or DefaultDERControl.
            cause_mrid: The event whose lifecycle produced the write: the event
                itself on activation, the event that ended on a fallback.
        """
        if self._observer is None:
            return
        if error is None:
            outcome = DeviceOutcome.OK
        elif error_type == "refused":
            outcome = DeviceOutcome.REFUSED
        else:
            outcome = DeviceOutcome.FAILED
        self._emit(
            operation=DeviceOperation.WRITE,
            device=device,
            resource=control,
            values=params,
            connector=connector,
            lfdi=lfdi,
            outcome=outcome,
            error=_bound_error(error),
            error_type=error_type,
            origin=str(origin) if origin is not None else None,
            applied_mrid=mrid_hex(applied_mrid),
            cause_mrid=mrid_hex(cause_mrid),
        )

    def _emit(
        self,
        *,
        operation: DeviceOperation,
        device: str,
        resource: str,
        values: dict[str, Any],
        connector: object,
        lfdi: str | None,
        **fields: Any,
    ) -> None:
        try:
            record = DeviceRecord(
                operation=operation,
                device=device,
                lfdi=lfdi,
                resource=resource,
                values=MappingProxyType(dict(values)),
                protocol=device_protocol(connector),
                endpoint=device_endpoint(connector),
                **fields,
            )
        except Exception:  # pylint: disable=broad-exception-caught
            self.emit_failures += 1
            log = logger.warning if self.emit_failures == 1 else logger.debug
            log("Could not build a device record", exc_info=True)
            return
        self._guard.deliver(self._observer, record)
enabled property
enabled: bool

Whether device reads are reported.

writes_enabled property
writes_enabled: bool

Whether device writes are reported.

observer_failures property
observer_failures: int

How many times the device observer raised.

attach_observer
attach_observer(observer: DeviceObserver | None) -> None

Report to observer from now on, or stop with None.

Source code in src/py20305/connectors/device_telemetry.py
def attach_observer(self, observer: DeviceObserver | None) -> None:
    """Report to ``observer`` from now on, or stop with None."""
    self._observer = observer
record_read
record_read(device: str, values: dict[str, Any], *, connector: object = None, lfdi: str | None = None, resource: str = 'monitoring') -> None

Report one set of values read from a device.

Parameters:

Name Type Description Default
device str

Device identifier the client knows it by.

required
values dict[str, Any]

The values read, as the connector returned them.

required
connector object

The connector the read went through.

None
lfdi str | None

The device's LFDI when one is known.

None
resource str

What was read: monitoring, nameplate, configuration, status or availability.

'monitoring'
Source code in src/py20305/connectors/device_telemetry.py
def record_read(
    self,
    device: str,
    values: dict[str, Any],
    *,
    connector: object = None,
    lfdi: str | None = None,
    resource: str = "monitoring",
) -> None:
    """Report one set of values read from a device.

    Args:
        device: Device identifier the client knows it by.
        values: The values read, as the connector returned them.
        connector: The connector the read went through.
        lfdi: The device's LFDI when one is known.
        resource: What was read: ``monitoring``, ``nameplate``,
            ``configuration``, ``status`` or ``availability``.
    """
    if not values or self._observer is None:
        # An empty record would be indistinguishable from a device
        # reporting all zero, which is a real reading.
        return
    self._emit(
        operation=DeviceOperation.READ,
        device=device,
        resource=resource,
        values=values,
        connector=connector,
        lfdi=lfdi,
    )
record_write
record_write(device: str, control: str, params: dict[str, Any], *, connector: object = None, lfdi: str | None = None, error: str | None = None, error_type: str | None = None, origin: str | None = None, applied_mrid: bytes | None = None, cause_mrid: bytes | None = None) -> None

Report one control written to a device, or refused or failed.

Parameters:

Name Type Description Default
device str

Device identifier the client knows it by.

required
control str

Control name, in the same vocabulary the management API uses.

required
params dict[str, Any]

The parameters written.

required
connector object

The connector the write went through.

None
lfdi str | None

The device's LFDI when one is known.

None
error str | None

The failure reason, when the write was refused or failed.

None
error_type str | None

The failure's exception class name, or refused when the command authority refused the write.

None
origin str | None

Who issued the write, e.g. "ieee2030_5".

None
applied_mrid bytes | None

The mRID of the control written, when it was a DERControl or DefaultDERControl.

None
cause_mrid bytes | None

The event whose lifecycle produced the write: the event itself on activation, the event that ended on a fallback.

None
Source code in src/py20305/connectors/device_telemetry.py
def record_write(
    self,
    device: str,
    control: str,
    params: dict[str, Any],
    *,
    connector: object = None,
    lfdi: str | None = None,
    error: str | None = None,
    error_type: str | None = None,
    origin: str | None = None,
    applied_mrid: bytes | None = None,
    cause_mrid: bytes | None = None,
) -> None:
    """Report one control written to a device, or refused or failed.

    Args:
        device: Device identifier the client knows it by.
        control: Control name, in the same vocabulary the management API
            uses.
        params: The parameters written.
        connector: The connector the write went through.
        lfdi: The device's LFDI when one is known.
        error: The failure reason, when the write was refused or failed.
        error_type: The failure's exception class name, or ``refused``
            when the command authority refused the write.
        origin: Who issued the write, e.g. ``"ieee2030_5"``.
        applied_mrid: The mRID of the control written, when it was a
            DERControl or DefaultDERControl.
        cause_mrid: The event whose lifecycle produced the write: the event
            itself on activation, the event that ended on a fallback.
    """
    if self._observer is None:
        return
    if error is None:
        outcome = DeviceOutcome.OK
    elif error_type == "refused":
        outcome = DeviceOutcome.REFUSED
    else:
        outcome = DeviceOutcome.FAILED
    self._emit(
        operation=DeviceOperation.WRITE,
        device=device,
        resource=control,
        values=params,
        connector=connector,
        lfdi=lfdi,
        outcome=outcome,
        error=_bound_error(error),
        error_type=error_type,
        origin=str(origin) if origin is not None else None,
        applied_mrid=mrid_hex(applied_mrid),
        cause_mrid=mrid_hex(cause_mrid),
    )

mrid_hex

mrid_hex(mrid: bytes | None) -> str | None

Return an mRID as uppercase hex, the form the mRID element takes on the wire.

Source code in src/py20305/connectors/device_telemetry.py
def mrid_hex(mrid: bytes | None) -> str | None:
    """Return an mRID as uppercase hex, the form the ``mRID`` element takes on the wire."""
    return mrid.hex().upper() if mrid is not None else None

device_protocol

device_protocol(connector: object) -> str

Return what the connector speaks, as it declares it in telemetry_protocol.

A connector that declares nothing usable is reported as generic.

Source code in src/py20305/connectors/device_telemetry.py
def device_protocol(connector: object) -> str:
    """Return what the connector speaks, as it declares it in ``telemetry_protocol``.

    A connector that declares nothing usable is reported as ``generic``.
    """
    declared = getattr(connector, "telemetry_protocol", None)
    if isinstance(declared, str) and declared:
        return declared.lower()
    return "generic"

device_endpoint

device_endpoint(connector: object) -> str | None

Return the connector's device address, such as host:port, or None.

Read defensively: a custom connector may expose nothing at all.

Source code in src/py20305/connectors/device_telemetry.py
def device_endpoint(connector: object) -> str | None:
    """Return the connector's device address, such as ``host:port``, or None.

    Read defensively: a custom connector may expose nothing at all.
    """
    endpoint_id = getattr(connector, "endpoint_id", None)
    return endpoint_id if isinstance(endpoint_id, str) and endpoint_id else None

py20305.audit

The control audit trail: event lifecycle and loss-of-communications records.

A utility program asks of a control client what it did with each control it was sent: when an event was scheduled, when it went active and on which devices, how it ended, and when the client stopped acting on the server because the server went quiet. The exchange records say what the server said, not what this client decided. These records are the decisions.

Each record is a flat document. It is kept in the operations history when one is attached, and handed to the audit observer as an :class:~py20305.observers.AuditRecord when one is attached. Either, both or neither may be attached.

Every record carries boot_id and seq, one counter per client, so a gap in seq marks a lost record and a new boot_id marks a restart.

Nothing here may raise into event processing. A trail that can stop a control from being applied is worse than no trail.

AuditSequence

One client's audit counter: a random boot_id and a rising seq.

One per client rather than per process: two clients interleaving on one counter would each show a gap at every other record, which reads as loss.

Source code in src/py20305/audit.py
class AuditSequence:
    """One client's audit counter: a random ``boot_id`` and a rising ``seq``.

    One per client rather than per process: two clients interleaving on one
    counter would each show a gap at every other record, which reads as loss.
    """

    def __init__(self) -> None:
        self.boot_id = uuid.uuid4().hex
        # next() on itertools.count is atomic under the GIL, so a record
        # made from a worker thread cannot reuse a number.
        self._counter = itertools.count(1)

    def stamp(self) -> dict[str, Any]:
        """The next ``boot_id`` and ``seq`` pair. Each call consumes a number."""
        return {"boot_id": self.boot_id, "seq": next(self._counter)}
stamp
stamp() -> dict[str, Any]

The next boot_id and seq pair. Each call consumes a number.

Source code in src/py20305/audit.py
def stamp(self) -> dict[str, Any]:
    """The next ``boot_id`` and ``seq`` pair. Each call consumes a number."""
    return {"boot_id": self.boot_id, "seq": next(self._counter)}

AuditEmitter

Builds lifecycle and loss-of-communications records, and hands them on.

Disabled until an operations history or an audit observer is attached.

Source code in src/py20305/audit.py
class AuditEmitter:
    """Builds lifecycle and loss-of-communications records, and hands them on.

    Disabled until an operations history or an audit observer is attached.
    """

    def __init__(
        self,
        observer: AuditObserver | None = None,
        *,
        client_id: str | None = None,
        sequence: AuditSequence | None = None,
    ) -> None:
        self._observer = observer
        self._guard = ObserverGuard("audit observer")
        self._client_id = client_id or ""
        self._sequence = sequence if sequence is not None else AuditSequence()
        self._history: EventHistory | None = None
        #: Records that failed to build or store, by kind. A trail that
        #: stopped working must not look like a client with nothing to report.
        self.emit_failures: dict[str, int] = {}

    @property
    def enabled(self) -> bool:
        """Whether records go anywhere: to the observer, the history, or both."""
        return self._observer is not None or self._history is not None

    @property
    def observing(self) -> bool:
        """Whether an audit observer is attached."""
        return self._observer is not None

    @property
    def observer_failures(self) -> int:
        """How many times the audit observer raised."""
        return self._guard.failures

    @property
    def keeps_history(self) -> bool:
        """Whether records are kept in the local operations history."""
        return self._history is not None

    def attach_history(self, history: EventHistory | None) -> None:
        """Keep every record in ``history`` as well, whether or not it is observed."""
        self._history = history

    def attach_observer(self, observer: AuditObserver | None) -> None:
        """Hand every record to ``observer``, or stop with None."""
        self._observer = observer

    @property
    def sequence(self) -> AuditSequence:
        """This client's counter."""
        return self._sequence

    def set_client_id(self, client_id: str) -> None:
        """Name the client in every record, usually by its certificate's LFDI."""
        self._client_id = client_id

    def event_transition(
        self,
        *,
        event_mrid: bytes,
        program_href: str,
        from_state: str | None,
        to_state: str,
        effective_start: int,
        effective_duration: int,
        primacy: int,
        lfdis: list[str],
        at: float,
        applied_lfdis: list[str] | None = None,
        rejected_lfdis: list[str] | None = None,
        superseded_by: bytes | None = None,
        superseded_lfdis: list[str] | None = None,
        superseded_modes: dict[str, list[str]] | None = None,
        control: Mapping[str, Any] | None = None,
    ) -> None:
        """Record one event moving from one state to another.

        Args:
            event_mrid: The event's mRID.
            program_href: The program the event belongs to.
            from_state: The state before, or ``None`` for an event first seen.
            to_state: ``scheduled``, ``active``, ``completed``, ``cancelled``,
                ``superseded``, ``opted_out``, ``expired`` (already over when
                first received) or ``skipped`` (inside a loss-of-communications
                window the client opted out of).
            effective_start: Start after randomization, epoch seconds.
            effective_duration: Duration after randomization, seconds.
            primacy: The program's primacy.
            lfdis: The devices the event targets.
            at: When the transition happened, on the server's timebase.
            applied_lfdis: On ``active``, the devices whose dispatch returned
                without error -- what was reported to the server as started.
            rejected_lfdis: On ``active``, the devices whose dispatch failed or
                missed the activation deadline.
            superseded_by: On ``superseded``, the superseding event.
            superseded_lfdis: On a partial supersession, the devices it covers.
            superseded_modes: On a partial supersession, the modes per device.
            control: The control's description and settings, kept in the local
                history only. Published records keep their existing shape.
        """
        if not self.enabled:
            return
        try:
            record: dict[str, Any] = {
                "kind": "der_event",
                "event_mrid": mrid_hex(event_mrid),
                "program_href": program_href,
                "from_state": from_state,
                "to_state": to_state,
                "effective_start": effective_start,
                "effective_duration": effective_duration,
                "primacy": primacy,
                "lfdis": sorted(_lfdi(x) for x in lfdis),
                "at": at,
            }
            if applied_lfdis is not None:
                record["applied_lfdis"] = sorted(_lfdi(x) for x in applied_lfdis)
            if rejected_lfdis is not None:
                record["rejected_lfdis"] = sorted(_lfdi(x) for x in rejected_lfdis)
            if superseded_by is not None:
                record["superseded_by"] = mrid_hex(superseded_by)
            if superseded_lfdis is not None:
                record["superseded_lfdis"] = sorted(_lfdi(x) for x in superseded_lfdis)
            if superseded_modes is not None:
                record["superseded_modes"] = {
                    _lfdi(dev): sorted(modes) for dev, modes in superseded_modes.items()
                }
            self._publish(record, control=control)
        except Exception:
            self._failed("der_event")

    def comms_loss(
        self,
        *,
        transition: str,
        threshold: int,
        simulated: bool,
        at: float,
        elapsed_seconds: int | None = None,
        duration_seconds: int | None = None,
        resume_after: int | None = None,
    ) -> None:
        """Record a step into or out of loss-of-communications mode.

        Published in the order things happen: ``entered`` before any event is
        opted out, ``recovering`` once contact returns and before the schedule
        is polled again, ``cleared`` once the mode ends. A recovery that fails
        is retried, so ``recovering`` can repeat before one ``cleared``.

        Args:
            transition: ``entered``, ``recovering`` or ``cleared``.
            threshold: The configured silence threshold.
            simulated: Whether an operator-triggered simulation caused it.
            at: When it happened, on the server's timebase.
            elapsed_seconds: On ``entered``, how long the server had been
                silent.
            duration_seconds: On ``recovering`` and ``cleared``, how long the
                client had been in the mode.
            resume_after: On ``cleared``, the epoch after which the schedule
                resumes, when the opted-out window has not yet passed.
        """
        if not self.enabled:
            return
        try:
            record: dict[str, Any] = {
                "kind": "comms_loss",
                "transition": transition,
                "threshold": threshold,
                "simulated": simulated,
                "at": at,
            }
            if transition == "entered":
                record["elapsed_seconds"] = elapsed_seconds
            else:
                record["duration_seconds"] = duration_seconds
            if transition == "cleared":
                record["resume_after"] = resume_after
            self._publish(record)
        except Exception:
            self._failed("comms_loss")

    def late_dispatch(
        self,
        *,
        event_mrid: bytes,
        lfdi: str,
        applied: bool,
        at: float,
        error: str | None = None,
        error_type: str | None = None,
    ) -> None:
        """Record how a dispatch that missed the activation deadline ended.

        The ``active`` record lists such a device as rejected, because that is
        what the server was told. The apply carries on regardless, and this is
        the record of whether it then reached the device.

        Args:
            event_mrid: The event whose control it was.
            lfdi: The device, or its href where no LFDI is known.
            applied: Whether the apply finished without error.
            at: When it finished, on the server's timebase.
            error: The failure, when it failed.
            error_type: The failure's exception class name.
        """
        if not self.enabled:
            return
        try:
            record: dict[str, Any] = {
                "kind": "late_dispatch",
                "event_mrid": mrid_hex(event_mrid),
                "lfdi": _lfdi(lfdi),
                "applied": applied,
                "at": at,
            }
            if error is not None:
                record["error"] = error[:512]
                record["error_type"] = error_type
            self._publish(record)
        except Exception:
            self._failed("late_dispatch")

    def _publish(self, record: dict[str, Any], *, control: Mapping[str, Any] | None = None) -> None:
        record["schema"] = AUDIT_SCHEMA_VERSION
        record["client_id"] = self._client_id
        record.update(self._sequence.stamp())
        if self._history is not None and not self._history.record(record, control=control):
            self._failed(f"{record['kind']} history")
        if self._observer is not None:
            self._guard.deliver(
                self._observer,
                AuditRecord(kind=str(record["kind"]), data=MappingProxyType(dict(record))),
            )

    def _failed(self, kind: str) -> None:
        count = self.emit_failures.get(kind, 0) + 1
        self.emit_failures[kind] = count
        if count == 1:
            logger.warning(
                "Audit trail failed to record a %s; further failures log at debug",
                kind,
                exc_info=True,
            )
        else:
            logger.debug("Audit trail failed to record a %s", kind, exc_info=True)
enabled property
enabled: bool

Whether records go anywhere: to the observer, the history, or both.

observing property
observing: bool

Whether an audit observer is attached.

observer_failures property
observer_failures: int

How many times the audit observer raised.

keeps_history property
keeps_history: bool

Whether records are kept in the local operations history.

sequence property
sequence: AuditSequence

This client's counter.

attach_history
attach_history(history: EventHistory | None) -> None

Keep every record in history as well, whether or not it is observed.

Source code in src/py20305/audit.py
def attach_history(self, history: EventHistory | None) -> None:
    """Keep every record in ``history`` as well, whether or not it is observed."""
    self._history = history
attach_observer
attach_observer(observer: AuditObserver | None) -> None

Hand every record to observer, or stop with None.

Source code in src/py20305/audit.py
def attach_observer(self, observer: AuditObserver | None) -> None:
    """Hand every record to ``observer``, or stop with None."""
    self._observer = observer
set_client_id
set_client_id(client_id: str) -> None

Name the client in every record, usually by its certificate's LFDI.

Source code in src/py20305/audit.py
def set_client_id(self, client_id: str) -> None:
    """Name the client in every record, usually by its certificate's LFDI."""
    self._client_id = client_id
event_transition
event_transition(*, event_mrid: bytes, program_href: str, from_state: str | None, to_state: str, effective_start: int, effective_duration: int, primacy: int, lfdis: list[str], at: float, applied_lfdis: list[str] | None = None, rejected_lfdis: list[str] | None = None, superseded_by: bytes | None = None, superseded_lfdis: list[str] | None = None, superseded_modes: dict[str, list[str]] | None = None, control: Mapping[str, Any] | None = None) -> None

Record one event moving from one state to another.

Parameters:

Name Type Description Default
event_mrid bytes

The event's mRID.

required
program_href str

The program the event belongs to.

required
from_state str | None

The state before, or None for an event first seen.

required
to_state str

scheduled, active, completed, cancelled, superseded, opted_out, expired (already over when first received) or skipped (inside a loss-of-communications window the client opted out of).

required
effective_start int

Start after randomization, epoch seconds.

required
effective_duration int

Duration after randomization, seconds.

required
primacy int

The program's primacy.

required
lfdis list[str]

The devices the event targets.

required
at float

When the transition happened, on the server's timebase.

required
applied_lfdis list[str] | None

On active, the devices whose dispatch returned without error -- what was reported to the server as started.

None
rejected_lfdis list[str] | None

On active, the devices whose dispatch failed or missed the activation deadline.

None
superseded_by bytes | None

On superseded, the superseding event.

None
superseded_lfdis list[str] | None

On a partial supersession, the devices it covers.

None
superseded_modes dict[str, list[str]] | None

On a partial supersession, the modes per device.

None
control Mapping[str, Any] | None

The control's description and settings, kept in the local history only. Published records keep their existing shape.

None
Source code in src/py20305/audit.py
def event_transition(
    self,
    *,
    event_mrid: bytes,
    program_href: str,
    from_state: str | None,
    to_state: str,
    effective_start: int,
    effective_duration: int,
    primacy: int,
    lfdis: list[str],
    at: float,
    applied_lfdis: list[str] | None = None,
    rejected_lfdis: list[str] | None = None,
    superseded_by: bytes | None = None,
    superseded_lfdis: list[str] | None = None,
    superseded_modes: dict[str, list[str]] | None = None,
    control: Mapping[str, Any] | None = None,
) -> None:
    """Record one event moving from one state to another.

    Args:
        event_mrid: The event's mRID.
        program_href: The program the event belongs to.
        from_state: The state before, or ``None`` for an event first seen.
        to_state: ``scheduled``, ``active``, ``completed``, ``cancelled``,
            ``superseded``, ``opted_out``, ``expired`` (already over when
            first received) or ``skipped`` (inside a loss-of-communications
            window the client opted out of).
        effective_start: Start after randomization, epoch seconds.
        effective_duration: Duration after randomization, seconds.
        primacy: The program's primacy.
        lfdis: The devices the event targets.
        at: When the transition happened, on the server's timebase.
        applied_lfdis: On ``active``, the devices whose dispatch returned
            without error -- what was reported to the server as started.
        rejected_lfdis: On ``active``, the devices whose dispatch failed or
            missed the activation deadline.
        superseded_by: On ``superseded``, the superseding event.
        superseded_lfdis: On a partial supersession, the devices it covers.
        superseded_modes: On a partial supersession, the modes per device.
        control: The control's description and settings, kept in the local
            history only. Published records keep their existing shape.
    """
    if not self.enabled:
        return
    try:
        record: dict[str, Any] = {
            "kind": "der_event",
            "event_mrid": mrid_hex(event_mrid),
            "program_href": program_href,
            "from_state": from_state,
            "to_state": to_state,
            "effective_start": effective_start,
            "effective_duration": effective_duration,
            "primacy": primacy,
            "lfdis": sorted(_lfdi(x) for x in lfdis),
            "at": at,
        }
        if applied_lfdis is not None:
            record["applied_lfdis"] = sorted(_lfdi(x) for x in applied_lfdis)
        if rejected_lfdis is not None:
            record["rejected_lfdis"] = sorted(_lfdi(x) for x in rejected_lfdis)
        if superseded_by is not None:
            record["superseded_by"] = mrid_hex(superseded_by)
        if superseded_lfdis is not None:
            record["superseded_lfdis"] = sorted(_lfdi(x) for x in superseded_lfdis)
        if superseded_modes is not None:
            record["superseded_modes"] = {
                _lfdi(dev): sorted(modes) for dev, modes in superseded_modes.items()
            }
        self._publish(record, control=control)
    except Exception:
        self._failed("der_event")
comms_loss
comms_loss(*, transition: str, threshold: int, simulated: bool, at: float, elapsed_seconds: int | None = None, duration_seconds: int | None = None, resume_after: int | None = None) -> None

Record a step into or out of loss-of-communications mode.

Published in the order things happen: entered before any event is opted out, recovering once contact returns and before the schedule is polled again, cleared once the mode ends. A recovery that fails is retried, so recovering can repeat before one cleared.

Parameters:

Name Type Description Default
transition str

entered, recovering or cleared.

required
threshold int

The configured silence threshold.

required
simulated bool

Whether an operator-triggered simulation caused it.

required
at float

When it happened, on the server's timebase.

required
elapsed_seconds int | None

On entered, how long the server had been silent.

None
duration_seconds int | None

On recovering and cleared, how long the client had been in the mode.

None
resume_after int | None

On cleared, the epoch after which the schedule resumes, when the opted-out window has not yet passed.

None
Source code in src/py20305/audit.py
def comms_loss(
    self,
    *,
    transition: str,
    threshold: int,
    simulated: bool,
    at: float,
    elapsed_seconds: int | None = None,
    duration_seconds: int | None = None,
    resume_after: int | None = None,
) -> None:
    """Record a step into or out of loss-of-communications mode.

    Published in the order things happen: ``entered`` before any event is
    opted out, ``recovering`` once contact returns and before the schedule
    is polled again, ``cleared`` once the mode ends. A recovery that fails
    is retried, so ``recovering`` can repeat before one ``cleared``.

    Args:
        transition: ``entered``, ``recovering`` or ``cleared``.
        threshold: The configured silence threshold.
        simulated: Whether an operator-triggered simulation caused it.
        at: When it happened, on the server's timebase.
        elapsed_seconds: On ``entered``, how long the server had been
            silent.
        duration_seconds: On ``recovering`` and ``cleared``, how long the
            client had been in the mode.
        resume_after: On ``cleared``, the epoch after which the schedule
            resumes, when the opted-out window has not yet passed.
    """
    if not self.enabled:
        return
    try:
        record: dict[str, Any] = {
            "kind": "comms_loss",
            "transition": transition,
            "threshold": threshold,
            "simulated": simulated,
            "at": at,
        }
        if transition == "entered":
            record["elapsed_seconds"] = elapsed_seconds
        else:
            record["duration_seconds"] = duration_seconds
        if transition == "cleared":
            record["resume_after"] = resume_after
        self._publish(record)
    except Exception:
        self._failed("comms_loss")
late_dispatch
late_dispatch(*, event_mrid: bytes, lfdi: str, applied: bool, at: float, error: str | None = None, error_type: str | None = None) -> None

Record how a dispatch that missed the activation deadline ended.

The active record lists such a device as rejected, because that is what the server was told. The apply carries on regardless, and this is the record of whether it then reached the device.

Parameters:

Name Type Description Default
event_mrid bytes

The event whose control it was.

required
lfdi str

The device, or its href where no LFDI is known.

required
applied bool

Whether the apply finished without error.

required
at float

When it finished, on the server's timebase.

required
error str | None

The failure, when it failed.

None
error_type str | None

The failure's exception class name.

None
Source code in src/py20305/audit.py
def late_dispatch(
    self,
    *,
    event_mrid: bytes,
    lfdi: str,
    applied: bool,
    at: float,
    error: str | None = None,
    error_type: str | None = None,
) -> None:
    """Record how a dispatch that missed the activation deadline ended.

    The ``active`` record lists such a device as rejected, because that is
    what the server was told. The apply carries on regardless, and this is
    the record of whether it then reached the device.

    Args:
        event_mrid: The event whose control it was.
        lfdi: The device, or its href where no LFDI is known.
        applied: Whether the apply finished without error.
        at: When it finished, on the server's timebase.
        error: The failure, when it failed.
        error_type: The failure's exception class name.
    """
    if not self.enabled:
        return
    try:
        record: dict[str, Any] = {
            "kind": "late_dispatch",
            "event_mrid": mrid_hex(event_mrid),
            "lfdi": _lfdi(lfdi),
            "applied": applied,
            "at": at,
        }
        if error is not None:
            record["error"] = error[:512]
            record["error_type"] = error_type
        self._publish(record)
    except Exception:
        self._failed("late_dispatch")

mrid_hex

mrid_hex(mrid: bytes | None) -> str | None

An mRID as uppercase hex, the form the mRID element takes on the wire.

Matching the wire form lets a record be joined to the raw control by a plain text match on the identifier.

Source code in src/py20305/audit.py
def mrid_hex(mrid: bytes | None) -> str | None:
    """An mRID as uppercase hex, the form the ``mRID`` element takes on the wire.

    Matching the wire form lets a record be joined to the raw control by a
    plain text match on the identifier.
    """
    return mrid.hex().upper() if mrid is not None else None