Skip to content

Commit

Permalink
feat: add perftracker
Browse files Browse the repository at this point in the history
  • Loading branch information
kod-kristoff committed May 25, 2023
1 parent c7829a9 commit ff7b993
Show file tree
Hide file tree
Showing 4 changed files with 54 additions and 10 deletions.
3 changes: 2 additions & 1 deletion flask_matomo2/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""Track requests to your Flask server with Matomo"""
from flask_matomo2 import trackers
from flask_matomo2.core import Matomo

__all__ = ["Matomo"]
__all__ = ["trackers", "Matomo"]
4 changes: 1 addition & 3 deletions flask_matomo2/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -134,8 +134,6 @@ def before_request(self):
):
data["action_name"] = self.routes_details.get(action_name, {}).get("action_name")

# Create new thread with request, because otherwise the original request will be blocked
# Thread(target=self.track, kwargs=keyword_arguments).start()
g.flask_matomo2 = {
"tracking": True,
"start_ns": time.perf_counter_ns(),
Expand All @@ -159,7 +157,7 @@ def teardown_request(self, exc: typing.Optional[Exception] = None) -> None:
tracking_state = g.get("flask_matomo2", {})
if not tracking_state.get("tracking", False):
return

print(f"{tracking_state=}")
tracking_data = tracking_state["tracking_data"]
for key, value in tracking_state.get("custom_tracking_data", {}).items():
if key == "cvar" and "cvar" in tracking_data:
Expand Down
35 changes: 35 additions & 0 deletions flask_matomo2/trackers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import time
import typing


class PerfMsTracker:
"""Measure time between enter and exit and records it in state."""

def __init__(self, scope: typing.MutableMapping[str, typing.Any], key: str) -> None:
print(f"{scope=}")
self.start_ns = 0.0
# if "state" not in scope:
# scope["state"] = {}
# if "flask_matomo2" not in scope:
# scope["flask_matomo2"] = {}
self.scope = scope
self.key = key
print(f"{self.scope=}")

def __enter__(self):
self.start_ns = time.perf_counter_ns()

def __exit__(self, exc_type, exc_value, exc_tb):
self._record_time(self.key, time.perf_counter_ns())

async def __aenter__(self):
self.start_ns = time.perf_counter_ns()

async def __aexit__(self, exc_type, exc_value, exc_tb):
self._record_time(self.key, time.perf_counter_ns())

def _record_time(self, key: str, end_ns: float) -> None:
print(f"{self.scope=}")

elapsed_time_ms = (end_ns - self.start_ns) / 1000.0
self.scope["tracking_data"][key] = elapsed_time_ms
22 changes: 16 additions & 6 deletions tests/test_flask_matomo.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import copy
import json
import time
import typing
from dataclasses import dataclass
from unittest import mock
Expand All @@ -12,6 +13,7 @@
from werkzeug import exceptions as werkzeug_exc

from flask_matomo2 import Matomo
from flask_matomo2.trackers import PerfMsTracker


@dataclass
Expand Down Expand Up @@ -70,11 +72,16 @@ def old():
def custom_var():
if "flask_matomo2" not in flask.g:
flask.g.flask_matomo2 = {"tracking": True}
flask.g.flask_matomo2["custom_tracking_data"] = {
"e_a": "Playing",
"pf_srv": "123",
"cvar": {"anything": "goes"},
}
# flask.g.flask_matomo2["custom_tracking_data"] = {
# "e_a": "Playing",
# "cvar": {"anything": "goes"},
# }
with PerfMsTracker(scope=flask.g.flask_matomo2, key="pf_srv"):
flask.g.flask_matomo2["custom_tracking_data"] = {
"e_a": "Playing",
"cvar": {"anything": "goes"},
}
time.sleep(0.1)
return "custom_var"

@app.route("/bor")
Expand Down Expand Up @@ -142,6 +149,9 @@ def assert_query_string(url: str, expected_q: dict) -> None:
assert q.pop("ua")[0].startswith("python-httpx")
cvar = q.pop("cvar")[0]
expected_cvar = expected_q.pop("cvar")[0]
if "pf_srv" in expected_q:
expected_lower_limit = expected_q.pop("pf_srv")
assert float(q.pop("pf_srv")[0]) >= expected_lower_limit

assert q == expected_q
assert json.loads(cvar) == json.loads(expected_cvar)
Expand Down Expand Up @@ -248,7 +258,7 @@ def test_matomo_client_gets_called_on_get_custom_var(
expected_q["url"][0] += "/set/custom/var"
expected_q["action_name"] = ["/set/custom/var"]
expected_q["e_a"] = ["Playing"]
expected_q["pf_srv"] = ["123"]
expected_q["pf_srv"] = 90000
expected_q["cvar"] = ['{"http_status_code": 200, "http_method": "GET", "anything": "goes"}']

assert_query_string(str(matomo_client.get.call_args), expected_q)
Expand Down

0 comments on commit ff7b993

Please sign in to comment.