From 1fad756db72e7cf36c90e02f56a2ca49fc98cdd1 Mon Sep 17 00:00:00 2001 From: Tanner Date: Sat, 14 Nov 2026 17:09:43 +0000 Subject: [PATCH] Handle concurrent API state mutations --- mosfet.py | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/mosfet.py b/mosfet.py index 37cbd9d..827782f 100644 --- a/mosfet.py +++ b/mosfet.py @@ -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')