Compare commits

..

3 Commits

Author SHA1 Message Date
huangzd1997 92af45a899 fix(后管表格): 操作列给 px 下限并统一可换行,店铺密钥整表 1538→1227px
三张截图同一个结构缺陷的两个方向:操作列 <td> 上直接 display:flex + overflow:hidden +
white-space:nowrap,而列宽是声明死的,超宽时的失败模式是"按钮静默消失"——DOM 里在、
事件也在,就是看不见点不到。
  - 写死 px(店铺密钥线上 160,三颗按钮实测需 215.5)⇒ 从右裁,删除整颗没了;
  - 写百分比(最低价 ASIN 9%,两颗需 114)⇒ 百分比跟容器一起缩,且 .asin-col-actions
    带 justify-content:flex-end 把溢出翻到左侧,于是"配置"被吃掉而"删除"看着完好。

flex-wrap 单独不够:900px 容器下 9% 只有 56.7px,连一颗 53px 按钮加 24px padding 都装不下,
换行之后照样裁。所以列必须有 px 下限。OPS_MIN_COL_PX 是 browser-use 在 100% 缩放下渲染
.btn.btn-sm 量的 offsetWidth(两字 53/四字 80/五字 93.5)+ gap 8 + td 左右 padding 24,
三元文案按较长分支计,不是按字数估的。

改动落在 18 处操作列里不达标的 6 处:UserSecrets 250→315、RecordsDigitalHuman 240→290、
DedupeRegistry 无声明→140、QueryAsin 与 SkipPrice 9%→140 并补 flex-wrap、
ShopKeys 270→245。另把店铺密钥整表 1538→1227px(代理 190→90、紫鸟令牌 220→160、
白名单状态 150→110 等按实测内容宽收窄):那页 100% 缩放下内容区只有 ~1280,
"操作"整列要横向滚动才看到,这才是"没显示全"的主账。

