feat(redis): add local expiration modes
This commit is contained in:
1 parent
3a2dc4225a
commit
51fa058edb
35 files changed
+2918
-98
No files matched your search
@@ -0,0 +1,524 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import { CalendarDateTime, resetLocalTimeZone, setLocalTimeZone } from "@internationalized/date";
|
||||
import { createApp, nextTick, type ComponentPublicInstance } from "vue";
|
||||
import { createI18n } from "vue-i18n";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { calendarDateTimeToUnixSeconds } from "@/components/ui/date-time-picker/dateTimePicker";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
redisScanKeysBatch: vi.fn(),
|
||||
redisGetValue: vi.fn(),
|
||||
redisSetString: vi.fn(),
|
||||
redisJsonSet: vi.fn(),
|
||||
redisHashSet: vi.fn(),
|
||||
redisListPush: vi.fn(),
|
||||
redisSetAdd: vi.fn(),
|
||||
redisZadd: vi.fn(),
|
||||
redisStreamAdd: vi.fn(),
|
||||
redisSetTtl: vi.fn(),
|
||||
redisSetExpireAt: vi.fn(),
|
||||
redisCheckJsonModule: vi.fn(),
|
||||
redisDeleteKey: vi.fn(),
|
||||
redisDeleteKeys: vi.fn(),
|
||||
toast: vi.fn(),
|
||||
updateRedisDbKeyStats: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/backend/api", () => ({
|
||||
redisScanKeysBatch: mocks.redisScanKeysBatch,
|
||||
redisGetValue: mocks.redisGetValue,
|
||||
redisSetString: mocks.redisSetString,
|
||||
redisJsonSet: mocks.redisJsonSet,
|
||||
redisHashSet: mocks.redisHashSet,
|
||||
redisListPush: mocks.redisListPush,
|
||||
redisSetAdd: mocks.redisSetAdd,
|
||||
redisZadd: mocks.redisZadd,
|
||||
redisStreamAdd: mocks.redisStreamAdd,
|
||||
redisSetTtl: mocks.redisSetTtl,
|
||||
redisSetExpireAt: mocks.redisSetExpireAt,
|
||||
redisCheckJsonModule: mocks.redisCheckJsonModule,
|
||||
redisDeleteKey: mocks.redisDeleteKey,
|
||||
redisDeleteKeys: mocks.redisDeleteKeys,
|
||||
}));
|
||||
|
||||
vi.mock("@/stores/connectionStore", () => ({
|
||||
useConnectionStore: () => ({
|
||||
ensureConnected: vi.fn().mockResolvedValue(undefined),
|
||||
getConfig: () => ({ name: "Redis", redis_key_separator: ":", redis_scan_page_size: 100 }),
|
||||
updateRedisDbKeyStats: mocks.updateRedisDbKeyStats,
|
||||
invalidateCompletionCache: vi.fn(),
|
||||
refreshRedisDbKeyCounts: vi.fn(),
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock("@/composables/useEditorFontFamilyStyle", () => ({
|
||||
useEditorFontFamilyStyle: () => ({}),
|
||||
}));
|
||||
|
||||
vi.mock("@/composables/useToast", () => ({
|
||||
useToast: () => ({ toast: mocks.toast }),
|
||||
}));
|
||||
|
||||
vi.mock("@/components/ui/button", async () => {
|
||||
const { defineComponent, h } = await import("vue");
|
||||
return {
|
||||
Button: defineComponent({
|
||||
inheritAttrs: false,
|
||||
props: { disabled: Boolean },
|
||||
setup(props, { attrs, slots }) {
|
||||
return () => h("button", { ...attrs, disabled: props.disabled }, slots.default?.());
|
||||
},
|
||||
}),
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("@/components/ui/input", async () => {
|
||||
const { defineComponent, h } = await import("vue");
|
||||
return {
|
||||
Input: defineComponent({
|
||||
inheritAttrs: false,
|
||||
props: { modelValue: String, disabled: Boolean },
|
||||
emits: ["update:modelValue"],
|
||||
setup(props, { attrs, emit }) {
|
||||
return () =>
|
||||
h("input", {
|
||||
...attrs,
|
||||
value: props.modelValue ?? "",
|
||||
disabled: props.disabled,
|
||||
onInput: (event: Event) => emit("update:modelValue", (event.target as HTMLInputElement).value),
|
||||
});
|
||||
},
|
||||
}),
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("@/components/ui/badge", async () => {
|
||||
const { defineComponent, h } = await import("vue");
|
||||
return {
|
||||
Badge: defineComponent({
|
||||
setup:
|
||||
(_, { attrs, slots }) =>
|
||||
() =>
|
||||
h("span", attrs, slots.default?.()),
|
||||
}),
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("@/components/ui/dialog", async () => {
|
||||
const { defineComponent, h } = await import("vue");
|
||||
const slotContainer = defineComponent({
|
||||
setup:
|
||||
(_, { attrs, slots }) =>
|
||||
() =>
|
||||
h("div", attrs, slots.default?.()),
|
||||
});
|
||||
return {
|
||||
Dialog: defineComponent({
|
||||
props: { open: Boolean },
|
||||
setup(props, { slots }) {
|
||||
return () => (props.open ? h("div", { "data-test-dialog": "" }, slots.default?.()) : null);
|
||||
},
|
||||
}),
|
||||
DialogContent: slotContainer,
|
||||
DialogFooter: slotContainer,
|
||||
DialogHeader: slotContainer,
|
||||
DialogTitle: slotContainer,
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("@/components/ui/select", async () => {
|
||||
const { defineComponent, h } = await import("vue");
|
||||
type SelectRoot = HTMLElement & { selectTestValue?: (value: string) => void };
|
||||
const slotContainer = defineComponent({
|
||||
setup:
|
||||
(_, { attrs, slots }) =>
|
||||
() =>
|
||||
h("div", attrs, slots.default?.()),
|
||||
});
|
||||
return {
|
||||
Select: defineComponent({
|
||||
inheritAttrs: false,
|
||||
props: { modelValue: String, disabled: Boolean },
|
||||
emits: ["update:modelValue", "update:open"],
|
||||
setup(props, { emit, slots }) {
|
||||
const selectValue = (value: string) => {
|
||||
if (!props.disabled) emit("update:modelValue", value);
|
||||
};
|
||||
return () =>
|
||||
h(
|
||||
"div",
|
||||
{
|
||||
"data-test-select-root": "",
|
||||
ref: (element: Element | ComponentPublicInstance | null) => {
|
||||
if (element instanceof HTMLElement) (element as SelectRoot).selectTestValue = selectValue;
|
||||
},
|
||||
},
|
||||
slots.default?.(),
|
||||
);
|
||||
},
|
||||
}),
|
||||
SelectContent: slotContainer,
|
||||
SelectItem: defineComponent({
|
||||
props: { value: String },
|
||||
setup(props, { slots }) {
|
||||
return () => h("button", { type: "button", "data-test-select-value": props.value }, slots.default?.());
|
||||
},
|
||||
}),
|
||||
SelectTrigger: slotContainer,
|
||||
SelectValue: slotContainer,
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("@/components/ui/option-help-panel", async () => {
|
||||
const { defineComponent, h } = await import("vue");
|
||||
return { OptionHelpPanel: defineComponent({ setup: () => () => h("div") }) };
|
||||
});
|
||||
|
||||
vi.mock("@/components/ui/tabs", async () => {
|
||||
const { defineComponent, h } = await import("vue");
|
||||
const slotContainer = defineComponent({
|
||||
setup:
|
||||
(_, { attrs, slots }) =>
|
||||
() =>
|
||||
h("div", attrs, slots.default?.()),
|
||||
});
|
||||
return { Tabs: slotContainer, TabsContent: slotContainer, TabsList: slotContainer, TabsTrigger: slotContainer };
|
||||
});
|
||||
|
||||
vi.mock("@/components/ui/switch", async () => {
|
||||
const { defineComponent, h } = await import("vue");
|
||||
return { Switch: defineComponent({ setup: () => () => h("button", { type: "button" }) }) };
|
||||
});
|
||||
|
||||
vi.mock("@/components/ui/date-time-picker/DateTimePicker.vue", async () => {
|
||||
const { CalendarDateTime } = await import("@internationalized/date");
|
||||
const { defineComponent, h } = await import("vue");
|
||||
return {
|
||||
default: defineComponent({
|
||||
props: { disabled: Boolean },
|
||||
emits: ["update:modelValue"],
|
||||
setup(props, { emit }) {
|
||||
return () =>
|
||||
h(
|
||||
"button",
|
||||
{
|
||||
type: "button",
|
||||
disabled: props.disabled,
|
||||
"data-test-absolute-date": "",
|
||||
onClick: () => emit("update:modelValue", new CalendarDateTime(2030, 1, 2, 3, 4, 5)),
|
||||
},
|
||||
"Set date",
|
||||
);
|
||||
},
|
||||
}),
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("@/components/ui/CustomContextMenu.vue", async () => {
|
||||
const { defineComponent, h } = await import("vue");
|
||||
return {
|
||||
default: defineComponent({
|
||||
setup(_, { slots }) {
|
||||
return () => h("div", slots.default?.({ onContextMenu: () => undefined }));
|
||||
},
|
||||
}),
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("@/components/editor/DangerConfirmDialog.vue", async () => {
|
||||
const { defineComponent, h } = await import("vue");
|
||||
return { default: defineComponent({ setup: () => () => h("div") }) };
|
||||
});
|
||||
|
||||
vi.mock("./RedisValueViewer.vue", async () => {
|
||||
const { defineComponent, h } = await import("vue");
|
||||
return { default: defineComponent({ setup: () => () => h("div") }) };
|
||||
});
|
||||
|
||||
vi.mock("./RedisPubSubPanel.vue", async () => {
|
||||
const { defineComponent, h } = await import("vue");
|
||||
return { default: defineComponent({ setup: () => () => h("div") }) };
|
||||
});
|
||||
|
||||
vi.mock("./RedisSlowlogPanel.vue", async () => {
|
||||
const { defineComponent, h } = await import("vue");
|
||||
return { default: defineComponent({ setup: () => () => h("div") }) };
|
||||
});
|
||||
|
||||
vi.mock("vue-virtual-scroller", async () => {
|
||||
const { defineComponent, h } = await import("vue");
|
||||
return { RecycleScroller: defineComponent({ setup: () => () => h("div") }) };
|
||||
});
|
||||
|
||||
vi.mock("splitpanes", async () => {
|
||||
const { defineComponent, h } = await import("vue");
|
||||
const slotContainer = defineComponent({
|
||||
setup:
|
||||
(_, { attrs, slots }) =>
|
||||
() =>
|
||||
h("div", attrs, slots.default?.()),
|
||||
});
|
||||
return { Splitpanes: slotContainer, Pane: slotContainer };
|
||||
});
|
||||
|
||||
import RedisKeyBrowser from "./RedisKeyBrowser.vue";
|
||||
|
||||
const KEY_NAME = "new-key";
|
||||
const KEY_RAW = "bmV3LWtleQ==";
|
||||
const mountedApps: Array<{ unmount: () => void; host: HTMLElement }> = [];
|
||||
|
||||
type CreateType = "string" | "hash" | "list" | "set" | "zset" | "stream" | "json";
|
||||
type TestSelectRoot = HTMLElement & { selectTestValue?: (value: string) => void };
|
||||
function redisValue(keyRaw = KEY_RAW) {
|
||||
return {
|
||||
key_display: KEY_NAME,
|
||||
key_raw: keyRaw,
|
||||
ttl: 90,
|
||||
redis_type: "string" as const,
|
||||
data: { kind: "string" as const, content: { raw_base64: "dmFsdWU=", encoding: "utf8" as const } },
|
||||
};
|
||||
}
|
||||
|
||||
function redisKeyInfo(keyType = "json") {
|
||||
return { key_display: KEY_NAME, key_raw: KEY_RAW, key_type: keyType, ttl: 90, size: 7, value_preview: "{}" };
|
||||
}
|
||||
|
||||
function resetApiMocks() {
|
||||
vi.clearAllMocks();
|
||||
mocks.redisScanKeysBatch.mockResolvedValue({ cursor: 0, keys: [], total_keys: 0 });
|
||||
mocks.redisGetValue.mockImplementation((_connectionId: string, _db: number, keyRaw: string) => Promise.resolve(redisValue(keyRaw)));
|
||||
mocks.redisSetString.mockResolvedValue(undefined);
|
||||
mocks.redisJsonSet.mockResolvedValue(undefined);
|
||||
mocks.redisHashSet.mockResolvedValue(undefined);
|
||||
mocks.redisListPush.mockResolvedValue(undefined);
|
||||
mocks.redisSetAdd.mockResolvedValue(undefined);
|
||||
mocks.redisZadd.mockResolvedValue(undefined);
|
||||
mocks.redisStreamAdd.mockResolvedValue(undefined);
|
||||
mocks.redisSetTtl.mockResolvedValue(undefined);
|
||||
mocks.redisSetExpireAt.mockResolvedValue(undefined);
|
||||
mocks.redisCheckJsonModule.mockResolvedValue(true);
|
||||
mocks.redisDeleteKey.mockResolvedValue(undefined);
|
||||
mocks.redisDeleteKeys.mockResolvedValue(0);
|
||||
}
|
||||
|
||||
function mountBrowser() {
|
||||
const host = document.createElement("div");
|
||||
document.body.append(host);
|
||||
const app = createApp(RedisKeyBrowser, { connectionId: "connection", db: 0, blockDangerousRedisCommands: false });
|
||||
app.use(createI18n({ legacy: false, locale: "en", messages: { en: {} }, missingWarn: false, fallbackWarn: false }));
|
||||
app.mount(host);
|
||||
mountedApps.push({ unmount: () => app.unmount(), host });
|
||||
}
|
||||
|
||||
async function settle() {
|
||||
await nextTick();
|
||||
await Promise.resolve();
|
||||
await nextTick();
|
||||
await Promise.resolve();
|
||||
await nextTick();
|
||||
}
|
||||
|
||||
function requiredElement<T extends Element>(selector: string): T {
|
||||
const element = document.querySelector<T>(selector);
|
||||
expect(element, selector).not.toBeNull();
|
||||
return element!;
|
||||
}
|
||||
|
||||
function clickButtonWithText(text: string) {
|
||||
const button = Array.from(document.querySelectorAll<HTMLButtonElement>("button")).find((candidate) => candidate.textContent?.includes(text));
|
||||
expect(button, text).toBeDefined();
|
||||
button!.click();
|
||||
}
|
||||
|
||||
async function setInput(selector: string, value: string) {
|
||||
const input = requiredElement<HTMLInputElement>(selector);
|
||||
input.value = value;
|
||||
input.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
await settle();
|
||||
}
|
||||
|
||||
async function select(value: string) {
|
||||
const item = requiredElement<HTMLButtonElement>(`[data-test-select-value="${value}"]`);
|
||||
const root = item.closest<TestSelectRoot>("[data-test-select-root]");
|
||||
expect(root).not.toBeNull();
|
||||
expect(root?.selectTestValue).toEqual(expect.any(Function));
|
||||
root!.selectTestValue!(value);
|
||||
await settle();
|
||||
}
|
||||
|
||||
async function openCreateDialog() {
|
||||
requiredElement<HTMLButtonElement>('button[title="redis.createKey"]').click();
|
||||
await settle();
|
||||
await setInput('input[placeholder="redis.createKeyNamePlaceholder"]', KEY_NAME);
|
||||
}
|
||||
|
||||
async function fillCreateValue(type: CreateType) {
|
||||
if (type === "string") {
|
||||
const textarea = requiredElement<HTMLTextAreaElement>("textarea");
|
||||
textarea.value = "value";
|
||||
textarea.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
await settle();
|
||||
return;
|
||||
}
|
||||
|
||||
await select(type);
|
||||
if (type === "json") {
|
||||
const textarea = requiredElement<HTMLTextAreaElement>("textarea");
|
||||
textarea.value = '{"value":true}';
|
||||
textarea.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
await settle();
|
||||
return;
|
||||
}
|
||||
|
||||
if (type === "hash" || type === "stream") {
|
||||
await setInput('input[placeholder="redis.createFieldPlaceholder"]', "field");
|
||||
await setInput('input[placeholder="redis.createValuePlaceholder"]', "value");
|
||||
return;
|
||||
}
|
||||
|
||||
if (type === "zset") {
|
||||
await setInput('input[placeholder="0"]', "1");
|
||||
await setInput('input[placeholder="redis.createMember"]', "member");
|
||||
return;
|
||||
}
|
||||
|
||||
await setInput('input[placeholder="redis.createValuePlaceholder"]', "value");
|
||||
}
|
||||
|
||||
async function submitCreate() {
|
||||
clickButtonWithText("redis.createKeySubmit");
|
||||
await settle();
|
||||
}
|
||||
|
||||
function expectWriterBefore(mock: { mock: { invocationCallOrder: number[] } }, after: { mock: { invocationCallOrder: number[] } }) {
|
||||
expect(mock.mock.invocationCallOrder).toHaveLength(1);
|
||||
expect(after.mock.invocationCallOrder).toHaveLength(1);
|
||||
expect(mock.mock.invocationCallOrder[0]).toBeLessThan(after.mock.invocationCallOrder[0]!);
|
||||
}
|
||||
|
||||
const writerForType = {
|
||||
string: mocks.redisSetString,
|
||||
hash: mocks.redisHashSet,
|
||||
list: mocks.redisListPush,
|
||||
set: mocks.redisSetAdd,
|
||||
zset: mocks.redisZadd,
|
||||
stream: mocks.redisStreamAdd,
|
||||
json: mocks.redisJsonSet,
|
||||
} as const;
|
||||
|
||||
beforeEach(() => {
|
||||
resetApiMocks();
|
||||
setLocalTimeZone("UTC");
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
for (const { unmount, host } of mountedApps.splice(0)) {
|
||||
unmount();
|
||||
host.remove();
|
||||
}
|
||||
resetLocalTimeZone();
|
||||
});
|
||||
|
||||
describe("RedisKeyBrowser expiry creation", () => {
|
||||
it.each(["string", "hash", "list", "set", "zset", "stream", "json"] as const)("writes %s before applying one relative TTL", async (type) => {
|
||||
mountBrowser();
|
||||
await settle();
|
||||
await openCreateDialog();
|
||||
await fillCreateValue(type);
|
||||
await select("ttl");
|
||||
await setInput('input[placeholder="redis.createKeyTtlPlaceholder"]', "90");
|
||||
|
||||
await submitCreate();
|
||||
|
||||
const writer = writerForType[type];
|
||||
expect(mocks.redisSetTtl).toHaveBeenCalledWith("connection", 0, KEY_RAW, 90);
|
||||
expect(mocks.redisSetExpireAt).not.toHaveBeenCalled();
|
||||
expectWriterBefore(writer, mocks.redisSetTtl);
|
||||
});
|
||||
|
||||
it("uses PERSIST after a String write when no expiry is selected", async () => {
|
||||
mountBrowser();
|
||||
await settle();
|
||||
await openCreateDialog();
|
||||
await fillCreateValue("string");
|
||||
|
||||
await submitCreate();
|
||||
|
||||
expect(mocks.redisSetTtl).toHaveBeenCalledWith("connection", 0, KEY_RAW, -1);
|
||||
expect(mocks.redisSetExpireAt).not.toHaveBeenCalled();
|
||||
expectWriterBefore(mocks.redisSetString, mocks.redisSetTtl);
|
||||
});
|
||||
|
||||
it("uses EXPIREAT after a String write when an absolute time is selected", async () => {
|
||||
mountBrowser();
|
||||
await settle();
|
||||
await openCreateDialog();
|
||||
await fillCreateValue("string");
|
||||
await select("at");
|
||||
requiredElement<HTMLButtonElement>("[data-test-absolute-date]").click();
|
||||
await settle();
|
||||
|
||||
await submitCreate();
|
||||
|
||||
const expected = calendarDateTimeToUnixSeconds(new CalendarDateTime(2030, 1, 2, 3, 4, 5));
|
||||
expect(mocks.redisSetExpireAt).toHaveBeenCalledWith("connection", 0, KEY_RAW, expected);
|
||||
expect(mocks.redisSetTtl).not.toHaveBeenCalled();
|
||||
expectWriterBefore(mocks.redisSetString, mocks.redisSetExpireAt);
|
||||
});
|
||||
|
||||
it("does not roll back a written key when its expiry command fails and refreshes it", async () => {
|
||||
mocks.redisSetTtl.mockRejectedValueOnce(new Error("TTL command failed"));
|
||||
mountBrowser();
|
||||
await settle();
|
||||
await openCreateDialog();
|
||||
await fillCreateValue("string");
|
||||
await select("ttl");
|
||||
await setInput('input[placeholder="redis.createKeyTtlPlaceholder"]', "90");
|
||||
|
||||
await submitCreate();
|
||||
|
||||
expectWriterBefore(mocks.redisSetString, mocks.redisSetTtl);
|
||||
expect(mocks.redisGetValue).toHaveBeenCalledWith("connection", 0, KEY_RAW);
|
||||
expect(mocks.redisDeleteKey).not.toHaveBeenCalled();
|
||||
expect(mocks.redisDeleteKeys).not.toHaveBeenCalled();
|
||||
expect(mocks.toast).toHaveBeenCalledWith("TTL command failed", 5000);
|
||||
});
|
||||
|
||||
it("removes an existing RedisJSON key only after recovery confirms its deletion", async () => {
|
||||
mocks.redisScanKeysBatch.mockResolvedValueOnce({ cursor: 0, keys: [redisKeyInfo()], total_keys: 1 });
|
||||
mocks.redisSetTtl.mockRejectedValueOnce(new Error("TTL command failed"));
|
||||
mocks.redisGetValue.mockRejectedValueOnce(new Error("RedisJSON key no longer exists")).mockRejectedValueOnce(new Error("RedisJSON key no longer exists"));
|
||||
mountBrowser();
|
||||
await settle();
|
||||
await openCreateDialog();
|
||||
await fillCreateValue("json");
|
||||
await select("ttl");
|
||||
await setInput('input[placeholder="redis.createKeyTtlPlaceholder"]', "90");
|
||||
|
||||
await submitCreate();
|
||||
await settle();
|
||||
|
||||
expect(mocks.redisGetValue).toHaveBeenCalledTimes(2);
|
||||
expect(mocks.updateRedisDbKeyStats).toHaveBeenCalledWith("connection", 0, { loaded: 0, totalDelta: -1 });
|
||||
expect(mocks.toast).toHaveBeenCalledWith("TTL command failed", 5000);
|
||||
});
|
||||
|
||||
it("keeps an existing RedisJSON key when retry cannot confirm its deletion", async () => {
|
||||
mocks.redisScanKeysBatch.mockResolvedValueOnce({ cursor: 0, keys: [redisKeyInfo()], total_keys: 1 });
|
||||
mocks.redisSetTtl.mockRejectedValueOnce(new Error("TTL command failed"));
|
||||
mocks.redisGetValue.mockRejectedValueOnce(new Error("RedisJSON key no longer exists")).mockRejectedValueOnce(new Error("network unavailable"));
|
||||
mountBrowser();
|
||||
await settle();
|
||||
await openCreateDialog();
|
||||
await fillCreateValue("json");
|
||||
await select("ttl");
|
||||
await setInput('input[placeholder="redis.createKeyTtlPlaceholder"]', "90");
|
||||
|
||||
await submitCreate();
|
||||
await settle();
|
||||
|
||||
expect(mocks.updateRedisDbKeyStats).not.toHaveBeenCalledWith("connection", 0, { loaded: 0, totalDelta: -1 });
|
||||
expect(mocks.toast).toHaveBeenCalledWith("TTL command failed", 5000);
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,6 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, ref, shallowRef, onMounted, onUnmounted, onActivated, onDeactivated, watch } from "vue";
|
||||
import type { CalendarDateTime } from "@internationalized/date";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import { Search, RefreshCw, Loader2, ChevronRight, ChevronDown, FolderClosed, FolderOpen, Trash2, Plus, KeyRound, TerminalSquare, Asterisk, History, Radio, Clock, Copy } from "@lucide/vue";
|
||||
import { RecycleScroller } from "vue-virtual-scroller";
|
||||
@@ -14,6 +15,7 @@ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@
|
||||
import { OptionHelpPanel } from "@/components/ui/option-help-panel";
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
import DateTimePicker from "@/components/ui/date-time-picker/DateTimePicker.vue";
|
||||
import CustomContextMenu, { type ContextMenuItem } from "@/components/ui/CustomContextMenu.vue";
|
||||
import DangerConfirmDialog from "@/components/editor/DangerConfirmDialog.vue";
|
||||
import RedisValueViewer from "./RedisValueViewer.vue";
|
||||
@@ -37,8 +39,9 @@ import { REDIS_SCAN_PAGE_SIZE_DEFAULT } from "@/lib/redis/redisKeyPattern";
|
||||
import { collectUniqueRedisKeys } from "@/lib/redis/redisKeyBatch";
|
||||
import { getRedisCreateKeyTypeHelp, redisCreateKeyTypeHelpOptionOnOpen, shouldActivateRedisCreateKeyTypeHelpOnFocus } from "@/lib/redis/redisCreateKeyTypeHelp";
|
||||
import { optionHelpPanelOffsetTop } from "@/lib/common/optionHelpPanelOffset";
|
||||
import { applyRedisExpiryPolicy, type RedisExpiryMode, validateRedisExpiry } from "@/lib/redis/redisExpiry";
|
||||
|
||||
const { t } = useI18n();
|
||||
const { t, locale } = useI18n();
|
||||
const { toast } = useToast();
|
||||
const connectionStore = useConnectionStore();
|
||||
const editorFontFamilyStyle = useEditorFontFamilyStyle();
|
||||
@@ -67,6 +70,11 @@ const props = defineProps<{
|
||||
blockDangerousRedisCommands: boolean;
|
||||
}>();
|
||||
|
||||
const redisExpiryTransport = {
|
||||
setTtl: api.redisSetTtl,
|
||||
setExpireAt: api.redisSetExpireAt,
|
||||
};
|
||||
|
||||
const flatKeys = shallowRef<RedisKeyInfo[]>([]);
|
||||
const treeKeys = ref<RedisKeyTreeNode[]>([]);
|
||||
const loading = ref(false);
|
||||
@@ -102,10 +110,13 @@ const createKeyValue = ref("");
|
||||
const createKeyField = ref("");
|
||||
const createKeyScore = ref("0");
|
||||
const createKeyError = ref("");
|
||||
const createKeyExpiryMode = ref<RedisExpiryMode>("none");
|
||||
const createKeyTtl = ref("");
|
||||
const createKeyExpireAt = shallowRef<CalendarDateTime | null>(null);
|
||||
const createKeyEntries = ref<CreateKeyEntry[]>([]);
|
||||
const createKeyRawMode = ref(false);
|
||||
const createKeyEntryId = ref("*");
|
||||
const createKeyPartiallyWritten = ref(false);
|
||||
const jsonModuleAvailable = ref<boolean | null>(null);
|
||||
const checkingJsonModule = ref(false);
|
||||
const activeCreateKeyTypeHelp = ref<RedisCreateKeyType>();
|
||||
@@ -481,11 +492,14 @@ function onRowClick(node: RedisKeyTreeNode) {
|
||||
activeSidePanel.value = "detail";
|
||||
}
|
||||
|
||||
function onKeyDeleted() {
|
||||
if (!selectedKeyRaw.value) return;
|
||||
loadedKeyRaws.delete(selectedKeyRaw.value);
|
||||
flatKeys.value = flatKeys.value.filter((key) => key.key_raw !== selectedKeyRaw.value);
|
||||
selectedKeyRaw.value = null;
|
||||
function removeKnownKey(keyRaw: string) {
|
||||
if (!flatKeys.value.some((key) => key.key_raw === keyRaw)) return;
|
||||
loadedKeyRaws.delete(keyRaw);
|
||||
flatKeys.value = flatKeys.value.filter((key) => key.key_raw !== keyRaw);
|
||||
if (selectedKeyRaw.value === keyRaw) selectedKeyRaw.value = null;
|
||||
const nextChecked = new Set(checkedKeys.value);
|
||||
nextChecked.delete(keyRaw);
|
||||
checkedKeys.value = nextChecked;
|
||||
rebuildTree(false);
|
||||
connectionStore.updateRedisDbKeyStats(props.connectionId, props.db, {
|
||||
loaded: isSearchMode.value ? undefined : flatKeys.value.length,
|
||||
@@ -493,6 +507,10 @@ function onKeyDeleted() {
|
||||
});
|
||||
}
|
||||
|
||||
function onKeyDeleted(keyRaw: string) {
|
||||
removeKnownKey(keyRaw);
|
||||
}
|
||||
|
||||
function redisValueToKeyInfo(value: RedisValue): RedisKeyInfo {
|
||||
return {
|
||||
key_display: value.key_display,
|
||||
@@ -505,6 +523,10 @@ function redisValueToKeyInfo(value: RedisValue): RedisKeyInfo {
|
||||
}
|
||||
|
||||
function onKeyLoaded(value: RedisValue) {
|
||||
if (value.redis_type === "none") {
|
||||
removeKnownKey(value.key_raw);
|
||||
return;
|
||||
}
|
||||
const keyInfo = redisValueToKeyInfo(value);
|
||||
const existingIndex = flatKeys.value.findIndex((key) => key.key_raw === keyInfo.key_raw);
|
||||
if (existingIndex < 0) return;
|
||||
@@ -705,6 +727,10 @@ function removeEntry(idx: number) {
|
||||
}
|
||||
}
|
||||
|
||||
function removeWrittenCreateKeyEntry(entryId: number) {
|
||||
createKeyEntries.value = createKeyEntries.value.filter((entry) => entry.id !== entryId);
|
||||
}
|
||||
|
||||
function resetCreateKeyForm() {
|
||||
createKeyName.value = "";
|
||||
createKeyType.value = "string";
|
||||
@@ -712,9 +738,12 @@ function resetCreateKeyForm() {
|
||||
createKeyField.value = "";
|
||||
createKeyScore.value = "0";
|
||||
createKeyError.value = "";
|
||||
createKeyExpiryMode.value = "none";
|
||||
createKeyTtl.value = "";
|
||||
createKeyExpireAt.value = null;
|
||||
createKeyRawMode.value = false;
|
||||
createKeyEntryId.value = "*";
|
||||
createKeyPartiallyWritten.value = false;
|
||||
jsonModuleAvailable.value = null;
|
||||
checkingJsonModule.value = false;
|
||||
activeCreateKeyTypeHelp.value = undefined;
|
||||
@@ -723,7 +752,14 @@ function resetCreateKeyForm() {
|
||||
resetEntries();
|
||||
}
|
||||
|
||||
function expiryValidationMessage(reason: "ttl" | "date" | "past"): string {
|
||||
if (reason === "ttl") return t("redis.expiryTtlInvalid");
|
||||
if (reason === "date") return t("redis.expiryDateRequired");
|
||||
return t("redis.expiryDatePast");
|
||||
}
|
||||
|
||||
function onCreateKeyTypeChange(type: any) {
|
||||
if (creatingKey.value || createKeyPartiallyWritten.value) return;
|
||||
createKeyType.value = (type || "string") as RedisCreateKeyType;
|
||||
createKeyRawMode.value = false;
|
||||
jsonModuleAvailable.value = null;
|
||||
@@ -760,6 +796,12 @@ function openCreateKeyDialog() {
|
||||
showCreateKeyDialog.value = true;
|
||||
}
|
||||
|
||||
function onCreateKeyDialogOpenChange(open: boolean) {
|
||||
// A create request may have already written a Redis value; keep its recovery state visible.
|
||||
if (!open && creatingKey.value) return;
|
||||
showCreateKeyDialog.value = open;
|
||||
}
|
||||
|
||||
function upsertCreatedKey(value: RedisValue) {
|
||||
const keyInfo: RedisKeyInfo = {
|
||||
key_display: value.key_display,
|
||||
@@ -784,7 +826,42 @@ function upsertCreatedKey(value: RedisValue) {
|
||||
});
|
||||
}
|
||||
|
||||
function errorMessage(error: unknown): string {
|
||||
return error instanceof Error ? error.message : String(error);
|
||||
}
|
||||
|
||||
function isRedisMissingKeyError(error: unknown): boolean {
|
||||
return /^Redis(?:JSON)? key no longer exists(?:;|$)/.test(errorMessage(error));
|
||||
}
|
||||
|
||||
async function syncWrittenKey(keyRaw: string): Promise<boolean> {
|
||||
const created = await api.redisGetValue(props.connectionId, props.db, keyRaw);
|
||||
if (created.redis_type === "none") {
|
||||
removeKnownKey(keyRaw);
|
||||
return false;
|
||||
}
|
||||
upsertCreatedKey(created);
|
||||
return true;
|
||||
}
|
||||
|
||||
async function reflectWrittenKey(keyRaw: string) {
|
||||
try {
|
||||
await syncWrittenKey(keyRaw);
|
||||
} catch (error) {
|
||||
// RedisJSON can lose a key between TYPE and JSON.GET. Confirm the race
|
||||
// before removing a possibly recreated key from the browser.
|
||||
if (!isRedisMissingKeyError(error)) return;
|
||||
try {
|
||||
await syncWrittenKey(keyRaw);
|
||||
} catch (retryError) {
|
||||
if (isRedisMissingKeyError(retryError)) removeKnownKey(keyRaw);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function createRedisKey() {
|
||||
if (creatingKey.value) return;
|
||||
|
||||
const keyName = createKeyName.value.trim();
|
||||
if (!keyName) {
|
||||
createKeyError.value = t("redis.createKeyNameRequired");
|
||||
@@ -792,74 +869,137 @@ async function createRedisKey() {
|
||||
return;
|
||||
}
|
||||
|
||||
const expiryValidation = validateRedisExpiry(createKeyExpiryMode.value, createKeyTtl.value, createKeyExpireAt.value);
|
||||
if (!expiryValidation.valid) {
|
||||
const message = expiryValidationMessage(expiryValidation.reason);
|
||||
createKeyError.value = message;
|
||||
toast(message, 3000);
|
||||
return;
|
||||
}
|
||||
|
||||
const keyType = createKeyType.value;
|
||||
const rawMode = createKeyRawMode.value;
|
||||
creatingKey.value = true;
|
||||
createKeyError.value = "";
|
||||
let wroteValue = false;
|
||||
let writtenKeyRaw: string | null = null;
|
||||
let writingStructuredEntries = false;
|
||||
try {
|
||||
const keyRaw = redisKeyTextToRaw(keyName);
|
||||
const ttl = createKeyTtl.value ? Number.parseInt(createKeyTtl.value) || undefined : undefined;
|
||||
writtenKeyRaw = keyRaw;
|
||||
const expiry = expiryValidation.policy;
|
||||
|
||||
if (createKeyType.value === "string" || createKeyType.value === "json" || createKeyRawMode.value) {
|
||||
if (keyType === "string" || keyType === "json" || rawMode) {
|
||||
// Raw text/JSON mode — single value
|
||||
if (createKeyType.value === "string") {
|
||||
await api.redisSetString(props.connectionId, props.db, keyRaw, createKeyValue.value, ttl ?? -1);
|
||||
} else if (createKeyType.value === "json") {
|
||||
await api.redisJsonSet(props.connectionId, props.db, keyRaw, createKeyValue.value, ttl);
|
||||
} else if (createKeyType.value === "hash") {
|
||||
await api.redisHashSet(props.connectionId, props.db, keyRaw, createKeyField.value, createKeyValue.value, ttl);
|
||||
} else if (createKeyType.value === "list") {
|
||||
await api.redisListPush(props.connectionId, props.db, keyRaw, createKeyValue.value, ttl);
|
||||
} else if (createKeyType.value === "set") {
|
||||
await api.redisSetAdd(props.connectionId, props.db, keyRaw, createKeyValue.value, ttl);
|
||||
} else if (createKeyType.value === "zset") {
|
||||
if (keyType === "string") {
|
||||
await api.redisSetString(props.connectionId, props.db, keyRaw, createKeyValue.value);
|
||||
wroteValue = true;
|
||||
} else if (keyType === "json") {
|
||||
await api.redisJsonSet(props.connectionId, props.db, keyRaw, createKeyValue.value);
|
||||
wroteValue = true;
|
||||
} else if (keyType === "hash") {
|
||||
await api.redisHashSet(props.connectionId, props.db, keyRaw, createKeyField.value, createKeyValue.value);
|
||||
wroteValue = true;
|
||||
} else if (keyType === "list") {
|
||||
await api.redisListPush(props.connectionId, props.db, keyRaw, createKeyValue.value);
|
||||
wroteValue = true;
|
||||
} else if (keyType === "set") {
|
||||
await api.redisSetAdd(props.connectionId, props.db, keyRaw, createKeyValue.value);
|
||||
wroteValue = true;
|
||||
} else if (keyType === "zset") {
|
||||
const score = Number.parseFloat(createKeyScore.value || "0");
|
||||
await api.redisZadd(props.connectionId, props.db, keyRaw, createKeyValue.value, score, ttl);
|
||||
await api.redisZadd(props.connectionId, props.db, keyRaw, createKeyValue.value, score);
|
||||
wroteValue = true;
|
||||
}
|
||||
} else {
|
||||
// Structured entries mode — insert each entry, then set TTL once
|
||||
if (createKeyType.value === "hash") {
|
||||
for (const entry of createKeyEntries.value) {
|
||||
// Write every member first so a single policy is applied to every key type.
|
||||
writingStructuredEntries = true;
|
||||
const pendingEntries = createKeyEntries.value.slice();
|
||||
if (keyType === "hash") {
|
||||
for (const entry of pendingEntries) {
|
||||
if (entry.field && entry.field.trim()) {
|
||||
await api.redisHashSet(props.connectionId, props.db, keyRaw, entry.field, entry.value);
|
||||
wroteValue = true;
|
||||
createKeyPartiallyWritten.value = true;
|
||||
removeWrittenCreateKeyEntry(entry.id);
|
||||
}
|
||||
}
|
||||
} else if (createKeyType.value === "list") {
|
||||
for (const entry of createKeyEntries.value) {
|
||||
} else if (keyType === "list") {
|
||||
for (const entry of pendingEntries) {
|
||||
if (entry.value) {
|
||||
await api.redisListPush(props.connectionId, props.db, keyRaw, entry.value);
|
||||
wroteValue = true;
|
||||
createKeyPartiallyWritten.value = true;
|
||||
removeWrittenCreateKeyEntry(entry.id);
|
||||
}
|
||||
}
|
||||
} else if (createKeyType.value === "set") {
|
||||
for (const entry of createKeyEntries.value) {
|
||||
} else if (keyType === "set") {
|
||||
for (const entry of pendingEntries) {
|
||||
if (entry.value) {
|
||||
await api.redisSetAdd(props.connectionId, props.db, keyRaw, entry.value);
|
||||
wroteValue = true;
|
||||
createKeyPartiallyWritten.value = true;
|
||||
removeWrittenCreateKeyEntry(entry.id);
|
||||
}
|
||||
}
|
||||
} else if (createKeyType.value === "zset") {
|
||||
for (const entry of createKeyEntries.value) {
|
||||
} else if (keyType === "zset") {
|
||||
for (const entry of pendingEntries) {
|
||||
if (entry.value) {
|
||||
const s = Number.parseFloat(entry.score || "0");
|
||||
if (!Number.isNaN(s)) {
|
||||
await api.redisZadd(props.connectionId, props.db, keyRaw, entry.value, s);
|
||||
wroteValue = true;
|
||||
createKeyPartiallyWritten.value = true;
|
||||
removeWrittenCreateKeyEntry(entry.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if (createKeyType.value === "stream") {
|
||||
const fields: [string, string][] = createKeyEntries.value.filter((e) => e.field && e.field.trim()).map((e) => [e.field!.trim(), e.value]);
|
||||
} else if (keyType === "stream") {
|
||||
const fields: [string, string][] = pendingEntries.filter((e) => e.field && e.field.trim()).map((e) => [e.field!.trim(), e.value]);
|
||||
if (fields.length > 0) {
|
||||
const entryId = createKeyEntryId.value.trim() || "*";
|
||||
await api.redisStreamAdd(props.connectionId, props.db, keyRaw, entryId, fields, ttl);
|
||||
await api.redisStreamAdd(props.connectionId, props.db, keyRaw, entryId, fields);
|
||||
wroteValue = true;
|
||||
}
|
||||
}
|
||||
if (ttl) {
|
||||
await api.redisSetTtl(props.connectionId, props.db, keyRaw, ttl);
|
||||
}
|
||||
writingStructuredEntries = false;
|
||||
}
|
||||
|
||||
const created = await api.redisGetValue(props.connectionId, props.db, keyRaw);
|
||||
upsertCreatedKey(created);
|
||||
if (!wroteValue) {
|
||||
const message = keyType === "hash" || keyType === "stream" ? t("redis.fieldRequired") : t("redis.valueRequired");
|
||||
createKeyError.value = message;
|
||||
toast(message, 3000);
|
||||
return;
|
||||
}
|
||||
|
||||
// Do not roll back a successful write if this separate policy command fails.
|
||||
await applyRedisExpiryPolicy(redisExpiryTransport, props.connectionId, props.db, keyRaw, expiry);
|
||||
|
||||
if (!(await syncWrittenKey(keyRaw))) {
|
||||
showCreateKeyDialog.value = false;
|
||||
toast(t("redis.keyExpiredBeforeDisplay"), 3000);
|
||||
return;
|
||||
}
|
||||
showCreateKeyDialog.value = false;
|
||||
} catch (error) {
|
||||
createKeyError.value = error instanceof Error ? error.message : String(error);
|
||||
const message = errorMessage(error);
|
||||
if (writingStructuredEntries) {
|
||||
if (wroteValue && writtenKeyRaw) {
|
||||
await reflectWrittenKey(writtenKeyRaw);
|
||||
createKeyError.value = `${message} ${t("redis.createKeyPartialWrite")}`;
|
||||
toast(message, 5000);
|
||||
} else {
|
||||
createKeyError.value = message;
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (wroteValue && writtenKeyRaw) {
|
||||
await reflectWrittenKey(writtenKeyRaw);
|
||||
showCreateKeyDialog.value = false;
|
||||
toast(message, 5000);
|
||||
return;
|
||||
}
|
||||
createKeyError.value = message;
|
||||
} finally {
|
||||
creatingKey.value = false;
|
||||
}
|
||||
@@ -1371,8 +1511,8 @@ defineExpose({ focusSearch, insertCommand, executeCommand: executeAiCommand });
|
||||
|
||||
<DangerConfirmDialog v-model:open="showDangerConfirm" :message="dangerMessage" :details="dangerDetails" :confirm-label="dangerConfirmLabel" @confirm="applyDangerAction" />
|
||||
|
||||
<Dialog v-model:open="showCreateKeyDialog">
|
||||
<DialogContent class="sm:max-w-md" :style="editorFontFamilyStyle">
|
||||
<Dialog :open="showCreateKeyDialog" @update:open="onCreateKeyDialogOpenChange">
|
||||
<DialogContent class="sm:max-w-md" :show-close-button="!creatingKey" :style="editorFontFamilyStyle">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{{ t("redis.createKey") }}</DialogTitle>
|
||||
</DialogHeader>
|
||||
@@ -1380,12 +1520,12 @@ defineExpose({ focusSearch, insertCommand, executeCommand: executeAiCommand });
|
||||
<div class="grid gap-3">
|
||||
<label class="grid gap-1.5 text-xs font-medium">
|
||||
<span>{{ t("redis.createKeyName") }}</span>
|
||||
<Input v-model="createKeyName" class="dbx-editor-font-family h-8 text-xs" :placeholder="t('redis.createKeyNamePlaceholder')" @keydown.enter="createRedisKey" />
|
||||
<Input v-model="createKeyName" class="dbx-editor-font-family h-8 text-xs" :disabled="creatingKey || createKeyPartiallyWritten" :placeholder="t('redis.createKeyNamePlaceholder')" @keydown.enter="createRedisKey" />
|
||||
</label>
|
||||
|
||||
<label class="grid gap-1.5 text-xs font-medium">
|
||||
<span>{{ t("redis.createKeyType") }}</span>
|
||||
<Select :model-value="createKeyType" @update:open="onCreateKeyTypeSelectOpen" @update:model-value="onCreateKeyTypeChange">
|
||||
<Select :model-value="createKeyType" :disabled="creatingKey || createKeyPartiallyWritten" @update:open="onCreateKeyTypeSelectOpen" @update:model-value="onCreateKeyTypeChange">
|
||||
<SelectTrigger class="h-8 text-xs" @keydown.capture="onCreateKeyTypeTriggerKeydown">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
@@ -1404,25 +1544,41 @@ defineExpose({ focusSearch, insertCommand, executeCommand: executeAiCommand });
|
||||
|
||||
<label v-if="createKeyType === 'hash' && createKeyRawMode" class="grid gap-1.5 text-xs font-medium">
|
||||
<span>{{ t("redis.createField") }}</span>
|
||||
<Input v-model="createKeyField" class="dbx-editor-font-family h-8 text-xs" :placeholder="t('redis.createFieldPlaceholder')" @keydown.enter="createRedisKey" />
|
||||
<Input v-model="createKeyField" class="dbx-editor-font-family h-8 text-xs" :disabled="creatingKey" :placeholder="t('redis.createFieldPlaceholder')" @keydown.enter="createRedisKey" />
|
||||
</label>
|
||||
|
||||
<label v-if="createKeyType === 'zset' && createKeyRawMode" class="grid gap-1.5 text-xs font-medium">
|
||||
<span>{{ t("redis.createScore") }}</span>
|
||||
<Input v-model="createKeyScore" class="dbx-editor-font-family h-8 text-xs" placeholder="0" @keydown.enter="createRedisKey" />
|
||||
<Input v-model="createKeyScore" class="dbx-editor-font-family h-8 text-xs" :disabled="creatingKey" placeholder="0" @keydown.enter="createRedisKey" />
|
||||
</label>
|
||||
|
||||
<!-- TTL input -- always visible -->
|
||||
<label class="grid gap-1.5 text-xs font-medium">
|
||||
<span>{{ t("redis.createKeyTtl") }}</span>
|
||||
<Input v-model="createKeyTtl" class="dbx-editor-font-family h-8 text-xs" type="number" min="0" :placeholder="t('redis.createKeyTtlPlaceholder')" @keydown.enter="createRedisKey" />
|
||||
</label>
|
||||
<div class="grid gap-1.5 text-xs font-medium">
|
||||
<span>{{ t("redis.expiry") }}</span>
|
||||
<Select v-model="createKeyExpiryMode" :disabled="creatingKey">
|
||||
<SelectTrigger class="h-8 text-xs">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="none">{{ t("redis.expiryNone") }}</SelectItem>
|
||||
<SelectItem value="ttl">{{ t("redis.expiryTtl") }}</SelectItem>
|
||||
<SelectItem value="at">{{ t("redis.expiryAt") }}</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<label v-if="createKeyExpiryMode === 'ttl'" class="grid gap-1.5 text-xs font-medium">
|
||||
<span>{{ t("redis.createKeyTtl") }}</span>
|
||||
<Input v-model="createKeyTtl" class="dbx-editor-font-family h-8 text-xs" :disabled="creatingKey" inputmode="numeric" :placeholder="t('redis.createKeyTtlPlaceholder')" @keydown.enter="createRedisKey" />
|
||||
</label>
|
||||
<label v-else-if="createKeyExpiryMode === 'at'" class="grid gap-1.5 text-xs font-medium">
|
||||
<span>{{ t("redis.expiryAt") }}</span>
|
||||
<DateTimePicker v-model="createKeyExpireAt" full-width :locale="locale" :disabled="creatingKey" />
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<!-- Raw mode toggle (non-string, non-stream, non-json types) -->
|
||||
<div v-if="createKeyType !== 'string' && createKeyType !== 'stream' && createKeyType !== 'json'" class="flex items-center justify-end gap-1.5">
|
||||
<label class="flex items-center gap-1.5 text-xs text-muted-foreground">
|
||||
<span>{{ t("redis.createKeyRawMode") }}</span>
|
||||
<Switch size="sm" v-model="createKeyRawMode" />
|
||||
<Switch size="sm" v-model="createKeyRawMode" :disabled="creatingKey || createKeyPartiallyWritten" />
|
||||
</label>
|
||||
</div>
|
||||
|
||||
@@ -1431,13 +1587,13 @@ defineExpose({ focusSearch, insertCommand, executeCommand: executeAiCommand });
|
||||
<!-- Stream entry ID -->
|
||||
<label v-if="createKeyType === 'stream'" class="grid gap-1.5 text-xs font-medium">
|
||||
<span>{{ t("redis.createKeyEntryId") }}</span>
|
||||
<Input v-model="createKeyEntryId" class="dbx-editor-font-family h-8 text-xs font-mono" placeholder="*" />
|
||||
<Input v-model="createKeyEntryId" class="dbx-editor-font-family h-8 text-xs font-mono" :disabled="creatingKey" placeholder="*" />
|
||||
</label>
|
||||
|
||||
<div class="grid gap-2">
|
||||
<div class="flex items-center justify-between">
|
||||
<span class="text-xs font-medium">{{ t("redis.createKeyEntries") }}</span>
|
||||
<Button variant="outline" size="sm" class="h-6 gap-1 text-xs" @click="addEntry">
|
||||
<Button variant="outline" size="sm" class="h-6 gap-1 text-xs" :disabled="creatingKey" @click="addEntry">
|
||||
<Plus class="h-3 w-3" />
|
||||
{{ t("redis.createKeyAddEntry") }}
|
||||
</Button>
|
||||
@@ -1445,19 +1601,19 @@ defineExpose({ focusSearch, insertCommand, executeCommand: executeAiCommand });
|
||||
<div v-for="(entry, idx) in createKeyEntries" :key="entry.id" class="flex items-start gap-2">
|
||||
<!-- Hash / Stream: field + value -->
|
||||
<template v-if="createKeyType === 'hash' || createKeyType === 'stream'">
|
||||
<Input v-model="entry.field" class="dbx-editor-font-family h-8 w-2/5 text-xs" :placeholder="t('redis.createFieldPlaceholder')" />
|
||||
<Input v-model="entry.value" class="dbx-editor-font-family h-8 flex-1 text-xs" :placeholder="t('redis.createValuePlaceholder')" />
|
||||
<Input v-model="entry.field" class="dbx-editor-font-family h-8 w-2/5 text-xs" :disabled="creatingKey" :placeholder="t('redis.createFieldPlaceholder')" />
|
||||
<Input v-model="entry.value" class="dbx-editor-font-family h-8 flex-1 text-xs" :disabled="creatingKey" :placeholder="t('redis.createValuePlaceholder')" />
|
||||
</template>
|
||||
<!-- ZSet: score + member -->
|
||||
<template v-else-if="createKeyType === 'zset'">
|
||||
<Input v-model="entry.score" class="dbx-editor-font-family h-8 w-20 text-xs" type="number" step="any" placeholder="0" />
|
||||
<Input v-model="entry.value" class="dbx-editor-font-family h-8 flex-1 text-xs" :placeholder="t('redis.createMember')" />
|
||||
<Input v-model="entry.score" class="dbx-editor-font-family h-8 w-20 text-xs" :disabled="creatingKey" type="number" step="any" placeholder="0" />
|
||||
<Input v-model="entry.value" class="dbx-editor-font-family h-8 flex-1 text-xs" :disabled="creatingKey" :placeholder="t('redis.createMember')" />
|
||||
</template>
|
||||
<!-- List / Set: single value -->
|
||||
<template v-else>
|
||||
<Input v-model="entry.value" class="dbx-editor-font-family h-8 flex-1 text-xs" :placeholder="t('redis.createValuePlaceholder')" />
|
||||
<Input v-model="entry.value" class="dbx-editor-font-family h-8 flex-1 text-xs" :disabled="creatingKey" :placeholder="t('redis.createValuePlaceholder')" />
|
||||
</template>
|
||||
<Button variant="ghost" size="sm" class="h-8 w-8 shrink-0 p-0 text-muted-foreground hover:text-destructive" :disabled="createKeyEntries.length <= 1" @click="removeEntry(idx)">
|
||||
<Button variant="ghost" size="sm" class="h-8 w-8 shrink-0 p-0 text-muted-foreground hover:text-destructive" :disabled="creatingKey || createKeyEntries.length <= 1" @click="removeEntry(idx)">
|
||||
<Trash2 class="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
@@ -1467,7 +1623,7 @@ defineExpose({ focusSearch, insertCommand, executeCommand: executeAiCommand });
|
||||
<!-- Raw value textarea (string, json, or raw mode for other types) -->
|
||||
<label v-if="createKeyType === 'string' || createKeyType === 'json' || createKeyRawMode" class="grid gap-1.5 text-xs font-medium">
|
||||
<span>{{ t(createKeyType === "set" || createKeyType === "zset" ? "redis.createMember" : "redis.createValue") }}</span>
|
||||
<textarea v-model="createKeyValue" class="dbx-editor-font-family min-h-28 resize-y rounded-md border bg-background p-2 text-xs outline-none focus-visible:ring-1 focus-visible:ring-ring" spellcheck="false" :placeholder="t('redis.createValuePlaceholder')" />
|
||||
<textarea v-model="createKeyValue" class="dbx-editor-font-family min-h-28 resize-y rounded-md border bg-background p-2 text-xs outline-none focus-visible:ring-1 focus-visible:ring-ring" :disabled="creatingKey" spellcheck="false" :placeholder="t('redis.createValuePlaceholder')" />
|
||||
</label>
|
||||
|
||||
<p v-if="createKeyError" class="text-xs text-destructive">{{ createKeyError }}</p>
|
||||
|
||||
@@ -0,0 +1,311 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import { createApp, defineComponent, h, nextTick } from "vue";
|
||||
import { createI18n } from "vue-i18n";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { calendarDateTimeToUnixSeconds, parseLocalDateTime } from "@/components/ui/date-time-picker/dateTimePicker";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
redisGetValue: vi.fn(),
|
||||
redisSetTtl: vi.fn(),
|
||||
redisSetExpireAt: vi.fn(),
|
||||
toast: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/backend/api", () => ({
|
||||
redisGetValue: mocks.redisGetValue,
|
||||
redisSetTtl: mocks.redisSetTtl,
|
||||
redisSetExpireAt: mocks.redisSetExpireAt,
|
||||
}));
|
||||
|
||||
vi.mock("@/composables/useEditorFontFamilyStyle", () => ({
|
||||
useEditorFontFamilyStyle: () => ({}),
|
||||
}));
|
||||
|
||||
vi.mock("@/composables/useToast", () => ({
|
||||
useToast: () => ({ toast: mocks.toast }),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/common/shikiJsonHighlighter", () => ({
|
||||
createShikiJsonHighlighter: vi.fn().mockResolvedValue(() => ""),
|
||||
}));
|
||||
|
||||
import RedisValueViewer from "./RedisValueViewer.vue";
|
||||
|
||||
const mountedApps: Array<{ unmount: () => void; host: HTMLElement }> = [];
|
||||
|
||||
afterEach(() => {
|
||||
for (const { unmount, host } of mountedApps.splice(0)) {
|
||||
unmount();
|
||||
host.remove();
|
||||
}
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
async function settle() {
|
||||
await nextTick();
|
||||
await Promise.resolve();
|
||||
await nextTick();
|
||||
await Promise.resolve();
|
||||
await nextTick();
|
||||
}
|
||||
|
||||
function stringValue(rawBase64 = "dmFsdWU=", ttl = 60) {
|
||||
return {
|
||||
key_display: "key",
|
||||
key_raw: "key",
|
||||
ttl,
|
||||
redis_type: "string",
|
||||
data: { kind: "string" as const, content: { raw_base64: rawBase64, encoding: "utf8" as const } },
|
||||
};
|
||||
}
|
||||
|
||||
function missingValue() {
|
||||
return {
|
||||
key_display: "key",
|
||||
key_raw: "key",
|
||||
ttl: -2,
|
||||
redis_type: "none",
|
||||
data: { kind: "unknown" as const },
|
||||
};
|
||||
}
|
||||
|
||||
function deferred<T>() {
|
||||
let resolve!: (value: T | PromiseLike<T>) => void;
|
||||
const promise = new Promise<T>((resolvePromise) => {
|
||||
resolve = resolvePromise;
|
||||
});
|
||||
return { promise, resolve };
|
||||
}
|
||||
|
||||
function mountViewer(onDeleted: (keyRaw: string) => void) {
|
||||
const host = document.createElement("div");
|
||||
document.body.append(host);
|
||||
const app = createApp(
|
||||
defineComponent({
|
||||
setup() {
|
||||
return () =>
|
||||
h(RedisValueViewer, {
|
||||
connectionId: "connection",
|
||||
db: 0,
|
||||
keyDisplay: "key",
|
||||
keyRaw: "key",
|
||||
onDeleted,
|
||||
});
|
||||
},
|
||||
}),
|
||||
);
|
||||
app.use(createI18n({ legacy: false, locale: "en", messages: { en: {} }, missingWarn: false, fallbackWarn: false }));
|
||||
app.mount(host);
|
||||
mountedApps.push({ unmount: () => app.unmount(), host });
|
||||
}
|
||||
|
||||
async function saveTtlFromEditor() {
|
||||
await openTtlEditor();
|
||||
await saveOpenTtlEditor();
|
||||
}
|
||||
|
||||
async function openTtlEditor() {
|
||||
document.querySelector<HTMLButtonElement>("[data-slot='badge'][aria-label='redis.expiry']")!.click();
|
||||
await settle();
|
||||
}
|
||||
|
||||
async function saveOpenTtlEditor() {
|
||||
document.querySelector<HTMLButtonElement>("[data-slot='button'][aria-label='grid.save']")!.click();
|
||||
await settle();
|
||||
}
|
||||
|
||||
async function selectExpiryMode(mode: "none" | "at") {
|
||||
const trigger = document.querySelector<HTMLButtonElement>("[data-slot='select-trigger'][aria-label='redis.expiry']")!;
|
||||
trigger.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowDown", bubbles: true, cancelable: true }));
|
||||
await settle();
|
||||
|
||||
const index = mode === "none" ? 0 : 2;
|
||||
const option = document.querySelectorAll<HTMLElement>("[data-redis-expiry-mode-content] [role='option']")[index]!;
|
||||
option.focus();
|
||||
option.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true }));
|
||||
await settle();
|
||||
}
|
||||
|
||||
async function setAbsoluteExpiry(value: string) {
|
||||
document.querySelector<HTMLButtonElement>("[data-date-time-picker-trigger]")!.click();
|
||||
await settle();
|
||||
|
||||
const input = document.querySelector<HTMLInputElement>("[data-date-time-picker-content] [data-date-time-picker-input]")!;
|
||||
input.value = value;
|
||||
input.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
await settle();
|
||||
|
||||
Array.from(document.querySelectorAll<HTMLButtonElement>("[data-date-time-picker-content] button"))
|
||||
.find((button) => button.textContent?.trim() === "Apply")!
|
||||
.click();
|
||||
await settle();
|
||||
}
|
||||
|
||||
async function setStringDraft(value: string) {
|
||||
const textarea = document.querySelector<HTMLTextAreaElement>("textarea")!;
|
||||
textarea.value = value;
|
||||
textarea.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
await settle();
|
||||
}
|
||||
|
||||
describe("RedisValueViewer expiry saving", () => {
|
||||
it("removes a key that disappears while a TTL save fails", async () => {
|
||||
mocks.redisGetValue.mockResolvedValueOnce(stringValue()).mockResolvedValueOnce(missingValue());
|
||||
mocks.redisSetTtl.mockRejectedValueOnce(new Error("Redis key no longer exists; EXPIRE was not applied"));
|
||||
const deleted = vi.fn();
|
||||
|
||||
mountViewer(deleted);
|
||||
await settle();
|
||||
|
||||
await saveTtlFromEditor();
|
||||
|
||||
expect(mocks.redisSetTtl).toHaveBeenCalledWith("connection", 0, "key", 60);
|
||||
expect(mocks.redisGetValue).toHaveBeenCalledTimes(2);
|
||||
expect(deleted).toHaveBeenCalledWith("key");
|
||||
expect(mocks.toast).toHaveBeenCalledWith("Redis key no longer exists; EXPIRE was not applied", 3000);
|
||||
});
|
||||
|
||||
it("keeps an unsaved value draft when a TTL save has an unrelated error", async () => {
|
||||
mocks.redisGetValue.mockResolvedValueOnce(stringValue()).mockResolvedValueOnce(stringValue("c2VydmVy"));
|
||||
mocks.redisSetTtl.mockRejectedValueOnce(new Error("NOPERM this user has no permissions to run the 'expire' command"));
|
||||
const deleted = vi.fn();
|
||||
|
||||
mountViewer(deleted);
|
||||
await settle();
|
||||
|
||||
await setStringDraft("draft");
|
||||
await saveTtlFromEditor();
|
||||
|
||||
expect(mocks.redisGetValue).toHaveBeenCalledTimes(2);
|
||||
expect(document.querySelector<HTMLTextAreaElement>("textarea")?.value).toBe("draft");
|
||||
expect(deleted).not.toHaveBeenCalled();
|
||||
expect(mocks.toast).toHaveBeenCalledWith("NOPERM this user has no permissions to run the 'expire' command", 3000);
|
||||
});
|
||||
|
||||
it("still removes a deleted key when another value draft is unsaved", async () => {
|
||||
mocks.redisGetValue.mockResolvedValueOnce(stringValue()).mockResolvedValueOnce(missingValue());
|
||||
mocks.redisSetTtl.mockRejectedValueOnce(new Error("Redis key no longer exists; EXPIRE was not applied"));
|
||||
const deleted = vi.fn();
|
||||
|
||||
mountViewer(deleted);
|
||||
await settle();
|
||||
await setStringDraft("draft");
|
||||
await saveTtlFromEditor();
|
||||
|
||||
expect(mocks.redisGetValue).toHaveBeenCalledTimes(2);
|
||||
expect(deleted).toHaveBeenCalledWith("key");
|
||||
});
|
||||
|
||||
it("keeps an unsaved value draft after a successful TTL save", async () => {
|
||||
mocks.redisGetValue.mockResolvedValueOnce(stringValue()).mockResolvedValueOnce(stringValue("c2VydmVy", 42));
|
||||
mocks.redisSetTtl.mockResolvedValueOnce(undefined);
|
||||
|
||||
mountViewer(vi.fn());
|
||||
await settle();
|
||||
await setStringDraft("draft");
|
||||
await saveTtlFromEditor();
|
||||
|
||||
expect(document.querySelector<HTMLTextAreaElement>("textarea")?.value).toBe("draft");
|
||||
expect(document.querySelector<HTMLElement>("[data-slot='badge'][aria-label='redis.expiry']")?.textContent).toContain("00:00:42");
|
||||
});
|
||||
|
||||
it("removes a key that disappears while refreshing after a successful TTL save", async () => {
|
||||
mocks.redisGetValue.mockResolvedValueOnce(stringValue()).mockRejectedValueOnce(new Error("RedisJSON key no longer exists")).mockResolvedValueOnce(missingValue());
|
||||
mocks.redisSetTtl.mockResolvedValueOnce(undefined);
|
||||
const deleted = vi.fn();
|
||||
|
||||
mountViewer(deleted);
|
||||
await settle();
|
||||
await saveTtlFromEditor();
|
||||
|
||||
expect(mocks.redisGetValue).toHaveBeenCalledTimes(3);
|
||||
expect(deleted).toHaveBeenCalledWith("key");
|
||||
expect(mocks.toast).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("removes a key when two refresh reads confirm a RedisJSON deletion", async () => {
|
||||
mocks.redisGetValue.mockResolvedValueOnce(stringValue()).mockRejectedValueOnce(new Error("RedisJSON key no longer exists")).mockRejectedValueOnce(new Error("RedisJSON key no longer exists"));
|
||||
mocks.redisSetTtl.mockResolvedValueOnce(undefined);
|
||||
const deleted = vi.fn();
|
||||
|
||||
mountViewer(deleted);
|
||||
await settle();
|
||||
await saveTtlFromEditor();
|
||||
|
||||
expect(mocks.redisGetValue).toHaveBeenCalledTimes(3);
|
||||
expect(deleted).toHaveBeenCalledOnce();
|
||||
expect(deleted).toHaveBeenCalledWith("key");
|
||||
expect(mocks.toast).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not remove a key from an old expiry error when refresh cannot confirm its state", async () => {
|
||||
mocks.redisGetValue.mockResolvedValueOnce(stringValue()).mockRejectedValueOnce(new Error("network unavailable")).mockRejectedValueOnce(new Error("network unavailable"));
|
||||
mocks.redisSetTtl.mockRejectedValueOnce(new Error("Redis key no longer exists; EXPIRE was not applied"));
|
||||
const deleted = vi.fn();
|
||||
|
||||
mountViewer(deleted);
|
||||
await settle();
|
||||
await saveTtlFromEditor();
|
||||
|
||||
expect(mocks.redisGetValue).toHaveBeenCalledTimes(3);
|
||||
expect(deleted).not.toHaveBeenCalled();
|
||||
expect(mocks.toast).toHaveBeenCalledWith("Redis key no longer exists; EXPIRE was not applied", 3000);
|
||||
});
|
||||
|
||||
it("persists a key when the editor is switched to no expiry", async () => {
|
||||
mocks.redisGetValue.mockResolvedValueOnce(stringValue()).mockResolvedValueOnce(stringValue("dmFsdWU=", -1));
|
||||
mocks.redisSetTtl.mockResolvedValueOnce(undefined);
|
||||
|
||||
mountViewer(vi.fn());
|
||||
await settle();
|
||||
await openTtlEditor();
|
||||
await selectExpiryMode("none");
|
||||
await saveOpenTtlEditor();
|
||||
|
||||
expect(mocks.redisSetTtl).toHaveBeenCalledOnce();
|
||||
expect(mocks.redisSetTtl).toHaveBeenCalledWith("connection", 0, "key", -1);
|
||||
expect(mocks.redisSetExpireAt).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("uses EXPIREAT with the selected local date and time", async () => {
|
||||
const localDateTime = "2099-02-03 04:05:06";
|
||||
mocks.redisGetValue.mockResolvedValueOnce(stringValue()).mockResolvedValueOnce(stringValue("dmFsdWU=", 60));
|
||||
mocks.redisSetExpireAt.mockResolvedValueOnce(undefined);
|
||||
|
||||
mountViewer(vi.fn());
|
||||
await settle();
|
||||
await openTtlEditor();
|
||||
await selectExpiryMode("at");
|
||||
await setAbsoluteExpiry(localDateTime);
|
||||
await saveOpenTtlEditor();
|
||||
|
||||
expect(mocks.redisSetExpireAt).toHaveBeenCalledOnce();
|
||||
expect(mocks.redisSetExpireAt).toHaveBeenCalledWith("connection", 0, "key", calendarDateTimeToUnixSeconds(parseLocalDateTime(localDateTime)!));
|
||||
expect(mocks.redisSetTtl).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not submit a second expiry policy while the first is pending", async () => {
|
||||
const pending = deferred<void>();
|
||||
mocks.redisGetValue.mockResolvedValueOnce(stringValue()).mockResolvedValueOnce(stringValue());
|
||||
mocks.redisSetTtl.mockImplementationOnce(() => pending.promise);
|
||||
|
||||
mountViewer(vi.fn());
|
||||
await settle();
|
||||
document.querySelector<HTMLButtonElement>("[data-slot='badge'][aria-label='redis.expiry']")!.click();
|
||||
await settle();
|
||||
|
||||
const save = document.querySelector<HTMLButtonElement>("[data-slot='button'][aria-label='grid.save']")!;
|
||||
save.click();
|
||||
await nextTick();
|
||||
expect(save.disabled).toBe(true);
|
||||
save.dispatchEvent(new MouseEvent("click", { bubbles: true }));
|
||||
expect(mocks.redisSetTtl).toHaveBeenCalledOnce();
|
||||
|
||||
pending.resolve();
|
||||
await settle();
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,6 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, ref, nextTick, onBeforeUnmount, onMounted, watch } from "vue";
|
||||
import { computed, ref, shallowRef, nextTick, onBeforeUnmount, onMounted, watch } from "vue";
|
||||
import type { CalendarDateTime } from "@internationalized/date";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import { onClickOutside } from "@vueuse/core";
|
||||
import { DynamicScroller, DynamicScrollerItem, RecycleScroller } from "vue-virtual-scroller";
|
||||
@@ -8,7 +9,9 @@ import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
import DateTimePicker from "@/components/ui/date-time-picker/DateTimePicker.vue";
|
||||
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||
import DangerConfirmDialog from "@/components/editor/DangerConfirmDialog.vue";
|
||||
import JsonTree from "@/components/common/JsonTree.vue";
|
||||
import RedisJsonEditor from "@/components/redis/RedisJsonEditor.vue";
|
||||
@@ -20,7 +23,7 @@ import { useEditorFontFamilyStyle } from "@/composables/useEditorFontFamilyStyle
|
||||
import { createShikiJsonHighlighter, type JsonHighlighter } from "@/lib/common/shikiJsonHighlighter";
|
||||
import { copyToClipboard } from "@/lib/common/clipboard";
|
||||
import { formatTtl } from "@/lib/common/ttlFormat";
|
||||
import { computeAutoRefreshTick, computeDisplayTtl, shouldStopAutoRefresh } from "@/lib/redis/redisAutoRefresh";
|
||||
import { computeAutoRefreshTick, computeDisplayTtl, computeTtlForExpiryEdit, shouldStopAutoRefresh } from "@/lib/redis/redisAutoRefresh";
|
||||
import {
|
||||
canRenderRedisValueFormat,
|
||||
canEditRedisMemberDetail,
|
||||
@@ -45,8 +48,10 @@ import {
|
||||
import { canFullHighlightRedisText, findRedisTextMatches, nextRedisSearchMatchIndex, REDIS_VALUE_SEARCH_MATCH_LIMIT, renderRedisTextSearchHtml, redisValueSearchStatus } from "@/lib/redis/redisValueSearch";
|
||||
import TextContentSearchBar from "@/components/common/TextContentSearchBar.vue";
|
||||
import { formatJsonSource } from "@/lib/common/safeJsonFormat";
|
||||
import { unixSecondsToCalendarDateTime } from "@/components/ui/date-time-picker/dateTimePicker";
|
||||
import { applyRedisExpiryPolicy, type RedisExpiryMode, redisExpiryModeForTtl, validateRedisExpiry } from "@/lib/redis/redisExpiry";
|
||||
|
||||
const { t } = useI18n();
|
||||
const { t, locale } = useI18n();
|
||||
const { toast } = useToast();
|
||||
const { isDark } = useTheme();
|
||||
const editorFontFamilyStyle = useEditorFontFamilyStyle();
|
||||
@@ -59,7 +64,12 @@ const props = defineProps<{
|
||||
metadata?: RedisKeyInfo | null;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{ deleted: []; loaded: [value: RedisValue] }>();
|
||||
const redisExpiryTransport = {
|
||||
setTtl: api.redisSetTtl,
|
||||
setExpireAt: api.redisSetExpireAt,
|
||||
};
|
||||
|
||||
const emit = defineEmits<{ deleted: [keyRaw: string]; loaded: [value: RedisValue] }>();
|
||||
|
||||
const REDIS_JSON_WRAP_STORAGE_KEY = "dbx-redis-json-word-wrap";
|
||||
const REDIS_VALUE_FORMAT_STORAGE_KEY = "dbx-redis-value-format";
|
||||
@@ -79,12 +89,19 @@ const newScore = ref("");
|
||||
const showDeleteConfirm = ref(false);
|
||||
const showMemberDetail = ref(false);
|
||||
const editingTtl = ref(false);
|
||||
const savingTtl = ref(false);
|
||||
const ttlExpiryMode = ref<RedisExpiryMode>("none");
|
||||
const ttlInput = ref("");
|
||||
const ttlExpireAt = shallowRef<CalendarDateTime | null>(null);
|
||||
const ttlInputEl = ref<InstanceType<typeof Input>>();
|
||||
const editTtlWrapper = ref<HTMLElement>();
|
||||
onClickOutside(editTtlWrapper, () => {
|
||||
if (editingTtl.value) cancelEditTtl();
|
||||
});
|
||||
onClickOutside(
|
||||
editTtlWrapper,
|
||||
() => {
|
||||
if (editingTtl.value && !savingTtl.value) cancelEditTtl();
|
||||
},
|
||||
{ ignore: ["[data-date-time-picker-content]", "[data-redis-expiry-mode-content]"] },
|
||||
);
|
||||
const collectionItems = ref<RedisCollectionItem[]>([]);
|
||||
const scanCursor = ref<number | undefined>(undefined);
|
||||
const selectedMemberTitle = ref("");
|
||||
@@ -595,7 +612,28 @@ async function load(options: { selectDefaultMember?: boolean; preserveDraft?: bo
|
||||
loading.value = true;
|
||||
try {
|
||||
const loadedValue = await api.redisGetValue(props.connectionId, props.db, props.keyRaw);
|
||||
if (requestId !== loadRequestId || (options.preserveDraft && hasUnsavedRedisDraft.value)) return false;
|
||||
if (requestId !== loadRequestId) return false;
|
||||
|
||||
// Redis reports a key that expired between refreshes as a `none` value.
|
||||
// Tell the browser to remove it instead of rendering a stale detail shell.
|
||||
if (loadedValue.redis_type === "none") {
|
||||
data.value = null;
|
||||
collectionItems.value = [];
|
||||
scanCursor.value = undefined;
|
||||
stopAutoRefresh();
|
||||
emit("deleted", props.keyRaw);
|
||||
return true;
|
||||
}
|
||||
|
||||
if (options.preserveDraft && hasUnsavedRedisDraft.value) {
|
||||
const currentValue = data.value;
|
||||
if (currentValue) {
|
||||
const preservedValue = { ...currentValue, ttl: loadedValue.ttl };
|
||||
data.value = preservedValue;
|
||||
emit("loaded", preservedValue);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
if (hashSearchTimer) clearTimeout(hashSearchTimer);
|
||||
hashSearchTimer = null;
|
||||
@@ -718,7 +756,7 @@ function discardRedisJsonEdit() {
|
||||
|
||||
async function applyDeleteKey() {
|
||||
await api.redisDeleteKey(props.connectionId, props.db, props.keyRaw);
|
||||
emit("deleted");
|
||||
emit("deleted", props.keyRaw);
|
||||
}
|
||||
|
||||
function requestDeleteKey() {
|
||||
@@ -1151,27 +1189,108 @@ function requestZsetRemove(member: string | null) {
|
||||
}
|
||||
|
||||
// TTL
|
||||
function startEditTtl() {
|
||||
if (!data.value) return;
|
||||
ttlInput.value = data.value.ttl > 0 ? String(data.value.ttl) : "";
|
||||
editingTtl.value = true;
|
||||
void nextTick(() => ttlInputEl.value?.$el?.focus());
|
||||
function currentEditableTtl(): number {
|
||||
if (!data.value) return -1;
|
||||
return computeTtlForExpiryEdit(autoRefreshEnabled.value, countdownTtl.value, data.value.ttl);
|
||||
}
|
||||
|
||||
function expiryValidationMessage(reason: "ttl" | "date" | "past"): string {
|
||||
if (reason === "ttl") return t("redis.expiryTtlInvalid");
|
||||
if (reason === "date") return t("redis.expiryDateRequired");
|
||||
return t("redis.expiryDatePast");
|
||||
}
|
||||
|
||||
function errorMessage(error: unknown): string {
|
||||
return error instanceof Error ? error.message : String(error);
|
||||
}
|
||||
|
||||
function isRedisMissingKeyError(error: unknown): boolean {
|
||||
return /^Redis(?:JSON)? key no longer exists(?:;|$)/.test(errorMessage(error));
|
||||
}
|
||||
|
||||
async function refreshTtlState(missingSignal?: unknown): Promise<unknown | null> {
|
||||
try {
|
||||
await load({ preserveDraft: true });
|
||||
return null;
|
||||
} catch (error) {
|
||||
// RedisJSON can lose a key between TYPE and JSON.GET. Retry that specific
|
||||
// race, but do not remove a key based only on an earlier command result.
|
||||
if (!isRedisMissingKeyError(missingSignal) && !isRedisMissingKeyError(error)) return error;
|
||||
try {
|
||||
await load({ preserveDraft: true });
|
||||
return null;
|
||||
} catch (retryError) {
|
||||
if (isRedisMissingKeyError(retryError)) {
|
||||
emit("deleted", props.keyRaw);
|
||||
return null;
|
||||
}
|
||||
return retryError;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function focusTtlExpiryControl(mode = ttlExpiryMode.value) {
|
||||
void nextTick(() => {
|
||||
if (!editingTtl.value) return;
|
||||
if (mode === "ttl") {
|
||||
ttlInputEl.value?.$el?.focus();
|
||||
return;
|
||||
}
|
||||
|
||||
const selector = mode === "at" ? "[data-date-time-picker-trigger]" : "[data-slot='select-trigger']";
|
||||
editTtlWrapper.value?.querySelector<HTMLElement>(selector)?.focus();
|
||||
});
|
||||
}
|
||||
|
||||
function startEditTtl() {
|
||||
if (!data.value || savingTtl.value) return;
|
||||
const ttl = currentEditableTtl();
|
||||
ttlExpiryMode.value = redisExpiryModeForTtl(ttl);
|
||||
ttlInput.value = ttl > 0 ? String(ttl) : "";
|
||||
ttlExpireAt.value = null;
|
||||
editingTtl.value = true;
|
||||
focusTtlExpiryControl();
|
||||
}
|
||||
|
||||
watch(ttlExpiryMode, (mode, previousMode) => {
|
||||
const ttl = currentEditableTtl();
|
||||
if (mode === "at" && previousMode !== "at" && ttl > 0) {
|
||||
// Convert the live TTL at the moment of switching, not the stale fetched value.
|
||||
ttlExpireAt.value = unixSecondsToCalendarDateTime(Math.ceil(Date.now() / 1_000) + ttl);
|
||||
}
|
||||
if (editingTtl.value && mode !== previousMode) focusTtlExpiryControl(mode);
|
||||
});
|
||||
|
||||
async function saveTtl() {
|
||||
const val = ttlInput.value.trim();
|
||||
const ttl = val === "" || val === "-1" ? -1 : parseInt(val, 10);
|
||||
if (isNaN(ttl)) {
|
||||
toast(t("redis.ttlInvalid"), 3000);
|
||||
if (savingTtl.value) return;
|
||||
const validation = validateRedisExpiry(ttlExpiryMode.value, ttlInput.value, ttlExpireAt.value);
|
||||
if (!validation.valid) {
|
||||
const message = expiryValidationMessage(validation.reason);
|
||||
toast(message, 3000);
|
||||
return;
|
||||
}
|
||||
await api.redisSetTtl(props.connectionId, props.db, props.keyRaw, ttl);
|
||||
editingTtl.value = false;
|
||||
await load();
|
||||
savingTtl.value = true;
|
||||
try {
|
||||
try {
|
||||
await applyRedisExpiryPolicy(redisExpiryTransport, props.connectionId, props.db, props.keyRaw, validation.policy);
|
||||
} catch (error) {
|
||||
// The expiry command may have raced with a deletion or succeeded before a transport error.
|
||||
await refreshTtlState(error);
|
||||
toast(errorMessage(error), 3000);
|
||||
return;
|
||||
}
|
||||
editingTtl.value = false;
|
||||
const refreshError = await refreshTtlState();
|
||||
if (refreshError) toast(errorMessage(refreshError), 3000);
|
||||
} finally {
|
||||
savingTtl.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function cancelEditTtl() {
|
||||
if (savingTtl.value) return;
|
||||
editingTtl.value = false;
|
||||
ttlExpireAt.value = null;
|
||||
}
|
||||
|
||||
// Hash
|
||||
@@ -1453,12 +1572,27 @@ defineExpose({ focusSearch });
|
||||
<Badge variant="secondary" class="dbx-editor-font-family text-xs uppercase">{{ data.redis_type }}</Badge>
|
||||
<Badge v-if="metadataSizeLabel" variant="outline" class="text-xs text-muted-foreground"> {{ t("redis.columnSize") }}: {{ metadataSizeLabel }} </Badge>
|
||||
<template v-if="!editingTtl">
|
||||
<Badge v-if="data.ttl > 0" variant="outline" class="text-xs cursor-pointer text-muted-foreground hover:bg-accent" @click="startEditTtl">TTL: {{ formatTtl(computeDisplayTtl(autoRefreshEnabled, countdownTtl, data.ttl), t) }}</Badge>
|
||||
<Badge v-else-if="data.ttl === -1" variant="outline" class="text-xs cursor-pointer text-muted-foreground hover:bg-accent" @click="startEditTtl">{{ t("redis.noExpiry") }}</Badge>
|
||||
<Badge v-if="data.ttl > 0" as="button" type="button" variant="outline" class="text-xs cursor-pointer text-muted-foreground hover:bg-accent disabled:cursor-not-allowed disabled:opacity-50" :disabled="savingTtl" :aria-label="t('redis.expiry')" @click="startEditTtl">
|
||||
TTL: {{ formatTtl(computeDisplayTtl(autoRefreshEnabled, countdownTtl, data.ttl), t) }}
|
||||
</Badge>
|
||||
<Badge v-else-if="data.ttl === -1" as="button" type="button" variant="outline" class="text-xs cursor-pointer text-muted-foreground hover:bg-accent disabled:cursor-not-allowed disabled:opacity-50" :disabled="savingTtl" :aria-label="t('redis.expiry')" @click="startEditTtl">
|
||||
{{ t("redis.noExpiry") }}
|
||||
</Badge>
|
||||
</template>
|
||||
<div ref="editTtlWrapper" v-else class="flex items-center gap-1">
|
||||
<Input ref="ttlInputEl" v-model="ttlInput" class="h-6 w-20 text-xs" placeholder="seconds (-1=no expiry)" @keydown.enter="saveTtl" @keydown.escape="cancelEditTtl" />
|
||||
<Button variant="ghost" size="icon" class="h-6 w-6" @click="saveTtl"><Save class="h-3 w-3" /></Button>
|
||||
<div ref="editTtlWrapper" v-else class="flex min-w-0 max-w-full flex-wrap items-center gap-1">
|
||||
<Select v-model="ttlExpiryMode" :disabled="savingTtl">
|
||||
<SelectTrigger size="sm" class="h-6 max-w-[min(100%,14rem)] shrink-0 gap-1 py-0 pl-2 pr-1.5 text-[11px]" :aria-label="t('redis.expiry')">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent data-redis-expiry-mode-content class="min-w-[12rem]">
|
||||
<SelectItem value="none">{{ t("redis.expiryNone") }}</SelectItem>
|
||||
<SelectItem value="ttl">{{ t("redis.expiryTtl") }}</SelectItem>
|
||||
<SelectItem value="at">{{ t("redis.expiryAt") }}</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<Input v-if="ttlExpiryMode === 'ttl'" ref="ttlInputEl" v-model="ttlInput" class="h-6 w-28 shrink-0 text-xs" :disabled="savingTtl" inputmode="numeric" :placeholder="t('redis.createKeyTtlPlaceholder')" @keydown.enter="saveTtl" @keydown.escape="cancelEditTtl" />
|
||||
<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>
|
||||
</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" />
|
||||
|
||||
Reference in new issue
Block a user