perf(代码审查落地): 后端 A1-A8 与前端 C1-C8 加固,retention 清理补索引(V141)
A 组(backend-java): - A1 载荷引用计数不再无条件回落全表 COUNT - A2 结果行读取由 LIMIT 1 改整页 - A3 ziniao 索引缓存过期判断下推 SQL - A4 循环子任务认领改 CAS,失败一律抛 - A5 建单事务里不碰外部 IO - A6 连接池补网络层超时(connectTimeout/socketTimeout,env 可覆盖) - A7 日志留现场 + 异步落盘 - A8 其余:货源图片预取、结果工作簿装配等 - V141:三条 retention DELETE 的可用索引,其中 biz_price_track_loop_run 用 STORED 生成列承载 COALESCE 时间线(该表实测 881 行/17MB,COPY 秒级) C 组(frontend-vue):URL 取值走 safe-url、行号取值走 row-id、 交付视频任务状态抽成 delivery-video-task-state.ts,各补用例。
This commit is contained in:
@@ -0,0 +1,96 @@
|
||||
import { test } from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { resolve, dirname } from 'node:path'
|
||||
import {
|
||||
isRecoverableFailedImageVideoTask,
|
||||
isTerminalCozeStatus,
|
||||
isTerminalImageVideoTask,
|
||||
normalizeTaskStatus,
|
||||
} from '../src/pages/image-video/delivery-video-task-state.ts'
|
||||
import type { ImageVideoAsyncTaskVo } from '../src/shared/api/types/modules/image-video.ts'
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url))
|
||||
|
||||
function task(patch: Partial<ImageVideoAsyncTaskVo>): ImageVideoAsyncTaskVo {
|
||||
return { taskId: 1, taskType: 'workflow', status: 'RUNNING', ...patch } as ImageVideoAsyncTaskVo
|
||||
}
|
||||
|
||||
// 判错的后果不是「少一次轮询」而是「把没跑完的任务当完成回传」,所以四条边界都要钉住。
|
||||
test('test_success_is_terminal', () => {
|
||||
const done = task({ status: 'SUCCESS', cozeExecuteId: 'exec-1', cozeStatus: 'running' })
|
||||
assert.equal(isTerminalImageVideoTask(done), true)
|
||||
assert.equal(isRecoverableFailedImageVideoTask(done), false, '成功单不属于可恢复失败')
|
||||
})
|
||||
|
||||
test('test_failed_without_execute_id_is_terminal', () => {
|
||||
assert.equal(isTerminalImageVideoTask(task({ status: 'FAILED' })), true)
|
||||
assert.equal(isTerminalImageVideoTask(task({ status: 'FAILED', cozeExecuteId: '' })), true,
|
||||
'cozeExecuteId 空串不能当「远端还在跑」,否则轮询要空转满 720 次')
|
||||
})
|
||||
|
||||
test('test_failed_with_running_remote_is_recoverable', () => {
|
||||
const recover = task({ status: 'FAILED', cozeExecuteId: 'exec-1', cozeStatus: 'running' })
|
||||
assert.equal(isRecoverableFailedImageVideoTask(recover), true)
|
||||
assert.equal(isTerminalImageVideoTask(recover), false, '远端未终态时不能判完成')
|
||||
assert.equal(isTerminalImageVideoTask(task({ status: 'FAILED', cozeExecuteId: 'exec-1' })), false,
|
||||
'cozeStatus 缺失按「未知=还在跑」处理')
|
||||
})
|
||||
|
||||
test('test_failed_with_terminal_remote_is_terminal', () => {
|
||||
for (const status of ['SUCCESS', 'succeeded', ' COMPLETED ', 'done', 'FINISHED', 'FAILED', 'fail', 'ERROR', 'CANCELED', 'cancelled']) {
|
||||
const item = task({ status: 'FAILED', cozeExecuteId: 'exec-1', cozeStatus: status })
|
||||
assert.equal(isTerminalCozeStatus(status), true, `${status} 应识别为远端终态`)
|
||||
assert.equal(isTerminalImageVideoTask(item), true, `远端 ${status} 时本地应判终态`)
|
||||
}
|
||||
})
|
||||
|
||||
test('test_status_normalization_and_unknown_remote', () => {
|
||||
assert.equal(normalizeTaskStatus(undefined), '')
|
||||
assert.equal(normalizeTaskStatus(' failed '), 'FAILED')
|
||||
for (const status of [undefined, '', 'RUNNING', 'PENDING', 'waiting', 'queued']) {
|
||||
assert.equal(isTerminalCozeStatus(status), false, `${status} 不是远端终态`)
|
||||
}
|
||||
})
|
||||
|
||||
test('test_pending_like_statuses_are_never_terminal', () => {
|
||||
for (const status of ['PENDING', 'RUNNING', 'WAITING', 'POLLING'] as const) {
|
||||
const item = task({ status })
|
||||
assert.equal(isTerminalImageVideoTask(item), false)
|
||||
assert.equal(isRecoverableFailedImageVideoTask(item), false)
|
||||
}
|
||||
})
|
||||
|
||||
// 漂移护栏:判定只允许有一份实现。组件里再写一个同名函数会被 import 遮蔽成「本地版说了算」,
|
||||
// 而本地版没人单测——正是这类逻辑历史上改坏的形状。
|
||||
const COMPONENT_RELATIVE_PATH = 'src/pages/image-video/components/DeliveryVideoWorkspace.vue'
|
||||
|
||||
function componentSource(): string {
|
||||
return readFileSync(resolve(here, '..', COMPONENT_RELATIVE_PATH), 'utf-8')
|
||||
}
|
||||
|
||||
test('test_component_imports_predicates_instead_of_redeclaring', () => {
|
||||
const source = componentSource()
|
||||
assert.match(
|
||||
source,
|
||||
/import\s*\{[^}]*\bisTerminalImageVideoTask\b[^}]*\}\s*from\s*'@\/pages\/image-video\/delivery-video-task-state'/,
|
||||
'组件必须从公共模块导入终态判定',
|
||||
)
|
||||
for (const name of ['isTerminalImageVideoTask', 'isRecoverableFailedImageVideoTask', 'isTerminalCozeStatus', 'normalizeTaskStatus']) {
|
||||
assert.doesNotMatch(
|
||||
source,
|
||||
new RegExp(`function\\s+${name}\\s*\\(`),
|
||||
`组件内不得再声明 ${name}(会与导入同名遮蔽)`,
|
||||
)
|
||||
}
|
||||
})
|
||||
|
||||
test('test_redeclare_detector_actually_catches_a_shadow', () => {
|
||||
const polluted = componentSource().replace(
|
||||
/async function waitForImageVideoTask/,
|
||||
'function isTerminalImageVideoTask(task: ImageVideoAsyncTaskVo) {\n return true\n}\n\nasync function waitForImageVideoTask',
|
||||
)
|
||||
assert.notEqual(polluted, componentSource(), '变异注入未生效,用例本身失效')
|
||||
assert.match(polluted, /function\s+isTerminalImageVideoTask\s*\(/, '检测正则要能抓到重复声明')
|
||||
})
|
||||
@@ -0,0 +1,153 @@
|
||||
import { test } from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFileSync, readdirSync, statSync } from 'node:fs'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { resolve, dirname, join, relative } from 'node:path'
|
||||
import { safeHttpUrl } from '../src/shared/utils/safe-url.ts'
|
||||
import { createRowId } from '../src/shared/utils/row-id.ts'
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url))
|
||||
const srcRoot = resolve(here, '../src')
|
||||
|
||||
/** 静态常量出口(构建期写死,不经服务端/客户端透传) */
|
||||
const STATIC_HREF_ALLOWLIST = new Set(['ALIPRICE_URL'])
|
||||
|
||||
function listVueFiles(dir: string, acc: string[] = []): string[] {
|
||||
for (const entry of readdirSync(dir)) {
|
||||
const full = join(dir, entry)
|
||||
if (statSync(full).isDirectory()) listVueFiles(full, acc)
|
||||
else if (entry.endsWith('.vue')) acc.push(full)
|
||||
}
|
||||
return acc
|
||||
}
|
||||
|
||||
/** 找出「函数体里调过 safeHttpUrl」的本地包装函数名(如 sourceFileHref)。 */
|
||||
function vettedWrapperNames(sources: string[]): Set<string> {
|
||||
const names = new Set<string>()
|
||||
for (const source of sources) {
|
||||
// 顶层函数以行首 } 收尾(与本仓 vue 文件书写一致),按函数体取,避免把邻近函数的调用算进来
|
||||
for (const match of source.matchAll(/function\s+(\w+)\s*\([^)]*\)\s*\{([\s\S]*?)\n\}/g)) {
|
||||
if (match[2].includes('safeHttpUrl(')) names.add(match[1])
|
||||
}
|
||||
}
|
||||
return names
|
||||
}
|
||||
|
||||
type HrefBinding = { file: string; line: string }
|
||||
|
||||
function collectHrefBindings(sources: Record<string, string>): HrefBinding[] {
|
||||
const found: HrefBinding[] = []
|
||||
for (const [file, content] of Object.entries(sources)) {
|
||||
for (const line of content.split(/\r?\n/)) {
|
||||
if (line.includes(':href="')) found.push({ file, line })
|
||||
}
|
||||
}
|
||||
return found
|
||||
}
|
||||
|
||||
function unvettedBindings(bindings: HrefBinding[], wrappers: Set<string>): HrefBinding[] {
|
||||
return bindings.filter(({ line }) => {
|
||||
const expr = (line.match(/:href="([^"]*)"/)?.[1] ?? '').trim()
|
||||
if (expr.includes('safeHttpUrl(')) return false
|
||||
if (/^[A-Z0-9_]+$/.test(expr) && STATIC_HREF_ALLOWLIST.has(expr)) return false
|
||||
const callName = expr.match(/^(\w+)\(/)?.[1]
|
||||
if (callName && wrappers.has(callName)) return false
|
||||
return true
|
||||
})
|
||||
}
|
||||
|
||||
test('test_safe_http_url_allows_only_http_and_https', () => {
|
||||
assert.equal(safeHttpUrl('https://cdn.example.com/a.mp4'), 'https://cdn.example.com/a.mp4')
|
||||
assert.equal(safeHttpUrl('http://127.0.0.1:5173/x'), 'http://127.0.0.1:5173/x')
|
||||
// 相对路径按当前页面补全后判定协议,保持原样返回(交给浏览器解析)
|
||||
assert.equal(safeHttpUrl('/newApi/api/files/x'), '/newApi/api/files/x')
|
||||
})
|
||||
|
||||
test('test_safe_http_url_blocks_pseudo_protocols', () => {
|
||||
for (const bad of [
|
||||
'javascript:alert(1)',
|
||||
'JavaScript:alert(1)',
|
||||
' javascript:alert(1) ',
|
||||
'java\tscript:alert(1)',
|
||||
'data:text/html,<script>alert(1)</script>',
|
||||
'vbscript:msgbox(1)',
|
||||
'file:///C:/Windows/win.ini',
|
||||
'http://[bad',
|
||||
]) {
|
||||
assert.equal(safeHttpUrl(bad), '#', `${bad} 必须被拦成 #`)
|
||||
}
|
||||
})
|
||||
|
||||
test('test_safe_http_url_handles_empty_input', () => {
|
||||
for (const empty of [undefined, null, '', ' ']) {
|
||||
assert.equal(safeHttpUrl(empty as string | null | undefined), '#')
|
||||
}
|
||||
})
|
||||
|
||||
test('test_safe_http_url_uses_page_origin_when_window_exists', () => {
|
||||
const previous = (globalThis as Record<string, unknown>).window
|
||||
;(globalThis as Record<string, unknown>).window = { location: { href: 'https://app.example.com/#group-front' } }
|
||||
try {
|
||||
assert.equal(safeHttpUrl('/api/result.zip'), '/api/result.zip')
|
||||
// 带 origin 的伪协议不会因为「相对路径」被放行
|
||||
assert.equal(safeHttpUrl('javascript:alert(1)'), '#')
|
||||
} finally {
|
||||
if (previous === undefined) delete (globalThis as Record<string, unknown>).window
|
||||
else (globalThis as Record<string, unknown>).window = previous
|
||||
}
|
||||
})
|
||||
|
||||
test('test_create_row_id_is_unique_per_call', () => {
|
||||
const ids = new Set<string>()
|
||||
for (let i = 0; i < 2000; i += 1) ids.add(createRowId('asset'))
|
||||
assert.equal(ids.size, 2000, '同一页会话内行 id 不能重复')
|
||||
for (const id of ids) assert.match(id, /^asset:/)
|
||||
})
|
||||
|
||||
test('test_create_row_id_falls_back_without_random_uuid', () => {
|
||||
const cryptoGlobal = (globalThis as { crypto?: Crypto }).crypto
|
||||
if (!cryptoGlobal) return // 没有 crypto 全局时走的就是降级路径
|
||||
const restore = Object.getOwnPropertyDescriptor(cryptoGlobal, 'randomUUID')
|
||||
try {
|
||||
// 1) randomUUID 缺失(http 非安全上下文下 WebView 不提供)
|
||||
Object.defineProperty(cryptoGlobal, 'randomUUID', { value: undefined, configurable: true, writable: true })
|
||||
const missing = createRowId('row')
|
||||
assert.match(missing, /^row:[0-9a-z]+-[0-9a-z]+-[0-9a-z]+$/, '降级实现要带前缀且分三段')
|
||||
// 2) 存在但会抛(部分内核在非安全上下文直接抛错)
|
||||
Object.defineProperty(cryptoGlobal, 'randomUUID', {
|
||||
value: () => { throw new Error('not a secure context') },
|
||||
configurable: true, writable: true,
|
||||
})
|
||||
const thrown = createRowId('row')
|
||||
assert.match(thrown, /^row:/, '抛错也必须产出可用 id')
|
||||
assert.notEqual(thrown, missing)
|
||||
} finally {
|
||||
if (restore) Object.defineProperty(cryptoGlobal, 'randomUUID', restore)
|
||||
else delete (cryptoGlobal as unknown as Record<string, unknown>).randomUUID
|
||||
}
|
||||
})
|
||||
|
||||
test('test_every_dynamic_href_outlet_goes_through_safe_http_url', () => {
|
||||
const files = listVueFiles(srcRoot)
|
||||
const sources: Record<string, string> = {}
|
||||
for (const file of files) {
|
||||
sources[relative(srcRoot, file).replace(/\\/g, '/')] = readFileSync(file, 'utf-8')
|
||||
}
|
||||
const bindings = collectHrefBindings(sources)
|
||||
assert.ok(bindings.length >= 4, `扫描到的 :href 出口只有 ${bindings.length} 处,检测面失效`)
|
||||
const violations = unvettedBindings(bindings, vettedWrapperNames(Object.values(sources)))
|
||||
assert.deepEqual(violations, [], '存在未经协议过滤的动态 :href')
|
||||
})
|
||||
|
||||
test('test_href_outlet_detector_actually_flags_raw_binding', () => {
|
||||
const wrappers = vettedWrapperNames(['function sourceFileHref(item) {\n return safeHttpUrl(item?.url)\n}'])
|
||||
assert.deepEqual([...wrappers], ['sourceFileHref'], '包装函数识别失效')
|
||||
const synthetic: HrefBinding[] = [
|
||||
{ file: 'a.vue', line: '<a :href="safeHttpUrl(x)">' },
|
||||
{ file: 'b.vue', line: '<a :href="sourceFileHref(x)">' },
|
||||
{ file: 'c.vue', line: '<a :href="ALIPRICE_URL">' },
|
||||
{ file: 'd.vue', line: '<a :href="item.task_data.file_url">' },
|
||||
]
|
||||
const violations = unvettedBindings(synthetic, wrappers)
|
||||
assert.deepEqual(violations.map((v) => v.file), ['d.vue'], '检测必须只漏放原始绑定')
|
||||
})
|
||||
Reference in New Issue
Block a user