Compare commits
8 Commits
4a97725e2a
...
ccb30aa99e
| Author | SHA1 | Date | |
|---|---|---|---|
| ccb30aa99e | |||
| 5547237950 | |||
| 1743666334 | |||
| ba20f5ed42 | |||
| b94555f411 | |||
| 9c4905c94e | |||
| 052f2bd4a5 | |||
| 68ec48b573 |
@@ -68,10 +68,6 @@ export const OPERATION_GUIDES: Record<string, OperationGuideData> = {
|
||||
text: '店铺信息按分组管理。长商城名会自动缩略,悬停即可查看完整内容。',
|
||||
steps: ['选择分组', '维护店铺信息', '筛选核对结果'],
|
||||
},
|
||||
admin_brand_gating: {
|
||||
text: '维护不符合规则的品牌(品牌Gating/类目Gating)。添加后可用筛选快速回查;云端Gating库与前端排查软件同步同一份数据,排查软件命中后会自动在此入库。',
|
||||
steps: ['新增或批量导入', '筛选回查', '停用或删除'],
|
||||
},
|
||||
admin_shop_data_crawl_tasks: {
|
||||
text: '店铺数据任务按状态和时间筛选。批量操作前请核对已选任务。',
|
||||
steps: ['筛选任务', '检查状态', '执行批量操作'],
|
||||
@@ -93,6 +89,10 @@ export const OPERATION_GUIDES: Record<string, OperationGuideData> = {
|
||||
text: '上传新的教程压缩包后即刻生效:工具台首页「立即下载教程」以下载最新上传的包为准。确认旧包不再需要后再删除。',
|
||||
steps: ['上传教程压缩包', '到工具台核对下载', '清理历史包'],
|
||||
},
|
||||
admin_workbench_client_package: {
|
||||
text: '上传新的工作台客户端 ZIP 包后即刻生效:客户端从 /api/workbench-client/version/latest 自动检测版本并升级;服务端会复算 sha256 供客户端校验。确认旧包不再需要后再删除。',
|
||||
steps: ['填写版本号并上传 ZIP', '核对版本与 sha256', '清理历史包'],
|
||||
},
|
||||
digital_human_version: {
|
||||
text: '数字人版本需先上传草稿,再发布并标记最新版本。',
|
||||
steps: ['上传草稿', '确认更新日志', '发布或设为最新'],
|
||||
|
||||
@@ -1,759 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
/** 品牌Gating库(biz_brand_gating 并入管理后台)· 自绘列表页,布局沿用 DedupeRegistryPage 的
|
||||
* panel-box + 双行筛选 + 旧式表格 + OldPagination,另加统计卡与新增/批量导入弹窗。 */
|
||||
import { computed, onMounted, reactive, ref } from 'vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { formatDateTime } from '@/utils/datetime'
|
||||
import OldPagination from '@/components/OldPagination.vue'
|
||||
import LoadFailureBar from '@/components/LoadFailureBar.vue'
|
||||
import { showAdminFeedback } from '@/components/admin-feedback-ui'
|
||||
import { loadFailureMessage } from '@/components/load-failure-model'
|
||||
import { openAdminConfirm } from '@/components/admin-confirm'
|
||||
import {
|
||||
createGating,
|
||||
deleteGating,
|
||||
fetchGatingPage,
|
||||
fetchGatingStats,
|
||||
importGatingText,
|
||||
updateGatingStatus,
|
||||
} from './gating-api.ts'
|
||||
import {
|
||||
GATING_COUNTRIES,
|
||||
GATING_DEFAULT_PAGE_SIZE,
|
||||
GATING_PAGE_SIZES,
|
||||
GATING_SOURCES,
|
||||
GATING_TYPES,
|
||||
createGatingFilterState,
|
||||
gatingStatusLabel,
|
||||
toGatingListParams,
|
||||
type GatingFilterState,
|
||||
type GatingItem,
|
||||
type GatingStats,
|
||||
} from './gating-model.ts'
|
||||
import { gatingImportOutcomeText, parseGatingImportText } from './gating-import.ts'
|
||||
|
||||
const loading = ref(false)
|
||||
const loadFailure = ref('')
|
||||
const rows = ref<GatingItem[]>([])
|
||||
const total = ref(0)
|
||||
const page = ref(1)
|
||||
const pageSize = ref(GATING_DEFAULT_PAGE_SIZE)
|
||||
const filter = reactive(createGatingFilterState())
|
||||
|
||||
const stats = ref<GatingStats | null>(null)
|
||||
|
||||
const addVisible = ref(false)
|
||||
const addSaving = ref(false)
|
||||
const addForm = reactive({
|
||||
brand: '',
|
||||
asin: '',
|
||||
country: '全部',
|
||||
gatingType: '品牌gating',
|
||||
source: 'MANUAL',
|
||||
shopName: '',
|
||||
remark: '',
|
||||
})
|
||||
|
||||
const importVisible = ref(false)
|
||||
const importRunning = ref(false)
|
||||
const importText = ref('')
|
||||
/** 导入前行数预览:同一份解析规则桌面版/后端共用,前端只做提示,不做拦截。 */
|
||||
const importPreviewCount = computed(() => parseGatingImportText(importText.value).items.length)
|
||||
|
||||
const totalPages = computed(() => Math.max(1, Math.ceil(total.value / pageSize.value)))
|
||||
|
||||
async function loadStats(): Promise<void> {
|
||||
try {
|
||||
stats.value = await fetchGatingStats()
|
||||
} catch {
|
||||
// 统计卡失败不拦列表:留空展示 0,列表自己的失败条会说话。
|
||||
stats.value = null
|
||||
}
|
||||
}
|
||||
|
||||
async function load(): Promise<void> {
|
||||
loading.value = true
|
||||
loadFailure.value = ''
|
||||
try {
|
||||
const result = await fetchGatingPage(toGatingListParams(filter, page.value, pageSize.value))
|
||||
rows.value = result.rows
|
||||
total.value = result.total
|
||||
} catch (error) {
|
||||
loadFailure.value = loadFailureMessage(error, 'Gating列表加载失败')
|
||||
showAdminFeedback(loadFailure.value, 'error')
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function apply(): void {
|
||||
page.value = 1
|
||||
void load()
|
||||
}
|
||||
|
||||
function resetFilter(): void {
|
||||
Object.assign(filter, createGatingFilterState())
|
||||
apply()
|
||||
}
|
||||
|
||||
function changePage(next: number): void {
|
||||
if (next < 1 || next > totalPages.value) return
|
||||
page.value = next
|
||||
void load()
|
||||
}
|
||||
|
||||
function changeSize(size: number): void {
|
||||
pageSize.value = size
|
||||
page.value = 1
|
||||
void load()
|
||||
}
|
||||
|
||||
function openAdd(): void {
|
||||
addForm.brand = ''
|
||||
addForm.asin = ''
|
||||
addForm.country = '全部'
|
||||
addForm.gatingType = '品牌gating'
|
||||
addForm.source = 'MANUAL'
|
||||
addForm.shopName = ''
|
||||
addForm.remark = ''
|
||||
addVisible.value = true
|
||||
}
|
||||
|
||||
async function submitAdd(): Promise<void> {
|
||||
const brand = addForm.brand.trim()
|
||||
if (!brand) {
|
||||
ElMessage.warning('请填写品牌')
|
||||
return
|
||||
}
|
||||
addSaving.value = true
|
||||
try {
|
||||
await createGating({
|
||||
brand,
|
||||
asin: addForm.asin.trim(),
|
||||
country: addForm.country,
|
||||
gatingType: addForm.gatingType,
|
||||
source: addForm.source,
|
||||
shopName: addForm.shopName.trim(),
|
||||
remark: addForm.remark.trim(),
|
||||
})
|
||||
addVisible.value = false
|
||||
ElMessage.success('新增成功')
|
||||
await Promise.all([load(), loadStats()])
|
||||
} catch (error) {
|
||||
showAdminFeedback(loadFailureMessage(error, '新增失败'), 'error')
|
||||
} finally {
|
||||
addSaving.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function openImport(): void {
|
||||
importText.value = ''
|
||||
importVisible.value = true
|
||||
}
|
||||
|
||||
async function submitImport(): Promise<void> {
|
||||
const text = importText.value.trim()
|
||||
if (!text) {
|
||||
ElMessage.warning('请粘贴批量数据')
|
||||
return
|
||||
}
|
||||
importRunning.value = true
|
||||
try {
|
||||
const result = await importGatingText(text)
|
||||
importVisible.value = false
|
||||
ElMessage.success(gatingImportOutcomeText(result.added, result.skipped))
|
||||
await Promise.all([load(), loadStats()])
|
||||
} catch (error) {
|
||||
showAdminFeedback(loadFailureMessage(error, '导入失败'), 'error')
|
||||
} finally {
|
||||
importRunning.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/** 启用/停用切换:停用需二次确认(解除后排查不再拦截),恢复直接执行。 */
|
||||
async function toggleStatus(row: GatingItem): Promise<void> {
|
||||
const next: 0 | 1 = row.status === 1 ? 0 : 1
|
||||
if (next === 0) {
|
||||
const confirmed = await openAdminConfirm({ message: `确认停用品牌「${row.brand}」?停用后排查自动跳过该品牌,不再拦截`, danger: true })
|
||||
if (!confirmed) return
|
||||
}
|
||||
try {
|
||||
await updateGatingStatus(row.id, next)
|
||||
ElMessage.success(next === 1 ? '已恢复生效' : '已停用,排查不再拦截')
|
||||
await Promise.all([load(), loadStats()])
|
||||
} catch (error) {
|
||||
showAdminFeedback(loadFailureMessage(error, '状态更新失败'), 'error')
|
||||
}
|
||||
}
|
||||
|
||||
async function removeRow(row: GatingItem): Promise<void> {
|
||||
const confirmed = await openAdminConfirm({ message: `确认删除 ID=${row.id} 的Gating记录(品牌:${row.brand})?`, danger: true })
|
||||
if (!confirmed) return
|
||||
try {
|
||||
await deleteGating(row.id)
|
||||
ElMessage.success('已删除')
|
||||
await Promise.all([load(), loadStats()])
|
||||
} catch (error) {
|
||||
showAdminFeedback(loadFailureMessage(error, '删除失败'), 'error')
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
void load()
|
||||
void loadStats()
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="gating-view">
|
||||
<section class="panel-box">
|
||||
<div class="gating-panel-head">
|
||||
<h3>品牌Gating库</h3>
|
||||
<div class="gating-head-actions">
|
||||
<button class="btn" type="button" @click="openAdd">新增</button>
|
||||
<button class="btn" type="button" @click="openImport">批量导入</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="gating-cards">
|
||||
<div class="stat-card">
|
||||
<div class="stat-n">{{ stats?.total ?? 0 }}</div>
|
||||
<div class="stat-t">Gating总记录</div>
|
||||
</div>
|
||||
<div class="stat-card stat-active">
|
||||
<div class="stat-n">{{ stats?.active ?? 0 }}</div>
|
||||
<div class="stat-t">生效中</div>
|
||||
</div>
|
||||
<div class="stat-card stat-disabled">
|
||||
<div class="stat-n">{{ stats?.disabled ?? 0 }}</div>
|
||||
<div class="stat-t">停用</div>
|
||||
</div>
|
||||
<div class="stat-card stat-brands">
|
||||
<div class="stat-n">{{ stats?.brands ?? 0 }}</div>
|
||||
<div class="stat-t">去重品牌数</div>
|
||||
</div>
|
||||
<div v-for="group in [
|
||||
{ title: '按Gating类型', data: stats?.byType ?? [] },
|
||||
{ title: '按国家', data: stats?.byCountry ?? [] },
|
||||
{ title: '按来源', data: stats?.bySource ?? [] },
|
||||
]" :key="group.title" class="stat-group">
|
||||
<div class="stat-group-title">{{ group.title }}</div>
|
||||
<div class="stat-group-body">
|
||||
<span v-for="entry in group.data" :key="entry.name" class="stat-chip">
|
||||
{{ entry.name }} <b>{{ entry.count }}</b>
|
||||
</span>
|
||||
<span v-if="!group.data.length" class="stat-chip stat-chip-empty">暂无</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="gating-filter-row">
|
||||
<div class="form-group">
|
||||
<label>关键词</label>
|
||||
<input v-model="filter.keyword" type="text" placeholder="品牌 / ASIN / 备注" @keyup.enter="apply" />
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>国家</label>
|
||||
<select v-model="filter.country">
|
||||
<option value="">全部国家</option>
|
||||
<option v-for="country in GATING_COUNTRIES" :key="country" :value="country">{{ country }}</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>Gating类型</label>
|
||||
<select v-model="filter.gatingType">
|
||||
<option value="">全部类型</option>
|
||||
<option v-for="gatingType in GATING_TYPES" :key="gatingType" :value="gatingType">{{ gatingType }}</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>状态</label>
|
||||
<select v-model="filter.status">
|
||||
<option value="">全部状态</option>
|
||||
<option value="1">生效</option>
|
||||
<option value="0">停用</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>来源</label>
|
||||
<select v-model="filter.source">
|
||||
<option value="">全部来源</option>
|
||||
<option v-for="source in GATING_SOURCES" :key="source" :value="source">{{ source }}</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="gating-filter-actions">
|
||||
<button class="btn" type="button" @click="apply">查询</button>
|
||||
<button class="btn btn-secondary" type="button" @click="resetFilter">重置</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<LoadFailureBar v-if="loadFailure" :message="loadFailure" @retry="load" />
|
||||
<div class="table-scroll gating-table-scroll">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th style="width: 60px">ID</th>
|
||||
<th>品牌</th>
|
||||
<th>ASIN</th>
|
||||
<th>国家</th>
|
||||
<th>Gating类型</th>
|
||||
<th style="width: 70px">状态</th>
|
||||
<th style="width: 80px">来源</th>
|
||||
<th>店铺</th>
|
||||
<th>备注</th>
|
||||
<th style="width: 150px">创建时间</th>
|
||||
<th style="width: 150px">更新时间</th>
|
||||
<th style="width: 150px">停用时间</th>
|
||||
<th style="width: 140px">操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<template v-if="rows.length">
|
||||
<tr v-for="row in rows" :key="row.id">
|
||||
<td>{{ row.id }}</td>
|
||||
<td class="brand-cell">{{ row.brand }}</td>
|
||||
<td class="mono-cell">{{ row.asin || '-' }}</td>
|
||||
<td>{{ row.country }}</td>
|
||||
<td><span class="type-tag">{{ row.gatingType }}</span></td>
|
||||
<td>
|
||||
<span class="status-tag" :class="row.status === 1 ? 'status-on' : 'status-off'">
|
||||
{{ gatingStatusLabel(row.status) }}
|
||||
</span>
|
||||
</td>
|
||||
<td>{{ row.source === 'AUTO' ? '自动同步' : '手动' }}</td>
|
||||
<td>{{ row.shopName || '-' }}</td>
|
||||
<td :title="row.remark">{{ row.remark || '-' }}</td>
|
||||
<td class="time-cell">{{ formatDateTime(row.createdAt) }}</td>
|
||||
<td class="time-cell">{{ formatDateTime(row.updatedAt) }}</td>
|
||||
<td class="time-cell">{{ formatDateTime(row.disabledAt) }}</td>
|
||||
<td class="ops-cell">
|
||||
<button class="btn btn-sm" type="button" @click="toggleStatus(row)">
|
||||
{{ row.status === 1 ? '停用' : '恢复' }}
|
||||
</button>
|
||||
<button class="btn btn-sm btn-danger" type="button" @click="removeRow(row)">删除</button>
|
||||
</td>
|
||||
</tr>
|
||||
</template>
|
||||
<tr v-else-if="loading">
|
||||
<td colspan="13" class="empty-tip">加载中...</td>
|
||||
</tr>
|
||||
<tr v-else>
|
||||
<td colspan="13" class="empty-tip">暂无Gating记录</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<OldPagination
|
||||
:total="total"
|
||||
:page="page"
|
||||
:page-size="pageSize"
|
||||
:sizes="[10, 20, 50]"
|
||||
@change="changePage"
|
||||
@size-change="changeSize"
|
||||
/>
|
||||
</section>
|
||||
|
||||
<div v-if="addVisible" class="modal-mask" @click.self="addVisible = false">
|
||||
<div class="modal">
|
||||
<h3>新增Gating品牌</h3>
|
||||
<div class="form-group">
|
||||
<label>品牌(必填)</label>
|
||||
<input v-model="addForm.brand" type="text" placeholder="请输入品牌" @keyup.enter="submitAdd" />
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>国家</label>
|
||||
<select v-model="addForm.country">
|
||||
<option v-for="country in GATING_COUNTRIES" :key="country" :value="country">{{ country }}</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>Gating类型</label>
|
||||
<select v-model="addForm.gatingType">
|
||||
<option v-for="gatingType in GATING_TYPES" :key="gatingType" :value="gatingType">{{ gatingType }}</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>来源</label>
|
||||
<select v-model="addForm.source">
|
||||
<option v-for="source in GATING_SOURCES" :key="source" :value="source">{{ source }}</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>ASIN(可选)</label>
|
||||
<input v-model="addForm.asin" type="text" placeholder="请输入 ASIN" />
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>店铺(可选)</label>
|
||||
<input v-model="addForm.shopName" type="text" placeholder="请输入店铺名" />
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>备注(可选)</label>
|
||||
<input v-model="addForm.remark" type="text" placeholder="请输入备注" />
|
||||
</div>
|
||||
<div class="modal-actions">
|
||||
<button class="btn" type="button" :disabled="addSaving" @click="submitAdd">保存</button>
|
||||
<button class="btn btn-secondary" type="button" :disabled="addSaving" @click="addVisible = false">取消</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="importVisible" class="modal-mask" @click.self="importVisible = false">
|
||||
<div class="modal">
|
||||
<h3>批量导入</h3>
|
||||
<div class="form-group">
|
||||
<label>每行一条:品牌[,国家[,类型[,ASIN[,备注]]]],支持逗号/分号/Tab 分隔;# 开头为注释行</label>
|
||||
<textarea
|
||||
v-model="importText"
|
||||
class="import-textarea"
|
||||
rows="10"
|
||||
placeholder="示例:
|
||||
tory burch,英国,品牌gating
|
||||
jellycat,全部,品牌gating
|
||||
crocs,德国,类目gating"
|
||||
></textarea>
|
||||
</div>
|
||||
<div class="import-preview">将导入 {{ importPreviewCount }} 行(空行与注释行自动跳过)</div>
|
||||
<div class="modal-actions">
|
||||
<button class="btn" type="button" :disabled="importRunning" @click="submitImport">导入</button>
|
||||
<button class="btn btn-secondary" type="button" :disabled="importRunning" @click="importVisible = false">取消</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
/* 布局与配色沿用去重总数据页(panel-box 蓝白末层样式)。 */
|
||||
.gating-view {
|
||||
font-family: inherit;
|
||||
color: var(--c-text, #24384d);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 18px;
|
||||
}
|
||||
.panel-box {
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
padding: 20px 22px 24px;
|
||||
border: 1px solid #d8e3ee;
|
||||
border-radius: 14px;
|
||||
background: linear-gradient(145deg, #ffffff, #f9fbfd);
|
||||
box-shadow: 0 1px 2px rgba(39, 67, 94, 0.04), 0 14px 30px -24px rgba(39, 67, 94, 0.28);
|
||||
}
|
||||
h3 {
|
||||
margin: 0 0 16px;
|
||||
font-size: 15px;
|
||||
font-weight: 650;
|
||||
color: #24384d;
|
||||
letter-spacing: 0.2px;
|
||||
}
|
||||
.gating-panel-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
.gating-panel-head h3 {
|
||||
margin: 0;
|
||||
}
|
||||
.gating-head-actions {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
}
|
||||
.gating-cards {
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
flex-wrap: wrap;
|
||||
align-items: stretch;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
.stat-card {
|
||||
flex: 0 0 132px;
|
||||
padding: 12px 14px;
|
||||
border: 1px solid #d8e3ee;
|
||||
border-top: 3px solid #2dd4bf;
|
||||
border-radius: 10px;
|
||||
background: #ffffff;
|
||||
}
|
||||
.stat-card.stat-active { border-top-color: #34d399; }
|
||||
.stat-card.stat-disabled { border-top-color: #9ca3af; }
|
||||
.stat-card.stat-brands { border-top-color: #a78bfa; }
|
||||
.stat-n {
|
||||
font-size: 24px;
|
||||
font-weight: 700;
|
||||
color: #24384d;
|
||||
}
|
||||
.stat-t {
|
||||
margin-top: 2px;
|
||||
font-size: 12px;
|
||||
color: #7a8194;
|
||||
}
|
||||
.stat-group {
|
||||
flex: 1 1 200px;
|
||||
min-width: 0;
|
||||
padding: 10px 14px;
|
||||
border: 1px solid #d8e3ee;
|
||||
border-radius: 10px;
|
||||
background: #ffffff;
|
||||
}
|
||||
.stat-group-title {
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
color: #5b6f83;
|
||||
margin-bottom: 6px;
|
||||
}
|
||||
.stat-group-body {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 6px;
|
||||
}
|
||||
.stat-chip {
|
||||
padding: 2px 8px;
|
||||
border-radius: 6px;
|
||||
background: #edf4fa;
|
||||
color: #4e6479;
|
||||
font-size: 12px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.stat-chip b {
|
||||
color: #2f5d8b;
|
||||
}
|
||||
.stat-chip-empty {
|
||||
color: #9baaba;
|
||||
}
|
||||
.gating-filter-row {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(5, minmax(140px, 1fr)) auto;
|
||||
gap: 12px;
|
||||
align-items: end;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
.gating-filter-row .form-group {
|
||||
min-width: 0;
|
||||
}
|
||||
.gating-filter-actions {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
align-items: center;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.form-group {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 7px;
|
||||
margin-bottom: 0;
|
||||
}
|
||||
.form-group label {
|
||||
color: #5b6f83;
|
||||
font-size: 12.5px;
|
||||
font-weight: 600;
|
||||
}
|
||||
.form-group input,
|
||||
.form-group select,
|
||||
.form-group textarea {
|
||||
min-width: 0;
|
||||
min-height: 42px;
|
||||
padding: 8px 12px;
|
||||
border: 1px solid #cbd9e6;
|
||||
border-radius: 9px;
|
||||
background: #f8fbfd;
|
||||
color: #24384d;
|
||||
font-size: 13.5px;
|
||||
font-family: inherit;
|
||||
color-scheme: light;
|
||||
outline: none;
|
||||
transition: border-color 160ms ease, box-shadow 160ms ease, background 160ms ease;
|
||||
}
|
||||
.form-group textarea {
|
||||
min-height: 0;
|
||||
resize: vertical;
|
||||
line-height: 1.6;
|
||||
}
|
||||
.form-group input:hover,
|
||||
.form-group select:hover,
|
||||
.form-group textarea:hover {
|
||||
border-color: #9fb7cd;
|
||||
}
|
||||
.form-group input:focus,
|
||||
.form-group select:focus,
|
||||
.form-group textarea:focus {
|
||||
background: #ffffff;
|
||||
border-color: #5f85ad;
|
||||
box-shadow: 0 0 0 3px rgba(95, 133, 173, 0.16);
|
||||
}
|
||||
.btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 8px;
|
||||
min-height: 42px;
|
||||
padding: 9px 18px;
|
||||
border: 1px solid #4f78a5;
|
||||
border-radius: 9px;
|
||||
background: linear-gradient(135deg, #5f85ad, #4f78a5);
|
||||
color: #ffffff;
|
||||
font-family: inherit;
|
||||
font-size: 13.5px;
|
||||
cursor: pointer;
|
||||
box-shadow: 0 8px 18px -14px rgba(79, 120, 165, 0.72);
|
||||
transition: background 160ms ease, box-shadow 160ms ease, transform 120ms ease;
|
||||
}
|
||||
.btn:hover:not(:disabled) {
|
||||
background: linear-gradient(135deg, #7094ba, #5d83ac);
|
||||
box-shadow: 0 11px 22px -14px rgba(79, 120, 165, 0.8);
|
||||
}
|
||||
.btn:disabled {
|
||||
cursor: not-allowed;
|
||||
opacity: 0.6;
|
||||
}
|
||||
.btn-secondary {
|
||||
background: #ffffff;
|
||||
color: #5b6f83;
|
||||
border-color: #c7d7e5;
|
||||
}
|
||||
.btn-secondary:hover:not(:disabled) {
|
||||
color: #2f5d8b;
|
||||
border-color: #95b1cb;
|
||||
background: #edf5fb;
|
||||
}
|
||||
.btn-danger {
|
||||
background: linear-gradient(135deg, #c06d77, #b35f6a);
|
||||
border-color: #b35f6a;
|
||||
}
|
||||
.btn-danger:hover:not(:disabled) {
|
||||
background: linear-gradient(135deg, #cb7c84, #b96570);
|
||||
}
|
||||
.btn-sm {
|
||||
min-height: 36px;
|
||||
padding: 7px 12px;
|
||||
}
|
||||
.table-scroll {
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
overflow-x: auto;
|
||||
border: 1px solid #dbe5ee;
|
||||
border-radius: 10px;
|
||||
background: #ffffff;
|
||||
}
|
||||
.table-scroll table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
table-layout: fixed;
|
||||
}
|
||||
.gating-table-scroll > table {
|
||||
min-width: 1360px;
|
||||
}
|
||||
.table-scroll th,
|
||||
.table-scroll td {
|
||||
padding: 10px 12px;
|
||||
text-align: left;
|
||||
font-size: 13.5px;
|
||||
line-height: 1.5;
|
||||
border-bottom: 1px solid #e0e8ef;
|
||||
vertical-align: middle;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.table-scroll th {
|
||||
background: #edf4fa;
|
||||
color: #4e6479;
|
||||
border-bottom-color: #d5e1eb;
|
||||
font-size: 12.5px;
|
||||
font-weight: 600;
|
||||
letter-spacing: 0.4px;
|
||||
}
|
||||
.table-scroll tbody tr:hover td {
|
||||
background: #f1f7fb;
|
||||
}
|
||||
.table-scroll tbody tr:last-child td {
|
||||
border-bottom: 0;
|
||||
}
|
||||
.brand-cell {
|
||||
font-weight: 650;
|
||||
}
|
||||
.mono-cell {
|
||||
font-family: "Cascadia Mono", "SF Mono", Consolas, "Courier New", monospace;
|
||||
font-size: 12.5px;
|
||||
}
|
||||
.time-cell {
|
||||
color: #6b7280;
|
||||
font-size: 12.5px;
|
||||
}
|
||||
.type-tag {
|
||||
display: inline-block;
|
||||
padding: 2px 8px;
|
||||
border-radius: 6px;
|
||||
background: #fef3c7;
|
||||
color: #b45309;
|
||||
font-size: 12px;
|
||||
}
|
||||
.status-tag {
|
||||
display: inline-block;
|
||||
padding: 2px 8px;
|
||||
border-radius: 6px;
|
||||
font-size: 12px;
|
||||
}
|
||||
.status-on {
|
||||
background: #d1fae5;
|
||||
color: #10b981;
|
||||
}
|
||||
.status-off {
|
||||
background: #e5e7eb;
|
||||
color: #9ca3af;
|
||||
}
|
||||
.ops-cell {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
white-space: nowrap;
|
||||
text-align: right;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.empty-tip {
|
||||
padding: 44px 24px;
|
||||
text-align: center;
|
||||
color: #8293a5;
|
||||
font-size: 13.5px;
|
||||
}
|
||||
.modal-mask {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 3000;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 40px 20px;
|
||||
background: rgba(45, 66, 86, 0.36);
|
||||
backdrop-filter: blur(6px);
|
||||
}
|
||||
.modal {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
width: min(560px, 100%);
|
||||
max-height: 84vh;
|
||||
padding: 22px 24px;
|
||||
border: 1px solid #c7d7e5;
|
||||
border-radius: 14px;
|
||||
background: #ffffff;
|
||||
box-shadow: 0 22px 60px rgba(39, 67, 94, 0.2);
|
||||
overflow-y: auto;
|
||||
}
|
||||
.modal .form-group {
|
||||
margin-bottom: 14px;
|
||||
}
|
||||
.modal-actions {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
margin-top: 16px;
|
||||
}
|
||||
.import-textarea {
|
||||
height: 180px;
|
||||
}
|
||||
.import-preview {
|
||||
font-size: 12.5px;
|
||||
color: #5b6f83;
|
||||
}
|
||||
</style>
|
||||
@@ -1,75 +0,0 @@
|
||||
/** 品牌Gating库 API 适配:GET/POST/DELETE /api/admin/brand-gating(契约路径与字段不得擅改)。 */
|
||||
import { http } from '@/api/http'
|
||||
import { unwrap } from '@/api/envelope'
|
||||
import {
|
||||
parseGatingPage,
|
||||
parseGatingStats,
|
||||
toGatingItem,
|
||||
type GatingItem,
|
||||
type GatingPageResult,
|
||||
type GatingStats,
|
||||
} from './gating-model.ts'
|
||||
|
||||
export const GATING_ENDPOINT = '/api/admin/brand-gating'
|
||||
|
||||
/** 列表:GET /api/admin/brand-gating?page&size&keyword&country&gatingType&status&source → { total, rows }。 */
|
||||
export async function fetchGatingPage(params: Record<string, string | number>): Promise<GatingPageResult> {
|
||||
const { data } = await http.get<unknown>(GATING_ENDPOINT, { params })
|
||||
return parseGatingPage(data)
|
||||
}
|
||||
|
||||
/** 统计:GET /api/admin/brand-gating/stats → { total, active, disabled, brands, byType, byCountry, bySource }。 */
|
||||
export async function fetchGatingStats(): Promise<GatingStats> {
|
||||
const { data } = await http.get<unknown>(`${GATING_ENDPOINT}/stats`)
|
||||
return parseGatingStats(data)
|
||||
}
|
||||
|
||||
/** 单条新增字段(驼峰);source/shopName 可缺省由后端落默认。 */
|
||||
export interface GatingCreatePayload {
|
||||
brand: string
|
||||
asin: string
|
||||
country: string
|
||||
gatingType: string
|
||||
source: string
|
||||
shopName: string
|
||||
remark: string
|
||||
}
|
||||
|
||||
/** 新增:POST /api/admin/brand-gating → { added }。 */
|
||||
export async function createGating(payload: GatingCreatePayload): Promise<number> {
|
||||
const { data } = await http.post<unknown>(GATING_ENDPOINT, payload)
|
||||
const core = unwrap<Record<string, unknown>>(data)
|
||||
const added = core && typeof core === 'object' ? Number((core as Record<string, unknown>).added) : NaN
|
||||
return Number.isFinite(added) ? added : 0
|
||||
}
|
||||
|
||||
/** 删除:DELETE /api/admin/brand-gating/{id} → { deleted }。 */
|
||||
export async function deleteGating(id: number): Promise<void> {
|
||||
const { data } = await http.delete<unknown>(`${GATING_ENDPOINT}/${id}`)
|
||||
unwrap<unknown>(data)
|
||||
}
|
||||
|
||||
/**
|
||||
* 启用/停用:POST /api/admin/brand-gating/{id}/status body { status } → { updated }。
|
||||
* 停用(status=0)由后端记 disabled_at=NOW(),恢复(status=1)清空 disabled_at。
|
||||
*/
|
||||
export async function updateGatingStatus(id: number, status: 0 | 1): Promise<void> {
|
||||
const { data } = await http.post<unknown>(`${GATING_ENDPOINT}/${id}/status`, { status })
|
||||
unwrap<unknown>(data)
|
||||
}
|
||||
|
||||
/** 批量导入:POST /api/admin/brand-gating/import body { text } → { added, skipped }。原始文本整段交后端解析。 */
|
||||
export async function importGatingText(text: string): Promise<{ added: number; skipped: number }> {
|
||||
const { data } = await http.post<unknown>(`${GATING_ENDPOINT}/import`, { text })
|
||||
const core = unwrap<Record<string, unknown>>(data)
|
||||
const record = (core && typeof core === 'object' ? core : {}) as Record<string, unknown>
|
||||
const added = Number(record.added)
|
||||
const skipped = Number(record.skipped)
|
||||
return {
|
||||
added: Number.isFinite(added) ? added : 0,
|
||||
skipped: Number.isFinite(skipped) ? skipped : 0,
|
||||
}
|
||||
}
|
||||
|
||||
/** 单条解析出口(供需要单取的场景复用,例如挂载测试构造数据)。 */
|
||||
export { toGatingItem, type GatingItem }
|
||||
@@ -1,66 +0,0 @@
|
||||
/** 批量导入文本解析(照抄桌面版 gating_web_admin.py parse_batch 的行格式与跳过规则)。
|
||||
* 纯逻辑、零依赖(tests/gating-import.test.ts 用 node --test 直连本文件)。
|
||||
*
|
||||
* 口径(与桌面版 L208-223 逐条对齐):
|
||||
* - 按行拆分;每行去首尾空白与 BOM(\uFEFF);
|
||||
* - 空行与以 # 开头的注释行跳过;
|
||||
* - 行内按中英文逗号/分号/制表符([,\t;,;])切分,各段去空白后丢掉空段;
|
||||
* - 字段序:品牌(必留)、国家(缺省「全部」)、Gating类型(缺省「品牌gating」)、ASIN(缺省空)、备注(缺省空);
|
||||
* 第 5 列之后的段照桌面版丢弃。
|
||||
*
|
||||
* 前端只用它做导入前的行数预览;真正提交仍把原始文本整段交给后端
|
||||
* (POST /api/admin/brand-gating/import { text },去重与入库由后端按同一份规则解析)。 */
|
||||
|
||||
export interface GatingImportItem {
|
||||
brand: string
|
||||
country: string
|
||||
gatingType: string
|
||||
asin: string
|
||||
remark: string
|
||||
}
|
||||
|
||||
export interface GatingImportParseResult {
|
||||
items: GatingImportItem[]
|
||||
/** 因空行/注释行/纯分隔符行被跳过的行数。 */
|
||||
skippedLines: number
|
||||
}
|
||||
|
||||
export const GATING_IMPORT_DEFAULT_COUNTRY = '全部'
|
||||
export const GATING_IMPORT_DEFAULT_TYPE = '品牌gating'
|
||||
/** 与桌面版一致的列分隔符:中英文逗号、中英文分号、制表符。 */
|
||||
const FIELD_SPLIT_RE = /[,\t;,;]/
|
||||
|
||||
/** 解析批量导入文本;永不抛错(坏行计入 skippedLines)。 */
|
||||
export function parseGatingImportText(text: string): GatingImportParseResult {
|
||||
const items: GatingImportItem[] = []
|
||||
let skippedLines = 0
|
||||
const lines = String(text ?? '').split(/\r?\n/)
|
||||
for (const rawLine of lines) {
|
||||
const line = rawLine.trim().replace(/^\uFEFF/, '').trim()
|
||||
if (!line || line.startsWith('#')) {
|
||||
if (rawLine.trim()) skippedLines += 1
|
||||
continue
|
||||
}
|
||||
const parts = line
|
||||
.split(FIELD_SPLIT_RE)
|
||||
.map((part) => part.trim())
|
||||
.filter((part) => part.length > 0)
|
||||
if (!parts.length) {
|
||||
skippedLines += 1
|
||||
continue
|
||||
}
|
||||
items.push({
|
||||
brand: parts[0],
|
||||
country: parts[1] ?? GATING_IMPORT_DEFAULT_COUNTRY,
|
||||
gatingType: parts[2] ?? GATING_IMPORT_DEFAULT_TYPE,
|
||||
asin: parts[3] ?? '',
|
||||
remark: parts[4] ?? '',
|
||||
})
|
||||
}
|
||||
return { items, skippedLines }
|
||||
}
|
||||
|
||||
/** 导入完成反馈文案:新增 X 条,跳过重复 Y 条。 */
|
||||
export function gatingImportOutcomeText(added: number, skipped: number): string {
|
||||
return `批量导入完成:新增 ${added} 条,跳过重复 ${skipped} 条`
|
||||
}
|
||||
@@ -1,183 +0,0 @@
|
||||
/** 品牌Gating库页面模型(biz_brand_gating 并入管理后台):类型、字典、筛选态与响应解析。
|
||||
* 纯逻辑、零依赖(tests/gating-model.test.ts 用 node --test 直连本文件,别 import 带 @ 别名/axios 的模块)。 */
|
||||
|
||||
export interface GatingItem {
|
||||
id: number
|
||||
brand: string
|
||||
asin: string
|
||||
country: string
|
||||
gatingType: string
|
||||
/** 1=生效 0=停用。 */
|
||||
status: number
|
||||
source: string
|
||||
shopName: string
|
||||
remark: string
|
||||
createdAt?: string
|
||||
updatedAt?: string
|
||||
disabledAt?: string
|
||||
}
|
||||
|
||||
export interface GatingPageResult {
|
||||
rows: GatingItem[]
|
||||
total: number
|
||||
}
|
||||
|
||||
/** 分组统计单行(GET stats 的 byType/byCountry/bySource)。 */
|
||||
export interface GatingNameCount {
|
||||
name: string
|
||||
count: number
|
||||
}
|
||||
|
||||
export interface GatingStats {
|
||||
total: number
|
||||
active: number
|
||||
disabled: number
|
||||
brands: number
|
||||
byType: GatingNameCount[]
|
||||
byCountry: GatingNameCount[]
|
||||
bySource: GatingNameCount[]
|
||||
}
|
||||
|
||||
export interface GatingFilterState {
|
||||
/** 品牌/ASIN/备注 LIKE 关键词。 */
|
||||
keyword: string
|
||||
country: string
|
||||
gatingType: string
|
||||
/** '' = 全部;'1' 生效;'0' 停用。 */
|
||||
status: string
|
||||
source: string
|
||||
}
|
||||
|
||||
/** 国家字典:与桌面版 gating_web_admin 下拉一致;'全部' 是表内真实取值(不限国家时用空串)。 */
|
||||
export const GATING_COUNTRIES = ['全部', '英国', '德国', '法国', '西班牙', '意大利'] as const
|
||||
export const GATING_TYPES = ['品牌gating', '类目gating', '账户不符合'] as const
|
||||
export const GATING_SOURCES = ['AUTO', 'MANUAL'] as const
|
||||
/** 每页条数档位(默认 10,可选 20/50)。 */
|
||||
export const GATING_PAGE_SIZES = [10, 20, 50] as const
|
||||
export const GATING_DEFAULT_PAGE_SIZE = 10
|
||||
|
||||
export function createGatingFilterState(): GatingFilterState {
|
||||
return { keyword: '', country: '', gatingType: '', status: '', source: '' }
|
||||
}
|
||||
|
||||
function text(value: unknown): string {
|
||||
return typeof value === 'string' ? value.trim() : ''
|
||||
}
|
||||
|
||||
function intOr(value: unknown, fallback: number): number {
|
||||
return typeof value === 'number' && Number.isFinite(value) ? Math.floor(value) : fallback
|
||||
}
|
||||
|
||||
/** 解析单条记录;缺 id 视为无效。兼容 camel 与 snake 字段名。 */
|
||||
export function toGatingItem(raw: unknown): GatingItem | null {
|
||||
if (!raw || typeof raw !== 'object') return null
|
||||
const record = raw as Record<string, unknown>
|
||||
const id = intOr(record.id, 0)
|
||||
if (id <= 0) return null
|
||||
const item: GatingItem = {
|
||||
id,
|
||||
brand: text(record.brand),
|
||||
asin: text(record.asin),
|
||||
country: text(record.country),
|
||||
gatingType: text(record.gatingType ?? record.gating_type),
|
||||
status: intOr(record.status, 0),
|
||||
source: text(record.source),
|
||||
shopName: text(record.shopName ?? record.shop_name),
|
||||
remark: text(record.remark),
|
||||
}
|
||||
const createdAt = text(record.createdAt ?? record.created_at)
|
||||
const updatedAt = text(record.updatedAt ?? record.updated_at)
|
||||
const disabledAt = text(record.disabledAt ?? record.disabled_at)
|
||||
if (createdAt) item.createdAt = createdAt
|
||||
if (updatedAt) item.updatedAt = updatedAt
|
||||
if (disabledAt) item.disabledAt = disabledAt
|
||||
return item
|
||||
}
|
||||
|
||||
/** 解析列表负载({ total, rows };rows 兼容 items 别名),空负载回空页。 */
|
||||
export function parseGatingPage(payload: unknown): GatingPageResult {
|
||||
const out: GatingPageResult = { rows: [], total: 0 }
|
||||
if (!payload || typeof payload !== 'object') return out
|
||||
const record = payload as Record<string, unknown>
|
||||
const rawRows = Array.isArray(record.rows) ? record.rows : Array.isArray(record.items) ? record.items : []
|
||||
out.rows = rawRows
|
||||
.map((raw) => toGatingItem(raw))
|
||||
.filter((item): item is GatingItem => item !== null)
|
||||
out.total = intOr(record.total, out.rows.length)
|
||||
return out
|
||||
}
|
||||
|
||||
/** 分组统计单组:数组 [{name,count}] 或桌面版遗留 dict({品牌gating: 3})都收。 */
|
||||
export function parseGatingNameCountList(raw: unknown): GatingNameCount[] {
|
||||
if (Array.isArray(raw)) {
|
||||
const out: GatingNameCount[] = []
|
||||
for (const item of raw) {
|
||||
if (!item || typeof item !== 'object') continue
|
||||
const record = item as Record<string, unknown>
|
||||
const name = text(record.name)
|
||||
if (!name) continue
|
||||
out.push({ name, count: intOr(record.count, 0) })
|
||||
}
|
||||
return out
|
||||
}
|
||||
if (raw && typeof raw === 'object') {
|
||||
const out: GatingNameCount[] = []
|
||||
for (const [name, count] of Object.entries(raw as Record<string, unknown>)) {
|
||||
if (!name) continue
|
||||
out.push({ name, count: intOr(count, 0) })
|
||||
}
|
||||
return out
|
||||
}
|
||||
return []
|
||||
}
|
||||
|
||||
/** 解析统计负载;缺省字段回 0/空数组。 */
|
||||
export function parseGatingStats(payload: unknown): GatingStats {
|
||||
const out: GatingStats = {
|
||||
total: 0,
|
||||
active: 0,
|
||||
disabled: 0,
|
||||
brands: 0,
|
||||
byType: [],
|
||||
byCountry: [],
|
||||
bySource: [],
|
||||
}
|
||||
if (!payload || typeof payload !== 'object') return out
|
||||
const record = payload as Record<string, unknown>
|
||||
out.total = intOr(record.total, 0)
|
||||
out.active = intOr(record.active, 0)
|
||||
out.disabled = intOr(record.disabled, 0)
|
||||
out.brands = intOr(record.brands, 0)
|
||||
out.byType = parseGatingNameCountList(record.byType ?? record.by_type)
|
||||
out.byCountry = parseGatingNameCountList(record.byCountry ?? record.by_country)
|
||||
out.bySource = parseGatingNameCountList(record.bySource ?? record.by_source)
|
||||
return out
|
||||
}
|
||||
|
||||
/** 筛选态 + 分页 → 列表查询参数(page/size/keyword/country/gatingType/status/source);空白值不下发。 */
|
||||
export function toGatingListParams(
|
||||
state: GatingFilterState,
|
||||
page: number,
|
||||
pageSize: number,
|
||||
): Record<string, string | number> {
|
||||
const params: Record<string, string | number> = {
|
||||
page: page >= 1 ? Math.floor(page) : 1,
|
||||
size: pageSize >= 1 ? Math.floor(pageSize) : GATING_DEFAULT_PAGE_SIZE,
|
||||
}
|
||||
const keyword = (state.keyword || '').trim()
|
||||
const country = (state.country || '').trim()
|
||||
const gatingType = (state.gatingType || '').trim()
|
||||
const status = (state.status || '').trim()
|
||||
const source = (state.source || '').trim()
|
||||
if (keyword) params.keyword = keyword
|
||||
if (country) params.country = country
|
||||
if (gatingType) params.gatingType = gatingType
|
||||
if (status === '1' || status === '0') params.status = status
|
||||
if (source) params.source = source
|
||||
return params
|
||||
}
|
||||
|
||||
/** 状态 → 展示文案;非 1 一律按停用。 */
|
||||
export function gatingStatusLabel(status: unknown): string {
|
||||
return status === 1 ? '生效' : '停用'
|
||||
}
|
||||
@@ -0,0 +1,503 @@
|
||||
<script setup lang="ts">
|
||||
import { formatDateTime } from '@/utils/datetime'
|
||||
/** 数富AI工作台客户端包管理页:上传 ZIP → 直传 MinIO → 服务端复算 sha256 落库;
|
||||
* 客户端从 /api/workbench-client/version/latest 自动检测并按最新上传升级。
|
||||
* 列表默认按上传时间倒序,第一条即当前生效版本;删除最新包后自动回落到上一版。 */
|
||||
import { computed, onMounted, ref, watch } from 'vue'
|
||||
import OldPagination from '@/components/OldPagination.vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import {
|
||||
deleteWorkbenchClientPackages,
|
||||
fetchWorkbenchClientPackages,
|
||||
uploadWorkbenchClientPackage,
|
||||
} from './workbench-client-api.ts'
|
||||
import { formatFileSize, isValidWorkbenchClientVersion, WORKBENCH_CLIENT_VERSION_MAX_LENGTH } from './workbench-client-model.ts'
|
||||
import type { WorkbenchClientPackageItem } from './workbench-client-dto.ts'
|
||||
import { showAdminFeedback } from '@/components/admin-feedback-ui'
|
||||
import { openAdminConfirm } from '@/components/admin-confirm'
|
||||
import LoadFailureBar from '@/components/LoadFailureBar.vue'
|
||||
|
||||
const loading = ref(false)
|
||||
const loadFailure = ref('')
|
||||
const items = ref<WorkbenchClientPackageItem[]>([])
|
||||
/** 版本号/文件名搜索(客户端过滤)。 */
|
||||
const keyword = ref('')
|
||||
const filteredItems = computed(() => {
|
||||
const kw = (keyword.value || '').trim().toLowerCase()
|
||||
if (!kw) return items.value
|
||||
return items.value.filter((item) =>
|
||||
`${item.version}`.toLowerCase().includes(kw) || item.fileName.toLowerCase().includes(kw),
|
||||
)
|
||||
})
|
||||
/** 全站分页统一:客户端分页(10/20/50/100)。 */
|
||||
const page = ref(1)
|
||||
const pageSize = ref(10)
|
||||
const pagedItems = computed(() => filteredItems.value.slice((page.value - 1) * pageSize.value, page.value * pageSize.value))
|
||||
function changePage(p: number) { page.value = p }
|
||||
function changeSize(size: number) { pageSize.value = size; page.value = 1 }
|
||||
// 搜索导致数据收缩时回钳页码,避免停在空页。
|
||||
watch(filteredItems, () => {
|
||||
page.value = Math.min(page.value, Math.max(1, Math.ceil(filteredItems.value.length / pageSize.value)))
|
||||
})
|
||||
|
||||
/** 当前生效版本 = 列表第一条(客户端更新接口下发的就是它)。 */
|
||||
const activeId = computed(() => items.value[0]?.id ?? null)
|
||||
|
||||
// 勾选删除:选中跨页累计;表头复选只作用于当前页,避免误选整表。
|
||||
const selectedIds = ref<Set<number>>(new Set())
|
||||
const selectedCount = computed(() => selectedIds.value.size)
|
||||
function toggleSelect(id: number) {
|
||||
const next = new Set(selectedIds.value)
|
||||
if (next.has(id)) next.delete(id)
|
||||
else next.add(id)
|
||||
selectedIds.value = next
|
||||
}
|
||||
function toggleSelectAllPage() {
|
||||
const pageRows = pagedItems.value
|
||||
const allOn = pageRows.length > 0 && pageRows.every((row) => selectedIds.value.has(row.id))
|
||||
const next = new Set(selectedIds.value)
|
||||
if (allOn) pageRows.forEach((row) => next.delete(row.id))
|
||||
else pageRows.forEach((row) => next.add(row.id))
|
||||
selectedIds.value = next
|
||||
}
|
||||
async function removeSelected() {
|
||||
if (!selectedCount.value) return
|
||||
const rows = items.value.filter((row) => selectedIds.value.has(row.id))
|
||||
const sample = rows.slice(0, 3).map((row) => row.version).join('、')
|
||||
const summary = rows.length > 3 ? `${sample} 等 ${rows.length} 个` : sample
|
||||
if (!(await openAdminConfirm({ message: `确认删除选中的 ${rows.length} 个客户端包(${summary})?此操作不可恢复。`, danger: true }))) return
|
||||
try {
|
||||
await deleteWorkbenchClientPackages(Array.from(selectedIds.value))
|
||||
ElMessage.success(`已删除 ${rows.length} 个客户端包`)
|
||||
selectedIds.value = new Set()
|
||||
await load()
|
||||
} catch (error) {
|
||||
showAdminFeedback(error instanceof Error ? error.message : '删除失败', 'error')
|
||||
}
|
||||
}
|
||||
async function removeOne(row: WorkbenchClientPackageItem) {
|
||||
if (!(await openAdminConfirm({ message: `确认删除客户端包 ${row.version}(${row.fileName})?此操作不可恢复。`, danger: true }))) return
|
||||
try {
|
||||
await deleteWorkbenchClientPackages([row.id])
|
||||
ElMessage.success('删除成功')
|
||||
selectedIds.value = new Set([...selectedIds.value].filter((id) => id !== row.id))
|
||||
await load()
|
||||
} catch (error) {
|
||||
showAdminFeedback(error instanceof Error ? error.message : '删除失败', 'error')
|
||||
}
|
||||
}
|
||||
|
||||
const uploadVisible = ref(false)
|
||||
const uploading = ref(false)
|
||||
const uploadPercent = ref(0)
|
||||
const newVersion = ref('')
|
||||
const pickedFile = ref<File | null>(null)
|
||||
const uploadMsg = ref('')
|
||||
const uploadMsgOk = ref(false)
|
||||
|
||||
async function load() {
|
||||
loading.value = true
|
||||
loadFailure.value = ''
|
||||
try {
|
||||
items.value = (await fetchWorkbenchClientPackages()).items
|
||||
} catch (error) {
|
||||
loadFailure.value = error instanceof Error ? error.message : '客户端包列表加载失败'
|
||||
showAdminFeedback(loadFailure.value, 'error')
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function onFileChange(file: File) {
|
||||
pickedFile.value = file
|
||||
}
|
||||
|
||||
function openUpload() {
|
||||
uploadMsg.value = ''
|
||||
uploadMsgOk.value = false
|
||||
newVersion.value = ''
|
||||
pickedFile.value = null
|
||||
uploadVisible.value = true
|
||||
}
|
||||
|
||||
async function submitUpload() {
|
||||
uploadMsg.value = ''
|
||||
uploadMsgOk.value = false
|
||||
uploadPercent.value = 0
|
||||
if (!newVersion.value.trim()) {
|
||||
uploadMsg.value = '请填写版本号'
|
||||
return
|
||||
}
|
||||
if (!isValidWorkbenchClientVersion(newVersion.value)) {
|
||||
uploadMsg.value = `版本号不能超过 ${WORKBENCH_CLIENT_VERSION_MAX_LENGTH} 个字符`
|
||||
return
|
||||
}
|
||||
if (!pickedFile.value) {
|
||||
uploadMsg.value = '请选择 zip 压缩包'
|
||||
return
|
||||
}
|
||||
if (!/\.zip$/i.test(pickedFile.value.name)) {
|
||||
uploadMsg.value = '仅支持 .zip 格式'
|
||||
return
|
||||
}
|
||||
if (pickedFile.value.size > 512 * 1024 * 1024) {
|
||||
uploadMsg.value = '文件超过允许的大小限制'
|
||||
return
|
||||
}
|
||||
uploading.value = true
|
||||
try {
|
||||
await uploadWorkbenchClientPackage(pickedFile.value, pickedFile.value.name, newVersion.value.trim(), (p) => {
|
||||
uploadPercent.value = p
|
||||
uploadMsg.value = p >= 100 ? '上传完成,正在复算 sha256 并登记...' : `正在上传:${p}%`
|
||||
})
|
||||
uploadMsg.value = '上传成功,客户端已可检测到新版本'
|
||||
uploadMsgOk.value = true
|
||||
newVersion.value = ''
|
||||
pickedFile.value = null
|
||||
uploadPercent.value = 0
|
||||
load()
|
||||
} catch (error) {
|
||||
uploadMsg.value = error instanceof Error ? error.message : '上传失败'
|
||||
} finally {
|
||||
uploading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(load)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="workbench-view">
|
||||
<section class="panel-box">
|
||||
<div class="workbench-head">
|
||||
<h3>客户端包列表</h3>
|
||||
<div class="workbench-head-tools">
|
||||
<input v-model="keyword" type="text" placeholder="搜索版本号或文件名" class="workbench-keyword" />
|
||||
<button class="btn btn-danger" type="button" :disabled="!selectedCount" @click="removeSelected">删除选中{{ selectedCount ? `(${selectedCount})` : '' }}</button>
|
||||
<button class="btn" type="button" @click="openUpload">上传客户端包</button>
|
||||
</div>
|
||||
</div>
|
||||
<p class="page-hint">客户端更新检查接口:<code>/api/workbench-client/version/latest</code>;最新上传的一条即当前生效版本。</p>
|
||||
|
||||
<LoadFailureBar v-if="loadFailure" :message="loadFailure" @retry="load" />
|
||||
<div class="table-scroll workbench-table-scroll">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th style="width: 40px" class="th-select">
|
||||
<input type="checkbox" :checked="pagedItems.length > 0 && pagedItems.every((r) => selectedIds.has(r.id))" @change="toggleSelectAllPage" :disabled="!pagedItems.length" />
|
||||
</th>
|
||||
<th style="width: 120px">版本号</th>
|
||||
<th style="width: 220px">文件名</th>
|
||||
<th style="width: 100px">大小</th>
|
||||
<th style="width: 220px">SHA-256</th>
|
||||
<th style="width: 150px">上传时间</th>
|
||||
<th>下载链接</th>
|
||||
<th style="width: 170px">操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<template v-if="filteredItems.length">
|
||||
<tr v-for="row in pagedItems" :key="row.id" :class="{ 'row-selected': selectedIds.has(row.id) }">
|
||||
<td class="td-select">
|
||||
<input type="checkbox" :checked="selectedIds.has(row.id)" @change="toggleSelect(row.id)" />
|
||||
</td>
|
||||
<td>
|
||||
<span class="version-cell" :title="row.version">{{ row.version }}</span>
|
||||
<span v-if="row.id === activeId" class="tag-active">当前生效</span>
|
||||
</td>
|
||||
<td>
|
||||
<span class="file-name" :title="row.fileName">{{ row.fileName }}</span>
|
||||
</td>
|
||||
<td>{{ formatFileSize(row.fileSize) }}</td>
|
||||
<td>
|
||||
<span v-if="row.sha256" class="sha-cell" :title="row.sha256">{{ row.sha256 }}</span>
|
||||
<span v-else class="dim">—</span>
|
||||
</td>
|
||||
<td>{{ formatDateTime(row.createdAt) }}</td>
|
||||
<td>
|
||||
<a v-if="row.fileUrl" class="link-cell" :href="row.fileUrl" target="_blank" rel="noopener" :title="row.fileUrl">{{ row.fileUrl }}</a>
|
||||
<span v-else class="dim">—</span>
|
||||
</td>
|
||||
<td class="ops-cell">
|
||||
<a v-if="row.fileUrl" class="btn btn-sm dl-btn" :href="row.fileUrl" download>下载</a>
|
||||
<span v-else class="dim">—</span>
|
||||
<button class="btn btn-sm btn-danger" type="button" @click="removeOne(row)">删除</button>
|
||||
</td>
|
||||
</tr>
|
||||
</template>
|
||||
<tr v-else-if="loading">
|
||||
<td colspan="8" class="empty-tip">加载中...</td>
|
||||
</tr>
|
||||
<tr v-else>
|
||||
<td colspan="8" class="empty-tip">{{ keyword ? '暂无匹配客户端包' : '暂无客户端包记录' }}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<OldPagination v-if="filteredItems.length > 0" :total="filteredItems.length" :page="page" :page-size="pageSize" @change="changePage" @size-change="changeSize" />
|
||||
</section>
|
||||
|
||||
<el-dialog v-model="uploadVisible" title="上传客户端包" width="540px">
|
||||
<p class="upload-desc">上传数富AI工作台客户端 ZIP 包后,客户端会从公开版本接口自动检测到新版本并升级;服务端会复算 sha256 供客户端校验。</p>
|
||||
<el-form label-width="110px">
|
||||
<el-form-item label="版本号" required>
|
||||
<el-input v-model="newVersion" :placeholder="`例如:1.0.0(最长 ${WORKBENCH_CLIENT_VERSION_MAX_LENGTH} 字符)`" :maxlength="WORKBENCH_CLIENT_VERSION_MAX_LENGTH" />
|
||||
<p class="zip-hint">客户端按版本号判断是否需要升级,必填</p>
|
||||
</el-form-item>
|
||||
<el-form-item label="ZIP 压缩包" required>
|
||||
<el-upload :auto-upload="false" :limit="1" accept=".zip" :on-change="(file: any) => onFileChange(file.raw)" :on-remove="() => (pickedFile = null)">
|
||||
<el-button>选择文件</el-button>
|
||||
</el-upload>
|
||||
<p class="zip-hint">仅支持 .zip 格式,最大 512MB</p>
|
||||
<div v-if="pickedFile" class="dim">{{ pickedFile.name }}({{ formatFileSize(pickedFile.size) }})</div>
|
||||
</el-form-item>
|
||||
<el-progress v-if="uploading && uploadPercent > 0" :percentage="uploadPercent" :stroke-width="10" :status="uploadPercent >= 100 ? 'success' : undefined" class="upload-progress" />
|
||||
<el-alert v-if="uploadMsg" :title="uploadMsg" :type="uploadMsgOk ? 'success' : 'error'" :closable="false" show-icon class="upload-msg" />
|
||||
</el-form>
|
||||
<template #footer>
|
||||
<el-button @click="uploadVisible = false">取消</el-button>
|
||||
<el-button type="primary" :loading="uploading" @click="submitUpload">上传客户端包</el-button>
|
||||
</template>
|
||||
</el-dialog>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
/* 沿用软件版本/教程管理页(旧版 admin.html panel-version)的样式语言。 */
|
||||
.workbench-view {
|
||||
font-family: inherit;
|
||||
color: #24384d;
|
||||
}
|
||||
.panel-box {
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
padding: 20px 22px 24px;
|
||||
border: 1px solid #d8e3ee;
|
||||
border-radius: 14px;
|
||||
background: linear-gradient(145deg, #ffffff, #f9fbfd);
|
||||
box-shadow: 0 1px 2px rgba(39, 67, 94, 0.04), 0 14px 30px -24px rgba(39, 67, 94, 0.28);
|
||||
}
|
||||
h3 {
|
||||
margin: 0;
|
||||
font-size: 15px;
|
||||
font-weight: 650;
|
||||
color: #24384d;
|
||||
letter-spacing: 0.2px;
|
||||
}
|
||||
.workbench-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
.workbench-head-tools {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
}
|
||||
.workbench-keyword {
|
||||
width: 220px;
|
||||
min-height: 42px;
|
||||
padding: 6px 12px;
|
||||
border: 1px solid #cbd9e6;
|
||||
border-radius: 9px;
|
||||
background: #f8fbfd;
|
||||
color: #24384d;
|
||||
font-size: 13.5px;
|
||||
font-family: inherit;
|
||||
color-scheme: light;
|
||||
outline: none;
|
||||
transition: border-color 160ms ease, box-shadow 160ms ease, background 160ms ease;
|
||||
}
|
||||
.workbench-keyword:hover {
|
||||
border-color: #9fb7cd;
|
||||
}
|
||||
.workbench-keyword:focus {
|
||||
background: #ffffff;
|
||||
border-color: #5f85ad;
|
||||
box-shadow: 0 0 0 3px rgba(95, 133, 173, 0.16);
|
||||
}
|
||||
.page-hint {
|
||||
margin: -6px 0 14px;
|
||||
color: #5b6f83;
|
||||
font-size: 12.5px;
|
||||
}
|
||||
.page-hint code {
|
||||
padding: 1px 6px;
|
||||
border-radius: 5px;
|
||||
background: #edf4fa;
|
||||
color: #2f5d8b;
|
||||
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
|
||||
font-size: 12px;
|
||||
}
|
||||
.btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 8px;
|
||||
min-height: 42px;
|
||||
padding: 9px 18px;
|
||||
border: 1px solid #4f78a5;
|
||||
border-radius: 9px;
|
||||
background: linear-gradient(135deg, #5f85ad, #4f78a5);
|
||||
color: #ffffff;
|
||||
font-family: inherit;
|
||||
font-size: 13.5px;
|
||||
cursor: pointer;
|
||||
box-shadow: 0 8px 18px -14px rgba(79, 120, 165, 0.72);
|
||||
transition: background 160ms ease, box-shadow 160ms ease, transform 120ms ease;
|
||||
}
|
||||
.btn:hover:not(:disabled) {
|
||||
background: linear-gradient(135deg, #7094ba, #5d83ac);
|
||||
box-shadow: 0 11px 22px -14px rgba(79, 120, 165, 0.8);
|
||||
}
|
||||
.btn:disabled {
|
||||
cursor: not-allowed;
|
||||
opacity: 0.55;
|
||||
}
|
||||
.btn-sm {
|
||||
min-height: 36px;
|
||||
padding: 7px 12px;
|
||||
}
|
||||
.btn-danger {
|
||||
background: linear-gradient(135deg, #c06d77, #b35f6a);
|
||||
border-color: #b35f6a;
|
||||
}
|
||||
.btn-danger:hover:not(:disabled) {
|
||||
background: linear-gradient(135deg, #cb7c84, #b96570);
|
||||
}
|
||||
.table-scroll {
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
overflow-x: auto;
|
||||
border: 1px solid #dbe5ee;
|
||||
border-radius: 10px;
|
||||
background: #ffffff;
|
||||
}
|
||||
.table-scroll table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
table-layout: fixed;
|
||||
}
|
||||
.workbench-table-scroll > table {
|
||||
min-width: 1200px;
|
||||
}
|
||||
.table-scroll th,
|
||||
.table-scroll td {
|
||||
padding: 10px 12px;
|
||||
text-align: left;
|
||||
font-size: 13.5px;
|
||||
line-height: 1.5;
|
||||
border-bottom: 1px solid #e0e8ef;
|
||||
vertical-align: middle;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.table-scroll th {
|
||||
background: #edf4fa;
|
||||
color: #4e6479;
|
||||
border-bottom-color: #d5e1eb;
|
||||
font-size: 12.5px;
|
||||
font-weight: 600;
|
||||
letter-spacing: 0.4px;
|
||||
}
|
||||
.table-scroll tbody tr:hover td {
|
||||
background: #f1f7fb;
|
||||
}
|
||||
.table-scroll tbody tr:last-child td {
|
||||
border-bottom: 0;
|
||||
}
|
||||
.file-name,
|
||||
.version-cell {
|
||||
display: inline-block;
|
||||
max-width: 100%;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
vertical-align: middle;
|
||||
}
|
||||
.tag-active {
|
||||
display: inline-block;
|
||||
margin-left: 6px;
|
||||
padding: 1px 7px;
|
||||
border: 1px solid #4f9a72;
|
||||
border-radius: 999px;
|
||||
background: #eaf6ef;
|
||||
color: #2f7a55;
|
||||
font-size: 11.5px;
|
||||
vertical-align: middle;
|
||||
}
|
||||
.sha-cell {
|
||||
display: block;
|
||||
overflow: hidden;
|
||||
color: #5b6f83;
|
||||
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
|
||||
font-size: 12px;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
.link-cell {
|
||||
display: block;
|
||||
color: #2f5d8b;
|
||||
text-decoration: none;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
.link-cell:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
.dl-btn {
|
||||
text-decoration: none;
|
||||
}
|
||||
.dim {
|
||||
color: #8293a5;
|
||||
font-size: 12px;
|
||||
}
|
||||
.empty-tip {
|
||||
padding: 44px 24px;
|
||||
text-align: center;
|
||||
color: #8293a5;
|
||||
font-size: 13.5px;
|
||||
}
|
||||
.upload-desc {
|
||||
margin: 0 0 12px;
|
||||
color: #5b6f83;
|
||||
font-size: 12.5px;
|
||||
line-height: 1.6;
|
||||
}
|
||||
.zip-hint {
|
||||
margin: 4px 0 0;
|
||||
color: #5b6f83;
|
||||
font-size: 12px;
|
||||
}
|
||||
.ops-cell {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
}
|
||||
.row-selected td {
|
||||
background: #fdf0ee;
|
||||
}
|
||||
.th-select,
|
||||
.td-select {
|
||||
text-align: center;
|
||||
padding-left: 4px !important;
|
||||
padding-right: 4px !important;
|
||||
}
|
||||
.th-select input,
|
||||
.td-select input {
|
||||
cursor: pointer;
|
||||
accent-color: #b33a2e;
|
||||
}
|
||||
.upload-progress {
|
||||
margin: 2px 0 10px;
|
||||
}
|
||||
.upload-msg {
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
.upload-msg :deep(.el-alert__title) {
|
||||
word-break: break-all;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,98 @@
|
||||
/** 工作台客户端包接口适配:列表 / 直传预签名 / 确认 / 删除。 */
|
||||
import axios from 'axios'
|
||||
import { http, unwrap } from '@/api/http'
|
||||
import {
|
||||
parseWorkbenchClientPackageList,
|
||||
parseWorkbenchClientPackageUpload,
|
||||
} from './workbench-client-model.ts'
|
||||
import type { WorkbenchClientPackageItem, WorkbenchClientPackageList } from './workbench-client-dto.ts'
|
||||
|
||||
export const WORKBENCH_CLIENT_PACKAGES_ENDPOINT = '/api/admin/workbench-client/packages'
|
||||
export const WORKBENCH_CLIENT_PACKAGE_ENDPOINT = '/api/admin/workbench-client/package'
|
||||
export const WORKBENCH_CLIENT_PRESIGN_ENDPOINT = `${WORKBENCH_CLIENT_PACKAGE_ENDPOINT}/presign`
|
||||
export const WORKBENCH_CLIENT_CONFIRM_ENDPOINT = `${WORKBENCH_CLIENT_PACKAGE_ENDPOINT}/confirm`
|
||||
export const WORKBENCH_CLIENT_DELETE_ENDPOINT = `${WORKBENCH_CLIENT_PACKAGE_ENDPOINT}/delete`
|
||||
|
||||
/** 客户端自动更新契约(后管页面不直接调用):GET 返回 {version,file_url,sha256,...}。 */
|
||||
export const WORKBENCH_CLIENT_PUBLIC_LATEST_ENDPOINT = '/api/workbench-client/version/latest'
|
||||
|
||||
/** MinIO 直传专用实例:不带 cookie、不挂 401 跳登录拦截器;大 zip 给足超时。 */
|
||||
const directPut = axios.create({ timeout: 600_000, withCredentials: false })
|
||||
|
||||
export async function fetchWorkbenchClientPackages(): Promise<WorkbenchClientPackageList> {
|
||||
const { data } = await http.get<unknown>(WORKBENCH_CLIENT_PACKAGES_ENDPOINT)
|
||||
return parseWorkbenchClientPackageList(data)
|
||||
}
|
||||
|
||||
export interface WorkbenchClientUploadTarget {
|
||||
objectKey: string
|
||||
uploadUrl: string
|
||||
fileUrl: string
|
||||
version: string
|
||||
fileName: string
|
||||
}
|
||||
|
||||
/** 第一步:向后端申请直传 PUT 预签名地址(登录会话签发,3 分钟有效)。 */
|
||||
export async function requestWorkbenchClientPresign(
|
||||
fileName: string,
|
||||
version: string,
|
||||
): Promise<WorkbenchClientUploadTarget> {
|
||||
const { data } = await http.post<unknown>(WORKBENCH_CLIENT_PRESIGN_ENDPOINT, null, {
|
||||
params: { file_name: fileName, version },
|
||||
})
|
||||
const core = (unwrap(data) ?? {}) as Record<string, unknown>
|
||||
const uploadUrl = typeof core.upload_url === 'string' ? core.upload_url : ''
|
||||
const objectKey = typeof core.object_key === 'string' ? core.object_key : ''
|
||||
if (!uploadUrl || !objectKey) {
|
||||
throw new Error('后端未返回直传地址,请重试')
|
||||
}
|
||||
return {
|
||||
objectKey,
|
||||
uploadUrl,
|
||||
fileUrl: typeof core.file_url === 'string' ? core.file_url : '',
|
||||
version: typeof core.version === 'string' ? core.version : version.trim(),
|
||||
fileName: typeof core.file_name === 'string' ? core.file_name : fileName,
|
||||
}
|
||||
}
|
||||
|
||||
/** 第三步:直传完成后通知后端核对对象、复算 sha256 并落库(data.item 为新记录行)。 */
|
||||
export async function confirmWorkbenchClientPackage(
|
||||
objectKey: string,
|
||||
fileName: string,
|
||||
version: string,
|
||||
): Promise<WorkbenchClientPackageItem | null> {
|
||||
const { data } = await http.post<unknown>(WORKBENCH_CLIENT_CONFIRM_ENDPOINT, null, {
|
||||
params: { object_key: objectKey, file_name: fileName, version },
|
||||
})
|
||||
return parseWorkbenchClientPackageUpload(data)
|
||||
}
|
||||
|
||||
/** 按 id 批量删除客户端包(后端会顺带清理无引用对象的 MinIO 包体);返回实际删除行数。 */
|
||||
export async function deleteWorkbenchClientPackages(ids: number[]): Promise<number> {
|
||||
if (!ids.length) return 0
|
||||
const { data } = await http.post<unknown>(WORKBENCH_CLIENT_DELETE_ENDPOINT, ids)
|
||||
const core = (unwrap(data) ?? {}) as Record<string, unknown>
|
||||
return typeof core.deleted === 'number' ? core.deleted : ids.length
|
||||
}
|
||||
|
||||
/**
|
||||
* 上传客户端包(浏览器直传):presign 申请 → 直接 PUT 到 MinIO client 桶(不走 Java 中转)
|
||||
* → confirm 由服务端复算 sha256 落库。onProgress 回传 0-100 上传进度。
|
||||
*/
|
||||
export async function uploadWorkbenchClientPackage(
|
||||
file: Blob,
|
||||
fileName: string,
|
||||
version: string,
|
||||
onProgress?: (percent: number) => void,
|
||||
): Promise<WorkbenchClientPackageItem | null> {
|
||||
const target = await requestWorkbenchClientPresign(fileName, version)
|
||||
await directPut.put(target.uploadUrl, file, {
|
||||
headers: { 'Content-Type': 'application/octet-stream' },
|
||||
onUploadProgress: (event) => {
|
||||
if (!onProgress) return
|
||||
const total = event.total || 0
|
||||
onProgress(total > 0 ? Math.min(Math.round((event.loaded / total) * 100), 100) : 0)
|
||||
},
|
||||
})
|
||||
return confirmWorkbenchClientPackage(target.objectKey, target.fileName, target.version)
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
/** 工作台客户端包 DTO(后管「数富AI工作台客户端包管理」页)。纯类型。 */
|
||||
|
||||
/** 客户端包行(GET /api/admin/workbench-client/packages data.items,Java snake)。 */
|
||||
export interface WorkbenchClientPackageItem {
|
||||
id: number
|
||||
version: string
|
||||
fileName: string
|
||||
objectKey: string
|
||||
fileSize: number
|
||||
/** 更新包 sha256(hex 小写),客户端下载后的完整性锚点 */
|
||||
sha256: string
|
||||
fileUrl: string
|
||||
createdAt: string
|
||||
}
|
||||
|
||||
export interface WorkbenchClientPackageList {
|
||||
items: WorkbenchClientPackageItem[]
|
||||
}
|
||||
|
||||
export function emptyWorkbenchClientPackageList(): WorkbenchClientPackageList {
|
||||
return { items: [] }
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
/** 工作台客户端包列表加载模型:解析 snake/camel、格式化大小与版本号校验;纯逻辑。 */
|
||||
import { unwrap } from '../../api/envelope.ts'
|
||||
import { type WorkbenchClientPackageItem, type WorkbenchClientPackageList } from './workbench-client-dto.ts'
|
||||
|
||||
/** 与后端 biz_workbench_client_package.version VARCHAR(64) 对齐。 */
|
||||
export const WORKBENCH_CLIENT_VERSION_MAX_LENGTH = 64
|
||||
|
||||
function text(value: unknown): string {
|
||||
return typeof value === 'string' ? value.trim() : ''
|
||||
}
|
||||
|
||||
function numberOrNull(value: unknown): number | null {
|
||||
return typeof value === 'number' && Number.isFinite(value) ? Math.floor(value) : null
|
||||
}
|
||||
|
||||
/** 解析单条客户端包行;缺 id 视为无效。 */
|
||||
export function toWorkbenchClientPackageItem(raw: unknown): WorkbenchClientPackageItem | null {
|
||||
if (!raw || typeof raw !== 'object') return null
|
||||
const r = raw as Record<string, unknown>
|
||||
const id = numberOrNull(r.id)
|
||||
if (id === null) return null
|
||||
return {
|
||||
id,
|
||||
version: text(r.version),
|
||||
fileName: text(r.file_name ?? r.fileName),
|
||||
objectKey: text(r.object_key ?? r.objectKey),
|
||||
fileSize: numberOrNull(r.file_size ?? r.fileSize) ?? 0,
|
||||
sha256: text(r.sha256),
|
||||
fileUrl: text(r.file_url ?? r.fileUrl),
|
||||
createdAt: text(r.created_at ?? r.createdAt),
|
||||
}
|
||||
}
|
||||
|
||||
/** 归一化客户端包列表负载为前端结果;缺省回空列表。 */
|
||||
export function parseWorkbenchClientPackageList(payload: unknown): WorkbenchClientPackageList {
|
||||
const data = unwrap<unknown>(payload)
|
||||
const record = data && typeof data === 'object' ? (data as Record<string, unknown>) : {}
|
||||
const items = Array.isArray(record.items)
|
||||
? record.items
|
||||
.map((raw) => toWorkbenchClientPackageItem(raw))
|
||||
.filter((item): item is WorkbenchClientPackageItem => item !== null)
|
||||
: []
|
||||
return { items }
|
||||
}
|
||||
|
||||
/** 上传成功后返回的新记录行(data.item);无 item 回 null。 */
|
||||
export function parseWorkbenchClientPackageUpload(payload: unknown): WorkbenchClientPackageItem | null {
|
||||
const data = unwrap<unknown>(payload)
|
||||
if (!data || typeof data !== 'object') return null
|
||||
const item = (data as Record<string, unknown>).item
|
||||
return item ? toWorkbenchClientPackageItem(item) : null
|
||||
}
|
||||
|
||||
/** 版本号必填且不超过后端列宽;客户端要靠它比较是否需要升级。 */
|
||||
export function isValidWorkbenchClientVersion(value: string): boolean {
|
||||
const normalized = typeof value === 'string' ? value.trim() : ''
|
||||
return normalized.length > 0 && normalized.length <= WORKBENCH_CLIENT_VERSION_MAX_LENGTH
|
||||
}
|
||||
|
||||
/** 字节数展示:0=未知展示为 -,其余按 KB/MB/GB 人性化。 */
|
||||
export function formatFileSize(bytes: number): string {
|
||||
if (!Number.isFinite(bytes) || bytes <= 0) return '—'
|
||||
if (bytes < 1024) return `${bytes} B`
|
||||
const units = ['KB', 'MB', 'GB']
|
||||
let value = bytes / 1024
|
||||
let unitIndex = 0
|
||||
while (value >= 1024 && unitIndex < units.length - 1) {
|
||||
value /= 1024
|
||||
unitIndex += 1
|
||||
}
|
||||
return `${value >= 100 ? value.toFixed(0) : value.toFixed(1)} ${units[unitIndex]}`
|
||||
}
|
||||
@@ -30,6 +30,7 @@ export const adminPages: AdminPageDef[] = [
|
||||
{ path: 'records/history', menuKey: 'admin_history', title: '生成记录', companyScoped: true, load: () => import('@/pages/records/RecordsHistoryPage.vue') },
|
||||
{ path: 'records/software-version', menuKey: 'admin_version', title: '软件版本管理', companyScoped: false, load: () => import('@/pages/records/RecordsSoftwareVersionPage.vue') },
|
||||
{ path: 'records/tutorial', menuKey: 'admin_tutorial', title: '教程管理', companyScoped: false, load: () => import('@/pages/records/RecordsTutorialPage.vue') },
|
||||
{ path: 'records/workbench-client-package', menuKey: 'admin_workbench_client_package', title: '数富AI工作台客户端包管理', companyScoped: false, load: () => import('@/pages/records/WorkbenchClientPackagePage.vue') },
|
||||
{ path: 'records/device-logs', menuKey: 'admin_device_logs', title: '日志管理', companyScoped: true, load: () => import('@/pages/records/DeviceLogsPage.vue') },
|
||||
{ path: 'task-center/board', menuKey: 'admin_task_center', title: '客户端任务管理', companyScoped: true, load: () => import('@/pages/task-center/TaskCenterBoardPage.vue') },
|
||||
{ path: 'records/digital-human-version', menuKey: 'digital_human_version', title: '数字人版本管理', load: () => import('@/pages/records/RecordsDigitalHumanVersionPage.vue') },
|
||||
@@ -40,8 +41,6 @@ export const adminPages: AdminPageDef[] = [
|
||||
{ path: 'asin-center/query', menuKey: 'admin_query_asin', title: '查询ASIN', companyScoped: true, load: () => import('@/pages/asin/QueryAsinPage.vue') },
|
||||
{ path: 'asin-center/categories', menuKey: 'admin_product_categories', title: '商品类目', companyScoped: false, load: () => import('@/pages/asin/ProductCategoryPage.vue') },
|
||||
{ path: 'asin-center/skip-price', menuKey: 'admin_skip_price_asin', title: '最低价ASIN', companyScoped: true, load: () => import('@/pages/asin/SkipPricePage.vue') },
|
||||
// 品牌Gating库(biz_brand_gating):全平台共享表(桌面版 gating_web_admin 同源数据),不参与公司 tab。
|
||||
{ path: 'asin-center/gating', menuKey: 'admin_brand_gating', title: '品牌Gating库', companyScoped: false, load: () => import('@/pages/gating/GatingPage.vue') },
|
||||
]
|
||||
|
||||
export function routeOf(page: AdminPageDef): RouteRecordRaw {
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { readSource } from './helpers.ts'
|
||||
import { adminPages } from '../src/router/routes.ts'
|
||||
import { OPERATION_GUIDES } from '../src/layout/operation-guides.ts'
|
||||
|
||||
/** 工作台客户端包管理页:独立渠道、上传直传、服务端 sha256、客户端自动更新契约。 */
|
||||
|
||||
test('align_workbench_client_page_registered', () => {
|
||||
const page = adminPages.find((p) => p.path === 'records/workbench-client-package')
|
||||
assert.ok(page, '路由注册表应包含 records/workbench-client-package')
|
||||
assert.equal(page.menuKey, 'admin_workbench_client_package')
|
||||
assert.equal(page.title, '数富AI工作台客户端包管理')
|
||||
assert.equal(page.companyScoped, false, '客户端包是全平台共享资源,不按公司隔离')
|
||||
})
|
||||
|
||||
test('align_workbench_client_page_wiring', () => {
|
||||
const page = readSource('src/pages/records/WorkbenchClientPackagePage.vue')
|
||||
// 上传:版本号必填 → zip → 直传(进度条)→ 成功提示留驻弹窗。
|
||||
assert.match(page, /上传客户端包/, '存在上传入口按钮')
|
||||
assert.match(page, /uploadWorkbenchClientPackage/, '上传走工作台客户端包直传链路')
|
||||
assert.match(page, /label="版本号" required/, '上传弹窗要求填写版本号')
|
||||
assert.match(page, /请填写版本号/, '未填版本号时提示')
|
||||
assert.match(page, /仅支持 \.zip 格式/, '格式校验提示')
|
||||
assert.match(page, /上传成功,客户端已可检测到新版本/, '成功提示说明客户端已能检测更新')
|
||||
// 列表:当前生效标记、sha256、下载、删除、空态。
|
||||
assert.match(page, /当前生效/, '最新上传的包标记当前生效')
|
||||
assert.match(page, /sha256/, '展示服务端复算的摘要')
|
||||
assert.match(page, /formatFileSize/, '展示包体大小')
|
||||
assert.match(page, /\/api\/workbench-client\/version\/latest/, '页面标明客户端更新检查接口')
|
||||
assert.match(page, /确认删除选中的/, '批量删除二次确认')
|
||||
assert.match(page, /暂无客户端包记录/, '空态文案')
|
||||
})
|
||||
|
||||
test('align_workbench_client_api_contract', () => {
|
||||
const api = readSource('src/pages/records/workbench-client-api.ts')
|
||||
assert.match(api, /\/api\/admin\/workbench-client\/packages/, '列表端点')
|
||||
assert.match(api, /WORKBENCH_CLIENT_PACKAGE_ENDPOINT = '\/api\/admin\/workbench-client\/package'/, '上传端点前缀')
|
||||
assert.match(api, /\$\{WORKBENCH_CLIENT_PACKAGE_ENDPOINT\}\/presign/, '直传预签名端点')
|
||||
assert.match(api, /\$\{WORKBENCH_CLIENT_PACKAGE_ENDPOINT\}\/confirm/, '确认端点')
|
||||
assert.match(api, /\$\{WORKBENCH_CLIENT_PACKAGE_ENDPOINT\}\/delete/, '删除端点')
|
||||
assert.match(api, /params: \{ file_name: fileName, version \}/, '预签名回传文件名与版本号')
|
||||
assert.match(api, /params: \{ object_key: objectKey, file_name: fileName, version \}/, '确认回传对象 key、文件名与版本号')
|
||||
assert.match(api, /withCredentials: false/, '直传实例不挂会话拦截器')
|
||||
assert.match(api, /\/api\/workbench-client\/version\/latest/, '公开更新契约路径固定')
|
||||
})
|
||||
|
||||
test('align_workbench_client_model_parsers', () => {
|
||||
const model = readSource('src/pages/records/workbench-client-model.ts')
|
||||
assert.match(model, /r\.file_name \?\? r\.fileName/, '兼容 snake/camel 文件名')
|
||||
assert.match(model, /r\.file_url \?\? r\.fileUrl/, '兼容 snake/camel 下载链接')
|
||||
assert.match(model, /r\.file_size \?\? r\.fileSize/, '兼容 snake/camel 文件大小')
|
||||
assert.match(model, /r\.object_key \?\? r\.objectKey/, '兼容 snake/camel 对象 key')
|
||||
assert.match(model, /r\.sha256/, '解析 sha256')
|
||||
assert.match(model, /isValidWorkbenchClientVersion/, '版本号必填校验')
|
||||
})
|
||||
|
||||
test('align_workbench_client_guide_registered', () => {
|
||||
const guide = OPERATION_GUIDES.admin_workbench_client_package
|
||||
assert.ok(guide, '每个菜单页都必须有操作提示')
|
||||
assert.match(guide.text, /sha256/, '提示说明服务端会复算摘要')
|
||||
assert.match(guide.text, /\/api\/workbench-client\/version\/latest/, '提示说明客户端更新检查接口')
|
||||
})
|
||||
@@ -1,10 +1,10 @@
|
||||
{
|
||||
"note": "readSource 钉子逐文件基线。两把尺子:pins=落在用例体内的读盘,reads=全文读点总数(含模块级夹具与 helper)。都只许减;pins 下降而 reads 没同步下降=把读盘挪出体内,不算改进。由 tests/source-pin-ratchet.test.ts 生成。",
|
||||
"totals": {
|
||||
"files": 244,
|
||||
"cases": 1728,
|
||||
"pins": 448,
|
||||
"reads": 639
|
||||
"files": 245,
|
||||
"cases": 1733,
|
||||
"pins": 451,
|
||||
"reads": 642
|
||||
},
|
||||
"files": {
|
||||
"admin-scaffold.test.ts": {
|
||||
@@ -182,6 +182,11 @@
|
||||
"pins": 1,
|
||||
"reads": 1
|
||||
},
|
||||
"align-workbench-client.test.ts": {
|
||||
"cases": 5,
|
||||
"pins": 3,
|
||||
"reads": 3
|
||||
},
|
||||
"company-config-entry-super-only.test.ts": {
|
||||
"cases": 4,
|
||||
"pins": 3,
|
||||
|
||||
@@ -1,58 +0,0 @@
|
||||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { gatingImportOutcomeText, parseGatingImportText } from '../src/pages/gating/gating-import.ts'
|
||||
|
||||
test('gating_import_single_field_defaults', () => {
|
||||
// 桌面版口径:只给品牌 → 国家=全部、类型=品牌gating、ASIN/备注空。
|
||||
const result = parseGatingImportText('jellycat')
|
||||
assert.equal(result.items.length, 1)
|
||||
assert.deepEqual(result.items[0], { brand: 'jellycat', country: '全部', gatingType: '品牌gating', asin: '', remark: '' })
|
||||
assert.equal(result.skippedLines, 0)
|
||||
})
|
||||
|
||||
test('gating_import_full_five_fields', () => {
|
||||
const result = parseGatingImportText('tory burch,英国,品牌gating,B0ABC123,人为录入')
|
||||
assert.deepEqual(result.items[0], { brand: 'tory burch', country: '英国', gatingType: '品牌gating', asin: 'B0ABC123', remark: '人为录入' })
|
||||
})
|
||||
|
||||
test('gating_import_mixed_separators_and_extra_fields_dropped', () => {
|
||||
// 桌面版分隔符集合 [,\t;,;];第 5 列之后的段丢弃。
|
||||
const result = parseGatingImportText('crocs,德国;类目gating\tB0X\t备注\t多余段')
|
||||
assert.deepEqual(result.items[0], { brand: 'crocs', country: '德国', gatingType: '类目gating', asin: 'B0X', remark: '备注' })
|
||||
})
|
||||
|
||||
test('gating_import_skip_blank_comment_and_separator_only_lines', () => {
|
||||
const text = [
|
||||
'',
|
||||
' ',
|
||||
'# 这是注释行',
|
||||
';;,', // 纯分隔符行 → 空段全被丢,整行跳过
|
||||
'jellycat',
|
||||
].join('\n')
|
||||
const result = parseGatingImportText(text)
|
||||
assert.equal(result.items.length, 1)
|
||||
assert.equal(result.items[0]?.brand, 'jellycat')
|
||||
assert.equal(result.skippedLines, 2) // 注释行 + 纯分隔符行;纯空白行不计数
|
||||
})
|
||||
|
||||
test('gating_import_bom_and_crlf_and_empty_parts', () => {
|
||||
const result = parseGatingImportText('\uFEFFcrocs,德国,,B0X\r\n,头部空段被丢')
|
||||
assert.equal(result.items.length, 2)
|
||||
assert.equal(result.items[0]?.brand, 'crocs')
|
||||
assert.equal(result.items[0]?.country, '德国')
|
||||
// 桌面版口径:空段在切分后就被丢弃,后续字段整体左移(B0X 落到类型位)——照抄不修正。
|
||||
assert.equal(result.items[0]?.gatingType, 'B0X')
|
||||
assert.equal(result.items[0]?.asin, '')
|
||||
assert.equal(result.items[1]?.brand, '头部空段被丢')
|
||||
assert.equal(result.items[1]?.country, '全部')
|
||||
})
|
||||
|
||||
test('gating_import_empty_input_never_throws', () => {
|
||||
assert.deepEqual(parseGatingImportText(''), { items: [], skippedLines: 0 })
|
||||
// @ts-expect-error 纯函数要扛住脏输入(运行时防呆)。
|
||||
assert.deepEqual(parseGatingImportText(null), { items: [], skippedLines: 0 })
|
||||
})
|
||||
|
||||
test('gating_import_outcome_text', () => {
|
||||
assert.equal(gatingImportOutcomeText(3, 2), '批量导入完成:新增 3 条,跳过重复 2 条')
|
||||
})
|
||||
@@ -1,99 +0,0 @@
|
||||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import {
|
||||
createGatingFilterState,
|
||||
gatingStatusLabel,
|
||||
parseGatingNameCountList,
|
||||
parseGatingPage,
|
||||
parseGatingStats,
|
||||
toGatingItem,
|
||||
toGatingListParams,
|
||||
} from '../src/pages/gating/gating-model.ts'
|
||||
|
||||
test('gating_filter_normal_primary_path', () => {
|
||||
// 完整筛选映射到契约查询参数(page/size/keyword/country/gatingType/status/source)。
|
||||
const state = { ...createGatingFilterState(), keyword: 'jellycat', country: '英国', gatingType: '品牌gating', status: '1', source: 'MANUAL' }
|
||||
const params = toGatingListParams(state, 3, 20)
|
||||
assert.equal(params.page, 3)
|
||||
assert.equal(params.size, 20)
|
||||
assert.equal(params.keyword, 'jellycat')
|
||||
assert.equal(params.country, '英国')
|
||||
assert.equal(params.gatingType, '品牌gating')
|
||||
assert.equal(params.status, '1')
|
||||
assert.equal(params.source, 'MANUAL')
|
||||
})
|
||||
|
||||
test('gating_filter_boundary_blank_dropped', () => {
|
||||
// 空筛选只带分页;非法 status(非 '0'/'1')不下发。
|
||||
const params = toGatingListParams({ ...createGatingFilterState(), status: 'all', keyword: ' ' }, 0, -5)
|
||||
assert.deepEqual(params, { page: 1, size: 10 })
|
||||
})
|
||||
|
||||
test('gating_item_parse_normal_and_snake_fallback', () => {
|
||||
const camel = toGatingItem({
|
||||
id: 7, brand: 'jellycat', asin: 'B0ABC123', country: '英国', gatingType: '品牌gating',
|
||||
status: 1, source: 'AUTO', shopName: '店A', remark: 'r',
|
||||
createdAt: '2026-01-02 03:04:05', updatedAt: '2026-01-03 03:04:05', disabledAt: null,
|
||||
})
|
||||
assert.ok(camel)
|
||||
assert.equal(camel.gatingType, '品牌gating')
|
||||
assert.equal(camel.shopName, '店A')
|
||||
assert.equal(camel.createdAt, '2026-01-02 03:04:05')
|
||||
assert.equal(camel.disabledAt, undefined)
|
||||
|
||||
const snake = toGatingItem({
|
||||
id: 9, gating_type: '类目gating', shop_name: '店B',
|
||||
created_at: '2026-02-01 00:00:00', updated_at: '2026-02-02 00:00:00', disabled_at: '2026-02-03 00:00:00',
|
||||
})
|
||||
assert.ok(snake)
|
||||
assert.equal(snake.gatingType, '类目gating')
|
||||
assert.equal(snake.shopName, '店B')
|
||||
assert.equal(snake.disabledAt, '2026-02-03 00:00:00')
|
||||
})
|
||||
|
||||
test('gating_item_parse_invalid_rows_dropped', () => {
|
||||
assert.equal(toGatingItem(null), null)
|
||||
assert.equal(toGatingItem({ brand: 'no-id' }), null)
|
||||
const page = parseGatingPage({ total: 3, rows: [{ id: 1, brand: 'a' }, { brand: 'bad' }, 'junk', null] })
|
||||
assert.equal(page.rows.length, 1)
|
||||
assert.equal(page.rows[0]?.brand, 'a')
|
||||
assert.equal(page.total, 3)
|
||||
})
|
||||
|
||||
test('gating_page_parse_empty_and_items_alias', () => {
|
||||
assert.deepEqual(parseGatingPage(null), { rows: [], total: 0 })
|
||||
const page = parseGatingPage({ total: 1, items: [{ id: 2, brand: 'b' }] })
|
||||
assert.equal(page.rows.length, 1)
|
||||
assert.equal(page.rows[0]?.id, 2)
|
||||
})
|
||||
|
||||
test('gating_stats_parse_array_and_dict_forms', () => {
|
||||
// 契约数组形态。
|
||||
const stats = parseGatingStats({
|
||||
total: 10, active: 8, disabled: 2, brands: 5,
|
||||
byType: [{ name: '品牌gating', count: 6 }, { name: '类目gating', count: 2 }],
|
||||
byCountry: [{ name: '英国', count: 4 }],
|
||||
bySource: [{ name: 'AUTO', count: 7 }],
|
||||
})
|
||||
assert.equal(stats.total, 10)
|
||||
assert.equal(stats.brands, 5)
|
||||
assert.equal(stats.byType[0]?.name, '品牌gating')
|
||||
assert.equal(stats.bySource[0]?.count, 7)
|
||||
// 桌面版遗留 dict 形态也要能收。
|
||||
const legacy = parseGatingStats({ total: 1, by_type: { '品牌gating': 3 }, by_country: { '全部': 1 }, by_source: { MANUAL: 1 } })
|
||||
assert.equal(legacy.byType[0]?.name, '品牌gating')
|
||||
assert.equal(legacy.byType[0]?.count, 3)
|
||||
assert.equal(legacy.byCountry[0]?.name, '全部')
|
||||
})
|
||||
|
||||
test('gating_name_count_list_garbage_in_empty_out', () => {
|
||||
assert.deepEqual(parseGatingNameCountList(null), [])
|
||||
assert.deepEqual(parseGatingNameCountList('x'), [])
|
||||
assert.deepEqual(parseGatingNameCountList([{ name: '', count: 1 }, { count: 2 }, 'junk']), [])
|
||||
})
|
||||
|
||||
test('gating_status_label', () => {
|
||||
assert.equal(gatingStatusLabel(1), '生效')
|
||||
assert.equal(gatingStatusLabel(0), '停用')
|
||||
assert.equal(gatingStatusLabel(undefined), '停用')
|
||||
})
|
||||
@@ -1,138 +0,0 @@
|
||||
/**
|
||||
* 品牌Gating库页面挂载测试:渲染(统计卡 + 行)与两次操作载荷断言(新增、恢复生效)。
|
||||
* 跑法:`npm run test:mount`(vitest + jsdom,配置见 vitest.config.ts)。
|
||||
*/
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { flushPromises, mount, type VueWrapper } from '@vue/test-utils'
|
||||
|
||||
import GatingPage from '@/pages/gating/GatingPage.vue'
|
||||
|
||||
const gatingApi = vi.hoisted(() => ({
|
||||
fetchGatingPage: vi.fn(),
|
||||
fetchGatingStats: vi.fn(),
|
||||
createGating: vi.fn(),
|
||||
deleteGating: vi.fn(),
|
||||
updateGatingStatus: vi.fn(),
|
||||
importGatingText: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/pages/gating/gating-api', () => gatingApi)
|
||||
|
||||
const listPayload = {
|
||||
total: 2,
|
||||
rows: [
|
||||
{
|
||||
id: 1,
|
||||
brand: 'jellycat',
|
||||
asin: 'B0ABC123',
|
||||
country: '英国',
|
||||
gatingType: '品牌gating',
|
||||
status: 1,
|
||||
source: 'AUTO',
|
||||
shopName: '',
|
||||
remark: '',
|
||||
createdAt: '2026-01-02 03:04:05',
|
||||
updatedAt: '2026-01-03 03:04:05',
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
brand: 'crocs',
|
||||
asin: '',
|
||||
country: '全部',
|
||||
gatingType: '类目gating',
|
||||
status: 0,
|
||||
source: 'MANUAL',
|
||||
shopName: '店A',
|
||||
remark: '人为录入',
|
||||
createdAt: '2026-02-01 00:00:00',
|
||||
updatedAt: '2026-02-02 00:00:00',
|
||||
disabledAt: '2026-02-03 00:00:00',
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
const statsPayload = {
|
||||
total: 2,
|
||||
active: 1,
|
||||
disabled: 1,
|
||||
brands: 2,
|
||||
byType: [{ name: '品牌gating', count: 1 }],
|
||||
byCountry: [{ name: '英国', count: 1 }],
|
||||
bySource: [{ name: 'MANUAL', count: 1 }],
|
||||
}
|
||||
|
||||
const findButton = (wrapper: VueWrapper, label: string) =>
|
||||
wrapper.findAll('button').find((button) => button.text().trim() === label)
|
||||
|
||||
describe('GatingPage', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
gatingApi.fetchGatingPage.mockResolvedValue(listPayload)
|
||||
gatingApi.fetchGatingStats.mockResolvedValue(statsPayload)
|
||||
})
|
||||
|
||||
it('渲染统计卡、筛选区与表格行', async () => {
|
||||
const wrapper = mount(GatingPage)
|
||||
await flushPromises()
|
||||
|
||||
const text = wrapper.text()
|
||||
expect(text).toContain('Gating总记录')
|
||||
expect(text).toContain('去重品牌数')
|
||||
expect(text).toContain('jellycat')
|
||||
expect(text).toContain('crocs')
|
||||
expect(text).toContain('生效')
|
||||
expect(text).toContain('停用')
|
||||
expect(text).toContain('按Gating类型')
|
||||
expect(wrapper.findAll('tbody tr').length).toBeGreaterThanOrEqual(2)
|
||||
expect(gatingApi.fetchGatingPage).toHaveBeenCalledTimes(1)
|
||||
expect(gatingApi.fetchGatingStats).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('新增弹窗提交后按驼峰字段发载荷', async () => {
|
||||
const wrapper = mount(GatingPage)
|
||||
await flushPromises()
|
||||
gatingApi.createGating.mockResolvedValue(1)
|
||||
|
||||
await findButton(wrapper, '新增')!.trigger('click')
|
||||
const modal = wrapper.get('.modal')
|
||||
const inputs = modal.findAll('input[type="text"]')
|
||||
await inputs[0]!.setValue('jellycat') // 品牌
|
||||
await inputs[1]!.setValue('B0Z9X') // ASIN
|
||||
await inputs[2]!.setValue('店A') // 店铺
|
||||
await inputs[3]!.setValue('测试备注') // 备注
|
||||
|
||||
await findButton(modal, '保存')!.trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
expect(gatingApi.createGating).toHaveBeenCalledTimes(1)
|
||||
expect(gatingApi.createGating).toHaveBeenCalledWith({
|
||||
brand: 'jellycat',
|
||||
asin: 'B0Z9X',
|
||||
country: '全部',
|
||||
gatingType: '品牌gating',
|
||||
source: 'MANUAL',
|
||||
shopName: '店A',
|
||||
remark: '测试备注',
|
||||
})
|
||||
})
|
||||
|
||||
it('停用行点恢复 → POST status 载荷 status=1;品牌为空时新增被拦截', async () => {
|
||||
const wrapper = mount(GatingPage)
|
||||
await flushPromises()
|
||||
|
||||
const crocsRow = wrapper
|
||||
.findAll('tbody tr')
|
||||
.find((row) => row.text().includes('crocs'))!
|
||||
await findButton(crocsRow, '恢复')!.trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
expect(gatingApi.updateGatingStatus).toHaveBeenCalledTimes(1)
|
||||
expect(gatingApi.updateGatingStatus).toHaveBeenCalledWith(2, 1)
|
||||
|
||||
// 品牌必填:空品牌提交不发请求
|
||||
await findButton(wrapper, '新增')!.trigger('click')
|
||||
await findButton(wrapper.get('.modal'), '保存')!.trigger('click')
|
||||
await flushPromises()
|
||||
expect(gatingApi.createGating).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,96 @@
|
||||
/**
|
||||
* 工作台客户端包管理页挂载测试:列表渲染、搜索、删除二次确认。
|
||||
* 直传与 Element Plus 弹窗在 mount 环境里用 stub 顶掉,只验页面自己的状态与 API 调用。
|
||||
*/
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { flushPromises, mount } from '@vue/test-utils'
|
||||
|
||||
import WorkbenchClientPackagePage from '@/pages/records/WorkbenchClientPackagePage.vue'
|
||||
|
||||
const api = vi.hoisted(() => ({
|
||||
fetchWorkbenchClientPackages: vi.fn(),
|
||||
uploadWorkbenchClientPackage: vi.fn(),
|
||||
deleteWorkbenchClientPackages: vi.fn(),
|
||||
}))
|
||||
const confirmMock = vi.hoisted(() => vi.fn())
|
||||
const feedbackMock = vi.hoisted(() => vi.fn())
|
||||
const messageMock = vi.hoisted(() => ({ success: vi.fn() }))
|
||||
|
||||
vi.mock('@/pages/records/workbench-client-api.ts', () => api)
|
||||
vi.mock('@/components/admin-confirm', () => ({ openAdminConfirm: confirmMock }))
|
||||
vi.mock('@/components/admin-feedback-ui', () => ({ showAdminFeedback: feedbackMock }))
|
||||
vi.mock('element-plus', () => ({ ElMessage: messageMock }))
|
||||
|
||||
const SHA = 'c'.repeat(64)
|
||||
const row = {
|
||||
id: 7,
|
||||
version: '1.2.3',
|
||||
fileName: 'ShuFuAI-Workbench-1.2.3.zip',
|
||||
objectKey: 'workbench-client/versions/20261024100000123-1.2.3.zip',
|
||||
fileSize: 2048,
|
||||
sha256: SHA,
|
||||
fileUrl: 'https://download.aishufu.top/client/workbench-client/versions/1.2.3.zip',
|
||||
createdAt: '2026-10-24 10:00',
|
||||
}
|
||||
|
||||
const stubs = {
|
||||
'el-dialog': { template: '<div><slot /></div>' },
|
||||
'el-form': { template: '<form><slot /></form>' },
|
||||
'el-form-item': { template: '<div><slot /></div>' },
|
||||
'el-input': {
|
||||
props: ['modelValue'],
|
||||
emits: ['update:modelValue'],
|
||||
template: '<input :value="modelValue" @input="$emit(\'update:modelValue\', $event.target.value)" />',
|
||||
},
|
||||
'el-upload': { template: '<div><slot /></div>' },
|
||||
'el-button': { template: '<button><slot /></button>' },
|
||||
'el-progress': true,
|
||||
'el-alert': { props: ['title'], template: '<div>{{ title }}</div>' },
|
||||
}
|
||||
|
||||
function mountPage() {
|
||||
return mount(WorkbenchClientPackagePage, { global: { stubs } })
|
||||
}
|
||||
|
||||
describe('WorkbenchClientPackagePage', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
api.fetchWorkbenchClientPackages.mockResolvedValue({ items: [row] })
|
||||
api.deleteWorkbenchClientPackages.mockResolvedValue(1)
|
||||
confirmMock.mockResolvedValue(true)
|
||||
})
|
||||
|
||||
it('渲染版本、文件名、sha256 与当前生效标记', async () => {
|
||||
const wrapper = mountPage()
|
||||
await flushPromises()
|
||||
|
||||
const text = wrapper.text()
|
||||
expect(text).toContain('1.2.3')
|
||||
expect(text).toContain('ShuFuAI-Workbench-1.2.3.zip')
|
||||
expect(text).toContain(SHA)
|
||||
expect(text).toContain('当前生效')
|
||||
expect(text).toContain('2.0 KB')
|
||||
})
|
||||
|
||||
it('搜索无命中时显示空态', async () => {
|
||||
const wrapper = mountPage()
|
||||
await flushPromises()
|
||||
|
||||
await wrapper.get('input.workbench-keyword').setValue('9.9.9')
|
||||
await flushPromises()
|
||||
|
||||
expect(wrapper.text()).toContain('暂无匹配客户端包')
|
||||
})
|
||||
|
||||
it('删除单条会二次确认并调用删除接口', async () => {
|
||||
const wrapper = mountPage()
|
||||
await flushPromises()
|
||||
|
||||
await wrapper.get('.ops-cell .btn-danger').trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
expect(confirmMock).toHaveBeenCalledTimes(1)
|
||||
expect(api.deleteWorkbenchClientPackages).toHaveBeenCalledWith([7])
|
||||
expect(api.fetchWorkbenchClientPackages).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
})
|
||||
@@ -36,11 +36,11 @@ const OPS_MIN_COL_PX: Record<string, number> = {
|
||||
'src/pages/asin/ProductCategoryPage.vue': 138,
|
||||
'src/pages/asin/QueryAsinPage.vue': 138,
|
||||
'src/pages/asin/SkipPricePage.vue': 138,
|
||||
'src/pages/gating/GatingPage.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/records/WorkbenchClientPackagePage.vue': 77,
|
||||
'src/pages/shop/ShopKeysPage.vue': 240,
|
||||
'src/pages/shop/ShopManagePage.vue': 199,
|
||||
}
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
formatFileSize,
|
||||
isValidWorkbenchClientVersion,
|
||||
parseWorkbenchClientPackageList,
|
||||
parseWorkbenchClientPackageUpload,
|
||||
WORKBENCH_CLIENT_VERSION_MAX_LENGTH,
|
||||
} from '@/pages/records/workbench-client-model.ts'
|
||||
|
||||
const SHA = 'a'.repeat(64)
|
||||
|
||||
describe('workbench-client model:列表解析', () => {
|
||||
it('解析 snake_case 行并丢弃缺 id 的坏行', () => {
|
||||
const list = parseWorkbenchClientPackageList({
|
||||
success: true,
|
||||
data: {
|
||||
items: [
|
||||
{
|
||||
id: 7,
|
||||
version: '1.2.3',
|
||||
file_name: 'ShuFuAI-Workbench-1.2.3.zip',
|
||||
object_key: 'workbench-client/versions/20261024100000123-1.2.3.zip',
|
||||
file_size: 2048,
|
||||
sha256: SHA,
|
||||
file_url: 'https://download.aishufu.top/client/workbench-client/versions/1.2.3.zip',
|
||||
created_at: '2026-10-24 10:00',
|
||||
},
|
||||
{ version: 'bad-no-id' },
|
||||
],
|
||||
},
|
||||
})
|
||||
|
||||
expect(list.items).toHaveLength(1)
|
||||
expect(list.items[0]).toMatchObject({
|
||||
id: 7,
|
||||
version: '1.2.3',
|
||||
fileName: 'ShuFuAI-Workbench-1.2.3.zip',
|
||||
objectKey: 'workbench-client/versions/20261024100000123-1.2.3.zip',
|
||||
fileSize: 2048,
|
||||
sha256: SHA,
|
||||
fileUrl: 'https://download.aishufu.top/client/workbench-client/versions/1.2.3.zip',
|
||||
createdAt: '2026-10-24 10:00',
|
||||
})
|
||||
})
|
||||
|
||||
it('兼容 camelCase 负载,缺省回空列表', () => {
|
||||
const camel = parseWorkbenchClientPackageList({
|
||||
success: true,
|
||||
data: { items: [{ id: 2, version: '2.0.0', fileName: 'a.zip', fileSize: 10, sha256: SHA, fileUrl: 'u', createdAt: 't' }] },
|
||||
})
|
||||
expect(camel.items[0].fileName).toBe('a.zip')
|
||||
expect(camel.items[0].fileUrl).toBe('u')
|
||||
|
||||
expect(parseWorkbenchClientPackageList({ success: true, data: {} }).items).toEqual([])
|
||||
})
|
||||
|
||||
it('上传返回行取 data.item,缺 item 回 null', () => {
|
||||
const item = parseWorkbenchClientPackageUpload({
|
||||
success: true,
|
||||
data: { item: { id: 3, version: '3.0.0', file_name: 'c.zip', sha256: SHA } },
|
||||
})
|
||||
expect(item?.version).toBe('3.0.0')
|
||||
expect(item?.sha256).toBe(SHA)
|
||||
expect(parseWorkbenchClientPackageUpload({ success: true, data: {} })).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('workbench-client model:版本号与大小', () => {
|
||||
it('版本号必填且不超过后端列宽', () => {
|
||||
expect(isValidWorkbenchClientVersion('')).toBe(false)
|
||||
expect(isValidWorkbenchClientVersion(' ')).toBe(false)
|
||||
expect(isValidWorkbenchClientVersion('1.0.0')).toBe(true)
|
||||
expect(isValidWorkbenchClientVersion('a'.repeat(WORKBENCH_CLIENT_VERSION_MAX_LENGTH))).toBe(true)
|
||||
expect(isValidWorkbenchClientVersion('a'.repeat(WORKBENCH_CLIENT_VERSION_MAX_LENGTH + 1))).toBe(false)
|
||||
})
|
||||
|
||||
it('大小展示与旧页面口径一致', () => {
|
||||
expect(formatFileSize(0)).toBe('—')
|
||||
expect(formatFileSize(2048)).toBe('2.0 KB')
|
||||
expect(formatFileSize(90 * 1024 * 1024)).toBe('90.0 MB')
|
||||
})
|
||||
})
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
package com.nanri.aiimage.common.exception;
|
||||
|
||||
/**
|
||||
* 账号任务已被损耗保护暂停:调用方必须立即停止重试(这不是上游抖动,重试不会变好),
|
||||
* 保留已完成数据,等用户在客户端点「继续任务」后再重跑剩余部分。
|
||||
*/
|
||||
public class TaskPausedException extends RuntimeException {
|
||||
|
||||
public TaskPausedException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
package com.nanri.aiimage.common.retry;
|
||||
|
||||
import cn.hutool.crypto.digest.DigestUtil;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.web.client.HttpStatusCodeException;
|
||||
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.Semaphore;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
|
||||
/**
|
||||
* 同一把 LLM key 的进程内全局请求门:并发上限 + 最小间隔 + 429 共享冷却。
|
||||
*
|
||||
* <p>多个账号配同一把 key 时,provider 的 RPM/TPM 是共享的;如果每个调用各自
|
||||
* 重试,429 会互相放大。这里把并发和节奏收到 key 级别,让排队替代重试:
|
||||
* 正常时几乎不等待,打满时后来者按顺序等,避免全员 429。
|
||||
*
|
||||
* <p>配置(环境变量,默认保守;按 provider 实际额度调):
|
||||
* <ul>
|
||||
* <li>{@code AIIMAGE_LLM_KEY_MAX_CONCURRENCY}:同 key 最大在途数,默认 8</li>
|
||||
* <li>{@code AIIMAGE_LLM_KEY_MIN_INTERVAL_MS}:同 key 两次请求最小间隔,默认 50ms</li>
|
||||
* <li>{@code AIIMAGE_LLM_KEY_ACQUIRE_TIMEOUT_MS}:排队等待上限,默认 120000ms</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>只存 key 的 SHA-256 指纹,不把原文写进 map/日志。
|
||||
*/
|
||||
@Slf4j
|
||||
public final class LlmKeyGate {
|
||||
|
||||
private static final java.util.regex.Pattern POSITIVE = java.util.regex.Pattern.compile("\\d+");
|
||||
|
||||
private static final int MAX_CONCURRENCY =
|
||||
(int) positive("AIIMAGE_LLM_KEY_MAX_CONCURRENCY", 3, 8);
|
||||
private static final long MIN_INTERVAL_NANOS =
|
||||
TimeUnit.MILLISECONDS.toNanos(positive("AIIMAGE_LLM_KEY_MIN_INTERVAL_MS", 9, 50L));
|
||||
private static final long ACQUIRE_TIMEOUT_NANOS =
|
||||
TimeUnit.MILLISECONDS.toNanos(positive("AIIMAGE_LLM_KEY_ACQUIRE_TIMEOUT_MS", 9, 120_000L));
|
||||
|
||||
private static final ConcurrentHashMap<String, Gate> GATES = new ConcurrentHashMap<>();
|
||||
|
||||
private LlmKeyGate() {
|
||||
}
|
||||
|
||||
/** 同 key 的排队许可;close 必须调用(try-with-resources 自动归还)。 */
|
||||
public static final class Permit implements AutoCloseable {
|
||||
private final Gate gate;
|
||||
|
||||
private Permit(Gate gate) {
|
||||
this.gate = gate;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
gate.release();
|
||||
}
|
||||
}
|
||||
|
||||
/** 排队超时:这是本地容量结论,重试只会继续排队,调用方应停止阶梯。 */
|
||||
public static final class QueueTimeoutException extends IllegalStateException {
|
||||
public QueueTimeoutException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
public static Permit acquire(String apiKey) {
|
||||
Gate gate = GATES.computeIfAbsent(fingerprint(apiKey), ignored -> new Gate());
|
||||
return gate.acquire();
|
||||
}
|
||||
|
||||
/** 429 时把同 key 的下一次许可整体后移,避免所有线程同时再撞一次。 */
|
||||
public static void penalizeRateLimited(String apiKey, long millis) {
|
||||
GATES.computeIfAbsent(fingerprint(apiKey), ignored -> new Gate())
|
||||
.penalize(TimeUnit.MILLISECONDS.toNanos(Math.max(0L, millis)));
|
||||
}
|
||||
|
||||
/** 从异常链里识别 HTTP 429;其他异常(超时/5xx)不改变 key 级节奏。 */
|
||||
public static boolean isRateLimited(Throwable error) {
|
||||
Throwable current = error;
|
||||
while (current != null) {
|
||||
if (current instanceof HttpStatusCodeException status
|
||||
&& status.getStatusCode().value() == 429) {
|
||||
return true;
|
||||
}
|
||||
current = current.getCause();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public static void resetForTests() {
|
||||
GATES.clear();
|
||||
}
|
||||
|
||||
private static String fingerprint(String apiKey) {
|
||||
String key = apiKey == null ? "" : apiKey.trim();
|
||||
return DigestUtil.sha256Hex(key);
|
||||
}
|
||||
|
||||
/** 环境变量读数:非纯数字/可能越界/非正一律走默认,坏配置不许把闸门拖崩。 */
|
||||
private static long positive(String name, int maxDigits, long fallback) {
|
||||
String raw = System.getenv().getOrDefault(name, "").trim();
|
||||
if (raw.length() > maxDigits || !POSITIVE.matcher(raw).matches()) {
|
||||
return fallback;
|
||||
}
|
||||
long value = Long.parseLong(raw);
|
||||
return value > 0 ? value : fallback;
|
||||
}
|
||||
|
||||
private static final class Gate {
|
||||
private final Semaphore permits = new Semaphore(MAX_CONCURRENCY);
|
||||
private final Object lock = new Object();
|
||||
private final AtomicLong nextAtNanos = new AtomicLong();
|
||||
|
||||
Permit acquire() {
|
||||
try {
|
||||
if (!permits.tryAcquire(ACQUIRE_TIMEOUT_NANOS, TimeUnit.NANOSECONDS)) {
|
||||
throw new QueueTimeoutException(
|
||||
"LLM key 排队超时(同 key 并发已满,等待上限 "
|
||||
+ TimeUnit.NANOSECONDS.toMillis(ACQUIRE_TIMEOUT_NANOS) + "ms)");
|
||||
}
|
||||
} catch (InterruptedException ex) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new IllegalStateException("LLM key 排队被中断", ex);
|
||||
}
|
||||
try {
|
||||
waitForInterval();
|
||||
return new Permit(this);
|
||||
} catch (RuntimeException ex) {
|
||||
permits.release();
|
||||
throw ex;
|
||||
}
|
||||
}
|
||||
|
||||
void release() {
|
||||
permits.release();
|
||||
}
|
||||
|
||||
void penalize(long nanos) {
|
||||
if (nanos <= 0) {
|
||||
return;
|
||||
}
|
||||
long now = System.nanoTime();
|
||||
nextAtNanos.accumulateAndGet(now + nanos, Math::max);
|
||||
}
|
||||
|
||||
private void waitForInterval() {
|
||||
long interval = MIN_INTERVAL_NANOS;
|
||||
while (interval > 0) {
|
||||
long now = System.nanoTime();
|
||||
long next = nextAtNanos.get();
|
||||
long wait = next - now;
|
||||
if (wait <= 0) {
|
||||
long assigned = now + interval;
|
||||
if (nextAtNanos.compareAndSet(next, assigned)) {
|
||||
return;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
TimeUnit.NANOSECONDS.sleep(Math.min(wait, TimeUnit.MILLISECONDS.toNanos(50)));
|
||||
} catch (InterruptedException ex) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new IllegalStateException("LLM key 间隔等待被中断", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -123,6 +123,8 @@ public class AdminApiGuardFilter extends OncePerRequestFilter {
|
||||
// 2026-09 全维度审查补:内部端点此前仅靠 controller 自校验令牌,纳入守卫后
|
||||
// 不带令牌的请求直接 401(带可信令牌的仍由 doFilterInternal 放行)
|
||||
"/api/internal",
|
||||
// 损耗监控的暂停/继续:uid 只从 JWT 取,匿名请求既读不到状态也不该能解除暂停闸
|
||||
"/api/user/cost-guard",
|
||||
};
|
||||
|
||||
private final AdminAuthSupport adminAuthSupport;
|
||||
|
||||
@@ -77,6 +77,7 @@ public class ApiGuardCoverageAuditor implements SmartInitializingSingleton {
|
||||
"/logout",
|
||||
"/api/version", // 客户端启动时拉最新版本号,必须先于登录
|
||||
"/api/tutorial", // 后台可维护的使用教程,公开内容
|
||||
"/api/workbench-client", // 数富AI工作台客户端更新检查:必须先于登录,公开只读版本元数据
|
||||
"/api/kd-flow/verify", // 开店流程访问密码校验:它自己就是那道门
|
||||
// 下面四条都是 AdminConsoleController 的 302 兜底(response.sendRedirect 完事,
|
||||
// 不读库、不回数据),旧书签打进这些地址只会被送到 /admin-vue/。
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
package com.nanri.aiimage.config;
|
||||
|
||||
import lombok.Data;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
|
||||
/**
|
||||
* 代理 / LLM 损耗保护:按分钟增量与当日累计两条线判定异常,命中即暂停该账号的新任务。
|
||||
*
|
||||
* <p>阈值默认值按「正常批次不该碰、失控循环一定碰」取:品牌补测单批最多百来个品牌,
|
||||
* 一分钟内正常提取几十次;失控时一个账号一分钟能烧到几百上千次。上线后按后台用量
|
||||
* 曲线调整,不把阈值写死在代码里。
|
||||
*/
|
||||
@Data
|
||||
@ConfigurationProperties(prefix = "aiimage.cost-guard")
|
||||
public class CostGuardProperties {
|
||||
|
||||
/** 总开关:关掉只停自动暂停与提示,记账与状态接口仍可用。 */
|
||||
private boolean enabled = true;
|
||||
|
||||
/** 扫描间隔(毫秒);用量是按分钟增量判定的,默认 60 秒。 */
|
||||
private long scanIntervalMs = 60_000L;
|
||||
|
||||
/** 首次扫描延迟(毫秒):避开应用启动时的迁移与预热。 */
|
||||
private long scanInitialDelayMs = 30_000L;
|
||||
|
||||
/** 展示给用户的窗口长度(秒);扫描间隔默认 60 秒,含义是「最近约一分钟增量」。 */
|
||||
private int windowSeconds = 60;
|
||||
|
||||
/** 窗口内代理提取次数阈值;超过即暂停。 */
|
||||
private int proxyWindowThreshold = 600;
|
||||
|
||||
/** 窗口内 LLM 调用次数阈值。 */
|
||||
private int llmWindowCallsThreshold = 180;
|
||||
|
||||
/** 窗口内 LLM token 阈值(prompt + completion)。 */
|
||||
private long llmWindowTokensThreshold = 600_000L;
|
||||
|
||||
/** 当日代理提取次数上限;0=关闭。 */
|
||||
private int dailyProxyThreshold = 8_000;
|
||||
|
||||
/** 当日 LLM 调用次数上限;0=关闭。 */
|
||||
private int dailyLlmCallsThreshold = 6_000;
|
||||
|
||||
/** 当日 LLM token 上限;0=关闭。 */
|
||||
private long dailyLlmTokensThreshold = 20_000_000L;
|
||||
|
||||
/** 同一把代理/LLM 密钥被多少个账号共用时提示;0=关闭。 */
|
||||
private int sharedAccountsThreshold = 3;
|
||||
|
||||
/** 共享密钥扫描间隔(毫秒);首轮随第一次损耗扫描一起跑。 */
|
||||
private long sharedScanIntervalMs = 600_000L;
|
||||
}
|
||||
@@ -4,6 +4,6 @@ import org.springframework.boot.context.properties.EnableConfigurationProperties
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration
|
||||
@EnableConfigurationProperties({OssProperties.class, TransientStorageProperties.class, StorageProperties.class, BrandProgressProperties.class, DeleteBrandProgressProperties.class, BrandCheckProperties.class, ZiniaoProperties.class, ModuleCleanupProperties.class, TaskPressureProperties.class, TaskImageCacheCleanupProperties.class, AppearancePatentProperties.class, SimilarAsinProperties.class, ImageVideoProperties.class, InstanceRoutingProperties.class, CapacityPlanProperties.class, UserSecretProperties.class, NotificationProperties.class, DeviceLogOssProperties.class, CollectDataBrandRecheckProperties.class, ClientCredentialProperties.class})
|
||||
@EnableConfigurationProperties({OssProperties.class, TransientStorageProperties.class, StorageProperties.class, BrandProgressProperties.class, DeleteBrandProgressProperties.class, BrandCheckProperties.class, ZiniaoProperties.class, ModuleCleanupProperties.class, TaskPressureProperties.class, TaskImageCacheCleanupProperties.class, AppearancePatentProperties.class, SimilarAsinProperties.class, ImageVideoProperties.class, InstanceRoutingProperties.class, CapacityPlanProperties.class, UserSecretProperties.class, NotificationProperties.class, DeviceLogOssProperties.class, CollectDataBrandRecheckProperties.class, ClientCredentialProperties.class, CostGuardProperties.class})
|
||||
public class PropertiesConfig {
|
||||
}
|
||||
|
||||
+20
-1
@@ -2,6 +2,7 @@ package com.nanri.aiimage.modules.appearancepatent.client;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.nanri.aiimage.common.retry.LlmKeyGate;
|
||||
import com.nanri.aiimage.common.retry.LlmRetryBackoff;
|
||||
import com.nanri.aiimage.common.retry.UnreachableCooldown;
|
||||
import com.nanri.aiimage.config.AppearancePatentProperties;
|
||||
@@ -156,6 +157,10 @@ public class AppearancePatentLlmClient {
|
||||
private final ExternalCallMetricsRecorder externalCallMetrics;
|
||||
private final BrandCheckClient brandCheckClient;
|
||||
private final UserSecretUsageService userSecretUsageService;
|
||||
|
||||
/** 损耗闸:字段注入避免改动手工构造的 LLM 用例;null=未启用(单测)。 */
|
||||
@org.springframework.beans.factory.annotation.Autowired(required = false)
|
||||
private com.nanri.aiimage.modules.usersecret.service.UserTaskGuardService taskGuard;
|
||||
private final UnreachableCooldown unreachableCooldown;
|
||||
|
||||
private volatile RestClient sharedRestClient;
|
||||
@@ -656,11 +661,21 @@ public class AppearancePatentLlmClient {
|
||||
Exception lastFailure = null;
|
||||
AtomicInteger connectFailures = new AtomicInteger();
|
||||
for (int attempt = 1; attempt <= attempts; attempt++) {
|
||||
try {
|
||||
try (LlmKeyGate.Permit ignored = LlmKeyGate.acquire(apiKey)) {
|
||||
String content = invokeChatOnce(model, system, userText, images, apiKey, responseFormat, attempt);
|
||||
unreachableCooldown.recordConnected(host);
|
||||
return content;
|
||||
} catch (Exception ex) {
|
||||
if (ex instanceof com.nanri.aiimage.common.exception.TaskPausedException paused) {
|
||||
// 暂停是账号级结论,重试不会变好;已完成的行走正常落库
|
||||
throw paused;
|
||||
}
|
||||
if (ex instanceof LlmKeyGate.QueueTimeoutException) {
|
||||
throw (LlmKeyGate.QueueTimeoutException) ex;
|
||||
}
|
||||
if (LlmKeyGate.isRateLimited(ex)) {
|
||||
LlmKeyGate.penalizeRateLimited(apiKey, 2_000L);
|
||||
}
|
||||
lastFailure = ex;
|
||||
if (UnreachableCooldown.isConnectFailure(ex)) {
|
||||
boolean entered = unreachableCooldown.recordConnectFailure(host, cooldownMillis);
|
||||
@@ -1351,6 +1366,10 @@ public class AppearancePatentLlmClient {
|
||||
if (context == null) {
|
||||
return;
|
||||
}
|
||||
if (taskGuard != null && taskGuard.isPaused(context.userId())) {
|
||||
throw new com.nanri.aiimage.common.exception.TaskPausedException(
|
||||
com.nanri.aiimage.modules.usersecret.service.UserTaskGuardService.PAUSED_MESSAGE);
|
||||
}
|
||||
userSecretUsageService.record(context.userId(), UserSecretModule.APPEARANCE_PATENT.key(), 1);
|
||||
}
|
||||
|
||||
|
||||
+8
@@ -109,6 +109,10 @@ public class AppearancePatentTaskService extends AbstractFileTaskPipeline<Appear
|
||||
private final TaskProgressLightAssembler taskProgressLightAssembler;
|
||||
private final UserApiSecretService userApiSecretService;
|
||||
|
||||
/** 损耗闸:字段注入避免改动手工构造器与 golden 用例;null=未启用(单测)。 */
|
||||
@org.springframework.beans.factory.annotation.Autowired(required = false)
|
||||
private com.nanri.aiimage.modules.usersecret.service.UserTaskGuardService taskGuard;
|
||||
|
||||
/**
|
||||
* 参数顺序=迁移前 {@code @RequiredArgsConstructor} 的字段声明顺序,一字未动;
|
||||
* 其中五枚(fileTaskMapper/fileResultMapper/taskDistributedLockService/
|
||||
@@ -196,6 +200,10 @@ public class AppearancePatentTaskService extends AbstractFileTaskPipeline<Appear
|
||||
|
||||
@Transactional
|
||||
public void activateTask(Long taskId, Long userId) {
|
||||
if (taskGuard != null && taskGuard.isPaused(userId)) {
|
||||
throw new com.nanri.aiimage.common.exception.BusinessException(com.nanri.aiimage.modules
|
||||
.usersecret.service.UserTaskGuardService.PAUSED_MESSAGE);
|
||||
}
|
||||
recordSupport().activateTask(taskId, userId);
|
||||
}
|
||||
|
||||
|
||||
+51
-2
@@ -2,6 +2,7 @@ package com.nanri.aiimage.modules.brand.client;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonAlias;
|
||||
import com.nanri.aiimage.config.BrandCheckProperties;
|
||||
import com.nanri.aiimage.modules.brand.support.BrandCheckFailureNotice;
|
||||
import com.nanri.aiimage.modules.usersecret.service.UserApiSecretService;
|
||||
import com.nanri.aiimage.modules.usersecret.support.UserSecretModule;
|
||||
import jakarta.annotation.PreDestroy;
|
||||
@@ -71,6 +72,16 @@ public class BrandCheckClient {
|
||||
private static final int CONNECT_FAILURE_EVIDENCE = 2;
|
||||
private static final String REASON_SERVICE_UNREACHABLE = "品牌检测服务不可达(连接未建立,非本行数据问题)";
|
||||
|
||||
/**
|
||||
* 代理出口被上游拒绝的证据条数:同一批里已有这么多个品牌在换过出口后仍被拒,
|
||||
* 后面的品牌不再发起首轮探针。2026-10-23 现网:16890 每个品牌最多换 2 个 IP,
|
||||
* Java 再按品牌重试 10 轮,一批几千品牌就是几千×2 次提取;这个计数器把
|
||||
* 「整条出口池在被打」的结论限制在前 2 个品牌,其余直接转补测。
|
||||
*/
|
||||
private static final int EGRESS_REJECTED_EVIDENCE = 2;
|
||||
private static final String REASON_EGRESS_REJECTED =
|
||||
"代理出口 IP 连续被商标库拒绝,本批已暂停换 IP";
|
||||
|
||||
/** 用户没配代理时交回的原因文案;采集侧与补测队列都按它把行判查询失败。 */
|
||||
public static final String NO_PROXY_REASON = "用户未配置代理";
|
||||
|
||||
@@ -78,6 +89,13 @@ public class BrandCheckClient {
|
||||
private final com.nanri.aiimage.metrics.ExternalCallMetricsRecorder externalCallMetrics;
|
||||
private final UserApiSecretService userApiSecretService;
|
||||
private final com.nanri.aiimage.common.retry.UnreachableCooldown unreachableCooldown;
|
||||
|
||||
/**
|
||||
* 损耗暂停闸用字段注入:本类在单测里被大量手工 new(4 参构造),把闸门塞进构造器
|
||||
* 会让每条用例都多传一个 null。生产由 Spring 注入,单测里为 null 时按未暂停处理。
|
||||
*/
|
||||
@org.springframework.beans.factory.annotation.Autowired(required = false)
|
||||
private com.nanri.aiimage.modules.usersecret.service.UserTaskGuardService taskGuard;
|
||||
/** 提交线程上的拒绝标记:队列满时由拒绝策略置位,提交方据此立即降级(不新增 catch 出口)。 */
|
||||
private final ThreadLocal<AtomicBoolean> rejectedSubmission = new ThreadLocal<>();
|
||||
private volatile RestClient sharedRestClient;
|
||||
@@ -260,6 +278,16 @@ public class BrandCheckClient {
|
||||
// 整批共用一个耗时预算:上游 16890 卡死时,单品牌 10 次重试曾把一次分片回传拖到
|
||||
// 103.5 秒(taskId 28599),客户端重试预算耗尽后中止了整个采集。预算用尽即停止重试。
|
||||
Map<String, BrandCheckOutcome> outcomes = new LinkedHashMap<>();
|
||||
if (taskGuard != null && taskGuard.isPaused(userId)) {
|
||||
// 损耗闸已落下:整批一个请求都不发,结论按查询失败留待补测;重试不会让暂停变好
|
||||
log.warn("[brand-check] 账号任务已暂停,整批不打上游 userId={} 品牌数={}",
|
||||
userId, brands.size());
|
||||
for (String brand : brands) {
|
||||
outcomes.put(brand, new BrandCheckOutcome(List.of(), List.of(brand),
|
||||
com.nanri.aiimage.modules.usersecret.service.UserTaskGuardService.PAUSED_MESSAGE));
|
||||
}
|
||||
return outcomes;
|
||||
}
|
||||
String proxyUrl = proxyUrlFor(userId);
|
||||
if (proxyUrl.isBlank()) {
|
||||
// 缺代理整批一个请求都不发:这是配置问题,十条重试阶梯在这里只会白烧,
|
||||
@@ -293,6 +321,8 @@ public class BrandCheckClient {
|
||||
// 连接层证据跨品牌累计:批内任一次成功响应清零(见 checkOneBrand)。
|
||||
// 一次批量一份,不跨批复用——另一批的 upstreamRejecting 也是这个理由。
|
||||
AtomicInteger connectFailures = new AtomicInteger();
|
||||
// 出口被上游拒绝的证据跨品牌累计:达到阈值后不再给后续品牌发首轮探针。
|
||||
AtomicInteger egressRejections = new AtomicInteger();
|
||||
for (String brand : brands) {
|
||||
AtomicBoolean started = new AtomicBoolean(false);
|
||||
AtomicBoolean rejected = new AtomicBoolean(false);
|
||||
@@ -303,7 +333,7 @@ public class BrandCheckClient {
|
||||
() -> {
|
||||
started.set(true);
|
||||
return checkOneBrand(brand, strategy, deadlineNanos, upstreamRejecting,
|
||||
proxyUrl, userId, connectFailures);
|
||||
proxyUrl, userId, connectFailures, egressRejections);
|
||||
},
|
||||
checkExecutor);
|
||||
} finally {
|
||||
@@ -333,7 +363,8 @@ public class BrandCheckClient {
|
||||
|
||||
private BrandCheckOutcome checkOneBrand(String brand, String strategy, long deadlineNanos,
|
||||
AtomicBoolean upstreamRejecting, String proxyUrl, Long userId,
|
||||
AtomicInteger connectFailures) {
|
||||
AtomicInteger connectFailures,
|
||||
AtomicInteger egressRejections) {
|
||||
int attempts = Math.max(1, properties.getRetryTimes());
|
||||
BrandCheckResponse response = null;
|
||||
Exception lastFailure = null;
|
||||
@@ -352,6 +383,14 @@ public class BrandCheckClient {
|
||||
lastFailure == null ? "query_faild_data 持续非空" : lastFailure.getMessage());
|
||||
break;
|
||||
}
|
||||
// 出口池已被上游连续拒绝:后面的品牌连首轮探针都不发。与 upstreamRejecting
|
||||
// 不同,这里允许在 attempt=1 就短路——前 2 个品牌已经各烧过出口 IP,再让
|
||||
// 每个品牌各打一次只是把同一笔失败摊成品牌数×2 的提取费。
|
||||
if (egressRejections.get() >= EGRESS_REJECTED_EVIDENCE) {
|
||||
log.warn("[brand-check] 代理出口已被连续拒绝 {} 次,本品牌不再换 IP brand={} attempt={}/{}",
|
||||
egressRejections.get(), brand, attempt, attempts);
|
||||
return queryFailedOutcome(brand, REASON_EGRESS_REJECTED);
|
||||
}
|
||||
// 同批已有品牌走完整个阶梯、每一轮都被判查询失败 ⇒ 上游在确定性拒绝,本品牌别再烧
|
||||
// 等待与整批预算。2026-10-19 现网:品牌库代理套餐过期 → 16890 全部直连 WIPO →
|
||||
// 整片 Forbidden,单品牌 10 轮含递增等待约 45~65 秒全是白烧,而它烧掉的正是后面
|
||||
@@ -411,6 +450,16 @@ public class BrandCheckClient {
|
||||
if (response.getReason() != null && !response.getReason().isBlank()) {
|
||||
reason = response.getReason().trim();
|
||||
}
|
||||
if (BrandCheckFailureNotice.isEgressRejected(reason)) {
|
||||
// 这个品牌已经换过出口仍被拒:停止它自己的阶梯,并累计批级证据。
|
||||
// 16890 侧也有出口熔断,两层都只省“继续换 IP”的钱,不改“这行没查成”的结论。
|
||||
ladderCompleted = false;
|
||||
upstreamRejecting.set(true);
|
||||
int seen = egressRejections.incrementAndGet();
|
||||
log.warn("[brand-check] 代理出口被上游拒绝(本批第 {} 次),停止换 IP brand={} attempt={}/{} reason={}",
|
||||
seen, brand, attempt, attempts, reason);
|
||||
break;
|
||||
}
|
||||
if (response != null && !response.isRetryable()) {
|
||||
// 上游当场判定"重试也不会变好"(供应商拒付、套餐过期、这类结论是确定的),
|
||||
// 阶梯到此为止并把同批一起短路——旧版这里要跑满 10 轮、约 45~65 秒才知道
|
||||
|
||||
+6
@@ -70,6 +70,12 @@ public final class BrandCheckFailureNotice {
|
||||
return Kind.UPSTREAM;
|
||||
}
|
||||
|
||||
/** 原始原因是否属于「代理出口 IP 被上游拒绝」。批量熔断共用这一份判据。 */
|
||||
public static boolean isEgressRejected(String rawReason) {
|
||||
String reason = rawReason == null ? "" : rawReason.trim();
|
||||
return !reason.isEmpty() && EGRESS_REJECTED.matcher(reason).find();
|
||||
}
|
||||
|
||||
/** 用户可读的那一句:先说发生了什么,再说该做什么。 */
|
||||
public static String userMessage(Kind kind) {
|
||||
if (kind == null) {
|
||||
|
||||
+11
@@ -59,6 +59,10 @@ public class CollectDataBrandRecheckScheduler {
|
||||
private final TaskFileJobService taskFileJobService;
|
||||
private final DistributedJobLockService distributedJobLockService;
|
||||
|
||||
/** 损耗闸:字段注入避免改动手工构造的调度器用例;null=未启用(单测)。 */
|
||||
@org.springframework.beans.factory.annotation.Autowired(required = false)
|
||||
private com.nanri.aiimage.modules.usersecret.service.UserTaskGuardService taskGuard;
|
||||
|
||||
@Scheduled(fixedDelayString = "${aiimage.collect-data.brand-recheck.scan-interval-ms:300000}",
|
||||
initialDelayString = "${aiimage.collect-data.brand-recheck.scan-initial-delay-ms:120000}")
|
||||
public void scan() {
|
||||
@@ -124,6 +128,13 @@ public class CollectDataBrandRecheckScheduler {
|
||||
}
|
||||
return new GroupRound(0, 0);
|
||||
}
|
||||
if (taskGuard != null && taskGuard.isPaused(task.getUserId())) {
|
||||
// 暂停不消耗尝试次数:用户排查完点继续后,这批条目应按原退避节奏重新到期
|
||||
recheckService.postponeWithoutAttempt(entries, properties.getIntervalBaseMinutes());
|
||||
log.info("[brand-recheck] 账号任务已暂停,整组顺延 taskId={} userId={} 条目={}",
|
||||
taskId, task.getUserId(), entries.size());
|
||||
return new GroupRound(0, 0);
|
||||
}
|
||||
if (!STATUS_SUCCESS.equals(task.getStatus()) && !STATUS_FAILED.equals(task.getStatus())) {
|
||||
// 任务仍在跑:补测只做终态之后的兜底,顺延不计数(避免与分片重提竞态)
|
||||
recheckService.postponeWithoutAttempt(entries, properties.getFirstDelayMinutes());
|
||||
|
||||
+96
-46
@@ -20,9 +20,13 @@ import org.springframework.stereotype.Service;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.File;
|
||||
import java.io.InputStream;
|
||||
import java.net.URI;
|
||||
import java.net.URLDecoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.util.HexFormat;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Objects;
|
||||
@@ -42,6 +46,8 @@ public class OssStorageService {
|
||||
private static final String SOFTWARE_VERSION_PREFIX = "nanri-image/versions/";
|
||||
/** 教程安装包对象键前缀(公开 client 桶,工具台「立即下载教程」直链来源)。 */
|
||||
private static final String TUTORIAL_PREFIX = "tutorial/";
|
||||
/** 数富AI工作台客户端安装/更新包前缀(公开 client 桶,独立于桌面端 nanri-image/versions/)。 */
|
||||
private static final String WORKBENCH_CLIENT_PREFIX = "workbench-client/versions/";
|
||||
private static final String LEGACY_MINIO_ENDPOINT = "http://47.110.241.161:9000";
|
||||
/** readObjectBytes 兜底读取上限(20MB):防止大对象一次性读入内存导致 OOM。 */
|
||||
private static final long DEFAULT_READ_MAX_BYTES = 20L * 1024 * 1024;
|
||||
@@ -191,12 +197,11 @@ public class OssStorageService {
|
||||
}
|
||||
|
||||
/**
|
||||
* 为软件版本安装包签发浏览器直传用的预签名 PUT URL(client 桶公开路径)。
|
||||
* 签名 host 取 public-endpoint(oss.aishufu.top),浏览器对返回的 URL 直接 PUT 即可落对象;
|
||||
* 服务端自己的读写走 internal-endpoint 那张 client,两者不能合用一张。
|
||||
* 公开 client 桶直传预签名共用实现:桌面端版本 / 教程 / 工作台客户端三族只差前缀守卫。
|
||||
* 签名 host 取 public-endpoint(oss.aishufu.top),浏览器拿到后直接 PUT;不能用内网 client 签。
|
||||
*/
|
||||
public String presignSoftwareVersionUpload(String objectKey, int expirySeconds) {
|
||||
requirePrefixedObjectKey(objectKey, SOFTWARE_VERSION_PREFIX, "software version");
|
||||
private String presignPublicClientUpload(String objectKey, String prefix, String what, int expirySeconds) {
|
||||
requirePrefixedObjectKey(objectKey, prefix, what);
|
||||
try {
|
||||
return presignClient().getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder()
|
||||
.method(Method.PUT)
|
||||
@@ -209,9 +214,18 @@ public class OssStorageService {
|
||||
}
|
||||
}
|
||||
|
||||
/** 返回软件版本对象的字节数;对象不存在返回 -1(直传完成后由服务端核对大小是否超限)。 */
|
||||
public long softwareVersionObjectSize(String objectKey) {
|
||||
requirePrefixedObjectKey(objectKey, SOFTWARE_VERSION_PREFIX, "software version");
|
||||
/**
|
||||
* 为软件版本安装包签发浏览器直传用的预签名 PUT URL(client 桶公开路径)。
|
||||
* 签名 host 取 public-endpoint(oss.aishufu.top),浏览器对返回的 URL 直接 PUT 即可落对象;
|
||||
* 服务端自己的读写走 internal-endpoint 那张 client,两者不能合用一张。
|
||||
*/
|
||||
public String presignSoftwareVersionUpload(String objectKey, int expirySeconds) {
|
||||
return presignPublicClientUpload(objectKey, SOFTWARE_VERSION_PREFIX, "software version", expirySeconds);
|
||||
}
|
||||
|
||||
/** 公开 client 桶对象大小共用实现:对象不存在返回 -1(直传确认时先卡大小)。 */
|
||||
private long publicClientObjectSize(String objectKey, String prefix, String what) {
|
||||
requirePrefixedObjectKey(objectKey, prefix, what);
|
||||
try {
|
||||
var stat = buildClient().statObject(StatObjectArgs.builder()
|
||||
.bucket(publicClientBucket())
|
||||
@@ -228,6 +242,11 @@ public class OssStorageService {
|
||||
}
|
||||
}
|
||||
|
||||
/** 返回软件版本对象的字节数;对象不存在返回 -1(直传完成后由服务端核对大小是否超限)。 */
|
||||
public long softwareVersionObjectSize(String objectKey) {
|
||||
return publicClientObjectSize(objectKey, SOFTWARE_VERSION_PREFIX, "software version");
|
||||
}
|
||||
|
||||
/** 生成软件版本对象的公开下载 URL(与历史 file_url 同构:path-style client 桶)。 */
|
||||
public String getSoftwareVersionDownloadUrl(String objectKey) {
|
||||
requirePrefixedObjectKey(objectKey, SOFTWARE_VERSION_PREFIX, "software version");
|
||||
@@ -246,9 +265,9 @@ public class OssStorageService {
|
||||
: buildPublicUrl(base, objectKey, publicClientBucket());
|
||||
}
|
||||
|
||||
/** 删除软件版本对象(client 桶);确认环节发现超限等异常时清理残留,避免公共桶悬挂大对象。 */
|
||||
public void removeSoftwareVersionObject(String objectKey) {
|
||||
requirePrefixedObjectKey(objectKey, SOFTWARE_VERSION_PREFIX, "software version");
|
||||
/** 公开 client 桶对象删除共用实现;后台删除记录时清理无引用对象。 */
|
||||
private void removePublicClientObject(String objectKey, String prefix, String what) {
|
||||
requirePrefixedObjectKey(objectKey, prefix, what);
|
||||
try {
|
||||
buildClient().removeObject(RemoveObjectArgs.builder()
|
||||
.bucket(publicClientBucket())
|
||||
@@ -259,41 +278,22 @@ public class OssStorageService {
|
||||
}
|
||||
}
|
||||
|
||||
/** 删除软件版本对象(client 桶);确认环节发现超限等异常时清理残留,避免公共桶悬挂大对象。 */
|
||||
public void removeSoftwareVersionObject(String objectKey) {
|
||||
removePublicClientObject(objectKey, SOFTWARE_VERSION_PREFIX, "software version");
|
||||
}
|
||||
|
||||
/**
|
||||
* 为教程安装包签发浏览器直传用的预签名 PUT URL(公开 client 桶 tutorial/ 前缀)。
|
||||
* 签名 host 同 {@link #presignSoftwareVersionUpload}:必须是公网入口,不能用内网 client。
|
||||
*/
|
||||
public String presignTutorialUpload(String objectKey, int expirySeconds) {
|
||||
requireTutorialKey(objectKey);
|
||||
try {
|
||||
return presignClient().getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder()
|
||||
.method(Method.PUT)
|
||||
.bucket(publicClientBucket())
|
||||
.object(objectKey)
|
||||
.expiry(Math.max(60, expirySeconds), TimeUnit.SECONDS)
|
||||
.build());
|
||||
} catch (Exception ex) {
|
||||
throw storageFailure("presign", objectKey, ex);
|
||||
}
|
||||
return presignPublicClientUpload(objectKey, TUTORIAL_PREFIX, "tutorial", expirySeconds);
|
||||
}
|
||||
|
||||
/** 返回教程对象的字节数;对象不存在返回 -1(直传完成后由服务端核对大小是否超限)。 */
|
||||
public long tutorialObjectSize(String objectKey) {
|
||||
requireTutorialKey(objectKey);
|
||||
try {
|
||||
var stat = buildClient().statObject(StatObjectArgs.builder()
|
||||
.bucket(publicClientBucket())
|
||||
.object(objectKey)
|
||||
.build());
|
||||
return stat.size();
|
||||
} catch (ErrorResponseException ex) {
|
||||
if (isNotFound(ex)) {
|
||||
return -1L;
|
||||
}
|
||||
throw storageFailure("stat", objectKey, ex);
|
||||
} catch (Exception ex) {
|
||||
throw storageFailure("stat", objectKey, ex);
|
||||
}
|
||||
return publicClientObjectSize(objectKey, TUTORIAL_PREFIX, "tutorial");
|
||||
}
|
||||
|
||||
/** 生成教程对象的公开下载 URL(与历史直链同构:https://oss.aishufu.top/client/tutorial/...)。 */
|
||||
@@ -304,21 +304,71 @@ public class OssStorageService {
|
||||
|
||||
/** 删除教程对象(client 桶);后台删除记录时清理无引用对象。 */
|
||||
public void removeTutorialObject(String objectKey) {
|
||||
requireTutorialKey(objectKey);
|
||||
try {
|
||||
buildClient().removeObject(RemoveObjectArgs.builder()
|
||||
.bucket(publicClientBucket())
|
||||
.object(objectKey)
|
||||
.build());
|
||||
} catch (Exception ex) {
|
||||
throw storageFailure("delete", objectKey, ex);
|
||||
}
|
||||
removePublicClientObject(objectKey, TUTORIAL_PREFIX, "tutorial");
|
||||
}
|
||||
|
||||
private void requireTutorialKey(String objectKey) {
|
||||
requirePrefixedObjectKey(objectKey, TUTORIAL_PREFIX, "tutorial");
|
||||
}
|
||||
|
||||
/**
|
||||
* 为工作台客户端包签发浏览器直传 PUT 预签名(client 桶 workbench-client/versions/ 前缀)。
|
||||
* 签名 host 与软件版本/教程包一致:必须走公网入口,不能拿内网 client 签。
|
||||
*/
|
||||
public String presignWorkbenchClientUpload(String objectKey, int expirySeconds) {
|
||||
return presignPublicClientUpload(objectKey, WORKBENCH_CLIENT_PREFIX, "workbench client", expirySeconds);
|
||||
}
|
||||
|
||||
/** 返回工作台客户端包字节数;对象不存在返回 -1(直传确认时先卡大小,再算摘要)。 */
|
||||
public long workbenchClientObjectSize(String objectKey) {
|
||||
return publicClientObjectSize(objectKey, WORKBENCH_CLIENT_PREFIX, "workbench client");
|
||||
}
|
||||
|
||||
/**
|
||||
* 服务端流式复算工作台客户端包的 sha256(hex 小写)。
|
||||
* 直传路径不能相信浏览器报的摘要:这条摘要是客户端更新时的硬校验锚点,必须对 MinIO 实物算。
|
||||
*/
|
||||
public String workbenchClientObjectSha256(String objectKey) {
|
||||
requireWorkbenchClientKey(objectKey);
|
||||
MessageDigest digest;
|
||||
try {
|
||||
digest = MessageDigest.getInstance("SHA-256");
|
||||
} catch (NoSuchAlgorithmException ex) {
|
||||
throw new IllegalStateException("SHA-256 not available", ex);
|
||||
}
|
||||
try (InputStream stream = buildClient().getObject(GetObjectArgs.builder()
|
||||
.bucket(publicClientBucket())
|
||||
.object(objectKey)
|
||||
.build())) {
|
||||
byte[] buffer = new byte[1 << 20];
|
||||
int read;
|
||||
while ((read = stream.read(buffer)) > 0) {
|
||||
digest.update(buffer, 0, read);
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
throw storageFailure("sha256", objectKey, ex);
|
||||
}
|
||||
return HexFormat.of().formatHex(digest.digest());
|
||||
}
|
||||
|
||||
/** 工作台客户端包公开下载 URL:优先 download-endpoint(主机 B 反代回源),未配置回退 public-endpoint。 */
|
||||
public String getWorkbenchClientDownloadUrl(String objectKey) {
|
||||
requireWorkbenchClientKey(objectKey);
|
||||
String base = downloadEndpoint();
|
||||
return base == null
|
||||
? getPublicUrl(objectKey, publicClientBucket())
|
||||
: buildPublicUrl(base, objectKey, publicClientBucket());
|
||||
}
|
||||
|
||||
/** 删除工作台客户端包对象(client 桶);后台删除记录时清理无引用对象。 */
|
||||
public void removeWorkbenchClientObject(String objectKey) {
|
||||
removePublicClientObject(objectKey, WORKBENCH_CLIENT_PREFIX, "workbench client");
|
||||
}
|
||||
|
||||
private void requireWorkbenchClientKey(String objectKey) {
|
||||
requirePrefixedObjectKey(objectKey, WORKBENCH_CLIENT_PREFIX, "workbench client");
|
||||
}
|
||||
|
||||
/** objectKey 前缀守卫:软件版本族与教程族八格同款,只是前缀与文案里的名字不同。 */
|
||||
private void requirePrefixedObjectKey(String objectKey, String prefix, String what) {
|
||||
if (objectKey == null || !objectKey.startsWith(prefix)) {
|
||||
|
||||
+6
@@ -60,6 +60,10 @@ public class NotificationService {
|
||||
public static final String SCENE_SERVICE_DOWN = "service_down";
|
||||
/** 麦象(18960 任务调度)异常:任务停滞/失败/队列积压。 */
|
||||
public static final String SCENE_MAIXIANG_ANOMALY = "maixiang_anomaly";
|
||||
/** 代理/LLM 消耗异常,账号任务已被自动暂停。 */
|
||||
public static final String SCENE_COST_GUARD = "cost_guard";
|
||||
/** 同一把代理/LLM 密钥被过多账号共用。 */
|
||||
public static final String SCENE_SECRET_SHARED = "secret_shared";
|
||||
public static final String SCENE_SYSTEM = "system";
|
||||
|
||||
/**
|
||||
@@ -78,10 +82,12 @@ public class NotificationService {
|
||||
private static final Map<String, String> SCENE_TO_CATEGORY = Map.of(
|
||||
SCENE_SERVICE_DOWN, CATEGORY_SYSTEM_ERROR,
|
||||
SCENE_MAIXIANG_ANOMALY, CATEGORY_SYSTEM_ERROR,
|
||||
SCENE_COST_GUARD, CATEGORY_SYSTEM_ERROR,
|
||||
SCENE_TASK_FAILED, CATEGORY_TASK_ERROR,
|
||||
SCENE_TASK_PARTIAL, CATEGORY_TASK_ERROR,
|
||||
SCENE_SECRET_BALANCE, CATEGORY_CONFIG_ERROR,
|
||||
SCENE_SECRET_INVALID, CATEGORY_CONFIG_ERROR,
|
||||
SCENE_SECRET_SHARED, CATEGORY_CONFIG_ERROR,
|
||||
SCENE_SYSTEM, CATEGORY_SYSTEM_NOTICE);
|
||||
|
||||
private static final long MAX_PAGE_SIZE = 100L;
|
||||
|
||||
+2
-2
@@ -82,7 +82,6 @@ public class PermissionMenuSchemaInitializer {
|
||||
new DefaultAdminMenu("品牌数据库", "admin_invalid_asin_data", "invalid-asin-data", 35, "admin_group_data"),
|
||||
new DefaultAdminMenu("查询ASIN", "admin_query_asin", "query-asin", 65, "admin_group_data"),
|
||||
new DefaultAdminMenu("商品类目", "admin_product_categories", "product-categories", 66, "admin_group_data"),
|
||||
new DefaultAdminMenu("品牌Gating库", "admin_brand_gating", "brand-gating", 36, "admin_group_data"),
|
||||
new DefaultAdminMenu("店铺密钥管理", "admin_shop_keys", "shop-keys", 40, "admin_group_shop"),
|
||||
new DefaultAdminMenu("店铺管理", "admin_shop_manage", "shop-manage", 50, "admin_group_shop"),
|
||||
new DefaultAdminMenu("最低价ASIN设置", "admin_skip_price_asin", "skip-price-asin", 60, "admin_group_shop"),
|
||||
@@ -91,7 +90,8 @@ public class PermissionMenuSchemaInitializer {
|
||||
new DefaultAdminMenu("生成记录", "admin_history", "history", 70, "admin_group_record"),
|
||||
new DefaultAdminMenu("视频任务记录", "admin_image_video_tasks", "image-video-tasks", 75, "admin_group_record"),
|
||||
new DefaultAdminMenu("软件版本管理", "admin_version", "version", 80, "admin_group_record"),
|
||||
new DefaultAdminMenu("数字人版本管理", "digital_human_version", "digital-human-version", 81, "admin_group_record")
|
||||
new DefaultAdminMenu("数字人版本管理", "digital_human_version", "digital-human-version", 81, "admin_group_record"),
|
||||
new DefaultAdminMenu("工作台客户端包管理", "admin_workbench_client_package", "records/workbench-client-package", 83, "admin_group_record")
|
||||
);
|
||||
|
||||
@EventListener(ApplicationReadyEvent.class)
|
||||
|
||||
+2
-2
@@ -58,7 +58,7 @@ public class PermissionMenuService {
|
||||
|
||||
/**
|
||||
* 管理/平台配置类菜单:出口仍是 {@code requireAdmin}(用户、菜单、分组、密钥、公司、版本、教程、
|
||||
* 日志),普通账号即使被勾了也用不了。
|
||||
* 工作台客户端包、日志),普通账号即使被勾了也用不了。
|
||||
*
|
||||
* <p>2026-10-06 入口放开后必须与下发集一起剪:现网实查有 13 个普通账号带着 {@code admin_users}、
|
||||
* 11 个带 {@code admin_user_secrets}、9 个带 {@code admin_version} 的授权行,只在出口拦而照常下发
|
||||
@@ -69,7 +69,7 @@ public class PermissionMenuService {
|
||||
"admin_users", "admin_columns", "admin_group_manage",
|
||||
"admin_user_secrets", "admin_user_secret_usage",
|
||||
"admin_version", "digital_human_version", "admin_tutorial",
|
||||
"admin_device_logs");
|
||||
"admin_workbench_client_package", "admin_device_logs");
|
||||
|
||||
private final PermissionMenuMapper permissionMenuMapper;
|
||||
private final UserColumnPermissionMapper userColumnPermissionMapper;
|
||||
|
||||
+9
@@ -58,6 +58,10 @@ public class PriceTrackLoopRunService {
|
||||
private final PriceTrackLoopRunMapper loopRunMapper;
|
||||
private final FileTaskMapper fileTaskMapper;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
/** 损耗闸:字段注入避免改动手工 new 的 7 处测试构造器;null=未启用(单测)。 */
|
||||
@org.springframework.beans.factory.annotation.Autowired(required = false)
|
||||
private com.nanri.aiimage.modules.usersecret.service.UserTaskGuardService taskGuard;
|
||||
private final ZiniaoShopSwitchService ziniaoShopSwitchService;
|
||||
|
||||
@Transactional
|
||||
@@ -104,6 +108,11 @@ public class PriceTrackLoopRunService {
|
||||
|
||||
@Transactional
|
||||
public PriceTrackLoopRunDispatchVo dispatchNext(Long loopRunId, Long userId) {
|
||||
if (taskGuard != null && taskGuard.isPaused(userId)) {
|
||||
// 不把循环标成 STOPPED:暂停只停派发,恢复后同一条循环还能接着跑
|
||||
throw new BusinessException(com.nanri.aiimage.modules.usersecret.service
|
||||
.UserTaskGuardService.PAUSED_MESSAGE);
|
||||
}
|
||||
PriceTrackLoopRunEntity entity = getOwnedLoopRun(loopRunId, userId);
|
||||
reconcileWithTerminalChild(entity);
|
||||
if (isTerminal(entity.getStatus())) {
|
||||
|
||||
+22
-1
@@ -2,6 +2,7 @@ package com.nanri.aiimage.modules.similarasin.client;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.nanri.aiimage.common.retry.LlmKeyGate;
|
||||
import com.nanri.aiimage.common.retry.LlmRetryBackoff;
|
||||
import com.nanri.aiimage.common.retry.UnreachableCooldown;
|
||||
import com.nanri.aiimage.config.HttpClientPool;
|
||||
@@ -50,6 +51,10 @@ public class SimilarAsinLlmClient {
|
||||
private final ObjectMapper objectMapper;
|
||||
private final ExternalCallMetricsRecorder externalCallMetrics;
|
||||
private final UserSecretUsageService userSecretUsageService;
|
||||
|
||||
/** 损耗闸:字段注入避免改动手工构造的 LLM 用例;null=未启用(单测)。 */
|
||||
@org.springframework.beans.factory.annotation.Autowired(required = false)
|
||||
private com.nanri.aiimage.modules.usersecret.service.UserTaskGuardService taskGuard;
|
||||
private final UnreachableCooldown unreachableCooldown;
|
||||
|
||||
private volatile RestClient sharedRestClient;
|
||||
@@ -97,11 +102,23 @@ public class SimilarAsinLlmClient {
|
||||
Exception lastFailure = null;
|
||||
int connectFailures = 0;
|
||||
for (int attempt = 1; attempt <= attempts; attempt++) {
|
||||
try {
|
||||
try (LlmKeyGate.Permit ignored = LlmKeyGate.acquire(resolvedKey)) {
|
||||
String content = invokeChatOnce(model, system, userText, images, resolvedKey, responseFormat, attempt);
|
||||
unreachableCooldown.recordConnected(host);
|
||||
return content;
|
||||
} catch (Exception ex) {
|
||||
if (ex instanceof com.nanri.aiimage.common.exception.TaskPausedException paused) {
|
||||
// 暂停是账号级结论,重试不会变好;已完成的行走正常落库
|
||||
throw paused;
|
||||
}
|
||||
if (ex instanceof LlmKeyGate.QueueTimeoutException) {
|
||||
// 本地 key 容量已满:重试只会继续排队,直接交给行级失败
|
||||
throw (LlmKeyGate.QueueTimeoutException) ex;
|
||||
}
|
||||
if (LlmKeyGate.isRateLimited(ex)) {
|
||||
// 429 时把同 key 的下一次许可整体后移,避免所有调用一起再撞
|
||||
LlmKeyGate.penalizeRateLimited(resolvedKey, 2_000L);
|
||||
}
|
||||
lastFailure = ex;
|
||||
if (UnreachableCooldown.isConnectFailure(ex)) {
|
||||
connectFailures++;
|
||||
@@ -344,6 +361,10 @@ public class SimilarAsinLlmClient {
|
||||
if (context == null) {
|
||||
return;
|
||||
}
|
||||
if (taskGuard != null && taskGuard.isPaused(context.userId())) {
|
||||
throw new com.nanri.aiimage.common.exception.TaskPausedException(
|
||||
com.nanri.aiimage.modules.usersecret.service.UserTaskGuardService.PAUSED_MESSAGE);
|
||||
}
|
||||
userSecretUsageService.record(context.userId(), UserSecretModule.SIMILAR_ASIN.key(), 1);
|
||||
}
|
||||
|
||||
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
package com.nanri.aiimage.modules.usersecret.controller;
|
||||
|
||||
import com.nanri.aiimage.common.api.ApiResponse;
|
||||
import com.nanri.aiimage.common.security.AdminAuthSupport;
|
||||
import com.nanri.aiimage.modules.usersecret.model.vo.CostGuardStatusVo;
|
||||
import com.nanri.aiimage.modules.usersecret.service.CostGuardService;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
/**
|
||||
* 桌面端损耗监控:身份一律取自 JWT,不接受前端传 uid。
|
||||
* 前端每 30 秒轮询 status;暂停时弹窗,用户排查后点「继续任务」调 resume。
|
||||
*/
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
@RequestMapping("/api/user/cost-guard")
|
||||
@Tag(name = "损耗监控(桌面端)", description = "代理/LLM 异常消耗的暂停状态与手动继续。")
|
||||
public class UserCostGuardController {
|
||||
|
||||
private final CostGuardService costGuardService;
|
||||
private final AdminAuthSupport adminAuthSupport;
|
||||
|
||||
@GetMapping("/status")
|
||||
@Operation(summary = "读取当前账号的损耗监控状态")
|
||||
public ApiResponse<CostGuardStatusVo> status(HttpServletRequest request) {
|
||||
return ApiResponse.success(costGuardService.status(currentUserId(request)));
|
||||
}
|
||||
|
||||
@PostMapping("/resume")
|
||||
@Operation(summary = "排查后继续任务", description = "只清暂停闸与损耗基线,不删除已完成任务和结果行。")
|
||||
public ApiResponse<CostGuardStatusVo> resume(HttpServletRequest request) {
|
||||
return ApiResponse.success("已继续任务", costGuardService.resume(currentUserId(request)));
|
||||
}
|
||||
|
||||
private Long currentUserId(HttpServletRequest request) {
|
||||
return adminAuthSupport.requireUser(request).getId();
|
||||
}
|
||||
}
|
||||
+12
@@ -1,11 +1,13 @@
|
||||
package com.nanri.aiimage.modules.usersecret.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.nanri.aiimage.modules.usersecret.model.dto.UserSecretUsageAggregate;
|
||||
import com.nanri.aiimage.modules.usersecret.model.entity.UserSecretUsageEntity;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.util.List;
|
||||
|
||||
@Mapper
|
||||
public interface UserSecretUsageMapper extends BaseMapper<UserSecretUsageEntity> {
|
||||
@@ -33,6 +35,16 @@ public interface UserSecretUsageMapper extends BaseMapper<UserSecretUsageEntity>
|
||||
@Param("promptTokens") long promptTokens,
|
||||
@Param("completionTokens") long completionTokens);
|
||||
|
||||
/**
|
||||
* 当日用量按用户 × 模块聚合(损耗扫描每分钟读一次)。
|
||||
* 表是「用户 × 模块 × 天」的日聚合,行数 = 用户数 × 3,全量 GROUP BY 成本可忽略。
|
||||
*/
|
||||
List<UserSecretUsageAggregate> sumByUserAndModule(@Param("businessDate") LocalDate businessDate);
|
||||
|
||||
/** 单个用户的当日读数:客户端状态接口每 30 秒轮询一次,不能为此全表 GROUP BY。 */
|
||||
List<UserSecretUsageAggregate> sumForUser(@Param("userId") Long userId,
|
||||
@Param("businessDate") LocalDate businessDate);
|
||||
|
||||
/** 分批删除保留期外的用量日统计行(该表此前只增不删)。 */
|
||||
int deleteBefore(@Param("cutoff") LocalDate cutoff, @Param("batchSize") int batchSize);
|
||||
}
|
||||
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package com.nanri.aiimage.modules.usersecret.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.nanri.aiimage.modules.usersecret.model.entity.UserTaskGuardEntity;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
|
||||
@Mapper
|
||||
public interface UserTaskGuardMapper extends BaseMapper<UserTaskGuardEntity> {
|
||||
|
||||
/** 幂等暂停:无记录则建,有记录则刷新原因与时刻。 */
|
||||
int pause(@Param("userId") Long userId, @Param("reason") String reason);
|
||||
|
||||
int resume(@Param("userId") Long userId);
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
package com.nanri.aiimage.modules.usersecret.model.dto;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
/** 按用户 × 模块聚合的当日用量读数(CostGuardScheduler 的扫描输入)。 */
|
||||
@Data
|
||||
public class UserSecretUsageAggregate {
|
||||
|
||||
private Long userId;
|
||||
private String moduleKey;
|
||||
private Long callCount;
|
||||
private Long tokens;
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
package com.nanri.aiimage.modules.usersecret.model.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.IdType;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/** 账号级任务暂停闸:损耗异常时停新派发,排查后由用户手动恢复。 */
|
||||
@Data
|
||||
@TableName("biz_user_task_guard")
|
||||
public class UserTaskGuardEntity {
|
||||
|
||||
@TableId(value = "user_id", type = IdType.INPUT)
|
||||
private Long userId;
|
||||
private Boolean paused;
|
||||
private String reason;
|
||||
private LocalDateTime pausedAt;
|
||||
private LocalDateTime updatedAt;
|
||||
}
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
package com.nanri.aiimage.modules.usersecret.model.vo;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
/** 客户端「损耗监控」状态:暂停闸 + 当日用量 + 本轮增量 + 共享密钥提示。 */
|
||||
@Data
|
||||
public class CostGuardStatusVo {
|
||||
|
||||
private boolean paused;
|
||||
private String reason;
|
||||
private LocalDateTime pausedAt;
|
||||
private TodayUsage today;
|
||||
private WindowUsage window;
|
||||
private Thresholds thresholds;
|
||||
private List<SharedSecretWarningVo> sharedWarnings;
|
||||
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
public static class TodayUsage {
|
||||
private long proxy;
|
||||
private long llmCalls;
|
||||
private long llmTokens;
|
||||
}
|
||||
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
public static class WindowUsage {
|
||||
private int seconds;
|
||||
private long proxy;
|
||||
private long llmCalls;
|
||||
private long llmTokens;
|
||||
}
|
||||
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
public static class Thresholds {
|
||||
private int proxyWindow;
|
||||
private int llmCallsWindow;
|
||||
private long llmTokensWindow;
|
||||
private int proxyDaily;
|
||||
private int llmCallsDaily;
|
||||
private long llmTokensDaily;
|
||||
private int sharedAccounts;
|
||||
}
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
package com.nanri.aiimage.modules.usersecret.model.vo;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
|
||||
/** 一把代理/LLM 密钥被多个账号共用的提示(只报账号数,不暴露其他账号身份)。 */
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
public class SharedSecretWarningVo {
|
||||
|
||||
/** proxy / llm */
|
||||
private String type;
|
||||
private String moduleLabel;
|
||||
private int accounts;
|
||||
private int threshold;
|
||||
private String message;
|
||||
}
|
||||
+216
@@ -0,0 +1,216 @@
|
||||
package com.nanri.aiimage.modules.usersecret.service;
|
||||
|
||||
import com.nanri.aiimage.common.service.DistributedJobLockService;
|
||||
import com.nanri.aiimage.config.CostGuardProperties;
|
||||
import com.nanri.aiimage.modules.notification.service.NotificationDispatchService;
|
||||
import com.nanri.aiimage.modules.notification.service.NotificationService;
|
||||
import com.nanri.aiimage.modules.usersecret.mapper.UserSecretUsageMapper;
|
||||
import com.nanri.aiimage.modules.usersecret.model.dto.UserSecretUsageAggregate;
|
||||
import com.nanri.aiimage.modules.usersecret.support.UserSecretModule;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.LocalDate;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
/**
|
||||
* 代理 / LLM 损耗扫描:每分钟读一次当日用量聚合表,用「本轮增量」判失控、用「日累计跨阈值」
|
||||
* 判慢烧;命中即置账号暂停闸并推用户通知。
|
||||
*
|
||||
* <p>为什么用日聚合表的增量而不是另建明细表:代理计次本来就是 16890/pt_worker 按批上报的,
|
||||
* LLM 计次在发请求前已落库;再建一条实时流水只会多一份可能对不上的账。日表行数 = 用户数×3,
|
||||
* 每分钟全量 GROUP BY 的成本可以忽略。
|
||||
*
|
||||
* <p>只在本轮真正「跨过」阈值时暂停:用户排查后点继续会调 {@link #resetBaseline(Long)},
|
||||
* 基线重置为当前值,不会因为日累计仍高于阈值而被立刻再次暂停。
|
||||
*/
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@Slf4j
|
||||
public class CostGuardScheduler {
|
||||
|
||||
static final String LOCK_NAME = "cost-guard-scan";
|
||||
|
||||
private final CostGuardProperties properties;
|
||||
private final UserSecretUsageMapper usageMapper;
|
||||
private final UserTaskGuardService guardService;
|
||||
private final SharedSecretMonitorService sharedSecretMonitorService;
|
||||
private final NotificationDispatchService notificationDispatchService;
|
||||
private final DistributedJobLockService distributedJobLockService;
|
||||
|
||||
private final Map<Long, UserTotals> previousTotals = new ConcurrentHashMap<>();
|
||||
private final Map<Long, WindowDelta> lastDeltas = new ConcurrentHashMap<>();
|
||||
private volatile long lastSharedRefreshAt = 0L;
|
||||
|
||||
@Scheduled(fixedDelayString = "${aiimage.cost-guard.scan-interval-ms:60000}",
|
||||
initialDelayString = "${aiimage.cost-guard.scan-initial-delay-ms:30000}")
|
||||
public void scan() {
|
||||
if (!properties.isEnabled()) {
|
||||
return;
|
||||
}
|
||||
var lock = distributedJobLockService.tryLock(LOCK_NAME, Duration.ofMinutes(2));
|
||||
if (lock == null) {
|
||||
log.info("[cost-guard] 另一实例持有损耗扫描锁,跳过本轮");
|
||||
return;
|
||||
}
|
||||
try (lock) {
|
||||
runOnce();
|
||||
} catch (Exception ex) {
|
||||
log.warn("[cost-guard] 损耗扫描异常终止 err={}", ex.getMessage(), ex);
|
||||
}
|
||||
}
|
||||
|
||||
/** 一轮扫描;package-private 供单测直接驱动,不依赖调度线程。 */
|
||||
void runOnce() {
|
||||
Map<Long, UserTotals> current = loadTodayTotals();
|
||||
Map<Long, WindowDelta> deltas = new LinkedHashMap<>();
|
||||
int paused = 0;
|
||||
for (Map.Entry<Long, UserTotals> entry : current.entrySet()) {
|
||||
Long userId = entry.getKey();
|
||||
UserTotals now = entry.getValue();
|
||||
UserTotals before = previousTotals.get(userId);
|
||||
if (before == null) {
|
||||
// 首轮只建基线:启动瞬间没有「增量」可比,拿日累计当分钟增量会误伤正在跑的大批次
|
||||
deltas.put(userId, WindowDelta.ZERO);
|
||||
continue;
|
||||
}
|
||||
WindowDelta delta = new WindowDelta(
|
||||
Math.max(0, now.proxy - before.proxy),
|
||||
Math.max(0, now.llmCalls - before.llmCalls),
|
||||
Math.max(0, now.llmTokens - before.llmTokens));
|
||||
deltas.put(userId, delta);
|
||||
if (guardService.isPaused(userId)) {
|
||||
continue;
|
||||
}
|
||||
String reason = breachReason(now, before, delta);
|
||||
if (reason == null) {
|
||||
continue;
|
||||
}
|
||||
guardService.pause(userId, reason);
|
||||
notificationDispatchService.pushToUser(userId, NotificationService.SCENE_COST_GUARD,
|
||||
NotificationService.LEVEL_ERROR, "已自动暂停任务:代理/LLM 消耗异常", reason
|
||||
+ "。请检查「密钥设置」与正在跑的任务配置,排查后点击客户端提示里的「继续任务」。",
|
||||
null);
|
||||
paused++;
|
||||
log.warn("[cost-guard] 触发暂停 userId={} reason={}", userId, reason);
|
||||
}
|
||||
previousTotals.clear();
|
||||
previousTotals.putAll(current);
|
||||
lastDeltas.clear();
|
||||
lastDeltas.putAll(deltas);
|
||||
maybeRefreshShared();
|
||||
log.info("[cost-guard] 扫描完成 用户={} 本轮暂停={} 共享密钥快照={}ms",
|
||||
current.size(), paused, sharedSecretMonitorService.snapshotAtMillis());
|
||||
}
|
||||
|
||||
/** 用户点击继续时调用:把基线对齐到当前值,避免下一轮拿历史累计再次触发。 */
|
||||
public void resetBaseline(Long userId) {
|
||||
if (userId == null) {
|
||||
return;
|
||||
}
|
||||
previousTotals.remove(userId);
|
||||
lastDeltas.remove(userId);
|
||||
}
|
||||
|
||||
public WindowDelta lastDelta(Long userId) {
|
||||
WindowDelta delta = userId == null ? null : lastDeltas.get(userId);
|
||||
return delta == null ? WindowDelta.ZERO : delta;
|
||||
}
|
||||
|
||||
public Map<Long, UserTotals> loadTodayTotals() {
|
||||
List<UserSecretUsageAggregate> rows = usageMapper.sumByUserAndModule(LocalDate.now());
|
||||
Map<Long, UserTotals> totals = new LinkedHashMap<>();
|
||||
for (UserSecretUsageAggregate row : rows) {
|
||||
if (row.getUserId() == null || row.getUserId() <= 0) {
|
||||
continue;
|
||||
}
|
||||
accumulate(totals.computeIfAbsent(row.getUserId(), key -> new UserTotals()), row);
|
||||
}
|
||||
return totals;
|
||||
}
|
||||
|
||||
private void accumulate(UserTotals item, UserSecretUsageAggregate row) {
|
||||
long calls = row.getCallCount() == null ? 0L : row.getCallCount();
|
||||
long tokens = row.getTokens() == null ? 0L : row.getTokens();
|
||||
if (UserSecretModule.PROXY.key().equals(row.getModuleKey())) {
|
||||
item.proxy += calls;
|
||||
} else {
|
||||
item.llmCalls += calls;
|
||||
item.llmTokens += tokens;
|
||||
}
|
||||
}
|
||||
|
||||
public UserTotals todayTotals(Long userId) {
|
||||
if (userId == null || userId <= 0) {
|
||||
return new UserTotals();
|
||||
}
|
||||
// 库抖动就让它抛:客户端把轮询失败当「维持上一次读数」处理,比在这里伪造一组零值诚实。
|
||||
UserTotals totals = new UserTotals();
|
||||
for (UserSecretUsageAggregate row : usageMapper.sumForUser(userId, LocalDate.now())) {
|
||||
accumulate(totals, row);
|
||||
}
|
||||
return totals;
|
||||
}
|
||||
|
||||
private String breachReason(UserTotals now, UserTotals before, WindowDelta delta) {
|
||||
int seconds = Math.max(60, properties.getWindowSeconds());
|
||||
if (properties.getProxyWindowThreshold() > 0
|
||||
&& delta.proxy >= properties.getProxyWindowThreshold()) {
|
||||
return "最近约 " + seconds + " 秒代理提取 " + delta.proxy + " 次,超过阈值 "
|
||||
+ properties.getProxyWindowThreshold() + " 次";
|
||||
}
|
||||
if (properties.getLlmWindowCallsThreshold() > 0
|
||||
&& delta.llmCalls >= properties.getLlmWindowCallsThreshold()) {
|
||||
return "最近约 " + seconds + " 秒 LLM 调用 " + delta.llmCalls + " 次,超过阈值 "
|
||||
+ properties.getLlmWindowCallsThreshold() + " 次";
|
||||
}
|
||||
if (properties.getLlmWindowTokensThreshold() > 0
|
||||
&& delta.llmTokens >= properties.getLlmWindowTokensThreshold()) {
|
||||
return "最近约 " + seconds + " 秒 LLM 消耗 " + delta.llmTokens + " tokens,超过阈值 "
|
||||
+ properties.getLlmWindowTokensThreshold();
|
||||
}
|
||||
if (crossed(before.proxy, now.proxy, properties.getDailyProxyThreshold())) {
|
||||
return "今日代理提取累计 " + now.proxy + " 次,超过当日上限 "
|
||||
+ properties.getDailyProxyThreshold() + " 次";
|
||||
}
|
||||
if (crossed(before.llmCalls, now.llmCalls, properties.getDailyLlmCallsThreshold())) {
|
||||
return "今日 LLM 调用累计 " + now.llmCalls + " 次,超过当日上限 "
|
||||
+ properties.getDailyLlmCallsThreshold() + " 次";
|
||||
}
|
||||
if (crossed(before.llmTokens, now.llmTokens, properties.getDailyLlmTokensThreshold())) {
|
||||
return "今日 LLM 消耗累计 " + now.llmTokens + " tokens,超过当日上限 "
|
||||
+ properties.getDailyLlmTokensThreshold();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private boolean crossed(long before, long now, long threshold) {
|
||||
return threshold > 0 && before < threshold && now >= threshold;
|
||||
}
|
||||
|
||||
private void maybeRefreshShared() {
|
||||
long now = System.currentTimeMillis();
|
||||
if (now - lastSharedRefreshAt < Math.max(60_000L, properties.getSharedScanIntervalMs())) {
|
||||
return;
|
||||
}
|
||||
lastSharedRefreshAt = now;
|
||||
// 不自己吞:runOnce 里这是最后一步,抛出由 scan() 的 [cost-guard] WARN 记名,下一间隔再试
|
||||
sharedSecretMonitorService.refresh();
|
||||
}
|
||||
|
||||
public static final class UserTotals {
|
||||
public long proxy;
|
||||
public long llmCalls;
|
||||
public long llmTokens;
|
||||
}
|
||||
|
||||
public record WindowDelta(long proxy, long llmCalls, long llmTokens) {
|
||||
public static final WindowDelta ZERO = new WindowDelta(0, 0, 0);
|
||||
}
|
||||
}
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
package com.nanri.aiimage.modules.usersecret.service;
|
||||
|
||||
import com.nanri.aiimage.config.CostGuardProperties;
|
||||
import com.nanri.aiimage.modules.usersecret.model.vo.CostGuardStatusVo;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/** 客户端损耗监控的状态读取与手动继续;不改任何任务结果行。 */
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class CostGuardService {
|
||||
|
||||
private final CostGuardProperties properties;
|
||||
private final UserTaskGuardService guardService;
|
||||
private final CostGuardScheduler costGuardScheduler;
|
||||
private final SharedSecretMonitorService sharedSecretMonitorService;
|
||||
|
||||
public CostGuardStatusVo status(Long userId) {
|
||||
UserTaskGuardService.GuardState state = guardService.state(userId);
|
||||
CostGuardScheduler.UserTotals today = costGuardScheduler.todayTotals(userId);
|
||||
CostGuardScheduler.WindowDelta delta = costGuardScheduler.lastDelta(userId);
|
||||
int windowSeconds = Math.max(60, properties.getWindowSeconds());
|
||||
|
||||
CostGuardStatusVo vo = new CostGuardStatusVo();
|
||||
vo.setPaused(state.paused());
|
||||
vo.setReason(state.reason());
|
||||
vo.setPausedAt(state.pausedAt());
|
||||
vo.setToday(new CostGuardStatusVo.TodayUsage(today.proxy, today.llmCalls, today.llmTokens));
|
||||
vo.setWindow(new CostGuardStatusVo.WindowUsage(windowSeconds,
|
||||
delta.proxy(), delta.llmCalls(), delta.llmTokens()));
|
||||
vo.setThresholds(new CostGuardStatusVo.Thresholds(
|
||||
properties.getProxyWindowThreshold(),
|
||||
properties.getLlmWindowCallsThreshold(),
|
||||
properties.getLlmWindowTokensThreshold(),
|
||||
properties.getDailyProxyThreshold(),
|
||||
properties.getDailyLlmCallsThreshold(),
|
||||
properties.getDailyLlmTokensThreshold(),
|
||||
properties.getSharedAccountsThreshold()));
|
||||
List<com.nanri.aiimage.modules.usersecret.model.vo.SharedSecretWarningVo> shared =
|
||||
sharedSecretMonitorService.warningsFor(userId);
|
||||
vo.setSharedWarnings(shared == null ? List.of() : shared);
|
||||
return vo;
|
||||
}
|
||||
|
||||
/** 用户排查后手动继续:清暂停位并把损耗基线对齐到当前,已完成的任务与结果原样保留。 */
|
||||
public CostGuardStatusVo resume(Long userId) {
|
||||
guardService.resume(userId);
|
||||
costGuardScheduler.resetBaseline(userId);
|
||||
return status(userId);
|
||||
}
|
||||
}
|
||||
+139
@@ -0,0 +1,139 @@
|
||||
package com.nanri.aiimage.modules.usersecret.service;
|
||||
|
||||
import cn.hutool.crypto.digest.DigestUtil;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
|
||||
import com.nanri.aiimage.config.CostGuardProperties;
|
||||
import com.nanri.aiimage.modules.notification.service.NotificationDispatchService;
|
||||
import com.nanri.aiimage.modules.notification.service.NotificationService;
|
||||
import com.nanri.aiimage.modules.usersecret.mapper.UserApiSecretMapper;
|
||||
import com.nanri.aiimage.modules.usersecret.model.entity.UserApiSecretEntity;
|
||||
import com.nanri.aiimage.modules.usersecret.model.vo.SharedSecretWarningVo;
|
||||
import com.nanri.aiimage.modules.usersecret.support.UserSecretModule;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
/**
|
||||
* 共享密钥提示:同一把代理/LLM 密钥被过多账号共用时,给每个使用者一条明确提示。
|
||||
*
|
||||
* <p>只统计、不暂停:共用同一把密钥本身不是故障(账单按 key 计费,平台也允许这样配),
|
||||
* 但它会把一次异常消耗放大到所有账号,也会让「谁烧的」无法归因。提示里只报账号数,
|
||||
* 不暴露其他账号身份。
|
||||
*
|
||||
* <p>分组键直接用密文:{@code ShopCredentialCryptoService} 是 AES/ECB 无 IV,
|
||||
* 同明文必同密文(与 {@link UserApiSecretService#checkAllForScheduler} 同一口径),
|
||||
* 因此本类不需要解密、也不会把明文密钥带进内存快照。
|
||||
*/
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@Slf4j
|
||||
public class SharedSecretMonitorService {
|
||||
|
||||
private final UserApiSecretMapper userApiSecretMapper;
|
||||
private final CostGuardProperties properties;
|
||||
private final NotificationDispatchService notificationDispatchService;
|
||||
|
||||
private volatile Map<Long, List<SharedSecretWarningVo>> warningsByUser = Map.of();
|
||||
private volatile long snapshotAtMillis = 0L;
|
||||
|
||||
/** 扫描全部密钥配置,刷新「谁和谁共用同一把」的快照,并给使用者推当日一次提示。 */
|
||||
public synchronized void refresh() {
|
||||
if (!properties.isEnabled() || properties.getSharedAccountsThreshold() <= 0) {
|
||||
warningsByUser = Map.of();
|
||||
snapshotAtMillis = System.currentTimeMillis();
|
||||
return;
|
||||
}
|
||||
// 用字符串列名而不是 lambda:本类在纯单测里不经过 MyBatis 的实体元数据初始化
|
||||
List<UserApiSecretEntity> rows = userApiSecretMapper.selectList(
|
||||
new QueryWrapper<UserApiSecretEntity>()
|
||||
.select("user_id", "module_key", "secret_value"));
|
||||
// groupKey = module|密文;值是该组的使用账号集合(去重)
|
||||
Map<String, SecretGroup> groups = new LinkedHashMap<>();
|
||||
for (UserApiSecretEntity row : rows) {
|
||||
if (row.getUserId() == null || row.getUserId() <= 0) {
|
||||
continue;
|
||||
}
|
||||
Optional<UserSecretModule> module = UserSecretModule.of(row.getModuleKey());
|
||||
if (module.isEmpty() || row.getSecretValue() == null || row.getSecretValue().isBlank()) {
|
||||
continue;
|
||||
}
|
||||
String groupKey = row.getModuleKey() + '|' + row.getSecretValue();
|
||||
groups.computeIfAbsent(groupKey, key -> new SecretGroup(module.get()))
|
||||
.userIds.add(row.getUserId());
|
||||
}
|
||||
|
||||
Map<Long, List<SharedSecretWarningVo>> next = new LinkedHashMap<>();
|
||||
int hitGroups = 0;
|
||||
for (Map.Entry<String, SecretGroup> entry : groups.entrySet()) {
|
||||
SecretGroup group = entry.getValue();
|
||||
int accounts = group.userIds.size();
|
||||
if (accounts < properties.getSharedAccountsThreshold()) {
|
||||
continue;
|
||||
}
|
||||
hitGroups++;
|
||||
String type = group.module == UserSecretModule.PROXY ? "proxy" : "llm";
|
||||
int threshold = properties.getSharedAccountsThreshold();
|
||||
String message = buildMessage(group.module, accounts, threshold);
|
||||
SharedSecretWarningVo warning = new SharedSecretWarningVo(
|
||||
type, group.module.label(), accounts, threshold, message);
|
||||
for (Long userId : group.userIds) {
|
||||
next.computeIfAbsent(userId, key -> new ArrayList<>()).add(warning);
|
||||
pushDailyWarning(userId, group.module, entry.getKey(), warning);
|
||||
}
|
||||
}
|
||||
warningsByUser = next;
|
||||
snapshotAtMillis = System.currentTimeMillis();
|
||||
log.info("[cost-guard] 共享密钥扫描完成 配置行={} 密钥组={} 超阈值组={} 受影响账号={}",
|
||||
rows.size(), groups.size(), hitGroups, next.size());
|
||||
}
|
||||
|
||||
/** 当前用户共享密钥提示;快照未建立时返回空,不阻塞客户端轮询。 */
|
||||
public List<SharedSecretWarningVo> warningsFor(Long userId) {
|
||||
if (userId == null || userId <= 0) {
|
||||
return List.of();
|
||||
}
|
||||
return warningsByUser.getOrDefault(userId, List.of());
|
||||
}
|
||||
|
||||
public long snapshotAtMillis() {
|
||||
return snapshotAtMillis;
|
||||
}
|
||||
|
||||
private void pushDailyWarning(Long userId, UserSecretModule module, String groupKey,
|
||||
SharedSecretWarningVo warning) {
|
||||
String day = LocalDate.now().format(DateTimeFormatter.BASIC_ISO_DATE);
|
||||
String dedupe = "secret_shared:" + module.key() + ':' + DigestUtil.sha256Hex(groupKey)
|
||||
+ ':' + userId + ':' + day;
|
||||
notificationDispatchService.pushToUser(userId, NotificationService.SCENE_SECRET_SHARED,
|
||||
NotificationService.LEVEL_WARNING,
|
||||
module.label() + "被 " + warning.getAccounts() + " 个账号共用",
|
||||
warning.getMessage(), dedupe);
|
||||
}
|
||||
|
||||
private String buildMessage(UserSecretModule module, int accounts, int threshold) {
|
||||
String what = module == UserSecretModule.PROXY ? "代理提取链接" : "LLM 密钥";
|
||||
return "你的" + module.label() + "(" + what + ")当前被 " + accounts
|
||||
+ " 个账号共用,已达到提示阈值 " + threshold + "。任一账号的异常消耗都会算在这把密钥的套餐上,"
|
||||
+ "建议在「密钥设置」里为不同账号拆分独立密钥,便于控费和定位问题。";
|
||||
}
|
||||
|
||||
private static final class SecretGroup {
|
||||
private final UserSecretModule module;
|
||||
private final Set<Long> userIds = new HashSet<>();
|
||||
|
||||
private SecretGroup(UserSecretModule module) {
|
||||
this.module = module;
|
||||
}
|
||||
}
|
||||
}
|
||||
+115
@@ -0,0 +1,115 @@
|
||||
package com.nanri.aiimage.modules.usersecret.service;
|
||||
|
||||
import com.nanri.aiimage.modules.usersecret.mapper.UserTaskGuardMapper;
|
||||
import com.nanri.aiimage.modules.usersecret.model.entity.UserTaskGuardEntity;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/**
|
||||
* 账号级任务暂停闸:损耗异常时由 CostGuardScheduler 置位,派发入口据此停新任务。
|
||||
*
|
||||
* <p>读侧带 3 秒内存缓存:品牌检测/LLM 每次请求都问一次,直接打库会把闸门本身变成热点;
|
||||
* 多实例下最迟 3 秒收敛,足够挡住下一分钟的任务。写侧立即清缓存,本机无延迟。
|
||||
*/
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@Slf4j
|
||||
public class UserTaskGuardService {
|
||||
|
||||
public static final String PAUSED_MESSAGE =
|
||||
"账号任务已暂停(损耗保护),请排查代理/LLM 消耗后在客户端点击「继续任务」";
|
||||
|
||||
private static final long CACHE_TTL_NANOS = TimeUnit.SECONDS.toNanos(3);
|
||||
private static final int REASON_MAX_LENGTH = 500;
|
||||
|
||||
private final UserTaskGuardMapper guardMapper;
|
||||
private final ConcurrentHashMap<Long, CachedState> cache = new ConcurrentHashMap<>();
|
||||
|
||||
public boolean isPaused(Long userId) {
|
||||
if (userId == null || userId <= 0) {
|
||||
return false;
|
||||
}
|
||||
CachedState cached = cache.get(userId);
|
||||
if (cached != null && System.nanoTime() - cached.readAtNanos() < CACHE_TTL_NANOS) {
|
||||
return cached.paused();
|
||||
}
|
||||
GuardState state = load(userId);
|
||||
cache.put(userId, new CachedState(state.paused(), state.reason(), state.pausedAt(),
|
||||
System.nanoTime()));
|
||||
return state.paused();
|
||||
}
|
||||
|
||||
/** 状态查询走库:客户端弹窗要看到其他实例刚写入的暂停,不吃本机缓存。 */
|
||||
public GuardState state(Long userId) {
|
||||
if (userId == null || userId <= 0) {
|
||||
return GuardState.ACTIVE;
|
||||
}
|
||||
GuardState state = load(userId);
|
||||
cache.put(userId, new CachedState(state.paused(), state.reason(), state.pausedAt(),
|
||||
System.nanoTime()));
|
||||
return state;
|
||||
}
|
||||
|
||||
public void pause(Long userId, String reason) {
|
||||
if (userId == null || userId <= 0) {
|
||||
return;
|
||||
}
|
||||
String safeReason = truncate(reason);
|
||||
try {
|
||||
guardMapper.pause(userId, safeReason);
|
||||
cache.remove(userId);
|
||||
log.warn("[cost-guard] 已暂停账号新任务 userId={} reason={}", userId, safeReason);
|
||||
} catch (Exception ex) {
|
||||
// 暂停失败不能拖垮扫描线程:下一轮还会再判一次,异常留在日志里
|
||||
log.error("[cost-guard] 暂停写入失败 userId={} reason={} err={}",
|
||||
userId, safeReason, ex.getMessage(), ex);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 用户手动继续:只清暂停位,不删任何已完成的任务/结果。
|
||||
* 写失败一律外抛——静默返回 false 会让接口把「没解开」回成「已继续任务」。
|
||||
*/
|
||||
public void resume(Long userId) {
|
||||
if (userId == null || userId <= 0) {
|
||||
return;
|
||||
}
|
||||
guardMapper.resume(userId);
|
||||
cache.remove(userId);
|
||||
log.info("[cost-guard] 用户手动继续任务 userId={}", userId);
|
||||
}
|
||||
|
||||
private GuardState load(Long userId) {
|
||||
try {
|
||||
UserTaskGuardEntity row = guardMapper.selectById(userId);
|
||||
if (row == null || !Boolean.TRUE.equals(row.getPaused())) {
|
||||
return GuardState.ACTIVE;
|
||||
}
|
||||
return new GuardState(true, row.getReason() == null ? "" : row.getReason(),
|
||||
row.getPausedAt());
|
||||
} catch (Exception ex) {
|
||||
// 读不到闸门状态时按「不暂停」走:数据库抖动不该把全体用户的合法任务一起冻住。
|
||||
// 真正的失控由下一轮扫描重新置位。
|
||||
log.warn("[cost-guard] 读取暂停状态失败,按未暂停处理 userId={} err={}",
|
||||
userId, ex.getMessage());
|
||||
return GuardState.ACTIVE;
|
||||
}
|
||||
}
|
||||
|
||||
private String truncate(String reason) {
|
||||
String value = reason == null ? "" : reason.trim();
|
||||
return value.length() <= REASON_MAX_LENGTH ? value : value.substring(0, REASON_MAX_LENGTH);
|
||||
}
|
||||
|
||||
private record CachedState(boolean paused, String reason, LocalDateTime pausedAt, long readAtNanos) {
|
||||
}
|
||||
|
||||
public record GuardState(boolean paused, String reason, LocalDateTime pausedAt) {
|
||||
public static final GuardState ACTIVE = new GuardState(false, "", null);
|
||||
}
|
||||
}
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
package com.nanri.aiimage.modules.workbenchclient.controller;
|
||||
|
||||
import com.nanri.aiimage.modules.workbenchclient.service.WorkbenchClientPackageService;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 工作台客户端公开版本接口。
|
||||
*
|
||||
* <p>返回裸 JSON(不套 ApiResponse),字段名固定为 {@code version/file_url/sha256}:
|
||||
* 客户端更新器直接按这三个字段比较版本、下载、校验摘要。新增字段只能追加,不能改名。
|
||||
*/
|
||||
@Slf4j
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
@RequestMapping("/api/workbench-client/version")
|
||||
@Tag(name = "工作台客户端公开版本接口", description = "工作台客户端自动更新检查")
|
||||
public class PublicWorkbenchClientVersionController {
|
||||
|
||||
private final WorkbenchClientPackageService packageService;
|
||||
|
||||
@GetMapping("/latest")
|
||||
@Operation(summary = "最新客户端包", description = "返回最新上传的版本号、公开下载直链与 sha256;空表时字段为 null")
|
||||
public Map<String, Object> latestVersion() {
|
||||
return packageService.latestPackage();
|
||||
}
|
||||
|
||||
@GetMapping("/list")
|
||||
@Operation(summary = "客户端包版本列表", description = "按上传时间倒序返回最近 50 条,供客户端「指定版本更新」使用")
|
||||
public Map<String, Object> listVersions() {
|
||||
return packageService.listPublicPackages();
|
||||
}
|
||||
}
|
||||
+82
@@ -0,0 +1,82 @@
|
||||
package com.nanri.aiimage.modules.workbenchclient.controller;
|
||||
|
||||
import com.nanri.aiimage.common.api.ApiResponse;
|
||||
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
|
||||
import com.nanri.aiimage.common.security.AdminAuthSupport;
|
||||
import com.nanri.aiimage.modules.workbenchclient.service.WorkbenchClientPackageService;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.Parameter;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 数富AI工作台客户端包管理(后台「工作台客户端包管理」页)。
|
||||
* <p>列表、直传预签名、确认落库、删除;客户端读公开接口
|
||||
* {@code /api/workbench-client/version/latest} 自动检查更新。
|
||||
*/
|
||||
@Slf4j
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
@RequestMapping("/api/admin/workbench-client")
|
||||
@Tag(name = "工作台客户端包管理", description = "数富AI工作台安装/更新包管理:列表与上传(浏览器直传 MinIO,服务端复算 sha256)")
|
||||
public class WorkbenchClientPackageAdminController {
|
||||
|
||||
private final WorkbenchClientPackageService packageService;
|
||||
private final AdminAuthSupport adminAuthSupport;
|
||||
|
||||
@GetMapping("/packages")
|
||||
@Operation(summary = "客户端包列表", description = "按上传时间倒序返回全部记录(第一条即客户端当前更新目标)")
|
||||
public ApiResponse<Map<String, Object>> listPackages(HttpServletRequest request) {
|
||||
AdminUserEntity operator = adminAuthSupport.requireAdminOrInternal(request);
|
||||
log.info("[workbench-client] 管理端查询客户端包列表 operator={}", operator.getUsername());
|
||||
return ApiResponse.success(Map.of("items", packageService.listPackages()));
|
||||
}
|
||||
|
||||
@PostMapping("/package/presign")
|
||||
@Operation(summary = "签发客户端包直传预签名", description = "返回浏览器直传 MinIO client 桶的 PUT 预签名地址;直传完成后调用 /package/confirm 校验落库")
|
||||
public ApiResponse<Map<String, Object>> presignPackage(
|
||||
HttpServletRequest request,
|
||||
@Parameter(description = "上传的 zip 文件名") @RequestParam(value = "file_name", required = false) String fileName,
|
||||
@Parameter(description = "客户端版本号,如 1.0.0") @RequestParam(value = "version", required = false) String version) {
|
||||
AdminUserEntity operator = adminAuthSupport.requireAdminOrInternal(request);
|
||||
log.info("[workbench-client] 管理端签发客户端包直传预签名 operator={} fileName={} version={}",
|
||||
operator.getUsername(), fileName, version);
|
||||
return ApiResponse.success(packageService.presignPackage(fileName, version));
|
||||
}
|
||||
|
||||
@PostMapping("/package/confirm")
|
||||
@Operation(summary = "确认客户端包直传完成", description = "服务端核对对象、复算 sha256 并落库,返回新记录行")
|
||||
public ApiResponse<Map<String, Object>> confirmPackage(
|
||||
HttpServletRequest request,
|
||||
@Parameter(description = "预签名返回的对象 key") @RequestParam(value = "object_key", required = false) String objectKey,
|
||||
@Parameter(description = "上传的 zip 文件名") @RequestParam(value = "file_name", required = false) String fileName,
|
||||
@Parameter(description = "客户端版本号,如 1.0.0") @RequestParam(value = "version", required = false) String version) {
|
||||
AdminUserEntity operator = adminAuthSupport.requireAdminOrInternal(request);
|
||||
log.info("[workbench-client] 管理端确认客户端包直传完成 operator={} objectKey={} fileName={} version={}",
|
||||
operator.getUsername(), objectKey, fileName, version);
|
||||
return ApiResponse.success("上传成功", Map.of("item",
|
||||
packageService.confirmPackage(objectKey, fileName, version)));
|
||||
}
|
||||
|
||||
@PostMapping("/package/delete")
|
||||
@Operation(summary = "批量删除客户端包", description = "按 id 删除记录;关联 MinIO 包体仅当无其它记录引用时清除")
|
||||
public ApiResponse<Map<String, Object>> deletePackages(
|
||||
HttpServletRequest request,
|
||||
@RequestBody List<Long> ids) {
|
||||
AdminUserEntity operator = adminAuthSupport.requireAdminOrInternal(request);
|
||||
log.info("[workbench-client] 管理端删除客户端包 operator={} ids={}", operator.getUsername(), ids);
|
||||
int deleted = packageService.deletePackages(ids);
|
||||
return ApiResponse.success("删除成功", Map.of("deleted", deleted));
|
||||
}
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package com.nanri.aiimage.modules.workbenchclient.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.nanri.aiimage.modules.workbenchclient.model.entity.WorkbenchClientPackageEntity;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
|
||||
@Mapper
|
||||
public interface WorkbenchClientPackageMapper extends BaseMapper<WorkbenchClientPackageEntity> {
|
||||
}
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
package com.nanri.aiimage.modules.workbenchclient.model.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.IdType;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* 数富AI工作台客户端安装/更新包记录。
|
||||
*
|
||||
* <p>包体放公开 client 桶 {@code workbench-client/versions/} 前缀,与桌面端 ShuFuAI 的
|
||||
* {@code nanri-image/versions/} 完全隔离;客户端从 {@code /api/workbench-client/version/latest}
|
||||
* 取版本号、下载直链与 sha256,自行比较版本并升级。
|
||||
*/
|
||||
@Data
|
||||
@TableName("biz_workbench_client_package")
|
||||
public class WorkbenchClientPackageEntity {
|
||||
|
||||
@TableId(type = IdType.AUTO)
|
||||
private Long id;
|
||||
|
||||
/** 客户端版本号(客户端据此判断是否需要升级) */
|
||||
private String version;
|
||||
|
||||
/** 原始 zip 文件名(展示用) */
|
||||
private String fileName;
|
||||
|
||||
/** MinIO 对象 key(client 桶,workbench-client/versions/ 前缀) */
|
||||
private String objectKey;
|
||||
|
||||
/** 文件字节数 */
|
||||
private Long fileSize;
|
||||
|
||||
/** 更新包 sha256(hex 小写),客户端下载后的完整性锚点 */
|
||||
private String sha256;
|
||||
|
||||
/** 上传时间,由数据库 CURRENT_TIMESTAMP 兜底;最新一条即客户端更新目标 */
|
||||
private LocalDateTime createdAt;
|
||||
}
|
||||
+295
@@ -0,0 +1,295 @@
|
||||
package com.nanri.aiimage.modules.workbenchclient.service;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
import com.nanri.aiimage.modules.file.service.oss.OssStorageService;
|
||||
import com.nanri.aiimage.modules.workbenchclient.mapper.WorkbenchClientPackageMapper;
|
||||
import com.nanri.aiimage.modules.workbenchclient.model.entity.WorkbenchClientPackageEntity;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* 数富AI工作台客户端安装/更新包管理。
|
||||
*
|
||||
* <p>后台只做三件事:上传 zip(浏览器直传 MinIO)、列表、删除。客户端更新接口按上传时间取
|
||||
* 最新一条({@code created_at DESC, id DESC}),删除最新包后自动回落到上一版。
|
||||
* <p>与教程包的关键差别:confirm 阶段必须由服务端从 MinIO 流式复算 sha256 并落库,
|
||||
* 不能留空——客户端下载后要用它做整包完整性校验。
|
||||
*/
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@Slf4j
|
||||
public class WorkbenchClientPackageService {
|
||||
|
||||
/** 独立于桌面端软件版本的前缀:同一公开 client 桶,互不覆盖。 */
|
||||
public static final String OBJECT_KEY_PREFIX = "workbench-client/versions/";
|
||||
|
||||
/** 与桌面端安装包同量级,沿用 512MB 上限。 */
|
||||
private static final long MAX_UPLOAD_BYTES = 512L * 1024 * 1024;
|
||||
|
||||
/** 版本号长度上限,与 biz_workbench_client_package.version VARCHAR(64) 对齐。 */
|
||||
private static final int MAX_VERSION_LENGTH = 64;
|
||||
|
||||
/** 直传预签名有效期:3 分钟足够数百 MB 级安装包上传。 */
|
||||
private static final int PRESIGN_EXPIRY_SECONDS = 180;
|
||||
|
||||
/** 公开版本列表上限:够客户端做「指定版本更新」下拉即可。 */
|
||||
private static final int PUBLIC_LIST_LIMIT = 50;
|
||||
|
||||
private static final DateTimeFormatter CREATED_AT_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
|
||||
|
||||
/** 毫秒级时间戳:同秒连续上传同一版本时也不会覆盖对象。 */
|
||||
private static final DateTimeFormatter OBJECT_NAME_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");
|
||||
|
||||
/** 对齐软件版本/教程包的 key 安全化规则:保留中文/字母/数字/._-,其余替换为 _。 */
|
||||
private static final Pattern UNSAFE_KEY_CHARS =
|
||||
Pattern.compile("[^\\w.\\-]", Pattern.UNICODE_CHARACTER_CLASS);
|
||||
|
||||
private final WorkbenchClientPackageMapper packageMapper;
|
||||
private final OssStorageService ossStorageService;
|
||||
|
||||
/** 管理端列表:按上传时间倒序,第一条即客户端当前更新目标。 */
|
||||
public List<Map<String, Object>> listPackages() {
|
||||
List<WorkbenchClientPackageEntity> entities = packageMapper.selectList(
|
||||
new LambdaQueryWrapper<WorkbenchClientPackageEntity>()
|
||||
.orderByDesc(WorkbenchClientPackageEntity::getCreatedAt)
|
||||
.orderByDesc(WorkbenchClientPackageEntity::getId));
|
||||
log.info("[workbench-client] 查询客户端包列表 count={}", entities.size());
|
||||
List<Map<String, Object>> items = new ArrayList<>(entities.size());
|
||||
for (WorkbenchClientPackageEntity entity : entities) {
|
||||
items.add(toItemMap(entity));
|
||||
}
|
||||
return items;
|
||||
}
|
||||
|
||||
/** 客户端更新检查:最新上传的一条;空表时字段全为 null,客户端保持当前版本。 */
|
||||
public Map<String, Object> latestPackage() {
|
||||
WorkbenchClientPackageEntity entity = newest();
|
||||
Map<String, Object> result = new LinkedHashMap<>();
|
||||
if (entity == null) {
|
||||
log.info("[workbench-client] 查询最新客户端包:无记录");
|
||||
result.put("version", null);
|
||||
result.put("file_url", null);
|
||||
result.put("sha256", null);
|
||||
result.put("file_name", null);
|
||||
result.put("file_size", null);
|
||||
result.put("created_at", null);
|
||||
return result;
|
||||
}
|
||||
log.info("[workbench-client] 查询最新客户端包 id={} version={} objectKey={}",
|
||||
entity.getId(), entity.getVersion(), entity.getObjectKey());
|
||||
result.put("version", entity.getVersion() == null ? "" : entity.getVersion());
|
||||
result.put("file_url", downloadUrl(entity));
|
||||
result.put("sha256", entity.getSha256() == null ? "" : entity.getSha256());
|
||||
result.put("file_name", entity.getFileName() == null ? "" : entity.getFileName());
|
||||
result.put("file_size", entity.getFileSize() == null ? 0L : entity.getFileSize());
|
||||
result.put("created_at", formatCreatedAt(entity));
|
||||
return result;
|
||||
}
|
||||
|
||||
/** 公开版本列表:桌面端/工作台「指定版本更新」下拉的数据源。 */
|
||||
public Map<String, Object> listPublicPackages() {
|
||||
List<WorkbenchClientPackageEntity> entities = packageMapper.selectList(
|
||||
new LambdaQueryWrapper<WorkbenchClientPackageEntity>()
|
||||
.orderByDesc(WorkbenchClientPackageEntity::getCreatedAt)
|
||||
.orderByDesc(WorkbenchClientPackageEntity::getId)
|
||||
.last("LIMIT " + PUBLIC_LIST_LIMIT));
|
||||
List<Map<String, Object>> items = new ArrayList<>(entities.size());
|
||||
for (WorkbenchClientPackageEntity entity : entities) {
|
||||
items.add(toItemMap(entity));
|
||||
}
|
||||
log.info("[workbench-client] 查询公开客户端包列表 limit={} count={}", PUBLIC_LIST_LIMIT, items.size());
|
||||
Map<String, Object> result = new LinkedHashMap<>();
|
||||
result.put("items", items);
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 签发直传预签名:对象 key 由「毫秒时间戳 + 安全版本号」组成,每次上传互不覆盖。
|
||||
*/
|
||||
public Map<String, Object> presignPackage(String fileName, String version) {
|
||||
String normalizedName = requireZipFileName(fileName);
|
||||
String normalizedVersion = requireVersion(version);
|
||||
String objectKey = OBJECT_KEY_PREFIX
|
||||
+ OBJECT_NAME_FORMATTER.format(LocalDateTime.now())
|
||||
+ "-" + safeVersionKey(normalizedVersion) + ".zip";
|
||||
log.info("[workbench-client] 签发客户端包直传预签名 version={} fileName={} objectKey={} expirySeconds={}",
|
||||
normalizedVersion, normalizedName, objectKey, PRESIGN_EXPIRY_SECONDS);
|
||||
String uploadUrl = ossStorageService.presignWorkbenchClientUpload(objectKey, PRESIGN_EXPIRY_SECONDS);
|
||||
Map<String, Object> result = new LinkedHashMap<>();
|
||||
result.put("object_key", objectKey);
|
||||
result.put("upload_url", uploadUrl);
|
||||
result.put("file_url", ossStorageService.getWorkbenchClientDownloadUrl(objectKey));
|
||||
result.put("version", normalizedVersion);
|
||||
result.put("file_name", normalizedName);
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 直传确认:校验对象存在、大小上限、版本号与对象名一致,服务端复算 sha256 后落库。
|
||||
* <p>sha256 为空或长度不对直接拒绝——宁可让管理员重传,也不让客户端拿到没有锚点的包。
|
||||
*/
|
||||
public Map<String, Object> confirmPackage(String objectKey, String fileName, String version) {
|
||||
if (objectKey == null || !objectKey.startsWith(OBJECT_KEY_PREFIX)) {
|
||||
log.warn("[workbench-client] 直传确认失败:非法对象路径 objectKey={}", objectKey);
|
||||
throw new BusinessException("非法的对象路径,请重新上传");
|
||||
}
|
||||
String normalizedName = requireZipFileName(fileName);
|
||||
String normalizedVersion = requireVersion(version);
|
||||
String expectedSuffix = "-" + safeVersionKey(normalizedVersion) + ".zip";
|
||||
if (!objectKey.endsWith(expectedSuffix)) {
|
||||
log.warn("[workbench-client] 直传确认失败:版本号与对象不匹配 version={} objectKey={}",
|
||||
normalizedVersion, objectKey);
|
||||
throw new BusinessException("版本号与上传对象不匹配,请重新上传");
|
||||
}
|
||||
long size = ossStorageService.workbenchClientObjectSize(objectKey);
|
||||
if (size < 0) {
|
||||
log.warn("[workbench-client] 直传确认失败:对象不存在 objectKey={}", objectKey);
|
||||
throw new BusinessException("对象存储中未找到上传的安装包,请重新上传");
|
||||
}
|
||||
if (size > MAX_UPLOAD_BYTES) {
|
||||
log.warn("[workbench-client] 直传对象超过大小上限,清理残留 objectKey={} bytes={}", objectKey, size);
|
||||
ossStorageService.removeWorkbenchClientObject(objectKey);
|
||||
throw new BusinessException("文件超过允许的大小限制");
|
||||
}
|
||||
String sha256 = ossStorageService.workbenchClientObjectSha256(objectKey);
|
||||
if (sha256 == null || sha256.length() != 64) {
|
||||
log.warn("[workbench-client] 直传确认失败:摘要计算异常 objectKey={} sha256={}", objectKey, sha256);
|
||||
throw new BusinessException("安装包摘要计算失败,请重新上传");
|
||||
}
|
||||
Long duplicated = packageMapper.selectCount(new LambdaQueryWrapper<WorkbenchClientPackageEntity>()
|
||||
.eq(WorkbenchClientPackageEntity::getObjectKey, objectKey));
|
||||
if (duplicated != null && duplicated > 0) {
|
||||
log.warn("[workbench-client] 直传确认失败:对象已被记录,重复提交 objectKey={}", objectKey);
|
||||
throw new BusinessException("该安装包已登记,请勿重复提交");
|
||||
}
|
||||
|
||||
WorkbenchClientPackageEntity entity = new WorkbenchClientPackageEntity();
|
||||
entity.setVersion(normalizedVersion);
|
||||
entity.setFileName(normalizedName);
|
||||
entity.setObjectKey(objectKey);
|
||||
entity.setFileSize(size);
|
||||
entity.setSha256(sha256);
|
||||
packageMapper.insert(entity);
|
||||
log.info("[workbench-client] 客户端包登记成功 id={} version={} fileName={} bytes={} sha256={}",
|
||||
entity.getId(), normalizedVersion, normalizedName, size, sha256);
|
||||
WorkbenchClientPackageEntity saved = packageMapper.selectById(entity.getId());
|
||||
return toItemMap(saved == null ? entity : saved);
|
||||
}
|
||||
|
||||
/**
|
||||
* 按 id 批量删除记录;MinIO 对象仅在删除后无任何剩余记录引用时才清除。
|
||||
* <p>最新包被删后,客户端下次检查自动回落到上一版(按上传时间取最新)。
|
||||
*/
|
||||
public int deletePackages(List<Long> ids) {
|
||||
List<Long> distinctIds = ids == null ? List.of() : ids.stream()
|
||||
.filter(id -> id != null).distinct().toList();
|
||||
if (distinctIds.isEmpty()) {
|
||||
throw new BusinessException("请选择要删除的客户端包");
|
||||
}
|
||||
List<WorkbenchClientPackageEntity> targets = packageMapper.selectBatchIds(distinctIds);
|
||||
int deleted = 0;
|
||||
for (Long id : distinctIds) {
|
||||
deleted += packageMapper.deleteById(id);
|
||||
}
|
||||
Set<String> touchedKeys = new LinkedHashSet<>();
|
||||
for (WorkbenchClientPackageEntity target : targets) {
|
||||
if (target.getObjectKey() != null && !target.getObjectKey().isBlank()) {
|
||||
touchedKeys.add(target.getObjectKey());
|
||||
}
|
||||
}
|
||||
int removedObjects = 0;
|
||||
for (String objectKey : touchedKeys) {
|
||||
Long remain = packageMapper.selectCount(new LambdaQueryWrapper<WorkbenchClientPackageEntity>()
|
||||
.eq(WorkbenchClientPackageEntity::getObjectKey, objectKey));
|
||||
if (remain == null || remain <= 0) {
|
||||
removedObjects += removeObjectQuietly(objectKey) ? 1 : 0;
|
||||
}
|
||||
}
|
||||
log.info("[workbench-client] 批量删除客户端包 ids={} deleted={} 清理关联文件数={}",
|
||||
distinctIds, deleted, removedObjects);
|
||||
return deleted;
|
||||
}
|
||||
|
||||
private WorkbenchClientPackageEntity newest() {
|
||||
return packageMapper.selectOne(new LambdaQueryWrapper<WorkbenchClientPackageEntity>()
|
||||
.orderByDesc(WorkbenchClientPackageEntity::getCreatedAt)
|
||||
.orderByDesc(WorkbenchClientPackageEntity::getId)
|
||||
.last("LIMIT 1"));
|
||||
}
|
||||
|
||||
private boolean removeObjectQuietly(String objectKey) {
|
||||
try {
|
||||
if (!objectKey.startsWith(OBJECT_KEY_PREFIX)) {
|
||||
return false;
|
||||
}
|
||||
ossStorageService.removeWorkbenchClientObject(objectKey);
|
||||
return true;
|
||||
} catch (RuntimeException ex) {
|
||||
log.warn("[workbench-client] 清理客户端包对象失败,保留对象 objectKey={} err={}",
|
||||
objectKey, ex.getMessage());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private String requireZipFileName(String fileName) {
|
||||
String normalized = fileName == null ? "" : fileName.trim();
|
||||
if (normalized.isEmpty()) {
|
||||
throw new BusinessException("请选择要上传的 zip 压缩包");
|
||||
}
|
||||
if (!normalized.toLowerCase(Locale.ROOT).endsWith(".zip")) {
|
||||
throw new BusinessException("仅支持 .zip 格式");
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
|
||||
private String requireVersion(String version) {
|
||||
String normalized = version == null ? "" : version.trim();
|
||||
if (normalized.isEmpty()) {
|
||||
throw new BusinessException("请填写版本号");
|
||||
}
|
||||
if (normalized.length() > MAX_VERSION_LENGTH) {
|
||||
throw new BusinessException("版本号不能超过 " + MAX_VERSION_LENGTH + " 个字符");
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
|
||||
private String safeVersionKey(String version) {
|
||||
String replaced = UNSAFE_KEY_CHARS.matcher(version).replaceAll("_");
|
||||
return replaced.isEmpty() ? "unknown" : replaced;
|
||||
}
|
||||
|
||||
private String downloadUrl(WorkbenchClientPackageEntity entity) {
|
||||
return entity.getObjectKey() == null || entity.getObjectKey().isBlank()
|
||||
? "" : ossStorageService.getWorkbenchClientDownloadUrl(entity.getObjectKey());
|
||||
}
|
||||
|
||||
private String formatCreatedAt(WorkbenchClientPackageEntity entity) {
|
||||
return entity.getCreatedAt() == null ? "" : entity.getCreatedAt().format(CREATED_AT_FORMATTER);
|
||||
}
|
||||
|
||||
private Map<String, Object> toItemMap(WorkbenchClientPackageEntity entity) {
|
||||
Map<String, Object> item = new LinkedHashMap<>();
|
||||
item.put("id", entity.getId());
|
||||
item.put("version", entity.getVersion() == null ? "" : entity.getVersion());
|
||||
item.put("file_name", entity.getFileName() == null ? "" : entity.getFileName());
|
||||
item.put("object_key", entity.getObjectKey() == null ? "" : entity.getObjectKey());
|
||||
item.put("file_size", entity.getFileSize() == null ? 0L : entity.getFileSize());
|
||||
item.put("sha256", entity.getSha256() == null ? "" : entity.getSha256());
|
||||
item.put("file_url", downloadUrl(entity));
|
||||
item.put("created_at", formatCreatedAt(entity));
|
||||
return item;
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,13 @@ AIIMAGE_INSTANCE_ID=local-121
|
||||
AIIMAGE_SERVER_PORT=18080
|
||||
AIIMAGE_INTERNAL_TOKEN=change-me-local-internal-token
|
||||
|
||||
# 代理/LLM 损耗保护:异常放大时暂停该账号新任务;共享密钥超过阈值只提示不暂停。
|
||||
AIIMAGE_COST_GUARD_ENABLED=true
|
||||
AIIMAGE_COST_GUARD_PROXY_WINDOW_THRESHOLD=600
|
||||
AIIMAGE_COST_GUARD_LLM_WINDOW_CALLS_THRESHOLD=180
|
||||
AIIMAGE_COST_GUARD_LLM_WINDOW_TOKENS_THRESHOLD=600000
|
||||
AIIMAGE_COST_GUARD_SHARED_ACCOUNTS_THRESHOLD=3
|
||||
|
||||
AIIMAGE_DB_URL=jdbc:mysql://127.0.0.1:3306/aiimage?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&useSSL=false
|
||||
AIIMAGE_DB_USERNAME=change-me
|
||||
AIIMAGE_DB_PASSWORD=change-me
|
||||
|
||||
@@ -501,6 +501,21 @@ aiimage:
|
||||
archive-connect-timeout-millis: ${AIIMAGE_IMAGE_VIDEO_ARCHIVE_CONNECT_TIMEOUT_MILLIS:10000}
|
||||
archive-read-timeout-millis: ${AIIMAGE_IMAGE_VIDEO_ARCHIVE_READ_TIMEOUT_MILLIS:600000}
|
||||
archive-max-attempts: ${AIIMAGE_IMAGE_VIDEO_ARCHIVE_MAX_ATTEMPTS:3}
|
||||
# 代理/LLM 损耗保护:分钟增量与当日累计双阈值,命中即暂停该账号新任务;
|
||||
# 共享密钥阈值只提示不暂停(共用本身不是故障,但会把异常消耗放大到所有账号)。
|
||||
cost-guard:
|
||||
enabled: ${AIIMAGE_COST_GUARD_ENABLED:true}
|
||||
scan-interval-ms: ${AIIMAGE_COST_GUARD_SCAN_INTERVAL_MS:60000}
|
||||
scan-initial-delay-ms: ${AIIMAGE_COST_GUARD_SCAN_INITIAL_DELAY_MS:30000}
|
||||
window-seconds: ${AIIMAGE_COST_GUARD_WINDOW_SECONDS:60}
|
||||
proxy-window-threshold: ${AIIMAGE_COST_GUARD_PROXY_WINDOW_THRESHOLD:600}
|
||||
llm-window-calls-threshold: ${AIIMAGE_COST_GUARD_LLM_WINDOW_CALLS_THRESHOLD:180}
|
||||
llm-window-tokens-threshold: ${AIIMAGE_COST_GUARD_LLM_WINDOW_TOKENS_THRESHOLD:600000}
|
||||
daily-proxy-threshold: ${AIIMAGE_COST_GUARD_DAILY_PROXY_THRESHOLD:8000}
|
||||
daily-llm-calls-threshold: ${AIIMAGE_COST_GUARD_DAILY_LLM_CALLS_THRESHOLD:6000}
|
||||
daily-llm-tokens-threshold: ${AIIMAGE_COST_GUARD_DAILY_LLM_TOKENS_THRESHOLD:20000000}
|
||||
shared-accounts-threshold: ${AIIMAGE_COST_GUARD_SHARED_ACCOUNTS_THRESHOLD:3}
|
||||
shared-scan-interval-ms: ${AIIMAGE_COST_GUARD_SHARED_SCAN_INTERVAL_MS:600000}
|
||||
user-secret:
|
||||
check-enabled: ${AIIMAGE_USER_SECRET_CHECK_ENABLED:true}
|
||||
check-cron: ${AIIMAGE_USER_SECRET_CHECK_CRON:0 30 4 * * *}
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
-- =============================================================
|
||||
-- 迁移 V166__remove_admin_brand_gating_menu
|
||||
--
|
||||
-- 1. 变更目的:按 2026-10-24 决定回滚「品牌Gating库」——删除 V164 落库的
|
||||
-- admin_brand_gating 后台菜单行及全部账号对它的直授;后管页面与入口同步下线。
|
||||
-- V164 文件本身保留(Flyway validate-on-migrate 要求已应用迁移可解析,禁止删文件)。
|
||||
--
|
||||
-- 2. 顺序:先删授权(user_column_permission → columns 无级联,残留会指向不存在的行),
|
||||
-- 再删菜单行。该行是叶子节点,父分组 admin_group_data 保留。
|
||||
--
|
||||
-- 3. 可重跑性:两条 DELETE 命中 0 行即 no-op。
|
||||
--
|
||||
-- 4. 回滚(如需恢复):重跑 V164 的菜单 INSERT,并按需重新发放授权。
|
||||
-- =============================================================
|
||||
|
||||
DELETE g
|
||||
FROM `user_column_permission` g
|
||||
JOIN `columns` c ON c.`id` = g.`column_id`
|
||||
WHERE c.`column_key` = 'admin_brand_gating';
|
||||
|
||||
DELETE FROM `columns`
|
||||
WHERE `column_key` = 'admin_brand_gating';
|
||||
@@ -0,0 +1,100 @@
|
||||
-- =============================================================
|
||||
-- 迁移 V167__workbench_client_package
|
||||
--
|
||||
-- 1. 变更目的:新增「数富AI工作台客户端包管理」独立渠道。
|
||||
-- - 新表 biz_workbench_client_package 存版本号、文件名、MinIO 对象 key、大小、sha256、上传时间。
|
||||
-- - 包体落公开 client 桶 workbench-client/versions/ 前缀,与桌面端 ShuFuAI 的
|
||||
-- nanri-image/versions/ 隔离;客户端从 /api/workbench-client/version/latest 自动检查更新。
|
||||
-- - 后台菜单 column_key='admin_workbench_client_package',
|
||||
-- route_path='records/workbench-client-package',挂在「记录与版本」组下,排序 83。
|
||||
--
|
||||
-- 2. 口径:
|
||||
-- - 最新包按 created_at DESC, id DESC 取第一条(不设 is_latest 标记);删掉最新包后
|
||||
-- 客户端下一次检查自动回落到上一版。
|
||||
-- - sha256 NOT NULL:后台上传 confirm 阶段由服务端从 MinIO 实物流式复算,空值直接拒绝落库。
|
||||
-- - 菜单 company_id=1 为模板树;其余公司(含停用公司)逐家复制,子行 parent_id 必须认
|
||||
-- 本公司的 admin_group_record 组行,严禁跨公司认父(V149/V164 同一口径)。
|
||||
-- - 本迁移不预授 user_column_permission:该页是管理/平台页(后端 requireAdmin),
|
||||
-- 管理员后续在「菜单权限配置」里按公司分配可见性。
|
||||
--
|
||||
-- 3. 影响表与数据量:新表 1 张;columns +N 行(N=公司数)。字典小表,毫秒级。
|
||||
--
|
||||
-- 4. 【可重跑性】建表 IF NOT EXISTS;两段菜单 INSERT 带 NOT EXISTS 守卫;重跑逐条 no-op。
|
||||
--
|
||||
-- 5. 回滚(如需):
|
||||
-- DELETE FROM columns WHERE column_key='admin_workbench_client_package';
|
||||
-- DROP TABLE IF EXISTS biz_workbench_client_package;
|
||||
-- =============================================================
|
||||
|
||||
CREATE TABLE IF NOT EXISTS `biz_workbench_client_package` (
|
||||
`id` BIGINT NOT NULL AUTO_INCREMENT,
|
||||
`version` VARCHAR(64) NOT NULL COMMENT '客户端版本号(客户端据此判断是否升级)',
|
||||
`file_name` VARCHAR(255) NOT NULL COMMENT '原始 zip 文件名(展示用)',
|
||||
`object_key` VARCHAR(512) NOT NULL COMMENT 'MinIO 对象 key(client 桶,workbench-client/versions/ 前缀)',
|
||||
`file_size` BIGINT NOT NULL DEFAULT 0 COMMENT '文件字节数',
|
||||
`sha256` VARCHAR(64) NOT NULL COMMENT '更新包 sha256(hex 小写),客户端下载后的完整性锚点',
|
||||
`created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '上传时间;最新一条即客户端更新目标',
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `uk_workbench_client_object_key` (`object_key`),
|
||||
KEY `idx_workbench_client_created_at` (`created_at`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='数富AI工作台客户端安装/更新包';
|
||||
|
||||
-- ---------- 1. 公司 1 模板行(认公司 1 的 admin_group_record 组行) ----------
|
||||
INSERT INTO `columns` (`name`, `column_key`, `menu_type`, `route_path`, `sort_order`, `parent_id`, `company_id`)
|
||||
SELECT '工作台客户端包管理', 'admin_workbench_client_package', 'admin', 'records/workbench-client-package', 83, grp.`id`, 1
|
||||
FROM `columns` grp
|
||||
WHERE grp.`company_id` = 1 AND grp.`column_key` = 'admin_group_record'
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM `columns`
|
||||
WHERE `company_id` = 1
|
||||
AND (`column_key` = 'admin_workbench_client_package'
|
||||
OR (`menu_type` = 'admin' AND `route_path` = 'records/workbench-client-package'))
|
||||
);
|
||||
|
||||
-- ---------- 2. 复制到其余公司(含停用公司),各自认本公司组行 ----------
|
||||
INSERT INTO `columns` (`name`, `column_key`, `menu_type`, `route_path`, `sort_order`, `parent_id`, `company_id`)
|
||||
SELECT '工作台客户端包管理', 'admin_workbench_client_package', 'admin', 'records/workbench-client-package', 83, grp.`id`, c.`id`
|
||||
FROM `company` c
|
||||
JOIN `columns` grp ON grp.`company_id` = c.`id` AND grp.`column_key` = 'admin_group_record'
|
||||
WHERE c.`id` <> 1
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM `columns` col
|
||||
WHERE col.`company_id` = c.`id`
|
||||
AND (col.`column_key` = 'admin_workbench_client_package'
|
||||
OR (col.`menu_type` = 'admin' AND col.`route_path` = 'records/workbench-client-package'))
|
||||
);
|
||||
|
||||
-- ---------- 3. 自检闸门:不为 0 就抛 1048(V143/V149/V164 家族) ----------
|
||||
CREATE TEMPORARY TABLE IF NOT EXISTS `_v167_gate` (`must_be_zero` INT NOT NULL);
|
||||
|
||||
-- 闸门 1:每家公司都必须恰好一行 admin_workbench_client_package(少一家=那家管理员静默看不到)
|
||||
INSERT INTO `_v167_gate`
|
||||
SELECT IF(COUNT(*) = 0, 0, NULL)
|
||||
FROM (
|
||||
SELECT c.`id`
|
||||
FROM `company` c
|
||||
LEFT JOIN `columns` col ON col.`company_id` = c.`id` AND col.`column_key` = 'admin_workbench_client_package'
|
||||
GROUP BY c.`id`
|
||||
HAVING COUNT(col.`id`) <> 1
|
||||
) bad;
|
||||
|
||||
-- 闸门 2:admin/records/workbench-client-package 路由不允许被别的 column_key 占行
|
||||
INSERT INTO `_v167_gate`
|
||||
SELECT IF(COUNT(*) = 0, 0, NULL)
|
||||
FROM `columns` col
|
||||
WHERE col.`menu_type` = 'admin'
|
||||
AND col.`route_path` = 'records/workbench-client-package'
|
||||
AND col.`column_key` <> 'admin_workbench_client_package';
|
||||
|
||||
-- 闸门 3:该菜单行的父必须是本公司的 admin_group_record 组行
|
||||
INSERT INTO `_v167_gate`
|
||||
SELECT IF(COUNT(*) = 0, 0, NULL)
|
||||
FROM (
|
||||
SELECT col.`id`
|
||||
FROM `columns` col
|
||||
LEFT JOIN `columns` grp ON grp.`id` = col.`parent_id` AND grp.`column_key` = 'admin_group_record'
|
||||
WHERE col.`column_key` = 'admin_workbench_client_package'
|
||||
AND (grp.`id` IS NULL OR grp.`company_id` <> col.`company_id`)
|
||||
) bad;
|
||||
|
||||
DROP TEMPORARY TABLE `_v167_gate`;
|
||||
@@ -0,0 +1,30 @@
|
||||
-- =============================================================
|
||||
-- 迁移 V168__user_task_guard
|
||||
--
|
||||
-- 1. 变更目的:新增「账号级任务暂停闸」。
|
||||
-- - 代理提取 / LLM 调用在短时间内异常放大(或同一把密钥被过多账号共用)时,
|
||||
-- 由 CostGuardScheduler 自动置 paused=1,所有派发入口据此停新任务;
|
||||
-- - 用户在客户端排查后点「继续任务」,走 resume 接口置 paused=0。
|
||||
-- - 暂停只停新派发,不删除、不回滚已完成的任务与结果行。
|
||||
--
|
||||
-- 2. 口径:
|
||||
-- - 一行一个 user_id(主键),无记录 = 未暂停;
|
||||
-- - reason 存给用户看的暂停原因(含触发数值),最长 512;
|
||||
-- - paused_at 只记录最后一次自动暂停时刻,恢复时清空。
|
||||
--
|
||||
-- 3. 影响表与数据量:新表 1 张,空表,无存量数据迁移。
|
||||
--
|
||||
-- 4. 【可重跑性】CREATE TABLE IF NOT EXISTS,重跑 no-op。
|
||||
--
|
||||
-- 5. 回滚(如需):DROP TABLE IF EXISTS `biz_user_task_guard`;
|
||||
-- =============================================================
|
||||
|
||||
CREATE TABLE IF NOT EXISTS `biz_user_task_guard` (
|
||||
`user_id` BIGINT NOT NULL COMMENT '账号 id',
|
||||
`paused` TINYINT(1) NOT NULL DEFAULT 0 COMMENT '1=暂停新任务派发',
|
||||
`reason` VARCHAR(512) NOT NULL DEFAULT '' COMMENT '暂停原因(展示给用户)',
|
||||
`paused_at` DATETIME NULL COMMENT '最后一次自动暂停时刻',
|
||||
`updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
PRIMARY KEY (`user_id`),
|
||||
KEY `idx_user_task_guard_paused` (`paused`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='账号级任务暂停闸(损耗保护)';
|
||||
@@ -22,4 +22,23 @@
|
||||
updated_at = NOW()
|
||||
WHERE user_id = #{userId} AND module_key = #{moduleKey} AND business_date = #{businessDate}
|
||||
</update>
|
||||
<select id="sumByUserAndModule" resultType="com.nanri.aiimage.modules.usersecret.model.dto.UserSecretUsageAggregate">
|
||||
SELECT user_id AS userId,
|
||||
module_key AS moduleKey,
|
||||
COALESCE(SUM(call_count), 0) AS callCount,
|
||||
COALESCE(SUM(prompt_tokens + completion_tokens), 0) AS tokens
|
||||
FROM biz_user_secret_usage_daily
|
||||
WHERE business_date = #{businessDate}
|
||||
GROUP BY user_id, module_key
|
||||
</select>
|
||||
<select id="sumForUser" resultType="com.nanri.aiimage.modules.usersecret.model.dto.UserSecretUsageAggregate">
|
||||
SELECT user_id AS userId,
|
||||
module_key AS moduleKey,
|
||||
COALESCE(SUM(call_count), 0) AS callCount,
|
||||
COALESCE(SUM(prompt_tokens + completion_tokens), 0) AS tokens
|
||||
FROM biz_user_secret_usage_daily
|
||||
WHERE business_date = #{businessDate}
|
||||
AND user_id = #{userId}
|
||||
GROUP BY user_id, module_key
|
||||
</select>
|
||||
</mapper>
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
|
||||
<mapper namespace="com.nanri.aiimage.modules.usersecret.mapper.UserTaskGuardMapper">
|
||||
<insert id="pause">
|
||||
INSERT INTO biz_user_task_guard (user_id, paused, reason, paused_at, updated_at)
|
||||
VALUES (#{userId}, 1, #{reason}, NOW(), NOW())
|
||||
ON DUPLICATE KEY UPDATE paused = 1, reason = #{reason},
|
||||
paused_at = NOW(), updated_at = NOW()
|
||||
</insert>
|
||||
<update id="resume">
|
||||
UPDATE biz_user_task_guard
|
||||
SET paused = 0, reason = '', paused_at = NULL, updated_at = NOW()
|
||||
WHERE user_id = #{userId}
|
||||
</update>
|
||||
</mapper>
|
||||
@@ -59,7 +59,9 @@ class MigratedSqlEquivalenceTest {
|
||||
// 67 → 78:keywordshare 模块新写 11 条 select,逐条登记进下方 NOT_MIGRATED。
|
||||
// 78 → 86:brandgating 模块新写 8 条 select,同样逐条点入
|
||||
// (与 SqlLayeringConventionTest.XML_STATEMENT_TOTAL 同轮 99 → 115 → 124)。
|
||||
private static final int XML_SELECT_TOTAL = 86;
|
||||
// 86 → 88:损耗监控在 UserSecretUsageMapper 新写 2 条聚合 select,逐条点入
|
||||
// (SqlLayeringConventionTest.XML_STATEMENT_TOTAL 同轮 124 → 126)。
|
||||
private static final int XML_SELECT_TOTAL = 88;
|
||||
|
||||
/**
|
||||
* 不是「从注解搬过来」的语句:注解时代没有原文可对撞,等价性这支只能跳过它们。
|
||||
@@ -92,7 +94,10 @@ class MigratedSqlEquivalenceTest {
|
||||
"BrandGatingMapper#countDistinctBrands",
|
||||
"BrandGatingMapper#countGroupByType",
|
||||
"BrandGatingMapper#countGroupByCountry",
|
||||
"BrandGatingMapper#countGroupBySource");
|
||||
"BrandGatingMapper#countGroupBySource",
|
||||
// 损耗监控(2026-10-24)新写的 2 条聚合 select:当日全量扫描 + 单用户读数。
|
||||
"UserSecretUsageMapper#sumByUserAndModule",
|
||||
"UserSecretUsageMapper#sumForUser");
|
||||
|
||||
/** 账本 5 列:接口 / 方法 / @Select 种类 / 是否含常量插值 / 注解原文(Java 反转义后那条串)。 */
|
||||
private static final int LEDGER_COLUMNS = 5;
|
||||
|
||||
@@ -75,7 +75,10 @@ class SqlLayeringConventionTest {
|
||||
// 99 → 115:keywordshare 模块(五国关键词共享网页化,5 份 XML 16 条)新写语句。
|
||||
// 115 → 124:brandgating 模块(品牌Gating库并入管理后台,1 份 XML 9 条)新写语句;
|
||||
// 两批 19 条 select 逐条登记进 MigratedSqlEquivalenceTest.NOT_MIGRATED(67 → 78 → 86)。
|
||||
private static final int XML_STATEMENT_TOTAL = 124;
|
||||
// 124 → 126:损耗监控在 {@code UserSecretUsageMapper} 新写 2 条聚合 select
|
||||
// (当日全量扫描 + 单用户读数),同样逐条登记进 NOT_MIGRATED(86 → 88)。
|
||||
// 126 → 128:同轮 {@code UserTaskGuardMapper} 的 pause/resume 两条写侧语句从注解迁进 XML。
|
||||
private static final int XML_STATEMENT_TOTAL = 128;
|
||||
|
||||
/**
|
||||
* wrapper 里夹带函数级 SQL 的现状("这不是简单单表"的证据),文件名 → 条数:
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
package com.nanri.aiimage.common.retry;
|
||||
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.web.client.HttpClientErrorException;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
class LlmKeyGateTest {
|
||||
|
||||
@AfterEach
|
||||
void tearDown() {
|
||||
LlmKeyGate.resetForTests();
|
||||
}
|
||||
|
||||
@Test
|
||||
void recognizesRateLimitThroughExceptionChain() {
|
||||
assertThat(LlmKeyGate.isRateLimited(
|
||||
new HttpClientErrorException(HttpStatus.TOO_MANY_REQUESTS))).isTrue();
|
||||
assertThat(LlmKeyGate.isRateLimited(
|
||||
new IllegalStateException("wrapped",
|
||||
new HttpClientErrorException(HttpStatus.TOO_MANY_REQUESTS)))).isTrue();
|
||||
assertThat(LlmKeyGate.isRateLimited(
|
||||
new IllegalStateException("read timeout"))).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void permitIsReleasedAfterUse() {
|
||||
try (LlmKeyGate.Permit ignored = LlmKeyGate.acquire("shared-key")) {
|
||||
assertThat(ignored).isNotNull();
|
||||
}
|
||||
// 能再次拿到同一个 key 的许可,说明 close 归还了信号量
|
||||
try (LlmKeyGate.Permit ignored = LlmKeyGate.acquire("shared-key")) {
|
||||
assertThat(ignored).isNotNull();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -65,7 +65,8 @@ class AdminGuardSwitchConfigTest {
|
||||
private static final String ANCHOR = AdminApiGuardFilter.SWITCH_ANCHOR;
|
||||
|
||||
private static final int USER_TOOL_PREFIX_COUNT = 15;
|
||||
private static final int SELF_SERVICE_PREFIX_COUNT = 6;
|
||||
// 6 → 7:损耗监控 /api/user/cost-guard 进无条件名单(uid 只从 JWT 取,匿名不该能解除暂停闸)。
|
||||
private static final int SELF_SERVICE_PREFIX_COUNT = 7;
|
||||
|
||||
/** {@code ${ENV:默认}} 形状;只取默认段,判的是出厂值,不受跑测试的机器上的环境变量影响。 */
|
||||
private static final Pattern PLACEHOLDER = Pattern.compile("^\\$\\{([^:}]+):([^}]*)\\}$");
|
||||
|
||||
+4
-2
@@ -67,8 +67,10 @@ class ApiGuardCoverageAuditorTest {
|
||||
assertTrue(guarded.contains("/debug"), "debug 前缀没进自检可见名单");
|
||||
// 这两组条数是实测基线(2026-10-08:用户态 15 条、自助 6 条)。
|
||||
// 只钉"contains 某条"的话,从数组里删掉一整段都可能不红,所以钉总数。
|
||||
assertEquals(22, count(guarded, "/api/"), () -> "以 /api/ 开头的守卫前缀数变了(基线 22 = admin 1 + 用户态 15 + 自助 6):" + guarded);
|
||||
assertEquals(23, guarded.size(), "守卫前缀总数变了(22 条 /api/ + /debug):" + guarded);
|
||||
// 2026-10-24 自助 6 → 7:cost-guard 的 status/resume 两个端点 uid 只从 JWT 取,
|
||||
// 匿名既读不到状态也不该能解除暂停闸,所以进无条件名单而不是登记成「方法内自校验」。
|
||||
assertEquals(23, count(guarded, "/api/"), () -> "以 /api/ 开头的守卫前缀数变了(基线 23 = admin 1 + 用户态 15 + 自助 7):" + guarded);
|
||||
assertEquals(24, guarded.size(), "守卫前缀总数变了(23 条 /api/ + /debug):" + guarded);
|
||||
assertTrue(guarded.contains("/api/publish"), "2026-10-07 补的上架前缀不能退回名单外");
|
||||
assertTrue(guarded.contains("/api/tasks"), "心跳/打断前缀不能退回名单外");
|
||||
assertTrue(guarded.contains("/api/internal"), "内部端点前缀不能退回名单外");
|
||||
|
||||
@@ -47,8 +47,9 @@ class CatchSilenceRatchetTest {
|
||||
// ==== 验收基线(用户 2026-10-08 12:0x 实测,HEAD 274ad017,单位:处)====
|
||||
// 10-17 心跳证据两处 fail-open 抬 559 -> 561,逐处出处见 STRICT_NOT_RETHROW 上方注释。
|
||||
// 10-18 外观专利失败兜底自吞抬 561 -> 562,逐处出处同下。
|
||||
// 10-24 损耗监控三处带锚点的 fail-open 抬 562 -> 564,逐处出处见 STRICT_NOT_RETHROW 上方注释。
|
||||
static final int GIVEN_TOTAL = 1000;
|
||||
static final int GIVEN_NOT_RETHROW = 562;
|
||||
static final int GIVEN_NOT_RETHROW = 564;
|
||||
static final int GIVEN_LOG_ONLY = 249;
|
||||
static final int GIVEN_EMPTY = 56;
|
||||
|
||||
@@ -71,6 +72,28 @@ class CatchSilenceRatchetTest {
|
||||
* 契约明确要求「实现应自吞异常(兜底失败只记日志,不影响 job 已终态失败的事实)」,与
|
||||
* DeleteBrandRunService 同名兜底同形状;Worker 侧另有 catch 双保险,让判死作业的兜底每轮
|
||||
* stuck 扫描幂等重入。实测 1004。
|
||||
* 10-24 损耗监控(cost-guard)本笔新增 6 处,逐处点名(同批先写后摘、没留在树上的 6 处:
|
||||
* SHA-256 指纹改走 {@code DigestUtil.sha256Hex}、env 读数改纯正则前置校验、共享密钥扫描的
|
||||
* 自吞交给 {@code scan()} 已有的那枚、当日用量读数改成直接抛(客户端把轮询失败当
|
||||
* 「维持上一次读数」处理,比伪造一组零值诚实)、{@code resume()} 的吞异常改成外抛——
|
||||
* 它返回 false 时控制器仍回「已继续任务」,那是假成功):
|
||||
* <ul>
|
||||
* <li>{@code LlmKeyGate.Gate.acquire()} 两枚:{@code InterruptedException} ⇒ 复位中断位并重抛
|
||||
* IllegalStateException;{@code RuntimeException} ⇒ 先 {@code permits.release()} 再原样重抛,
|
||||
* 少了这一处排队令牌就永久漏一个(两枚都是 RETHROW 形状);</li>
|
||||
* <li>{@code LlmKeyGate.Gate.waitForInterval()} 一枚:同为 InterruptedException 重抛形状;</li>
|
||||
* <li>{@code CostGuardScheduler.scan()} 一枚:调度线程整轮异常只打 {@code [cost-guard]} WARN,
|
||||
* 下一轮照跑——让它抛出等于这条监控自己变成噪声源;</li>
|
||||
* <li>{@code UserTaskGuardService.pause()} 一枚:单个账号的暂停写失败不能中止整轮扫描
|
||||
* (否则排在这之后的账号这轮全不被检查),下一轮还会再判一次;</li>
|
||||
* <li>{@code UserTaskGuardService.load()} 一枚:读不到闸门状态按「未暂停」走——数据库抖动
|
||||
* 不该把全体用户的合法任务一起冻住,真失控由下一轮重新置位。</li>
|
||||
* </ul>
|
||||
* 本格实测 1004:这 6 处落进的是 1004 之前已被更早删腾出、无人认领的额度里(上一笔整树实测
|
||||
* 997,见 RETHROW_FLOOR 上方),所以基线不抬反而按实测收到 1003;**再 +1 是同一时段
|
||||
* {@code ba20f5ed feat(workbench-client)} 那枚新增 catch,不属本批、也未由本批记名**,
|
||||
* 该由那一笔自己把出处补进这份 diff。每一处本批的新增都在这里点名。
|
||||
* 不重抛/只 log/空体三格上限一个字没动。
|
||||
*/
|
||||
static final int STRICT_TOTAL = 1004;
|
||||
/**
|
||||
@@ -144,15 +167,28 @@ class CatchSilenceRatchetTest {
|
||||
* 与 {@code DeleteBrandRunService.fallbackAssembleResultFile} 同形状、同性质:兜底失败不得掩盖
|
||||
* 作业已终态失败的事实,也不得打断 stuck 扫描对终态失败作业的幂等重入。形状是 log+return false,
|
||||
* 因此只进本格与 total,不进 STRICT_LOG_ONLY(严格口径不数 log 后接 return)。
|
||||
* 10-24 抬 562 -> 564,逐处记名(损耗监控 cost-guard 的三处 fail-open,都带 {@code [cost-guard]}
|
||||
* 日志锚点、巡检按锚点数得到,不是「异常到此为止外面看不见」那种无声出口):
|
||||
* 1){@code CostGuardScheduler.scan()}:整轮扫描异常只 WARN——这条监控抛出就等于自己变成
|
||||
* 现网噪声源,而下一轮 fixedDelay 照跑,暂停判定不会因此停摆;
|
||||
* 2){@code UserTaskGuardService.pause()}:单个账号的暂停写失败若外抛,{@code runOnce} 的
|
||||
* 逐账号循环就地中止,排在这之后的账号这一轮全部不被检查(最坏晚一个间隔才暂停=多烧钱);
|
||||
* 3){@code UserTaskGuardService.load()}:读不到闸门状态按「未暂停」走——一次库抖动不该把
|
||||
* 全体用户的合法任务一起冻住,真失控由下一轮扫描重新置位(方向是「少冻一个号」)。
|
||||
* 其中 1)、2) 块体只有一句 log,故同时进 STRICT_LOG_ONLY;3) 是 log+return,不进。
|
||||
* 同批先写后摘、没留在树上的 6 处静默出口见 total 那一格的点名。
|
||||
*/
|
||||
static final int STRICT_NOT_RETHROW = 562;
|
||||
static final int STRICT_NOT_RETHROW = 564;
|
||||
/**
|
||||
* 10-17 抬 172 -> 173,出处就是上面点名过的 {@code TaskHeartbeatLivenessService.stamp()}:
|
||||
* 块体只有「取到 key 名 + log.warn」一句,写心跳证据失败时既不重试也不抛出——
|
||||
* 心跳接口不许因为「记不下证据」而 500。同类的 {@code lastHeartbeatMillis()} 读失败还要
|
||||
* 落 0 返回,形状是 log+return 默认值,因此不进这一格。
|
||||
* 10-24 抬 173 -> 175,出处即上面 STRICT_NOT_RETHROW 里点名过的 cost-guard 两处:
|
||||
* {@code CostGuardScheduler.scan()} 与 {@code UserTaskGuardService.pause()}——块体各只有一句
|
||||
* {@code log.warn}/{@code log.error},都是带锚点的 fail-open,不是把已有出口改回吞掉。
|
||||
*/
|
||||
static final int STRICT_LOG_ONLY = 173; // 严格口径:块内每条顶层语句都是 log 调用才算
|
||||
static final int STRICT_LOG_ONLY = 175; // 严格口径:块内每条顶层语句都是 log 调用才算
|
||||
static final int STRICT_EMPTY = 56;
|
||||
|
||||
/**
|
||||
|
||||
+79
@@ -81,6 +81,31 @@ class BrandCheckClientTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void pausedAccountStopsBatchWithoutHittingUpstream() throws Exception {
|
||||
AtomicInteger attempts = new AtomicInteger();
|
||||
HttpServer server = startBrandCheckServer(exchange -> {
|
||||
attempts.incrementAndGet();
|
||||
respond(exchange, "{\"faild_data\":[],\"query_faild_data\":[]}");
|
||||
});
|
||||
try {
|
||||
BrandCheckClient client = newClient(server, 3);
|
||||
com.nanri.aiimage.modules.usersecret.service.UserTaskGuardService guard =
|
||||
mock(com.nanri.aiimage.modules.usersecret.service.UserTaskGuardService.class);
|
||||
when(guard.isPaused(7L)).thenReturn(true);
|
||||
ReflectionTestUtils.setField(client, "taskGuard", guard);
|
||||
|
||||
BrandCheckClient.BrandCheckBatchResult result =
|
||||
client.checkAll(List.of("Apple", "Nike"), "Terms", 7L);
|
||||
|
||||
assertThat(attempts.get()).as("账号已暂停时一个上游请求都不该发").isZero();
|
||||
assertThat(result.queryFaildData()).containsExactly("Apple", "Nike");
|
||||
assertThat(result.reason()).contains("账号任务已暂停");
|
||||
} finally {
|
||||
server.stop(0);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void queryFailureRetriesUntilSuccess() throws Exception {
|
||||
AtomicInteger attempts = new AtomicInteger();
|
||||
@@ -176,6 +201,60 @@ class BrandCheckClientTest {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 出口被上游连续拒绝时,整批不再给每个品牌各发一次首轮探针。
|
||||
*
|
||||
* <p>2026-10-23 账单形状:16890 每个品牌最多换 2 个出口 IP,Java 再按品牌重试
|
||||
* 10 轮;一批几千个品牌就是几千×2 次提取。出口熔断证据只需前 2 个品牌,
|
||||
* 后面的品牌直接判查询失败转补测。
|
||||
*/
|
||||
@Test
|
||||
void egressClassifierMatchesUpstreamReason() {
|
||||
assertThat(com.nanri.aiimage.modules.brand.support.BrandCheckFailureNotice.isEgressRejected(
|
||||
"上游拒绝代理出口 IP,换 IP 重试仍未放行")).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void egressReasonParsesFromUpstream() throws Exception {
|
||||
HttpServer server = startBrandCheckServer(exchange -> respond(exchange,
|
||||
"{\"faild_data\":[],\"query_faild_data\":[\"x\"],"
|
||||
+ "\"reason\":\"上游拒绝代理出口 IP,换 IP 重试仍未放行\",\"retryable\":false}"));
|
||||
try {
|
||||
BrandCheckClient client = newClient(server, 1);
|
||||
BrandCheckClient.BrandCheckResponse response = client.check("b1", "Terms", 7L);
|
||||
assertThat(response.getReason()).contains("代理出口");
|
||||
assertThat(response.isRetryable()).isFalse();
|
||||
} finally {
|
||||
server.stop(0);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void egressRejectionStopsBatchAfterTwoBrands() throws Exception {
|
||||
AtomicInteger requests = new AtomicInteger();
|
||||
HttpServer server = startBrandCheckServer(exchange -> {
|
||||
requests.incrementAndGet();
|
||||
respond(exchange, "{\"faild_data\":[],\"query_faild_data\":[\"x\"],"
|
||||
+ "\"reason\":\"上游拒绝代理出口 IP,换 IP 重试仍未放行\",\"retryable\":false}");
|
||||
});
|
||||
try {
|
||||
BrandCheckClient client = newClient(server, 10);
|
||||
List<String> brands = List.of("b1", "b2", "b3", "b4", "b5", "b6", "b7", "b8");
|
||||
|
||||
BrandCheckClient.BrandCheckBatchResult result = client.checkAll(brands, "Terms", 7L);
|
||||
|
||||
assertThat(requests.get())
|
||||
// 检查池并发 3:三条在飞 + 一条在首个响应回来后替补进来,最多 4 次;
|
||||
// 关键是这个上界与品牌数无关,不能回到「品牌数 × 10 轮」的放大形态
|
||||
.as("出口被拒后只允许并发在飞的前几个品牌各打一次,不能按品牌数×10 轮放大")
|
||||
.isBetween(1, 4);
|
||||
assertThat(result.hasQueryFailedData()).isTrue();
|
||||
assertThat(result.reason()).contains("代理出口");
|
||||
} finally {
|
||||
server.stop(0);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 短路判据必须保守:只有"跑满整条阶梯仍每轮查询失败"才成立。
|
||||
* 成功品牌首轮就返回、从不置标志,所以同一批里的个别失败品牌要照旧拿满它的重试机会——
|
||||
|
||||
+18
@@ -31,6 +31,24 @@ import static org.mockito.Mockito.when;
|
||||
|
||||
class PriceTrackLoopRunServiceTest {
|
||||
|
||||
@Test
|
||||
void pausedAccountCannotDispatchNext() {
|
||||
PriceTrackLoopRunMapper loopRunMapper = mock(PriceTrackLoopRunMapper.class);
|
||||
PriceTrackLoopRunService service = new PriceTrackLoopRunService(
|
||||
loopRunMapper, mock(FileTaskMapper.class), new ObjectMapper(),
|
||||
mock(ZiniaoShopSwitchService.class));
|
||||
com.nanri.aiimage.modules.usersecret.service.UserTaskGuardService guard =
|
||||
mock(com.nanri.aiimage.modules.usersecret.service.UserTaskGuardService.class);
|
||||
when(guard.isPaused(1L)).thenReturn(true);
|
||||
org.springframework.test.util.ReflectionTestUtils.setField(service, "taskGuard", guard);
|
||||
|
||||
BusinessException error = assertThrows(BusinessException.class,
|
||||
() -> service.dispatchNext(743L, 1L));
|
||||
|
||||
assertTrue(error.getMessage().contains("账号任务已暂停"));
|
||||
verify(loopRunMapper, never()).selectById(743L);
|
||||
}
|
||||
|
||||
@Test
|
||||
void syncLoopRunAfterChildTerminalUsesChildContextWhenLoopRowAlreadyDrifted() throws Exception {
|
||||
ObjectMapper objectMapper = new ObjectMapper();
|
||||
|
||||
+137
@@ -0,0 +1,137 @@
|
||||
package com.nanri.aiimage.modules.usersecret.service;
|
||||
|
||||
import com.nanri.aiimage.common.service.DistributedJobLockService;
|
||||
import com.nanri.aiimage.config.CostGuardProperties;
|
||||
import com.nanri.aiimage.modules.notification.service.NotificationDispatchService;
|
||||
import com.nanri.aiimage.modules.notification.service.NotificationService;
|
||||
import com.nanri.aiimage.modules.usersecret.mapper.UserSecretUsageMapper;
|
||||
import com.nanri.aiimage.modules.usersecret.model.dto.UserSecretUsageAggregate;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyLong;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.contains;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.ArgumentMatchers.isNull;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class CostGuardSchedulerTest {
|
||||
|
||||
@Mock
|
||||
private UserSecretUsageMapper usageMapper;
|
||||
@Mock
|
||||
private UserTaskGuardService guardService;
|
||||
@Mock
|
||||
private SharedSecretMonitorService sharedSecretMonitorService;
|
||||
@Mock
|
||||
private NotificationDispatchService notificationDispatchService;
|
||||
@Mock
|
||||
private DistributedJobLockService distributedJobLockService;
|
||||
|
||||
private CostGuardScheduler scheduler;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
CostGuardProperties properties = new CostGuardProperties();
|
||||
properties.setProxyWindowThreshold(10);
|
||||
properties.setLlmWindowCallsThreshold(5);
|
||||
properties.setLlmWindowTokensThreshold(1_000);
|
||||
properties.setDailyProxyThreshold(100);
|
||||
properties.setDailyLlmCallsThreshold(100);
|
||||
properties.setDailyLlmTokensThreshold(10_000);
|
||||
scheduler = new CostGuardScheduler(properties, usageMapper, guardService,
|
||||
sharedSecretMonitorService, notificationDispatchService, distributedJobLockService);
|
||||
}
|
||||
|
||||
@Test
|
||||
void firstScanOnlyBuildsBaseline() {
|
||||
when(usageMapper.sumByUserAndModule(any(LocalDate.class)))
|
||||
.thenReturn(List.of(row(7L, "proxy", 50, 0)));
|
||||
when(usageMapper.sumForUser(eq(7L), any(LocalDate.class)))
|
||||
.thenReturn(List.of(row(7L, "proxy", 50, 0)));
|
||||
|
||||
scheduler.runOnce();
|
||||
|
||||
verify(guardService, never()).pause(anyLong(), anyString());
|
||||
assertThat(scheduler.todayTotals(7L).proxy).isEqualTo(50);
|
||||
}
|
||||
|
||||
@Test
|
||||
void proxyWindowJumpPausesAndNotifies() {
|
||||
when(usageMapper.sumByUserAndModule(any(LocalDate.class)))
|
||||
.thenReturn(List.of(row(7L, "proxy", 0, 0)))
|
||||
.thenReturn(List.of(row(7L, "proxy", 12, 0)));
|
||||
when(guardService.isPaused(7L)).thenReturn(false);
|
||||
|
||||
scheduler.runOnce();
|
||||
scheduler.runOnce();
|
||||
|
||||
verify(guardService).pause(eq(7L), contains("代理提取 12 次"));
|
||||
verify(notificationDispatchService).pushToUser(eq(7L),
|
||||
eq(NotificationService.SCENE_COST_GUARD), eq(NotificationService.LEVEL_ERROR),
|
||||
anyString(), contains("继续任务"), isNull());
|
||||
}
|
||||
|
||||
@Test
|
||||
void llmCallsWindowJumpPauses() {
|
||||
when(usageMapper.sumByUserAndModule(any(LocalDate.class)))
|
||||
.thenReturn(List.of(row(8L, "similar-asin", 0, 0)))
|
||||
.thenReturn(List.of(row(8L, "similar-asin", 6, 100)));
|
||||
when(guardService.isPaused(8L)).thenReturn(false);
|
||||
|
||||
scheduler.runOnce();
|
||||
scheduler.runOnce();
|
||||
|
||||
verify(guardService).pause(eq(8L), contains("LLM 调用 6 次"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void dailyCrossingOnlyPausesOnceAndRespectsResetBaseline() {
|
||||
when(usageMapper.sumByUserAndModule(any(LocalDate.class)))
|
||||
.thenReturn(List.of(row(9L, "proxy", 99, 0)))
|
||||
.thenReturn(List.of(row(9L, "proxy", 100, 0)))
|
||||
.thenReturn(List.of(row(9L, "proxy", 101, 0)));
|
||||
when(guardService.isPaused(9L)).thenReturn(false);
|
||||
|
||||
scheduler.runOnce();
|
||||
scheduler.runOnce();
|
||||
scheduler.resetBaseline(9L);
|
||||
scheduler.runOnce();
|
||||
|
||||
verify(guardService).pause(eq(9L), contains("当日上限 100 次"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void alreadyPausedUserIsNotPausedAgain() {
|
||||
when(usageMapper.sumByUserAndModule(any(LocalDate.class)))
|
||||
.thenReturn(List.of(row(7L, "proxy", 0, 0)))
|
||||
.thenReturn(List.of(row(7L, "proxy", 50, 0)));
|
||||
when(guardService.isPaused(7L)).thenReturn(true);
|
||||
|
||||
scheduler.runOnce();
|
||||
scheduler.runOnce();
|
||||
|
||||
verify(guardService, never()).pause(anyLong(), anyString());
|
||||
}
|
||||
|
||||
private UserSecretUsageAggregate row(long userId, String module, long calls, long tokens) {
|
||||
UserSecretUsageAggregate row = new UserSecretUsageAggregate();
|
||||
row.setUserId(userId);
|
||||
row.setModuleKey(module);
|
||||
row.setCallCount(calls);
|
||||
row.setTokens(tokens);
|
||||
return row;
|
||||
}
|
||||
}
|
||||
+101
@@ -0,0 +1,101 @@
|
||||
package com.nanri.aiimage.modules.usersecret.service;
|
||||
|
||||
import com.nanri.aiimage.config.CostGuardProperties;
|
||||
import com.nanri.aiimage.modules.notification.service.NotificationDispatchService;
|
||||
import com.nanri.aiimage.modules.notification.service.NotificationService;
|
||||
import com.nanri.aiimage.modules.usersecret.mapper.UserApiSecretMapper;
|
||||
import com.nanri.aiimage.modules.usersecret.model.entity.UserApiSecretEntity;
|
||||
import com.nanri.aiimage.modules.usersecret.model.vo.SharedSecretWarningVo;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyLong;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.contains;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class SharedSecretMonitorServiceTest {
|
||||
|
||||
@Mock
|
||||
private UserApiSecretMapper userApiSecretMapper;
|
||||
@Mock
|
||||
private NotificationDispatchService notificationDispatchService;
|
||||
|
||||
private CostGuardProperties properties;
|
||||
private SharedSecretMonitorService service;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
properties = new CostGuardProperties();
|
||||
properties.setSharedAccountsThreshold(3);
|
||||
service = new SharedSecretMonitorService(userApiSecretMapper, properties,
|
||||
notificationDispatchService);
|
||||
}
|
||||
|
||||
@Test
|
||||
void threeAccountsSharingProxyProducesWarningAndDailyNotice() {
|
||||
when(userApiSecretMapper.selectList(any())).thenReturn(List.of(
|
||||
row(1L, "proxy", "same-cipher"),
|
||||
row(2L, "proxy", "same-cipher"),
|
||||
row(3L, "proxy", "same-cipher"),
|
||||
row(4L, "proxy", "own-cipher")));
|
||||
|
||||
service.refresh();
|
||||
|
||||
List<SharedSecretWarningVo> warnings = service.warningsFor(1L);
|
||||
assertThat(warnings).hasSize(1);
|
||||
assertThat(warnings.get(0).getType()).isEqualTo("proxy");
|
||||
assertThat(warnings.get(0).getAccounts()).isEqualTo(3);
|
||||
assertThat(warnings.get(0).getMessage()).contains("3 个账号共用").contains("拆分独立密钥");
|
||||
assertThat(service.warningsFor(4L)).isEmpty();
|
||||
verify(notificationDispatchService, times(3)).pushToUser(anyLong(),
|
||||
eq(NotificationService.SCENE_SECRET_SHARED), eq(NotificationService.LEVEL_WARNING),
|
||||
contains("3 个账号共用"), contains("拆分独立密钥"), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void belowThresholdProducesNoWarning() {
|
||||
when(userApiSecretMapper.selectList(any())).thenReturn(List.of(
|
||||
row(1L, "similar-asin", "same"),
|
||||
row(2L, "similar-asin", "same")));
|
||||
|
||||
service.refresh();
|
||||
|
||||
assertThat(service.warningsFor(1L)).isEmpty();
|
||||
verify(notificationDispatchService, never()).pushToUser(anyLong(), anyString(), anyString(),
|
||||
anyString(), anyString(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void llmModuleIsTypedAsLlm() {
|
||||
when(userApiSecretMapper.selectList(any())).thenReturn(List.of(
|
||||
row(1L, "appearance-patent", "llm-key"),
|
||||
row(2L, "appearance-patent", "llm-key"),
|
||||
row(3L, "appearance-patent", "llm-key")));
|
||||
|
||||
service.refresh();
|
||||
|
||||
assertThat(service.warningsFor(2L).get(0).getType()).isEqualTo("llm");
|
||||
assertThat(service.warningsFor(2L).get(0).getModuleLabel()).isEqualTo("外观专利密钥");
|
||||
}
|
||||
|
||||
private UserApiSecretEntity row(long userId, String moduleKey, String cipher) {
|
||||
UserApiSecretEntity row = new UserApiSecretEntity();
|
||||
row.setUserId(userId);
|
||||
row.setModuleKey(moduleKey);
|
||||
row.setSecretValue(cipher);
|
||||
return row;
|
||||
}
|
||||
}
|
||||
+66
@@ -0,0 +1,66 @@
|
||||
package com.nanri.aiimage.modules.usersecret.service;
|
||||
|
||||
import com.nanri.aiimage.modules.usersecret.mapper.UserTaskGuardMapper;
|
||||
import com.nanri.aiimage.modules.usersecret.model.entity.UserTaskGuardEntity;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class UserTaskGuardServiceTest {
|
||||
|
||||
@Mock
|
||||
private UserTaskGuardMapper guardMapper;
|
||||
|
||||
@Test
|
||||
void pausedStateIsCachedForHotPaths() {
|
||||
UserTaskGuardEntity row = new UserTaskGuardEntity();
|
||||
row.setUserId(7L);
|
||||
row.setPaused(true);
|
||||
row.setReason("代理提取异常");
|
||||
row.setPausedAt(LocalDateTime.now());
|
||||
when(guardMapper.selectById(7L)).thenReturn(row);
|
||||
UserTaskGuardService service = new UserTaskGuardService(guardMapper);
|
||||
|
||||
assertThat(service.isPaused(7L)).isTrue();
|
||||
assertThat(service.isPaused(7L)).isTrue();
|
||||
|
||||
verify(guardMapper, org.mockito.Mockito.times(1)).selectById(7L);
|
||||
}
|
||||
|
||||
@Test
|
||||
void pauseAndResumeClearCacheImmediately() {
|
||||
UserTaskGuardService service = new UserTaskGuardService(guardMapper);
|
||||
when(guardMapper.selectById(7L)).thenReturn(null);
|
||||
|
||||
service.pause(7L, "LLM 消耗异常");
|
||||
verify(guardMapper).pause(7L, "LLM 消耗异常");
|
||||
|
||||
service.resume(7L);
|
||||
verify(guardMapper).resume(7L);
|
||||
assertThat(service.isPaused(7L)).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void missingUserIsNeverPaused() {
|
||||
UserTaskGuardService service = new UserTaskGuardService(guardMapper);
|
||||
|
||||
assertThat(service.isPaused(null)).isFalse();
|
||||
assertThat(service.isPaused(0L)).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void mapperFailureFallsBackToNotPaused() {
|
||||
when(guardMapper.selectById(7L)).thenThrow(new IllegalStateException("db down"));
|
||||
UserTaskGuardService service = new UserTaskGuardService(guardMapper);
|
||||
|
||||
assertThat(service.isPaused(7L)).isFalse();
|
||||
}
|
||||
}
|
||||
+170
@@ -0,0 +1,170 @@
|
||||
package com.nanri.aiimage.modules.workbenchclient.service;
|
||||
|
||||
import com.baomidou.mybatisplus.core.MybatisConfiguration;
|
||||
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
import com.nanri.aiimage.modules.file.service.oss.OssStorageService;
|
||||
import com.nanri.aiimage.modules.workbenchclient.mapper.WorkbenchClientPackageMapper;
|
||||
import com.nanri.aiimage.modules.workbenchclient.model.entity.WorkbenchClientPackageEntity;
|
||||
import org.apache.ibatis.builder.MapperBuilderAssistant;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyList;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* 工作台客户端包独立渠道:上传确认必须由服务端把 sha256 算出来并落库。
|
||||
* 直传路径若留空摘要,客户端就只能退回「只验 zip 结构」,等于丢了完整性锚点。
|
||||
*/
|
||||
class WorkbenchClientPackageServiceTest {
|
||||
|
||||
private static final String PREFIX = WorkbenchClientPackageService.OBJECT_KEY_PREFIX;
|
||||
private static final String SHA = "b".repeat(64);
|
||||
|
||||
private final WorkbenchClientPackageMapper packageMapper = mock(WorkbenchClientPackageMapper.class);
|
||||
private final OssStorageService ossStorageService = mock(OssStorageService.class);
|
||||
|
||||
private WorkbenchClientPackageService service() {
|
||||
return new WorkbenchClientPackageService(packageMapper, ossStorageService);
|
||||
}
|
||||
|
||||
@BeforeAll
|
||||
static void initializeMybatisMetadata() {
|
||||
TableInfoHelper.initTableInfo(
|
||||
new MapperBuilderAssistant(new MybatisConfiguration(), ""), WorkbenchClientPackageEntity.class);
|
||||
}
|
||||
|
||||
private static WorkbenchClientPackageEntity row(long id, String version, String objectKey) {
|
||||
WorkbenchClientPackageEntity entity = new WorkbenchClientPackageEntity();
|
||||
entity.setId(id);
|
||||
entity.setVersion(version);
|
||||
entity.setFileName("ShuFuAI-Workbench-" + version + ".zip");
|
||||
entity.setObjectKey(objectKey);
|
||||
entity.setFileSize(1234L);
|
||||
entity.setSha256(SHA);
|
||||
entity.setCreatedAt(LocalDateTime.of(2026, 10, 24, 10, 0));
|
||||
return entity;
|
||||
}
|
||||
|
||||
@Test
|
||||
void presignUsesIndependentPrefixAndReturnsUploadUrl() {
|
||||
when(ossStorageService.presignWorkbenchClientUpload(anyString(), eq(180)))
|
||||
.thenReturn("https://oss.aishufu.top/client/workbench-client/versions/put");
|
||||
when(ossStorageService.getWorkbenchClientDownloadUrl(anyString()))
|
||||
.thenReturn("https://download.aishufu.top/client/workbench-client/versions/1.2.3.zip");
|
||||
|
||||
Map<String, Object> result = service().presignPackage("ShuFuAI-Workbench-1.2.3.zip", "1.2.3");
|
||||
|
||||
String objectKey = (String) result.get("object_key");
|
||||
assertTrue(objectKey.startsWith(PREFIX), "对象 key 必须落在独立前缀下: " + objectKey);
|
||||
assertTrue(objectKey.endsWith("-1.2.3.zip"), "对象 key 必须以版本号收尾: " + objectKey);
|
||||
assertEquals("1.2.3", result.get("version"));
|
||||
assertEquals("ShuFuAI-Workbench-1.2.3.zip", result.get("file_name"));
|
||||
assertEquals("https://oss.aishufu.top/client/workbench-client/versions/put", result.get("upload_url"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void presignRejectsNonZipAndBlankVersion() {
|
||||
assertThrows(BusinessException.class, () -> service().presignPackage("pkg.exe", "1.0.0"));
|
||||
assertThrows(BusinessException.class, () -> service().presignPackage("pkg.zip", " "));
|
||||
verifyNoInteractions(ossStorageService);
|
||||
}
|
||||
|
||||
@Test
|
||||
void confirmRecomputesSha256BeforeInsert() {
|
||||
String objectKey = PREFIX + "20261024100000123-1.2.3.zip";
|
||||
when(ossStorageService.workbenchClientObjectSize(objectKey)).thenReturn(1234L);
|
||||
when(ossStorageService.workbenchClientObjectSha256(objectKey)).thenReturn(SHA);
|
||||
when(ossStorageService.getWorkbenchClientDownloadUrl(objectKey))
|
||||
.thenReturn("https://download.aishufu.top/client/" + objectKey);
|
||||
when(packageMapper.selectCount(any())).thenReturn(0L);
|
||||
when(packageMapper.insert(any(WorkbenchClientPackageEntity.class))).thenAnswer(invocation -> {
|
||||
((WorkbenchClientPackageEntity) invocation.getArgument(0)).setId(99L);
|
||||
return 1;
|
||||
});
|
||||
when(packageMapper.selectById(99L)).thenReturn(row(99, "1.2.3", objectKey));
|
||||
|
||||
Map<String, Object> result = service().confirmPackage(
|
||||
objectKey, "ShuFuAI-Workbench-1.2.3.zip", "1.2.3");
|
||||
|
||||
assertEquals(SHA, result.get("sha256"), "返回行必须带服务端复算出的摘要");
|
||||
verify(ossStorageService).workbenchClientObjectSha256(objectKey);
|
||||
verify(packageMapper).insert(any(WorkbenchClientPackageEntity.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void confirmRejectsVersionThatDoesNotMatchObjectKey() {
|
||||
String objectKey = PREFIX + "20261024100000123-1.2.3.zip";
|
||||
|
||||
assertThrows(BusinessException.class, () -> service().confirmPackage(
|
||||
objectKey, "ShuFuAI-Workbench-1.2.4.zip", "1.2.4"));
|
||||
|
||||
verifyNoInteractions(ossStorageService);
|
||||
verify(packageMapper, never()).insert(any(WorkbenchClientPackageEntity.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void confirmRemovesOversizeObjectWithoutHashing() {
|
||||
String objectKey = PREFIX + "20261024100000123-1.2.3.zip";
|
||||
when(ossStorageService.workbenchClientObjectSize(objectKey)).thenReturn(513L * 1024 * 1024);
|
||||
|
||||
assertThrows(BusinessException.class, () -> service().confirmPackage(
|
||||
objectKey, "ShuFuAI-Workbench-1.2.3.zip", "1.2.3"));
|
||||
|
||||
verify(ossStorageService).removeWorkbenchClientObject(objectKey);
|
||||
verify(ossStorageService, never()).workbenchClientObjectSha256(anyString());
|
||||
verify(packageMapper, never()).insert(any(WorkbenchClientPackageEntity.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void latestReturnsNullFieldsWhenTableIsEmpty() {
|
||||
when(packageMapper.selectOne(any())).thenReturn(null);
|
||||
|
||||
Map<String, Object> result = service().latestPackage();
|
||||
|
||||
assertNull(result.get("version"));
|
||||
assertNull(result.get("file_url"));
|
||||
assertNull(result.get("sha256"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteRemovesObjectOnlyWhenNoOtherRowReferencesIt() {
|
||||
WorkbenchClientPackageEntity target = row(9, "1.2.3", PREFIX + "20261024100000123-1.2.3.zip");
|
||||
when(packageMapper.selectBatchIds(anyList())).thenReturn(List.of(target));
|
||||
when(packageMapper.deleteById(9L)).thenReturn(1);
|
||||
when(packageMapper.selectCount(any())).thenReturn(0L);
|
||||
|
||||
int deleted = service().deletePackages(List.of(9L));
|
||||
|
||||
assertEquals(1, deleted);
|
||||
verify(ossStorageService).removeWorkbenchClientObject(target.getObjectKey());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteKeepsObjectWhenAnotherRowStillReferencesIt() {
|
||||
WorkbenchClientPackageEntity target = row(9, "1.2.3", PREFIX + "20261024100000123-1.2.3.zip");
|
||||
when(packageMapper.selectBatchIds(anyList())).thenReturn(List.of(target));
|
||||
when(packageMapper.deleteById(9L)).thenReturn(1);
|
||||
when(packageMapper.selectCount(any())).thenReturn(1L);
|
||||
|
||||
service().deletePackages(List.of(9L));
|
||||
|
||||
verify(ossStorageService, never()).removeWorkbenchClientObject(anyString());
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@
|
||||
<router-view />
|
||||
<ExpiryNotice />
|
||||
<ProxyBalanceAlert />
|
||||
<CostGuardAlert />
|
||||
<ForceUpdateGate />
|
||||
</el-config-provider>
|
||||
</template>
|
||||
@@ -18,6 +19,7 @@ import { onBeforeUnmount } from 'vue'
|
||||
import ExpiryNotice from '@/shared/components/ExpiryNotice.vue'
|
||||
import ForceUpdateGate from '@/shared/components/ForceUpdateGate.vue'
|
||||
import ProxyBalanceAlert from '@/shared/components/ProxyBalanceAlert.vue'
|
||||
import CostGuardAlert from '@/shared/components/CostGuardAlert.vue'
|
||||
import { disposeGlobalErrorGuard } from '@/shared/utils/app-error'
|
||||
import { uninstallUserTokenSync } from '@/shared/auth/user-token-sync'
|
||||
import { disposeDownloadProgressListener } from '@/shared/utils/download-progress'
|
||||
|
||||
@@ -207,6 +207,10 @@ export const API_ENDPOINTS = {
|
||||
proxyBalance: '/api/user-secrets/proxy-balance',
|
||||
proxyPlan: '/api/user-secrets/proxy-plan',
|
||||
},
|
||||
costGuard: {
|
||||
status: '/api/user/cost-guard/status',
|
||||
resume: '/api/user/cost-guard/resume',
|
||||
},
|
||||
notification: {
|
||||
summary: '/api/notifications/summary',
|
||||
list: '/api/notifications',
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
import { get, post, type JavaApiResponse, unwrapJavaResponse } from '../../http.ts'
|
||||
import { buildJavaUrl } from '../../url.ts'
|
||||
import { API_ENDPOINTS } from '../../endpoints.ts'
|
||||
|
||||
/** 代理/LLM 共享密钥提示:只报账号数,不暴露其他账号身份。 */
|
||||
export interface SharedSecretWarning {
|
||||
type: 'proxy' | 'llm' | string
|
||||
moduleLabel: string
|
||||
accounts: number
|
||||
threshold: number
|
||||
message: string
|
||||
}
|
||||
|
||||
export interface CostGuardUsage {
|
||||
proxy: number
|
||||
llmCalls: number
|
||||
llmTokens: number
|
||||
}
|
||||
|
||||
export interface CostGuardStatus {
|
||||
paused: boolean
|
||||
reason: string
|
||||
pausedAt: string | null
|
||||
today: CostGuardUsage
|
||||
window: CostGuardUsage & { seconds: number }
|
||||
thresholds: {
|
||||
proxyWindow: number
|
||||
llmCallsWindow: number
|
||||
llmTokensWindow: number
|
||||
proxyDaily: number
|
||||
llmCallsDaily: number
|
||||
llmTokensDaily: number
|
||||
sharedAccounts: number
|
||||
}
|
||||
sharedWarnings: SharedSecretWarning[]
|
||||
}
|
||||
|
||||
export function fetchCostGuardStatus() {
|
||||
return unwrapJavaResponse(
|
||||
get<JavaApiResponse<CostGuardStatus>>(buildJavaUrl(API_ENDPOINTS.costGuard.status)),
|
||||
)
|
||||
}
|
||||
|
||||
/** 排查后手动继续:只清暂停闸,不删除已完成任务与结果行。 */
|
||||
export function resumeCostGuard() {
|
||||
return unwrapJavaResponse(
|
||||
post<JavaApiResponse<CostGuardStatus>, undefined>(
|
||||
buildJavaUrl(API_ENDPOINTS.costGuard.resume),
|
||||
undefined,
|
||||
),
|
||||
)
|
||||
}
|
||||
@@ -2,7 +2,7 @@ import { get, post, type JavaApiResponse, unwrapJavaResponse } from '../../http.
|
||||
import { buildJavaUrl } from '../../url.ts'
|
||||
import { API_ENDPOINTS } from '../../endpoints.ts'
|
||||
|
||||
/** 通知场景:密钥欠费 / 密钥失效 / 任务失败 / 交付不完整 / 服务异常 / 麦象异常 / 系统。 */
|
||||
/** 通知场景:密钥欠费 / 密钥失效 / 任务失败 / 交付不完整 / 服务异常 / 麦象异常 / 损耗暂停 / 密钥共用 / 系统。 */
|
||||
export type NotificationScene =
|
||||
| 'secret_balance'
|
||||
| 'secret_invalid'
|
||||
@@ -10,6 +10,8 @@ export type NotificationScene =
|
||||
| 'task_partial'
|
||||
| 'service_down'
|
||||
| 'maixiang_anomaly'
|
||||
| 'cost_guard'
|
||||
| 'secret_shared'
|
||||
| 'system'
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,278 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* 代理/LLM 损耗保护常驻提示(2026-10-24 需求):
|
||||
* 异常时客户端立刻弹窗并暂停该账号的新任务;已跑完的任务与结果行不受影响。
|
||||
*
|
||||
* - 暂停:红色不可忽略横幅 + 首次弹确认框,用户排查后点「继续任务」走 resume;
|
||||
* - 共用密钥:黄色提示条,只报账号数,不阻断任务;
|
||||
* - 轮询失败保留上一轮状态(与 ProxyBalanceAlert 同口径),不把网络抖动刷成误报。
|
||||
*/
|
||||
import { onBeforeUnmount, onMounted, ref } from 'vue'
|
||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
import {
|
||||
fetchCostGuardStatus,
|
||||
resumeCostGuard,
|
||||
type CostGuardStatus,
|
||||
type SharedSecretWarning,
|
||||
} from '@/shared/api/types/modules/cost-guard'
|
||||
import { AUTH_TOKEN_KEY } from '@/shared/auth/session-keys'
|
||||
import {
|
||||
COST_GUARD_POLL_MS,
|
||||
pausedPromptKey,
|
||||
sharedWarningKey,
|
||||
usageLine,
|
||||
} from '@/shared/utils/cost-guard-alert'
|
||||
|
||||
const status = ref<CostGuardStatus | null>(null)
|
||||
const sharedWarnings = ref<SharedSecretWarning[]>([])
|
||||
const resuming = ref(false)
|
||||
let timer: number | null = null
|
||||
let inflight = false
|
||||
let disposed = false
|
||||
let promptedKey = ''
|
||||
const warnedSharedKeys = new Set<string>()
|
||||
|
||||
function hasLoginToken(): boolean {
|
||||
if (typeof window === 'undefined') return false
|
||||
return Boolean(window.localStorage.getItem(AUTH_TOKEN_KEY))
|
||||
}
|
||||
|
||||
async function refresh(): Promise<void> {
|
||||
if (disposed || inflight) return
|
||||
if (!hasLoginToken()) {
|
||||
status.value = null
|
||||
sharedWarnings.value = []
|
||||
return
|
||||
}
|
||||
inflight = true
|
||||
try {
|
||||
const next = await fetchCostGuardStatus().catch((error) => {
|
||||
console.warn('[cost-guard] 损耗状态读取失败,本轮不提示:', error)
|
||||
return null
|
||||
})
|
||||
if (next === null || disposed) return
|
||||
status.value = next
|
||||
sharedWarnings.value = next.sharedWarnings || []
|
||||
notifySharedWarnings(sharedWarnings.value)
|
||||
maybePromptPaused(next)
|
||||
} finally {
|
||||
inflight = false
|
||||
}
|
||||
}
|
||||
|
||||
function notifySharedWarnings(warnings: SharedSecretWarning[]): void {
|
||||
for (const warning of warnings) {
|
||||
const key = sharedWarningKey(warning)
|
||||
if (warnedSharedKeys.has(key)) continue
|
||||
warnedSharedKeys.add(key)
|
||||
ElMessage.warning({ message: warning.message, duration: 8000, showClose: true })
|
||||
}
|
||||
}
|
||||
|
||||
function maybePromptPaused(next: CostGuardStatus): void {
|
||||
const key = pausedPromptKey(next)
|
||||
if (!key || key === promptedKey) return
|
||||
promptedKey = key
|
||||
ElMessageBox.confirm(
|
||||
`${next.reason}\n\n${usageLine(next)}\n\n已完成的任务与数据不受影响。排查后点击「继续任务」;也可以先点「稍后处理」,处理完再从右上角横幅继续。`,
|
||||
'任务已自动暂停(损耗保护)',
|
||||
{
|
||||
confirmButtonText: '继续任务',
|
||||
cancelButtonText: '稍后处理',
|
||||
distinguishCancelAndClose: true,
|
||||
closeOnClickModal: false,
|
||||
closeOnPressEscape: false,
|
||||
type: 'error',
|
||||
customStyle: { whiteSpace: 'pre-line' },
|
||||
},
|
||||
)
|
||||
.then(() => resume())
|
||||
.catch(() => {
|
||||
/* 稍后处理/关闭:保留横幅,不重复弹 */
|
||||
})
|
||||
}
|
||||
|
||||
async function resume(): Promise<void> {
|
||||
if (resuming.value) return
|
||||
resuming.value = true
|
||||
try {
|
||||
const next = await resumeCostGuard()
|
||||
status.value = next
|
||||
sharedWarnings.value = next.sharedWarnings || []
|
||||
promptedKey = ''
|
||||
ElMessage.success('已继续任务,后续派发会从当前进度接着跑')
|
||||
} catch (error) {
|
||||
console.warn('[cost-guard] 继续任务失败:', error)
|
||||
ElMessage.error('继续任务失败,请稍后重试')
|
||||
} finally {
|
||||
resuming.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function refreshWhenVisible(): void {
|
||||
if (typeof document !== 'undefined' && document.visibilityState === 'hidden') return
|
||||
void refresh()
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
void refresh()
|
||||
timer = window.setInterval(() => void refresh(), COST_GUARD_POLL_MS)
|
||||
window.addEventListener('focus', refreshWhenVisible)
|
||||
document.addEventListener('visibilitychange', refreshWhenVisible)
|
||||
})
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
disposed = true
|
||||
if (timer !== null) window.clearInterval(timer)
|
||||
window.removeEventListener('focus', refreshWhenVisible)
|
||||
document.removeEventListener('visibilitychange', refreshWhenVisible)
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div v-if="status?.paused || sharedWarnings.length" class="cost-guard-stack">
|
||||
<div
|
||||
v-if="status?.paused"
|
||||
class="cost-guard-alert cost-guard-alert--paused"
|
||||
role="alert"
|
||||
aria-live="assertive"
|
||||
>
|
||||
<div class="cost-guard-alert-icon" aria-hidden="true">!</div>
|
||||
<div class="cost-guard-alert-content">
|
||||
<div class="cost-guard-alert-title">任务已自动暂停(损耗保护)</div>
|
||||
<div class="cost-guard-alert-reason">{{ status.reason }}</div>
|
||||
<div class="cost-guard-alert-metrics">{{ usageLine(status) }}</div>
|
||||
<div class="cost-guard-alert-hint">
|
||||
已完成的任务与结果行不受影响。请检查「密钥设置」与被暂停任务,排查后继续。
|
||||
</div>
|
||||
<button class="cost-guard-alert-button" :disabled="resuming" @click="resume">
|
||||
{{ resuming ? '正在恢复…' : '继续任务' }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="sharedWarnings.length"
|
||||
class="cost-guard-alert cost-guard-alert--shared"
|
||||
role="status"
|
||||
>
|
||||
<div class="cost-guard-alert-icon" aria-hidden="true">i</div>
|
||||
<div class="cost-guard-alert-content">
|
||||
<div class="cost-guard-alert-title">密钥共用提示</div>
|
||||
<div
|
||||
v-for="warning in sharedWarnings"
|
||||
:key="sharedWarningKey(warning)"
|
||||
class="cost-guard-alert-reason"
|
||||
>
|
||||
{{ warning.message }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
/* 放在代理余量警告(top:68px)下方,两个常驻提示同时出现时不互相遮挡 */
|
||||
.cost-guard-stack {
|
||||
position: fixed;
|
||||
top: 230px;
|
||||
right: 16px;
|
||||
z-index: 3000;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
width: 400px;
|
||||
max-width: calc(100vw - 32px);
|
||||
}
|
||||
|
||||
.cost-guard-alert {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 10px;
|
||||
width: 100%;
|
||||
padding: 14px 16px;
|
||||
box-sizing: border-box;
|
||||
border-radius: 12px;
|
||||
box-shadow: 0 14px 36px -18px rgba(60, 20, 20, 0.55);
|
||||
}
|
||||
|
||||
.cost-guard-alert--paused {
|
||||
border: 1px solid #d64545;
|
||||
background: #fff1f1;
|
||||
color: #7d1d1d;
|
||||
}
|
||||
|
||||
.cost-guard-alert--shared {
|
||||
border: 1px solid #e0a13c;
|
||||
background: #fff8e8;
|
||||
color: #7a4a06;
|
||||
}
|
||||
|
||||
.cost-guard-alert-icon {
|
||||
flex-shrink: 0;
|
||||
width: 22px;
|
||||
height: 22px;
|
||||
border-radius: 50%;
|
||||
color: #ffffff;
|
||||
font-size: 14px;
|
||||
font-weight: 800;
|
||||
line-height: 22px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.cost-guard-alert--paused .cost-guard-alert-icon {
|
||||
background: #d64545;
|
||||
}
|
||||
|
||||
.cost-guard-alert--shared .cost-guard-alert-icon {
|
||||
background: #e0a13c;
|
||||
}
|
||||
|
||||
.cost-guard-alert-content {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 5px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.cost-guard-alert-title {
|
||||
font-size: 14px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.cost-guard-alert-reason,
|
||||
.cost-guard-alert-metrics {
|
||||
font-size: 13px;
|
||||
line-height: 1.5;
|
||||
word-break: break-word;
|
||||
}
|
||||
|
||||
.cost-guard-alert-metrics {
|
||||
color: #9a4a4a;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.cost-guard-alert-hint {
|
||||
color: #9a4a4a;
|
||||
font-size: 12px;
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.cost-guard-alert-button {
|
||||
align-self: flex-start;
|
||||
margin-top: 4px;
|
||||
padding: 6px 14px;
|
||||
border: 0;
|
||||
border-radius: 8px;
|
||||
background: #d64545;
|
||||
color: #ffffff;
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.cost-guard-alert-button:disabled {
|
||||
opacity: 0.6;
|
||||
cursor: default;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,29 @@
|
||||
import type { CostGuardStatus, SharedSecretWarning } from '@/shared/api/types/modules/cost-guard'
|
||||
|
||||
/** 损耗状态轮询间隔:与后端每分钟扫描配合,30 秒足够把暂停提示送到界面。 */
|
||||
export const COST_GUARD_POLL_MS = 30_000
|
||||
|
||||
export function formatCount(value: number | null | undefined): string {
|
||||
const number = Number(value ?? 0)
|
||||
if (!Number.isFinite(number)) return '0'
|
||||
return number.toLocaleString('zh-CN')
|
||||
}
|
||||
|
||||
/** 暂停弹窗/横幅里的用量行:当日累计 + 本轮增量,用户一眼看出是哪一项超了。 */
|
||||
export function usageLine(status: CostGuardStatus | null): string {
|
||||
if (!status) return ''
|
||||
const today = status.today
|
||||
const window = status.window
|
||||
return `今日代理提取 ${formatCount(today.proxy)} 次 · LLM ${formatCount(today.llmCalls)} 次 / ${formatCount(today.llmTokens)} tokens;`
|
||||
+ `最近 ${window.seconds} 秒:代理 ${formatCount(window.proxy)} 次 · LLM ${formatCount(window.llmCalls)} 次 / ${formatCount(window.llmTokens)} tokens`
|
||||
}
|
||||
|
||||
/** 同一个暂停事件只弹一次:pausedAt 变化(新的自动暂停)才重新弹。 */
|
||||
export function pausedPromptKey(status: CostGuardStatus | null): string {
|
||||
if (!status?.paused) return ''
|
||||
return status.pausedAt || status.reason || 'paused'
|
||||
}
|
||||
|
||||
export function sharedWarningKey(warning: SharedSecretWarning): string {
|
||||
return `${warning.type}|${warning.moduleLabel}|${warning.accounts}`
|
||||
}
|
||||
@@ -27,7 +27,11 @@ const BASELINE = {
|
||||
// 299 = 298 + 桌面端铃铛 toggleGroup 的一支 try/catch(10-13 通知聚合改造):展开明细要单独发请求,
|
||||
// 失败写进面板内 loadError(与列表加载同一个可见出口,不弹全局打扰),改前是"点了没反应"。
|
||||
// silent 一格没涨:该支首条语句不是 console.*,且有可见出口。
|
||||
blocks: 299,
|
||||
// 300 = 299 + 损耗保护弹窗 resume() 的一支 try/catch(10-24 cost-guard):用户点「继续任务」
|
||||
// 解闸失败时必须当场说清楚(console.warn 留链 + ElMessage.error 给用户),不能让按钮变成
|
||||
// 「点了没反应」——这一支首条语句虽是 console.*,但块内有 ElMessage 用户可见出口,
|
||||
// 按扫描器口径不算静默,所以 silent 一格没动、只进 blocks。
|
||||
blocks: 300,
|
||||
// 298 = 296 + 全局错误出口 app-error.ts 的两支新 try/catch(10-09 装 app.config.errorHandler /
|
||||
// window.onerror / unhandledrejection 时引入),两支都不是"吞":
|
||||
// ① String(reason) 对无 toString 的对象/Symbol 会抛,兜法返回一句中文占位文本,
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
import { test } from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { join } from 'node:path'
|
||||
|
||||
/**
|
||||
* 代理/LLM 损耗保护(2026-10-24 需求):
|
||||
* 「异常要立刻弹窗警告在客户端界面上,并暂停任务;排查后手动点击接着跑」。
|
||||
*
|
||||
* 分两层钉:
|
||||
* ① 行为层:暂停键只随 pausedAt 变化、用量行含当日与窗口两段、共享提示按键去重;
|
||||
* ② 源码层:全局挂载、30 秒轮询、暂停弹窗带「继续任务」、resume 走独立接口。
|
||||
*/
|
||||
|
||||
const COMPONENT = 'src/shared/components/CostGuardAlert.vue'
|
||||
const APP = 'src/App.vue'
|
||||
const ENDPOINTS = 'src/shared/api/endpoints.ts'
|
||||
const NOTIFICATION_TYPES = 'src/shared/api/types/modules/notification.ts'
|
||||
|
||||
function read(rel: string): string {
|
||||
return readFileSync(join(process.cwd(), rel), 'utf8')
|
||||
}
|
||||
|
||||
const component = read(COMPONENT)
|
||||
const app = read(APP)
|
||||
|
||||
test('用量行同时给出当日累计与最近窗口增量', async () => {
|
||||
const { usageLine, formatCount } = await import('../src/shared/utils/cost-guard-alert.ts')
|
||||
const status = {
|
||||
paused: true,
|
||||
reason: '代理提取异常',
|
||||
pausedAt: '2026-10-24T10:00:00',
|
||||
today: { proxy: 12345, llmCalls: 678, llmTokens: 900000 },
|
||||
window: { seconds: 120, proxy: 600, llmCalls: 180, llmTokens: 600000 },
|
||||
thresholds: {
|
||||
proxyWindow: 600,
|
||||
llmCallsWindow: 180,
|
||||
llmTokensWindow: 600000,
|
||||
proxyDaily: 8000,
|
||||
llmCallsDaily: 6000,
|
||||
llmTokensDaily: 20000000,
|
||||
sharedAccounts: 3,
|
||||
},
|
||||
sharedWarnings: [],
|
||||
}
|
||||
|
||||
const line = usageLine(status as never)
|
||||
assert.match(line, /今日代理提取 12,345 次/)
|
||||
assert.match(line, /最近 120 秒:代理 600 次/)
|
||||
assert.match(line, /LLM 180 次 \/ 600,000 tokens/)
|
||||
assert.equal(formatCount(undefined), '0')
|
||||
})
|
||||
|
||||
test('同一个暂停事件只弹一次,pausedAt 变化才重新弹', async () => {
|
||||
const { pausedPromptKey } = await import('../src/shared/utils/cost-guard-alert.ts')
|
||||
const base = { paused: true, reason: 'r', pausedAt: '2026-10-24T10:00:00' }
|
||||
const next = { paused: true, reason: 'r', pausedAt: '2026-10-24T11:00:00' }
|
||||
|
||||
assert.equal(pausedPromptKey(base as never), pausedPromptKey({ ...base } as never))
|
||||
assert.notEqual(pausedPromptKey(base as never), pausedPromptKey(next as never))
|
||||
assert.equal(pausedPromptKey({ paused: false, reason: 'r', pausedAt: null } as never), '')
|
||||
})
|
||||
|
||||
test('共享密钥提示按键去重,不按文案去重', async () => {
|
||||
const { sharedWarningKey } = await import('../src/shared/utils/cost-guard-alert.ts')
|
||||
|
||||
assert.equal(
|
||||
sharedWarningKey({ type: 'proxy', moduleLabel: '代理设置', accounts: 3, threshold: 3, message: 'a' }),
|
||||
sharedWarningKey({ type: 'proxy', moduleLabel: '代理设置', accounts: 3, threshold: 3, message: 'b' }),
|
||||
)
|
||||
assert.notEqual(
|
||||
sharedWarningKey({ type: 'llm', moduleLabel: '代理设置', accounts: 3, threshold: 3, message: 'a' }),
|
||||
sharedWarningKey({ type: 'proxy', moduleLabel: '代理设置', accounts: 3, threshold: 3, message: 'a' }),
|
||||
)
|
||||
})
|
||||
|
||||
test('全局挂载并在暂停时提供「继续任务」', () => {
|
||||
assert.ok(app.includes("import CostGuardAlert from '@/shared/components/CostGuardAlert.vue'"))
|
||||
assert.ok(app.includes('<CostGuardAlert />'), '组件没挂到 App.vue,异常时界面不会弹')
|
||||
|
||||
assert.ok(component.includes('setInterval'), '缺少轮询,用户停在页面上等不到暂停提示')
|
||||
assert.ok(component.includes('COST_GUARD_POLL_MS'))
|
||||
assert.ok(component.includes('fetchCostGuardStatus'))
|
||||
assert.ok(component.includes('resumeCostGuard'))
|
||||
assert.ok(component.includes('ElMessageBox.confirm'))
|
||||
assert.ok(component.includes('继续任务'))
|
||||
assert.ok(component.includes('已完成的任务与数据不受影响'))
|
||||
})
|
||||
|
||||
test('接口与通知场景已登记', () => {
|
||||
const endpoints = read(ENDPOINTS)
|
||||
assert.ok(endpoints.includes("status: '/api/user/cost-guard/status'"))
|
||||
assert.ok(endpoints.includes("resume: '/api/user/cost-guard/resume'"))
|
||||
|
||||
const notification = read(NOTIFICATION_TYPES)
|
||||
assert.ok(notification.includes("| 'cost_guard'"))
|
||||
assert.ok(notification.includes("| 'secret_shared'"))
|
||||
})
|
||||
@@ -19,6 +19,7 @@ const MODULE_KEYS = [
|
||||
'similarAsin',
|
||||
'appearancePatent',
|
||||
'userSecret',
|
||||
'costGuard',
|
||||
'notification',
|
||||
'collectData',
|
||||
'imageVideo',
|
||||
@@ -315,6 +316,10 @@ test('test_endpoints_frozen_snapshot', () => {
|
||||
"proxyBalance": "/api/user-secrets/proxy-balance",
|
||||
"proxyPlan": "/api/user-secrets/proxy-plan"
|
||||
},
|
||||
"costGuard": {
|
||||
"status": "/api/user/cost-guard/status",
|
||||
"resume": "/api/user/cost-guard/resume"
|
||||
},
|
||||
"notification": {
|
||||
"summary": "/api/notifications/summary",
|
||||
"list": "/api/notifications",
|
||||
|
||||
Reference in New Issue
Block a user