Handle concurrent API state mutations
This commit is contained in:
1 parent
ae0f6ff8e4
commit
1fad756db7
1 file changed
+16
-2
@@ -96,6 +96,20 @@ def _api_plain(value, depth=0):
|
||||
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):
|
||||
"""Normalize snapshots for JSON, including non-string dictionary keys."""
|
||||
if depth > 12:
|
||||
@@ -104,7 +118,7 @@ def _api_json_safe(value, depth=0):
|
||||
return value
|
||||
if isinstance(value, dict):
|
||||
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)):
|
||||
return [_api_json_safe(item, depth + 1) for item in value]
|
||||
|
||||
@@ -140,7 +154,7 @@ def _api_json_default(value):
|
||||
|
||||
@app.route('/api/global')
|
||||
def api_global():
|
||||
snapshot = dict(g)
|
||||
snapshot = dict(_api_dict_items(g))
|
||||
job = g.get('job')
|
||||
job_state = getattr(job, 'state', None) if job else None
|
||||
snapshot['job_state'] = getattr(job_state, '__name__', 'idle')
|
||||
|
||||
Reference in new issue
Block a user