Skip to content

armgit / dbx

Public Imported from GitHub
0

25 MB lightweight cross-platform database client for 100+ databases, including MySQL, PostgreSQL, SQLite, Redis, MongoDB, DuckDB, SQL Server, and Dameng. Built-in AI, MCP Server, CLI, desktop and Docker. | 轻量级跨平台数据库管理工具,支持 MySQL、PostgreSQL、SQLite、Redis、MongoDB、达梦等 100+ 数据库,提供桌面端、Docker、CLI、内置 AI 助手和 MCP。

feat(redis): add TTL metadata support

dadong39ce50b68123
diff --git a/apps/desktop/src/components/redis/RedisKeyBrowser.expiry.spec.ts b/apps/desktop/src/components/redis/RedisKeyBrowser.expiry.spec.ts
index 746becd1e8..b8be04618e 100644
--- a/apps/desktop/src/components/redis/RedisKeyBrowser.expiry.spec.ts
+++ b/apps/desktop/src/components/redis/RedisKeyBrowser.expiry.spec.ts
@@ -664,6 +664,132 @@ describe("RedisKeyBrowser scope changes", () => {
});
});
+describe("RedisKeyBrowser TTL list badges and no-expiry filter", () => {
+ it("renders TTL badges per row and filters rows to keys without expiry", async () => {
+ mocks.redisScanKeysBatch.mockResolvedValue({
+ cursor: 0,
+ keys: [
+ {
+ key_display: "session:a",
+ key_raw: "c2Vzc2lvbjph",
+ key_type: "string",
+ ttl: -1,
+ },
+ {
+ key_display: "cache:b",
+ key_raw: "Y2FjaGU6Yg==",
+ key_type: "string",
+ ttl: 3600,
+ },
+ ],
+ total_keys: 2,
+ });
+ mountBrowser();
+ await settle();
+ // 初始 "*" 浏览是树模式且分组默认折叠;切到 key 搜索后走平铺行,leaf 直接可见
+ await submitKeySearch("session");
+
+ expect(document.body.textContent).toContain("session:a");
+ // 永不过期(TTL = -1)显示为本地化的 redis.noExpiry 文案,
+ // 剩余 3600 秒显示为加载时刻快照 redis.ttlHour(测试未配置 i18n 文案时回退为 key)
+ expect(document.body.textContent).toContain("redis.noExpiry");
+ expect(document.body.textContent).toContain("redis.ttlHour");
+
+ requiredElement<HTMLButtonElement>("[data-redis-no-expiry-filter]").click();
+ await settle();
+
+ expect(document.body.textContent).toContain("session:a");
+ expect(document.body.textContent).not.toContain("cache:b");
+ });
+
+ it("shows an empty hint when no loaded key is without expiry", async () => {
+ mocks.redisScanKeysBatch.mockResolvedValue({
+ cursor: 0,
+ keys: [
+ {
+ key_display: "cache:b",
+ key_raw: "Y2FjaGU6Yg==",
+ key_type: "string",
+ ttl: 60,
+ },
+ ],
+ total_keys: 1,
+ });
+ mountBrowser();
+ await settle();
+ await submitKeySearch("cache");
+
+ requiredElement<HTMLButtonElement>("[data-redis-no-expiry-filter]").click();
+ await settle();
+
+ expect(document.body.textContent).toContain("redis.noExpiryKeysEmpty");
+ });
+
+ it("counts down the list TTL locally without extra network requests", async () => {
+ vi.useFakeTimers();
+ try {
+ mocks.redisScanKeysBatch.mockResolvedValue({
+ cursor: 0,
+ keys: [
+ {
+ key_display: "cache:b",
+ key_raw: "Y2FjaGU6Yg==",
+ key_type: "string",
+ ttl: 60,
+ },
+ ],
+ total_keys: 1,
+ });
+ mountBrowser();
+ await settle();
+ await submitKeySearch("cache");
+
+ // 刚加载时流逝为 0,60 秒只展示分钟单位(未配置文案时回退为 key)
+ expect(document.body.textContent).toContain("redis.ttlMinute");
+
+ const scanCalls = mocks.redisScanKeysBatch.mock.calls.length;
+ await vi.advanceTimersByTimeAsync(5000);
+ await settle();
+
+ // 倒计时是纯本地计算,不发额外请求;55 秒只展示秒单位
+ expect(mocks.redisScanKeysBatch).toHaveBeenCalledTimes(scanCalls);
+ expect(document.body.textContent).toContain("redis.ttlSecond");
+ expect(document.body.textContent).not.toContain("redis.ttlMinute");
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it("shows an expired badge when the local countdown reaches zero", async () => {
+ vi.useFakeTimers();
+ try {
+ mocks.redisScanKeysBatch.mockResolvedValue({
+ cursor: 0,
+ keys: [
+ {
+ key_display: "cache:b",
+ key_raw: "Y2FjaGU6Yg==",
+ key_type: "string",
+ ttl: 1,
+ },
+ ],
+ total_keys: 1,
+ });
+ mountBrowser();
+ await settle();
+ await submitKeySearch("cache");
+
+ await vi.advanceTimersByTimeAsync(2000);
+ await settle();
+
+ // 倒计时归零后展示已过期文案,而不是停留在旧快照
+ expect(document.body.textContent).toContain("redis.expired");
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+});
+
describe("RedisKeyBrowser command completion", () => {
it("uses the connected server's module command docs and accepts the selection with Tab", async () => {
mountBrowser();
diff --git a/apps/desktop/src/components/redis/RedisKeyBrowser.vue b/apps/desktop/src/components/redis/RedisKeyBrowser.vue
index d73ab0859f..2132599119 100644
--- a/apps/desktop/src/components/redis/RedisKeyBrowser.vue
+++ b/apps/desktop/src/components/redis/RedisKeyBrowser.vue
@@ -29,6 +29,7 @@ import { useSettingsStore } from "@/stores/settingsStore";
import { continuousQueryResultMaxRows } from "@/lib/dataGrid/queryResultRowLimit";
import {
appendRedisKeysToTreeIndex,
+ buildRedisKeyTree,
canBuildRedisFuzzyTree,
collectExpandedGroupIds,
collectRedisGroupKeyRaws,
@@ -57,6 +58,8 @@ import { getRedisCreateKeyTypeHelp, redisCreateKeyTypeHelpOptionOnOpen, shouldAc
import { optionHelpPanelOffsetTop } from "@/lib/common/optionHelpPanelOffset";
import { applyRedisExpiryPolicy, type RedisExpiryMode, validateRedisExpiry } from "@/lib/redis/redisExpiry";
import { shouldLoadMoreRedisKeys } from "@/lib/redis/redisKeyInfiniteScroll";
+import { formatTtl } from "@/lib/common/ttlFormat";
+import { computeTtlCountdownValue } from "@/lib/redis/redisAutoRefresh";
const { t, locale } = useI18n();
const { toast } = useToast();
@@ -229,7 +232,23 @@ watch(redisKeySeparator, () => {
rebuildTree(false);
});
const lastTotalKeys = ref(0);
-const displayedKeyCount = computed(() => (isFetchingAll.value ? fetchAllLoadedCount.value : flatKeys.value.length));
+// “仅看无过期”过滤开关:开启后只保留 TTL 为 -1(永不过期)的已加载 key。
+// TTL 为 -2 的行(fetch-all 链路未查询 TTL)不会出现在过滤结果里。
+const noExpiryOnly = ref(false);
+// 过滤后的平铺 key 列表:未开启过滤时与 flatKeys 完全一致,避免额外开销
+const filteredFlatKeys = computed(() => (noExpiryOnly.value ? flatKeys.value.filter((key) => key.ttl === -1) : flatKeys.value));
+// 过滤后的树:独立重建而不复用 treeIndex,避免污染后续 SCAN 增量合并的全量树基准;
+// 分组 id 只由 db+路径决定,与全量树一致,因此展开状态可直接复用
+const filteredTreeKeys = computed(() => {
+ if (!noExpiryOnly.value) return treeKeys.value;
+ return buildRedisKeyTree(filteredFlatKeys.value, props.db, redisKeySeparator.value);
+});
+const displayedKeyCount = computed(() => {
+ if (isFetchingAll.value) return fetchAllLoadedCount.value;
+ // 过滤时展示匹配数量,便于确认“无过期”key 的规模
+ if (noExpiryOnly.value) return filteredFlatKeys.value.length;
+ return flatKeys.value.length;
+});
const fetchAllProgressText = computed(() => {
if (!isFetchingAll.value) return "";
if (lastTotalKeys.value > 0) {
@@ -335,7 +354,62 @@ async function updateCreateKeyTypeHelpOffset() {
watch(activeCreateKeyTypeHelp, () => {
void updateCreateKeyTypeHelpOffset();
});
-const visibleRows = computed(() => (useFlatKeySearchRows.value ? flatKeys.value.map((key) => redisKeyToFlatTreeRow(key, props.db)) : flattenVisibleRedisKeyTree(treeKeys.value, expandedGroupIds.value)));
+const visibleRows = computed(() => {
+ return useFlatKeySearchRows.value ? filteredFlatKeys.value.map((key) => redisKeyToFlatTreeRow(key, props.db)) : flattenVisibleRedisKeyTree(filteredTreeKeys.value, expandedGroupIds.value);
+});
+// 列表行的 TTL 徽标文案:-1 表示永不过期,展示本地化文案;
+// 大于 0 时展示本地倒计时后的剩余时间,倒计时归零展示已过期;其余(-2 未查询)不显示
+function redisTtlBadgeText(ttl: number, displayTtl: number): string | null {
+ if (ttl === -1) return t("redis.noExpiry");
+ if (ttl > 0 && displayTtl <= 0) return t("redis.expired");
+ return formatTtl(displayTtl, t);
+}
+// 列表行的 TTL 徽标配色:永不过期用琥珀色,已过期或 1 小时内即将过期用红色警示,其余用中性色
+function redisTtlBadgeClass(ttl: number, displayTtl: number): string {
+ if (ttl === -1) return "border-amber-300 bg-amber-50 text-amber-700 dark:border-amber-500/40 dark:bg-amber-500/10 dark:text-amber-300";
+ if (displayTtl <= 3600) return "border-red-300 bg-red-50 text-red-600 dark:border-red-500/40 dark:bg-red-500/10 dark:text-red-300";
+ return "border-border bg-muted/60 text-muted-foreground";
+}
+// 记录每个 key 的 TTL 被观测到的时刻(毫秒);本地倒计时 = 观测时的 TTL - 已流逝时间,
+// 与右侧详情面板同源(computeTtlCountdownValue),不需要额外的网络请求
+const ttlObservedAtByRaw = new Map<string, number>();
+// 驱动列表行 TTL 倒计时的当前时刻,仅在存在需要倒计时的 key 时每秒更新
+const listTtlNowMs = ref(Date.now());
+let listTtlTimer: ReturnType<typeof setInterval> | null = null;
+
+// 批次加载/详情回写等入口统一记录 key 的 TTL 观测时刻;非正 TTL 无需倒计时,移除旧记录
+function recordKeyTtlObservedAt(key: RedisKeyInfo) {
+ const ttl = key.ttl ?? -2;
+ if (ttl > 0) {
+ ttlObservedAtByRaw.set(key.key_raw, Date.now());
+ } else {
+ ttlObservedAtByRaw.delete(key.key_raw);
+ }
+}
+
+// 列表行展示的 TTL:正 TTL 按观测时刻到当前时刻的流逝本地递减;-1/-2 原样透传
+function redisRowDisplayTtl(ttl: number, keyRaw: string): number {
+ if (ttl <= 0) return ttl;
+ const observedAt = ttlObservedAtByRaw.get(keyRaw) ?? Date.now();
+ return computeTtlCountdownValue(ttl, observedAt, listTtlNowMs.value);
+}
+
+// 按需启停倒计时定时器:只在组件激活且存在正 TTL 的 key 时运行,避免空转
+function syncListTtlTimer() {
+ const needed = redisBrowserIsActive && flatKeys.value.some((key) => (key.ttl ?? -2) > 0);
+ if (needed && !listTtlTimer) {
+ listTtlNowMs.value = Date.now();
+ listTtlTimer = setInterval(() => {
+ listTtlNowMs.value = Date.now();
+ }, 1000);
+ } else if (!needed && listTtlTimer) {
+ clearInterval(listTtlTimer);
+ listTtlTimer = null;
+ }
+}
+
+// flatKeys 的每次变更都是整体替换数组,浅监听即可感知增删改
+watch(flatKeys, syncListTtlTimer);
let commandHistoryId = 0;
function resetCheckedKeys() {
@@ -597,6 +671,8 @@ async function fetchScanBatchPage(maxIterations: number, options: { count?: numb
function appendScanResult(result: RedisScanResult, options: { updateTree?: boolean; buffer?: RedisKeyInfo[] } = {}): number {
const newKeys = collectUniqueRedisKeys(result.keys, loadedKeyRaws);
+ // 批次到达前端即为 TTL 的观测时刻,直连合并与 Fetch All 缓冲两条路径在此统一记录
+ for (const key of newKeys) recordKeyTtlObservedAt(key);
if (options.buffer) {
for (const key of newKeys) options.buffer.push(key);
} else if (newKeys.length > 0) {
@@ -658,6 +734,7 @@ async function loadKeys() {
fetchAllLoadedCount.value = 0;
loading.value = true;
loadedKeyRaws.clear();
+ ttlObservedAtByRaw.clear();
flatKeys.value = [];
treeKeys.value = [];
treeIndex = null;
@@ -856,6 +933,7 @@ function onRowClick(node: RedisKeyTreeNode, event?: MouseEvent) {
function removeKnownKey(keyRaw: string) {
if (!flatKeys.value.some((key) => key.key_raw === keyRaw)) return;
loadedKeyRaws.delete(keyRaw);
+ ttlObservedAtByRaw.delete(keyRaw);
flatKeys.value = flatKeys.value.filter((key) => key.key_raw !== keyRaw);
if (selectedKeyRaw.value === keyRaw) selectedKeyRaw.value = null;
if (useFlatKeySearchRows.value) {
@@ -890,6 +968,10 @@ function onKeyRenamed(oldKeyRaw: string, newKeyRaw: string, newKeyDisplay: strin
loadedKeyRaws.delete(oldKeyRaw);
loadedKeyRaws.add(newKeyRaw);
+ // 改名不换 TTL,观测时刻随 key 一起迁移,倒计时不中断
+ const observedAt = ttlObservedAtByRaw.get(oldKeyRaw);
+ ttlObservedAtByRaw.delete(oldKeyRaw);
+ if (observedAt !== undefined) ttlObservedAtByRaw.set(newKeyRaw, observedAt);
flatKeys.value = flatKeys.value.map((key) => (key.key_raw === oldKeyRaw ? { ...key, key_raw: newKeyRaw, key_display: newKeyDisplay } : key));
if (selectedKeyRaw.value === oldKeyRaw) selectedKeyRaw.value = newKeyRaw;
if (checkedKeys.value.has(oldKeyRaw)) {
@@ -926,6 +1008,8 @@ function onKeyLoaded(value: RedisValue) {
const keyInfo = redisValueToKeyInfo(value);
const existingIndex = flatKeys.value.findIndex((key) => key.key_raw === keyInfo.key_raw);
if (existingIndex < 0) return;
+ // 详情面板回写了最新的 TTL,同步刷新观测时刻,保证两侧倒计时一致
+ recordKeyTtlObservedAt(keyInfo);
flatKeys.value = flatKeys.value.map((key, index) => (index === existingIndex ? keyInfo : key));
loadedKeyRaws.add(keyInfo.key_raw);
if (useFlatKeySearchRows.value) {
@@ -995,6 +1079,7 @@ function resetLoadedKeys() {
fetchAllStopRequested.value = false;
fetchAllLoadedCount.value = 0;
loadedKeyRaws.clear();
+ ttlObservedAtByRaw.clear();
flatKeys.value = [];
treeKeys.value = [];
treeIndex = null;
@@ -1019,7 +1104,10 @@ async function deleteKeyRaws(keys: string[]) {
deletedCount += await api.redisDeleteKeys(props.connectionId, props.db, batch);
}
const deleted = new Set(uniqueKeys);
- for (const key of deleted) loadedKeyRaws.delete(key);
+ for (const key of deleted) {
+ loadedKeyRaws.delete(key);
+ ttlObservedAtByRaw.delete(key);
+ }
flatKeys.value = flatKeys.value.filter((key) => !deleted.has(key.key_raw));
if (selectedKeyRaw.value && deleted.has(selectedKeyRaw.value)) {
selectedKeyRaw.value = null;
@@ -1245,6 +1333,8 @@ function upsertCreatedKey(value: RedisValue) {
value_preview: redisValuePreview(value),
};
const existingIndex = flatKeys.value.findIndex((key) => key.key_raw === keyInfo.key_raw);
+ // 新建 key 携带的 TTL 以当前时刻为观测起点
+ recordKeyTtlObservedAt(keyInfo);
if (existingIndex >= 0) {
flatKeys.value = flatKeys.value.map((key, index) => (index === existingIndex ? keyInfo : key));
} else {
@@ -1764,6 +1854,8 @@ function pauseRedisBrowserBackgroundWork() {
// keys that were never rendered.
const discardIncompleteFetchAll = isFetchingAll.value;
redisBrowserIsActive = false;
+ // 组件停用/卸载后不再展示列表,停掉 TTL 倒计时定时器
+ syncListTtlTimer();
// 与 onUnmounted 对称:组件被 keep-alive 包裹,停用时(onDeactivated)若不取消挂起的 rAF,
// 帧回调仍会在隐藏组件上触发并调用 loadMore() 跑一次冗余 SCAN,故在此一并取消并置 0。
if (redisInfiniteScrollFrame) cancelAnimationFrame(redisInfiniteScrollFrame);
@@ -1783,6 +1875,8 @@ function pauseRedisBrowserBackgroundWork() {
function resumeRedisBrowserBackgroundWork() {
redisBrowserIsActive = true;
registerRedisDbFlushedListener();
+ // 重新激活后恢复 TTL 倒计时定时器
+ syncListTtlTimer();
}
async function clearInMemoryHistory() {
@@ -1985,19 +2079,35 @@ defineExpose({ focusSearch, insertCommand, executeCommand: executeAiCommand });
@keydown="onSearchKeydown"
/>
</div>
- <Button
- v-if="searchMode === 'key'"
- variant="ghost"
- size="sm"
- class="h-8 max-w-full shrink-0 whitespace-nowrap px-2 text-xs"
- :class="fuzzyKeySearch ? 'bg-accent text-accent-foreground' : 'border border-dashed border-border/70 text-muted-foreground hover:text-foreground'"
- :title="t('redis.fuzzyMatchTitle')"
- :aria-pressed="fuzzyKeySearch"
- @click="toggleFuzzyKeySearch"
- >
- <Asterisk class="redis-fuzzy-icon h-3 w-3 mr-1" />
- <span class="redis-fuzzy-label">{{ t("redis.fuzzyMatch") }}</span>
- </Button>
+ <div class="flex shrink-0 items-center gap-1">
+ <Button
+ v-if="searchMode === 'key'"
+ variant="ghost"
+ size="sm"
+ class="h-8 max-w-full shrink-0 whitespace-nowrap px-2 text-xs"
+ :class="fuzzyKeySearch ? 'bg-accent text-accent-foreground' : 'border border-dashed border-border/70 text-muted-foreground hover:text-foreground'"
+ :title="t('redis.fuzzyMatchTitle')"
+ :aria-pressed="fuzzyKeySearch"
+ @click="toggleFuzzyKeySearch"
+ >
+ <Asterisk class="redis-fuzzy-icon h-3 w-3 mr-1" />
+ <span class="redis-fuzzy-label">{{ t("redis.fuzzyMatch") }}</span>
+ </Button>
+ <!-- 仅看无过期:在已加载结果里过滤出 TTL 为 -1 的 key,方便批量定位未设置过期时间的缓存 -->
+ <Button
+ variant="ghost"
+ size="sm"
+ class="h-8 shrink-0 whitespace-nowrap px-2 text-xs"
+ :class="noExpiryOnly ? 'bg-accent text-accent-foreground' : 'border border-dashed border-border/70 text-muted-foreground hover:text-foreground'"
+ :title="t('redis.noExpiryOnlyTitle')"
+ :aria-pressed="noExpiryOnly"
+ data-redis-no-expiry-filter
+ @click="noExpiryOnly = !noExpiryOnly"
+ >
+ <Clock class="h-3 w-3 mr-1" />
+ <span>{{ t("redis.noExpiryOnly") }}</span>
+ </Button>
+ </div>
</div>
</div>
@@ -2017,6 +2127,10 @@ defineExpose({ focusSearch, insertCommand, executeCommand: executeAiCommand });
<Loader2 class="w-3.5 h-3.5 animate-spin" />
<span>{{ loadingEmptyText }}</span>
</div>
+ <!-- 过滤开启但没有命中任何无过期 key 时,给出明确空态提示而不是空白列表 -->
+ <div v-else-if="noExpiryOnly && visibleRows.length === 0" class="flex-1 flex items-center justify-center text-muted-foreground text-xs p-4 text-center">
+ {{ t("redis.noExpiryKeysEmpty") }}
+ </div>
<RecycleScroller v-else ref="redisKeyScrollerRef" class="redis-key-scroller flex-1" :items="visibleRows" :item-size="30" :buffer="600" :skip-hover="true" key-field="id" @scroll="onRedisKeyScroll" @resize="maybeAutoLoadMoreRedisKeys">
<template #default="{ item: row }">
<CustomContextMenu :items="redisKeyContextMenuItems(row.node)" v-slot="{ onContextMenu, isOpen }">
@@ -2067,6 +2181,14 @@ defineExpose({ focusSearch, insertCommand, executeCommand: executeAiCommand });
</div>
<div class="flex shrink-0 items-center justify-end gap-1">
<Badge v-if="row.node.kind === 'leaf' && row.node.keyType" variant="outline" class="text-xs px-1.5 py-0" :class="typeColor(row.node.keyType)">{{ row.node.keyType }}</Badge>
+ <!-- TTL 徽标:与类型徽标保持一致的胶囊样式,永不过期为琥珀色、临近过期/已过期为红色警示 -->
+ <span
+ v-if="row.node.kind === 'leaf' && redisTtlBadgeText(row.node.ttl, redisRowDisplayTtl(row.node.ttl, row.node.keyRaw))"
+ class="inline-flex shrink-0 items-center whitespace-nowrap rounded border px-1.5 py-0.5 text-[11px] leading-none"
+ :class="redisTtlBadgeClass(row.node.ttl, redisRowDisplayTtl(row.node.ttl, row.node.keyRaw))"
+ :title="row.node.ttl === -1 ? t('redis.noExpiry') : t('redis.ttlCountdownTitle')"
+ >{{ redisTtlBadgeText(row.node.ttl, redisRowDisplayTtl(row.node.ttl, row.node.keyRaw)) }}</span
+ >
<Button v-if="row.node.kind === 'group' && !isFuzzyHierarchyView" variant="ghost" size="icon" class="h-5 w-5 shrink-0 text-destructive opacity-0 group-hover:opacity-100" :title="t('redis.deleteGroup')" :disabled="selectionBusy" @click="requestGroupDelete(row.node, $event)">
<Trash2 class="h-3 w-3" />
</Button>
diff --git a/apps/desktop/src/components/redis/RedisValueViewer.expiry.spec.ts b/apps/desktop/src/components/redis/RedisValueViewer.expiry.spec.ts
index 7f9370e35a..57a6513566 100644
--- a/apps/desktop/src/components/redis/RedisValueViewer.expiry.spec.ts
+++ b/apps/desktop/src/components/redis/RedisValueViewer.expiry.spec.ts
@@ -130,6 +130,17 @@ function deferred<T>() {
return { promise, resolve };
}
+const testI18nMessages = {
+ en: {
+ redis: {
+ ttlDay: "{count}d",
+ ttlHour: "{count}h",
+ ttlMinute: "{count}m",
+ ttlSecond: "{count}s",
+ },
+ },
+};
+
function mountViewer(onDeleted: (keyRaw: string) => void, onLoaded = vi.fn()) {
const host = document.createElement("div");
document.body.append(host);
@@ -148,7 +159,7 @@ function mountViewer(onDeleted: (keyRaw: string) => void, onLoaded = vi.fn()) {
},
}),
);
- app.use(createI18n({ legacy: false, locale: "en", messages: { en: {} }, missingWarn: false, fallbackWarn: false }));
+ app.use(createI18n({ legacy: false, locale: "en", messages: testI18nMessages, missingWarn: false, fallbackWarn: false }));
app.mount(host);
mountedApps.push({ unmount: () => app.unmount(), host });
}
@@ -178,7 +189,7 @@ function mountKeepAliveViewer(onDeleted = vi.fn()) {
},
}),
);
- app.use(createI18n({ legacy: false, locale: "en", messages: { en: {} }, missingWarn: false, fallbackWarn: false }));
+ app.use(createI18n({ legacy: false, locale: "en", messages: testI18nMessages, missingWarn: false, fallbackWarn: false }));
app.mount(host);
mountedApps.push({ unmount: () => app.unmount(), host });
return {
@@ -272,7 +283,7 @@ describe("RedisValueViewer expiry saving", () => {
expect(mocks.redisGetValue).toHaveBeenCalledOnce();
expect(mocks.redisGetTtl).not.toHaveBeenCalled();
- expect(document.querySelector<HTMLElement>("[data-slot='badge'][aria-label='redis.expiry']")?.textContent).toContain("00:00:50");
+ expect(document.querySelector<HTMLElement>("[data-slot='badge'][aria-label='redis.expiry']")?.textContent).toContain("50s");
});
it("polls the full value at the configured interval without refreshing the parent key tree", async () => {
@@ -291,7 +302,7 @@ describe("RedisValueViewer expiry saving", () => {
expect(mocks.redisGetTtl).not.toHaveBeenCalled();
expect(loaded).toHaveBeenCalledOnce();
expect(document.querySelector<HTMLTextAreaElement>("textarea")?.value).toBe("refreshed");
- expect(document.querySelector<HTMLElement>("[data-slot='badge'][aria-label='redis.expiry']")?.textContent).toContain("00:00:45");
+ expect(document.querySelector<HTMLElement>("[data-slot='badge'][aria-label='redis.expiry']")?.textContent).toContain("45s");
});
it("pauses automatic value polling while a collection member is open", async () => {
@@ -332,7 +343,7 @@ describe("RedisValueViewer expiry saving", () => {
await settle();
expect(mocks.redisGetValue).toHaveBeenCalledTimes(2);
- expect(document.querySelector<HTMLElement>("[data-slot='badge'][aria-label='redis.expiry']")?.textContent).toContain("00:00:30");
+ expect(document.querySelector<HTMLElement>("[data-slot='badge'][aria-label='redis.expiry']")?.textContent).toContain("30s");
});
it("stops auto-refresh after a full-value polling error", async () => {
@@ -368,7 +379,7 @@ describe("RedisValueViewer expiry saving", () => {
await settle();
expect(mocks.redisGetValue).toHaveBeenCalledTimes(3);
- expect(document.querySelector<HTMLElement>("[data-slot='badge'][aria-label='redis.expiry']")?.textContent).toContain("00:00:30");
+ expect(document.querySelector<HTMLElement>("[data-slot='badge'][aria-label='redis.expiry']")?.textContent).toContain("30s");
});
it("pauses polling while the document is hidden and resumes when visible", async () => {
@@ -412,7 +423,7 @@ describe("RedisValueViewer expiry saving", () => {
document.dispatchEvent(new Event("visibilitychange"));
await settle();
- expect(document.querySelector<HTMLElement>("[data-slot='badge'][aria-label='redis.expiry']")?.textContent).toContain("00:00:30");
+ expect(document.querySelector<HTMLElement>("[data-slot='badge'][aria-label='redis.expiry']")?.textContent).toContain("30s");
});
it("pauses polling while deactivated and resumes from the saved setting", async () => {
@@ -536,7 +547,7 @@ describe("RedisValueViewer expiry saving", () => {
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");
+ expect(document.querySelector<HTMLElement>("[data-slot='badge'][aria-label='redis.expiry']")?.textContent).toContain("42s");
});
it("removes a key that disappears while refreshing after a successful TTL save", async () => {
diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.ts
index bcb9013f39..2ba1bc72ca 100644
--- a/apps/desktop/src/i18n/locales/en.ts
+++ b/apps/desktop/src/i18n/locales/en.ts
@@ -4367,6 +4367,11 @@ export default {
loadMoreEntries: "Load more entries",
loadMorePending: "Load more pending entries",
noExpiry: "no expiry",
+ noExpiryOnly: "No expiry only",
+ noExpiryOnlyTitle: "Show only keys without TTL in loaded results",
+ noExpiryKeysEmpty: "No keys without expiry in loaded results",
+ ttlCountdownTitle: "Local countdown from the TTL at load time",
+ expired: "expired",
expiry: "Expiration",
expiryNone: "No expiry",
expiryTtl: "TTL (seconds)",
@@ -4377,6 +4382,9 @@ export default {
keyExpiredBeforeDisplay: "The key expired before it could be displayed.",
autoRefresh: "Auto-refresh countdown",
ttlDay: "{count}d",
+ ttlHour: "{count}h",
+ ttlMinute: "{count}m",
+ ttlSecond: "{count}s",
columnType: "Type",
columnKey: "Key",
columnValue: "Value",
diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.ts
index b1839dd58d..d86dba3c78 100644
--- a/apps/desktop/src/i18n/locales/es.ts
+++ b/apps/desktop/src/i18n/locales/es.ts
@@ -4213,6 +4213,11 @@ export default withEnglishFallback({
loadMoreEntries: "Cargar más entradas",
loadMorePending: "Cargar más entradas pendientes",
noExpiry: "sin expiración",
+ noExpiryOnly: "Solo sin expiración",
+ noExpiryOnlyTitle: "Mostrar solo claves sin TTL en los resultados cargados",
+ noExpiryKeysEmpty: "No hay claves sin expiración en los resultados cargados",
+ ttlCountdownTitle: "Cuenta regresiva local desde el TTL al cargar",
+ expired: "expirada",
expiry: "Expiración",
expiryNone: "Sin expiración",
expiryTtl: "TTL (segundos)",
@@ -4223,6 +4228,9 @@ export default withEnglishFallback({
keyExpiredBeforeDisplay: "La clave expiró antes de que pudiera mostrarse.",
autoRefresh: "Actualización automática",
ttlDay: "{count}d",
+ ttlHour: "{count}h",
+ ttlMinute: "{count}m",
+ ttlSecond: "{count}s",
columnType: "Tipo",
columnKey: "Clave",
columnValue: "Valor",
diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.ts
index 319f1a7de5..08b1aec925 100644
--- a/apps/desktop/src/i18n/locales/it.ts
+++ b/apps/desktop/src/i18n/locales/it.ts
@@ -4211,6 +4211,11 @@ export default withEnglishFallback({
loadMoreEntries: "Carica altre voci",
loadMorePending: "Carica altre voci in sospeso",
noExpiry: "nessuna scadenza",
+ noExpiryOnly: "Solo senza scadenza",
+ noExpiryOnlyTitle: "Mostra solo le chiavi senza TTL nei risultati caricati",
+ noExpiryKeysEmpty: "Nessuna chiave senza scadenza nei risultati caricati",
+ ttlCountdownTitle: "Conto alla rovescia locale dal TTL al caricamento",
+ expired: "scaduta",
expiry: "Scadenza",
expiryNone: "Nessuna scadenza",
expiryTtl: "TTL (secondi)",
@@ -4221,6 +4226,9 @@ export default withEnglishFallback({
keyExpiredBeforeDisplay: "La chiave è scaduta prima di poter essere visualizzata.",
autoRefresh: "Aggiornamento automatico",
ttlDay: "{count}g",
+ ttlHour: "{count}h",
+ ttlMinute: "{count}m",
+ ttlSecond: "{count}s",
columnType: "Tipo",
columnKey: "Chiave",
columnValue: "Valore",
diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.ts
index a5d3046a5c..ee87ded752 100644
--- a/apps/desktop/src/i18n/locales/ja.ts
+++ b/apps/desktop/src/i18n/locales/ja.ts
@@ -4241,6 +4241,11 @@ export default withEnglishFallback({
loadMoreEntries: "さらにエントリを読み込む",
loadMorePending: "保留中のエントリをさらに読み込む",
noExpiry: "期限なし",
+ noExpiryOnly: "期限なしのみ",
+ noExpiryOnlyTitle: "読み込み済みの結果から期限なし(TTL = -1)のキーのみ表示",
+ noExpiryKeysEmpty: "読み込み済みの結果に期限なしのキーはありません",
+ ttlCountdownTitle: "読み込み時点の TTL にもとづくローカルカウントダウン",
+ expired: "期限切れ",
expiry: "有効期限",
expiryNone: "期限なし",
expiryTtl: "TTL(秒)",
@@ -4251,6 +4256,9 @@ export default withEnglishFallback({
keyExpiredBeforeDisplay: "キーは表示される前に期限切れになりました。",
autoRefresh: "自動更新(カウントダウン)",
ttlDay: "{count}日",
+ ttlHour: "{count}時間",
+ ttlMinute: "{count}分",
+ ttlSecond: "{count}秒",
columnType: "型",
columnKey: "キー",
columnValue: "値",
diff --git a/apps/desktop/src/i18n/locales/ko.ts b/apps/desktop/src/i18n/locales/ko.ts
index 5269560aef..8c208aafc1 100644
--- a/apps/desktop/src/i18n/locales/ko.ts
+++ b/apps/desktop/src/i18n/locales/ko.ts
@@ -3851,6 +3851,11 @@ export default withEnglishFallback({
loadMoreEntries: "항목 더 불러오기",
loadMorePending: "대기 항목 더 불러오기",
noExpiry: "만료 없음",
+ noExpiryOnly: "만료 없음만",
+ noExpiryOnlyTitle: "로드된 결과에서 만료 없음(TTL = -1) 키만 표시",
+ noExpiryKeysEmpty: "로드된 결과에 만료 없음 키가 없습니다",
+ ttlCountdownTitle: "로드 시점 TTL 기준 로컬 카운트다운",
+ expired: "만료됨",
expiry: "만료",
expiryNone: "만료 없음",
expiryTtl: "TTL (초)",
@@ -3861,6 +3866,9 @@ export default withEnglishFallback({
keyExpiredBeforeDisplay: "표시하기 전에 키가 만료되었습니다.",
autoRefresh: "자동 새로고침 카운트다운",
ttlDay: "{count}일",
+ ttlHour: "{count}시간",
+ ttlMinute: "{count}분",
+ ttlSecond: "{count}초",
columnType: "타입",
columnKey: "키",
columnValue: "값",
diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.ts
index 313ebc0f6e..6906865782 100644
--- a/apps/desktop/src/i18n/locales/pt-BR.ts
+++ b/apps/desktop/src/i18n/locales/pt-BR.ts
@@ -4213,6 +4213,11 @@ export default withEnglishFallback({
loadMoreEntries: "Carregar mais entradas",
loadMorePending: "Carregar mais entradas pendentes",
noExpiry: "sem expiração",
+ noExpiryOnly: "Somente sem expiração",
+ noExpiryOnlyTitle: "Mostrar apenas chaves sem TTL nos resultados carregados",
+ noExpiryKeysEmpty: "Nenhuma chave sem expiração nos resultados carregados",
+ ttlCountdownTitle: "Contagem regressiva local a partir do TTL no carregamento",
+ expired: "expirada",
expiry: "Expiração",
expiryNone: "Sem expiração",
expiryTtl: "TTL (segundos)",
@@ -4223,6 +4228,9 @@ export default withEnglishFallback({
keyExpiredBeforeDisplay: "A chave expirou antes de poder ser exibida.",
autoRefresh: "Atualização automática",
ttlDay: "{count}d",
+ ttlHour: "{count}h",
+ ttlMinute: "{count}min",
+ ttlSecond: "{count}s",
columnType: "Tipo",
columnKey: "Chave",
columnValue: "Valor",
diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.ts
index f0483f65ae..e8d075678a 100644
--- a/apps/desktop/src/i18n/locales/zh-CN.ts
+++ b/apps/desktop/src/i18n/locales/zh-CN.ts
@@ -4354,6 +4354,11 @@ export default withEnglishFallback({
loadMoreEntries: "加载更多条目",
loadMorePending: "加载更多待处理条目",
noExpiry: "永不过期",
+ noExpiryOnly: "仅无过期",
+ noExpiryOnlyTitle: "在已加载的结果中仅显示没有过期时间(TTL = -1)的 key",
+ noExpiryKeysEmpty: "已加载的结果中没有无过期的 key",
+ ttlCountdownTitle: "基于加载时刻 TTL 的本地倒计时",
+ expired: "已过期",
expiry: "过期时间",
expiryNone: "永不过期",
expiryTtl: "TTL(秒)",
@@ -4364,6 +4369,9 @@ export default withEnglishFallback({
keyExpiredBeforeDisplay: "该键在显示前已过期。",
autoRefresh: "自动刷新(倒计时)",
ttlDay: "{count}天",
+ ttlHour: "{count}小时",
+ ttlMinute: "{count}分钟",
+ ttlSecond: "{count}秒",
columnType: "类型",
columnKey: "键",
columnValue: "值",
diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.ts
index a774737058..7f6a2ff5ea 100644
--- a/apps/desktop/src/i18n/locales/zh-TW.ts
+++ b/apps/desktop/src/i18n/locales/zh-TW.ts
@@ -3540,6 +3540,11 @@ export default withEnglishFallback({
loadMoreEntries: "載入更多項目",
loadMorePending: "載入更多待處理項目",
noExpiry: "永不過期",
+ noExpiryOnly: "僅無過期",
+ noExpiryOnlyTitle: "在已載入的結果中僅顯示沒有過期時間(TTL = -1)的 key",
+ noExpiryKeysEmpty: "已載入的結果中沒有無過期的 key",
+ ttlCountdownTitle: "基於載入時刻 TTL 的本地倒計時",
+ expired: "已過期",
expiry: "到期時間",
expiryNone: "永不過期",
expiryTtl: "TTL(秒)",
@@ -3550,6 +3555,9 @@ export default withEnglishFallback({
keyExpiredBeforeDisplay: "此鍵在顯示前已過期。",
autoRefresh: "自動刷新(倒計時)",
ttlDay: "{count}天",
+ ttlHour: "{count}小時",
+ ttlMinute: "{count}分鐘",
+ ttlSecond: "{count}秒",
columnType: "類型",
columnKey: "鍵",
columnValue: "值",
diff --git a/apps/desktop/src/lib/__tests__/common/ttlFormat.spec.ts b/apps/desktop/src/lib/__tests__/common/ttlFormat.spec.ts
index 25f2faee79..d8f6b55199 100644
--- a/apps/desktop/src/lib/__tests__/common/ttlFormat.spec.ts
+++ b/apps/desktop/src/lib/__tests__/common/ttlFormat.spec.ts
@@ -2,48 +2,38 @@ import { describe, expect, it } from "vitest";
import { formatTtl } from "@/lib/common/ttlFormat";
// ---------------------------------------------------------------------------
-// Mock `t()` helpers — only the day unit needs localization
+// Mock `t()` helpers — day/hour/minute/second units are all localized
// ---------------------------------------------------------------------------
-function enT(key: string, options?: Record<string, unknown>): string {
- const messages: Record<string, string> = {
- "redis.ttlDay": "{count}d",
+function makeT(messages: Record<string, string>): (key: string, options?: Record<string, unknown>) => string {
+ return (key, options) => {
+ const msg = messages[key] ?? key;
+ const count = (options as { count?: number })?.count;
+ if (count != null) return msg.replace("{count}", String(count));
+ return msg;
};
- const msg = messages[key] ?? key;
- const count = (options as { count?: number })?.count;
- if (count != null) return msg.replace("{count}", String(count));
- return msg;
}
-function zhT(key: string, options?: Record<string, unknown>): string {
- const messages: Record<string, string> = {
- "redis.ttlDay": "{count}天",
- };
- const msg = messages[key] ?? key;
- const count = (options as { count?: number })?.count;
- if (count != null) return msg.replace("{count}", String(count));
- return msg;
-}
+const enT = makeT({
+ "redis.ttlDay": "{count}d",
+ "redis.ttlHour": "{count}h",
+ "redis.ttlMinute": "{count}m",
+ "redis.ttlSecond": "{count}s",
+});
-function esT(key: string, options?: Record<string, unknown>): string {
- const messages: Record<string, string> = {
- "redis.ttlDay": "{count}d",
- };
- const msg = messages[key] ?? key;
- const count = (options as { count?: number })?.count;
- if (count != null) return msg.replace("{count}", String(count));
- return msg;
-}
+const zhT = makeT({
+ "redis.ttlDay": "{count}天",
+ "redis.ttlHour": "{count}小时",
+ "redis.ttlMinute": "{count}分钟",
+ "redis.ttlSecond": "{count}秒",
+});
-function itT(key: string, options?: Record<string, unknown>): string {
- const messages: Record<string, string> = {
- "redis.ttlDay": "{count}g",
- };
- const msg = messages[key] ?? key;
- const count = (options as { count?: number })?.count;
- if (count != null) return msg.replace("{count}", String(count));
- return msg;
-}
+const itT = makeT({
+ "redis.ttlDay": "{count}g",
+ "redis.ttlHour": "{count}h",
+ "redis.ttlMinute": "{count}m",
+ "redis.ttlSecond": "{count}s",
+});
// ---------------------------------------------------------------------------
// Tests
@@ -64,93 +54,82 @@ describe("formatTtl — special values", () => {
});
});
-describe("formatTtl — sub-day, HH:mm:ss (no i18n)", () => {
- it("formats 45s as 00:00:45", () => {
- expect(formatTtl(45, enT)).toBe("00:00:45");
+describe("formatTtl — sub-hour, single unit or minute+second", () => {
+ it("formats 45s with only the seconds unit", () => {
+ expect(formatTtl(45, enT)).toBe("45s");
+ expect(formatTtl(45, zhT)).toBe("45秒");
});
- it("formats 1m as 00:01:00", () => {
- expect(formatTtl(60, enT)).toBe("00:01:00");
+ it("formats 1m with only the minutes unit", () => {
+ expect(formatTtl(60, enT)).toBe("1m");
+ expect(formatTtl(60, zhT)).toBe("1分钟");
});
- it("formats 1m 30s as 00:01:30", () => {
- expect(formatTtl(90, enT)).toBe("00:01:30");
+ it("formats 1m 30s as two units", () => {
+ expect(formatTtl(90, enT)).toBe("1m 30s");
+ expect(formatTtl(90, zhT)).toBe("1分钟 30秒");
});
- it("formats 2m 5s as 00:02:05", () => {
- expect(formatTtl(125, enT)).toBe("00:02:05");
+ it("formats 2m 5s as two units", () => {
+ expect(formatTtl(125, enT)).toBe("2m 5s");
+ expect(formatTtl(125, zhT)).toBe("2分钟 5秒");
});
+});
- it("formats 1h as 01:00:00", () => {
- expect(formatTtl(3600, enT)).toBe("01:00:00");
+describe("formatTtl — sub-day, keeps only the two largest non-zero units", () => {
+ it("formats 1h with only the hours unit", () => {
+ expect(formatTtl(3600, enT)).toBe("1h");
+ expect(formatTtl(3600, zhT)).toBe("1小时");
});
- it("formats 1h 1m 1s as 01:01:01", () => {
- expect(formatTtl(3661, enT)).toBe("01:01:01");
+ it("formats 1h 1m 1s by dropping the seconds unit", () => {
+ expect(formatTtl(3661, enT)).toBe("1h 1m");
+ expect(formatTtl(3661, zhT)).toBe("1小时 1分钟");
});
- it("formats 23h 59m 59s as 23:59:59", () => {
- expect(formatTtl(86399, enT)).toBe("23:59:59");
+ it("formats 23h 59m 59s by dropping the seconds unit", () => {
+ expect(formatTtl(86399, enT)).toBe("23h 59m");
+ expect(formatTtl(86399, zhT)).toBe("23小时 59分钟");
});
});
-describe("formatTtl — multi-day, {n}d HH:mm:ss (day unit localized)", () => {
- it("formats exactly 1 day as 1d 00:00:00", () => {
- expect(formatTtl(86400, enT)).toBe("1d 00:00:00");
- expect(formatTtl(86400, zhT)).toBe("1天 00:00:00");
+describe("formatTtl — multi-day, day unit plus hours when present", () => {
+ it("formats exactly 1 day with only the day unit", () => {
+ expect(formatTtl(86400, enT)).toBe("1d");
+ expect(formatTtl(86400, zhT)).toBe("1天");
});
- it("formats 7 days as 7d 00:00:00", () => {
- expect(formatTtl(604800, enT)).toBe("7d 00:00:00");
- expect(formatTtl(604800, zhT)).toBe("7天 00:00:00");
+ it("formats 7 days with only the day unit", () => {
+ expect(formatTtl(604800, enT)).toBe("7d");
+ expect(formatTtl(604800, zhT)).toBe("7天");
});
- it("formats 365 days as 365d 00:00:00", () => {
- expect(formatTtl(31536000, enT)).toBe("365d 00:00:00");
- expect(formatTtl(31536000, zhT)).toBe("365天 00:00:00");
+ it("formats 365 days with only the day unit", () => {
+ expect(formatTtl(31536000, enT)).toBe("365d");
+ expect(formatTtl(31536000, zhT)).toBe("365天");
});
- it("formats 1d 1h 1m 1s", () => {
- expect(formatTtl(90061, enT)).toBe("1d 01:01:01");
- expect(formatTtl(90061, zhT)).toBe("1天 01:01:01");
+ it("formats 1d 1h 1m 1s by keeping only day and hour", () => {
+ expect(formatTtl(90061, enT)).toBe("1d 1h");
+ expect(formatTtl(90061, zhT)).toBe("1天 1小时");
});
- it("formats 2d 3h 4m 5s", () => {
+ it("formats 2d 3h 4m 5s by keeping only day and hour", () => {
const ttl = 2 * 86400 + 3 * 3600 + 4 * 60 + 5; // 183845
- expect(formatTtl(ttl, enT)).toBe("2d 03:04:05");
- expect(formatTtl(ttl, zhT)).toBe("2天 03:04:05");
- });
-});
-
-describe("formatTtl — Spanish locale", () => {
- it("formats sub-day values with no i18n", () => {
- expect(formatTtl(45, esT)).toBe("00:00:45");
- expect(formatTtl(3661, esT)).toBe("01:01:01");
- });
-
- it("formats multi-day with localized d", () => {
- expect(formatTtl(86400, esT)).toBe("1d 00:00:00");
- expect(formatTtl(604800, esT)).toBe("7d 00:00:00");
- });
-
- it("returns null for -1", () => {
- expect(formatTtl(-1, esT)).toBeNull();
- });
-
- it("returns null for 0", () => {
- expect(formatTtl(0, esT)).toBeNull();
+ expect(formatTtl(ttl, enT)).toBe("2d 3h");
+ expect(formatTtl(ttl, zhT)).toBe("2天 3小时");
});
});
describe("formatTtl — Italian locale", () => {
- it("formats sub-day values with no i18n", () => {
- expect(formatTtl(45, itT)).toBe("00:00:45");
- expect(formatTtl(3661, itT)).toBe("01:01:01");
+ it("formats multi-day with localized g", () => {
+ expect(formatTtl(86400, itT)).toBe("1g");
+ expect(formatTtl(604800, itT)).toBe("7g");
});
- it("formats multi-day with localized g", () => {
- expect(formatTtl(86400, itT)).toBe("1g 00:00:00");
- expect(formatTtl(604800, itT)).toBe("7g 00:00:00");
+ it("formats sub-day with localized units", () => {
+ expect(formatTtl(3661, itT)).toBe("1h 1m");
+ expect(formatTtl(45, itT)).toBe("45s");
});
it("returns null for -1", () => {
diff --git a/apps/desktop/src/lib/common/ttlFormat.ts b/apps/desktop/src/lib/common/ttlFormat.ts
index 1ddab936dc..3bca1a0ad7 100644
--- a/apps/desktop/src/lib/common/ttlFormat.ts
+++ b/apps/desktop/src/lib/common/ttlFormat.ts
@@ -1,7 +1,9 @@
/**
- * Formats Redis TTL (seconds) as a compact string:
- * < 1 day → HH:mm:ss
- * >= 1 day → {n}d HH:mm:ss (day unit localized)
+ * Formats Redis TTL (seconds) as a compact human-readable remaining time:
+ * 从大到小取前两个非零单位,例如:
+ * 45 → 45s / 45秒
+ * 3661 → 1h 1m / 1小时 1分钟
+ * 93784 → 1d 2h / 1天 2小时
*
* Returns null for ttl === -1 (no expiry) or ttl <= 0.
*/
@@ -17,10 +19,17 @@ export function formatTtl(ttl: number, t: TranslateFn): string | null {
const minutes = Math.floor((ttl % 3_600) / 60);
const seconds = ttl % 60;
- const time = [String(hours).padStart(2, "0"), String(minutes).padStart(2, "0"), String(seconds).padStart(2, "0")].join(":");
+ // 按从大到小排列四个单位,只保留前两个非零单位,避免展示过长
+ const units: Array<[number, string]> = [
+ [days, "redis.ttlDay"],
+ [hours, "redis.ttlHour"],
+ [minutes, "redis.ttlMinute"],
+ [seconds, "redis.ttlSecond"],
+ ];
- if (days > 0) {
- return `${t("redis.ttlDay", { count: days })} ${time}`;
- }
- return time;
+ return units
+ .filter(([value]) => value > 0)
+ .slice(0, 2)
+ .map(([value, key]) => t(key, { count: value }))
+ .join(" ");
}
diff --git a/crates/dbx-core/src/db/redis_driver.rs b/crates/dbx-core/src/db/redis_driver.rs
index 857422c5b3..272dbad476 100644
--- a/crates/dbx-core/src/db/redis_driver.rs
+++ b/crates/dbx-core/src/db/redis_driver.rs
@@ -2074,8 +2074,8 @@ where
/// Batch-scan keys with server-side multi-SCAN support.
///
-/// Performs up to `max_iterations` SCAN cycles in a single call. TYPE metadata
-/// is optional so large key-name searches can avoid extra Redis work.
+/// Performs up to `max_iterations` SCAN cycles in a single call. TYPE and TTL
+/// metadata is optional so large key-name searches can avoid extra Redis work.
/// DBSIZE is only called on the first iteration (cursor == 0).
pub async fn scan_keys_batch<C>(
con: &mut C,
@@ -2116,6 +2116,13 @@ where
} else {
String::new()
};
+ // 精确命中单个 key 时顺带查询一次 TTL(O(1) 命令),
+ // 让前端列表行无需再点开 key 就能看到过期信息。
+ let key_ttl: i64 = if include_types {
+ redis::cmd("TTL").arg(pattern).query_async(con).await.unwrap_or(-2)
+ } else {
+ -2
+ };
let value_preview = if include_types { redis_key_value_preview(&key_type) } else { String::new() };
@@ -2123,7 +2130,7 @@ where
key_display: redis_key_bytes_to_display(pattern.as_bytes()),
key_raw: redis_key_bytes_to_raw(pattern.as_bytes()),
key_type,
- ttl: -2,
+ ttl: key_ttl,
size: 0,
value_preview,
};
@@ -2154,14 +2161,28 @@ where
let (next_cursor, keys) = parse_scan_keys(raw)?;
if !keys.is_empty() {
- let key_types: Vec<String> = if include_types {
- let mut pipe = redis::pipe();
+ let (key_types, key_ttls): (Vec<String>, Vec<i64>) = if include_types {
+ let mut type_pipe = redis::pipe();
+ for key in &keys {
+ type_pipe.cmd("TYPE").arg(key);
+ }
+ let type_count = type_pipe.len();
+ let type_values = con.req_packed_commands(&type_pipe, 0, type_count).await.unwrap_or_default();
+ let key_types = type_values
+ .iter()
+ .map(|value| String::from_redis_value(value).unwrap_or_else(|_| "unknown".to_string()))
+ .collect();
+
+ let mut ttl_pipe = redis::pipe();
for key in &keys {
- pipe.cmd("TYPE").arg(key);
+ ttl_pipe.cmd("TTL").arg(key);
}
- pipe.query_async(con).await.unwrap_or_default()
+ let ttl_count = ttl_pipe.len();
+ let ttl_values = con.req_packed_commands(&ttl_pipe, 0, ttl_count).await.unwrap_or_default();
+ let key_ttls = ttl_values.iter().map(|value| i64::from_redis_value(value).unwrap_or(-2)).collect();
+ (key_types, key_ttls)
} else {
- Vec::new()
+ (Vec::new(), Vec::new())
};
for (index, key) in keys.iter().enumerate() {
@@ -2179,7 +2200,7 @@ where
key_display: redis_key_bytes_to_display(key),
key_raw: redis_key_bytes_to_raw(key),
key_type,
- ttl: -2,
+ ttl: key_ttls.get(index).copied().unwrap_or(-2),
size: 0,
value_preview,
});
@@ -4360,6 +4381,85 @@ mod tests {
assert_eq!(con.command_count("SCAN"), 2);
}
+ #[tokio::test]
+ async fn scan_keys_batch_batches_type_and_ttl_metadata() {
+ let mut con = FakeRedisConnection::new(vec![
+ RedisRawValue::Int(2),
+ scan_response("0", vec!["session:a", "cache:b"]),
+ RedisRawValue::SimpleString("string".to_string()),
+ RedisRawValue::SimpleString("hash".to_string()),
+ RedisRawValue::Int(-1),
+ RedisRawValue::Int(3600),
+ ]);
+
+ let result = super::scan_keys_batch(&mut con, 0, "*", 100, 1, true).await.unwrap();
+
+ assert_eq!(result.keys.len(), 2);
+ assert_eq!(result.keys[0].key_type, "string");
+ assert_eq!(result.keys[0].ttl, -1);
+ assert_eq!(result.keys[1].key_type, "hash");
+ assert_eq!(result.keys[1].ttl, 3600);
+ let type_pipeline = con.commands.iter().find(|packed| packed.contains("\r\nTYPE\r\n")).unwrap();
+ let ttl_pipeline = con.commands.iter().find(|packed| packed.contains("\r\nTTL\r\n")).unwrap();
+ assert_eq!(type_pipeline.matches("\r\nTYPE\r\n").count(), 2);
+ assert_eq!(type_pipeline.matches("\r\nTTL\r\n").count(), 0);
+ assert_eq!(ttl_pipeline.matches("\r\nTYPE\r\n").count(), 0);
+ assert_eq!(ttl_pipeline.matches("\r\nTTL\r\n").count(), 2);
+ }
+
+ #[tokio::test]
+ async fn scan_keys_batch_preserves_types_when_one_ttl_command_fails() {
+ let mut con = FakeRedisConnection::new(vec![
+ RedisRawValue::Int(2),
+ scan_response("0", vec!["session:a", "cache:b"]),
+ RedisRawValue::SimpleString("string".to_string()),
+ RedisRawValue::SimpleString("hash".to_string()),
+ redis::parse_redis_value(b"-NOPERM this user has no permissions to run the 'ttl' command\r\n").unwrap(),
+ RedisRawValue::Int(3600),
+ ]);
+
+ let result = super::scan_keys_batch(&mut con, 0, "*", 100, 1, true).await.unwrap();
+
+ assert_eq!(result.keys.len(), 2);
+ assert_eq!(result.keys[0].key_type, "string");
+ assert_eq!(result.keys[0].ttl, -2);
+ assert_eq!(result.keys[1].key_type, "hash");
+ assert_eq!(result.keys[1].ttl, 3600);
+ }
+
+ #[tokio::test]
+ async fn scan_keys_batch_skips_type_and_ttl_when_metadata_disabled() {
+ // include_types=false 是“加载全部”的百万 key 链路,不能多发出任何 TYPE/TTL 命令
+ let mut con = FakeRedisConnection::new(vec![RedisRawValue::Int(1), scan_response("0", vec!["cache:b"])]);
+
+ let result = super::scan_keys_batch(&mut con, 0, "*", 100, 1, false).await.unwrap();
+
+ assert_eq!(result.keys.len(), 1);
+ assert_eq!(result.keys[0].key_type, "");
+ assert_eq!(result.keys[0].ttl, -2);
+ assert_eq!(con.command_count("TYPE"), 0);
+ assert_eq!(con.command_count("TTL"), 0);
+ }
+
+ #[tokio::test]
+ async fn scan_keys_batch_exact_match_returns_ttl() {
+ let mut con = FakeRedisConnection::new(vec![
+ RedisRawValue::Int(1),
+ RedisRawValue::Int(1),
+ RedisRawValue::SimpleString("string".to_string()),
+ RedisRawValue::Int(-1),
+ ]);
+
+ let result = super::scan_keys_batch(&mut con, 0, "session:a", 100, 1, true).await.unwrap();
+
+ assert_eq!(result.keys.len(), 1);
+ assert_eq!(result.keys[0].key_display, "session:a");
+ assert_eq!(result.keys[0].key_type, "string");
+ assert_eq!(result.keys[0].ttl, -1);
+ assert_eq!(con.command_count("EXISTS"), 1);
+ assert_eq!(con.command_count("TTL"), 1);
+ }
+
#[tokio::test]
async fn cluster_key_batch_reuses_node_connections_across_scan_iterations() {
let sessions = tokio::sync::Mutex::new(super::RedisClusterScanSessions::default());
diff --git a/crates/dbx-core/src/redis_ops.rs b/crates/dbx-core/src/redis_ops.rs
index 5549343b22..16f62c3207 100644
--- a/crates/dbx-core/src/redis_ops.rs
+++ b/crates/dbx-core/src/redis_ops.rs
@@ -42,7 +42,7 @@ pub async fn redis_scan_keys_core(
///
/// Performs up to `max_iterations` SCAN cycles server-side in a single API
/// call, dramatically reducing frontend↔backend roundtrips when fetching many
-/// keys (e.g. "fetch all" in the key browser). TYPE metadata is optional.
+/// keys (e.g. "fetch all" in the key browser). TYPE and TTL metadata is optional.
pub async fn redis_scan_keys_batch_core(
state: &AppState,
connection_id: &str,