458 lines
14 KiB
Rust
458 lines
14 KiB
Rust
use axum::{
|
|
extract::State,
|
|
http::StatusCode,
|
|
Json,
|
|
};
|
|
use futures_util::TryStreamExt;
|
|
use mongodb::bson::Document;
|
|
use serde::{Deserialize, Serialize};
|
|
use std::sync::Arc;
|
|
use std::time::Instant;
|
|
|
|
use crate::db::ConnectionManager;
|
|
use crate::logger::{LogEntry, RequestLogger};
|
|
|
|
pub type AppState = Arc<(Arc<ConnectionManager>, Arc<RequestLogger>)>;
|
|
|
|
// ============== 请求结构 ==============
|
|
|
|
#[derive(Debug, Deserialize)]
|
|
pub struct FindRequest {
|
|
pub conn: String,
|
|
pub collection: String,
|
|
#[serde(default)]
|
|
pub filter: Option<Document>,
|
|
#[serde(default)]
|
|
pub projection: Option<Document>,
|
|
#[serde(default)]
|
|
pub sort: Option<Document>,
|
|
#[serde(default)]
|
|
pub limit: Option<i64>,
|
|
#[serde(default)]
|
|
pub skip: Option<u64>,
|
|
}
|
|
|
|
#[derive(Debug, Deserialize)]
|
|
pub struct InsertRequest {
|
|
pub conn: String,
|
|
pub collection: String,
|
|
pub documents: Vec<Document>,
|
|
}
|
|
|
|
#[derive(Debug, Deserialize)]
|
|
pub struct UpdateRequest {
|
|
pub conn: String,
|
|
pub collection: String,
|
|
pub filter: Document,
|
|
pub update: Document,
|
|
#[serde(default)]
|
|
pub upsert: Option<bool>,
|
|
#[serde(default)]
|
|
pub multi: Option<bool>,
|
|
}
|
|
|
|
#[derive(Debug, Deserialize)]
|
|
pub struct DeleteRequest {
|
|
pub conn: String,
|
|
pub collection: String,
|
|
pub filter: Document,
|
|
#[serde(default)]
|
|
pub multi: Option<bool>,
|
|
}
|
|
|
|
#[derive(Debug, Deserialize)]
|
|
pub struct AggregateRequest {
|
|
pub conn: String,
|
|
pub collection: String,
|
|
pub pipeline: Vec<Document>,
|
|
}
|
|
|
|
#[derive(Debug, Deserialize)]
|
|
pub struct CountRequest {
|
|
pub conn: String,
|
|
pub collection: String,
|
|
#[serde(default)]
|
|
pub filter: Option<Document>,
|
|
}
|
|
|
|
#[derive(Debug, Deserialize)]
|
|
pub struct AddConnectionRequest {
|
|
pub name: String,
|
|
pub host: String,
|
|
#[serde(default = "default_port")]
|
|
pub port: u16,
|
|
pub database: String,
|
|
pub username: Option<String>,
|
|
pub password: Option<String>,
|
|
pub auth_source: Option<String>,
|
|
}
|
|
|
|
fn default_port() -> u16 { 27017 }
|
|
|
|
// ============== 响应结构 ==============
|
|
|
|
#[derive(Debug, Serialize)]
|
|
pub struct FindResponse {
|
|
pub documents: Vec<serde_json::Value>,
|
|
pub count: usize,
|
|
#[serde(rename = "durationMs")]
|
|
pub duration_ms: u64,
|
|
}
|
|
|
|
#[derive(Debug, Serialize)]
|
|
pub struct InsertResponse {
|
|
#[serde(rename = "insertedIds")]
|
|
pub inserted_ids: Vec<String>,
|
|
#[serde(rename = "insertedCount")]
|
|
pub inserted_count: usize,
|
|
#[serde(rename = "durationMs")]
|
|
pub duration_ms: u64,
|
|
}
|
|
|
|
#[derive(Debug, Serialize)]
|
|
pub struct UpdateResponse {
|
|
#[serde(rename = "matchedCount")]
|
|
pub matched_count: u64,
|
|
#[serde(rename = "modifiedCount")]
|
|
pub modified_count: u64,
|
|
#[serde(rename = "upsertedId")]
|
|
pub upserted_id: Option<String>,
|
|
#[serde(rename = "durationMs")]
|
|
pub duration_ms: u64,
|
|
}
|
|
|
|
#[derive(Debug, Serialize)]
|
|
pub struct DeleteResponse {
|
|
#[serde(rename = "deletedCount")]
|
|
pub deleted_count: u64,
|
|
#[serde(rename = "durationMs")]
|
|
pub duration_ms: u64,
|
|
}
|
|
|
|
#[derive(Debug, Serialize)]
|
|
pub struct AggregateResponse {
|
|
pub documents: Vec<serde_json::Value>,
|
|
#[serde(rename = "durationMs")]
|
|
pub duration_ms: u64,
|
|
}
|
|
|
|
#[derive(Debug, Serialize)]
|
|
pub struct CountResponse {
|
|
pub count: u64,
|
|
#[serde(rename = "durationMs")]
|
|
pub duration_ms: u64,
|
|
}
|
|
|
|
#[derive(Debug, Serialize)]
|
|
pub struct ConnectionsResponse {
|
|
pub connections: Vec<crate::db::ConnectionInfo>,
|
|
}
|
|
|
|
#[derive(Debug, Serialize)]
|
|
pub struct HealthResponse {
|
|
pub status: String,
|
|
pub connections: usize,
|
|
}
|
|
|
|
#[derive(Debug, Serialize)]
|
|
pub struct ErrorResponse {
|
|
pub error: String,
|
|
#[serde(rename = "usage")]
|
|
pub usage: Option<String>,
|
|
}
|
|
|
|
impl ErrorResponse {
|
|
pub fn new(msg: &str) -> Self {
|
|
Self { error: msg.to_string(), usage: None }
|
|
}
|
|
|
|
pub fn with_usage(mut self, usage: &str) -> Self {
|
|
self.usage = Some(usage.to_string());
|
|
self
|
|
}
|
|
}
|
|
|
|
// ============== 处理器 ==============
|
|
|
|
pub async fn find(
|
|
State(state): State<AppState>,
|
|
Json(req): Json<FindRequest>,
|
|
) -> Result<Json<FindResponse>, (StatusCode, Json<ErrorResponse>)> {
|
|
let (manager, logger) = &*state;
|
|
let start = Instant::now();
|
|
|
|
let client = manager.get_client(&req.conn).await
|
|
.map_err(|e| error_response_with_usage(&e.to_string(),
|
|
&format!("Usage: POST /find {{\"conn\": \"name\", \"collection\": \"coll\", \"filter\": {{}}}}\nAvailable: {}", list_conn_names(manager))))?;
|
|
|
|
let db = client.database(&get_database(manager, &req.conn));
|
|
let coll = db.collection::<Document>(&req.collection);
|
|
|
|
let mut find = coll.find(req.filter.unwrap_or_default());
|
|
if let Some(p) = req.projection { find = find.projection(p); }
|
|
if let Some(s) = req.sort { find = find.sort(s); }
|
|
if let Some(l) = req.limit { find = find.limit(l); }
|
|
if let Some(s) = req.skip { find = find.skip(s); }
|
|
|
|
let mut cursor = find.await
|
|
.map_err(|e| error_response(&e.to_string()))?;
|
|
|
|
let mut documents = Vec::new();
|
|
while let Some(result) = cursor.try_next().await.map_err(|e: mongodb::error::Error| error_response(&e.to_string()))? {
|
|
documents.push(bson_to_json(&result));
|
|
}
|
|
|
|
let count = documents.len();
|
|
let duration = start.elapsed();
|
|
|
|
logger.log(&LogEntry::new("/find", "http")
|
|
.with_conn(&req.conn)
|
|
.with_command(&format!("{}.{}", req.conn, req.collection))
|
|
.with_duration(duration.as_millis() as u64)
|
|
.with_rows(count));
|
|
|
|
Ok(Json(FindResponse { documents, count, duration_ms: duration.as_millis() as u64 }))
|
|
}
|
|
|
|
pub async fn insert(
|
|
State(state): State<AppState>,
|
|
Json(req): Json<InsertRequest>,
|
|
) -> Result<Json<InsertResponse>, (StatusCode, Json<ErrorResponse>)> {
|
|
let (manager, logger) = &*state;
|
|
let start = Instant::now();
|
|
|
|
let client = manager.get_client(&req.conn).await
|
|
.map_err(|e| error_response_with_usage(&e.to_string(),
|
|
&format!("Usage: POST /insert {{\"conn\": \"name\", \"collection\": \"coll\", \"documents\": [{{}}]}}")))?;
|
|
|
|
let db = client.database(&get_database(manager, &req.conn));
|
|
let coll = db.collection::<Document>(&req.collection);
|
|
|
|
let result = coll.insert_many(req.documents).await
|
|
.map_err(|e| error_response(&e.to_string()))?;
|
|
|
|
let inserted_ids: Vec<String> = result.inserted_ids.iter()
|
|
.map(|(k, v)| format!("{}:{}", k, v))
|
|
.collect();
|
|
let inserted_count = result.inserted_ids.len();
|
|
let duration = start.elapsed();
|
|
|
|
logger.log(&LogEntry::new("/insert", "http")
|
|
.with_conn(&req.conn)
|
|
.with_command(&format!("{}.{}", req.conn, req.collection))
|
|
.with_duration(duration.as_millis() as u64)
|
|
.with_rows(inserted_count));
|
|
|
|
Ok(Json(InsertResponse { inserted_ids, inserted_count, duration_ms: duration.as_millis() as u64 }))
|
|
}
|
|
|
|
pub async fn update(
|
|
State(state): State<AppState>,
|
|
Json(req): Json<UpdateRequest>,
|
|
) -> Result<Json<UpdateResponse>, (StatusCode, Json<ErrorResponse>)> {
|
|
let (manager, logger) = &*state;
|
|
let start = Instant::now();
|
|
|
|
let client = manager.get_client(&req.conn).await
|
|
.map_err(|e| error_response_with_usage(&e.to_string(),
|
|
"Usage: POST /update {\"conn\": \"name\", \"collection\": \"coll\", \"filter\": {}, \"update\": {\"$set\": {}}}"))?;
|
|
|
|
let db = client.database(&get_database(manager, &req.conn));
|
|
let coll = db.collection::<Document>(&req.collection);
|
|
|
|
let result = if req.multi.unwrap_or(false) {
|
|
let mut cmd = coll.update_many(req.filter, req.update);
|
|
if req.upsert.unwrap_or(false) { cmd = cmd.upsert(true); }
|
|
cmd.await
|
|
} else {
|
|
let mut cmd = coll.update_one(req.filter, req.update);
|
|
if req.upsert.unwrap_or(false) { cmd = cmd.upsert(true); }
|
|
cmd.await
|
|
}.map_err(|e| error_response(&e.to_string()))?;
|
|
|
|
let upserted_id = result.upserted_id.map(|id| format!("{:?}", id));
|
|
let duration = start.elapsed();
|
|
|
|
logger.log(&LogEntry::new("/update", "http")
|
|
.with_conn(&req.conn)
|
|
.with_command(&format!("{}.{}", req.conn, req.collection))
|
|
.with_duration(duration.as_millis() as u64));
|
|
|
|
Ok(Json(UpdateResponse {
|
|
matched_count: result.matched_count,
|
|
modified_count: result.modified_count,
|
|
upserted_id,
|
|
duration_ms: duration.as_millis() as u64,
|
|
}))
|
|
}
|
|
|
|
pub async fn delete(
|
|
State(state): State<AppState>,
|
|
Json(req): Json<DeleteRequest>,
|
|
) -> Result<Json<DeleteResponse>, (StatusCode, Json<ErrorResponse>)> {
|
|
let (manager, logger) = &*state;
|
|
let start = Instant::now();
|
|
|
|
let client = manager.get_client(&req.conn).await
|
|
.map_err(|e| error_response_with_usage(&e.to_string(),
|
|
"Usage: POST /delete {\"conn\": \"name\", \"collection\": \"coll\", \"filter\": {}}"))?;
|
|
|
|
let db = client.database(&get_database(manager, &req.conn));
|
|
let coll = db.collection::<Document>(&req.collection);
|
|
|
|
let result = if req.multi.unwrap_or(false) {
|
|
coll.delete_many(req.filter).await
|
|
} else {
|
|
coll.delete_one(req.filter).await
|
|
}.map_err(|e| error_response(&e.to_string()))?;
|
|
|
|
let deleted_count = result.deleted_count;
|
|
let duration = start.elapsed();
|
|
|
|
logger.log(&LogEntry::new("/delete", "http")
|
|
.with_conn(&req.conn)
|
|
.with_command(&format!("{}.{}", req.conn, req.collection))
|
|
.with_duration(duration.as_millis() as u64));
|
|
|
|
Ok(Json(DeleteResponse { deleted_count, duration_ms: duration.as_millis() as u64 }))
|
|
}
|
|
|
|
pub async fn aggregate(
|
|
State(state): State<AppState>,
|
|
Json(req): Json<AggregateRequest>,
|
|
) -> Result<Json<AggregateResponse>, (StatusCode, Json<ErrorResponse>)> {
|
|
let (manager, logger) = &*state;
|
|
let start = Instant::now();
|
|
|
|
let client = manager.get_client(&req.conn).await
|
|
.map_err(|e| error_response_with_usage(&e.to_string(),
|
|
"Usage: POST /aggregate {\"conn\": \"name\", \"collection\": \"coll\", \"pipeline\": [{\"$match\": {}}, ...]}"))?;
|
|
|
|
let db = client.database(&get_database(manager, &req.conn));
|
|
let coll = db.collection::<Document>(&req.collection);
|
|
|
|
let mut cursor = coll.aggregate(req.pipeline).await
|
|
.map_err(|e| error_response(&e.to_string()))?;
|
|
|
|
let mut documents = Vec::new();
|
|
while let Some(result) = cursor.try_next().await.map_err(|e: mongodb::error::Error| error_response(&e.to_string()))? {
|
|
documents.push(bson_to_json(&result));
|
|
}
|
|
|
|
let count = documents.len();
|
|
let duration = start.elapsed();
|
|
|
|
logger.log(&LogEntry::new("/aggregate", "http")
|
|
.with_conn(&req.conn)
|
|
.with_command(&format!("{}.{}", req.conn, req.collection))
|
|
.with_duration(duration.as_millis() as u64)
|
|
.with_rows(count));
|
|
|
|
Ok(Json(AggregateResponse { documents, duration_ms: duration.as_millis() as u64 }))
|
|
}
|
|
|
|
pub async fn count(
|
|
State(state): State<AppState>,
|
|
Json(req): Json<CountRequest>,
|
|
) -> Result<Json<CountResponse>, (StatusCode, Json<ErrorResponse>)> {
|
|
let (manager, logger) = &*state;
|
|
let start = Instant::now();
|
|
|
|
let client = manager.get_client(&req.conn).await
|
|
.map_err(|e| error_response_with_usage(&e.to_string(),
|
|
"Usage: POST /count {\"conn\": \"name\", \"collection\": \"coll\", \"filter\": {}}"))?;
|
|
|
|
let db = client.database(&get_database(manager, &req.conn));
|
|
let coll = db.collection::<Document>(&req.collection);
|
|
|
|
let count = coll.count_documents(req.filter.unwrap_or_default()).await
|
|
.map_err(|e| error_response(&e.to_string()))?;
|
|
|
|
let duration = start.elapsed();
|
|
|
|
logger.log(&LogEntry::new("/count", "http")
|
|
.with_conn(&req.conn)
|
|
.with_command(&format!("{}.{}", req.conn, req.collection))
|
|
.with_duration(duration.as_millis() as u64));
|
|
|
|
Ok(Json(CountResponse { count, duration_ms: duration.as_millis() as u64 }))
|
|
}
|
|
|
|
pub async fn connections(
|
|
State(state): State<AppState>,
|
|
) -> Json<ConnectionsResponse> {
|
|
let (manager, _) = &*state;
|
|
Json(ConnectionsResponse {
|
|
connections: manager.list_connections(),
|
|
})
|
|
}
|
|
|
|
pub async fn health(
|
|
State(state): State<AppState>,
|
|
) -> Json<HealthResponse> {
|
|
let (manager, _) = &*state;
|
|
Json(HealthResponse {
|
|
status: "ok".to_string(),
|
|
connections: manager.list_connections().len(),
|
|
})
|
|
}
|
|
|
|
pub async fn add_connection(
|
|
State(state): State<AppState>,
|
|
Json(req): Json<AddConnectionRequest>,
|
|
) -> Result<Json<serde_json::Value>, (StatusCode, Json<ErrorResponse>)> {
|
|
let (manager, logger) = &*state;
|
|
use crate::config::ConnectionConfig;
|
|
|
|
let cfg = ConnectionConfig {
|
|
name: req.name.clone(),
|
|
host: req.host,
|
|
port: req.port,
|
|
database: req.database,
|
|
username: req.username,
|
|
password: req.password,
|
|
auth_source: req.auth_source,
|
|
};
|
|
|
|
manager.add_connection(cfg).await
|
|
.map_err(|e| error_response(&e.to_string()))?;
|
|
|
|
logger.log(&LogEntry::new("/connections/add", "http")
|
|
.with_conn(&req.name)
|
|
.with_duration(0));
|
|
|
|
Ok(Json(serde_json::json!({
|
|
"success": true,
|
|
"message": format!("Connection '{}' added (temporary)", req.name)
|
|
})))
|
|
}
|
|
|
|
// ============== 辅助函数 ==============
|
|
|
|
fn error_response(msg: &str) -> (StatusCode, Json<ErrorResponse>) {
|
|
(StatusCode::BAD_REQUEST, Json(ErrorResponse::new(msg)))
|
|
}
|
|
|
|
fn error_response_with_usage(msg: &str, usage: &str) -> (StatusCode, Json<ErrorResponse>) {
|
|
(StatusCode::BAD_REQUEST, Json(ErrorResponse::new(msg).with_usage(usage)))
|
|
}
|
|
|
|
fn list_conn_names(manager: &ConnectionManager) -> String {
|
|
manager.list_connections()
|
|
.iter()
|
|
.map(|c| c.name.clone())
|
|
.collect::<Vec<_>>()
|
|
.join(", ")
|
|
}
|
|
|
|
fn get_database(manager: &ConnectionManager, name: &str) -> String {
|
|
manager.list_connections().iter()
|
|
.find(|c| c.name == name)
|
|
.map(|c| c.database.clone())
|
|
.unwrap_or_default()
|
|
}
|
|
|
|
fn bson_to_json(doc: &Document) -> serde_json::Value {
|
|
serde_json::to_value(doc).unwrap_or(serde_json::Value::Null)
|
|
}
|