feat: add metrics endpoint and improve month handling

Added a new /_metrics/ endpoint to expose financial data in Prometheus format, facilitating better monitoring and analytics.

Enhanced the get_latest_month function to optionally exclude the current month, preventing potential issues in incomplete data scenarios, with this behavior being toggled by the application's development mode status.
This commit is contained in:
Kumi 2024-06-30 19:15:45 +02:00
parent ac5b16d2f7
commit 2357427d96
Signed by: kumi
GPG key ID: ECBCC9082395383F
2 changed files with 35 additions and 2 deletions

View file

@ -1,12 +1,24 @@
from decimal import Decimal
from datetime import datetime
def get_latest_month(data):
def get_latest_month(data, allow_current=False):
years = sorted(data.keys())
latest_year = years[-1]
months = sorted(data[latest_year].keys())
latest_month = months[-1]
if (
not allow_current
and latest_year == str(datetime.now().year)
and latest_month == str(datetime.now().month)
):
try:
latest_month = months[-2]
except IndexError:
latest_year = years[-2]
latest_month = months[-1]
return int(latest_month), int(latest_year)

23
main.py
View file

@ -54,7 +54,9 @@ def catch_all(path):
(pathlib.Path(__file__).parent / "data" / "finances.json").read_text()
)
finances_month, finances_year = get_latest_month(finances)
allow_current = app.development_mode
finances_month, finances_year = get_latest_month(finances, allow_current)
finances_period = datetime.date(finances_year, finances_month, 1)
finances_period_str = finances_period.strftime("%B %Y")
@ -97,6 +99,25 @@ def catch_all(path):
return "404 Not Found", 404
@app.route("/_metrics/")
def metrics():
finances = json.loads(
(pathlib.Path(__file__).parent / "data" / "finances.json").read_text()
)
balances = get_transparency_data(finances)["end_balance"]
response = (
"# HELP privatecoffee_balance The balance of the private.coffee account\n"
)
response += "# TYPE privatecoffee_balance gauge\n"
for currency, balance in balances.items():
response += f'privatecoffee_balance{{currency="{currency}"}} {balance}\n'
return response
app.development_mode = False
if os.environ.get("PRIVATECOFFEE_DEV"):