From 246a1ac053ef56a1930d3ad2ae3bd0784e01c513 Mon Sep 17 00:00:00 2001 From: YetAnotherZephyruso <176294927+YetAnotherZephyruso@users.noreply.github.com> Date: Sat, 14 Sep 2024 23:53:54 +0800 Subject: [PATCH] feat: reconnect ws when logs level changed (#1003) --- src/signals/logs.ts | 27 +++++++++++++++++---------- src/signals/request.ts | 16 +++++++++++++++- 2 files changed, 32 insertions(+), 11 deletions(-) diff --git a/src/signals/logs.ts b/src/signals/logs.ts index 0b7776e..37eac17 100644 --- a/src/signals/logs.ts +++ b/src/signals/logs.ts @@ -3,21 +3,28 @@ import { logLevel, logMaxRows } from '~/signals/config' import { Log, LogWithSeq } from '~/types' let seq = 1 -const [logs, setLogs] = createSignal([]) -const logsData = useWsRequest('logs', { level: logLevel() }) +const [logs, setLogs] = createSignal([]) 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('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 { diff --git a/src/signals/request.ts b/src/signals/request.ts index 52850c0..855652e 100644 --- a/src/signals/request.ts +++ b/src/signals/request.ts @@ -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() + export const useWsRequest = ( path: string, queries: Record = {}, ) => { + 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 = ( message: MessageEvent }>(ws, 'message') + webSocketInstanceMap.set(path, ws) + return createMemo(() => { const e = event()