add safety checks and debug logging to period time calculations
This commit adds logging infrastructure and safety checks to prevent time adjustment overflows in get_period_totals(). Includes early return for empty results and detailed debug logging for troubleshooting period calculations. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
@@ -1,10 +1,15 @@
|
||||
from collections import Counter, defaultdict
|
||||
from datetime import datetime, timedelta
|
||||
from pprint import pprint
|
||||
import logging
|
||||
|
||||
from pymongo import MongoClient
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
# Setup logging for debugging
|
||||
logging.basicConfig(level=logging.DEBUG)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
timezone = ZoneInfo("America/Argentina/Buenos_Aires")
|
||||
utctz = ZoneInfo("UTC")
|
||||
|
||||
@@ -266,6 +271,10 @@ def get_period_totals(start, end, task=None):
|
||||
|
||||
aux_results = list(switches.aggregate(pipeline_before_after))
|
||||
|
||||
# Safety check: if aux_results is empty, return early with no data
|
||||
if not aux_results:
|
||||
return [{"ws": "No Data", "total": ""}]
|
||||
|
||||
bfirst = aux_results[0]["before_first"]
|
||||
|
||||
if bfirst:
|
||||
@@ -279,14 +288,30 @@ def get_period_totals(start, end, task=None):
|
||||
rows = []
|
||||
active_vs_idle = {"Active": 0, "Idle": 0}
|
||||
|
||||
# Debug logging
|
||||
logger.debug(f"Processing results for period {start} to {end}")
|
||||
logger.debug(f"bfirst workspace: {bfirst['workspace'] if bfirst else 'None'}")
|
||||
logger.debug(f"ldoc workspace: {ldoc['workspace']}")
|
||||
|
||||
for result in results:
|
||||
original_total = result["total"]
|
||||
|
||||
if bfirst:
|
||||
if result["_id"] == bfirst["workspace"]:
|
||||
result["total"] -= start_delta
|
||||
# Safety: ensure start_delta doesn't exceed total
|
||||
adjustment = min(start_delta, result["total"])
|
||||
result["total"] -= adjustment
|
||||
logger.debug(f"{result['_id']}: adjusted start by -{adjustment}s (was {original_total}s, now {result['total']}s)")
|
||||
|
||||
if end < now():
|
||||
if result["_id"] == ldoc["workspace"]:
|
||||
result["total"] -= ldoc["delta"] - end_delta
|
||||
# Safety: ensure we don't subtract more than the total
|
||||
adjustment = ldoc["delta"] - end_delta
|
||||
safe_adjustment = min(adjustment, result["total"])
|
||||
result["total"] -= safe_adjustment
|
||||
logger.debug(f"{result['_id']}: adjusted end by -{safe_adjustment}s (was {original_total}s, now {result['total']}s)")
|
||||
|
||||
logger.debug(f"{result['_id']}: final total = {result['total']}s ({convert_seconds(result['total'])})")
|
||||
|
||||
for result in results:
|
||||
if result["total"] > 0:
|
||||
|
||||
Reference in New Issue
Block a user