434 lines
16 KiB
Rust
434 lines
16 KiB
Rust
use core::str;
|
|
use std::collections::HashMap;
|
|
use std::sync::Arc;
|
|
use tokio::io::AsyncReadExt;
|
|
use tokio::io::AsyncWriteExt;
|
|
use tokio::sync::{Mutex, oneshot};
|
|
|
|
use std::sync::atomic::{AtomicU64, Ordering};
|
|
|
|
use crate::cmd::Cmd;
|
|
use crate::error::DBError;
|
|
use crate::options;
|
|
use crate::protocol::Protocol;
|
|
use crate::storage_trait::StorageBackend;
|
|
use crate::admin_meta;
|
|
|
|
// Embeddings: config and cache
|
|
use crate::embedding::{EmbeddingConfig, create_embedder, Embedder};
|
|
use serde_json;
|
|
|
|
#[derive(Clone)]
|
|
pub struct Server {
|
|
pub db_cache: std::sync::Arc<std::sync::RwLock<HashMap<u64, Arc<dyn StorageBackend>>>>,
|
|
pub option: options::DBOption,
|
|
pub client_name: Option<String>,
|
|
pub selected_db: u64, // Changed from usize to u64
|
|
pub queued_cmd: Option<Vec<(Cmd, Protocol)>>,
|
|
pub current_permissions: Option<crate::rpc::Permissions>,
|
|
|
|
// In-memory registry of Tantivy search indexes for this server
|
|
pub search_indexes: Arc<std::sync::RwLock<HashMap<String, Arc<crate::tantivy_search::TantivySearch>>>>,
|
|
|
|
// Per-DB Lance stores (vector DB), keyed by db_id
|
|
pub lance_stores: Arc<std::sync::RwLock<HashMap<u64, Arc<crate::lance_store::LanceStore>>>>,
|
|
|
|
// Per-(db_id, dataset) embedder cache
|
|
pub embedders: Arc<std::sync::RwLock<HashMap<(u64, String), Arc<dyn Embedder>>>>,
|
|
|
|
// BLPOP waiter registry: per (db_index, key) FIFO of waiters
|
|
pub list_waiters: Arc<Mutex<HashMap<u64, HashMap<String, Vec<Waiter>>>>>,
|
|
pub waiter_seq: Arc<AtomicU64>,
|
|
}
|
|
|
|
pub struct Waiter {
|
|
pub id: u64,
|
|
pub side: PopSide,
|
|
pub tx: oneshot::Sender<(String, String)>, // (key, element)
|
|
}
|
|
|
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
|
pub enum PopSide {
|
|
Left,
|
|
Right,
|
|
}
|
|
|
|
impl Server {
|
|
pub async fn new(option: options::DBOption) -> Self {
|
|
Server {
|
|
db_cache: Arc::new(std::sync::RwLock::new(HashMap::new())),
|
|
option,
|
|
client_name: None,
|
|
selected_db: 0,
|
|
queued_cmd: None,
|
|
current_permissions: None,
|
|
|
|
search_indexes: Arc::new(std::sync::RwLock::new(HashMap::new())),
|
|
lance_stores: Arc::new(std::sync::RwLock::new(HashMap::new())),
|
|
embedders: Arc::new(std::sync::RwLock::new(HashMap::new())),
|
|
list_waiters: Arc::new(Mutex::new(HashMap::new())),
|
|
waiter_seq: Arc::new(AtomicU64::new(1)),
|
|
}
|
|
}
|
|
|
|
// Path where search indexes are stored, namespaced per selected DB:
|
|
// <base_dir>/search_indexes/<db_id>
|
|
pub fn search_index_path(&self) -> std::path::PathBuf {
|
|
let base = std::path::PathBuf::from(&self.option.dir)
|
|
.join("search_indexes")
|
|
.join(self.selected_db.to_string());
|
|
if !base.exists() {
|
|
let _ = std::fs::create_dir_all(&base);
|
|
}
|
|
base
|
|
}
|
|
|
|
// Path where Lance datasets are stored, namespaced per selected DB:
|
|
// <base_dir>/lance/<db_id>
|
|
pub fn lance_data_path(&self) -> std::path::PathBuf {
|
|
let base = std::path::PathBuf::from(&self.option.dir)
|
|
.join("lance")
|
|
.join(self.selected_db.to_string());
|
|
if !base.exists() {
|
|
let _ = std::fs::create_dir_all(&base);
|
|
}
|
|
base
|
|
}
|
|
|
|
pub fn current_storage(&self) -> Result<Arc<dyn StorageBackend>, DBError> {
|
|
let mut cache = self.db_cache.write().unwrap();
|
|
|
|
if let Some(storage) = cache.get(&self.selected_db) {
|
|
return Ok(storage.clone());
|
|
}
|
|
|
|
// Use process-wide shared handles to avoid sled/reDB double-open lock contention.
|
|
let storage = if self.selected_db == 0 {
|
|
// Admin DB 0: always via singleton
|
|
admin_meta::open_admin_storage(
|
|
&self.option.dir,
|
|
self.option.backend.clone(),
|
|
&self.option.admin_secret,
|
|
)?
|
|
} else {
|
|
// Data DBs: via global registry keyed by id
|
|
admin_meta::open_data_storage(
|
|
&self.option.dir,
|
|
self.option.backend.clone(),
|
|
&self.option.admin_secret,
|
|
self.selected_db,
|
|
)?
|
|
};
|
|
|
|
cache.insert(self.selected_db, storage.clone());
|
|
Ok(storage)
|
|
}
|
|
|
|
/// Get or create the LanceStore for the currently selected DB.
|
|
/// Only valid for non-zero DBs and when the backend is Lance.
|
|
pub fn lance_store(&self) -> Result<Arc<crate::lance_store::LanceStore>, DBError> {
|
|
if self.selected_db == 0 {
|
|
return Err(DBError("Lance not available on admin DB 0".to_string()));
|
|
}
|
|
// Resolve backend for selected_db
|
|
let backend_opt = crate::admin_meta::get_database_backend(
|
|
&self.option.dir,
|
|
self.option.backend.clone(),
|
|
&self.option.admin_secret,
|
|
self.selected_db,
|
|
)
|
|
.ok()
|
|
.flatten();
|
|
|
|
if !matches!(backend_opt, Some(crate::options::BackendType::Lance)) {
|
|
return Err(DBError("ERR DB backend is not Lance; LANCE.* commands are not allowed".to_string()));
|
|
}
|
|
|
|
// Fast path: read lock
|
|
{
|
|
let map = self.lance_stores.read().unwrap();
|
|
if let Some(store) = map.get(&self.selected_db) {
|
|
return Ok(store.clone());
|
|
}
|
|
}
|
|
|
|
// Slow path: create and insert
|
|
let store = Arc::new(crate::lance_store::LanceStore::new(&self.option.dir, self.selected_db)?);
|
|
{
|
|
let mut map = self.lance_stores.write().unwrap();
|
|
map.insert(self.selected_db, store.clone());
|
|
}
|
|
Ok(store)
|
|
}
|
|
|
|
// ----- Embedding configuration and resolution -----
|
|
|
|
// Sidecar embedding config path: <base_dir>/lance/<db_id>/<dataset>.lance.embedding.json
|
|
fn dataset_embedding_config_path(&self, dataset: &str) -> std::path::PathBuf {
|
|
let mut base = self.lance_data_path();
|
|
// Ensure parent dir exists
|
|
if !base.exists() {
|
|
let _ = std::fs::create_dir_all(&base);
|
|
}
|
|
base.push(format!("{}.lance.embedding.json", dataset));
|
|
base
|
|
}
|
|
|
|
/// Persist per-dataset embedding config as JSON sidecar.
|
|
pub fn set_dataset_embedding_config(&self, dataset: &str, cfg: &EmbeddingConfig) -> Result<(), DBError> {
|
|
if self.selected_db == 0 {
|
|
return Err(DBError("Lance not available on admin DB 0".to_string()));
|
|
}
|
|
let p = self.dataset_embedding_config_path(dataset);
|
|
let data = serde_json::to_vec_pretty(cfg)
|
|
.map_err(|e| DBError(format!("Failed to serialize embedding config: {}", e)))?;
|
|
std::fs::write(&p, data)
|
|
.map_err(|e| DBError(format!("Failed to write embedding config {}: {}", p.display(), e)))?;
|
|
// Invalidate embedder cache entry for this dataset
|
|
{
|
|
let mut map = self.embedders.write().unwrap();
|
|
map.remove(&(self.selected_db, dataset.to_string()));
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
/// Load per-dataset embedding config.
|
|
pub fn get_dataset_embedding_config(&self, dataset: &str) -> Result<EmbeddingConfig, DBError> {
|
|
if self.selected_db == 0 {
|
|
return Err(DBError("Lance not available on admin DB 0".to_string()));
|
|
}
|
|
let p = self.dataset_embedding_config_path(dataset);
|
|
if !p.exists() {
|
|
return Err(DBError(format!(
|
|
"Embedding config not set for dataset '{}'. Use LANCE.EMBEDDING CONFIG SET ... or RPC to configure.",
|
|
dataset
|
|
)));
|
|
}
|
|
let data = std::fs::read(&p)
|
|
.map_err(|e| DBError(format!("Failed to read embedding config {}: {}", p.display(), e)))?;
|
|
let cfg: EmbeddingConfig = serde_json::from_slice(&data)
|
|
.map_err(|e| DBError(format!("Failed to parse embedding config {}: {}", p.display(), e)))?;
|
|
Ok(cfg)
|
|
}
|
|
|
|
/// Resolve or build an embedder for (db_id, dataset). Caches instance.
|
|
pub fn get_embedder_for(&self, dataset: &str) -> Result<Arc<dyn Embedder>, DBError> {
|
|
if self.selected_db == 0 {
|
|
return Err(DBError("Lance not available on admin DB 0".to_string()));
|
|
}
|
|
// Fast path
|
|
{
|
|
let map = self.embedders.read().unwrap();
|
|
if let Some(e) = map.get(&(self.selected_db, dataset.to_string())) {
|
|
return Ok(e.clone());
|
|
}
|
|
}
|
|
// Load config and instantiate
|
|
let cfg = self.get_dataset_embedding_config(dataset)?;
|
|
let emb = create_embedder(&cfg)?;
|
|
{
|
|
let mut map = self.embedders.write().unwrap();
|
|
map.insert((self.selected_db, dataset.to_string()), emb.clone());
|
|
}
|
|
Ok(emb)
|
|
}
|
|
|
|
/// Check if current permissions allow read operations
|
|
pub fn has_read_permission(&self) -> bool {
|
|
// If an explicit permission is set for this connection, honor it.
|
|
if let Some(perms) = self.current_permissions.as_ref() {
|
|
return matches!(*perms, crate::rpc::Permissions::Read | crate::rpc::Permissions::ReadWrite);
|
|
}
|
|
// Fallback ONLY when no explicit permission context (e.g., JSON-RPC flows without SELECT).
|
|
match crate::admin_meta::verify_access(
|
|
&self.option.dir,
|
|
self.option.backend.clone(),
|
|
&self.option.admin_secret,
|
|
self.selected_db,
|
|
None,
|
|
) {
|
|
Ok(Some(crate::rpc::Permissions::Read)) | Ok(Some(crate::rpc::Permissions::ReadWrite)) => true,
|
|
_ => false,
|
|
}
|
|
}
|
|
|
|
/// Check if current permissions allow write operations
|
|
pub fn has_write_permission(&self) -> bool {
|
|
// If an explicit permission is set for this connection, honor it.
|
|
if let Some(perms) = self.current_permissions.as_ref() {
|
|
return matches!(*perms, crate::rpc::Permissions::ReadWrite);
|
|
}
|
|
// Fallback ONLY when no explicit permission context (e.g., JSON-RPC flows without SELECT).
|
|
match crate::admin_meta::verify_access(
|
|
&self.option.dir,
|
|
self.option.backend.clone(),
|
|
&self.option.admin_secret,
|
|
self.selected_db,
|
|
None,
|
|
) {
|
|
Ok(Some(crate::rpc::Permissions::ReadWrite)) => true,
|
|
_ => false,
|
|
}
|
|
}
|
|
|
|
// ----- BLPOP waiter helpers -----
|
|
|
|
pub async fn register_waiter(&self, db_index: u64, key: &str, side: PopSide) -> (u64, oneshot::Receiver<(String, String)>) {
|
|
let id = self.waiter_seq.fetch_add(1, Ordering::Relaxed);
|
|
let (tx, rx) = oneshot::channel::<(String, String)>();
|
|
|
|
let mut guard = self.list_waiters.lock().await;
|
|
let per_db = guard.entry(db_index).or_insert_with(HashMap::new);
|
|
let q = per_db.entry(key.to_string()).or_insert_with(Vec::new);
|
|
q.push(Waiter { id, side, tx });
|
|
(id, rx)
|
|
}
|
|
|
|
pub async fn unregister_waiter(&self, db_index: u64, key: &str, id: u64) {
|
|
let mut guard = self.list_waiters.lock().await;
|
|
if let Some(per_db) = guard.get_mut(&db_index) {
|
|
if let Some(q) = per_db.get_mut(key) {
|
|
q.retain(|w| w.id != id);
|
|
if q.is_empty() {
|
|
per_db.remove(key);
|
|
}
|
|
}
|
|
if per_db.is_empty() {
|
|
guard.remove(&db_index);
|
|
}
|
|
}
|
|
}
|
|
|
|
// Called after LPUSH/RPUSH to deliver to blocked BLPOP waiters.
|
|
pub async fn drain_waiters_after_push(&self, key: &str) -> Result<(), DBError> {
|
|
let db_index = self.selected_db;
|
|
|
|
loop {
|
|
// Check if any waiter exists
|
|
let maybe_waiter = {
|
|
let mut guard = self.list_waiters.lock().await;
|
|
if let Some(per_db) = guard.get_mut(&db_index) {
|
|
if let Some(q) = per_db.get_mut(key) {
|
|
if !q.is_empty() {
|
|
// Pop FIFO
|
|
Some(q.remove(0))
|
|
} else {
|
|
None
|
|
}
|
|
} else {
|
|
None
|
|
}
|
|
} else {
|
|
None
|
|
}
|
|
};
|
|
|
|
let waiter = if let Some(w) = maybe_waiter { w } else { break };
|
|
|
|
// Pop one element depending on waiter side
|
|
let elems = match waiter.side {
|
|
PopSide::Left => self.current_storage()?.lpop(key, 1)?,
|
|
PopSide::Right => self.current_storage()?.rpop(key, 1)?,
|
|
};
|
|
if elems.is_empty() {
|
|
// Nothing to deliver; re-register waiter at the front to preserve order
|
|
let mut guard = self.list_waiters.lock().await;
|
|
let per_db = guard.entry(db_index).or_insert_with(HashMap::new);
|
|
let q = per_db.entry(key.to_string()).or_insert_with(Vec::new);
|
|
q.insert(0, waiter);
|
|
break;
|
|
} else {
|
|
let elem = elems[0].clone();
|
|
// Send to waiter; if receiver dropped, just continue
|
|
let _ = waiter.tx.send((key.to_string(), elem));
|
|
// Loop to try to satisfy more waiters if more elements remain
|
|
continue;
|
|
}
|
|
}
|
|
|
|
Ok(())
|
|
}
|
|
|
|
pub async fn handle(
|
|
&mut self,
|
|
mut stream: tokio::net::TcpStream,
|
|
) -> Result<(), DBError> {
|
|
// Accumulate incoming bytes to handle partial RESP frames
|
|
let mut acc = String::new();
|
|
let mut buf = vec![0u8; 8192];
|
|
|
|
loop {
|
|
let n = match stream.read(&mut buf).await {
|
|
Ok(0) => {
|
|
println!("[handle] connection closed");
|
|
return Ok(());
|
|
}
|
|
Ok(n) => n,
|
|
Err(e) => {
|
|
println!("[handle] read error: {:?}", e);
|
|
return Err(e.into());
|
|
}
|
|
};
|
|
|
|
// Append to accumulator. RESP for our usage is ASCII-safe.
|
|
acc.push_str(str::from_utf8(&buf[..n])?);
|
|
|
|
// Try to parse as many complete commands as are available in 'acc'.
|
|
loop {
|
|
let parsed = Cmd::from(&acc);
|
|
let (cmd, protocol, remaining) = match parsed {
|
|
Ok((cmd, protocol, remaining)) => (cmd, protocol, remaining),
|
|
Err(_e) => {
|
|
// Incomplete or invalid frame; assume incomplete and wait for more data.
|
|
// This avoids emitting spurious protocol_error for split frames.
|
|
break;
|
|
}
|
|
};
|
|
|
|
// Advance the accumulator to the unparsed remainder
|
|
acc = remaining.to_string();
|
|
|
|
if self.option.debug {
|
|
println!("\x1b[34;1mgot command: {:?}, protocol: {:?}\x1b[0m", cmd, protocol);
|
|
} else {
|
|
println!("got command: {:?}, protocol: {:?}", cmd, protocol);
|
|
}
|
|
|
|
// Check if this is a QUIT command before processing
|
|
let is_quit = matches!(cmd, Cmd::Quit);
|
|
|
|
let res = match cmd.run(self).await {
|
|
Ok(p) => p,
|
|
Err(e) => {
|
|
if self.option.debug {
|
|
eprintln!("[run error] {:?}", e);
|
|
}
|
|
Protocol::err(&format!("ERR {}", e.0))
|
|
}
|
|
};
|
|
|
|
if self.option.debug {
|
|
println!("\x1b[34;1mqueued cmd {:?}\x1b[0m", self.queued_cmd);
|
|
println!("\x1b[32;1mgoing to send response {}\x1b[0m", res.encode());
|
|
} else {
|
|
print!("queued cmd {:?}", self.queued_cmd);
|
|
println!("going to send response {}", res.encode());
|
|
}
|
|
|
|
_ = stream.write(res.encode().as_bytes()).await?;
|
|
|
|
// If this was a QUIT command, close the connection
|
|
if is_quit {
|
|
println!("[handle] QUIT command received, closing connection");
|
|
return Ok(());
|
|
}
|
|
|
|
// Continue parsing any further complete commands already in 'acc'
|
|
if acc.is_empty() {
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|