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:
ExchangeRecordis 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:
ConnectionEventis 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:
ProtocolAnomalyis one body the client could not use, one response with a status it did not expect, or one notification it dropped. - :class:
DeviceRecordis one read from or write to a device through a connector. - :class:
AuditRecordis 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_versionis 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
of
classmethod
¶
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
ExchangeDirection ¶
Bases: StrEnum
Which end started an exchange.
Source code in src/py20305/observers.py
ErrorKind ¶
Bases: StrEnum
Why an exchange received no response, or a connection failed. The values are stable.
Source code in src/py20305/observers.py
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
|
|
received_monotonic |
float | 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
|
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
139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 | |
ConnectionRole ¶
Bases: StrEnum
Which part of the client reported a connection event.
Source code in src/py20305/observers.py
ConnectionDirection ¶
Bases: StrEnum
Which end opened the connection, seen from the client.
Source code in src/py20305/observers.py
ConnectionTransport ¶
ConnectionOutcome ¶
Bases: StrEnum
What happened to a connection. The values are stable.
Source code in src/py20305/observers.py
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 |
error_kind |
ErrorKind | None
|
The kind of failure, for |
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
AnomalyCode ¶
Bases: StrEnum
What the client could not use or did not expect. The values are stable.
Source code in src/py20305/observers.py
AnomalySeverity ¶
Bases: StrEnum
How much an anomaly says about the peer, from least to most.
Source code in src/py20305/observers.py
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 |
message |
str
|
What happened, in a few words. |
exchange_id |
str | None
|
The :class: |
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
of
classmethod
¶
Return an anomaly with the severity its code is reported with.
DeviceOperation ¶
DeviceOutcome ¶
Bases: StrEnum
How a device read or write ended.
Source code in src/py20305/observers.py
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: |
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: |
error_type |
str | None
|
The failure's exception class name, or None. |
origin |
str | None
|
Who issued a write, such as |
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 ( |
endpoint |
str | None
|
The connector's device address, such as |
timestamp |
float
|
When the record was made, in seconds since the Unix epoch. |
Source code in src/py20305/observers.py
AuditRecord
dataclass
¶
One record of the control audit trail.
Attributes:
| Name | Type | Description |
|---|---|---|
record_version |
int
|
The record shape version. |
kind |
str
|
|
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
Observers
dataclass
¶
The protocol observers of one client, and how exchanges are captured.
Attributes:
| Name | Type | Description |
|---|---|---|
exchange |
ExchangeObserver | None
|
Receives each :class: |
connection |
ConnectionObserver | None
|
Receives each :class: |
anomaly |
AnomalyObserver | None
|
Receives each :class: |
capture_bodies |
bool
|
Put request and response bodies in exchange records.
Off, |
redacted_headers |
frozenset[str]
|
Header names whose values are replaced by
:data: |
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
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
deliver ¶
Call observer with record, unless there is no observer.
Source code in src/py20305/observers.py
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
577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 | |
close ¶
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
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
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
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 | |
attach_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'
|
Source code in src/py20305/connectors/device_telemetry.py
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 |
None
|
origin
|
str | None
|
Who issued the write, e.g. |
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
mrid_hex ¶
Return an mRID as uppercase hex, the form the mRID element takes on the wire.
device_protocol ¶
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
device_endpoint ¶
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
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
stamp ¶
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
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 | |
enabled
property
¶
Whether records go anywhere: to the observer, the history, or both.
keeps_history
property
¶
Whether records are kept in the local operations history.
attach_history ¶
attach_observer ¶
set_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 |
required |
to_state
|
str
|
|
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 |
None
|
rejected_lfdis
|
list[str] | None
|
On |
None
|
superseded_by
|
bytes | None
|
On |
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
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
|
|
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 |
None
|
duration_seconds
|
int | None
|
On |
None
|
resume_after
|
int | None
|
On |
None
|
Source code in src/py20305/audit.py
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
mrid_hex ¶
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.