feat(redis): support database aliases
This commit is contained in:
1 parent
5309170bf7
commit
4a6422365b
39 files changed
+443
-9
No files matched your search
@@ -0,0 +1,145 @@
|
||||
import { createPinia, setActivePinia } from "pinia";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { ConnectionConfig, TreeNode } from "@/types/database";
|
||||
|
||||
function installLocalStorage() {
|
||||
const data = new Map<string, string>();
|
||||
vi.stubGlobal("localStorage", {
|
||||
getItem: vi.fn((key: string) => data.get(key) ?? null),
|
||||
setItem: vi.fn((key: string, value: string) => data.set(key, value)),
|
||||
removeItem: vi.fn((key: string) => data.delete(key)),
|
||||
});
|
||||
}
|
||||
|
||||
function redisConnection(): ConnectionConfig {
|
||||
return {
|
||||
id: "redis-1",
|
||||
name: "Redis",
|
||||
db_type: "redis",
|
||||
host: "127.0.0.1",
|
||||
port: 6379,
|
||||
username: "",
|
||||
password: "",
|
||||
database: "0",
|
||||
};
|
||||
}
|
||||
|
||||
function seedRedisTree(store: { treeNodes: TreeNode[] }) {
|
||||
store.treeNodes.push({
|
||||
id: "redis-1",
|
||||
label: "Redis",
|
||||
type: "connection",
|
||||
connectionId: "redis-1",
|
||||
children: [
|
||||
{
|
||||
id: "redis-1:db3",
|
||||
label: "db3 (12)",
|
||||
type: "redis-db",
|
||||
connectionId: "redis-1",
|
||||
database: "3",
|
||||
loadedKeyCount: 0,
|
||||
totalKeyCount: 12,
|
||||
children: [],
|
||||
},
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
describe("connectionStore Redis database aliases", () => {
|
||||
beforeEach(() => {
|
||||
vi.resetModules();
|
||||
vi.unstubAllGlobals();
|
||||
installLocalStorage();
|
||||
setActivePinia(createPinia());
|
||||
});
|
||||
|
||||
it("persists an alias without disconnecting and keeps it during count refreshes", async () => {
|
||||
const saveConnections = vi.fn().mockResolvedValue(undefined);
|
||||
vi.doMock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));
|
||||
vi.doMock("@/lib/backend/api", () => ({
|
||||
saveConnections,
|
||||
saveSidebarLayout: vi.fn().mockResolvedValue(undefined),
|
||||
deleteSchemaCachePrefix: vi.fn().mockResolvedValue(undefined),
|
||||
loadSchemaCache: vi.fn().mockResolvedValue(null),
|
||||
saveSchemaCache: vi.fn().mockResolvedValue(undefined),
|
||||
}));
|
||||
|
||||
const { useConnectionStore } = await import("@/stores/connectionStore");
|
||||
const store = useConnectionStore();
|
||||
store.addEphemeralConnection(redisConnection());
|
||||
seedRedisTree(store);
|
||||
|
||||
await store.setRedisDatabaseAlias("redis-1", "3", " orders ");
|
||||
|
||||
expect(store.getRedisDatabaseAlias("redis-1", 3)).toBe("orders");
|
||||
expect(store.connectedIds.has("redis-1")).toBe(true);
|
||||
expect(store.treeNodes[0].children?.[0].label).toBe("db3 · orders (12)");
|
||||
expect(saveConnections).toHaveBeenLastCalledWith([
|
||||
expect.objectContaining({
|
||||
id: "redis-1",
|
||||
redis_database_aliases: { "3": "orders" },
|
||||
}),
|
||||
]);
|
||||
|
||||
store.updateRedisDbKeyStats("redis-1", 3, { total: 15 });
|
||||
expect(store.treeNodes[0].children?.[0].label).toBe("db3 · orders (15)");
|
||||
});
|
||||
|
||||
it("clears an alias and removes the empty map from persisted config", async () => {
|
||||
const saveConnections = vi.fn().mockResolvedValue(undefined);
|
||||
vi.doMock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));
|
||||
vi.doMock("@/lib/backend/api", () => ({
|
||||
saveConnections,
|
||||
saveSidebarLayout: vi.fn().mockResolvedValue(undefined),
|
||||
deleteSchemaCachePrefix: vi.fn().mockResolvedValue(undefined),
|
||||
loadSchemaCache: vi.fn().mockResolvedValue(null),
|
||||
saveSchemaCache: vi.fn().mockResolvedValue(undefined),
|
||||
}));
|
||||
|
||||
const { useConnectionStore } = await import("@/stores/connectionStore");
|
||||
const store = useConnectionStore();
|
||||
store.addEphemeralConnection({
|
||||
...redisConnection(),
|
||||
redis_database_aliases: { "3": "orders" },
|
||||
});
|
||||
seedRedisTree(store);
|
||||
|
||||
await store.setRedisDatabaseAlias("redis-1", 3);
|
||||
|
||||
expect(store.getRedisDatabaseAlias("redis-1", 3)).toBeUndefined();
|
||||
expect(store.treeNodes[0].children?.[0].label).toBe("db3 (12)");
|
||||
expect(saveConnections).toHaveBeenLastCalledWith([
|
||||
expect.objectContaining({
|
||||
id: "redis-1",
|
||||
redis_database_aliases: undefined,
|
||||
}),
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps aliases for one-time Redis connections in memory without persisting secrets", async () => {
|
||||
const saveConnections = vi.fn().mockResolvedValue(undefined);
|
||||
vi.doMock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));
|
||||
vi.doMock("@/lib/backend/api", () => ({
|
||||
saveConnections,
|
||||
saveSidebarLayout: vi.fn().mockResolvedValue(undefined),
|
||||
deleteSchemaCachePrefix: vi.fn().mockResolvedValue(undefined),
|
||||
loadSchemaCache: vi.fn().mockResolvedValue(null),
|
||||
saveSchemaCache: vi.fn().mockResolvedValue(undefined),
|
||||
}));
|
||||
|
||||
const { useConnectionStore } = await import("@/stores/connectionStore");
|
||||
const store = useConnectionStore();
|
||||
store.addEphemeralConnection({
|
||||
...redisConnection(),
|
||||
one_time: true,
|
||||
password: "one-time-secret",
|
||||
});
|
||||
seedRedisTree(store);
|
||||
|
||||
await store.setRedisDatabaseAlias("redis-1", 3, "orders");
|
||||
|
||||
expect(store.getRedisDatabaseAlias("redis-1", 3)).toBe("orders");
|
||||
expect(store.connections[0]).toEqual(expect.objectContaining({ password: "one-time-secret", redis_database_aliases: { "3": "orders" } }));
|
||||
expect(saveConnections).toHaveBeenLastCalledWith([]);
|
||||
});
|
||||
});
|
||||
@@ -102,6 +102,7 @@ import { toMongoCollectionKind } from "@/lib/sidebar/mongoCollectionMutation";
|
||||
import { completionSchemasFromTree, completionTablesFromTree } from "@/lib/metadata/completionTreeIndex";
|
||||
import { kvRootNodeLabel } from "@/lib/kv/kvRootPresentation";
|
||||
import { REDIS_SCAN_PAGE_SIZE_DEFAULT } from "@/lib/redis/redisKeyPattern";
|
||||
import { normalizeRedisDatabaseAliases, redisDatabaseAlias, redisDatabaseLabel } from "@/lib/redis/redisDatabaseAlias";
|
||||
import { appendAgentDriverUpdateHint, hasAgentDriverUpdate, hasInstalledAgentVersion, type AgentDriverInstallState } from "@/lib/connection/agentDriverInstallHint";
|
||||
import { appendConnectionErrorHints } from "@/lib/connection/connectionErrorHints";
|
||||
import { appendVisibleDatabaseSelection } from "@/lib/connection/connectionVisibleDatabases";
|
||||
@@ -286,11 +287,6 @@ type BeforeConnectHandler = (config: ConnectionConfig) => Promise<void>;
|
||||
|
||||
export const CONNECTION_ATTEMPT_CANCELLED_MESSAGE = "Connection attempt was cancelled";
|
||||
|
||||
function redisDbLabel(db: number, _loadedKeyCount?: number, totalKeyCount?: number): string {
|
||||
if (totalKeyCount == null) return `db${db}`;
|
||||
return `db${db} (${totalKeyCount})`;
|
||||
}
|
||||
|
||||
function metadataDriverProfile(config?: ConnectionConfig): string | undefined {
|
||||
return config?.driver_profile || config?.db_type;
|
||||
}
|
||||
@@ -1033,6 +1029,7 @@ export const useConnectionStore = defineStore("connection", () => {
|
||||
query_timeout_secs: config.query_timeout_secs ?? 30,
|
||||
idle_timeout_secs: config.idle_timeout_secs ?? 60,
|
||||
keepalive_interval_secs: config.keepalive_interval_secs ?? DEFAULT_KEEPALIVE_INTERVAL_SECS,
|
||||
redis_database_aliases: normalizeRedisDatabaseAliases(config.redis_database_aliases),
|
||||
database_info: normalizeDatabaseConnectionInfo(config.database_info),
|
||||
};
|
||||
}
|
||||
@@ -2389,6 +2386,37 @@ export const useConnectionStore = defineStore("connection", () => {
|
||||
return config?.database === database && database !== "";
|
||||
}
|
||||
|
||||
function getRedisDatabaseAlias(connectionId: string, database: string | number): string | undefined {
|
||||
return redisDatabaseAlias(getConfig(connectionId)?.redis_database_aliases, database);
|
||||
}
|
||||
|
||||
async function setRedisDatabaseAlias(connectionId: string, database: string | number, alias?: string) {
|
||||
const index = typeof database === "number" ? database : Number(database);
|
||||
const configIndex = connections.value.findIndex((connection) => connection.id === connectionId);
|
||||
const config = connections.value[configIndex];
|
||||
if (!config || config.db_type !== "redis" || !Number.isInteger(index) || index < 0) return;
|
||||
|
||||
const key = String(index);
|
||||
const aliases = { ...(config.redis_database_aliases || {}) };
|
||||
const normalizedAlias = alias?.trim() || "";
|
||||
if (normalizedAlias) aliases[key] = normalizedAlias;
|
||||
else delete aliases[key];
|
||||
|
||||
const redisDatabaseAliases = normalizeRedisDatabaseAliases(aliases);
|
||||
const nextConnections = [...connections.value];
|
||||
nextConnections[configIndex] = {
|
||||
...config,
|
||||
redis_database_aliases: redisDatabaseAliases,
|
||||
};
|
||||
await persistConnections(nextConnections);
|
||||
connections.value = nextConnections;
|
||||
|
||||
const node = findNode(treeNodes.value, `${connectionId}:db${key}`);
|
||||
if (node?.type === "redis-db") {
|
||||
node.label = redisDatabaseLabel(index, redisDatabaseAliases, node.totalKeyCount);
|
||||
}
|
||||
}
|
||||
|
||||
async function setVisibleDatabases(connectionId: string, databaseNames: string[]) {
|
||||
const config = getConfig(connectionId);
|
||||
if (!config) return;
|
||||
@@ -3041,7 +3069,7 @@ export const useConnectionStore = defineStore("connection", () => {
|
||||
.filter((db) => visibleNameSet.has(String(db.db)))
|
||||
.map((db) => ({
|
||||
id: `${connectionId}:db${db.db}`,
|
||||
label: redisDbLabel(db.db, 0, db.keys),
|
||||
label: redisDatabaseLabel(db.db, config?.redis_database_aliases, db.keys),
|
||||
type: "redis-db" as const,
|
||||
connectionId,
|
||||
database: String(db.db),
|
||||
@@ -3251,7 +3279,7 @@ export const useConnectionStore = defineStore("connection", () => {
|
||||
if (stats.totalDelta != null && node.totalKeyCount != null) {
|
||||
node.totalKeyCount = Math.max(0, node.totalKeyCount + stats.totalDelta);
|
||||
}
|
||||
node.label = redisDbLabel(db, node.loadedKeyCount, node.totalKeyCount);
|
||||
node.label = redisDatabaseLabel(db, getConfig(connectionId)?.redis_database_aliases, node.totalKeyCount);
|
||||
}
|
||||
|
||||
// Re-fetch the authoritative per-db key counts (INFO keyspace, lightweight) and update
|
||||
@@ -5890,7 +5918,7 @@ export const useConnectionStore = defineStore("connection", () => {
|
||||
}
|
||||
|
||||
async function persistConnections(nextConnections: ConnectionConfig[] = connections.value) {
|
||||
await api.saveConnections(nextConnections);
|
||||
await api.saveConnections(nextConnections.filter((connection) => connection.one_time !== true));
|
||||
}
|
||||
|
||||
function persistSidebarLayoutDebounced() {
|
||||
@@ -6462,6 +6490,8 @@ export const useConnectionStore = defineStore("connection", () => {
|
||||
setDefaultDatabase,
|
||||
clearDefaultDatabase,
|
||||
isDefaultDatabase,
|
||||
getRedisDatabaseAlias,
|
||||
setRedisDatabaseAlias,
|
||||
setVisibleDatabases,
|
||||
clearVisibleDatabases,
|
||||
ensureVisibleDatabase,
|
||||
|
||||
Reference in new issue
Block a user