Connect production replacement and recovery to owned private CAD sessions

This commit is contained in:
阿白叔 committed 2026-10-15 11:16:11 +08:00
1 parent f26e868bfc
commit fee1aff557
13 files changed
+553 -20

No files matched your search

+31 -3
View File
@@ -156,7 +156,15 @@ Sub QPMain()
If QP_Fso.FileExists(QP_Fso.BuildPath(QP_Root, "recovery.request")) Then
If Trim(QPReadUtf8(QP_Fso.BuildPath(QP_Root, "recovery.request"))) <> QP_CurrentJobId Then _
Err.Raise vbObjectError + 864, "QuickPartReplace.Recovery", "recovery job mismatch"
If Len(CStr(CreateObject("WScript.Shell").Environment("PROCESS")("DXPART_DESKTOP"))) > 0 Then QP_BatchMode = True
QPRecoverSavedJob Command, SnapshotPath
If QP_BatchMode Then
If QP_BatchState = "restored_ok" Then
QPFinishBatchItem
Else
QP_BatchMode = False
End If
End If
QPProgress "finished", 1, 1
Exit Sub
End If
@@ -191,12 +199,13 @@ Sub QPBootstrapSession()
QPProgress "session_startup", 0, 0
TargetPath = QPConfirmedProjectPath()
If QP_Fso.FileExists(QP_Fso.BuildPath(QP_Root, "recovery.request")) Then
If QPDesignerProcessCount() <> 0 Then _
If Len(CStr(CreateObject("WScript.Shell").Environment("PROCESS")("DXPART_DESKTOP"))) = 0 And QPDesignerProcessCount() <> 0 Then _
Err.Raise vbObjectError + 864, "QuickPartReplace.Recovery", _
"recovery requires a fresh CAD session; close existing DxDesigner first without discarding wanted edits"
If Len(CStr(CreateObject("WScript.Shell").Environment("PROCESS")("DXPART_DESKTOP"))) > 0 Then QP_BatchMode = True
End If
If Len(TargetPath) = 0 Then
Set QP_App = GetObject(, "Viewdraw.Application")
Set QP_App = QPAttachOrStart(QPDesignerProcessCount())
Else
Set QP_App = QPAttachOrStart(QPDesignerProcessCount())
If QP_SessionMode Then WScript.ConnectObject QP_App, "QPEvent_"
@@ -534,7 +543,24 @@ Function QPTryAttach()
End Function
Function QPAttachOrStart(ByVal ProcessCount)
Dim App, Attempt
Dim App, Attempt, Environment, PrivateDesktop, ExpectedGuid
Set Environment = CreateObject("WScript.Shell").Environment("PROCESS")
PrivateDesktop = CStr(Environment("DXPART_DESKTOP"))
ExpectedGuid = CStr(Environment("DXPART_CAD_GUID"))
If Len(PrivateDesktop) = 0 And (Len(ExpectedGuid) > 0 Or Len(CStr(Environment("DXPART_CAD_PID"))) > 0 Or _
Len(CStr(Environment("DXPART_SESSION_TOKEN"))) > 0) Then _
Err.Raise vbObjectError + 874, "QuickPartReplace.PrivateDesktop", "incomplete private CAD identity"
If Len(PrivateDesktop) > 0 Then
If Len(ExpectedGuid) = 0 Or Len(CStr(Environment("DXPART_CAD_PID"))) = 0 Or _
Len(CStr(Environment("DXPART_SESSION_TOKEN"))) <> 32 Then _
Err.Raise vbObjectError + 874, "QuickPartReplace.PrivateDesktop", "incomplete private CAD identity"
Set App = QPTryAttach()
If App Is Nothing Then Err.Raise vbObjectError + 874, "QuickPartReplace.PrivateDesktop", "owned private CAD is unavailable"
If LCase(CStr(App.Guid())) <> LCase(ExpectedGuid) Then _
Err.Raise vbObjectError + 874, "QuickPartReplace.PrivateDesktop", "private CAD GUID mismatch; no project was changed"
Set QPAttachOrStart = App
Exit Function
End If
If ProcessCount > 1 Then _
Err.Raise vbObjectError + 851, "QuickPartReplace.Session", "multiple DxDesigner instances; no project was changed"
Set App = QPTryAttach()
@@ -910,6 +936,8 @@ Sub QPFinishBatchItem()
QPWriteStatus QP_Root, QP_CurrentJobId, FinalState, "session_verified", QP_BatchMessage
QPWriteUtf8 QP_Fso.BuildPath(QP_Root, "project-session-result.tsv"), _
QP_SessionToken & vbTab & QP_CurrentJobId & vbTab & FinalState & vbTab & "session_verified"
ElseIf QP_Fso.FileExists(QP_Fso.BuildPath(QP_Root, "recovery.request")) Then
QPWriteStatus QP_Root, QP_CurrentJobId, "restored_ok", "recovery_saved_verified", QP_BatchMessage
Else
QPWriteStatus QP_Root, QP_CurrentJobId, FinalState, "batch_closed", QP_BatchMessage
End If
@@ -35,6 +35,9 @@ def _parse_arguments(argv: Sequence[str] | None) -> argparse.Namespace:
parser.add_argument("--native-helper", action="store_true", help=argparse.SUPPRESS)
parser.add_argument("--snapshot", type=Path, help=argparse.SUPPRESS)
parser.add_argument("--sceneos-cli", action="store_true", help=argparse.SUPPRESS)
parser.add_argument('--private-cad-action', choices=('probe', 'quit'), help=argparse.SUPPRESS)
parser.add_argument('--private-cad-evidence', type=Path, help=argparse.SUPPRESS)
parser.add_argument('--private-cad-pid', type=int, help=argparse.SUPPRESS)
return parser.parse_args(list(argv) if argv is not None else None)
@@ -91,6 +94,11 @@ def _flush(context: LoggingContext) -> None:
def main(argv: Sequence[str] | None = None) -> int:
"""Run the Qt shell, returning a conventional process status code."""
arguments = _parse_arguments(argv)
if arguments.private_cad_action:
if arguments.private_cad_evidence is None or arguments.private_cad_pid is None:
return 2
from .isolated_cad import native_action
return native_action(arguments.private_cad_action, arguments.private_cad_evidence, arguments.private_cad_pid)
if arguments.native_helper:
if arguments.snapshot is None:
return 2
@@ -0,0 +1,68 @@
"""Identity certificate shared by the private desktop worker and native helper."""
from dataclasses import dataclass
import ctypes
from ctypes import wintypes
import os
import re
def current_desktop_name():
user = ctypes.WinDLL('user32', use_last_error=True)
kernel = ctypes.WinDLL('kernel32', use_last_error=True)
user.GetThreadDesktop.argtypes = [wintypes.DWORD]
user.GetThreadDesktop.restype = wintypes.HANDLE
user.GetUserObjectInformationW.argtypes = [wintypes.HANDLE, ctypes.c_int, ctypes.c_void_p,
wintypes.DWORD, ctypes.POINTER(wintypes.DWORD)]
desktop = user.GetThreadDesktop(kernel.GetCurrentThreadId())
value, required = ctypes.create_unicode_buffer(256), wintypes.DWORD()
if not user.GetUserObjectInformationW(desktop, 2, value, ctypes.sizeof(value), ctypes.byref(required)):
raise ctypes.WinError(ctypes.get_last_error())
return value.value
def window_pid(handle):
import win32process
return win32process.GetWindowThreadProcessId(handle)[1]
@dataclass(frozen=True, slots=True)
class CadBinding:
desktop: str
pid: int
guid: str
token: str
@classmethod
def from_environment(cls, environment=None):
environment = os.environ if environment is None else environment
fields = ('DXPART_DESKTOP', 'DXPART_CAD_PID', 'DXPART_CAD_GUID', 'DXPART_SESSION_TOKEN')
values = [environment.get(field, '') for field in fields]
if not any(values):
return None
if not all(values):
raise ValueError('incomplete private CAD identity')
desktop, pid, guid, token = values
if not re.fullmatch(r'dx-[A-Za-z0-9-]{1,80}', desktop) or int(pid) <= 0:
raise ValueError('invalid private CAD desktop or PID')
if not re.fullmatch(r'[0-9a-f]{32}', token):
raise ValueError('invalid private CAD session token')
return cls(desktop, int(pid), guid, token)
def environment(self):
return dict(os.environ, DXPART_DESKTOP=self.desktop, DXPART_CAD_PID=str(self.pid),
DXPART_CAD_GUID=self.guid, DXPART_SESSION_TOKEN=self.token)
def verify_application(app, binding=None, *, require_view=True):
binding = CadBinding.from_environment() if binding is None else binding
if binding is None:
return None
if current_desktop_name() != binding.desktop:
raise ValueError('CAD helper is not running on its owned desktop')
if str(app.Guid()).casefold() != binding.guid.casefold():
raise ValueError('CAD COM GUID does not match its owned session')
if require_view:
handle = int(app.ActiveViewHandle)
if not handle or window_pid(handle) != binding.pid:
raise ValueError('CAD view PID does not match its owned session')
return binding
@@ -0,0 +1,210 @@
"""Start the real CAD and its automation on one owned Windows desktop."""
from dataclasses import asdict
import json
import os
from pathlib import Path
import subprocess
import sys
import time
from uuid import uuid4
from .cad_identity import CadBinding, current_desktop_name, verify_application
from .isolated_desktop import PrivateDesktop
from .worker_monitor import WorkerMonitorError
def _helper_command(action, evidence, pid):
if getattr(sys, 'frozen', False):
return (sys.executable, '--private-cad-action', action, '--private-cad-evidence', str(evidence),
'--private-cad-pid', str(pid))
return (sys.executable, '-m', __name__, action, str(evidence), str(pid))
def _child_environment(environment):
environment = dict(environment)
if not getattr(sys, 'frozen', False):
environment['PYTHONPATH'] = str(Path(__file__).resolve().parents[2]) + os.pathsep + environment.get('PYTHONPATH', '')
return environment
def _designer_executable():
import winreg
with winreg.OpenKey(winreg.HKEY_CLASSES_ROOT, r'Viewdraw.Application\CLSID') as key:
clsid = winreg.QueryValue(key, None)
with winreg.OpenKey(winreg.HKEY_CLASSES_ROOT, rf'CLSID\{clsid}\LocalServer32',
0, winreg.KEY_READ | winreg.KEY_WOW64_32KEY) as key:
command = winreg.QueryValue(key, None)
# Mentor registers an absolute LocalServer32 path, sometimes quoted.
command = command.strip()
executable = command.split('"', 2)[1] if command.startswith('"') else command[:command.lower().index('.exe') + 4]
path = Path(executable)
if path.name.casefold() != 'viewdraw.exe' or not path.is_file():
raise WorkerMonitorError('registered DxDesigner executable is unavailable')
return path
class IsolatedCadSession:
"""The supervisor never attaches to COM on the user's input desktop."""
def __init__(self, root, *, abort_event=None):
self.root = Path(root)
self.token = uuid4().hex
self.desktop = PrivateDesktop('dx-' + self.token, enabled=True)
self.cad = None
self.binding = None
self.started = time.monotonic()
self.abort_event = abort_event
self.record = {'desktop': self.desktop.name, 'token': self.token, 'state': 'starting'}
def _record(self, **values):
self.record.update(values)
self.root.mkdir(parents=True, exist_ok=True)
target = self.root / 'private-desktop.json'
temporary = target.with_suffix('.tmp')
temporary.write_text(json.dumps(self.record, ensure_ascii=False, indent=2), encoding='utf-8')
temporary.replace(target)
def __enter__(self):
try:
self._check_abort()
self.desktop.__enter__()
self.cad = self.desktop.start_process((str(_designer_executable()),))
self._record(cad_pid=self.cad.pid)
bootstrap = self.root / ('cad-binding-' + self.token + '.json')
environment = dict(os.environ, DXPART_DESKTOP=self.desktop.name,
DXPART_CAD_PID=str(self.cad.pid), DXPART_SESSION_TOKEN=self.token)
environment.pop('DXPART_CAD_GUID', None)
probe = self.desktop.start_process(_helper_command('probe', bootstrap, self.cad.pid), env=_child_environment(environment),
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
try:
deadline = time.monotonic() + 75
while probe.poll() is None:
self._check_abort()
if time.monotonic() >= deadline:
raise WorkerMonitorError('private CAD bootstrap timed out')
time.sleep(0.05)
code = probe.poll()
if code:
raise WorkerMonitorError('private CAD startup identity failed: ' + probe.stderr.read().decode('utf-8', errors='replace'))
finally:
probe.close()
result = json.loads(bootstrap.read_text(encoding='utf-8'))
self.binding = CadBinding(**result)
if (self.binding.pid, self.binding.desktop, self.binding.token) != (self.cad.pid, self.desktop.name, self.token):
raise WorkerMonitorError('private CAD bootstrap returned a foreign identity')
self._record(state='ready', guid=self.binding.guid, startup_seconds=time.monotonic() - self.started)
return self
except Exception as error:
try:
self.desktop.close()
except Exception as failure:
self._uncertain('startup cleanup failed: ' + str(failure))
raise WorkerMonitorError('private CAD startup cleanup requires reconciliation: ' + str(failure)) from error
self._record(state='released', clean=False, startup_error=str(error))
raise
def _check_abort(self):
if self.abort_event is not None and self.abort_event.is_set():
raise WorkerMonitorError('private CAD startup was cancelled before execution')
def start_worker(self, command, **options):
if self.binding is None or self.cad.poll() is not None:
raise WorkerMonitorError('owned private CAD is unavailable')
return self.desktop.start_process(command, env=_child_environment(self.binding.environment()), **options)
def __exit__(self, error_type, error, traceback):
closing_started = time.monotonic()
cleanup_error = None
try:
self._record(state='closing')
if error is not None:
self._uncertain(str(error))
if self.cad is not None and self.cad.poll() is not None:
raise WorkerMonitorError('owned CAD exited before the authorized quit request')
if self.cad is not None and self.binding is not None:
closing = self.desktop.start_process(_helper_command('quit', self.root / 'private-desktop.json', self.cad.pid),
env=_child_environment(self.binding.environment()), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
try:
if closing.wait(timeout=20):
raise WorkerMonitorError('owned CAD refused orderly exit: ' + closing.stderr.read().decode('utf-8', errors='replace'))
if self.cad.wait(timeout=15) != 0:
raise WorkerMonitorError('owned CAD returned a nonzero exit code after quit')
finally:
closing.close()
except Exception as failure:
cleanup_error = failure
self._uncertain(str(failure))
finally:
try:
self.desktop.close()
self._record(state='released', clean=error is None and cleanup_error is None,
shutdown_seconds=time.monotonic() - closing_started)
except Exception as failure:
self._uncertain(str(failure))
cleanup_error = failure
if cleanup_error is not None:
raise WorkerMonitorError('private CAD cleanup requires reconciliation: ' + str(cleanup_error)) from cleanup_error
def _uncertain(self, message):
from .quick_run import _write_uncertain_flag
_write_uncertain_flag(self.root / 'uncertain.flag', 'private_desktop: ' + message)
self._record(state='uncertain', error=message)
def run_isolated_process(command, timeout, *, abort_event=None):
from .worker_monitor import run_monitored_process
with IsolatedCadSession(Path(command[3]), abort_event=abort_event) as session:
return run_monitored_process(command, timeout, abort_event=abort_event, process_factory=session.start_worker)
def native_action(action, evidence, expected_pid):
"""Runs in a child created with lpDesktop, never in a Python thread switch."""
import pythoncom
import win32com.client
import win32gui
import win32process
pythoncom.CoInitialize()
try:
desktop = os.environ.get('DXPART_DESKTOP', '')
token = os.environ.get('DXPART_SESSION_TOKEN', '')
if not desktop.startswith('dx-') or current_desktop_name() != desktop:
raise ValueError('CAD bootstrap is not on the requested private desktop')
expected_pid = int(expected_pid)
if expected_pid <= 0 or str(expected_pid) != os.environ.get('DXPART_CAD_PID'):
raise ValueError('invalid CAD bootstrap PID')
deadline = time.monotonic() + 60
while True:
try:
app = win32com.client.GetActiveObject('Viewdraw.Application')
break
except pythoncom.com_error:
if action != 'probe' or time.monotonic() >= deadline:
raise
time.sleep(0.2)
if action == 'probe':
cad_windows = []
win32gui.EnumWindows(lambda handle, _: cad_windows.append(handle)
if win32process.GetWindowThreadProcessId(handle)[1] == expected_pid else None, None)
if not cad_windows:
raise ValueError('owned CAD has no windows on its private desktop')
# ROT is scoped to this desktop. Certify the freshly launched instance
# here; every subsequent VBS/helper attachment checks its GUID.
binding = CadBinding(desktop, expected_pid, str(app.Guid()), token)
verify_application(app, binding, require_view=False)
Path(evidence).write_text(json.dumps(asdict(binding)), encoding='utf-8')
elif action == 'quit':
binding = CadBinding.from_environment()
# ActiveViewHandle can retain a destroyed/reused HWND after closing
# the last project. The private ROT/GUID binds this empty instance.
verify_application(app, binding, require_view=False)
if app.GetProjectData().GetProjectFilePath():
raise ValueError('owned CAD still has a project open; no implicit save or discard')
app.Quit()
else:
raise ValueError('unknown private CAD action')
finally:
pythoncom.CoUninitialize()
return 0
if __name__ == '__main__':
raise SystemExit(native_action(sys.argv[1], Path(sys.argv[2]), int(sys.argv[3])))
@@ -1,4 +1,4 @@
"""Research-only worker protocol for a single project.
"""Legacy research-only request protocol; production uses isolated_cad.
The worker writes versioned request/evidence files and delegates process
launching to an injected callback. It never attaches to an existing CAD
@@ -88,7 +88,7 @@ class IsolatedDesktopWorker:
*,
evidence_root: Path | None = None,
) -> IsolatedWorkerEvidence:
"""Validate an already-created read-only probe result.
"""Validate an injected callback result; this does not move CAD desktops.
The callback is the only native integration point and must return the
PID and project identity it observed. Tests inject it; production can
@@ -205,6 +205,8 @@ def attach():
api = win32com.client.gencache.EnsureModule(
"{4ADEF4E1-690A-11CE-9261-0020C5E26659}", 0, 1, 0)
app = api.IVdApp(win32com.client.GetActiveObject("Viewdraw.Application")._oleobj_)
from .cad_identity import verify_application
verify_application(app)
return app, api
@@ -226,6 +228,8 @@ def components_on_sheet(app, api):
def check_active_context(app, metadata):
from .cad_identity import verify_application
verify_application(app)
if os.path.normcase(os.path.abspath(app.GetProjectData().GetProjectFilePath())) != os.path.normcase(os.path.abspath(metadata[1])):
raise ValueError("Active project changed")
if f"{app.ActiveView.GetName(0)}:{app.ActiveView.Block.SheetNum}" != metadata[4]:
@@ -21,7 +21,7 @@ class ProjectSessionWorker:
The VBS worker owns CAD. This driver never attaches to COM or terminates CAD.
A separate monitor thread retains the existing idle watchdog and worker job.
"""
def __init__(self, project: Path, root: Path):
def __init__(self, project: Path, root: Path, *, private_desktop=False):
self.project, self.root = Path(project), Path(root)
self.token = uuid4().hex
self._done, self._abort = Event(), Event()
@@ -33,10 +33,15 @@ class ProjectSessionWorker:
self._failure_delivered = False
self._timeout = 150
self.starts = 0
self.private_desktop = private_desktop
def _monitor(self, command, timeout):
try:
self._result = run_monitored_process(command, timeout, abort_event=self._abort)
if self.private_desktop:
from .isolated_cad import run_isolated_process
self._result = run_isolated_process(command, timeout, abort_event=self._abort)
else:
self._result = run_monitored_process(command, timeout, abort_event=self._abort)
except Exception as error:
self._error = error
finally:
@@ -87,16 +92,20 @@ class ProjectSessionWorker:
def close(self):
if self._closed:
return
self._closed = True
try:
if self._thread is None:
self._closed = True
return
if not self._done.is_set():
_write_control(self.root / 'project-session-next.tsv', f'{self.token}\tclose')
if not self._done.wait(min(30, max(10, self._timeout))):
close_grace = 60 if self.private_desktop else min(30, max(10, self._timeout))
if not self._done.wait(close_grace):
self._abort.set()
self._done.wait(10)
if not self._done.wait(30):
raise WorkerMonitorError('owned project cleanup is still pending; retry closing before another task')
self._closed = True
raise WorkerMonitorError('owned project did not acknowledge session closing')
self._closed = True
if self._error is not None:
raise self._error
if self._result.returncode != 0 and not self._failure_delivered:
@@ -109,9 +118,10 @@ class ProjectSessionWorker:
class ProjectSessionScope:
"""One serial task can visit projects, but can hold only one worker at a time."""
def __init__(self, fallback, *, enabled):
def __init__(self, fallback, *, enabled, private_desktop=False):
self.fallback, self.enabled = fallback, enabled
self.worker = None
self.private_desktop = private_desktop
def __enter__(self):
return self
@@ -121,7 +131,7 @@ class ProjectSessionScope:
return self.fallback(command, timeout)
self.prepare(project)
if self.worker is None:
self.worker = ProjectSessionWorker(Path(project), Path(command[3]))
self.worker = ProjectSessionWorker(Path(project), Path(command[3]), private_desktop=self.private_desktop)
return self.worker.run_step(command, timeout)
def prepare(self, project):
@@ -300,7 +300,7 @@ class QuickRunPreparer:
from .worker_monitor import WorkerMonitorError
try:
with ProjectSessionScope(self._process_runner,
enabled=enabled and self._process_runner is _run_process) as scope:
enabled=enabled and self._process_runner is _run_process, private_desktop=True) as scope:
yield scope
except (WorkerMonitorError, subprocess.TimeoutExpired) as error:
_write_uncertain_flag(self._data_root / 'quick-run/uncertain.flag', 'project_session_cleanup')
@@ -323,6 +323,10 @@ class QuickRunPreparer:
uncertain_path = self._data_root / "quick-run" / "uncertain.flag"
if uncertain_path.exists():
raise TaskCenterError("quick_run_uncertain", "a previous quick-run worker timed out or returned an uncorrelated status; reconcile the project before retrying")
if self._process_runner is _run_process and not batch_mode:
from .single_step import prepare_private_single_step
prepare_private_single_step(self, task_id, projects, rules, copy_part_number_to_value)
batch_mode = True
current_root = self._data_root / "quick-run"
if batch_session is None and self.evidence_path(task_id) == current_root and (current_root / "status.tsv").is_file():
recorded = _read_status_details(current_root / "status.tsv")
@@ -1692,9 +1696,9 @@ def _cached_native_helper_launch_arguments(frozen: bool, executable: str) -> tup
def _run_process(command: tuple[str, ...], timeout: int) -> subprocess.CompletedProcess[str]:
from .worker_monitor import run_monitored_process
from .isolated_cad import run_isolated_process
return run_monitored_process(command, timeout)
return run_isolated_process(command, timeout)
def _log_text(value: str) -> str:
@@ -237,7 +237,10 @@ def recover(preparer, task_id, projects, rules, *, copy_part_number_to_value=Fal
raise
progress = preparer.progress(task_id, projects, rules, copy_part_number_to_value=copy_part_number_to_value)
message = ('磁盘工程与替换前快照一致,只读核验工程已关闭,已准备新的执行编号;尚未再次替换,请确认后执行。'
if state == 'retry_ready' else '已核验并恢复本项任务记录;没有重复执行原生替换。若补做了属性恢复,请保存当前工程。')
if state == 'retry_ready' else
'已核验并恢复本项任务记录,属性已保存并重开回读,工程已关闭;没有重复执行原生替换。'
if after[0][2] == 'recovery_saved_verified' else
'已核验并恢复本项任务记录;没有重复执行原生替换。若补做了属性恢复,请保存当前工程。')
return QuickRunStepResult(root / 'QuickPartReplace.vbs', root / 'command.tsv', root / 'status.tsv',
audit / 'worker-output.txt', state, message, progress.next_project_path,
progress.next_old_part_number, progress.next_new_part_number,
@@ -0,0 +1,18 @@
"""Give the legacy single-step entry the same durable private execution boundary."""
from uuid import uuid4
from .errors import TaskCenterError
from .schematic_backup import create_schematic_backup
def prepare_private_single_step(preparer, task_id, projects, rules, copy_part_number_to_value):
progress = preparer.progress(task_id, projects, rules,
copy_part_number_to_value=copy_part_number_to_value)
if progress.queue_complete or progress.next_project_path is None:
raise TaskCenterError('quick_run_complete', 'all replacement rules in this queue are complete')
# Back up before discovery or any CAD activation. A standalone invocation
# has no batch backup coordinator to provide this boundary.
create_schematic_backup(preparer.data_root, progress.next_project_path,
preparer.data_root / 'single-step-backups' / uuid4().hex)
preparer.ensure_batch_handoff(task_id, projects, rules,
copy_part_number_to_value=copy_part_number_to_value)
@@ -157,7 +157,8 @@ class _OwnedWorkers:
self.job.Close()
def run_monitored_process(command: tuple[str, ...], idle_timeout: float, *, abort_event=None) -> subprocess.CompletedProcess[str]:
def run_monitored_process(command: tuple[str, ...], idle_timeout: float, *, abort_event=None,
process_factory=None) -> subprocess.CompletedProcess[str]:
root = Path(command[3])
job_id = command[-1]
token = uuid4().hex
@@ -195,9 +196,14 @@ def run_monitored_process(command: tuple[str, ...], idle_timeout: float, *, abor
output[channel].extend(line[:1024 * 1024 - len(output[channel])])
try:
process = subprocess.Popen((*command, token), stdout=subprocess.PIPE, stderr=subprocess.PIPE,
creationflags=subprocess.CREATE_NO_WINDOW)
owned.assign(process)
if process_factory is None:
process = subprocess.Popen((*command, token), stdout=subprocess.PIPE, stderr=subprocess.PIPE,
creationflags=subprocess.CREATE_NO_WINDOW)
owned.assign(process)
else:
# PrivateDesktop already assigns its suspended process to an owned
# Job before resuming it. Do not reassign it to another Job here.
process = process_factory((*command, token), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
for channel, stream in enumerate((process.stdout, process.stderr)):
thread = threading.Thread(target=read_stream, args=(stream, channel), daemon=True)
thread.start()
@@ -249,3 +255,5 @@ def run_monitored_process(command: tuple[str, ...], idle_timeout: float, *, abor
for thread in threads:
thread.join(0.2)
owned.close()
if process_factory is not None and process is not None:
process.close()
+65
View File
@@ -0,0 +1,65 @@
from types import SimpleNamespace
import pytest
from dx_productivity.trial_task_center import cad_identity as identity
def environment(**changes):
return {'DXPART_DESKTOP': 'dx-test', 'DXPART_CAD_PID': '123',
'DXPART_CAD_GUID': '{owned}', 'DXPART_SESSION_TOKEN': 'a' * 32, **changes}
def test_partial_identity_is_rejected_instead_of_using_interactive_cad():
with pytest.raises(ValueError, match='incomplete'):
identity.CadBinding.from_environment({'DXPART_DESKTOP': 'dx-test'})
def test_identity_checks_desktop_before_reading_com(monkeypatch):
binding = identity.CadBinding.from_environment(environment())
monkeypatch.setattr(identity, 'current_desktop_name', lambda: 'Default')
with pytest.raises(ValueError, match='desktop'):
identity.verify_application(object(), binding)
def test_foreign_com_guid_is_rejected_before_project_access(monkeypatch):
binding = identity.CadBinding.from_environment(environment())
monkeypatch.setattr(identity, 'current_desktop_name', lambda: 'dx-test')
with pytest.raises(ValueError, match='GUID'):
identity.verify_application(SimpleNamespace(Guid=lambda: '{foreign}'), binding)
def test_foreign_view_pid_is_rejected(monkeypatch):
binding = identity.CadBinding.from_environment(environment())
monkeypatch.setattr(identity, 'current_desktop_name', lambda: 'dx-test')
monkeypatch.setattr(identity, 'window_pid', lambda _: 456)
app = SimpleNamespace(Guid=lambda: '{owned}', ActiveViewHandle=7)
with pytest.raises(ValueError, match='PID'):
identity.verify_application(app, binding)
def test_owned_app_matches_certificate_and_window_pid(monkeypatch):
binding = identity.CadBinding.from_environment(environment())
monkeypatch.setattr(identity, 'current_desktop_name', lambda: 'dx-test')
monkeypatch.setattr(identity, 'window_pid', lambda _: 123)
assert identity.verify_application(SimpleNamespace(Guid=lambda: '{owned}', ActiveViewHandle=7), binding) == binding
def test_no_identity_retains_explicit_legacy_helper_compatibility():
assert identity.CadBinding.from_environment({}) is None
def test_closed_project_does_not_treat_stale_view_handle_as_current_pid(monkeypatch):
binding = identity.CadBinding.from_environment(environment())
monkeypatch.setattr(identity, 'current_desktop_name', lambda: 'dx-test')
monkeypatch.setattr(identity, 'window_pid', lambda _: 456)
app = SimpleNamespace(Guid=lambda: '{owned}', ActiveViewHandle=7)
assert identity.verify_application(app, binding, require_view=False) == binding
with pytest.raises(ValueError, match='PID'):
identity.verify_application(app, binding)
@pytest.mark.parametrize('pid', ['0', '-1', 'abc'])
def test_invalid_pid_cannot_become_an_owned_cad(pid):
with pytest.raises(ValueError):
identity.CadBinding.from_environment(environment(DXPART_CAD_PID=pid))
+107
View File
@@ -0,0 +1,107 @@
import io
import json
from pathlib import Path
from threading import Event
from types import SimpleNamespace
import pytest
from dx_productivity.trial_task_center import isolated_cad as runtime
from dx_productivity.trial_task_center.worker_monitor import WorkerMonitorError
def fake_desktop(monkeypatch, tmp_path, *, abort=None, quit_code=0, cad_exit_code=0):
events = []
cad = SimpleNamespace(pid=123, returncode=None)
cad.poll = lambda: cad.returncode
cad.wait = lambda timeout: cad.returncode
class Desktop:
def __init__(self, name, **kwargs):
self.name = name
def __enter__(self):
events.append('create')
return self
def start_process(self, command, **kwargs):
events.append(command[0])
if command[0] == 'cad.exe':
return cad
action, path, pid = command
if action == 'probe':
Path(path).write_text(json.dumps({'desktop': self.name, 'pid': pid,
'guid': '{owned}', 'token': kwargs['env']['DXPART_SESSION_TOKEN']}))
if abort is not None:
abort.set()
else:
cad.returncode = cad_exit_code
return SimpleNamespace(poll=lambda: None if abort is not None else 0,
wait=lambda timeout: quit_code, close=lambda: events.append('close-helper'),
stderr=io.BytesIO(b'project still open'))
def close(self):
events.append(('release', (tmp_path / 'uncertain.flag').exists()))
cad.returncode = 1 if cad.returncode is None else cad.returncode
monkeypatch.setattr(runtime, 'PrivateDesktop', Desktop)
monkeypatch.setattr(runtime, '_designer_executable', lambda: 'cad.exe')
monkeypatch.setattr(runtime, '_helper_command', lambda action, path, pid: (action, str(path), pid))
return events, cad
def test_success_quits_owned_cad_before_releasing_desktop(monkeypatch, tmp_path):
events, cad = fake_desktop(monkeypatch, tmp_path)
with runtime.IsolatedCadSession(tmp_path):
assert cad.poll() is None
assert events.index('quit') < events.index(('release', False))
record = json.loads((tmp_path / 'private-desktop.json').read_text())
assert record['state'] == 'released' and record['clean']
def test_startup_cancellation_releases_without_waiting_for_com_timeout(monkeypatch, tmp_path):
abort = Event()
events, _ = fake_desktop(monkeypatch, tmp_path, abort=abort)
with pytest.raises(WorkerMonitorError, match='cancelled'):
with runtime.IsolatedCadSession(tmp_path, abort_event=abort):
pytest.fail('cancelled startup entered replacement body')
assert 'quit' not in events
assert ('release', False) in events
def test_startup_cleanup_failure_keeps_uncertain_lock(monkeypatch, tmp_path):
abort = Event()
fake_desktop(monkeypatch, tmp_path, abort=abort)
session = runtime.IsolatedCadSession(tmp_path, abort_event=abort)
def failure():
raise OSError('owned process did not exit')
session.desktop.close = failure
with pytest.raises(WorkerMonitorError, match='cleanup requires reconciliation'):
session.__enter__()
assert (tmp_path / 'uncertain.flag').exists()
@pytest.mark.parametrize('failure', ['quit', 'cad_exit', 'unexpected_exit'])
def test_uncertain_cleanup_is_durable_before_forced_owned_release(monkeypatch, tmp_path, failure):
events, cad = fake_desktop(monkeypatch, tmp_path,
quit_code=1 if failure == 'quit' else 0,
cad_exit_code=7 if failure == 'cad_exit' else 0)
with pytest.raises(WorkerMonitorError, match='reconciliation'):
with runtime.IsolatedCadSession(tmp_path):
if failure == 'unexpected_exit':
cad.returncode = 9
assert ('release', True) in events
assert not json.loads((tmp_path / 'private-desktop.json').read_text())['clean']
def test_single_step_backup_precedes_discovery_and_failure_blocks_discovery(monkeypatch, tmp_path):
from dx_productivity.trial_task_center import single_step
events = []
preparer = SimpleNamespace(data_root=tmp_path,
progress=lambda *args, **kwargs: SimpleNamespace(queue_complete=False, next_project_path=tmp_path / 'one.prj'),
ensure_batch_handoff=lambda *args, **kwargs: events.append('discover'))
monkeypatch.setattr(single_step, 'create_schematic_backup', lambda *args: events.append('backup'))
single_step.prepare_private_single_step(preparer, 'task', (), (), False)
assert events == ['backup', 'discover']
def failed_backup(*args):
raise OSError('backup failed')
monkeypatch.setattr(single_step, 'create_schematic_backup', failed_backup)
events.clear()
with pytest.raises(OSError, match='backup failed'):
single_step.prepare_private_single_step(preparer, 'task', (), (), False)
assert not events