Skip to content

Add optional Prometheus metrics for client operations - #901

Merged
gijzelaerr merged 4 commits into
gijzelaerr:masterfrom
Poseidonas:metrics-support
Oct 3, 2026
Merged

gijzelaerr merged 4 commits into
gijzelaerr:masterfrom
Poseidonas:metrics-support

Conversation

@Poseidonas

@Poseidonas Poseidonas commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

Adds an on_operation callback to the synchronous and asynchronous clients, following up on #843: invoked after each PLC operation with its name, duration, and whether it raised — same shape as the existing on_disconnect/on_reconnect callbacks.

Instrumentation sits in read_area/write_area/read_multi_vars/write_multi_vars/upload/download via a decorator in client_base.py (shared by Client and AsyncClient), so these methods keep their original body. A nested instrumented call runs normally but isn't reported on its own, so one logical operation isn't counted and timed twice.

example/prometheus_metrics.py shows building a Prometheus registry and GET /metrics HTTP server on top of this hook plus the existing on_disconnect/on_reconnect callbacks — separate from the exporter described in #623.

14 tests in tests/test_operation_hook.py. Full suite passes; ruff (check + format), mypy, and the Sphinx build (-W) are clean.

@gijzelaerr gijzelaerr left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for following up on #843 so quickly — having operation metrics available from the client is useful, and it fits alongside the existing OperationLogger, rate limiter and connection callbacks. Tests, mypy and pre-commit all pass locally. A few things I'd like to see changed before merging:

1. Avoid re-indenting read_area / write_area. Wrapping the whole body in with self._instrumented(...) shifts ~100 lines, which makes the diff hard to review, pollutes git blame, and will conflict with every future change to these methods. A decorator (e.g. @_instrumented("read_area")) gives the same behaviour without touching the body.

2. Keep the HTTP server out of the library. I'd rather not ship a hand-rolled HTTP server in a PLC communication library. Preferably the client exposes a small generic hook — something like on_operation(name: str, seconds: float, error: bool) — so users can feed prometheus_client, OpenTelemetry or anything else. MetricsRegistry + MetricsServer would then make a nice example/ script rather than part of the package API.

3. If a server stays anywhere, don't bind 0.0.0.0 by default. In OT networks this publishes PLC addresses on every interface; 127.0.0.1 is the safer default.

4. Duration metric type. snap7_operation_duration_seconds_sum is declared as a standalone counter. The Prometheus convention is a summary (or histogram) named snap7_operation_duration_seconds exposing _sum and _count.

5. Connected gauge keying. The gauge is keyed only by host, so two clients to the same PLC (different rack/slot/port) overwrite each other. Also, calling disconnect() on a client that never connected emits snap7_client_connected{plc=""} 0:

r = MetricsRegistry(); Client(metrics=r).disconnect()
# -> snap7_client_connected{plc=""} 0

6. Async parity and coverage. We keep Client and AsyncClient at parity, so AsyncClient should accept the same option. Multi-var reads/writes and block upload/download are currently not instrumented either.

7. Please add a short docs section and a CHANGES.md entry under "Unreleased".

Happy to look again once it's slimmed down — the hook-based approach in (1)+(2) would also make most of (3)–(5) go away.

@Poseidonas

Copy link
Copy Markdown
Contributor Author

Reworked along these lines:

  1. _instrumented is now a decorator (in client_base.py, shared with AsyncClient), not a context manager — read_area/write_area keep their original body, one @_instrumented(...) line each.
  2. snap7/metrics.py is gone. Client/AsyncClient expose a generic on_operation(name, seconds, error) hook instead, same shape as on_disconnect/on_reconnect. example/prometheus_metrics.py builds a registry + HTTP server on top of it.
  3. Example server defaults to 127.0.0.1.
  4. snap7_operation_duration_seconds is now a summary (_sum/_count), not a standalone counter.
  5. Connected-state tracking is out of the core entirely. The example keys it by a caller-supplied connection_id instead of host — so it doesn't collide across connections — and updates it explicitly around connect()/disconnect(), plus via on_disconnect/on_reconnect for auto-reconnect transitions.
  6. AsyncClient now takes on_operation too. read_multi_vars/write_multi_vars/upload/download are instrumented on both clients.
  7. Added a section to doc/connection-issues.rst and a CHANGES.md entry.

client.py diff against master is 14 lines now. Tests, mypy, ruff (check + format), and the Sphinx build (-W) pass locally; 12 new tests replace the old test_metrics.py.

@gijzelaerr gijzelaerr left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, this is much better. The hook API is what I had in mind, and client.py barely changes now. A few things are left, mostly small:

1. Python 3.14 deprecation. asyncio.iscoroutinefunction is deprecated in 3.14 (removal in 3.16), and _instrumented calls it while the module is imported. So on 3.14 every import snap7 emits a DeprecationWarning. Please use inspect.iscoroutinefunction instead.

2. Nested calls are counted twice. AsyncClient.read_multi_vars / write_multi_vars loop over self.read_area / self.write_area, and the sync read_multi_vars does the same on its dict-items path. One multi-var read of 5 items then reports one read_multi_vars plus five read_area operations, and the time is counted twice in the totals. The sync and async clients also report differently for the same call. The simplest fix is to report only the outermost operation, e.g. a per-client depth counter (or a ContextVar for async) that skips reporting while an instrumented call is already in progress. A test for it would be good.

3. Duplication in the decorator. The sync and async wrappers repeat the timing and callback logic. Moving the try: self._on_operation(...) except: logger.debug(...) part into one small helper (e.g. _report_operation(self, operation, started, error)) would leave only the await as the difference.

4. Rebase. CHANGES.md conflicts with master, which already has an Unreleased section. Please add your entry there instead of a second heading.

5. PR description. It still describes snap7/metrics.py, metrics=, and tests/test_metrics.py. Please update it to the hook design, since it ends up in the squash commit.

After that I think this is ready to merge.

@Poseidonas

Copy link
Copy Markdown
Contributor Author

Thanks, all addressed:

  1. Switched to inspect.iscoroutinefunction — confirmed it behaves identically to asyncio.iscoroutinefunction for plain async def methods.
  2. Added depth tracking via a per-instance ContextVar, set in each client's __init__. A nested call runs normally but is only reported when it's the outermost instrumented call.
  3. Using ContextVar on both sync and async makes the wrapper code identical except for the await — this also folds in the _report_operation() helper you suggested.
  4. Rebased onto master; CHANGES.md entry now sits under the existing Unreleased heading.
  5. Updated the PR description to match the current hook design.

Added two tests (test_nested_calls_are_not_double_reported, sync + async) — confirmed they fail without the depth-tracking fix and pass with it. 14 tests total now. Full suite, mypy, ruff (check + format), and the Sphinx build pass locally.

@gijzelaerr gijzelaerr left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the quick turnaround — all points addressed, and the depth tracking with tests for both clients is exactly what I had in mind. Merging.

@gijzelaerr
gijzelaerr merged commit 18a1bb2 into gijzelaerr:master Oct 3, 2026
17 checks passed
@gijzelaerr gijzelaerr mentioned this pull request Oct 4, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants