Files
clash-verge-rev/src/hooks/use-memory-data.ts
T
Tunglies 33e3b9f0f9 refactor(hooks): drop the write-only error channel and key-rotating refresh
The mihomo ws subscription's next callback accepted an error half that
baseNext silently discarded while traffic, memory and log consumers
kept constructing fallback payloads for it. Refresh minted a fresh
SWR key per call via a localStorage timestamp, abandoning old keys in
the cache forever. Reduce next to its data half and reset the snapshot
under a stable key instead.
2026-11-02 21:48:54 +08:00

60 lines
1.5 KiB
TypeScript

import { MihomoWebSocket } from 'tauri-plugin-mihomo-api'
import { useMihomoWsSubscription } from './use-mihomo-ws-subscription'
export interface IMemoryUsageItem {
inuse: number
oslimit?: number
}
const FALLBACK_MEMORY_USAGE: IMemoryUsageItem = { inuse: 0 }
const DUPLICATE_MEMORY_WINDOW_MS = 50
let lastMemorySignature = ''
let lastMemoryTimestamp = 0
const shouldSkipDuplicateMemory = (memory: IMemoryUsageItem) => {
const now = Date.now()
const signature = `${memory.inuse}:${memory.oslimit ?? ''}`
if (
signature === lastMemorySignature &&
now - lastMemoryTimestamp <= DUPLICATE_MEMORY_WINDOW_MS
) {
return true
}
lastMemorySignature = signature
lastMemoryTimestamp = now
return false
}
export const useMemoryData = (options?: { enabled?: boolean }) => {
const enabled = options?.enabled ?? true
const { response, refresh } = useMihomoWsSubscription<IMemoryUsageItem>({
subscriptionKey: enabled ? 'getClashMemory' : null,
fallbackData: FALLBACK_MEMORY_USAGE,
connect: () => MihomoWebSocket.connect_memory(),
throttleMs: 500,
setupHandlers: ({ next, scheduleReconnect }) => ({
handleMessage: (data) => {
if (data.startsWith('Websocket error')) {
void scheduleReconnect()
return
}
try {
const parsed = JSON.parse(data) as IMemoryUsageItem
if (shouldSkipDuplicateMemory(parsed)) {
return
}
next(parsed)
} catch {}
},
}),
})
return { response, refreshGetClashMemory: refresh }
}