feat: reconnect ws when logs level changed (#1003)

This commit is contained in:
YetAnotherZephyruso 2024-09-14 23:53:54 +08:00 committed by GitHub
parent 45d969c970
commit 246a1ac053
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 32 additions and 11 deletions

View File

@ -3,21 +3,28 @@ import { logLevel, logMaxRows } from '~/signals/config'
import { Log, LogWithSeq } from '~/types'
let seq = 1
const [logs, setLogs] = createSignal<LogWithSeq[]>([])
const logsData = useWsRequest<Log>('logs', { level: logLevel() })
const [logs, setLogs] = createSignal<LogWithSeq[]>([])
const [paused, setPaused] = createSignal(false)
createEffect(() => {
const data = logsData()
createEffect(
on(logLevel, (value, oldValue) => {
if (value === oldValue) return
if (!data || paused()) {
return
}
const logsData = useWsRequest<Log>('logs', { level: logLevel() })
setLogs((logs) => [{ ...data, seq }, ...logs].slice(0, logMaxRows()))
seq++
})
createEffect(() => {
const data = logsData()
if (!data || paused()) {
return
}
setLogs((logs) => [{ ...data, seq }, ...logs].slice(0, logMaxRows()))
seq++
})
}),
)
export const useLogs = () => {
return {

View File

@ -1,6 +1,9 @@
import { createEventSignal } from '@solid-primitives/event-listener'
import { makePersisted } from '@solid-primitives/storage'
import { createReconnectingWS } from '@solid-primitives/websocket'
import {
createReconnectingWS,
ReconnectingWebSocket,
} from '@solid-primitives/websocket'
import ky from 'ky'
import _ from 'lodash'
@ -50,10 +53,19 @@ export const secret = () => endpoint()?.secret
export const wsEndpointURL = () =>
_.trimEnd(new URL(endpoint()?.url ?? '').href.replace('http', 'ws'), '/')
const webSocketInstanceMap = new Map<string, ReconnectingWebSocket>()
export const useWsRequest = <T>(
path: string,
queries: Record<string, string> = {},
) => {
const oldInstance = webSocketInstanceMap.get(path)
if (oldInstance) {
oldInstance.close()
webSocketInstanceMap.delete(path)
}
const queryParams = new URLSearchParams(queries)
queryParams.set('token', secret() ?? '')
@ -65,6 +77,8 @@ export const useWsRequest = <T>(
message: MessageEvent
}>(ws, 'message')
webSocketInstanceMap.set(path, ws)
return createMemo<T | null>(() => {
const e = event()