"""Close only an idle document whose native identity was already established.""" import json import os from pathlib import Path import time def close_failed_document(job, *, emit=lambda **event: None, timeout_seconds=30): from .desktop_worker import launch_save_helper root = Path(job['root']) log_path = root/'failure-close.log' command = [str(Path(os.environ.get('WINDIR', r'C:\Windows'))/'SysWOW64/cscript.exe'), '//nologo', str(Path(__file__).with_name('close_failed_block.vbs')), job['project'], Path(job['pcb']).name] with log_path.open('w', encoding='utf-8') as log: process = launch_save_helper(command, stdout=log, stderr=log) emit(stage='failure_close_started', helper_pid=process.pid) deadline = time.monotonic()+max(.1, float(timeout_seconds)) while process.poll() is None and time.monotonic() < deadline: time.sleep(.2) # A slow native Close can still be flushing. Retain the helper as well as # PCB/iCDB; never force it to abandon the native call at this deadline. text = log_path.read_text('utf-8', errors='replace') result = {'status': ('CLOSED' if process.poll() == 0 and all(marker in text.splitlines() for marker in ('FAILURE_CLOSE_OK', 'FAILURE_QUIT_OK')) else 'RETAINED' if process.poll() is None else 'UNCONFIRMED'), 'helper_pid': process.pid, 'returncode': process.poll(), 'log': str(log_path)} (root/'failure-close.json').write_text(json.dumps(result, indent=2), encoding='utf-8') emit(stage='failure_close_result', **result) return result