护栏扩到 5 条。一个真发现:旧护栏只扫 .ops-cell,扫不到 .asin-col-actions——这就是
1051d844 声称"扫过 8 个页面"却把最低价 ASIN 两页整个留在盲区的原因。现补上双向登记表
相等断言(新增页面不登记就红)。过程中护栏抓到我自己写的缺陷:<th[^>]*> 会连 <thead>
一起吃掉,再被新加的 HTML 注释里的"操作"两字喂饱,把"序号 52px"当成操作列宽度报出来;
已改为排除 <thead> + 解析前剥注释,并补一条内存反例自证(专喂"注释里写 flex-wrap 但代码
没设"和"百分比列"两种形状),防止尺子变恒绿。

验证:干净 worktree(2455b8fa + 只本批 7 个文件,git status 恰好 7 行 M)实跑前端 1765 例
0 红、vue-tsc rc=0、vite build rc=0;产物正反锚点已核 ShopKeys chunk 245px→1/旧值
270px→0、SkipPrice chunk 140px→1/旧值 9%→0。真浏览器复验 1280/1440/1516 三种容器下
三页 hScroll=0 且操作列不裁,900px 极端容器下仍不裁、只有文本列走 ellipsis(都有 title)。
主树混合态另跑 1769 例 0 红,差的 4 例是并行会话未提交的测试,与本批无关。
2026-10-08 20:59:49 +08:00
huangzd1997 3571004423 fix(产品风险结果文件): 表头样式改在 SXSSF flush 之前施加,大结果集不再永久卡死
现网证据(10-08 19:42,biz_task_file_job):job 21603 / task 30219 / user 983 的 ASSEMBLE_RESULT
FAILED,error_message 是 `generate product-risk excel failed: Cannot invoke
"Row.getCell(int)" because "headerRow" is null`,retry_count=5 全是同一个错;
10-07 20:55 的 job 21549 是同一条错 ⇒ 不是这次重启弄的,是早就存在的确定性缺陷,只是没人归因过。

机制:SxssfWorkbookWriter 用的是 SXSSF(流式,行访问窗口 200)。
`writeWorkbook` 在把整批数据行写完之后才 `applyDetailHeaderStyle(sheet.getRow(0), detailStyle)`,
而数据一超过 200 行,第 0 行早被 flush 出内存,`getRow(0)` 回读到 null,逐格取样式就 NPE;
外层 `catch (Exception)` 把它吞成一条业务失败文案,于是**结果集小的任务正常、大的永远出不来文件**,
任务一直挂 RUNNING。所以这条 bug 只在行数跨过分界时出现,跟数据内容无关。

修法是把那一次表头样式施加挪到写数据之前(createSheet 刚建好第 0 行,必然在窗口内),
一行位置变动,样式范围(6..8 列)与语义都不动。

验证:先写复现用例(260 行 > 窗口)⇒ 红,且报错文字与现网逐字一致;挪位置后 5/5 绿、
`ProductRiskTaskServiceTest` 5 例同绿(共 10 例 0 红)。变异自证 3/3 被杀:
M1 把调用挪回循环之后(生产原样)1 红、M2 整行删掉调用 1 红(断言同时钉住"样式还在",
不许只钉"不抛异常")、M3 把 6..8 悄悄缩成只第 6 列 1 红;三轮还原后文件哈希
`68c32f8ef2c0` 与注入前逐字节一致。
2026-10-08 20:53:27 +08:00
huangzd1997 2455b8fafc feat(版本硬地板): ClientVersionGuardFilter 双模式闸门,默认惰性+只记账
口径出处:四面 9 分文档 §2 后端最后一项。此前全仓唯一的 minClientVersion 在 digitalhuman
里,且 DigitalHumanVersionService:86 写入、:258 读出两处都是**透传**,全树没有一处比较过它
(grep getMinClientVersion 只有这两处命中)——对桌面客户端 API 面零约束。

新增 backend-java/src/main/java/com/nanri/aiimage/config/ClientVersionGuardFilter.java:
读 X-Client-Version,与 aiimage.client-version.min-supported-version 比较,三档开关:
- min 留空(默认)= 闸门整条惰性,逐请求等价于没装;
- enforce=false(默认)= 只记账:Counter aiimage.client.version.floor{verdict,version,enforce}
  + 每个 (verdict,version) 至多一条 [版本地板] WARN(日志去重不吞计数,与 10-06 通知放大同口径);
- enforce=true 才拒,响应体沿用项目约定 HTTP 200 + {success:false, code:4012, message, data}。
另有一条 reject-unreported=false:4.0.46 及更早的装机不知道有这个头,光翻 enforce 就把它们
判死等于用一次配置变更打停全线存量,所以"未上报"默认只进 unreported 桶;报不出格式的
(4.x.6)永不拒。

受管前缀**复用** AdminApiGuardFilter.USER_TOOL_PREFIXES(同一份"桌面客户端直连的用户态前缀"
口径,改成包级可见,不复制清单),另补 /api/client(取凭据第一跳)。/api/version/** 明确不在
名单内——被拒的老客户端必须永远能拿到升级信息,否则闸门把自己变成砖。

ClientVersionGuardFilterTest 12 例(mvn -o test -Dtest=ClientVersionGuardFilterTest:
Tests run: 12, Failures: 0, Errors: 0):两种模式各钉一条正断言(记账必须"响应体一个字节都
不许多"、执法必须"chain 不前进"),另钉默认态零行为、三类非客户端面零判定、unreported 与
unparsable 分桶、名单逐条继承 + 三个排除项、版本解析/比较边界(4.0==4.0.0、4.0<4.0.1、
4.0.46.2>4.0.46、v4.0.6/4..6/4.x.6 判不出)、WARN 去重与计数不相干、min 配置写坏时不拒任何人。

不出包、不重启、不改任何 yml(默认值即现网态)。
2026-10-08 20:25:59 +08:00
12 changed files with 783 additions and 34 deletions
@@ -287,7 +287,7 @@ onMounted(load)
<th style="width: 130px">状态</th>
<th style="width: 170px">创建时间</th>
<th style="width: 170px">更新时间</th>
<th style="width: 250px">操作</th>
<th style="width: 315px">操作</th>
</tr>
</thead>
<tbody>
@@ -390,7 +390,7 @@ onMounted(() => {
<th v-if="isSuperAdmin">分组</th>
<th>创建时间</th>
<th>更新时间</th>
<th>操作</th>
<th style="width: 140px">操作</th>
</tr>
</thead>
<tbody>
@@ -405,7 +405,7 @@ onMounted(() => {
<th style="width: 12%">国家</th>
<th style="width: 170px">创建时间</th>
<th style="width: 170px">更新时间</th>
<th style="width: 9%">操作</th>
<th style="width: 140px">操作</th>
</tr>
</thead>
<tbody>
@@ -723,6 +723,9 @@ h3 {
justify-content: flex-end;
gap: 8px;
white-space: nowrap;
/* 与最低价 ASIN 同形:列宽已从 9% 改成 140px 下限,再补 wrap 兜住文案变长的情况,
让"超宽"从"按钮静默消失"退化成"多占一行"。 */
flex-wrap: wrap;
background: #ffffff;
box-shadow: -9px 0 12px -10px rgba(31, 48, 66, 0.45);
}
@@ -459,7 +459,7 @@ onMounted(() => {
<th style="width: 10%">最低价</th>
<th style="width: 170px">创建时间</th>
<th style="width: 170px">更新时间</th>
<th style="width: 9%">操作</th>
<th style="width: 140px">操作</th>
</tr>
</thead>
<tbody>
@@ -805,6 +805,10 @@ h3 {
justify-content: flex-end;
gap: 8px;
white-space: nowrap;
/* 列宽已从 9% 改成 140px 下限(两字按钮 53×2 + gap 8 + td 左右 padding 24 = 138)。
百分比会跟着容器一起缩,配上 justify-content:flex-end 后溢出翻到左侧,
"配置"整颗被吃掉而"删除"看着完好——2026-10-08 那单截图就是这个形状。 */
flex-wrap: wrap;
background: #ffffff;
box-shadow: -9px 0 12px -10px rgba(31, 48, 66, 0.45);
}
@@ -225,7 +225,7 @@ onMounted(load)
<th style="width: 120px">MD5</th>
<th>更新日志</th>
<th style="width: 140px">发布时间</th>
<th style="width: 240px">操作</th>
<th style="width: 290px">操作</th>
</tr>
</thead>
<tbody>
@@ -222,16 +222,18 @@ onMounted(load)
<div class="shop-key-table-scroll">
<table>
<thead>
<!-- 刚性列(序号/两个时间/操作)给准 px,文本列收到"能 ellipsis 但不白占"的宽度:
原来 1538px 在 ~1280 的内容区里放不下,"操作"整列要横向滚动才看得见。 -->
<tr>
<th style="width: 58px">序号</th>
<th style="width: 150px">备注名</th>
<th style="width: 160px">紫鸟账号名称</th>
<th style="width: 220px">紫鸟令牌</th>
<th style="width: 190px">代理</th>
<th style="width: 150px">白名单状态 <span class="table-help" aria-hidden="true">?</span></th>
<th style="width: 170px">创建时间</th>
<th style="width: 170px">修改时间</th>
<th style="width: 270px">操作</th>
<th style="width: 52px">序号</th>
<th style="width: 110px">备注名</th>
<th style="width: 140px">紫鸟账号名称</th>
<th style="width: 160px">紫鸟令牌</th>
<th style="width: 90px">代理</th>
<th style="width: 110px">白名单状态 <span class="table-help" aria-hidden="true">?</span></th>
<th style="width: 160px">创建时间</th>
<th style="width: 160px">修改时间</th>
<th style="width: 245px">操作</th>
</tr>
</thead>
<tbody>
@@ -6,15 +6,47 @@ import { readSource } from './helpers.ts'
/**
* 操作列的按钮一旦超过列宽,会**整颗消失**而不是换行:这些页的 td 是 `overflow:hidden` +
* `table-layout:fixed`,而 `.ops-cell` 是 nowrap flex。2026-10-08 店铺密钥那单"没有删除功能"
* 就是这么来的——按钮在线上包的 DOM 里、事件也在,只是被裁到看不见点不到(列给 160px、实测需 240px)。
* `table-layout:fixed`,而 `.ops-cell` / `.asin-col-actions` 是 nowrap flex。2026-10-08 店铺密钥
* 那单"没有删除功能"就是这么来的——按钮在线上包的 DOM 里、事件也在,只是被裁到看不见点不到
* (列给 160px、实测需 215.5px)。
*
* 这条看守钉的是**结构**不是像素:宽度按当前文案够,改天多一颗按钮或文案变长就又塌了,
* 而 `flex-wrap: wrap` 让"超宽"从"静默消失"退化成"多占一行",不需要有人去重算宽度。
* 两条失败方向都见过:
* - 列宽写死 px(店铺密钥 160)⇒ 从**右**裁,最后一颗(删除)整颗没了;
* - 列宽写百分比(最低价 ASIN `9%`)⇒ 百分比跟着容器一起缩,且 `.asin-col-actions` 带
* `justify-content: flex-end`,溢出翻到**左**侧,于是"配置"被吃掉、"删除"看着完好。
* 所以光补 `flex-wrap` 不够:900px 容器下 9% 只有 56.7px,连一颗 53px 的按钮加 24px padding
* 都装不下,wrap 之后照样裁。列必须有 **px 下限**。
*
* 下面 OPS_MIN_COL_PX 是实测不是估算:browser-use 在 100% 缩放下渲染 `.btn.btn-sm` 量的
* offsetWidth(两字 53 / 四字 80 / 五字 93.5),加 `gap: 8px` 与 td 左右 padding 各 12px。
* 三元文案按**较长**分支计(`检测中…` vs `检测白名单` 取后者)。
*/
const SRC = 'src/pages'
/** 每页操作列「单行装下全部按钮」所需的列最小宽(px,实测算出)。 */
const OPS_MIN_COL_PX: Record<string, number> = {
'src/pages/account/CompaniesPage.vue': 77,
'src/pages/account/GroupsPage.vue': 138,
'src/pages/account/MenusPage.vue': 138,
'src/pages/account/UserSecretsPage.vue': 314,
'src/pages/account/UsersPage.vue': 138,
'src/pages/asin/AsinInvalidPage.vue': 138,
'src/pages/asin/DedupeRegistryPage.vue': 138,
'src/pages/asin/ProductCategoryPage.vue': 138,
'src/pages/asin/QueryAsinPage.vue': 138,
'src/pages/asin/SkipPricePage.vue': 138,
'src/pages/records/DeviceLogsPage.vue': 138,
'src/pages/records/RecordsDigitalHumanVersionPage.vue': 287,
'src/pages/records/RecordsSoftwareVersionPage.vue': 77,
'src/pages/records/RecordsTutorialPage.vue': 77,
'src/pages/shop/ShopKeysPage.vue': 240,
'src/pages/shop/ShopManagePage.vue': 199,
}
/** 操作列的 flex 容器类名。漏一个就是把一整族页面留在盲区里(`.asin-col-actions` 曾这么漏过两页)。 */
const OPS_CELL_CLASSES = ['ops-cell', 'asin-col-actions']
function vueFiles(dir: string): string[] {
const out: string[] = []
for (const name of readdirSync(dir)) {
@@ -25,6 +57,11 @@ function vueFiles(dir: string): string[] {
return out
}
/** 相对工程根的正斜杠路径。 */
function rel(file: string): string {
return file.replace(/\\/g, '/')
}
interface Cell {
file: string
buttons: number
@@ -35,32 +72,133 @@ interface Cell {
function opsCells(sources: Array<{ file: string; source: string }>): Cell[] {
const cells: Cell[] = []
for (const { file, source } of sources) {
const block = /\.ops-cell[ \t]*\{([^}]*)\}/.exec(source)
if (!block) continue
const td = /<td[^>]*class="[^"]*ops[^"]*"[^>]*>([\s\S]*?)<\/td>/.exec(source)
const buttons = td ? (td[1].match(/<button/g) || []).length : 0
// 行锚 + 分号:不锚就会被块内注释里的散文喂饱(本仓踩过一次)。
const wrapped = /\n[ \t]*flex-wrap:[ \t]*wrap[ \t]*;/.test(block[1])
cells.push({ file: file.replace(/\\/g, '/'), buttons, wrapped })
// 注释先剥掉:CSS 注释里的 `flex-wrap: wrap;` 会把"这条页已经能换行"判成恒真。
const markup = stripHtmlComments(source)
let fileCells = 0
for (const cls of OPS_CELL_CLASSES) {
const block = new RegExp('\\.' + cls + '[ \\t]*\\{([^}]*)\\}').exec(source)
if (!block) continue
const td = new RegExp('<td[^>]*class="[^"]*' + cls + '[^"]*"[^>]*>([\\s\\S]*?)<\\/td>').exec(markup)
const buttons = td ? (td[1].match(/<button/g) || []).length : 0
// 行锚 + 分号:不锚就会被块内注释里的散文喂饱(本仓踩过一次)。
const wrapped = /\n[ \t]*flex-wrap:[ \t]*wrap[ \t]*;/.test(stripCssComments(block[1]))
cells.push({ file: rel(file), buttons, wrapped })
fileCells += 1
}
if (fileCells === 0 && OPS_MIN_COL_PX[rel(file)]) {
// 登记表里有这页、扫描却认不出它的 flex 容器 ⇒ 形状与源码脱节,单独报出来。
cells.push({ file: rel(file), buttons: -1, wrapped: false })
}
}
return cells
}
test('ops_cell_ruler_actually_sees_the_family', () => {
function stripHtmlComments(s: string): string {
return s.replace(/<!--[\s\S]*?-->/g, '')
}
function stripCssComments(s: string): string {
return s.replace(/\/\*[\s\S]*?\*\//g, '')
}
/**
* 抓「操作」列的 <th> 宽度声明:返回 null = 压根没声明,返回 '9%' 这类 = 非 px。
* 两处坑都踩过:`<th[^>]*>` 会连 `<thead>` 一起吃掉;HTML 注释里出现"操作"就会把
* 匹配范围截在第一个真 <th> 之前,于是把"序号 52px"当成操作列宽度报出来。
*/
function opsColDecl(source: string): string | null {
const cleaned = stripHtmlComments(source)
const m = /<th(?![\w-])([^>]*)>(?:(?!<\/th>)[\s\S])*?操作(?:(?!<\/th>)[\s\S])*?<\/th>/.exec(cleaned)
if (!m) return '__no_header__'
const style = /style="[^"]*width:\s*([^;"]+)/.exec(m[1])
return style ? style[1].trim() : null
}
function sourcesOfAll(): Array<{ file: string; source: string }> {
return vueFiles(SRC).map((file) => ({ file, source: readSource(file) }))
}
test('ops_ruler_actually_sees_the_family', () => {
assert.ok(existsSync(SRC), `扫不到 ${SRC}:目录挪了就是整面恒绿`)
const cells = opsCells(vueFiles(SRC).map((file) => ({ file, source: readSource(file) })))
assert.ok(cells.length >= 14,
`只认出 ${cells.length} 个带 .ops-cell 的页(今天 14 个)⇒ 扫描形状与源码脱节,这条看守已经失明`)
const cells = opsCells(sourcesOfAll())
assert.ok(cells.length >= Object.keys(OPS_MIN_COL_PX).length,
`只认出 ${cells.length} 个操作列容器,登记表有 ${Object.keys(OPS_MIN_COL_PX).length} 页`
+ ' ⇒ 扫描形状与源码脱节,下面的断言已经失明')
const multi = cells.filter((c) => c.buttons >= 2)
assert.ok(multi.length >= 11,
`只认出 ${multi.length} 页操作列有 ≥2 颗按钮(今天 11 页)⇒ 按钮计数读不到,下面的断言无从判定`)
assert.ok(multi.length >= 13,
`只认出 ${multi.length} 页操作列有 ≥2 颗按钮(今天 13 页)⇒ 按钮计数读不到,无从判定`)
})
test('ops_cell_registry_matches_scanned_files_both_ways', () => {
const scanned = new Set(opsCells(sourcesOfAll()).map((c) => c.file))
const registered = new Set(Object.keys(OPS_MIN_COL_PX))
const unregistered = [...scanned].filter((f) => !registered.has(f))
const vanished = [...registered].filter((f) => !scanned.has(f))
assert.deepEqual(unregistered, [],
'这些页有操作列但没登记列宽下限 ⇒ 新增页面必须显式登记,否则这条看守对它无效')
assert.deepEqual(vanished, [],
'登记表里这些页已经扫不到了 ⇒ 页面删了要同步删表项,不许留死条目')
})
test('every_multi_button_ops_cell_wraps', () => {
const offenders = opsCells(vueFiles(SRC).map((file) => ({ file, source: readSource(file) })))
const offenders = opsCells(sourcesOfAll())
.filter((c) => c.buttons >= 2 && !c.wrapped)
.map((c) => `${c.file}(${c.buttons} 颗按钮)`)
assert.deepEqual(offenders, [],
'这些页的操作列是 nowrap flex + td overflow:hidden:按钮总宽一旦超过列宽,'
+ '最后一颗会整颗被裁掉(看不见也点不到),补一行 flex-wrap: wrap 即可')
})
test('ops_column_width_is_px_and_wide_enough', () => { const bad: string[] = []
for (const [file, minPx] of Object.entries(OPS_MIN_COL_PX)) {
const decl = opsColDecl(readSource(file))
if (decl === '__no_header__') { bad.push(`${file} 找不到「操作」列表头`); continue }
if (decl === null) { bad.push(`${file} 操作列 <th> 没声明宽度(fixed layout 下拿剩余空间,可被压到 0)`); continue }
const px = /^(\d+(?:\.\d+)?)px$/.exec(decl)
if (!px) { bad.push(`${file} 操作列声明 ${decl}:百分比会跟着容器缩,缩到装不下按钮就从左侧静默裁切`); continue }
if (parseFloat(px[1]) < minPx) {
bad.push(`${file} 操作列 ${px[1]}px < 实测需 ${minPx}px(按钮占宽 + gap + 左右 padding 24)`)
}
}
assert.deepEqual(bad, [], '操作列必须是 px 且 ≥ 实测需求,否则超宽时的失败模式是"按钮静默消失"')
})
/**
* 尺子自己得可证伪:下面四份内存假源码各对应一种"会判错"的形状,
* 判不出来就是恒绿——本仓在"注释喂饱判据"和"`<th` 连 `<thead>` 一起吃"上各踩过一次。
*/
test('ruler_is_falsifiable_on_in_memory_counterexamples', () => {
const withCommentTrap = [
'<thead>',
' <!-- 刚性列(序号/两个时间/操作)给准 px -->',
' <tr>',
' <th style="width: 52px">序号</th>',
' <th style="width: 245px">操作</th>',
' </tr>',
'</thead>',
].join('\n')
assert.equal(opsColDecl(withCommentTrap), '245px',
'注释里的"操作"把匹配截在第一个真 <th> 之前 ⇒ 会把"序号"的宽度当成操作列宽度')
assert.equal(opsColDecl('<tr><th>操作</th></tr>'), null,
'<th> 没写 style 时必须报 null,不能悄悄放过')
assert.equal(opsColDecl('<tr><th style="width: 9%">操作</th></tr>'), '9%',
'百分比必须原样报出来,由调用方判成违规')
assert.equal(opsColDecl('<tr><th>别的列</th></tr>'), '__no_header__',
'找不到「操作」表头要显式报,不能回 null 与"没声明"混成一类')
const wrapOnlyInComment = [
'<td class="ops-cell"><button class="btn"></button><button class="btn"></button></td>',
'<style>',
'.ops-cell {',
' display: flex;',
' /* 这里写了 flex-wrap: wrap; 但代码其实没设 */',
'}',
'</style>',
].join('\n')
const cells = opsCells([{ file: 'src/pages/asin/TrapPage.vue', source: wrapOnlyInComment }])
assert.equal(cells.length, 1, '假源码没被认出容器 ⇒ 扫描形状与源码脱节')
assert.equal(cells[0].buttons, 2, `按钮数应认出 2,实际 ${cells[0].buttons}`)
assert.equal(cells[0].wrapped, false,
'CSS 注释里的 flex-wrap: wrap; 被当成了真声明 ⇒ 这条看守对"只写在注释里"的修复恒绿')
})
@@ -72,8 +72,11 @@ public class AdminApiGuardFilter extends OncePerRequestFilter {
* <p>原因:桌面客户端(Python)直连这些接口且不带任何认证头,先于客户端发布开启会
* 让线上集采/跟价全线 401。待携带 X-Internal-Token 的新客户端铺开后,把开关置 true
* (或把这些前缀从 USER_TOOL_PREFIXES 移除、直接无条件纳入)即可完成收紧。
*
* <p>包级可见(不是 private):{@code ClientVersionGuardFilter} 复用同一份"桌面客户端直连的
* 用户态前缀"口径。**这份清单改动会同时改动两个闸门的覆盖面**,改前先想清楚版本地板是否也该跟着变。
*/
private static final String[] USER_TOOL_PREFIXES = {
static final String[] USER_TOOL_PREFIXES = {
"/api/collect-data",
"/api/price-track",
// 2026-09 全维度审查补:以下前缀此前完全在守卫范围之外。
@@ -0,0 +1,291 @@
package com.nanri.aiimage.config;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.nanri.aiimage.common.api.ApiResponse;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.MeterRegistry;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
/**
* 客户端版本硬地板:桌面客户端(ShuFuAI)上报的 {@value #HEADER} 低于服务端最低支持版本时的判定点。
*
* <p>此前全仓唯一的 {@code minClientVersion} 在 digitalhuman 模块里,而且只是个**存进库又原样
* 吐回 VO 的字段**({@code DigitalHumanVersionService:86} 写入、{@code :258} 读出,两处都是透传,
* 全树没有一处比较过它),对桌面客户端的 API 面零约束。本类是那个缺口的真闸门。
*
* <p>三档开关,默认态 = **现网零行为变更**:
* <ul>
* <li>{@code aiimage.client-version.min-supported-version}(默认空):留空即整个闸门惰性
* ({@link #shouldNotFilter} 直接跳过),与"没装这个过滤器"逐请求等价;</li>
* <li>{@code aiimage.client-version.enforce}(默认 false):只**记账**不拒绝——计指标 +
* 每个版本号至多一条 WARN,业务响应照常放行。这一档用来在真实装机分布上量"翻 true 会打到
* 多少台",量完再决定;</li>
* <li>{@code aiimage.client-version.reject-unreported}(默认 false):翻 true 时,
* **不报版本**的老客户端要不要一起拒。这一条单独成开关,是因为 4.0.46 及更早的装机根本不知道
* 有这个头——把它们算成"低于地板"等于用一次配置变更把存量装机全线打停;默认 false 时它们只进
* {@code unreported} 计数,不挨拒。</li>
* </ul>
* 判不出来的头({@code "abc"}、{@code "4.x.6"})永不被拒,只进 {@code unparsable} 计数:
* 一次格式异常不该由客户端承担断服代价。
*
* <p>受管前缀取自 {@link AdminApiGuardFilter#USER_TOOL_PREFIXES}(**同一份出处**,不复制清单:
* 那份常量记的正是"桌面客户端直连的用户态接口"),另加 {@value #CLIENT_ENTRY_PREFIX}
* ({@code /api/client}——客户端取凭据的第一跳,不在那份名单里,但它同样得能被地板挡住)。
* {@code /api/version/**}(更新检查)与 {@code /api/admin/**}、{@code /api/internal/**} 一律**不在**
* 受管集合内:被拒的老客户端必须永远能拿到升级信息,否则闸门把自己变成砖。
*
* <p>响应体沿用项目约定(HTTP 200 + {@code {success:false, code, message, data}},与
* {@code GlobalExceptionHandler} 同形),业务码 {@value #CODE_TOO_OLD}:401/403 已被鉴权与
* 越权占用,4011 是被顶下线,这里取同一族的 4012。
*
* <p>紧急回退:把 {@code min-supported-version} 置空即可(无需重启改代码),或
* {@code aiimage.client-version.enforce=false} 退回纯记账。
*/
@Slf4j
@Component
@Order(Ordered.LOWEST_PRECEDENCE)
public class ClientVersionGuardFilter extends OncePerRequestFilter {
/** 客户端自报版本的请求头(由 app_client 的 user_token 出口钩子注入,只对自家后端基址生效)。 */
public static final String HEADER = "X-Client-Version";
/** 低于地板时的业务码;与 {@code DeviceSessionPolicy.CODE_KICKED=4011} 同族。 */
public static final int CODE_TOO_OLD = 4012;
/** 取凭据那一跳:桌面端入口,不在 {@link AdminApiGuardFilter#USER_TOOL_PREFIXES} 里,单独补上。 */
static final String CLIENT_ENTRY_PREFIX = "/api/client";
/** 指标名:按 verdict(below/unreported/unparsable)与是否 enforce 打标签,装机分布由 version 标签给出。 */
static final String METRIC = "aiimage.client.version.floor";
private static final String VERDICT_BELOW = "below";
private static final String VERDICT_UNREPORTED = "unreported";
private static final String VERDICT_UNPARSABLE = "unparsable";
/** WARN 去重上限:版本号是有限集合,超上限后不再新增键(只继续计数),防无界增长。 */
private static final int WARN_KEYS_MAX = 64;
private final ObjectMapper objectMapper;
private final MeterRegistry meterRegistry;
private final Set<String> warned = ConcurrentHashMap.newKeySet();
@Value("${aiimage.client-version.min-supported-version:}")
private String minSupportedVersion;
@Value("${aiimage.client-version.enforce:false}")
private boolean enforce;
@Value("${aiimage.client-version.reject-unreported:false}")
private boolean rejectUnreported;
public ClientVersionGuardFilter(ObjectMapper objectMapper) {
this(objectMapper, (MeterRegistry) null);
}
public ClientVersionGuardFilter(ObjectMapper objectMapper, MeterRegistry meterRegistry) {
this.objectMapper = objectMapper;
this.meterRegistry = meterRegistry;
}
/** 生产构造:Micrometer 注册表可选(无注册表时只留日志,与 {@code IdempotentRetryGuard} 同口径)。 */
@Autowired
public ClientVersionGuardFilter(ObjectMapper objectMapper,
ObjectProvider<MeterRegistry> meterRegistryProvider) {
this(objectMapper, meterRegistryProvider == null ? null : meterRegistryProvider.getIfAvailable());
}
/** 闸门是否已配置(最低版本非空)。空 = 惰性,现网默认态。 */
public boolean isConfigured() {
return minSupportedVersion != null && !minSupportedVersion.trim().isEmpty();
}
@Override
protected boolean shouldNotFilter(HttpServletRequest request) {
return !isConfigured() || !isClientFacing(request.getRequestURI());
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws IOException, ServletException {
String uri = request.getRequestURI();
String reported = headerValue(request);
String verdict = verdictOf(reported);
if (verdict == null) {
chain.doFilter(request, response);
return;
}
count(verdict, reported);
if (firstWitness(verdict, reported)) {
// 一次配置变更会被每个在跑的客户端逐请求命中:这里按 (verdict, version) 去重,
// 量交给指标,日志只留第一条(与 10-06 通知放大的处置同一口径)。
log.warn("[版本地板] {} {} 自报版本={} 最低支持={} verdict={} enforce={} —— {}",
request.getMethod(), uri, reported, minSupportedVersion.trim(), verdict, enforce,
enforce ? "本次已拒绝" : "记账模式,暂不拒绝");
}
if (shouldReject(verdict)) {
writeTooOld(request, response, reported, verdict);
return;
}
chain.doFilter(request, response);
}
/**
* 归类:{@value #VERDICT_BELOW}/{@value #VERDICT_UNREPORTED}/{@value #VERDICT_UNPARSABLE};
* 达标返回 null(什么都不做)。
*/
private String verdictOf(String reported) {
long[] floor = parse(minSupportedVersion);
if (floor == null) {
// 配置本身写坏了(比如塞了个 "v4.0"):不猜、不拒,只记一条,等人工把配置改对。
return isBlank(reported) ? null : VERDICT_UNPARSABLE;
}
if (isBlank(reported)) {
return VERDICT_UNREPORTED;
}
long[] actual = parse(reported);
if (actual == null) {
return VERDICT_UNPARSABLE;
}
return compare(actual, floor) < 0 ? VERDICT_BELOW : null;
}
/** 只有"确实低于地板"(以及显式打开的 unreported)才拒;unparsable 永不被拒。 */
private boolean shouldReject(String verdict) {
if (!enforce) {
return false;
}
if (VERDICT_BELOW.equals(verdict)) {
return true;
}
return VERDICT_UNREPORTED.equals(verdict) && rejectUnreported;
}
/** 桌面客户端会走的入口前缀(含取凭据那一跳)。 */
static boolean isClientFacing(String uri) {
if (uri == null) {
return false;
}
for (String prefix : AdminApiGuardFilter.USER_TOOL_PREFIXES) {
if (uri.startsWith(prefix)) {
return true;
}
}
return uri.startsWith(CLIENT_ENTRY_PREFIX);
}
private static String headerValue(HttpServletRequest request) {
String raw = request.getHeader(HEADER);
return raw == null ? "" : raw.trim();
}
private static boolean isBlank(String value) {
return value == null || value.isEmpty();
}
/**
* 解析点分数字版本:{@code 4.0.46} → {@code [4,0,46]};任何一段非数字(含空串、{@code 4.x})返回 null。
* 故意不做"取前缀数字"这类容错:猜出来的版本号会被当成合法装机统计进去。
*/
static long[] parse(String version) {
if (version == null) {
return null;
}
String text = version.trim();
if (text.isEmpty()) {
return null;
}
String[] parts = text.split("\\.", -1);
long[] segments = new long[parts.length];
for (int i = 0; i < parts.length; i++) {
String part = parts[i].trim();
if (part.isEmpty() || !isAllDigits(part)) {
return null;
}
try {
segments[i] = Long.parseLong(part);
} catch (NumberFormatException overflow) {
return null;
}
}
return segments;
}
private static boolean isAllDigits(String text) {
for (int i = 0; i < text.length(); i++) {
if (text.charAt(i) < '0' || text.charAt(i) > '9') {
return false;
}
}
return true;
}
/** 逐段比较,短的一方缺段按 0 补:{@code 4.0 == 4.0.0},{@code 4.0 < 4.0.1},{@code 4.0.46.2 > 4.0.46}。 */
static int compare(long[] left, long[] right) {
int length = Math.max(left.length, right.length);
for (int i = 0; i < length; i++) {
long a = i < left.length ? left[i] : 0L;
long b = i < right.length ? right[i] : 0L;
if (a != b) {
return Long.compare(a, b);
}
}
return 0;
}
/** 每个 (verdict, version) 组合只许第一条 WARN 通过;返回 true 表示"这次是第一条"。 */
boolean firstWitness(String verdict, String version) {
String key = verdict + "@" + version;
if (warned.contains(key)) {
return false;
}
if (warned.size() >= WARN_KEYS_MAX) {
return false;
}
return warned.add(key);
}
private void count(String verdict, String version) {
if (meterRegistry == null) {
return;
}
Counter.builder(METRIC)
.tag("verdict", verdict)
.tag("version", isBlank(version) ? "unknown" : version)
.tag("enforce", String.valueOf(enforce))
.register(meterRegistry)
.increment();
}
private void writeTooOld(HttpServletRequest request, HttpServletResponse response,
String reported, String verdict) throws IOException {
Map<String, String> data = new LinkedHashMap<>();
data.put("minSupportedVersion", minSupportedVersion.trim());
data.put("reportedVersion", reported);
data.put("verdict", verdict);
data.put("uri", request.getRequestURI());
String message = VERDICT_UNREPORTED.equals(verdict)
? "客户端版本未知(未上报 " + HEADER + "),请升级到 " + minSupportedVersion.trim() + " 及以上"
: "客户端版本过低(" + reported + "),请升级到 " + minSupportedVersion.trim() + " 及以上";
response.setStatus(HttpServletResponse.SC_OK);
response.setContentType("application/json;charset=UTF-8");
response.getWriter().write(objectMapper.writeValueAsString(
new ApiResponse<>(false, message, data, CODE_TOO_OLD)));
}
}
@@ -51,6 +51,9 @@ public class ProductRiskExcelAssemblyService {
List<ProductRiskRowDto> rows = safe.getOrDefault(sheetName, List.of());
CellStyle detailStyle = createDetailStyle(workbook);
CellStyle detailAsinStyle = createDetailAsinStyle(workbook);
// 表头样式必须在写数据之前施加:SXSSF 是流式的,窗口只有 200 行,
// 数据一超过这个数第 0 行就被 flush 出内存,此后 sheet.getRow(0) 回读到的是 null。
applyDetailHeaderStyle(sheet.getRow(0), detailStyle);
int rowIdx = 1;
for (ProductRiskRowDto dto : rows) {
List<ProductRiskRowDto.ViolationDetail> details = violationDetails(dto);
@@ -80,7 +83,6 @@ public class ProductRiskExcelAssemblyService {
}
rowIdx += groupSize;
}
applyDetailHeaderStyle(sheet.getRow(0), detailStyle);
applyDefaultColumnWidths(sheet);
}
writer.write(outputXlsx);
@@ -0,0 +1,267 @@
package com.nanri.aiimage.config;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
import org.junit.jupiter.api.Test;
import org.springframework.mock.web.MockFilterChain;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.util.ReflectionTestUtils;
import java.util.ArrayList;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
/**
* 客户端版本硬地板判据:**两种模式各钉一条**,并证明默认态(min 未配置)逐请求等价于没装闸门。
*
* <p>记账模式必须"只留痕不动响应"(chain 继续、响应体一个字节都不许多),执法模式必须"根本不放行"
* (chain 不前进 + 4012 体)。这两个断言分别挡住两类事故:只记账却顺手改了响应 = 现网故障;
* 想执法却只记了账 = 地板形同虚设。
*
* <p>重跑:{@code mvn -o test -Dtest=ClientVersionGuardFilterTest}(cwd = backend-java)。
*/
class ClientVersionGuardFilterTest {
private final ObjectMapper objectMapper = new ObjectMapper();
private ClientVersionGuardFilter filter(String minVersion, boolean enforce, boolean rejectUnreported,
MeterRegistry registry) {
ClientVersionGuardFilter filter = new ClientVersionGuardFilter(objectMapper, registry);
ReflectionTestUtils.setField(filter, "minSupportedVersion", minVersion);
ReflectionTestUtils.setField(filter, "enforce", enforce);
ReflectionTestUtils.setField(filter, "rejectUnreported", rejectUnreported);
return filter;
}
private ClientVersionGuardFilter accounting(String minVersion) {
return filter(minVersion, false, false, null);
}
private ClientVersionGuardFilter enforcing(String minVersion) {
return filter(minVersion, true, false, null);
}
private MockHttpServletRequest post(String uri, String reportedVersion) {
MockHttpServletRequest request = new MockHttpServletRequest("POST", uri);
if (reportedVersion != null) {
request.addHeader(ClientVersionGuardFilter.HEADER, reportedVersion);
}
return request;
}
private long counterValue(MeterRegistry registry, String verdict, String version) {
io.micrometer.core.instrument.Counter counter = registry.find(ClientVersionGuardFilter.METRIC)
.tag("verdict", verdict).tag("version", version).counter();
return counter == null ? 0L : (long) counter.count();
}
// ------------------------------------------------------------- 默认态:零行为变更
@Test
void minVersionUnsetMakesTheGateTotallyInert() throws Exception {
MeterRegistry registry = new SimpleMeterRegistry();
ClientVersionGuardFilter filter = filter("", false, false, registry);
// 一个明显"该被挡住"的老版本 + 一个不带版本的客户端核心入口:闸门惰性时都必须原样放行
for (MockHttpServletRequest request :
new MockHttpServletRequest[]{post("/api/shop-match/tasks/1/result", "1.0.0"),
post("/api/client/credentials", null)}) {
MockHttpServletResponse response = new MockHttpServletResponse();
MockFilterChain chain = new MockFilterChain();
filter.doFilter(request, response, chain);
assertThat(chain.getRequest()).as("%s 应被放行", request.getRequestURI()).isNotNull();
assertThat(response.getContentAsByteArray()).isEmpty();
}
assertThat(registry.find(ClientVersionGuardFilter.METRIC).counter()).isNull();
}
@Test
void nonClientFacingPathsAreNeverJudged() throws Exception {
MeterRegistry registry = new SimpleMeterRegistry();
ClientVersionGuardFilter filter = filter("4.0.46", true, true, registry);
// 执法模式、且 unreported 也拒:这三类面一条都不许被 judge
for (MockHttpServletRequest request : new MockHttpServletRequest[]{
post("/api/version/latest", "1.0.0"),
post("/api/admin/users", "1.0.0"),
post("/api/internal/user-proxy", null)}) {
MockHttpServletResponse response = new MockHttpServletResponse();
MockFilterChain chain = new MockFilterChain();
filter.doFilter(request, response, chain);
assertThat(chain.getRequest()).as("%s 不在受管面内", request.getRequestURI()).isNotNull();
assertThat(response.getContentAsByteArray()).isEmpty();
}
assertThat(registry.find(ClientVersionGuardFilter.METRIC).counter()).isNull();
}
// ------------------------------------------------------------- 记账模式(默认档位)
@Test
void belowFloorInAccountingModeRecordsWithoutTouchingTheResponse() throws Exception {
MeterRegistry registry = new SimpleMeterRegistry();
ClientVersionGuardFilter filter = filter("4.0.46", false, false, registry);
MockFilterChain chain = new MockFilterChain();
MockHttpServletResponse response = new MockHttpServletResponse();
filter.doFilter(post("/api/publish/tasks/7/result", "4.0.45"), response, chain);
assertThat(chain.getRequest()).as("记账模式不许截断请求").isNotNull();
assertThat(response.getContentAsByteArray()).as("记账模式响应体必须一个字节都不许多").isEmpty();
assertThat(counterValue(registry, "below", "4.0.45")).isEqualTo(1L);
}
@Test
void accountingCountsEveryRequestButWarnsOncePerVersion() throws Exception {
MeterRegistry registry = new SimpleMeterRegistry();
ClientVersionGuardFilter filter = filter("4.0.46", false, false, registry);
// 同一个老客户端连打三次:指标必须数到 3(巡检看的是量),WARN 只许第一条
for (int i = 0; i < 3; i++) {
filter.doFilter(post("/api/price-track/tasks/1/result", "4.0.40"),
new MockHttpServletResponse(), new MockFilterChain());
}
assertThat(counterValue(registry, "below", "4.0.40")).as("日志去重不许把计数一起吞掉").isEqualTo(3L);
assertThat(filter.firstWitness("below", "4.0.40")).as("4.0.40 已经留过一条 WARN").isFalse();
assertThat(filter.firstWitness("below", "4.0.41")).as("新出现过低版本应允许留第一条").isTrue();
}
@Test
void unreportedAndUnparsableBothLandInTheirOwnBuckets() throws Exception {
MeterRegistry registry = new SimpleMeterRegistry();
ClientVersionGuardFilter filter = filter("4.0.46", false, false, registry);
filter.doFilter(post("/api/brand/tasks", null), new MockHttpServletResponse(), new MockFilterChain());
filter.doFilter(post("/api/brand/tasks", " "), new MockHttpServletResponse(), new MockFilterChain());
filter.doFilter(post("/api/brand/tasks", "4.x.6"), new MockHttpServletResponse(), new MockFilterChain());
assertThat(counterValue(registry, "unreported", "unknown")).isEqualTo(2L);
assertThat(counterValue(registry, "unparsable", "4.x.6")).isEqualTo(1L);
assertThat(registry.find(ClientVersionGuardFilter.METRIC).tag("verdict", "below").counter())
.as("报不出版本不等于版本低").isNull();
}
// ------------------------------------------------------------- 执法模式
@Test
void belowFloorInEnforceModeRefusesWithoutReachingTheController() throws Exception {
MeterRegistry registry = new SimpleMeterRegistry();
ClientVersionGuardFilter filter = filter("4.0.46", true, false, registry);
MockHttpServletResponse response = new MockHttpServletResponse();
MockFilterChain chain = new MockFilterChain();
filter.doFilter(post("/api/similar-asin/tasks/9/result", "4.0.44"), response, chain);
assertThat(chain.getRequest()).as("执法模式必须截断,不能让老客户端进到 controller").isNull();
JsonNode body = objectMapper.readTree(response.getContentAsString());
assertThat(body.get("success").asBoolean()).isFalse();
assertThat(body.get("code").asInt()).isEqualTo(ClientVersionGuardFilter.CODE_TOO_OLD);
assertThat(body.get("message").asText()).contains("客户端版本过低").contains("4.0.46");
assertThat(body.get("data").get("minSupportedVersion").asText()).isEqualTo("4.0.46");
assertThat(body.get("data").get("reportedVersion").asText()).isEqualTo("4.0.44");
assertThat(counterValue(registry, "below", "4.0.44")).isEqualTo(1L);
}
@Test
void unreportedOldInstallsAreSparedUntilTheSeparateSwitchIsFlipped() throws Exception {
MockFilterChain spared = new MockFilterChain();
MockHttpServletResponse sparedResponse = new MockHttpServletResponse();
// 存量装机不知道有这个头:光翻 enforce 就把它们判死 = 一次配置变更打停全线
enforcing("4.0.46").doFilter(post("/api/shop-match/tasks/1/items", null), sparedResponse, spared);
assertThat(spared.getRequest()).as("reject-unreported 默认 false,未上报的装机不许被误杀").isNotNull();
assertThat(sparedResponse.getContentAsByteArray()).isEmpty();
MeterRegistry registry = new SimpleMeterRegistry();
ClientVersionGuardFilter both = filter("4.0.46", true, true, registry);
MockFilterChain refused = new MockFilterChain();
MockHttpServletResponse refusedResponse = new MockHttpServletResponse();
both.doFilter(post("/api/shop-match/tasks/1/items", null), refusedResponse, refused);
assertThat(refused.getRequest()).as("两个开关都打开后,未上报也要被拒").isNull();
assertThat(objectMapper.readTree(refusedResponse.getContentAsString()).get("code").asInt())
.isEqualTo(ClientVersionGuardFilter.CODE_TOO_OLD);
assertThat(counterValue(registry, "unreported", "unknown")).isEqualTo(1L);
}
@Test
void unparsableVersionIsNeverRefusedEvenInEnforceMode() throws Exception {
ClientVersionGuardFilter filter = enforcing("4.0.46");
MockFilterChain chain = new MockFilterChain();
MockHttpServletResponse response = new MockHttpServletResponse();
filter.doFilter(post("/api/publish/tasks/1/result", "4.x.6"), response, chain);
assertThat(chain.getRequest()).as("一次格式异常不该由客户端承担断服代价").isNotNull();
assertThat(response.getContentAsByteArray()).isEmpty();
}
@Test
void aVersionAtOrAboveTheFloorIsPassedWithoutAnyTrace() throws Exception {
MeterRegistry registry = new SimpleMeterRegistry();
ClientVersionGuardFilter filter = filter("4.0.46", true, true, registry);
filter.doFilter(post("/api/publish/tasks/1/result", "4.0.46"), new MockHttpServletResponse(),
new MockFilterChain());
filter.doFilter(post("/api/publish/tasks/1/result", "4.1.0"), new MockHttpServletResponse(),
new MockFilterChain());
assertThat(registry.find(ClientVersionGuardFilter.METRIC).counter()).isNull();
}
@Test
void aBrokenFloorConfigNeverRefusesAnyone() throws Exception {
// 把最低版本写成 "v4.0" 这类解析不出来的值:闸门不许据此拒绝任何客户端
ClientVersionGuardFilter filter = enforcing("v4.0");
MockFilterChain chain = new MockFilterChain();
MockHttpServletResponse response = new MockHttpServletResponse();
filter.doFilter(post("/api/publish/tasks/1/result", "1.0.0"), response, chain);
assertThat(chain.getRequest()).isNotNull();
assertThat(response.getContentAsByteArray()).isEmpty();
}
// ------------------------------------------------------------- 名单与解析
@Test
void clientFacingPrefixesComeFromTheAdminGuardListPlusTheCredentialEntry() {
List<String> missing = new ArrayList<>();
for (String prefix : AdminApiGuardFilter.USER_TOOL_PREFIXES) {
if (!ClientVersionGuardFilter.isClientFacing(prefix + "/anything")) {
missing.add(prefix);
}
}
assertThat(missing).as("受管面必须整份继承用户态名单,不许有漏项").isEmpty();
assertThat(ClientVersionGuardFilter.isClientFacing("/api/client/credentials")).isTrue();
// 反向:这三类必须不在名单里,否则被拒的老客户端拿不到升级信息(闸门把自己变成砖)
assertThat(ClientVersionGuardFilter.isClientFacing("/api/version/latest")).isFalse();
assertThat(ClientVersionGuardFilter.isClientFacing("/api/admin/users")).isFalse();
assertThat(ClientVersionGuardFilter.isClientFacing("/api/internal/user-proxy")).isFalse();
assertThat(ClientVersionGuardFilter.isClientFacing(null)).isFalse();
}
@Test
void versionParsingAndOrdering() {
assertThat(ClientVersionGuardFilter.parse("4.0.46")).containsExactly(4L, 0L, 46L);
assertThat(ClientVersionGuardFilter.parse(" 4.0.46 ")).containsExactly(4L, 0L, 46L);
assertThat(ClientVersionGuardFilter.parse("4.0")).containsExactly(4L, 0L);
assertThat(ClientVersionGuardFilter.parse("")).isNull();
assertThat(ClientVersionGuardFilter.parse(" ")).isNull();
assertThat(ClientVersionGuardFilter.parse("4..6")).isNull();
assertThat(ClientVersionGuardFilter.parse("4.x.6")).isNull();
assertThat(ClientVersionGuardFilter.parse("v4.0.6")).isNull();
assertThat(ClientVersionGuardFilter.parse("4.0.6-beta")).isNull();
assertThat(ClientVersionGuardFilter.compare(
ClientVersionGuardFilter.parse("4.0"), ClientVersionGuardFilter.parse("4.0.0"))).isZero();
assertThat(ClientVersionGuardFilter.compare(
ClientVersionGuardFilter.parse("4.0"), ClientVersionGuardFilter.parse("4.0.1"))).isNegative();
assertThat(ClientVersionGuardFilter.compare(
ClientVersionGuardFilter.parse("4.0.46.2"), ClientVersionGuardFilter.parse("4.0.46"))).isPositive();
assertThat(ClientVersionGuardFilter.compare(
ClientVersionGuardFilter.parse("10.0"), ClientVersionGuardFilter.parse("9.9.9"))).isPositive();
}
}
@@ -3,6 +3,7 @@ package com.nanri.aiimage.modules.productrisk.service;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.nanri.aiimage.modules.productrisk.model.dto.ProductRiskRowDto;
import com.nanri.aiimage.modules.productrisk.model.enums.ProductRiskCountryCode;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
@@ -25,6 +26,44 @@ class ProductRiskExcelAssemblyServiceTest {
private final ProductRiskExcelAssemblyService service = new ProductRiskExcelAssemblyService();
/**
* 复现生产那支永久卡住的作业(10-08 现网 job 21603 / task 30219 / user 983):
* 结果集一旦超过 SXSSF 的 200 行窗口,第 0 行就被 flush 出内存,
* 数据写完之后再 {@code sheet.getRow(0)} 拿到的是 <b>null</b>,
* {@code applyDetailHeaderStyle} 直接 NPE,被外层 {@code catch (Exception)} 吞成
* "generate product-risk excel failed: Cannot invoke Row.getCell(int) because headerRow is null",
* 于是重试 5 次全是同一个错、任务永远停在 RUNNING、结果文件永远出不来(同族还有 10-07 的 job 21549)。
*
* <p>断言打在两件事上:文件真的一次写成了(行数完整),而且表头样式仍然落在 6..8 列上——
* 前者挡住"改成不抛异常但把表头样式整段丢掉"那种假修。</p>
*/
@Test
void writesWholeWorkbookWhenRowsExceedTheSxssfFlushWindow() throws Exception {
Path xlsx = Files.createTempFile("product-risk-over-window-", ".xlsx");
try {
List<ProductRiskRowDto> rows = new java.util.ArrayList<>();
for (int i = 0; i < 260; i++) {
rows.add(row("B0WINDOW" + i, "处理完成", Boolean.FALSE));
}
service.writeWorkbook(
xlsx.toFile(), "店铺A",
Map.of(ProductRiskCountryCode.DE.getSheetName(), rows));
try (InputStream in = Files.newInputStream(xlsx);
Workbook workbook = new XSSFWorkbook(in)) {
Sheet sheet = workbook.getSheet(ProductRiskCountryCode.DE.getSheetName());
assertNotNull(sheet, "工作表没出来");
assertEquals(260, sheet.getLastRowNum(), "260 行数据 + 第 0 行表头,一行都不该少");
assertEquals(BorderStyle.THIN, sheet.getRow(0).getCell(7).getCellStyle().getBorderTop(),
"表头 6..8 列的细边框必须还在(修法只是把它挪到 flush 之前,不是删掉)");
assertEquals("原因", sheet.getRow(0).getCell(7).getStringCellValue());
}
} finally {
Files.deleteIfExists(xlsx);
}
}
@Test
void completionColumnUsesChineseValueAndCompletedStatusWinsOverFalseDone() throws Exception {
Path xlsx = Files.createTempFile("product-risk-result-", ".xlsx");