文件
fluent-learn/backend/app/services/lsp_service.py
T

243 行
9.3 KiB
Python
原始文件 Blame 文件历史

此文件含有模棱两可的 Unicode 字符
此文件含有可能会与其他字符混淆的 Unicode 字符。 如果您是想特意这样的,可以安全地忽略该警告。 使用 Escape 按钮显示他们。
"""LSP 服务:本地语言服务器进程池(pyright/clangd 常驻、jdt.ls 按需),JSON-RPC over stdio。
对外接口(请求-响应模式,适配"代码片段提交"教学场景):
- diagnostics(lang, code) -> 报错/警告列表(LSP publishDiagnostics)
- complete(lang, code, line, char) -> 补全项
- hover(lang, code, line, char) -> 悬停提示
"""
from __future__ import annotations
import json
import logging
import queue
import re
import subprocess
import threading
import time
import uuid
logger = logging.getLogger("fluent.services.lsp")
LANG_IDS = {"python": "python", "java": "java", "cpp": "cpp", "c": "c"}
EXT = {"python": ".py", "java": ".java", "cpp": ".cpp", "c": ".c"}
# 语言服务器命令(可按部署环境覆盖)
LSP_COMMANDS: dict[str, list[str]] = {
"python": ["pyright-langserver", "--stdio"],
"cpp": ["clangd", "--background-index=false"],
# jdt.ls 按需:需 eclipse.jdt.ls 包(约 200MB,Java 17+);未装时返回提示
"java": ["java", "-jar", "/opt/jdtls/plugins/org.eclipse.equinox.launcher_*.jar"],
}
class LspError(Exception):
pass
class LspProcess:
"""单个语言服务器进程:JSON-RPC 帧封装 + 请求/响应 + 诊断收集。"""
def __init__(self, lang: str, cmd: list[str], uri_prefix: str = "file:///tmp/fl"):
self.lang = lang
self.cmd = cmd
self.uri_prefix = uri_prefix
self.proc: subprocess.Popen | None = None
self._lock = threading.Lock()
self._pending: dict[int, queue.Queue] = {}
self._diags: dict[str, list[dict]] = {}
self._diag_event: dict[str, threading.Event] = {}
self._msg_id = 0
self._ready = threading.Event()
self._closed = False
def start(self) -> None:
try:
self.proc = subprocess.Popen(
self.cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL,
)
except FileNotFoundError:
raise LspError(f"{self.lang} 语言服务器未安装({self.cmd[0]} 不存在)")
threading.Thread(target=self._read_loop, daemon=True, name=f"lsp-{self.lang}").start()
self._initialize()
# ---------- 帧读写 ----------
def _send(self, payload: dict) -> None:
body = json.dumps(payload, ensure_ascii=False).encode("utf-8")
frame = b"Content-Length: " + str(len(body)).encode() + b"\r\n\r\n" + body
with self._lock:
if not self.proc or self.proc.stdin is None:
raise LspError("LSP 进程未启动")
self.proc.stdin.write(frame)
self.proc.stdin.flush()
def _read_loop(self) -> None:
try:
while not self._closed and self.proc and self.proc.stdout:
line = self.proc.stdout.readline()
if not line:
break
if not line.startswith(b"Content-Length:"):
continue
n = int(line.split(b":")[1])
self.proc.stdout.readline() # 空行
raw = self.proc.stdout.read(n)
if not raw:
break
try:
msg = json.loads(raw)
except json.JSONDecodeError:
continue
self._dispatch(msg)
except Exception as e: # noqa: BLE001
logger.warning("LSP %s 读线程退出: %s", self.lang, e)
def _dispatch(self, msg: dict) -> None:
if "id" in msg and "method" not in msg:
q = self._pending.pop(msg.get("id"), None)
if q:
q.put(msg)
elif msg.get("method") == "publishDiagnostics":
uri = msg["params"].get("uri", "")
self._diags[uri] = msg["params"].get("diagnostics", [])
ev = self._diag_event.get(uri)
if ev:
ev.set()
elif msg.get("method") == "window/logMessage":
logger.debug("LSP %s: %s", self.lang, msg["params"].get("message", ""))
# 其他 notification 忽略
# ---------- RPC ----------
def request(self, method: str, params: dict, timeout: float = 15.0) -> dict:
self._msg_id += 1
mid = self._msg_id
q: queue.Queue = queue.Queue()
self._pending[mid] = q
self._send({"jsonrpc": "2.0", "id": mid, "method": method, "params": params})
try:
resp = q.get(timeout=timeout)
except queue.Empty:
self._pending.pop(mid, None)
raise LspError(f"{self.lang} LSP 请求超时({method})")
if "error" in resp:
raise LspError(f"{self.lang} LSP 错误: {resp['error'].get('message', resp['error'])}")
return resp.get("result", {})
def notify(self, method: str, params: dict) -> None:
self._send({"jsonrpc": "2.0", "method": method, "params": params})
# ---------- 生命周期 ----------
def _initialize(self) -> None:
self.request("initialize", {
"processId": None, "rootUri": None,
"capabilities": {
"textDocument": {"completion": {"completionItem": {"snippetSupport": True}},
"hover": {"contentFormat": ["markdown", "plaintext"]}},
},
"workspaceFolders": None,
}, timeout=30)
self.notify("initialized", {})
self._ready.set()
def close(self) -> None:
self._closed = True
try:
self.proc and self.proc.terminate()
except Exception: # noqa: BLE001
pass
# ---------- 文档操作 ----------
def _uri(self) -> str:
return f"{self.uri_prefix}/{self.lang}/{uuid.uuid4().hex}{EXT[self.lang]}"
def open_doc(self, uri: str, code: str) -> None:
self.notify("textDocument/didOpen", {
"textDocument": {"uri": uri, "languageId": LANG_IDS[self.lang],
"version": 1, "text": code},
})
def diagnostics(self, code: str, timeout: float = 12.0) -> list[dict]:
uri = self._uri()
self._diag_event[uri] = threading.Event()
self.open_doc(uri, code)
if not self._diag_event[uri].wait(timeout):
self._diag_event.pop(uri, None)
raise LspError(f"{self.lang} 诊断超时(服务器无响应)")
self._diag_event.pop(uri, None)
return self._diags.pop(uri, [])
def completion(self, code: str, line: int, character: int) -> list[dict]:
uri = self._uri()
self.open_doc(uri, code)
result = self.request("textDocument/completion", {
"textDocument": {"uri": uri}, "position": {"line": line, "character": character},
"context": {"triggerKind": 1},
})
items = result.get("items", []) if isinstance(result, dict) else result or []
return [{
"label": it.get("label", ""),
"kind": it.get("kind"),
"detail": it.get("detail", ""),
"insertText": it.get("insertText") or it.get("label", ""),
"sortText": it.get("sortText"),
} for it in items]
def hover(self, code: str, line: int, character: int) -> str:
uri = self._uri()
self.open_doc(uri, code)
result = self.request("textDocument/hover", {
"textDocument": {"uri": uri}, "position": {"line": line, "character": character},
})
contents = result.get("contents") if isinstance(result, dict) else None
if isinstance(contents, str):
return contents
if isinstance(contents, dict):
return contents.get("value", "")
if isinstance(contents, list):
parts = []
for c in contents:
if isinstance(c, str):
parts.append(c)
elif isinstance(c, dict):
parts.append(c.get("value", ""))
return "\n".join(parts)
return ""
class LspManager:
"""语言实例注册表:pyright/clangd 常驻,jdt.ls 按需。"""
def __init__(self):
self._procs: dict[str, LspProcess] = {}
self._lock = threading.Lock()
def get(self, lang: str) -> LspProcess:
if lang not in LANG_IDS:
raise LspError(f"暂不支持的 LSP 语言: {lang}(支持 python/java/cpp)")
with self._lock:
proc = self._procs.get(lang)
if proc is None or proc.proc is None or proc.proc.poll() is not None:
cmd = LSP_COMMANDS[lang]
if lang == "java" and not __import__("glob").glob("/opt/jdtls/**/org.eclipse.equinox.launcher_*.jar", recursive=True):
raise LspError("Java LSP(jdt.ls)未安装:需部署 eclipse.jdt.ls 到 /opt/jdtls(约 200MB),安装后自动启用")
proc = LspProcess(lang, cmd)
proc.start()
self._procs[lang] = proc
logger.info("LSP %s 已启动: %s", lang, cmd[0])
return proc
def status(self) -> dict:
out = {}
for lang, cmd in LSP_COMMANDS.items():
proc = self._procs.get(lang)
alive = bool(proc and proc.proc and proc.proc.poll() is None)
out[lang] = {"configured": True, "running": alive}
return out
def shutdown(self) -> None:
for proc in self._procs.values():
proc.close()
manager = LspManager()