diff --git a/README.md b/README.md index d62566a..db39f6e 100644 --- a/README.md +++ b/README.md @@ -202,6 +202,7 @@ moving on. Fix any type errors or missing imports immediately. | Plugin not active | Run `claude plugin list` to verify, then `/reload-plugins` | | Diagnostics slow on first open | Normal — tree-sitter parses on first load, then incremental | | Java errors show up one tool call after the edit | Claude Code doesn't wait for LSP diagnostics after Edit/Write ([anthropics/claude-code#93321](https://github.com/anthropics/claude-code/issues/93321)). The plugin's hook waits up to 3s for them; if jdtls is slower (large projects), raise `JAVA_FUNCTIONAL_LSP_HOOK_WAIT` (max 4). See [Fresh jdtls diagnostics after edits](#fresh-jdtls-diagnostics-after-edits) | +| False "X cannot be resolved" / "The hierarchy of the type X is inconsistent" on classes from another Maven group of the same repository | jdtls imports only the opened file's Maven group, so a sibling module from another group must come from the local Maven repository; if it was never installed at the reactor's version, its types are missing. Check the server's log (stderr, as captured by your LSP client) for `jdtls: pom.xml errors changed for /pom.xml: ... Missing artifact g:a:jar:v`, `jdtls[log:1]: ...` and `jdtls[status:Error]: ...` lines, and `jdtls: group scope: ...` for which folder was imported. Workaround: `mvn install` the missing modules. Automatic import of in-repo dependencies is tracked in [#110](https://github.com/aviadshiber/java-functional-lsp/issues/110) | ### Other Editors diff --git a/pyproject.toml b/pyproject.toml index 8dd39f7..4f74831 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "hatchling.build" [project] name = "java-functional-lsp" -version = "0.13.0" +version = "0.13.1" description = "Java LSP server enforcing functional programming best practices — null safety, immutability, no exceptions" readme = "README.md" license = { text = "MIT" } @@ -85,6 +85,7 @@ ignore = ["PLR0913", "PLC0415", "PLW0603", "PLW0602"] "**/test_*.py" = ["PLR2004"] "**/cli.py" = ["T20", "PLR0912", "PLR2004"] "**/fixes.py" = ["PLR0911", "PLR0912"] +"scripts/*.py" = ["T20", "PLR2004"] [tool.ruff.format] quote-style = "double" diff --git a/scripts/generate-formula.py b/scripts/generate-formula.py index 81c2c8b..ea8af5a 100755 --- a/scripts/generate-formula.py +++ b/scripts/generate-formula.py @@ -3,6 +3,7 @@ Usage: python3 scripts/generate-formula.py """ + from __future__ import annotations import json diff --git a/src/java_functional_lsp/__init__.py b/src/java_functional_lsp/__init__.py index d7749e3..46c01e4 100644 --- a/src/java_functional_lsp/__init__.py +++ b/src/java_functional_lsp/__init__.py @@ -1,3 +1,3 @@ """java-functional-lsp: A Java LSP server enforcing functional programming best practices.""" -__version__ = "0.13.0" +__version__ = "0.13.1" diff --git a/src/java_functional_lsp/proxy.py b/src/java_functional_lsp/proxy.py index 76392b6..b29dfa5 100644 --- a/src/java_functional_lsp/proxy.py +++ b/src/java_functional_lsp/proxy.py @@ -475,17 +475,48 @@ def _version_key(name: str) -> tuple[int, ...]: return tuple(parts) +@lru_cache(maxsize=64) +def _find_repo_boundary(resolved_module: Path) -> Path: + """Return the repository/reactor boundary enclosing *resolved_module*. + + The boundary is the nearest ancestor (the module itself included) that + contains ``.git`` — a directory, or a file for git worktrees/submodules. + Without any ``.git`` ancestor it is the topmost directory reachable from the + module through consecutive ``pom.xml``-bearing ancestors (the reactor root). + + *resolved_module* must already be resolved (``Path.resolve()``) so symlinked + and real paths share one cache entry and the walk cannot escape via links. + """ + current = resolved_module + while True: + if (current / ".git").exists(): + return current + parent = current.parent + if parent == current: + break + current = parent + top = resolved_module + while top.parent != top and (top.parent / "pom.xml").is_file(): + top = top.parent + return top + + @lru_cache(maxsize=64) def _find_maven_group_root(initial_module: Path, workspace_root: Path) -> Path: """Return the tightest Maven multi-module parent of *initial_module*. - Walks up from ``initial_module.parent`` toward (but NOT including) - ``workspace_root``, returning the first ancestor whose ``pom.xml`` + Walks up from ``initial_module.parent`` toward (but NOT including) the + exclusive upper bound, returning the first ancestor whose ``pom.xml`` contains a ```` section. Falls back to ``initial_module`` itself when no intermediate group pom exists (e.g. modules that sit - directly under ``workspace_root``), keeping the scope as tight as + directly under the reactor root), keeping the scope as tight as possible and avoiding accidental full-monorepo indexing. + The exclusive upper bound is the repository/reactor boundary (see + ``_find_repo_boundary``), or *workspace_root* when the client root lies + below that boundary. A client root *above* the repository (e.g. ``~/git``) + therefore never makes the repository's aggregator pom a candidate (#110). + This keeps the jdtls index bounded to a module *group* (typically 5-20 modules) rather than the full IDE workspace (potentially 200+ modules) which would cause ``OutOfMemoryError: Java heap space`` during indexing. @@ -501,10 +532,16 @@ def _find_maven_group_root(initial_module: Path, workspace_root: Path) -> Path: # outside workspace_root). if not current.is_relative_to(workspace_root): return workspace_root - # Walk up to (but NOT including) workspace_root. Inspecting workspace_root's - # own pom.xml would include the entire monorepo (e.g. 200+ modules) → OOM. + boundary = _find_repo_boundary(resolved_module) + # The client root stays the bound only when it is strictly below the boundary. + bound = workspace_root if workspace_root != boundary and workspace_root.is_relative_to(boundary) else boundary + # Case 2: the module IS the bound (e.g. the repository root) — nothing to walk. + if not current.is_relative_to(bound): + return resolved_module + # Walk up to (but NOT including) the bound. Inspecting the reactor root's + # own pom.xml would include the entire monorepo (e.g. 1000+ modules) → OOM. # `current.parent == current` detects the filesystem root (POSIX `/` or Windows drive). - while current not in (workspace_root, current.parent): + while current not in (bound, current.parent): pom = current / "pom.xml" if pom.is_file(): try: @@ -513,8 +550,8 @@ def _find_maven_group_root(initial_module: Path, workspace_root: Path) -> Path: except OSError: pass current = current.parent - # Case 2: no intermediate group pom found — use the initial module as its own scope - # (tightest possible; avoids full-monorepo indexing for flat modules under workspace_root). + # Case 3: no intermediate group pom found — use the initial module as its own scope + # (tightest possible; avoids full-monorepo indexing for modules directly under the bound). return resolved_module @@ -788,6 +825,135 @@ def _build_effective_params( return effective_params +#: Forwarded jdtls log text is capped at this many characters (after sanitizing). +_JDTLS_LOG_MAX_CHARS = 2048 +#: Raw text is pre-capped before redaction to bound regex cost on huge stack traces. +#: Far above ``_JDTLS_LOG_MAX_CHARS`` so a secret straddling the final cut is still redacted. +_JDTLS_LOG_PRECAP_CHARS = 16384 +#: Token bucket per message kind: at most this many lines per window. +_JDTLS_LOG_RATE = 20 +_JDTLS_LOG_WINDOW_SEC = 10.0 +#: Bound on remembered message fingerprints used for in-window dedupe. +_JDTLS_LOG_DEDUPE_MAX = 512 +#: Pom.xml diagnostics summary: messages shown per change, each capped at this length. +_POM_DIAG_SHOWN = 3 +_POM_DIAG_MSG_MAX_CHARS = 300 + +#: LSP ``MessageType`` (window/logMessage) → proxy log level. Info/Log are DEBUG. +_LOG_MESSAGE_LEVELS: dict[int, int] = {1: logging.WARNING, 2: logging.INFO} +#: Known kinds; anything else is logged as ``other`` so jdtls-provided values never +#: reach the log line unsanitized and the per-kind rate-limit buckets stay bounded. +_LOG_MESSAGE_TYPES = frozenset({1, 2, 3, 4, 5}) +_LANGUAGE_STATUS_TYPES = frozenset({"Starting", "Started", "Error", "Message", "ProjectStatus", "ServiceReady"}) + +# All patterns must stay linear in the input: they run on jdtls text (which can echo +# pom content) synchronously on the reader loop. The userinfo run cannot contain "/", +# so matches starting at different "://" never overlap; query names are bounded and the +# secret keyword is checked in the callback instead of inside the pattern. +_URL_USERINFO_RE = re.compile(r"(://)[^/\s@]+@") +_QUERY_PARAM_RE = re.compile(r"([?&;][^=&;#\s?]{1,64}=)[^&;#\s?]*") +_SECRET_PARAM_NAME_RE = re.compile(r"token|key|secret|password|auth|sig", re.IGNORECASE) +_AUTH_HEADER_RE = re.compile(r"(authorization\s*[:=]\s*)(?:(bearer|basic|token|digest)\s+)?[^\s,;]+", re.IGNORECASE) +_BEARER_RE = re.compile(r"\b(bearer)\s+[A-Za-z0-9._~+/=\-]+", re.IGNORECASE) +_CONTROL_CHARS_RE = re.compile(r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f]") + + +def _secret_query_sub(match: re.Match[str]) -> str: + name = match.group(1) + return f"{name}***" if _SECRET_PARAM_NAME_RE.search(name) else match.group(0) + + +def _auth_header_sub(match: re.Match[str]) -> str: + scheme = match.group(2) + return f"{match.group(1)}{scheme} ***" if scheme else f"{match.group(1)}***" + + +def _sanitize_jdtls_log(text: str, max_chars: int = _JDTLS_LOG_MAX_CHARS) -> str: + """Return a log-safe single-line version of jdtls-provided *text*. + + Redacts URL userinfo (``scheme://***@``), secret-looking query parameters + (``token``/``key``/``secret``/``password``/``auth``/``sig``), and + ``Authorization``/``Bearer`` values; escapes CR/LF; strips every other + C0/C1 control character (incl. ESC, so no terminal escape injection); and + truncates to *max_chars*. Redaction runs before truncation so a cut can + never split a secret out of its matching context. + """ + text = text[:_JDTLS_LOG_PRECAP_CHARS] + text = _URL_USERINFO_RE.sub(r"\1***@", text) + text = _QUERY_PARAM_RE.sub(_secret_query_sub, text) + text = _AUTH_HEADER_RE.sub(_auth_header_sub, text) + text = _BEARER_RE.sub(r"\1 ***", text) + text = text.replace("\r", "\\r").replace("\n", "\\n").replace("\t", " ") + text = _CONTROL_CHARS_RE.sub("", text) + if len(text) > max_chars: + text = text[:max_chars] + "...(truncated)" + return text + + +class _JdtlsLogForwarder: + """Forward jdtls log notifications to the proxy logger, sanitized and rate limited. + + Each message kind (e.g. ``logMessage:1``) has its own token bucket of + ``_JDTLS_LOG_RATE`` lines per ``_JDTLS_LOG_WINDOW_SEC``. A message identical + to one logged within the window is dropped. Dropped lines are counted and + reported as one ``suppressed N jdtls log messages`` line once the window + has rolled over. The clock is injectable for tests. + """ + + def __init__(self, clock: Callable[[], float] = time.monotonic) -> None: + self._clock = clock + self._buckets: dict[str, tuple[float, float]] = {} # kind -> (tokens, last refill) + self._recent: dict[tuple[str, str], float] = {} # (kind, text) -> last logged at + self._suppressed = 0 + self._report_at = clock() + + def forward(self, level: int, kind: str, raw: object) -> None: + """Log *raw* under *kind* at *level* unless rate limited or duplicated.""" + if not logger.isEnabledFor(level): + return + now = self._clock() + self._maybe_report(now) + text = _sanitize_jdtls_log(raw if isinstance(raw, str) else str(raw)) + key = (kind, text) + last = self._recent.get(key) + if last is not None and now - last < _JDTLS_LOG_WINDOW_SEC: + self._suppressed += 1 + return + if not self._take_token(kind, now): + self._suppressed += 1 + return + if len(self._recent) >= _JDTLS_LOG_DEDUPE_MAX: + self._recent = {k: t for k, t in self._recent.items() if now - t < _JDTLS_LOG_WINDOW_SEC} + if len(self._recent) >= _JDTLS_LOG_DEDUPE_MAX: + self._recent.clear() + self._recent[key] = now + logger.log(level, "jdtls[%s]: %s", kind, text) + + def _take_token(self, kind: str, now: float) -> bool: + tokens, last = self._buckets.get(kind, (float(_JDTLS_LOG_RATE), now)) + tokens = min(float(_JDTLS_LOG_RATE), tokens + (now - last) * _JDTLS_LOG_RATE / _JDTLS_LOG_WINDOW_SEC) + if tokens < 1.0: + self._buckets[kind] = (tokens, now) + return False + self._buckets[kind] = (tokens - 1.0, now) + return True + + def _maybe_report(self, now: float) -> None: + if now - self._report_at < _JDTLS_LOG_WINDOW_SEC: + return + if self._suppressed: + logger.info("jdtls: suppressed %d jdtls log messages", self._suppressed) + self._suppressed = 0 + self._report_at = now + + def flush(self) -> None: + """Report any pending suppressed count (called on stop).""" + if self._suppressed: + logger.info("jdtls: suppressed %d jdtls log messages", self._suppressed) + self._suppressed = 0 + self._report_at = self._clock() + + class JdtlsProxy: """Manages a jdtls subprocess and provides async request/notification forwarding.""" @@ -809,6 +975,10 @@ def __init__( self._on_diagnostics = on_diagnostics self._on_stopped = on_stopped self._dropped_request_counts: dict[str, int] = {} + # jdtls window/logMessage + language/status → proxy log (sanitized, rate limited). + self._log_forwarder = _JdtlsLogForwarder() + # uri_key(pom.xml URI) → Error diagnostic messages last seen (m2e import errors, #110). + self._pom_errors: dict[str, tuple[str, ...]] = {} self._available = False self._jdtls_capabilities: dict[str, Any] = {} # Lazy-start state @@ -856,6 +1026,8 @@ def _mark_stopped(self) -> None: self._available = False cached = len(self._diagnostics_cache) self._diagnostics_cache.clear() + self._pom_errors.clear() + self._log_forwarder.flush() if cached: logger.info("jdtls stopped: cleared cached diagnostics for %d files", cached) if self._on_stopped: @@ -1095,6 +1267,12 @@ async def add_module_if_new(self, file_uri: str) -> str | None: if module_path and workspace_path: group_root = _find_maven_group_root(Path(module_path), Path(workspace_path)) group_uri = from_fs_path(str(group_root)) or module_uri + logger.debug( + "jdtls: group scope for %s: boundary %s, group root %s", + _redact_path(module_path), + _redact_path(str(_find_repo_boundary(Path(module_path).resolve()))), + _redact_path(str(group_root)), + ) else: group_uri = module_uri @@ -1166,6 +1344,12 @@ async def expand_full_workspace(self) -> None: if self._initial_module_uri: initial_path = to_fs_path(self._initial_module_uri) or self._initial_module_uri group_root_path = str(_find_maven_group_root(Path(initial_path), Path(workspace_path))) + logger.info( + "jdtls: group scope: client root %s, repository boundary %s, group root %s", + _redact_path(workspace_path), + _redact_path(str(_find_repo_boundary(Path(initial_path).resolve()))), + _redact_path(group_root_path), + ) root_path = group_root_path root_uri = from_fs_path(root_path) or self._original_root_uri @@ -1198,6 +1382,7 @@ async def expand_full_workspace(self) -> None: async def stop(self) -> None: """Shutdown jdtls subprocess gracefully.""" self._mark_stopped() + self._log_forwarder.flush() if self._reader_task and not self._reader_task.done(): self._reader_task.cancel() @@ -1364,4 +1549,62 @@ def _handle_notification(self, msg: dict[str, Any]) -> None: self._diagnostics_cache[self._uri_key(uri)] = diagnostics if self._on_diagnostics: self._on_diagnostics(uri, diagnostics) - # Other notifications (window/logMessage, etc.) are silently ignored + if isinstance(uri, str) and uri.endswith("/pom.xml"): + self._note_pom_diagnostics(uri, diagnostics) + elif method == "window/logMessage" and isinstance(params, dict): + msg_type = params.get("type") + level = _LOG_MESSAGE_LEVELS.get(msg_type, logging.DEBUG) if isinstance(msg_type, int) else logging.DEBUG + kind = f"log:{msg_type}" if msg_type in _LOG_MESSAGE_TYPES else "log:other" + self._log_forwarder.forward(level, kind, params.get("message", "")) + elif method == "language/status" and isinstance(params, dict): + status_type = params.get("type") + level = logging.INFO if status_type == "Error" else logging.DEBUG + kind = f"status:{status_type}" if status_type in _LANGUAGE_STATUS_TYPES else "status:other" + self._log_forwarder.forward(level, kind, params.get("message", "")) + # Other notifications are silently ignored + + def _note_pom_diagnostics(self, uri: str, diagnostics: Any) -> None: + """Log a one-line summary whenever the Error diagnostics set of a pom.xml changes. + + m2e reports import failures (e.g. ``Missing artifact g:a:t:v``) only as + diagnostics on the module's pom.xml, which the server never publishes + (it filters to ``.java``). Logging them here makes the cause of false + "cannot be resolved" errors visible (#110). Does not alter what is + published to the client. + """ + errors: tuple[str, ...] = () + if isinstance(diagnostics, list): + errors = tuple( + str(d.get("message", "")) + for d in diagnostics + if isinstance(d, dict) and d.get("severity") == 1 # DiagnosticSeverity.Error + ) + key = self._uri_key(uri) + if self._pom_errors.get(key, ()) == errors: + return + if errors: + self._pom_errors[key] = errors + else: + self._pom_errors.pop(key, None) + shown = "; ".join(_sanitize_jdtls_log(m, _POM_DIAG_MSG_MAX_CHARS) for m in errors[:_POM_DIAG_SHOWN]) + more = f" (+{len(errors) - _POM_DIAG_SHOWN} more)" if len(errors) > _POM_DIAG_SHOWN else "" + logger.info( + "jdtls: pom.xml errors changed for %s: %d error(s)%s%s", + self._pom_display_path(uri), + len(errors), + f": {shown}" if shown else "", + more, + ) + + def _pom_display_path(self, uri: str) -> str: + """Return *uri*'s path relative to the client root, else a redacted basename.""" + from pygls.uris import to_fs_path + + path = to_fs_path(uri) + root = to_fs_path(self._original_root_uri) if self._original_root_uri else None + if path and root: + try: + return _sanitize_jdtls_log(str(Path(path).relative_to(root)), _POM_DIAG_MSG_MAX_CHARS) + except ValueError: + pass + return _sanitize_jdtls_log(_redact_path(path), _POM_DIAG_MSG_MAX_CHARS) diff --git a/tests/test_proxy.py b/tests/test_proxy.py index 640aa28..67d11aa 100644 --- a/tests/test_proxy.py +++ b/tests/test_proxy.py @@ -989,9 +989,10 @@ class TestLazyStart: @pytest.fixture(autouse=True) def _clear_group_root_cache(self) -> None: # type: ignore[override] """Clear _find_maven_group_root lru_cache between tests.""" - from java_functional_lsp.proxy import _find_maven_group_root + from java_functional_lsp.proxy import _find_maven_group_root, _find_repo_boundary _find_maven_group_root.cache_clear() + _find_repo_boundary.cache_clear() def test_check_available_true(self) -> None: from java_functional_lsp.proxy import JdtlsProxy @@ -1204,6 +1205,7 @@ async def test_expand_full_workspace_removes_initial_module(self, tmp_path: Path for d in (module_a, module_b): d.mkdir(parents=True) (group / "pom.xml").write_text("module-a") + (monorepo / ".git").mkdir() # repository boundary: group sits below it, so it is a candidate module_a_uri = module_a.as_uri() module_b_uri = module_b.as_uri() @@ -1270,6 +1272,7 @@ async def test_add_module_cross_group_expands_new_group(self, tmp_path: Path) -> (d / "pom.xml").write_text("") (group_a / "pom.xml").write_text("mod-a") (group_b / "pom.xml").write_text("mod-b") + (monorepo / ".git").mkdir() # repository boundary: the groups sit below it proxy = JdtlsProxy() proxy._available = True @@ -1310,6 +1313,7 @@ async def test_add_module_within_expanded_group_is_noop(self, tmp_path: Path) -> (group / "pom.xml").write_text( "mod-amod-b" ) + (monorepo / ".git").mkdir() # repository boundary: group sits below it proxy = JdtlsProxy() proxy._available = True diff --git a/tests/test_proxy_scope_logging.py b/tests/test_proxy_scope_logging.py new file mode 100644 index 0000000..3f91c99 --- /dev/null +++ b/tests/test_proxy_scope_logging.py @@ -0,0 +1,360 @@ +"""Tests for #110 part A: repository-bounded group scope (F2) and jdtls log forwarding (F3).""" + +from __future__ import annotations + +import logging +from collections.abc import Iterator +from pathlib import Path +from unittest.mock import AsyncMock + +import pytest + +from java_functional_lsp.proxy import ( + _JDTLS_LOG_MAX_CHARS, + _JDTLS_LOG_RATE, + _JDTLS_LOG_WINDOW_SEC, + JdtlsProxy, + _find_maven_group_root, + _find_repo_boundary, + _JdtlsLogForwarder, + _sanitize_jdtls_log, +) + +_AGGREGATOR = "x" +_LEAF = "leaf" + + +@pytest.fixture(autouse=True) +def _clear_scope_caches() -> Iterator[None]: + _find_maven_group_root.cache_clear() + _find_repo_boundary.cache_clear() + yield + _find_maven_group_root.cache_clear() + _find_repo_boundary.cache_clear() + + +def _has_git_ancestor(path: Path) -> bool: + return any((p / ".git").exists() for p in [path, *path.parents]) + + +@pytest.fixture +def git_tree(tmp_path: Path) -> dict[str, Path]: + """``git/repo`` (.git, aggregator pom) with ``group/mod``, ``top-leaf`` and ``group/sub/leaf``.""" + assert not _has_git_ancestor(tmp_path), "tmp_path must not sit inside a git repository" + git_dir = tmp_path / "git" + repo = git_dir / "repo" + group = repo / "group" + mod = group / "mod" + top_leaf = repo / "top-leaf" + for d in (mod, top_leaf): + d.mkdir(parents=True) + (repo / ".git").mkdir() + (repo / "pom.xml").write_text(_AGGREGATOR) + (group / "pom.xml").write_text(_AGGREGATOR) + (mod / "pom.xml").write_text(_LEAF) + (top_leaf / "pom.xml").write_text(_LEAF) + return {"git": git_dir, "repo": repo, "group": group, "mod": mod, "top_leaf": top_leaf} + + +class TestRepoBoundary: + def test_boundary_is_nearest_git_dir(self, git_tree: dict[str, Path]) -> None: + assert _find_repo_boundary(git_tree["mod"].resolve()) == git_tree["repo"].resolve() + + def test_boundary_accepts_git_file_worktree(self, tmp_path: Path) -> None: + wt = tmp_path / "wt" + mod = wt / "mod" + mod.mkdir(parents=True) + (wt / ".git").write_text("gitdir: /elsewhere/.git/worktrees/wt\n") + (wt / "pom.xml").write_text(_AGGREGATOR) + (mod / "pom.xml").write_text(_LEAF) + assert _find_repo_boundary(mod.resolve()) == wt.resolve() + + def test_boundary_without_git_is_topmost_consecutive_pom(self, tmp_path: Path) -> None: + assert not _has_git_ancestor(tmp_path) + reactor = tmp_path / "outer" / "reactor" + mod = reactor / "group" / "mod" + mod.mkdir(parents=True) + for d in (reactor, reactor / "group", mod): + (d / "pom.xml").write_text(_AGGREGATOR) + # tmp_path/outer has no pom.xml → chain stops at reactor. + assert _find_repo_boundary(mod.resolve()) == reactor.resolve() + + +class TestGroupRootBoundary: + def test_client_root_above_repo_does_not_scope_to_reactor(self, git_tree: dict[str, Path]) -> None: + """Regression (#110 M2): client root ~/git made a top-level module scope to the whole reactor.""" + assert _find_maven_group_root(git_tree["top_leaf"], git_tree["git"]) == git_tree["top_leaf"].resolve() + + def test_client_root_above_repo_still_finds_group(self, git_tree: dict[str, Path]) -> None: + assert _find_maven_group_root(git_tree["mod"], git_tree["git"]) == git_tree["group"].resolve() + + def test_client_root_at_repo(self, git_tree: dict[str, Path]) -> None: + assert _find_maven_group_root(git_tree["mod"], git_tree["repo"]) == git_tree["group"].resolve() + assert _find_maven_group_root(git_tree["top_leaf"], git_tree["repo"]) == git_tree["top_leaf"].resolve() + + def test_client_root_below_repo_stays_the_bound(self, git_tree: dict[str, Path]) -> None: + # Client root = group: group's own pom must not be a candidate → module scopes to itself. + assert _find_maven_group_root(git_tree["mod"], git_tree["group"]) == git_tree["mod"].resolve() + + def test_module_is_repo_root(self, git_tree: dict[str, Path]) -> None: + assert _find_maven_group_root(git_tree["repo"], git_tree["git"]) == git_tree["repo"].resolve() + + def test_module_directly_under_reactor_without_git(self, tmp_path: Path) -> None: + assert not _has_git_ancestor(tmp_path) + reactor = tmp_path / "ws" / "reactor" + leaf = reactor / "leaf" + leaf.mkdir(parents=True) + (reactor / "pom.xml").write_text(_AGGREGATOR) + (leaf / "pom.xml").write_text(_LEAF) + # Client root (tmp_path) is above the reactor; the reactor pom must not be used. + assert _find_maven_group_root(leaf, tmp_path) == leaf.resolve() + + def test_nested_group_without_git(self, tmp_path: Path) -> None: + reactor = tmp_path / "reactor" + group = reactor / "group" + mod = group / "mod" + mod.mkdir(parents=True) + (reactor / "pom.xml").write_text(_AGGREGATOR) + (group / "pom.xml").write_text(_AGGREGATOR) + (mod / "pom.xml").write_text(_LEAF) + assert _find_maven_group_root(mod, tmp_path) == group.resolve() + + def test_symlinked_paths_resolve_to_real_scope(self, git_tree: dict[str, Path], tmp_path: Path) -> None: + link_root = tmp_path / "link-to-git" + link_root.symlink_to(git_tree["git"], target_is_directory=True) + via_link_mod = link_root / "repo" / "top-leaf" + assert _find_maven_group_root(via_link_mod, link_root) == git_tree["top_leaf"].resolve() + assert _find_maven_group_root(link_root / "repo" / "group" / "mod", git_tree["git"]) == ( + git_tree["group"].resolve() + ) + + async def test_expand_logs_scope_once_at_info( + self, git_tree: dict[str, Path], caplog: pytest.LogCaptureFixture + ) -> None: + proxy = JdtlsProxy() + proxy._available = True + proxy._original_root_uri = git_tree["git"].as_uri() + proxy._initial_module_uri = git_tree["top_leaf"].as_uri() + proxy.modules.mark_added(git_tree["top_leaf"].as_uri()) + proxy.send_notification = AsyncMock() # type: ignore[assignment] + with caplog.at_level(logging.INFO, logger="java_functional_lsp.proxy"): + await proxy.expand_full_workspace() + lines = [r.getMessage() for r in caplog.records if "group scope" in r.getMessage()] + assert lines == [ + "jdtls: group scope: client root .../git, repository boundary .../repo, group root .../top-leaf" + ] + proxy.send_notification.assert_not_called() # type: ignore[attr-defined] + + +class TestSanitize: + def test_redacts_url_userinfo(self) -> None: + out = _sanitize_jdtls_log("fetch https://bob:hunter2@repo.example.com/x failed") + assert "hunter2" not in out + assert "bob" not in out + assert "https://***@repo.example.com/x" in out + + @pytest.mark.parametrize("name", ["token", "access_token", "apiKey", "X-Amz-Signature", "password", "auth", "sig"]) + def test_redacts_secret_query_params(self, name: str) -> None: + out = _sanitize_jdtls_log(f"GET https://h/p?a=1&{name}=S3CRET&b=2") + assert "S3CRET" not in out + assert "a=1" in out + assert "b=2" in out + + def test_redacts_authorization_and_bearer(self) -> None: + out = _sanitize_jdtls_log("Authorization: Basic dXNlcjpwYXNz and Bearer abc.def.ghi") + assert "dXNlcjpwYXNz" not in out + assert "abc.def.ghi" not in out + assert "Authorization: Basic ***" in out + assert "Bearer ***" in out + + def test_escapes_newlines_and_strips_control_chars(self) -> None: + out = _sanitize_jdtls_log("line1\r\nline2\x1b[31mred\x00\x85\x9b end") + assert out == "line1\\r\\nline2[31mred end" + + def test_truncates(self) -> None: + out = _sanitize_jdtls_log("x" * 10_000) + assert out.startswith("x" * _JDTLS_LOG_MAX_CHARS) + assert out.endswith("...(truncated)") + assert len(out) == _JDTLS_LOG_MAX_CHARS + len("...(truncated)") + + def test_redacts_before_truncating(self) -> None: + text = "x" * (_JDTLS_LOG_MAX_CHARS - 20) + "https://u:topsecretpassword@h/" + assert "topsecret" not in _sanitize_jdtls_log(text) + + +class TestSanitizeIsLinear: + """Hostile jdtls text (it can echo pom content) must not stall the reader loop.""" + + @pytest.mark.parametrize( + "text", + ["?token" * 3000, "a" * 16384, "?a" * 8000, "x://" * 4000, "&" + "k" * 16000], + ) + def test_pathological_input_is_fast(self, text: str) -> None: + import time + + started = time.monotonic() + _sanitize_jdtls_log(text) + assert time.monotonic() - started < 0.5 + + def test_non_secret_params_are_kept(self) -> None: + assert _sanitize_jdtls_log("https://h/p?version=1&token=abc") == "https://h/p?version=1&token=***" + + +class _Clock: + def __init__(self) -> None: + self.now = 1000.0 + + def __call__(self) -> float: + return self.now + + +def _jdtls_lines(caplog: pytest.LogCaptureFixture) -> list[str]: + return [r.getMessage() for r in caplog.records if r.name == "java_functional_lsp.proxy"] + + +class TestLogForwarding: + def _notify(self, proxy: JdtlsProxy, method: str, params: object) -> None: + proxy._dispatch_message({"jsonrpc": "2.0", "method": method, "params": params}) + + def test_log_message_levels(self, caplog: pytest.LogCaptureFixture) -> None: + proxy = JdtlsProxy() + with caplog.at_level(logging.DEBUG, logger="java_functional_lsp.proxy"): + self._notify(proxy, "window/logMessage", {"type": 1, "message": "boom"}) + self._notify(proxy, "window/logMessage", {"type": 2, "message": "careful"}) + self._notify(proxy, "window/logMessage", {"type": 3, "message": "fyi"}) + self._notify(proxy, "window/logMessage", {"message": "no type"}) + got = [(r.levelno, r.getMessage()) for r in caplog.records if r.name == "java_functional_lsp.proxy"] + assert got == [ + (logging.WARNING, "jdtls[log:1]: boom"), + (logging.INFO, "jdtls[log:2]: careful"), + (logging.DEBUG, "jdtls[log:3]: fyi"), + (logging.DEBUG, "jdtls[log:other]: no type"), + ] + + def test_language_status_levels(self, caplog: pytest.LogCaptureFixture) -> None: + proxy = JdtlsProxy() + with caplog.at_level(logging.INFO, logger="java_functional_lsp.proxy"): + self._notify(proxy, "language/status", {"type": "Starting", "message": "Init..."}) + self._notify(proxy, "language/status", {"type": "Error", "message": "import failed"}) + assert _jdtls_lines(caplog) == ["jdtls[status:Error]: import failed"] + + def test_unknown_kinds_are_folded(self, caplog: pytest.LogCaptureFixture) -> None: + proxy = JdtlsProxy() + with caplog.at_level(logging.DEBUG, logger="java_functional_lsp.proxy"): + self._notify(proxy, "window/logMessage", {"type": "1\nFAKE LINE", "message": "a"}) + self._notify(proxy, "language/status", {"type": "Err\x1b[31m", "message": "b"}) + assert _jdtls_lines(caplog) == ["jdtls[log:other]: a", "jdtls[status:other]: b"] + assert set(proxy._log_forwarder._buckets) == {"log:other", "status:other"} + + def test_format_characters_are_logged_literally(self, caplog: pytest.LogCaptureFixture) -> None: + proxy = JdtlsProxy() + with caplog.at_level(logging.WARNING, logger="java_functional_lsp.proxy"): + self._notify(proxy, "window/logMessage", {"type": 1, "message": "bad %s %(x)s %d"}) + assert _jdtls_lines(caplog) == ["jdtls[log:1]: bad %s %(x)s %d"] + + def test_malformed_params_do_not_raise(self) -> None: + proxy = JdtlsProxy() + self._notify(proxy, "window/logMessage", None) + self._notify(proxy, "window/logMessage", {"type": "1", "message": 42}) + self._notify(proxy, "language/status", ["not", "a", "dict"]) + + def test_dedupe_and_suppressed_report(self, caplog: pytest.LogCaptureFixture) -> None: + clock = _Clock() + fwd = _JdtlsLogForwarder(clock=clock) + with caplog.at_level(logging.INFO, logger="java_functional_lsp.proxy"): + for _ in range(5): + fwd.forward(logging.WARNING, "log:1", "same") + clock.now += _JDTLS_LOG_WINDOW_SEC + 1 + fwd.forward(logging.WARNING, "log:1", "next") + assert _jdtls_lines(caplog) == [ + "jdtls[log:1]: same", + "jdtls: suppressed 4 jdtls log messages", + "jdtls[log:1]: next", + ] + + def test_token_bucket_per_kind(self, caplog: pytest.LogCaptureFixture) -> None: + clock = _Clock() + fwd = _JdtlsLogForwarder(clock=clock) + with caplog.at_level(logging.INFO, logger="java_functional_lsp.proxy"): + for i in range(_JDTLS_LOG_RATE + 10): + fwd.forward(logging.WARNING, "log:1", f"msg {i}") + fwd.forward(logging.INFO, "log:2", "other kind still flows") + fwd.flush() + lines = _jdtls_lines(caplog) + assert sum(1 for m in lines if m.startswith("jdtls[log:1]")) == _JDTLS_LOG_RATE + assert "jdtls[log:2]: other kind still flows" in lines + assert lines[-1] == "jdtls: suppressed 10 jdtls log messages" + + def test_bucket_refills_over_time(self, caplog: pytest.LogCaptureFixture) -> None: + clock = _Clock() + fwd = _JdtlsLogForwarder(clock=clock) + with caplog.at_level(logging.WARNING, logger="java_functional_lsp.proxy"): + for i in range(_JDTLS_LOG_RATE): + fwd.forward(logging.WARNING, "log:1", f"a{i}") + fwd.forward(logging.WARNING, "log:1", "dropped") + clock.now += _JDTLS_LOG_WINDOW_SEC / _JDTLS_LOG_RATE # one token back + fwd.forward(logging.WARNING, "log:1", "allowed") + lines = _jdtls_lines(caplog) + assert "jdtls[log:1]: dropped" not in lines + assert lines[-1] == "jdtls[log:1]: allowed" + + def test_sanitizes_forwarded_text(self, caplog: pytest.LogCaptureFixture) -> None: + proxy = JdtlsProxy() + with caplog.at_level(logging.WARNING, logger="java_functional_lsp.proxy"): + self._notify(proxy, "window/logMessage", {"type": 1, "message": "GET https://u:pw@h/r?token=abc\n\x1b[2Jx"}) + assert _jdtls_lines(caplog) == ["jdtls[log:1]: GET https://***@h/r?token=***\\n[2Jx"] + + +class TestPomDiagnosticsSummary: + def _publish(self, proxy: JdtlsProxy, uri: str, diagnostics: list[dict[str, object]]) -> None: + proxy._dispatch_message( + { + "jsonrpc": "2.0", + "method": "textDocument/publishDiagnostics", + "params": {"uri": uri, "diagnostics": diagnostics}, + } + ) + + def test_logs_only_on_change_and_keeps_publishing(self, tmp_path: Path, caplog: pytest.LogCaptureFixture) -> None: + published: list[tuple[str, list[object]]] = [] + proxy = JdtlsProxy(on_diagnostics=lambda u, d: published.append((u, d))) + proxy._original_root_uri = tmp_path.as_uri() + pom_uri = (tmp_path / "groupB" / "it" / "pom.xml").as_uri() + missing = [ + {"severity": 1, "message": f"Offline / Missing artifact com.example:c{i}:jar:X-DEFAULT"} for i in range(5) + ] + warn = [{"severity": 2, "message": "just a warning"}] + with caplog.at_level(logging.INFO, logger="java_functional_lsp.proxy"): + self._publish(proxy, pom_uri, warn) # no errors, unseen → nothing logged + self._publish(proxy, pom_uri, missing) + self._publish(proxy, pom_uri, missing + warn) # same Error set → nothing + self._publish(proxy, pom_uri, []) + self._publish(proxy, pom_uri, []) + rel = str(Path("groupB") / "it" / "pom.xml") + assert _jdtls_lines(caplog) == [ + f"jdtls: pom.xml errors changed for {rel}: 5 error(s): " + "Offline / Missing artifact com.example:c0:jar:X-DEFAULT; " + "Offline / Missing artifact com.example:c1:jar:X-DEFAULT; " + "Offline / Missing artifact com.example:c2:jar:X-DEFAULT (+2 more)", + f"jdtls: pom.xml errors changed for {rel}: 0 error(s)", + ] + # Publishing to the client is unchanged: every notification is forwarded as-is. + assert [d for _, d in published] == [warn, missing, missing + warn, [], []] + assert proxy.get_cached_diagnostics(pom_uri) == [] + + def test_java_files_are_not_summarized(self, tmp_path: Path, caplog: pytest.LogCaptureFixture) -> None: + proxy = JdtlsProxy() + uri = (tmp_path / "A.java").as_uri() + with caplog.at_level(logging.INFO, logger="java_functional_lsp.proxy"): + self._publish(proxy, uri, [{"severity": 1, "message": "x cannot be resolved"}]) + assert _jdtls_lines(caplog) == [] + + def test_pom_outside_client_root_is_redacted(self, tmp_path: Path, caplog: pytest.LogCaptureFixture) -> None: + proxy = JdtlsProxy() + proxy._original_root_uri = (tmp_path / "elsewhere").as_uri() + uri = (tmp_path / "secret-user" / "pom.xml").as_uri() + with caplog.at_level(logging.INFO, logger="java_functional_lsp.proxy"): + self._publish(proxy, uri, [{"severity": 1, "message": "Missing artifact g:a:jar:1\n\x1b[0m"}]) + assert _jdtls_lines(caplog) == [ + "jdtls: pom.xml errors changed for .../pom.xml: 1 error(s): Missing artifact g:a:jar:1\\n[0m" + ] diff --git a/uv.lock b/uv.lock index 769f2fc..98af412 100644 --- a/uv.lock +++ b/uv.lock @@ -184,7 +184,7 @@ wheels = [ [[package]] name = "java-functional-lsp" -version = "0.13.0" +version = "0.13.1" source = { editable = "." } dependencies = [ { name = "pygls" },