feat(redis): improve key detail auto-refresh and TTL polling

This commit is contained in:
二丫讲梵 authored and GitHub committed 2026-07-31 02:41:26 +08:00
1 parent a662d12f57
commit c697d0c7ad
15 files changed
+540 -106

No files matched your search

@@ -1,12 +1,13 @@
// @vitest-environment happy-dom // @vitest-environment happy-dom
import { createApp, defineComponent, h, nextTick } from "vue"; import { createApp, defineComponent, h, KeepAlive, nextTick, ref } from "vue";
import { createI18n } from "vue-i18n"; import { createI18n } from "vue-i18n";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { calendarDateTimeToUnixSeconds, parseLocalDateTime } from "@/components/ui/date-time-picker/dateTimePicker"; import { calendarDateTimeToUnixSeconds, parseLocalDateTime } from "@/components/ui/date-time-picker/dateTimePicker";
const mocks = vi.hoisted(() => ({ const mocks = vi.hoisted(() => ({
redisGetValue: vi.fn(), redisGetValue: vi.fn(),
redisGetTtl: vi.fn(),
redisSetTtl: vi.fn(), redisSetTtl: vi.fn(),
redisSetExpireAt: vi.fn(), redisSetExpireAt: vi.fn(),
toast: vi.fn(), toast: vi.fn(),
@@ -14,6 +15,7 @@ const mocks = vi.hoisted(() => ({
vi.mock("@/lib/backend/api", () => ({ vi.mock("@/lib/backend/api", () => ({
redisGetValue: mocks.redisGetValue, redisGetValue: mocks.redisGetValue,
redisGetTtl: mocks.redisGetTtl,
redisSetTtl: mocks.redisSetTtl, redisSetTtl: mocks.redisSetTtl,
redisSetExpireAt: mocks.redisSetExpireAt, redisSetExpireAt: mocks.redisSetExpireAt,
})); }));
@@ -34,15 +36,44 @@ import RedisValueViewer from "./RedisValueViewer.vue";
const mountedApps: Array<{ unmount: () => void; host: HTMLElement }> = []; const mountedApps: Array<{ unmount: () => void; host: HTMLElement }> = [];
function createLocalStorage(): Storage {
const entries = new Map<string, string>();
return {
get length() {
return entries.size;
},
clear() {
entries.clear();
},
getItem(key) {
return entries.get(key) ?? null;
},
key(index) {
return [...entries.keys()][index] ?? null;
},
removeItem(key) {
entries.delete(key);
},
setItem(key, value) {
entries.set(key, String(value));
},
};
}
afterEach(() => { afterEach(() => {
for (const { unmount, host } of mountedApps.splice(0)) { for (const { unmount, host } of mountedApps.splice(0)) {
unmount(); unmount();
host.remove(); host.remove();
} }
localStorage.removeItem("dbx-redis-auto-refresh-enabled-v2");
localStorage.removeItem("dbx-redis-auto-refresh-interval-seconds-v2");
vi.unstubAllGlobals();
vi.useRealTimers();
}); });
beforeEach(() => { beforeEach(() => {
vi.clearAllMocks(); vi.clearAllMocks();
vi.stubGlobal("localStorage", createLocalStorage());
}); });
async function settle() { async function settle() {
@@ -81,7 +112,7 @@ function deferred<T>() {
return { promise, resolve }; return { promise, resolve };
} }
function mountViewer(onDeleted: (keyRaw: string) => void) { function mountViewer(onDeleted: (keyRaw: string) => void, onLoaded = vi.fn()) {
const host = document.createElement("div"); const host = document.createElement("div");
document.body.append(host); document.body.append(host);
const app = createApp( const app = createApp(
@@ -94,6 +125,7 @@ function mountViewer(onDeleted: (keyRaw: string) => void) {
keyDisplay: "key", keyDisplay: "key",
keyRaw: "key", keyRaw: "key",
onDeleted, onDeleted,
onLoaded,
}); });
}, },
}), }),
@@ -103,6 +135,42 @@ function mountViewer(onDeleted: (keyRaw: string) => void) {
mountedApps.push({ unmount: () => app.unmount(), host }); mountedApps.push({ unmount: () => app.unmount(), host });
} }
function mountKeepAliveViewer(onDeleted = vi.fn()) {
const host = document.createElement("div");
document.body.append(host);
const active = ref(true);
const inactiveView = defineComponent({ setup: () => () => h("div") });
const app = createApp(
defineComponent({
setup() {
return () =>
h(KeepAlive, null, {
default: () =>
active.value
? h(RedisValueViewer, {
key: "viewer",
connectionId: "connection",
db: 0,
keyDisplay: "key",
keyRaw: "key",
onDeleted,
})
: h(inactiveView, { key: "inactive" }),
});
},
}),
);
app.use(createI18n({ legacy: false, locale: "en", messages: { en: {} }, missingWarn: false, fallbackWarn: false }));
app.mount(host);
mountedApps.push({ unmount: () => app.unmount(), host });
return {
async setActive(value: boolean) {
active.value = value;
await settle();
},
};
}
async function saveTtlFromEditor() { async function saveTtlFromEditor() {
await openTtlEditor(); await openTtlEditor();
await saveOpenTtlEditor(); await saveOpenTtlEditor();
@@ -153,6 +221,179 @@ async function setStringDraft(value: string) {
} }
describe("RedisValueViewer expiry saving", () => { describe("RedisValueViewer expiry saving", () => {
it("defaults to manual refresh without TTL polling", async () => {
vi.useFakeTimers();
mocks.redisGetValue.mockResolvedValueOnce(stringValue("dmFsdWU=", 60));
mountViewer(vi.fn());
await settle();
await vi.advanceTimersByTimeAsync(10_000);
expect(mocks.redisGetTtl).not.toHaveBeenCalled();
expect(document.querySelector<HTMLButtonElement>("[aria-label='grid.refresh']")?.getAttribute("aria-pressed")).toBe("false");
});
it("polls only the TTL at the configured interval", async () => {
vi.useFakeTimers();
localStorage.setItem("dbx-redis-auto-refresh-enabled-v2", "true");
localStorage.setItem("dbx-redis-auto-refresh-interval-seconds-v2", "5");
mocks.redisGetValue.mockResolvedValueOnce(stringValue("dmFsdWU=", 60));
mocks.redisGetTtl.mockResolvedValueOnce(45);
const loaded = vi.fn();
mountViewer(vi.fn(), loaded);
await settle();
await vi.advanceTimersByTimeAsync(5000);
await settle();
expect(mocks.redisGetTtl).toHaveBeenCalledWith("connection", 0, "key");
expect(mocks.redisGetValue).toHaveBeenCalledOnce();
expect(loaded).toHaveBeenCalledOnce();
expect(document.querySelector<HTMLElement>("[data-slot='badge'][aria-label='redis.expiry']")?.textContent).toContain("00:00:45");
});
it("keeps polling when the loaded TTL starts at zero", async () => {
vi.useFakeTimers();
localStorage.setItem("dbx-redis-auto-refresh-enabled-v2", "true");
localStorage.setItem("dbx-redis-auto-refresh-interval-seconds-v2", "1");
mocks.redisGetValue.mockResolvedValueOnce(stringValue("dmFsdWU=", 0));
mocks.redisGetTtl.mockResolvedValueOnce(30);
mountViewer(vi.fn());
await settle();
await vi.advanceTimersByTimeAsync(1000);
await settle();
expect(mocks.redisGetTtl).toHaveBeenCalledOnce();
expect(document.querySelector<HTMLElement>("[data-slot='badge'][aria-label='redis.expiry']")?.textContent).toContain("00:00:30");
});
it("shows auto-refresh as stopped after a TTL polling error", async () => {
vi.useFakeTimers();
localStorage.setItem("dbx-redis-auto-refresh-enabled-v2", "true");
localStorage.setItem("dbx-redis-auto-refresh-interval-seconds-v2", "1");
mocks.redisGetValue.mockResolvedValueOnce(stringValue("dmFsdWU=", 60));
mocks.redisGetTtl.mockRejectedValueOnce(new Error("network unavailable"));
mountViewer(vi.fn());
await settle();
await vi.advanceTimersByTimeAsync(1000);
await settle();
expect(document.querySelector<HTMLButtonElement>("[aria-label='grid.refresh']")?.getAttribute("aria-pressed")).toBe("false");
});
it("keeps polling after an external PERSIST and picks up a later TTL", async () => {
vi.useFakeTimers();
localStorage.setItem("dbx-redis-auto-refresh-enabled-v2", "true");
localStorage.setItem("dbx-redis-auto-refresh-interval-seconds-v2", "1");
mocks.redisGetValue.mockResolvedValueOnce(stringValue("dmFsdWU=", 60));
mocks.redisGetTtl.mockResolvedValueOnce(-1).mockResolvedValueOnce(30);
mountViewer(vi.fn());
await settle();
await vi.advanceTimersByTimeAsync(1000);
await settle();
expect(document.querySelector<HTMLElement>("[data-slot='badge'][aria-label='redis.expiry']")?.textContent).toContain("redis.noExpiry");
await vi.advanceTimersByTimeAsync(1000);
await settle();
expect(mocks.redisGetTtl).toHaveBeenCalledTimes(2);
expect(document.querySelector<HTMLButtonElement>("[data-redis-value-refresh]")?.getAttribute("aria-pressed")).toBe("true");
expect(document.querySelector<HTMLElement>("[data-slot='badge'][aria-label='redis.expiry']")?.textContent).toContain("00:00:30");
});
it("pauses polling while the document is hidden and resumes when visible", async () => {
vi.useFakeTimers();
localStorage.setItem("dbx-redis-auto-refresh-enabled-v2", "true");
localStorage.setItem("dbx-redis-auto-refresh-interval-seconds-v2", "1");
mocks.redisGetValue.mockResolvedValueOnce(stringValue("dmFsdWU=", 60));
mocks.redisGetTtl.mockResolvedValue(45);
let visibilityState: DocumentVisibilityState = "visible";
vi.spyOn(document, "visibilityState", "get").mockImplementation(() => visibilityState);
mountViewer(vi.fn());
await settle();
visibilityState = "hidden";
document.dispatchEvent(new Event("visibilitychange"));
await vi.advanceTimersByTimeAsync(5000);
expect(mocks.redisGetTtl).not.toHaveBeenCalled();
visibilityState = "visible";
document.dispatchEvent(new Event("visibilitychange"));
await vi.advanceTimersByTimeAsync(1000);
await settle();
expect(mocks.redisGetTtl).toHaveBeenCalledOnce();
});
it("pauses polling while deactivated and resumes from the saved setting", async () => {
vi.useFakeTimers();
localStorage.setItem("dbx-redis-auto-refresh-enabled-v2", "true");
localStorage.setItem("dbx-redis-auto-refresh-interval-seconds-v2", "1");
mocks.redisGetValue.mockResolvedValueOnce(stringValue("dmFsdWU=", 60));
mocks.redisGetTtl.mockResolvedValue(45);
const viewer = mountKeepAliveViewer();
await settle();
await viewer.setActive(false);
await vi.advanceTimersByTimeAsync(5000);
expect(mocks.redisGetTtl).not.toHaveBeenCalled();
await viewer.setActive(true);
await vi.advanceTimersByTimeAsync(1000);
await settle();
expect(mocks.redisGetTtl).toHaveBeenCalledOnce();
});
it("pauses TTL polling while a value draft is unsaved", async () => {
vi.useFakeTimers();
localStorage.setItem("dbx-redis-auto-refresh-enabled-v2", "true");
localStorage.setItem("dbx-redis-auto-refresh-interval-seconds-v2", "1");
mocks.redisGetValue.mockResolvedValueOnce(stringValue("dmFsdWU=", 60));
const deleted = vi.fn();
mountViewer(deleted);
await settle();
await setStringDraft("draft");
await vi.advanceTimersByTimeAsync(5000);
await settle();
expect(mocks.redisGetTtl).not.toHaveBeenCalled();
expect(deleted).not.toHaveBeenCalled();
expect(document.querySelector<HTMLTextAreaElement>("textarea")?.value).toBe("draft");
});
it("ignores a missing-key response when a draft is created during TTL polling", async () => {
vi.useFakeTimers();
localStorage.setItem("dbx-redis-auto-refresh-enabled-v2", "true");
localStorage.setItem("dbx-redis-auto-refresh-interval-seconds-v2", "1");
mocks.redisGetValue.mockResolvedValueOnce(stringValue("dmFsdWU=", 60));
const ttlRequest = deferred<number>();
mocks.redisGetTtl.mockReturnValueOnce(ttlRequest.promise);
const deleted = vi.fn();
mountViewer(deleted);
await settle();
await vi.advanceTimersByTimeAsync(1000);
await settle();
expect(mocks.redisGetTtl).toHaveBeenCalledOnce();
await setStringDraft("draft");
ttlRequest.resolve(-2);
await settle();
await vi.advanceTimersByTimeAsync(5000);
await settle();
expect(mocks.redisGetTtl).toHaveBeenCalledOnce();
expect(deleted).not.toHaveBeenCalled();
expect(document.querySelector<HTMLTextAreaElement>("textarea")?.value).toBe("draft");
});
it("removes a key that disappears while a TTL save fails", async () => { it("removes a key that disappears while a TTL save fails", async () => {
mocks.redisGetValue.mockResolvedValueOnce(stringValue()).mockResolvedValueOnce(missingValue()); mocks.redisGetValue.mockResolvedValueOnce(stringValue()).mockResolvedValueOnce(missingValue());
mocks.redisSetTtl.mockRejectedValueOnce(new Error("Redis key no longer exists; EXPIRE was not applied")); mocks.redisSetTtl.mockRejectedValueOnce(new Error("Redis key no longer exists; EXPIRE was not applied"));
@@ -159,6 +159,15 @@ function openGroups(host: HTMLElement) {
host.querySelector<HTMLButtonElement>("[data-redis-stream-groups-tab]")!.dispatchEvent(new MouseEvent("mousedown", { bubbles: true, button: 0 })); host.querySelector<HTMLButtonElement>("[data-redis-stream-groups-tab]")!.dispatchEvent(new MouseEvent("mousedown", { bubbles: true, button: 0 }));
} }
async function refreshValue(host: HTMLElement) {
host.querySelector<HTMLButtonElement>("[data-redis-value-refresh]")!.click();
await settle();
const refreshItem = document.querySelector<HTMLElement>("[data-slot='dropdown-menu-content'] [data-slot='dropdown-menu-item']");
expect(refreshItem).not.toBeNull();
refreshItem!.click();
await settle();
}
describe("RedisValueViewer stream monitoring", () => { describe("RedisValueViewer stream monitoring", () => {
it("loads more Stream entries from the returned cursor", async () => { it("loads more Stream entries from the returned cursor", async () => {
mocks.redisGetValue.mockResolvedValue(streamValue([streamEntry("1714470000000-0")], "1714470000000-0")); mocks.redisGetValue.mockResolvedValue(streamValue([streamEntry("1714470000000-0")], "1714470000000-0"));
@@ -347,8 +356,7 @@ describe("RedisValueViewer stream monitoring", () => {
host.querySelector<HTMLButtonElement>("[data-redis-stream-consumer-row]")!.click(); host.querySelector<HTMLButtonElement>("[data-redis-stream-consumer-row]")!.click();
await settle(); await settle();
host.querySelector<HTMLButtonElement>("[data-redis-value-refresh]")!.click(); await refreshValue(host);
await settle();
expect(mocks.redisGetValue).toHaveBeenCalledTimes(2); expect(mocks.redisGetValue).toHaveBeenCalledTimes(2);
expect(mocks.redisGetStreamGroups).toHaveBeenCalledTimes(2); expect(mocks.redisGetStreamGroups).toHaveBeenCalledTimes(2);
@@ -372,8 +380,7 @@ describe("RedisValueViewer stream monitoring", () => {
host.querySelector<HTMLButtonElement>("[data-redis-stream-consumer-row]")!.click(); host.querySelector<HTMLButtonElement>("[data-redis-stream-consumer-row]")!.click();
await settle(); await settle();
host.querySelector<HTMLButtonElement>("[data-redis-value-refresh]")!.click(); await refreshValue(host);
await settle();
expect(mocks.redisGetStreamConsumers).toHaveBeenCalledTimes(2); expect(mocks.redisGetStreamConsumers).toHaveBeenCalledTimes(2);
expect(host.querySelector("[data-redis-stream-consumer-crumb]")).toBeNull(); expect(host.querySelector("[data-redis-stream-consumer-crumb]")).toBeNull();
@@ -399,8 +406,7 @@ describe("RedisValueViewer stream monitoring", () => {
host.querySelector<HTMLElement>("[data-redis-stream-group-row]")!.click(); host.querySelector<HTMLElement>("[data-redis-stream-group-row]")!.click();
await settle(); await settle();
host.querySelector<HTMLButtonElement>("[data-redis-value-refresh]")!.click(); await refreshValue(host);
await settle();
expect(mocks.redisGetStreamGroups).toHaveBeenCalledTimes(2); expect(mocks.redisGetStreamGroups).toHaveBeenCalledTimes(2);
expect(host.querySelector("[data-redis-stream-group-detail]")).toBeNull(); expect(host.querySelector("[data-redis-stream-group-detail]")).toBeNull();
@@ -1,10 +1,10 @@
<script setup lang="ts"> <script setup lang="ts">
import { computed, ref, shallowRef, nextTick, onBeforeUnmount, onMounted, watch } from "vue"; import { computed, ref, shallowRef, nextTick, onActivated, onBeforeUnmount, onDeactivated, onMounted, watch } from "vue";
import type { CalendarDateTime } from "@internationalized/date"; import type { CalendarDateTime } from "@internationalized/date";
import { useI18n } from "vue-i18n"; import { useI18n } from "vue-i18n";
import { onClickOutside } from "@vueuse/core"; import { onClickOutside } from "@vueuse/core";
import { DynamicScroller, DynamicScrollerItem, RecycleScroller } from "vue-virtual-scroller"; import { DynamicScroller, DynamicScrollerItem, RecycleScroller } from "vue-virtual-scroller";
import { Copy, ClipboardCopy, Eye, Trash2, Save, RefreshCw, Plus, Loader2, Pencil, WrapText, ArrowUp, ArrowDown, ArrowUpDown, Search, Clock } from "@lucide/vue"; import { Check, Copy, ClipboardCopy, Eye, Trash2, Save, RefreshCw, Plus, Loader2, Pencil, WrapText, ArrowUp, ArrowDown, ArrowUpDown, Search } from "@lucide/vue";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input"; import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge"; import { Badge } from "@/components/ui/badge";
@@ -13,6 +13,7 @@ import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import DateTimePicker from "@/components/ui/date-time-picker/DateTimePicker.vue"; import DateTimePicker from "@/components/ui/date-time-picker/DateTimePicker.vue";
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog"; import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
import DangerConfirmDialog from "@/components/editor/DangerConfirmDialog.vue"; import DangerConfirmDialog from "@/components/editor/DangerConfirmDialog.vue";
import JsonTree from "@/components/common/JsonTree.vue"; import JsonTree from "@/components/common/JsonTree.vue";
import RedisJsonEditor from "@/components/redis/RedisJsonEditor.vue"; import RedisJsonEditor from "@/components/redis/RedisJsonEditor.vue";
@@ -24,7 +25,7 @@ import { useEditorFontFamilyStyle } from "@/composables/useEditorFontFamilyStyle
import { createShikiJsonHighlighter, type JsonHighlighter } from "@/lib/common/shikiJsonHighlighter"; import { createShikiJsonHighlighter, type JsonHighlighter } from "@/lib/common/shikiJsonHighlighter";
import { copyToClipboard } from "@/lib/common/clipboard"; import { copyToClipboard } from "@/lib/common/clipboard";
import { formatTtl } from "@/lib/common/ttlFormat"; import { formatTtl } from "@/lib/common/ttlFormat";
import { computeAutoRefreshTick, computeDisplayTtl, computeTtlForExpiryEdit, shouldStopAutoRefresh } from "@/lib/redis/redisAutoRefresh"; import { computeAutoRefreshTick, computeDisplayTtl, computeTtlForExpiryEdit, DEFAULT_REDIS_AUTO_REFRESH_INTERVAL_SECONDS, normalizeRedisAutoRefreshInterval } from "@/lib/redis/redisAutoRefresh";
import { import {
canRenderRedisValueFormat, canRenderRedisValueFormat,
canEditRedisMemberDetail, canEditRedisMemberDetail,
@@ -74,6 +75,11 @@ const emit = defineEmits<{ deleted: [keyRaw: string]; loaded: [value: RedisValue
const REDIS_JSON_WRAP_STORAGE_KEY = "dbx-redis-json-word-wrap"; const REDIS_JSON_WRAP_STORAGE_KEY = "dbx-redis-json-word-wrap";
const REDIS_VALUE_FORMAT_STORAGE_KEY = "dbx-redis-value-format"; const REDIS_VALUE_FORMAT_STORAGE_KEY = "dbx-redis-value-format";
// Versioned after moving the setting into the refresh menu so the previous
// always-on default does not carry into the new manual-refresh default.
const REDIS_AUTO_REFRESH_ENABLED_STORAGE_KEY = "dbx-redis-auto-refresh-enabled-v2";
const REDIS_AUTO_REFRESH_INTERVAL_STORAGE_KEY = "dbx-redis-auto-refresh-interval-seconds-v2";
const REDIS_AUTO_REFRESH_INTERVAL_OPTIONS = [1, 3, 5, 10] as const;
const REDIS_COLLECTION_ROW_HEIGHT = 32; const REDIS_COLLECTION_ROW_HEIGHT = 32;
const REDIS_STREAM_MIN_ROW_HEIGHT = 96; const REDIS_STREAM_MIN_ROW_HEIGHT = 96;
@@ -158,58 +164,112 @@ const memberValueView = ref<RedisValueFormat>(readPreferredRedisValueFormat());
const redisJsonWordWrap = ref(readRedisJsonWordWrap()); const redisJsonWordWrap = ref(readRedisJsonWordWrap());
const redisJsonHighlighter = ref<JsonHighlighter>(); const redisJsonHighlighter = ref<JsonHighlighter>();
// Auto-refresh // Auto-refresh keeps the displayed TTL moving locally and periodically asks
const autoRefreshEnabled = ref(true); // Redis for the authoritative value. The two timers stay separate so a short
// polling interval never causes a full key-value reload.
const autoRefreshEnabled = ref(readRedisAutoRefreshEnabled());
const autoRefreshIntervalSeconds = ref(readRedisAutoRefreshInterval());
const countdownTtl = ref(0); const countdownTtl = ref(0);
const refreshingTtl = ref(false);
let autoRefreshTimer: ReturnType<typeof setInterval> | null = null; let autoRefreshTimer: ReturnType<typeof setInterval> | null = null;
let countdownTimer: ReturnType<typeof setInterval> | null = null;
let ttlRefreshRequestId = 0;
let redisValueViewerIsActive = true;
function toggleAutoRefresh() { function canRunAutoRefresh(): boolean {
autoRefreshEnabled.value = !autoRefreshEnabled.value; return redisValueViewerIsActive && document.visibilityState !== "hidden";
if (autoRefreshEnabled.value) { }
startAutoRefresh();
} else { function disableAutoRefresh() {
stopAutoRefresh(); autoRefreshEnabled.value = false;
persistRedisAutoRefreshEnabled(false);
stopAutoRefresh();
}
function selectAutoRefreshInterval(interval: number) {
autoRefreshIntervalSeconds.value = interval;
persistRedisAutoRefreshInterval(interval);
if (!autoRefreshEnabled.value) {
autoRefreshEnabled.value = true;
persistRedisAutoRefreshEnabled(true);
} }
startAutoRefresh();
} }
function startAutoRefresh() { function startAutoRefresh() {
stopAutoRefresh(); stopAutoRefresh();
if (data.value && data.value.ttl > 0) { if (!autoRefreshEnabled.value || !data.value || !canRunAutoRefresh()) return;
countdownTtl.value = data.value.ttl;
} countdownTtl.value = data.value.ttl;
autoRefreshTimer = setInterval(() => { countdownTimer = setInterval(() => {
const action = computeAutoRefreshTick(autoRefreshEnabled.value, countdownTtl.value, loading.value); const action = computeAutoRefreshTick(autoRefreshEnabled.value, countdownTtl.value);
if (action.type === "decrement") { if (action.type === "decrement") {
countdownTtl.value--; countdownTtl.value--;
return;
}
if (action.type === "refresh") {
// Do not let a background refresh overwrite a Redis value draft.
if (hasUnsavedRedisDraft.value) return;
load({ preserveDraft: true })
.then((applied) => {
if (!applied || !autoRefreshEnabled.value) return;
if (!data.value || shouldStopAutoRefresh(data.value.ttl)) {
stopAutoRefresh();
autoRefreshEnabled.value = false;
}
})
.catch(() => {
// Network / connection error — stop auto-refresh to avoid tight retry loop
if (autoRefreshEnabled.value) {
stopAutoRefresh();
autoRefreshEnabled.value = false;
}
});
} }
}, 1000); }, 1000);
autoRefreshTimer = setInterval(() => void refreshTtl(), autoRefreshIntervalSeconds.value * 1000);
}
async function refreshTtl() {
if (refreshingTtl.value || loading.value || editingTtl.value || savingTtl.value || hasUnsavedRedisDraft.value || !autoRefreshEnabled.value || !data.value || !canRunAutoRefresh()) return;
const requestId = ++ttlRefreshRequestId;
refreshingTtl.value = true;
try {
const ttl = await api.redisGetTtl(props.connectionId, props.db, props.keyRaw);
// A draft may be created while the request is in flight. Never apply even
// a missing-key response after the user has started editing.
if (requestId !== ttlRefreshRequestId || hasUnsavedRedisDraft.value || !autoRefreshEnabled.value || !data.value || !canRunAutoRefresh()) return;
if (ttl === -2) {
data.value = null;
collectionItems.value = [];
scanCursor.value = undefined;
resetStreamEntries();
resetStreamMonitoring();
stopAutoRefresh();
emit("deleted", props.keyRaw);
return;
}
const refreshedValue = { ...data.value, ttl };
data.value = refreshedValue;
countdownTtl.value = ttl;
} catch {
// A failed background read must not retry in a tight loop. Manual refresh
// remains available and starts a fresh polling lifecycle on success.
if (requestId === ttlRefreshRequestId) {
stopAutoRefresh();
// The user did not turn the preference off, so do not persist this
// transient failure. The visible state must still match the stopped
// timers and let one click restart polling.
autoRefreshEnabled.value = false;
}
} finally {
if (requestId === ttlRefreshRequestId) refreshingTtl.value = false;
}
} }
function stopAutoRefresh() { function stopAutoRefresh() {
ttlRefreshRequestId++;
refreshingTtl.value = false;
if (autoRefreshTimer !== null) { if (autoRefreshTimer !== null) {
clearInterval(autoRefreshTimer); clearInterval(autoRefreshTimer);
autoRefreshTimer = null; autoRefreshTimer = null;
} }
if (countdownTimer !== null) {
clearInterval(countdownTimer);
countdownTimer = null;
}
}
function handleDocumentVisibilityChange() {
if (document.visibilityState === "hidden") {
stopAutoRefresh();
return;
}
startAutoRefresh();
} }
const hashSortBy = ref<"field" | "value" | null>(null); const hashSortBy = ref<"field" | "value" | null>(null);
@@ -776,6 +836,39 @@ function readRedisJsonWordWrap(): boolean {
} }
} }
function readRedisAutoRefreshEnabled(): boolean {
try {
return localStorage.getItem(REDIS_AUTO_REFRESH_ENABLED_STORAGE_KEY) === "true";
} catch {
return false;
}
}
function persistRedisAutoRefreshEnabled(enabled: boolean) {
try {
localStorage.setItem(REDIS_AUTO_REFRESH_ENABLED_STORAGE_KEY, enabled ? "true" : "false");
} catch {
// Keep the preference for this component if storage is unavailable.
}
}
function readRedisAutoRefreshInterval(): number {
try {
const stored = localStorage.getItem(REDIS_AUTO_REFRESH_INTERVAL_STORAGE_KEY);
return stored === null ? DEFAULT_REDIS_AUTO_REFRESH_INTERVAL_SECONDS : normalizeRedisAutoRefreshInterval(stored);
} catch {
return DEFAULT_REDIS_AUTO_REFRESH_INTERVAL_SECONDS;
}
}
function persistRedisAutoRefreshInterval(interval: number) {
try {
localStorage.setItem(REDIS_AUTO_REFRESH_INTERVAL_STORAGE_KEY, String(interval));
} catch {
// Keep the current interval if storage is unavailable.
}
}
function setRedisJsonWordWrap(value: boolean) { function setRedisJsonWordWrap(value: boolean) {
redisJsonWordWrap.value = value; redisJsonWordWrap.value = value;
try { try {
@@ -1008,7 +1101,7 @@ async function load(options: { selectDefaultMember?: boolean; preserveDraft?: bo
} finally { } finally {
if (requestId === loadRequestId) { if (requestId === loadRequestId) {
loading.value = false; loading.value = false;
if (autoRefreshEnabled.value && data.value && data.value.ttl > 0) { if (autoRefreshEnabled.value && data.value) {
startAutoRefresh(); startAutoRefresh();
} }
} }
@@ -1849,6 +1942,7 @@ watch(showMemberDetail, (open) => {
onMounted(() => { onMounted(() => {
window.addEventListener("pointerdown", handleValueViewerPointerDown, true); window.addEventListener("pointerdown", handleValueViewerPointerDown, true);
document.addEventListener("visibilitychange", handleDocumentVisibilityChange);
void load(); void load();
void createShikiJsonHighlighter({ void createShikiJsonHighlighter({
appearance: () => redisJsonAppearance.value, appearance: () => redisJsonAppearance.value,
@@ -1860,8 +1954,18 @@ onMounted(() => {
redisJsonHighlighter.value = undefined; redisJsonHighlighter.value = undefined;
}); });
}); });
onActivated(() => {
redisValueViewerIsActive = true;
startAutoRefresh();
});
onDeactivated(() => {
redisValueViewerIsActive = false;
stopAutoRefresh();
});
onBeforeUnmount(() => { onBeforeUnmount(() => {
window.removeEventListener("pointerdown", handleValueViewerPointerDown, true); window.removeEventListener("pointerdown", handleValueViewerPointerDown, true);
document.removeEventListener("visibilitychange", handleDocumentVisibilityChange);
redisValueViewerIsActive = false;
stopAutoRefresh(); stopAutoRefresh();
stopResizeHashColumns(); stopResizeHashColumns();
stopResizeZsetColumns(); stopResizeZsetColumns();
@@ -1897,7 +2001,39 @@ defineExpose({ focusSearch });
<div class="shrink-0 border-b bg-background"> <div class="shrink-0 border-b bg-background">
<div class="flex h-9 items-center gap-2 px-4"> <div class="flex h-9 items-center gap-2 px-4">
<span class="dbx-editor-font-family min-w-0 flex-1 truncate text-sm font-semibold">{{ formatValue(data.key_display) }}</span> <span class="dbx-editor-font-family min-w-0 flex-1 truncate text-sm font-semibold">{{ formatValue(data.key_display) }}</span>
<Button data-redis-value-refresh variant="ghost" size="icon" class="h-7 w-7 shrink-0 animate-none" :disabled="hasUnsavedRedisDraft" @click="refreshValueAndStreamGroups"><RefreshCw class="h-3.5 w-3.5 animate-none" /></Button> <DropdownMenu>
<DropdownMenuTrigger as-child>
<Button
data-redis-value-refresh
variant="ghost"
size="icon"
class="h-7 w-7 shrink-0 animate-none"
:class="autoRefreshEnabled ? 'bg-primary/10 text-primary hover:bg-primary/15' : ''"
:title="autoRefreshEnabled ? `${t('redis.autoRefresh')}: ${autoRefreshIntervalSeconds}s` : t('grid.refresh')"
:aria-label="autoRefreshEnabled ? `${t('redis.autoRefresh')}: ${autoRefreshIntervalSeconds}s` : t('grid.refresh')"
:aria-pressed="autoRefreshEnabled"
><RefreshCw class="h-3.5 w-3.5 animate-none"
/></Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" class="w-40">
<DropdownMenuItem class="gap-2" :disabled="hasUnsavedRedisDraft" @select="refreshValueAndStreamGroups">
<RefreshCw class="h-3.5 w-3.5" />
{{ t("grid.refresh") }}
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuLabel>{{ t("redis.autoRefresh") }}</DropdownMenuLabel>
<DropdownMenuItem class="gap-2" @select="disableAutoRefresh">
<Check v-if="!autoRefreshEnabled" class="h-3.5 w-3.5" />
<span v-else class="h-3.5 w-3.5" />
{{ t("serverDashboard.off") }}
</DropdownMenuItem>
<DropdownMenuItem v-for="interval in REDIS_AUTO_REFRESH_INTERVAL_OPTIONS" :key="interval" class="gap-2" @select="selectAutoRefreshInterval(interval)">
<Check v-if="autoRefreshEnabled && autoRefreshIntervalSeconds === interval" class="h-3.5 w-3.5" />
<span v-else class="h-3.5 w-3.5" />
{{ interval }}s
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
<Button variant="ghost" size="icon" class="h-7 w-7 shrink-0" :title="t('grid.copyValue')" :aria-label="t('grid.copyValue')" @click="copyValue"><Copy class="h-3.5 w-3.5" /></Button> <Button variant="ghost" size="icon" class="h-7 w-7 shrink-0" :title="t('grid.copyValue')" :aria-label="t('grid.copyValue')" @click="copyValue"><Copy class="h-3.5 w-3.5" /></Button>
<Button variant="ghost" size="icon" class="h-7 w-7 shrink-0" :title="t('redis.copyInsertStatement')" :aria-label="t('redis.copyInsertStatement')" @click="copyInsertStatement"><ClipboardCopy class="h-3.5 w-3.5" /></Button> <Button variant="ghost" size="icon" class="h-7 w-7 shrink-0" :title="t('redis.copyInsertStatement')" :aria-label="t('redis.copyInsertStatement')" @click="copyInsertStatement"><ClipboardCopy class="h-3.5 w-3.5" /></Button>
<Button variant="ghost" size="icon" class="h-7 w-7 shrink-0 text-destructive" @click="requestDeleteKey"><Trash2 class="h-3.5 w-3.5" /></Button> <Button variant="ghost" size="icon" class="h-7 w-7 shrink-0 text-destructive" @click="requestDeleteKey"><Trash2 class="h-3.5 w-3.5" /></Button>
@@ -1929,9 +2065,6 @@ defineExpose({ focusSearch });
<DateTimePicker v-else-if="ttlExpiryMode === 'at'" v-model="ttlExpireAt" compact :locale="locale" :disabled="savingTtl" /> <DateTimePicker v-else-if="ttlExpiryMode === 'at'" v-model="ttlExpireAt" compact :locale="locale" :disabled="savingTtl" />
<Button variant="ghost" size="icon" class="h-6 w-6 shrink-0" :disabled="savingTtl" :title="t('grid.save')" :aria-label="t('grid.save')" @click="saveTtl"><Save class="h-3 w-3" /></Button> <Button variant="ghost" size="icon" class="h-6 w-6 shrink-0" :disabled="savingTtl" :title="t('grid.save')" :aria-label="t('grid.save')" @click="saveTtl"><Save class="h-3 w-3" /></Button>
</div> </div>
<Button variant="ghost" size="icon" class="h-6 w-6 shrink-0" :class="{ 'text-primary bg-accent': autoRefreshEnabled }" :title="t('redis.autoRefresh')" @click="toggleAutoRefresh">
<Clock class="h-3.5 w-3.5" />
</Button>
</div> </div>
</div> </div>
@@ -234,7 +234,7 @@ describe("native RedisJSON editor", () => {
}); });
it("keeps retained drafts out of background refresh and exposes word wrap for every JSON editor", () => { it("keeps retained drafts out of background refresh and exposes word wrap for every JSON editor", () => {
const autoRefresh = findFunction("startAutoRefresh"); const refreshTtl = findFunction("refreshTtl");
const hashSearch = findFunction("onHashSearch"); const hashSearch = findFunction("onHashSearch");
const viewMember = findFunction("viewMember"); const viewMember = findFunction("viewMember");
const setMemberValueFormat = findFunction("setMemberValueFormat"); const setMemberValueFormat = findFunction("setMemberValueFormat");
@@ -243,10 +243,9 @@ describe("native RedisJSON editor", () => {
const labels = templateElements(parsedViewer.descriptor.template!.ast as unknown as TemplateElement); const labels = templateElements(parsedViewer.descriptor.template!.ast as unknown as TemplateElement);
const stringTextarea = findTemplateElement((element) => element.tag === "textarea" && directiveExpression(element, "model") === "editValue"); const stringTextarea = findTemplateElement((element) => element.tag === "textarea" && directiveExpression(element, "model") === "editValue");
const memberTextarea = findTemplateElement((element) => element.tag === "textarea" && directiveExpression(element, "model") === "memberEditValue"); const memberTextarea = findTemplateElement((element) => element.tag === "textarea" && directiveExpression(element, "model") === "memberEditValue");
const refreshButton = findTemplateElement((element) => element.tag === "Button" && directiveExpression(element, "on", "click") === "refreshValueAndStreamGroups"); const refreshItem = findTemplateElement((element) => element.tag === "DropdownMenuItem" && directiveExpression(element, "on", "select") === "refreshValueAndStreamGroups");
expect(autoRefresh.getText()).toContain("if (hasUnsavedRedisDraft.value) return;"); expect(refreshTtl.getText().match(/hasUnsavedRedisDraft\.value/g)).toHaveLength(2);
expect(autoRefresh.getText()).toContain("load({ preserveDraft: true })");
expect(hashSearch.getText()).toContain("if (!hasRetainedMemberDraft.value) clearSelectedMember();"); expect(hashSearch.getText()).toContain("if (!hasRetainedMemberDraft.value) clearSelectedMember();");
expect(viewMember.getText()).toContain("hasRetainedMemberDraft.value"); expect(viewMember.getText()).toContain("hasRetainedMemberDraft.value");
// Clean JSON → other format must clear memberDraftFormat so rawText is not compared to the pretty baseline. // Clean JSON → other format must clear memberDraftFormat so rawText is not compared to the pretty baseline.
@@ -259,6 +258,6 @@ describe("native RedisJSON editor", () => {
expect(labels.some((element) => element.tag === "label" && directiveExpression(element, "if") === "isTextRedisFormat(memberValueView)")).toBe(true); expect(labels.some((element) => element.tag === "label" && directiveExpression(element, "if") === "isTextRedisFormat(memberValueView)")).toBe(true);
expect(directiveExpression(stringTextarea, "bind", "readonly")).toBe("!canEditCurrentStringFormat || savingString"); expect(directiveExpression(stringTextarea, "bind", "readonly")).toBe("!canEditCurrentStringFormat || savingString");
expect(directiveExpression(memberTextarea, "bind", "readonly")).toBe("savingMember"); expect(directiveExpression(memberTextarea, "bind", "readonly")).toBe("savingMember");
expect(directiveExpression(refreshButton, "bind", "disabled")).toBe("hasUnsavedRedisDraft"); expect(directiveExpression(refreshItem, "bind", "disabled")).toBe("hasUnsavedRedisDraft");
}); });
}); });
+16 -33
View File
@@ -1,48 +1,31 @@
import { describe, expect, it } from "vitest"; import { describe, expect, it } from "vitest";
import { computeAutoRefreshTick, computeDisplayTtl, computeTtlForExpiryEdit, shouldStopAutoRefresh } from "@/lib/redis/redisAutoRefresh"; import { computeAutoRefreshTick, computeDisplayTtl, computeTtlForExpiryEdit, DEFAULT_REDIS_AUTO_REFRESH_INTERVAL_SECONDS, normalizeRedisAutoRefreshInterval } from "@/lib/redis/redisAutoRefresh";
describe("computeAutoRefreshTick", () => { describe("computeAutoRefreshTick", () => {
it("returns idle when auto-refresh is disabled", () => { it("returns idle when auto-refresh is disabled", () => {
expect(computeAutoRefreshTick(false, 10, false)).toEqual({ type: "idle" }); expect(computeAutoRefreshTick(false, 10)).toEqual({ type: "idle" });
// countdown value and loading flag don't matter when disabled expect(computeAutoRefreshTick(false, 0)).toEqual({ type: "idle" });
expect(computeAutoRefreshTick(false, 0, false)).toEqual({ type: "idle" }); expect(computeAutoRefreshTick(false, 5)).toEqual({ type: "idle" });
expect(computeAutoRefreshTick(false, 5, true)).toEqual({ type: "idle" });
}); });
it("returns decrement while more than one second remains", () => { it("returns decrement while a positive TTL remains", () => {
expect(computeAutoRefreshTick(true, 10, false)).toEqual({ type: "decrement" }); expect(computeAutoRefreshTick(true, 10)).toEqual({ type: "decrement" });
// decrement even when loading — countdown should keep ticking expect(computeAutoRefreshTick(true, 1)).toEqual({ type: "decrement" });
expect(computeAutoRefreshTick(true, 3, true)).toEqual({ type: "decrement" });
}); });
it("refreshes on the expiry tick instead of exposing a zero countdown", () => { it("stops decrementing after the TTL has reached zero", () => {
expect(computeAutoRefreshTick(true, 1, false)).toEqual({ type: "refresh" }); expect(computeAutoRefreshTick(true, 0)).toEqual({ type: "idle" });
expect(computeAutoRefreshTick(true, 0, false)).toEqual({ type: "refresh" }); expect(computeAutoRefreshTick(true, -1)).toEqual({ type: "idle" });
expect(computeAutoRefreshTick(true, -1, false)).toEqual({ type: "refresh" });
});
it("does not start another refresh when a load is already in flight", () => {
expect(computeAutoRefreshTick(true, 1, true)).toEqual({ type: "decrement" });
// This prevents concurrent load() calls
expect(computeAutoRefreshTick(true, 0, true)).toEqual({ type: "idle" });
expect(computeAutoRefreshTick(true, -1, true)).toEqual({ type: "idle" });
}); });
}); });
describe("shouldStopAutoRefresh", () => { describe("normalizeRedisAutoRefreshInterval", () => {
it("returns true when TTL is zero (key expired)", () => { it("uses the default for invalid values and clamps arbitrary input to safe seconds", () => {
expect(shouldStopAutoRefresh(0)).toBe(true); expect(normalizeRedisAutoRefreshInterval("invalid")).toBe(DEFAULT_REDIS_AUTO_REFRESH_INTERVAL_SECONDS);
}); expect(normalizeRedisAutoRefreshInterval(0)).toBe(1);
expect(normalizeRedisAutoRefreshInterval(1.9)).toBe(1);
it("returns true when TTL is negative (no expiry or key deleted)", () => { expect(normalizeRedisAutoRefreshInterval(9_999)).toBe(3600);
expect(shouldStopAutoRefresh(-1)).toBe(true);
expect(shouldStopAutoRefresh(-2)).toBe(true);
});
it("returns false when TTL is positive (key still alive)", () => {
expect(shouldStopAutoRefresh(1)).toBe(false);
expect(shouldStopAutoRefresh(3600)).toBe(false);
}); });
}); });
+1
View File
@@ -392,6 +392,7 @@ export const redisScanKeys = forward("redisScanKeys");
export const redisScanKeysBatch = forward("redisScanKeysBatch"); export const redisScanKeysBatch = forward("redisScanKeysBatch");
export const redisScanValues = forward("redisScanValues"); export const redisScanValues = forward("redisScanValues");
export const redisGetValue = forward("redisGetValue"); export const redisGetValue = forward("redisGetValue");
export const redisGetTtl = forward("redisGetTtl");
export const redisGetStreamEntries = forward("redisGetStreamEntries"); export const redisGetStreamEntries = forward("redisGetStreamEntries");
export const redisGetStreamGroups = forward("redisGetStreamGroups"); export const redisGetStreamGroups = forward("redisGetStreamGroups");
export const redisGetStreamConsumers = forward("redisGetStreamConsumers"); export const redisGetStreamConsumers = forward("redisGetStreamConsumers");
+4
View File
@@ -2259,6 +2259,10 @@ export async function redisGetValue(connectionId: string, db: number, keyRaw: st
return post("/api/redis/get-value", { connectionId, db, keyRaw }); return post("/api/redis/get-value", { connectionId, db, keyRaw });
} }
export async function redisGetTtl(connectionId: string, db: number, keyRaw: string): Promise<number> {
return post("/api/redis/get-ttl", { connectionId, db, keyRaw });
}
export async function redisGetStreamEntries(connectionId: string, db: number, keyRaw: string, cursor?: string): Promise<RedisStreamPage> { export async function redisGetStreamEntries(connectionId: string, db: number, keyRaw: string, cursor?: string): Promise<RedisStreamPage> {
return post("/api/redis/get-stream-entries", { connectionId, db, keyRaw, cursor }); return post("/api/redis/get-stream-entries", { connectionId, db, keyRaw, cursor });
} }
+4
View File
@@ -2090,6 +2090,10 @@ export async function redisGetValue(connectionId: string, db: number, keyRaw: st
return invoke("redis_get_value", { connectionId, db, keyRaw }); return invoke("redis_get_value", { connectionId, db, keyRaw });
} }
export async function redisGetTtl(connectionId: string, db: number, keyRaw: string): Promise<number> {
return invoke("redis_get_ttl", { connectionId, db, keyRaw });
}
export async function redisGetStreamEntries(connectionId: string, db: number, keyRaw: string, cursor?: string): Promise<RedisStreamPage> { export async function redisGetStreamEntries(connectionId: string, db: number, keyRaw: string, cursor?: string): Promise<RedisStreamPage> {
return invoke("redis_get_stream_entries", { connectionId, db, keyRaw, cursor }); return invoke("redis_get_stream_entries", { connectionId, db, keyRaw, cursor });
} }
+17 -19
View File
@@ -5,31 +5,29 @@
* state-machine logic without mounting a Vue component. * state-machine logic without mounting a Vue component.
*/ */
/** Action computed after evaluating one auto-refresh tick. */ export const MIN_REDIS_AUTO_REFRESH_INTERVAL_SECONDS = 1;
export type AutoRefreshTickAction = { type: "idle" } | { type: "decrement" } | { type: "refresh" }; export const MAX_REDIS_AUTO_REFRESH_INTERVAL_SECONDS = 3600;
export const DEFAULT_REDIS_AUTO_REFRESH_INTERVAL_SECONDS = 5;
/** /** Action computed after evaluating one visible TTL countdown tick. */
* Evaluate one tick of the auto-refresh interval. export type AutoRefreshTickAction = { type: "idle" } | { type: "decrement" };
*
* @param enabled Whether auto-refresh is currently toggled on. /** Keep a user-entered polling frequency within a safe, whole-second range. */
* @param countdownTtl Current countdown value in seconds. export function normalizeRedisAutoRefreshInterval(value: unknown): number {
* @param isLoading Whether a data load is already in flight. const seconds = typeof value === "number" ? value : Number(value);
* @returns The action the caller should take this tick. if (!Number.isFinite(seconds)) return DEFAULT_REDIS_AUTO_REFRESH_INTERVAL_SECONDS;
*/ return Math.min(MAX_REDIS_AUTO_REFRESH_INTERVAL_SECONDS, Math.max(MIN_REDIS_AUTO_REFRESH_INTERVAL_SECONDS, Math.floor(seconds)));
export function computeAutoRefreshTick(enabled: boolean, countdownTtl: number, isLoading: boolean): AutoRefreshTickAction {
if (!enabled) return { type: "idle" };
if (isLoading) return countdownTtl > 0 ? { type: "decrement" } : { type: "idle" };
return countdownTtl <= 1 ? { type: "refresh" } : { type: "decrement" };
} }
/** /**
* Determine whether auto-refresh should be automatically disabled * Evaluate one one-second visible TTL countdown tick.
* after a server load completes (e.g. key expired or deleted).
* *
* @param ttl The TTL value returned by the server (seconds, -1 = no expiry). * @param enabled Whether auto-refresh is currently toggled on.
* @param countdownTtl Current countdown value in seconds.
* @returns The action the caller should take this tick.
*/ */
export function shouldStopAutoRefresh(ttl: number): boolean { export function computeAutoRefreshTick(enabled: boolean, countdownTtl: number): AutoRefreshTickAction {
return ttl <= 0; return enabled && countdownTtl > 0 ? { type: "decrement" } : { type: "idle" };
} }
/** /**
+12
View File
@@ -2358,6 +2358,18 @@ where
}) })
} }
/// Read only a key's TTL without loading its value or collection members.
///
/// Redis returns `-2` for a missing key and `-1` for a key without an expiry;
/// callers preserve those sentinel values so the UI can update its detail view
/// without an additional round trip.
pub async fn get_ttl<C>(con: &mut C, key: &[u8]) -> Result<i64, String>
where
C: ConnectionLike + Send + Sync + Unpin,
{
redis::cmd("TTL").arg(key).query_async(con).await.map_err(|e| e.to_string())
}
fn redis_value_matches_query(value: &RedisValue, query: &str) -> bool { fn redis_value_matches_query(value: &RedisValue, query: &str) -> bool {
let query = query.trim(); let query = query.trim();
if query.is_empty() { if query.is_empty() {
+31
View File
@@ -137,6 +137,37 @@ pub async fn redis_get_value_in_db_core(
} }
} }
/// Fetch only the TTL for a selected key. This avoids repeatedly loading a
/// potentially large Redis value when the desktop detail view is polling.
pub async fn redis_get_ttl_in_db_core(
state: &AppState,
connection_id: &str,
db: u32,
key_raw: &str,
) -> Result<i64, String> {
ensure_redis_pool(state, connection_id).await?;
let connections = state.connections.read().await;
let pool = connections.get(connection_id).ok_or("Connection not found")?;
match pool {
PoolKind::Redis(redis) => {
let key = redis_driver::redis_key_raw_to_bytes(key_raw)?;
match redis {
RedisConnection::Direct(con) => {
let mut con = con.lock().await;
redis_driver::select_db(&mut *con, db).await?;
redis_driver::get_ttl(&mut *con, &key).await
}
RedisConnection::Cluster(cluster) => {
redis_driver::ensure_cluster_db(db)?;
let mut con = redis_driver::cluster_key_connection(cluster, &key).await?;
redis_driver::get_ttl(&mut con, &key).await
}
}
}
_ => Err("Not a Redis connection".to_string()),
}
}
pub async fn redis_stream_entries_in_db_core( pub async fn redis_stream_entries_in_db_core(
state: &AppState, state: &AppState,
connection_id: &str, connection_id: &str,
+1
View File
@@ -493,6 +493,7 @@ async fn main() {
.route("/redis/scan-keys-batch", post(routes::redis::scan_keys_batch)) .route("/redis/scan-keys-batch", post(routes::redis::scan_keys_batch))
.route("/redis/scan-values", post(routes::redis::scan_values)) .route("/redis/scan-values", post(routes::redis::scan_values))
.route("/redis/get-value", post(routes::redis::get_value)) .route("/redis/get-value", post(routes::redis::get_value))
.route("/redis/get-ttl", post(routes::redis::get_ttl))
.route("/redis/get-stream-entries", post(routes::redis::get_stream_entries)) .route("/redis/get-stream-entries", post(routes::redis::get_stream_entries))
.route("/redis/get-stream-groups", post(routes::redis::get_stream_groups)) .route("/redis/get-stream-groups", post(routes::redis::get_stream_groups))
.route("/redis/get-stream-consumers", post(routes::redis::get_stream_consumers)) .route("/redis/get-stream-consumers", post(routes::redis::get_stream_consumers))
+10
View File
@@ -331,6 +331,16 @@ pub async fn get_value(
Ok(Json(serde_json::to_value(result).map_err(|e| AppError::from(e.to_string()))?)) Ok(Json(serde_json::to_value(result).map_err(|e| AppError::from(e.to_string()))?))
} }
pub async fn get_ttl(
State(state): State<Arc<WebState>>,
Json(req): Json<RedisKeyRequest>,
) -> Result<Json<i64>, AppError> {
let ttl = dbx_core::redis_ops::redis_get_ttl_in_db_core(&state.app, &req.connection_id, req.db, &req.key_raw)
.await
.map_err(AppError::from)?;
Ok(Json(ttl))
}
pub async fn get_stream_entries( pub async fn get_stream_entries(
State(state): State<Arc<WebState>>, State(state): State<Arc<WebState>>,
Json(req): Json<RedisStreamEntriesRequest>, Json(req): Json<RedisStreamEntriesRequest>,
+10
View File
@@ -87,6 +87,16 @@ pub async fn redis_get_value(
dbx_core::redis_ops::redis_get_value_in_db_core(&state, &connection_id, db, &key_raw).await dbx_core::redis_ops::redis_get_value_in_db_core(&state, &connection_id, db, &key_raw).await
} }
#[tauri::command]
pub async fn redis_get_ttl(
state: State<'_, Arc<AppState>>,
connection_id: String,
db: u32,
key_raw: String,
) -> Result<i64, String> {
dbx_core::redis_ops::redis_get_ttl_in_db_core(&state, &connection_id, db, &key_raw).await
}
#[tauri::command] #[tauri::command]
pub async fn redis_get_stream_entries( pub async fn redis_get_stream_entries(
state: State<'_, Arc<AppState>>, state: State<'_, Arc<AppState>>,
+1
View File
@@ -1765,6 +1765,7 @@ pub fn run() {
commands::redis_cmd::redis_scan_keys_batch, commands::redis_cmd::redis_scan_keys_batch,
commands::redis_cmd::redis_scan_values, commands::redis_cmd::redis_scan_values,
commands::redis_cmd::redis_get_value, commands::redis_cmd::redis_get_value,
commands::redis_cmd::redis_get_ttl,
commands::redis_cmd::redis_get_stream_entries, commands::redis_cmd::redis_get_stream_entries,
commands::redis_cmd::redis_get_stream_groups, commands::redis_cmd::redis_get_stream_groups,
commands::redis_cmd::redis_get_stream_consumers, commands::redis_cmd::redis_get_stream_consumers,