Compare commits

...
4 Commits
Author SHA1 Message Date
阿白叔 1340f6c233 build: stage immutable release files without duplicate copies
Core regression / Python core and release configuration (push) Successful in 18s
Core regression / JavaScript syntax (push) Successful in 3s
2026-11-04 15:47:21 +08:00
阿白叔 5aeddacfc9 build: prepare V1.2.2 with portable 7-Zip self-extraction
Core regression / Python core and release configuration (push) Successful in 17s
Core regression / JavaScript syntax (push) Successful in 3s
2026-11-04 15:22:24 +08:00
abaishu0730 453d288a6c Merge pull request 'UI:完善毛玻璃工作台、操作历史和同任务安全续跑' (#15) from codex/ui-update into main
Core regression / Python core and release configuration (push) Successful in 16s
Core regression / JavaScript syntax (push) Successful in 4s
2026-11-04 14:40:47 +08:00
阿白叔 c86b0eefa0 fix-history-recording-at-service-commit-boundaries
Core regression / Python core and release configuration (push) Successful in 17s
Core regression / JavaScript syntax (push) Successful in 3s
Core regression / Python core and release configuration (pull_request) Successful in 16s
Core regression / JavaScript syntax (pull_request) Successful in 3s
2026-11-04 14:14:25 +08:00
17 changed files with 611 additions and 31 deletions

No files matched your search

+1
View File
@@ -38,6 +38,7 @@ jobs:
tests/dsh/test_issue_broker.py
tests/packaging/test_dsh_runtime_staging.py
tests/packaging/test_release_configuration.py
tests/packaging/test_self_extracting_release.py
--junitxml=build/ci-results.xml --tb=short
- name: Windows release scope
run: |
+6 -4
View File
@@ -4,11 +4,11 @@
面向 **Windows + DxDesigner / Expedition Enterprise 7.9.5** 的器件批量替换工具。一个工程对应一个任务,可以只替换同料号下的部分位号;支持直接编辑和 Excel BOM 导入,同批工程按顺序执行。
**最新版本:V1.2.1(预发布)** · [下载便携包](https://git.simgreek.com/Skyworth_Digital_Hardware/dxdesigner-part-replacement/releases/download/v1.2.1/DxPartReplace-1.2.1.zip) · [版本说明与附件](https://git.simgreek.com/Skyworth_Digital_Hardware/dxdesigner-part-replacement/releases/tag/v1.2.1) · [完整使用说明](docs/user/v1.1.0-project-tasks.md)
**最新版本:V1.2.2(预发布)** · [自解压 EXE](https://git.simgreek.com/Skyworth_Digital_Hardware/dxdesigner-part-replacement/releases/download/v1.2.2/DxPartReplace-1.2.2.exe) · [ZIP 便携包](https://git.simgreek.com/Skyworth_Digital_Hardware/dxdesigner-part-replacement/releases/download/v1.2.2/DxPartReplace-1.2.2.zip) · [版本说明与附件](https://git.simgreek.com/Skyworth_Digital_Hardware/dxdesigner-part-replacement/releases/tag/v1.2.2) · [完整使用说明](docs/user/v1.1.0-project-tasks.md)
V1.2.1 提供完整 Node/Qt 运行时、DSH 任务功能和全部 UI 资源。升级前备份 data,完整更新 EXE 与 _internal,不要只替换 EXE。
V1.2.2 新增操作历史、安全续跑与内置 7-Zip 的自解压 EXE,同时提供完整 Node/Qt 运行时、DSH 任务功能和全部 UI 资源。升级前备份 data,完整更新 EXE 与 _internal,不要只替换 EXE。
本版修复冻结应用缺少 SVG 资源的问题,保留维护者配置的工单上报能力,并增加云端 CI。[本版变更](docs/releases/v1.2.1.md)。
本版合并 PR15 与 PR17,补齐操作历史和模型设置,提供自解压 EXE 与 ZIP 两种同内容发行包。[本版变更](docs/releases/v1.2.2.md)。
本版提供[目标封装选择](docs/user/target-cell-selection.md):目标封装可留空,此时工具不主动覆写封装,可后续与中心库同步;需要指定时,在料号规则中读取并选择合法封装。BOM 保持原 11 列。
@@ -44,7 +44,9 @@ node tools/verify_dsh_runtime.mjs
### 第 1 步:解压并打开应用
[下载 V1.2.1 便携包](https://git.simgreek.com/Skyworth_Digital_Hardware/dxdesigner-part-replacement/releases/download/v1.2.1/DxPartReplace-1.2.1.zip),**完整解压**,双击 `DxPartReplace.exe`。保留它与 `_internal` 的相对位置,无需安装 Python;本机需要可用的 DxDesigner、许可证和中央库。
推荐下载上方自解压 EXE,双击后选择新的解压目录,完成后运行目录内的 DxPartReplace.exe。自解压引擎已内置,无需另外安装 7-Zip,也无需通过 Windows 资源管理器解压。
[下载 V1.2.2 便携包](https://git.simgreek.com/Skyworth_Digital_Hardware/dxdesigner-part-replacement/releases/download/v1.2.2/DxPartReplace-1.2.2.zip),**完整解压**,双击 `DxPartReplace.exe`。保留它与 `_internal` 的相对位置,无需安装 Python;本机需要可用的 DxDesigner、许可证和中央库。
打开后看到下图主窗口。首次使用请准备完整的工程副本,执行前保存并关闭待处理工程。
+7
View File
@@ -0,0 +1,7 @@
# V1.2.2
本版本合并 PR15 的操作历史与安全续跑改进,并提供带内置 7-Zip 解压引擎的 Windows 自解压包。
下载 `DxPartReplace-1.2.2.exe` 可使用自解压界面选择目标目录;`DxPartReplace-1.2.2.zip` 作为同内容回退包。两种包都包含完整的 `DxPartReplace.exe`、`_internal`、DSH Node 运行时、Qt WebEngine 依赖和资源文件。
解压后请保留 `DxPartReplace.exe` 与 `_internal` 的相对位置。本机仍需可用的 DxDesigner、许可证和中央库。沿用旧任务前先安全退出旧版本并备份 `data`,不要同时使用不同版本打开同一数据目录。
@@ -0,0 +1,43 @@
# PR #15:补齐业务变更的操作历史
针对[审查评论 179](https://git.simgreek.com/Skyworth_Digital_Hardware/dxdesigner-part-replacement/pulls/15#issuecomment-179)。修复范围为操作历史接入,不修改 DSH 业务逻辑,也不执行真实 CAD、模型或 DSH 运行时。
## 根因及修复边界
原实现依赖 `_MUTATIONS` 手工登记入口,遗漏时直接执行业务动作,不生成历史。助手创建任务、采集位号和重新读取绑定工程因此存在历史缺口。同类入口检查还发现 Value 策略已登记,但调用路径没有经过捕获器。
- 助手创建:纳入普通历史事务;一次确认产生的任务、工程和规则按任务分组记录,重放同一请求不重复生成历史。
- 采集位号:读取工程时保留原执行互斥,读取结束后仅对已有的位号保存事务捕获差异;默认料号、位号计划模式和新增位号一起记录。
- 重新读取:文件状态检查和随后上下文读取在历史事务外,只捕获 `sync_projects` 对工程可用性等字段的实际修改。
- Value 策略:复用统一的服务入口捕获逻辑,记录开关的前后值;重复保存相同值不生成记录。
采集和工程刷新使用显式的 `capture_history=False` 保留外层执行准入,并在内部短保存阶段调用历史捕获器,避免重复记录及长时间持有数据库访问锁。
## 回归证据
新增 13 项真实服务入口回归,覆盖四类操作的准确差异、助手请求重放、无变化刷新/轮询、重复采集、取消采集、四类历史写入失败时的事务回滚,以及 CAD 读取等待期间另一线程仍可写入独立历史。
断言按 `operation` 精确选择事件,检查实际字段前后值,避免全文搜索误命中临时工程路径造成假阳性。
在干净的 PR 提交 `56588a9` 源码快照上运行同一组精确记录断言,四项均因历史事件缺失失败;修复后的 13 项全部通过。未改动当前工作树源码来制造这个失败对照。
验证命令与结果:
- `python -m pytest -q tests/v1_1/test_history_service_entrypoints.py`:13 项通过。
- 历史及执行相关定向测试组:92 项通过;随后增加的 Value 策略回归包含在上述 13 项中。
- `python -m pytest -q tests/dsh tests/packaging tests/trial_task_center/test_service.py tests/trial_task_center/test_quick_run.py tests/trial_task_center/test_store.py`:282 项通过。
- 独立代码审查未发现可操作问题,包括 Value 策略入口及采集、刷新事务边界的补充检查。
### 原生脚本时限对照
同步工作目录中单独运行原生保护测试时,正向用例触发 `subprocess.TimeoutExpired`:`cscript.exe` 等待 Python 标记辅助程序超过测试的 15 秒限制;其他 4 个保护用例通过。直接调用同一标记程序和已生成的 VBScript 则正常返回,分别耗时 7.69 秒和 6.16 秒。
为区分代码差异和运行位置影响,将干净提交的源码、测试及 VBS 导出至 `F:/dxpt-ui-history-verify-20261104/entrypoint-baseline-2`,再将相同提交加本次全部 3 个源码修改导出至独立的 `native-current-snapshot`。两份快照在同步目录外运行原测试、保持原有 15 秒时限,均为 **5 项通过**(57.05 秒 / 49.54 秒)。没有改动原生保护代码或放宽测试时限。这支持运行位置/本机耗时影响的判断,尚未定位具体的系统级延迟来源。
### 默认全套
`python -m pytest -q --tb=short`:**1245 项通过、1 项超时失败、1 条现有 pywinauto STA 提示**,耗时 1169.33 秒。
该次超时出现在同组的 `missing-path` 参数分支,并非单独复跑时超时的正向分支,异常同为 `cscript.exe` 的 15 秒等待超时。两个版本快照的整个 5 项参数组均已通过,不能将本次默认全套描述为全部通过。原生测试、VBS、辅助程序和 DSH 源码均未修改。
全套结束后,在原同步工作目录中以原时限单独复跑 `-k missing-path`:**1 项通过、4 项未选择**,耗时 6.86 秒。
+6
View File
@@ -33,6 +33,12 @@ legacy_runtime_datas = [
# The native assistant loads the official web UI; include its pinned Node runtime.
dsh_root = project_root / 'integration' / 'dsh'
for required in ('node_modules/@deepseek-ai/dsh/package.json', 'issue-bootstrap.json',
'start.mjs', 'package.json', 'task-plugin/host.mjs'):
if not (dsh_root / required).is_file():
raise RuntimeError(f'Complete DSH release runtime is required; missing: {required}')
if shutil.which('node') is None:
raise RuntimeError('Node executable is required for the complete release')
if (dsh_root / 'issue-bootstrap.json').is_file():
legacy_runtime_datas.append((str(dsh_root / 'issue-bootstrap.json'), 'dsh-runtime'))
if (dsh_root / 'node_modules' / '@deepseek-ai' / 'dsh' / 'package.json').is_file():
+21
View File
@@ -0,0 +1,21 @@
# Windows self-extracting release
Build the complete application with `Build-DxPartReplace.ps1` first. The spec now fails if the installed DSH package, reporter configuration or Node executable is missing. Keep the entire installed `integration/dsh/node_modules` tree, including lazy runtime dependencies.
Use the official **7-Zip 26.05 x64** tools from:
- Binary: https://github.com/ip7z/7zip/releases/download/26.05/7z2605-x64.exe
- SHA256: `fd99e86f57d8f429ef5ed045bf98315af962e2309b0f1ba87a147a44c71647d0`
- Source and license: https://github.com/ip7z/7zip/releases/tag/26.05 and https://www.7-zip.org/license.txt
Extract the installer with an existing 7-Zip tool into a build-only directory. No machine-wide installation is needed. Use that directory's `7z.exe`, `7z.dll`, `7z.sfx` and `License.txt`. The standard `7z.sfx` opens a destination selector and extracts to a persistent directory. It is not the install-to-temp SFX module; it takes no installer configuration and does not auto-launch or delete the extracted application.
```powershell
python tools/build_self_extracting_release.py --source-dir dist/DxPartReplace --output-dir G:/dx-release-1.2.2 --version 1.2.2 --seven-zip build/7zip-2605/full/7z.exe --sfx-stub build/7zip-2605/full/7z.sfx --license build/7zip-2605/full/License.txt
```
Use a fresh output directory and keep the completed build input unchanged during packaging. The tool rejects an existing directory, overlapping input/output paths and an application input containing `data`. It stages the complete input using same-volume hardlinks (copying when links are unavailable), includes the 7-Zip license, produces independent EXE + ZIP archives, and writes artifact and per-file SHA256 hashes. LZMA2 level 3 and bounded solid blocks keep decoding memory modest; tiny files still incur filesystem costs, so do not promise a fixed speedup across machines.
Before publishing, run the self-extracting EXE itself with `-y -o<fresh directory>`, compare every resulting file and every ZIP member against the manifest, and run `tools/verify_packaged_runtime.py` and Qt/DSH UI acceptance on that extracted EXE. Neither merely listing the archive nor the source UI tests replaces this check.
The optional Windows integration test exercises the real SFX with Chinese/spaced paths and empty/binary files. Set `DX_SFX_TEST_TOOLS` to the official tools directory and run `python -m pytest tests/packaging/test_self_extracting_release.py`. Linux CI runs the portable output-protection checks and explicitly skips the Windows integration.
+4 -4
View File
@@ -1,8 +1,8 @@
# UTF-8
VSVersionInfo(
ffi=FixedFileInfo(
filevers=(1, 2, 1, 0),
prodvers=(1, 2, 1, 0),
filevers=(1, 2, 2, 0),
prodvers=(1, 2, 2, 0),
mask=0x3f,
flags=0x2,
OS=0x40004,
@@ -15,11 +15,11 @@ VSVersionInfo(
StringTable('040904B0', [
StringStruct('CompanyName', 'DxProductivity'),
StringStruct('FileDescription', 'DxDesigner Part Replacement'),
StringStruct('FileVersion', '1.2.1.0'),
StringStruct('FileVersion', '1.2.2.0'),
StringStruct('InternalName', 'DxPartReplace'),
StringStruct('OriginalFilename', 'DxPartReplace.exe'),
StringStruct('ProductName', 'DxDesigner Part Replacement'),
StringStruct('ProductVersion', '1.2.1')
StringStruct('ProductVersion', '1.2.2')
])
]),
VarFileInfo([VarStruct('Translation', [1033, 1200])])
+1 -1
View File
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "dx-productivity"
version = "1.2.1"
version = "1.2.2"
requires-python = ">=3.12,<3.13"
dependencies = ["PySide6>=6.7,<7", "pywin32>=306", "pywinauto>=0.6.9,<1", "openpyxl>=3.1,<4"]
@@ -17,22 +17,25 @@ from .store_read_model import checkpoint, read_lock
_MUTATIONS={
'create_task','create_project_tasks','create_scanned_task','update_task','delete_task',
'create_task','create_project_tasks','create_assistant_project_tasks','create_scanned_task','update_task','delete_task',
'restore_task','purge_task','add_rule','update_rule','delete_rule','move_rule',
'replace_target_plan','import_target_plan','save_bom_batch','save_plan_drafts',
'set_value_policy','move_project_task','set_project_selected','select_all_projects',
'clear_project_selection','scan_projects',
'clear_project_selection','scan_projects','refresh_bound_project','collect_target_inventory',
}
# start_new_round deliberately records inside its existing compensating
# transaction. Wrapping its filesystem moves in another transaction would let
# its inner savepoint report committed before the outer history COMMIT.
_LABELS={'create_task':'新建任务','create_project_tasks':'创建工程任务','create_scanned_task':'创建工程任务',
# Inventory collection and bound-project refresh capture only their save phase;
# their external reads and subsequent context reads stay outside this transaction.
_LABELS={'create_task':'新建任务','create_project_tasks':'创建工程任务','create_assistant_project_tasks':'助手创建工程任务','create_scanned_task':'创建工程任务',
'update_task':'编辑任务','delete_task':'归档任务','restore_task':'恢复任务','purge_task':'删除任务记录',
'add_rule':'添加规则','update_rule':'修改规则','delete_rule':'删除规则','move_rule':'调整规则顺序',
'replace_target_plan':'保存位号计划','import_target_plan':'导入位号计划','save_bom_batch':'保存 BOM 计划',
'save_plan_drafts':'保存位号计划','set_value_policy':'修改 Value 策略','move_project_task':'调整任务顺序',
'set_project_selected':'修改工程选择','select_all_projects':'全选工程',
'clear_project_selection':'清空工程选择','scan_projects':'扫描工程'}
'clear_project_selection':'清空工程选择','scan_projects':'扫描工程','refresh_bound_project':'重新读取工程',
'collect_target_inventory':'采集位号计划'}
_TABLES={
'tasks':(('task_id',),('task_id','name','note','discovery_root','status','copy_part_number_to_value',
@@ -276,9 +276,11 @@ class TaskCenterService:
paths = (project.path,)
except FileNotFoundError:
pass
self._store.sync_projects(task_id, project.discovery_root, paths)
from .history_recording import record_operation
record_operation(self, 'refresh_bound_project', task_id,
lambda: self._store.sync_projects(task_id, project.discovery_root, paths))
return self._refresh_project_context(task_id, allow_legacy=False)
return self._idle_quick_run_operation("refresh_bound_project", task_id, refresh)
return self._idle_quick_run_operation("refresh_bound_project", task_id, refresh, capture_history=False)
def _refresh_project_context(self, task_id: str, *, allow_legacy: bool, read_control=None) -> ProjectTaskContext:
def refresh() -> ProjectTaskContext:
@@ -478,16 +480,19 @@ class TaskCenterService:
runtime=runtime, **control_options(stop_event, on_progress))
check_cancelled(stop_event)
metric['completed_units'] = len(rows)
with self._store.transaction():
if self._store.list_target_plan(task_id) != prior:
raise TaskCenterError('target_identity', '位号计划在采集时已改变,请重新采集')
current = self._store.record_target_inventory(task_id, rows)
known = {row.target.key: row for row in prior}
seeded = seed_defaults(current, rules)
result = tuple(known.get(row.target.key, row) for row in seeded)
check_cancelled(stop_event)
return self._store.replace_target_plan(task_id, result)
return self._idle_quick_run_operation("collect_target_inventory", task_id, collect)
from .history_recording import record_operation
def save_inventory():
with self._store.transaction():
if self._store.list_target_plan(task_id) != prior:
raise TaskCenterError('target_identity', '位号计划在采集时已改变,请重新采集')
current = self._store.record_target_inventory(task_id, rows)
known = {row.target.key: row for row in prior}
seeded = seed_defaults(current, rules)
result = tuple(known.get(row.target.key, row) for row in seeded)
check_cancelled(stop_event)
return self._store.replace_target_plan(task_id, result)
return record_operation(self, 'collect_target_inventory', task_id, save_inventory)
return self._idle_quick_run_operation("collect_target_inventory", task_id, collect, capture_history=False)
def scan_projects(self, task_id: str, root: Path) -> tuple[ProjectRecord, ...]:
def scan_and_sync() -> tuple[ProjectRecord, ...]:
@@ -713,10 +718,7 @@ class TaskCenterService:
details={"copy_part_label_to_value": enabled})
return task
from .task_queue import assert_task_queue_idle
assert_task_queue_idle(self._logging.root)
with _quick_run_lease(self._logging.root):
return self._operation("set_value_policy", task_id, update)
return self._idle_quick_run_operation("set_value_policy", task_id, update)
def execute_quick_run(self, task_id: str, *, expected_item: tuple[str, str, str, str] | None = None, runtime=None) -> QuickRunStepResult:
"""Execute one replacement rule through restoration and verification."""
@@ -1229,12 +1231,17 @@ class TaskCenterService:
name: str,
task_id: str | None,
action: Callable[[], _Result],
*,
capture_history: bool = True,
) -> _Result:
from .task_queue import assert_task_queue_idle
assert_task_queue_idle(self._logging.root)
with _quick_run_lease(self._logging.root):
from .history_recording import record_operation
return self._operation(name, task_id, lambda: record_operation(self, name, task_id, action))
# External reads can capture their short save phase explicitly,
# retaining execution admission without holding the DB lock here.
wrapped = (lambda: record_operation(self, name, task_id, action)) if capture_history else action
return self._operation(name, task_id, wrapped)
def _manual_operation(self, name: str, task_id: str, action: Callable[[], _Result]) -> _Result:
def checked_action():
@@ -21,6 +21,8 @@ OPERATIONS={'quick_run_executed':'替换执行','quick_run_prepared':'准备执
'quick_run_recovered':'核验恢复','quick_run_queue_paused':'暂停执行',
'quick_run_retry_prepared':'准备失败项重试','create_project_tasks':'创建工程任务',
'create_task':'新建任务','update_task':'编辑任务','delete_task':'归档任务',
'create_assistant_project_tasks':'助手创建工程任务','collect_target_inventory':'采集位号计划',
'refresh_bound_project':'重新读取工程',
'restore_task':'恢复任务','purge_task':'删除任务记录','add_rule':'添加规则',
'update_rule':'修改规则','delete_rule':'删除规则','move_rule':'调整规则顺序',
'replace_target_plan':'保存位号计划','save_plan_drafts':'保存位号计划',
@@ -1 +1 @@
VERSION = "1.2.1"
VERSION = "1.2.2"
@@ -0,0 +1,81 @@
from pathlib import Path
import os
import subprocess
import sys
import zipfile
import pytest
ROOT = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(ROOT / 'tools'))
from build_self_extracting_release import build_release
from verify_self_extracting_release import verify
def test_release_refuses_existing_output_without_deleting_it(tmp_path):
source = tmp_path / 'app'
source.mkdir()
output = tmp_path / 'valuable'
output.mkdir()
sentinel = output / 'keep.txt'
sentinel.write_text('user files')
tool = tmp_path / 'tool.exe'
tool.write_bytes(b'MZ')
with pytest.raises((FileExistsError, ValueError)):
build_release(source, output, version='1.2.2', seven_zip=tool, sfx_stub=tool)
assert sentinel.read_text() == 'user files'
def test_release_rejects_output_inside_source(tmp_path):
source = tmp_path / 'app'
source.mkdir()
tool = tmp_path / 'tool.exe'
tool.write_bytes(b'MZ')
with pytest.raises(ValueError, match='inside'):
build_release(source, source / 'out', version='1.2.2', seven_zip=tool, sfx_stub=tool)
assert not (source / 'out').exists()
def test_release_refuses_user_data_in_payload(tmp_path):
source = tmp_path / 'app'
(source / 'data').mkdir(parents=True)
(source / 'data' / 'tasks.db').write_bytes(b'private')
tool = tmp_path / 'tool.exe'
tool.write_bytes(b'MZ')
with pytest.raises(ValueError, match='data'):
build_release(source, tmp_path / 'out', version='1.2.2', seven_zip=tool, sfx_stub=tool)
assert not (tmp_path / 'out').exists()
@pytest.mark.skipif(os.name != 'nt' or not os.environ.get('DX_SFX_TEST_TOOLS'),
reason='Windows and explicit official 7-Zip tools required')
def test_actual_sfx_and_zip_extract_identical_unicode_and_empty_files(tmp_path):
tools = Path(os.environ['DX_SFX_TEST_TOOLS']).resolve()
source = tmp_path / 'payload'
source.mkdir()
(source / 'DxPartReplace.exe').write_bytes(b'sample application')
(source / '中文 目录').mkdir()
(source / '中文 目录' / '空.txt').write_bytes(b'')
(source / '中文 目录' / 'file.bin').write_bytes(bytes(range(256)) * 2048)
(source / 'licenses').mkdir()
original_license=source/'licenses'/'7-Zip-LICENSE.txt'
original_license.write_text('original input must remain unchanged')
output = tmp_path / 'release'
manifest = build_release(source, output, version='1.2.2', seven_zip=tools/'7z.exe',
sfx_stub=tools/'7z.sfx', license_path=tools/'License.txt')
assert original_license.read_text() == 'original input must remain unchanged'
destination = tmp_path / '解压 结果'
result = verify(output/'release-manifest-1.2.2.json', destination)
assert result['passed'] and result['files'] == 4
with zipfile.ZipFile(output/'DxPartReplace-1.2.2.zip') as archive:
assert archive.testzip() is None
assert {p.relative_to(destination).as_posix() for p in destination.rglob('*') if p.is_file()} == set(archive.namelist())
assert len(archive.namelist()) == 4 == manifest['file_count']
for name in archive.namelist():
assert (destination/name).read_bytes() == archive.read(name)
assert (destination/'DxPartReplace'/'中文 目录'/'file.bin').read_bytes() == bytes(range(256))*2048
with (output/'DxPartReplace-1.2.2.exe').open('ab') as stream:
stream.write(b'corrupt download')
with pytest.raises(ValueError, match='Artifact checksum'):
verify(output/'release-manifest-1.2.2.json', tmp_path/'corrupt-extraction')
assert not (tmp_path/'corrupt-extraction').exists()
@@ -0,0 +1,173 @@
"""Real service mutations must commit their history at the same SQL boundary."""
from concurrent.futures import ThreadPoolExecutor
from threading import Event
from types import SimpleNamespace
import pytest
from dx_productivity.dsh.task_creation import validate_creation_spec
from dx_productivity.trial_task_center.errors import TaskCenterError
from dx_productivity.trial_task_center.history_store import HistoryRepository
from dx_productivity.trial_task_center.logging_setup import configure_logging
from dx_productivity.trial_task_center.service import TaskCenterService
from dx_productivity.trial_task_center.store import TaskStore
from dx_productivity.trial_task_center.target_plan import ComponentTarget
@pytest.fixture
def case(tmp_path):
root=tmp_path/'projects'
paths=[]
for name in ('A','B'):
path=root/name/'board.prj';path.parent.mkdir(parents=True)
path.write_text('KEY FrontEndSnapshot "DxD"\nKEY iCDBDir "database"\n')
paths.append(path)
store=TaskStore(tmp_path/'tasks.db')
service=TaskCenterService(store,configure_logging(tmp_path/'data'))
spec=validate_creation_spec({'name':'Assistant history','note':'sample',
'rules':[{'old_part_number':'OLD','new_part_number':'NEW'}]})
yield SimpleNamespace(store=store,service=service,root=root,paths=tuple(paths),spec=spec,
history=HistoryRepository(store))
store.close()
def bound_task(case):
task=case.service.create_project_tasks(case.root,selected_paths=(case.paths[0],))[0]
case.service.add_rule(task.task_id,'OLD','NEW')
target=ComponentTarget(case.paths[0],'MAIN','1','uid-1','R1','OLD','10K')
case.service.for_project_task(task.task_id)._quick_run_preparer.collect_inventory=lambda *args,**kwargs:(target,)
return task
def events(case,operation):
return tuple(row for row in case.history.page().rows if row['operation']==operation)
def test_assistant_creation_records_task_project_and_rule_changes_per_task(case):
result=case.service.create_assistant_project_tasks('a'*32,case.spec,case.root,case.paths)
rows=events(case,'create_assistant_project_tasks')
assert len(rows)==2 and {row['task_id'] for row in rows}==set(result['task_ids'])
for row in rows:
changes=row['details']['changes']
assert {change['table'] for change in changes}=={'tasks','projects','rules'}
assert all(change['before'] is None for change in changes)
rule=next(change for change in changes if change['table']=='rules')
assert rule['after']['old_part_number']=='OLD' and rule['after']['new_part_number']=='NEW'
def test_assistant_request_replay_does_not_duplicate_history(case):
first=case.service.create_assistant_project_tasks('a'*32,case.spec,case.root,case.paths)
before=case.history.page().rows
replay=case.service.create_assistant_project_tasks('a'*32,case.spec,case.root,case.paths)
assert replay['replayed'] and replay['task_ids']==first['task_ids']
assert case.history.page().rows==before
def test_refresh_bound_project_records_exact_availability_change(case):
task=bound_task(case)
case.paths[0].rename(case.paths[0].with_suffix('.moved'))
case.service.refresh_bound_project(task.task_id)
rows=events(case,'refresh_bound_project')
assert len(rows)==1
change=next(change for change in rows[0]['details']['changes'] if change['table']=='projects')
assert change['before']['available']==1 and change['after']['available']==0
assert not case.store.list_projects(task.task_id)[0].available
def test_unchanged_refresh_and_context_polling_do_not_manufacture_history(case):
task=bound_task(case)
before=case.history.page().rows
for _ in range(2):
case.service.refresh_bound_project(task.task_id)
case.service.task_context(task.task_id)
assert case.history.page().rows==before
def test_collect_inventory_records_plan_defaults_and_mode_in_one_event(case):
task=bound_task(case)
case.service.collect_target_inventory(task.task_id,('OLD',),runtime=object())
rows=events(case,'collect_target_inventory')
assert len(rows)==1 and rows[0]['task_id']==task.task_id
changes=rows[0]['details']['changes']
target=next(change for change in changes if change['table']=='target_plan')
assert target['before'] is None
assert target['after']['refdes']=='R1' and target['after']['new_part_number']=='NEW'
task_change=next(change for change in changes if change['table']=='tasks')
assert task_change['before']['target_plan_mode']==0 and task_change['after']['target_plan_mode']==1
def test_identical_inventory_collection_does_not_duplicate_history(case):
task=bound_task(case)
case.service.collect_target_inventory(task.task_id,('OLD',),runtime=object())
before=case.history.page().rows
case.service.collect_target_inventory(task.task_id,('OLD',),runtime=object())
assert case.history.page().rows==before
def test_value_policy_records_actual_change_and_ignores_repeated_value(case):
task=bound_task(case)
case.service.set_copy_part_number_to_value(task.task_id,True)
rows=events(case,'set_value_policy')
assert len(rows)==1
change=next(change for change in rows[0]['details']['changes'] if change['table']=='tasks')
assert change['before']['copy_part_number_to_value']==0 and change['after']['copy_part_number_to_value']==1
before=case.history.page().rows
case.service.set_copy_part_number_to_value(task.task_id,True)
assert case.history.page().rows==before
@pytest.mark.parametrize('operation',['create_assistant_project_tasks','collect_target_inventory','refresh_bound_project','set_value_policy'])
def test_history_write_failure_rolls_back_each_real_service_mutation(case,monkeypatch,operation):
task=None if operation=='create_assistant_project_tasks' else bound_task(case)
before=case.history.page().rows
def fail(*args,**kwargs):raise OSError('controlled history write failure')
monkeypatch.setattr(HistoryRepository,'append',fail)
with pytest.raises(TaskCenterError):
if operation=='create_assistant_project_tasks':
case.service.create_assistant_project_tasks('b'*32,case.spec,case.root,case.paths)
elif operation=='collect_target_inventory':
case.service.collect_target_inventory(task.task_id,('OLD',),runtime=object())
elif operation=='set_value_policy':
case.service.set_copy_part_number_to_value(task.task_id,True)
else:
case.paths[0].rename(case.paths[0].with_suffix('.moved'))
case.service.refresh_bound_project(task.task_id)
assert case.history.page().rows==before
if task is None:
assert case.store.list_tasks()==() and case.store.assistant_creation_receipt('b'*32) is None
elif operation=='collect_target_inventory':
assert case.store.list_target_plan(task.task_id)==() and not case.store.get_task(task.task_id).target_plan_mode
elif operation=='set_value_policy':
assert not case.store.get_task(task.task_id).copy_part_number_to_value
else:
assert case.store.list_projects(task.task_id)[0].available
def test_cancelled_inventory_read_saves_neither_plan_nor_history(case):
task=bound_task(case)
before=case.history.page().rows;stop=Event()
def collect(*args,**kwargs):stop.set();return ()
case.service.for_project_task(task.task_id)._quick_run_preparer.collect_inventory=collect
with pytest.raises(TaskCenterError) as error:
case.service.collect_target_inventory(task.task_id,('OLD',),runtime=object(),stop_event=stop)
assert error.value.code=='operation_cancelled'
assert case.history.page().rows==before and not case.store.list_target_plan(task.task_id)
def test_history_writes_remain_available_while_cad_inventory_read_is_waiting(case):
task=bound_task(case);started=Event();release=Event()
def collect(*args,**kwargs):
started.set()
if not release.wait(5):raise RuntimeError('inventory test was not released')
return (ComponentTarget(case.paths[0],'MAIN','1','uid-1','R1','OLD','10K'),)
case.service.for_project_task(task.task_id)._quick_run_preparer.collect_inventory=collect
with ThreadPoolExecutor(max_workers=2) as pool:
inventory=pool.submit(case.service.collect_target_inventory,task.task_id,('OLD',),runtime=object())
try:
assert started.wait(3)
other=pool.submit(case.history.append,task_id=task.task_id,task_name=task.name,
operation='probe',summary='concurrent history write')
other.result(timeout=2)
finally:release.set()
assert inventory.result(timeout=5)
assert len(events(case,'collect_target_inventory'))==1 and len(events(case,'probe'))==1
+130
View File
@@ -0,0 +1,130 @@
"""Create the ZIP and 7-Zip self-extracting artifacts for a release."""
from __future__ import annotations
import argparse
import hashlib
import json
import os
import re
from pathlib import Path
import shutil
import subprocess
import zipfile
from self_extracting_release import build_sfx
def _sha256(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as stream:
for chunk in iter(lambda: stream.read(1024 * 1024), b""):
digest.update(chunk)
return digest.hexdigest()
def _zip_tree(source: Path, output: Path) -> int:
files = 0
with zipfile.ZipFile(output, "x", compression=zipfile.ZIP_DEFLATED, compresslevel=6, allowZip64=True) as archive:
for path in sorted(source.rglob("*")):
if path.is_file():
archive.write(path, path.relative_to(source.parent).as_posix())
files += 1
return files
def _stage_file(source, destination):
# Release input is immutable during packaging. Same-volume links avoid a
# second copy of tens of thousands of runtime files; archives are independent.
try:
os.link(source, destination)
except OSError:
shutil.copyfile(source, destination)
return destination
def build_release(source_dir: Path, output_dir: Path, *, version: str, seven_zip: Path, sfx_stub: Path,
license_path: Path | None = None) -> dict:
source_dir = Path(source_dir).resolve(strict=True)
output_dir = Path(output_dir).resolve()
if not source_dir.is_dir():
raise ValueError("source_dir must be a directory")
if output_dir.is_relative_to(source_dir) or source_dir.is_relative_to(output_dir):
raise ValueError('Output must not be inside or contain the source directory')
if (source_dir / 'data').exists():
raise ValueError('Release input must not include user data')
if not re.fullmatch(r'[0-9]+\.[0-9]+\.[0-9]+(?:-[A-Za-z0-9.]+)?', version):
raise ValueError('Invalid release version')
seven_zip = Path(seven_zip).resolve(strict=True)
sfx_stub = Path(sfx_stub).resolve(strict=True)
output_dir.mkdir(parents=True, exist_ok=False)
staging = output_dir / "staging" / "DxPartReplace"
shutil.copytree(source_dir, staging, copy_function=_stage_file)
if license_path is not None:
license_target = staging / "licenses" / "7-Zip-LICENSE.txt"
license_target.parent.mkdir(parents=True, exist_ok=True)
# Break a possible staging hardlink before replacing a pre-existing notice.
license_target.unlink(missing_ok=True)
shutil.copyfile(Path(license_path).resolve(strict=True), license_target)
archive_7z = output_dir / f"DxPartReplace-{version}.7z"
subprocess.run([
str(seven_zip), "a", "-t7z", "-mx=3", "-m0=LZMA2", "-mmt=4", "-ms=64m",
str(archive_7z), "DxPartReplace"
], cwd=staging.parent, check=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True,
timeout=3600)
zip_path = output_dir / f"DxPartReplace-{version}.zip"
file_count = _zip_tree(staging, zip_path)
sfx_path = output_dir / f"DxPartReplace-{version}.exe"
build_sfx(sfx_stub, archive_7z, sfx_path)
archive_7z.unlink()
manifest = {
"version": version,
"file_count": file_count,
"artifacts": {
zip_path.name: {"bytes": zip_path.stat().st_size, "sha256": _sha256(zip_path)},
sfx_path.name: {"bytes": sfx_path.stat().st_size, "sha256": _sha256(sfx_path)},
},
"extractor": {
"kind": "7zip-sfx",
"stub": sfx_stub.name,
"stub_sha256": _sha256(sfx_stub),
"compressor": seven_zip.name,
"compressor_sha256": _sha256(seven_zip),
"version_output": subprocess.check_output([str(seven_zip)], text=True, errors='replace')[:500],
"settings": "LZMA2 level 3, 4 threads, 64 MiB solid blocks",
},
"files": {path.relative_to(staging.parent).as_posix(): _sha256(path)
for path in sorted(staging.rglob('*')) if path.is_file()},
}
(output_dir / f"release-manifest-{version}.json").write_text(
json.dumps(manifest, ensure_ascii=False, indent=2) + "\n", encoding="utf-8"
)
(output_dir / f"SHA256SUMS-{version}.txt").write_text(
"".join(f"{item['sha256']} {name}\n" for name, item in manifest["artifacts"].items()),
encoding="ascii",
)
return manifest
def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument("--source-dir", type=Path, required=True)
parser.add_argument("--output-dir", type=Path, required=True)
parser.add_argument("--version", required=True)
parser.add_argument("--seven-zip", type=Path, required=True)
parser.add_argument("--sfx-stub", type=Path, required=True)
parser.add_argument("--license", type=Path)
args = parser.parse_args()
manifest = build_release(args.source_dir, args.output_dir, version=args.version,
seven_zip=args.seven_zip, sfx_stub=args.sfx_stub,
license_path=args.license)
print(json.dumps(manifest, ensure_ascii=False, indent=2))
return 0
if __name__ == "__main__":
raise SystemExit(main())
+45
View File
@@ -0,0 +1,45 @@
"""Build a 7-Zip SFX wrapper around a prepared .7z release archive."""
from __future__ import annotations
from pathlib import Path
import os
import shutil
def build_sfx(
stub: Path,
archive: Path,
output: Path,
) -> Path:
"""Use the official 7z.sfx extractor (not the temporary installer stub).
Its native dialog selects a persistent destination. No installer config,
registry modifications, temporary extraction or automatic launch is needed.
"""
stub = Path(stub)
archive = Path(archive)
output = Path(output)
if not stub.is_file() or not archive.is_file():
raise FileNotFoundError("SFX stub and archive must both exist")
if output.exists():
raise FileExistsError(output)
with stub.open('rb') as stream:
if stream.read(2) != b'MZ':
raise ValueError('Expected Windows SFX executable')
with archive.open('rb') as stream:
if stream.read(6) != b'7z\xbc\xaf\x27\x1c':
raise ValueError('Expected 7z archive')
output.parent.mkdir(parents=True, exist_ok=True)
temporary = output.with_name(f".{output.name}.{os.getpid()}.tmp")
try:
with temporary.open("xb") as target:
for source in (stub, archive):
with source.open('rb') as stream:
shutil.copyfileobj(stream, target, 1024 * 1024)
target.flush()
os.fsync(target.fileno())
os.replace(temporary, output)
finally:
temporary.unlink(missing_ok=True)
return output
+59
View File
@@ -0,0 +1,59 @@
"""Run the delivered SFX and verify its files and every ZIP member against SHA256."""
import argparse
import hashlib
import json
import os
from pathlib import Path
import subprocess
import time
import zipfile
def digest(stream):
return hashlib.file_digest(stream, 'sha256').hexdigest()
def verify(manifest_path: Path, destination: Path):
manifest = json.loads(manifest_path.read_text(encoding='utf-8'))
root = manifest_path.resolve().parent
destination = destination.resolve()
if destination.exists():
raise FileExistsError('Use a fresh extraction destination')
for name, expected in manifest['artifacts'].items():
with (root/name).open('rb') as stream:
if digest(stream) != expected['sha256']:
raise ValueError('Artifact checksum mismatch: '+name)
version = manifest['version']
started = time.monotonic()
subprocess.run([str(root/f'DxPartReplace-{version}.exe'), '-y', '-o'+str(destination)],
check=True, timeout=1800, creationflags=getattr(subprocess, 'CREATE_NO_WINDOW', 0))
elapsed = time.monotonic()-started
actual = {p.relative_to(destination).as_posix(): p for p in destination.rglob('*') if p.is_file()}
if set(actual) != set(manifest['files']):
raise ValueError('Self-extracted file set differs from manifest')
for name, path in actual.items():
with path.open('rb') as stream:
if digest(stream) != manifest['files'][name]:
raise ValueError('Self-extracted checksum mismatch: '+name)
with zipfile.ZipFile(root/f'DxPartReplace-{version}.zip') as archive:
if len(archive.namelist()) != len(actual) or set(archive.namelist()) != set(actual):
raise ValueError('ZIP file set differs from manifest')
# Reading to EOF also checks ZIP CRC for every member.
for name in archive.namelist():
with archive.open(name) as stream:
if digest(stream) != manifest['files'][name]:
raise ValueError('ZIP checksum mismatch: '+name)
return dict(passed=True, files=len(actual), sfx_extraction_seconds=round(elapsed, 3),
actual_sfx_executed=True, zip_crc_and_sha256=True,
destination=str(destination))
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('manifest', type=Path)
parser.add_argument('destination', type=Path)
parser.add_argument('--report', type=Path, required=True)
args = parser.parse_args()
result = verify(args.manifest, args.destination)
args.report.write_text(json.dumps(result, ensure_ascii=False, indent=2)+'\n', encoding='utf-8')
print(json.dumps(result, ensure_ascii=False, indent=2))