session_worker_spawn.py 1.2 KB

123456789101112131415161718192021222324252627282930313233343536
  1. """Cancellation-safe handoff of a managed subprocess acquired off the owner loop."""
  2. import asyncio
  3. import threading
  4. async def acquire_process(spawn, *args, **kwargs):
  5. from gateway.session_managed_worker import ManagedWorker
  6. lock = threading.Lock()
  7. state = {'cancelled': False, 'process': None}
  8. def create():
  9. process = spawn(*args, **kwargs)
  10. with lock:
  11. cancelled = state['cancelled']
  12. if not cancelled:
  13. state['process'] = process
  14. if cancelled:
  15. ManagedWorker(process).close()
  16. return process
  17. pending = asyncio.create_task(asyncio.to_thread(create))
  18. try:
  19. process = await asyncio.shield(pending)
  20. with lock:
  21. state['process'] = None
  22. return process
  23. except asyncio.CancelledError:
  24. with lock:
  25. state['cancelled'] = True
  26. process = state['process']
  27. state['process'] = None
  28. if process is not None:
  29. await asyncio.to_thread(ManagedWorker(process).close)
  30. # If creation still runs, its thread owns cleanup; consume an eventual spawn exception.
  31. pending.add_done_callback(lambda task: task.exception() if not task.cancelled() else None)
  32. raise