Add Redis cluster support and improve key loading
This commit is contained in:
Generated
+9
@@ -1445,6 +1445,12 @@ dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "crc16"
|
||||
version = "0.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "338089f42c427b86394a5ee60ff321da23a5c89c9d89514c829687b26359fcff"
|
||||
|
||||
[[package]]
|
||||
name = "crc32fast"
|
||||
version = "1.5.0"
|
||||
@@ -6002,8 +6008,11 @@ dependencies = [
|
||||
"bytes",
|
||||
"cfg-if",
|
||||
"combine",
|
||||
"crc16",
|
||||
"futures-sink",
|
||||
"futures-util",
|
||||
"itoa",
|
||||
"log",
|
||||
"num-bigint",
|
||||
"percent-encoding",
|
||||
"pin-project-lite",
|
||||
|
||||
@@ -105,6 +105,7 @@ const defaultForm = (): Omit<ConnectionConfig, "id"> => ({
|
||||
redis_sentinel_username: "",
|
||||
redis_sentinel_password: "",
|
||||
redis_sentinel_tls: false,
|
||||
redis_cluster_nodes: "",
|
||||
});
|
||||
|
||||
const form = ref(defaultForm());
|
||||
@@ -362,6 +363,7 @@ watch(
|
||||
redis_sentinel_username: config.redis_sentinel_username || "",
|
||||
redis_sentinel_password: config.redis_sentinel_password || "",
|
||||
redis_sentinel_tls: config.redis_sentinel_tls || false,
|
||||
redis_cluster_nodes: config.redis_cluster_nodes || "",
|
||||
};
|
||||
selectedType.value = profile;
|
||||
mongoUseUrl.value = !!config.connection_string;
|
||||
@@ -753,15 +755,29 @@ function connectionConfigForSubmit(id: string): ConnectionConfig {
|
||||
config.redis_sentinel_username = undefined;
|
||||
config.redis_sentinel_password = undefined;
|
||||
config.redis_sentinel_tls = undefined;
|
||||
config.redis_cluster_nodes = undefined;
|
||||
} else if (config.redis_connection_mode === "sentinel") {
|
||||
config.redis_sentinel_master = config.redis_sentinel_master?.trim() || "";
|
||||
config.redis_sentinel_nodes = normalizeRedisSentinelNodes(config.redis_sentinel_nodes || "");
|
||||
config.redis_sentinel_username = config.redis_sentinel_username?.trim() || "";
|
||||
config.redis_cluster_nodes = undefined;
|
||||
const firstNode = firstRedisSentinelEndpoint(config.redis_sentinel_nodes);
|
||||
if (firstNode) {
|
||||
config.host = firstNode.host;
|
||||
config.port = firstNode.port;
|
||||
}
|
||||
} else if (config.redis_connection_mode === "cluster") {
|
||||
config.redis_sentinel_master = undefined;
|
||||
config.redis_sentinel_nodes = undefined;
|
||||
config.redis_sentinel_username = undefined;
|
||||
config.redis_sentinel_password = undefined;
|
||||
config.redis_sentinel_tls = undefined;
|
||||
config.redis_cluster_nodes = normalizeRedisClusterNodes(config.redis_cluster_nodes || "");
|
||||
const firstNode = firstRedisClusterEndpoint(config.redis_cluster_nodes);
|
||||
if (firstNode) {
|
||||
config.host = firstNode.host;
|
||||
config.port = firstNode.port;
|
||||
}
|
||||
} else {
|
||||
config.redis_connection_mode = "standalone";
|
||||
config.redis_sentinel_master = undefined;
|
||||
@@ -769,6 +785,7 @@ function connectionConfigForSubmit(id: string): ConnectionConfig {
|
||||
config.redis_sentinel_username = undefined;
|
||||
config.redis_sentinel_password = undefined;
|
||||
config.redis_sentinel_tls = undefined;
|
||||
config.redis_cluster_nodes = undefined;
|
||||
}
|
||||
if (config.db_type !== "mysql" && config.db_type !== "clickhouse") {
|
||||
config.ca_cert_path = undefined;
|
||||
@@ -875,6 +892,14 @@ function normalizePostgresSslMode(value: string): string {
|
||||
}
|
||||
|
||||
function normalizeRedisSentinelNodes(value: string): string {
|
||||
return normalizeRedisNodeList(value);
|
||||
}
|
||||
|
||||
function normalizeRedisClusterNodes(value: string): string {
|
||||
return normalizeRedisNodeList(value);
|
||||
}
|
||||
|
||||
function normalizeRedisNodeList(value: string): string {
|
||||
return value
|
||||
.split(/[\n,;]+/)
|
||||
.map((node) => node.trim())
|
||||
@@ -883,13 +908,21 @@ function normalizeRedisSentinelNodes(value: string): string {
|
||||
}
|
||||
|
||||
function firstRedisSentinelEndpoint(value?: string): { host: string; port: number } | null {
|
||||
const first = normalizeRedisSentinelNodes(value || "")
|
||||
const first = normalizeRedisNodeList(value || "")
|
||||
.split("\n")
|
||||
.find(Boolean);
|
||||
if (!first) return null;
|
||||
return parseRedisEndpoint(first, 26379);
|
||||
}
|
||||
|
||||
function firstRedisClusterEndpoint(value?: string): { host: string; port: number } | null {
|
||||
const first = normalizeRedisNodeList(value || "")
|
||||
.split("\n")
|
||||
.find(Boolean);
|
||||
if (!first) return null;
|
||||
return parseRedisEndpoint(first, 6379);
|
||||
}
|
||||
|
||||
function parseRedisEndpoint(value: string, defaultPort: number): { host: string; port: number } {
|
||||
const endpoint = value
|
||||
.trim()
|
||||
@@ -1616,7 +1649,7 @@ function openExternalUrl(url: string) {
|
||||
<div class="col-span-3 flex gap-2">
|
||||
<Button
|
||||
size="sm"
|
||||
:variant="form.redis_connection_mode === 'sentinel' ? 'outline' : 'default'"
|
||||
:variant="form.redis_connection_mode === 'standalone' ? 'default' : 'outline'"
|
||||
@click="form.redis_connection_mode = 'standalone'"
|
||||
>
|
||||
{{ t("connection.redisStandaloneMode") }}
|
||||
@@ -1628,13 +1661,22 @@ function openExternalUrl(url: string) {
|
||||
>
|
||||
{{ t("connection.redisSentinelMode") }}
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
:variant="form.redis_connection_mode === 'cluster' ? 'default' : 'outline'"
|
||||
@click="form.redis_connection_mode = 'cluster'"
|
||||
>
|
||||
{{ t("connection.redisClusterMode") }}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="grid grid-cols-4 items-center gap-4">
|
||||
<Label class="text-right">{{
|
||||
form.redis_connection_mode === "sentinel"
|
||||
? t("connection.redisFirstSentinel")
|
||||
: t("connection.host")
|
||||
: form.redis_connection_mode === "cluster"
|
||||
? t("connection.redisFirstClusterNode")
|
||||
: t("connection.host")
|
||||
}}</Label>
|
||||
<Input v-model="form.host" class="col-span-2" />
|
||||
<Input v-model.number="form.port" type="number" class="col-span-1" />
|
||||
@@ -1669,6 +1711,17 @@ function openExternalUrl(url: string) {
|
||||
</label>
|
||||
</div>
|
||||
</template>
|
||||
<template v-else-if="form.redis_connection_mode === 'cluster'">
|
||||
<div class="grid grid-cols-4 items-start gap-4">
|
||||
<Label class="text-right mt-2">{{ t("connection.redisClusterNodes") }}</Label>
|
||||
<textarea
|
||||
v-model="form.redis_cluster_nodes"
|
||||
class="col-span-3 flex min-h-[76px] w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"
|
||||
placeholder="redis-1:6379 redis-2:6379"
|
||||
spellcheck="false"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
<div class="grid grid-cols-4 items-center gap-4">
|
||||
<Label class="text-right">{{ t("connection.user") }}</Label>
|
||||
<Input v-model="form.username" class="col-span-3" placeholder="default" />
|
||||
|
||||
@@ -196,6 +196,25 @@ async function streamValueSearch(requestId: number) {
|
||||
}
|
||||
}
|
||||
|
||||
async function fillInitialKeyBatch(requestId: number) {
|
||||
const targetCount = Math.max(1, settingsStore.editorSettings.redisScanPageSize);
|
||||
let rounds = 0;
|
||||
while (
|
||||
requestId === searchRequestId &&
|
||||
searchMode.value === "key" &&
|
||||
hasMore.value &&
|
||||
flatKeys.value.length < targetCount
|
||||
) {
|
||||
const beforeCount = flatKeys.value.length;
|
||||
const applied = await scanNextPage(requestId);
|
||||
if (!applied) return;
|
||||
rounds += 1;
|
||||
if (flatKeys.value.length >= targetCount) return;
|
||||
if (rounds >= 12 && flatKeys.value.length === beforeCount) return;
|
||||
if (rounds >= 24) return;
|
||||
}
|
||||
}
|
||||
|
||||
async function loadKeys() {
|
||||
const requestId = ++searchRequestId;
|
||||
loading.value = true;
|
||||
@@ -211,8 +230,12 @@ async function loadKeys() {
|
||||
return;
|
||||
}
|
||||
const applied = await scanNextPage(requestId);
|
||||
if (applied && searchMode.value === "value") {
|
||||
await streamValueSearch(requestId);
|
||||
if (applied) {
|
||||
if (searchMode.value === "value") {
|
||||
await streamValueSearch(requestId);
|
||||
} else {
|
||||
await fillInitialKeyBatch(requestId);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
if (requestId === searchRequestId) {
|
||||
|
||||
@@ -162,8 +162,11 @@ export default {
|
||||
modeForm: "Form",
|
||||
redisStandaloneMode: "Standalone",
|
||||
redisSentinelMode: "Sentinel",
|
||||
redisClusterMode: "Cluster",
|
||||
redisFirstSentinel: "First Sentinel",
|
||||
redisFirstClusterNode: "First Seed Node",
|
||||
redisSentinelNodes: "Sentinel Nodes",
|
||||
redisClusterNodes: "Cluster Seed Nodes",
|
||||
redisSentinelMaster: "Master Name",
|
||||
redisSentinelUser: "Sentinel User",
|
||||
redisSentinelPassword: "Sentinel Password",
|
||||
|
||||
@@ -154,8 +154,11 @@ export default {
|
||||
modeForm: "Formulario",
|
||||
redisStandaloneMode: "Directa",
|
||||
redisSentinelMode: "Sentinel",
|
||||
redisClusterMode: "Cluster",
|
||||
redisFirstSentinel: "Primer Sentinel",
|
||||
redisFirstClusterNode: "Primer nodo semilla",
|
||||
redisSentinelNodes: "Nodos Sentinel",
|
||||
redisClusterNodes: "Nodos semilla del cluster",
|
||||
redisSentinelMaster: "Nombre del master",
|
||||
redisSentinelUser: "Usuario Sentinel",
|
||||
redisSentinelPassword: "Contraseña Sentinel",
|
||||
|
||||
@@ -159,8 +159,11 @@ export default {
|
||||
modeForm: "表单",
|
||||
redisStandaloneMode: "直连",
|
||||
redisSentinelMode: "哨兵",
|
||||
redisClusterMode: "集群",
|
||||
redisFirstSentinel: "首个哨兵",
|
||||
redisFirstClusterNode: "首个种子节点",
|
||||
redisSentinelNodes: "哨兵节点",
|
||||
redisClusterNodes: "集群种子节点",
|
||||
redisSentinelMaster: "Master 名称",
|
||||
redisSentinelUser: "哨兵用户名",
|
||||
redisSentinelPassword: "哨兵密码",
|
||||
|
||||
@@ -87,12 +87,13 @@ export interface ConnectionConfig {
|
||||
connection_string?: string;
|
||||
jdbc_driver_class?: string;
|
||||
jdbc_driver_paths?: string[];
|
||||
redis_connection_mode?: "standalone" | "sentinel";
|
||||
redis_connection_mode?: "standalone" | "sentinel" | "cluster";
|
||||
redis_sentinel_master?: string;
|
||||
redis_sentinel_nodes?: string;
|
||||
redis_sentinel_username?: string;
|
||||
redis_sentinel_password?: string;
|
||||
redis_sentinel_tls?: boolean;
|
||||
redis_cluster_nodes?: string;
|
||||
one_time?: boolean;
|
||||
}
|
||||
|
||||
|
||||
@@ -27,7 +27,7 @@ webpki-roots = "0.26"
|
||||
rusqlite = { version = "0.32", features = ["bundled"] }
|
||||
mysql_async = { version = "0.36", default-features = false, features = ["default-rustls", "client_ed25519", "chrono", "rust_decimal"] }
|
||||
sqlparser = "0.62.0"
|
||||
redis = { version = "0.32.2", features = ["tokio-comp", "tls-rustls", "tokio-rustls-comp", "sentinel"] }
|
||||
redis = { version = "0.32.2", features = ["tokio-comp", "tls-rustls", "tokio-rustls-comp", "sentinel", "cluster-async"] }
|
||||
rustls = { version = "0.23", features = ["aws-lc-rs"] }
|
||||
rustls-pemfile = "2.2"
|
||||
duckdb = "1.3.2"
|
||||
|
||||
@@ -519,6 +519,7 @@ mod tests {
|
||||
redis_sentinel_username: String::new(),
|
||||
redis_sentinel_password: "sentinel".to_string(),
|
||||
redis_sentinel_tls: false,
|
||||
redis_cluster_nodes: String::new(),
|
||||
external_config: None,
|
||||
jdbc_driver_class: None,
|
||||
jdbc_driver_paths: Vec::new(),
|
||||
|
||||
@@ -43,7 +43,7 @@ pub enum PoolKind {
|
||||
Mysql(db::mysql::MySqlPool, MysqlMode),
|
||||
Postgres(deadpool_postgres::Pool),
|
||||
Sqlite(db::sqlite::SqliteHandle),
|
||||
Redis(tokio::sync::Mutex<redis::aio::MultiplexedConnection>),
|
||||
Redis(db::redis_driver::RedisConnection),
|
||||
DuckDb(Arc<std::sync::Mutex<duckdb::Connection>>),
|
||||
MongoDb(mongodb::Client),
|
||||
ClickHouse(db::clickhouse_driver::ChClient),
|
||||
@@ -187,12 +187,18 @@ impl AppState {
|
||||
}
|
||||
DatabaseType::Sqlite => PoolKind::Sqlite(db::sqlite::connect_path(&expand_tilde(&db_config.host)).await?),
|
||||
DatabaseType::Redis => {
|
||||
let con = if db_config.uses_redis_sentinel() {
|
||||
db::redis_driver::connect_sentinel(&db_config).await?
|
||||
let con = if db_config.uses_redis_cluster() {
|
||||
db::redis_driver::RedisConnection::Cluster(db::redis_driver::connect_cluster(&db_config).await?)
|
||||
} else if db_config.uses_redis_sentinel() {
|
||||
db::redis_driver::RedisConnection::Direct(tokio::sync::Mutex::new(
|
||||
db::redis_driver::connect_sentinel(&db_config).await?,
|
||||
))
|
||||
} else {
|
||||
db::redis_driver::connect(&url).await?
|
||||
db::redis_driver::RedisConnection::Direct(tokio::sync::Mutex::new(
|
||||
db::redis_driver::connect(&url).await?,
|
||||
))
|
||||
};
|
||||
PoolKind::Redis(tokio::sync::Mutex::new(con))
|
||||
PoolKind::Redis(con)
|
||||
}
|
||||
DatabaseType::DuckDb => {
|
||||
let con = db::duckdb_driver::connect_path(&expand_tilde(&db_config.host))?;
|
||||
@@ -919,6 +925,7 @@ mod tests {
|
||||
redis_sentinel_username: String::new(),
|
||||
redis_sentinel_password: String::new(),
|
||||
redis_sentinel_tls: false,
|
||||
redis_cluster_nodes: String::new(),
|
||||
external_config: None,
|
||||
jdbc_driver_class: None,
|
||||
jdbc_driver_paths: Vec::new(),
|
||||
|
||||
@@ -329,6 +329,7 @@ mod tests {
|
||||
redis_sentinel_username: String::new(),
|
||||
redis_sentinel_password: String::new(),
|
||||
redis_sentinel_tls: false,
|
||||
redis_cluster_nodes: String::new(),
|
||||
external_config: None,
|
||||
jdbc_driver_class: None,
|
||||
jdbc_driver_paths: Vec::new(),
|
||||
|
||||
@@ -1,15 +1,22 @@
|
||||
use crate::models::connection::ConnectionConfig;
|
||||
use base64::Engine;
|
||||
use redis::{
|
||||
aio::ConnectionLike,
|
||||
cluster::ClusterClient,
|
||||
cluster_async::ClusterConnection,
|
||||
sentinel::{Sentinel, SentinelNodeConnectionInfo},
|
||||
ConnectionAddr, ConnectionInfo, FromRedisValue, ProtocolVersion, RedisConnectionInfo, TlsMode,
|
||||
Value as RedisRawValue,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use tokio::sync::Mutex;
|
||||
|
||||
const STREAM_ENTRY_LIMIT: usize = 100;
|
||||
const COLLECTION_PAGE_SIZE: usize = 200;
|
||||
const DEFAULT_REDIS_DATABASES: u32 = 16;
|
||||
const CLUSTER_CURSOR_NODE_BITS: u64 = 16;
|
||||
const CLUSTER_CURSOR_NODE_MASK: u64 = (1 << CLUSTER_CURSOR_NODE_BITS) - 1;
|
||||
const CLUSTER_CURSOR_SCAN_MASK: u64 = (1 << (64 - CLUSTER_CURSOR_NODE_BITS)) - 1;
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct RedisDatabaseInfo {
|
||||
@@ -61,19 +68,28 @@ pub struct RedisCommandResult {
|
||||
pub value: serde_json::Value,
|
||||
}
|
||||
|
||||
pub enum RedisConnection {
|
||||
Direct(Mutex<redis::aio::MultiplexedConnection>),
|
||||
Cluster(RedisClusterPool),
|
||||
}
|
||||
|
||||
pub struct RedisClusterPool {
|
||||
pub connection: Mutex<ClusterConnection>,
|
||||
pub seed_nodes: Vec<RedisNodeEndpoint>,
|
||||
pub tls: bool,
|
||||
pub username: String,
|
||||
pub password: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
pub struct RedisNodeEndpoint {
|
||||
pub host: String,
|
||||
pub port: u16,
|
||||
}
|
||||
|
||||
pub async fn connect(url: &str) -> Result<redis::aio::MultiplexedConnection, String> {
|
||||
let client = redis::Client::open(url).map_err(|e| format!("Redis connection failed: {e}"))?;
|
||||
let mut con = tokio::time::timeout(super::connection_timeout(), client.get_multiplexed_async_connection())
|
||||
.await
|
||||
.map_err(|_| format!("Redis connection timed out ({}s)", super::CONNECTION_TIMEOUT_SECS))?
|
||||
.map_err(|e| format!("Redis connection failed: {e}"))?;
|
||||
|
||||
tokio::time::timeout(super::connection_timeout(), redis::cmd("PING").query_async::<String>(&mut con))
|
||||
.await
|
||||
.map_err(|_| format!("Redis ping timed out ({}s)", super::CONNECTION_TIMEOUT_SECS))?
|
||||
.map_err(|e| format!("Redis authentication failed or command rejected: {e}"))?;
|
||||
|
||||
Ok(con)
|
||||
connect_client(client).await
|
||||
}
|
||||
|
||||
pub async fn connect_sentinel(config: &ConnectionConfig) -> Result<redis::aio::MultiplexedConnection, String> {
|
||||
@@ -96,17 +112,35 @@ pub async fn connect_sentinel(config: &ConnectionConfig) -> Result<redis::aio::M
|
||||
.map_err(|_| format!("Redis Sentinel lookup timed out ({}s)", super::CONNECTION_TIMEOUT_SECS))?
|
||||
.map_err(|e| format!("Redis Sentinel master lookup failed: {e}"))?;
|
||||
|
||||
let mut con = tokio::time::timeout(super::connection_timeout(), client.get_multiplexed_async_connection())
|
||||
connect_client(client).await
|
||||
}
|
||||
|
||||
pub async fn connect_cluster(config: &ConnectionConfig) -> Result<RedisClusterPool, String> {
|
||||
let seed_nodes = redis_cluster_seed_nodes(config)?;
|
||||
let cluster_nodes: Vec<ConnectionInfo> = seed_nodes
|
||||
.iter()
|
||||
.map(|endpoint| {
|
||||
connection_info(&endpoint.host, endpoint.port, config.ssl, &config.username, &config.password, 0)
|
||||
})
|
||||
.collect();
|
||||
let client = ClusterClient::new(cluster_nodes).map_err(|e| format!("Redis cluster connection failed: {e}"))?;
|
||||
let mut con = tokio::time::timeout(super::connection_timeout(), client.get_async_connection())
|
||||
.await
|
||||
.map_err(|_| format!("Redis connection timed out ({}s)", super::CONNECTION_TIMEOUT_SECS))?
|
||||
.map_err(|e| format!("Redis connection failed: {e}"))?;
|
||||
.map_err(|_| format!("Redis cluster connection timed out ({}s)", super::CONNECTION_TIMEOUT_SECS))?
|
||||
.map_err(|e| format!("Redis cluster connection failed: {e}"))?;
|
||||
|
||||
tokio::time::timeout(super::connection_timeout(), redis::cmd("PING").query_async::<String>(&mut con))
|
||||
.await
|
||||
.map_err(|_| format!("Redis ping timed out ({}s)", super::CONNECTION_TIMEOUT_SECS))?
|
||||
.map_err(|e| format!("Redis authentication failed or command rejected: {e}"))?;
|
||||
.map_err(|_| format!("Redis cluster ping timed out ({}s)", super::CONNECTION_TIMEOUT_SECS))?
|
||||
.map_err(|e| format!("Redis cluster authentication failed or command rejected: {e}"))?;
|
||||
|
||||
Ok(con)
|
||||
Ok(RedisClusterPool {
|
||||
connection: Mutex::new(con),
|
||||
seed_nodes,
|
||||
tls: config.ssl,
|
||||
username: config.username.clone(),
|
||||
password: config.password.clone(),
|
||||
})
|
||||
}
|
||||
|
||||
fn redis_sentinel_nodes(config: &ConnectionConfig) -> Result<Vec<ConnectionInfo>, String> {
|
||||
@@ -129,6 +163,16 @@ fn redis_sentinel_nodes(config: &ConnectionConfig) -> Result<Vec<ConnectionInfo>
|
||||
endpoints.iter().map(|endpoint| redis_sentinel_node_connection_info(config, endpoint)).collect()
|
||||
}
|
||||
|
||||
fn redis_cluster_seed_nodes(config: &ConnectionConfig) -> Result<Vec<RedisNodeEndpoint>, String> {
|
||||
redis_node_endpoints(
|
||||
config.redis_cluster_nodes.trim(),
|
||||
config.host.trim(),
|
||||
config.port,
|
||||
"Redis cluster seed node",
|
||||
6379,
|
||||
)
|
||||
}
|
||||
|
||||
fn redis_sentinel_node_connection_info(config: &ConnectionConfig, endpoint: &str) -> Result<ConnectionInfo, String> {
|
||||
let (host, port) = parse_redis_endpoint(endpoint, 26379)?;
|
||||
Ok(connection_info(
|
||||
@@ -141,6 +185,37 @@ fn redis_sentinel_node_connection_info(config: &ConnectionConfig, endpoint: &str
|
||||
))
|
||||
}
|
||||
|
||||
fn redis_node_endpoints(
|
||||
raw_nodes: &str,
|
||||
fallback_host: &str,
|
||||
fallback_port: u16,
|
||||
label: &str,
|
||||
default_port: u16,
|
||||
) -> Result<Vec<RedisNodeEndpoint>, String> {
|
||||
let endpoints: Vec<String> = if raw_nodes.is_empty() {
|
||||
vec![format!("{fallback_host}:{}", if fallback_port == 0 { default_port } else { fallback_port })]
|
||||
} else {
|
||||
raw_nodes
|
||||
.split(|ch: char| ch == ',' || ch == ';' || ch == '\n' || ch == '\r')
|
||||
.map(str::trim)
|
||||
.filter(|node| !node.is_empty())
|
||||
.map(ToOwned::to_owned)
|
||||
.collect()
|
||||
};
|
||||
|
||||
if endpoints.is_empty() {
|
||||
return Err(format!("At least one {label} is required"));
|
||||
}
|
||||
|
||||
endpoints
|
||||
.iter()
|
||||
.map(|endpoint| {
|
||||
let (host, port) = parse_redis_endpoint(endpoint, default_port)?;
|
||||
Ok(RedisNodeEndpoint { host, port })
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn connection_info(host: &str, port: u16, tls: bool, username: &str, password: &str, db: i64) -> ConnectionInfo {
|
||||
let addr = if tls {
|
||||
ConnectionAddr::TcpTls { host: host.to_string(), port, insecure: false, tls_params: None }
|
||||
@@ -171,7 +246,7 @@ fn non_empty_string(value: &str) -> Option<String> {
|
||||
fn parse_redis_endpoint(endpoint: &str, default_port: u16) -> Result<(String, u16), String> {
|
||||
let endpoint = endpoint.trim();
|
||||
if endpoint.is_empty() {
|
||||
return Err("Redis Sentinel node cannot be empty".to_string());
|
||||
return Err("Redis node cannot be empty".to_string());
|
||||
}
|
||||
let endpoint = endpoint.strip_prefix("redis://").or_else(|| endpoint.strip_prefix("rediss://")).unwrap_or(endpoint);
|
||||
let endpoint = endpoint.rsplit_once('@').map(|(_, tail)| tail).unwrap_or(endpoint);
|
||||
@@ -179,7 +254,7 @@ fn parse_redis_endpoint(endpoint: &str, default_port: u16) -> Result<(String, u1
|
||||
|
||||
if let Some(rest) = endpoint.strip_prefix('[') {
|
||||
let Some((host, tail)) = rest.split_once(']') else {
|
||||
return Err(format!("Invalid Redis Sentinel node '{endpoint}'"));
|
||||
return Err(format!("Invalid Redis node '{endpoint}'"));
|
||||
};
|
||||
let port = tail.strip_prefix(':').filter(|value| !value.is_empty()).map(parse_redis_port).transpose()?;
|
||||
return Ok((host.to_string(), port.unwrap_or(default_port)));
|
||||
@@ -195,10 +270,38 @@ fn parse_redis_endpoint(endpoint: &str, default_port: u16) -> Result<(String, u1
|
||||
}
|
||||
|
||||
fn parse_redis_port(port: &str) -> Result<u16, String> {
|
||||
port.parse::<u16>().map_err(|_| format!("Invalid Redis Sentinel port '{port}'"))
|
||||
port.parse::<u16>().map_err(|_| format!("Invalid Redis port '{port}'"))
|
||||
}
|
||||
|
||||
pub async fn list_databases(con: &mut redis::aio::MultiplexedConnection) -> Result<Vec<RedisDatabaseInfo>, String> {
|
||||
async fn connect_client(client: redis::Client) -> Result<redis::aio::MultiplexedConnection, String> {
|
||||
let mut con = tokio::time::timeout(super::connection_timeout(), client.get_multiplexed_async_connection())
|
||||
.await
|
||||
.map_err(|_| format!("Redis connection timed out ({}s)", super::CONNECTION_TIMEOUT_SECS))?
|
||||
.map_err(|e| format!("Redis connection failed: {e}"))?;
|
||||
|
||||
tokio::time::timeout(super::connection_timeout(), redis::cmd("PING").query_async::<String>(&mut con))
|
||||
.await
|
||||
.map_err(|_| format!("Redis ping timed out ({}s)", super::CONNECTION_TIMEOUT_SECS))?
|
||||
.map_err(|e| format!("Redis authentication failed or command rejected: {e}"))?;
|
||||
|
||||
Ok(con)
|
||||
}
|
||||
|
||||
pub async fn connect_direct_node(
|
||||
endpoint: &RedisNodeEndpoint,
|
||||
tls: bool,
|
||||
username: &str,
|
||||
password: &str,
|
||||
) -> Result<redis::aio::MultiplexedConnection, String> {
|
||||
let client = redis::Client::open(connection_info(&endpoint.host, endpoint.port, tls, username, password, 0))
|
||||
.map_err(|e| format!("Redis connection failed: {e}"))?;
|
||||
connect_client(client).await
|
||||
}
|
||||
|
||||
pub async fn list_databases<C>(con: &mut C) -> Result<Vec<RedisDatabaseInfo>, String>
|
||||
where
|
||||
C: ConnectionLike + Send + Sync + Unpin,
|
||||
{
|
||||
let configured_count =
|
||||
redis::cmd("CONFIG").arg("GET").arg("databases").query_async(con).await.ok().and_then(parse_database_count);
|
||||
|
||||
@@ -230,9 +333,10 @@ fn parse_database_count(value: redis::Value) -> Option<u32> {
|
||||
})
|
||||
}
|
||||
|
||||
async fn list_keyspace_databases(
|
||||
con: &mut redis::aio::MultiplexedConnection,
|
||||
) -> Result<Vec<RedisDatabaseInfo>, String> {
|
||||
async fn list_keyspace_databases<C>(con: &mut C) -> Result<Vec<RedisDatabaseInfo>, String>
|
||||
where
|
||||
C: ConnectionLike + Send + Sync + Unpin,
|
||||
{
|
||||
let info: String = redis::cmd("INFO").arg("keyspace").query_async(con).await.map_err(|e| e.to_string())?;
|
||||
|
||||
let mut dbs = Vec::new();
|
||||
@@ -254,10 +358,235 @@ async fn list_keyspace_databases(
|
||||
Ok(dbs)
|
||||
}
|
||||
|
||||
pub async fn select_db(con: &mut redis::aio::MultiplexedConnection, db: u32) -> Result<(), String> {
|
||||
pub async fn select_db<C>(con: &mut C, db: u32) -> Result<(), String>
|
||||
where
|
||||
C: ConnectionLike + Send + Sync + Unpin,
|
||||
{
|
||||
redis::cmd("SELECT").arg(db).query_async(con).await.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
pub fn ensure_cluster_db(db: u32) -> Result<(), String> {
|
||||
if db == 0 {
|
||||
Ok(())
|
||||
} else {
|
||||
Err("Redis Cluster only supports db0".to_string())
|
||||
}
|
||||
}
|
||||
|
||||
pub fn encode_cluster_cursor(node_index: usize, cursor: u64) -> Result<u64, String> {
|
||||
if node_index > CLUSTER_CURSOR_NODE_MASK as usize {
|
||||
return Err("Redis cluster cursor exceeded node limit".to_string());
|
||||
}
|
||||
if cursor > CLUSTER_CURSOR_SCAN_MASK {
|
||||
return Err("Redis cluster cursor exceeded scan limit".to_string());
|
||||
}
|
||||
Ok(((node_index as u64) << (64 - CLUSTER_CURSOR_NODE_BITS)) | (cursor & CLUSTER_CURSOR_SCAN_MASK))
|
||||
}
|
||||
|
||||
pub fn decode_cluster_cursor(cursor: u64) -> (usize, u64) {
|
||||
if cursor == 0 {
|
||||
return (0, 0);
|
||||
}
|
||||
let node_index = (cursor >> (64 - CLUSTER_CURSOR_NODE_BITS)) as usize;
|
||||
let node_cursor = cursor & CLUSTER_CURSOR_SCAN_MASK;
|
||||
(node_index, node_cursor)
|
||||
}
|
||||
|
||||
pub async fn list_cluster_databases(pool: &RedisClusterPool) -> Result<Vec<RedisDatabaseInfo>, String> {
|
||||
let master_nodes = cluster_master_nodes(pool).await?;
|
||||
let keys = cluster_total_keys(pool, &master_nodes).await;
|
||||
Ok(vec![RedisDatabaseInfo { db: 0, keys }])
|
||||
}
|
||||
|
||||
pub async fn scan_cluster_keys_page(
|
||||
pool: &RedisClusterPool,
|
||||
cursor: u64,
|
||||
pattern: &str,
|
||||
count: usize,
|
||||
) -> Result<RedisScanResult, String> {
|
||||
let master_nodes = cluster_master_nodes(pool).await?;
|
||||
if master_nodes.is_empty() {
|
||||
return Ok(RedisScanResult { cursor: 0, keys: Vec::new(), total_keys: 0 });
|
||||
}
|
||||
|
||||
let (mut node_index, node_cursor) = decode_cluster_cursor(cursor);
|
||||
if node_index >= master_nodes.len() {
|
||||
node_index = 0;
|
||||
}
|
||||
|
||||
let total_keys = cluster_total_keys(pool, &master_nodes).await;
|
||||
for index in node_index..master_nodes.len() {
|
||||
let endpoint = &master_nodes[index];
|
||||
let mut con = connect_direct_node(endpoint, pool.tls, &pool.username, &pool.password).await?;
|
||||
let current_cursor = if index == node_index { node_cursor } else { 0 };
|
||||
let result = scan_keys_page(&mut con, current_cursor, pattern, count).await?;
|
||||
if !result.keys.is_empty() {
|
||||
let next_cursor = if result.cursor != 0 {
|
||||
encode_cluster_cursor(index, result.cursor)?
|
||||
} else if index + 1 < master_nodes.len() {
|
||||
encode_cluster_cursor(index + 1, 0)?
|
||||
} else {
|
||||
0
|
||||
};
|
||||
return Ok(RedisScanResult { cursor: next_cursor, keys: result.keys, total_keys });
|
||||
}
|
||||
if result.cursor != 0 {
|
||||
return Ok(RedisScanResult {
|
||||
cursor: encode_cluster_cursor(index, result.cursor)?,
|
||||
keys: Vec::new(),
|
||||
total_keys,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Ok(RedisScanResult { cursor: 0, keys: Vec::new(), total_keys })
|
||||
}
|
||||
|
||||
pub async fn scan_cluster_values_page(
|
||||
pool: &RedisClusterPool,
|
||||
cursor: u64,
|
||||
pattern: &str,
|
||||
query: &str,
|
||||
count: usize,
|
||||
) -> Result<RedisScanResult, String> {
|
||||
let master_nodes = cluster_master_nodes(pool).await?;
|
||||
if master_nodes.is_empty() {
|
||||
return Ok(RedisScanResult { cursor: 0, keys: Vec::new(), total_keys: 0 });
|
||||
}
|
||||
|
||||
let (mut node_index, node_cursor) = decode_cluster_cursor(cursor);
|
||||
if node_index >= master_nodes.len() {
|
||||
node_index = 0;
|
||||
}
|
||||
|
||||
let total_keys = cluster_total_keys(pool, &master_nodes).await;
|
||||
for index in node_index..master_nodes.len() {
|
||||
let endpoint = &master_nodes[index];
|
||||
let mut con = connect_direct_node(endpoint, pool.tls, &pool.username, &pool.password).await?;
|
||||
let current_cursor = if index == node_index { node_cursor } else { 0 };
|
||||
let result = scan_values_page(&mut con, current_cursor, pattern, query, count).await?;
|
||||
if !result.keys.is_empty() {
|
||||
let next_cursor = if result.cursor != 0 {
|
||||
encode_cluster_cursor(index, result.cursor)?
|
||||
} else if index + 1 < master_nodes.len() {
|
||||
encode_cluster_cursor(index + 1, 0)?
|
||||
} else {
|
||||
0
|
||||
};
|
||||
return Ok(RedisScanResult { cursor: next_cursor, keys: result.keys, total_keys });
|
||||
}
|
||||
if result.cursor != 0 {
|
||||
return Ok(RedisScanResult {
|
||||
cursor: encode_cluster_cursor(index, result.cursor)?,
|
||||
keys: Vec::new(),
|
||||
total_keys,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Ok(RedisScanResult { cursor: 0, keys: Vec::new(), total_keys })
|
||||
}
|
||||
|
||||
pub async fn cluster_master_nodes(pool: &RedisClusterPool) -> Result<Vec<RedisNodeEndpoint>, String> {
|
||||
cluster_master_nodes_from_seeds(&pool.seed_nodes, pool.tls, &pool.username, &pool.password).await
|
||||
}
|
||||
|
||||
pub async fn flush_cluster(pool: &RedisClusterPool) -> Result<(), String> {
|
||||
let master_nodes = cluster_master_nodes(pool).await?;
|
||||
for endpoint in master_nodes {
|
||||
let mut con = connect_direct_node(&endpoint, pool.tls, &pool.username, &pool.password).await?;
|
||||
flush_db(&mut con).await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn cluster_total_keys(pool: &RedisClusterPool, master_nodes: &[RedisNodeEndpoint]) -> u64 {
|
||||
let mut total = 0;
|
||||
for endpoint in master_nodes {
|
||||
let Ok(mut con) = connect_direct_node(endpoint, pool.tls, &pool.username, &pool.password).await else {
|
||||
continue;
|
||||
};
|
||||
total += redis::cmd("DBSIZE").query_async::<u64>(&mut con).await.unwrap_or(0);
|
||||
}
|
||||
total
|
||||
}
|
||||
|
||||
async fn cluster_master_nodes_from_seeds(
|
||||
seed_nodes: &[RedisNodeEndpoint],
|
||||
tls: bool,
|
||||
username: &str,
|
||||
password: &str,
|
||||
) -> Result<Vec<RedisNodeEndpoint>, String> {
|
||||
let mut last_error = None;
|
||||
for endpoint in seed_nodes {
|
||||
let mut con = match connect_direct_node(endpoint, tls, username, password).await {
|
||||
Ok(con) => con,
|
||||
Err(err) => {
|
||||
last_error = Some(err);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let raw: RedisRawValue = match redis::cmd("CLUSTER").arg("SLOTS").query_async(&mut con).await {
|
||||
Ok(raw) => raw,
|
||||
Err(err) => {
|
||||
last_error = Some(err.to_string());
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let nodes = parse_cluster_slots(raw, &endpoint.host)?;
|
||||
if !nodes.is_empty() {
|
||||
return Ok(nodes);
|
||||
}
|
||||
}
|
||||
|
||||
Err(last_error.unwrap_or_else(|| "Redis cluster master discovery failed".to_string()))
|
||||
}
|
||||
|
||||
fn parse_cluster_slots(raw: RedisRawValue, fallback_host: &str) -> Result<Vec<RedisNodeEndpoint>, String> {
|
||||
let RedisRawValue::Array(slots) = raw else {
|
||||
return Err("Invalid Redis CLUSTER SLOTS response".to_string());
|
||||
};
|
||||
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
let mut nodes = Vec::new();
|
||||
for slot in slots {
|
||||
let RedisRawValue::Array(parts) = slot else {
|
||||
continue;
|
||||
};
|
||||
if parts.len() < 3 {
|
||||
continue;
|
||||
}
|
||||
let Some(endpoint) = parse_cluster_slot_master(parts[2].clone(), fallback_host)? else {
|
||||
continue;
|
||||
};
|
||||
if seen.insert((endpoint.host.clone(), endpoint.port)) {
|
||||
nodes.push(endpoint);
|
||||
}
|
||||
}
|
||||
Ok(nodes)
|
||||
}
|
||||
|
||||
fn parse_cluster_slot_master(value: RedisRawValue, fallback_host: &str) -> Result<Option<RedisNodeEndpoint>, String> {
|
||||
let RedisRawValue::Array(parts) = value else {
|
||||
return Ok(None);
|
||||
};
|
||||
if parts.len() < 2 {
|
||||
return Ok(None);
|
||||
}
|
||||
let host = match &parts[0] {
|
||||
RedisRawValue::Nil => fallback_host.to_string(),
|
||||
other => redis_value_to_string(other.clone()).unwrap_or_else(|| fallback_host.to_string()),
|
||||
};
|
||||
if host.trim().is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
let Some(port_text) = redis_value_to_string(parts[1].clone()) else {
|
||||
return Err("Invalid Redis cluster node port".to_string());
|
||||
};
|
||||
let port = parse_redis_port(&port_text)?;
|
||||
Ok(Some(RedisNodeEndpoint { host, port }))
|
||||
}
|
||||
|
||||
pub fn parse_command_argv(command_text: &str) -> Result<Vec<String>, String> {
|
||||
let mut argv = Vec::new();
|
||||
let mut current = String::new();
|
||||
@@ -414,14 +743,17 @@ pub fn redis_key_value_preview(key_type: &str) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn flush_db(con: &mut redis::aio::MultiplexedConnection) -> Result<(), String> {
|
||||
pub async fn flush_db<C>(con: &mut C) -> Result<(), String>
|
||||
where
|
||||
C: ConnectionLike + Send + Sync + Unpin,
|
||||
{
|
||||
redis::cmd("FLUSHDB").query_async::<()>(con).await.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
pub async fn execute_command(
|
||||
con: &mut redis::aio::MultiplexedConnection,
|
||||
command_text: &str,
|
||||
) -> Result<RedisCommandResult, String> {
|
||||
pub async fn execute_command<C>(con: &mut C, command_text: &str) -> Result<RedisCommandResult, String>
|
||||
where
|
||||
C: ConnectionLike + Send + Sync + Unpin,
|
||||
{
|
||||
let argv = parse_command_argv(command_text)?;
|
||||
let command = argv[0].to_ascii_uppercase();
|
||||
let safety = classify_command(&command);
|
||||
@@ -438,12 +770,10 @@ pub async fn execute_command(
|
||||
Ok(RedisCommandResult { command, safety, value: redis_command_raw_to_json(raw) })
|
||||
}
|
||||
|
||||
pub async fn scan_keys_page(
|
||||
con: &mut redis::aio::MultiplexedConnection,
|
||||
cursor: u64,
|
||||
pattern: &str,
|
||||
count: usize,
|
||||
) -> Result<RedisScanResult, String> {
|
||||
pub async fn scan_keys_page<C>(con: &mut C, cursor: u64, pattern: &str, count: usize) -> Result<RedisScanResult, String>
|
||||
where
|
||||
C: ConnectionLike + Send + Sync + Unpin,
|
||||
{
|
||||
let raw: RedisRawValue = redis::cmd("SCAN")
|
||||
.arg(cursor)
|
||||
.arg("MATCH")
|
||||
@@ -481,13 +811,16 @@ pub async fn scan_keys_page(
|
||||
Ok(RedisScanResult { cursor: next_cursor, keys: result, total_keys })
|
||||
}
|
||||
|
||||
pub async fn scan_values_page(
|
||||
con: &mut redis::aio::MultiplexedConnection,
|
||||
pub async fn scan_values_page<C>(
|
||||
con: &mut C,
|
||||
cursor: u64,
|
||||
pattern: &str,
|
||||
query: &str,
|
||||
count: usize,
|
||||
) -> Result<RedisScanResult, String> {
|
||||
) -> Result<RedisScanResult, String>
|
||||
where
|
||||
C: ConnectionLike + Send + Sync + Unpin,
|
||||
{
|
||||
let total_keys: u64 = redis::cmd("DBSIZE").query_async(con).await.unwrap_or(0);
|
||||
if query.trim().is_empty() {
|
||||
return Ok(RedisScanResult { cursor, keys: Vec::new(), total_keys });
|
||||
@@ -528,7 +861,10 @@ pub async fn scan_values_page(
|
||||
Ok(RedisScanResult { cursor: next_cursor, keys: result, total_keys })
|
||||
}
|
||||
|
||||
pub async fn get_value(con: &mut redis::aio::MultiplexedConnection, key: &[u8]) -> Result<RedisValue, String> {
|
||||
pub async fn get_value<C>(con: &mut C, key: &[u8]) -> Result<RedisValue, String>
|
||||
where
|
||||
C: ConnectionLike + Send + Sync + Unpin,
|
||||
{
|
||||
let key_type: String = redis::cmd("TYPE").arg(key).query_async(con).await.map_err(|e| e.to_string())?;
|
||||
|
||||
let ttl: i64 = redis::cmd("TTL").arg(key).query_async(con).await.unwrap_or(-1);
|
||||
@@ -622,10 +958,10 @@ fn redis_search_value_size(value: &serde_json::Value, total: Option<u64>) -> u64
|
||||
}
|
||||
}
|
||||
|
||||
async fn get_stream_entries(
|
||||
con: &mut redis::aio::MultiplexedConnection,
|
||||
key: &[u8],
|
||||
) -> Result<serde_json::Value, String> {
|
||||
async fn get_stream_entries<C>(con: &mut C, key: &[u8]) -> Result<serde_json::Value, String>
|
||||
where
|
||||
C: ConnectionLike + Send + Sync + Unpin,
|
||||
{
|
||||
let raw: RedisRawValue = redis::cmd("XRANGE")
|
||||
.arg(key)
|
||||
.arg("-")
|
||||
@@ -780,12 +1116,10 @@ pub fn redis_key_raw_to_bytes(value: &str) -> Result<Vec<u8>, String> {
|
||||
base64::engine::general_purpose::STANDARD.decode(value).map_err(|e| format!("Invalid Redis key encoding: {e}"))
|
||||
}
|
||||
|
||||
pub async fn set_string(
|
||||
con: &mut redis::aio::MultiplexedConnection,
|
||||
key: &[u8],
|
||||
value: &str,
|
||||
ttl: Option<i64>,
|
||||
) -> Result<(), String> {
|
||||
pub async fn set_string<C>(con: &mut C, key: &[u8], value: &str, ttl: Option<i64>) -> Result<(), String>
|
||||
where
|
||||
C: ConnectionLike + Send + Sync + Unpin,
|
||||
{
|
||||
redis::cmd("SET").arg(key).arg(value).query_async::<()>(con).await.map_err(|e| e.to_string())?;
|
||||
if let Some(t) = ttl {
|
||||
if t > 0 {
|
||||
@@ -795,64 +1129,82 @@ pub async fn set_string(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn delete_key(con: &mut redis::aio::MultiplexedConnection, key: &[u8]) -> Result<(), String> {
|
||||
pub async fn delete_key<C>(con: &mut C, key: &[u8]) -> Result<(), String>
|
||||
where
|
||||
C: ConnectionLike + Send + Sync + Unpin,
|
||||
{
|
||||
redis::cmd("DEL").arg(key).query_async::<()>(con).await.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
pub async fn hash_set(
|
||||
con: &mut redis::aio::MultiplexedConnection,
|
||||
key: &[u8],
|
||||
field: &str,
|
||||
value: &str,
|
||||
) -> Result<(), String> {
|
||||
pub async fn hash_set<C>(con: &mut C, key: &[u8], field: &str, value: &str) -> Result<(), String>
|
||||
where
|
||||
C: ConnectionLike + Send + Sync + Unpin,
|
||||
{
|
||||
redis::cmd("HSET").arg(key).arg(field).arg(value).query_async::<()>(con).await.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
pub async fn hash_del(con: &mut redis::aio::MultiplexedConnection, key: &[u8], field: &str) -> Result<(), String> {
|
||||
pub async fn hash_del<C>(con: &mut C, key: &[u8], field: &str) -> Result<(), String>
|
||||
where
|
||||
C: ConnectionLike + Send + Sync + Unpin,
|
||||
{
|
||||
redis::cmd("HDEL").arg(key).arg(field).query_async::<()>(con).await.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
pub async fn list_push(con: &mut redis::aio::MultiplexedConnection, key: &[u8], value: &str) -> Result<(), String> {
|
||||
pub async fn list_push<C>(con: &mut C, key: &[u8], value: &str) -> Result<(), String>
|
||||
where
|
||||
C: ConnectionLike + Send + Sync + Unpin,
|
||||
{
|
||||
redis::cmd("RPUSH").arg(key).arg(value).query_async::<()>(con).await.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
pub async fn list_set(
|
||||
con: &mut redis::aio::MultiplexedConnection,
|
||||
key: &[u8],
|
||||
index: i64,
|
||||
value: &str,
|
||||
) -> Result<(), String> {
|
||||
pub async fn list_set<C>(con: &mut C, key: &[u8], index: i64, value: &str) -> Result<(), String>
|
||||
where
|
||||
C: ConnectionLike + Send + Sync + Unpin,
|
||||
{
|
||||
redis::cmd("LSET").arg(key).arg(index).arg(value).query_async::<()>(con).await.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
pub async fn list_remove(con: &mut redis::aio::MultiplexedConnection, key: &[u8], index: i64) -> Result<(), String> {
|
||||
pub async fn list_remove<C>(con: &mut C, key: &[u8], index: i64) -> Result<(), String>
|
||||
where
|
||||
C: ConnectionLike + Send + Sync + Unpin,
|
||||
{
|
||||
let placeholder = "__DELETED_PLACEHOLDER__";
|
||||
redis::cmd("LSET").arg(key).arg(index).arg(placeholder).query_async::<()>(con).await.map_err(|e| e.to_string())?;
|
||||
redis::cmd("LREM").arg(key).arg(1).arg(placeholder).query_async::<()>(con).await.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
pub async fn set_add(con: &mut redis::aio::MultiplexedConnection, key: &[u8], member: &str) -> Result<(), String> {
|
||||
pub async fn set_add<C>(con: &mut C, key: &[u8], member: &str) -> Result<(), String>
|
||||
where
|
||||
C: ConnectionLike + Send + Sync + Unpin,
|
||||
{
|
||||
redis::cmd("SADD").arg(key).arg(member).query_async::<()>(con).await.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
pub async fn set_remove(con: &mut redis::aio::MultiplexedConnection, key: &[u8], member: &str) -> Result<(), String> {
|
||||
pub async fn set_remove<C>(con: &mut C, key: &[u8], member: &str) -> Result<(), String>
|
||||
where
|
||||
C: ConnectionLike + Send + Sync + Unpin,
|
||||
{
|
||||
redis::cmd("SREM").arg(key).arg(member).query_async::<()>(con).await.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
pub async fn zadd(
|
||||
con: &mut redis::aio::MultiplexedConnection,
|
||||
key: &[u8],
|
||||
member: &str,
|
||||
score: f64,
|
||||
) -> Result<(), String> {
|
||||
pub async fn zadd<C>(con: &mut C, key: &[u8], member: &str, score: f64) -> Result<(), String>
|
||||
where
|
||||
C: ConnectionLike + Send + Sync + Unpin,
|
||||
{
|
||||
redis::cmd("ZADD").arg(key).arg(score).arg(member).query_async::<()>(con).await.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
pub async fn zrem(con: &mut redis::aio::MultiplexedConnection, key: &[u8], member: &str) -> Result<(), String> {
|
||||
pub async fn zrem<C>(con: &mut C, key: &[u8], member: &str) -> Result<(), String>
|
||||
where
|
||||
C: ConnectionLike + Send + Sync + Unpin,
|
||||
{
|
||||
redis::cmd("ZREM").arg(key).arg(member).query_async::<()>(con).await.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
pub async fn set_ttl(con: &mut redis::aio::MultiplexedConnection, key: &[u8], ttl: i64) -> Result<(), String> {
|
||||
pub async fn set_ttl<C>(con: &mut C, key: &[u8], ttl: i64) -> Result<(), String>
|
||||
where
|
||||
C: ConnectionLike + Send + Sync + Unpin,
|
||||
{
|
||||
if ttl > 0 {
|
||||
redis::cmd("EXPIRE").arg(key).arg(ttl).query_async::<()>(con).await.map_err(|e| e.to_string())
|
||||
} else {
|
||||
@@ -860,7 +1212,10 @@ pub async fn set_ttl(con: &mut redis::aio::MultiplexedConnection, key: &[u8], tt
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn delete_keys(con: &mut redis::aio::MultiplexedConnection, keys: &[Vec<u8>]) -> Result<u64, String> {
|
||||
pub async fn delete_keys<C>(con: &mut C, keys: &[Vec<u8>]) -> Result<u64, String>
|
||||
where
|
||||
C: ConnectionLike + Send + Sync + Unpin,
|
||||
{
|
||||
let mut cmd = redis::cmd("DEL");
|
||||
for key in keys {
|
||||
cmd.arg(key.as_slice());
|
||||
@@ -868,13 +1223,16 @@ pub async fn delete_keys(con: &mut redis::aio::MultiplexedConnection, keys: &[Ve
|
||||
cmd.query_async(con).await.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
pub async fn load_more_collection(
|
||||
con: &mut redis::aio::MultiplexedConnection,
|
||||
pub async fn load_more_collection<C>(
|
||||
con: &mut C,
|
||||
key: &[u8],
|
||||
key_type: &str,
|
||||
cursor: u64,
|
||||
count: usize,
|
||||
) -> Result<RedisValue, String> {
|
||||
) -> Result<RedisValue, String>
|
||||
where
|
||||
C: ConnectionLike + Send + Sync + Unpin,
|
||||
{
|
||||
let (value, next_cursor) = match key_type {
|
||||
"list" => {
|
||||
let start = cursor as i64;
|
||||
@@ -916,12 +1274,15 @@ pub async fn load_more_collection(
|
||||
})
|
||||
}
|
||||
|
||||
async fn hscan_page_raw(
|
||||
con: &mut redis::aio::MultiplexedConnection,
|
||||
async fn hscan_page_raw<C>(
|
||||
con: &mut C,
|
||||
key: &[u8],
|
||||
cursor: u64,
|
||||
count: usize,
|
||||
) -> Result<(u64, Vec<serde_json::Value>), String> {
|
||||
) -> Result<(u64, Vec<serde_json::Value>), String>
|
||||
where
|
||||
C: ConnectionLike + Send + Sync + Unpin,
|
||||
{
|
||||
let raw: RedisRawValue = redis::cmd("HSCAN")
|
||||
.arg(key)
|
||||
.arg(cursor)
|
||||
@@ -933,12 +1294,15 @@ async fn hscan_page_raw(
|
||||
parse_scan_pairs(raw, "hash")
|
||||
}
|
||||
|
||||
async fn sscan_page_raw(
|
||||
con: &mut redis::aio::MultiplexedConnection,
|
||||
async fn sscan_page_raw<C>(
|
||||
con: &mut C,
|
||||
key: &[u8],
|
||||
cursor: u64,
|
||||
count: usize,
|
||||
) -> Result<(u64, Vec<serde_json::Value>), String> {
|
||||
) -> Result<(u64, Vec<serde_json::Value>), String>
|
||||
where
|
||||
C: ConnectionLike + Send + Sync + Unpin,
|
||||
{
|
||||
let raw: RedisRawValue = redis::cmd("SSCAN")
|
||||
.arg(key)
|
||||
.arg(cursor)
|
||||
@@ -950,12 +1314,15 @@ async fn sscan_page_raw(
|
||||
parse_scan_members(raw)
|
||||
}
|
||||
|
||||
async fn zscan_page_raw(
|
||||
con: &mut redis::aio::MultiplexedConnection,
|
||||
async fn zscan_page_raw<C>(
|
||||
con: &mut C,
|
||||
key: &[u8],
|
||||
cursor: u64,
|
||||
count: usize,
|
||||
) -> Result<(u64, Vec<serde_json::Value>), String> {
|
||||
) -> Result<(u64, Vec<serde_json::Value>), String>
|
||||
where
|
||||
C: ConnectionLike + Send + Sync + Unpin,
|
||||
{
|
||||
let raw: RedisRawValue = redis::cmd("ZSCAN")
|
||||
.arg(key)
|
||||
.arg(cursor)
|
||||
@@ -1026,11 +1393,11 @@ fn parse_scan_members(raw: RedisRawValue) -> Result<(u64, Vec<serde_json::Value>
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{
|
||||
classify_command, is_redis_json_type, parse_command_argv, parse_database_count, parse_redis_endpoint,
|
||||
parse_scan_keys, parse_stream_entries, redis_command_raw_to_json, redis_json_raw_to_json,
|
||||
redis_json_value_preview, redis_key_bytes_to_display, redis_key_bytes_to_raw, redis_key_raw_to_bytes,
|
||||
redis_key_value_preview, redis_raw_to_json, redis_value_contains_binary, redis_value_matches_query,
|
||||
RedisCommandSafety, RedisRawValue,
|
||||
classify_command, decode_cluster_cursor, encode_cluster_cursor, is_redis_json_type, parse_cluster_slots,
|
||||
parse_command_argv, parse_database_count, parse_redis_endpoint, parse_scan_keys, parse_stream_entries,
|
||||
redis_command_raw_to_json, redis_json_raw_to_json, redis_json_value_preview, redis_key_bytes_to_display,
|
||||
redis_key_bytes_to_raw, redis_key_raw_to_bytes, redis_key_value_preview, redis_raw_to_json,
|
||||
redis_value_contains_binary, redis_value_matches_query, RedisCommandSafety, RedisNodeEndpoint, RedisRawValue,
|
||||
};
|
||||
|
||||
fn bulk(value: &str) -> RedisRawValue {
|
||||
@@ -1209,6 +1576,46 @@ mod tests {
|
||||
assert_eq!(parse_redis_endpoint("::1", 26379).unwrap(), ("::1".to_string(), 26379));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn encodes_and_decodes_cluster_scan_cursor() {
|
||||
let encoded = encode_cluster_cursor(12, 3456).unwrap();
|
||||
|
||||
assert_eq!(decode_cluster_cursor(encoded), (12, 3456));
|
||||
assert_eq!(decode_cluster_cursor(0), (0, 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_cluster_slots_master_nodes() {
|
||||
let raw = RedisRawValue::Array(vec![
|
||||
RedisRawValue::Array(vec![
|
||||
RedisRawValue::Int(0),
|
||||
RedisRawValue::Int(5460),
|
||||
RedisRawValue::Array(vec![
|
||||
RedisRawValue::BulkString(b"10.0.0.1".to_vec()),
|
||||
RedisRawValue::Int(7000),
|
||||
RedisRawValue::BulkString(b"node-a".to_vec()),
|
||||
]),
|
||||
]),
|
||||
RedisRawValue::Array(vec![
|
||||
RedisRawValue::Int(5461),
|
||||
RedisRawValue::Int(10922),
|
||||
RedisRawValue::Array(vec![
|
||||
RedisRawValue::BulkString(b"10.0.0.2".to_vec()),
|
||||
RedisRawValue::Int(7001),
|
||||
RedisRawValue::BulkString(b"node-b".to_vec()),
|
||||
]),
|
||||
]),
|
||||
]);
|
||||
|
||||
assert_eq!(
|
||||
parse_cluster_slots(raw, "127.0.0.1").unwrap(),
|
||||
vec![
|
||||
RedisNodeEndpoint { host: "10.0.0.1".to_string(), port: 7000 },
|
||||
RedisNodeEndpoint { host: "10.0.0.2".to_string(), port: 7001 },
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_redis_json_get_bulk_string() {
|
||||
let raw = bulk(r#"{"id":1,"embedding":[0.1,0.2],"meta":{"source":"test"}}"#);
|
||||
|
||||
@@ -75,6 +75,8 @@ pub struct ConnectionConfig {
|
||||
pub redis_sentinel_password: String,
|
||||
#[serde(default, skip_serializing_if = "is_false")]
|
||||
pub redis_sentinel_tls: bool,
|
||||
#[serde(default, skip_serializing_if = "String::is_empty")]
|
||||
pub redis_cluster_nodes: String,
|
||||
/// Typed configuration for external tabular sources.
|
||||
#[serde(default)]
|
||||
pub external_config: Option<serde_json::Value>,
|
||||
@@ -251,6 +253,11 @@ impl ConnectionConfig {
|
||||
&& self.redis_connection_mode.as_deref().is_some_and(|mode| mode.eq_ignore_ascii_case("sentinel"))
|
||||
}
|
||||
|
||||
pub fn uses_redis_cluster(&self) -> bool {
|
||||
self.db_type == DatabaseType::Redis
|
||||
&& self.redis_connection_mode.as_deref().is_some_and(|mode| mode.eq_ignore_ascii_case("cluster"))
|
||||
}
|
||||
|
||||
pub fn connection_url(&self) -> String {
|
||||
self.connection_url_with_host(&self.host, self.port)
|
||||
}
|
||||
@@ -837,6 +844,7 @@ mod tests {
|
||||
redis_sentinel_username: String::new(),
|
||||
redis_sentinel_password: String::new(),
|
||||
redis_sentinel_tls: false,
|
||||
redis_cluster_nodes: String::new(),
|
||||
external_config: None,
|
||||
jdbc_driver_class: None,
|
||||
jdbc_driver_paths: Vec::new(),
|
||||
|
||||
@@ -1423,6 +1423,7 @@ mod tests {
|
||||
redis_sentinel_username: String::new(),
|
||||
redis_sentinel_password: String::new(),
|
||||
redis_sentinel_tls: false,
|
||||
redis_cluster_nodes: String::new(),
|
||||
external_config: None,
|
||||
jdbc_driver_class: None,
|
||||
jdbc_driver_paths: Vec::new(),
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
use crate::connection::{AppState, PoolKind};
|
||||
use crate::db::redis_driver::{self, RedisCommandResult, RedisDatabaseInfo, RedisScanResult, RedisValue};
|
||||
use crate::db::redis_driver::{
|
||||
self, RedisCommandResult, RedisConnection, RedisDatabaseInfo, RedisScanResult, RedisValue,
|
||||
};
|
||||
|
||||
pub async fn redis_list_databases_core(
|
||||
state: &AppState,
|
||||
@@ -8,10 +10,13 @@ pub async fn redis_list_databases_core(
|
||||
let connections = state.connections.read().await;
|
||||
let pool = connections.get(connection_id).ok_or("Connection not found")?;
|
||||
match pool {
|
||||
PoolKind::Redis(con) => {
|
||||
let mut con = con.lock().await;
|
||||
redis_driver::list_databases(&mut con).await
|
||||
}
|
||||
PoolKind::Redis(redis) => match redis {
|
||||
RedisConnection::Direct(con) => {
|
||||
let mut con = con.lock().await;
|
||||
redis_driver::list_databases(&mut *con).await
|
||||
}
|
||||
RedisConnection::Cluster(cluster) => redis_driver::list_cluster_databases(cluster).await,
|
||||
},
|
||||
_ => Err("Not a Redis connection".to_string()),
|
||||
}
|
||||
}
|
||||
@@ -27,11 +32,17 @@ pub async fn redis_scan_keys_core(
|
||||
let connections = state.connections.read().await;
|
||||
let pool = connections.get(connection_id).ok_or("Connection not found")?;
|
||||
match pool {
|
||||
PoolKind::Redis(con) => {
|
||||
let mut con = con.lock().await;
|
||||
redis_driver::select_db(&mut con, db).await?;
|
||||
redis_driver::scan_keys_page(&mut con, cursor, pattern, count).await
|
||||
}
|
||||
PoolKind::Redis(redis) => match redis {
|
||||
RedisConnection::Direct(con) => {
|
||||
let mut con = con.lock().await;
|
||||
redis_driver::select_db(&mut *con, db).await?;
|
||||
redis_driver::scan_keys_page(&mut *con, cursor, pattern, count).await
|
||||
}
|
||||
RedisConnection::Cluster(cluster) => {
|
||||
redis_driver::ensure_cluster_db(db)?;
|
||||
redis_driver::scan_cluster_keys_page(cluster, cursor, pattern, count).await
|
||||
}
|
||||
},
|
||||
_ => Err("Not a Redis connection".to_string()),
|
||||
}
|
||||
}
|
||||
@@ -48,11 +59,17 @@ pub async fn redis_scan_values_core(
|
||||
let connections = state.connections.read().await;
|
||||
let pool = connections.get(connection_id).ok_or("Connection not found")?;
|
||||
match pool {
|
||||
PoolKind::Redis(con) => {
|
||||
let mut con = con.lock().await;
|
||||
redis_driver::select_db(&mut con, db).await?;
|
||||
redis_driver::scan_values_page(&mut con, cursor, pattern, query, count).await
|
||||
}
|
||||
PoolKind::Redis(redis) => match redis {
|
||||
RedisConnection::Direct(con) => {
|
||||
let mut con = con.lock().await;
|
||||
redis_driver::select_db(&mut *con, db).await?;
|
||||
redis_driver::scan_values_page(&mut *con, cursor, pattern, query, count).await
|
||||
}
|
||||
RedisConnection::Cluster(cluster) => {
|
||||
redis_driver::ensure_cluster_db(db)?;
|
||||
redis_driver::scan_cluster_values_page(cluster, cursor, pattern, query, count).await
|
||||
}
|
||||
},
|
||||
_ => Err("Not a Redis connection".to_string()),
|
||||
}
|
||||
}
|
||||
@@ -70,11 +87,20 @@ pub async fn redis_get_value_in_db_core(
|
||||
let connections = state.connections.read().await;
|
||||
let pool = connections.get(connection_id).ok_or("Connection not found")?;
|
||||
match pool {
|
||||
PoolKind::Redis(con) => {
|
||||
let mut con = con.lock().await;
|
||||
PoolKind::Redis(redis) => {
|
||||
let key = redis_driver::redis_key_raw_to_bytes(key_raw)?;
|
||||
redis_driver::select_db(&mut con, db).await?;
|
||||
redis_driver::get_value(&mut con, &key).await
|
||||
match redis {
|
||||
RedisConnection::Direct(con) => {
|
||||
let mut con = con.lock().await;
|
||||
redis_driver::select_db(&mut *con, db).await?;
|
||||
redis_driver::get_value(&mut *con, &key).await
|
||||
}
|
||||
RedisConnection::Cluster(cluster) => {
|
||||
redis_driver::ensure_cluster_db(db)?;
|
||||
let mut con = cluster.connection.lock().await;
|
||||
redis_driver::get_value(&mut *con, &key).await
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => Err("Not a Redis connection".to_string()),
|
||||
}
|
||||
@@ -101,11 +127,20 @@ pub async fn redis_set_string_in_db_core(
|
||||
let connections = state.connections.read().await;
|
||||
let pool = connections.get(connection_id).ok_or("Connection not found")?;
|
||||
match pool {
|
||||
PoolKind::Redis(con) => {
|
||||
let mut con = con.lock().await;
|
||||
PoolKind::Redis(redis) => {
|
||||
let key = redis_driver::redis_key_raw_to_bytes(key_raw)?;
|
||||
redis_driver::select_db(&mut con, db).await?;
|
||||
redis_driver::set_string(&mut con, &key, value, ttl).await
|
||||
match redis {
|
||||
RedisConnection::Direct(con) => {
|
||||
let mut con = con.lock().await;
|
||||
redis_driver::select_db(&mut *con, db).await?;
|
||||
redis_driver::set_string(&mut *con, &key, value, ttl).await
|
||||
}
|
||||
RedisConnection::Cluster(cluster) => {
|
||||
redis_driver::ensure_cluster_db(db)?;
|
||||
let mut con = cluster.connection.lock().await;
|
||||
redis_driver::set_string(&mut *con, &key, value, ttl).await
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => Err("Not a Redis connection".to_string()),
|
||||
}
|
||||
@@ -124,11 +159,20 @@ pub async fn redis_delete_key_in_db_core(
|
||||
let connections = state.connections.read().await;
|
||||
let pool = connections.get(connection_id).ok_or("Connection not found")?;
|
||||
match pool {
|
||||
PoolKind::Redis(con) => {
|
||||
let mut con = con.lock().await;
|
||||
PoolKind::Redis(redis) => {
|
||||
let key = redis_driver::redis_key_raw_to_bytes(key_raw)?;
|
||||
redis_driver::select_db(&mut con, db).await?;
|
||||
redis_driver::delete_key(&mut con, &key).await
|
||||
match redis {
|
||||
RedisConnection::Direct(con) => {
|
||||
let mut con = con.lock().await;
|
||||
redis_driver::select_db(&mut *con, db).await?;
|
||||
redis_driver::delete_key(&mut *con, &key).await
|
||||
}
|
||||
RedisConnection::Cluster(cluster) => {
|
||||
redis_driver::ensure_cluster_db(db)?;
|
||||
let mut con = cluster.connection.lock().await;
|
||||
redis_driver::delete_key(&mut *con, &key).await
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => Err("Not a Redis connection".to_string()),
|
||||
}
|
||||
@@ -154,11 +198,20 @@ pub async fn redis_hash_set_in_db_core(
|
||||
) -> Result<(), String> {
|
||||
let connections = state.connections.read().await;
|
||||
match connections.get(connection_id).ok_or("Not found")? {
|
||||
PoolKind::Redis(con) => {
|
||||
let mut con = con.lock().await;
|
||||
PoolKind::Redis(redis) => {
|
||||
let key = redis_driver::redis_key_raw_to_bytes(key_raw)?;
|
||||
redis_driver::select_db(&mut con, db).await?;
|
||||
redis_driver::hash_set(&mut con, &key, field, value).await
|
||||
match redis {
|
||||
RedisConnection::Direct(con) => {
|
||||
let mut con = con.lock().await;
|
||||
redis_driver::select_db(&mut *con, db).await?;
|
||||
redis_driver::hash_set(&mut *con, &key, field, value).await
|
||||
}
|
||||
RedisConnection::Cluster(cluster) => {
|
||||
redis_driver::ensure_cluster_db(db)?;
|
||||
let mut con = cluster.connection.lock().await;
|
||||
redis_driver::hash_set(&mut *con, &key, field, value).await
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => Err("Not a Redis connection".to_string()),
|
||||
}
|
||||
@@ -177,11 +230,20 @@ pub async fn redis_hash_del_in_db_core(
|
||||
) -> Result<(), String> {
|
||||
let connections = state.connections.read().await;
|
||||
match connections.get(connection_id).ok_or("Not found")? {
|
||||
PoolKind::Redis(con) => {
|
||||
let mut con = con.lock().await;
|
||||
PoolKind::Redis(redis) => {
|
||||
let key = redis_driver::redis_key_raw_to_bytes(key_raw)?;
|
||||
redis_driver::select_db(&mut con, db).await?;
|
||||
redis_driver::hash_del(&mut con, &key, field).await
|
||||
match redis {
|
||||
RedisConnection::Direct(con) => {
|
||||
let mut con = con.lock().await;
|
||||
redis_driver::select_db(&mut *con, db).await?;
|
||||
redis_driver::hash_del(&mut *con, &key, field).await
|
||||
}
|
||||
RedisConnection::Cluster(cluster) => {
|
||||
redis_driver::ensure_cluster_db(db)?;
|
||||
let mut con = cluster.connection.lock().await;
|
||||
redis_driver::hash_del(&mut *con, &key, field).await
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => Err("Not a Redis connection".to_string()),
|
||||
}
|
||||
@@ -200,11 +262,20 @@ pub async fn redis_list_push_in_db_core(
|
||||
) -> Result<(), String> {
|
||||
let connections = state.connections.read().await;
|
||||
match connections.get(connection_id).ok_or("Not found")? {
|
||||
PoolKind::Redis(con) => {
|
||||
let mut con = con.lock().await;
|
||||
PoolKind::Redis(redis) => {
|
||||
let key = redis_driver::redis_key_raw_to_bytes(key_raw)?;
|
||||
redis_driver::select_db(&mut con, db).await?;
|
||||
redis_driver::list_push(&mut con, &key, value).await
|
||||
match redis {
|
||||
RedisConnection::Direct(con) => {
|
||||
let mut con = con.lock().await;
|
||||
redis_driver::select_db(&mut *con, db).await?;
|
||||
redis_driver::list_push(&mut *con, &key, value).await
|
||||
}
|
||||
RedisConnection::Cluster(cluster) => {
|
||||
redis_driver::ensure_cluster_db(db)?;
|
||||
let mut con = cluster.connection.lock().await;
|
||||
redis_driver::list_push(&mut *con, &key, value).await
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => Err("Not a Redis connection".to_string()),
|
||||
}
|
||||
@@ -220,11 +291,20 @@ pub async fn redis_list_set_in_db_core(
|
||||
) -> Result<(), String> {
|
||||
let connections = state.connections.read().await;
|
||||
match connections.get(connection_id).ok_or("Not found")? {
|
||||
PoolKind::Redis(con) => {
|
||||
let mut con = con.lock().await;
|
||||
PoolKind::Redis(redis) => {
|
||||
let key = redis_driver::redis_key_raw_to_bytes(key_raw)?;
|
||||
redis_driver::select_db(&mut con, db).await?;
|
||||
redis_driver::list_set(&mut con, &key, index, value).await
|
||||
match redis {
|
||||
RedisConnection::Direct(con) => {
|
||||
let mut con = con.lock().await;
|
||||
redis_driver::select_db(&mut *con, db).await?;
|
||||
redis_driver::list_set(&mut *con, &key, index, value).await
|
||||
}
|
||||
RedisConnection::Cluster(cluster) => {
|
||||
redis_driver::ensure_cluster_db(db)?;
|
||||
let mut con = cluster.connection.lock().await;
|
||||
redis_driver::list_set(&mut *con, &key, index, value).await
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => Err("Not a Redis connection".to_string()),
|
||||
}
|
||||
@@ -248,11 +328,20 @@ pub async fn redis_list_remove_in_db_core(
|
||||
) -> Result<(), String> {
|
||||
let connections = state.connections.read().await;
|
||||
match connections.get(connection_id).ok_or("Not found")? {
|
||||
PoolKind::Redis(con) => {
|
||||
let mut con = con.lock().await;
|
||||
PoolKind::Redis(redis) => {
|
||||
let key = redis_driver::redis_key_raw_to_bytes(key_raw)?;
|
||||
redis_driver::select_db(&mut con, db).await?;
|
||||
redis_driver::list_remove(&mut con, &key, index).await
|
||||
match redis {
|
||||
RedisConnection::Direct(con) => {
|
||||
let mut con = con.lock().await;
|
||||
redis_driver::select_db(&mut *con, db).await?;
|
||||
redis_driver::list_remove(&mut *con, &key, index).await
|
||||
}
|
||||
RedisConnection::Cluster(cluster) => {
|
||||
redis_driver::ensure_cluster_db(db)?;
|
||||
let mut con = cluster.connection.lock().await;
|
||||
redis_driver::list_remove(&mut *con, &key, index).await
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => Err("Not a Redis connection".to_string()),
|
||||
}
|
||||
@@ -271,11 +360,20 @@ pub async fn redis_set_add_in_db_core(
|
||||
) -> Result<(), String> {
|
||||
let connections = state.connections.read().await;
|
||||
match connections.get(connection_id).ok_or("Not found")? {
|
||||
PoolKind::Redis(con) => {
|
||||
let mut con = con.lock().await;
|
||||
PoolKind::Redis(redis) => {
|
||||
let key = redis_driver::redis_key_raw_to_bytes(key_raw)?;
|
||||
redis_driver::select_db(&mut con, db).await?;
|
||||
redis_driver::set_add(&mut con, &key, member).await
|
||||
match redis {
|
||||
RedisConnection::Direct(con) => {
|
||||
let mut con = con.lock().await;
|
||||
redis_driver::select_db(&mut *con, db).await?;
|
||||
redis_driver::set_add(&mut *con, &key, member).await
|
||||
}
|
||||
RedisConnection::Cluster(cluster) => {
|
||||
redis_driver::ensure_cluster_db(db)?;
|
||||
let mut con = cluster.connection.lock().await;
|
||||
redis_driver::set_add(&mut *con, &key, member).await
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => Err("Not a Redis connection".to_string()),
|
||||
}
|
||||
@@ -299,11 +397,20 @@ pub async fn redis_set_remove_in_db_core(
|
||||
) -> Result<(), String> {
|
||||
let connections = state.connections.read().await;
|
||||
match connections.get(connection_id).ok_or("Not found")? {
|
||||
PoolKind::Redis(con) => {
|
||||
let mut con = con.lock().await;
|
||||
PoolKind::Redis(redis) => {
|
||||
let key = redis_driver::redis_key_raw_to_bytes(key_raw)?;
|
||||
redis_driver::select_db(&mut con, db).await?;
|
||||
redis_driver::set_remove(&mut con, &key, member).await
|
||||
match redis {
|
||||
RedisConnection::Direct(con) => {
|
||||
let mut con = con.lock().await;
|
||||
redis_driver::select_db(&mut *con, db).await?;
|
||||
redis_driver::set_remove(&mut *con, &key, member).await
|
||||
}
|
||||
RedisConnection::Cluster(cluster) => {
|
||||
redis_driver::ensure_cluster_db(db)?;
|
||||
let mut con = cluster.connection.lock().await;
|
||||
redis_driver::set_remove(&mut *con, &key, member).await
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => Err("Not a Redis connection".to_string()),
|
||||
}
|
||||
@@ -319,11 +426,20 @@ pub async fn redis_zadd_in_db_core(
|
||||
) -> Result<(), String> {
|
||||
let connections = state.connections.read().await;
|
||||
match connections.get(connection_id).ok_or("Not found")? {
|
||||
PoolKind::Redis(con) => {
|
||||
let mut con = con.lock().await;
|
||||
PoolKind::Redis(redis) => {
|
||||
let key = redis_driver::redis_key_raw_to_bytes(key_raw)?;
|
||||
redis_driver::select_db(&mut con, db).await?;
|
||||
redis_driver::zadd(&mut con, &key, member, score).await
|
||||
match redis {
|
||||
RedisConnection::Direct(con) => {
|
||||
let mut con = con.lock().await;
|
||||
redis_driver::select_db(&mut *con, db).await?;
|
||||
redis_driver::zadd(&mut *con, &key, member, score).await
|
||||
}
|
||||
RedisConnection::Cluster(cluster) => {
|
||||
redis_driver::ensure_cluster_db(db)?;
|
||||
let mut con = cluster.connection.lock().await;
|
||||
redis_driver::zadd(&mut *con, &key, member, score).await
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => Err("Not a Redis connection".to_string()),
|
||||
}
|
||||
@@ -338,11 +454,20 @@ pub async fn redis_zrem_in_db_core(
|
||||
) -> Result<(), String> {
|
||||
let connections = state.connections.read().await;
|
||||
match connections.get(connection_id).ok_or("Not found")? {
|
||||
PoolKind::Redis(con) => {
|
||||
let mut con = con.lock().await;
|
||||
PoolKind::Redis(redis) => {
|
||||
let key = redis_driver::redis_key_raw_to_bytes(key_raw)?;
|
||||
redis_driver::select_db(&mut con, db).await?;
|
||||
redis_driver::zrem(&mut con, &key, member).await
|
||||
match redis {
|
||||
RedisConnection::Direct(con) => {
|
||||
let mut con = con.lock().await;
|
||||
redis_driver::select_db(&mut *con, db).await?;
|
||||
redis_driver::zrem(&mut *con, &key, member).await
|
||||
}
|
||||
RedisConnection::Cluster(cluster) => {
|
||||
redis_driver::ensure_cluster_db(db)?;
|
||||
let mut con = cluster.connection.lock().await;
|
||||
redis_driver::zrem(&mut *con, &key, member).await
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => Err("Not a Redis connection".to_string()),
|
||||
}
|
||||
@@ -357,11 +482,20 @@ pub async fn redis_set_ttl_in_db_core(
|
||||
) -> Result<(), String> {
|
||||
let connections = state.connections.read().await;
|
||||
match connections.get(connection_id).ok_or("Not found")? {
|
||||
PoolKind::Redis(con) => {
|
||||
let mut con = con.lock().await;
|
||||
PoolKind::Redis(redis) => {
|
||||
let key = redis_driver::redis_key_raw_to_bytes(key_raw)?;
|
||||
redis_driver::select_db(&mut con, db).await?;
|
||||
redis_driver::set_ttl(&mut con, &key, ttl).await
|
||||
match redis {
|
||||
RedisConnection::Direct(con) => {
|
||||
let mut con = con.lock().await;
|
||||
redis_driver::select_db(&mut *con, db).await?;
|
||||
redis_driver::set_ttl(&mut *con, &key, ttl).await
|
||||
}
|
||||
RedisConnection::Cluster(cluster) => {
|
||||
redis_driver::ensure_cluster_db(db)?;
|
||||
let mut con = cluster.connection.lock().await;
|
||||
redis_driver::set_ttl(&mut *con, &key, ttl).await
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => Err("Not a Redis connection".to_string()),
|
||||
}
|
||||
@@ -375,12 +509,26 @@ pub async fn redis_delete_keys_in_db_core(
|
||||
) -> Result<u64, String> {
|
||||
let connections = state.connections.read().await;
|
||||
match connections.get(connection_id).ok_or("Not found")? {
|
||||
PoolKind::Redis(con) => {
|
||||
let mut con = con.lock().await;
|
||||
redis_driver::select_db(&mut con, db).await?;
|
||||
PoolKind::Redis(redis) => {
|
||||
let keys: Result<Vec<Vec<u8>>, String> =
|
||||
key_raws.iter().map(|k| redis_driver::redis_key_raw_to_bytes(k)).collect();
|
||||
redis_driver::delete_keys(&mut con, &keys?).await
|
||||
let keys = keys?;
|
||||
match redis {
|
||||
RedisConnection::Direct(con) => {
|
||||
let mut con = con.lock().await;
|
||||
redis_driver::select_db(&mut *con, db).await?;
|
||||
redis_driver::delete_keys(&mut *con, &keys).await
|
||||
}
|
||||
RedisConnection::Cluster(cluster) => {
|
||||
redis_driver::ensure_cluster_db(db)?;
|
||||
let mut con = cluster.connection.lock().await;
|
||||
let mut deleted = 0;
|
||||
for key in &keys {
|
||||
deleted += redis_driver::delete_keys(&mut *con, std::slice::from_ref(key)).await?;
|
||||
}
|
||||
Ok(deleted)
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => Err("Not a Redis connection".to_string()),
|
||||
}
|
||||
@@ -389,11 +537,17 @@ pub async fn redis_delete_keys_in_db_core(
|
||||
pub async fn redis_flush_db_core(state: &AppState, connection_id: &str, db: u32) -> Result<(), String> {
|
||||
let connections = state.connections.read().await;
|
||||
match connections.get(connection_id).ok_or("Not found")? {
|
||||
PoolKind::Redis(con) => {
|
||||
let mut con = con.lock().await;
|
||||
redis_driver::select_db(&mut con, db).await?;
|
||||
redis_driver::flush_db(&mut con).await
|
||||
}
|
||||
PoolKind::Redis(redis) => match redis {
|
||||
RedisConnection::Direct(con) => {
|
||||
let mut con = con.lock().await;
|
||||
redis_driver::select_db(&mut *con, db).await?;
|
||||
redis_driver::flush_db(&mut *con).await
|
||||
}
|
||||
RedisConnection::Cluster(cluster) => {
|
||||
redis_driver::ensure_cluster_db(db)?;
|
||||
redis_driver::flush_cluster(cluster).await
|
||||
}
|
||||
},
|
||||
_ => Err("Not a Redis connection".to_string()),
|
||||
}
|
||||
}
|
||||
@@ -406,11 +560,23 @@ pub async fn redis_execute_command_core(
|
||||
) -> Result<RedisCommandResult, String> {
|
||||
let connections = state.connections.read().await;
|
||||
match connections.get(connection_id).ok_or("Not found")? {
|
||||
PoolKind::Redis(con) => {
|
||||
let mut con = con.lock().await;
|
||||
redis_driver::select_db(&mut con, db).await?;
|
||||
redis_driver::execute_command(&mut con, command).await
|
||||
}
|
||||
PoolKind::Redis(redis) => match redis {
|
||||
RedisConnection::Direct(con) => {
|
||||
let mut con = con.lock().await;
|
||||
redis_driver::select_db(&mut *con, db).await?;
|
||||
redis_driver::execute_command(&mut *con, command).await
|
||||
}
|
||||
RedisConnection::Cluster(cluster) => {
|
||||
redis_driver::ensure_cluster_db(db)?;
|
||||
if let Ok(argv) = redis_driver::parse_command_argv(command) {
|
||||
if argv.first().is_some_and(|name| name.eq_ignore_ascii_case("SELECT")) {
|
||||
return Err("Redis Cluster only supports db0; SELECT is not available".to_string());
|
||||
}
|
||||
}
|
||||
let mut con = cluster.connection.lock().await;
|
||||
redis_driver::execute_command(&mut *con, command).await
|
||||
}
|
||||
},
|
||||
_ => Err("Not a Redis connection".to_string()),
|
||||
}
|
||||
}
|
||||
@@ -426,11 +592,20 @@ pub async fn redis_load_more_in_db_core(
|
||||
) -> Result<redis_driver::RedisValue, String> {
|
||||
let connections = state.connections.read().await;
|
||||
match connections.get(connection_id).ok_or("Not found")? {
|
||||
PoolKind::Redis(con) => {
|
||||
let mut con = con.lock().await;
|
||||
PoolKind::Redis(redis) => {
|
||||
let key = redis_driver::redis_key_raw_to_bytes(key_raw)?;
|
||||
redis_driver::select_db(&mut con, db).await?;
|
||||
redis_driver::load_more_collection(&mut con, &key, key_type, cursor, count).await
|
||||
match redis {
|
||||
RedisConnection::Direct(con) => {
|
||||
let mut con = con.lock().await;
|
||||
redis_driver::select_db(&mut *con, db).await?;
|
||||
redis_driver::load_more_collection(&mut *con, &key, key_type, cursor, count).await
|
||||
}
|
||||
RedisConnection::Cluster(cluster) => {
|
||||
redis_driver::ensure_cluster_db(db)?;
|
||||
let mut con = cluster.connection.lock().await;
|
||||
redis_driver::load_more_collection(&mut *con, &key, key_type, cursor, count).await
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => Err("Not a Redis connection".to_string()),
|
||||
}
|
||||
|
||||
@@ -1268,6 +1268,7 @@ mod tests {
|
||||
redis_sentinel_username: String::new(),
|
||||
redis_sentinel_password: String::new(),
|
||||
redis_sentinel_tls: false,
|
||||
redis_cluster_nodes: String::new(),
|
||||
external_config: None,
|
||||
jdbc_driver_class: None,
|
||||
jdbc_driver_paths: Vec::new(),
|
||||
|
||||
@@ -2,18 +2,21 @@ import { readFileSync } from "node:fs";
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
|
||||
test("Redis connection dialog exposes standalone and sentinel modes", () => {
|
||||
test("Redis connection dialog exposes standalone, sentinel, and cluster modes", () => {
|
||||
const source = readFileSync("apps/desktop/src/components/connection/ConnectionDialog.vue", "utf8");
|
||||
|
||||
assert.match(source, /redis_connection_mode: "standalone"/);
|
||||
assert.match(source, /form\.redis_connection_mode === 'sentinel'/);
|
||||
assert.match(source, /form\.redis_connection_mode === 'cluster'/);
|
||||
assert.match(source, /t\("connection\.redisStandaloneMode"\)/);
|
||||
assert.match(source, /t\("connection\.redisSentinelMode"\)/);
|
||||
assert.match(source, /t\("connection\.redisClusterMode"\)/);
|
||||
assert.match(source, /v-model="form\.redis_sentinel_nodes"/);
|
||||
assert.match(source, /v-model="form\.redis_sentinel_master"/);
|
||||
assert.match(source, /v-model="form\.redis_sentinel_username"/);
|
||||
assert.match(source, /v-model="form\.redis_sentinel_password"/);
|
||||
assert.match(source, /v-model="form\.redis_sentinel_tls"/);
|
||||
assert.match(source, /v-model="form\.redis_cluster_nodes"/);
|
||||
});
|
||||
|
||||
test("Redis sentinel submit config normalizes nodes and uses the first sentinel as endpoint", () => {
|
||||
@@ -27,24 +30,41 @@ test("Redis sentinel submit config normalizes nodes and uses the first sentinel
|
||||
assert.match(source, /config\.redis_connection_mode = "standalone"/);
|
||||
});
|
||||
|
||||
test("Redis sentinel fields are typed and localized", () => {
|
||||
test("Redis cluster submit config normalizes nodes and uses the first cluster seed as endpoint", () => {
|
||||
const source = readFileSync("apps/desktop/src/components/connection/ConnectionDialog.vue", "utf8");
|
||||
|
||||
assert.match(source, /normalizeRedisClusterNodes/);
|
||||
assert.match(source, /firstRedisClusterEndpoint/);
|
||||
assert.match(source, /config\.redis_cluster_nodes = normalizeRedisClusterNodes\(config\.redis_cluster_nodes \|\| ""\)/);
|
||||
assert.match(source, /config\.host = firstNode\.host/);
|
||||
assert.match(source, /config\.port = firstNode\.port/);
|
||||
});
|
||||
|
||||
test("Redis sentinel and cluster fields are typed and localized", () => {
|
||||
const typesSource = readFileSync("apps/desktop/src/types/database.ts", "utf8");
|
||||
const zhSource = readFileSync("apps/desktop/src/i18n/locales/zh-CN.ts", "utf8");
|
||||
const enSource = readFileSync("apps/desktop/src/i18n/locales/en.ts", "utf8");
|
||||
|
||||
assert.match(typesSource, /redis_connection_mode\?: "standalone" \| "sentinel"/);
|
||||
assert.match(typesSource, /redis_connection_mode\?: "standalone" \| "sentinel" \| "cluster"/);
|
||||
assert.match(typesSource, /redis_sentinel_master\?: string/);
|
||||
assert.match(typesSource, /redis_sentinel_nodes\?: string/);
|
||||
assert.match(typesSource, /redis_sentinel_password\?: string/);
|
||||
assert.match(typesSource, /redis_cluster_nodes\?: string/);
|
||||
assert.match(zhSource, /redisSentinelMode: "哨兵"/);
|
||||
assert.match(zhSource, /redisClusterMode: "集群"/);
|
||||
assert.match(enSource, /redisSentinelMode: "Sentinel"/);
|
||||
assert.match(enSource, /redisClusterMode: "Cluster"/);
|
||||
});
|
||||
|
||||
test("Tauri Redis connection commands route sentinel configs through the sentinel connector", () => {
|
||||
test("Tauri Redis connection commands route sentinel and cluster configs through the matching connector", () => {
|
||||
const source = readFileSync("src-tauri/src/commands/connection.rs", "utf8");
|
||||
|
||||
assert.match(source, /config\.uses_redis_sentinel\(\)/);
|
||||
assert.match(source, /config\.uses_redis_cluster\(\)/);
|
||||
assert.match(source, /db_config\.uses_redis_sentinel\(\)/);
|
||||
assert.match(source, /db_config\.uses_redis_cluster\(\)/);
|
||||
assert.match(source, /db::redis_driver::connect_sentinel\(&config\)/);
|
||||
assert.match(source, /db::redis_driver::connect_sentinel\(&db_config\)/);
|
||||
assert.match(source, /db::redis_driver::connect_cluster\(&config\)/);
|
||||
assert.match(source, /db::redis_driver::connect_cluster\(&db_config\)/);
|
||||
});
|
||||
|
||||
@@ -38,7 +38,10 @@ test("Redis value search streams incremental scan pages from the browser", () =>
|
||||
const driverSource = readFileSync("crates/dbx-core/src/db/redis_driver.rs", "utf8");
|
||||
|
||||
assert.match(browserSource, /async function streamValueSearch/);
|
||||
assert.match(browserSource, /async function fillInitialKeyBatch/);
|
||||
assert.match(browserSource, /searchRequestId/);
|
||||
assert.match(browserSource, /redis\.searchingValues/);
|
||||
assert.match(browserSource, /flatKeys\.value\.length < targetCount/);
|
||||
assert.match(browserSource, /await fillInitialKeyBatch\(requestId\)/);
|
||||
assert.doesNotMatch(driverSource, /while\s+result\.len\(\)\s*<\s*target_count/);
|
||||
});
|
||||
|
||||
@@ -36,7 +36,7 @@ tauri-plugin-shell = "2"
|
||||
tauri-plugin-updater = "2"
|
||||
tauri-plugin-process = "2"
|
||||
tauri-plugin-window-state = "2"
|
||||
redis = { version = "0.32.2", features = ["tokio-comp", "tls-rustls", "tokio-rustls-comp"] }
|
||||
redis = { version = "0.32.2", features = ["tokio-comp", "tls-rustls", "tokio-rustls-comp", "cluster-async"] }
|
||||
rustls = { version = "0.23", features = ["aws-lc-rs"] }
|
||||
portpicker = "0.1.1"
|
||||
duckdb = "1.3.2"
|
||||
|
||||
@@ -162,6 +162,7 @@ mod tests {
|
||||
redis_sentinel_username: String::new(),
|
||||
redis_sentinel_password: String::new(),
|
||||
redis_sentinel_tls: false,
|
||||
redis_cluster_nodes: String::new(),
|
||||
external_config: None,
|
||||
jdbc_driver_class: None,
|
||||
jdbc_driver_paths: Vec::new(),
|
||||
@@ -257,7 +258,10 @@ pub async fn test_connection(state: State<'_, Arc<AppState>>, config: Connection
|
||||
Err(e) => Err(e),
|
||||
},
|
||||
DatabaseType::Redis => {
|
||||
let con = if config.uses_redis_sentinel() {
|
||||
let con = if config.uses_redis_cluster() {
|
||||
db::redis_driver::connect_cluster(&config).await?;
|
||||
return Ok("Connection successful".to_string());
|
||||
} else if config.uses_redis_sentinel() {
|
||||
db::redis_driver::connect_sentinel(&config).await?
|
||||
} else {
|
||||
db::redis_driver::connect(&url).await?
|
||||
@@ -375,12 +379,20 @@ pub async fn connect_db(state: State<'_, Arc<AppState>>, config: ConnectionConfi
|
||||
}
|
||||
DatabaseType::Sqlite => PoolKind::Sqlite(db::sqlite::connect_path(&expand_tilde(&db_config.host)).await?),
|
||||
DatabaseType::Redis => {
|
||||
let con = if db_config.uses_redis_sentinel() {
|
||||
db::redis_driver::connect_sentinel(&db_config).await?
|
||||
let con = if db_config.uses_redis_cluster() {
|
||||
PoolKind::Redis(db::redis_driver::RedisConnection::Cluster(
|
||||
db::redis_driver::connect_cluster(&db_config).await?,
|
||||
))
|
||||
} else if db_config.uses_redis_sentinel() {
|
||||
PoolKind::Redis(db::redis_driver::RedisConnection::Direct(tokio::sync::Mutex::new(
|
||||
db::redis_driver::connect_sentinel(&db_config).await?,
|
||||
)))
|
||||
} else {
|
||||
db::redis_driver::connect(&url).await?
|
||||
PoolKind::Redis(db::redis_driver::RedisConnection::Direct(tokio::sync::Mutex::new(
|
||||
db::redis_driver::connect(&url).await?,
|
||||
)))
|
||||
};
|
||||
PoolKind::Redis(tokio::sync::Mutex::new(con))
|
||||
con
|
||||
}
|
||||
DatabaseType::DuckDb => {
|
||||
let con = db::duckdb_driver::connect_path(&expand_tilde(&db_config.host))?;
|
||||
|
||||
Reference in New Issue
Block a user