修复:旧浏览器样式与安全操作编号兼容,复用已完成的 Windows 数据库恢复
This commit is contained in:
@@ -24,6 +24,16 @@ Linux 默认只允许本机访问,使用 `./start.sh --lan` 开启内网监听
|
||||
|
||||
维护人员可运行 `python3 deploy/offline/repair_windows_cache.py --write-command /path/to/修复缓存校验并启动.cmd` 生成单文件修复工具。后续构建会在生成清单前移除可再生缓存,Windows 入口同时设置 `PYTHONDONTWRITEBYTECODE=1`。
|
||||
|
||||
## Windows 来源路径校验修复与已导入库续用
|
||||
|
||||
若迁移在“来源文件路径重绑定失败”处停止,维护人员可生成 `修复来源路径并继续恢复.cmd`,放到原 QualityCenter 根目录后双击。工具仅接受已核验的原交付恢复脚本,备份该脚本和 manifest,再修复 Windows 反斜杠的数据库输出校验;此前的 Python 缓存修复保留。
|
||||
|
||||
此入口强制“只复用已导入库”:核对暂存恢复库的数据表行数、原账号、正式统计结果、来源引用及归档文件摘要后,继续路径绑定和配置切换。未通过校验会停止,绝不自动重新导入 SQL。既有库、迁移包及失败现场保留。需使用本入口完成续用;成功后原入口会根据迁移回执直接启动。
|
||||
|
||||
```sh
|
||||
python3 deploy/offline/repair_windows_source_paths.py --write-command /path/to/修复来源路径并继续恢复.cmd
|
||||
```
|
||||
|
||||
## Windows 增量更新包(维护人员)
|
||||
|
||||
离线签名工具读取 Windows x64 部署包的 `manifest.json`,只打包 `update_manager.program_path` 认可的完整程序清单,并使用包内运行环境和 wheel 信息计算运行时指纹。私有配置、业务数据、迁移文件、启动引导和密钥不会进入更新包。普通发布的序号必须大于部署包当前的 `updateSequence`。首次通道种子可显式加 `--allow-baseline`,但版本和序号必须分别与 `updateVersion`、`updateSequence` 完全相同;低序号始终拒绝。私钥必须是与包内更新公钥匹配的 Ed25519 PEM 文件,并保存在部署包及产物目录之外。
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -121,13 +121,98 @@ def rebind_sources(query, manifest, archive):
|
||||
raise RuntimeError('来源文件校验失败,恢复未切换。')
|
||||
query('UPDATE `' + entry['table'] + '` SET `' + entry['column'] + '`=' + sql_text(str(target))
|
||||
+ ' WHERE id=' + sql_text(entry['id']) + ' AND `' + entry['column'] + '`=' + sql_text(entry['oldPath']) + ';')
|
||||
actual = query('SELECT `' + entry['column'] + '` FROM `' + entry['table'] + '` WHERE id=' + sql_text(entry['id']) + ';').strip()
|
||||
if actual != str(target):
|
||||
actual = query('SELECT HEX(`' + entry['column'] + '`) FROM `' + entry['table'] + '` WHERE id=' + sql_text(entry['id']) + ';').strip().lower()
|
||||
# 按 UTF-8 十六进制核对,避免 mysql --batch 转义 Windows 反斜杠。
|
||||
if actual != str(target).encode('utf-8').hex():
|
||||
raise RuntimeError('来源文件路径重绑定失败。')
|
||||
counts[entry['table']] += 1
|
||||
return counts
|
||||
|
||||
|
||||
def restored_source_paths(query, manifest):
|
||||
"""批量读取原始路径;HEX 避免 Windows 路径受到客户端转义影响。"""
|
||||
allowed = {('source_revision', 'archive_path'), ('source_candidate', 'source_path'),
|
||||
('source_candidate', 'archive_path'), ('source_upload_draft', 'source_path')}
|
||||
result = {}
|
||||
pairs = {(entry['table'], entry['column']) for entry in manifest['pathBindings']}
|
||||
if not pairs.issubset(allowed):
|
||||
raise RuntimeError('来源路径绑定类型无效。')
|
||||
for table, column in sorted(pairs):
|
||||
values = {}
|
||||
for line in query('SELECT id,HEX(`' + column + '`) FROM `' + table + '` WHERE `' + column + '` IS NOT NULL;').splitlines():
|
||||
identity, encoded = line.split('\t', 1)
|
||||
values[identity] = bytes.fromhex(encoded).decode('utf-8')
|
||||
for entry in manifest['pathBindings']:
|
||||
if (entry['table'], entry['column']) == (table, column):
|
||||
if entry['id'] not in values:
|
||||
raise RuntimeError('恢复库缺少已登记的来源引用。')
|
||||
result[(table, column, entry['id'])] = values[entry['id']]
|
||||
return result
|
||||
|
||||
|
||||
def reusable_archive(manifest, paths):
|
||||
"""只复用本部署目录此前恢复生成、且全部文件通过校验的归档。"""
|
||||
parent = (control.DATA / 'migrations').resolve()
|
||||
attempts = set()
|
||||
for entry in manifest['pathBindings']:
|
||||
actual = paths[(entry['table'], entry['column'], entry['id'])]
|
||||
if actual == entry['oldPath']:
|
||||
continue
|
||||
relative = relative_name(entry['relative'])
|
||||
path = Path(actual)
|
||||
if not path.is_absolute() or not path.resolve().is_relative_to(parent):
|
||||
raise RuntimeError('恢复库来源路径不属于本目录。')
|
||||
parts = path.relative_to(parent).parts
|
||||
if (len(parts) != len(relative.parts) + 2 or not re.fullmatch(r'[a-f0-9]{16}', parts[0])
|
||||
or parts[1] != 'archive' or tuple(parts[2:]) != relative.parts):
|
||||
raise RuntimeError('恢复库来源路径与原迁移包不一致。')
|
||||
attempts.add(parts[0])
|
||||
if len(attempts) != 1:
|
||||
raise RuntimeError('无法确定上次恢复的来源归档,未重新导入。')
|
||||
archive = parent / next(iter(attempts)) / 'archive'
|
||||
observed = {path.relative_to(archive).as_posix() for path in archive.rglob('*') if path.is_file()}
|
||||
if observed != set(manifest['archiveFiles']):
|
||||
raise RuntimeError('上次恢复的来源文件数量不一致。')
|
||||
for name, expected in manifest['archiveFiles'].items():
|
||||
target = archive.joinpath(*relative_name(name).parts)
|
||||
if (target.is_symlink() or not target.resolve().is_relative_to(archive.resolve())
|
||||
or target.stat().st_size != expected['bytes'] or sha256(target) != expected['sha256']):
|
||||
raise RuntimeError('上次恢复的来源文件未通过校验。')
|
||||
return archive
|
||||
|
||||
|
||||
def select_reusable_import(value, manifest):
|
||||
"""复核完整导入及来源文件后复用暂存库;绝不回退为重新导入。"""
|
||||
names = run_query(value, 'SHOW DATABASES;').splitlines()
|
||||
candidates = [name for name in names if re.fullmatch(r'quality_restore_[a-f0-9]{12,32}', name)
|
||||
and name != value.get('mysqlDatabase')]
|
||||
verified = []
|
||||
for name in candidates:
|
||||
query = lambda statement: run_query(value, statement, name)
|
||||
try:
|
||||
paths = restored_source_paths(query, manifest)
|
||||
archive = reusable_archive(manifest, paths)
|
||||
counts = table_counts(query)
|
||||
if counts != manifest['tableCounts']:
|
||||
continue
|
||||
users = [json.loads(line) for line in query("SELECT JSON_OBJECT('id',id,'username',username,'passwordHashSha256',SHA2(password_hash,256),'active',active) FROM app_user ORDER BY id;").splitlines()]
|
||||
if sorted(users, key=lambda row: row['id']) != sorted(manifest['sourceUsers'], key=lambda row: row['id']):
|
||||
continue
|
||||
if query_evidence(query) != manifest['queryEvidence']:
|
||||
continue
|
||||
# 已确认原路径或同一受控归档路径,后续仍以当前值作为条件更新。
|
||||
bound = {**manifest, 'pathBindings': [{**entry, 'oldPath': paths[(entry['table'], entry['column'], entry['id'])]}
|
||||
for entry in manifest['pathBindings']]}
|
||||
verified.append((archive.stat().st_mtime_ns, name, archive, counts, bound))
|
||||
except (RuntimeError, ValueError, OSError):
|
||||
continue
|
||||
if not verified:
|
||||
raise RuntimeError('未找到通过完整校验的已导入恢复库。已有数据库保留,本次未重新导入;请保留 runtimedata/logs 供核查。')
|
||||
_, database, archive, counts, bound = max(verified, key=lambda item: item[0])
|
||||
print('已核验并复用上次导入完成的数据库,跳过数据库重新导入。', flush=True)
|
||||
return database, archive, counts, bound
|
||||
|
||||
|
||||
def relocate_native(stage, source_root):
|
||||
source_root = PurePosixPath(source_root)
|
||||
def relocated(value):
|
||||
@@ -247,8 +332,11 @@ def restore_locked(check_runtime):
|
||||
raise RuntimeError('迁移包文件不完整,已停止恢复。')
|
||||
if manifest.get('modelConfigSha256') and sha256(PAYLOAD / 'model-config.json') != manifest['modelConfigSha256']:
|
||||
raise RuntimeError('模型配置校验失败。')
|
||||
if shutil.disk_usage(ROOT).free < manifest['minimumFreeBytes']:
|
||||
raise RuntimeError('可用磁盘空间不足,请至少预留 ' + str((manifest['minimumFreeBytes'] + 1024**3 - 1) // 1024**3) + ' GB。')
|
||||
reuse_only = os.environ.get('QUALITY_MIGRATION_REUSE_ONLY') == '1'
|
||||
required_free = (sum(item['bytes'] for item in manifest['nativeHistoryFiles'].values()) + 128 * 1024**2
|
||||
if reuse_only else manifest['minimumFreeBytes'])
|
||||
if shutil.disk_usage(ROOT).free < required_free:
|
||||
raise RuntimeError('可用磁盘空间不足,请至少预留 ' + str((required_free + 1024**3 - 1) // 1024**3) + ' GB。')
|
||||
attempt = uuid.uuid4().hex[:16]
|
||||
stage = control.PRIVATE / ('migration-stage-' + attempt)
|
||||
stage.mkdir(mode=0o700)
|
||||
@@ -256,7 +344,8 @@ def restore_locked(check_runtime):
|
||||
archive.parent.mkdir(parents=True, mode=0o700)
|
||||
native = stage / 'nao-users'
|
||||
print('正在恢复来源文件和分析历史……', flush=True)
|
||||
extract_checked(PAYLOAD / 'archive.tar.gz', archive, manifest['archiveFiles'])
|
||||
if not reuse_only:
|
||||
extract_checked(PAYLOAD / 'archive.tar.gz', archive, manifest['archiveFiles'])
|
||||
extract_checked(PAYLOAD / 'native-history.tar.gz', native, manifest['nativeHistoryFiles'])
|
||||
native_count = relocate_native(native, manifest['sourceProjectRoot'])
|
||||
if native_count != manifest['nativeHistoryDatabases']:
|
||||
@@ -271,18 +360,23 @@ def restore_locked(check_runtime):
|
||||
database = 'quality_restore_' + uuid.uuid4().hex
|
||||
try:
|
||||
start_database(value)
|
||||
run_query(value, 'CREATE DATABASE `' + database + '` CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci;')
|
||||
restore_dump(value, database, PAYLOAD / 'database.sql.gz')
|
||||
query = lambda statement: run_query(value, statement, database)
|
||||
print('正在核对全部数据表、原账号和正式统计结果……', flush=True)
|
||||
actual_counts = table_counts(query)
|
||||
if actual_counts != manifest['tableCounts']:
|
||||
raise RuntimeError('恢复后的数据表行数不一致,未切换正式使用库。')
|
||||
actual_users = [json.loads(line) for line in query("SELECT JSON_OBJECT('id',id,'username',username,'passwordHashSha256',SHA2(password_hash,256),'active',active) FROM app_user ORDER BY id;").splitlines()]
|
||||
if sorted(actual_users, key=lambda row: row['id']) != sorted(manifest['sourceUsers'], key=lambda row: row['id']):
|
||||
raise RuntimeError('原用户账号校验失败,未切换使用库。')
|
||||
if query_evidence(query) != manifest['queryEvidence']:
|
||||
raise RuntimeError('正式版本和月度统计结果不一致,未切换使用库。')
|
||||
if reuse_only:
|
||||
print('正在核验上次已导入的数据库和来源文件,不会重新导入……', flush=True)
|
||||
database, archive, actual_counts, manifest = select_reusable_import(value, manifest)
|
||||
query = lambda statement: run_query(value, statement, database)
|
||||
else:
|
||||
run_query(value, 'CREATE DATABASE `' + database + '` CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci;')
|
||||
restore_dump(value, database, PAYLOAD / 'database.sql.gz')
|
||||
query = lambda statement: run_query(value, statement, database)
|
||||
print('正在核对全部数据表、原账号和正式统计结果……', flush=True)
|
||||
actual_counts = table_counts(query)
|
||||
if actual_counts != manifest['tableCounts']:
|
||||
raise RuntimeError('恢复后的数据表行数不一致,未切换正式使用库。')
|
||||
actual_users = [json.loads(line) for line in query("SELECT JSON_OBJECT('id',id,'username',username,'passwordHashSha256',SHA2(password_hash,256),'active',active) FROM app_user ORDER BY id;").splitlines()]
|
||||
if sorted(actual_users, key=lambda row: row['id']) != sorted(manifest['sourceUsers'], key=lambda row: row['id']):
|
||||
raise RuntimeError('原用户账号校验失败,未切换使用库。')
|
||||
if query_evidence(query) != manifest['queryEvidence']:
|
||||
raise RuntimeError('正式版本和月度统计结果不一致,未切换使用库。')
|
||||
rebound = rebind_sources(query, manifest, archive)
|
||||
run_query(value, 'GRANT ALL PRIVILEGES ON `' + database + "`.* TO 'quality_app'@'127.0.0.1';")
|
||||
run_query(value, 'FLUSH TABLES;')
|
||||
@@ -304,7 +398,7 @@ def restore_locked(check_runtime):
|
||||
'totalRows': sum(actual_counts.values()), 'sourceReferencesRebound': rebound,
|
||||
'modelProfilesMigrated': manifest['modelProfilesMigrated'], 'modelProfilesExcluded': manifest['modelProfilesExcluded'],
|
||||
'nativeHistoryDatabases': native_count, 'originalDatabasesPreserved': True,
|
||||
'archiveDirectory': new_config['archiveDirectory']}
|
||||
'archiveDirectory': new_config['archiveDirectory'], 'reusedCompletedImport': reuse_only}
|
||||
plan = {'attempt': attempt, 'previousConfig': value, 'newConfig': new_config, 'privateSwitches': switches}
|
||||
commit_plan(plan, receipt)
|
||||
print('迁移恢复完成。请使用原来的账号和密码登录;MiMo 配置未迁移。', flush=True)
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
HERE = Path(__file__).resolve().parent
|
||||
sys.path.insert(0, str(HERE))
|
||||
import repair_windows_source_paths as fix
|
||||
ORIGINAL_SHA = fix.OLD_SHA
|
||||
|
||||
|
||||
class SourcePathRepairTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory(prefix='quality source path repair ')
|
||||
self.addCleanup(self.temp.cleanup)
|
||||
self.root = Path(self.temp.name) / '中文 QualityCenter & files'
|
||||
self.root.mkdir()
|
||||
self.original = b'original source fixture\n'
|
||||
self.old_sha = hashlib.sha256(self.original).hexdigest()
|
||||
self.guard = patch.object(fix, 'OLD_SHA', self.old_sha)
|
||||
self.guard.start()
|
||||
self.addCleanup(self.guard.stop)
|
||||
for name, value in {fix.SCRIPT: self.original,
|
||||
'deploy/bootstrap/windows-start.ps1': b'original bootstrap',
|
||||
'migration/database.sql.gz': b'existing migration payload',
|
||||
'.runtime/deployment.json': b'original private configuration',
|
||||
'runtimedata/mysql/retained-database': b'imported database data'}.items():
|
||||
target = self.root / name
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
target.write_bytes(value)
|
||||
self.manifest = {'platform': 'windows', 'updateVersion': '2026.11.04.1', 'updateSequence': 1,
|
||||
'runtimeFingerprint': 'unchanged', 'otherMetadata': {'keep': True},
|
||||
'files': [{'path': fix.SCRIPT, 'sha256': self.old_sha},
|
||||
{'path': 'deploy/bootstrap/windows-start.ps1', 'sha256': 'unchanged'}]}
|
||||
self.manifest_path = self.root / 'manifest.json'
|
||||
self.manifest_path.write_text(json.dumps(self.manifest), encoding='utf-8')
|
||||
|
||||
def test_backup_manifest_and_script_only_preserving_database_and_configuration(self):
|
||||
private = {name: (self.root / name).read_bytes() for name in
|
||||
['migration/database.sql.gz', '.runtime/deployment.json', 'runtimedata/mysql/retained-database']}
|
||||
result = fix.repair(self.root)
|
||||
self.assertTrue(result['sourcePathCheckRepaired'])
|
||||
self.assertEqual((self.root / fix.SCRIPT).read_bytes(), fix.PATCHED_SCRIPT)
|
||||
expected = json.loads(json.dumps(self.manifest))
|
||||
expected['files'][0]['sha256'] = fix.NEW_SHA
|
||||
self.assertEqual(json.loads(self.manifest_path.read_text()), expected)
|
||||
backup = self.root / result['backup']
|
||||
self.assertEqual((backup / 'restore_migration.py').read_bytes(), self.original)
|
||||
self.assertEqual(json.loads((backup / 'manifest.json').read_text()), self.manifest)
|
||||
for name, value in private.items():
|
||||
self.assertEqual((self.root / name).read_bytes(), value)
|
||||
self.assertTrue(fix.repair(self.root)['alreadyRepaired'])
|
||||
|
||||
def test_modified_script_or_manifest_is_not_approved_as_a_repair(self):
|
||||
before = self.manifest_path.read_bytes()
|
||||
(self.root / fix.SCRIPT).write_bytes(b'unrecognized source')
|
||||
with self.assertRaisesRegex(RuntimeError, '版本'):
|
||||
fix.repair(self.root)
|
||||
self.assertEqual(self.manifest_path.read_bytes(), before)
|
||||
|
||||
def test_failed_second_write_restores_original_program_and_manifest(self):
|
||||
before = self.manifest_path.read_bytes()
|
||||
original_atomic = fix.atomic
|
||||
calls = []
|
||||
def failing(path, data):
|
||||
calls.append(path)
|
||||
if len(calls) == 2:
|
||||
raise OSError('simulated manifest write failure')
|
||||
original_atomic(path, data)
|
||||
with patch.object(fix, 'atomic', side_effect=failing), self.assertRaises(OSError):
|
||||
fix.repair(self.root)
|
||||
self.assertEqual((self.root / fix.SCRIPT).read_bytes(), self.original)
|
||||
self.assertEqual(self.manifest_path.read_bytes(), before)
|
||||
|
||||
def test_retry_completes_an_interrupted_script_manifest_pair(self):
|
||||
(self.root / fix.SCRIPT).write_bytes(fix.PATCHED_SCRIPT)
|
||||
fix.repair(self.root)
|
||||
self.assertEqual(json.loads(self.manifest_path.read_text())['files'][0]['sha256'], fix.NEW_SHA)
|
||||
|
||||
def test_cmd_payload_runs_with_bundled_standard_library_and_requires_reuse_only(self):
|
||||
# 真实原包脚本由交付包集成验证;此单元测试使用受控旧源码摘要。
|
||||
command = self.root / '修复来源路径并继续恢复.cmd'
|
||||
body = fix.command_file().decode('utf-8').replace(ORIGINAL_SHA, self.old_sha)
|
||||
command.write_bytes(body.encode('utf-8'))
|
||||
code = body.split(' -c "', 1)[1].split('" "%~f0"', 1)[0]
|
||||
result = subprocess.run([sys.executable, '-I', '-S', '-B', '-X', 'utf8', '-c', code, str(command)], capture_output=True, text=True)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertEqual((self.root / fix.SCRIPT).read_bytes(), fix.PATCHED_SCRIPT)
|
||||
self.assertIn('set "QUALITY_MIGRATION_REUSE_ONLY=1"', body)
|
||||
self.assertIn('本次不会重新导入数据库', body)
|
||||
|
||||
def test_active_migration_lock_blocks_patching(self):
|
||||
before = self.manifest_path.read_bytes()
|
||||
with fix.migration_lock(self.root), self.assertRaisesRegex(RuntimeError, '仍在运行'):
|
||||
fix.repair(self.root)
|
||||
self.assertEqual(self.manifest_path.read_bytes(), before)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -8,6 +8,7 @@
|
||||
"build": "tsc -b && vite build"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ant-design/cssinjs": "2.1.2",
|
||||
"@ant-design/icons": "6.0.0",
|
||||
"antd": "6.6.7",
|
||||
"echarts": "6.0.0",
|
||||
|
||||
Generated
+3
@@ -8,6 +8,9 @@ importers:
|
||||
|
||||
.:
|
||||
dependencies:
|
||||
'@ant-design/cssinjs':
|
||||
specifier: 2.1.2
|
||||
version: 2.1.2(react-dom@19.3.1(react@19.3.1))(react@19.3.1)
|
||||
'@ant-design/icons':
|
||||
specifier: 6.0.0
|
||||
version: 6.0.0(react-dom@19.3.1(react@19.3.1))(react@19.3.1)
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { createRequestUuid } from './requestUuid';
|
||||
import { ManagementSections } from './ManagementSections';
|
||||
import { configurationDateTime } from './configurationName';
|
||||
import { alertObject, alertsForStatus, monitorLabel } from './taskMonitorModel';
|
||||
@@ -393,7 +394,7 @@ export function SourceGovernancePanel({ user, currentReleaseId, onUnauthorized }
|
||||
if (actionLock.current) return; actionLock.current = true;
|
||||
try {
|
||||
const value = await changeForm.validateFields(); setActionBusy('change');
|
||||
await api.createSourceChange({ ...value, reason: String(value.reason || '').trim(), idempotencyKey: crypto.randomUUID() });
|
||||
await api.createSourceChange({ ...value, reason: String(value.reason || '').trim(), idempotencyKey: createRequestUuid() });
|
||||
message.success('来源变更申请已提交,当前数据保持不变'); setChangeOpen(false); changeForm.resetFields(); markAffectedResources(['changes', 'candidates']);
|
||||
} catch (value) { if (value && typeof value === 'object' && 'errorFields' in value) return; if (!onUnauthorized(value)) message.error(value instanceof Error ? value.message : '来源变更申请失败'); }
|
||||
finally { actionLock.current = false; setActionBusy(''); }
|
||||
@@ -412,7 +413,7 @@ export function SourceGovernancePanel({ user, currentReleaseId, onUnauthorized }
|
||||
setActionBusy(id);
|
||||
try {
|
||||
const result = await api.releases();
|
||||
await api.buildSourceChange(id, { expectedCurrentReleaseId: result.currentReleaseId ?? null, idempotencyKey: crypto.randomUUID() });
|
||||
await api.buildSourceChange(id, { expectedCurrentReleaseId: result.currentReleaseId ?? null, idempotencyKey: createRequestUuid() });
|
||||
message.success('来源变更处理已完成;请检查候选数据与校验状态。'); markAffectedResources(['changes', 'candidates', 'coverage']);
|
||||
} catch (value) { if (!onUnauthorized(value)) message.error(value instanceof ApiError && value.status === 409 ? '当前数据或申请状态已变化,请刷新核对。' : value instanceof Error ? value.message : '变更处理失败'); if (value instanceof ApiError && value.status === 409) await refreshAffectedCurrent(['changes', 'candidates', 'coverage']); }
|
||||
finally { actionLock.current = false; setActionBusy(''); }
|
||||
@@ -531,7 +532,7 @@ export function BackupOperationsPanel({ user, onUnauthorized, onNavigate }: { us
|
||||
const runJob = async (type: string, backupId?: string) => {
|
||||
if (actionLock.current) return; actionLock.current = true;
|
||||
setBusy(true);
|
||||
try { await api.createBackupJob({ type, ...(backupId ? { backupId } : {}), idempotencyKey: crypto.randomUUID() }); message.success('备份任务已登记'); await load(); }
|
||||
try { await api.createBackupJob({ type, ...(backupId ? { backupId } : {}), idempotencyKey: createRequestUuid() }); message.success('备份任务已登记'); await load(); }
|
||||
catch (value) { if (!onUnauthorized(value)) message.error(value instanceof Error ? value.message : '备份任务提交失败'); }
|
||||
finally { actionLock.current = false; setBusy(false); }
|
||||
};
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { createRequestUuid } from './requestUuid';
|
||||
import { ConfigurationWorkbookActions } from './ConfigurationWorkbookActions';
|
||||
import { MappingEditorContext } from './MappingEditorContext';
|
||||
import { ClassificationRuleEditor } from './ClassificationRuleEditor';
|
||||
@@ -916,7 +917,7 @@ function TaskTable({ items, importOnly, user, onUnauthorized, onRefresh }: { ite
|
||||
setBusyId(id);
|
||||
try {
|
||||
const releases = await api.releases();
|
||||
const result = await api.retryTask(id, { idempotencyKey: crypto.randomUUID(), expectedCurrentReleaseId: releases.currentReleaseId ?? null });
|
||||
const result = await api.retryTask(id, { idempotencyKey: createRequestUuid(), expectedCurrentReleaseId: releases.currentReleaseId ?? null });
|
||||
const body = result && typeof result === 'object' ? result as Record<string, unknown> : {};
|
||||
const run = body.run && typeof body.run === 'object' ? body.run as Record<string, unknown> : {};
|
||||
if (String(run.status).toUpperCase() === 'FAILED') message.error(`重试后仍失败:${toText(run.errorMessage || run.errorCode)}`);
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { createRequestUuid } from './requestUuid';
|
||||
import { useDeleteConfirmation } from './useDeleteConfirmation';
|
||||
import { configurationDateTime } from './configurationName';
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
@@ -115,7 +116,7 @@ function SimplifiedDataWorkflow({ options, workflowStatus, pendingDeletion, onBu
|
||||
const period = sourceFilenamePeriod(file.name);
|
||||
const nextMonth = period.month || new Date().getMonth() + 1;
|
||||
const nextYear = period.year || batchYear;
|
||||
return { id: crypto.randomUUID(), file, workbook: result, stage: detected, year: nextYear, month: nextMonth, sheetName: result.preview.sheetName, headerRow: result.preview.headerRow, fieldMap: matchFields(options.fields[detected] || [], result.preview.headers), mode: 'APPEND' as const, fileId: crypto.randomUUID(), targetId: '', scopeCode: options.scopes[0] || 'ALL' };
|
||||
return { id: createRequestUuid(), file, workbook: result, stage: detected, year: nextYear, month: nextMonth, sheetName: result.preview.sheetName, headerRow: result.preview.headerRow, fieldMap: matchFields(options.fields[detected] || [], result.preview.headers), mode: 'APPEND' as const, fileId: createRequestUuid(), targetId: '', scopeCode: options.scopes[0] || 'ALL' };
|
||||
} catch (value) { if (!onUnauthorized(value)) failures.push(`${file.name}:${failure(value)}`); return null; }
|
||||
}));
|
||||
const ready = results.filter(item => item !== null);
|
||||
@@ -350,7 +351,7 @@ function SourceDeletionDialog({ user, sourceId, restoring, sources, onUnauthoriz
|
||||
const [busy, setBusy] = useState(true); const [error, setError] = useState(''); const [notice, setNotice] = useState('');
|
||||
const [reason, setReason] = useState(''); const [confirmed, setConfirmed] = useState(false); const [finished, setFinished] = useState(false);
|
||||
const [candidateId, setCandidateId] = useState(''); const [options, setOptions] = useState<SourceUploadOptions | null>(null);
|
||||
const requestKey = useRef(crypto.randomUUID()); const buildKey = useRef(crypto.randomUUID());
|
||||
const requestKey = useRef(createRequestUuid()); const buildKey = useRef(createRequestUuid());
|
||||
const actionLock = useRef(false); const candidateLock = useRef(false);
|
||||
const showBusy = useDelayedIndicator(busy, 150);
|
||||
const reportError = useCallback((value: unknown) => { if (!onUnauthorized(value)) setError(failure(value)); }, [onUnauthorized]);
|
||||
@@ -371,7 +372,7 @@ function SourceDeletionDialog({ user, sourceId, restoring, sources, onUnauthoriz
|
||||
try {
|
||||
if (kind === 'delete') {
|
||||
const result = await api.deleteSource(sourceId, { expectedCurrentReleaseId: preview.currentReleaseId, expectedDeleteVersion: preview.deleteVersion, ...(preview.currentUsage ? { expectedRevisionId: preview.currentUsage.revisionId } : {}), reason: reason.trim(), idempotencyKey: requestKey.current });
|
||||
setPreview(result); requestKey.current = crypto.randomUUID(); setNotice(result.hidden ? '来源已从日常清单删除,可在“查看已删除来源”中恢复。' : '删除申请已提交,当前正式数据保持不变;下一步由发布者审批。'); setFinished(result.hidden);
|
||||
setPreview(result); requestKey.current = createRequestUuid(); setNotice(result.hidden ? '来源已从日常清单删除,可在“查看已删除来源”中恢复。' : '删除申请已提交,当前正式数据保持不变;下一步由发布者审批。'); setFinished(result.hidden);
|
||||
} else if (kind === 'restore') {
|
||||
const result = await api.restoreSource(sourceId, { expectedCurrentReleaseId: preview.currentReleaseId, expectedDeleteVersion: preview.deleteVersion, reason: reason.trim() });
|
||||
setPreview(result); setNotice('来源已恢复到日常清单。恢复文件清单不会修改已发布的数据结果。'); setFinished(true);
|
||||
@@ -429,7 +430,7 @@ function SourceDeletionDialog({ user, sourceId, restoring, sources, onUnauthoriz
|
||||
}
|
||||
|
||||
function DataUploadWizard({ user, mode, purpose, handoffSourceId, initialReason, options, sources, resumeId, onUnauthorized, onClose, onComplete }: { user: AuthUser; mode: 'ADD' | 'REPLACE' | 'REBUILD'; purpose?: 'WITHDRAW'; handoffSourceId?: string; initialReason?: string; options: SourceUploadOptions; sources: SourceItem[]; resumeId: string; onUnauthorized: (error: unknown) => boolean; onClose: () => void; onComplete: () => void }) {
|
||||
const { message } = App.useApp(); const { active } = usePageCache(); const activeRef = useRef(active); activeRef.current = active; const input = useRef<HTMLInputElement>(null); const generation = useRef(0); const importKey = useRef(crypto.randomUUID()); const publishKey = useRef(crypto.randomUUID());
|
||||
const { message } = App.useApp(); const { active } = usePageCache(); const activeRef = useRef(active); activeRef.current = active; const input = useRef<HTMLInputElement>(null); const generation = useRef(0); const importKey = useRef(createRequestUuid()); const publishKey = useRef(createRequestUuid());
|
||||
const runStorageKey = `quality-import-run:${user.id}`;
|
||||
const [storedRunId] = useState(() => { try { return localStorage.getItem(runStorageKey) || ''; } catch { return ''; } });
|
||||
const [step, setStep] = useState(resumeId ? 4 : storedRunId ? 3 : 0); const [busy, setBusy] = useState(Boolean(storedRunId)); const [error, setError] = useState('');
|
||||
@@ -526,7 +527,7 @@ function DataUploadWizard({ user, mode, purpose, handoffSourceId, initialReason,
|
||||
const uploaded = await api.previewSourceWorkbook(file);
|
||||
const detected = await detectSourceWorkbook(uploaded, options.fields, api.sourceWorkbookPreview);
|
||||
if (!detectedStage) detectedStage = detected.stage;
|
||||
ready.push({ id: crypto.randomUUID(), file, workbook: detected.workbook, sheetName: detected.workbook.preview.sheetName, headerRow: detected.workbook.preview.headerRow, fieldMap: matchFields(options.fields[detectedStage] || [], detected.workbook.preview.headers), fileId: crypto.randomUUID() });
|
||||
ready.push({ id: createRequestUuid(), file, workbook: detected.workbook, sheetName: detected.workbook.preview.sheetName, headerRow: detected.workbook.preview.headerRow, fieldMap: matchFields(options.fields[detectedStage] || [], detected.workbook.preview.headers), fileId: createRequestUuid() });
|
||||
} catch (value) { if (!onUnauthorized(value)) failures.push(`${file.name}:${failure(value)}`); }
|
||||
}
|
||||
if (ownGeneration !== generation.current) return;
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { createRequestUuid } from './requestUuid';
|
||||
import { useDeleteConfirmation } from './useDeleteConfirmation';
|
||||
import { newMasterDataCode } from './masterDataIdentity';
|
||||
import { ConfigurationWorkbookActions } from './ConfigurationWorkbookActions';
|
||||
@@ -260,7 +261,7 @@ export function MatchRulesDefinitionEditor({ value, onChange, metadata, readOnly
|
||||
if (!next.name) { setError('请填写规则名称'); return; }
|
||||
if (!next.conditions.length || next.conditions.some(condition => !condition.field || (!['IS_BLANK', 'IS_NOT_BLANK'].includes(condition.operator) && !condition.value))) { setError('请补全每条条件的字段和判断值'); return; }
|
||||
if (!next.value) { setError('请填写匹配结果'); return; }
|
||||
const updated=editing.id ? rules.map(rule => rule.id === editing.id ? next : rule) : [...rules, { ...next, id: `match-${crypto.randomUUID()}` }];
|
||||
const updated=editing.id ? rules.map(rule => rule.id === editing.id ? next : rule) : [...rules, { ...next, id: `match-${createRequestUuid()}` }];
|
||||
const conflicts=matchRuleConflicts(updated);if(conflicts.length){setError(conflicts.join(';'));return;}
|
||||
commit(updated); setEditing(null);
|
||||
}}>
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { createRequestUuid } from './requestUuid';
|
||||
import { ManagementSections } from './ManagementSections';
|
||||
import { useCallback, useEffect, useState, useRef } from 'react';
|
||||
import { Alert, App, Button, Drawer, Empty, Progress, Select, Spin, Tag } from 'antd';
|
||||
@@ -45,7 +46,7 @@ export function TasksMonitorPage({user,onUnauthorized}:{user:AuthUser;onUnauthor
|
||||
if(actionInFlight.current)return; actionInFlight.current=true;
|
||||
setBusy(true);
|
||||
try {
|
||||
if(action==='retry') {const releases=await api.releases();await api.retryTask(String(row.id),{idempotencyKey:crypto.randomUUID(),expectedCurrentReleaseId:releases.currentReleaseId??null});}
|
||||
if(action==='retry') {const releases=await api.releases();await api.retryTask(String(row.id),{idempotencyKey:createRequestUuid(),expectedCurrentReleaseId:releases.currentReleaseId??null});}
|
||||
else await api.cancelTask(String(row.id),{expectedStatus:String(row.status)});
|
||||
message.success(action==='retry'?'已提交重试,请查看最新任务状态':'已取消排队任务');setSelected(null);await load();
|
||||
} catch(error){if(!onUnauthorized(error))message.error(error instanceof Error?error.message:'任务操作失败');}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { createRequestUuid } from './requestUuid.ts';
|
||||
type Context = Record<string, unknown> | undefined;
|
||||
export type SubmissionInput = { sessionId: string; question: string; context?: Context; generation: number };
|
||||
export type AnalysisSubmission = SubmissionInput & {
|
||||
@@ -17,7 +18,7 @@ function canonical(value: unknown): string {
|
||||
}
|
||||
|
||||
/** Only an uncertain retry of the same question, session and frozen context reuses its key. */
|
||||
export function beginAnalysisSubmission(previous: AnalysisSubmission | null, input: SubmissionInput, key: () => string = () => crypto.randomUUID()): AnalysisSubmission {
|
||||
export function beginAnalysisSubmission(previous: AnalysisSubmission | null, input: SubmissionInput, key: () => string = () => createRequestUuid()): AnalysisSubmission {
|
||||
const contextKey = canonical(input.context || {});
|
||||
if (previous?.uncertain && previous.generation === input.generation && previous.sessionId === input.sessionId
|
||||
&& previous.question === input.question && previous.contextKey === contextKey) {
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
/** 不按浏览器名称判断;只对缺少现代选择器的内核启用降级样式。 */
|
||||
export function needsLegacyComponentStyles(css: Pick<typeof CSS, 'supports'> | undefined = globalThis.CSS): boolean {
|
||||
try { return typeof css?.supports !== 'function' || !css.supports('selector(:where(*))'); }
|
||||
catch { return true; }
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import { createRequestUuid } from './requestUuid.ts';
|
||||
import { editClassification, type ClassificationSelection, type ClassificationRuleOptions } from './classificationMaintenance.ts';
|
||||
import type { DataWorkflowOperation, DataWorkflowStatus } from './NoCodeDataTypes.ts';
|
||||
|
||||
@@ -33,7 +34,7 @@ export class ClassificationQueue {
|
||||
let definition=base;
|
||||
for(const job of this.jobs.filter(job=>!['failed','completed'].includes(job.status))) definition=editClassification(definition,job.selection,job.target,defaults,job.options);
|
||||
editClassification(definition,command.selection,command.target,defaults,command.options);
|
||||
const job:ClassificationJob={...structuredClone(command),id:crypto.randomUUID(),status:'queued'};
|
||||
const job:ClassificationJob={...structuredClone(command),id:createRequestUuid(),status:'queued'};
|
||||
this.jobs=[...this.jobs,job];this.emit();void this.run();return job.id;
|
||||
}
|
||||
retry(id: string) {
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { StyleProvider, legacyLogicalPropertiesTransformer } from '@ant-design/cssinjs';
|
||||
import { needsLegacyComponentStyles } from './browserStyleCompatibility';
|
||||
import React, { useLayoutEffect, useState } from 'react';
|
||||
import ReactDOM from 'react-dom/client';
|
||||
import { App, ConfigProvider, theme as antdTheme } from 'antd';
|
||||
@@ -9,6 +11,9 @@ import './dark-theme.css';
|
||||
import './quality-table.css';
|
||||
import './workspace-finish.css';
|
||||
|
||||
const legacyComponentStyles = needsLegacyComponentStyles();
|
||||
const legacyStyleTransformers = [legacyLogicalPropertiesTransformer];
|
||||
|
||||
function QualityCenterApp() {
|
||||
const [themeId, setThemeId] = useState<WorkspaceThemeId>(getStoredWorkspaceThemeId);
|
||||
const appearance = getWorkspaceTheme(themeId);
|
||||
@@ -37,6 +42,7 @@ function QualityCenterApp() {
|
||||
}, [appearance]);
|
||||
|
||||
return (
|
||||
<StyleProvider hashPriority={legacyComponentStyles ? 'high' : undefined} transformers={legacyComponentStyles ? legacyStyleTransformers : undefined}>
|
||||
<ConfigProvider
|
||||
locale={zhCN}
|
||||
theme={{
|
||||
@@ -83,6 +89,7 @@ function QualityCenterApp() {
|
||||
<QualityWorkspace appearance={appearance} onAppearanceChange={setThemeId} />
|
||||
</App>
|
||||
</ConfigProvider>
|
||||
</StyleProvider>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { createRequestUuid } from './requestUuid.ts';
|
||||
/** Internal catalog identity never needs user input. Existing identities survive renames. */
|
||||
export function newMasterDataCode(existing: Iterable<string>): string {
|
||||
const used = existing instanceof Set ? existing : new Set(existing);
|
||||
let code: string;
|
||||
do { code = `REF-${crypto.randomUUID()}`; } while (used.has(code));
|
||||
do { code = `REF-${createRequestUuid()}`; } while (used.has(code));
|
||||
return code;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
type UuidCrypto = Pick<Crypto, 'getRandomValues'> & { randomUUID?: () => string };
|
||||
|
||||
/** 旧内核与局域网 HTTP 仍使用安全随机数,操作编号保持 UUID v4 格式。 */
|
||||
export function createRequestUuid(source: UuidCrypto | undefined = globalThis.crypto): string {
|
||||
if (typeof source?.randomUUID === 'function') return source.randomUUID();
|
||||
if (typeof source?.getRandomValues !== 'function') throw new Error('当前浏览器无法生成安全操作编号,请升级浏览器后重试');
|
||||
const bytes = source.getRandomValues(new Uint8Array(16));
|
||||
bytes[6] = (bytes[6] & 0x0f) | 0x40;
|
||||
bytes[8] = (bytes[8] & 0x3f) | 0x80;
|
||||
const hex = Array.from(bytes, value => value.toString(16).padStart(2, '0')).join('');
|
||||
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { webcrypto } from 'node:crypto';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import ts from 'typescript';
|
||||
import { createRequestUuid } from '../src/requestUuid.ts';
|
||||
import { needsLegacyComponentStyles } from '../src/browserStyleCompatibility.ts';
|
||||
import { beginAnalysisSubmission } from '../src/analysisSubmission.ts';
|
||||
|
||||
const secureOnly = {getRandomValues:bytes=>webcrypto.getRandomValues(bytes)};
|
||||
const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
|
||||
function withoutNativeUuid(run) {
|
||||
const previous=Object.getOwnPropertyDescriptor(globalThis,'crypto');
|
||||
Object.defineProperty(globalThis,'crypto',{value:secureOnly,configurable:true});
|
||||
return Promise.resolve().then(run).finally(()=>{if(previous)Object.defineProperty(globalThis,'crypto',previous);else delete globalThis.crypto;});
|
||||
}
|
||||
test('old browser / LAN HTTP uses secure UUID v4 without native randomUUID',()=>{
|
||||
const ids=new Set(Array.from({length:1000},()=>createRequestUuid(secureOnly)));
|
||||
assert.equal(ids.size,1000);for(const id of ids)assert.match(id,uuid);
|
||||
assert.equal(createRequestUuid({getRandomValues:bytes=>bytes.fill(0)}),'00000000-0000-4000-8000-000000000000');
|
||||
});
|
||||
test('native UUID retains method binding and missing secure randomness fails explicitly',()=>{
|
||||
const provider={getRandomValues(){throw Error('fallback should not run');},randomUUID(){assert.equal(this,provider);return 'native-uuid';}};
|
||||
assert.equal(createRequestUuid(provider),'native-uuid');
|
||||
assert.throws(()=>createRequestUuid({}),/安全操作编号/);
|
||||
});
|
||||
test('capability detection downgrades old selector support while retaining modern styles',()=>{
|
||||
assert.equal(needsLegacyComponentStyles({supports:()=>false}),true);
|
||||
assert.equal(needsLegacyComponentStyles({supports:()=>{throw Error('unsupported selector query');}}),true);
|
||||
assert.equal(needsLegacyComponentStyles({supports:query=>query==='selector(:where(*))'}),false);
|
||||
});
|
||||
test('actual multi-file intake closure accepts files when crypto.randomUUID is absent',async()=>withoutNativeUuid(async()=>{
|
||||
const source=readFileSync(process.env.NO_CODE_WORKFLOW_SOURCE||new URL('../src/NoCodeDataWorkflow.tsx',import.meta.url),'utf8');
|
||||
const closure=source.slice(source.indexOf(' const readFiles = async'),source.indexOf(' const changePreview = async'));
|
||||
const prelude=`let drafts=[],error='',busy=false,reading=null;const importBusy=false,actionLock={current:false},input={current:{value:'selected'}};
|
||||
const options={fields:{black:[{name:'产品'}]},scopes:['ALL']};
|
||||
const setDrafts=value=>{drafts=typeof value==='function'?value(drafts):value},setError=value=>error=value,setBusy=value=>busy=value,setReading=value=>reading=value;
|
||||
const onUnauthorized=()=>false,failure=e=>e.message,sourceBatchYear=()=>2025,sourceFilenamePeriod=()=>({year:2025,month:1}),matchFields=()=>({'产品':'产品'});
|
||||
const api={previewSourceWorkbook:async file=>({sourceFile:file.name,preview:{sheetName:'sheet',headerRow:1,headers:['产品']}})};
|
||||
const detectSourceWorkbook=async workbook=>({workbook,stage:'black'});\n`;
|
||||
const compiled=ts.transpileModule(prelude+closure+'\nreturn {readFiles,state:()=>({drafts,error,busy,reading,locked:actionLock.current})};',{compilerOptions:{target:ts.ScriptTarget.ES2020}}).outputText;
|
||||
const f=new Function('createRequestUuid','crypto',compiled)(createRequestUuid,secureOnly);
|
||||
const files=Array.from({length:25},(_,i)=>({name:`2025年1月黑片-${i}.xlsx`,size:100+i,lastModified:1}));await f.readFiles(files);
|
||||
const state=f.state();assert.equal(state.error,'');assert.equal(state.drafts.length,25);assert.equal(state.busy,false);assert.equal(state.reading,null);assert.equal(state.locked,false);
|
||||
const ids=state.drafts.flatMap(d=>[d.id,...(d.fileId?[d.fileId]:[])]);for(const id of ids)assert.match(id,uuid);assert.equal(new Set(ids).size,ids.length);
|
||||
}));
|
||||
test('uncertain AI retries reuse the original secure idempotency key under LAN HTTP',async()=>withoutNativeUuid(()=>{
|
||||
const input={sessionId:'session',question:'质量变化',context:{year:2025},generation:1};const first=beginAnalysisSubmission(null,input);assert.match(first.idempotencyKey,uuid);
|
||||
first.uncertain=true;assert.equal(beginAnalysisSubmission(first,input).idempotencyKey,first.idempotencyKey);
|
||||
}));
|
||||
Reference in New Issue
Block a user