diff --git a/apps/frontend/src/state/valkey-features/connection/connectionSlice.test.ts b/apps/frontend/src/state/valkey-features/connection/connectionSlice.test.ts index a2717399..0d71c0a1 100644 --- a/apps/frontend/src/state/valkey-features/connection/connectionSlice.test.ts +++ b/apps/frontend/src/state/valkey-features/connection/connectionSlice.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect, beforeEach, vi } from "vitest" -import { CONNECTED, CONNECTING, ERROR, DISCONNECTED, DISCONNECTING } from "@common/src/constants" +import { CONNECTED, CONNECTING, ERROR, DISCONNECTED, DISCONNECTING, VALKEY } from "@common/src/constants" import connectionReducer, { connectPending, standaloneConnectFulfilled, @@ -973,4 +973,88 @@ describe("connectionSlice", () => { expect(Object.keys(state.connections)).toEqual(["bad-abc-db0"]) }) }) + + describe("hotKeysFulfilled extraReducer", () => { + it("updates keyEvictionPolicy and clusterSlotStatsEnabled for cluster connections", () => { + const previousState = { + connections: { + "node-1-db0": { + status: CONNECTED, + errorMessage: null, + connectionDetails: { + host: "127.0.0.1", + port: "7000", + clusterId: "cluster-1", + keyEvictionPolicy: "allkeys-lru", + clusterSlotStatsEnabled: false, + tls: false, + verifyTlsCertificate: false, + }, + }, + "node-2-db0": { + status: CONNECTED, + errorMessage: null, + connectionDetails: { + host: "127.0.0.1", + port: "7001", + clusterId: "cluster-1", + keyEvictionPolicy: "allkeys-lru", + clusterSlotStatsEnabled: false, + tls: false, + verifyTlsCertificate: false, + }, + }, + } as ValkeyConnectionsState, + } + + const state = connectionReducer( + previousState, + { + type: VALKEY.HOTKEYS.hotKeysFulfilled, + payload: { + clusterId: "cluster-1", + keyEvictionPolicy: "allkeys-lfu", + clusterSlotStatsEnabled: true, + }, + }, + ) + + expect(state.connections["node-1-db0"].connectionDetails.keyEvictionPolicy).toBe("allkeys-lfu") + expect(state.connections["node-1-db0"].connectionDetails.clusterSlotStatsEnabled).toBe(true) + expect(state.connections["node-2-db0"].connectionDetails.keyEvictionPolicy).toBe("allkeys-lfu") + expect(state.connections["node-2-db0"].connectionDetails.clusterSlotStatsEnabled).toBe(true) + }) + + it("updates keyEvictionPolicy for standalone connections by matching nodeId", () => { + const previousState = { + connections: { + "host-6379-db0": { + status: CONNECTED, + errorMessage: null, + connectionDetails: { + host: "localhost", + port: "6379", + keyEvictionPolicy: "noeviction", + clusterSlotStatsEnabled: false, + tls: false, + verifyTlsCertificate: false, + }, + }, + } as ValkeyConnectionsState, + } + + const state = connectionReducer( + previousState, + { + type: VALKEY.HOTKEYS.hotKeysFulfilled, + payload: { + nodeId: "host-6379", + keyEvictionPolicy: "allkeys-lfu", + }, + }, + ) + + expect(state.connections["host-6379-db0"].connectionDetails.keyEvictionPolicy).toBe("allkeys-lfu") + }) + }) }) diff --git a/apps/frontend/src/state/valkey-features/connection/connectionSlice.ts b/apps/frontend/src/state/valkey-features/connection/connectionSlice.ts index de3f1248..dae49eec 100644 --- a/apps/frontend/src/state/valkey-features/connection/connectionSlice.ts +++ b/apps/frontend/src/state/valkey-features/connection/connectionSlice.ts @@ -13,7 +13,7 @@ import { type EndpointType } from "@common/src/constants" import * as R from "ramda" -import { buildConnectionId, normalizeEndpoint } from "@common/src/connection-id.ts" +import { buildConnectionId, normalizeEndpoint, toNodeId } from "@common/src/connection-id.ts" import type { NodeRole } from "@/state/valkey-features/cluster/clusterSlice" import { secureStorage } from "@/utils/secureStorage" import { persistConnections } from "@/state/persistConnections" @@ -368,6 +368,41 @@ const connectionSlice = createSlice({ state.connections = R.map(stripUnencryptedPassword, state.connections as ValkeyConnectionsState) }, }, + extraReducers: (builder) => { + builder.addCase(VALKEY.HOTKEYS.hotKeysFulfilled, (state, action: PayloadAction<{ + clusterId?: string + nodeId?: string + keyEvictionPolicy?: KeyEvictionPolicy + clusterSlotStatsEnabled?: boolean + }>) => { + const { clusterId, nodeId, keyEvictionPolicy, clusterSlotStatsEnabled } = action.payload ?? {} + if (keyEvictionPolicy === undefined && clusterSlotStatsEnabled === undefined) return + + if (clusterId) { + Object.values(state.connections).forEach((conn) => { + if (conn.connectionDetails?.clusterId === clusterId) { + if (keyEvictionPolicy !== undefined) { + conn.connectionDetails.keyEvictionPolicy = keyEvictionPolicy + } + if (clusterSlotStatsEnabled !== undefined) { + conn.connectionDetails.clusterSlotStatsEnabled = clusterSlotStatsEnabled + } + } + }) + } else if (nodeId) { + Object.entries(state.connections).forEach(([connId, conn]) => { + if (toNodeId(connId) === nodeId) { + if (keyEvictionPolicy !== undefined) { + conn.connectionDetails.keyEvictionPolicy = keyEvictionPolicy + } + if (clusterSlotStatsEnabled !== undefined) { + conn.connectionDetails.clusterSlotStatsEnabled = clusterSlotStatsEnabled + } + } + }) + } + }) + }, }) export default connectionSlice.reducer diff --git a/apps/server/src/__tests__/hotkeys-commandlogs.test.ts b/apps/server/src/__tests__/hotkeys-commandlogs.test.ts index eaadbf49..b1367447 100644 --- a/apps/server/src/__tests__/hotkeys-commandlogs.test.ts +++ b/apps/server/src/__tests__/hotkeys-commandlogs.test.ts @@ -113,6 +113,46 @@ describe("hotKeysRequested reply shape", () => { assert.strictEqual(sent.payload.nodeErrors[0].nodeId, "node-2") assert.ok(!/-db\d+$/.test(sent.payload.nodeErrors[0].nodeId)) }) + + it("re-reads live maxmemory_policy and cluster-slot-stats from client and passes useHotSlots", async () => { + metricsServerMap.set("node-1", { metricsURI: "http://localhost:9001" }) + clusterNodesRegistry = new Map([ + ["cluster-1", { + "node-1": { host: "127.0.0.1", port: 7000, tls: false, verifyTlsCertificate: false }, + }], + ]) + const fetchCalls = mockFetch({ nodeId: "node-1", hotKeys: [], checkAt: 0, monitorRunning: true, lastCollectedAt: null }) + + const mockClusterClient = { + constructor: { name: "GlideClusterClient" }, + info: mock.fn(async () => "# Memory\r\nmaxmemory_policy:allkeys-lfu\r\n"), + customCommand: mock.fn(async () => [["slot", 1], ["cpu-usec", 100]]), + } + + const clientsMap = new Map([ + ["node-1", { client: mockClusterClient as any, clusterId: "cluster-1" }], + ]) + + const d = { + ...deps(), + clients: clientsMap, + } + + const action = { + type: VALKEY.HOTKEYS.hotKeysRequested, + payload: { connectionId: "node-1", clusterId: "cluster-1", lfuEnabled: false, clusterSlotStatsEnabled: false }, + } + + await hotKeysRequested(d)(action as any) + + assert.strictEqual(messages.length, 1) + const sent = JSON.parse(messages[0]) + assert.strictEqual(sent.type, VALKEY.HOTKEYS.hotKeysFulfilled) + assert.strictEqual(sent.payload.clusterId, "cluster-1") + assert.strictEqual(sent.payload.keyEvictionPolicy, "allkeys-lfu") + assert.strictEqual(sent.payload.clusterSlotStatsEnabled, true) + assert.ok(fetchCalls[0].includes("useHotSlots=true")) + }) }) describe("commandLogsRequested reply shape", () => { diff --git a/apps/server/src/actions/hotkeys.ts b/apps/server/src/actions/hotkeys.ts index bf0dd98b..027100cb 100644 --- a/apps/server/src/actions/hotkeys.ts +++ b/apps/server/src/actions/hotkeys.ts @@ -5,10 +5,12 @@ import { type HotKeysResponse, type NodeError, toNodeId, - buildUrl + buildUrl, + type KeyEvictionPolicy } from "valkey-common" import * as R from "ramda" import { withDeps, Deps, collectorFeaturesDisabled, KUBERNETES_METRICS_UNAVAILABLE } from "./utils" +import { getKeyEvictionPolicy, getClusterSlotStatsEnabled } from "../utils" // One node's reply from the metrics server. Its tuples have no nodeId; the merge below adds it for HotKeysResponse. type MetricsHotKeysResponse = { @@ -24,6 +26,7 @@ const sendHotKeysFulfilled = ( replyId: AggregateReplyId, // Hotkeys aggregates all cluster nodes into one result parsedResponse: HotKeysResponse, nodeErrors?: NodeError[], + configUpdates?: { keyEvictionPolicy?: KeyEvictionPolicy; clusterSlotStatsEnabled?: boolean }, ) => { ws.send( JSON.stringify({ @@ -32,6 +35,8 @@ const sendHotKeysFulfilled = ( ...replyId, parsedResponse, ...(nodeErrors?.length ? { nodeErrors } : {}), + ...(configUpdates?.keyEvictionPolicy !== undefined && { keyEvictionPolicy: configUpdates.keyEvictionPolicy }), + ...(configUpdates?.clusterSlotStatsEnabled !== undefined && { clusterSlotStatsEnabled: configUpdates.clusterSlotStatsEnabled }), }, }), ) @@ -57,7 +62,7 @@ const sendHotKeysError = ( } export const hotKeysRequested = withDeps( - async ({ ws, metricsServerMap, action, clusterNodesRegistry }) => { + async ({ ws, metricsServerMap, action, clusterNodesRegistry, clients }) => { const { connectionId, clusterId, lfuEnabled, clusterSlotStatsEnabled } = action.payload if (collectorFeaturesDisabled()) { sendHotKeysError(ws, toNodeId(connectionId), KUBERNETES_METRICS_UNAVAILABLE, clusterId) @@ -65,6 +70,53 @@ export const hotKeysRequested = withDeps( } const count = Number(action.payload.count) || Number(process.env.HOT_KEYS_COUNT) || 50 + let client = clients?.get(connectionId)?.client + if (!client && clusterId && clients) { + for (const entry of clients.values()) { + if (entry.clusterId === clusterId) { + client = entry.client + break + } + } + } + + let liveKeyEvictionPolicy: KeyEvictionPolicy | undefined + let liveClusterSlotStatsEnabled: boolean | undefined + + if (client) { + try { + const isCluster = Boolean(clusterId) || client.constructor.name === "GlideClusterClient" + if (isCluster) { + const [evictionPolicy, slotStats] = await Promise.all([ + getKeyEvictionPolicy(client), + getClusterSlotStatsEnabled(client as never), + ]) + liveKeyEvictionPolicy = evictionPolicy + liveClusterSlotStatsEnabled = slotStats + } else { + liveKeyEvictionPolicy = await getKeyEvictionPolicy(client) + liveClusterSlotStatsEnabled = false + } + } catch (err) { + console.warn("[Hot keys] Failed to query live config:", err) + } + } + + const effectiveLfuEnabled = liveKeyEvictionPolicy !== undefined + ? liveKeyEvictionPolicy.includes("lfu") + : Boolean(lfuEnabled) + + const effectiveClusterSlotStatsEnabled = liveClusterSlotStatsEnabled !== undefined + ? liveClusterSlotStatsEnabled + : Boolean(clusterSlotStatsEnabled) + + const useHotSlots = effectiveClusterSlotStatsEnabled && effectiveLfuEnabled + + const configUpdates = { + keyEvictionPolicy: liveKeyEvictionPolicy, + clusterSlotStatsEnabled: liveClusterSlotStatsEnabled, + } + const nodes = typeof clusterId === "string" ? clusterNodesRegistry.get(clusterId) @@ -79,7 +131,7 @@ export const hotKeysRequested = withDeps( return { nodeId, error: "Metrics server not started" } as NodeError } const url = buildUrl(metricsServerURI, "/hot-keys", { - ...(clusterSlotStatsEnabled && lfuEnabled ? { useHotSlots: "true" } : {}), + ...(useHotSlots ? { useHotSlots: "true" } : {}), count, }) try { @@ -123,7 +175,7 @@ export const hotKeysRequested = withDeps( if (results.length === 0) { if (nodes) { const emptyResponse: HotKeysResponse = { hotKeys: [], monitorRunning: false, checkAt: 0, nodeId: "" } - sendHotKeysFulfilled(ws, { clusterId: clusterId as string }, emptyResponse, nodeErrors) + sendHotKeysFulfilled(ws, { clusterId: clusterId as string }, emptyResponse, nodeErrors, configUpdates) return } // Standalone: surface the node's error if it failed; otherwise emit an @@ -133,13 +185,13 @@ export const hotKeysRequested = withDeps( } else { const nodeId = toNodeId(connectionId) const emptyResponse: HotKeysResponse = { hotKeys: [], monitorRunning: false, checkAt: 0, nodeId } - sendHotKeysFulfilled(ws, { nodeId }, emptyResponse) + sendHotKeysFulfilled(ws, { nodeId }, emptyResponse, undefined, configUpdates) } return } if (!nodes) { - sendHotKeysFulfilled(ws, { nodeId: toNodeId(connectionId) }, results[0] as unknown as HotKeysResponse) + sendHotKeysFulfilled(ws, { nodeId: toNodeId(connectionId) }, results[0] as unknown as HotKeysResponse, undefined, configUpdates) return } @@ -164,5 +216,5 @@ export const hotKeysRequested = withDeps( const aggregatedResponse = { hotKeys: aggregatedHotKeys, monitorRunning, checkAt, nodeId, lastCollectedAt, } as unknown as HotKeysResponse - sendHotKeysFulfilled(ws, { clusterId: clusterId as string }, aggregatedResponse, nodeErrors) + sendHotKeysFulfilled(ws, { clusterId: clusterId as string }, aggregatedResponse, nodeErrors, configUpdates) })