fix: centralize native dispatch and itemize retained session release

This commit is contained in:
阿白叔 committed 2026-11-09 14:03:07 +08:00
1 parent 60101b7195
commit 306aa5c544
4 files changed
+149 -29

No files matched your search

+8 -2
View File
@@ -528,7 +528,8 @@ def release_retained_library(library, evidence_dir, *, block_name=None):
"""
import win32con, win32event, win32file
library = Path(library).resolve(strict=True)
from .session_record import retained_session_snapshot, acknowledge_library_release
from .session_record import (retained_session_snapshot, acknowledge_library_release,
reconciled_retained_sessions)
retained = retained_session_snapshot(library)
evidence = Path(evidence_dir).resolve()
if evidence.is_relative_to(library.parent) or library.parent.is_relative_to(evidence):
@@ -581,10 +582,15 @@ def release_retained_library(library, evidence_dir, *, block_name=None):
raise LibraryBusy('释放检查期间协调检查点变化,保留原文件。')
root = evidence/('release-' + uuid4().hex)
root.mkdir(parents=True, exist_ok=False)
reconciled_sessions = reconciled_retained_sessions(retained, block_name=scoped)
reconciled_blocks = sorted({item['block_name'] for item in (*reconciled, *reconciled_sessions)
if item.get('block_name')})
record = {'library': str(library), 'status': 'RELEASE_CONFIRMED', **proof,
'requested_block_name': block_name, 'proof_scope': 'BLOCK' if scoped else 'LIBRARY',
'proof_block_name': scoped, 'reconciled_checkpoints': reconciled,
'reconciled_foreign_blockers': foreign,
'reconciled_foreign_blockers': sorted(set(foreign) | {
block for block in reconciled_blocks if block_name and block != block_name}),
'reconciled_blocks': reconciled_blocks, 'reconciled_sessions': reconciled_sessions,
'unknown_checkpoint_archived': unknown,
'data_recovery_confirmed': False, 'evidence_path': str(root/'release.json')}
(root/'release.json').write_text(json.dumps(record, ensure_ascii=False, indent=2), encoding='utf-8')
+20 -23
View File
@@ -835,10 +835,11 @@ def _probe_add_dialog_impl(app, job, desktop, owned_pids, root, *, library=None)
_write_json(root/'native-add-log-baseline.json', log_baseline)
observed_failures = {}
_require_add_supervisor(job, root)
from .session_record import update_worker_state
update_worker_state(job, 'NATIVE_CALL', required=True)
job['_native_add_pending'] = True
win32gui.PostMessage(ok, win32con.BM_CLICK, 0, 0)
from .session_record import dispatch_native, update_worker_state
def submit_add():
job['_native_add_pending'] = True
win32gui.PostMessage(ok, win32con.BM_CLICK, 0, 0)
dispatch_native(job, submit_add, asynchronous=True, required=True)
success = None
while time.monotonic() < deadline:
pythoncom.PumpWaitingMessages()
@@ -1106,9 +1107,10 @@ def _catalog_com(job, root):
watcher = None
try:
_require_management_continuation(job, root)
from .session_record import update_worker_state
update_worker_state(job, 'NATIVE_CALL')
app = win32com.client.DispatchEx('LibraryManager.Application')
from .session_record import dispatch_native, update_worker_state
# Keep the launch pending until its exact native identity is recorded.
app = dispatch_native(job, lambda: win32com.client.DispatchEx('LibraryManager.Application'),
asynchronous=True)
app.Visible = True
processes = _process_details('LibraryManager.exe')
owned_pids.update(int(p[0]) for p in processes)
@@ -1124,15 +1126,14 @@ def _catalog_com(job, root):
if job['operation'] in ('probe_create_add', 'probe_create'):
target = prepare_probe_library(job, root)
_require_management_continuation(job, root)
update_worker_state(job, 'NATIVE_CALL')
library = app.CreateLibrary(str(target), 1)
library = dispatch_native(job, lambda: app.CreateLibrary(str(target), 1), asynchronous=True)
_write_json(root.parent/'probe-owner.json', {'library': str(target), 'token': job['probe_token']})
else:
if job['operation'] == 'probe_readd':
validate_probe_readd(job, root)
_require_management_continuation(job, root)
update_worker_state(job, 'NATIVE_CALL')
library = app.OpenLibrary(str(absolute_preserving_drive(job['library'])))
library = dispatch_native(job, lambda: app.OpenLibrary(str(absolute_preserving_drive(job['library']))),
asynchronous=True)
update_worker_state(job, 'POSTCALL')
if refused:
raise RuntimeError('目录读取需要升级中心库或选择流程;已拒绝,目标未获准自动升级。')
@@ -1142,12 +1143,10 @@ def _catalog_com(job, root):
if int(library.FlowType) != 1:
raise RuntimeError('Native Add requires the DxDesigner Logical-Physical library flow.')
_probe_add_dialog(app, job, desktop, owned_pids, root, library=library)
update_worker_state(job, 'CLOSING')
library.Close()
dispatch_native(job, lambda: library.Close(), phase='CLOSING')
library = None
_require_management_continuation(job, root)
update_worker_state(job, 'NATIVE_CALL')
library = app.OpenLibrary(str(absolute_preserving_drive(job['library'])))
library = dispatch_native(job, lambda: app.OpenLibrary(str(absolute_preserving_drive(job['library']))))
if (library is None or Path(str(library.FullName)).resolve() != Path(job['library']).resolve()
or int(library.FlowType) != 1):
raise RuntimeError('Native Add reopen did not confirm the exact library and flow.')
@@ -1189,16 +1188,14 @@ def _catalog_com(job, root):
finally:
if library is not None and not job.get('_native_add_pending'):
try:
update_worker_state(job, 'CLOSING')
library.Close()
dispatch_native(job, lambda: library.Close(), phase='CLOSING')
except Exception as error:
result['close_detail'] = str(error)
result['close_exception'] = _exception_details(error)
library = None
if app is not None and not job.get('_native_add_pending'):
try:
update_worker_state(job, 'CLOSING')
app.Quit()
dispatch_native(job, lambda: app.Quit(), phase='CLOSING')
except Exception as error:
result['quit_detail'] = str(error)
result['quit_exception'] = _exception_details(error)
@@ -1266,12 +1263,11 @@ def management_worker_main(request_path):
_write_json(root/'command.json', command)
with (root/'native-output.txt').open('wb') as output:
_require_management_continuation(job, root)
from .session_record import update_worker_state
update_worker_state(job, 'NATIVE_CALL')
from .session_record import dispatch_native, update_worker_state
result['safe_to_continue'] = False
try:
process = subprocess.Popen(command, stdout=output, stderr=subprocess.STDOUT,
creationflags=subprocess.CREATE_NO_WINDOW)
process = dispatch_native(job, lambda: subprocess.Popen(command, stdout=output,
stderr=subprocess.STDOUT, creationflags=subprocess.CREATE_NO_WINDOW), asynchronous=True)
except (FileNotFoundError, PermissionError):
result['safe_to_continue'] = True
raise
@@ -1292,6 +1288,7 @@ def management_worker_main(request_path):
except subprocess.TimeoutExpired:
continue
result['wait_exceeded'] = True
update_worker_state(job, 'POSTCALL')
result.update(safe_to_continue=True, exit_code=code)
text = (root/'native-output.txt').read_bytes().decode('mbcs', errors='replace')
result.update(success=removal_output_ok(code, text, job['name'], job['partition']),
+30 -4
View File
@@ -32,24 +32,36 @@ def library_available(library):
def retained_session_snapshot(library):
key = _library_key(library)
with _observer_guard:
return {path: (aliases, _retained_results.get(path, {}).get('block'))
return {path: (aliases, _retained_results.get(path, {}).get('block'),
_retained_results.get(path, {}).get('operation_id'))
for path, aliases in _retained_libraries.items() if key in aliases}
def reconciled_retained_sessions(snapshot, *, block_name=None):
with _observer_guard:
return [{'path': path, 'block_name': block, 'operation_id': operation_id}
for path, (aliases, block, operation_id) in snapshot.items()
if _retained_libraries.get(path) is aliases
and _retained_results.get(path, {}).get('operation_id') == operation_id
and (block_name is None or block == block_name)]
def acknowledge_library_release(proof, snapshot, *, block_name=None):
"""Called under fresh proof handles; never clear a newer handoff."""
if proof.get('status') != 'RELEASE_CONFIRMED':
return
key = _library_key(proof['library'])
with _observer_guard:
records = [dict(_retained_results.get(path, {}), path=path)
for path, (aliases, block) in snapshot.items()
records = [dict(path=path, operation_id=operation_id)
for path, (aliases, block, operation_id) in snapshot.items()
if key in aliases and _retained_libraries.get(path) is aliases
and _retained_results.get(path, {}).get('operation_id') == operation_id
and (block_name is None or block == block_name)]
record_session_release(proof, records)
with _observer_guard:
for path, (aliases, block) in snapshot.items():
for path, (aliases, block, operation_id) in snapshot.items():
if (key in aliases and _retained_libraries.get(path) is aliases
and _retained_results.get(path, {}).get('operation_id') == operation_id
and (block_name is None or block == block_name)):
_retained_libraries.pop(path, None)
_retained_results.pop(path, None)
@@ -95,6 +107,7 @@ def register_worker_session(worker, job):
def update_worker_state(job, phase, *, identities=(), write_outcome=None, required=False):
"""required controls journal I/O; a supervisor-loss dispatch veto always raises."""
if not job.get('session_record_path'):
if required:
raise ValueError('原生写入缺少会话记录位置,未提交新的调用')
@@ -123,6 +136,19 @@ def update_worker_state(job, phase, *, identities=(), write_outcome=None, requir
return False
def dispatch_native(job, call, *, phase='NATIVE_CALL', asynchronous=False, required=False):
"""Reserve the native call before dispatch; asynchronous results require an explicit acknowledgment."""
update_worker_state(job, phase, required=required)
try:
result = call()
except BaseException:
update_worker_state(job, 'UNCONFIRMED')
raise
if not asynchronous:
update_worker_state(job, 'POSTCALL')
return result
def process_identity(pid):
from .residual_sessions import _process_handle, _handle_identity, _force_ownership
with _process_handle(pid) as handle: