-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathapi.rs
More file actions
400 lines (351 loc) · 10.4 KB
/
api.rs
File metadata and controls
400 lines (351 loc) · 10.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
use anyhow::Result;
use axum::{
extract::State,
http::StatusCode,
response::IntoResponse,
routing::{get, post},
Json, Router,
};
use serde::{Deserialize, Serialize};
use std::net::SocketAddr;
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
use tower_http::cors::{Any, CorsLayer};
use crate::config::Config;
use crate::core::{Database, EmbeddingEngine};
pub struct ServerState {
embedding_engine: Mutex<EmbeddingEngine>,
config: Config,
}
#[derive(Debug, Deserialize)]
pub struct SearchRequest {
pub query: String,
#[serde(default)]
pub path: Option<String>,
#[serde(default = "default_max_results")]
pub max_results: usize,
}
fn default_max_results() -> usize {
10
}
#[derive(Debug, Serialize)]
pub struct SearchResponse {
pub results: Vec<SearchResultJson>,
pub query: String,
pub total: usize,
}
#[derive(Debug, Serialize)]
pub struct SearchResultJson {
pub path: String,
pub score: f32,
pub score_percent: String,
pub preview: Option<String>,
pub start_line: i32,
pub end_line: i32,
}
#[derive(Debug, Deserialize)]
pub struct EmbedRequest {
pub text: String,
}
#[derive(Debug, Deserialize)]
pub struct EmbedBatchRequest {
pub texts: Vec<String>,
}
#[derive(Debug, Serialize)]
pub struct EmbedBatchResponse {
pub embeddings: Vec<Vec<f32>>,
#[allow(dead_code)]
pub count: usize,
}
#[derive(Debug, Serialize)]
pub struct EmbedResponse {
pub embedding: Vec<f32>,
pub dimensions: usize,
}
#[derive(Debug, Serialize)]
pub struct StatusResponse {
pub status: String,
pub indexed_files: usize,
pub total_chunks: usize,
pub embedding_model: Option<String>,
pub reranker_model: Option<String>,
}
type SharedState = Arc<ServerState>;
pub async fn run_server(config: &Config, host: &str, port: u16) -> Result<()> {
let config = config.clone();
if !config.has_embedding_model() {
anyhow::bail!("Embedding model not found. Please run: vgrep models download");
}
crate::ui::print_banner();
println!(" {}Loading embedding model...", crate::ui::BRAIN);
let engine = EmbeddingEngine::new(&config)?;
println!(" {}Model loaded successfully!", crate::ui::CHECK);
println!();
let state = Arc::new(ServerState {
embedding_engine: Mutex::new(engine),
config,
});
let cors = CorsLayer::new()
.allow_origin(Any)
.allow_methods(Any)
.allow_headers(Any);
let app = Router::new()
.route("/", get(root))
.route("/health", get(health))
.route("/status", get(status))
.route("/search", post(search))
.route("/embed", post(embed))
.route("/embed_batch", post(embed_batch))
.layer(cors)
.with_state(state);
let addr: SocketAddr = format!("{}:{}", host, port).parse()?;
crate::ui::print_server_banner(host, port);
let listener = tokio::net::TcpListener::bind(addr).await?;
axum::serve(listener, app).await?;
Ok(())
}
async fn root() -> impl IntoResponse {
Json(serde_json::json!({
"name": "vgrep",
"version": env!("CARGO_PKG_VERSION"),
"description": "Local semantic grep server"
}))
}
async fn health() -> impl IntoResponse {
Json(serde_json::json!({
"status": "ok"
}))
}
async fn status(State(state): State<SharedState>) -> impl IntoResponse {
let db = match Database::new(&state.config.db_path().unwrap_or_default()) {
Ok(db) => db,
Err(e) => {
return (
StatusCode::INTERNAL_SERVER_ERROR,
Json(serde_json::json!({
"error": format!("Failed to open database: {}", e)
})),
)
.into_response();
}
};
let stats = match db.get_stats() {
Ok(stats) => stats,
Err(e) => {
return (
StatusCode::INTERNAL_SERVER_ERROR,
Json(serde_json::json!({
"error": format!("Failed to get stats: {}", e)
})),
)
.into_response();
}
};
Json(StatusResponse {
status: "ok".to_string(),
indexed_files: stats.file_count,
total_chunks: stats.chunk_count,
embedding_model: state
.config
.embedding_model_path()
.ok()
.map(|p| p.to_string_lossy().to_string()),
reranker_model: state
.config
.reranker_model_path()
.ok()
.map(|p| p.to_string_lossy().to_string()),
})
.into_response()
}
async fn search(
State(state): State<SharedState>,
Json(req): Json<SearchRequest>,
) -> impl IntoResponse {
if req.query.trim().is_empty() {
return (
StatusCode::BAD_REQUEST,
Json(serde_json::json!({
"error": "Query cannot be empty or whitespace only"
})),
)
.into_response();
}
let path = req
.path
.map(PathBuf::from)
.unwrap_or_else(|| std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")));
let abs_path = std::fs::canonicalize(&path).unwrap_or(path);
// Generate query embedding
let query_embedding = {
let engine = match state.embedding_engine.lock() {
Ok(e) => e,
Err(e) => {
return (
StatusCode::INTERNAL_SERVER_ERROR,
Json(serde_json::json!({
"error": format!("Failed to lock engine: {}", e)
})),
)
.into_response();
}
};
match engine.embed(&req.query) {
Ok(emb) => emb,
Err(e) => {
return (
StatusCode::INTERNAL_SERVER_ERROR,
Json(serde_json::json!({
"error": format!("Failed to generate embedding: {}", e)
})),
)
.into_response();
}
}
};
// Search in database
let db = match Database::new(&state.config.db_path().unwrap_or_default()) {
Ok(db) => db,
Err(e) => {
return (
StatusCode::INTERNAL_SERVER_ERROR,
Json(serde_json::json!({
"error": format!("Failed to open database: {}", e)
})),
)
.into_response();
}
};
let candidates = match db.search_similar(&query_embedding, &abs_path, req.max_results * 3) {
Ok(c) => c,
Err(e) => {
return (
StatusCode::INTERNAL_SERVER_ERROR,
Json(serde_json::json!({
"error": format!("Search failed: {}", e)
})),
)
.into_response();
}
};
// Deduplicate by file (keep best chunk per file)
use std::collections::HashMap;
let mut best_per_file: HashMap<PathBuf, _> = HashMap::new();
for result in candidates {
let entry = best_per_file
.entry(result.path.clone())
.or_insert(result.clone());
if result.similarity > entry.similarity {
*entry = result;
}
}
// Convert to final results
let mut results: Vec<SearchResultJson> = best_per_file
.into_values()
.map(|r| SearchResultJson {
path: r.path.to_string_lossy().to_string(),
score: r.similarity,
score_percent: format!("{:.2}%", r.similarity * 100.0),
preview: Some(r.content),
start_line: r.start_line,
end_line: r.end_line,
})
.collect();
// Sort by score descending
results.sort_by(|a, b| {
b.score
.partial_cmp(&a.score)
.unwrap_or(std::cmp::Ordering::Equal)
});
results.truncate(req.max_results);
let total = results.len();
Json(SearchResponse {
results,
query: req.query,
total,
})
.into_response()
}
async fn embed(
State(state): State<SharedState>,
Json(req): Json<EmbedRequest>,
) -> impl IntoResponse {
if req.text.trim().is_empty() {
return (
StatusCode::BAD_REQUEST,
Json(serde_json::json!({
"error": "Text cannot be empty or whitespace only"
})),
)
.into_response();
}
let engine = match state.embedding_engine.lock() {
Ok(e) => e,
Err(e) => {
return (
StatusCode::INTERNAL_SERVER_ERROR,
Json(serde_json::json!({
"error": format!("Failed to lock engine: {}", e)
})),
)
.into_response();
}
};
match engine.embed(&req.text) {
Ok(embedding) => {
let dimensions = embedding.len();
Json(EmbedResponse {
embedding,
dimensions,
})
.into_response()
}
Err(e) => (
StatusCode::INTERNAL_SERVER_ERROR,
Json(serde_json::json!({
"error": format!("Embedding failed: {}", e)
})),
)
.into_response(),
}
}
async fn embed_batch(
State(state): State<SharedState>,
Json(req): Json<EmbedBatchRequest>,
) -> impl IntoResponse {
if req.texts.is_empty() || req.texts.iter().all(|s| s.trim().is_empty()) {
return (
StatusCode::BAD_REQUEST,
Json(serde_json::json!({
"error": "Batch texts cannot be empty or contain only empty strings"
})),
)
.into_response();
}
let engine = match state.embedding_engine.lock() {
Ok(e) => e,
Err(e) => {
return (
StatusCode::INTERNAL_SERVER_ERROR,
Json(serde_json::json!({
"error": format!("Failed to lock engine: {}", e)
})),
)
.into_response();
}
};
let texts: Vec<&str> = req.texts.iter().map(|s| s.as_str()).collect();
match engine.embed_batch(&texts) {
Ok(embeddings) => {
let count = embeddings.len();
Json(EmbedBatchResponse { embeddings, count }).into_response()
}
Err(e) => (
StatusCode::INTERNAL_SERVER_ERROR,
Json(serde_json::json!({
"error": format!("Batch embedding failed: {}", e)
})),
)
.into_response(),
}
}