mirror of
https://github.com/Wei-Shaw/sub2api.git
synced 2026-12-06 08:06:50 +00:00
fix(accounts): keep older proxy counts when a newer refresh fails
Review follow-up for the proxy account count refresh: - Apply a proxy list response only if it is newer than the last applied one. Previously a failed newer refresh also discarded a slower older success, which could leave the selector empty. - Refresh proxy counts on every `created` event. Batch creation can partially succeed and keep the dialog open, so opening the dialog was not enough. - Test ProxySelector with the real vue-i18n and locale files instead of a hand-written mock of the plural rule.
This commit is contained in:
1 parent
fd2f9770a2
commit
2ad419706d
3 files changed
+93
-30
No files matched your search
@@ -1,34 +1,27 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { enableAutoUnmount, mount, type VueWrapper } from '@vue/test-utils'
|
||||
import { createI18n } from 'vue-i18n'
|
||||
import ProxySelector from '../ProxySelector.vue'
|
||||
import enResources from '@/i18n/locales/en/admin/resources'
|
||||
import zhResources from '@/i18n/locales/zh/admin/resources'
|
||||
import type { Proxy } from '@/types'
|
||||
|
||||
vi.mock('@/api/admin', () => ({ adminAPI: { proxies: { testProxy: vi.fn() } } }))
|
||||
// vitest resolves vue-i18n to the runtime-only build, which cannot compile raw
|
||||
// locale strings. Resolve keys against the real locale files instead and apply
|
||||
// vue-i18n's two-choice plural rule ("one | other": 1 -> first, else second).
|
||||
const { locale } = vi.hoisted(() => ({ locale: { current: 'zh' as 'zh' | 'en' } }))
|
||||
vi.mock('vue-i18n', () => ({
|
||||
useI18n: () => ({
|
||||
t: (key: string, plural?: number): string => {
|
||||
const messages = locale.current === 'zh' ? zhResources : enResources
|
||||
const value = key.split('.').slice(1).reduce<unknown>(
|
||||
(node: unknown, part: string) => (node as Record<string, unknown> | undefined)?.[part],
|
||||
{ proxies: messages.proxies }
|
||||
)
|
||||
if (typeof value !== 'string') return key
|
||||
const choices = value.split('|').map((choice: string) => choice.trim())
|
||||
const message = typeof plural === 'number' && choices.length === 2 ? choices[plural === 1 ? 0 : 1] : value
|
||||
return typeof plural === 'number' ? message.replace(/\{(count|n)\}/g, String(plural)) : message
|
||||
}
|
||||
})
|
||||
}))
|
||||
enableAutoUnmount(afterEach)
|
||||
|
||||
async function openSelector(lang: 'zh' | 'en', accountCounts: Array<number | undefined>): Promise<VueWrapper> {
|
||||
locale.current = lang
|
||||
async function openSelector(locale: 'zh' | 'en', accountCounts: Array<number | undefined>): Promise<VueWrapper> {
|
||||
// Real vue-i18n with the real locale files: pluralization and interpolation
|
||||
// are exercised exactly as in the app.
|
||||
const i18n = createI18n({
|
||||
legacy: false,
|
||||
locale,
|
||||
missingWarn: false,
|
||||
fallbackWarn: false,
|
||||
messages: {
|
||||
en: { admin: { proxies: enResources.proxies } },
|
||||
zh: { admin: { proxies: zhResources.proxies } }
|
||||
}
|
||||
})
|
||||
const proxies: Proxy[] = accountCounts.map((count: number | undefined, i: number) => ({
|
||||
id: i + 1,
|
||||
name: `Proxy ${i + 1}`,
|
||||
@@ -42,7 +35,7 @@ async function openSelector(lang: 'zh' | 'en', accountCounts: Array<number | und
|
||||
} as Proxy))
|
||||
const wrapper = mount(ProxySelector, {
|
||||
props: { modelValue: null, proxies },
|
||||
global: { stubs: { Icon: true } }
|
||||
global: { plugins: [i18n], stubs: { Icon: true } }
|
||||
})
|
||||
await wrapper.get('.select-trigger').trigger('click')
|
||||
return wrapper
|
||||
@@ -63,9 +56,9 @@ describe('ProxySelector account counts', () => {
|
||||
expect(rows[1].get('[data-test="proxy-account-count"]').attributes('title')).toBe('当前绑定此代理的账号数')
|
||||
|
||||
// The badge sits on the right: after the name/address block, before the test button.
|
||||
const children = rows[1].element.children
|
||||
const badgeIndex = Array.from(children).findIndex((el: Element) => el.getAttribute('data-test') === 'proxy-account-count')
|
||||
const testButtonIndex = Array.from(children).findIndex((el: Element) => el.classList.contains('test-btn'))
|
||||
const children = Array.from(rows[1].element.children)
|
||||
const badgeIndex = children.findIndex((el: Element) => el.getAttribute('data-test') === 'proxy-account-count')
|
||||
const testButtonIndex = children.findIndex((el: Element) => el.classList.contains('test-btn'))
|
||||
expect(badgeIndex).toBeGreaterThan(0)
|
||||
expect(testButtonIndex).toBe(badgeIndex + 1)
|
||||
})
|
||||
@@ -75,6 +68,7 @@ describe('ProxySelector account counts', () => {
|
||||
const texts = proxyRows(wrapper).map((row) => row.get('[data-test="proxy-account-count"]').text())
|
||||
|
||||
expect(texts).toEqual(['0 accounts', '1 account', '3 accounts'])
|
||||
expect(proxyRows(wrapper)[0].get('[data-test="proxy-account-count"]').attributes('title')).toBe('Accounts currently using this proxy')
|
||||
})
|
||||
|
||||
it('omits the badge when the list was loaded without counts', async () => {
|
||||
|
||||
@@ -467,7 +467,7 @@
|
||||
</template>
|
||||
<template #pagination><Pagination v-if="pagination.total > 0" :page="pagination.page" :total="pagination.total" :page-size="pagination.page_size" @update:page="handlePageChange" @update:pageSize="handlePageSizeChange" /></template>
|
||||
</TablePageLayout>
|
||||
<CreateAccountModal :show="showCreate" :proxies="proxies" :groups="groups" @close="showCreate = false" @created="reload" />
|
||||
<CreateAccountModal :show="showCreate" :proxies="proxies" :groups="groups" @close="showCreate = false" @created="handleAccountsCreated" />
|
||||
<EditAccountModal :show="showEdit" :account="edAcc" :proxies="proxies" :groups="groups" @close="showEdit = false" @updated="handleAccountUpdated" />
|
||||
<ReAuthAccountModal :show="showReAuth" :account="reAuthAcc" @close="closeReAuthModal" @reauthorized="handleAccountUpdated" />
|
||||
<AccountTestModal :show="showTest" :account="testingAcc" @close="closeTestModal" />
|
||||
@@ -624,15 +624,20 @@ const showErrorPassthrough = ref(false)
|
||||
const showTLSFingerprintProfiles = ref(false)
|
||||
|
||||
// Proxy account counts change whenever accounts are created, deleted, imported
|
||||
// or rebound, so reload them each time a proxy-picking dialog opens. The
|
||||
// sequence guard drops responses that arrive after a newer request; a failed
|
||||
// refresh keeps the previous list so the selector never goes empty.
|
||||
// or rebound, so reload them each time a proxy-picking dialog opens. Only a
|
||||
// response newer than the last applied one is used, so a slow older response
|
||||
// never overwrites fresher counts, while a failed newer request does not
|
||||
// discard an older success; a failed refresh keeps the previous list.
|
||||
let proxiesLoadSeq = 0
|
||||
let proxiesAppliedSeq = 0
|
||||
const loadProxies = async (): Promise<void> => {
|
||||
const seq = ++proxiesLoadSeq
|
||||
try {
|
||||
const list: AccountProxy[] = await adminAPI.proxies.getAllWithCount()
|
||||
if (seq === proxiesLoadSeq) proxies.value = list
|
||||
if (seq > proxiesAppliedSeq) {
|
||||
proxiesAppliedSeq = seq
|
||||
proxies.value = list
|
||||
}
|
||||
} catch (error: unknown) {
|
||||
console.error('Failed to load proxies:', error)
|
||||
}
|
||||
@@ -640,6 +645,12 @@ const loadProxies = async (): Promise<void> => {
|
||||
watch([showCreate, showEdit, showBulkEdit], (open: boolean[], wasOpen: boolean[] | undefined) => {
|
||||
if (open.some((isOpen: boolean, i: number) => isOpen && !wasOpen?.[i])) void loadProxies()
|
||||
})
|
||||
// Batch creation can partially succeed and keep the dialog open for the
|
||||
// remaining items, so refresh counts on every successful creation too.
|
||||
const handleAccountsCreated = (): void => {
|
||||
void reload()
|
||||
void loadProxies()
|
||||
}
|
||||
|
||||
const edAcc = ref<Account | null>(null)
|
||||
const tempUnschedAcc = ref<Account | null>(null)
|
||||
|
||||
@@ -229,6 +229,64 @@ describe('admin AccountsView lite account list', () => {
|
||||
wrapper.unmount()
|
||||
})
|
||||
|
||||
it('applies an older proxy response when a newer refresh fails, but never lets it overwrite a newer one', async () => {
|
||||
type ProxyList = Array<{ id: number; name: string; account_count: number }>
|
||||
const deferred = () => {
|
||||
let resolve!: (value: ProxyList) => void
|
||||
let reject!: (reason: Error) => void
|
||||
const promise = new Promise<ProxyList>((res, rej) => { resolve = res; reject = rej })
|
||||
return { promise, resolve, reject }
|
||||
}
|
||||
vi.spyOn(console, 'error').mockImplementation(() => {})
|
||||
const createModal = (wrapper: ReturnType<typeof mountView>) => wrapper.findComponent({ name: 'CreateAccountModal' })
|
||||
|
||||
// Mount request is slow; the dialog-open request fails first.
|
||||
const mountLoad = deferred()
|
||||
const openLoad = deferred()
|
||||
getAllProxies.mockReturnValueOnce(mountLoad.promise).mockReturnValueOnce(openLoad.promise)
|
||||
let wrapper = mountView()
|
||||
await flushPromises()
|
||||
await wrapper.get('[data-test="open-create"]').trigger('click')
|
||||
openLoad.reject(new Error('offline'))
|
||||
await flushPromises()
|
||||
mountLoad.resolve([{ id: 1, name: 'Shared proxy', account_count: 3 }])
|
||||
await flushPromises()
|
||||
expect(createModal(wrapper).props('proxies')).toEqual([{ id: 1, name: 'Shared proxy', account_count: 3 }])
|
||||
wrapper.unmount()
|
||||
|
||||
// Mount request is slow; the dialog-open request succeeds first with newer counts.
|
||||
const slowMount = deferred()
|
||||
const fastOpen = deferred()
|
||||
getAllProxies.mockReset().mockReturnValueOnce(slowMount.promise).mockReturnValueOnce(fastOpen.promise)
|
||||
wrapper = mountView()
|
||||
await flushPromises()
|
||||
await wrapper.get('[data-test="open-create"]').trigger('click')
|
||||
fastOpen.resolve([{ id: 1, name: 'Shared proxy', account_count: 4 }])
|
||||
await flushPromises()
|
||||
slowMount.resolve([{ id: 1, name: 'Shared proxy', account_count: 3 }])
|
||||
await flushPromises()
|
||||
expect(createModal(wrapper).props('proxies')).toEqual([{ id: 1, name: 'Shared proxy', account_count: 4 }])
|
||||
wrapper.unmount()
|
||||
})
|
||||
|
||||
it('refreshes proxy account counts after accounts are created while the dialog stays open', async () => {
|
||||
const before = [{ id: 2, name: 'Shared proxy', account_count: 7 }]
|
||||
const after = [{ id: 2, name: 'Shared proxy', account_count: 9 }]
|
||||
getAllProxies.mockResolvedValueOnce(before).mockResolvedValueOnce(before).mockResolvedValueOnce(after)
|
||||
const wrapper = mountView()
|
||||
await flushPromises()
|
||||
await wrapper.get('[data-test="open-create"]').trigger('click')
|
||||
await flushPromises()
|
||||
const createModal = wrapper.findComponent({ name: 'CreateAccountModal' })
|
||||
expect(createModal.props('proxies')).toEqual(before)
|
||||
|
||||
createModal.vm.$emit('created')
|
||||
await flushPromises()
|
||||
expect(getAllProxies).toHaveBeenCalledTimes(3)
|
||||
expect(createModal.props('proxies')).toEqual(after)
|
||||
wrapper.unmount()
|
||||
})
|
||||
|
||||
it('syncs the selected row without clearing notes missing from the upstream', async () => {
|
||||
const account = { ...listRow, type: 'apikey', notes: 'local notes' }
|
||||
listAccounts.mockResolvedValue({ items: [account], total: 1, page: 1, page_size: 20, pages: 1 })
|
||||
|
||||
Reference in new issue
Block a user