Handle concurrent API state mutations

This commit is contained in:
Tanner committed 2026-11-14 17:09:43 +00:00
1 parent ae0f6ff8e4
commit 1fad756db7
1 file changed
+16 -2
+16 -2
View File
@@ -96,6 +96,20 @@ def _api_plain(value, depth=0):
return str(value) return str(value)
def _api_dict_items(value):
"""Take a best-effort mapping snapshot while live state may be changing."""
for _ in range(3):
try:
return list(value.items())
except RuntimeError:
# Network callbacks can mutate these dictionaries between API polls.
pass
try:
return list(value.copy().items())
except (RuntimeError, AttributeError):
return []
def _api_json_safe(value, depth=0): def _api_json_safe(value, depth=0):
"""Normalize snapshots for JSON, including non-string dictionary keys.""" """Normalize snapshots for JSON, including non-string dictionary keys."""
if depth > 12: if depth > 12:
@@ -104,7 +118,7 @@ def _api_json_safe(value, depth=0):
return value return value
if isinstance(value, dict): if isinstance(value, dict):
return {str(key): _api_json_safe(item, depth + 1) return {str(key): _api_json_safe(item, depth + 1)
for key, item in value.items()} for key, item in _api_dict_items(value)}
if isinstance(value, (list, tuple, set)): if isinstance(value, (list, tuple, set)):
return [_api_json_safe(item, depth + 1) for item in value] return [_api_json_safe(item, depth + 1) for item in value]
@@ -140,7 +154,7 @@ def _api_json_default(value):
@app.route('/api/global') @app.route('/api/global')
def api_global(): def api_global():
snapshot = dict(g) snapshot = dict(_api_dict_items(g))
job = g.get('job') job = g.get('job')
job_state = getattr(job, 'state', None) if job else None job_state = getattr(job, 'state', None) if job else None
snapshot['job_state'] = getattr(job_state, '__name__', 'idle') snapshot['job_state'] = getattr(job_state, '__name__', 'idle')