fix: scope catalog availability and report status progress
This commit is contained in:
1 parent
31a93cd313
commit
4fb978ee21
5 files changed
+465
-44
No files matched your search
@@ -202,7 +202,7 @@ class BatchStatusSession:
|
||||
self.restart_count = 0
|
||||
|
||||
def scan(self, names: Iterable[str], lmc_file: Path, checkpoint_path: Path | None,
|
||||
*, block_type: str = "RULP", resume: bool = False) -> list[BatchStatusRecord]:
|
||||
*, block_type: str = "RULP", resume: bool = False, progress=None) -> list[BatchStatusRecord]:
|
||||
from .operation_queue import check_active
|
||||
|
||||
check_active()
|
||||
@@ -229,6 +229,8 @@ class BatchStatusSession:
|
||||
if (previous and previous.status in {'READY', 'PENDING'}
|
||||
and previous.fingerprint == fingerprint and previous.block_type == block_type):
|
||||
results.append(previous)
|
||||
if progress is not None:
|
||||
progress(len(results), len(names))
|
||||
continue
|
||||
try:
|
||||
result: BridgeResult = self.bridge.query(
|
||||
@@ -275,6 +277,8 @@ class BatchStatusSession:
|
||||
check_active()
|
||||
checkpoint.append(checkpoint_path, record)
|
||||
results.append(record)
|
||||
if progress is not None:
|
||||
progress(len(results), len(names))
|
||||
if record.status == "UNAVAILABLE" and index + 1 < len(names):
|
||||
# Startup/protocol failures cannot be repaired by retrying
|
||||
# the same request contract for every CBB.
|
||||
@@ -288,6 +292,8 @@ class BatchStatusSession:
|
||||
)
|
||||
checkpoint.append(checkpoint_path, unavailable_record)
|
||||
results.append(unavailable_record)
|
||||
if progress is not None:
|
||||
progress(len(results), len(names))
|
||||
break
|
||||
queried += 1
|
||||
if server is not None and queried % self.rotate_every == 0 and name != names[-1]:
|
||||
@@ -300,7 +306,7 @@ class BatchStatusSession:
|
||||
|
||||
def authoritative_status_map(names: Iterable[str], lmc_file: Path, checkpoint_path: Path | None = None,
|
||||
*, bridge_path: Path | None = None,
|
||||
timeout_seconds: float = 10.0) -> dict[str, str]:
|
||||
timeout_seconds: float = 10.0, progress=None) -> dict[str, str]:
|
||||
"""Return only bridge-backed statuses for an optional UI integration.
|
||||
|
||||
Production always queries fresh statuses, including after native writes;
|
||||
@@ -313,7 +319,7 @@ def authoritative_status_map(names: Iterable[str], lmc_file: Path, checkpoint_pa
|
||||
names = tuple(str(name) for name in names)
|
||||
try:
|
||||
records = BatchStatusSession(bridge, timeout_seconds=timeout_seconds).scan(
|
||||
names, lmc_file, checkpoint_path, resume=False)
|
||||
names, lmc_file, checkpoint_path, resume=False, progress=progress)
|
||||
return {record.block_name: record.status for record in records}
|
||||
except BridgeUnavailable:
|
||||
return {name: "UNAVAILABLE" for name in names}
|
||||
|
||||
@@ -24,9 +24,10 @@ _retained_workers = []
|
||||
|
||||
|
||||
class NativeOperationError(RuntimeError):
|
||||
def __init__(self, detail, *, safe_to_continue):
|
||||
def __init__(self, detail, *, safe_to_continue, blocking_manager_pids=()):
|
||||
super().__init__(detail)
|
||||
self.safe_to_continue = safe_to_continue
|
||||
self.blocking_manager_pids = tuple(blocking_manager_pids)
|
||||
# Coordinator-owned Create/Add/conflict/update/remove/backup-reimport evidence:
|
||||
# diagnostics/issue2-native-crud-20261103/engine-e2e/cycle-result.json
|
||||
_PRODUCTION_ADD_VALIDATED = True
|
||||
@@ -286,15 +287,20 @@ class NativeManagementAdapter:
|
||||
finally:
|
||||
worker.close()
|
||||
|
||||
def catalog(self, library, evidence):
|
||||
def catalog(self, library, evidence, *, include_engineering_identity=True):
|
||||
result = self._worker({'operation': 'catalog', 'worker_role': 'catalog_readonly',
|
||||
'library': str(absolute_preserving_drive(library))}, evidence)
|
||||
'library': str(absolute_preserving_drive(library)),
|
||||
'include_engineering_identity': include_engineering_identity}, evidence)
|
||||
if not result.get('success') or not result.get('safe_to_continue'):
|
||||
raise NativeOperationError(result.get('detail', '原生目录复读未确认,禁止文件夹回退。'),
|
||||
safe_to_continue=result.get('safe_to_continue') is True)
|
||||
safe_to_continue=result.get('safe_to_continue') is True,
|
||||
blocking_manager_pids=result.get('blocking_manager_pids', ()))
|
||||
return Catalog(Path(result['library']), int(result['flow']),
|
||||
tuple(CatalogEntry(**entry) for entry in result['entries']), result['safe_to_continue'])
|
||||
|
||||
def catalog_registrations(self, library, evidence):
|
||||
return self.catalog(library, evidence, include_engineering_identity=False)
|
||||
|
||||
def remove(self, request, evidence):
|
||||
caps = self.capabilities()
|
||||
if not caps['remove'].supported:
|
||||
@@ -1087,6 +1093,77 @@ def _wait_native_exit(pids, timeout=10):
|
||||
return True
|
||||
|
||||
|
||||
def _catalog_shared_dependencies(library):
|
||||
from .icdb_ownership import shared_symbol_database
|
||||
database = shared_symbol_database(library) / 'icdb.dat'
|
||||
try:
|
||||
info = database.stat()
|
||||
except FileNotFoundError:
|
||||
return set()
|
||||
return {(info.st_dev, info.st_ino, database.resolve())}
|
||||
|
||||
|
||||
def _probe_catalog_files(library):
|
||||
import pywintypes, win32con, win32file
|
||||
from contextlib import ExitStack
|
||||
|
||||
with ExitStack() as handles:
|
||||
paths = (library, *(path for _, _, path in _catalog_shared_dependencies(library)))
|
||||
for path in paths:
|
||||
try:
|
||||
handle = win32file.CreateFile(str(path), win32con.GENERIC_READ, 0, None,
|
||||
win32con.OPEN_EXISTING, 0, None)
|
||||
except (OSError, pywintypes.error) as error:
|
||||
raise OSError(f'{path}:{error}') from error
|
||||
handles.callback(handle.Close)
|
||||
|
||||
|
||||
def _open_catalog_manager_library(pid):
|
||||
from .residual_sessions import _process_windows, _window_error
|
||||
|
||||
windows = _process_windows({pid})
|
||||
if _window_error(windows, pid):
|
||||
return None
|
||||
paths = set()
|
||||
for window in windows[pid]:
|
||||
title = window['title']
|
||||
if title.startswith('Library Manager: '):
|
||||
path = Path(title.removeprefix('Library Manager: ').strip())
|
||||
if path.is_absolute() and path.suffix.casefold() == '.lmc':
|
||||
paths.add(path)
|
||||
return next(iter(paths)) if len(paths) == 1 else None
|
||||
|
||||
|
||||
def _check_catalog_owners(library, processes):
|
||||
"""A foreign LM is compatible only with a disjoint library and free target resources."""
|
||||
library = Path(library).resolve()
|
||||
manager_pids = [pid for pid, *_ in processes]
|
||||
target_dependencies = _catalog_shared_dependencies(library)
|
||||
for pid in manager_pids:
|
||||
try:
|
||||
current = _open_catalog_manager_library(pid)
|
||||
if current is None:
|
||||
detail = '无法确认已运行的 Library Manager 对应哪个库'
|
||||
else:
|
||||
other = current.resolve(strict=True)
|
||||
if library.samefile(other):
|
||||
detail = '当前库已在另一个 Library Manager 中打开'
|
||||
elif any(left[2] == right[2] or (left[1] and left[:2] == right[:2])
|
||||
for left in target_dependencies for right in _catalog_shared_dependencies(other)):
|
||||
detail = '另一个 Library Manager 正在使用相同的共享符号库'
|
||||
else:
|
||||
continue
|
||||
except (OSError, ValueError) as error:
|
||||
detail = f'无法确认另一中心库的资源范围:{error}'
|
||||
raise NativeOperationError(f'LIBRARY_MANAGER_BUSY: PID {pid} · {detail}。',
|
||||
safe_to_continue=True, blocking_manager_pids=(pid,))
|
||||
try:
|
||||
_probe_catalog_files(library)
|
||||
except OSError as error:
|
||||
raise NativeOperationError(f'LIBRARY_MANAGER_BUSY: PID {manager_pids} · 当前库资源占用未确认:{error}',
|
||||
safe_to_continue=True, blocking_manager_pids=manager_pids) from error
|
||||
|
||||
|
||||
def _catalog_native(job, root):
|
||||
import gc, pythoncom
|
||||
from .com_runtime import initialize_com, uninitialize_com
|
||||
@@ -1102,7 +1179,8 @@ def _catalog_native(job, root):
|
||||
uninitialize_com(initialized)
|
||||
# A failed COM activation can have created an unaccounted server. An empty
|
||||
# PID list is missing release evidence, not proof that nothing was launched.
|
||||
result['safe_to_continue'] = bool(result.get('native_pids')) and _wait_native_exit(result['native_pids'])
|
||||
result['safe_to_continue'] = bool(result.get('no_new_manager') or (
|
||||
result.get('native_pids') and _wait_native_exit(result['native_pids'])))
|
||||
return result
|
||||
|
||||
|
||||
@@ -1121,8 +1199,16 @@ def _catalog_com(job, root):
|
||||
desktop, name = _current_desktop()
|
||||
if name != job['desktop'] or not name.startswith('CbbManagement_'):
|
||||
raise RuntimeError('拒绝在非本次私有桌面读取原生目录。')
|
||||
if _process_details('LibraryManager.exe'):
|
||||
raise RuntimeError('LIBRARY_MANAGER_BUSY: 已有 Library Manager 运行,请关闭后重试。')
|
||||
previous_managers = _process_details('LibraryManager.exe')
|
||||
if previous_managers:
|
||||
if job.get('worker_role') != 'catalog_readonly' or job.get('include_engineering_identity', True):
|
||||
raise RuntimeError('LIBRARY_MANAGER_BUSY: 已有 Library Manager 运行,请关闭后重试。')
|
||||
expected = Path(job['mentor_home'])/'lm/win32/bin/LibraryManager.exe'
|
||||
if hash_file(expected) != _BINARY_PROOF['lm/win32/bin/LibraryManager.exe']:
|
||||
pids = sorted(pid for pid, *_ in previous_managers)
|
||||
raise NativeOperationError(f'LIBRARY_MANAGER_BUSY: PID {pids} · 当前安装尚未验证并行目录读取。',
|
||||
safe_to_continue=True, blocking_manager_pids=pids)
|
||||
_check_catalog_owners(job['library'], previous_managers)
|
||||
except Exception as error:
|
||||
error.safe_to_continue = True
|
||||
raise
|
||||
@@ -1178,16 +1264,26 @@ def _catalog_com(job, root):
|
||||
# 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)
|
||||
from .session_record import update_worker_state
|
||||
update_worker_state(job, 'POSTCALL', identities=[('native', pid) for pid in owned_pids])
|
||||
if len(owned_pids) != 1:
|
||||
previous_pids = {pid for pid, *_ in previous_managers}
|
||||
new_processes = [process for process in processes if process[0] not in previous_pids]
|
||||
if not new_processes and previous_pids and {p[0] for p in processes} == previous_pids:
|
||||
# DispatchEx reused an existing instance. Drop this proxy without invoking any method.
|
||||
result.update(no_new_manager=True, blocking_manager_pids=sorted(previous_pids))
|
||||
raise RuntimeError(f'LIBRARY_MANAGER_BUSY: 当前 COM 注册复用了已有 Library Manager,PID {sorted(previous_pids)}。')
|
||||
if len(new_processes) != 1:
|
||||
raise RuntimeError('无法唯一确认本次 Library Manager 进程。')
|
||||
pid, executable, *_ = new_processes[0]
|
||||
expected_binary = Path(job['mentor_home'])/'lm/win32/bin/LibraryManager.exe'
|
||||
if Path(processes[0][1]).resolve() != expected_binary.resolve():
|
||||
if Path(executable).resolve() != expected_binary.resolve():
|
||||
raise RuntimeError('COM 注册指向不同的 Library Manager 安装,拒绝打开中心库。')
|
||||
if job.get('session_record_path') or previous_pids:
|
||||
desktop_pids = {win32process.GetWindowThreadProcessId(hwnd)[1] for hwnd in desktop.EnumDesktopWindows()}
|
||||
if pid not in desktop_pids:
|
||||
raise RuntimeError('无法确认新 Library Manager 位于本次私有桌面。')
|
||||
owned_pids.add(pid)
|
||||
update_worker_state(job, 'POSTCALL', identities=[('native', pid)])
|
||||
app.Visible = True
|
||||
watcher = threading.Thread(target=observe_dialogs, daemon=True)
|
||||
watcher.start()
|
||||
if job['operation'] in ('probe_create_add', 'probe_create'):
|
||||
@@ -1228,13 +1324,14 @@ def _catalog_com(job, root):
|
||||
block_name, partition_name = str(item.Name), str(item.PartitionName)
|
||||
validate_name(block_name)
|
||||
identity = {}
|
||||
work = Path(job['library']).parent/'ReusableBlocksLP'/block_name/'Work'
|
||||
projects = list(work.glob('*.prj'))
|
||||
if len(projects) == 1:
|
||||
try:
|
||||
identity = engineering_identity(projects[0])
|
||||
except (ValueError, OSError):
|
||||
pass
|
||||
if job.get('include_engineering_identity', True):
|
||||
work = Path(job['library']).parent/'ReusableBlocksLP'/block_name/'Work'
|
||||
projects = list(work.glob('*.prj'))
|
||||
if len(projects) == 1:
|
||||
try:
|
||||
identity = engineering_identity(projects[0])
|
||||
except (ValueError, OSError):
|
||||
pass
|
||||
entries.append(asdict(CatalogEntry(block_name, partition_name, identity)))
|
||||
item = None
|
||||
partition = None
|
||||
@@ -1262,7 +1359,7 @@ def _catalog_com(job, root):
|
||||
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'):
|
||||
if app is not None and owned_pids and not job.get('_native_add_pending'):
|
||||
try:
|
||||
dispatch_native(job, lambda: app.Quit(), phase='CLOSING')
|
||||
except Exception as error:
|
||||
@@ -1381,6 +1478,8 @@ def management_worker_main(request_path, *, catalog_readonly=False):
|
||||
except Exception as error:
|
||||
if getattr(error, 'safe_to_continue', None) is True:
|
||||
result['safe_to_continue'] = True
|
||||
if getattr(error, 'blocking_manager_pids', ()):
|
||||
result['blocking_manager_pids'] = list(error.blocking_manager_pids)
|
||||
result['detail'] = str(error)
|
||||
result['exception'] = _exception_details(error)
|
||||
finally:
|
||||
|
||||
@@ -5,6 +5,7 @@ import ntpath
|
||||
import time
|
||||
from collections import Counter
|
||||
from dataclasses import replace
|
||||
from datetime import datetime
|
||||
from types import SimpleNamespace
|
||||
import json
|
||||
|
||||
@@ -76,6 +77,7 @@ STATUS_LABELS = {
|
||||
'MALFORMED': '状态桥协议错误',
|
||||
'CRASHED': '状态桥崩溃',
|
||||
}
|
||||
CATALOG_MANAGER_WAIT_SECONDS = 120
|
||||
VERIFY_RELEASE_WAIT_SECONDS = 120
|
||||
|
||||
def application_icon_path():
|
||||
@@ -118,13 +120,16 @@ class MainWindow(QWidget):
|
||||
self.native_backup_timer.timeout.connect(self._poll_native_backup)
|
||||
self._injected_reader = reader is not None
|
||||
self.reader = reader or read_library_fast
|
||||
self.catalog_reader = catalog_reader or (None if reader is not None else getattr(self.management_adapter,'catalog',None))
|
||||
self.catalog_reader = catalog_reader or (None if reader is not None else getattr(
|
||||
self.management_adapter, 'catalog_registrations', getattr(self.management_adapter, 'catalog', None)))
|
||||
self._view_revision = 0
|
||||
self._jobs = {}
|
||||
self._dialogs = []
|
||||
self._current_job = None
|
||||
self._stale_table = False
|
||||
self._table_library_path = None
|
||||
self._catalog_snapshot_time = ''
|
||||
self._catalog_retry = False
|
||||
self._read_counts = (None, None, None)
|
||||
self._diagnostic_evidence = {}
|
||||
self.pool = QThreadPool(self); self.pool.setMaxThreadCount(8)
|
||||
@@ -218,6 +223,9 @@ class MainWindow(QWidget):
|
||||
self.status_filter.currentIndexChanged.connect(self._apply_filters)
|
||||
self.timeout_spin = QSpinBox(); self.timeout_spin.setRange(30, 1800); self.timeout_spin.setValue(DEFAULT_TIMEOUT_SECONDS); self.timeout_spin.setSuffix(' 秒 / 无进展')
|
||||
self.load_button = QPushButton('读取 CBB'); self.load_button.clicked.connect(self.load_library)
|
||||
self.catalog_status_button = QPushButton('刷新已登记项状态')
|
||||
self.catalog_status_button.clicked.connect(self._refresh_registered_catalog)
|
||||
self.catalog_status_button.hide()
|
||||
self.browse_button = QPushButton('选择'); self.browse_button.clicked.connect(self.choose_library)
|
||||
self.selected_batch_button = QPushButton('批量校验已选'); self.selected_batch_button.clicked.connect(self.verify_selected)
|
||||
self.batch_button = QPushButton('校验可见非 READY'); self.batch_button.clicked.connect(self.verify_all)
|
||||
@@ -256,7 +264,7 @@ class MainWindow(QWidget):
|
||||
self.output.setMaximumHeight(180)
|
||||
layout = QVBoxLayout(self)
|
||||
row = QHBoxLayout(); row.addWidget(QLabel('中心库')); row.addWidget(self.lmc_edit)
|
||||
row.addWidget(self.browse_button); row.addWidget(self.load_button)
|
||||
row.addWidget(self.browse_button); row.addWidget(self.load_button); row.addWidget(self.catalog_status_button)
|
||||
layout.addLayout(row)
|
||||
self.library_notice = QLabel()
|
||||
self.library_notice.setWordWrap(True)
|
||||
@@ -363,6 +371,7 @@ class MainWindow(QWidget):
|
||||
self._reimport_offers = ()
|
||||
self._diagnostic_evidence.clear()
|
||||
self._resume_batch = None
|
||||
self._catalog_retry = False
|
||||
self._stale_table = bool(self._records_by_name)
|
||||
self._release_library_lease()
|
||||
self.loaded_path = None
|
||||
@@ -548,7 +557,17 @@ class MainWindow(QWidget):
|
||||
current_library = _path_key(self.mentor_lmc_path or self.lmc_edit.text()) if self.lmc_edit.text().strip() else None
|
||||
notice = ('上次操作结果待复查,执行前将重新检查占用。'
|
||||
if self._management_library_unsafe(current_library) else '')
|
||||
notice = '当前显示上次读取结果(已失效)· 请重新读取中心库。' if self._stale_table else notice
|
||||
if self._stale_table:
|
||||
if self._catalog_snapshot_time:
|
||||
when = self._catalog_snapshot_time
|
||||
notice = f'显示上次完整清单({when},待刷新)· {self._table_library_path}'
|
||||
else:
|
||||
notice = '当前显示上次读取结果(已失效)· 请重新读取中心库。'
|
||||
self.catalog_status_button.setVisible(
|
||||
self._catalog_retry and not self._closing and self._table_library_path == self.lmc_edit.text()
|
||||
and self._read_counts[1] is not None and self.mentor_lmc_path is not None)
|
||||
self.catalog_status_button.setEnabled(not self.busy)
|
||||
self.load_button.setText('重试读取' if self._catalog_retry else '读取 CBB')
|
||||
self.library_notice.setText(notice)
|
||||
self.library_notice.setVisible(bool(notice))
|
||||
for widget in (self.lmc_edit, self.browse_button, self.load_button,
|
||||
@@ -1272,11 +1291,14 @@ class MainWindow(QWidget):
|
||||
|
||||
def load_library(self):
|
||||
if self._closing or not self.lmc_edit.text(): return
|
||||
if (self._current_job is not None and self._current_job.kind == 'read'
|
||||
and self._current_job.active and self._current_job.revision == self._view_revision): return
|
||||
if any(job.kind in ('read', 'catalog') and job.active
|
||||
and not job.context.stop.is_set() and job.revision == self._view_revision
|
||||
for job in self._jobs.values()):
|
||||
return
|
||||
self._cancel_catalog_read()
|
||||
self._view_revision += 1
|
||||
self._diagnostic_evidence.clear()
|
||||
self._catalog_retry = False
|
||||
self._stale_table = bool(self._records_by_name)
|
||||
job = self._new_job('read', library=self.lmc_edit.text())
|
||||
job.lease = None
|
||||
@@ -1293,7 +1315,7 @@ class MainWindow(QWidget):
|
||||
self._release_library_lease()
|
||||
self.loaded_path = None
|
||||
path = self.lmc_edit.text()
|
||||
preserve = self._table_library_path == path and self._read_counts[1] is not None
|
||||
preserve = self._read_counts[1] is not None
|
||||
self.status_label.setText('正在读取中心库…')
|
||||
def read():
|
||||
import pythoncom
|
||||
@@ -1323,8 +1345,9 @@ class MainWindow(QWidget):
|
||||
len(result.records), int((time.monotonic() - started) * 1000),
|
||||
dict(statuses), unknown[:20])
|
||||
skip_reasons = {}
|
||||
if not result.error:
|
||||
if not result.error and (self.catalog_reader is None or result.catalog_verified):
|
||||
for record in result.records:
|
||||
job.context.check_active()
|
||||
reason = preflight_skip_reason(mentor_path, record.name)
|
||||
if reason:
|
||||
skip_reasons[record.name] = reason
|
||||
@@ -1352,12 +1375,14 @@ class MainWindow(QWidget):
|
||||
self._publish_check_statuses(mentor_path,
|
||||
{record.name: record.status for record in result.records
|
||||
if record.catalog_source != 'directory_only'}, lease)
|
||||
preview = self.catalog_reader is not None and not result.catalog_verified
|
||||
self._stale_table = False
|
||||
self._table_library_path = path
|
||||
self._catalog_snapshot_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S') if result.catalog_verified else ''
|
||||
self._read_counts = (result.directory_count, result.native_count,
|
||||
result.missing_project_count if result.missing_project_count is not None else len(skip_reasons))
|
||||
self._maintenance_recovery_view = recovery_view
|
||||
self.loaded_path = path
|
||||
self.loaded_path = path if not preview or self._injected_reader else None
|
||||
try:
|
||||
if self._settings_enabled:
|
||||
self.data_root.mkdir(parents=True, exist_ok=True)
|
||||
@@ -1426,7 +1451,7 @@ class MainWindow(QWidget):
|
||||
self.status_label.setText('协调阻止恢复视图:仅按目录显示工程,状态未确认(UNKNOWN),不代表损坏。'
|
||||
'仅可明确执行 ICDB 维护或释放检查,其他写入与原生状态读取已禁用。')
|
||||
self._apply_filters()
|
||||
if self.catalog_reader is not None and not result.catalog_verified:
|
||||
if preview:
|
||||
self._start_catalog(job, result, lease, mentor_path, loaded)
|
||||
self._start(read, loaded, queued=False, job=job, metadata_only=True,
|
||||
stale=lambda payload: self._close_path_lease(payload[2]))
|
||||
@@ -1462,18 +1487,29 @@ class MainWindow(QWidget):
|
||||
directories = {record.name: record for record in initial.records}
|
||||
names = tuple(sorted(native.keys() | directories.keys()))
|
||||
context.check_active()
|
||||
phase('catalog_status', f'正在核对 {len(native)} 项原生状态…')
|
||||
phase('catalog_status', f'已核对 0/{len(native)} 项原生状态…')
|
||||
if checkpoint is None:
|
||||
statuses = self.status_refresher(tuple(native), Path(library))
|
||||
else:
|
||||
statuses = self.status_refresher(tuple(native), Path(library), checkpoint)
|
||||
if native and (not native.keys() <= statuses.keys()
|
||||
or any(statuses[name] == 'UNAVAILABLE' for name in native)
|
||||
or not any(statuses[name] in {'READY', 'PENDING'} for name in native)):
|
||||
from cbb_refresh_verify.operation_queue import note_metadata_progress
|
||||
last_notice = 0.0
|
||||
|
||||
def report_progress(done, total):
|
||||
nonlocal last_notice
|
||||
note_metadata_progress()
|
||||
now = time.monotonic()
|
||||
if done == total or now - last_notice >= .2:
|
||||
last_notice = now
|
||||
phase('catalog_status', f'已核对 {done}/{total} 项原生状态…')
|
||||
|
||||
statuses = self.status_refresher(tuple(native), Path(library), checkpoint, progress=report_progress)
|
||||
if any(statuses.get(name) not in {'READY', 'PENDING'} for name in native):
|
||||
raise ValueError('原生状态读取未确认,请重新读取中心库。')
|
||||
context.check_active()
|
||||
phase('catalog_reconcile', '正在合并目录和状态…')
|
||||
records, reasons = [], {}
|
||||
for name in names:
|
||||
context.check_active()
|
||||
source = ('both' if name in native and name in directories else
|
||||
'native_only' if name in native else 'directory_only')
|
||||
reason = ('CATALOG_NOT_REGISTERED: 仅发现目录,原生目录未登记。' if name not in native else
|
||||
@@ -1502,13 +1538,19 @@ class MainWindow(QWidget):
|
||||
except NativeOperationError as error:
|
||||
if not error.safe_to_continue or not str(error).startswith('LIBRARY_MANAGER_BUSY:'):
|
||||
raise
|
||||
phase('catalog_waiting', 'Library Manager 正在使用,退出后将自动重试读取。')
|
||||
deadline = time.monotonic() + 30
|
||||
phase('catalog_waiting', f'{error} 等待释放后自动重试读取。')
|
||||
deadline = time.monotonic() + CATALOG_MANAGER_WAIT_SECONDS
|
||||
blockers = set(error.blocking_manager_pids)
|
||||
while time.monotonic() < deadline:
|
||||
context.check_active()
|
||||
owners = query_owners(('LibraryManager.exe',), timeout_seconds=2)
|
||||
try:
|
||||
owners = query_owners(('LibraryManager.exe',),
|
||||
timeout_seconds=min(2, max(.1, deadline - time.monotonic())))
|
||||
except (OSError, RuntimeError):
|
||||
context.stop.wait(1)
|
||||
continue
|
||||
context.check_active()
|
||||
if not owners:
|
||||
if not owners or blockers and blockers.isdisjoint(owner['pid'] for owner in owners):
|
||||
return attempt(root/'retry')
|
||||
context.stop.wait(1)
|
||||
context.check_active()
|
||||
@@ -1529,6 +1571,8 @@ class MainWindow(QWidget):
|
||||
cancelled = context.stop.is_set() or isinstance(error, QueueCancelled)
|
||||
detail = '已取消读取中心库。' if cancelled else f'原生目录未确认,请重新读取:{error}'
|
||||
phase('catalog_cancelled' if cancelled else 'catalog_failed', detail)
|
||||
self._catalog_retry = True
|
||||
self._stale_table = bool(self._records_by_name) and bool(self._catalog_snapshot_time)
|
||||
self.status_label.setText(detail)
|
||||
|
||||
def completed(payload):
|
||||
@@ -1550,6 +1594,28 @@ class MainWindow(QWidget):
|
||||
worker.signals.finished.connect(lambda:(self._lifecycle_workers.discard(worker),self._finish_job(job)))
|
||||
self.pool.start(worker)
|
||||
|
||||
def _refresh_registered_catalog(self):
|
||||
if (self.busy or not self._catalog_retry or self.mentor_lmc_path is None
|
||||
or self._table_library_path != self.lmc_edit.text() or self._read_counts[1] is None):
|
||||
return
|
||||
library, lease = self.mentor_lmc_path, self.library_lease
|
||||
names = tuple(name for name, record in self._records_by_name.items()
|
||||
if record.catalog_source in {'both', 'native_only'})
|
||||
if not names:
|
||||
self.status_label.setText('上次清单中没有已登记项。')
|
||||
return
|
||||
job = self._new_job('status', library=library, targets=names, lease=lease)
|
||||
self.status_label.setText('正在刷新上次登记项的原生状态…')
|
||||
|
||||
def refreshed(statuses):
|
||||
if any(statuses.get(name) not in {'READY', 'PENDING'} for name in names):
|
||||
self.status_label.setText('原生状态未确认,保留上次读取结果。')
|
||||
return
|
||||
self._apply_refreshed_records((names, statuses, None, ''))
|
||||
self.status_label.setText(f'已刷新 {len(names)} 项原生状态,目录仍待重新读取。')
|
||||
|
||||
self._start(lambda: self.status_refresher(names, Path(library)), refreshed, job=job)
|
||||
|
||||
def _execution_status_reader(self, operation_id, lease):
|
||||
"""Recheck registration once per submission and status at each admission."""
|
||||
catalog_reader, status_reader = self.catalog_reader, self.status_refresher
|
||||
@@ -2000,7 +2066,7 @@ class MainWindow(QWidget):
|
||||
from shiboken6 import isValid
|
||||
if not isValid(self) or not isValid(self.cbb_table):
|
||||
return
|
||||
if event.get('stage') in {'catalog_start', 'catalog_status', 'catalog_waiting'}:
|
||||
if event.get('stage') in {'catalog_start', 'catalog_status', 'catalog_waiting', 'catalog_reconcile'}:
|
||||
catalog_job = self._jobs.get(event.get('catalog_id'))
|
||||
if catalog_job is None or catalog_job.context.stop.is_set():
|
||||
return
|
||||
|
||||
@@ -660,7 +660,7 @@ def test_uncommitted_catalog_refresh_preserves_last_full_result(qtbot, tmp_path,
|
||||
calls = []
|
||||
snapshot = tmp_path/'status-refresh.jsonl'
|
||||
|
||||
def read_status(names, path, checkpoint_path=None):
|
||||
def read_status(names, path, checkpoint_path=None, *, progress=None):
|
||||
calls.append(names)
|
||||
if checkpoint_path is not None:
|
||||
checkpoint_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
@@ -0,0 +1,250 @@
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from cbb_refresh_verify import native_management as native
|
||||
from cbb_refresh_verify.batch_status import BatchStatusSession
|
||||
from cbb_refresh_verify.status_bridge import BridgeResult
|
||||
|
||||
|
||||
def test_status_scan_delivers_progress_after_each_record(tmp_path):
|
||||
snapshots = []
|
||||
bridge = SimpleNamespace(query=lambda *args, **kwargs: BridgeResult("READY", "test"))
|
||||
lmc = tmp_path / 'library.lmc'
|
||||
lmc.write_bytes(b'library')
|
||||
checkpoint = tmp_path / 'pending.jsonl'
|
||||
|
||||
def progress(completed, total):
|
||||
snapshots.append((completed, total, len(checkpoint.read_text('utf-8').splitlines())))
|
||||
|
||||
results = BatchStatusSession(bridge).scan(['A', 'B'], lmc, checkpoint, progress=progress)
|
||||
assert [record.status for record in results] == ['READY', 'READY']
|
||||
assert snapshots == [(1, 2, 1), (2, 2, 2)]
|
||||
|
||||
|
||||
@pytest.mark.parametrize('include_identity', [False, True])
|
||||
def test_catalog_registration_only_skips_project_identities(tmp_path, monkeypatch, include_identity):
|
||||
import win32com.client
|
||||
from cbb_refresh_verify import mentor_adapter
|
||||
|
||||
lmc = tmp_path / 'lib.lmc'
|
||||
lmc.touch()
|
||||
project = tmp_path / 'ReusableBlocksLP/A/Work/A.prj'
|
||||
project.parent.mkdir(parents=True)
|
||||
project.touch()
|
||||
hashed = []
|
||||
monkeypatch.setattr(native, 'engineering_identity', lambda p: hashed.append(p) or {'identity': True})
|
||||
|
||||
partition = SimpleNamespace(Count=1,
|
||||
Item=lambda _: SimpleNamespace(Name='A', PartitionName='Logical-Physical'))
|
||||
library = SimpleNamespace(FullName=str(lmc), FlowType=1, Close=lambda: None,
|
||||
Partitions=lambda _: SimpleNamespace(Count=1, Item=lambda _: partition))
|
||||
app = SimpleNamespace(OpenLibrary=lambda _: library, Quit=lambda: None)
|
||||
exe = tmp_path / 'lm/win32/bin/LibraryManager.exe'
|
||||
no_owners = iter([[], [(123, str(exe), '', 0)]])
|
||||
monkeypatch.setattr(mentor_adapter, '_process_details', lambda _: next(no_owners))
|
||||
monkeypatch.setattr(native, '_current_desktop',
|
||||
lambda: (SimpleNamespace(EnumDesktopWindows=lambda: []), 'CbbManagement_test'))
|
||||
monkeypatch.setattr(win32com.client, 'DispatchEx', lambda _: app)
|
||||
result = native._catalog_com({'operation': 'catalog', 'worker_role': 'catalog_readonly',
|
||||
'include_engineering_identity': include_identity, 'library': str(lmc),
|
||||
'desktop': 'CbbManagement_test', 'mentor_home': str(tmp_path), 'supervisor_pid': __import__('os').getpid()}, tmp_path)
|
||||
assert result['success']
|
||||
assert hashed == ([project] if include_identity else [])
|
||||
|
||||
|
||||
@pytest.mark.parametrize('scope', ['foreign', 'same', 'shared', 'unknown', 'switched', 'occupied'])
|
||||
def test_catalog_distinguishes_foreign_and_conflicting_manager(tmp_path, monkeypatch, scope):
|
||||
target = tmp_path/'target'/'lib.lmc'
|
||||
outside = tmp_path/'outside'/'lib.lmc'
|
||||
for lmc in (target, outside):
|
||||
lmc.parent.mkdir()
|
||||
lmc.touch()
|
||||
if scope == 'shared':
|
||||
from cbb_refresh_verify.icdb_ownership import shared_symbol_database
|
||||
first = shared_symbol_database(target)/'icdb.dat'
|
||||
second = shared_symbol_database(outside)/'icdb.dat'
|
||||
first.parent.mkdir(parents=True)
|
||||
second.parent.mkdir(parents=True)
|
||||
first.touch()
|
||||
second.hardlink_to(first)
|
||||
lk = target if scope == 'same' else outside
|
||||
actual = None if scope == 'unknown' else target if scope == 'switched' else lk
|
||||
monkeypatch.setattr(native, '_open_catalog_manager_library', lambda _: actual, raising=False)
|
||||
owners = [(123, 'LibraryManager.exe', '' if scope == 'unknown' else f'LibraryManager.exe "{lk}"', 0)]
|
||||
if scope == 'occupied':
|
||||
def held(library):
|
||||
raise OSError('shared database handle is occupied')
|
||||
monkeypatch.setattr(native, '_probe_catalog_files', held)
|
||||
if scope == 'foreign':
|
||||
native._check_catalog_owners(target, owners)
|
||||
else:
|
||||
with pytest.raises(RuntimeError, match='LIBRARY_MANAGER_BUSY.*123'):
|
||||
native._check_catalog_owners(target, owners)
|
||||
|
||||
|
||||
def test_catalog_rejects_reused_foreign_com_proxy_without_mutating_it(tmp_path, monkeypatch):
|
||||
import win32com.client
|
||||
from cbb_refresh_verify import mentor_adapter
|
||||
|
||||
target = tmp_path/'target'/'lib.lmc'
|
||||
other = tmp_path/'other'/'lib.lmc'
|
||||
for lmc in (target, other):
|
||||
lmc.parent.mkdir()
|
||||
lmc.touch()
|
||||
exe = tmp_path/'lm/win32/bin/LibraryManager.exe'
|
||||
exe.parent.mkdir(parents=True)
|
||||
exe.write_bytes(b'library manager')
|
||||
monkeypatch.setitem(native._BINARY_PROOF, 'lm/win32/bin/LibraryManager.exe', native.hash_file(exe))
|
||||
before = [(123, 'LibraryManager.exe', f'LibraryManager.exe "{other}"', 0)]
|
||||
monkeypatch.setattr(mentor_adapter, '_process_details', lambda _: before)
|
||||
monkeypatch.setattr(native, '_open_catalog_manager_library', lambda _: other, raising=False)
|
||||
monkeypatch.setattr(native, '_current_desktop',
|
||||
lambda: (SimpleNamespace(EnumDesktopWindows=lambda: []), 'CbbManagement_test'))
|
||||
|
||||
class Foreign:
|
||||
def __setattr__(self, key, value):
|
||||
pytest.fail(f'changed foreign LM property {key}')
|
||||
def OpenLibrary(self, *_):
|
||||
pytest.fail('opened target from a foreign LM')
|
||||
def Quit(self):
|
||||
pytest.fail('quit foreign LM')
|
||||
|
||||
monkeypatch.setattr(win32com.client, 'DispatchEx', lambda _: Foreign())
|
||||
result = native._catalog_com({'operation': 'catalog', 'worker_role': 'catalog_readonly',
|
||||
'include_engineering_identity': False, 'library': str(target),
|
||||
'desktop': 'CbbManagement_test', 'mentor_home': str(tmp_path), 'supervisor_pid': __import__('os').getpid()}, tmp_path)
|
||||
assert not result['success']
|
||||
assert result['native_pids'] == []
|
||||
assert result['no_new_manager'] is True
|
||||
assert 'LIBRARY_MANAGER_BUSY' in result['detail']
|
||||
|
||||
|
||||
|
||||
def test_catalog_progress_and_pending_preview_are_visible(qtbot, tmp_path, monkeypatch):
|
||||
from threading import Event
|
||||
from cbb_refresh_verify.management import Catalog, CatalogEntry
|
||||
from cbb_refresh_verify.ui import main_window as ui
|
||||
from test_issue15_ui_integration import load
|
||||
|
||||
checked, finish = Event(), Event()
|
||||
library = tmp_path/'lib.lmc'
|
||||
library.write_bytes(b'test catalog')
|
||||
for name in ('A', 'B'):
|
||||
(tmp_path/'ReusableBlocksLP'/name).mkdir(parents=True)
|
||||
|
||||
def status(names, path, checkpoint=None, *, progress=None):
|
||||
if progress is not None:
|
||||
progress(1, len(names))
|
||||
checked.set()
|
||||
assert finish.wait(5)
|
||||
checkpoint.parent.mkdir(parents=True, exist_ok=True)
|
||||
checkpoint.write_text('complete', encoding='utf-8')
|
||||
return {name: 'READY' for name in names}
|
||||
|
||||
monkeypatch.setattr(ui, 'authoritative_status_map', status)
|
||||
monkeypatch.setattr(ui, 'preflight_skip_reason', lambda *_: None)
|
||||
window = ui.MainWindow(data_root=tmp_path/'data', catalog_reader=lambda path, _: Catalog(
|
||||
path, 1, tuple(CatalogEntry(name, 'Logical-Physical') for name in ('A', 'B'))))
|
||||
qtbot.addWidget(window)
|
||||
window.show()
|
||||
try:
|
||||
load(window, qtbot, str(library))
|
||||
qtbot.waitUntil(checked.is_set)
|
||||
qtbot.waitUntil(lambda: '已核对 1/2' in window.status_label.text(), timeout=1000)
|
||||
assert window.ready_names == set()
|
||||
assert not window.icdb_repair_button.isEnabled()
|
||||
assert not window.backup_restore_button.isEnabled()
|
||||
assert not (tmp_path/'data'/'status-refresh.jsonl').exists()
|
||||
finish.set()
|
||||
qtbot.waitUntil(lambda: window.ready_names == {'A', 'B'})
|
||||
finally:
|
||||
finish.set()
|
||||
window.pool.waitForDone(6000)
|
||||
|
||||
|
||||
def test_timed_out_catalog_can_refresh_already_registered_status_only(qtbot, tmp_path, monkeypatch):
|
||||
from cbb_refresh_verify.management import Catalog, CatalogEntry
|
||||
from cbb_refresh_verify.models import CbbRecord, LibraryReadResult
|
||||
from cbb_refresh_verify.ui import main_window as ui
|
||||
from test_issue15_ui_integration import load, window_for
|
||||
|
||||
calls = []
|
||||
still_active = []
|
||||
|
||||
def catalog(library, _):
|
||||
calls.append(library)
|
||||
if len(calls) > 1:
|
||||
raise native.NativeOperationError('LIBRARY_MANAGER_BUSY: PID 123', safe_to_continue=True,
|
||||
blocking_manager_pids=(123,))
|
||||
return Catalog(library, 1, (CatalogEntry('A', 'Logical-Physical'),))
|
||||
|
||||
monkeypatch.setattr(ui, 'CATALOG_MANAGER_WAIT_SECONDS', 0, raising=False)
|
||||
window = window_for(qtbot, tmp_path, monkeypatch,
|
||||
reader=lambda _: LibraryReadResult((CbbRecord('A', 'LP'), CbbRecord('Ghost', 'LP')), directory_count=2),
|
||||
catalog_reader=catalog, status_refresher=lambda names, _: (
|
||||
still_active.append(tuple(names)) or {name: ('READY' if len(calls) == 1 else 'PENDING') for name in names}))
|
||||
try:
|
||||
load(window, qtbot)
|
||||
qtbot.waitUntil(lambda: window.ready_names == {'A'})
|
||||
window.load_button.click()
|
||||
qtbot.waitUntil(lambda: window.load_button.text() == '重试读取')
|
||||
assert window.ready_names == {'A'}
|
||||
assert not window.batch_button.isEnabled()
|
||||
window.catalog_status_button.click()
|
||||
qtbot.waitUntil(lambda: window._records_by_name['A'].status == 'PENDING')
|
||||
assert window._records_by_name['Ghost'].status == 'UNKNOWN'
|
||||
assert not window.batch_button.isEnabled()
|
||||
assert len(calls) == 2 and still_active == [('A',), ('A',)]
|
||||
assert window.loaded_path is None
|
||||
finally:
|
||||
window.pool.waitForDone(6000)
|
||||
|
||||
|
||||
def test_catalog_switch_retains_complete_snapshot_and_ignores_duplicate_reads(qtbot, tmp_path, monkeypatch):
|
||||
from threading import Event
|
||||
from cbb_refresh_verify.management import Catalog, CatalogEntry
|
||||
from cbb_refresh_verify.ui import main_window as ui
|
||||
from test_issue15_ui_integration import load
|
||||
|
||||
paths = {name: tmp_path/name/'lib.lmc' for name in ('A', 'B')}
|
||||
for name, library in paths.items():
|
||||
(library.parent/'ReusableBlocksLP'/name).mkdir(parents=True)
|
||||
library.write_bytes(b'catalog')
|
||||
reading, allow_return = Event(), Event()
|
||||
calls = []
|
||||
|
||||
def catalog(path, _):
|
||||
calls.append(path.parent.name)
|
||||
if path == paths['B']:
|
||||
reading.set()
|
||||
assert allow_return.wait(5)
|
||||
return Catalog(path, 1, (CatalogEntry(path.parent.name, 'Logical-Physical'),))
|
||||
|
||||
def statuses(names, path, checkpoint=None, *, progress=None):
|
||||
checkpoint.parent.mkdir(parents=True, exist_ok=True)
|
||||
checkpoint.write_text(path.parent.name, encoding='utf-8')
|
||||
return {name: 'READY' for name in names}
|
||||
|
||||
monkeypatch.setattr(ui, 'authoritative_status_map', statuses)
|
||||
monkeypatch.setattr(ui, 'preflight_skip_reason', lambda *_: None)
|
||||
window = ui.MainWindow(data_root=tmp_path/'data', catalog_reader=catalog)
|
||||
qtbot.addWidget(window)
|
||||
window.show()
|
||||
try:
|
||||
load(window, qtbot, str(paths['A']))
|
||||
qtbot.waitUntil(lambda: window.ready_names == {'A'})
|
||||
load(window, qtbot, str(paths['B']))
|
||||
qtbot.waitUntil(reading.is_set)
|
||||
window.load_button.click()
|
||||
assert window.ready_names == {'A'}
|
||||
assert str(paths['A']) in window.library_notice.text()
|
||||
assert not window.batch_button.isEnabled()
|
||||
allow_return.set()
|
||||
qtbot.waitUntil(lambda: window.ready_names == {'B'})
|
||||
assert calls == ['A', 'B']
|
||||
assert (tmp_path/'data/status-refresh.jsonl').read_text('utf-8') == 'B'
|
||||
finally:
|
||||
allow_return.set()
|
||||
window.pool.waitForDone(6000)
|
||||
Reference in new issue
Block a user