Extract read-only project discovery worker orchestration
This commit is contained in:
1 parent
e265ca515d
commit
80f1cfd799
2 files changed
+200
No files matched your search
@@ -0,0 +1,95 @@
|
||||
"""Read-only project discovery worker orchestration, independent of execution queues."""
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
from uuid import uuid4
|
||||
|
||||
from .errors import TaskCenterError
|
||||
from .quick_run_protocol import ProjectDiscovery, _encode_vbs_field
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class DiscoveryRuntime:
|
||||
"""Worker and evidence adapters shared with the execution entry point."""
|
||||
process_runner: Callable[[tuple[str, ...], int], subprocess.CompletedProcess[str]]
|
||||
cscript_resolver: Callable[[], Path]
|
||||
worker_paths: Callable[[Path, Path], tuple[str, str]]
|
||||
helper_launch_arguments: Callable[[], tuple[str, ...]]
|
||||
failure_message: Callable[[str], str]
|
||||
read_sheets: Callable[[Path, Path], tuple[tuple[str, str], ...]]
|
||||
read_matches: Callable[[Path, Path, tuple[tuple[str, str], ...]], dict[tuple[str, str], frozenset[str]]]
|
||||
timeout: int
|
||||
|
||||
|
||||
def discover_project(
|
||||
project_path: Path,
|
||||
old_part_numbers: tuple[str, ...],
|
||||
*,
|
||||
data_root: Path,
|
||||
script_source: Path,
|
||||
runtime: DiscoveryRuntime,
|
||||
collect_components: bool = False,
|
||||
) -> ProjectDiscovery:
|
||||
"""Enumerate sheets and requested source parts while the owned project is open."""
|
||||
project = project_path.resolve(strict=True)
|
||||
token = uuid4().hex
|
||||
job_id = "discover_" + token
|
||||
root = data_root / "quick-run-history" / ("sheet-discovery-" + token)
|
||||
root.mkdir(parents=True, exist_ok=False)
|
||||
script = root / "QuickPartReplace.vbs"
|
||||
shutil.copyfile(script_source, script)
|
||||
(root / "command.tsv").write_text(
|
||||
"task_id\tjob_id\tproject_path\told_part\tnew_part\tvalue_mode\r\n"
|
||||
f"sheet_discovery\t{job_id}\t{project}\tDISCOVERY_OLD\tDISCOVERY_NEW\tpreserve\r\n",
|
||||
encoding="utf-8",
|
||||
newline="",
|
||||
)
|
||||
(root / "status.tsv").write_text("job_id\tstate\tcode\tmessage\r\n", encoding="utf-8", newline="")
|
||||
(root / "batch.request").write_text(job_id, encoding="ascii")
|
||||
(root / "sheet-discovery.request").write_text(job_id, encoding="ascii")
|
||||
requested: dict[str, str] = {}
|
||||
for old_part_number in old_part_numbers:
|
||||
requested.setdefault(old_part_number.casefold(), old_part_number)
|
||||
(root / "inventory-request.tsv").write_text(
|
||||
"old_part\r\n" + "".join(
|
||||
f"{_encode_vbs_field(old_part_number)}\r\n"
|
||||
for old_part_number in requested.values()
|
||||
),
|
||||
encoding="utf-8",
|
||||
newline="",
|
||||
)
|
||||
if collect_components:
|
||||
(root / "component-inventory.request").write_text(job_id, encoding="ascii")
|
||||
script_argument, root_argument = runtime.worker_paths(script, root)
|
||||
command = (
|
||||
str(runtime.cscript_resolver()),
|
||||
"//nologo",
|
||||
script_argument,
|
||||
root_argument,
|
||||
*runtime.helper_launch_arguments(),
|
||||
job_id,
|
||||
)
|
||||
try:
|
||||
completed = runtime.process_runner(command, runtime.timeout)
|
||||
except (OSError, subprocess.SubprocessError) as error:
|
||||
raise TaskCenterError(
|
||||
"quick_run_sheet_discovery",
|
||||
f"枚举工程图页时执行器未能安全结束:{project};{error}",
|
||||
) from error
|
||||
(root / "worker-output.txt").write_text(completed.stdout + "\n" + completed.stderr, encoding="utf-8")
|
||||
if completed.returncode != 0:
|
||||
detail = completed.stderr.strip() or completed.stdout.strip() or "sheet discovery failed"
|
||||
raise TaskCenterError("quick_run_sheet_discovery", runtime.failure_message(detail))
|
||||
sheets = runtime.read_sheets(root / "sheets.tsv", project)
|
||||
matches = runtime.read_matches(root / "inventory.tsv", project, sheets)
|
||||
if collect_components:
|
||||
from .inventory import read_component_inventory
|
||||
components = read_component_inventory(root / "components.tsv", project, sheets)
|
||||
else:
|
||||
components = ()
|
||||
return ProjectDiscovery(sheets, matches, components)
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
"""Discovery orchestration uses injected workers and validates their evidence."""
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
|
||||
import pytest
|
||||
|
||||
from dx_productivity.trial_task_center import quick_run
|
||||
from dx_productivity.trial_task_center.errors import TaskCenterError
|
||||
from dx_productivity.trial_task_center.quick_run import QuickRunPreparer
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def discovery(tmp_path, monkeypatch):
|
||||
project = tmp_path / 'board.prj'
|
||||
project.write_text('project')
|
||||
source = tmp_path / 'runtime.vbs'
|
||||
source.write_text('runtime sentinel')
|
||||
roots = []
|
||||
def worker_paths(script, root):
|
||||
assert script.read_text() == 'runtime sentinel'
|
||||
roots.append(root)
|
||||
return 'short-script.vbs', 'short-root'
|
||||
monkeypatch.setattr(quick_run, '_vbs_worker_paths', worker_paths)
|
||||
monkeypatch.setattr(quick_run, '_native_helper_launch_arguments', lambda: ('helper.vbs', 'bridge.ps1'))
|
||||
def prepare(runner):
|
||||
return QuickRunPreparer(tmp_path / 'data', script_source=source,
|
||||
process_runner=runner, cscript_resolver=lambda: Path('injected-cscript.exe'))
|
||||
return project, roots, prepare
|
||||
|
||||
|
||||
def write_evidence(root, project, *, corrupt=False):
|
||||
evidence_project = root / 'foreign.prj' if corrupt else project
|
||||
(root / 'sheets.tsv').write_text(
|
||||
'project_path\tschematic_name\tsheet_number\n' + f'{evidence_project}\tMAIN\t1\n')
|
||||
(root / 'inventory.tsv').write_text(
|
||||
'project_path\tschematic_name\tsheet_number\told_part\n' + f'{project}\tMAIN\t1\tOLD\n')
|
||||
(root / 'components.tsv').write_text(
|
||||
'project_path\tschematic_name\tsheet_number\tuid\trefdes\told_part\told_value\n'
|
||||
+ f'{project}\tMAIN\t1\tu1\tR1\tOLD\t10k\n')
|
||||
|
||||
|
||||
def test_discovery_preserves_worker_paths_protocol_and_component_inventory(discovery):
|
||||
project, roots, prepare = discovery
|
||||
def worker(command, timeout):
|
||||
assert command[:6] == ('injected-cscript.exe', '//nologo', 'short-script.vbs',
|
||||
'short-root', 'helper.vbs', 'bridge.ps1')
|
||||
assert timeout == quick_run.IDLE_PROGRESS_TIMEOUT_SECONDS
|
||||
root = roots[-1]
|
||||
job = command[-1]
|
||||
assert job.startswith('discover_')
|
||||
for marker in ('batch.request', 'sheet-discovery.request', 'component-inventory.request'):
|
||||
assert (root / marker).read_text() == job
|
||||
assert (root / 'inventory-request.tsv').read_text().splitlines() == ['old_part', 'OLD', 'A%0009B']
|
||||
assert (root / 'command.tsv').read_text().splitlines()[1].split('\t')[2] == str(project)
|
||||
write_evidence(root, project)
|
||||
return subprocess.CompletedProcess(command, 0, 'worker stdout', 'worker stderr')
|
||||
result = prepare(worker)._discover_project_sheets(project, ('OLD', 'old', 'A\tB'), collect_components=True)
|
||||
assert result.sheets == (('MAIN', '1'),)
|
||||
assert result.matched_old_parts == {('MAIN', '1'): frozenset({'old'})}
|
||||
assert len(result.components) == 1 and result.components[0].refdes == 'R1'
|
||||
assert (roots[0] / 'worker-output.txt').read_text() == 'worker stdout\nworker stderr'
|
||||
|
||||
|
||||
def test_discovery_without_components_never_requests_or_requires_component_file(discovery):
|
||||
project, roots, prepare = discovery
|
||||
def worker(command, timeout):
|
||||
root = roots[-1]
|
||||
assert not (root / 'component-inventory.request').exists()
|
||||
write_evidence(root, project)
|
||||
(root / 'components.tsv').unlink()
|
||||
return subprocess.CompletedProcess(command, 0, '', '')
|
||||
result = prepare(worker)._discover_project_sheets(project, ('OLD',))
|
||||
assert result.components == ()
|
||||
|
||||
|
||||
@pytest.mark.parametrize('failure', [OSError('launch failed'), subprocess.TimeoutExpired('worker', 150)])
|
||||
def test_discovery_worker_failures_keep_stable_error_code(discovery, failure):
|
||||
project, roots, prepare = discovery
|
||||
def worker(command, timeout):
|
||||
raise failure
|
||||
with pytest.raises(TaskCenterError) as raised:
|
||||
prepare(worker)._discover_project_sheets(project, ('OLD',))
|
||||
assert raised.value.code == 'quick_run_sheet_discovery'
|
||||
assert raised.value.__cause__ is failure
|
||||
|
||||
|
||||
def test_discovery_nonzero_exit_keeps_operator_diagnostic_and_output(discovery):
|
||||
project, roots, prepare = discovery
|
||||
def worker(command, timeout):
|
||||
return subprocess.CompletedProcess(command, 1, 'stdout', 'another project is already open')
|
||||
with pytest.raises(TaskCenterError) as raised:
|
||||
prepare(worker)._discover_project_sheets(project, ('OLD',))
|
||||
assert raised.value.code == 'quick_run_sheet_discovery'
|
||||
assert 'another project is already open' in str(raised.value)
|
||||
assert '保存并关闭' in str(raised.value)
|
||||
assert (roots[0] / 'worker-output.txt').read_text().endswith('another project is already open')
|
||||
|
||||
|
||||
def test_discovery_rejects_foreign_sheet_evidence(discovery):
|
||||
project, roots, prepare = discovery
|
||||
def worker(command, timeout):
|
||||
write_evidence(roots[-1], project, corrupt=True)
|
||||
return subprocess.CompletedProcess(command, 0, '', '')
|
||||
with pytest.raises(TaskCenterError, match='another project'):
|
||||
prepare(worker)._discover_project_sheets(project, ('OLD',))
|
||||
Reference in new issue
Block a user