diff --git a/apps/desktop/src/components/redis/RedisValueViewer.vue b/apps/desktop/src/components/redis/RedisValueViewer.vue index 1dc5bc7f97..c1d2cb29dd 100644 --- a/apps/desktop/src/components/redis/RedisValueViewer.vue +++ b/apps/desktop/src/components/redis/RedisValueViewer.vue @@ -5,7 +5,7 @@ import type { CalendarDateTime } from "@internationalized/date"; import { useI18n } from "vue-i18n"; import { onClickOutside } from "@vueuse/core"; import { DynamicScroller, DynamicScrollerItem, RecycleScroller } from "vue-virtual-scroller"; -import { Check, ChevronDown, Copy, ClipboardCopy, Eye, Trash2, Save, RefreshCw, Plus, Loader2, Pencil, WrapText, ArrowUp, ArrowDown, ArrowUpDown, Search, X, FileArchive } from "@lucide/vue"; +import { Check, ChevronDown, Copy, ClipboardCopy, Eye, Trash2, Save, RefreshCw, Plus, Loader2, Pencil, WrapText, ArrowUp, ArrowDown, ArrowUpDown, Search, X, FileArchive, Download } from "@lucide/vue"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Badge } from "@/components/ui/badge"; @@ -69,6 +69,7 @@ import { unixSecondsToCalendarDateTime } from "@/components/ui/date-time-picker/ import { applyRedisExpiryPolicy, type RedisExpiryMode, redisExpiryModeForTtl, validateRedisExpiry } from "@/lib/redis/redisExpiry"; import { redisKeyRawToText, redisKeyTextToDisplay, redisKeyTextToRaw } from "@/lib/redis/redisCommandSession"; import { formatBytes } from "@/lib/database/serverMetrics"; +import { isTauriRuntime } from "@/lib/backend/tauriRuntime"; const { t, locale } = useI18n(); const { toast } = useToast(); @@ -103,6 +104,7 @@ const REDIS_COLLECTION_ROW_HEIGHT = 32; const REDIS_STREAM_MIN_ROW_HEIGHT = 96; const data = ref(null); const loading = ref(false); +const downloadingLargeValue = ref(false); const loadingMore = ref(false); const showRenameKeyDialog = ref(false); const renamingKey = ref(false); @@ -674,6 +676,46 @@ const largeStringPreviewHint = computed(() => { } return t("redis.largeStringPreviewHintUnknown", { loaded: formatBytes(loaded) }); }); + +function redisDownloadFileName(keyDisplay: string, encoding: RedisBlob["encoding"]): string { + const safe = + keyDisplay + .replace(/[\\/:*?"<>|\u0000-\u001f]/g, "_") + .trim() + .slice(0, 120) || "redis-value"; + return `${safe}.${encoding === "utf8" ? "txt" : "bin"}`; +} + +async function downloadLargeValue() { + if (downloadingLargeValue.value || !isStringValueTruncated.value) return; + downloadingLargeValue.value = true; + try { + const blob = await api.redisGetRawValue(props.connectionId, props.db, props.keyRaw); + const bytes = decodeRedisBlob(blob); + const filename = redisDownloadFileName(props.keyDisplay, blob.encoding); + if (isTauriRuntime()) { + const [{ save }, { writeFile }] = await Promise.all([import("@tauri-apps/plugin-dialog"), import("@tauri-apps/plugin-fs")]); + const extension = blob.encoding === "utf8" ? "txt" : "bin"; + const path = await save({ defaultPath: filename, filters: [{ name: t(blob.encoding === "utf8" ? "redis.downloadValueTextFileType" : "redis.downloadValueFileType"), extensions: [extension] }] }); + if (path) { + await writeFile(path, bytes); + toast(t("redis.downloadValueSuccess"), 2500); + } + } else { + const url = URL.createObjectURL(new Blob([bytes.slice().buffer as ArrayBuffer], { type: blob.encoding === "utf8" ? "text/plain;charset=utf-8" : "application/octet-stream" })); + const anchor = document.createElement("a"); + anchor.href = url; + anchor.download = filename; + anchor.click(); + URL.revokeObjectURL(url); + toast(t("redis.downloadValueSuccess"), 2500); + } + } catch (error) { + toast(errorMessage(error), 4000); + } finally { + downloadingLargeValue.value = false; + } +} const streamRows = computed(() => { if (redisKind.value !== "stream") return []; return streamEntries.value.map((entry, index) => ({ @@ -2953,7 +2995,12 @@ useUpdateBlocker(() => (hasUnsavedRedisDraft.value || editingTtl.value || saving
{{ detailTextForFormat(stringValueDetail, stringValueView) }}
- {{ largeStringPreviewHint }} + {{ largeStringPreviewHint }} +
{{ t("redis.binaryStringReadonlyHint") }} diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.ts index 31796e538a..e2fbf3e42c 100644 --- a/apps/desktop/src/i18n/locales/en.ts +++ b/apps/desktop/src/i18n/locales/en.ts @@ -6171,6 +6171,10 @@ export default { unsupportedValueTypeHint: "This is a proprietary type of kvrocks-compatible servers; DBX has not adapted it yet", largeStringPreviewHint: "This value is large. Only the first {loaded} of {total} is loaded, and the preview is read-only.", largeStringPreviewHintUnknown: "This value is large. Only the first {loaded} is loaded, and the preview is read-only.", + downloadValue: "Download full value", + downloadValueFileType: "Redis value", + downloadValueTextFileType: "Text file", + downloadValueSuccess: "Redis value downloaded", largeStringPreviewActionUnavailable: "Large-value previews cannot be copied, decoded, or used to generate insert statements", selectedKeys: "Selected keys", selectAllLoaded: "Select all", diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.ts index ea1215ccfb..2b1dbc0b6b 100644 --- a/apps/desktop/src/i18n/locales/es.ts +++ b/apps/desktop/src/i18n/locales/es.ts @@ -5776,6 +5776,10 @@ export default withEnglishFallback({ keySearchHistory: "Historial de búsqueda", keySearchHistoryForget: "Eliminar del historial", keySearchHistoryEmpty: "No hay historial", + downloadValue: "Descargar valor completo", + downloadValueFileType: "Valor de Redis", + downloadValueTextFileType: "Archivo de texto", + downloadValueSuccess: "Valor de Redis descargado", }, mongo: { documents: "{count} documentos", diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.ts index 4021c85a47..6052ec93aa 100644 --- a/apps/desktop/src/i18n/locales/it.ts +++ b/apps/desktop/src/i18n/locales/it.ts @@ -5698,6 +5698,10 @@ export default withEnglishFallback({ keySearchHistory: "Cronologia ricerche", keySearchHistoryForget: "Rimuovi dalla cronologia", keySearchHistoryEmpty: "Nessuna cronologia", + downloadValue: "Scarica valore completo", + downloadValueFileType: "Valore Redis", + downloadValueTextFileType: "File di testo", + downloadValueSuccess: "Valore Redis scaricato", }, mongo: { documents: "{count} documenti", diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.ts index 253941c71f..7cd5fe51b7 100644 --- a/apps/desktop/src/i18n/locales/ja.ts +++ b/apps/desktop/src/i18n/locales/ja.ts @@ -5726,6 +5726,10 @@ export default withEnglishFallback({ keySearchHistory: "検索履歴", keySearchHistoryForget: "履歴から削除", keySearchHistoryEmpty: "履歴はありません", + downloadValue: "完全な値をダウンロード", + downloadValueFileType: "Redis 値", + downloadValueTextFileType: "テキストファイル", + downloadValueSuccess: "Redis 値をダウンロードしました", }, mongo: { documents: "{count}ドキュメント", diff --git a/apps/desktop/src/i18n/locales/ko.ts b/apps/desktop/src/i18n/locales/ko.ts index 7ee400dccf..4506d77e0d 100644 --- a/apps/desktop/src/i18n/locales/ko.ts +++ b/apps/desktop/src/i18n/locales/ko.ts @@ -5361,6 +5361,10 @@ export default withEnglishFallback({ keySearchHistory: "검색 기록", keySearchHistoryForget: "기록에서 제거", keySearchHistoryEmpty: "검색 기록이 없습니다", + downloadValue: "전체 값 다운로드", + downloadValueFileType: "Redis 값", + downloadValueTextFileType: "텍스트 파일", + downloadValueSuccess: "Redis 값이 다운로드됨", }, mongo: { documents: "문서 {count}개", diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.ts index a45e0c0914..92036aa4ef 100644 --- a/apps/desktop/src/i18n/locales/pt-BR.ts +++ b/apps/desktop/src/i18n/locales/pt-BR.ts @@ -5700,6 +5700,10 @@ export default withEnglishFallback({ keySearchHistory: "Histórico de pesquisa", keySearchHistoryForget: "Remover do histórico", keySearchHistoryEmpty: "Nenhum histórico", + downloadValue: "Baixar valor completo", + downloadValueFileType: "Valor Redis", + downloadValueTextFileType: "Arquivo de texto", + downloadValueSuccess: "Valor Redis baixado", }, mongo: { documents: "{count} documentos", diff --git a/apps/desktop/src/i18n/locales/ru.ts b/apps/desktop/src/i18n/locales/ru.ts index ec7a627e15..cec950a856 100644 --- a/apps/desktop/src/i18n/locales/ru.ts +++ b/apps/desktop/src/i18n/locales/ru.ts @@ -6726,6 +6726,10 @@ export default withEnglishFallback({ keyspace: "Пространство ключей", }, }, + downloadValue: "Скачать полное значение", + downloadValueFileType: "Значение Redis", + downloadValueTextFileType: "Текстовый файл", + downloadValueSuccess: "Значение Redis скачано", }, mongoDump: { selectAll: "Выбрать все коллекции", diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.ts index b226067b85..684eb93a64 100644 --- a/apps/desktop/src/i18n/locales/zh-CN.ts +++ b/apps/desktop/src/i18n/locales/zh-CN.ts @@ -6144,6 +6144,10 @@ export default withEnglishFallback({ unsupportedValueTypeHint: "这是 kvrocks 等兼容服务的专有类型,DBX 尚未适配", largeStringPreviewHint: "值过大,仅加载前 {loaded}(共 {total})。预览为只读。", largeStringPreviewHintUnknown: "值过大,仅加载前 {loaded}。预览为只读。", + downloadValue: "下载完整值", + downloadValueFileType: "Redis 值", + downloadValueTextFileType: "文本文件", + downloadValueSuccess: "Redis 值已下载", largeStringPreviewActionUnavailable: "大值预览不支持复制、解码或生成插入语句", selectedKeys: "已选择的 key", selectAllLoaded: "全选", diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.ts index cbc61b9316..9abe307db9 100644 --- a/apps/desktop/src/i18n/locales/zh-TW.ts +++ b/apps/desktop/src/i18n/locales/zh-TW.ts @@ -4829,6 +4829,10 @@ export default withEnglishFallback({ unsupportedValueTypeHint: "這是 kvrocks 等相容服務的專有類型,DBX 尚未支援", largeStringPreviewHint: "值過大,僅載入前 {loaded}(共 {total})。預覽為唯讀。", largeStringPreviewHintUnknown: "值過大,僅載入前 {loaded}。預覽為唯讀。", + downloadValue: "下載完整值", + downloadValueFileType: "Redis 值", + downloadValueTextFileType: "文字檔", + downloadValueSuccess: "Redis 值已下載", largeStringPreviewActionUnavailable: "大值預覽不支援複製、解碼或產生插入語句", selectedKeys: "已選擇的 key", selectAllLoaded: "全選", diff --git a/apps/desktop/src/lib/backend/api.ts b/apps/desktop/src/lib/backend/api.ts index 392ac2d337..5f1d6bdee7 100644 --- a/apps/desktop/src/lib/backend/api.ts +++ b/apps/desktop/src/lib/backend/api.ts @@ -583,6 +583,7 @@ export const redisScanKeys = forward("redisScanKeys"); export const redisScanKeysBatch = forward("redisScanKeysBatch"); export const redisScanValues = forward("redisScanValues"); export const redisGetValue = forward("redisGetValue"); +export const redisGetRawValue = forward("redisGetRawValue"); export const redisGetTtl = forward("redisGetTtl"); export const redisGetStreamEntries = forward("redisGetStreamEntries"); export const redisGetStreamGroups = forward("redisGetStreamGroups"); diff --git a/apps/desktop/src/lib/backend/http.ts b/apps/desktop/src/lib/backend/http.ts index 6a8630edaf..ee65ea2b5c 100644 --- a/apps/desktop/src/lib/backend/http.ts +++ b/apps/desktop/src/lib/backend/http.ts @@ -110,6 +110,7 @@ import type { DownloadedUpdate, UpdateDownloadSource, RedisCollectionPage, + RedisBlob, RedisDatabaseInfo, RedisStreamConsumer, RedisStreamGroup, @@ -3556,6 +3557,10 @@ export async function redisGetValue(connectionId: string, db: number, keyRaw: st return post("/api/redis/get-value", { connectionId, db, keyRaw }); } +export async function redisGetRawValue(connectionId: string, db: number, keyRaw: string): Promise { + return post("/api/redis/get-raw-value", { connectionId, db, keyRaw }); +} + export async function redisGetTtl(connectionId: string, db: number, keyRaw: string): Promise { return post("/api/redis/get-ttl", { connectionId, db, keyRaw }); } diff --git a/apps/desktop/src/lib/backend/tauri.ts b/apps/desktop/src/lib/backend/tauri.ts index d052b9cef4..9c9b53228f 100644 --- a/apps/desktop/src/lib/backend/tauri.ts +++ b/apps/desktop/src/lib/backend/tauri.ts @@ -3412,6 +3412,10 @@ export async function redisGetValue(connectionId: string, db: number, keyRaw: st return invoke("redis_get_value", { connectionId, db, keyRaw }); } +export async function redisGetRawValue(connectionId: string, db: number, keyRaw: string): Promise { + return invoke("redis_get_raw_value", { connectionId, db, keyRaw }); +} + export async function redisGetTtl(connectionId: string, db: number, keyRaw: string): Promise { return invoke("redis_get_ttl", { connectionId, db, keyRaw }); } diff --git a/crates/dbx-core/src/query/redis_ops.rs b/crates/dbx-core/src/query/redis_ops.rs index 2f3e179db8..0f8534669f 100644 --- a/crates/dbx-core/src/query/redis_ops.rs +++ b/crates/dbx-core/src/query/redis_ops.rs @@ -1,6 +1,6 @@ use crate::connection::{AppState, PoolKind}; use crate::db::redis_driver::{ - self, RedisCollectionPage, RedisCommandResult, RedisConnection, RedisDatabaseInfo, RedisKeysExpiry, + self, RedisBlob, RedisCollectionPage, RedisCommandResult, RedisConnection, RedisDatabaseInfo, RedisKeysExpiry, RedisKeysExpiryResult, RedisScanResult, RedisStreamConsumer, RedisStreamGroup, RedisStreamPage, RedisStreamPendingPage, RedisValue, }; @@ -134,6 +134,34 @@ pub async fn redis_get_value_in_db_core( } } +pub async fn redis_get_raw_value_in_db_core( + state: &AppState, + connection_id: &str, + db: u32, + key_raw: &str, +) -> Result { + ensure_redis_pool(state, connection_id).await?; + let pool = state.pool_handle(connection_id).await.ok_or("Connection not found")?; + match &pool { + PoolKind::Redis(redis) => { + let key = redis_driver::redis_key_raw_to_bytes(key_raw)?; + match redis.as_ref() { + RedisConnection::Direct(con) => { + let mut con = con.lock().await; + redis_driver::select_db(&mut *con, db).await?; + redis_driver::get_raw_value(&mut *con, &key).await + } + RedisConnection::Cluster(cluster) => { + redis_driver::ensure_cluster_db(db)?; + let mut con = redis_driver::cluster_key_connection(cluster, &key).await?; + redis_driver::get_raw_value(&mut con, &key).await + } + } + } + _ => Err("Not a Redis connection".to_string()), + } +} + /// Fetch only the TTL for a selected key. This avoids repeatedly loading a /// potentially large Redis value when the desktop detail view is polling. pub async fn redis_get_ttl_in_db_core( diff --git a/crates/dbx-driver-redis/src/lib.rs b/crates/dbx-driver-redis/src/lib.rs index 99c47f197f..6b9c0c6cca 100644 --- a/crates/dbx-driver-redis/src/lib.rs +++ b/crates/dbx-driver-redis/src/lib.rs @@ -2796,6 +2796,24 @@ where }) } +/// Read the complete raw payload for a Redis string-like key. +/// +/// The normal value path deliberately caps previews at 64 KiB. Downloads must +/// bypass that cap while preserving the exact bytes, including non-UTF-8 data. +pub async fn get_raw_value(con: &mut C, key: &[u8]) -> Result +where + C: ConnectionLike + Send + Sync + Unpin, +{ + let redis_type: String = redis::cmd("TYPE").arg(key).query_async(con).await.map_err(|e| e.to_string())?; + let raw: RedisRawValue = match redis_type.as_str() { + "string" | "bitmap" => redis::cmd("GET").arg(key).query_async(con).await.map_err(|e| e.to_string())?, + "none" => return Err("Redis key does not exist".to_string()), + _ => return Err("Only Redis string values can be downloaded".to_string()), + }; + let bytes = redis_value_to_bytes(raw).ok_or_else(|| "Redis value is not byte-addressable".to_string())?; + Ok(redis_blob_from_bytes(&bytes)) +} + /// Read only a key's TTL without loading its value or collection members. /// /// Redis returns `-2` for a missing key and `-1` for a key without an expiry; diff --git a/crates/dbx-web/src/main.rs b/crates/dbx-web/src/main.rs index 79ac7a3b7d..b523564f39 100644 --- a/crates/dbx-web/src/main.rs +++ b/crates/dbx-web/src/main.rs @@ -830,6 +830,7 @@ async fn serve() { .route("/redis/scan-keys-batch", post(routes::redis::scan_keys_batch)) .route("/redis/scan-values", post(routes::redis::scan_values)) .route("/redis/get-value", post(routes::redis::get_value)) + .route("/redis/get-raw-value", post(routes::redis::get_raw_value)) .route("/redis/get-ttl", post(routes::redis::get_ttl)) .route("/redis/get-stream-entries", post(routes::redis::get_stream_entries)) .route("/redis/get-stream-groups", post(routes::redis::get_stream_groups)) diff --git a/crates/dbx-web/src/routes/redis.rs b/crates/dbx-web/src/routes/redis.rs index 6ccaf154e3..898b3f9cf7 100644 --- a/crates/dbx-web/src/routes/redis.rs +++ b/crates/dbx-web/src/routes/redis.rs @@ -411,6 +411,17 @@ pub async fn get_value( Ok(Json(serde_json::to_value(result).map_err(|e| AppError::from(e.to_string()))?)) } +pub async fn get_raw_value( + State(state): State>, + Json(req): Json, +) -> Result, AppError> { + let result = + dbx_core::redis_ops::redis_get_raw_value_in_db_core(&state.app, &req.connection_id, req.db, &req.key_raw) + .await + .map_err(AppError::from)?; + Ok(Json(serde_json::to_value(result).map_err(|e| AppError::from(e.to_string()))?)) +} + pub async fn get_ttl( State(state): State>, Json(req): Json, diff --git a/src-tauri/src/commands/redis_cmd.rs b/src-tauri/src/commands/redis_cmd.rs index d193c676a8..8faf16233c 100644 --- a/src-tauri/src/commands/redis_cmd.rs +++ b/src-tauri/src/commands/redis_cmd.rs @@ -3,7 +3,7 @@ use tauri::State; use crate::commands::connection::{ensure_connection_writable, AppState}; use dbx_core::db::redis_driver::{ - classify_command, parse_command_argv, RedisCollectionPage, RedisCommandResult, RedisCommandSafety, + classify_command, parse_command_argv, RedisBlob, RedisCollectionPage, RedisCommandResult, RedisCommandSafety, RedisDatabaseInfo, RedisKeysExpiryResult, RedisScanResult, RedisStreamConsumer, RedisStreamGroup, RedisStreamPage, RedisStreamPendingPage, RedisValue, }; @@ -87,6 +87,16 @@ pub async fn redis_get_value( dbx_core::redis_ops::redis_get_value_in_db_core(&state, &connection_id, db, &key_raw).await } +#[tauri::command] +pub async fn redis_get_raw_value( + state: State<'_, Arc>, + connection_id: String, + db: u32, + key_raw: String, +) -> Result { + dbx_core::redis_ops::redis_get_raw_value_in_db_core(&state, &connection_id, db, &key_raw).await +} + #[tauri::command] pub async fn redis_get_ttl( state: State<'_, Arc>, diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 13b4633fd7..104747799a 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -2174,6 +2174,7 @@ pub fn run() { commands::redis_cmd::redis_scan_keys_batch, commands::redis_cmd::redis_scan_values, commands::redis_cmd::redis_get_value, + commands::redis_cmd::redis_get_raw_value, commands::redis_cmd::redis_get_ttl, commands::redis_cmd::redis_get_stream_entries, commands::redis_cmd::redis_get_stream_groups,