use crate::error::{QdrantError, QdrantResult};
use crate::driver::QdrantDriver;
use std::sync::Arc;
use tokio::sync::Semaphore;
#[derive(Debug, Clone)]
pub struct PoolConfig {
pub max_connections: usize,
pub host: String,
pub port: u16,
}
impl PoolConfig {
pub fn new(host: impl Into<String>, port: u16) -> Self {
Self {
max_connections: 10,
host: host.into(),
port,
}
}
pub fn max_connections(mut self, max: usize) -> Self {
self.max_connections = max;
self
}
}
impl Default for PoolConfig {
fn default() -> Self {
Self {
max_connections: 10,
host: "localhost".to_string(),
port: 6334,
}
}
}
#[derive(Clone)]
pub struct QdrantPool {
config: Arc<PoolConfig>,
semaphore: Arc<Semaphore>,
}
impl QdrantPool {
pub async fn new(config: PoolConfig) -> QdrantResult<Self> {
Ok(Self {
semaphore: Arc::new(Semaphore::new(config.max_connections)),
config: Arc::new(config),
})
}
pub async fn get(&self) -> QdrantResult<PooledConnection> {
let permit = self.semaphore
.clone()
.acquire_owned()
.await
.map_err(|e| QdrantError::Connection(e.to_string()))?;
let driver = QdrantDriver::connect(&self.config.host, self.config.port).await?;
Ok(PooledConnection {
driver,
_permit: permit,
})
}
pub fn available(&self) -> usize {
self.semaphore.available_permits()
}
pub fn max_connections(&self) -> usize {
self.config.max_connections
}
}
pub struct PooledConnection {
driver: QdrantDriver,
_permit: tokio::sync::OwnedSemaphorePermit,
}
impl std::ops::Deref for PooledConnection {
type Target = QdrantDriver;
fn deref(&self) -> &Self::Target {
&self.driver
}
}
impl std::ops::DerefMut for PooledConnection {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.driver
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_pool_config_builder() {
let config = PoolConfig::new("localhost", 6334)
.max_connections(20);
assert_eq!(config.max_connections, 20);
assert_eq!(config.host, "localhost");
assert_eq!(config.port, 6334);
}
#[test]
fn test_pool_config_default() {
let config = PoolConfig::default();
assert_eq!(config.max_connections, 10);
assert_eq!(config.host, "localhost");
assert_eq!(config.port, 6334);
}
}