1use anyhow::{Context, Result};
7use serde::{Deserialize, Serialize};
8use serde_json::{Value, json};
9use std::path::PathBuf;
10
11use super::file_search_bridge::{self, FileMatchType, FileSearchConfig};
12
13#[derive(Debug, Clone, Serialize, Deserialize)]
15pub struct SearchFilesRequest {
16 pub pattern: String,
18 pub workspace_root: PathBuf,
20 pub max_results: usize,
22 pub exclude_patterns: Vec<String>,
24 pub respect_gitignore: bool,
26}
27
28#[derive(Debug, Clone, Serialize, Deserialize)]
30pub struct ListFilesRequest {
31 pub workspace_root: PathBuf,
33 pub exclude_patterns: Vec<String>,
35 pub respect_gitignore: bool,
37 pub max_results: usize,
39}
40
41#[derive(Debug, Clone, Serialize, Deserialize)]
43pub struct FileMatchRpc {
44 pub path: String,
46 pub match_type: FileMatchType,
48 pub score: u32,
50 pub indices: Option<Vec<u32>>,
52}
53
54#[derive(Debug, Clone, Serialize, Deserialize)]
56pub struct SearchFilesResponse {
57 pub matches: Vec<FileMatchRpc>,
59 pub total_match_count: usize,
61 pub truncated: bool,
63}
64
65#[derive(Debug, Clone, Serialize, Deserialize)]
67pub struct ListFilesResponse {
68 pub files: Vec<String>,
70 pub total: usize,
72}
73
74#[derive(Debug, Clone, Serialize, Deserialize)]
76pub struct RpcError {
77 pub code: i32,
79 pub message: String,
81 pub data: Option<Value>,
83}
84
85impl RpcError {
86 pub fn new(code: i32, message: impl Into<String>) -> Self {
88 Self { code, message: message.into(), data: None }
89 }
90
91 pub fn invalid_request(message: impl Into<String>) -> Self {
93 Self::new(-32600, message)
94 }
95
96 pub fn method_not_found() -> Self {
98 Self::new(-32601, "Method not found")
99 }
100
101 pub fn invalid_params(message: impl Into<String>) -> Self {
103 Self::new(-32602, message)
104 }
105
106 pub fn internal_error(message: impl Into<String>) -> Self {
108 Self::new(-32603, message)
109 }
110
111 pub fn custom(code: i32, message: impl Into<String>) -> Self {
113 Self::new(code, message)
114 }
115}
116
117#[derive(Debug, Clone, Serialize, Deserialize)]
119pub struct RpcRequest {
120 pub jsonrpc: String,
122 pub method: String,
124 pub params: Value,
126 pub id: Option<Value>,
128}
129
130#[derive(Debug, Clone, Serialize, Deserialize)]
132pub struct RpcResponse {
133 pub jsonrpc: String,
135 pub id: Option<Value>,
137 pub result: Option<Value>,
139 pub error: Option<RpcError>,
141}
142
143impl RpcResponse {
144 pub fn success(id: Option<Value>, result: Value) -> Self {
146 Self {
147 jsonrpc: "2.0".to_string(),
148 id,
149 result: Some(result),
150 error: None,
151 }
152 }
153
154 pub fn error(id: Option<Value>, error: RpcError) -> Self {
156 Self {
157 jsonrpc: "2.0".to_string(),
158 id,
159 result: None,
160 error: Some(error),
161 }
162 }
163}
164
165pub struct FileSearchRpcHandler;
167
168impl FileSearchRpcHandler {
169 pub async fn handle_request(request: RpcRequest) -> RpcResponse {
179 let id = request.id.clone();
180
181 if request.jsonrpc != "2.0" {
183 return RpcResponse::error(id, RpcError::invalid_request("Invalid JSON-RPC version"));
184 }
185
186 let result = match request.method.as_str() {
188 "search_files" => Self::handle_search_files(&request.params, id.clone()).await,
189 "list_files" => Self::handle_list_files(&request.params).await,
190 "find_references" => Self::handle_find_references(&request.params).await,
191 _ => return RpcResponse::error(id, RpcError::method_not_found()),
192 };
193
194 match result {
195 Ok(response) => RpcResponse::success(id, response),
196 Err(error) => RpcResponse::error(id, RpcError::internal_error(error.to_string())),
197 }
198 }
199
200 async fn handle_search_files(params: &Value, _id: Option<Value>) -> Result<Value> {
204 let request: SearchFilesRequest =
205 serde_json::from_value(params.clone()).context("Failed to parse search_files parameters")?;
206
207 if !tokio::fs::try_exists(&request.workspace_root).await.unwrap_or(false) {
209 return Err(anyhow::anyhow!("Workspace root does not exist: {}", request.workspace_root.display()));
210 }
211
212 let max_results = file_search_bridge::effective_max_results(request.max_results);
214 let config = FileSearchConfig::new(request.pattern, request.workspace_root)
215 .with_limit(max_results)
216 .respect_gitignore(request.respect_gitignore);
217
218 let results = file_search_bridge::search_files_async(config, None).await?;
220
221 let matches: Vec<FileMatchRpc> = results
223 .matches
224 .into_iter()
225 .map(|m| FileMatchRpc {
226 path: m.path,
227 match_type: m.match_type,
228 score: m.score,
229 indices: m.indices,
230 })
231 .collect();
232
233 let truncated = results.total_match_count > matches.len();
236
237 Ok(json!({
238 "matches": matches,
239 "total_match_count": results.total_match_count,
240 "truncated": truncated,
241 }))
242 }
243
244 async fn handle_list_files(params: &Value) -> Result<Value> {
248 let request: ListFilesRequest =
249 serde_json::from_value(params.clone()).context("Failed to parse list_files parameters")?;
250
251 if !tokio::fs::try_exists(&request.workspace_root).await.unwrap_or(false) {
253 return Err(anyhow::anyhow!("Workspace root does not exist: {}", request.workspace_root.display()));
254 }
255
256 let max_results = file_search_bridge::effective_max_results(request.max_results);
258 let mut config = FileSearchConfig::new(String::new(), request.workspace_root)
259 .with_limit(max_results)
260 .respect_gitignore(request.respect_gitignore);
261
262 for pattern in request.exclude_patterns {
263 config = config.exclude(pattern);
264 }
265
266 let results = file_search_bridge::search_files_async(config, None).await?;
268
269 let files: Vec<String> = file_search_bridge::file_matches_only(results.matches)
271 .into_iter()
272 .map(|m| m.path)
273 .collect();
274 let total = files.len();
275
276 Ok(json!({
277 "files": files,
278 "total": total,
279 }))
280 }
281
282 async fn handle_find_references(params: &Value) -> Result<Value> {
286 let _symbol: String =
289 serde_json::from_value(params.clone()).context("Failed to parse find_references parameters")?;
290
291 Ok(json!({
292 "matches": [],
293 "message": "find_references not yet implemented",
294 }))
295 }
296}
297
298pub fn parse_rpc_request(json_string: &str) -> Result<RpcRequest, Box<RpcResponse>> {
308 match serde_json::from_str::<RpcRequest>(json_string) {
309 Ok(request) => Ok(request),
310 Err(err) => {
311 let error_response = RpcResponse::error(None, RpcError::invalid_request(err.to_string()));
312 Err(Box::new(error_response))
313 }
314 }
315}
316
317#[cfg(test)]
318mod tests {
319 use super::*;
320
321 #[test]
322 fn test_rpc_error_codes() {
323 assert_eq!(RpcError::invalid_request("test").code, -32600);
324 assert_eq!(RpcError::method_not_found().code, -32601);
325 assert_eq!(RpcError::invalid_params("test").code, -32602);
326 assert_eq!(RpcError::internal_error("test").code, -32603);
327 }
328
329 #[test]
330 fn test_rpc_response_success() {
331 let response = RpcResponse::success(Some(json!(1)), json!({"ok": true}));
332 assert_eq!(response.jsonrpc, "2.0");
333 assert_eq!(response.id, Some(json!(1)));
334 assert!(response.result.is_some());
335 assert!(response.error.is_none());
336 }
337
338 #[test]
339 fn test_rpc_response_error() {
340 let error = RpcError::internal_error("test error");
341 let response = RpcResponse::error(Some(json!(1)), error);
342 assert_eq!(response.jsonrpc, "2.0");
343 assert_eq!(response.id, Some(json!(1)));
344 assert!(response.result.is_none());
345 assert!(response.error.is_some());
346 }
347
348 #[test]
349 fn test_search_files_request_parsing() {
350 let json = r#"{
351 "pattern": "main",
352 "workspace_root": "/workspace",
353 "max_results": 100,
354 "exclude_patterns": [],
355 "respect_gitignore": true
356 }"#;
357
358 let value: Value = serde_json::from_str(json).unwrap();
359 let request: SearchFilesRequest = serde_json::from_value(value).unwrap();
360
361 assert_eq!(request.pattern, "main");
362 assert_eq!(request.max_results, 100);
363 assert!(request.respect_gitignore);
364 }
365
366 #[test]
367 fn test_list_files_request_parsing() {
368 let json = r#"{
369 "workspace_root": "/workspace",
370 "exclude_patterns": ["**/node_modules/**"],
371 "respect_gitignore": true,
372 "max_results": 1000
373 }"#;
374
375 let value: Value = serde_json::from_str(json).unwrap();
376 let request: ListFilesRequest = serde_json::from_value(value).unwrap();
377
378 assert_eq!(request.exclude_patterns.len(), 1);
379 assert_eq!(request.max_results, 1000);
380 }
381
382 #[test]
383 fn test_parse_invalid_rpc_request() {
384 let invalid_json = "not valid json";
385 let result = parse_rpc_request(invalid_json);
386 result.unwrap_err();
387 }
388
389 #[test]
390 fn test_file_match_rpc_serialization() {
391 let file_match = FileMatchRpc {
392 path: "src/main.rs".to_string(),
393 match_type: FileMatchType::File,
394 score: 100,
395 indices: Some(vec![4, 5]),
396 };
397
398 let json = serde_json::to_string(&file_match).unwrap();
399 let deserialized: FileMatchRpc = serde_json::from_str(&json).unwrap();
400
401 assert_eq!(deserialized.path, "src/main.rs");
402 assert_eq!(deserialized.score, 100u32);
403 assert_eq!(deserialized.indices, Some(vec![4u32, 5u32]));
404 }
405
406 #[tokio::test]
407 async fn search_files_truncated_reflects_total_match_count() {
408 let workspace = tempfile::tempdir().unwrap();
409 let file_names = [
410 "zzsearchmatch_one.txt",
411 "zzsearchmatch_two.txt",
412 "zzsearchmatch_three.txt",
413 ];
414 for name in file_names {
415 std::fs::write(workspace.path().join(name), b"x").unwrap();
416 }
417
418 let request = |max_results: usize| SearchFilesRequest {
419 pattern: "zzsearchmatch".to_string(),
420 workspace_root: workspace.path().to_path_buf(),
421 max_results,
422 exclude_patterns: Vec::new(),
423 respect_gitignore: false,
424 };
425
426 let complete_page = FileSearchRpcHandler::handle_search_files(&json!(request(file_names.len())), None)
428 .await
429 .unwrap();
430 assert_eq!(complete_page["matches"].as_array().unwrap().len(), file_names.len());
431 assert_eq!(complete_page["total_match_count"], file_names.len());
432 assert_eq!(complete_page["truncated"], false);
433
434 let short_page = FileSearchRpcHandler::handle_search_files(&json!(request(2)), None)
436 .await
437 .unwrap();
438 assert_eq!(short_page["matches"].as_array().unwrap().len(), 2);
439 assert_eq!(short_page["total_match_count"], file_names.len());
440 assert_eq!(short_page["truncated"], true);
441 }
442}