返回 CodeWhale
lsp.rs
1 //! LSP-over-HTTP for native clients (APPS-93).
2 //!
3 //! A native file view needs live diagnostics and semantic references, not just
4 //! receipt-projected ones. These routes serve the *server workspace* through
5 //! one lazily-built [`LspManager`]; engine threads keep their own per-thread
6 //! managers for the post-edit hook. Language servers spawn on first use only —
7 //! a server that never serves an LSP route never pays for one.
8 //!
9 //! Fail-closed as data: a file with no language server, a disabled or absent
10 //! `[lsp]` config, a server the person has not approved for this folder, or an
11 //! LSP timeout all answer `200` with `ok: false` + a machine-
12 //! readable `reason`. Only malformed input (bad path, missing `line`) is an
13 //! HTTP error — a file without a server is a normal state, not a failure.
14 //!
15 //! Routes:
16 //! GET /v1/lsp — capability: enabled, languages, operations
17 //! GET /v1/diagnostics — ?path= (workspace-relative); `items[].line`/`column`
18 //! are 1-based (`position_base: 1`)
19 //! GET /v1/definition — ?path=&line=&character= (1-based input);
20 //! `locations[].range`/`result` are raw 0-based
21 //! LSP positions (`position_base: 0`, `position_encoding:
22 //! "utf-16"`)
23 //! GET /v1/references — same input/output position contract as /v1/definition
24 //! GET /v1/symbols — ?path=&query= (query empty → document symbols);
25 //! same 0-based output positions as /v1/definition
26
27 use std::path::PathBuf;
28 use std::sync::Arc;
29
30 use axum::Json;
31 use axum::extract::{Query, State};
32 use serde::Deserialize;
33 use serde_json::{Value, json};
34
35 use super::workspace::{canonical_workspace, precheck_file_target, relative_request_path};
36 use super::{ApiError, RuntimeApiState};
37 use codewhale_lsp::LspManager;
38 use codewhale_lsp::registry::Language;
39
40 const LSP_OPERATIONS: &[&str] = &["diagnostics", "symbols", "definition", "references"];
41
42 /// The shared workspace manager: built once, from the live config's `[lsp]`
43 /// table and the canonical workspace root.
44 async fn lsp_manager(state: &RuntimeApiState) -> Result<Arc<LspManager>, ApiError> {
45 state
46 .workspace_scope
47 .validate()
48 .await
49 .map_err(|_| ApiError::conflict("selected workspace identity changed"))?;
50 let config = state
51 .config
52 .read()
53 .lsp
54 .clone()
55 .map(codewhale_lsp::LspConfig::from);
56 Ok(state
57 .workspace_scope
58 .lsp
59 .get_or_init(|| {
60 Arc::new(match config {
61 Some(config) => LspManager::new(config, state.workspace_scope.canonical.clone()),
62 None => LspManager::disabled(),
63 })
64 })
65 .clone())
66 }
67
68 /// Resolve a workspace-relative `path` to an absolute file inside the
69 /// workspace, refusing traversal, `.git`, links, and missing files — the same
70 /// confinement the file routes apply.
71 ///
72 /// Async because the confinement it applies is filesystem work:
73 /// `canonical_workspace` canonicalizes and `precheck_file_target` stats every
74 /// component. Both are blocking syscalls, so they ride `spawn_blocking` rather
75 /// than the caller's Tokio worker (#6149). The blocking-calls budget cannot
76 /// see this — the `std::fs` calls live in `workspace.rs`, so a handler calling
77 /// straight through to them is invisible to a per-file scanner.
78 async fn resolve_workspace_file(state: &RuntimeApiState, raw: &str) -> Result<PathBuf, ApiError> {
79 let relative = relative_request_path(raw, false)?;
80 let workspace = state.workspace.clone();
81 tokio::task::spawn_blocking(move || {
82 let root = canonical_workspace(&workspace)?;
83 precheck_file_target(&root, &relative)?
84 .ok_or_else(|| ApiError::not_found("file not found"))?;
85 Ok(root.join(&relative))
86 })
87 .await
88 .map_err(|_| ApiError::internal("workspace file resolution failed"))?
89 }
90
91 /// `intelligence` reports ordinary states (disabled, no server) as error
92 /// strings; split them back into the honest machine-readable reasons.
93 fn lsp_failure(error: String) -> Value {
94 let reason = if error == "stale_document" {
95 "stale_document"
96 } else if error.starts_with(codewhale_lsp::NOT_APPROVED_PREFIX) {
97 "not_approved"
98 } else if error.contains("no LSP server") {
99 "no_server"
100 } else if error.contains("disabled") {
101 "lsp_disabled"
102 } else if error.contains("timed out") {
103 "timeout"
104 } else {
105 "lsp_error"
106 };
107 json!({ "ok": false, "reason": reason, "detail": error })
108 }
109
110 async fn run_intelligence(
111 state: &RuntimeApiState,
112 operation: &str,
113 file: PathBuf,
114 line: Option<u32>,
115 character: Option<u32>,
116 query: Option<String>,
117 expected_revision: Option<String>,
118 ) -> Result<Json<Value>, ApiError> {
119 let manager = lsp_manager(state).await?;
120 if !manager.config().enabled {
121 return Ok(Json(
122 json!({ "ok": false, "reason": "lsp_disabled", "enabled": false }),
123 ));
124 }
125 let result = manager
126 .intelligence_at_revision(
127 operation,
128 &file,
129 line,
130 character,
131 query.as_deref(),
132 expected_revision.as_deref(),
133 )
134 .await;
135 match result {
136 Ok(mut value) => {
137 if let Some(object) = value.as_object_mut() {
138 object.insert("ok".to_string(), Value::Bool(true));
139 }
140 Ok(Json(value))
141 }
142 Err(error) => Ok(Json(lsp_failure(error))),
143 }
144 }
145
146 #[derive(Deserialize)]
147 #[serde(deny_unknown_fields)]
148 pub(super) struct LspFileQuery {
149 path: String,
150 expected_revision: Option<String>,
151 }
152
153 #[derive(Deserialize)]
154 #[serde(deny_unknown_fields)]
155 pub(super) struct LspPositionQuery {
156 path: String,
157 expected_revision: Option<String>,
158 /// 1-based line; required by definition/references.
159 line: Option<u32>,
160 /// 1-based column; defaults to 1.
161 character: Option<u32>,
162 }
163
164 #[derive(Deserialize)]
165 #[serde(deny_unknown_fields)]
166 pub(super) struct LspSymbolsQuery {
167 path: String,
168 expected_revision: Option<String>,
169 query: Option<String>,
170 }
171
172 /// `GET /v1/lsp` — capability report: what this runtime can serve without
173 /// probing or spawning anything.
174 pub(super) async fn lsp_status(
175 State(state): State<RuntimeApiState>,
176 ) -> Result<Json<Value>, ApiError> {
177 let manager = lsp_manager(&state).await?;
178 let config = manager.config();
179 let languages: Vec<Value> = Language::BUILT_IN
180 .iter()
181 .filter_map(|language| {
182 config
183 .resolve_command(*language)
184 .map(|(command, _)| json!({ "language": language.as_key(), "server": command }))
185 })
186 .collect();
187 let custom: Vec<Value> = config
188 .custom
189 .iter()
190 .map(|(extension, def)| {
191 json!({
192 "extension": extension,
193 "language_id": def.language_id,
194 "server": def.command,
195 })
196 })
197 .collect();
198 Ok(Json(json!({
199 "enabled": config.enabled,
200 "diagnostics_contract_version": 1,
201 "semantic_contract_version": 1,
202 "position_encoding": "utf-16",
203 "capability_source": "configuration",
204 "server_probe": "on_request",
205 "workspace": state.workspace.display().to_string(),
206 "operations": LSP_OPERATIONS,
207 "languages": languages,
208 "custom_languages": custom,
209 "poll_after_edit_ms": config.poll_after_edit_ms,
210 "max_diagnostics_per_file": config.max_diagnostics_per_file,
211 "include_warnings": config.include_warnings,
212 })))
213 }
214
215 pub(super) async fn lsp_diagnostics(
216 State(state): State<RuntimeApiState>,
217 Query(query): Query<LspFileQuery>,
218 ) -> Result<Json<Value>, ApiError> {
219 let file = resolve_workspace_file(&state, &query.path).await?;
220 let Json(result) =
221 run_intelligence(&state, "diagnostics", file, None, None, None, None).await?;
222 if result.get("ok").and_then(Value::as_bool) == Some(true)
223 && query.expected_revision.as_deref().is_some_and(|expected| {
224 result.get("source_revision").and_then(Value::as_str) != Some(expected)
225 })
226 {
227 return Ok(Json(json!({"ok":false,"reason":"stale_document"})));
228 }
229 Ok(Json(result))
230 }
231
232 pub(super) async fn lsp_definition(
233 State(state): State<RuntimeApiState>,
234 Query(query): Query<LspPositionQuery>,
235 ) -> Result<Json<Value>, ApiError> {
236 let line = query
237 .line
238 .ok_or_else(|| ApiError::bad_request("definition requires line (1-based)"))?;
239 let file = resolve_workspace_file(&state, &query.path).await?;
240 run_intelligence(
241 &state,
242 "definition",
243 file,
244 Some(line),
245 query.character,
246 None,
247 query.expected_revision,
248 )
249 .await
250 }
251
252 pub(super) async fn lsp_references(
253 State(state): State<RuntimeApiState>,
254 Query(query): Query<LspPositionQuery>,
255 ) -> Result<Json<Value>, ApiError> {
256 let line = query
257 .line
258 .ok_or_else(|| ApiError::bad_request("references requires line (1-based)"))?;
259 let file = resolve_workspace_file(&state, &query.path).await?;
260 run_intelligence(
261 &state,
262 "references",
263 file,
264 Some(line),
265 query.character,
266 None,
267 query.expected_revision,
268 )
269 .await
270 }
271
272 pub(super) async fn lsp_symbols(
273 State(state): State<RuntimeApiState>,
274 Query(query): Query<LspSymbolsQuery>,
275 ) -> Result<Json<Value>, ApiError> {
276 let file = resolve_workspace_file(&state, &query.path).await?;
277 run_intelligence(
278 &state,
279 "symbols",
280 file,
281 None,
282 None,
283 query.query,
284 query.expected_revision,
285 )
286 .await
287 }
288
289 #[cfg(test)]
290 mod diagnostic_freshness_tests {
291 use super::*;
292
293 #[test]
294 fn semantic_queries_accept_expected_revision_without_changing_position_units() {
295 let position: LspPositionQuery = serde_json::from_value(
296 json!({"path":"a.rs","line":2,"character":4,"expected_revision":"abc"}),
297 )
298 .unwrap();
299 assert_eq!(position.expected_revision.as_deref(), Some("abc"));
300 assert_eq!(position.line, Some(2));
301 assert_eq!(position.character, Some(4));
302 let symbols: LspSymbolsQuery =
303 serde_json::from_value(json!({"path":"a.rs","expected_revision":"abc"})).unwrap();
304 assert_eq!(symbols.expected_revision.as_deref(), Some("abc"));
305 assert_eq!(
306 lsp_failure("stale_document".into())["reason"],
307 "stale_document"
308 );
309 }
310
311 #[test]
312 fn failures_keep_unavailable_disabled_and_timeout_distinct() {
313 for (error, reason) in [
314 ("no LSP server is available for this file", "no_server"),
315 ("LSP is disabled ([lsp] enabled = false)", "lsp_disabled"),
316 (
317 "language server not approved: `pyright-langserver` cannot start",
318 "not_approved",
319 ),
320 ("LSP diagnostics timed out after 5 ms", "timeout"),
321 (
322 "LSP diagnostics request failed: server crashed",
323 "lsp_error",
324 ),
325 ] {
326 let result = lsp_failure(error.to_owned());
327 assert_eq!(result["ok"], false);
328 assert_eq!(result["reason"], reason);
329 }
330 }
331 }
332
332 lines RUST