Skip to content

ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.

Gate request metrics the way the sweeps expect

Juan Denis11af8a588dc5
diff --git a/backend/app/api/bandwidth.py b/backend/app/api/bandwidth.py
index e1179298..05e35a63 100644
--- a/backend/app/api/bandwidth.py
+++ b/backend/app/api/bandwidth.py
@@ -7,6 +7,7 @@ Mounted at /api/v1/bandwidth (registered in app/__init__.py).
from flask import Blueprint, jsonify, request
from app.middleware.rbac import get_current_user
from app.error_reporting import unexpected_response
+from app.exceptions import NotFoundError
from ..middleware.rbac import admin_required, viewer_required
from ..models import Application
@@ -57,10 +58,13 @@ def get_app_bandwidth(app_id):
def get_app_request_metrics(app_id):
"""Request rate, status classes, latency percentiles and cache hit ratio
from the timed access log (plan 86 §A2). ``period``: 1h, 24h, 7d or 30d."""
- # Unknown/foreign app → NotFoundError (404); bad period → ValidationError
- # (400); both through the global handler.
- return jsonify(RequestMetricsService.series_for_user(
- get_current_user(), app_id, period=request.args.get('period', '24h')))
+ # Same 404 for a missing and a foreign app (plan 29 #9); a bad period is a
+ # ValidationError (400). Both go through the global handler.
+ app = RequestMetricsService.live_app(app_id)
+ if app is None or not ResourceGrantService.can_access_app(get_current_user(), app):
+ raise NotFoundError('Not found')
+ return jsonify(RequestMetricsService.series(
+ app_id, period=request.args.get('period', '24h')))
@bandwidth_bp.route('/aggregate', methods=['POST'])
diff --git a/backend/app/models/app_request_metric.py b/backend/app/models/app_request_metric.py
index dd80be87..e08ba57e 100644
--- a/backend/app/models/app_request_metric.py
+++ b/backend/app/models/app_request_metric.py
@@ -9,13 +9,13 @@ hour built from sixty minutes — still yields correct p50/p95/p99 to bucket
resolution. Pruned on every sampler tick (minute rows after 48h, hour rows
after 30 days).
"""
-import json
from datetime import datetime
from app import db
+from app.models.json_column_mixin import JsonColumnMixin
-class AppRequestMetric(db.Model):
+class AppRequestMetric(JsonColumnMixin, db.Model):
__tablename__ = 'app_request_metrics'
__table_args__ = (
db.UniqueConstraint('app_id', 'level', 'bucket',
@@ -53,14 +53,22 @@ class AppRequestMetric(db.Model):
updated_at = db.Column(db.DateTime, default=datetime.utcnow,
onupdate=datetime.utcnow)
+ # Parent-side relationship so a hard-deleted app takes its rollups with it
+ # (the soft-delete purge door cascades through declared relationships).
+ application = db.relationship(
+ 'Application',
+ backref=db.backref('request_metrics', cascade='all, delete-orphan',
+ passive_deletes=True, lazy='select'),
+ )
+
def get_hist(self):
try:
- return [int(n) for n in json.loads(self.latency_hist_json or '[]')]
+ return [int(n) for n in self._json_read('latency_hist_json', [], expect=list)]
except (TypeError, ValueError):
return []
def set_hist(self, hist):
- self.latency_hist_json = json.dumps([int(n) for n in hist])
+ self._json_write('latency_hist_json', [int(n) for n in hist])
def __repr__(self):
return f'<AppRequestMetric app={self.app_id} {self.level} {self.bucket}>'
diff --git a/backend/app/services/request_metrics_service.py b/backend/app/services/request_metrics_service.py
index 7ee5ca03..82f133c5 100644
--- a/backend/app/services/request_metrics_service.py
+++ b/backend/app/services/request_metrics_service.py
@@ -369,18 +369,11 @@ class RequestMetricsService:
# Read side
# ------------------------------------------------------------------ #
- @classmethod
- def series_for_user(cls, user, app_id, period='24h'):
- """:meth:`series` scoped to apps ``user`` can see. A missing or foreign
- app is the same 404, so the route can't be used to probe app ids."""
- from app.exceptions import NotFoundError
+ @staticmethod
+ def live_app(app_id):
+ """The live (not soft-deleted) application, or None."""
from app.models.application import Application
- from app.services.resource_grant_service import ResourceGrantService
-
- app_row = Application.query_active().filter_by(id=app_id).first()
- if app_row is None or not ResourceGrantService.can_access_app(user, app_row):
- raise NotFoundError('Not found')
- return cls.series(app_id, period=period)
+ return Application.query_active().filter_by(id=app_id).first()
@classmethod
def series(cls, app_id, period='24h', now=None):