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

View File

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