perf(files): 优化私有文件鉴权与高成本查询隔离
This commit is contained in:
@@ -1,12 +1,16 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import {
|
||||
accountSourceLabel,
|
||||
estimateOrderEndAt,
|
||||
formatHandoffRecordType,
|
||||
handoffModeLabel,
|
||||
orderPlatformFeeBreakdown,
|
||||
paymentBizTypeLabel,
|
||||
paymentPaidAt,
|
||||
paymentStatusLabel,
|
||||
paymentStatusType,
|
||||
settlementModeLabel,
|
||||
} from '../adminOrderPresentation'
|
||||
|
||||
describe('admin order presentation', () => {
|
||||
@@ -25,11 +29,27 @@ describe('admin order presentation', () => {
|
||||
|
||||
it('maps known payment states and preserves unknown channel values', () => {
|
||||
expect(paymentStatusLabel('refunded')).toBe('已退款')
|
||||
expect(paymentStatusType('paid')).toBe('success')
|
||||
expect(paymentStatusType('failed')).toBe('danger')
|
||||
expect(paymentStatusType('refunding')).toBe('warning')
|
||||
expect(paymentStatusType('created')).toBe('info')
|
||||
expect(paymentBizTypeLabel('order_pay')).toBe('订单支付')
|
||||
expect(paymentBizTypeLabel('future_type')).toBe('future_type')
|
||||
})
|
||||
|
||||
it('maps handoff, settlement, and account source labels with safe fallbacks', () => {
|
||||
expect(formatHandoffRecordType('owner_handoff')).toBe('卖家交接')
|
||||
expect(formatHandoffRecordType('future_type')).toBe('future_type')
|
||||
expect(handoffModeLabel()).toBe('号主交接')
|
||||
expect(handoffModeLabel('platform')).toBe('平台代管')
|
||||
expect(handoffModeLabel('future')).toBe('future')
|
||||
expect(settlementModeLabel()).toBe('号主钱包')
|
||||
expect(settlementModeLabel('platform_managed')).toBe('线下结算')
|
||||
expect(settlementModeLabel('future')).toBe('future')
|
||||
expect(accountSourceLabel('external')).toBe('外部上传')
|
||||
expect(accountSourceLabel('internal')).toBe('站内上传')
|
||||
})
|
||||
|
||||
it('selects the most meaningful payment completion time', () => {
|
||||
expect(
|
||||
paymentPaidAt({
|
||||
@@ -81,4 +101,32 @@ describe('admin order presentation', () => {
|
||||
totalFeeCent: 4000,
|
||||
})
|
||||
})
|
||||
|
||||
it('normalizes missing and invalid fee snapshots', () => {
|
||||
expect(orderPlatformFeeBreakdown(null)).toEqual({
|
||||
baseFeeCent: 0,
|
||||
insuranceFeeCent: 0,
|
||||
insuranceFeeBps: 0,
|
||||
totalFeeCent: 0,
|
||||
})
|
||||
expect(
|
||||
orderPlatformFeeBreakdown({
|
||||
status: 'completed',
|
||||
platform_fee_cent: -1,
|
||||
insurance_fee_cent: Number.NaN,
|
||||
insurance_fee_bps: 500,
|
||||
checkout: {
|
||||
platform_fee_cent: 1200,
|
||||
insurance_fee_cent: 200,
|
||||
insurance_fee_bps: 800,
|
||||
},
|
||||
})
|
||||
).toEqual({
|
||||
baseFeeCent: 1000,
|
||||
insuranceFeeCent: 200,
|
||||
insuranceFeeBps: 800,
|
||||
totalFeeCent: 1200,
|
||||
})
|
||||
expect(estimateOrderEndAt(undefined, '2026-09-02T12:00:00Z', 0)).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
get: vi.fn(),
|
||||
post: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('./client', () => ({
|
||||
apiClient: {
|
||||
get: mocks.get,
|
||||
post: mocks.post,
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@/shared/utils/imageUpload', () => ({
|
||||
optimizeImageForUpload: vi.fn(),
|
||||
}))
|
||||
|
||||
import { fetchAdminFileBlob, fetchFileAccessTicket, fetchFileBlobByURL } from './files'
|
||||
|
||||
describe('file access tickets', () => {
|
||||
beforeEach(() => {
|
||||
mocks.get.mockReset()
|
||||
mocks.post.mockReset()
|
||||
})
|
||||
|
||||
it('batches same-tick user image keys and reuses in-flight tickets', async () => {
|
||||
mocks.post.mockResolvedValue({
|
||||
data: {
|
||||
data: {
|
||||
tickets: {
|
||||
'listing/a.webp': 'ticket-a',
|
||||
'listing/b.webp': 'ticket-b',
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const first = fetchFileAccessTicket('listing/a.webp')
|
||||
const duplicate = fetchFileAccessTicket('listing/a.webp')
|
||||
const second = fetchFileAccessTicket('listing/b.webp')
|
||||
|
||||
await expect(Promise.all([first, duplicate, second])).resolves.toEqual([
|
||||
'ticket-a',
|
||||
'ticket-a',
|
||||
'ticket-b',
|
||||
])
|
||||
expect(mocks.post).toHaveBeenCalledTimes(1)
|
||||
expect(mocks.post).toHaveBeenCalledWith('/files/access/batch', {
|
||||
keys: ['listing/a.webp', 'listing/b.webp'],
|
||||
})
|
||||
})
|
||||
|
||||
it('uses the admin batch endpoint and appends the ticket to object requests', async () => {
|
||||
mocks.post.mockResolvedValue({
|
||||
data: {
|
||||
data: {
|
||||
tickets: {
|
||||
'chat/message.webp': 'admin-ticket',
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
mocks.get.mockResolvedValue({ data: new Blob(['image']) })
|
||||
|
||||
const ticket = await fetchFileAccessTicket('chat/message.webp', true)
|
||||
await fetchAdminFileBlob('chat/message.webp', ticket)
|
||||
await fetchFileBlobByURL('/api/files/object?key=chat%2Fmessage.webp', ticket)
|
||||
|
||||
expect(mocks.post).toHaveBeenCalledWith('/admin/files/access/batch', {
|
||||
keys: ['chat/message.webp'],
|
||||
})
|
||||
expect(mocks.get).toHaveBeenNthCalledWith(1, '/admin/files/object', {
|
||||
params: { key: 'chat/message.webp', ticket: 'admin-ticket' },
|
||||
responseType: 'blob',
|
||||
})
|
||||
expect(mocks.get).toHaveBeenNthCalledWith(
|
||||
2,
|
||||
'/files/object?key=chat%2Fmessage.webp&ticket=admin-ticket',
|
||||
{
|
||||
responseType: 'blob',
|
||||
}
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -12,6 +12,22 @@ export interface UploadedFile {
|
||||
size: number
|
||||
}
|
||||
|
||||
interface AccessTicketsResponse {
|
||||
tickets: Record<string, string>
|
||||
expires_in_seconds: number
|
||||
}
|
||||
|
||||
interface PendingTicket {
|
||||
promise: Promise<string>
|
||||
resolve: (ticket: string) => void
|
||||
reject: (error: unknown) => void
|
||||
}
|
||||
|
||||
const pendingTickets: Record<'user' | 'admin', Map<string, PendingTicket>> = {
|
||||
user: new Map(),
|
||||
admin: new Map(),
|
||||
}
|
||||
|
||||
export async function uploadFile(file: File, scene: string) {
|
||||
const uploadTarget = await optimizeImageForUpload(file, scene)
|
||||
const form = new FormData()
|
||||
@@ -38,15 +54,55 @@ export async function uploadAdminFile(
|
||||
return data.data
|
||||
}
|
||||
|
||||
export async function fetchAdminFileBlob(key: string) {
|
||||
export async function fetchAdminFileBlob(key: string, ticket = '') {
|
||||
const { data } = await apiClient.get<Blob>('/admin/files/object', {
|
||||
params: { key },
|
||||
params: { key, ...(ticket ? { ticket } : {}) },
|
||||
responseType: 'blob',
|
||||
})
|
||||
return data
|
||||
}
|
||||
|
||||
export async function fetchFileBlobByURL(fileURL: string) {
|
||||
export function fetchFileAccessTicket(key: string, admin = false): Promise<string> {
|
||||
const scope = admin ? 'admin' : 'user'
|
||||
const pending = pendingTickets[scope]
|
||||
const existing = pending.get(key)
|
||||
if (existing) return existing.promise
|
||||
|
||||
let resolveTicket!: (ticket: string) => void
|
||||
let rejectTicket!: (error: unknown) => void
|
||||
const promise = new Promise<string>((resolve, reject) => {
|
||||
resolveTicket = resolve
|
||||
rejectTicket = reject
|
||||
})
|
||||
pending.set(key, { promise, resolve: resolveTicket, reject: rejectTicket })
|
||||
queueMicrotask(flushTicketQueue)
|
||||
return promise
|
||||
}
|
||||
|
||||
function flushTicketQueue() {
|
||||
flushTicketScope('user')
|
||||
flushTicketScope('admin')
|
||||
}
|
||||
|
||||
function flushTicketScope(scope: 'user' | 'admin') {
|
||||
const pending = pendingTickets[scope]
|
||||
if (!pending.size) return
|
||||
const batch = Array.from(pending.entries())
|
||||
pending.clear()
|
||||
const keys = [...new Set(batch.map(([key]) => key))]
|
||||
const path = scope === 'admin' ? '/admin/files/access/batch' : '/files/access/batch'
|
||||
apiClient
|
||||
.post<ApiResponse<AccessTicketsResponse>>(path, { keys })
|
||||
.then(({ data }) => {
|
||||
const tickets = data.data?.tickets || {}
|
||||
batch.forEach(([key, entry]) => entry.resolve(tickets[key] || ''))
|
||||
})
|
||||
.catch(error => {
|
||||
batch.forEach(([, entry]) => entry.reject(error))
|
||||
})
|
||||
}
|
||||
|
||||
export async function fetchFileBlobByURL(fileURL: string, ticket = '') {
|
||||
let apiPath = fileURL
|
||||
try {
|
||||
const parsed = new URL(fileURL, window.location.origin)
|
||||
@@ -65,6 +121,11 @@ export async function fetchFileBlobByURL(fileURL: string) {
|
||||
apiPath = `/files/object${queryIndex >= 0 ? apiPath.slice(queryIndex) : ''}`
|
||||
}
|
||||
}
|
||||
if (ticket) {
|
||||
const parsed = new URL(apiPath, window.location.origin)
|
||||
parsed.searchParams.set('ticket', ticket)
|
||||
apiPath = parsed.pathname + parsed.search
|
||||
}
|
||||
const { data } = await apiClient.get<Blob>(apiPath, {
|
||||
responseType: 'blob',
|
||||
})
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onBeforeUnmount, ref, watch } from 'vue'
|
||||
import { fetchAdminFileBlob, fetchFileBlobByURL } from '@/shared/api/files'
|
||||
import { fetchAdminFileBlob, fetchFileAccessTicket, fetchFileBlobByURL } from '@/shared/api/files'
|
||||
import { isAdminPath } from '@/shared/utils/adminPath'
|
||||
|
||||
const props = withDefaults(
|
||||
@@ -96,8 +96,17 @@ function shouldFetchAsAdmin(value: string) {
|
||||
async function resolveURL(url: string): Promise<string> {
|
||||
if (!url || !shouldFetchWithAuth(url)) return url
|
||||
const key = extractObjectKey(url)
|
||||
const admin = shouldFetchAsAdmin(url)
|
||||
let ticket = ''
|
||||
if (key) {
|
||||
try {
|
||||
ticket = await fetchFileAccessTicket(key, admin)
|
||||
} catch {
|
||||
// 批量票据失败时继续走单文件服务端鉴权,避免图片直接不可用。
|
||||
}
|
||||
}
|
||||
const blob = await withAuthImageLoadSlot(() =>
|
||||
shouldFetchAsAdmin(url) && key ? fetchAdminFileBlob(key) : fetchFileBlobByURL(url)
|
||||
admin && key ? fetchAdminFileBlob(key, ticket) : fetchFileBlobByURL(url, ticket)
|
||||
)
|
||||
const blobURL = URL.createObjectURL(blob)
|
||||
createdURLs.push(blobURL)
|
||||
|
||||
Reference in New Issue
Block a user