Порівняти коміти

...
Автор SHA1 Повідомлення Дата
Deng Liu c92501fda8 fix(agents): settle in-flight turns cleanly on manager shutdown 2026-11-27 16:12:38 -08:00
l0ng-ai 44aab11296 fix(java): open output-directory class files decompiled (#6605)
Opening a .class under target/classes or build/classes jumped to the project .java it was built from. The resolver now returns the class document itself, so the compiled class opens read-only as decompiled text. Library classes in archives are unchanged.

Fixes #6410
2026-11-28 08:11:48 +08:00
l0ng-ai fcd24885c1 fix(build): select Maven projects by coordinates when processing launch resources (#6604)
The launch resources step selected changed modules by their Maven basedir relative to the reactor root. On Windows the basedir need not share a spelling with the opened folder, so the absolute path reached -pl and Maven could not find the project in the reactor. It now selects them by groupId:artifactId.

Fixes #6409
2026-11-28 08:08:24 +08:00
Vladislav Kuzmin 4b3717618f fix(database): isolate JDBC console sessions (#6553)
Two SQL consoles on one JDBC data source waited on the same connection, so a long query, cancellation or close in one blocked the other. The JDBC bridge now multiplexes one connection per console inside the existing bridge JVM (capped at 32, with bounded reply buffers), and result reads, cancel and close are routed to the originating console's connection. DuckDB console connections share the database and its attachments with separate temporary tables and session settings; anonymous SQLite and H2 databases keep one shared connection so their contents stay visible.

Fixes #6484

Co-authored-by: principalwater <[email protected]>
2026-11-28 08:05:59 +08:00
Vladislav Kuzmin 8fd5ee382d fix(database): isolate PostgreSQL manual transactions by SQL console (#6482)
Two PostgreSQL consoles on the same data source shared one manual transaction, so one console could see and commit the other's pending work. Each console now owns its manual transaction: Commit, Roll Back, Stop, result reads and close act on the originating console, retained results keep their transaction until the last reference closes, and a statement for a lost transaction fails before executing. The pool reserves capacity for ordinary work; up to two manual transactions can hold a connection per target, and a third gets a message on how to free a slot. Auto-commit and the transaction-pooler read-only path are unchanged.

Fixes #6445

Co-authored-by: principalwater <[email protected]>
2026-11-28 07:57:17 +08:00
Vladislav Kuzmin 3a3b2e424a perf(remote): reuse the verified release archive for SSH installs (#6288)
The first SSH install recompressed the unpacked server with fast gzip before uploading it. The release download now keeps its gzip next to the cached binary, and the SSH install sends that archive when it decodes to exactly the selected binary (size and BLAKE3 hash); custom binaries and missing or mismatched archives fall back to the existing upload. Container and WSL installs are unchanged. For the Linux arm64 payload this sends about 51 MB instead of 66 MB.

Fixes #6283

Co-authored-by: principalwater <[email protected]>
2026-11-28 07:44:18 +08:00
Vladislav Kuzmin b9d0e28f7a fix(database): bound idle waits for ClickHouse HTTP responses (#6456)
A ClickHouse HTTP response that stalled (a relay holding the reply, a dropped connection) left the console showing Running forever. The built-in driver now stops waiting after 600 seconds without response data and reports that the outcome is unknown, with the query_id; it does not replay or cancel the statement. Reading another chunk restarts the timer, and the Advanced property http_read_timeout (seconds) changes the interval.

Fixes #6435

Co-authored-by: principalwater <[email protected]>
2026-11-28 07:39:50 +08:00
Vladislav Kuzmin 53627ea2e9 fix(database): reject session SET on stateless ClickHouse HTTP (#6442)
ClickHouse accepts a standalone SET over HTTP, but without a session the setting is gone before the next request, so a console script silently ran its later statements with other settings. With use_http_session=false the driver now refuses a session-scoped SET before sending it and says to use a session or query-level SETTINGS; named sessions, SETTINGS clauses and SET DEFAULT ROLE are unchanged. The ClickHouse splitter now also treats # line comments and nested block comments as comments.

Fixes #6432

Co-authored-by: principalwater <[email protected]>
2026-11-28 07:38:29 +08:00
Vladislav Kuzmin 55366a2a31 test(build): report Gradle output when fixture preparation fails (#6564)
When the Gradle model fixture could not be prepared, the test panicked with only the unsupported reason and hid the build error. It now appends the last 150 lines of the build output from both streams, with a unit test for the tail.

Fixes #6555

Co-authored-by: principalwater <[email protected]>
2026-11-28 07:37:09 +08:00
Deng Liuтаdengliu 0b9610fe69 feat(appearance): add a project color strength setting (#6592)
Settings › Appearance › Use project colors in main toolbar gains a Project color strength slider (10–70%) that scales the header's project colour wash. The default stays at today's 22%, so nothing changes unless the slider is moved.

Co-authored-by: dengliu <[email protected]>
2026-11-28 07:34:23 +08:00
l0ng-ai 43e3575eb2 test(settings): expect the Thymeleaf inspection group (#6599)
#6598 added the Thymeleaf inspection group; the inspections tree test still listed the old groups.
2026-11-28 07:33:01 +08:00
Deng Liuтаdengliu bc4a422424 feat(remote-dev): show the remote host in grouped project window tabs (#6577)
Window group tabs of remote development windows now show a flat 'SSH · host' (WSL, Dev Container) label after the project name, with the full host and remote path in the tab's tooltip, and take their name from the remote project's display name instead of the window title. WindowTab carries the connection's host, and remote connections keep the project's display name.

Co-authored-by: dengliu <[email protected]>
2026-11-28 07:26:55 +08:00
Deng Liuтаdengliu 7ccaa10496 feat(remote-dev): distinguish remote windows and project switcher entries (#6557)
Remote projects in the project switcher and the welcome screen's recent list now carry a server badge on their avatar and an 'SSH · host' (WSL, Dev Container) label above the remote path, with search highlights split between host and path. The Remote Host status bar item gains the remote icon, and shows its disconnected state as a warning-coloured label.

Co-authored-by: dengliu <[email protected]>
2026-11-28 07:21:32 +08:00
Deng Liuтаdengliu b5e45ca98b feat(agents): consolidate session stats into a Session Info popover (#6563)
The agent status strip showed context usage, last-turn tokens, every usage-limit window and session cost inline. It now shows the context ring and percentage, plus any usage limit at 80% or more in its warning tone; everything else moves into one Session Info popover with a Context Window bar (reserved-for-response segment, System and User Context breakdown with token counts on hover), the last turn's tokens, usage limits and cost. Free space and deferred categories are skipped by name for Claude Code.

GitHub Copilot sessions now report a context breakdown through _openidea/context_usage (session.metadata.getContextAttribution, with contextInfo and usage_info fallbacks), accumulate AI-credit spend across turns and subagents, keep session cost across usage updates without cost, map /compact to session.history.compact, and label quota windows Chat, Completions and Premium requests.

Co-authored-by: dengliu <[email protected]>
2026-11-28 07:19:50 +08:00
Deng Liuтаdengliu 6faff1b1a8 feat(agents): autocomplete slash command arguments and show inline hints (#6567)
Typing a slash command and a space (/skills, /sandbox, /remote, Codex's /goal) now offers its subcommands with descriptions, chains /skills info and /skills remove into the session's active skills, and shows a muted inline argument hint after /command until an argument is typed. AgentCommand keeps structured choices from Copilot's commands.list, Codex builtins and ACP available_commands_update, with a fallback that parses literal [a|b|c] hints. Enter on /skills and /mcp still opens the session pickers; Tab or a trailing space enters subcommands.

Co-authored-by: dengliu <[email protected]>
2026-11-28 07:14:43 +08:00
Vladislav Kuzmin 1edfa9180b test(profiler): wait for profiled loop work before stopping (#6588)
a_stopped_run_still_writes_its_profile sent SIGINT right after the fixture printed done, which could land before the loop ran, so the profile held only the initial fib(22) calls and the 'the loop ran' assertion failed. The fixture now prints looped after its first fib(18), and the test stops the run only after reading it, then checks for both completed passes.

Fixes #6585

Co-authored-by: principalwater <[email protected]>
2026-11-28 07:09:47 +08:00
Vladislav Kuzmin b15c56cdb0 test(project): wait for the updated attached-root index (#6587)
attached_projects_keep_their_own_excluded_folders waited for the attached project's exclusion settings to change, then for the index to go idle. The settings become visible before the background refresh queues the rescan, so the index could be idle with its previous results. The test now waits for the newly included file to appear in the index.

Fixes #6584

Co-authored-by: principalwater <[email protected]>
2026-11-28 07:09:15 +08:00
audichuang 91ff5c8a15 feat(thymeleaf): warn on fragment expressions naming a missing template or fragment (#6598)
Templates under src/main/resources/templates get a warning (underline and Problems) on a fragment expression whose template does not exist or does not define the fragment, as the inspection Thymeleaf > Unresolved template and fragment references. A fragment counts as defined by th:fragment, th:ref, an element of that name, or an id. It stays silent where names cannot be resolved as Spring Boot's defaults do: spring.thymeleaf.prefix or suffix set in application.properties / .yml, missing templates outside the project folder's own templates directory, ~{_}, ?: fallbacks, expression names, relative names and comments. Template names get .html unless they end in an extension Thymeleaf recognizes, which also fixes Go to Declaration on names with a dot.

Part of #2889

Co-authored-by: audichuang <[email protected]>
2026-11-28 07:07:06 +08:00
Vladislav Kuzmin 929b6837f9 fix(agents): keep archived tasks from resuming on a permission reply (#6586)
Archiving a task cancels its pending permission request. The reply handler checked whether to resume the task, released the state lock, then reacquired it to write Running; an archive finishing in between left running on disk, so the task came back outside the archive after a restart. The handler now records the answer and resumes the task under the same state lock, so a later archive still takes effect. A regression test overlaps settlement with archiving and checks the persisted Archived status and the recorded answer.

Fixes #6583

Co-authored-by: principalwater <[email protected]>
2026-11-28 07:05:44 +08:00
Deng Liuтаdengliu d1af5f656a fix(windows): include remote development windows in Merge All Project Windows (#6593)
Merge All Project Windows only collected windows with a local project, so remote development windows were left out. Candidates now include every local or remote project window (welcome and LightEdit windows stay out), selected by a unit-tested merge_candidates helper in ide-workspace. A member that shares a native tab group or frame with a window outside the merge is split from it first, so that window is neither pulled in nor left hidden.

Co-authored-by: dengliu <[email protected]>
2026-11-28 07:02:55 +08:00
audichuang 604e9348f2 fix(vcs): offer New Changelist and Move under Group By Staging State (#6596)
With the staging area off and the Commit tool window grouped by Staging State, the Staged / Unstaged nodes carry no changelist, so Move to Another Changelist… was hidden and New Changelist… (only on changelist headers) was unreachable. Their nodes and files now offer Move to Another Changelist… in the first group and New Changelist… next to Create Patch and Shelve. Nothing changes with the staging area on.

Fixes #6422

Co-authored-by: audichuang <[email protected]>
2026-11-28 07:01:37 +08:00
audichuang 9592b9ee1b fix(vcs): Jump to Source in the comparison window opens the file in the project window (#6595)
Jump to Source from a diff in the Compare with Branch window went to the comparison window's own editor area, which stays hidden until Show Diff, so nothing appeared. The comparison window now hands openFile to the project window's editor, as the diff window does, for files in any folder of the project (workspace projects included); files outside the project still open in the comparison window.

Fixes #6405

Co-authored-by: audichuang <[email protected]>
2026-11-28 06:59:28 +08:00
Paweł SzymańskiтаPawelSzymanski89 c658b3eb88 fix(notifications): stop leaking a thread per macOS system toast (#6597)
With an action handler registered, tauri-plugin-notification shows every macOS toast on a thread of its own that waits for a click. Toasts that are never clicked keep their thread and NSUserNotificationCenter work alive, so the app slowly gets laggy.

macOS now skips the action handler, so toasts are delivered without tracking; clicking one activates the app instead of focusing the exact window that raised it. Windows and Linux keep per-window focus.

Co-authored-by: PawelSzymanski89 <[email protected]>
2026-11-28 06:57:19 +08:00
audichuang cc5d9d95e4 feat(vcs): bold the current revision's lines in the annotate gutter (#6594)
Lines last changed by the file's current revision are drawn bold in a last-commit colour in the Annotate gutter. The current revision is the last commit to the file at HEAD, or at the annotated revision for Annotate Revision and the diff/merge panes; it is read with vcs_log after the gutter paints and again when HEAD moves. The colour is a new token, --git-annotations-last-commit, listed under Color Scheme > Git > Annotations > Last commit and imported/exported as ANNOTATIONS_LAST_COMMIT_COLOR.

Refs #6397

Co-authored-by: audichuang <[email protected]>
2026-11-28 05:55:03 +08:00
Vladislav Kuzmin 75a15b7eed fix(database): isolate ClickHouse console sessions (#6455)
The built-in ClickHouse HTTP driver gives each SQL console its own named session: a second console finishes while the first one runs, and repeated statements in one console keep their SET values and temporary tables. Result paging, Explain and Stop use the same console identity, and closing the console's last editor or result releases it. Requests without a console stay stateless and can run concurrently. The PR also carries the TODO layout and bookmarks fixture fixes from #6507/#6458.

Closes #6433

Co-authored-by: principalwater <[email protected]>
2026-11-28 05:50:23 +08:00
audichuang b2998cb37a fix(project-tree): scroll the inline name field into view when it starts (#6590)
In a folder scrolled so its top was out of view, New > File / Directory / Package showed no name field and keystrokes went to the tree's speed search: the tree is virtualized and the placeholder row was never mounted. Starting an inline edit (new item or rename) now scrolls its row into view through a new TreeHandle.scrollIntoView, leaving the viewport alone when the row is already visible.

Closes #6461

Co-authored-by: audichuang <[email protected]>
2026-11-28 05:43:05 +08:00
audichuang 5c131edb7e feat(http-client): go to the Spring endpoint from a RestTemplate or WebClient URL (#6581)
Go to Declaration on a literal URL in a RestTemplate, WebClient or RestClient call (the *For* methods, put, delete, exchange with HttpMethod.X, and the fluent .get()/.method(HttpMethod.X).uri(...)) in Java and Kotlin now opens the matching controller method, reusing the Feign controller index, path matching and service filtering. A bare host narrows the targets to that spring.application.name, and falls back to every matching endpoint when no module has that name. With no match, Cmd-click still opens the URL.

Refs #3882

Co-authored-by: audichuang <[email protected]>
2026-11-28 05:41:20 +08:00
audichuang bb8906edb8 feat(vcs): Colors submenu in the Annotate Options menu (#6582)
The Annotate gutter's Options menu gets a Colors submenu with Author, Order (the default, tint by commit order) and Hide. Author gives the authors, sorted by name, the palette colours in turn. The choice is kept in localStorage and applies to every annotated editor, like the column and Names options.

Refs #6397

Co-authored-by: audichuang <[email protected]>
2026-11-28 05:40:40 +08:00
Deng Liuтаdengliu 2e3b087db7 fix(remote-dev): apply custom project color on remote windows and tabs (#6576)
Change Project Color… did nothing in a remote development window: the window group's tab had no root, because it only looked up local projects. Remote windows now report their remote location (ssh://host/path) as the tab root, and the workbench reads the custom colour under the same key the project popup, Welcome and the window tabs store it, so the tab, title bar avatar and frame tint update. Window tabs refresh when a remote session connects or disconnects.

Co-authored-by: dengliu <[email protected]>
2026-11-28 05:38:40 +08:00
l0ng-ai 0c5f1ffabf fix(ci): rebuild the execution-output plugin component after formatting its source (#6591)
#6572 rustfmt-formatted the fixture's source, which changes its source fingerprint, so plugins/build.sh --check reported dist/plugin.wasm as stale. Rebuilt with plugins/build.sh.

Refs #6569
2026-11-28 05:35:34 +08:00
Vladislav Kuzmin 0a9055b40d test(clipboard): serialize Windows clipboard fixtures in Nextest (#6574)
Nextest runs each test in its own process, so the per-process SERIAL mutex of the three Windows clipboard tests from #6549 did not keep them from writing the system clipboard at the same time. A Nextest test group with one slot runs them in turn while other tests stay parallel.

Closes #6571

Co-authored-by: principalwater <[email protected]>
2026-11-28 05:32:15 +08:00
Bert Verhelstтаbertyhell 8776bf536f feat(database): add and drop keys and indexes from Modify Table (#6578)
Modify Table can change an existing table's primary key, add and drop unique keys, and create and drop indexes, each statement shown in the Preview. The index catalog query now marks the indexes that enforce a primary or unique key (DbIndexInfo.key), so they are listed under Keys and dropped with their constraint instead of a drop index the server rejects. Engines that cannot express a change don't offer it (SQLite: indexes only; Snowflake: primary key only). Existing keys and indexes are kept or dropped, not edited. The tree's Drop of a SQL Server index now emits drop index ix on schema.table.

Part of #6307

Co-authored-by: bertyhell <[email protected]>
2026-11-28 04:19:28 +08:00
Vladislav Kuzmin 9cc781717d fix(coverage): align headers while the tree scrolls (#6506)
#6468 increased the Tree's end inset while its scrollbar is visible, so in a narrow Coverage dock the percentage cells shifted 2 px from their headings. The Coverage header now uses the matching inset.

Closes #6499

Co-authored-by: principalwater <[email protected]>
2026-11-28 04:14:12 +08:00
Vladislav Kuzmin 8f1e95e5a2 test(diff): align navigation fixtures with the initial difference (#6505)
#6471 opens a diff at its first change when the caller gives no line, so the cross-file navigation test clicked Next once too often before checking the boundary hint. The tests that navigate from the top now pass an explicit starting line.

Closes #6500

Co-authored-by: principalwater <[email protected]>
2026-11-28 04:14:03 +08:00
l0ng-ai e49c634064 fix(ci): expect commit fixOnCommit in default settings and format the execution-output fixture (#6572)
#6540 added vcs.commit.fixOnCommit, so the defaults JSON shape test now lists it. #5131 left the execution-output plugin fixture unformatted, which failed the plugin crates' cargo fmt --check.
2026-11-28 03:38:37 +08:00
Vadim LazukтаInf1mum 4e82599c49 feat(dotnet): show solution tree discovery states (#6566)
While the .NET workspace scan runs, or after it failed, the Project view showed nothing where the solutions would appear. One placeholder .NET root now carries the state as grey detail text (Scanning… / Scan failed); idle and empty still registers no root, and a failed scan still retries on next use.

Refs #5635

Co-authored-by: Inf1mum <[email protected]>
2026-11-28 03:26:26 +08:00
Akbar Husain e08de6771d feat(mcp): add optimize_imports tool (#6562)
reformat_file's description pointed agents at an optimize_imports tool for import-only cleanup, but none was registered. optimize_imports runs the existing organize-imports path (including the Ruff fallback for Python) on the given files without reformatting and returns the same capped unified diff as reformat_file. Documented in the English and Chinese MCP guides.

Co-authored-by: akbar1214 <[email protected]>
2026-11-28 02:24:34 +08:00
Bert Verhelstтаbertyhell d31a22b5dd perf(editor): let Alt+Enter and refactorings go before Code Vision usage counts (#6560)
Code Vision usage counts run project-wide searches on the same language server and only gave way to Go to Declaration, so Alt+Enter, Refactor menu actions, Refactor This, code actions by kind and Apply Quick Fix queued behind them on a busy server (jdtls on a large project).

The foreground mark now covers every request the user waits for: those requests mark themselves while they ask the server, and the usage counts and implementation gutter markers cancel in-flight work and resume afterwards. Refactor menu actions show a pending hint while the server is busy.

Refs #6381

Co-authored-by: bertyhell <[email protected]>
2026-11-28 02:20:06 +08:00
Bert Verhelstтаbertyhell cead5f08f7 fix(terminal): expand ~ to the remote home in remote windows (#6559)
In a remote window (WSL, SSH, dev container), a ~/ path in the terminal never became a Ctrl+hover link, and a ~/...:12 link opened only through the project-wide basename search, so it could open a same-named file in the project. Terminal links took ~ from the desktop's home only, and had no home at all in a remote window. Both now use the home of the machine the shell runs on: the desktop's home in a local window, and $HOME (else %USERPROFILE%) of the project host in a remote window, read through run_system_env, which runs on that host.

Closes #6246

Co-authored-by: bertyhell <[email protected]>
2026-11-28 02:13:02 +08:00
l0ng-ai 1fc9a9f5d5 feat(vcs): settings to hide the change markers in the gutter and on the scrollbar (#6558)
Editor > General gets a Gutter section with "Highlight modified lines in the gutter" and, under it, "Highlight modified lines in error stripe on the scrollbar". Both are on by default; turning off the first hides the scrollbar marks too, and the change applies to open editors right away through a changeMarkerDisplay facet set from the prefs compartment.

Fixes #6539
2026-11-28 02:01:47 +08:00
Deng Liuтаdengliu 11a8152988 feat(remote-dev): show used and total disk space in resources dashboard (#6554)
The Disk card in Remote Host Resources replaced total capacity with live read/write throughput once disk I/O counters arrived, leaving only the free space in its header. The header now shows used / total like the Memory card, and the subtitle and status bar tooltip keep the free space beside the read/write rates (or the used percentage when I/O counters are unavailable).

Co-authored-by: dengliu <[email protected]>
2026-11-28 01:53:16 +08:00
LU XIANGRUIтаwildcatDownstairs 10b459268e feat(python): set Django up in the Python Console of a Django project (#6543)
In a Django project the Python Console started a plain interpreter, so importing models failed with ImproperlyConfigured. When the project's manage.py sets DJANGO_SETTINGS_MODULE, the console now starts in manage.py's directory and its driver calls django.setup() with that settings module (one already in the environment wins, as for manage.py). On Django 5.2+ it also defines what manage.py shell imports automatically (the models, settings, timezone, ...) and keeps those names out of the Variables pane. The header shows the Django version; if setup fails, the traceback is printed and the console works as before.

Closes #6536

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-28 01:51:13 +08:00
LU XIANGRUIтаwildcatDownstairs 382c22cfc3 feat(python): complete Django field lookups and offer django-types for model typing (#6545)
In Model.objects.filter( (and exclude, get, get_or_create, update_or_create, also after other queryset calls) the keyword completes the model's fields: pk, fields inherited from project base models, and reverse relations by related_name or the lowercase model name. __ follows a relation, and after a plain field come its lookups, with date and time transforms for date fields. Models are read from the project's models.py files and read again when one changes.

When the project's interpreter has Django but neither django-types nor django-stubs, a banner on Python files offers to install django-types (pip as a background task, then the type checker restarts), so basedpyright types managers and model fields.

The stubs check and the manage.py, URL-name and model lookups run again once indexing ends, since on a fresh open they can run before the index has the project's files.

Closes #6541

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-28 01:50:02 +08:00
LU XIANGRUIтаwildcatDownstairs 7bb69e353d feat(python): complete and navigate Django URL names in reverse() calls (#6544)
In Python files, the first string argument of reverse(, reverse_lazy(, redirect( and resolve_url( completes URL names, and Go to Declaration on it opens the path(..., name=...) entry. Names come from the project's urls.py files under their module's app_name (shop:product), with the file shown beside each, and are read again when a urls.py changes. They rank above the parameter names the language server suggests in the string.

Closes #6537

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-28 01:48:54 +08:00
LU XIANGRUIтаwildcatDownstairs 988f93be46 feat(python): run manage.py tasks from Run Anything with command completion (#6542)
Adds Run manage.py Task… (django.runManageTask), which opens Run Anything with manage.py typed. A Run Anything provider recognises manage.py lines (also ./manage.py and python manage.py), completes the command word from manage.py help (read once per project, shown with the app that defines each command), and runs the line with the project interpreter in manage.py's directory in a terminal-emulating Run tab, so createsuperuser and shell can prompt. runAnything.show now takes an optional initial line.

Closes #6535

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-28 01:48:00 +08:00
Muuтаmuutot 494dd61193 feat(settings): import JetBrains live templates (#6546)
Import Settings now reads templates/*.xml from a JetBrains settings archive or settings folder and, after confirmation, merges the templates (group, abbreviation, description, body, variables and defaults, contexts, deactivated state) into the custom live templates under stable jetbrains.* ids, so importing again updates rather than duplicates. Built-in and unrelated custom templates are kept.

Contexts are read as IDEA writes them: the full context id first (JAVA_SCRIPT, SHELL_SCRIPT), then its shorter prefixes down to the language (JAVA_STATEMENT, Python_Class, JS_STATEMENT, KOTLIN_TOPLEVEL), OTHER as everywhere, and comment or string contexts expand outside code. Templates whose contexts don't map to a language are listed as not imported, never made global; expressions OpenIDEA can't evaluate are listed and kept as text.

Co-authored-by: muutot <[email protected]>
2026-11-28 01:39:19 +08:00
audichuang cbabb5e9b5 fix(debug): cancel pending debug builds and launches when closing a project (#6282)
Closing a project while a debug launch was still starting (a Cargo build before CodeLLDB, or the adapter spawning and connecting) didn't stop it, so the adapter started for the closed project once the build finished: nothing between debug_start and session registration was tied to the project's lifetime.

Project now has a closed token that debug_start passes down. Closing the project cancels the Cargo build (killing its process tree, through a Job object on Windows) and the adapter launch.

Co-authored-by: audichuang <[email protected]>
2026-11-28 01:35:15 +08:00
GuoYuтаguoyucode 75997ae0ee fix(clipboard): read and write the Windows clipboard one call at a time (#6549)
Concurrent clipboard reads from the project tree raced on the Windows clipboard, which only one caller can open at a time, so a paste could fail with an access error. All Windows clipboard functions now hold a process-wide lock, and the project tree joins an OS clipboard refresh that is still running instead of starting another read.

Fixes #6388

Co-authored-by: guoyucode <[email protected]>
2026-11-28 01:25:36 +08:00
Muuтаmuutot 81df8f2649 feat(python): apply Ruff safe fixes on save and commit (#6540)
Adds a "Fix safe lint issues on save" Ruff setting that runs ruff check --fix-only on Python files when saving, and a commit check that applies the same safe fixes before committing. Safe fixes run separately from formatting and Format on save.

Also translates the new "No safe lint fixes to apply" message and drops the replaced on-save hint from the ko/ru/tr catalogs.

Co-authored-by: muutot <[email protected]>
2026-11-28 01:23:52 +08:00
253 змінених файлів з 13512 додано та 1887 видалено

No files matched your search

+13
Переглянути файл
@@ -0,0 +1,13 @@
# Nextest runs tests in separate processes. These three tests write the same Windows clipboard.
[test-groups.windows-clipboard]
max-threads = 1
[[profile.default.overrides]]
filter = '''
package(=ide-clipboard) & (
test(=tests::text_reads_on_one_thread_do_not_corrupt_the_heap)
| test(=tests::text_reads_taking_turns_do_not_corrupt_the_heap)
| test(=tests::concurrent_text_reads_do_not_corrupt_the_heap)
)
'''
test-group = "windows-clipboard"
Створено
+1
Переглянути файл
@@ -5003,6 +5003,7 @@ dependencies = [
name = "ide-tools"
version = "0.1.54"
dependencies = [
"blake3",
"flate2",
"hex",
"http",
+40 -3
Переглянути файл
@@ -2,8 +2,8 @@
//! the agent reports them over ACP.
use crate::model::{
AgentCommand, AgentCommandSource, AgentConfigOption, AgentConfigValue, AgentConfigVia, AgentCost, AgentLimit,
AgentModelPricing, AgentTokens, AgentUsage,
AgentCommand, AgentCommandChoice, AgentCommandSource, AgentConfigOption, AgentConfigValue, AgentConfigVia,
AgentCost, AgentLimit, AgentModelPricing, AgentTokens, AgentUsage,
};
use serde_json::{Value, json};
@@ -278,11 +278,30 @@ pub(crate) fn commands_of(update: &Value, provider: &str) -> Vec<AgentCommand> {
} else {
c.get("source").and_then(|s| serde_json::from_value(s.clone()).ok()).unwrap_or_default()
};
let mut seen_choices = std::collections::HashSet::new();
let choices = c
.pointer("/input/choices")
.and_then(Value::as_array)
.into_iter()
.flatten()
.filter_map(|ch| {
let choice_name =
ch.get("name").and_then(Value::as_str).map(str::trim).filter(|n| !n.is_empty())?;
if !seen_choices.insert(choice_name.to_ascii_lowercase()) {
return None;
}
Some(AgentCommandChoice {
name: choice_name.to_owned(),
description: str_of(ch, "description").unwrap_or_default(),
})
})
.collect();
Some(AgentCommand {
name: name.to_owned(),
source,
description: str_of(c, "description").unwrap_or_default(),
hint: c.pointer("/input/hint").and_then(Value::as_str).filter(|h| !h.is_empty()).map(str::to_owned),
choices,
})
})
.collect()
@@ -654,6 +673,7 @@ mod tests {
let old: AgentCommand =
serde_json::from_value(json!({"name": "review", "description": "Review", "hint": null})).unwrap();
assert_eq!(old.source, AgentCommandSource::Command);
assert!(old.choices.is_empty());
let skill = AgentCommand { source: AgentCommandSource::Skill, ..old };
assert_eq!(serde_json::from_value::<AgentCommand>(serde_json::to_value(&skill).unwrap()).unwrap(), skill);
}
@@ -663,13 +683,30 @@ mod tests {
let cmds = commands_of(
&json!({"availableCommands": [
{"name": "review", "description": "Review changes", "input": {"hint": "what to review"}},
{"name": "/init", "description": "Write CLAUDE.md", "input": null}
{"name": "/init", "description": "Write CLAUDE.md", "input": null},
{"name": "skills", "description": "Manage skills", "input": {
"hint": "[list|info]",
"choices": [
{"name": "list", "description": "List all available skills"},
{"name": "LIST", "description": "Duplicate ignored"},
{"name": " ", "description": "Blank ignored"},
{"name": "info", "description": "Show details for a skill"}
]
}}
]}),
"claude",
);
assert_eq!(cmds[0].source, AgentCommandSource::Command);
assert_eq!(cmds[0].hint.as_deref(), Some("what to review"));
assert!(cmds[0].choices.is_empty());
assert_eq!((cmds[1].name.as_str(), cmds[1].hint.as_ref()), ("init", None));
assert_eq!(
cmds[2].choices,
vec![
AgentCommandChoice { name: "list".into(), description: "List all available skills".into() },
AgentCommandChoice { name: "info".into(), description: "Show details for a skill".into() },
]
);
let u = usage_of(&json!({"used": 1200, "size": 200000, "cost": {"amount": 0.42, "currency": "USD"}})).unwrap();
assert_eq!((u.used, u.size), (1200, 200000));
assert!(usage_of(&json!({"used": 1, "size": 0})).is_none());
File diff suppressed because it is too large. Load diff
+18 -1
Переглянути файл
@@ -255,6 +255,14 @@ pub enum AgentCommandSource {
Skill,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentCommandChoice {
pub name: String,
#[serde(default)]
pub description: String,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentCommand {
@@ -265,6 +273,9 @@ pub struct AgentCommand {
pub hint: Option<String>,
#[serde(default)]
pub source: AgentCommandSource,
/// Fixed subcommand/argument choices advertised by the agent (e.g. `list`, `info` for `/skills`).
#[serde(default)]
pub choices: Vec<AgentCommandChoice>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
@@ -289,6 +300,9 @@ pub struct AgentContextUsage {
pub model: String,
pub is_auto_compact_enabled: Option<bool>,
pub auto_compact_threshold: Option<u32>,
/// Tokens reserved for model response / output buffer, when the agent reports it.
#[serde(default)]
pub reserved_tokens: Option<u32>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
@@ -296,13 +310,16 @@ pub struct AgentContextCategory {
pub name: String,
pub tokens: u32,
pub kind: Option<String>,
/// Visual section group (e.g. `"System"`, `"User Context"`).
#[serde(default)]
pub group: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentCost {
pub amount: f64,
/// ISO 4217 code, e.g. `USD`.
/// ISO 4217 code (e.g. `USD`), or `"credits"` for AI-credit billing.
pub currency: String,
}
+31 -5
Переглянути файл
@@ -8,43 +8,69 @@ pub(crate) struct BuiltinCommandSpec {
pub name: &'static str,
pub description: &'static str,
pub hint: Option<&'static str>,
pub choices: &'static [(&'static str, &'static str)],
}
pub(crate) const BUILTIN_COMMANDS: &[BuiltinCommandSpec] = &[
BuiltinCommandSpec { name: "plan", description: "Turn plan mode on or off.", hint: None },
BuiltinCommandSpec { name: "plan", description: "Turn plan mode on or off.", hint: None, choices: &[] },
BuiltinCommandSpec {
name: "mcp",
description: "Show the status of the MCP servers, or reconnect them.",
hint: Some("[reconnect]"),
choices: &[("reconnect", "Reload and reconnect MCP servers.")],
},
BuiltinCommandSpec { name: "skills", description: "List available skills.", hint: None, choices: &[] },
BuiltinCommandSpec {
name: "status",
description: "Display session configuration and token usage.",
hint: None,
choices: &[],
},
BuiltinCommandSpec { name: "skills", description: "List available skills.", hint: None },
BuiltinCommandSpec { name: "status", description: "Display session configuration and token usage.", hint: None },
BuiltinCommandSpec {
name: "review",
description: "Review uncommitted changes, or review with custom instructions.",
hint: Some("optional review instructions"),
choices: &[],
},
BuiltinCommandSpec {
name: "review-branch",
description: "Review changes relative to a base branch.",
hint: Some("branch name"),
choices: &[],
},
BuiltinCommandSpec {
name: "review-commit",
description: "Review a specific commit.",
hint: Some("commit sha"),
choices: &[],
},
BuiltinCommandSpec { name: "review-commit", description: "Review a specific commit.", hint: Some("commit sha") },
BuiltinCommandSpec {
name: "compact",
description: "Summarize conversation to avoid hitting the context limit.",
hint: None,
choices: &[],
},
BuiltinCommandSpec {
name: "goal",
description: "Set a goal to keep pursuing.",
hint: Some("[<objective>|clear|pause|resume]"),
choices: &[
("clear", "Clear the current goal."),
("pause", "Pause the current goal."),
("resume", "Resume a paused goal."),
],
},
BuiltinCommandSpec {
name: "rename",
description: "Rename the current session.",
hint: Some("new name"),
choices: &[],
},
BuiltinCommandSpec { name: "rename", description: "Rename the current session.", hint: Some("new name") },
BuiltinCommandSpec {
name: "logout",
description: "Sign out of Codex. This option is available when you are logged in via ChatGPT.",
hint: None,
choices: &[],
},
];
+9 -1
Переглянути файл
@@ -14,7 +14,7 @@ mod tests;
use super::Shim;
use crate::acp::AUTH_REQUIRED;
use crate::provider::ProviderSpec;
use crate::{AgentCommand, AgentCommandSource};
use crate::{AgentCommand, AgentCommandChoice, AgentCommandSource};
use commands::{BuiltinCommand, ParsedCommand};
use ide_jsonrpc::{Framing, Handler, Peer, RpcError, codes};
use parking_lot::Mutex;
@@ -47,6 +47,14 @@ pub(crate) fn builtin_commands() -> Vec<AgentCommand> {
description: command.description.to_owned(),
hint: command.hint.map(str::to_owned),
source: AgentCommandSource::Command,
choices: command
.choices
.iter()
.map(|(name, description)| AgentCommandChoice {
name: (*name).to_owned(),
description: (*description).to_owned(),
})
.collect(),
})
.collect()
}
+5
Переглянути файл
@@ -2084,6 +2084,11 @@ fn skills_become_commands_with_their_invocation_names() {
let commands = crate::config::commands_of(&update, "codex");
assert!(commands.iter().all(|c| c.source == crate::AgentCommandSource::Skill));
assert_eq!(commands[0].name, "$review");
let builtins = builtin_commands();
let goal = builtins.iter().find(|c| c.name == "goal").unwrap();
assert_eq!(goal.choices.iter().map(|c| c.name.as_str()).collect::<Vec<_>>(), ["clear", "pause", "resume"]);
let mcp = builtins.iter().find(|c| c.name == "mcp").unwrap();
assert_eq!(mcp.choices.iter().map(|c| c.name.as_str()).collect::<Vec<_>>(), ["reconnect"]);
assert!(skill_commands(&json!({"data": []})).unwrap()["availableCommands"].as_array().unwrap().is_empty());
assert!(skill_commands(&json!({})).is_none());
}
+185 -7
Переглянути файл
@@ -522,6 +522,7 @@ impl CopilotShim {
"session/set_config_option" => self.set_config(&params).await,
"session/prompt" => self.prompt(&params, false).await,
"_openidea/steer" => self.prompt(&params, true).await,
"_openidea/context_usage" => self.context_usage(&params).await,
"_openidea/stop_task" => self.stop_task(&params).await,
"session/close" => self.close_session(&params).await,
_ => Err(error(codes::METHOD_NOT_FOUND, format!("unsupported method {method}"))),
@@ -537,7 +538,7 @@ impl CopilotShim {
"promptCapabilities": { "image": true, "audio": false, "embeddedContext": true },
"mcpCapabilities": { "http": true, "sse": true, "stdio": true },
"sessionCapabilities": { "close": {}, "list": {} },
"_meta": { "openidea": { "steer": true, "backgroundTasks": true } },
"_meta": { "openidea": { "steer": true, "backgroundTasks": true, "contextUsage": true } },
},
"agentInfo": {
"name": "copilot",
@@ -655,12 +656,47 @@ impl CopilotShim {
let options = models::config_options(&catalog, &settings);
self.state.lock().sessions.insert(actual_id.clone(), SessionEntry::new(settings));
self.publish_commands(&actual_id, cwd);
self.sync_usage_metrics(&actual_id);
Ok(json!({
"sessionId": actual_id,
"configOptions": options,
}))
}
fn sync_usage_metrics(self: &Arc<Self>, session_id: &str) {
let shim = self.clone();
let sid = session_id.to_owned();
self.runtime.spawn(async move {
let Ok(metrics) = shim.call("session.usage.getMetrics", json!({ "sessionId": sid })).await else {
return;
};
let Some(nano_aiu) = metrics.get("totalNanoAiu").and_then(Value::as_f64) else {
return;
};
let catalog = shim.catalog.try_lock().ok().and_then(|g| g.clone());
let update = {
let mut st = shim.state.lock();
st.sessions.get_mut(&sid).and_then(|entry| {
entry.translator.set_total_nano_aiu(nano_aiu);
let used = entry.translator.last_used_tokens?;
let size = entry
.translator
.last_usage_snapshot
.as_ref()
.map(|s| s.token_limit)
.filter(|&s| s > 0)
.or_else(|| {
catalog.as_deref().and_then(|m| entry.settings.active_context_tokens(m)).filter(|&s| s > 0)
})?;
Some(entry.translator.usage_update(used, size))
})
};
if let Some(update) = update {
shim.send_update(&sid, update);
}
});
}
fn publish_commands(self: &Arc<Self>, session_id: &str, cwd: &str) {
let shim = self.clone();
let sid = session_id.to_owned();
@@ -735,25 +771,152 @@ impl CopilotShim {
let new_limit = next_settings.active_context_tokens(&catalog);
let options = models::config_options(&catalog, &next_settings);
{
let usage_update = {
let mut st = self.state.lock();
if let Some(entry) = st.sessions.get_mut(session_id) {
entry.settings = next_settings;
if matches!(option, MODEL | CONTEXT_TIER)
&& let (Some(used), Some(size)) = (last_used, new_limit.filter(|&s| s > 0))
{
Some(entry.translator.usage_update(used, size))
} else {
None
}
} else {
None
}
}
if matches!(option, MODEL | CONTEXT_TIER)
&& let (Some(used), Some(size)) = (last_used, new_limit.filter(|&s| s > 0))
{
self.send_update(session_id, json!({ "sessionUpdate": "usage_update", "used": used, "size": size }));
};
if let Some(update) = usage_update {
self.send_update(session_id, update);
}
Ok(json!({ "configOptions": options }))
}
async fn context_usage(&self, params: &Value) -> Result<Value, ResponseError> {
let session_id = str_param(params, "sessionId")?;
let catalog = self.models().await.ok();
let (model_id, fallback_limit, snapshot) = {
let st = self.state.lock();
let entry = st.sessions.get(session_id).ok_or_else(|| invalid(format!("unknown session {session_id}")))?;
let limit = catalog.as_deref().and_then(|models| entry.settings.active_context_tokens(models));
(entry.settings.model.clone(), limit, entry.translator.last_usage_snapshot.clone())
};
let (attr_res, metrics_res) = tokio::join!(
self.call("session.metadata.getContextAttribution", json!({ "sessionId": session_id })),
self.call("session.usage.getMetrics", json!({ "sessionId": session_id })),
);
if let Ok(metrics) = metrics_res
&& let Some(nano_aiu) = metrics.get("totalNanoAiu").and_then(Value::as_f64)
&& let Some(entry) = self.state.lock().sessions.get_mut(session_id)
{
entry.translator.set_total_nano_aiu(nano_aiu);
}
let mut usage =
attr_res.ok().and_then(|v| translate::context_usage_from_attribution(&v, &model_id, fallback_limit));
if usage.is_none()
&& !model_id.is_empty()
&& let Ok(info) = self
.call("session.metadata.contextInfo", json!({ "sessionId": session_id, "modelName": model_id }))
.await
{
usage = translate::context_usage_from_context_info(&info, &model_id, fallback_limit);
}
let usage = usage
.or_else(|| snapshot.as_ref().map(|snap| translate::context_usage_from_snapshot(snap, &model_id)))
.ok_or_else(|| error(codes::INTERNAL_ERROR, "Context details are not available yet"))?;
let meter_update = {
let mut st = self.state.lock();
st.sessions.get_mut(session_id).map(|entry| {
entry.translator.last_used_tokens = Some(usage.total_tokens);
entry.translator.usage_update(usage.total_tokens, usage.max_tokens)
})
};
if let Some(update) = meter_update {
self.send_update(session_id, update);
}
serde_json::to_value(usage).map_err(|e| error(codes::INTERNAL_ERROR, e.to_string()))
}
async fn compact_session(&self, session_id: &str, instructions: Option<&str>) -> Result<Value, ResponseError> {
let mut req = json!({
"sessionId": session_id,
"trigger": "manual",
});
if let Some(text) = instructions.map(str::trim).filter(|s| !s.is_empty()) {
req["customInstructions"] = json!(text);
}
let res = self.call("session.history.compact", req).await?;
let success = res.get("success").and_then(Value::as_bool).unwrap_or(true);
if !success {
let msg = res.get("error").and_then(Value::as_str).unwrap_or("Conversation compaction failed");
return Err(error(codes::INTERNAL_ERROR, msg));
}
let catalog = self.models().await.ok();
let meter_update = {
let mut st = self.state.lock();
st.sessions.get_mut(session_id).and_then(|entry| {
let cw = res.get("contextWindow")?;
let used = cw.get("currentTokens").and_then(Value::as_u64).and_then(|n| u32::try_from(n).ok())?;
let fallback_limit = catalog.as_deref().and_then(|models| entry.settings.active_context_tokens(models));
let size = cw
.get("tokenLimit")
.and_then(Value::as_u64)
.and_then(|n| u32::try_from(n).ok())
.filter(|&n| n > 0)
.or(fallback_limit.filter(|&n| n > 0))?;
let u32_field = |k: &str| cw.get(k).and_then(Value::as_u64).and_then(|n| u32::try_from(n).ok());
entry.translator.record_snapshot(translate::UsageSnapshot {
current_tokens: used,
token_limit: size,
system_tokens: u32_field("systemTokens"),
tool_definitions_tokens: u32_field("toolDefinitionsTokens"),
conversation_tokens: u32_field("conversationTokens"),
});
Some(entry.translator.usage_update(used, size))
})
};
if let Some(update) = meter_update {
self.send_update(session_id, update);
}
let tokens_removed = res.get("tokensRemoved").and_then(Value::as_u64).unwrap_or(0);
let messages_removed = res.get("messagesRemoved").and_then(Value::as_u64).unwrap_or(0);
let summary = if tokens_removed > 0 || messages_removed > 0 {
format!("Compacted conversation ({tokens_removed} tokens, {messages_removed} messages removed).")
} else {
"Conversation compacted.".to_owned()
};
self.send_update(
session_id,
json!({ "sessionUpdate": "agent_message_chunk", "content": { "type": "text", "text": summary } }),
);
if let Some(entry) = self.state.lock().sessions.get_mut(session_id) {
entry.early_cancel = None;
}
Ok(json!({ "stopReason": "end_turn" }))
}
async fn prompt(&self, params: &Value, steer: bool) -> Result<Value, ResponseError> {
let session_id = str_param(params, "sessionId")?.to_owned();
let blocks = params.get("prompt").and_then(Value::as_array).ok_or_else(|| invalid("missing prompt"))?;
let (text, attachments, temp_files) = build_prompt_payload(&session_id, blocks);
if !steer
&& attachments.is_empty()
&& let Some(instructions) = parse_compact_command(&text)
{
cleanup_files(&temp_files);
return self.compact_session(&session_id, instructions).await;
}
if steer {
let (is_running, main_busy) = {
let st = self.state.lock();
@@ -1070,6 +1233,21 @@ impl CopilotShim {
}
}
fn parse_compact_command(text: &str) -> Option<Option<&str>> {
let trimmed = text.trim();
if trimmed == "/compact" {
return Some(None);
}
let rest = trimmed.strip_prefix("/compact")?;
let first = rest.chars().next()?;
if first.is_whitespace() {
let focus = rest.trim();
Some((!focus.is_empty()).then_some(focus))
} else {
None
}
}
fn build_prompt_payload(session_id: &str, blocks: &[Value]) -> (String, Vec<Value>, Vec<PathBuf>) {
let mut text_parts = Vec::new();
let mut attachments = Vec::new();
+309
Переглянути файл
@@ -1,6 +1,11 @@
use super::models::{self, CONTEXT_TIER, EFFORT, MODEL, Mode, Settings, UserDefaults};
use super::translate::{
self, EventTranslator, UsageSnapshot, context_usage_from_attribution, context_usage_from_context_info,
context_usage_from_snapshot,
};
use super::{acp_args, acp_fallback_spec, attach, headless_args};
use crate::config;
use crate::model::{AgentContextCategory, AgentContextUsage};
use crate::provider::Driver;
use ide_jsonrpc::{Framing, Handler, Peer, codes};
use parking_lot::Mutex;
@@ -443,6 +448,38 @@ impl Handler for FakeCopilotServer {
] })),
"session.tasks.cancel" => Ok(json!({ "cancelled": true })),
"session.abort" => Ok(json!({})),
"session.usage.getMetrics" => Ok(json!({
"totalNanoAiu": 4_211_400_000_000.0,
"totalPremiumRequestCost": 12.0,
})),
"session.metadata.getContextAttribution" => Ok(json!({
"contextAttribution": {
"totalTokens": 405_200,
"limit": 1_000_000,
"promptTokenLimit": 936_000,
"bufferTokens": 64_000,
"compactionThreshold": 800_000,
"modelId": "gemini-4-carbon",
"entries": [
{ "kind": "system", "id": "system:root", "label": "System", "tokens": 223_000 },
{ "kind": "system", "id": "system:prompt", "label": "System Prompt", "tokens": 20_000, "parentId": "system:root" },
{ "kind": "toolDefinition", "id": "toolDefinition:bash", "label": "bash", "tokens": 203_000, "parentId": "system:root" },
{ "kind": "tool", "id": "tool:bash", "label": "bash", "tokens": 69_000 }
]
}
})),
"session.history.compact" => Ok(json!({
"success": true,
"tokensRemoved": 250_000,
"messagesRemoved": 12,
"contextWindow": {
"currentTokens": 155_200,
"tokenLimit": 1_000_000,
"systemTokens": 20_000,
"toolDefinitionsTokens": 100_000,
"conversationTokens": 35_200
}
})),
"session.send" if self.background_shell => {
if let Some(peer) = self.peer.get().cloned() {
let sid = params["sessionId"].as_str().unwrap_or("cop-sess-1").to_owned();
@@ -795,3 +832,275 @@ async fn session_new_and_load_forward_staged_skill_directories_and_disabled_skil
assert!(params.get("enableConfigDiscovery").is_none(), "{method} must not auto-enable workspace MCP discovery");
}
}
#[test]
fn translates_context_attribution_without_double_counting_parent_rollups() {
let payload = json!({
"contextAttribution": {
"totalTokens": 405_200,
"limit": 1_000_000,
"bufferTokens": 64_000,
"compactionThreshold": 800_000,
"modelId": "gemini-4-carbon",
"entries": [
{ "kind": "system", "id": "system:root", "label": "System", "tokens": 223_000 },
{ "kind": "system", "id": "system:prompt", "label": "System Prompt", "tokens": 20_000, "parentId": "system:root" },
{ "kind": "toolDefinition", "id": "toolDefinition:bash", "label": "bash", "tokens": 120_000, "parentId": "system:root" },
{ "kind": "toolDefinition", "id": "toolDefinition:view", "label": "view", "tokens": 83_000, "parentId": "system:root" },
{ "kind": "tool", "id": "tool:bash", "label": "bash", "tokens": 69_000 },
{ "kind": "plugin", "id": "plugin:git", "label": "git", "tokens": 5_000 },
{ "kind": "skill", "id": "skill:pr", "label": "pr", "tokens": 5_000, "parentId": "plugin:git" }
]
}
});
let usage = context_usage_from_attribution(&payload, "fallback", None).unwrap();
assert_eq!(usage.total_tokens, 405_200);
assert_eq!(usage.max_tokens, 1_000_000);
assert_eq!(usage.reserved_tokens, Some(64_000));
assert_eq!(usage.auto_compact_threshold, Some(800_000));
assert_eq!(usage.is_auto_compact_enabled, Some(true));
assert_eq!(
usage.categories,
vec![
AgentContextCategory {
name: "System prompt".into(),
tokens: 20_000,
kind: Some("used".into()),
group: Some("System".into()),
},
AgentContextCategory {
name: "Tool Definitions".into(),
tokens: 203_000,
kind: Some("used".into()),
group: Some("System".into()),
},
AgentContextCategory {
name: "Tool Results".into(),
tokens: 69_000,
kind: Some("used".into()),
group: Some("User Context".into()),
},
AgentContextCategory {
name: "Messages".into(),
tokens: 108_200,
kind: Some("used".into()),
group: Some("User Context".into()),
},
AgentContextCategory {
name: "Skills".into(),
tokens: 5_000,
kind: Some("used".into()),
group: Some("User Context".into()),
},
AgentContextCategory { name: "Free space".into(), tokens: 530_800, kind: Some("free".into()), group: None },
]
);
}
#[test]
fn translates_context_info_and_usage_snapshot_fallbacks() {
let info = json!({
"contextInfo": {
"modelName": "claude-sonnet-4.5",
"systemTokens": 12_000,
"toolDefinitionsTokens": 48_000,
"conversationTokens": 40_000,
"totalTokens": 100_000,
"limit": 200_000,
"bufferTokens": 20_000,
"compactionThreshold": 160_000
}
});
let from_info = context_usage_from_context_info(&info, "fallback", None).unwrap();
assert_eq!(from_info.reserved_tokens, Some(20_000));
assert_eq!(
from_info.categories.iter().map(|c| (c.name.as_str(), c.tokens, c.group.as_deref())).collect::<Vec<_>>(),
vec![
("System prompt", 12_000, Some("System")),
("Tool Definitions", 48_000, Some("System")),
("Messages", 40_000, Some("User Context")),
("Free space", 80_000, None),
]
);
let from_snap = context_usage_from_snapshot(
&UsageSnapshot {
current_tokens: 50_000,
token_limit: 200_000,
system_tokens: Some(10_000),
tool_definitions_tokens: Some(25_000),
conversation_tokens: Some(15_000),
},
"gpt-5.6-sol",
);
assert_eq!(from_snap.total_tokens, 50_000);
assert_eq!(from_snap.max_tokens, 200_000);
assert_eq!(from_snap.categories.len(), 4);
}
#[test]
fn accumulates_copilot_credits_across_turns_subagents_and_compaction() {
let mut tr = EventTranslator::default();
let first = tr.translate(
"s1",
&json!({
"type": "session.usage_info",
"data": { "currentTokens": 40_000, "tokenLimit": 200_000, "systemTokens": 10_000, "toolDefinitionsTokens": 20_000, "conversationTokens": 10_000 }
}),
Some(200_000),
);
assert_eq!(first.updates[0].1["used"], 40_000);
assert!(first.updates[0].1.get("cost").is_none());
// Main-agent usage reports 1.5 credits; subagent usage adds 0.5 credits -> 2.0 credits total.
let main_usage = tr.translate(
"s1",
&json!({
"type": "assistant.usage",
"data": { "inputTokens": 45_000, "copilotUsage": { "totalNanoAiu": 1_500_000_000.0 } }
}),
Some(200_000),
);
assert_eq!(main_usage.updates[0].1["cost"]["currency"], "credits");
assert!((main_usage.updates[0].1["cost"]["amount"].as_f64().unwrap() - 1.5).abs() < 1e-6);
let sub_usage = tr.translate(
"s1",
&json!({
"type": "assistant.usage",
"agentId": "sub-1",
"data": { "inputTokens": 12_000, "copilotUsage": { "totalNanoAiu": 500_000_000.0 } }
}),
Some(200_000),
);
assert_eq!(sub_usage.updates[0].1["used"], 45_000);
assert!((sub_usage.updates[0].1["cost"]["amount"].as_f64().unwrap() - 2.0).abs() < 1e-6);
// Compaction updates token count while keeping accumulated credits.
let compacted = tr.translate(
"s1",
&json!({
"type": "session.compaction_complete",
"data": { "success": true, "postCompactionTokens": 22_000, "tokenLimit": 200_000 }
}),
Some(200_000),
);
assert_eq!(compacted.updates[0].1["used"], 22_000);
assert!((compacted.updates[0].1["cost"]["amount"].as_f64().unwrap() - 2.0).abs() < 1e-6);
}
#[test]
fn available_commands_includes_compact_when_omitted_by_server() {
let cmds = translate::available_commands(Some(&json!({ "commands": [{ "name": "review" }] })), None);
assert!(cmds.iter().any(|c| c["name"] == "compact"));
assert!(cmds.iter().any(|c| c["name"] == "review"));
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn context_usage_rpc_and_compact_command_work_end_to_end() {
let server =
Arc::new(FakeCopilotServer { peer: OnceLock::new(), calls: Mutex::new(Vec::new()), background_shell: false });
let updates = Arc::new(CollectUpdates(Mutex::new(Vec::new())));
let server_clone = server.clone();
let client = attach(updates.clone(), move |events| {
let (a, b) = tokio::io::duplex(1 << 16);
let (ar, aw) = tokio::io::split(a);
let (br, bw) = tokio::io::split(b);
let srv_peer = Peer::connect_framed(br, bw, server_clone.clone(), Framing::ContentLength);
let _ = server_clone.peer.set(srv_peer);
Ok(Peer::connect_framed(ar, aw, events, Framing::ContentLength))
})
.unwrap();
let init: Value = client.request("initialize", json!({}), None).await.unwrap();
assert_eq!(init["agentCapabilities"]["_meta"]["openidea"]["contextUsage"], true);
let _: Value = client.request("session/new", json!({ "cwd": "/tmp", "mcpServers": [] }), None).await.unwrap();
let ctx: AgentContextUsage =
client.request("_openidea/context_usage", json!({ "sessionId": "cop-sess-1" }), None).await.unwrap();
assert_eq!(ctx.total_tokens, 405_200);
assert_eq!(ctx.max_tokens, 1_000_000);
assert_eq!(ctx.reserved_tokens, Some(64_000));
assert!(ctx.categories.iter().any(|c| c.name == "System prompt" && c.group.as_deref() == Some("System")));
assert!(ctx.categories.iter().any(|c| c.name == "Tool Definitions" && c.group.as_deref() == Some("System")));
assert!(ctx.categories.iter().any(|c| c.name == "Tool Results" && c.group.as_deref() == Some("User Context")));
assert!(ctx.categories.iter().any(|c| c.name == "Messages" && c.group.as_deref() == Some("User Context")));
// Syncing metrics updated usage_update with credits cost.
tokio::time::sleep(Duration::from_millis(20)).await;
assert!(updates.0.lock().iter().any(|u| {
u["sessionUpdate"] == "usage_update"
&& u["used"] == 405_200
&& u["cost"]["currency"] == "credits"
&& (u["cost"]["amount"].as_f64().unwrap_or(0.0) - 4211.4).abs() < 0.01
}));
// `/compact` invokes `session.history.compact` instead of `session.send`.
let res: Value = client
.request(
"session/prompt",
json!({ "sessionId": "cop-sess-1", "prompt": [{ "type": "text", "text": "/compact keep PR notes" }] }),
None,
)
.await
.unwrap();
assert_eq!(res["stopReason"], "end_turn");
assert!(server.calls.lock().iter().any(|(m, p)| {
m == "session.history.compact"
&& p["sessionId"] == "cop-sess-1"
&& p["trigger"] == "manual"
&& p["customInstructions"] == "keep PR notes"
}));
tokio::time::sleep(Duration::from_millis(20)).await;
assert!(updates.0.lock().iter().any(|u| u["sessionUpdate"] == "usage_update" && u["used"] == 155_200));
}
#[test]
fn available_commands_preserves_input_choices() {
let cmds = json!({
"commands": [
{
"name": "skills",
"description": "Manage skills for enhanced capabilities",
"input": {
"hint": "[list|info|reload]",
"choices": [
{ "name": "list", "description": "List all available skills" },
{ "name": "info", "description": "Show details for a skill" },
{ "name": "INFO", "description": "Duplicate ignored" },
{ "name": "", "description": "Empty ignored" },
{ "name": "reload", "description": "Reload skills from disk" }
]
}
},
{
"name": "subconscious",
"description": "Manage memory",
"input": {
"choices": [{ "name": "run", "description": "Consolidate now" }]
}
}
]
});
let list = super::translate::available_commands(Some(&cmds), None);
let parsed = crate::config::commands_of(&json!({ "availableCommands": list }), "copilot");
// Then the built-in /compact.
assert_eq!(parsed.len(), 3);
assert_eq!(parsed[2].name, "compact");
assert_eq!(parsed[0].name, "skills");
assert_eq!(parsed[0].hint.as_deref(), Some("[list|info|reload]"));
assert_eq!(
parsed[0].choices,
vec![
crate::AgentCommandChoice { name: "list".into(), description: "List all available skills".into() },
crate::AgentCommandChoice { name: "info".into(), description: "Show details for a skill".into() },
crate::AgentCommandChoice { name: "reload".into(), description: "Reload skills from disk".into() },
]
);
assert_eq!(parsed[1].name, "subconscious");
assert_eq!(parsed[1].hint, None);
assert_eq!(
parsed[1].choices,
vec![crate::AgentCommandChoice { name: "run".into(), description: "Consolidate now".into() }]
);
}
+364 -20
Переглянути файл
@@ -2,11 +2,22 @@
//! permissions, slash commands, MCP servers) and ACP v1.
use crate::LIMITS_UPDATE;
use crate::model::{AgentContextCategory, AgentContextUsage};
use serde_json::{Map, Value, json};
use std::collections::{HashMap, HashSet};
use std::collections::{BTreeMap, HashMap, HashSet};
use std::path::Path;
const MAX_OUTPUT: usize = 64 * 1024;
const NANO_AIU_PER_CREDIT: f64 = 1_000_000_000.0;
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) struct UsageSnapshot {
pub current_tokens: u32,
pub token_limit: u32,
pub system_tokens: Option<u32>,
pub tool_definitions_tokens: Option<u32>,
pub conversation_tokens: Option<u32>,
}
#[derive(Default)]
pub(super) struct EventTranslator {
@@ -18,6 +29,11 @@ pub(super) struct EventTranslator {
subagents: HashMap<String, String>,
/// Last reported prompt token count, used when updating context size.
pub last_used_tokens: Option<u32>,
/// Last reported `session.usage_info` / compaction breakdown, used as fallback when RPC metadata is absent.
pub last_usage_snapshot: Option<UsageSnapshot>,
/// Accumulated session AI-credit spend in nano-AIU (across main agent and subagents).
total_nano_aiu: f64,
has_nano_aiu: bool,
}
#[derive(Clone, Debug)]
@@ -46,6 +62,29 @@ impl EventTranslator {
self.streamed_messages.clear();
}
pub fn set_total_nano_aiu(&mut self, nano_aiu: f64) {
if nano_aiu.is_finite() && nano_aiu > 0.0 {
self.total_nano_aiu = nano_aiu;
self.has_nano_aiu = true;
}
}
pub fn record_snapshot(&mut self, snapshot: UsageSnapshot) {
self.last_used_tokens = Some(snapshot.current_tokens);
self.last_usage_snapshot = Some(snapshot);
}
pub fn usage_update(&self, used: u32, size: u32) -> Value {
let mut update = json!({ "sessionUpdate": "usage_update", "used": used, "size": size });
if self.has_nano_aiu && self.total_nano_aiu > 0.0 {
update["cost"] = json!({
"amount": self.total_nano_aiu / NANO_AIU_PER_CREDIT,
"currency": "credits",
});
}
update
}
pub fn translate(&mut self, main_session: &str, event: &Value, fallback_limit: Option<u32>) -> Translated {
let mut out = Translated { updates: Vec::new(), terminal: None };
let event_type = str_of(event, "type").unwrap_or_default();
@@ -239,36 +278,75 @@ impl EventTranslator {
}
}
"session.usage_info" => {
let used = data.get("currentTokens").and_then(Value::as_u64).and_then(|n| u32::try_from(n).ok());
let limit = data
.get("tokenLimit")
.and_then(Value::as_u64)
.and_then(|n| u32::try_from(n).ok())
.filter(|&n| n > 0)
.or(fallback_limit);
let used = u32_of(data, "currentTokens");
let limit = u32_of(data, "tokenLimit").filter(|&n| n > 0).or(fallback_limit);
if let (Some(used), Some(size)) = (used, limit) {
self.last_used_tokens = Some(used);
out.updates.push((
main_session.to_owned(),
json!({ "sessionUpdate": "usage_update", "used": used, "size": size }),
));
self.record_snapshot(UsageSnapshot {
current_tokens: used,
token_limit: size,
system_tokens: u32_of(data, "systemTokens"),
tool_definitions_tokens: u32_of(data, "toolDefinitionsTokens"),
conversation_tokens: u32_of(data, "conversationTokens"),
});
out.updates.push((main_session.to_owned(), self.usage_update(used, size)));
}
}
"assistant.usage" => {
let added_credits = data
.pointer("/copilotUsage/totalNanoAiu")
.and_then(Value::as_f64)
.filter(|n| n.is_finite() && *n > 0.0);
if let Some(nano_aiu) = added_credits {
self.total_nano_aiu += nano_aiu;
self.has_nano_aiu = true;
}
if agent_id.is_none() {
let used = data.get("inputTokens").and_then(Value::as_u64).and_then(|n| u32::try_from(n).ok());
if let (Some(used), Some(size)) = (used, fallback_limit.filter(|&s| s > 0)) {
let used = u32_of(data, "inputTokens").or(self.last_used_tokens);
let size = self
.last_usage_snapshot
.as_ref()
.map(|s| s.token_limit)
.filter(|&s| s > 0)
.or(fallback_limit.filter(|&s| s > 0));
if let (Some(used), Some(size)) = (used, size) {
self.last_used_tokens = Some(used);
out.updates.push((
main_session.to_owned(),
json!({ "sessionUpdate": "usage_update", "used": used, "size": size }),
));
out.updates.push((main_session.to_owned(), self.usage_update(used, size)));
}
} else if added_credits.is_some()
&& let (Some(used), Some(size)) = (
self.last_used_tokens,
self.last_usage_snapshot
.as_ref()
.map(|s| s.token_limit)
.filter(|&s| s > 0)
.or(fallback_limit.filter(|&s| s > 0)),
)
{
out.updates.push((main_session.to_owned(), self.usage_update(used, size)));
}
if let Some(limits) = quota_limits(data.get("quotaSnapshots")) {
out.updates.push((main_session.to_owned(), limits));
}
}
"session.compaction_complete" if agent_id.is_none() => {
if data.get("success").and_then(Value::as_bool) == Some(true) {
let used = u32_of(data, "postCompactionTokens");
let size = u32_of(data, "tokenLimit")
.filter(|&n| n > 0)
.or_else(|| self.last_usage_snapshot.as_ref().map(|s| s.token_limit).filter(|&n| n > 0))
.or(fallback_limit.filter(|&n| n > 0));
if let (Some(used), Some(size)) = (used, size) {
self.record_snapshot(UsageSnapshot {
current_tokens: used,
token_limit: size,
system_tokens: u32_of(data, "systemTokens"),
tool_definitions_tokens: u32_of(data, "toolDefinitionsTokens"),
conversation_tokens: u32_of(data, "conversationTokens"),
});
out.updates.push((main_session.to_owned(), self.usage_update(used, size)));
}
}
}
"session.idle" if agent_id.is_none() => {
let mode = str_of(data, "mode").unwrap_or_default();
if mode != "autopilot" {
@@ -542,11 +620,34 @@ pub(super) fn available_commands(commands_res: Option<&Value>, skills_res: Optio
continue;
}
let hint = cmd.pointer("/input/hint").and_then(Value::as_str).filter(|h| !h.is_empty());
let mut seen_choices = HashSet::new();
let choices: Vec<Value> = cmd
.pointer("/input/choices")
.and_then(Value::as_array)
.into_iter()
.flatten()
.filter_map(|ch| {
let choice_name = str_of(ch, "name").map(str::trim).filter(|n| !n.is_empty())?;
if !seen_choices.insert(choice_name.to_ascii_lowercase()) {
return None;
}
Some(json!({
"name": choice_name,
"description": str_of(ch, "description").unwrap_or_default(),
}))
})
.collect();
let input = match (hint, choices.is_empty()) {
(Some(h), false) => Some(json!({ "hint": h, "choices": choices })),
(Some(h), true) => Some(json!({ "hint": h })),
(None, false) => Some(json!({ "choices": choices })),
(None, true) => None,
};
out.push(json!({
"name": name,
"description": str_of(cmd, "description").unwrap_or_default(),
"source": "command",
"input": hint.map(|h| json!({ "hint": h })),
"input": input,
}));
}
for skill in skills_res.and_then(|v| v.get("skills")).and_then(Value::as_array).into_iter().flatten() {
@@ -573,9 +674,252 @@ pub(super) fn available_commands(commands_res: Option<&Value>, skills_res: Optio
"input": hint.map(|h| json!({ "hint": h })),
}));
}
if seen.insert("compact".to_owned()) {
out.push(json!({
"name": "compact",
"description": "Compact conversation history to free context window space",
"source": "command",
"input": { "hint": "optional focus instructions" },
}));
}
out
}
/// Converts Copilot's `session.metadata.getContextAttribution` payload into [`AgentContextUsage`],
/// grouping items into `System` (`System prompt`, `Tool Definitions`, …) and `User Context`
/// (`Tool Results`, `Messages`, `Skills`, …) without double-counting parent rollup entries.
pub(super) fn context_usage_from_attribution(
res: &Value,
fallback_model: &str,
fallback_limit: Option<u32>,
) -> Option<AgentContextUsage> {
let attr = res.get("contextAttribution").unwrap_or(res);
if !attr.is_object() {
return None;
}
let total_tokens = u32_of(attr, "totalTokens")?;
let max_tokens = u32_of(attr, "limit")
.filter(|&n| n > 0)
.or_else(|| u32_of(attr, "promptTokenLimit").filter(|&n| n > 0))
.or_else(|| fallback_limit.filter(|&n| n > 0))?;
let reserved_tokens = u32_of(attr, "bufferTokens").filter(|&n| n > 0);
let model = str_of(attr, "modelId").filter(|s| !s.is_empty()).unwrap_or(fallback_model).to_owned();
let auto_compact_threshold = u32_of(attr, "compactionThreshold").filter(|&n| n > 0);
let is_auto_compact_enabled = auto_compact_threshold.map(|_| true);
let mut categories = Vec::new();
let entries = attr.get("entries").and_then(Value::as_array).filter(|e| !e.is_empty());
if let Some(entries) = entries {
// Any entry referenced via `parentId` is a rollup parent whose children are accounted for individually.
let parent_ids: HashSet<&str> = entries.iter().filter_map(|e| str_of(e, "parentId")).collect();
let mut system_rows: Vec<(String, u32)> = Vec::new();
let mut tool_definitions: u32 = 0;
let mut tool_results: u32 = 0;
let mut skills: u32 = 0;
let mut subagents: u32 = 0;
let mut mcp_tools: u32 = 0;
let mut plugins: u32 = 0;
let mut other_user: BTreeMap<String, u32> = BTreeMap::new();
let mut accounted: u32 = 0;
for entry in entries {
if let Some(id) = str_of(entry, "id")
&& parent_ids.contains(id)
{
continue;
}
let tokens = u32_of(entry, "tokens").unwrap_or(0);
if tokens == 0 {
continue;
}
accounted = accounted.saturating_add(tokens);
match str_of(entry, "kind").unwrap_or_default() {
"system" => {
let label = normalize_system_label(str_of(entry, "label").unwrap_or("System prompt"));
if let Some((_, existing)) = system_rows.iter_mut().find(|(k, _)| k == &label) {
*existing = existing.saturating_add(tokens);
} else {
system_rows.push((label, tokens));
}
}
"toolDefinition" => tool_definitions = tool_definitions.saturating_add(tokens),
"tool" => tool_results = tool_results.saturating_add(tokens),
"skill" => skills = skills.saturating_add(tokens),
"subagent" => subagents = subagents.saturating_add(tokens),
"mcpServer" => mcp_tools = mcp_tools.saturating_add(tokens),
"plugin" => plugins = plugins.saturating_add(tokens),
kind => {
let label = str_of(entry, "label").filter(|s| !s.is_empty()).unwrap_or(kind).to_owned();
let slot = other_user.entry(label).or_insert(0);
*slot = slot.saturating_add(tokens);
}
}
}
for (name, tokens) in system_rows {
categories.push(used_category(name, tokens, "System"));
}
if tool_definitions > 0 {
categories.push(used_category("Tool Definitions", tool_definitions, "System"));
}
if tool_results > 0 {
categories.push(used_category("Tool Results", tool_results, "User Context"));
}
let messages = total_tokens.saturating_sub(accounted);
if messages > 0 {
categories.push(used_category("Messages", messages, "User Context"));
}
if skills > 0 {
categories.push(used_category("Skills", skills, "User Context"));
}
if subagents > 0 {
categories.push(used_category("Sub-agents", subagents, "User Context"));
}
if mcp_tools > 0 {
categories.push(used_category("MCP tools", mcp_tools, "User Context"));
}
if plugins > 0 {
categories.push(used_category("Plugins", plugins, "User Context"));
}
for (name, tokens) in other_user {
categories.push(used_category(name, tokens, "User Context"));
}
} else if let Some(cats) = attr.get("categories").and_then(Value::as_object) {
let get = |k: &str| cats.get(k).and_then(Value::as_u64).and_then(|n| u32::try_from(n).ok()).unwrap_or(0);
let sys_prompt = get("systemPrompt");
let custom_inst = get("customInstructions");
let tool_defs = get("systemTools").saturating_add(get("mcpTools"));
let messages = get("messages");
if sys_prompt > 0 {
categories.push(used_category("System prompt", sys_prompt, "System"));
}
if custom_inst > 0 {
categories.push(used_category("Custom instructions", custom_inst, "System"));
}
if tool_defs > 0 {
categories.push(used_category("Tool Definitions", tool_defs, "System"));
}
if messages > 0 {
categories.push(used_category("Messages", messages, "User Context"));
}
}
push_free_space(&mut categories, total_tokens, max_tokens, reserved_tokens);
Some(AgentContextUsage {
categories,
total_tokens,
max_tokens,
model,
is_auto_compact_enabled,
auto_compact_threshold,
reserved_tokens,
})
}
/// Converts Copilot's `session.metadata.contextInfo` payload into [`AgentContextUsage`].
pub(super) fn context_usage_from_context_info(
res: &Value,
fallback_model: &str,
fallback_limit: Option<u32>,
) -> Option<AgentContextUsage> {
let info = res.get("contextInfo").unwrap_or(res);
if !info.is_object() {
return None;
}
let total_tokens = u32_of(info, "totalTokens")?;
let max_tokens = u32_of(info, "limit")
.filter(|&n| n > 0)
.or_else(|| u32_of(info, "promptTokenLimit").filter(|&n| n > 0))
.or_else(|| fallback_limit.filter(|&n| n > 0))?;
let reserved_tokens = u32_of(info, "bufferTokens").filter(|&n| n > 0);
let model = str_of(info, "displayModelName")
.or_else(|| str_of(info, "modelName"))
.filter(|s| !s.is_empty())
.unwrap_or(fallback_model)
.to_owned();
let auto_compact_threshold = u32_of(info, "compactionThreshold").filter(|&n| n > 0);
let is_auto_compact_enabled = auto_compact_threshold.map(|_| true);
let mut categories = Vec::new();
if let Some(sys) = u32_of(info, "systemTokens").filter(|&n| n > 0) {
categories.push(used_category("System prompt", sys, "System"));
}
if let Some(tools) = u32_of(info, "toolDefinitionsTokens").filter(|&n| n > 0) {
categories.push(used_category("Tool Definitions", tools, "System"));
}
if let Some(conv) = u32_of(info, "conversationTokens").filter(|&n| n > 0) {
categories.push(used_category("Messages", conv, "User Context"));
}
push_free_space(&mut categories, total_tokens, max_tokens, reserved_tokens);
Some(AgentContextUsage {
categories,
total_tokens,
max_tokens,
model,
is_auto_compact_enabled,
auto_compact_threshold,
reserved_tokens,
})
}
/// Fallback breakdown from the latest `session.usage_info` / compaction snapshot.
pub(super) fn context_usage_from_snapshot(snap: &UsageSnapshot, model: &str) -> AgentContextUsage {
let mut categories = Vec::new();
if let Some(sys) = snap.system_tokens.filter(|&n| n > 0) {
categories.push(used_category("System prompt", sys, "System"));
}
if let Some(tools) = snap.tool_definitions_tokens.filter(|&n| n > 0) {
categories.push(used_category("Tool Definitions", tools, "System"));
}
if let Some(conv) = snap.conversation_tokens.filter(|&n| n > 0) {
categories.push(used_category("Messages", conv, "User Context"));
}
push_free_space(&mut categories, snap.current_tokens, snap.token_limit, None);
AgentContextUsage {
categories,
total_tokens: snap.current_tokens,
max_tokens: snap.token_limit,
model: model.to_owned(),
is_auto_compact_enabled: None,
auto_compact_threshold: None,
reserved_tokens: None,
}
}
fn used_category(name: impl Into<String>, tokens: u32, group: &str) -> AgentContextCategory {
AgentContextCategory { name: name.into(), tokens, kind: Some("used".to_owned()), group: Some(group.to_owned()) }
}
fn push_free_space(
categories: &mut Vec<AgentContextCategory>,
total_tokens: u32,
max_tokens: u32,
reserved_tokens: Option<u32>,
) {
let free = max_tokens.saturating_sub(total_tokens.saturating_add(reserved_tokens.unwrap_or(0)));
if free > 0 {
categories.push(AgentContextCategory {
name: "Free space".to_owned(),
tokens: free,
kind: Some("free".to_owned()),
group: None,
});
}
}
fn normalize_system_label(raw: &str) -> String {
match raw.trim().to_ascii_lowercase().as_str() {
"system prompt" | "system" | "system instructions" => "System prompt".to_owned(),
"custom instructions" => "Custom instructions".to_owned(),
_ => raw.trim().to_owned(),
}
}
fn u32_of(v: &Value, key: &str) -> Option<u32> {
v.get(key).and_then(Value::as_u64).and_then(|n| u32::try_from(n).ok())
}
/// The running entries of a `session.tasks.list` result, in the background-task shape the
/// app shows (`task_id`, `task_type`, `description`).
pub(super) fn background_tasks(list: &Value) -> Vec<Value> {
+3
Переглянути файл
@@ -209,6 +209,7 @@ impl Frontmatter {
source,
description: truncate(&description),
hint: self.get("argument-hint").filter(|h| !h.is_empty()).map(str::to_owned),
choices: Vec::new(),
}
}
}
@@ -913,6 +914,7 @@ pub fn menu_commands(offered: Vec<AgentCommand>, states: &[AgentSkillState]) ->
description: state.skill.description.clone(),
hint: state.skill.hint.clone(),
source: AgentCommandSource::Skill,
choices: Vec::new(),
});
}
}
@@ -938,6 +940,7 @@ mod tests {
description: description.into(),
hint: None,
source: AgentCommandSource::Command,
choices: Vec::new(),
}
}
+236 -5
Переглянути файл
@@ -198,7 +198,11 @@ impl Handler for FakeAgent {
}
"session/new" => {
if self.hold_session_new.load(Ordering::Acquire) {
std::thread::sleep(Duration::from_secs(5));
let peer = self.latest();
let deadline = std::time::Instant::now() + Duration::from_secs(5);
while !peer.is_closed() && std::time::Instant::now() < deadline {
std::thread::sleep(Duration::from_millis(10));
}
}
if self.empty_config.load(Ordering::Acquire) {
return Ok(json!({"sessionId": "s1"}));
@@ -457,8 +461,9 @@ impl Handler for FakeAgent {
return Ok(json!({ "stopReason": "end_turn" }));
}
if text == "wait" {
// Works until cancelled.
while !self.calls.lock().iter().any(|c| c == "session/cancel") {
// Works until cancelled or the client closes the connection.
let peer = self.latest();
while !peer.is_closed() && !self.calls.lock().iter().any(|c| c == "session/cancel") {
std::thread::sleep(Duration::from_millis(5));
}
return Ok(json!({"stopReason": "cancelled"}));
@@ -695,6 +700,52 @@ async fn an_archived_task_keeps_no_command_list_and_completes_the_known_one() {
restored.shutdown();
}
#[tokio::test(flavor = "multi_thread")]
async fn archiving_a_task_keeps_the_permission_answer_that_is_settling() {
let tmp = tempfile::tempdir().unwrap();
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
let task = mgr
.create(NewAgentTask { prompt: text("hello"), provider: "claude".into(), ..Default::default() })
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::NeedsInput).await;
let handle = mgr.task(&task.id).unwrap();
let permission = *handle.permissions.lock().keys().next().unwrap();
let answered = |e: &AgentEntry| matches!(e, AgentEntry::Permission { chosen: Some(name), .. } if name == "Allow");
let status_at_answer = tokio::task::block_in_place(|| {
// Pause delivery of the changed entry so archive runs before the reply handler returns.
let _delivery = handle.dirty.lock();
mgr.respond(&task.id, permission, Some("yes".into())).unwrap();
let deadline = std::time::Instant::now() + Duration::from_secs(5);
let status = loop {
let s = handle.state.lock();
if s.history.conversation.main.entries.iter().any(answered) {
break s.task.status;
}
drop(s);
assert!(std::time::Instant::now() < deadline, "permission answer was never recorded");
std::thread::sleep(Duration::from_millis(1));
};
mgr.archive(&task.id).unwrap();
status
});
tokio::time::timeout(Duration::from_secs(5), async {
while handle.state.lock().busy {
tokio::time::sleep(Duration::from_millis(5)).await;
}
})
.await
.expect("the archived turn did not finish");
mgr.shutdown();
let restored = manager(tmp.path(), Arc::new(FakeAgent::default()));
assert_eq!(restored.task(&task.id).unwrap().state.lock().task.status, AgentStatus::Archived);
assert!(restored.entries(&task.id, None).unwrap().iter().any(answered));
assert_eq!(status_at_answer, AgentStatus::Running, "the recorded answer must finish the wait for input");
restored.shutdown();
}
#[tokio::test(flavor = "multi_thread")]
async fn a_conversation_that_cannot_be_read_is_never_saved_over() {
let tmp = tempfile::tempdir().unwrap();
@@ -1281,6 +1332,7 @@ async fn builtin_commands_only_fill_verified_gaps_and_preserve_advertised_metada
description: "Agent supplied description".into(),
hint: Some("instructions".into()),
source: AgentCommandSource::Command,
choices: Vec::new(),
};
mgr.task(&task.id).unwrap().state.lock().task.commands = vec![advertised.clone()];
// The task's provider wins over the caller's provider; metadata is not replaced.
@@ -1791,6 +1843,184 @@ async fn shutdown_skips_rewriting_untouched_restored_tasks() {
assert_eq!(saved_title(&dirty_path).as_deref(), Some("updated"));
}
/// Closing a project while a turn is in flight must not let the killed turn wake up and
/// mark the persisted task as `Failed` with "The agent process exited.".
#[tokio::test(flavor = "multi_thread")]
async fn shutdown_during_running_turn_does_not_mark_task_failed() {
let tmp = tempfile::tempdir().unwrap();
let agent = Arc::new(FakeAgent::default());
let mgr = manager(tmp.path(), agent.clone());
let task = mgr
.create(NewAgentTask {
prompt: text("wait"),
provider: "claude".into(),
isolation: Isolation::Local,
..Default::default()
})
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Running).await;
for _ in 0..500 {
if agent.calls.lock().iter().any(|c| c == "session/prompt") {
break;
}
tokio::time::sleep(Duration::from_millis(5)).await;
}
assert!(agent.calls.lock().iter().any(|c| c == "session/prompt"));
mgr.shutdown();
// Wait past TURN_GRACE so any unguarded Task::run continuation would have settled and failed.
tokio::time::sleep(TURN_GRACE * 3).await;
let path = task_file(tmp.path(), &task.id);
assert_eq!(saved_task(&path).map(|(status, _)| status), Some(serde_json::to_value(AgentStatus::Ready).unwrap()));
let restored = manager(tmp.path(), Arc::new(FakeAgent::default()));
let restored_task = restored.task(&task.id).unwrap();
assert_eq!(restored_task.state.lock().task.status, AgentStatus::Ready);
assert_eq!(restored_task.state.lock().task.error, None);
let entries = restored.entries(&task.id, None).unwrap();
assert!(
!entries.iter().any(|e| matches!(e, AgentEntry::Error { .. })),
"shutdown must not append an exit error entry: {entries:?}"
);
assert!(
entries.iter().any(|e| matches!(e, AgentEntry::User { text, done_ms: None, .. } if text == "wait")),
"interrupted turn must not stamp a bogus completion timestamp: {entries:?}"
);
restored.prompt(&task.id, text("again"), false).await.unwrap();
wait_for(&restored, &task.id, AgentStatus::Ready).await;
restored.shutdown();
}
/// Shutting down while `open_session` is still mid-handshake kills the connecting peer
/// immediately and leaves the task `Ready` rather than failing or leaking the process.
#[tokio::test(flavor = "multi_thread")]
async fn shutdown_during_session_open_kills_connecting_peer_without_failing() {
let tmp = tempfile::tempdir().unwrap();
let agent = Arc::new(FakeAgent::default());
agent.hold_session_new.store(true, Ordering::Release);
let mgr = manager(tmp.path(), agent.clone());
let task = mgr
.create(NewAgentTask {
prompt: text("again"),
provider: "claude".into(),
isolation: Isolation::Local,
..Default::default()
})
.await
.unwrap();
for _ in 0..500 {
if agent.calls.lock().iter().any(|c| c == "session/new") {
break;
}
tokio::time::sleep(Duration::from_millis(5)).await;
}
assert!(agent.calls.lock().iter().any(|c| c == "session/new"));
mgr.shutdown();
tokio::time::sleep(TURN_GRACE * 3).await;
assert!(agent.latest().is_closed(), "shutdown must kill the in-flight connecting peer");
let handle = mgr.task(&task.id).unwrap();
assert!(handle.live.lock().is_none(), "opening peer must not be published after shutdown");
assert_eq!(handle.state.lock().task.status, AgentStatus::Ready);
assert_eq!(handle.state.lock().task.error, None);
let restored = manager(tmp.path(), Arc::new(FakeAgent::default()));
let restored_task = restored.task(&task.id).unwrap();
assert_eq!(restored_task.state.lock().task.status, AgentStatus::Ready);
assert_eq!(restored_task.state.lock().task.error, None);
let entries = restored.entries(&task.id, None).unwrap();
assert!(
!entries.iter().any(|e| matches!(e, AgentEntry::Error { .. })),
"shutdown during session open must not record an error: {entries:?}"
);
restored.shutdown();
}
/// Shutting down while the agent is blocked on a permission prompt settles the pending
/// permission as Cancelled and leaves the task `Ready` without an exit error.
#[tokio::test(flavor = "multi_thread")]
async fn shutdown_during_permission_request_settles_without_failing() {
let tmp = tempfile::tempdir().unwrap();
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
let task = mgr
.create(NewAgentTask {
prompt: text("decide"),
provider: "claude".into(),
isolation: Isolation::Local,
..Default::default()
})
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::NeedsInput).await;
mgr.shutdown();
tokio::time::sleep(TURN_GRACE * 3).await;
let restored = manager(tmp.path(), Arc::new(FakeAgent::default()));
let restored_task = restored.task(&task.id).unwrap();
assert_eq!(restored_task.state.lock().task.status, AgentStatus::Ready);
assert_eq!(restored_task.state.lock().task.error, None);
let entries = restored.entries(&task.id, None).unwrap();
assert!(
!entries.iter().any(|e| matches!(e, AgentEntry::Error { .. })),
"shutdown during permission prompt must not append an exit error: {entries:?}"
);
assert!(
entries.iter().any(|e| matches!(e, AgentEntry::Permission { chosen: Some(c), .. } if c == "Cancelled")),
"unanswered permission should be settled as Cancelled: {entries:?}"
);
restored.shutdown();
}
/// Revoking and restoring project trust calls `shutdown()` on a manager that stays in use;
/// interrupting a running turn must leave the manager ready to accept later prompts.
#[tokio::test(flavor = "multi_thread")]
async fn manager_can_run_new_turns_after_shutdown_replaces_an_interrupted_turn() {
let tmp = tempfile::tempdir().unwrap();
let agent = Arc::new(FakeAgent::default());
let mgr = manager(tmp.path(), agent.clone());
let task = mgr
.create(NewAgentTask {
prompt: text("wait"),
provider: "claude".into(),
isolation: Isolation::Local,
..Default::default()
})
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Running).await;
for _ in 0..500 {
if agent.calls.lock().iter().any(|c| c == "session/prompt") {
break;
}
tokio::time::sleep(Duration::from_millis(5)).await;
}
mgr.shutdown();
tokio::time::sleep(TURN_GRACE * 3).await;
let handle = mgr.task(&task.id).unwrap();
assert_eq!(handle.state.lock().task.status, AgentStatus::Ready);
assert!(!handle.state.lock().busy);
mgr.prompt(&task.id, text("again"), false).await.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
let entries = mgr.entries(&task.id, None).unwrap();
assert!(
entries.iter().any(|e| matches!(e, AgentEntry::Agent { text } if text == "second turn")),
"follow-up turn on the same manager after shutdown should succeed: {entries:?}"
);
assert!(
!entries.iter().any(|e| matches!(e, AgentEntry::Error { .. })),
"no stale shutdown error should appear: {entries:?}"
);
mgr.shutdown();
}
/// Archiving saves the task as it is, including changes nobody asked to be saved.
#[tokio::test]
async fn archiving_saves_the_task_before_it_returns() {
@@ -2767,7 +2997,7 @@ async fn startup_warnings_survive_replay_and_restart_without_failing_the_task()
let handle = mgr.task(&task.id).unwrap();
handle.replaying.store(true, Ordering::Release);
handle.turn_started.store(false, Ordering::Release);
let client = Client::new(&handle, None);
let client = Client::new(&handle, handle.shared.shutdown_epoch(), None);
client.on_notification(WARNING_NOTIFICATION, json!({"message": "Project MCP config is disabled until trusted."}));
client.on_notification(WARNING_NOTIFICATION, json!({"message": " "}));
client.on_notification(WARNING_NOTIFICATION, json!({}));
@@ -2803,7 +3033,8 @@ async fn persistent_project_trust_needs_confirmation_even_with_bypass() {
let asking = {
let handle = handle.clone();
let params = params.clone();
tokio::task::spawn_blocking(move || handle.ask_permission(&params))
let epoch = handle.shared.shutdown_epoch();
tokio::task::spawn_blocking(move || handle.ask_permission(&params, epoch))
};
wait_for(&mgr, &task.id, AgentStatus::NeedsInput).await;
assert!(!asking.is_finished());
+12 -11
Переглянути файл
@@ -46,6 +46,16 @@ fn subdir(root: &Path, rel: &str) -> PathBuf {
root.join(rel).components().collect()
}
/// The `-pl` value selecting `projects` in their Maven reactor, by `groupId:artifactId`. Their
/// directories are the absolute `basedir`s Maven reported, which need not share a spelling with the
/// opened folder (drive letter case, separators, links), so a path selector could miss the reactor.
fn maven_project_selection<'a>(projects: impl Iterator<Item = &'a ProjectModel>) -> String {
let mut selection: Vec<String> = projects.map(|p| format!("{}:{}", p.group_id, p.artifact_id)).collect();
selection.sort();
selection.dedup();
selection.join(",")
}
/// The resident part of the build: javac servers and one lock per reactor.
#[derive(Default)]
pub struct JavaBuildService {
@@ -691,17 +701,8 @@ impl JavaBuild<'_> {
let out = model::output_root(self.cache, &top.key());
let step = match top {
Reactor::Maven(top) => {
let top_dir = subdir(self.root, &top.dir);
let mut selection: Vec<String> = changed
.iter()
.map(|(p, _, _)| {
let rel = p.dir.strip_prefix(&top_dir).unwrap_or(&p.dir).to_string_lossy().replace('\\', "/");
if rel.is_empty() { ".".to_owned() } else { rel }
})
.collect();
selection.sort();
selection.dedup();
let mut extra = vec!["-q".to_owned(), "-pl".to_owned(), selection.join(",")];
let selection = maven_project_selection(changed.iter().map(|(p, _, _)| *p));
let mut extra = vec!["-q".to_owned(), "-pl".to_owned(), selection];
extra.push("resources:resources".into());
if changed.iter().any(|(_, test, _)| *test) {
extra.push("resources:testResources".into());
+49 -2
Переглянути файл
@@ -11,6 +11,50 @@ fn write(root: &Path, rel: &str, text: &str) {
fs::write(path, text).unwrap();
}
fn build_output_tail(events: &[BuildEvent]) -> String {
let mut lines: Vec<_> = events
.iter()
.filter_map(|event| match event {
BuildEvent::Output { text, .. } => Some(text.as_str()),
_ => None,
})
.flat_map(str::lines)
.rev()
.take(150)
.collect();
lines.reverse();
lines.join("\n")
}
#[test]
fn build_output_tail_keeps_the_last_150_lines_across_streams() {
let lines = |range: std::ops::Range<usize>| range.map(|n| n.to_string()).collect::<Vec<_>>().join("\n");
let events = [
BuildEvent::Output { text: lines(0..100), stderr: false },
BuildEvent::Progress { message: "building".into(), fraction: None },
BuildEvent::Output { text: lines(100..155), stderr: true },
];
assert_eq!(build_output_tail(&events), lines(5..155));
}
#[test]
fn maven_resources_select_projects_by_coordinates_not_by_basedir() {
// Maven reports absolute basedirs whose spelling can differ from the opened folder on Windows
// (`D:/worktree/jxc/organ` against `d:\\worktree\\jxc`); coordinates always name a reactor project.
let project = |dir: &str, artifact: &str| ProjectModel {
dir: PathBuf::from(dir),
group_id: "org.starry".into(),
artifact_id: artifact.into(),
..Default::default()
};
let projects = [
project("D:/worktree/jxc/organ", "organ"),
project("D:/worktree/jxc", "cloud"),
project("D:/worktree/jxc/organ", "organ"),
];
assert_eq!(maven_project_selection(projects.iter()), "org.starry:cloud,org.starry:organ");
}
/// A JDK (`JAVA_HOME`) and Maven on the search path, else `None` (the test is skipped).
fn tools() -> Option<(PathBuf, PathBuf)> {
let home = std::env::var_os("JAVA_HOME").map(PathBuf::from).filter(|h| h.join("bin").is_dir())?;
@@ -139,7 +183,10 @@ impl Fixture {
let on_event = |e: BuildEvent| self.events.lock().unwrap().push(e);
match build.build(target, BuildKind::Build, &CancellationToken::new(), &on_event) {
Ok(Built::Done(outputs)) => outputs,
Ok(Built::Unsupported(reason)) => panic!("unsupported: {reason}"),
Ok(Built::Unsupported(reason)) => {
let output = build_output_tail(&self.events.lock().unwrap());
panic!("unsupported: {reason}\n{output}");
}
Err(e) => panic!("{e:?}"),
}
}
@@ -210,7 +257,7 @@ fn builds_maven_modules_with_javac_and_only_what_changed() {
f.write("app/src/main/resources/app.properties", "version=${project.version}\nmore=1\n");
let steps = f.steps_of_launch();
assert_eq!(steps.len(), 1, "{steps:?}");
assert!(steps[0].contains("resources:resources") && steps[0].contains("-pl app"), "{steps:?}");
assert!(steps[0].contains("resources:resources") && steps[0].contains("-pl t:app"), "{steps:?}");
assert_eq!(fs::read_to_string(f.out("t.app/classes/app.properties")).unwrap(), "version=1\nmore=1\n");
// A deleted source leaves no class behind.
+116
Переглянути файл
@@ -340,6 +340,18 @@ mod imp {
const OPEN_ATTEMPTS: usize = 10;
const OPEN_RETRY: Duration = Duration::from_millis(20);
/// WARNING: reading or writing the clipboard from two threads at once crashes the whole
/// process. `OpenClipboard(NULL)` does not keep the other threads of this process out, and
/// a second `GetClipboardData` can free the block the first thread is still reading, so
/// `GlobalSize` finds a corrupted heap and Windows ends the app with 0xc0000374 (#6388:
/// restoring a minimized window starts several reads). Every function below that opens the
/// clipboard holds this lock from before `OpenClipboard` until after `CloseClipboard`.
static CLIPBOARD: std::sync::Mutex<()> = std::sync::Mutex::new(());
fn lock() -> std::sync::MutexGuard<'static, ()> {
CLIPBOARD.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
}
#[link(name = "user32")]
unsafe extern "system" {
fn OpenClipboard(owner: Handle) -> i32;
@@ -389,6 +401,7 @@ mod imp {
}
pub fn png() -> Option<Vec<u8>> {
let _clipboard = lock();
if !open() {
return None;
}
@@ -405,6 +418,7 @@ mod imp {
}
pub fn text() -> Option<String> {
let _clipboard = lock();
// Empty rather than None: a None falls back to the WebView, which prompts the user.
if unsafe { IsClipboardFormatAvailable(CF_UNICODETEXT) } == 0 {
return Some(String::new());
@@ -447,6 +461,7 @@ mod imp {
}
pub fn files() -> std::io::Result<Vec<PathBuf>> {
let _clipboard = lock();
if !open() {
return Err(std::io::Error::last_os_error());
}
@@ -528,6 +543,7 @@ mod imp {
}
pub fn set_text(text: &str, owner: usize) -> std::io::Result<()> {
let _clipboard = lock();
let (memory, _) = global_text(text);
if memory.is_null() {
return Err(std::io::Error::last_os_error());
@@ -551,6 +567,7 @@ mod imp {
}
pub fn set_png(png: &[u8], owner: usize) -> std::io::Result<()> {
let _clipboard = lock();
let dib = super::image::png_to_dib(png)?;
let format = png_format();
if format == 0 {
@@ -593,6 +610,7 @@ mod imp {
}
pub fn set_files(paths: &[PathBuf]) -> bool {
let _clipboard = lock();
let bytes = encode(paths);
if bytes.len() <= HEADER {
return false;
@@ -923,6 +941,104 @@ mod tests {
assert_eq!(unicode_text(&bytes), "héllo\r\n世界");
}
#[cfg(windows)]
const READ_TEXT: &str = "clipboard read test";
/// Reads the clipboard's text for 5 s from `threads` threads, one at a time when
/// `serialized`, in a child process: heap corruption ends a process, and the test
/// keeps the result. Replaces the clipboard with text and writes the earlier text
/// back afterwards; skipped where no clipboard can be written.
#[cfg(windows)]
fn reads_survive(test: &str, threads: usize, serialized: bool) {
use std::process::Command;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
const STAGE: &str = "IDE_CLIPBOARD_READ_STAGE";
if std::env::var_os(STAGE).is_some() {
#[link(name = "kernel32")]
unsafe extern "system" {
fn WerSetFlags(flags: u32) -> i32;
}
// WER_FAULT_REPORTING_NO_UI: a crash ends the child instead of waiting on a dialog.
unsafe { WerSetFlags(0x20) };
let stop = Instant::now() + Duration::from_secs(5);
let turn = Arc::new(Mutex::new(()));
let readers: Vec<_> = (0..threads)
.map(|_| {
let turn = turn.clone();
std::thread::spawn(move || {
let mut reads = 0usize;
while Instant::now() < stop {
let _turn = serialized.then(|| turn.lock().unwrap());
// None: another reader kept the clipboard open through every retry.
let read = text();
assert!(matches!(read.as_deref(), None | Some(READ_TEXT)), "read {read:?}");
reads += 1;
}
reads
})
})
.collect();
let reads: usize = readers.into_iter().map(|reader| reader.join().unwrap()).sum();
println!("reads: {reads}");
return;
}
// The tests share the one clipboard: one at a time, so none rewrites it under another.
static SERIAL: Mutex<()> = Mutex::new(());
let _serial = SERIAL.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let earlier = text();
if let Err(error) = set_text(READ_TEXT, 0) {
eprintln!("skipped: the clipboard cannot be written here ({error})");
return;
}
let mut child = Command::new(std::env::current_exe().unwrap())
.args(["--exact", test, "--test-threads=1", "--nocapture"])
.env(STAGE, "1")
.spawn()
.unwrap();
let deadline = Instant::now() + Duration::from_secs(60);
let status = loop {
if let Some(status) = child.try_wait().unwrap() {
break Some(status);
}
if Instant::now() > deadline {
let _ = child.kill();
break None;
}
std::thread::sleep(Duration::from_millis(100));
};
if let Some(earlier) = earlier.filter(|earlier| !earlier.is_empty()) {
let _ = set_text(&earlier, 0);
}
let status = status.expect("the reads did not finish within 60 s");
assert!(
status.success(),
"clipboard reads ended the process: exit code {:#x}",
status.code().unwrap_or_default() as u32
);
}
#[cfg(windows)]
#[test]
fn text_reads_on_one_thread_do_not_corrupt_the_heap() {
reads_survive("tests::text_reads_on_one_thread_do_not_corrupt_the_heap", 1, false);
}
#[cfg(windows)]
#[test]
fn text_reads_taking_turns_do_not_corrupt_the_heap() {
reads_survive("tests::text_reads_taking_turns_do_not_corrupt_the_heap", 8, true);
}
/// The project view reads the clipboard's text whenever a window gains focus, on
/// whichever worker thread the command lands, so restoring a minimized window can
/// start several reads at once (#6388).
#[cfg(windows)]
#[test]
fn concurrent_text_reads_do_not_corrupt_the_heap() {
reads_survive("tests::concurrent_text_reads_do_not_corrupt_the_heap", 8, false);
}
fn paths(list: &[&str]) -> Vec<PathBuf> {
list.iter().map(PathBuf::from).collect()
}
+6
Переглянути файл
@@ -33,6 +33,10 @@ pub struct EditorGeneralSettings {
pub remove_trailing_blank_lines: bool,
/// Copy as rich text (HTML with syntax colours) by default.
pub rich_text_copy: bool,
/// Gutter › Highlight modified lines in the gutter: the VCS change bars next to the line numbers.
pub highlight_modified_lines: bool,
/// Gutter › Highlight modified lines in error stripe on the scrollbar (with `highlight_modified_lines`).
pub highlight_modified_lines_in_scrollbar: bool,
}
impl Default for EditorGeneralSettings {
@@ -51,6 +55,8 @@ impl Default for EditorGeneralSettings {
keep_trailing_on_caret_line: true,
remove_trailing_blank_lines: false,
rich_text_copy: true,
highlight_modified_lines: true,
highlight_modified_lines_in_scrollbar: true,
}
}
}
+16
Переглянути файл
@@ -862,6 +862,8 @@ pub struct AppearanceSettings {
pub smooth_scrolling: bool,
pub full_path_in_title: bool,
pub project_colors_in_toolbar: bool,
/// Strength of the project colour tint in the window header, in percent (10–70).
pub project_color_strength: u8,
pub dnd_with_alt_only: bool,
pub menu_icons: bool,
/// `hamburger` | `merged` | `toolbar` (a separate row): main menu presentation in the frameless title bar.
@@ -1001,6 +1003,7 @@ impl Default for AppearanceSettings {
smooth_scrolling: true,
full_path_in_title: false,
project_colors_in_toolbar: true,
project_color_strength: 22,
dnd_with_alt_only: false,
menu_icons: true,
main_menu_style: "hamburger".into(),
@@ -1395,6 +1398,8 @@ pub struct ExternalFormatterSettings {
/// Prefer this formatter even when a language server offers formatting.
pub prefer: bool,
pub run_on_save: bool,
/// Ruff only: apply safe lint fixes (`ruff check --fix-only`) on save, independently of formatting.
pub fix_on_save: bool,
}
impl Default for ExternalFormatterSettings {
@@ -1423,6 +1428,7 @@ impl Default for ExternalFormatterSettings {
.collect(),
prefer: false,
run_on_save: false,
fix_on_save: false,
}
}
}
@@ -1953,6 +1959,16 @@ impl Settings {
mod tests {
use super::*;
#[test]
fn ruff_safe_fixes_on_save_default_off_and_round_trip() {
let old: Settings = serde_json::from_str(r#"{"languages":{"ruff":{"runOnSave":true}}}"#).unwrap();
assert!(old.languages.ruff.run_on_save);
assert!(!old.languages.ruff.fix_on_save);
let on: Settings = serde_json::from_str(r#"{"languages":{"ruff":{"fixOnSave":true}}}"#).unwrap();
assert!(on.languages.ruff.fix_on_save);
assert_eq!(serde_json::to_value(&on).unwrap()["languages"]["ruff"]["fixOnSave"], true);
}
#[test]
fn python_interpreter_may_name_a_run_target() {
let python = |interpreter: &str| PythonSettings { interpreter: interpreter.into(), ..Default::default() };
+13
Переглянути файл
@@ -250,6 +250,8 @@ pub struct CommitSettings {
pub reformat: bool,
pub optimize_imports: bool,
pub cleanup: bool,
/// Apply Ruff's safe lint fixes before composing the commit, independently of formatting.
pub fix_on_commit: bool,
pub blank_line_after_subject: bool,
pub limit_subject: bool,
pub subject_limit: u32,
@@ -291,6 +293,7 @@ impl Default for CommitSettings {
reformat: false,
optimize_imports: false,
cleanup: false,
fix_on_commit: false,
blank_line_after_subject: true,
limit_subject: true,
subject_limit: 72,
@@ -728,6 +731,16 @@ impl Default for AgentSecuritySettings {
mod tests {
use super::*;
#[test]
fn ruff_safe_fixes_on_commit_default_off_and_round_trip() {
let old: CommitSettings = serde_json::from_str(r#"{"reformat":true}"#).unwrap();
assert!(old.reformat);
assert!(!old.fix_on_commit);
let on: CommitSettings = serde_json::from_str(r#"{"fixOnCommit":true}"#).unwrap();
assert!(on.fix_on_commit);
assert_eq!(serde_json::to_value(&on).unwrap()["fixOnCommit"], true);
}
#[test]
fn clone_submodules_defaults_on_and_can_be_disabled() {
let missing: GitSettings = serde_json::from_str("{}").unwrap();
+44 -12
Переглянути файл
@@ -51,12 +51,17 @@ pub async fn build(
cwd: &Path,
args: &[String],
filter: &CargoFilter,
cancel: &ide_core::CancellationToken,
on_output: impl Fn(String) + Send + Sync + 'static,
) -> IdeResult<PathBuf> {
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
let cargo = find_binary("cargo", cwd).ok_or_else(|| IdeError::unavailable("`cargo` not found on PATH"))?;
let mut cmd = tokio::process::Command::new(cargo);
cmd.current_dir(cwd);
ide_core::process::prepare(cmd.as_std_mut());
ide_core::process::own_group(cmd.as_std_mut());
cmd.args(args)
.arg("--message-format=json-render-diagnostics")
.stdin(Stdio::null())
@@ -65,11 +70,13 @@ pub async fn build(
.kill_on_drop(true);
on_output(format!("> cargo {}\n", args.join(" ")));
let mut child = cmd.spawn().map_err(|e| IdeError::unavailable(format!("failed to run cargo: {e}")))?;
#[cfg(windows)]
let job = child.id().and_then(ide_core::process::Job::for_pid);
let stderr = child.stderr.take().ok_or_else(|| IdeError::internal("cargo stderr unavailable"))?;
let stdout = child.stdout.take().ok_or_else(|| IdeError::internal("cargo stdout unavailable"))?;
let on_output = std::sync::Arc::new(on_output);
let err_out = on_output.clone();
let err_task = tokio::spawn(async move {
let mut err_task = tokio::spawn(async move {
let mut lines = BufReader::new(stderr).split(b'\n');
while let Ok(Some(line)) = lines.next_segment().await {
let line = ide_core::output_encoding::decode_tool_output(&line);
@@ -77,19 +84,44 @@ pub async fn build(
err_out(format!("{line}\n"));
}
});
let mut found = None;
let mut lines = BufReader::new(stdout).lines();
while let Ok(Some(line)) = lines.next_line().await {
if let Some(exe) = artifact_executable(&line, filter) {
found = Some(exe);
let outcome = tokio::select! {
biased;
_ = cancel.cancelled() => None,
result = async {
let mut found = None;
let mut lines = BufReader::new(stdout).lines();
while let Ok(Some(line)) = lines.next_line().await {
if let Some(exe) = artifact_executable(&line, filter) {
found = Some(exe);
}
}
let _ = (&mut err_task).await;
let status = child.wait().await?;
if !status.success() {
return Err(IdeError::invalid(format!("cargo {} failed ({status})", args.first().map_or("", |s| s))));
}
found.ok_or_else(|| IdeError::invalid("cargo produced no executable to debug"))
} => Some(result),
};
match outcome {
Some(result) => result,
None => {
err_task.abort();
if let Some(pid) = child.id() {
let _ = tokio::task::spawn_blocking(move || {
#[cfg(windows)]
if let Some(job) = job {
job.terminate();
return;
}
ide_core::process::kill_tree_of(pid);
})
.await;
}
let _ = child.kill().await;
Err(IdeError::cancelled())
}
}
let _ = err_task.await;
let status = child.wait().await?;
if !status.success() {
return Err(IdeError::invalid(format!("cargo {} failed ({status})", args.first().map_or("", |s| s))));
}
found.ok_or_else(|| IdeError::invalid("cargo produced no executable to debug"))
}
#[cfg(test)]
+64 -9
Переглянути файл
@@ -901,6 +901,23 @@ impl DebugManager {
custom_command: impl FnOnce(&str) -> Option<String>,
exception_classes: Option<Arc<dyn ide_jvm_inspect::ExceptionClassBreakpoints>>,
) -> IdeResult<DebugSessionId> {
self.start_with_cancel(config, owner, custom_command, exception_classes, ide_core::CancellationToken::new())
.await
}
/// [`start_with_exception_classes`](Self::start_with_exception_classes), cancelling a pending
/// pre-launch build, adapter launch or configuration when `cancel` is triggered.
pub async fn start_with_cancel(
&self,
config: LaunchConfig,
owner: SessionOwner,
custom_command: impl FnOnce(&str) -> Option<String>,
exception_classes: Option<Arc<dyn ide_jvm_inspect::ExceptionClassBreakpoints>>,
cancel: ide_core::CancellationToken,
) -> IdeResult<DebugSessionId> {
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
let mut arguments = launch_arguments(&config)?;
if debugpy::listens(&config.adapter, &config.request, &arguments) {
debugpy::require_free_port(&arguments).await?;
@@ -992,7 +1009,7 @@ impl DebugManager {
.unwrap_or_else(|| vec!["build".into()]);
let filter = cargo::CargoFilter::from_json(cargo.get("filter"));
let sink = owner.sink.clone();
let program = cargo::build(&cwd, &cargo_args, &filter, move |line| {
let program = cargo::build(&cwd, &cargo_args, &filter, &cancel, move |line| {
sink.emit(ide_core::IdeEvent::Debug {
session: id,
event: ide_core::event::DebugEvent::Output { category: "console".into(), output: line },
@@ -1008,7 +1025,11 @@ impl DebugManager {
other => other.as_u64().and_then(|p| u32::try_from(p).ok()),
});
if let Some(pid) = pid {
let port = attach::enable_node_inspector(pid).await?;
let port = tokio::select! {
biased;
_ = cancel.cancelled() => return Err(IdeError::cancelled()),
port = attach::enable_node_inspector(pid) => port?,
};
if let Some(obj) = arguments.as_object_mut() {
obj.remove("processId");
obj.insert("port".into(), port.into());
@@ -1056,6 +1077,7 @@ impl DebugManager {
spec,
port,
exception_classes,
cancel,
)
.await
}
@@ -1090,6 +1112,7 @@ impl DebugManager {
spec,
port,
None,
ide_core::CancellationToken::new(),
)
.await
.map(|_| ())
@@ -1108,11 +1131,19 @@ impl DebugManager {
spec: AdapterSpec,
reuse_port: Option<u16>,
exception_classes: Option<Arc<dyn ide_jvm_inspect::ExceptionClassBreakpoints>>,
cancel: ide_core::CancellationToken,
) -> IdeResult<DebugSessionId> {
if request != "launch" && request != "attach" {
return Err(IdeError::invalid(format!("request must be `launch` or `attach`, got `{request}`")));
}
let io = self.launcher.launch(spec.clone(), reuse_port).await?;
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
let io = tokio::select! {
biased;
_ = cancel.cancelled() => return Err(IdeError::cancelled()),
io = self.launcher.launch(spec.clone(), reuse_port) => io?,
};
let launch_after_configuration = io.launch_after_configuration && request == "launch";
let stderr = io.stderr.clone();
let (conn, incoming) = {
@@ -1133,6 +1164,21 @@ impl DebugManager {
if let Some(pid) = rdbg_pid {
session.debuggee_pid.store(i64::from(pid), Ordering::Release);
}
let cancelled = {
let mut sessions = self.sessions.lock();
if cancel.is_cancelled() {
true
} else {
sessions.insert(id, session.clone());
self.order.lock().push(id);
false
}
};
if cancelled {
session.conn.close();
session.kill_processes();
return Err(IdeError::cancelled());
}
if let Some(mut output) = io.program_output {
session.output_drained.send_replace(false);
let session = session.clone();
@@ -1143,8 +1189,6 @@ impl DebugManager {
session.output_drained.send_replace(true);
});
}
self.sessions.lock().insert(id, session.clone());
self.order.lock().push(id);
// Announced before the event loop runs, so it precedes every adapter event.
session.emit(ide_core::event::DebugEvent::Started {
name: session.name.clone(),
@@ -1156,14 +1200,25 @@ impl DebugManager {
if debugpy::listens(&session.adapter, &session.request, &arguments) {
session.debugpy_version_unchecked.store(true, Ordering::Release);
}
enum ConfigOutcome {
Done(IdeResult<()>),
Stopped,
Cancelled,
}
let configured = tokio::select! {
biased;
_ = session.startup_cancel.cancelled() => return Err(IdeError::cancelled()),
result = self.configure(&session, arguments, launch_after_configuration) => result,
_ = session.startup_cancel.cancelled() => ConfigOutcome::Stopped,
_ = cancel.cancelled() => ConfigOutcome::Cancelled,
result = self.configure(&session, arguments, launch_after_configuration) => ConfigOutcome::Done(result),
};
match configured {
Ok(()) => Ok(id),
Err(e) => {
ConfigOutcome::Done(Ok(())) => Ok(id),
ConfigOutcome::Stopped => Err(IdeError::cancelled()),
ConfigOutcome::Cancelled => {
let _ = self.stop(id).await;
Err(IdeError::cancelled())
}
ConfigOutcome::Done(Err(e)) => {
let e = if session.conn.is_closed() {
let mut msg = format!("debug adapter `{}` exited during startup", session.adapter);
let tail = stderr.lock().join("\n");
+409 -77
Переглянути файл
@@ -1,11 +1,13 @@
use crate::ConsoleId;
use crate::conn::{QueryResult, ResultColumn, Setup};
use crate::source::{DataSource, DbSslMode, DbTxMode};
use ide_core::{CancellationToken, IdeError, IdeResult, error::ErrorKind};
use parking_lot::RwLock;
use reqwest::{Client, RequestBuilder, StatusCode, Url};
use std::collections::HashMap;
use std::sync::Arc;
use std::time::{Duration, Instant};
use tokio::sync::Mutex;
use tokio::sync::{Mutex, MutexGuard};
#[derive(Clone)]
pub struct ClickhousePool(Arc<State>);
@@ -18,11 +20,17 @@ struct State {
database: String,
settings: Vec<(String, String)>,
read_only: bool,
session: Mutex<Session>,
connect_timeout: Duration,
startup_statements: Vec<String>,
use_http_session: bool,
session: SessionSlot,
console_sessions: parking_lot::Mutex<HashMap<(String, String), Arc<SessionSlot>>>,
closed: CancellationToken,
}
#[derive(Default)]
type SessionSlot = Mutex<Option<Session>>;
#[derive(Clone, Default)]
struct Session {
id: Option<String>,
initialized: bool,
@@ -32,6 +40,7 @@ struct Session {
/// The response format: a names line, a types line, then one JSON array per row, so rows past
/// the grid's limit are skipped without being parsed.
const FORMAT: &str = "JSONCompactEachRowWithNamesAndTypes";
const DEFAULT_READ_TIMEOUT: Duration = Duration::from_secs(600);
const SESSION_LOST: &str = "ClickHouse HTTP session expired or is missing on this node (code 372). Reconnect to start a new session. Behind a load balancer, use one node or session affinity, or set use_http_session=false in Advanced for independent queries.";
pub(crate) fn transaction_error() -> IdeError {
@@ -44,6 +53,7 @@ impl ClickhousePool {
return Err(transaction_error());
}
let mut use_http_session = None;
let mut read_timeout = None;
let mut settings = Vec::with_capacity(setup.params.len());
for (name, value) in setup.params {
if name.eq_ignore_ascii_case("use_http_session") {
@@ -57,6 +67,14 @@ impl ClickhousePool {
} else {
return Err(IdeError::invalid("ClickHouse use_http_session must be true or false"));
});
} else if name.eq_ignore_ascii_case("http_read_timeout") {
if read_timeout.is_some() {
return Err(IdeError::invalid("ClickHouse http_read_timeout must be specified only once"));
}
let seconds = value.parse::<std::num::NonZeroU32>().map_err(|_| {
IdeError::invalid("ClickHouse http_read_timeout must be a positive whole number of seconds")
})?;
read_timeout = Some(Duration::from_secs(u64::from(seconds.get())));
} else if reserved_setting(&name) {
return Err(IdeError::invalid(format!("ClickHouse HTTP manages the {name} setting")));
} else {
@@ -89,6 +107,7 @@ impl ClickhousePool {
let _ = rustls::crypto::ring::default_provider().install_default();
let mut builder = Client::builder()
.connect_timeout(timeout)
.read_timeout(read_timeout.unwrap_or(DEFAULT_READ_TIMEOUT))
.pool_max_idle_per_host(4)
.redirect(reqwest::redirect::Policy::none())
.user_agent(concat!("OpenIDEA/", env!("CARGO_PKG_VERSION")));
@@ -136,79 +155,126 @@ impl ClickhousePool {
database: database.into(),
settings,
read_only: source.read_only,
session: Mutex::new(Session {
id: use_http_session.then(|| uuid::Uuid::new_v4().to_string()),
..Session::default()
}),
connect_timeout: timeout,
startup_statements: setup.statements,
use_http_session,
session: Mutex::new(None),
console_sessions: parking_lot::Mutex::new(HashMap::new()),
closed: CancellationToken::new(),
}));
let cancel = CancellationToken::new();
let initialize = async {
if let Err(error) = pool.execute("SELECT 1", 1, &cancel).await {
let Some(setting) = rejected_driver_setting(&error) else {
return Err(error);
};
if !use_http_session {
if setting == "readonly" {
return Err(error);
}
if !source.read_only {
return Err(IdeError::new(
error.kind,
format!(
"{}; enable Read-only for independent queries on a strict read-only server",
error.message
),
));
}
// Every request still sends readonly=1, regardless of which node answers.
pool.0.session.lock().await.strict_read_only = true;
pool.execute("SELECT 1", 1, &cancel).await?;
} else {
// Only rely on the server's write protection after proving strict read-only
// in this same named session.
{
let mut session = pool.0.session.lock().await;
// The rejected probe may have opened a session on a different node.
session.id = Some(uuid::Uuid::new_v4().to_string());
session.strict_read_only = true;
}
let result = pool.execute("SELECT getSetting('readonly')", 1, &cancel).await?;
if result.rows.first().and_then(|row| row.first()).and_then(Option::as_deref) != Some("1") {
return Err(error);
}
}
}
// The HTTP database parameter applies to one request. A named session needs
// USE once so later queries inherit the selection (and may change it).
if use_http_session && !database.is_empty() {
let name = crate::sql::quote_ident(crate::DbDriver::Clickhouse, database);
pool.execute(&format!("USE {name}"), 0, &cancel).await?;
}
for sql in setup.statements {
pool.execute(&sql, 0, &cancel).await?;
}
Ok(pool.clone())
if let Err(error) = pool.session(&pool.0.session, &cancel).await {
pool.close();
return Err(error);
}
Ok(pool)
}
async fn session<'a>(
&self,
slot: &'a SessionSlot,
cancel: &CancellationToken,
) -> IdeResult<MutexGuard<'a, Option<Session>>> {
let mut slot = tokio::select! {
biased;
() = cancel.cancelled() => return Err(IdeError::cancelled()),
() = self.0.closed.cancelled() => return Err(IdeError::new(ErrorKind::Io, "ClickHouse connection is closed")),
session = slot.lock() => session,
};
tokio::pin!(initialize);
tokio::select! {
result = &mut initialize => {
if result.is_err() {
pool.close();
if slot.is_none() {
let mut session =
Session { id: self.0.use_http_session.then(|| uuid::Uuid::new_v4().to_string()), ..Session::default() };
{
let cancel = cancel.child_token();
let initialize = self.initialize(&mut session, &cancel);
tokio::pin!(initialize);
tokio::select! {
result = &mut initialize => result?,
() = tokio::time::sleep(self.0.connect_timeout) => {
cancel.cancel();
let _ = initialize.await;
return Err(IdeError::new(ErrorKind::TimedOut, "timed out connecting to ClickHouse HTTP"));
}
}
}
*slot = Some(session);
}
Ok(slot)
}
async fn initialize(&self, session: &mut Session, cancel: &CancellationToken) -> IdeResult<()> {
if let Err(error) = self.execute_request("SELECT 1", 0, 1, cancel, session).await {
let Some(setting) = rejected_driver_setting(&error) else {
return Err(error);
};
if session.id.is_none() {
if setting == "readonly" {
return Err(error);
}
if !self.0.read_only {
return Err(IdeError::new(
error.kind,
format!(
"{}; enable Read-only for independent queries on a strict read-only server",
error.message
),
));
}
// Every request still sends readonly=1, regardless of which node answers.
session.strict_read_only = true;
self.execute_request("SELECT 1", 0, 1, cancel, session).await?;
} else {
// Only rely on the server's write protection after proving strict read-only
// in this same named session. The rejected probe may have used a different node.
session.id = Some(uuid::Uuid::new_v4().to_string());
session.strict_read_only = true;
let result = self.execute_request("SELECT getSetting('readonly')", 0, 1, cancel, session).await?;
if result.rows.first().and_then(|row| row.first()).and_then(Option::as_deref) != Some("1") {
return Err(error);
}
result
},
() = tokio::time::sleep(timeout) => {
cancel.cancel();
let _ = initialize.await;
pool.close();
Err(IdeError::new(ErrorKind::TimedOut, "timed out connecting to ClickHouse HTTP"))
}
}
// A named session needs USE once so later queries inherit the database and may change it.
if session.id.is_some() && !self.0.database.is_empty() {
let name = crate::sql::quote_ident(crate::DbDriver::Clickhouse, &self.0.database);
self.execute_request(&format!("USE {name}"), 0, 0, cancel, session).await?;
}
for sql in &self.0.startup_statements {
if transaction_statement(sql) {
return Err(transaction_error());
}
self.execute_request(sql, 0, 0, cancel, session).await?;
}
Ok(())
}
pub async fn ping(&self) -> IdeResult<()> {
let cancel = CancellationToken::new();
if !self.0.use_http_session {
return self.execute("SELECT 1", 1, &cancel).await.map(|_| ());
}
let mut result = Ok(());
let consoles = self.0.console_sessions.lock().values().cloned().collect::<Vec<_>>();
let sessions = std::iter::once(&self.0.session).chain(consoles.iter().map(Arc::as_ref));
for slot in sessions {
// A running query already keeps its session active.
if let Ok(mut slot) = slot.try_lock()
&& let Some(session) = slot.as_mut()
&& let Err(error) = self.execute_request("SELECT 1", 0, 1, &cancel, session).await
{
result = result.and(Err(error));
}
}
result
}
pub fn release_console(&self, console: ConsoleId<'_>) {
self.0.console_sessions.lock().remove(&(console.window.into(), console.path.into()));
}
pub fn close(&self) {
self.0.closed.cancel();
self.0.console_sessions.lock().clear();
self.0.client.write().take();
}
@@ -261,22 +327,69 @@ impl ClickhousePool {
skip: usize,
max_rows: usize,
cancel: &CancellationToken,
) -> IdeResult<QueryResult> {
self.execute_in_console(sql, skip, max_rows, cancel, None).await
}
pub async fn execute_in_console(
&self,
sql: &str,
skip: usize,
max_rows: usize,
cancel: &CancellationToken,
console: Option<ConsoleId<'_>>,
) -> IdeResult<QueryResult> {
if transaction_statement(sql) {
return Err(transaction_error());
}
let mut session = tokio::select! {
biased;
() = cancel.cancelled() => return Err(IdeError::cancelled()),
() = self.0.closed.cancelled() => return Err(IdeError::new(ErrorKind::Io, "ClickHouse connection is closed")),
session = self.0.session.lock() => session,
};
let console_slot = console.filter(|_| self.0.use_http_session).map(|console| {
self.0.console_sessions.lock().entry((console.window.into(), console.path.into())).or_default().clone()
});
let slot = console_slot.as_deref().unwrap_or(&self.0.session);
let mut session = self.session(slot, cancel).await?;
let state = session.as_mut().expect("session was initialized");
if self.0.use_http_session {
self.execute_request(sql, skip, max_rows, cancel, state).await
} else {
// Stateless requests use the setup's read-only flags, and have no server session to lock.
let mut request = state.clone();
drop(session);
self.execute_request(sql, skip, max_rows, cancel, &mut request).await
}
}
async fn execute_request(
&self,
sql: &str,
skip: usize,
max_rows: usize,
cancel: &CancellationToken,
session: &mut Session,
) -> IdeResult<QueryResult> {
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
let client = self.client()?;
if session.id.is_none() && session_set_statement(sql) {
return Err(IdeError::invalid(
"Standalone SET needs a ClickHouse HTTP session. Set use_http_session=true in Advanced or use query-level SETTINGS where applicable.",
));
}
let query_id = uuid::Uuid::new_v4().to_string();
let request = self.request(&client, &query_id, skip.saturating_add(max_rows), &session).body(sql.to_owned());
let request = self.request(&client, &query_id, skip.saturating_add(max_rows), session).body(sql.to_owned());
let started = Instant::now();
let request_error = |error: reqwest::Error| {
if error.is_timeout() && !error.is_connect() {
IdeError::new(
ErrorKind::TimedOut,
format!("ClickHouse HTTP response timed out. The query outcome is unknown (query_id={query_id})."),
)
} else {
http_error(error)
}
};
let fetch = async {
let mut response = request.send().await.map_err(http_error)?;
let mut response = request.send().await.map_err(request_error)?;
let execution_ms = started.elapsed().as_secs_f64() * 1000.0;
let status = response.status();
let header = |name: &str| response.headers().get(name).and_then(|v| v.to_str().ok()).map(str::to_owned);
@@ -289,11 +402,11 @@ impl ClickhousePool {
.and_then(|n| n.as_str().and_then(|n| n.parse::<u64>().ok()).or_else(|| n.as_u64()))
});
if !status.is_success() || exception_code.as_deref().is_some_and(|code| code != "0") {
let body = response.bytes().await.map_err(http_error)?;
let body = response.bytes().await.map_err(request_error)?;
return Err(self.server_error(status, exception_code.as_deref(), &body));
}
let (columns, rows, has_more) = if format.as_deref().is_some_and(|f| f != FORMAT) {
let body = response.bytes().await.map_err(http_error)?;
let body = response.bytes().await.map_err(request_error)?;
if !body.iter().all(u8::is_ascii_whitespace) {
return Err(IdeError::invalid(
"ClickHouse result grids need the default output format; remove the query's FORMAT clause",
@@ -302,7 +415,7 @@ impl ClickhousePool {
(Vec::new(), Vec::new(), false)
} else {
let mut reader = RowReader::new(skip, max_rows);
while let Some(chunk) = response.chunk().await.map_err(http_error)? {
while let Some(chunk) = response.chunk().await.map_err(request_error)? {
reader.push(&chunk)?;
}
reader.finish().map_err(|error| self.redact_error(error))?
@@ -333,7 +446,7 @@ impl ClickhousePool {
result
}
None => {
let killed = self.kill(&client, &query_id, &session).await;
let killed = self.kill(&client, &query_id, session).await;
match killed {
Ok(()) => Err(IdeError::cancelled()),
Err(error) => Err(IdeError::new(
@@ -596,6 +709,13 @@ fn reserved_setting(name: &str) -> bool {
)
}
fn session_set_statement(mut sql: &str) -> bool {
let mut next_is =
|word: &str| crate::split::clickhouse_keyword(&mut sql).is_some_and(|part| part.eq_ignore_ascii_case(word));
// SET DEFAULT ROLE persists a user's default roles outside the current session.
next_is("SET") && !(next_is("DEFAULT") && next_is("ROLE"))
}
fn transaction_statement(sql: &str) -> bool {
let mut sql = sql.trim_start();
loop {
@@ -832,6 +952,71 @@ mod tests {
}
}
#[tokio::test]
async fn stateless_session_settings_are_refused_before_sending() {
let (port, requests) = server(vec![("200 OK", "", ONE), ("200 OK", "", ONE), ("200 OK", "", "")]).await;
let source = DataSource { properties: vec![property("use_http_session", "false")], ..source(port) };
let pool = Pool::connect(&source, None, None).await.unwrap();
let cancel = CancellationToken::new();
for statement in [
"SET log_comment='openidea-test'",
"-- leading\n/* outer /* nested */ tail */ SeT `log_comment`='a;b', max_threads=1",
"# leading\nSET ROLE NONE",
"SET profile='test'",
"SET TIME ZONE 'UTC'",
] {
let error = pool.execute(statement, 1, &cancel).await.expect_err("stateless SET must fail locally");
assert_eq!(error.kind, ErrorKind::InvalidInput);
assert!(error.message.contains("use_http_session=true"), "{error}");
assert!(error.message.contains("query-level SETTINGS"), "{error}");
}
let stopped = CancellationToken::new();
stopped.cancel();
assert_eq!(
pool.execute("SET log_comment='not sent'", 1, &stopped).await.unwrap_err().kind,
ErrorKind::Cancelled
);
// A query-level setting and a persistent role change both still reach the server.
let select = "SELECT 'SET;' LIMIT 1 SETTINGS log_comment='local' FORMAT JSONCompactEachRowWithNamesAndTypes";
pool.execute(select, 1, &cancel).await.unwrap();
let default_role = "SET /* persistent */ DEFAULT # on login\n ROLE NONE TO fixture_user";
pool.execute(default_role, 0, &cancel).await.unwrap();
let requests = requests.await.unwrap();
assert!(requests[0].ends_with("SELECT 1"));
assert!(requests[1].ends_with(select));
assert!(requests[2].ends_with(default_role));
assert!(requests.iter().all(|request| query_value(&request_url(request), "session_id").is_none()));
}
#[tokio::test]
#[ignore = "requires the disposable ClickHouse fixture on loopback"]
async fn clickhouse_live_http_session_settings() -> IdeResult<()> {
let port = std::env::var("OPENIDEA_CLICKHOUSE_SET_PORT").unwrap().parse().unwrap();
let cancel = CancellationToken::new();
let read = "SELECT concat('[', getSetting('log_comment'), ']') LIMIT 1";
for (session, expected) in [("false", "[]"), ("true", "[openidea-test]")] {
let source = DataSource {
user: "set_fixture".into(),
properties: vec![property("use_http_session", session)],
..source(port)
};
let pool = Pool::connect(&source, None, None).await?;
let result = pool.execute("SET log_comment='openidea-test'", 1, &cancel).await;
if session == "true" {
result?;
} else {
let error = result.unwrap_err();
assert_eq!(error.kind, ErrorKind::InvalidInput);
assert!(error.message.contains("use_http_session=true"), "{error}");
let local = format!("{read} SETTINGS log_comment='one-query'");
assert_eq!(pool.execute(&local, 1, &cancel).await?.rows, [vec![Some("[one-query]".into())]]);
}
assert_eq!(pool.execute(read, 1, &cancel).await?.rows, [vec![Some(expected.into())]]);
}
Ok(())
}
#[tokio::test]
async fn stateless_requests_keep_database_settings_readonly_and_limits() {
let (port, requests) = server(vec![("200 OK", "", ONE); 3]).await;
@@ -898,6 +1083,90 @@ mod tests {
}
}
#[tokio::test]
async fn stalled_http_response_reports_unknown_outcome_with_query_id() {
for prefix in [
"",
"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\n",
"HTTP/1.1 500 Internal Server Error\r\nContent-Length: 128\r\nConnection: close\r\n\r\nCode:",
] {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
let fixture = tokio::spawn(async move {
let (mut probe, _) = listener.accept().await.unwrap();
read_request(&mut probe).await;
reply(&mut probe, "200 OK", "", ONE).await;
drop(probe);
let (mut stream, _) = listener.accept().await.unwrap();
let request = read_request(&mut stream).await;
let id = query_value(&request_url(&request), "query_id").unwrap();
stream.write_all(prefix.as_bytes()).await.unwrap();
assert_eq!(
tokio::time::timeout(Duration::from_secs(4), stream.read(&mut [0])).await.unwrap().unwrap(),
0
);
assert_eq!(query_value(&request_url(&request), "http_read_timeout"), None);
id
});
let source = DataSource { properties: vec![property("http_read_timeout", "1")], ..source(port) };
let pool = Pool::connect(&source, None, None).await.unwrap();
let error = tokio::time::timeout(
Duration::from_secs(3),
pool.execute("DELETE FROM fixture WHERE id = 1", 0, &CancellationToken::new()),
)
.await
.expect("ClickHouse must stop waiting for a stalled response")
.unwrap_err();
assert_eq!(error.kind, ErrorKind::TimedOut);
assert!(error.message.contains("outcome is unknown"), "{error}");
let id = fixture.await.unwrap();
assert!(error.message.contains(&format!("query_id={id}")), "{error}");
}
}
#[tokio::test]
async fn read_timeout_resets_while_response_keeps_arriving() {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
let fixture = tokio::spawn(async move {
let (mut probe, _) = listener.accept().await.unwrap();
read_request(&mut probe).await;
reply(&mut probe, "200 OK", "", ONE).await;
drop(probe);
let (mut stream, _) = listener.accept().await.unwrap();
read_request(&mut stream).await;
let (first, rest) = ONE.split_at(6);
let headers = format!("HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", ONE.len());
stream.write_all(headers.as_bytes()).await.unwrap();
tokio::time::sleep(Duration::from_millis(1100)).await;
stream.write_all(first.as_bytes()).await.unwrap();
tokio::time::sleep(Duration::from_millis(1100)).await;
stream.write_all(rest.as_bytes()).await.unwrap();
});
let source = DataSource { properties: vec![property("http_read_timeout", "2")], ..source(port) };
let pool = Pool::connect(&source, None, None).await.unwrap();
let result = pool.execute("SELECT 1", 1, &CancellationToken::new()).await.unwrap();
assert_eq!(result.rows, vec![vec![Some("1".into())]]);
fixture.await.unwrap();
}
#[tokio::test]
async fn http_read_timeout_rejects_invalid_or_duplicate_values() {
for properties in [
vec![property("http_read_timeout", "0")],
vec![property("http_read_timeout", "1.5")],
vec![property("http_read_timeout", "4294967296")],
vec![property("http_read_timeout", "1"), property("HTTP-READ-TIMEOUT", "2")],
] {
let source = DataSource { properties, ..source(0) };
let error = Pool::connect(&source, None, None).await.err().unwrap();
assert_eq!(error.kind, ErrorKind::InvalidInput);
assert!(error.message.contains("http_read_timeout"), "{error}");
}
}
#[tokio::test]
async fn sequential_queries_reuse_the_http_connection() {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
@@ -1151,6 +1420,69 @@ mod tests {
requests.await.unwrap();
}
#[tokio::test]
async fn console_sessions_have_distinct_http_ids() {
let (port, requests) = server(vec![("200 OK", "", ONE); 8]).await;
let Pool::Clickhouse(pool) = Pool::connect(&source(port), None, None).await.unwrap() else { unreachable!() };
let first = ConsoleId::new("main", "console.sql");
let second = ConsoleId::new("main", "console_1.sql");
let cancel = CancellationToken::new();
for console in [first, second, first] {
pool.execute_in_console("SELECT 2", 0, 1, &cancel, Some(console)).await.unwrap();
}
pool.release_console(second);
pool.ping().await.unwrap();
let requests = requests.await.unwrap();
let ids = requests
.iter()
.map(|request| query_value(&request_url(request), "session_id").unwrap())
.collect::<Vec<_>>();
assert_ne!(ids[0], ids[1]);
assert_ne!(ids[1], ids[3]);
assert_eq!(ids[1], ids[2]);
assert_eq!(ids[3], ids[4]);
assert_eq!(ids[1], ids[5]);
assert_eq!(ids[0], ids[6]);
assert_eq!(ids[1], ids[7]);
}
#[tokio::test]
async fn stateless_queries_do_not_wait_for_a_shared_session() {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
let (started, received) = tokio::sync::oneshot::channel();
let server = tokio::spawn(async move {
let (mut probe, _) = listener.accept().await.unwrap();
read_request(&mut probe).await;
reply(&mut probe, "200 OK", "", ONE).await;
let (mut first, _) = listener.accept().await.unwrap();
let first_request = read_request(&mut first).await;
started.send(()).unwrap();
let (mut second, _) = listener.accept().await.unwrap();
let second_request = read_request(&mut second).await;
reply(&mut second, "200 OK", "", ONE).await;
reply(&mut first, "200 OK", "", ONE).await;
(first_request, second_request)
});
let source = DataSource { properties: vec![property("use_http_session", "false")], ..source(port) };
let pool = Pool::connect(&source, None, None).await.unwrap();
let cancel = CancellationToken::new();
let first = pool.execute("SELECT 1", 1, &cancel);
let second = async {
received.await.unwrap();
pool.execute("SELECT 2", 1, &cancel).await
};
let (first, second) = tokio::time::timeout(Duration::from_secs(5), async { tokio::join!(first, second) })
.await
.expect("both requests should reach the server");
first.unwrap();
second.unwrap();
let (first, second) = server.await.unwrap();
for request in [first, second] {
assert_eq!(query_value(&request_url(&request), "session_id"), None);
}
}
#[tokio::test]
async fn cancellation_sends_kill_outside_the_busy_session() {
for stateless in [false, true] {
+1
Переглянути файл
@@ -1000,6 +1000,7 @@ impl Pool {
pub async fn ping(&self) -> IdeResult<()> {
match self {
Pool::Jdbc(p) => p.ping().await,
Pool::Clickhouse(p) => p.ping().await,
_ => self.rows(self.ping_sql(), 1).await.map(|_| ()),
}
}
+15
Переглянути файл
@@ -30,6 +30,7 @@ pub(crate) struct Key {
target: String,
statement: String,
schema: Option<String>,
console: Option<(String, String)>,
}
impl Key {
@@ -38,8 +39,14 @@ impl Key {
target: target.to_owned(),
statement: statement.to_owned(),
schema: schema.filter(|s| !s.is_empty()).map(str::to_owned),
console: None,
}
}
pub(crate) fn with_console(mut self, console: Option<crate::ConsoleId<'_>>) -> Self {
self.console = console.map(|console| (console.window.to_owned(), console.path.to_owned()));
self
}
}
/// A request for the next rows of a cursor's statement.
@@ -186,6 +193,14 @@ impl Cursors {
self.registry.lock().slots.retain(|s| s.key != *key);
}
pub(crate) fn release_console(&self, console: crate::ConsoleId<'_>, target: Option<&str>) {
self.registry.lock().slots.retain(|slot| {
let key = &slot.key;
!target.is_none_or(|target| key.target == target)
|| !key.console.as_ref().is_some_and(|(window, path)| window == console.window && path == console.path)
});
}
/// Closes the cursors of `target`: it disconnects, or a statement that changes
/// data or schema is about to run there.
pub(crate) fn release_target(&self, target: &str) {
+416
Переглянути файл
@@ -0,0 +1,416 @@
use ide_core::{CancellationToken, IdeError, IdeResult, error::ErrorKind};
use parking_lot::Mutex;
use std::{
collections::HashMap,
path::Path,
process::Stdio,
sync::{
Arc,
atomic::{AtomicU64, Ordering},
},
time::Duration,
};
use tokio::{
io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt},
process::Command,
sync::{mpsc, oneshot},
time::{Instant, timeout, timeout_at},
};
const LIMIT: usize = 16 * 1024 * 1024;
const HEADER: usize = 16;
const CANCEL_GRACE: Duration = Duration::from_secs(3);
type Replies = Arc<Mutex<HashMap<u64, mpsc::Sender<Vec<u8>>>>>;
pub(super) struct Bridge {
closed: CancellationToken,
exited: CancellationToken,
sequence: AtomicU64,
outgoing: mpsc::Sender<Outgoing>,
replies: Replies,
}
struct Outgoing {
frame: Vec<u8>,
session: CancellationToken,
sent: oneshot::Sender<IdeResult<()>>,
}
struct Pending<'a> {
bridge: &'a Bridge,
id: u64,
incoming: mpsc::Receiver<Vec<u8>>,
}
impl Drop for Pending<'_> {
fn drop(&mut self) {
self.bridge.replies.lock().remove(&self.id);
}
}
impl Pending<'_> {
async fn recv(&mut self) -> IdeResult<Vec<u8>> {
tokio::select! {
biased;
frame = self.incoming.recv() => frame.ok_or_else(disconnected),
() = self.bridge.closed.cancelled() => Err(disconnected()),
}
}
}
impl Bridge {
pub(super) fn start(cache: &Path, jars: &[String]) -> IdeResult<Self> {
let jdks = ide_sdk::java::installed_jdks();
let java = ide_sdk::java::java_runtime(&jdks, 17)
.ok_or_else(|| IdeError::invalid("Install a Java 17 or newer runtime to use custom JDBC drivers"))?;
let jar = ide_sdk::java::jdbc_bridge_jar(cache)
.ok_or_else(|| IdeError::invalid("Cannot install the JDBC bridge in the application data directory"))?;
let classpath = std::env::join_paths(std::iter::once(jar.as_path()).chain(jars.iter().map(Path::new)))
.map_err(|_| IdeError::invalid("A JDBC JAR path contains the system classpath separator"))?;
// Embedded databases can resolve file URLs against the JVM's working directory.
let files = cache.join("files");
std::fs::create_dir_all(&files)?;
let mut command = Command::new(ide_sdk::java::java_executable(&java.home));
command.current_dir(files);
ide_core::process::prepare(command.as_std_mut());
let mut child = command
.args(["-Xms8m", "-Xmx192m", "--enable-native-access=ALL-UNNAMED", "-cp"])
.arg(classpath)
.args(["ai.openidea.jdbc.OpenIdeaJdbc", "--multiplex"])
.env_remove("CLASSPATH")
.env_remove("JDK_JAVA_OPTIONS")
.env_remove("JAVA_TOOL_OPTIONS")
.env_remove("_JAVA_OPTIONS")
.kill_on_drop(true)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.spawn()?;
let input = child.stdin.take().expect("piped");
let output = child.stdout.take().expect("piped");
let closed = CancellationToken::new();
let exited = CancellationToken::new();
tokio::spawn({
let closed = closed.clone();
let exited = exited.clone();
async move {
tokio::select! {
_ = child.wait() => {}
() = closed.cancelled() => {
// The writer drops stdin. Give file-based drivers time to flush.
if timeout(Duration::from_secs(2), child.wait()).await.is_err() {
let _ = child.kill().await;
}
}
}
closed.cancel();
exited.cancel();
}
});
Ok(Self::with_io(input, output, closed, exited))
}
fn with_io(
input: impl AsyncWrite + Unpin + Send + 'static,
output: impl AsyncRead + Unpin + Send + 'static,
closed: CancellationToken,
exited: CancellationToken,
) -> Self {
let (outgoing, writes) = mpsc::channel(4);
let replies = Replies::default();
tokio::spawn(write_frames(input, writes, closed.clone()));
tokio::spawn(read_frames(output, replies.clone(), closed.clone()));
Self { closed, exited, sequence: AtomicU64::new(1), outgoing, replies }
}
pub(super) fn shutdown(&self) {
self.closed.cancel();
}
pub(super) fn is_closed(&self) -> bool {
self.closed.is_cancelled()
}
pub(super) async fn close(&self) {
self.shutdown();
self.exited.cancelled().await;
}
async fn send(&self, frame: Vec<u8>, session: &CancellationToken) -> IdeResult<()> {
let (sent, receipt) = oneshot::channel();
tokio::select! {
() = self.closed.cancelled() => return Err(disconnected()),
result = self.outgoing.send(Outgoing { frame, session: session.clone(), sent }) => {
result.map_err(|_| disconnected())?;
}
}
tokio::select! {
biased;
result = receipt => result.map_err(|_| disconnected())?,
() = self.closed.cancelled() => Err(disconnected()),
}
}
pub(super) async fn exchange(
&self,
session: u32,
fields: &[&str],
cancel: &CancellationToken,
active: &CancellationToken,
) -> IdeResult<Option<Vec<u8>>> {
if cancel.is_cancelled() {
return Ok(None);
}
if active.is_cancelled() {
return Err(IdeError::cancelled());
}
let id = self
.sequence
.try_update(Ordering::Relaxed, Ordering::Relaxed, |next| next.checked_add(1))
.map_err(|_| IdeError::internal("JDBC request IDs exhausted"))?;
let frame = encode(id, session, fields)?;
let (sender, incoming) = mpsc::channel(2);
self.replies.lock().insert(id, sender);
let mut pending = Pending { bridge: self, id, incoming };
let send = self.send(frame, active);
tokio::pin!(send);
let early_deadline = tokio::select! {
result = &mut send => { result?; None },
() = cancel.cancelled() => {
let end = Instant::now() + CANCEL_GRACE;
timeout_at(end, send).await.map_err(|_| cancel_timeout())??;
Some(end)
}
};
let deadline = tokio::select! {
biased;
() = cancel.cancelled() => early_deadline.unwrap_or_else(|| Instant::now() + CANCEL_GRACE),
data = pending.recv() => {
let data = data?;
if data.is_empty() { return Err(IdeError::invalid("Unexpected JDBC cancellation acknowledgement")); }
return Ok(Some(data));
}
};
let data = timeout_at(deadline, async {
self.send(header(id, session, 0).to_vec(), active).await?;
let first = pending.recv().await?;
let second = pending.recv().await?;
match (first.is_empty(), second.is_empty()) {
(true, false) => Ok(second),
(false, true) => Ok(first),
_ => Err(IdeError::invalid("Invalid JDBC cancellation acknowledgement")),
}
})
.await
.map_err(|_| cancel_timeout())??;
match data.first() {
// A committed statement may finish before the bridge receives Cancel.
Some(1) => Ok(Some(data)),
Some(0) => Ok(None),
_ => Err(IdeError::invalid("Invalid JDBC cancellation response")),
}
}
pub(super) async fn close_session(&self, session: u32) -> IdeResult<()> {
if self.is_closed() {
return Ok(());
}
let control = CancellationToken::new();
let data = timeout(CANCEL_GRACE, self.exchange(session, &["close"], &control, &control))
.await
.map_err(|_| IdeError::new(ErrorKind::TimedOut, "Closing the JDBC console timed out"))??;
super::decode(&data.ok_or_else(IdeError::cancelled)?, "", 0.).map(|_| ())
}
}
impl Drop for Bridge {
fn drop(&mut self) {
self.shutdown();
}
}
async fn write_frames(
mut input: impl AsyncWrite + Unpin,
mut writes: mpsc::Receiver<Outgoing>,
closed: CancellationToken,
) {
while let Some(outgoing) = tokio::select! {
biased;
() = closed.cancelled() => None,
outgoing = writes.recv() => outgoing,
} {
// If Close raced with an enqueued Open or query, discard it before writing.
if outgoing.session.is_cancelled() {
let _ = outgoing.sent.send(Err(IdeError::cancelled()));
continue;
}
let result = tokio::select! {
() = closed.cancelled() => break,
result = input.write_all(&outgoing.frame) => result.map_err(IdeError::from),
};
let failed = result.is_err();
let _ = outgoing.sent.send(result);
if failed {
break;
}
}
closed.cancel();
}
async fn read_frames(mut output: impl AsyncRead + Unpin, replies: Replies, closed: CancellationToken) {
loop {
let frame = async {
let id = output.read_u64().await?;
Ok::<_, IdeError>((id, read_frame(&mut output).await?))
};
let (id, data) = match tokio::select! {
() = closed.cancelled() => break,
result = frame => result,
} {
Ok(frame) => frame,
Err(_) => break,
};
let sender = replies.lock().get(&id).cloned();
// A response may arrive after its caller was cancelled and retired.
if let Some(sender) = sender
&& matches!(sender.try_send(data), Err(mpsc::error::TrySendError::Full(_)))
{
break;
}
}
closed.cancel();
}
fn disconnected() -> IdeError {
IdeError::new(ErrorKind::Io, "JDBC connection was lost")
}
fn cancel_timeout() -> IdeError {
IdeError::invalid(
"Cancellation timed out and the JDBC session was closed. Check the statement's status on the server before running it again. The next query will try to reconnect.",
)
}
fn header(id: u64, session: u32, fields: u32) -> [u8; HEADER] {
let mut bytes = [0; HEADER];
bytes[..8].copy_from_slice(&id.to_be_bytes());
bytes[8..12].copy_from_slice(&session.to_be_bytes());
bytes[12..].copy_from_slice(&fields.to_be_bytes());
bytes
}
pub(super) fn frame_size(fields: &[&str]) -> IdeResult<usize> {
if fields.is_empty() || fields.len() > 8192 {
return Err(IdeError::invalid("Invalid JDBC field count"));
}
fields
.iter()
.try_fold(HEADER, |n, s| n.checked_add(4)?.checked_add(s.len()).filter(|n| *n <= LIMIT))
.ok_or_else(|| IdeError::invalid("JDBC request exceeds 16 MiB"))
}
fn encode(id: u64, session: u32, fields: &[&str]) -> IdeResult<Vec<u8>> {
let size = frame_size(fields)?;
let mut data = Vec::with_capacity(size);
data.extend_from_slice(&header(id, session, fields.len() as u32));
for field in fields {
data.extend_from_slice(&(field.len() as u32).to_be_bytes());
data.extend_from_slice(field.as_bytes());
}
Ok(data)
}
async fn read_frame(output: &mut (impl AsyncRead + Unpin)) -> IdeResult<Vec<u8>> {
let n = output.read_u32().await? as usize;
if n > LIMIT {
return Err(IdeError::invalid("JDBC response exceeds 16 MiB"));
}
let mut data = vec![0; n];
output.read_exact(&mut data).await?;
Ok(data)
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn frame_codec_checks_both_16_mib_boundaries() {
assert_eq!(encode(7, 3, &["a"]).unwrap(), [0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0, 3, 0, 0, 0, 1, 0, 0, 0, 1, b'a']);
let mut field = "x".repeat(LIMIT - HEADER - 4);
assert_eq!(encode(1, 0, &[&field]).unwrap().len(), LIMIT);
field.push('x');
assert!(encode(1, 0, &[&field]).is_err());
let mut framed = vec![0u8; LIMIT + 4];
framed[..4].copy_from_slice(&(LIMIT as u32).to_be_bytes());
assert_eq!(read_frame(&mut framed.as_slice()).await.unwrap().len(), LIMIT);
assert!(read_frame(&mut &((LIMIT + 1) as u32).to_be_bytes()[..]).await.is_err());
assert!(read_frame(&mut &[0, 0, 0, 2, 1u8][..]).await.is_err());
}
async fn reply(output: &mut (impl AsyncWrite + Unpin), id: u64, body: &[u8]) {
output.write_u64(id).await.unwrap();
output.write_u32(body.len() as u32).await.unwrap();
output.write_all(body).await.unwrap();
}
#[tokio::test]
async fn exchange_rejects_an_acknowledgement_for_an_uncancelled_request() {
let (input, mut peer_input) = tokio::io::duplex(32);
let (output, mut peer_output) = tokio::io::duplex(32);
let active = CancellationToken::new();
let bridge = Bridge::with_io(input, output, CancellationToken::new(), CancellationToken::new());
let peer = async {
let frame = encode(1, 0, &["query"]).unwrap();
let mut actual = vec![0; frame.len()];
peer_input.read_exact(&mut actual).await.unwrap();
assert_eq!(actual, frame);
reply(&mut peer_output, 1, &[]).await;
};
let (result, ()) = tokio::join!(bridge.exchange(0, &["query"], &active, &active), peer);
assert!(result.unwrap_err().message.contains("Unexpected JDBC cancellation acknowledgement"));
}
#[tokio::test]
async fn cancellation_drains_tagged_replies_without_stealing_a_siblings_response() {
for ack_first in [true, false] {
let (input, mut peer_input) = tokio::io::duplex(1);
let (output, mut peer_output) = tokio::io::duplex(1);
let active = CancellationToken::new();
let cancel = CancellationToken::new();
let bridge = Bridge::with_io(input, output, CancellationToken::new(), CancellationToken::new());
let peer = async {
let frame = encode(1, 11, &["query"]).unwrap();
let mut request = vec![0; frame.len()];
peer_input.read_exact(&mut request).await.unwrap();
assert_eq!(request, frame);
peer_input.read_exact(&mut request).await.unwrap();
assert_eq!(request, encode(2, 22, &["query"]).unwrap());
// Cancel during a partial reply header; the reader must stay on that frame.
peer_output.write_all(&1u64.to_be_bytes()[..2]).await.unwrap();
cancel.cancel();
let mut stop = [0; HEADER];
peer_input.read_exact(&mut stop).await.unwrap();
assert_eq!(stop, header(1, 11, 0));
peer_output.write_all(&1u64.to_be_bytes()[2..]).await.unwrap();
let terminal = !ack_first;
peer_output.write_u32(u32::from(terminal)).await.unwrap();
if terminal {
peer_output.write_u8(1).await.unwrap();
}
reply(&mut peer_output, 2, &[1, b'b']).await;
reply(&mut peer_output, 1, if ack_first { &[0] } else { &[] }).await;
};
let (a, b, ()) = tokio::join!(
biased;
bridge.exchange(11, &["query"], &cancel, &active),
bridge.exchange(22, &["query"], &active, &active),
peer,
);
assert_eq!(a.unwrap(), (!ack_first).then(|| vec![1]));
assert_eq!(b.unwrap(), Some(vec![1, b'b']));
}
}
}
+239 -298
Переглянути файл
@@ -2,21 +2,21 @@
//! can run driver-specific initialization. A project source may connect only with the
//! settings its user last accepted in the dialog; the approval lives outside the project.
use crate::local_settings::persist_local;
use crate::{DataSource, DbManager, QueryResult, ResultColumn};
use ide_core::{CancellationToken, IdeError, IdeResult};
use crate::{ConsoleId, DataSource, DbManager, QueryResult, ResultColumn};
use ide_core::{CancellationToken, IdeError, IdeResult, error::ErrorKind};
use serde::{Deserialize, Serialize};
use specta::Type;
use std::collections::HashMap;
use std::io::{Cursor, Read};
use std::path::{Path, PathBuf};
use std::process::Stdio;
use std::sync::Arc;
use std::time::{Duration, Instant};
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
use tokio::process::{ChildStdin, ChildStdout, Command};
use tokio::sync::Mutex;
use tokio::time::{Instant as Deadline, timeout_at};
use tokio::time::timeout;
const LIMIT: usize = 16 * 1024 * 1024;
mod bridge;
use bridge::Bridge;
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
@@ -203,171 +203,73 @@ impl DbManager {
}
}
struct Bridge {
stop: tokio::sync::oneshot::Sender<()>,
exited: tokio::task::JoinHandle<()>,
sequence: u64,
input: ChildStdin,
output: ChildStdout,
struct Session {
id: u32,
// A physical JDBC Connection executes one request at a time.
opened: Mutex<bool>,
retired: CancellationToken,
}
impl Session {
fn new(id: u32) -> Self {
Self { id, opened: Mutex::new(id == 0), retired: CancellationToken::new() }
}
}
#[derive(Default)]
struct ConsoleSessions {
latest: u32,
opened: HashMap<(String, String), Arc<Session>>,
}
pub struct JdbcPool {
bridge: Mutex<Option<Bridge>>,
closed: CancellationToken,
bridge: Arc<Bridge>,
service: Session,
consoles: parking_lot::Mutex<ConsoleSessions>,
shared_connection: bool,
pub(crate) version: String,
pub(crate) identifier_quote: String,
}
impl Bridge {
fn start(cache: &Path, jars: &[String]) -> IdeResult<Self> {
let jdks = ide_sdk::java::installed_jdks();
let java = ide_sdk::java::java_runtime(&jdks, 17)
.ok_or_else(|| IdeError::invalid("Install a Java 17 or newer runtime to use custom JDBC drivers"))?;
let jar = ide_sdk::java::jdbc_bridge_jar(cache)
.ok_or_else(|| IdeError::invalid("Cannot install the JDBC bridge in the application data directory"))?;
let classpath = std::env::join_paths(std::iter::once(jar.as_path()).chain(jars.iter().map(Path::new)))
.map_err(|_| IdeError::invalid("A JDBC JAR path contains the system classpath separator"))?;
// Embedded databases can resolve file URLs against the JVM's working directory.
let files = cache.join("files");
std::fs::create_dir_all(&files)?;
let mut command = Command::new(ide_sdk::java::java_executable(&java.home));
command.current_dir(files);
ide_core::process::prepare(command.as_std_mut());
let mut child = command
.args(["-Xms8m", "-Xmx192m", "--enable-native-access=ALL-UNNAMED", "-cp"])
.arg(classpath)
.arg("ai.openidea.jdbc.OpenIdeaJdbc")
.env_remove("CLASSPATH")
.env_remove("JDK_JAVA_OPTIONS")
.env_remove("JAVA_TOOL_OPTIONS")
.env_remove("_JAVA_OPTIONS")
.kill_on_drop(true)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.spawn()?;
let input = child.stdin.take().expect("piped");
let output = child.stdout.take().expect("piped");
let (stop, stopped) = tokio::sync::oneshot::channel();
let exited = tokio::spawn(async move {
tokio::select! {
stop = stopped => {
// Disconnect closes stdin so a file-backed driver can flush. A dropped
// request or an unresponsive driver must be reaped without waiting.
if stop.is_err() || tokio::time::timeout(Duration::from_secs(2), child.wait()).await.is_err() {
let _ = child.kill().await;
}
}
_ = child.wait() => {}
}
});
Ok(Self { input, output, stop, exited, sequence: 0 })
}
async fn close(self) {
drop(self.input);
let _ = self.stop.send(());
let _ = self.exited.await;
}
/// Dropped futures and uncertain transport errors retire the connection they were using.
struct ActiveRequest<'a> {
pool: &'a JdbcPool,
session: &'a Session,
completed: bool,
}
// Request: u64 request id, u32 field count, then length-prefixed UTF-8 fields.
// Zero fields cancels that id. Replies have a u32 length; zero acknowledges Cancel.
fn encode(id: u64, fields: &[&str]) -> IdeResult<Vec<u8>> {
if fields.is_empty() || fields.len() > 8192 {
return Err(IdeError::invalid("Invalid JDBC field count"));
}
let size = fields
.iter()
.try_fold(12usize, |n, s| n.checked_add(4)?.checked_add(s.len()).filter(|n| *n <= LIMIT))
.ok_or_else(|| IdeError::invalid("JDBC request exceeds 16 MiB"))?;
let mut data = Vec::with_capacity(size);
data.extend_from_slice(&id.to_be_bytes());
data.extend_from_slice(&(fields.len() as u32).to_be_bytes());
for field in fields {
data.extend_from_slice(&(field.len() as u32).to_be_bytes());
data.extend_from_slice(field.as_bytes());
}
Ok(data)
}
async fn read_frame(output: &mut (impl AsyncRead + Unpin)) -> IdeResult<Vec<u8>> {
let n = output.read_u32().await? as usize;
if n > LIMIT {
return Err(IdeError::invalid("JDBC response exceeds 16 MiB"));
}
let mut data = vec![0; n];
output.read_exact(&mut data).await?;
Ok(data)
}
const CANCEL_GRACE: Duration = Duration::from_secs(3);
fn cancel_timeout() -> IdeError {
IdeError::invalid(
"Cancellation timed out and the JDBC session was closed. Check the statement's status on the server before running it again. The next query will try to reconnect.",
)
}
async fn exchange(
input: &mut (impl AsyncWrite + Unpin),
output: &mut (impl AsyncRead + Unpin),
frame: Vec<u8>,
cancel: &CancellationToken,
) -> IdeResult<Option<Vec<u8>>> {
let mut stop = [0; 12];
stop[..8].copy_from_slice(&frame[..8]);
let early_deadline = {
let send = input.write_all(&frame);
tokio::pin!(send);
tokio::select! {
result = &mut send => { result?; None },
() = cancel.cancelled() => {
let end = Deadline::now() + CANCEL_GRACE;
timeout_at(end, send).await.map_err(|_| cancel_timeout())??;
Some(end)
}
impl Drop for ActiveRequest<'_> {
fn drop(&mut self) {
if !self.completed {
self.pool.retire(self.session);
}
};
drop(frame);
let (first, deadline) = {
let reply = read_frame(output);
tokio::pin!(reply);
let end = tokio::select! {
biased;
() = cancel.cancelled() => early_deadline.unwrap_or_else(|| Deadline::now() + CANCEL_GRACE),
data = &mut reply => {
let data = data?;
if data.is_empty() { return Err(IdeError::invalid("Unexpected JDBC cancellation acknowledgement")); }
return Ok(Some(data));
}
};
let first = timeout_at(end, async {
input.write_all(&stop).await?;
reply.await
})
.await
.map_err(|_| cancel_timeout())??;
(first, end)
};
// Drain both frames before the next statement can use this session. The driver
// may complete the statement before or after the control thread acknowledges it.
let data = if first.is_empty() {
timeout_at(deadline, read_frame(output)).await.map_err(|_| cancel_timeout())??
} else {
if timeout_at(deadline, output.read_u32()).await.map_err(|_| cancel_timeout())?? != 0 {
return Err(IdeError::invalid("Invalid JDBC cancellation acknowledgement"));
}
first
};
match data.first() {
// A committed statement may have finished before the control thread received Cancel.
Some(1) => Ok(Some(data)),
Some(0) => Ok(None),
_ => Err(IdeError::invalid("Invalid JDBC cancellation response")),
}
}
/// A second connection to an anonymous database would see a different database.
fn private_database_url(url: &str) -> bool {
if let Some(h2) = url.strip_prefix("jdbc:h2:mem:") {
return h2.is_empty() || h2.starts_with(';');
}
let Some(sqlite) = url.strip_prefix("jdbc:sqlite:") else {
return false;
};
let (path, query) = sqlite.split_once('?').unwrap_or((sqlite, ""));
if matches!(path, "" | ":memory:" | "file:") {
return true;
}
let option = |name| {
query
.split('&')
.rev()
.filter_map(|part| part.split_once('='))
.find_map(|(key, value)| (key == name).then_some(value))
};
path.starts_with("file:")
&& (path == "file::memory:" || option("mode") == Some("memory"))
&& option("cache") != Some("shared")
}
impl JdbcPool {
async fn connect(
source: &DataSource,
@@ -393,32 +295,85 @@ impl JdbcPool {
let bridge = tokio::task::spawn_blocking(move || Bridge::start(&cache, &driver.jars))
.await
.map_err(|e| IdeError::internal(e.to_string()))??;
let mut pool = Self {
bridge: Mutex::new(Some(bridge)),
closed: CancellationToken::new(),
version: String::new(),
identifier_quote: String::new(),
};
let args: Vec<_> = fields.iter().map(String::as_str).collect();
let cancel = CancellationToken::new();
let result = tokio::time::timeout(Duration::from_secs(30), pool.request(&args, "", &cancel))
let data = timeout(Duration::from_secs(30), bridge.exchange(0, &args, &cancel, &cancel))
.await
.map_err(|_| IdeError::new(ide_core::error::ErrorKind::TimedOut, "JDBC connection timed out"))??;
.map_err(|_| IdeError::new(ErrorKind::TimedOut, "JDBC connection timed out"))??;
let result = decode(&data.ok_or_else(IdeError::cancelled)?, "", 0.)?;
let mut metadata = result.rows.into_iter().next().unwrap_or_default().into_iter();
pool.version = metadata.next().flatten().unwrap_or_else(|| "Connected".into());
pool.identifier_quote = metadata.next().flatten().unwrap_or_default().trim().into();
Ok(pool)
Ok(Self {
bridge: Arc::new(bridge),
service: Session::new(0),
consoles: Default::default(),
shared_connection: private_database_url(&source.url),
version: metadata.next().flatten().unwrap_or_else(|| "Connected".into()),
identifier_quote: metadata.next().flatten().unwrap_or_default().trim().into(),
})
}
pub(crate) async fn close(&self) {
self.closed.cancel();
if let Some(bridge) = self.bridge.lock().await.take() {
bridge.close().await;
}
self.bridge.close().await;
}
pub(crate) fn is_closed(&self) -> bool {
self.closed.is_cancelled()
self.bridge.is_closed()
}
fn console(&self, console: ConsoleId<'_>) -> IdeResult<Arc<Session>> {
let key = (console.window.to_owned(), console.path.to_owned());
let mut sessions = self.consoles.lock();
if let Some(existing) = sessions.opened.get(&key)
&& !existing.retired.is_cancelled()
{
return Ok(existing.clone());
}
let id = sessions.latest.checked_add(1).ok_or_else(|| IdeError::internal("JDBC session IDs exhausted"))?;
sessions.latest = id;
let session = Arc::new(Session::new(id));
sessions.opened.insert(key, session.clone());
Ok(session)
}
pub(crate) async fn release_console(&self, console: ConsoleId<'_>) -> IdeResult<()> {
let key = (console.window.to_owned(), console.path.to_owned());
// Retire the ID before allowing a reopened editor to allocate a replacement.
let session = self.consoles.lock().opened.remove(&key).inspect(|session| session.retired.cancel());
if let Some(session) = session {
let closed = self.bridge.close_session(session.id).await;
self.shutdown_service_if_idle();
closed?;
}
Ok(())
}
fn retire(&self, session: &Session) {
if session.retired.is_cancelled() {
return;
}
session.retired.cancel();
if session.id != 0 {
let bridge = self.bridge.clone();
let id = session.id;
tokio::spawn(async move {
let _ = bridge.close_session(id).await;
});
}
self.shutdown_service_if_idle();
}
fn shutdown_service_if_idle(&self) {
if !self.service.retired.is_cancelled() {
return;
}
let has_consoles =
self.consoles.lock().opened.values().any(|session| {
!session.retired.is_cancelled() && session.opened.try_lock().map_or(true, |opened| *opened)
});
// Service failure cannot discard a healthy editor's transaction or temporary tables.
if !has_consoles {
self.bridge.shutdown();
}
}
pub(crate) async fn query(
@@ -439,7 +394,21 @@ impl JdbcPool {
cancel: &CancellationToken,
schema: Option<&str>,
) -> IdeResult<QueryResult> {
self.request(
self.query_in_console(sql, skip, max, cancel, schema, None).await
}
pub(crate) async fn query_in_console(
&self,
sql: &str,
skip: usize,
max: usize,
cancel: &CancellationToken,
schema: Option<&str>,
console: Option<ConsoleId<'_>>,
) -> IdeResult<QueryResult> {
let session = console.filter(|_| !self.shared_connection).map(|console| self.console(console)).transpose()?;
self.request_on(
session.as_deref().unwrap_or(&self.service),
&["query", sql, &skip.to_string(), &max.min(i32::MAX as usize).to_string(), schema.unwrap_or_default()],
sql,
cancel,
@@ -462,77 +431,84 @@ impl JdbcPool {
}
async fn request(&self, fields: &[&str], sql: &str, cancel: &CancellationToken) -> IdeResult<QueryResult> {
let result = self.exchange_once(fields, sql, cancel).await;
if let Err(e) = &result
&& fields.first() != Some(&"open")
&& e.kind != ide_core::error::ErrorKind::Cancelled
&& !self.is_closed()
&& !self.session_valid().await
{
// The session is gone (a proxy or tunnel dropped the idle TCP connection): close the
// pool so the next statement or Connect starts a new one instead of failing forever.
self.close().await;
self.request_on(&self.service, fields, sql, cancel).await
}
async fn request_on(
&self,
session: &Session,
fields: &[&str],
sql: &str,
cancel: &CancellationToken,
) -> IdeResult<QueryResult> {
// A rejected local request has not used the connection and cannot invalidate it.
bridge::frame_size(fields)?;
let mut opened = tokio::select! {
biased;
() = cancel.cancelled() => return Err(IdeError::cancelled()),
() = session.retired.cancelled() => {
return Err(if session.id == 0 {
IdeError::new(ErrorKind::Io, "The JDBC service connection was lost. Reconnect to restore catalog access.")
} else {
IdeError::cancelled()
});
}
slot = session.opened.lock() => slot,
};
let mut active = ActiveRequest { pool: self, session, completed: false };
if !*opened {
let data = timeout(Duration::from_secs(30), self.exchange(session, &["open"], cancel))
.await
.map_err(|_| IdeError::new(ErrorKind::TimedOut, "JDBC connection timed out"))??;
decode(&data.ok_or_else(IdeError::cancelled)?, "", 0.)?;
*opened = true;
}
let start = Instant::now();
let data = self.exchange(session, fields, cancel).await?;
let result = data
.ok_or_else(IdeError::cancelled)
.and_then(|data| decode(&data, sql, start.elapsed().as_secs_f64() * 1000.0));
if result.as_ref().is_err_and(|error| error.kind != ErrorKind::Cancelled) && !self.session_valid(session).await
{
return result;
}
active.completed = true;
result
}
/// Keep-alive: checks the session (any SQL would be dialect-specific) and closes a dead one.
async fn exchange(
&self,
session: &Session,
fields: &[&str],
cancel: &CancellationToken,
) -> IdeResult<Option<Vec<u8>>> {
tokio::select! {
biased;
() = session.retired.cancelled() => Err(IdeError::cancelled()),
data = self.bridge.exchange(session.id, fields, cancel, &session.retired) => data,
}
}
/// Keep-alive operates on the service connection without waiting on an editor's query.
pub(crate) async fn ping(&self) -> IdeResult<()> {
if self.session_valid().await {
let _service = self.service.opened.lock().await;
if self.service.retired.is_cancelled() || self.session_valid(&self.service).await {
return Ok(());
}
self.close().await;
Err(IdeError::new(ide_core::error::ErrorKind::Io, "JDBC connection was lost"))
self.retire(&self.service);
Err(IdeError::new(ErrorKind::Io, "JDBC connection was lost"))
}
/// Whether the JDBC session still works, asked after a failed statement.
async fn session_valid(&self) -> bool {
if self.bridge.lock().await.is_none() {
return false;
}
/// Checks that an error was local to this statement before reusing its connection.
async fn session_valid(&self, session: &Session) -> bool {
let cancel = CancellationToken::new();
match tokio::time::timeout(Duration::from_secs(10), self.exchange_once(&["valid"], "", &cancel)).await {
Ok(Ok(result)) => {
result.rows.first().and_then(|row| row.first()).cloned().flatten().as_deref() != Some("false")
}
Ok(Err(_)) | Err(_) => false,
}
}
async fn exchange_once(&self, fields: &[&str], sql: &str, cancel: &CancellationToken) -> IdeResult<QueryResult> {
let mut slot = tokio::select! {
biased;
() = cancel.cancelled() => return Err(IdeError::cancelled()),
() = self.closed.cancelled() => return Err(IdeError::invalid("JDBC connection is closed")),
slot = self.bridge.lock() => slot,
let Ok(Ok(Some(data))) = timeout(Duration::from_secs(10), self.exchange(session, &["valid"], &cancel)).await
else {
return false;
};
let bridge = slot
.as_mut()
.ok_or_else(|| IdeError::invalid("JDBC connection is closed; reconnect to start a new session"))?;
bridge.sequence = bridge.sequence.wrapping_add(1);
let frame = encode(bridge.sequence, fields)?;
let mut bridge = slot.take().expect("checked above");
// Dropping an in-flight request must discard its process and partially consumed frame.
let interrupted = self.closed.clone().drop_guard();
let start = Instant::now();
let response = tokio::select! {
biased;
() = self.closed.cancelled() => Err(IdeError::cancelled()),
response = exchange(&mut bridge.input, &mut bridge.output, frame, cancel) => response,
};
let data = match response {
Ok(data) => {
*slot = Some(bridge);
interrupted.disarm();
data
}
Err(e) => {
drop(bridge.stop);
let _ = bridge.exited.await;
return Err(e);
}
};
decode(&data.ok_or_else(IdeError::cancelled)?, sql, start.elapsed().as_secs_f64() * 1000.0)
decode(&data, "", 0.).is_ok_and(|result| {
result.rows.first().and_then(|row| row.first()).and_then(Option::as_deref) == Some("true")
})
}
}
@@ -682,6 +658,33 @@ fn schema_columns(rows: Vec<Vec<Option<String>>>) -> HashMap<String, Vec<crate::
mod tests {
use super::*;
#[test]
fn only_private_jdbc_databases_keep_one_connection() {
for url in [
"jdbc:sqlite:",
"jdbc:sqlite::memory:",
"jdbc:sqlite:file:",
"jdbc:sqlite:file:private?mode=memory&cache=private",
"jdbc:h2:mem:",
"jdbc:h2:mem:;DB_CLOSE_DELAY=-1",
] {
assert!(private_database_url(url), "{url}");
}
for url in [
"jdbc:sqlite:/tmp/data.db",
"jdbc:sqlite:file:data.db?cache=shared",
"jdbc:sqlite:file:shared?mode=memory&cache=shared",
"jdbc:sqlite:file::memory:?cache=shared",
"jdbc:h2:mem:shared;DB_CLOSE_DELAY=-1",
"jdbc:h2:file:/tmp/data",
"jdbc:h2:tcp://server/data",
"jdbc:duckdb:",
"jdbc:clickhouse://localhost/default",
] {
assert!(!private_database_url(url), "{url}");
}
}
#[test]
fn schema_columns_group_by_table() {
let row = |t: &str, n: &str, null: &str, def: Option<&str>| {
@@ -703,68 +706,6 @@ mod tests {
assert_eq!(by_table.len(), 2);
}
#[tokio::test]
async fn frame_codec_checks_both_16_mib_boundaries() {
assert_eq!(encode(7, &["a"]).unwrap(), [0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0, 1, 0, 0, 0, 1, b'a']);
let mut field = "x".repeat(LIMIT - 16);
assert_eq!(encode(1, &[&field]).unwrap().len(), LIMIT);
field.push('x');
assert!(encode(1, &[&field]).is_err());
let mut framed = vec![0u8; LIMIT + 4];
framed[..4].copy_from_slice(&(LIMIT as u32).to_be_bytes());
assert_eq!(read_frame(&mut framed.as_slice()).await.unwrap().len(), LIMIT);
assert!(read_frame(&mut &((LIMIT + 1) as u32).to_be_bytes()[..]).await.is_err());
assert!(read_frame(&mut &[0, 0, 0, 2, 1u8][..]).await.is_err());
}
#[tokio::test]
async fn cancel_drains_partial_replies_in_either_order() {
for ack_first in [true, false] {
let (mut input, mut peer_input) = tokio::io::duplex(1);
let (mut output, mut peer_output) = tokio::io::duplex(1);
let cancel = CancellationToken::new();
let frame = encode(42, &["query"]).unwrap();
let peer = async {
let mut request = vec![0; frame.len()];
peer_input.read_exact(&mut request).await.unwrap();
assert_eq!(request, frame);
// The one-byte pipe forces the reader to consume part of the header before Cancel.
peer_output.write_all(&[0, 0]).await.unwrap();
cancel.cancel();
let mut stop = [0; 12];
peer_input.read_exact(&mut stop).await.unwrap();
assert_eq!(&stop[..8], &42u64.to_be_bytes());
assert_eq!(&stop[8..], &[0; 4]);
let frames = if ack_first { [0, 0, 0, 0, 0, 1, 0] } else { [0, 1, 1, 0, 0, 0, 0] };
peer_output.write_all(&frames).await.unwrap();
};
let (result, ()) = tokio::join!(exchange(&mut input, &mut output, frame.clone(), &cancel), peer);
assert_eq!(result.unwrap(), (!ack_first).then(|| vec![1]));
}
}
#[tokio::test]
async fn exchange_rejects_unexpected_acknowledgements() {
let cancel = CancellationToken::new();
let mut sink = tokio::io::sink();
let mut reply = &[0, 0, 0, 1, 1u8][..];
assert_eq!(
exchange(&mut sink, &mut reply, encode(1, &["query"]).unwrap(), &cancel).await.unwrap(),
Some(vec![1])
);
for cancelled in [false, true] {
if cancelled {
cancel.cancel();
}
let mut duplicate_ack = &[0u8; 8][..];
assert!(exchange(&mut sink, &mut duplicate_ack, encode(1, &["query"]).unwrap(), &cancel).await.is_err());
}
let (mut peer, mut output) = tokio::io::duplex(4);
peer.write_u32(0).await.unwrap();
let error = exchange(&mut sink, &mut output, encode(1, &["query"]).unwrap(), &cancel).await.unwrap_err();
assert_eq!(error.message, cancel_timeout().message);
}
#[test]
fn result_codec_preserves_null_and_rejects_incomplete_frames() {
let mut frame =
+186 -73
Переглянути файл
@@ -8,6 +8,7 @@ mod external_tunnel;
pub use external_tunnel::stop_external_tunnels_on_exit;
mod jdbc;
mod local_settings;
mod manual_session;
mod route;
mod tunnel_approval;
pub use jdbc::{DbJdbcDriver, jdbc_driver_classes};
@@ -174,6 +175,30 @@ pub struct IndexInfo {
pub name: String,
pub unique: bool,
pub columns: Vec<String>,
/// The key this index enforces; such an index is dropped with its constraint, not `drop index`.
/// `None` for a plain index, and on engines that don't tell.
#[serde(default)]
#[specta(optional)]
pub key: Option<DbKeyKind>,
}
/// A table key backed by an index.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum DbKeyKind {
Primary,
Unique,
}
impl DbKeyKind {
/// The [`sql::indexes`] key column: `p` (primary key), `u` (unique constraint).
fn from_catalog(v: Option<&str>) -> Option<Self> {
match v {
Some("p") => Some(Self::Primary),
Some("u") => Some(Self::Unique),
_ => None,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
@@ -310,7 +335,33 @@ pub struct DbManager {
on_disk: Mutex<Option<Vec<DataSource>>>,
}
type Session = Arc<tokio::sync::Mutex<Option<Held>>>;
use manual_session::Session;
/// A SQL editor's connection identity within the owning project's lifetime.
#[derive(Clone, Copy)]
pub struct ConsoleId<'a> {
pub window: &'a str,
pub path: &'a str,
expected_manual: Option<bool>,
}
impl<'a> ConsoleId<'a> {
pub const fn new(window: &'a str, path: &'a str) -> Self {
Self { window, path, expected_manual: None }
}
pub fn expecting_manual(mut self, manual: Option<bool>) -> Self {
self.expected_manual = manual;
self
}
}
fn postgres_console_mode_changed() -> IdeError {
IdeError::new(
ErrorKind::OutOfSync,
"PostgreSQL console transaction mode changed. Set the mode again before running SQL.",
)
}
const MAX_META_ROWS: usize = 100_000;
/// Completion columns of the default schema, which are read without the shared cap.
@@ -422,12 +473,7 @@ pub(crate) fn keep_alive(pool: &Arc<Pool>, every: Duration) {
/// Rolls back a session's transaction and releases its connection.
async fn end_session(session: &Session) {
let held = session.lock().await.take();
if let Some(mut conn) = held
&& (conn.finish_manual(false).await.is_err() || conn.restore_default().await.is_err())
{
conn.discard().await;
}
let _ = session.rollback_and_release().await;
}
impl DbManager {
@@ -1173,7 +1219,12 @@ impl DbManager {
};
match indexes.last_mut() {
Some(last) if last.name == name => last.columns.push(col),
_ => indexes.push(IndexInfo { name, unique: flag(&unique), columns: vec![col] }),
_ => indexes.push(IndexInfo {
name,
unique: flag(&unique),
columns: vec![col],
key: DbKeyKind::from_catalog(it.next().flatten().as_deref()),
}),
}
}
let fk_rows = if matches!(driver, DbDriver::Clickhouse | DbDriver::Snowflake) {
@@ -1576,13 +1627,26 @@ impl DbManager {
/// Refuses transaction control anywhere in a guarded console script before running its first statement.
pub async fn validate_script(&self, id: &str, statements: &[split::SqlStatement]) -> IdeResult<()> {
self.validate_console_script(id, statements, None).await
}
pub async fn validate_console_script(
&self,
id: &str,
statements: &[split::SqlStatement],
console: Option<ConsoleId<'_>>,
) -> IdeResult<()> {
if statements.len() > 1
&& self.source(id).is_ok_and(|s| s.driver == DbDriver::Postgres && s.read_only)
&& self.pool(id).await?.transaction_read_only()
{
for statement in statements {
if let Err(error) = conn::validate_pg_read_only(&statement.text) {
self.finish_transaction(id, false).await?;
if let Some(console) = console {
self.finish_postgres_console_transaction(id, console, false).await?;
} else {
self.finish_transaction(id, false).await?;
}
return Err(IdeError::invalid(error));
}
}
@@ -1603,7 +1667,22 @@ impl DbManager {
cancel: &CancellationToken,
schema: Option<&str>,
) -> IdeResult<QueryResult> {
let r = self.run(id, statement, skip, max_rows, cancel, schema).await;
self.execute_in_console(id, statement, skip, max_rows, cancel, schema, None).await
}
/// Executes in the originating editor's transaction or session when supported by the driver.
#[allow(clippy::too_many_arguments)]
pub async fn execute_in_console(
&self,
id: &str,
statement: &str,
skip: usize,
max_rows: usize,
cancel: &CancellationToken,
schema: Option<&str>,
console: Option<ConsoleId<'_>>,
) -> IdeResult<QueryResult> {
let r = self.run(id, statement, skip, max_rows, cancel, schema, console).await;
let ran = match &r {
Ok(_) => true,
Err(e) => !matches!(e.kind, ErrorKind::Cancelled | ErrorKind::PermissionDenied),
@@ -1625,12 +1704,34 @@ impl DbManager {
cancel: &CancellationToken,
schema: Option<&str>,
) -> IdeResult<QueryResult> {
self.run_paged(id, statement, row, 1, cancel, schema, false).await
self.read_console_row(id, statement, row, cancel, schema, None).await
}
pub async fn read_console_row(
&self,
id: &str,
statement: &str,
row: usize,
cancel: &CancellationToken,
schema: Option<&str>,
console: Option<ConsoleId<'_>>,
) -> IdeResult<QueryResult> {
self.run_paged(id, statement, row, 1, cancel, schema, console, false).await
}
/// Closes the cursor that reads the pages of `statement` on `id` (its result tab was closed).
pub fn release_result(&self, id: &str, statement: &str, schema: Option<&str>) {
self.cursors.release(&conn::CursorKey::new(id, statement, schema));
self.release_console_result(id, statement, schema, None);
}
pub fn release_console_result(
&self,
id: &str,
statement: &str,
schema: Option<&str>,
console: Option<ConsoleId<'_>>,
) {
self.cursors.release(&conn::CursorKey::new(id, statement, schema).with_console(console));
}
fn remember_statement(&self, id: &str, statement: &str) {
@@ -1662,6 +1763,17 @@ impl DbManager {
statement: &str,
cancel: &CancellationToken,
schema: Option<&str>,
) -> IdeResult<Vec<PlanNode>> {
self.explain_in_console(id, statement, cancel, schema, None).await
}
pub async fn explain_in_console(
&self,
id: &str,
statement: &str,
cancel: &CancellationToken,
schema: Option<&str>,
console: Option<ConsoleId<'_>>,
) -> IdeResult<Vec<PlanNode>> {
let driver = self.pool(id).await?.driver();
if driver == DbDriver::Jdbc {
@@ -1684,18 +1796,21 @@ impl DbManager {
MAX_META_ROWS,
cancel,
schema,
None,
)
.await?;
let result = self.run(id, &plan::oracle_plan_query(&plan_id), 0, MAX_META_ROWS, cancel, None).await?;
let result = self.run(id, &plan::oracle_plan_query(&plan_id), 0, MAX_META_ROWS, cancel, None, None).await?;
let nodes = plan::parse(driver, &result);
let _ = self.run(id, &plan::oracle_plan_cleanup(&plan_id), 0, 0, cancel, None).await;
let _ = self.run(id, &plan::oracle_plan_cleanup(&plan_id), 0, 0, cancel, None, None).await;
return nodes;
}
let result =
self.run(id, &plan::explain_statement(driver, statement), 0, MAX_META_ROWS, cancel, schema).await?;
let result = self
.run(id, &plan::explain_statement(driver, statement), 0, MAX_META_ROWS, cancel, schema, console)
.await?;
plan::parse(driver, &result)
}
#[allow(clippy::too_many_arguments)]
async fn run(
&self,
id: &str,
@@ -1704,8 +1819,9 @@ impl DbManager {
max_rows: usize,
cancel: &CancellationToken,
schema: Option<&str>,
console: Option<ConsoleId<'_>>,
) -> IdeResult<QueryResult> {
self.run_paged(id, statement, skip, max_rows, cancel, schema, true).await
self.run_paged(id, statement, skip, max_rows, cancel, schema, console, true).await
}
/// `paging`: whether the page may continue a cursor of `statement` (see `conn::cursor`).
@@ -1718,13 +1834,31 @@ impl DbManager {
max_rows: usize,
cancel: &CancellationToken,
schema: Option<&str>,
console: Option<ConsoleId<'_>>,
paging: bool,
) -> IdeResult<QueryResult> {
let pool = self.pool(id).await?;
let connection = self.connection(id).await?;
let pool = connection.pool;
let expected_manual = console.and_then(|console| console.expected_manual);
if expected_manual.is_some() && !matches!(&*pool, Pool::Postgres(_)) {
return Err(postgres_console_mode_changed());
}
if let Pool::Jdbc(p) = &*pool {
return p.query_in_schema(statement, skip, max_rows, cancel, schema).await;
return p.query_in_console(statement, skip, max_rows, cancel, schema, console).await;
}
if let Pool::Clickhouse(p) = &*pool
&& console.is_some()
{
return p.execute_in_console(statement, skip, max_rows, cancel, console).await;
}
let console = console.filter(|_| matches!(&*pool, Pool::Postgres(_)));
let session = match console {
Some(console) => connection.console_transactions.session(console),
None => self.sessions.lock().get(id).cloned(),
};
if expected_manual.is_some_and(|manual| manual != session.is_some()) {
return Err(postgres_console_mode_changed());
}
let session = self.sessions.lock().get(id).cloned();
let protected = pool.transaction_read_only();
let cursor = protected || conn::cursor_statement(statement);
if !cursor || (protected && skip == 0 && paging) {
@@ -1732,7 +1866,7 @@ impl DbManager {
self.cursors.release_target(id);
}
if paging && session.is_none() && (skip > 0 || protected) && pool.keeps_cursors() && cursor {
let key = conn::CursorKey::new(id, statement, schema);
let key = conn::CursorKey::new(id, statement, schema).with_console(console);
let started = std::time::Instant::now();
let page = match self.cursors.resume(&key, skip, max_rows, cancel, protected).await {
Some(page) => page,
@@ -1768,44 +1902,9 @@ impl DbManager {
if pool.driver() == DbDriver::Clickhouse {
return Err(IdeError::invalid("ClickHouse manual transactions are unsupported"));
}
let mut held = session.lock().await;
if pool.transaction_read_only() {
// Own the session during awaits so a dropped request cannot return an unfinished transaction.
let mut conn = match held.take() {
Some(conn) => conn,
None => {
let mut conn = Held::acquire(&pool).await?;
conn.begin_manual(pool.driver()).await?;
conn
}
};
let result = async {
conn.apply_context(schema).await?;
conn.execute_from(&pool, statement, skip, max_rows, cancel).await
}
.await;
if result.is_ok() {
*held = Some(conn);
} else if cancel.is_cancelled() || conn.finish_manual(false).await.is_err() {
conn.discard().await;
}
return result;
}
if held.is_none() {
let mut conn = Held::acquire(&pool).await?;
conn.apply_context(schema).await?;
conn.begin_manual(pool.driver()).await?;
*held = Some(conn);
}
let conn = held.as_mut().expect("opened above");
conn.apply_context(schema).await?;
let r = conn.execute_from(&pool, statement, skip, max_rows, cancel).await;
if cancel.is_cancelled() {
// The server rolls the transaction back with the connection.
held.take().expect("opened above").discard().await;
return Err(IdeError::cancelled());
}
r
session
.execute(&pool, &connection.console_transactions.capacity, statement, skip, max_rows, cancel, schema)
.await
}
/// Switches `id` between auto-commit and manual commit. Leaving manual
@@ -1838,23 +1937,37 @@ impl DbManager {
}
let session = self.sessions.lock().get(id).cloned();
let Some(session) = session else { return Ok(()) };
let mut held = session.lock().await;
let Some(mut conn) = held.take() else { return Ok(()) };
if let Err(e) = conn.finish_manual(commit).await {
// Discarding a Snowflake connection doesn't end its session, which the data source's
// other targets share: the transaction stays open, so it stays held to be ended again.
if matches!(conn, conn::Held::Snowflake(..)) {
*held = Some(conn);
} else {
conn.discard().await;
session.finish(commit).await
}
/// Changes manual-commit mode for one PostgreSQL console. Returns whether it opened a new mode entry.
pub async fn set_postgres_console_manual(&self, id: &str, console: ConsoleId<'_>, manual: bool) -> IdeResult<bool> {
if self.source(id)?.driver != DbDriver::Postgres {
return Err(IdeError::invalid("Scoped manual transactions require a PostgreSQL data source"));
}
if manual {
self.connection(id).await?.console_transactions.enable(console)
} else {
if let Some(connection) = self.opened_connection(id) {
connection.console_transactions.release(console).await?;
}
return Err(e);
Ok(false)
}
if let Err(e) = conn.restore_default().await {
conn.discard().await;
return Err(e);
}
/// Commits or rolls back work held by this PostgreSQL console.
pub async fn finish_postgres_console_transaction(
&self,
id: &str,
console: ConsoleId<'_>,
commit: bool,
) -> IdeResult<()> {
let session =
self.opened_connection(id).and_then(|connection| connection.console_transactions.session(console));
match session {
Some(session) => session.finish(commit).await,
None => Err(postgres_console_mode_changed()),
}
Ok(())
}
#[allow(clippy::too_many_arguments)]
+202
Переглянути файл
@@ -0,0 +1,202 @@
use crate::{ConsoleId, Held, Pool, QueryResult};
use ide_core::{CancellationToken, IdeError, IdeResult};
use parking_lot::Mutex;
use std::collections::HashMap;
use std::sync::Arc;
use tokio::sync::{Mutex as AsyncMutex, OwnedSemaphorePermit, Semaphore};
pub(super) type Session = Arc<ManualSession>;
type ConsoleKey = (String, String);
struct Transaction {
connection: Held,
_permit: Option<OwnedSemaphorePermit>,
}
impl Transaction {
async fn acquire(pool: &Pool, capacity: &Arc<Semaphore>) -> IdeResult<Self> {
let permit = if matches!(pool, Pool::Postgres(_)) {
Some(capacity.clone().try_acquire_owned().map_err(|_| {
IdeError::unavailable("PostgreSQL manual transactions are using the available slots. Commit or roll back an open transaction.")
})?)
} else {
None
};
Ok(Self { connection: Held::acquire(pool).await?, _permit: permit })
}
}
#[derive(Default)]
pub(super) struct ManualSession {
transaction: AsyncMutex<Option<Transaction>>,
retired: CancellationToken,
}
impl ManualSession {
#[allow(clippy::too_many_arguments)]
pub(super) async fn execute(
&self,
pool: &Pool,
capacity: &Arc<Semaphore>,
statement: &str,
skip: usize,
max_rows: usize,
request: &CancellationToken,
schema: Option<&str>,
) -> IdeResult<QueryResult> {
let cancel = self.retired.child_token();
let mut held = tokio::select! {
biased;
() = request.cancelled() => return Err(IdeError::cancelled()),
() = cancel.cancelled() => return Err(IdeError::cancelled()),
held = self.transaction.lock() => held,
};
let execute = async {
if pool.transaction_read_only() {
// Own the connection while applying the guard so a dropped call cannot return an open transaction.
let mut tx = match held.take() {
Some(tx) => tx,
None => {
let mut tx = Transaction::acquire(pool, capacity).await?;
tx.connection.begin_manual(pool.driver()).await?;
tx
}
};
let result = async {
tx.connection.apply_context(schema).await?;
tx.connection.execute_from(pool, statement, skip, max_rows, &cancel).await
}
.await;
if result.is_ok() {
*held = Some(tx);
} else if cancel.is_cancelled() || tx.connection.finish_manual(false).await.is_err() {
tx.connection.discard().await;
}
return result;
}
if held.is_none() {
let mut tx = Transaction::acquire(pool, capacity).await?;
tx.connection.apply_context(schema).await?;
tx.connection.begin_manual(pool.driver()).await?;
*held = Some(tx);
}
let conn = &mut held.as_mut().expect("opened above").connection;
conn.apply_context(schema).await?;
let result = conn.execute_from(pool, statement, skip, max_rows, &cancel).await;
if cancel.is_cancelled() {
held.take().expect("opened above").connection.discard().await;
return Err(IdeError::cancelled());
}
result
};
tokio::pin!(execute);
tokio::select! {
biased;
() = request.cancelled() => {
cancel.cancel();
execute.await
}
result = &mut execute => result,
}
}
pub(super) async fn finish(&self, commit: bool) -> IdeResult<()> {
let mut held = self.transaction.lock().await;
if commit && self.retired.is_cancelled() {
return Err(IdeError::cancelled());
}
let Some(mut tx) = held.take() else { return Ok(()) };
if let Err(error) = tx.connection.finish_manual(commit).await {
// Snowflake targets share the same server session, so keep the failed transaction to be ended again.
if matches!(tx.connection, Held::Snowflake(..)) {
*held = Some(tx);
} else {
tx.connection.discard().await;
}
return Err(error);
}
if let Err(error) = tx.connection.restore_default().await {
tx.connection.discard().await;
return Err(error);
}
Ok(())
}
pub(super) async fn rollback_and_release(&self) -> IdeResult<()> {
let transaction = self.transaction.lock().await.take();
let Some(mut tx) = transaction else { return Ok(()) };
if let Err(error) = tx.connection.finish_manual(false).await {
tx.connection.discard().await;
return Err(error);
}
if let Err(error) = tx.connection.restore_default().await {
tx.connection.discard().await;
return Err(error);
}
Ok(())
}
async fn retire(&self) -> IdeResult<()> {
self.retired.cancel();
self.rollback_and_release().await
}
}
pub(super) struct ConsoleTransactions {
sessions: Mutex<HashMap<ConsoleKey, Session>>,
closed: CancellationToken,
/// The four-slot pool also serves ordinary work and one retained result cursor.
pub(super) capacity: Arc<Semaphore>,
}
impl Default for ConsoleTransactions {
fn default() -> Self {
Self { sessions: Mutex::default(), closed: CancellationToken::new(), capacity: Arc::new(Semaphore::new(2)) }
}
}
fn key(console: ConsoleId<'_>) -> ConsoleKey {
(console.window.to_owned(), console.path.to_owned())
}
impl ConsoleTransactions {
pub(super) fn session(&self, console: ConsoleId<'_>) -> Option<Session> {
self.sessions.lock().get(&key(console)).cloned()
}
pub(super) fn enable(&self, console: ConsoleId<'_>) -> IdeResult<bool> {
let mut sessions = self.sessions.lock();
if self.closed.is_cancelled() {
return Err(IdeError::cancelled());
}
match sessions.entry(key(console)) {
std::collections::hash_map::Entry::Occupied(_) => Ok(false),
std::collections::hash_map::Entry::Vacant(entry) => {
entry.insert(Session::default());
Ok(true)
}
}
}
pub(super) async fn release(&self, console: ConsoleId<'_>) -> IdeResult<()> {
let session = self.sessions.lock().remove(&key(console));
if let Some(session) = session {
session.retire().await?;
}
Ok(())
}
pub(super) async fn close(&self) {
let sessions = {
let mut sessions = self.sessions.lock();
self.closed.cancel();
std::mem::take(&mut *sessions)
};
for session in sessions.values() {
session.retired.cancel();
}
for session in sessions.into_values() {
let _ = session.rollback_and_release().await;
}
}
}
+38 -1
Переглянути файл
@@ -55,6 +55,7 @@ pub(super) type Routes = Mutex<HashMap<String, CachedRoute>>;
#[derive(Clone)]
pub(super) struct Connection {
pub(super) pool: Arc<Pool>,
pub(super) console_transactions: Arc<crate::manual_session::ConsoleTransactions>,
route: Option<RouteSlot>,
}
@@ -211,7 +212,7 @@ impl DbManager {
if let Some(secs) = source.options.keep_alive_secs.filter(|s| *s > 0) {
keep_alive(&pool, Duration::from_secs(secs.into()));
}
Ok(Connection { pool, route })
Ok(Connection { pool, route, console_transactions: Default::default() })
}
async fn close_target(&self, id: &str, slot: Arc<ConnectionSlot>) {
@@ -223,10 +224,46 @@ impl DbManager {
}
self.cursors.release_target(id);
if let Some(c) = slot.value.get() {
c.console_transactions.close().await;
c.pool.close().await;
}
}
pub(super) fn opened_connection(&self, id: &str) -> Option<Connection> {
self.pools.lock().get(id).and_then(|slot| slot.value.get()).cloned()
}
/// Retires a closed editor's sessions without opening any data sources.
pub async fn release_console(&self, console: crate::ConsoleId<'_>) -> IdeResult<()> {
self.release_target_console(console, None).await
}
pub async fn release_target_console(&self, console: crate::ConsoleId<'_>, target: Option<&str>) -> IdeResult<()> {
self.cursors.release_console(console, target);
let connections: Vec<_> = self
.pools
.lock()
.iter()
.filter(|(id, _)| target.is_none_or(|target| id.as_str() == target))
.filter_map(|(_, slot)| slot.value.get().cloned())
.collect();
let mut result = Ok(());
for connection in connections {
let released = match &*connection.pool {
Pool::Clickhouse(pool) => {
pool.release_console(console);
Ok(())
}
Pool::Jdbc(pool) => pool.release_console(console).await,
_ => connection.console_transactions.release(console).await,
};
if let Err(error) = released {
result = Err(error);
}
}
result
}
pub async fn disconnect(&self, id: &str) {
let slot = self.pools.lock().remove(id);
if let Some(slot) = slot {
+59 -1
Переглянути файл
@@ -26,6 +26,49 @@ enum State {
BlockComment,
}
// Starts just after the opening `/*`. ClickHouse supports nested block comments.
fn after_clickhouse_block_comment(mut text: &str) -> &str {
let mut depth = 1usize;
while let Some(at) = text.find(['/', '*']) {
text = &text[at..];
if let Some(rest) = text.strip_prefix("/*") {
text = rest;
depth += 1;
} else if let Some(rest) = text.strip_prefix("*/") {
text = rest;
depth -= 1;
if depth == 0 {
return text;
}
} else {
text = &text[1..];
}
}
""
}
/// Consume an unquoted leading word, leaving quoted identifiers and SQL literals alone.
pub(super) fn clickhouse_keyword<'a>(sql: &mut &'a str) -> Option<&'a str> {
let mut text = *sql;
loop {
text = text.trim_start_matches(|ch: char| ch.is_whitespace() || ch == '\u{feff}');
if let Some(comment) = text.strip_prefix('#').or_else(|| text.strip_prefix("--")) {
text = comment.split_once('\n').map_or("", |(_, rest)| rest);
} else if let Some(comment) = text.strip_prefix("/*") {
text = after_clickhouse_block_comment(comment);
} else {
break;
}
}
let end = text.find(|ch: char| !ch.is_ascii_alphanumeric() && ch != '_').unwrap_or(text.len());
if end == 0 {
return None;
}
let (keyword, rest) = text.split_at(end);
*sql = rest;
Some(keyword)
}
/// Every statement of `text` that contains more than whitespace and comments.
pub fn split(text: &str, driver: DbDriver) -> Vec<SqlStatement> {
let mysql = driver == DbDriver::Mysql;
@@ -134,6 +177,12 @@ pub fn split(text: &str, driver: DbDriver) -> Vec<SqlStatement> {
has_code = true;
}
'/' if next == Some('*') => {
if clickhouse {
let rest = after_clickhouse_block_comment(&text[byte_at(i + 2)..]);
let end = text.len() - rest.len();
i = chars.partition_point(|&(offset, _)| offset < end);
continue;
}
state = State::BlockComment;
i += 1;
}
@@ -154,7 +203,7 @@ pub fn split(text: &str, driver: DbDriver) -> Vec<SqlStatement> {
state = State::LineComment;
i += 1;
}
'#' if mysql => state = State::LineComment,
'#' if mysql || clickhouse => state = State::LineComment,
// The `//` of `file://…` (PUT, GET) or another URL is not a comment.
'/' if snowflake && next == Some('/') && chars[..i].last().is_some_and(|&(_, c)| c == ':') => {
has_code = true;
@@ -416,6 +465,15 @@ fn utf16_slice(text: &str, from: u32, to: u32) -> &str {
mod tests {
use super::*;
#[test]
fn clickhouse_session_settings_split_after_comments_and_quoted_values() {
let set = "# leading ;\n/* outer /* nested ; */ tail ; */ SET log_comment='a;b', max_threads=1";
let query = "SELECT getSetting('log_comment')";
let script = format!("{set}; {query};");
let statements: Vec<_> = split(&script, DbDriver::Clickhouse).into_iter().map(|item| item.text).collect();
assert_eq!(statements, [set, query]);
}
fn texts(sql: &str, d: DbDriver) -> Vec<String> {
split(sql, d).into_iter().map(|s| s.text).collect()
}
+14 -6
Переглянути файл
@@ -236,7 +236,8 @@ pub fn table_comment(driver: DbDriver, schema: &str, table: &str) -> Option<Stri
}
}
/// Rows: `index name, unique (0/1), column` (one row per indexed column, in order).
/// Rows: `index name, unique (0/1), column, key` (one row per indexed column, in order); `key` is
/// `p` for the primary key's index, `u` for a unique constraint's, NULL otherwise (ClickHouse: absent).
// Key columns are paired from one series up to `max_index_keys` (the server's INDEX_MAX_KEYS, the
// most columns an index or key has): unlike a series per catalog row, it lets the planner find the
// table's rows through the catalog's index first.
@@ -251,11 +252,14 @@ pub fn indexes(driver: DbDriver, schema: &str, table: &str) -> String {
WHERE database = {s} AND table = {t}) ORDER BY index_name"
),
DbDriver::Sqlite => format!(
"SELECT il.name, il.\"unique\", ii.name FROM pragma_index_list({t}, {s}) il \
"SELECT il.name, il.\"unique\", ii.name, CASE il.origin WHEN 'pk' THEN 'p' WHEN 'u' THEN 'u' END \
FROM pragma_index_list({t}, {s}) il \
JOIN pragma_index_info(il.name, {s}) ii ORDER BY il.name, ii.seqno"
),
DbDriver::Postgres => format!(
"SELECT i.relname, CASE WHEN ix.indisunique THEN 1 ELSE 0 END, a.attname \
"SELECT i.relname, CASE WHEN ix.indisunique THEN 1 ELSE 0 END, a.attname, \
CASE WHEN ix.indisprimary THEN 'p' WHEN EXISTS (SELECT 1 FROM pg_constraint con \
WHERE con.conindid = ix.indexrelid AND con.conrelid = ix.indrelid AND con.contype = 'u') THEN 'u' END \
FROM pg_index ix JOIN pg_class t ON t.oid = ix.indrelid JOIN pg_class i ON i.oid = ix.indexrelid \
JOIN pg_namespace n ON n.oid = t.relnamespace \
JOIN generate_series(0, current_setting('max_index_keys')::int - 1) AS k(ord) ON k.ord < ix.indnatts \
@@ -263,12 +267,14 @@ pub fn indexes(driver: DbDriver, schema: &str, table: &str) -> String {
WHERE n.nspname = {s} AND t.relname = {t} ORDER BY i.relname, k.ord"
),
DbDriver::Mysql => format!(
"SELECT index_name, CASE WHEN non_unique = 0 THEN 1 ELSE 0 END, column_name \
"SELECT index_name, CASE WHEN non_unique = 0 THEN 1 ELSE 0 END, column_name, \
CASE WHEN index_name = 'PRIMARY' THEN 'p' WHEN non_unique = 0 THEN 'u' END \
FROM information_schema.statistics WHERE table_schema = {s} AND table_name = {t} \
ORDER BY index_name, seq_in_index"
),
DbDriver::SqlServer => format!(
"SELECT i.name, CASE WHEN i.is_unique = 1 THEN 1 ELSE 0 END, c.name \
"SELECT i.name, CASE WHEN i.is_unique = 1 THEN 1 ELSE 0 END, c.name, \
CASE WHEN i.is_primary_key = 1 THEN 'p' WHEN i.is_unique_constraint = 1 THEN 'u' END \
FROM sys.indexes i JOIN sys.index_columns ic ON ic.object_id = i.object_id AND ic.index_id = i.index_id \
JOIN sys.columns c ON c.object_id = ic.object_id AND c.column_id = ic.column_id \
WHERE OBJECT_SCHEMA_NAME(i.object_id) = {s} AND OBJECT_NAME(i.object_id) = {t} AND i.name IS NOT NULL \
@@ -276,7 +282,9 @@ pub fn indexes(driver: DbDriver, schema: &str, table: &str) -> String {
),
DbDriver::Snowflake => "SELECT '', 0, '' WHERE 1 = 0".to_owned(),
DbDriver::Oracle => format!(
"SELECT i.index_name, CASE WHEN i.uniqueness = 'UNIQUE' THEN 1 ELSE 0 END, ic.column_name \
"SELECT i.index_name, CASE WHEN i.uniqueness = 'UNIQUE' THEN 1 ELSE 0 END, ic.column_name, \
(SELECT MIN(LOWER(con.constraint_type)) FROM all_constraints con WHERE con.owner = i.table_owner \
AND con.table_name = i.table_name AND con.index_name = i.index_name AND con.constraint_type IN ('P', 'U')) \
FROM all_indexes i JOIN all_ind_columns ic \
ON ic.index_owner = i.owner AND ic.index_name = i.index_name \
WHERE i.owner = {s} AND i.table_name = {t} ORDER BY i.index_name, ic.column_position"
+91 -1
Переглянути файл
@@ -1,5 +1,5 @@
use ide_core::{CancellationToken, IdeError, IdeResult};
use ide_db::{CellValue, DataSource, DbDriver, DbManager, DbRowEdit, DbSslMode, SortKey, sql};
use ide_db::{CellValue, ConsoleId, DataSource, DbDriver, DbManager, DbRowEdit, DbSslMode, SortKey, sql};
use std::sync::Arc;
use std::time::{SystemTime, UNIX_EPOCH};
@@ -134,3 +134,93 @@ async fn clickhouse_cloud_manager_catalogs_and_session_table() -> IdeResult<()>
cleanup?;
Ok(())
}
#[tokio::test]
#[ignore = "requires a disposable loopback ClickHouse console fixture"]
async fn clickhouse_named_console_sessions_run_concurrently_and_preserve_state() -> IdeResult<()> {
use std::time::Duration;
let port = std::env::var("CLICKHOUSE_CONSOLE_TEST_PORT")
.expect("set the disposable loopback console fixture's port")
.parse()
.expect("numeric console fixture port");
let password = std::env::var("CLICKHOUSE_CONSOLE_TEST_PASSWORD").expect("set the console fixture password");
let tmp = tempfile::tempdir()?;
let root = tmp.path().to_path_buf();
let ssh = Arc::new(ide_ssh::SshManager::new(root.join("ssh-passwords.json")));
let db = DbManager::new(root.clone(), root.join("passwords.json"), root.join("history.json"), ssh);
let source = DataSource {
id: "clickhouse".into(),
name: "ClickHouse console fixture".into(),
driver: DbDriver::Clickhouse,
host: "127.0.0.1".into(),
port: Some(port),
user: "console_fixture".into(),
database: "default".into(),
..Default::default()
};
let observer = DataSource { id: "observer".into(), ..source.clone() };
db.save_sources(vec![source, observer]).await?;
for id in ["clickhouse", "observer"] {
db.set_password(id, Some(password.clone()), false).await?;
db.execute(id, "SELECT 1", 1, &CancellationToken::new()).await?;
}
let a = ConsoleId::new("window-a", "/console.sql");
let b = ConsoleId::new("window-a", "/console_1.sql");
let other_window = ConsoleId::new("window-b", "/console.sql");
let idle = CancellationToken::new();
let run = |console, sql, cancel| db.execute_in_console("clickhouse", sql, 0, 1, cancel, None, Some(console));
run(b, "SELECT 1", &idle).await?;
run(a, "SET max_threads = 2", &idle).await?;
run(a, "CREATE TEMPORARY TABLE console_state (id UInt8)", &idle).await?;
run(a, "INSERT INTO console_state VALUES (17)", &idle).await?;
let cancel = CancellationToken::new();
let long_sql = "SELECT sum(sleepEachRow(1)) FROM numbers(12) SETTINGS max_block_size=1";
let running = run(a, long_sql, &cancel);
let other = async {
let checked = tokio::time::timeout(Duration::from_secs(4), async {
loop {
let observed = db
.execute(
"observer",
"SELECT count() FROM system.processes WHERE startsWith(query, 'SELECT sum(sleepEachRow(1))')",
1,
&idle,
)
.await?;
if observed.rows[0][0].as_deref() == Some("1") {
break;
}
tokio::time::sleep(Duration::from_millis(30)).await;
}
run(b, "SELECT 2", &idle).await
})
.await;
cancel.cancel();
checked.map_err(|_| IdeError::invalid("console B did not complete while console A was active"))?
};
let (cancelled, other) = tokio::time::timeout(Duration::from_secs(17), async { tokio::join!(running, other) })
.await
.expect("console queries and cancellation should drain");
assert_eq!(other?.rows, vec![vec![Some("2".into())]]);
assert_eq!(cancelled.unwrap_err().kind, ide_core::error::ErrorKind::Cancelled);
let first = run(a, "SELECT getSetting('max_threads'), id FROM console_state", &idle).await?;
assert_eq!(first.rows, vec![vec![Some("2".into()), Some("17".into())]]);
for console in [b, other_window] {
let second = run(console, "SELECT id FROM console_state", &idle).await;
assert!(second.is_err_and(|error| error.message.contains("UNKNOWN_TABLE")));
}
run(b, "CREATE TEMPORARY TABLE console_state (id UInt8)", &idle).await?;
db.release_console(a).await?;
let reopened = run(a, "SELECT id FROM console_state", &idle).await;
assert!(reopened.is_err_and(|error| error.message.contains("UNKNOWN_TABLE")));
assert!(run(b, "SELECT id FROM console_state", &idle).await?.rows.is_empty());
db.disconnect_source("clickhouse").await;
let reset = run(b, "SELECT id FROM console_state", &idle).await;
assert!(reset.is_err_and(|error| error.message.contains("UNKNOWN_TABLE")));
Ok(())
}
+155 -4
Переглянути файл
@@ -1,5 +1,5 @@
use ide_core::{CancellationToken, IdeResult};
use ide_db::{DataSource, DbDriver, DbJdbcDriver, DbManager, DbProperty, SortKey};
use ide_db::{ConsoleId, DataSource, DbDriver, DbJdbcDriver, DbManager, DbProperty, SortKey};
use std::{path::Path, sync::Arc};
fn manager(dir: &Path) -> DbManager {
@@ -208,9 +208,11 @@ async fn duckdb_named_file_enforces_read_only_at_open() -> IdeResult<()> {
reopened.save_sources(vec![source.clone()]).await?;
assert_eq!(reopened.source("test")?.vendor, "duckdb");
assert_eq!(reopened.execute("test", "select id from items", 1, &cancel).await?.rows, [vec![Some("1".into())]]);
for query in ["insert into items values (2)", "create table added (id int)"] {
let err = reopened.execute("test", query, 1, &cancel).await.unwrap_err();
assert!(err.message.to_lowercase().contains("read-only"), "{}", err.message);
for console in [None, Some(ConsoleId::new("window", "/reader.sql"))] {
for query in ["insert into items values (2)", "create table added (id int)"] {
let err = reopened.execute_in_console("test", query, 0, 1, &cancel, None, console).await.unwrap_err();
assert!(err.message.to_lowercase().contains("read-only"), "{}", err.message);
}
}
assert!(!reopened.tables("test", "main").await?.iter().any(|table| table.name == "added"));
reopened.disconnect("test").await;
@@ -259,6 +261,89 @@ async fn duckdb_named_memory_lives_until_disconnect() -> IdeResult<()> {
Ok(())
}
#[tokio::test]
#[ignore = "requires DUCKDB_JDBC_JAR and a local Java 17+ runtime"]
async fn duckdb_consoles_share_catalog_but_isolate_transactions_and_temporary_tables() -> IdeResult<()> {
let tmp = tempfile::tempdir()?;
let db = manager(tmp.path());
register_duckdb(&db, Some("duckdb"))?;
db.save_sources(vec![DataSource {
id: "test".into(),
name: "DuckDB in memory".into(),
driver: DbDriver::Jdbc,
vendor: "duckdb".into(),
global: true,
jdbc_driver: "duck".into(),
url: "jdbc:duckdb:".into(),
..Default::default()
}])
.await?;
let cancel = CancellationToken::new();
let a = ConsoleId::new("first", "/console.sql");
let b = ConsoleId::new("second", "/console.sql");
let run = |console, sql: &'static str| db.execute_in_console("test", sql, 0, 10, &cancel, None, Some(console));
db.execute("test", "CREATE TABLE durable (id INTEGER)", 1, &cancel).await?;
run(a, "CREATE TEMP TABLE local_only AS SELECT 7 AS id").await?;
assert!(run(b, "SELECT id FROM local_only").await.is_err(), "B must not see A's temporary table");
run(b, "CREATE TEMP TABLE local_only AS SELECT 9 AS id").await?;
assert_eq!(run(a, "SELECT id FROM local_only").await?.rows, [vec![Some("7".into())]]);
run(a, "BEGIN TRANSACTION").await?;
run(a, "INSERT INTO durable VALUES (1)").await?;
assert_eq!(run(a, "SELECT id FROM durable").await?.rows, [vec![Some("1".into())]]);
assert!(run(b, "SELECT id FROM durable").await?.rows.is_empty());
db.release_target_console(a, Some("test")).await?;
assert_eq!(run(b, "SELECT id FROM local_only").await?.rows, [vec![Some("9".into())]]);
assert!(run(a, "SELECT id FROM local_only").await.is_err(), "a reopened console starts a fresh session");
assert!(run(a, "SELECT id FROM durable").await?.rows.is_empty(), "closing A rolls back its transaction");
db.disconnect("test").await;
Ok(())
}
#[tokio::test]
#[ignore = "requires SQLITE_JDBC_CLASSPATH, H2_JDBC_JAR and a local Java 17+ runtime"]
async fn anonymous_jdbc_databases_stay_shared_across_consoles() -> IdeResult<()> {
let sqlite = std::env::split_paths(&std::env::var_os("SQLITE_JDBC_CLASSPATH").expect("SQLITE_JDBC_CLASSPATH"))
.map(|p| p.display().to_string())
.collect();
let h2 = vec![std::env::var("H2_JDBC_JAR").expect("H2_JDBC_JAR")];
for (class_name, jars, url) in
[("org.sqlite.JDBC", sqlite, "jdbc:sqlite::memory:"), ("org.h2.Driver", h2, "jdbc:h2:mem:;DB_CLOSE_DELAY=-1")]
{
let tmp = tempfile::tempdir()?;
let db = manager(tmp.path());
db.save_jdbc_driver(DbJdbcDriver {
id: "private".into(),
class_name: class_name.into(),
name: class_name.into(),
vendor: None,
jars,
url_template: String::new(),
})?;
db.save_sources(vec![DataSource {
id: "test".into(),
name: "Anonymous memory".into(),
driver: DbDriver::Jdbc,
global: true,
jdbc_driver: "private".into(),
url: url.into(),
..Default::default()
}])
.await?;
let cancel = CancellationToken::new();
let a = ConsoleId::new("window", "/a.sql");
let b = ConsoleId::new("window", "/b.sql");
let run = |console, sql: &'static str| db.execute_in_console("test", sql, 0, 1, &cancel, None, Some(console));
db.execute("test", "CREATE TABLE preserved (id INTEGER)", 1, &cancel).await?;
run(a, "INSERT INTO preserved VALUES (1)").await?;
db.release_target_console(a, Some("test")).await?;
assert_eq!(run(b, "SELECT id FROM preserved").await?.rows, [vec![Some("1".into())]]);
db.disconnect("test").await;
}
Ok(())
}
#[tokio::test]
#[ignore = "requires CLICKHOUSE_JDBC_CLASSPATH and a loopback ClickHouse fixture on CLICKHOUSE_JDBC_TEST_PORT"]
async fn clickhouse_vendor_driver_reads_catalog_and_results() -> IdeResult<()> {
@@ -363,6 +448,72 @@ async fn unresponsive_driver_closes_before_reconnect() -> IdeResult<()> {
Ok(())
}
#[tokio::test]
#[ignore = "requires JDBC_FIXTURE_JAR (java/jdbc-bridge/build.py --test --out fixture.jar) and Java 17+"]
async fn unresponsive_console_cancellation_keeps_other_jdbc_connections() -> IdeResult<()> {
use std::time::Duration;
let tmp = tempfile::tempdir()?;
let db = manager(tmp.path());
let started = tmp.path().join("started");
db.save_jdbc_driver(DbJdbcDriver {
id: "fixture".into(),
name: "Fixture".into(),
vendor: None,
jars: vec![std::env::var("JDBC_FIXTURE_JAR").unwrap()],
class_name: "ai.openidea.jdbc.SelfTest$Fixture".into(),
url_template: String::new(),
})?;
db.save_sources(vec![DataSource {
id: "test".into(),
name: "Fixture".into(),
driver: DbDriver::Jdbc,
global: true,
jdbc_driver: "fixture".into(),
url: format!("jdbc:fixture:{}", started.display()),
..Default::default()
}])
.await?;
let a = ConsoleId::new("window", "/a.sql");
let b = ConsoleId::new("window", "/b.sql");
let stop = CancellationToken::new();
let normal = CancellationToken::new();
let (ran_a, sibling) = tokio::time::timeout(Duration::from_secs(15), async {
tokio::join!(db.execute_in_console("test", "ignore cancel", 0, 1, &stop, None, Some(a)), async {
while !started.is_file() {
tokio::time::sleep(Duration::from_millis(10)).await;
}
let sibling = tokio::time::timeout(Duration::from_secs(2), async {
let b = db.execute_in_console("test", "from B", 0, 1, &normal, None, Some(b)).await?;
let service = db.execute("test", "service", 1, &normal).await?;
Ok::<_, ide_core::IdeError>((b.affected, service.affected))
})
.await;
stop.cancel();
sibling
})
})
.await
.expect("cancellation must remain bounded");
assert_eq!(sibling.expect("B and service can finish while A is executing")?, (Some(1.0), Some(1.0)));
assert!(ran_a.unwrap_err().message.contains("Cancellation timed out"));
assert_eq!(db.connected(), ["test"]);
// The fixture's update count is cumulative within a physical connection.
assert_eq!(db.execute_in_console("test", "still B", 0, 1, &normal, None, Some(b)).await?.affected, Some(2.0));
assert_eq!(db.execute_in_console("test", "new session A", 0, 1, &normal, None, Some(a)).await?.affected, Some(1.0));
assert!(db.execute("test", "drop", 1, &normal).await.unwrap_err().message.contains("connection reset"));
assert!(db.is_connected("test"), "a lost service connection must not retire the console sessions");
assert_eq!(
db.execute_in_console("test", "B after service failure", 0, 1, &normal, None, Some(b)).await?.affected,
Some(3.0)
);
db.release_target_console(a, Some("test")).await?;
db.release_target_console(b, Some("test")).await?;
assert!(!db.is_connected("test"), "the failed service pool can be re-established after the last console");
assert_eq!(db.execute("test", "new service session", 1, &normal).await?.affected, Some(1.0));
db.disconnect("test").await;
Ok(())
}
#[tokio::test]
#[ignore = "requires JDBC_FIXTURE_JAR (java/jdbc-bridge/build.py --test --out fixture.jar) and Java 17+"]
async fn a_lost_session_reconnects_on_the_next_statement() -> IdeResult<()> {
+122
Переглянути файл
@@ -0,0 +1,122 @@
use ide_core::{CancellationToken, IdeResult, error::ErrorKind};
use ide_db::{ConsoleId, DataSource, DbDriver, DbManager, QueryResult};
use std::sync::Arc;
use std::time::Duration;
const TARGET: &str = "fixture";
const A: ConsoleId<'static> = ConsoleId::new("main", "a.sql");
const B: ConsoleId<'static> = ConsoleId::new("main", "b.sql");
const C: ConsoleId<'static> = ConsoleId::new("other", "a.sql");
async fn run(db: &DbManager, console: ConsoleId<'_>, sql: &str, token: &CancellationToken) -> IdeResult<QueryResult> {
db.execute_in_console(TARGET, sql, 0, 10, token, Some("public"), Some(console)).await
}
#[tokio::test]
#[ignore = "requires a disposable local PostgreSQL fixture with OPENIDEA_PG_CONSOLE_PORT and console_fixture db/user"]
async fn console_transactions_have_independent_commit_stop_and_release() -> IdeResult<()> {
let dir = tempfile::tempdir()?;
let root = dir.path();
let ssh = Arc::new(ide_ssh::SshManager::new(root.join("ssh-passwords.json")));
let db = DbManager::new(root.into(), root.join("passwords.json"), root.join("history.json"), ssh);
db.save_sources(vec![DataSource {
id: TARGET.into(),
name: "Local PostgreSQL".into(),
driver: DbDriver::Postgres,
host: "127.0.0.1".into(),
port: Some(std::env::var("OPENIDEA_PG_CONSOLE_PORT").expect("disposable fixture port").parse().unwrap()),
user: "console_fixture".into(),
database: "console_fixture".into(),
..Default::default()
}])
.await?;
let cancel = CancellationToken::new();
let observer = db.pool(TARGET).await?;
db.execute(TARGET, "CREATE TABLE public.console_tx (id int PRIMARY KEY)", 0, &cancel).await?;
for console in [A, B, C] {
assert!(db.set_postgres_console_manual(TARGET, console, true).await?);
assert!(!db.set_postgres_console_manual(TARGET, console, true).await?);
}
run(&db, A, "INSERT INTO public.console_tx VALUES (1)", &cancel).await?;
let status = "SELECT pg_backend_pid(), txid_current(), count(*) FROM public.console_tx";
let a = run(&db, A, status, &cancel).await?.rows;
let b = run(&db, B, status, &cancel).await?.rows;
assert_ne!(a[0][0], b[0][0]);
assert_ne!(a[0][1], b[0][1]);
assert_eq!(a[0][2].as_deref(), Some("1"));
assert_eq!(b[0][2].as_deref(), Some("0"));
let error = run(&db, C, "SELECT 1", &cancel).await.unwrap_err();
assert_eq!(error.kind, ErrorKind::Unavailable);
assert!(error.message.contains("Commit or roll back"));
let rows = "SELECT id FROM public.console_tx ORDER BY id";
assert!(observer.rows(rows, 10).await?.is_empty());
run(&db, B, "INSERT INTO public.console_tx VALUES (2)", &cancel).await?;
db.finish_postgres_console_transaction(TARGET, B, true).await?;
assert_eq!(observer.rows(rows, 10).await?, [[Some("2".into())]]);
db.release_target_console(A, Some("other-target")).await?;
let retained =
db.read_console_row(TARGET, rows, 0, &cancel, Some("public"), Some(A.expecting_manual(Some(true)))).await?;
assert_eq!(retained.rows, [[Some("1".into())]]);
let a_after_b = run(&db, A, status, &cancel).await?.rows;
assert_eq!(&a_after_b[0][..2], &a[0][..2]);
assert_eq!(a_after_b[0][2].as_deref(), Some("2"));
println!("Separate backend/transaction IDs: A {:?}, B {:?}; observer sees only B's committed row", a[0], b[0]);
run(&db, B, "INSERT INTO public.console_tx VALUES (3)", &cancel).await?;
let stop = CancellationToken::new();
let slow = "SELECT pg_sleep(8) AS scoped_manual_a";
let mut a_slow = std::pin::pin!(run(&db, A, slow, &stop));
let active = async {
loop {
let rows = observer.rows(
"SELECT pid FROM pg_stat_activity WHERE state = 'active' AND query = 'SELECT pg_sleep(8) AS scoped_manual_a'",
1,
).await?;
if !rows.is_empty() {
return IdeResult::Ok(());
}
tokio::time::sleep(Duration::from_millis(30)).await;
}
};
tokio::select! {
result = &mut a_slow => panic!("A ended before observer saw it: {result:?}"),
observed = tokio::time::timeout(Duration::from_secs(3), active) => observed.expect("A reached PostgreSQL")?,
}
let waiting = CancellationToken::new();
let still_running = async {
let (waited, ()) = tokio::join!(run(&db, A, "SELECT 1", &waiting), async {
tokio::time::sleep(Duration::from_millis(100)).await;
waiting.cancel();
});
assert_eq!(waited.unwrap_err().kind, ErrorKind::Cancelled);
let b = run(&db, B, rows, &cancel).await?;
assert_eq!(b.rows, [[Some("2".into())], [Some("3".into())]]);
IdeResult::Ok(())
};
tokio::select! {
result = &mut a_slow => panic!("A ended before B finished: {result:?}"),
result = tokio::time::timeout(Duration::from_secs(2), still_running) => result.expect("B did not wait for A")?,
}
stop.cancel();
let error = tokio::time::timeout(Duration::from_secs(4), &mut a_slow).await.expect("A stopped").unwrap_err();
assert_eq!(error.kind, ErrorKind::Cancelled);
assert_eq!(observer.rows(rows, 10).await?, [[Some("2".into())]]);
db.finish_postgres_console_transaction(TARGET, B, true).await?;
assert_eq!(observer.rows(rows, 10).await?, [[Some("2".into())], [Some("3".into())]]);
run(&db, A, "INSERT INTO public.console_tx VALUES (4)", &cancel).await?;
db.release_console(A).await?;
let stale = run(&db, A.expecting_manual(Some(true)), "INSERT INTO public.console_tx VALUES (5)", &cancel)
.await
.unwrap_err();
assert_eq!(stale.kind, ErrorKind::OutOfSync);
let stale_commit = db.finish_postgres_console_transaction(TARGET, A, true).await.unwrap_err();
assert_eq!(stale_commit.kind, ErrorKind::OutOfSync);
assert_eq!(run(&db, C, rows, &cancel).await?.rows, [[Some("2".into())], [Some("3".into())]]);
db.finish_postgres_console_transaction(TARGET, C, false).await?;
db.disconnect(TARGET).await;
println!(
"Stop A rolled back only A. B committed afterward, and releasing A rolled back its next transaction and freed a slot."
);
Ok(())
}
+2
Переглянути файл
@@ -393,6 +393,8 @@ async fn opening_a_table_reads_multi_column_keys_in_order() -> IdeResult<()> {
let details = db.table_details("p", "oi_keys", "refs").await?;
let indexes: Vec<_> = details.indexes.iter().map(|i| (i.name.as_str(), i.unique, i.columns.join(","))).collect();
assert_eq!(indexes, [("refs_pkey", true, "id".into()), ("refs_yx", true, "y,x".into())]);
let keys: Vec<_> = details.indexes.iter().map(|i| i.key).collect();
assert_eq!(keys, [Some(ide_db::DbKeyKind::Primary), None]);
let key = |k: &ide_db::ForeignKey| (k.columns.join(","), k.ref_table.clone(), k.ref_columns.join(","));
assert_eq!(
details.foreign_keys.iter().map(key).collect::<Vec<_>>(),
+29 -2
Переглянути файл
@@ -2,8 +2,8 @@
use ide_core::{CancellationToken, IdeResult};
use ide_db::{
CellValue, DataSource, DbDriver, DbManager, DbOptions, DbProperty, DbRowEdit, DbSchemaSelection, DbTableKind,
DbVisibilityChange, QueryResult, SortKey,
CellValue, DataSource, DbDriver, DbKeyKind, DbManager, DbOptions, DbProperty, DbRowEdit, DbSchemaSelection,
DbTableKind, DbVisibilityChange, QueryResult, SortKey,
};
async fn setup() -> (tempfile::TempDir, DbManager) {
@@ -47,6 +47,7 @@ async fn introspects_schemas_tables_columns_and_indexes() -> IdeResult<()> {
assert_eq!(d.indexes[0].name, "users_name");
assert!(d.indexes[0].unique);
assert_eq!(d.indexes[0].columns, vec!["name"]);
assert_eq!(d.indexes[0].key, None, "a unique index is not a constraint");
let completion = db.completion("s1").await?;
assert_eq!(completion.default_schema, "main");
let users = completion.tables.iter().find(|t| t.name == "users").unwrap();
@@ -64,6 +65,32 @@ async fn introspects_schemas_tables_columns_and_indexes() -> IdeResult<()> {
Ok(())
}
/// The indexes SQLite makes for a non-rowid primary key and a UNIQUE constraint say which
/// key they enforce: Modify Table cannot drop those with `drop index`.
#[tokio::test]
async fn tells_key_indexes_from_plain_ones() -> IdeResult<()> {
let (_tmp, db) = setup().await;
let c = CancellationToken::new();
for stmt in [
"CREATE TABLE codes (region TEXT, code TEXT, label TEXT, PRIMARY KEY (region, code), UNIQUE (label))",
"CREATE INDEX codes_label ON codes (label, code)",
] {
db.execute("s1", stmt, 1, &c).await?;
}
let d = db.table_details("s1", "main", "codes").await?;
let mut keys: Vec<_> = d.indexes.iter().map(|i| (i.columns.join(","), i.unique, i.key)).collect();
keys.sort_by(|a, b| a.0.cmp(&b.0));
assert_eq!(
keys,
vec![
("label".into(), true, Some(DbKeyKind::Unique)),
("label,code".into(), false, None),
("region,code".into(), true, Some(DbKeyKind::Primary)),
]
);
Ok(())
}
#[tokio::test]
async fn completion_model_has_foreign_keys() -> IdeResult<()> {
let (_tmp, db) = setup().await;
+136
Переглянути файл
@@ -480,6 +480,95 @@ pub async fn format_text(
format_source(host, window, &project, source, None, options).await
}
/// Ruff safe fixes are independent of the formatter selection, language server and format-on-save setting.
fn ruff_fix_enabled(language: &LanguageId, on_save: bool, settings: &Settings) -> bool {
language.as_str() == "python" && (!on_save || settings.languages.ruff.fix_on_save)
}
/// Apply `ruff check --fix-only` to the supplied (possibly unsaved) text without writing the file.
fn ruff_fix_edits(
tools: &Tools,
settings: &Settings,
root: &Path,
path: &Path,
language: &LanguageId,
text: &str,
on_save: bool,
) -> IdeResult<Vec<TextEdit>> {
if !ruff_fix_enabled(language, on_save, settings) {
return Ok(Vec::new());
}
let config_file = ide_sdk::apply::ruff_configuration(root, &settings.languages.ruff.configuration_directory)?;
let custom = ide_sdk::apply::setting_path(root, &settings.languages.ruff.path)
.or_else(|| interpreter_tool(root, path.parent(), settings, "ruff"));
let mut command = tools.formatter_command("ruff", path, custom.as_deref())?;
let dir = config_file.as_deref().and_then(Path::parent).or_else(|| path.parent());
if let Some(dir) = dir {
command.current_dir(dir);
}
command.args(formatter::ruff_safe_fix_arguments(path, config_file.as_deref()));
let fixed = formatter::run("ruff", command, text, &Default::default())?;
if excluded_output(text, &fixed) {
return Ok(Vec::new());
}
Ok(diff_edits(&ide_text::Document::new(text), &fixed))
}
async fn ruff_fix_source(
host: &Host,
window: &str,
project: &crate::Project,
snap: &FormatSource,
on_save: bool,
) -> IdeResult<Vec<TextEdit>> {
let settings = project.settings.effective();
if !ruff_fix_enabled(&snap.language, on_save, &settings) {
return Ok(Vec::new());
}
host.require_trust(window)?;
if snap.read_only {
return Err(IdeError::invalid("The file is read-only"));
}
let tools = Tools::new(&host.local_data_dir);
let root = project.root.clone();
let path = snap.path.0.clone();
let language = snap.language.clone();
let text = snap.text.clone();
tokio::task::spawn_blocking(move || ruff_fix_edits(&tools, &settings, &root, &path, &language, &text, on_save))
.await
.map_err(|e| IdeError::internal(e.to_string()))?
.map_err(|e| e.with_tool("ruff"))
}
/// Apply Ruff's safe lint fixes to the current unsaved document.
pub async fn ruff_fix(host: &Host, window: &str, doc: DocId) -> IdeResult<Vec<TextEdit>> {
let project = host.project(window)?;
let snap = project.documents.snapshot(doc)?;
let source = FormatSource {
path: snap.path,
language: snap.language,
text: snap.text,
doc: Some(doc),
version: snap.version,
read_only: snap.read_only,
};
ruff_fix_source(host, window, &project, &source, true).await
}
/// Apply Ruff's safe lint fixes to a separate snapshot using the file's language and Ruff settings.
pub async fn ruff_fix_text(host: &Host, window: &str, path: PathBuf, text: String) -> IdeResult<Vec<TextEdit>> {
let project = host.project(window)?;
if !path.is_absolute() || path.file_name().is_none() {
return Err(IdeError::invalid("Ruff safe fixes require a file path"));
}
if text.len() as u64 > ide_vfs::LARGE_FILE_THRESHOLD {
return Ok(Vec::new());
}
let language = project.documents.language_of(&path, text.lines().next()).language;
let source = FormatSource { path: path.into(), language, text, doc: None, version: 0, read_only: false };
ruff_fix_source(host, window, &project, &source, false).await
}
struct FormatSource {
path: IpcPath,
language: LanguageId,
@@ -1325,6 +1414,53 @@ mod tests {
assert!(runs_on_save(Prettier, true, false, false));
}
#[test]
fn ruff_safe_fixes_on_save_are_opt_in_and_independent_of_formatting() {
let mut settings = Settings::default();
let python = LanguageId::new("python");
assert!(!ruff_fix_enabled(&python, true, &settings));
assert!(ruff_fix_enabled(&python, false, &settings), "commit fixes do not require the save option");
settings.editor.format_on_save = true;
settings.languages.ruff.run_on_save = true;
assert!(!ruff_fix_enabled(&python, true, &settings));
settings.languages.ruff.fix_on_save = true;
assert!(ruff_fix_enabled(&python, true, &settings));
assert!(!ruff_fix_enabled(&LanguageId::new("typescript"), true, &settings));
}
#[cfg(unix)]
#[test]
fn ruff_safe_fixes_use_unsaved_text_and_leave_the_file_on_disk_alone() {
use std::ffi::OsString;
use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
let file = root.join("main.py");
std::fs::write(&file, "on disk\n").unwrap();
let fake = root.join("ruff");
std::fs::write(
&fake,
"#!/bin/sh\nprintf '%s\\n' \"$@\" > \"$0.args\"\nwhile IFS= read -r line || [ -n \"$line\" ]; do\n if [ \"$line\" = 'import os' ]; then printf 'import sys\\n'; else printf '%s\\n' \"$line\"; fi\ndone\n",
)
.unwrap();
std::fs::set_permissions(&fake, std::fs::Permissions::from_mode(0o755)).unwrap();
let tools = Tools::with_paths(root.join("tools"), OsString::new(), ide_tools::platform::Platform::current());
let mut settings = Settings::default();
settings.languages.ruff.path = fake.to_string_lossy().into_owned();
let python = LanguageId::new("python");
let unsaved = "import os\nprint(os.name)\n";
assert!(ruff_fix_edits(&tools, &settings, root, &file, &python, unsaved, true).unwrap().is_empty());
assert!(!root.join("ruff.args").exists());
settings.languages.ruff.fix_on_save = true;
let edits = ruff_fix_edits(&tools, &settings, root, &file, &python, unsaved, true).unwrap();
assert_eq!(after(unsaved, &edits), "import sys\nprint(os.name)\n");
assert_eq!(std::fs::read_to_string(&file).unwrap(), "on disk\n");
let args = std::fs::read_to_string(root.join("ruff.args")).unwrap();
assert!(args.starts_with("check\n--fix-only\n--force-exclude\n--stdin-filename\n"), "{args}");
assert!(args.ends_with(&format!("{}\n-\n", file.display())), "{args}");
}
#[test]
fn forced_tool_runs_that_formatter_or_reports_why_not() {
let dir = tempfile::tempdir().unwrap();
+243
Переглянути файл
@@ -393,6 +393,7 @@ impl Host {
// After the cancels: a capture or open still running then discards what it registers.
ops::heap::close_window_snapshots(self, window);
let project = self.projects.write().remove(window)?;
project.closed.cancel();
if let Some(plugins) = self.plugin_host() {
if self.windows_for_root(&project.root).is_empty() {
plugins.project_closed(&project.root, window);
@@ -650,6 +651,7 @@ impl Host {
self.terminals.kill_all();
let projects: Vec<_> = self.projects.write().drain().map(|(_, p)| p).collect();
for project in &projects {
project.closed.cancel();
project.files_events_active.store(false, std::sync::atomic::Ordering::Release);
project.flutter.kill();
project.devtools.kill();
@@ -788,4 +790,245 @@ mod tests {
host.open_project("main", &root).unwrap();
host.close_project("main");
}
async fn minimal_debug_adapter<S: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin + Send + 'static>(
stream: S,
) {
use ide_jsonrpc::framing;
use serde_json::{Value, json};
use tokio::io::BufReader;
let (r, mut w) = tokio::io::split(stream);
let mut r = BufReader::new(r);
let mut seq = 1000;
while let Ok(Some(body)) = framing::read_message(&mut r).await {
let msg: Value = serde_json::from_slice(&body).unwrap();
if msg["type"] != "request" {
continue;
}
let cmd = msg["command"].as_str().unwrap_or_default();
seq += 1;
let resp = json!({
"seq": seq,
"type": "response",
"request_seq": msg["seq"],
"command": cmd,
"success": true,
"body": if cmd == "initialize" {
json!({"supportsConfigurationDoneRequest": true})
} else {
json!({})
}
});
if framing::write_message(&mut w, &serde_json::to_vec(&resp).unwrap()).await.is_err() {
break;
}
if cmd == "initialize" {
seq += 1;
let ev = json!({"seq": seq, "type": "event", "event": "initialized"});
if framing::write_message(&mut w, &serde_json::to_vec(&ev).unwrap()).await.is_err() {
break;
}
}
if cmd == "disconnect" {
break;
}
}
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn closing_project_during_debug_start_cancels_the_launch_and_keeps_other_windows() {
use ide_dap::adapter::{AdapterIo, AdapterLauncher, AdapterSpec, LaunchFuture};
struct BlockingLauncher {
blocked_cwd: PathBuf,
entered: Arc<tokio::sync::Notify>,
release: Arc<tokio::sync::Notify>,
}
impl AdapterLauncher for BlockingLauncher {
fn launch(&self, spec: AdapterSpec, _reuse: Option<u16>) -> LaunchFuture {
let block = spec.cwd == self.blocked_cwd;
let entered = self.entered.clone();
let release = self.release.clone();
Box::pin(async move {
if block {
entered.notify_one();
let _ = tokio::time::timeout(std::time::Duration::from_secs(5), release.notified()).await;
}
let (client, server) = tokio::io::duplex(1 << 16);
tokio::spawn(minimal_debug_adapter(server));
let (r, w) = tokio::io::split(client);
Ok(AdapterIo {
launch_after_configuration: false,
reader: Box::new(r),
writer: Box::new(w),
child: None,
port: None,
stderr: Arc::default(),
program_output: None,
})
})
}
}
let temp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(temp.path()).unwrap();
let root_a = base.join("proj-a");
let root_b = base.join("proj-b");
std::fs::create_dir(&root_a).unwrap();
std::fs::create_dir(&root_b).unwrap();
let entered = Arc::new(tokio::sync::Notify::new());
let release = Arc::new(tokio::sync::Notify::new());
let mut host = Host::new(HostConfig { local_data_dir: base.join("local"), ..HostConfig::for_test(&base) });
host.debugger = ide_dap::DebugManager::with_launcher(
host.languages.clone(),
Arc::new(BlockingLauncher {
blocked_cwd: root_a.clone(),
entered: entered.clone(),
release: release.clone(),
}),
);
let host = Arc::new(host);
host.open_project("main", &root_a).unwrap();
host.set_project_trust(&root_a, true, false).await.unwrap();
host.open_project("other", &root_b).unwrap();
host.set_project_trust(&root_b, true, false).await.unwrap();
let launch_cfg = |cwd: &Path| ide_dap::LaunchConfig {
name: "app".into(),
adapter: "codelldb".into(),
request: "launch".into(),
program: Some("/bin/true".into()),
args: vec![],
cwd: Some(cwd.into()),
env: Default::default(),
extra_json: None,
};
let other_id = ops::debug::debug_start(&host, "other", launch_cfg(&root_b)).await.unwrap();
let start_a = tokio::spawn({
let host = host.clone();
let cfg = launch_cfg(&root_a);
async move { ops::debug::debug_start(&host, "main", cfg).await }
});
tokio::time::timeout(std::time::Duration::from_secs(5), entered.notified()).await.unwrap();
host.close_project("main");
release.notify_waiters();
let result = tokio::time::timeout(std::time::Duration::from_secs(5), start_a).await.unwrap().unwrap();
assert_eq!(
result.as_ref().map_err(|e| e.kind),
Err(ide_core::error::ErrorKind::Cancelled),
"debug_start should fail as cancelled when project closes mid-launch, got {result:?}"
);
assert!(host.debugger.sessions(Some("main")).is_empty(), "closed window must have no live debug sessions");
assert_eq!(
host.debugger.sessions(Some("other")).into_iter().map(|s| s.id).collect::<Vec<_>>(),
vec![other_id],
"other window's debug session must remain alive"
);
host.close_project("other");
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn closing_project_during_cargo_debug_build_cancels_build_and_skips_adapter() {
use ide_dap::adapter::{AdapterIo, AdapterLauncher, AdapterSpec, LaunchFuture};
use std::sync::atomic::{AtomicUsize, Ordering};
struct CountingLauncher(Arc<AtomicUsize>);
impl AdapterLauncher for CountingLauncher {
fn launch(&self, _spec: AdapterSpec, _reuse: Option<u16>) -> LaunchFuture {
self.0.fetch_add(1, Ordering::SeqCst);
let (client, server) = tokio::io::duplex(1 << 16);
tokio::spawn(minimal_debug_adapter(server));
let (r, w) = tokio::io::split(client);
Box::pin(async move {
Ok(AdapterIo {
launch_after_configuration: false,
reader: Box::new(r),
writer: Box::new(w),
child: None,
port: None,
stderr: Arc::default(),
program_output: None,
})
})
}
}
let temp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(temp.path()).unwrap();
let root = base.join("rust-proj");
let marker = root.join("build-script.pid");
std::fs::create_dir_all(root.join("src")).unwrap();
std::fs::write(
root.join("Cargo.toml"),
"[package]\nname = \"slowbuild\"\nversion = \"0.1.0\"\nedition = \"2021\"\n",
)
.unwrap();
std::fs::write(
root.join("build.rs"),
format!(
"fn main() {{\n std::fs::write({:?}, std::process::id().to_string()).unwrap();\n std::thread::sleep(std::time::Duration::from_secs(5));\n}}\n",
marker
),
)
.unwrap();
std::fs::write(root.join("src/main.rs"), "fn main() {}\n").unwrap();
let launches = Arc::new(AtomicUsize::new(0));
let mut host = Host::new(HostConfig { local_data_dir: base.join("local"), ..HostConfig::for_test(&base) });
host.debugger =
ide_dap::DebugManager::with_launcher(host.languages.clone(), Arc::new(CountingLauncher(launches.clone())));
let host = Arc::new(host);
host.open_project("main", &root).unwrap();
host.set_project_trust(&root, true, false).await.unwrap();
let cfg = ide_dap::LaunchConfig {
name: "cargo build".into(),
adapter: "codelldb".into(),
request: "launch".into(),
program: None,
args: vec![],
cwd: Some(root.clone().into()),
env: Default::default(),
extra_json: Some(serde_json::json!({ "cargo": { "args": ["build", "--bin", "slowbuild"] } }).to_string()),
};
let start = tokio::spawn({
let host = host.clone();
async move { ops::debug::debug_start(&host, "main", cfg).await }
});
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30);
let build_pid: u32 = loop {
if let Ok(text) = std::fs::read_to_string(&marker)
&& let Ok(pid) = text.trim().parse::<u32>()
{
break pid;
}
assert!(std::time::Instant::now() < deadline, "cargo build script never started");
tokio::time::sleep(std::time::Duration::from_millis(20)).await;
};
host.close_project_detached("main");
let result = tokio::time::timeout(std::time::Duration::from_secs(10), start).await.unwrap().unwrap();
host.wait_detached_closes();
assert_eq!(
result.as_ref().map_err(|e| e.kind),
Err(ide_core::error::ErrorKind::Cancelled),
"cargo build debug_start should be cancelled on close, got {result:?}"
);
assert_eq!(launches.load(Ordering::SeqCst), 0, "adapter must not be launched after close");
assert!(host.debugger.sessions(Some("main")).is_empty(), "no session may be registered after close");
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(3);
while ide_core::process::process_alive(build_pid) {
assert!(std::time::Instant::now() < deadline, "cargo build script pid {build_pid} outlived cancellation");
tokio::time::sleep(std::time::Duration::from_millis(20)).await;
}
}
}
+8 -1
Переглянути файл
@@ -20,7 +20,14 @@ use std::fmt::Write as _;
use std::path::{Path, PathBuf};
pub fn tools() -> Vec<Tool> {
vec![create_new_file(), apply_patch(), format::reformat_file(), rename::rename_refactoring(), open_file_in_editor()]
vec![
create_new_file(),
apply_patch(),
format::reformat_file(),
format::optimize_imports(),
rename::rename_refactoring(),
open_file_in_editor(),
]
}
/// What tools without a result value answer (JetBrains renders `Unit` so).
+19
Переглянути файл
@@ -44,6 +44,25 @@ To remove unused imports without reformatting, use optimize_imports.",
))
}
pub(super) fn optimize_imports() -> Tool {
Tool::new(
"optimize_imports",
"Removes unused imports and orders the remaining ones in the specified files, without reformatting them.
Returns a unified diff of the changes that the import optimizer applied, or \"ok\" when the imports are already \
optimized.
The diff shows the import changes only. It never repeats the edit that you applied yourself.
The diff stops at 200 lines. A footer names the file(s) that it leaves out.
To also apply the code formatter, use reformat_file with optimizeImports: true.",
|call| async move { run(&call, Job { organize: true, format: false }).await },
)
.write()
.param(Param::required(
"files",
ParamType::StringList,
"List of project-relative files whose imports to optimize. Duplicate paths are ignored after normalization.",
))
}
#[derive(Clone, Copy)]
struct Job {
organize: bool,
+198 -25
Переглянути файл
@@ -5,11 +5,11 @@
use super::Channel;
use crate::Host;
use ide_command::command;
use ide_core::{IdeError, IdeResult, IpcPath, RequestId};
use ide_core::{CancellationToken, IdeError, IdeResult, IpcPath, RequestId};
use ide_db::split::SqlStatement;
use ide_db::{
CompletionModel, DataSource, Databases, DbObjectKind, DbRowEdit, DbSourceFolder, DbVisibilityChange, HistoryEntry,
PlanNode, QueryResult, SchemaObjects, SortKey, TableDetails, TableGrant, TableInfo, TablePage,
CompletionModel, ConsoleId, DataSource, Databases, DbObjectKind, DbRowEdit, DbSourceFolder, DbVisibilityChange,
HistoryEntry, PlanNode, QueryResult, SchemaObjects, SortKey, TableDetails, TableGrant, TableInfo, TablePage,
};
use serde::{Deserialize, Serialize};
use specta::Type;
@@ -201,6 +201,28 @@ pub async fn db_finish_transaction(host: &Host, window: &str, id: String, commit
db.finish_transaction(&id, commit).await
}
#[command(trust = trusted)]
pub async fn db_set_console_manual_commit(
host: &Host,
window: &str,
id: String,
console: String,
manual: bool,
) -> IdeResult<bool> {
host.project(window)?.db.set_postgres_console_manual(&id, ConsoleId::new(window, &console), manual).await
}
#[command(trust = trusted)]
pub async fn db_finish_console_transaction(
host: &Host,
window: &str,
id: String,
console: String,
commit: bool,
) -> IdeResult<()> {
host.project(window)?.db.finish_postgres_console_transaction(&id, ConsoleId::new(window, &console), commit).await
}
#[command(trust = trusted)]
pub async fn db_disconnect(host: &Host, window: &str, id: String, whole_source: Option<bool>) -> IdeResult<()> {
// A source-level Deactivate includes databases still opening in the background.
@@ -348,6 +370,24 @@ pub async fn db_object_ddl(
db.object_ddl(&id, &schema, kind, &name).await
}
fn console_request<'a>(
host: &Host,
window: &'a str,
request: RequestId,
path: Option<&'a str>,
manual: Option<bool>,
) -> IdeResult<(CancellationToken, Option<ConsoleId<'a>>)> {
match path {
Some(path) => Ok((
host.begin_project_request(window, request),
Some(ConsoleId::new(window, path).expecting_manual(manual)),
)),
None if manual.is_some() => Err(IdeError::invalid("Console transaction mode requires a console")),
None => Ok((host.begin_request(request), None)),
}
}
#[allow(clippy::too_many_arguments)]
#[command(trust = trusted)]
pub async fn db_explain(
host: &Host,
@@ -356,11 +396,13 @@ pub async fn db_explain(
id: String,
statement: String,
schema: Option<String>,
#[default] console: Option<String>,
#[default] console_manual: Option<bool>,
) -> IdeResult<Vec<PlanNode>> {
// Explain Plan: the execution plan of `statement` on `id`, without running it.
let db = host.project(window)?.db.clone();
let cancel = host.begin_request(request);
let result = db.explain(&id, &statement, &cancel, schema.as_deref()).await;
let (cancel, console) = console_request(host, window, request, console.as_deref(), console_manual)?;
let result = db.explain_in_console(&id, &statement, &cancel, schema.as_deref(), console).await;
host.end_request(request);
result
}
@@ -418,21 +460,35 @@ pub async fn db_execute(
schema: Option<String>,
// Cells longer than this many UTF-16 units come back cut (`truncated` lists them); none: whole.
#[default] cell_limit: Option<u32>,
#[default] console: Option<String>,
#[default] console_manual: Option<bool>,
) -> IdeResult<Vec<StatementOutcome>> {
let mut outcomes = Vec::new();
let limits = Limits { skip, max_rows, cell_limit };
execute_statements(host, window, request, &id, statements, limits, schema.as_deref(), |event| {
if let ExecutionEvent::Completed { outcome, .. } = event {
outcomes.push(outcome);
}
Ok(())
})
execute_statements(
host,
window,
request,
&id,
statements,
limits,
schema.as_deref(),
console.as_deref(),
console_manual,
|event| {
if let ExecutionEvent::Completed { outcome, .. } = event {
outcomes.push(outcome);
}
Ok(())
},
)
.await?;
Ok(outcomes)
}
/// Row `row` (from 0) of the result of `statement`, whole: what a page of a run with a
/// `cell_limit` shows cut short.
#[allow(clippy::too_many_arguments)]
#[command(trust = trusted)]
pub async fn db_result_row(
host: &Host,
@@ -442,10 +498,12 @@ pub async fn db_result_row(
statement: SqlStatement,
row: u32,
schema: Option<String>,
#[default] console: Option<String>,
#[default] console_manual: Option<bool>,
) -> IdeResult<QueryResult> {
let db = host.project(window)?.db.clone();
let cancel = host.begin_request(request);
let result = db.read_row(&id, &statement.text, row as usize, &cancel, schema.as_deref()).await;
let (cancel, console) = console_request(host, window, request, console.as_deref(), console_manual)?;
let result = db.read_console_row(&id, &statement.text, row as usize, &cancel, schema.as_deref(), console).await;
host.end_request(request);
result
}
@@ -458,11 +516,23 @@ pub fn db_release_result(
id: String,
statement: String,
schema: Option<String>,
#[default] console: Option<String>,
) -> IdeResult<()> {
host.project(window)?.db.release_result(&id, &statement, schema.as_deref());
let console = console.as_deref().map(|path| ConsoleId::new(window, path));
host.project(window)?.db.release_console_result(&id, &statement, schema.as_deref(), console);
Ok(())
}
#[command(trust = trusted)]
pub async fn db_release_console(
host: &Host,
window: &str,
console: String,
#[default] id: Option<String>,
) -> IdeResult<()> {
host.project(window)?.db.release_target_console(ConsoleId::new(window, &console), id.as_deref()).await
}
#[allow(clippy::too_many_arguments)]
#[command(trust = trusted)]
pub async fn db_execute_stream(
@@ -475,11 +545,22 @@ pub async fn db_execute_stream(
schema: Option<String>,
#[default] cell_limit: Option<u32>,
on_progress: Channel<ExecutionEvent>,
#[default] console: Option<String>,
#[default] console_manual: Option<bool>,
) -> IdeResult<()> {
let limits = Limits { skip: 0, max_rows, cell_limit };
let result = execute_statements(host, window, request, &id, statements, limits, schema.as_deref(), |event| {
on_progress.send(event)
})
let result = execute_statements(
host,
window,
request,
&id,
statements,
limits,
schema.as_deref(),
console.as_deref(),
console_manual,
|event| on_progress.send(event),
)
.await;
// The invocation reply can reach the viewer before a large result frame.
on_progress.send(ExecutionEvent::Done { error: result.err() })
@@ -503,19 +584,29 @@ async fn execute_statements(
statements: Vec<SqlStatement>,
Limits { skip, max_rows, cell_limit }: Limits,
schema: Option<&str>,
console: Option<&str>,
console_manual: Option<bool>,
mut emit: impl FnMut(ExecutionEvent) -> IdeResult<()>,
) -> IdeResult<()> {
let db = host.project(window)?.db.clone();
let cancel = host.begin_request(request);
let (cancel, console) = console_request(host, window, request, console, console_manual)?;
let result = async {
db.validate_script(id, &statements).await?;
db.validate_console_script(id, &statements, console).await?;
for (index, statement) in statements.into_iter().enumerate() {
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
emit(ExecutionEvent::Started { index: index as u32 })?;
let outcome = match db
.execute_from(id, &statement.text, skip as usize, max_rows.max(1) as usize, &cancel, schema)
.execute_in_console(
id,
&statement.text,
skip as usize,
max_rows.max(1) as usize,
&cancel,
schema,
console,
)
.await
{
Ok(mut result) => {
@@ -705,6 +796,7 @@ ide_command::domain!(
db_execute_stream,
db_explain,
db_finish_transaction,
db_finish_console_transaction,
db_history,
db_jdbc_driver_classes,
db_jdbc_drivers,
@@ -713,6 +805,7 @@ ide_command::domain!(
db_remove_jdbc_driver,
db_object_ddl,
db_release_result,
db_release_console,
db_result_row,
db_remove_history,
db_retain_catalog,
@@ -724,6 +817,7 @@ ide_command::domain!(
db_schemas,
db_session_context,
db_set_manual_commit,
db_set_console_manual_commit,
db_set_password,
db_set_ssh_secret,
db_source_folders,
@@ -766,6 +860,78 @@ mod tests {
host
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[ignore = "requires a disposable loopback PostgreSQL fixture with OPENIDEA_PG_CONSOLE_PORT"]
async fn postgres_console_commands_keep_commit_result_reads_and_release_scoped() {
let temp = tempfile::tempdir().unwrap();
let host = host_with_sqlite(&temp).await;
let window = "main";
let id = "postgres";
db_save_sources(
&host,
window,
vec![DataSource {
id: id.into(),
name: "Local PostgreSQL".into(),
driver: DbDriver::Postgres,
host: "127.0.0.1".into(),
port: Some(std::env::var("OPENIDEA_PG_CONSOLE_PORT").unwrap().parse().unwrap()),
user: "console_fixture".into(),
database: "console_fixture".into(),
..Default::default()
}],
)
.await
.unwrap();
let run = async |request, sql: &str, console: Option<&str>| {
let outcomes = db_execute(
&host,
window,
RequestId(request),
id.into(),
ide_db::split::split(sql, DbDriver::Postgres),
0,
10,
Some("public".into()),
None,
console.map(str::to_owned),
console.map(|_| true),
)
.await
.unwrap();
assert!(outcomes[0].error.is_none(), "{:?}", outcomes[0].error);
outcomes.into_iter().next().unwrap().result.unwrap()
};
run(1, "CREATE TABLE public.host_console_tx (id integer PRIMARY KEY)", None).await;
for console in ["/a.sql", "/b.sql"] {
assert!(db_set_console_manual_commit(&host, window, id.into(), console.into(), true).await.unwrap());
}
run(2, "INSERT INTO public.host_console_tx VALUES (1)", Some("/a.sql")).await;
run(3, "INSERT INTO public.host_console_tx VALUES (2)", Some("/b.sql")).await;
db_finish_console_transaction(&host, window, id.into(), "/b.sql".into(), true).await.unwrap();
let select = "SELECT id FROM public.host_console_tx ORDER BY id";
assert_eq!(run(4, select, None).await.rows, [[Some("2".into())]]);
let statement = ide_db::split::split(select, DbDriver::Postgres).pop().unwrap();
let retained = db_result_row(
&host,
window,
RequestId(5),
id.into(),
statement,
0,
Some("public".into()),
Some("/a.sql".into()),
Some(true),
)
.await
.unwrap();
assert_eq!(retained.rows, [[Some("1".into())]]);
db_release_console(&host, window, "/a.sql".into(), Some(id.into())).await.unwrap();
assert_eq!(run(6, select, None).await.rows, [[Some("2".into())]]);
let error = db_finish_console_transaction(&host, window, id.into(), "/a.sql".into(), true).await.unwrap_err();
assert_eq!(error.kind, ide_core::error::ErrorKind::OutOfSync);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_reporting_error_stops_the_batch_and_releases_the_request() {
let temp = tempfile::tempdir().unwrap();
@@ -782,6 +948,8 @@ mod tests {
statements,
Limits { skip: 0, max_rows: 10, cell_limit: None },
None,
None,
None,
|event| match event {
ExecutionEvent::Started { index: 0 } => Ok(()),
ExecutionEvent::Completed { index: 0, outcome } => {
@@ -803,7 +971,8 @@ mod tests {
"SELECT 99 AS n UNION ALL SELECT count(*) FROM items ORDER BY n DESC",
DbDriver::Sqlite,
);
let outcomes = db_execute(&host, window, RequestId(2), id.into(), query, 1, 10, None, None).await.unwrap();
let outcomes =
db_execute(&host, window, RequestId(2), id.into(), query, 1, 10, None, None, None, None).await.unwrap();
assert_eq!(outcomes[0].result.as_ref().unwrap().rows, vec![vec![Some("0".into())]]);
}
@@ -819,10 +988,12 @@ mod tests {
),
DbDriver::Sqlite,
);
db_execute(&host, window, RequestId(1), id.into(), setup, 0, 10, None, None).await.unwrap();
db_execute(&host, window, RequestId(1), id.into(), setup, 0, 10, None, None, None, None).await.unwrap();
let query = || ide_db::split::split("SELECT n, body FROM docs ORDER BY n", DbDriver::Sqlite);
let capped = db_execute(&host, window, RequestId(2), id.into(), query(), 0, 10, None, Some(100)).await.unwrap();
let capped = db_execute(&host, window, RequestId(2), id.into(), query(), 0, 10, None, Some(100), None, None)
.await
.unwrap();
let page = capped[0].result.as_ref().unwrap();
// The page no longer carries more than the limit of each cell.
let size: usize = page.rows.iter().flatten().flatten().map(String::len).sum();
@@ -843,7 +1014,8 @@ mod tests {
// The row of a cut cell, read alone and without a limit, is the whole value.
for row in [1, 2] {
let statement = query().remove(0);
let one = db_result_row(&host, window, RequestId(3), id.into(), statement, row, None).await.unwrap();
let one =
db_result_row(&host, window, RequestId(3), id.into(), statement, row, None, None, None).await.unwrap();
assert!(one.truncated.is_empty());
let full = one.rows[0][1].clone().unwrap();
assert_eq!(full.encode_utf16().count(), whole as usize);
@@ -851,7 +1023,8 @@ mod tests {
}
// Without a limit nothing is cut or listed.
let all = db_execute(&host, window, RequestId(4), id.into(), query(), 0, 10, None, None).await.unwrap();
let all =
db_execute(&host, window, RequestId(4), id.into(), query(), 0, 10, None, None, None, None).await.unwrap();
let all = all[0].result.as_ref().unwrap();
assert!(all.truncated.is_empty());
assert_eq!(all.rows[2][1].as_deref(), Some(wide.as_str()));
+7 -2
Переглянути файл
@@ -12,7 +12,9 @@ use std::path::PathBuf;
/// Starts a session owned by this window: its events (and those of child sessions) go here only.
#[command(trust = trusted)]
pub async fn debug_start(host: &Host, window: &str, config: LaunchConfig) -> IdeResult<DebugSessionId> {
host.require_trust(window)?;
let project = host.project(window)?;
project.require_trust()?;
let cancel = project.closed.child_token();
let unity_pid = if config.adapter == "unity" {
if config.request != "attach" {
return Err(ide_core::IdeError::invalid("Unity debugging only supports attachment to a running Editor"));
@@ -150,10 +152,13 @@ pub async fn debug_start(host: &Host, window: &str, config: LaunchConfig) -> Ide
.or_else(|| ruby_tools.into_iter().find(|(name, _)| *name == command).map(|(_, path)| path))?;
Some(path.to_string_lossy().into_owned())
};
if cancel.is_cancelled() {
return Err(ide_core::IdeError::cancelled());
}
host.require_trust(window)?;
let server_port = debug_server_port(&config);
let exception_classes = server_port.and_then(|port| exception_class_backend(host, window, port));
let result = host.debugger.start_with_exception_classes(config, owner, custom, exception_classes).await;
let result = host.debugger.start_with_cancel(config, owner, custom, exception_classes, cancel).await;
flush_output();
if let Ok(id) = &result {
let sink = host.window_sink(label);
+20 -1
Переглянути файл
@@ -846,7 +846,7 @@ pub async fn lsp_library_sources(
#[command(trust = trusted)]
pub async fn lsp_resolve_class_file(host: &Host, window: &str, path: std::path::PathBuf) -> IdeResult<String> {
// Opens compiled classes through JDT, with project source taking priority on disk.
// Opens compiled classes through JDT as decompiled class documents.
let archive = ide_vfs::split_archive_path(&path);
host.project(window)?.lsp.java_class_file(&path, archive).await
}
@@ -1836,6 +1836,23 @@ pub async fn lsp_format_text(
crate::formatter::format_text(host, window, path, text, options).await
}
/// Apply Ruff's safe lint fixes (`ruff check --fix-only`) to the current unsaved Python document.
#[command(trust = trusted)]
pub async fn ruff_fix(host: &Host, window: &str, doc: DocId) -> IdeResult<Vec<TextEdit>> {
crate::formatter::ruff_fix(host, window, doc).await
}
/// Apply Ruff's safe lint fixes to a Python text snapshot without writing the file.
#[command(trust = trusted)]
pub async fn ruff_fix_text(
host: &Host,
window: &str,
path: std::path::PathBuf,
text: String,
) -> IdeResult<Vec<TextEdit>> {
crate::formatter::ruff_fix_text(host, window, path, text).await
}
#[command(trust = trusted)]
pub async fn lsp_source_action_text(
host: &Host,
@@ -3259,6 +3276,8 @@ ide_command::domain!(
lsp_extract_interface_info,
lsp_format,
lsp_format_text,
ruff_fix,
ruff_fix_text,
lsp_snapshot_completion,
lsp_snapshot_diagnostics,
lsp_source_action_text,
+4
Переглянути файл
@@ -24,6 +24,8 @@ use std::time::{Duration, Instant};
pub struct Project {
pub(crate) trusted: Arc<AtomicBool>,
pub(crate) files_events_active: Arc<AtomicBool>,
/// Cancelled synchronously when this project incarnation begins closing.
pub(crate) closed: CancellationToken,
pub root: PathBuf,
/// Window-scoped event sink, for commands that emit project events.
pub sink: SharedSink,
@@ -673,6 +675,7 @@ impl Host {
let project = Arc::new(Project {
plugin_diagnostics,
trusted,
closed: CancellationToken::new(),
flutter: ide_flutter::FlutterDaemon::new(
root.clone(),
sink.clone(),
@@ -945,6 +948,7 @@ impl Host {
let project = Arc::new(Project {
plugin_diagnostics,
trusted: Arc::new(AtomicBool::new(false)),
closed: CancellationToken::new(),
flutter: ide_flutter::FlutterDaemon::new(
dir.clone(),
sink.clone(),
+4 -2
Переглянути файл
@@ -82,14 +82,16 @@ async fn attached_projects_keep_their_own_excluded_folders() {
host.open_project("lib", &lib).unwrap();
ops::project::set_settings(&host, "lib", SettingsScope::Project, "projectStructure.excluded", "[]").unwrap();
let project = host.project("main").unwrap();
let expected_dist = expect(&["app/dist/dist.txt", "lib/dist/dist.txt"]);
// The exclusion can update before the index rescan has been queued.
for _ in 0..100 {
if project.exclude_globs_in(&lib).iter().all(|g| g != "/dist") {
if project.index.files_named("dist.txt") == expected_dist {
break;
}
tokio::time::sleep(Duration::from_millis(50)).await;
}
assert!(excluded(&host, &lib).await.is_empty());
assert_eq!(indexed(&host, "dist.txt"), expect(&["app/dist/dist.txt", "lib/dist/dist.txt"]));
assert_eq!(indexed(&host, "dist.txt"), expected_dist);
ops::project::set_settings(&host, "lib", SettingsScope::Project, "projectStructure.excluded", r#"["dist"]"#)
.unwrap();
host.shutdown().await;
+35
Переглянути файл
@@ -731,6 +731,41 @@ async fn reformat_uses_the_formatter_chain_and_preserves_a_dirty_buffer() {
assert!(p.documents.is_dirty(doc.id).unwrap());
}
#[tokio::test(flavor = "multi_thread")]
async fn optimize_imports_is_a_write_tool_with_only_a_files_argument() {
let h = Harness::new();
h.trust().await;
let tools = Registry::new(h.host.clone()).tools(&h.root).unwrap();
let tool = tools.iter().find(|t| t.name == "optimize_imports").expect("optimize_imports is registered");
assert!(!tool.read_only && !tool.destructive);
assert_eq!(tool.input_schema["required"], json!(["files"]));
assert!(tool.input_schema["properties"].get("optimizeImports").is_none());
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread")]
async fn optimize_imports_removes_unused_imports_without_reformatting() {
use std::os::unix::fs::PermissionsExt;
let h = Harness::new();
h.trust().await;
let ruff = h.root.join("fake-ruff");
std::fs::write(
&ruff,
"#!/bin/sh\n[ \"$1 $2 $3 $4 $5\" = \"check --extend-select I --fixable I,F401\" ] || exit 2\nsed '/^import sys$/d'\n",
)
.unwrap();
std::fs::set_permissions(&ruff, std::fs::Permissions::from_mode(0o755)).unwrap();
let p = h.host.project("main").unwrap();
p.settings
.set(ide_workspace::SettingsScope::Project, "languages.ruff.path", json!(ruff.to_string_lossy()))
.unwrap();
let path = h.root.join("src/example.py");
std::fs::write(&path, "import os\nimport sys\n\nprint(os)\n").unwrap();
let diff = h.call("optimize_imports", json!({"files":["src/example.py"]})).await;
assert!(diff.contains("-import sys"), "{diff}");
assert_eq!(std::fs::read_to_string(&path).unwrap(), "import os\n\nprint(os)\n");
}
/// Answers `execute_run_configuration`'s window requests the way the Run tool window does:
/// starts the configuration in a tab and says whether it started. Returns what it started.
fn config_run_window(h: &Harness) -> Arc<std::sync::Mutex<Vec<ide_run::RunConfig>>> {
+5 -22
Переглянути файл
@@ -1204,35 +1204,18 @@ impl LspManager {
.map_err(|e| IdeError::internal(e.to_string()))?
}
/// Resolve a disk/archive class to project source or the server's binary document.
/// Resolve a disk/archive class to the server's class document, opened decompiled.
/// Archive URIs must come from JDT's Java model: fabricated handles cannot map debug lines.
/// A class in an output directory opens as itself even when its project source exists:
/// the user asked for the compiled class, not the file it was built from.
pub async fn java_class_file(&self, path: &Path, archive: Option<(PathBuf, String)>) -> IdeResult<String> {
if let Some((jar, entry)) = archive {
return self.archive_class(jar, entry, false).await;
}
let cancel = CancellationToken::new();
self.jdtls(&self.project_root, &cancel).await?;
let uri = crate::uri::path_to_uri_string(path);
// classFileContents accepts file URIs, but java-debug's line mapping only accepts JDT handles.
let doc = self.virtual_document(&uri).await?;
let name = path.file_stem().and_then(|s| s.to_str()).unwrap_or("").split('$').next().unwrap_or("");
let package = doc
.text
.lines()
.find_map(|l| l.trim().strip_prefix("package ").and_then(|p| p.strip_suffix(';')))
.unwrap_or("");
let relative = PathBuf::from(package.replace('.', "/")).join(format!("{name}.java"));
let key = "org.eclipse.jdt.ls.core.sourcePaths";
let settings = self
.jdtls_project_command(path, "java.project.getSettings", vec![json!(uri), json!([key])], &cancel)
.await?;
let roots: Vec<PathBuf> =
settings[key].as_array().into_iter().flatten().filter_map(Value::as_str).map(PathBuf::from).collect();
let source =
tokio::task::spawn_blocking(move || roots.into_iter().map(|r| r.join(&relative)).find(|p| p.is_file()))
.await
.map_err(|e| IdeError::internal(e.to_string()))?;
Ok(source.map(|s| s.to_string_lossy().into_owned()).unwrap_or(uri))
// classFileContents accepts file URIs for classes outside the Java model.
Ok(crate::uri::path_to_uri_string(path))
}
/// Starts (or reuses) java-debug's DAP server inside jdtls and returns its port.
+4 -8
Переглянути файл
@@ -5558,7 +5558,7 @@ async fn jar_library_sources_reload_with_another_encoding() {
}
#[tokio::test(flavor = "multi_thread")]
async fn class_file_opening_routes_sources_and_binary_documents() {
async fn class_file_opening_routes_archive_and_output_classes() {
let mut caps = incremental_caps();
caps["workspaceSymbolProvider"] = json!(true);
let h = harness_for("java", "java", &[("jdtls", caps)], &[]);
@@ -5581,18 +5581,14 @@ async fn class_file_opening_routes_sources_and_binary_documents() {
.is_err()
);
// An output class opens as its decompiled class document even when the project source exists.
let sources = h.root.join("src/main/java");
std::fs::create_dir_all(sources.join("p")).unwrap();
let source = sources.join("p/Outer.java");
std::fs::write(&source, "package p; class Outer {} ").unwrap();
std::fs::write(sources.join("p/Outer.java"), "package p; class Outer {} ").unwrap();
s.respond("java/classFileContents", json!("// Source code is decompiled from a .class file using FernFlower decompiler (from Intellij IDEA).\npackage p;\npublic class Outer {}"));
s.respond("workspace/executeCommand", json!({ "org.eclipse.jdt.ls.core.sourcePaths": [sources] }));
for class in ["Outer", "Outer$Nested", "Outer$1"] {
let path = h.root.join(format!("target/classes/p/{class}.class"));
let resolved = h.mgr.java_class_file(&path, None).await.unwrap();
// Compare as paths: the manager joins the relative source path with std::path, so
// separators can differ from the literal "p/Outer.java" used to build `source` on Windows.
assert_eq!(Path::new(&resolved), source.as_path());
assert_eq!(h.mgr.java_class_file(&path, None).await.unwrap(), uri_of(&path));
}
let path = h.root.join("build/classes/java/main/p/Missing.class");
let uri = uri_of(&path);
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
6ee319bf6071871f7d9d0674b83be11d7b6f8ed2693572303f15d7e450a86b4b
3f5a85c4e3802a93b74513c1981b4202ad5bc70566a5cfcca7a1be2573a03f24
+4 -10
Переглянути файл
@@ -16,12 +16,8 @@ impl Plugin for ExecutionOutput {
_ => None,
};
let debug = parts.next() == Some("debug");
host::start_run_with_options(
config,
&["extra".into()],
&RunStartOptions { debug, output_mode: mode },
)
.map(Some)
host::start_run_with_options(config, &["extra".into()], &RunStartOptions { debug, output_mode: mode })
.map(Some)
}
"start-legacy" => host::start_run(arg.unwrap_or("pty-default"), &["legacy".into()], false).map(Some),
"events" => host::storage::get("events"),
@@ -30,10 +26,8 @@ impl Plugin for ExecutionOutput {
}
fn handle_events(&mut self, events: &[Event], _: &Invocation) {
let mut received: Vec<serde_json::Value> = host::storage::get("events")
.unwrap()
.and_then(|s| serde_json::from_str(&s).ok())
.unwrap_or_default();
let mut received: Vec<serde_json::Value> =
host::storage::get("events").unwrap().and_then(|s| serde_json::from_str(&s).ok()).unwrap_or_default();
for event in events {
if let Event::Other { kind, data } = event {
received.push(serde_json::json!({"kind": kind, "data": data}));
+8 -4
Переглянути файл
@@ -80,12 +80,16 @@ fn a_stopped_run_still_writes_its_profile() {
let out = tempfile::tempdir().unwrap();
let (mut cmd, spec) = plan(&python, &["cpu_heavy.py", "--loop"], out.path());
let mut child = cmd.spawn().unwrap();
let mut line = String::new();
BufReader::new(child.stdout.take().unwrap()).read_line(&mut line).unwrap();
assert_eq!(line.trim(), "done");
let mut stdout = BufReader::new(child.stdout.take().unwrap());
for marker in ["done", "looped"] {
let mut line = String::new();
stdout.read_line(&mut line).unwrap();
assert_eq!(line.trim(), marker);
}
// What the first Stop sends.
assert!(Command::new("kill").args(["-INT", &child.id().to_string()]).status().unwrap().success());
child.wait().unwrap();
let p = collect(&spec).unwrap();
assert!(method(&p, "fib").calls.unwrap() > 57313.0, "the loop ran");
// One completed fib(22) followed by one completed fib(18).
assert!(method(&p, "fib").calls.unwrap() >= 65_674.0, "both completed passes were profiled");
}
+1 -1
Переглянути файл
@@ -1639,7 +1639,7 @@ pub fn jdbc_bridge_jar(data_dir: &Path) -> Option<PathBuf> {
install_bundle(
data_dir,
"jdbc-bridge",
"1.0.0",
"2.0.0",
include_bytes!("../../../java/jdbc-bridge/openidea-jdbc-bridge.jar"),
)
}
+10 -1
Переглянути файл
@@ -340,7 +340,16 @@ impl Session {
use std::io::Write as _;
let mut gz = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::fast());
gz.write_all(data)?;
let packed = gz.finish()?;
self.put_gzip_with_progress(remote, &gz.finish()?, progress).await
}
/// Sends an already compressed gzip stream; the remote file contains the decoded bytes.
pub async fn put_gzip_with_progress(
&self,
remote: &str,
packed: &[u8],
progress: &(dyn Fn(f64) + Send + Sync),
) -> IdeResult<()> {
let q = crate::shell::quote;
let dir = crate::sftp::parent(remote).unwrap_or("/");
let command = format!("mkdir -p {} && gzip -dc > {}", q(dir), q(remote));
+1
Переглянути файл
@@ -16,6 +16,7 @@ http = "1"
hyper-util = { version = "0.1", default-features = false, features = ["client-proxy", "client-proxy-system"] }
tracing.workspace = true
which = "8"
blake3.workspace = true
flate2 = "1"
tar = "0.4"
zip.workspace = true
+38
Переглянути файл
@@ -247,6 +247,16 @@ pub fn with_python_style(tool: &str, mut args: Vec<OsString>, style: PythonStyle
args
}
/// `ruff check --fix-only` over stdin, honoring the project's exclusions and applying no unsafe fixes.
pub fn ruff_safe_fix_arguments(file: &Path, config_file: Option<&Path>) -> Vec<OsString> {
let mut args: Vec<OsString> = ["check", "--fix-only", "--force-exclude"].map(OsString::from).into();
if let Some(config_file) = config_file {
args.extend(["--config".into(), config_file.as_os_str().to_owned()]);
}
args.extend(["--stdin-filename".into(), file.as_os_str().to_owned(), "-".into()]);
args
}
/// `ruff check` that sorts the imports (I) of the text on stdin and removes the unused ones (F401)
/// and prints the result, for Optimize Imports where the Ruff server isn't running. Only those two
/// are fixed, and F401 only where the project's rules check it (it is in Ruff's defaults; an
@@ -596,6 +606,34 @@ mod tests {
assert!(supports_range("black", &config));
}
#[test]
fn ruff_applies_only_safe_fixes_to_stdin_with_the_project_config() {
let file = Path::new("/project with spaces/src/example.py");
let args = |config: Option<&Path>| -> Vec<String> {
ruff_safe_fix_arguments(file, config).into_iter().map(|a| a.to_string_lossy().into_owned()).collect()
};
assert_eq!(
args(None),
["check", "--fix-only", "--force-exclude", "--stdin-filename", "/project with spaces/src/example.py", "-"]
);
assert_eq!(
args(Some(Path::new("/shared/ruff.toml"))),
[
"check",
"--fix-only",
"--force-exclude",
"--config",
"/shared/ruff.toml",
"--stdin-filename",
"/project with spaces/src/example.py",
"-"
]
);
assert!(args(None).contains(&"--force-exclude".into()));
assert!(!args(None).contains(&"--unsafe-fixes".into()));
assert!(!args(None).contains(&"format".into()));
}
#[test]
fn ruff_organizes_imports_of_stdin_without_failing_on_what_it_cannot_fix() {
let file = Path::new("/project/src/example.py");
+57
Переглянути файл
@@ -5,6 +5,7 @@ use crate::process::Http;
use crate::{InstallEvent, fetch_verified, sources};
use ide_core::CancellationToken;
use ide_core::{IdeError, IdeResult};
use std::io::Read;
use std::path::{Path, PathBuf};
const RELEASES: &str = "https://github.com/l0ng-ai/openidea/releases/download";
@@ -65,18 +66,42 @@ pub fn fetch(
let unpacked = staging.join("openidea-server");
let mut gz = flate2::read::GzDecoder::new(std::fs::File::open(&archive)?);
std::io::copy(&mut gz, &mut std::fs::File::create(&unpacked)?)?;
drop(gz);
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&unpacked, std::fs::Permissions::from_mode(0o755))?;
}
std::fs::rename(&unpacked, &dest)?;
// The executable is the cache entry; keeping the archive only optimizes SSH uploads.
let _ = std::fs::rename(archive, dest.with_extension("gz"));
Ok(dest.clone())
})();
let _ = std::fs::remove_dir_all(&staging);
result
}
/// The cached release gzip, if it unpacks to the selected server binary.
pub fn matching_archive(binary: &Path, expected: blake3::Hash) -> Option<Vec<u8>> {
let archive = binary.with_extension("gz");
let binary_size = binary.metadata().ok()?.len();
let meta = archive.metadata().ok()?;
if !meta.is_file() || meta.len() >= binary_size {
return None;
}
let mut packed = Vec::with_capacity(meta.len().try_into().ok()?);
std::fs::File::open(archive).ok()?.take(binary_size).read_to_end(&mut packed).ok()?;
if packed.len() as u64 >= binary_size {
return None;
}
// The receiver decodes every gzip member. Read one byte past the expected size
// so a correct-sized stream still has its trailer and any remaining input checked.
let gzip = flate2::read::MultiGzDecoder::new(packed.as_slice());
let mut hash = blake3::Hasher::new();
let decoded_size = std::io::copy(&mut gzip.take(binary_size.checked_add(1)?), &mut hash).ok()?;
(decoded_size == binary_size && hash.finalize() == expected).then_some(packed)
}
fn tempfile_dir(parent: &Path) -> IdeResult<PathBuf> {
// Unique per call: two windows of this process may download at once.
static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
@@ -98,6 +123,38 @@ mod tests {
assert_eq!(p, Path::new("/data/server/1.2.3/linux-aarch64/openidea-server"));
}
#[test]
fn cached_archive_must_decode_to_the_selected_build() {
use std::io::Write as _;
let pack = |bytes: &[u8]| {
let mut gzip = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::best());
gzip.write_all(bytes).unwrap();
gzip.finish().unwrap()
};
let tmp = tempfile::tempdir().unwrap();
let binary = tmp.path().join("openidea-server");
let archive = binary.with_extension("gz");
let payload = [b'a'; 4096];
let expected = blake3::hash(&payload);
std::fs::write(&binary, payload).unwrap();
assert!(matching_archive(&binary, expected).is_none());
let gzip = pack(&payload);
std::fs::write(&archive, &gzip).unwrap();
assert_eq!(matching_archive(&binary, expected), Some(gzip.clone()));
let extra_member = pack(b"extra output");
for invalid in [
pack(&[b'b'; 4096]),
gzip[..gzip.len() - 1].to_vec(),
[gzip.as_slice(), &extra_member].concat(),
[gzip.as_slice(), b"trailing junk"].concat(),
] {
std::fs::write(&archive, &invalid).unwrap();
assert!(matching_archive(&binary, expected).is_none());
}
}
#[test]
fn unsupported_hosts_are_refused_without_downloading() {
let tmp = tempfile::tempdir().unwrap();
+31 -6
Переглянути файл
@@ -522,7 +522,7 @@ impl SettingsStore {
pub struct JetBrainsSettings {
pub entries: Vec<String>,
/// Entry name → text, for the files OpenIDEA reads: `colors/*.icls`, `keymaps/*.xml`,
/// `codestyles/*.xml` and some of `options/`.
/// `codestyles/*.xml`, `templates/*.xml` and some of `options/`.
pub files: BTreeMap<String, String>,
}
@@ -540,7 +540,8 @@ const JETBRAINS_OPTIONS: [&str; 9] = [
"options/linux/keymap.xml",
];
/// Folders whose files are all read: (folder, extension).
const JETBRAINS_READ_DIRS: [(&str, &str); 3] = [("colors/", ".icls"), ("keymaps/", ".xml"), ("codestyles/", ".xml")];
const JETBRAINS_READ_DIRS: [(&str, &str); 4] =
[("colors/", ".icls"), ("keymaps/", ".xml"), ("codestyles/", ".xml"), ("templates/", ".xml")];
const JETBRAINS_MAX_TEXT: u64 = 4 << 20;
/// The settings of a JetBrains IDE: an exported `settings.zip`, or the IDE's own settings folder
@@ -999,6 +1000,7 @@ mod tests {
"reformat": false,
"optimizeImports": false,
"cleanup": false,
"fixOnCommit": false,
"blankLineAfterSubject": true,
"limitSubject": true,
"subjectLimit": 72,
@@ -1146,12 +1148,15 @@ mod tests {
("keymaps/macOS.xml", "<keymap/>"),
("keymaps/nested/ignored.xml", "<keymap/>"),
("codestyles/Default.xml", "<code_scheme/>"),
("templates/Python.xml", "<templateSet name=\"Python\"/>"),
("templates/nested/ignored.xml", "<templateSet/>"),
("templates/ignored.txt", "not XML"),
("options/mac/keymap.xml", "<application/>"),
("options/terminal-font.xml", "<application/>"),
],
);
let read = read_jetbrains_settings(&ok).unwrap();
assert_eq!(read.entries.len(), 9);
assert_eq!(read.entries.len(), 12);
assert_eq!(
read.files.keys().collect::<Vec<_>>(),
[
@@ -1160,7 +1165,8 @@ mod tests {
"keymaps/macOS.xml",
"options/editor-font.xml",
"options/mac/keymap.xml",
"options/terminal-font.xml"
"options/terminal-font.xml",
"templates/Python.xml"
]
);
assert!(read_jetbrains_settings(&write("other.zip", &[("options/editor.xml", "")])).is_err());
@@ -1184,6 +1190,8 @@ mod tests {
put("options/mac/keymap.xml", "<application/>");
put("keymaps/macOS.xml", "<keymap/>");
put("codestyles/Default.xml", "<code_scheme/>");
put("templates/Python.xml", "<templateSet name=\"Python\"/>");
put("templates/nested/ignored.xml", "<templateSet/>");
put("plugins/Tools/lib/tools.jar", "jar");
let read = read_jetbrains_settings(&config).unwrap();
@@ -1194,7 +1202,8 @@ mod tests {
"colors/_@user_Darcula.icls",
"keymaps/macOS.xml",
"options/editor-font.xml",
"options/mac/keymap.xml"
"options/mac/keymap.xml",
"templates/Python.xml"
]
);
assert_eq!(
@@ -1206,6 +1215,7 @@ mod tests {
"colors/_@user_Darcula.icls",
"keymaps/macOS.xml",
"codestyles/Default.xml",
"templates/Python.xml",
"installed.txt"
]
);
@@ -1243,13 +1253,28 @@ mod tests {
}
#[test]
fn jetbrains_folder_bounds_mapped_text_like_an_archive() {
fn jetbrains_folder_and_archive_bound_mapped_template_text() {
use std::io::Write;
let tmp = tempfile::tempdir().unwrap();
std::fs::create_dir(tmp.path().join("options")).unwrap();
std::fs::create_dir(tmp.path().join("templates")).unwrap();
std::fs::write(tmp.path().join("options/editor-font.xml"), vec![b'x'; JETBRAINS_MAX_TEXT as usize + 1])
.unwrap();
let large = vec![b'x'; JETBRAINS_MAX_TEXT as usize + 1];
std::fs::write(tmp.path().join("templates/Python.xml"), &large).unwrap();
let read = read_jetbrains_settings(tmp.path()).unwrap();
assert_eq!(read.files["options/editor-font.xml"].len(), JETBRAINS_MAX_TEXT as usize);
assert_eq!(read.files["templates/Python.xml"].len(), JETBRAINS_MAX_TEXT as usize);
let archive = tmp.path().join("settings.zip");
let mut zip = zip::ZipWriter::new(std::fs::File::create(&archive).unwrap());
zip.start_file(JETBRAINS_MARKER, zip::write::SimpleFileOptions::default()).unwrap();
zip.start_file("templates/Python.xml", zip::write::SimpleFileOptions::default()).unwrap();
zip.write_all(&large).unwrap();
zip.finish().unwrap();
let read = read_jetbrains_settings(&archive).unwrap();
assert_eq!(read.files["templates/Python.xml"].len(), JETBRAINS_MAX_TEXT as usize);
}
#[test]
+27
Переглянути файл
@@ -3,6 +3,16 @@ use ide_core::{IdeError, IdeResult};
use serde::{Deserialize, Serialize};
use std::path::PathBuf;
/// Selects every open project window eligible to merge with `caller`.
/// `is_project` returns `true` for open local or remote project windows and `false` for
/// non-project windows (welcome screen, LightEdit).
pub fn merge_candidates(windows: &[String], caller: &str, is_project: impl Fn(&str) -> bool) -> Vec<String> {
if !is_project(caller) {
return Vec::new();
}
windows.iter().filter(|label| is_project(label)).cloned().collect()
}
/// Platform adapters supply the system's tab preference and active project state.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TabbingPreference {
@@ -269,4 +279,21 @@ mod tests {
// A grouped window still opening its project: keep the previous session.
assert_eq!(session(&groups, &windows, |l| (l != "project-2").then(|| PathBuf::from(l))), None);
}
#[test]
fn merge_candidates_includes_local_and_remote_project_windows() {
let windows = members(&["local-1", "local-2", "ssh-a-1", "ssh-b-1", "welcome", "light"]);
let is_project = |label: &str| matches!(label, "local-1" | "local-2" | "ssh-a-1" | "ssh-b-1");
assert_eq!(
merge_candidates(&windows, "local-1", is_project),
members(&["local-1", "local-2", "ssh-a-1", "ssh-b-1"])
);
assert_eq!(
merge_candidates(&windows, "ssh-a-1", is_project),
members(&["local-1", "local-2", "ssh-a-1", "ssh-b-1"])
);
assert!(merge_candidates(&windows, "welcome", is_project).is_empty());
assert!(merge_candidates(&windows, "light", is_project).is_empty());
}
}
+8 -1
Переглянути файл
@@ -40,6 +40,10 @@ When switching to JDBC, configure TLS and driver-specific settings in the JDBC U
Select the profile, enter the vendor's JDBC URL, and use the **User**, **Password**, and **Advanced** fields for credentials and driver properties. The URL and Advanced properties are stored in the data source configuration. Put credentials in the password field to use the existing OS credential store. On Linux, saving a password requires a running Secret Service. You can also enter the password for the current session. The **Read-only** option asks the JDBC driver for a read-only connection. Use a database account with read-only privileges to enforce it. Cancelling a query keeps the session and its temporary tables when the driver stops the statement. If the driver does not respond within three seconds, OpenIDEA closes the session. A submitted statement can still finish on the server. **Test Connection** reports the database product and version. Schema, table and column browsing use JDBC metadata; the SQL console supports auto-commit queries and updates. Vendor-specific DDL, execution plans and table-grid writes are unavailable for custom drivers.
Each SQL console uses its own JDBC connection. Use the same console for statements that need its temporary tables or session settings. Other consoles can run queries while it is busy. OpenIDEA keeps the connection until you close the console and its result tabs.
DuckDB consoles share the same database, including an in-memory database. Anonymous SQLite and H2 databases belong to one connection, so their consoles share that connection. For independent consoles on the same in-memory database, use a named URL such as `jdbc:sqlite:file:work?mode=memory&cache=shared` or `jdbc:h2:mem:work`.
For a file-backed database, use an absolute path to choose its location. Relative paths start in the persistent `jdbc/files` folder inside OpenIDEA’s application data directory.
Profiles are reused across projects. If a project file changes a connection's URL or properties outside the IDE, review the settings in the data source dialog and save them before reconnecting.
@@ -140,6 +144,7 @@ The console toolbar has:
- **Browse Query History**: the last 500 statements per data source, with search and **Paste**.
- A row limit (100 to 50,000; default 500).
- **Tx: Auto** / **Tx: Manual**. In manual mode **Commit** and **Roll Back** appear.
With the built-in PostgreSQL driver, each console owns its manual transaction. Retained result tabs keep access to that console until its last tab closes. Closing the last tab rolls back pending work. Switching the console to **Tx: Auto** also releases its transaction slot, including after a read-only query.
- A schema picker (PostgreSQL, MySQL, SQL Server, Oracle, Snowflake) and the data source picker. Snowflake consoles also have warehouse and role pickers.
Statements are split on `;`, respecting strings, comments and PostgreSQL dollar quoting. Oracle PL/SQL blocks are kept whole, and a line with only `/` ends a statement. Snowflake `$$` bodies and Snowflake Scripting blocks (`BEGIN … END`, `DECLARE …`) are kept whole too. Parameters such as `:id`, `?`, `$1` or `@name` open a **Parameters** dialog; values are inserted as SQL text, so quote strings.
@@ -193,9 +198,11 @@ The export button offers **Export Data…** and quick copies: **Copy as CSV**, *
The built-in HTTP driver uses a named session by default (`use_http_session=true`). Route requests to one node or enable session affinity. If the session expires or another node reports code 372, OpenIDEA shows a reconnect error and never replays the statement.
The HTTP driver waits up to 600 seconds for response headers or the next part of a response body. To change this interval, set `http_read_timeout` in **Advanced** to a positive whole number of seconds. The interval restarts when body data arrives, so a streaming query can run longer. If the response times out, OpenIDEA reports that the query outcome is unknown and shows its `query_id`. Verify the outcome before retrying a write.
For endpoints that route each request to a different node, add **Advanced** property `use_http_session` with value `false`. Each request omits `session_id`, `session_check` and `session_timeout`, and sends the configured database (or **Default schema**), time zone and Advanced settings again. **Read-only** sends `readonly=1` on every request.
Stateless statements must be independent: `USE`, standalone `SET`, temporary tables and other session state cannot carry over to later requests. Configure the database and settings on the data source. Startup scripts and explicit session properties (`session_id`, `session_check`, `session_timeout`) are rejected. SQL transactions and statement caching are unsupported in either mode.
In stateless mode, the driver rejects standalone session changes such as `SET max_threads = 2` before sending them. A console script stops there. Set a data source property for all requests or add a `SETTINGS` clause to a query that supports it. Choose the database on the data source. `USE` and temporary tables cannot carry state between requests. Startup scripts and explicit session properties (`session_id`, `session_check`, `session_timeout`) are rejected. SQL transactions and statement caching are unsupported in either mode.
For strict read-only accounts behind a load balancer, set `use_http_session=false` and enable **Read-only**. If the initial connection check receives ClickHouse code 164 for a driver-managed result setting, OpenIDEA repeats the check without its result-limit and JSON number-format settings. Each request still sends `readonly=1`, and the grid still retains only the requested page. Configure server-side limits in the account's settings profile. With the server's default JSON settings, `NaN` and infinities may appear as `NULL`.
+13 -12
Переглянути файл
@@ -83,18 +83,18 @@ While the server runs, OpenIDEA writes its port and token to `mcp/server.json` i
## Tools
| Area | Tools |
| ------------- | ------------------------------------------------------------------------------------------------- |
| Files | `get_workspace_roots`, `read_file`, `list_directory_tree`, `create_new_file`, `apply_patch` |
| Search | `search_text`, `search_regex`, `search_symbol`, `search_file` |
| Editors | `get_all_open_file_paths`, `get_current_file`, `open_file_in_editor` |
| Code | `get_symbol_info`, `find_references`, `get_call_hierarchy`, `rename_refactoring`, `reformat_file` |
| Problems | `get_file_problems`, `get_project_problems`, `check_files` |
| Run and build | `get_run_configurations`, `execute_run_configuration`, `build_project` |
| Commands | `run_command`, `wait_for_run`, `send_run_input`, `stop_run` |
| Command state | `get_run_status`, `read_run_output`, `list_runs` |
| Git | `get_repositories`, `git_status`, `git_diff` |
| HTTP Client | `http_list_requests`, `http_run_request` |
| Area | Tools |
| ------------- | --------------------------------------------------------------------------------------------------------------------- |
| Files | `get_workspace_roots`, `read_file`, `list_directory_tree`, `create_new_file`, `apply_patch` |
| Search | `search_text`, `search_regex`, `search_symbol`, `search_file` |
| Editors | `get_all_open_file_paths`, `get_current_file`, `open_file_in_editor` |
| Code | `get_symbol_info`, `find_references`, `get_call_hierarchy`, `rename_refactoring`, `reformat_file`, `optimize_imports` |
| Problems | `get_file_problems`, `get_project_problems`, `check_files` |
| Run and build | `get_run_configurations`, `execute_run_configuration`, `build_project` |
| Commands | `run_command`, `wait_for_run`, `send_run_input`, `stop_run` |
| Command state | `get_run_status`, `read_run_output`, `list_runs` |
| Git | `get_repositories`, `git_status`, `git_diff` |
| HTTP Client | `http_list_requests`, `http_run_request` |
Notes on what they do:
@@ -109,6 +109,7 @@ Notes on what they do:
- `get_file_problems` and `get_project_problems` return what the Problems tool window shows, after your inspection profile is applied, rather than a fresh analysis.
- `check_files` is the fresh analysis, for after an edit made by any tool: it syncs each file from disk, tells its language servers it was saved (so on-save checks such as `cargo check` run) and waits until they answered and finished. Each file gets a `status` that says whether the problems are complete, or why it could not be checked: no language server for it, or one that is not installed, misconfigured or crashed.
- `rename_refactoring` renames through the language server, so references that a text search would miss are updated too. It can preview without writing.
- `reformat_file` applies the code formatter; `optimize_imports` removes unused imports and orders the remaining ones without reformatting. Both return a unified diff capped at 200 lines, and `reformat_file` can do both jobs with `optimizeImports: true`.
- `apply_patch` accepts the Codex `apply_patch` format and unified diffs. Paths must stay inside the project.
- `git_diff` compares files on disk, so unsaved editor text is not included.
- `http_list_requests` lists requests in a project `.http` / `.rest` file; `http_run_request` sends one by index (optional `env` from `http-client.env.json`), asks first, and returns status plus a truncated body — not request headers or body.
+6 -1
Переглянути файл
@@ -37,11 +37,16 @@ Use **File › Manage IDE Settings › Import Settings from JetBrains IDE…** a
A confirmation lists what will be imported before anything changes:
- Color schemes (the `.icls` files) and the color scheme in use
- Keymaps and the active keymap
- Editor font: family, size, line spacing (as line height) and ligatures
- Trailing-space stripping, final newline on save, sticky lines, whitespace display, soft wraps
- Tabs and indents from the current code style scheme
- Live templates from `templates/*.xml`, including their groups, abbreviations, `$VAR$` bodies, variables and mapped language contexts
- **Confirm before exiting the IDE**
Keymaps, code styles, live templates, inspection profiles and plugins are not imported; the confirmation lists the ones it skipped. Imported values go to the global settings.
The confirmation shows imported and skipped live-template counts before anything is written. Cancelling changes nothing. Imported templates join the per-user custom templates without replacing built-ins or unrelated templates; importing again updates the same `jetbrains.*` ids instead of adding duplicates. Unknown or ambiguous contexts are listed as skipped rather than made global. Unsupported macro expressions are preserved as text for editing but are not evaluated; imported defaults still apply, otherwise the field remains editable.
Inspection profiles, plugins and code style options other than Tabs and Indents are not imported; the confirmation lists them as skipped. Imported settings go to the global settings layer.
### Import a theme
+8
Переглянути файл
@@ -17,6 +17,14 @@ After expansion, the caret is in the first field. `⇥` / `Tab` moves to the nex
Built-in templates exist for Rust, JavaScript / TypeScript, Python, Go, Java, Kotlin, PHP and SQL, plus a few general ones (`todo`, `fixme`, `hack`, `date`). **Insert Live Template…** lists the templates that apply at the caret. By default templates expand only in code, not in comments or strings.
### Import from JetBrains
Choose **File › Manage IDE Settings › Import Settings from JetBrains IDE…** to use an IDE's settings directory on this computer, or **Import Settings…** to select an exported `settings.zip`. The importer reads `templates/*.xml` and lists the imported and skipped counts before writing. Cancel leaves existing templates unchanged.
Template groups, abbreviations, descriptions, `$VAR$` bodies, variable expressions/defaults and language contexts are preserved. JetBrains `alwaysStopAt="false"` becomes **Skip if defined**. Imports use stable `jetbrains.*` ids, so importing again updates the same templates without replacing built-ins or unrelated custom templates.
Unknown or ambiguous contexts are skipped, not treated as global. Macro expressions OpenIDEA cannot evaluate are preserved as expression text and listed in the confirmation; imported defaults still apply, otherwise the field stays editable. Malformed XML is reported and none of that file's templates are imported.
### Surround With
Select code and press `⌥⌘T` / `Ctrl+Alt+T`. The list starts with the language's wrappers (`if`, `while`, `try` and so on), followed by live templates that use `$SELECTION$`. **Surround with Live Template…** shows only the latter.
+2 -1
Переглянути файл
@@ -91,7 +91,7 @@ Changelists group local changes without touching Git. The default list is called
The gear button (**Commit Options**) next to **Commit** has:
- **Author:** to commit as someone else (`Name <email>`), and **Sign-off commit**.
- **Commit Checks**: **Reformat code**, **Optimize imports**, **Cleanup** (applies fix-all code actions) and **Run Git hooks** (off adds `--no-verify`).
- **Commit Checks**: **Reformat code**, **Optimize imports**, **Cleanup** (applies fix-all code actions), **Fix Ruff safe lint issues** (`ruff check --fix-only` on Python files before composing the commit, separate from formatting) and **Run Git hooks** (off adds `--no-verify`).
- **Advanced Commit Checks**: **Analyze code** (errors and warnings from the language servers) and **Check TODO** (matches from **Settings › Editor › TODO** in changed lines).
Create named TODO filters in **Settings › Editor › TODO**. Choose one from **Configure** beside **Check TODO** to check only its patterns. The Commit tool window and TODO tool window save their selections separately for each project. **Review TODOs** opens a tab in the TODO tool window with every finding and a preview of the checked content. Open a finding to jump to its source or diff. If a selected file cannot be checked, the result lists the file and the reason so you can address it before retrying.
@@ -247,6 +247,7 @@ Turn on **Combine stashes and shelves in one tab** in the Git settings to show b
## Blame and history
- **Annotate with Git Blame** shows author and date per line in the gutter (also from the gutter's context menu). Click an entry to open the commit in the log. **Show inline blame for the current line** in the Git settings shows the author at the end of the caret line; a click on it opens the commit unless **Open the commit when the inline blame is clicked** is off.
- **Options › Colors** in the gutter's context menu tints the gutter by **Author**, by **Order** of changes (the default) or not at all (**Hide**) in every annotated editor.
- **Options › Names** in the gutter's context menu shows authors as **Initials**, **Last Name** (the default), **First Name** or **Full Name** in every annotated editor.
- **Annotate Revision** in an annotated line's menu opens the file as it was at that commit, annotated, next to the working copy. A file renamed since then is read under its name at that commit.
- **Annotate Previous Revision** in an annotated line's menu opens the file as it was before that commit, annotated, next to the commit's version.
+1 -1
Переглянути файл
@@ -136,7 +136,7 @@ See [Debugging](/en/guide/debugging).
- **Spring Boot run configurations** are created from `@SpringBootApplication` classes, and they are listed in the **Services** tool window by default.
- **Configuration navigation**: Go to Definition on a key in `application.yml` or `.properties` opens the Java members bound to it (`@ConfigurationProperties`, `@Value`, `Environment.getProperty`). It also works the other way, from `${…}` placeholders in Java, YAML, properties or Spring XML. Keys described by `spring-configuration-metadata.json` in dependencies resolve to their source classes. **Find Usages** on a key lists configuration declarations and Java usages together.
- **Thymeleaf templates**: `.html` files in a project with `src/main/resources/templates` highlight `th:*` and `data-th-*` values as Thymeleaf expressions and complete the attribute names after `th:`. Go to Declaration on a fragment expression (`~{fragments/nav :: menu}`, or the bare form in `th:replace` / `th:insert`) opens the template or its `th:fragment`; on a message key (`#{home.title}`) it lists the key in each `messages*.properties` of the bundles set by `spring.messages.basename`.
- **Thymeleaf templates**: `.html` files in a project with `src/main/resources/templates` highlight `th:*` and `data-th-*` values as Thymeleaf expressions and complete the attribute names after `th:`. Go to Declaration on a fragment expression (`~{fragments/nav :: menu}`, or the bare form in `th:replace` / `th:insert`) opens the template or its `th:fragment`; on a message key (`#{home.title}`) it lists the key in each `messages*.properties` of the bundles set by `spring.messages.basename`. A fragment expression that names a fragment the template does not define (no `th:fragment`, `th:ref` or element of that name; an `id` of that name is tolerated too) is underlined as a warning, and so is a missing template in a single-module project; not when `application.properties` / `.yml` sets `spring.thymeleaf.prefix` or `suffix`, or for a `~{…} ?: …` fallback.
- **Spring Web endpoints**: request mappings in Java and Kotlin controllers get a gutter icon, plus **Generate Request in HTTP Client** and **Generate Requests for Controller** actions that write requests to a scratch `.http` file. Search Everywhere matches request paths in its **All** tab. See [HTTP Client](/en/guide/http-client).
- **Facets** in **Project Structure** (`⌘;` / `Ctrl+Alt+Shift+S`) record the frameworks a module uses (Web, Spring, JPA). A Web facet also adds its `WEB-INF/lib/*.jar` to the jdtls classpath.
+3 -1
Переглянути файл
@@ -94,7 +94,9 @@ Other options on the page:
### Formatting
**Reformat Code** (`⌘⌥L` / `Ctrl+Alt+L`) uses Ruff. In **Settings › Languages & Frameworks › Ruff** you can set the Ruff path, a configuration directory, the **Formatting provider** (**Automatic (language server first)** or Ruff), and **Run on save**. Without a configuration directory, Ruff reads the nearest `pyproject.toml` (`[tool.ruff]`), `ruff.toml` or `.ruff.toml`. When neither the project nor your user configuration has one, Ruff formats with the indentation and line length the editor uses: the file's `.editorconfig` (`indent_size`, `indent_style`, `max_line_length`), then the indent, tab character and hard wrap you set in **Settings › Editor › Code Style › Python**. Values set in neither are not passed, so Ruff keeps its own (4 spaces, 88 columns).
**Reformat Code** (`⌘⌥L` / `Ctrl+Alt+L`) uses Ruff. In **Settings › Languages & Frameworks › Ruff** you can set the Ruff path, a configuration directory, the **Formatting provider** (**Automatic (language server first)** or Ruff), and **Format on save**. Without a configuration directory, Ruff reads the nearest `pyproject.toml` (`[tool.ruff]`), `ruff.toml` or `.ruff.toml`. When neither the project nor your user configuration has one, Ruff formats with the indentation and line length the editor uses: the file's `.editorconfig` (`indent_size`, `indent_style`, `max_line_length`), then the indent, tab character and hard wrap you set in **Settings › Editor › Code Style › Python**. Values set in neither are not passed, so Ruff keeps its own (4 spaces, 88 columns).
**Fix safe lint issues on save** is off by default and runs `ruff check --fix-only` on the current unsaved Python text before it is written. It applies only Ruff's safe fixes, not formatting, honors the project's exclusions, and does not depend on the formatting provider or either on-save formatting option. Enable **Fix Ruff safe lint issues** under **Settings › Version Control › Commit › Commit Checks** (or in **Commit Options**) to run the same fixes over each committed Python file before composing a commit. Partial commits keep excluded changes out.
Black formats instead of Ruff below a `pyproject.toml` with a `[tool.black]` table, or everywhere when **Formatting provider** is set to Black in **Settings › Languages & Frameworks › Black formatter**. Black reads its `[tool.black]` options itself. The IDE runs the `black` of the project interpreter's environment, else the one in its tools folder or on `PATH`; when none is installed, Reformat Code offers to install it. **Reformat with Black** in Find Action formats with Black whatever the project uses. Black runs on save when its own **Run on save** or the editor's **Format on save** is on. Without a `[tool.black]` (looked up the way Black does: past a `pyproject.toml` without it, up to the repository root) or a user configuration, Black uses that line length too. Files Black's configuration excludes (`force-exclude`) are left unchanged, and Black before 23.11 formats the whole file instead of a selection.
+16 -14
Переглянути файл
@@ -206,19 +206,21 @@ Settings › Appearance & Behavior › System Settings › HTTP Proxy. Used by t
### Other sections
| Key | Description |
| ------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------- |
| `[actionsOnSave]` | `optimizeImports`, `cleanup` (Tools › Actions on Save). |
| `[mcpServer]` | `enabled`, `backgroundProjects` and the related options (Agents › IDE MCP Server, global only). See [MCP server](/en/guide/mcp). |
| `[agents]` | What agent task headers show (Tools › Agents › Chat). |
| `[languages]` | Interpreters, SDKs and options per language, e.g. `[languages.java]`, `[languages.python]`, `[languages.go]`. |
| `[languageServers]` | Per language server, by name: launch and protocol options, or a server defined here. |
| `[tools]` | Language servers and debug adapters at a location you chose, by command name. |
| `[vcs]`, `[console]`, `[debugger]`, `[run]` | Version Control, Console, Debugger and Run/Debug pages. |
| `[inspections]`, `[spelling]` | Editor › Inspections, Editor › Natural Languages › Spelling. |
| `[ssh]`, `[deployment]`, `runTargets`, `[cmake]` | SSH Configurations, Deployment, Run Targets, CMake. |
| `[projectStructure]` | Source, test, resource and excluded folders (Project Structure). |
| `externalTools` | Tools › External Tools entries. |
| `[plugins.<plugin-id>]` | Settings that plugins declare. |
| Key | Description |
| ------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------- |
| `[actionsOnSave]` | `optimizeImports`, `cleanup` (Tools › Actions on Save). |
| `[mcpServer]` | `enabled`, `backgroundProjects` and the related options (Agents › IDE MCP Server, global only). See [MCP server](/en/guide/mcp). |
| `[agents]` | What agent task headers show (Tools › Agents › Chat). |
| `[languages]` | Interpreters, SDKs and options per language, e.g. `[languages.java]`, `[languages.python]`, `[languages.go]`. |
| `[languages.ruff]` | Ruff `path`, `configurationDirectory`, `languages`, `prefer`, formatting `runOnSave`, and safe-fix `fixOnSave` (default `false`). |
| `[vcs.commit]` | Before-commit checks and modifications, including `fixOnCommit` for Ruff safe lint fixes (default `false`). |
| `[languageServers]` | Per language server, by name: launch and protocol options, or a server defined here. |
| `[tools]` | Language servers and debug adapters at a location you chose, by command name. |
| `[vcs]`, `[console]`, `[debugger]`, `[run]` | Version Control, Console, Debugger and Run/Debug pages. |
| `[inspections]`, `[spelling]` | Editor › Inspections, Editor › Natural Languages › Spelling. |
| `[ssh]`, `[deployment]`, `runTargets`, `[cmake]` | SSH Configurations, Deployment, Run Targets, CMake. |
| `[projectStructure]` | Source, test, resource and excluded folders (Project Structure). |
| `externalTools` | Tools › External Tools entries. |
| `[plugins.<plugin-id>]` | Settings that plugins declare. |
The complete list of keys and their defaults is in the source: [`crates/ide-core/src/settings.rs`](https://github.com/l0ng-ai/openidea/blob/main/crates/ide-core/src/settings.rs) and the other `*_settings.rs` files next to it.
+8 -1
Переглянути файл
@@ -40,6 +40,10 @@ description: "连接 SQL 数据库、浏览架构、在查询控制台中执行
选择驱动配置,填写厂商的 JDBC URL,在 **用户**、**密码** 和 **高级** 中设置凭据和驱动属性。通过密码字段输入的密码可以保存到系统凭据库。在 Linux 上,保存密码需要正在运行的 Secret Service;也可以仅为当前会话输入密码。**测试连接** 显示数据库产品和版本。可以通过 JDBC 元数据浏览模式、表和列,在 SQL 控制台中查询或以自动提交方式更新数据。自定义驱动不支持厂商特有的 DDL、执行计划或表格编辑。
每个 SQL 控制台使用独立的 JDBC 连接。依赖临时表或会话设置的语句应在同一控制台中执行,其他控制台可以同时运行查询。关闭控制台及其结果标签页后,OpenIDEA 会释放连接。
DuckDB 的各个控制台共享同一个数据库,包括内存数据库。SQLite 和 H2 的匿名数据库仅属于一个连接,因此其控制台会共用该连接。如需让多个控制台通过独立连接访问同一个内存数据库,可使用命名 URL,例如 `jdbc:sqlite:file:work?mode=memory&cache=shared` 或 `jdbc:h2:mem:work`。
文件数据库可使用绝对路径指定存储位置。相对路径以 OpenIDEA 应用数据目录下的持久化 `jdbc/files` 文件夹为起点。
驱动配置可以跨项目复用。在 IDE 外更改项目数据源的 URL 或连接属性后,需要在数据源对话框中检查并保存设置,才能重新连接。
@@ -140,6 +144,7 @@ description: "连接 SQL 数据库、浏览架构、在查询控制台中执行
- **浏览查询历史记录**:每个数据源最近 500 条语句,可搜索并粘贴回控制台。
- 行数上限(100 到 50,000,默认 500)。
- **事务:自动** / **事务:手动**。手动模式下会出现 **提交** 和 **回滚**。
使用内置 PostgreSQL 驱动时,每个控制台都有独立的手动事务。保留的结果标签页仍可访问所属控制台。最后一个标签页关闭时,未提交的更改会被回滚。即使只执行过只读查询,切换到 **事务:自动** 也会释放事务连接。
- 架构选择器(PostgreSQL、MySQL、SQL Server、Oracle、Snowflake)和数据源选择器。Snowflake 控制台还提供仓库和角色选择器。
语句按 `;` 拆分,会正确处理字符串、注释和 PostgreSQL 的美元引号。Oracle 的 PL/SQL 块保持完整,只有 `/` 的一行表示语句结束。`:id`、`?`、`$1`、`@name` 等参数会弹出 **参数** 对话框;值按 SQL 文本插入,字符串需要自己加引号。
@@ -192,9 +197,11 @@ SQL 补全基于已连接的架构:`FROM`/`JOIN` 后补全表(并根据外
内置 HTTP 驱动默认使用命名会话(`use_http_session=true`)。请求应路由到同一节点,或启用会话亲和性。如果会话过期或其他节点返回代码 372,OpenIDEA 会提示重新连接,且不会重放语句。
HTTP 驱动默认最多等待 600 秒接收响应标头或响应正文的下一部分。如需调整,请在 **高级** 中将 `http_read_timeout` 设为正整数秒数。收到正文数据后会重新计时,因此流式查询可以运行更长时间。如果响应超时,OpenIDEA 会提示查询结果未知,并显示 `query_id`。重试写入前请先确认执行结果。
如果端点把每个请求路由到不同节点,可在 **高级** 中添加属性 `use_http_session`,值设为 `false`。每个请求都省略 `session_id`、`session_check` 和 `session_timeout`,并重新发送配置的数据库(或 **默认架构**)、时区及高级设置。启用 **只读** 时,每个请求都发送 `readonly=1`。
无会话模式下,每条语句必须独立:`USE`、独立的 `SET`、临时表及其他会话状态无法延续到后续请求。请在数据源中配置数据库和设置。驱动会拒绝启动脚本以及显式会话属性(`session_id`、`session_check`、`session_timeout`)。两种模式均不支持 SQL 事务和语句缓存。
在无会话模式下,驱动会在发送前拒绝独立的会话设置语句,例如 `SET max_threads = 2`。控制台脚本遇到该错误时会停止。可在数据源属性中为所有请求指定设置,或在支持的查询中添加 `SETTINGS` 子句。请在数据源中选择数据库。`USE` 和临时表的状态无法延续到后续请求。驱动会拒绝启动脚本以及显式会话属性(`session_id`、`session_check`、`session_timeout`)。两种模式均不支持 SQL 事务和语句缓存。
对于负载均衡器后的严格只读账户,请设置 `use_http_session=false` 并启用 **只读**。如果初次连接检查因驱动管理的结果设置收到 ClickHouse 错误码 164,OpenIDEA 会省略驱动的结果行数限制和 JSON 数字格式设置,再进行一次连接检查。每个请求仍会发送 `readonly=1`,结果表格仍只保留所请求的一页。请在账户的设置配置文件中配置服务端限制。使用服务器的默认 JSON 设置时,`NaN` 和无穷值可能显示为 `NULL`。
+13 -12
Переглянути файл
@@ -82,18 +82,18 @@ stdio 配置大致如下(路径以你机器上的为准):
## 工具
| 类别 | 工具 |
| ----------- | ------------------------------------------------------------------------------------------------- |
| 文件 | `get_workspace_roots`、`read_file`、`list_directory_tree`、`create_new_file`、`apply_patch` |
| 搜索 | `search_text`、`search_regex`、`search_symbol`、`search_file` |
| 编辑器 | `get_all_open_file_paths`、`get_current_file`、`open_file_in_editor` |
| 代码 | `get_symbol_info`、`find_references`、`get_call_hierarchy`、`rename_refactoring`、`reformat_file` |
| 问题 | `get_file_problems`、`get_project_problems`、`check_files` |
| 运行与构建 | `get_run_configurations`、`execute_run_configuration`、`build_project` |
| 命令 | `run_command`、`wait_for_run`、`send_run_input`、`stop_run` |
| 命令状态 | `get_run_status`、`read_run_output`、`list_runs` |
| Git | `get_repositories`、`git_status`、`git_diff` |
| HTTP 客户端 | `http_list_requests`、`http_run_request` |
| 类别 | 工具 |
| ----------- | --------------------------------------------------------------------------------------------------------------------- |
| 文件 | `get_workspace_roots`、`read_file`、`list_directory_tree`、`create_new_file`、`apply_patch` |
| 搜索 | `search_text`、`search_regex`、`search_symbol`、`search_file` |
| 编辑器 | `get_all_open_file_paths`、`get_current_file`、`open_file_in_editor` |
| 代码 | `get_symbol_info`、`find_references`、`get_call_hierarchy`、`rename_refactoring`、`reformat_file`、`optimize_imports` |
| 问题 | `get_file_problems`、`get_project_problems`、`check_files` |
| 运行与构建 | `get_run_configurations`、`execute_run_configuration`、`build_project` |
| 命令 | `run_command`、`wait_for_run`、`send_run_input`、`stop_run` |
| 命令状态 | `get_run_status`、`read_run_output`、`list_runs` |
| Git | `get_repositories`、`git_status`、`git_diff` |
| HTTP 客户端 | `http_list_requests`、`http_run_request` |
几点说明:
@@ -108,6 +108,7 @@ stdio 配置大致如下(路径以你机器上的为准):
- `get_file_problems` 和 `get_project_problems` 返回的是问题工具窗口当前显示的内容(已应用你的检查配置文件),而不是重新分析的结果。
- `check_files` 才是重新分析,适合在任何工具修改文件之后调用:它从磁盘同步每个文件,通知语言服务器文件已保存(这样 `cargo check` 等保存时检查也会运行),并等到服务器答复且分析完成。每个文件都有一个 `status`,说明问题列表是否完整,或者为什么无法检查:没有对应的语言服务器,或者服务器未安装、配置错误、已崩溃。
- `rename_refactoring` 通过语言服务器重命名,文本搜索找不到的引用也会一并更新;也可以只预览不写入。
- `reformat_file` 应用代码格式化;`optimize_imports` 只删除未使用的 import 并排序其余 import,不重新格式化。两者都返回最多 200 行的 unified diff;`reformat_file` 传 `optimizeImports: true` 可同时完成两项工作。
- `apply_patch` 接受 Codex 的 `apply_patch` 格式和 unified diff,路径必须在项目内。
- `git_diff` 比较的是磁盘上的文件,不包含编辑器中尚未保存的内容。
- `http_list_requests` 列出项目中 `.http` / `.rest` 文件里的请求;`http_run_request` 按索引发送其中一个(可选 `env`,来自 `http-client.env.json`),会先询问,并返回状态和截断后的响应体——不含请求头或请求体。
+6 -1
Переглянути файл
@@ -37,11 +37,16 @@ OpenIDEA 内置六套快捷键方案:
修改生效前会弹出确认框,列出将要导入的内容:
- 配色方案(`.icls` 文件)以及当前使用的配色方案
- 快捷键方案和当前使用的快捷键方案
- 编辑器字体:字体、字号、行距(换算为行高)和连字
- 去除行尾空格、保存时确保末尾换行、粘性行、显示空白字符、软换行
- 当前代码样式方案中的制表符和缩进
- `templates/*.xml` 中的实时模板,包括组、缩写、`$VAR$` 正文、变量和映射后的语言上下文
- **退出 IDE 前确认**
快捷键方案、代码样式、实时模板、检查配置和插件不会导入,确认框会列出被跳过的项。导入的值写入全局设置。
确认框会在写入前显示实时模板的导入和跳过数量。取消不会产生任何更改。导入的模板会加入按用户保存的自定义模板,不会替换内置模板或无关模板;再次导入会更新相同的 `jetbrains.*` id,而不会重复添加。未知或存在歧义的上下文会列为跳过项,不会改成全局适用。不支持的宏表达式会保留为文本供编辑,但不会执行;仍会应用导入的默认值,否则该字段保持可编辑。
检查配置、插件以及制表符和缩进以外的代码样式选项不会导入,确认框会将其列为跳过项。导入的设置写入全局设置层。
### 导入主题
+8
Переглянути файл
@@ -17,6 +17,14 @@ description: "展开缩写、包围代码、使用后缀补全和 Emmet、编写
内置模板覆盖 Rust、JavaScript / TypeScript、Python、Go、Java、Kotlin、PHP 和 SQL,另有几个通用模板(`todo`、`fixme`、`hack`、`date`)。**插入实时模板…** 列出在光标处适用的模板。默认情况下模板只在代码中展开,在注释和字符串中不会展开。
### 从 JetBrains 导入
选择 **文件 › 管理 IDE 设置 › 从 JetBrains IDE 导入设置…** 使用本机某个 IDE 的设置目录,或选择 **导入设置…** 选中导出的 `settings.zip`。导入器会读取 `templates/*.xml`,并在写入前显示导入和跳过的数量。取消不会更改现有模板。
模板组、缩写、描述、`$VAR$` 正文、变量表达式/默认值和语言上下文都会保留。JetBrains 的 `alwaysStopAt="false"` 对应 **已定义时跳过**。导入使用稳定的 `jetbrains.*` id,再次导入会更新相同模板,不会替换内置模板或无关的自定义模板。
未知或存在歧义的上下文会被跳过,不会当作全局上下文。OpenIDEA 无法计算的宏表达式会保留为表达式文本,并在确认框中列出;导入的默认值仍会应用,否则该字段保持可编辑。XML 格式错误时会给出报告,并且不会导入该文件中的任何模板。
### 包围
选中代码后按 `⌥⌘T` / `Ctrl+Alt+T`。列表最前面是该语言的包围结构(`if`、`while`、`try` 等),后面是使用了 `$SELECTION$` 的实时模板。**用实时模板包围…** 只显示后者。
+2 -1
Переглянути файл
@@ -89,7 +89,7 @@ OpenIDEA 会找到包含项目的仓库,以及向下最多四层的嵌套仓
**提交** 按钮旁的齿轮按钮(**提交选项**)包含:
- **作者:**:以其他身份提交(`Name <email>`),以及 **签署提交**。
- **提交检查**:**重新格式化代码**、**优化导入**、**清理**(应用 fix-all 代码操作)和 **运行 Git 钩子**(关闭时加 `--no-verify`)。
- **提交检查**:**重新格式化代码**、**优化导入**、**清理**(应用 fix-all 代码操作)、**修复 Ruff 安全的 lint 问题**(组成提交前对 Python 文件运行 `ruff check --fix-only`,与格式化相互独立)和 **运行 Git 钩子**(关闭时加 `--no-verify`)。
- **高级提交检查**:**分析代码**(语言服务器报告的错误和警告)和 **检查 TODO**(检查改动行是否匹配 **设置 › 编辑器 › TODO** 中的规则)。
在 **设置 › 编辑器 › TODO** 中创建命名筛选器,再通过 **检查 TODO** 旁的 **配置** 选择要检查的模式组。提交工具窗口和 TODO 工具窗口分别按项目保存选择。点击 **查看 TODO** 会在 TODO 工具窗口打开结果标签页,可以浏览全部匹配项和检查时的内容,并跳转到对应源码或差异。若所选文件无法检查,结果会列出文件和原因,便于处理后重试。
@@ -245,6 +245,7 @@ Git 工具窗口的 **日志** 标签页显示提交图。
## Blame 与历史
- **使用 Git Blame 注解** 在边栏中逐行显示作者和日期(也可以从边栏右键菜单打开)。点击某条记录会在日志中打开对应提交。在 Git 设置中打开 **为当前行显示内联 Git Blame**,会在光标所在行末尾显示作者;点击它会打开对应提交,关闭 **点击内联 Git Blame 时打开提交** 后则不会。
- 边栏右键菜单的 **选项 › 颜色** 可让所有已注解的编辑器按 **作者**、按变更 **顺序**(默认)上色,或不上色(**隐藏**)。
- 边栏右键菜单的 **选项 › 姓名** 可让所有已注解的编辑器以 **首字母缩写**、**姓**(默认)、**名** 或 **全名**显示作者。
- 注解行的右键菜单中,**注解此修订版** 会打开该提交时的文件(已注解),与工作区文件并排显示。此后重命名过的文件按它在该提交中的名称读取。
- 注解行的右键菜单中,**标注上一版本** 会打开该提交之前版本的文件(已注解),与这个提交的版本并排显示。
+1 -1
Переглянути файл
@@ -134,7 +134,7 @@ Java 调试使用 jdtls 内的 Microsoft java-debug,Kotlin 调试使用 Kotlin
- **Spring Boot 运行配置**:根据 `@SpringBootApplication` 类创建,默认显示在 **服务** 工具窗口中。
- **配置导航**:在 `application.yml` 或 `.properties` 的键上转到定义,会打开绑定到它的 Java 成员(`@ConfigurationProperties`、`@Value`、`Environment.getProperty`);反过来,从 Java、YAML、properties 或 Spring XML 里的 `${…}` 占位符也能跳到配置键。依赖中 `spring-configuration-metadata.json` 描述的键会跳到对应的源类。对配置键执行 **查找用法**,会同时列出配置声明和 Java 中的使用处。
- **Thymeleaf 模板**:项目中有 `src/main/resources/templates` 时,`.html` 文件里 `th:*` 和 `data-th-*` 的值按 Thymeleaf 表达式高亮,输入 `th:` 后补全属性名。在片段表达式(`~{fragments/nav :: menu}`,或 `th:replace` / `th:insert` 中不带 `~{}` 的写法)上转到声明,打开对应模板或其 `th:fragment`;在消息键(`#{home.title}`)上转到声明,列出 `spring.messages.basename` 所设消息包中每个 `messages*.properties` 里的该键。
- **Thymeleaf 模板**:项目中有 `src/main/resources/templates` 时,`.html` 文件里 `th:*` 和 `data-th-*` 的值按 Thymeleaf 表达式高亮,输入 `th:` 后补全属性名。在片段表达式(`~{fragments/nav :: menu}`,或 `th:replace` / `th:insert` 中不带 `~{}` 的写法)上转到声明,打开对应模板或其 `th:fragment`;在消息键(`#{home.title}`)上转到声明,列出 `spring.messages.basename` 所设消息包中每个 `messages*.properties` 里的该键。片段表达式指向模板中没有的片段(没有同名的 `th:fragment`、`th:ref` 或元素;同名 `id` 也放过)时以警告标出,单模块项目中指向不存在的模板也会标出;`application.properties` / `.yml` 设置了 `spring.thymeleaf.prefix` 或 `suffix`,或写成 `~{…} ?: …` 回退时不检查。
- **Spring Web 端点**:Java 和 Kotlin 控制器中的请求映射旁有边栏图标,还有 **在 HTTP 客户端中生成请求** 和 **为控制器生成请求** 两个操作,会把请求写进一个临时 `.http` 文件。随处搜索的 **全部** 标签页可以按请求路径搜索。见 [HTTP Client](/zh/guide/http-client)。
- **Facet**:在 **项目结构**(`⌘;` / `Ctrl+Alt+Shift+S`)里记录模块使用的框架(Web、Spring、JPA)。添加 Web Facet 还会把其中的 `WEB-INF/lib/*.jar` 加入 jdtls 的类路径。
+3 -1
Переглянути файл
@@ -94,7 +94,9 @@ Ruff 只为位于 Ruff 配置之下的文件启动:`ruff.toml`、`.ruff.toml`
### 格式化
**重新格式化代码**(`⌘⌥L` / `Ctrl+Alt+L`)使用 Ruff。在 **设置 › 语言和框架 › Ruff** 中可以设置 Ruff 路径、配置目录、**格式化工具**(**自动(优先语言服务器)** 或 Ruff)以及 **保存时运行**。不指定配置目录时,Ruff 读取最近的 `pyproject.toml`(`[tool.ruff]`)、`ruff.toml` 或 `.ruff.toml`。项目和用户配置里都没有时,Ruff 按编辑器使用的缩进和行宽格式化:先看文件的 `.editorconfig`(`indent_size`、`indent_style`、`max_line_length`),再看 **设置 › 编辑器 › 代码样式 › Python** 中设置的缩进、制表符和硬换行。两处都没设置的值不会传给 Ruff,Ruff 仍用自己的默认值(4 个空格、88 列)。
**重新格式化代码**(`⌘⌥L` / `Ctrl+Alt+L`)使用 Ruff。在 **设置 › 语言和框架 › Ruff** 中可以设置 Ruff 路径、配置目录、**格式化工具**(**自动(优先语言服务器)** 或 Ruff)以及 **保存时格式化**。不指定配置目录时,Ruff 读取最近的 `pyproject.toml`(`[tool.ruff]`)、`ruff.toml` 或 `.ruff.toml`。项目和用户配置里都没有时,Ruff 按编辑器使用的缩进和行宽格式化:先看文件的 `.editorconfig`(`indent_size`、`indent_style`、`max_line_length`),再看 **设置 › 编辑器 › 代码样式 › Python** 中设置的缩进、制表符和硬换行。两处都没设置的值不会传给 Ruff,Ruff 仍用自己的默认值(4 个空格、88 列)。
**保存时修复安全的 lint 问题**默认关闭,会在写入前对当前未保存的 Python 文本运行 `ruff check --fix-only`。它只应用 Ruff 的安全修复,不执行格式化,遵循项目的排除配置,并且不依赖所选格式化工具或任一保存时格式化选项。在 **设置 › 版本控制 › 提交 › 提交检查**(或 **提交选项**)中开启 **修复 Ruff 安全的 lint 问题**,会在组成提交前对每个提交的 Python 文件执行相同修复。部分提交不会带入未选择的更改。
在含 `[tool.black]` 表的 `pyproject.toml` 所在目录及其子目录中,或在 **设置 › 语言和框架 › Black 格式化工具** 中把 **格式化工具** 设为 Black 后,由 Black 代替 Ruff 格式化。Black 自己读取 `[tool.black]` 中的选项。IDE 优先使用项目解释器环境中的 `black`,其次是工具文件夹或 `PATH` 中的;都没有安装时,重新格式化代码会提示安装。在查找操作中运行 **使用 Black 重新格式化**,无论项目用什么格式化工具,都会用 Black 格式化。Black 自己的 **保存时运行** 或编辑器的 **保存时格式化** 打开时,保存文件会运行 Black。没有 `[tool.black]`(按 Black 的方式查找:跳过不含它的 `pyproject.toml`,一直到仓库根目录)或用户配置时,Black 也使用这个行宽。Black 配置排除的文件(`force-exclude`)保持不变;23.11 之前的 Black 不能格式化选区,会格式化整个文件。
+16 -14
Переглянути файл
@@ -206,19 +206,21 @@ exclude = ["**/.git", "**/node_modules", "**/target", "**/dist"]
### 其他配置节
| 键 | 说明 |
| ------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------- |
| `[actionsOnSave]` | `optimizeImports`、`cleanup`(工具 › 保存时操作)。 |
| `[mcpServer]` | `enabled`、`backgroundProjects` 等 MCP 服务器的选项(智能体 › IDE MCP 服务器,仅全局)。参见 [MCP Server](/zh/guide/mcp)。 |
| `[agents]` | 智能体任务标题栏显示哪些信息(工具 › 智能体 › 聊天)。 |
| `[languages]` | 各语言的解释器、SDK 和选项,例如 `[languages.java]`、`[languages.python]`、`[languages.go]`。 |
| `[languageServers]` | 按名称配置各语言服务器的启动和协议选项,或在这里定义新的服务器。 |
| `[tools]` | 放在自定义位置的语言服务器和调试适配器,按命令名配置。 |
| `[vcs]`、`[console]`、`[debugger]`、`[run]` | 版本控制、控制台、调试器和运行/调试页面。 |
| `[inspections]`、`[spelling]` | 编辑器 › 检查、编辑器 › 自然语言 › 拼写。 |
| `[ssh]`、`[deployment]`、`runTargets`、`[cmake]` | SSH 配置、部署、运行目标、CMake。 |
| `[projectStructure]` | 源代码、测试、资源和排除文件夹(项目结构)。 |
| `externalTools` | 工具 › 外部工具中的条目。 |
| `[plugins.<plugin-id>]` | 插件声明的设置。 |
| 键 | 说明 |
| ------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------- |
| `[actionsOnSave]` | `optimizeImports`、`cleanup`(工具 › 保存时操作)。 |
| `[mcpServer]` | `enabled`、`backgroundProjects` 等 MCP 服务器的选项(智能体 › IDE MCP 服务器,仅全局)。参见 [MCP Server](/zh/guide/mcp)。 |
| `[agents]` | 智能体任务标题栏显示哪些信息(工具 › 智能体 › 聊天)。 |
| `[languages]` | 各语言的解释器、SDK 和选项,例如 `[languages.java]`、`[languages.python]`、`[languages.go]`。 |
| `[languages.ruff]` | Ruff 的 `path`、`configurationDirectory`、`languages`、`prefer`、格式化 `runOnSave`,以及安全修复 `fixOnSave`(默认 `false`)。 |
| `[vcs.commit]` | 提交前检查和修改,包括用于 Ruff 安全 lint 修复的 `fixOnCommit`(默认 `false`)。 |
| `[languageServers]` | 按名称配置各语言服务器的启动和协议选项,或在这里定义新的服务器。 |
| `[tools]` | 放在自定义位置的语言服务器和调试适配器,按命令名配置。 |
| `[vcs]`、`[console]`、`[debugger]`、`[run]` | 版本控制、控制台、调试器和运行/调试页面。 |
| `[inspections]`、`[spelling]` | 编辑器 › 检查、编辑器 › 自然语言 › 拼写。 |
| `[ssh]`、`[deployment]`、`runTargets`、`[cmake]` | SSH 配置、部署、运行目标、CMake。 |
| `[projectStructure]` | 源代码、测试、资源和排除文件夹(项目结构)。 |
| `externalTools` | 工具 › 外部工具中的条目。 |
| `[plugins.<plugin-id>]` | 插件声明的设置。 |
完整的配置键和默认值见源码:[`crates/ide-core/src/settings.rs`](https://github.com/l0ng-ai/openidea/blob/main/crates/ide-core/src/settings.rs) 及同目录下的其他 `*_settings.rs` 文件。
+62 -1
Переглянути файл
@@ -17,7 +17,33 @@ const task: AgentTask = {
createdMs: 0,
updatedMs: 0,
config: [],
commands: [],
commands: [
{
name: "skills",
description: "Manage skills for enhanced capabilities",
hint: "[list|info|reload|add|remove]",
source: "command",
choices: [
{ name: "list", description: "List all available skills" },
{ name: "info", description: "Show details for a skill" },
{ name: "reload", description: "Reload skills from disk" },
{ name: "add", description: "Install a skill file, directory or HTTPS URL" },
{ name: "remove", description: "Remove a personal or project skill" },
],
},
{
name: "review",
description: "Run code review agent to analyze changes",
hint: "additional instructions",
source: "command",
},
{
name: "triage",
description: "One pass over open issues and PRs",
hint: null,
source: "skill",
},
],
usage: null,
queue: [],
};
@@ -115,3 +141,38 @@ test("first-open @ results can grow and flip after asynchronous file search", as
await expect.poll(() => geometry(list)).toMatchObject(fullList);
await expect(editor).toBeFocused();
});
test("slash command arguments autocomplete subcommands, skills, and inline hints", async ({ workbench: page }) => {
const { editor } = await openTask(page);
const commandsList = page.getByRole("listbox", { name: "Commands", exact: true });
await editor.pressSequentially("/skills ");
await expect(commandsList).toBeVisible();
await expect(commandsList.getByRole("option")).toHaveCount(5);
await expect(commandsList.getByRole("option").nth(1)).toContainText("/skills info");
await expect(commandsList.getByRole("option").nth(1)).toContainText("Show details for a skill");
await editor.pressSequentially("in");
await expect(commandsList.getByRole("option")).toHaveCount(1);
await editor.press("Enter");
await expect(editor).toContainText("/skills info ");
// Choosing `info` chains into active skills.
await expect(commandsList).toBeVisible();
await expect(commandsList.getByRole("option")).toHaveCount(1);
await expect(commandsList.getByRole("option").first()).toContainText("/skills info triage");
await editor.press("Enter");
await expect(commandsList).toBeHidden();
await expect(editor).toHaveText("/skills info triage ");
// Free-text hints show inline after `/command ` and vanish once typing begins.
// Cleared key by key: the select-all shortcut depends on the host and the mocked platform.
await editor.press("End");
for (let i = 0; i < "/skills info triage ".length; i++) await editor.press("Backspace");
await expect(editor).not.toContainText("/skills");
await editor.pressSequentially("/review ");
await expect(commandsList).toBeHidden();
await expect(editor.locator('span[aria-hidden="true"]')).toHaveText("additional instructions");
await editor.pressSequentially("auth");
await expect(editor.locator('span[aria-hidden="true"]')).toHaveCount(0);
});
+6
Переглянути файл
@@ -26,6 +26,11 @@ test("configures a ClickHouse HTTP source and keeps transaction controls unavail
await expect(dialog.locator("#db-port")).toHaveValue("8443");
await expect(dialog.locator("#db-user")).toHaveValue("reader");
await expect(dialog.locator("#db-database")).toHaveValue("analytics");
await dialog.getByRole("tab", { name: "Advanced", exact: true }).click();
await expect(dialog.locator('#db-property-names option[value="http_read_timeout"]')).toHaveCount(1);
await dialog.getByRole("button", { name: "Add Property", exact: true }).click();
await dialog.getByLabel("Property name").fill("http_read_timeout");
await dialog.getByLabel("Property value").fill("900");
await dialog.getByRole("button", { name: "Test Connection", exact: true }).click();
await expect(dialog.getByRole("status")).toHaveText("Succeeded: ClickHouse");
expect(await page.evaluate(() => JSON.parse(document.documentElement.dataset.testedSource!))).toMatchObject({
@@ -35,6 +40,7 @@ test("configures a ClickHouse HTTP source and keeps transaction controls unavail
user: "reader",
database: "analytics",
ssl: "verifyFull",
properties: [{ name: "http_read_timeout", value: "900" }],
});
await dialog.screenshot({ path: info.outputPath("clickhouse-source.png") });
await dialog.getByRole("tab", { name: "Options", exact: true }).click();
+97
Переглянути файл
@@ -0,0 +1,97 @@
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
test("a refused stateless SET gives a fix in the console and leaves it usable", async ({ workbench: page }) => {
const path = "/app-data/consoles/db/fixture/console.sql";
const help =
"Standalone SET needs a ClickHouse HTTP session. Set use_http_session=true in Advanced or use query-level SETTINGS where applicable.";
await stubDesktop(page);
await page.evaluate(
async ({ path, help }) => {
const storePath = "/src/features/database/store.ts";
const editorPath = "/src/workbench/contributions.ts";
const { useDatabase, bindConsole } = await import(/* @vite-ignore */ storePath);
const { editorService } = await import(/* @vite-ignore */ editorPath);
const sources = [
{
id: "fixture",
name: "ClickHouse fixture",
driver: "clickhouse",
properties: [{ name: "use_http_session", value: "false" }],
},
];
const completion = { defaultSchema: "default", tables: [], foreignKeys: [] };
useDatabase.setState({
sources,
loaded: true,
connected: new Set(["fixture"]),
completion: { fixture: completion },
});
Object.assign(window.__ipc.handlers, {
db_sources: () => sources,
db_connected: () => ["fixture"],
db_completion: () => completion,
db_statements: ({ text }: { text: string }) => {
let offset = 0;
return text.split(";").flatMap((part) => {
const from = offset + part.length - part.trimStart().length;
offset += part.length + 1;
const sql = part.trim();
return sql ? [{ from, to: from + sql.length, text: sql }] : [];
});
},
db_execute_stream: ({
statements,
onProgress,
}: {
statements: Array<{ text: string }>;
onProgress: unknown;
}) => {
const send = (event: unknown) => window.__ipc.send(onProgress, event);
send({ type: "started", index: 0 });
send({ type: "completed", index: 0, outcome: { statement: statements[0], result: null, error: help } });
send({ type: "done", error: null });
return null;
},
db_execute: ({ statements }: { statements: Array<{ text: string }> }) =>
statements.map((statement) => ({
statement,
error: null,
result: {
statement: statement.text,
columns: [{ name: "value", typeName: "String" }],
rows: [["one-query"]],
affected: null,
hasMore: false,
elapsedMs: 1,
executionMs: 1,
truncated: [],
},
})),
});
bindConsole(path, "fixture");
await editorService().openFile(path, { focus: true });
},
{ path, help },
);
const toolbar = page.getByRole("toolbar", { name: "Query Console", exact: true });
const editor = page.locator(".cm-editor:visible .cm-content[contenteditable=true]");
const write = async (sql: string) => {
await editor.focus();
await editor.press("Meta+A");
await page.keyboard.insertText(sql);
};
await write("SET log_comment='openidea-test';\nSELECT getSetting('log_comment');");
await toolbar.getByRole("button", { name: "Execute Script", exact: true }).click();
await expect(page.getByRole("alert").filter({ hasText: help })).toBeVisible();
await expect(page.locator(".cm-openidea-db-run-error")).toHaveCount(1);
await expect(page.locator(".cm-openidea-db-run-ok")).toHaveCount(0);
expect(await ipcCalls(page, "db_execute_stream")).toHaveLength(1);
expect(await ipcCalls(page, "db_execute")).toHaveLength(0);
await write("SELECT getSetting('log_comment') LIMIT 1 SETTINGS log_comment='one-query'");
await toolbar.getByRole("button", { name: "Execute Script", exact: true }).click();
await expect(page.getByRole("gridcell", { name: "one-query", exact: true })).toBeVisible();
await expect(page.getByRole("alert").filter({ hasText: help })).toHaveCount(0);
expect(await ipcCalls(page, "db_execute")).toHaveLength(1);
expect(await ipcCalls(page, "db_execute_stream")).toHaveLength(1);
});
+1 -1
Переглянути файл
@@ -273,7 +273,6 @@ test("maximizes a diff preview tab and restores its previous layout", async ({ w
test("continues between changed files from toolbar buttons and the keymap", async ({ workbench: page }) => {
const toolbar = await openChain(page);
const selected = page.getByRole("tablist", { name: "Editor tabs" }).locator('[aria-selected="true"]');
await toolbar.getByRole("button", { name: "Next Difference", exact: true }).click();
await expect(toolbar).toContainText("1 of 1 differences");
await toolbar.getByRole("button", { name: "Next Difference", exact: true }).click();
await expect(page.getByRole("status").filter({ hasText: "Press again to go to the next file" })).toBeVisible();
@@ -359,6 +358,7 @@ for (const reducedMotion of ["reduce", "no-preference"] as const) {
for (const i of [100, 400, 700]) right[i] = `const changed${i} = ${i};`;
await openDiff({
path: "/dev/acme-api/navigation.ts",
line: 0, // Start before the first difference to exercise every navigation step.
left: { type: "text", text: lines.join("\n"), label: "Before" },
right: { type: "text", text: right.join("\n"), label: "After" },
});
+22
Переглянути файл
@@ -215,3 +215,25 @@ test("one possible client requires a choice and a changed workspace invalidates
});
await expect(page.locator(".cm-content").last()).toContainText("interface UserClient");
});
test("Go to Declaration on a RestTemplate URL opens the endpoint of the named service", async ({ workbench: page }) => {
await page.evaluate(async () => {
const backend = "/src/editor/core/backend.ts";
const api = "/src/editor/api.ts";
const contributions = "/src/workbench/contributions.ts";
const path = "/dev/acme-api/client/src/main/java/UserCalls.java";
const text = `package shop;
import org.springframework.web.client.RestTemplate;
class UserCalls {
RestTemplate rest;
String find(long id) { return rest.getForObject("http://admin/users/{id}", String.class, id); }
}`;
(await import(backend)).docBackend().files.set(path, text);
await (await import(contributions)).editorService().openFile(path);
const editor = (await import(api)).activeEditor();
editor.view.dispatch({ selection: { anchor: text.indexOf("/users/{id}") + 2 } });
editor.view.focus();
});
await page.keyboard.press("Meta+b");
await expect(page.locator(".cm-content").last()).toContainText('return "admin"');
});
+8 -2
Переглянути файл
@@ -24,8 +24,9 @@ test("Git annotations align dates and full author names at UI text size", async
];
handlers.vcs_blame = () => lines;
handlers.vcs_log = ({ query }) => {
const { branch } = query as { branch?: string };
const line = lines.find(({ commit }) => commit === branch);
const { branch, path } = query as { branch?: string | null; path?: string | null };
// The file's last commit, which Annotate draws bold, is the newer one.
const line = path && branch === "HEAD" ? lines[1] : lines.find(({ commit }) => commit === branch);
if (!line) return [];
return [
{
@@ -73,6 +74,11 @@ test("Git annotations align dates and full author names at UI text size", async
await expect
.poll(async () => Math.abs((await firstAuthor.boundingBox())!.x - (await secondAuthor.boundingBox())!.x))
.toBeLessThan(1);
// The bold labels of the file's last commit still fit their columns.
await expect(secondAuthor).toHaveCSS("font-weight", "700");
await expect(firstAuthor).toHaveCSS("font-weight", "400");
for (const cell of [second.locator(".cm-vcs-blame-date"), secondAuthor])
await expect.poll(() => cell.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(0);
await first.hover();
const details = page.getByRole("dialog").filter({ has: page.getByTitle("Show Commit in Git Log") });
+87
Переглянути файл
@@ -0,0 +1,87 @@
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
test("PostgreSQL console toolbar commits only the console with pending changes", async ({ workbench: page }) => {
const id = "pg-console-scope";
const name = "PostgreSQL console fixture";
const a = `/app-data/consoles/db/${id}/console.sql`;
const b = `/app-data/consoles/db/${id}/console_1.sql`;
await stubDesktop(page);
await page.evaluate(
async ({ id, name, a, b }) => {
const storePath = "/src/features/database/store.ts";
const contributionsPath = "/src/workbench/contributions.ts";
const { bindConsole, useDatabase } = await import(storePath);
const { editorService } = await import(contributionsPath);
const source = { id, name, driver: "postgres", database: "test", options: { transaction: "manual" } };
const manual = new Set<string>();
Object.assign(window.__ipc.handlers, {
db_sources: () => [source],
db_connected: () => [id],
db_databases: () => ({ names: ["test"], current: "test" }),
db_schemas: () => ["public"],
db_completion: () => ({ defaultSchema: "public", tables: [], foreignKeys: [] }),
db_statements: ({ text }: { text: string }) => [{ from: 0, to: text.length, text }],
db_set_console_manual_commit: ({ console, manual: enabled }: { console: string; manual: boolean }) => {
if (!enabled) {
manual.delete(console);
return false;
}
const initialized = !manual.has(console);
manual.add(console);
return initialized;
},
db_execute: ({ statements }: { statements: { text: string }[] }) =>
statements.map((statement) => ({
statement,
result: { columns: [], rows: [], affected: 1, elapsedMs: 1, executionMs: 1, truncated: [] },
error: null,
})),
db_finish_console_transaction: () => null,
db_release_result: () => null,
db_release_console: () => null,
});
useDatabase.setState({ sources: [source], loaded: true, connected: new Set([id]) });
bindConsole(a, id);
bindConsole(b, id);
await editorService().openFile(b, { focus: true });
await editorService().openFile(a, { focus: true });
},
{ id, name, a, b },
);
const toolbar = page.getByRole("toolbar", { name: "Query Console", exact: true });
const mode = toolbar.getByRole("button", { name: "Transaction mode" });
const commit = toolbar.getByRole("button", { name: "Commit", exact: true });
const run = (path: string) =>
page.evaluate(async (path) => {
const storePath = "/src/features/database/store.ts";
const { executeConsole } = await import(storePath);
const sql = "INSERT INTO t VALUES (1)";
await executeConsole(path, sql, 0, sql.length);
}, path);
await expect(mode).toHaveText("Tx: Manual");
await run(a);
await expect(commit).toBeEnabled();
await page.getByRole("tab", { name: `console_1 [${name}]`, exact: true }).click();
await expect(commit).toBeDisabled();
await mode.click();
await page.getByRole("option", { name: "Tx: Auto" }).click();
await expect(mode).toHaveText("Tx: Auto");
await run(b);
await expect
.poll(async () =>
(await ipcCalls(page, "db_execute")).map(({ console, consoleManual }) => [console, consoleManual]),
)
.toEqual([
[a, true],
[b, false],
]);
await page.getByRole("tab", { name: `console [${name}]`, exact: true }).click();
await expect(commit).toBeEnabled();
await commit.click();
await expect(commit).toBeDisabled();
await expect.poll(() => ipcCalls(page, "db_finish_console_transaction")).toEqual([{ id, console: a, commit: true }]);
});
+63
Переглянути файл
@@ -44,3 +44,66 @@ test("a project's own icon replaces its initials; any project's colour changes f
await expect.poll(color).not.toBe(before);
expect(await page.evaluate(() => localStorage.getItem("openidea.tabColor.v1:/dev/acme-api"))).toBe("7");
});
test("changing a remote project's colour from its window tab updates both the tab and the remote window frame", async ({
workbench: page,
}) => {
await stubDesktop(page);
await page.evaluate(async () => {
const remoteMod = "/src/platform/remote.ts";
const windowGroupsMod = "/src/platform/windowGroups.ts";
const projectMod = "/src/platform/project.ts";
const { enableRemote, remoteLocation } = await import(/* @vite-ignore */ remoteMod);
const { useWindowGroup } = await import(/* @vite-ignore */ windowGroupsMod);
const { useProject } = await import(/* @vite-ignore */ projectMod);
const target = { kind: "ssh" as const, config: "coder" };
const remoteRoot = "/home/coder/git/acme-api";
const cur = useProject.getState().project;
if (cur) {
useProject.setState({ project: { ...cur, name: "acme-api", displayName: "acme-api", root: remoteRoot } });
}
enableRemote({
target,
root: remoteRoot,
host: "[email protected]:22",
os: "linux",
commands: [],
idlePolicy: null,
takenOver: false,
});
useWindowGroup.setState({
tabs: [
{ label: "local", name: "acme-api", root: "/Users/deng/acme-api", current: false },
{
label: "main",
name: "acme-api [[email protected]:22]",
root: remoteLocation(target, remoteRoot),
current: true,
},
],
});
});
const widget = page.getByRole("button", { name: "acme-api", exact: true });
const avatar = widget.locator("span[aria-hidden]").first();
const avatarBg = () => avatar.evaluate((el) => getComputedStyle(el).backgroundImage);
const beforeAvatar = await avatarBg();
const remoteTab = page.locator('[data-project-tab="main"]');
await expect(remoteTab).toBeVisible();
await expect(remoteTab).not.toHaveAttribute("data-tinted");
await remoteTab.click({ button: "right" });
await page.getByRole("menuitem", { name: "Change Project Color…" }).click();
const picker = page.getByRole("dialog", { name: "Project Color" });
await expect(picker).toBeVisible();
await picker.getByRole("radio", { name: "Rose" }).click();
await expect(picker).toBeHidden();
await expect(remoteTab).toHaveAttribute("data-tinted", "");
await expect.poll(avatarBg).not.toBe(beforeAvatar);
expect(
await page.evaluate(() => localStorage.getItem("openidea.tabColor.v1:ssh://coder/home/coder/git/acme-api")),
).toBe("6");
});
+3
Переглянути файл
@@ -50,6 +50,9 @@ test("project switcher keeps names and metadata on separate lines and highlights
);
const remote = popup.getByRole("option", { name: /Payment Ledger/ });
await expect(remote.locator("[data-remote-badge]")).toHaveCount(1);
await expect(remote.locator('[data-remote-kind="ssh"]')).toBeVisible();
await expect(local.locator("[data-remote-badge]")).toHaveCount(0);
await expectBelow(remote, "Payment Ledger", HOST);
await expectBelow(remote, HOST, REMOTE_PATH);
+2 -1
Переглянути файл
@@ -120,7 +120,8 @@ test("shows compact remote CPU+RAM pill beside SSH status and opens detailed das
await expect(dialog).toBeVisible();
await expect(dialog.getByText("SSH: [email protected]")).toBeVisible();
await expect(dialog.getByText("16 cores · load 1.42 · 1.18 · 0.95")).toBeVisible();
await expect(dialog.getByText("84 GB free")).toBeVisible();
await expect(dialog.getByText("116G / 200G")).toBeVisible();
await expect(dialog.getByText(/84G free · R/)).toBeVisible();
await expect(dialog.getByRole("group", { name: "Language servers" })).toContainText("rust-analyzer");
await expect(dialog.getByRole("group", { name: "Other host processes" })).toContainText("dockerd");
+3 -6
Переглянути файл
@@ -7,15 +7,12 @@ test("keeps the file count visible beside a long directory in the TODO pane", as
const todoModule = "/src/features/todo/store.ts";
const layoutModule = "/src/workbench/toolwindows/store.ts";
const { useProject } = await import(/* @vite-ignore */ projectModule);
const { useTodos } = await import(/* @vite-ignore */ todoModule);
const { setLiveTodos } = await import(/* @vite-ignore */ todoModule);
const { showToolWindow } = await import(/* @vite-ignore */ layoutModule);
const directory = "src/features/checkout/shared/services/with-a-long-directory-name/for-order-processing";
const path = `${useProject.getState().project.root}/${directory}/orders.ts`;
useTodos.setState({
scannedOnce: true,
error: null,
scanned: new Map([[path, [{ path, line: 8, col: 3, keyword: "TODO", text: "TODO: validate orders" }]]]),
});
// The browser's startup scan clears the scan cache.
setLiveTodos(path, [{ path, line: 8, col: 3, keyword: "TODO", text: "TODO: validate orders" }]);
showToolWindow("todo", true);
});
+4 -1
Переглянути файл
@@ -28,8 +28,11 @@ def main():
primes(20000)
checksum(str(i) for i in range(200000))
print("done", flush=True)
while "--loop" in sys.argv:
if "--loop" in sys.argv:
fib(18)
print("looped", flush=True)
while True:
fib(18)
if __name__ == "__main__":
+7
Переглянути файл
@@ -10,7 +10,10 @@ root = Path(__file__).resolve().parent
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--test", action="store_true")
parser.add_argument("--out", type=Path, help="output JAR (with --test: the fixture driver for JDBC_FIXTURE_JAR)")
parser.add_argument("--duckdb-jar", type=Path, help="run the real DuckDB pipe tests with this existing JDBC jar")
args = parser.parse_args()
if args.duckdb_jar and not args.test:
parser.error("--duckdb-jar requires --test")
java_home = os.environ.get("JAVA_HOME")
def tool(name):
return str(Path(java_home) / "bin" / name) if java_home else name
@@ -25,6 +28,10 @@ with tempfile.TemporaryDirectory() as scratch:
"-d", classes, *sources], check=True)
if args.test:
subprocess.run([tool("java"), "-ea", "-cp", classes, "ai.openidea.jdbc.SelfTest"], check=True, timeout=45)
if args.duckdb_jar:
classpath = os.pathsep.join((str(classes), str(args.duckdb_jar.resolve(strict=True))))
subprocess.run([tool("java"), "-ea", "-cp", classpath, "ai.openidea.jdbc.DuckDbSelfTest"],
check=True, timeout=45)
if not args.test or args.out:
with zipfile.ZipFile(args.out or root / "openidea-jdbc-bridge.jar", "w") as jar:
for path in sorted(classes.rglob("SelfTest*.class" if args.test else "*.class")):
Бінарний файл не відображається.
+225
Переглянути файл
@@ -0,0 +1,225 @@
package ai.openidea.jdbc;
import java.io.*;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import java.util.Set;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
/**
* Opt-in framing: request ID, connection ID and field count, then the legacy fields.
* Replies carry the request ID before the legacy length and payload. Zero fields
* requests cancellation, and a reply with zero length acknowledges it.
*/
final class MultiplexBridge {
private static final int SERVICE = 0;
// The service/shared session and closing drivers occupy slots as well.
private static final int MAX_CONNECTIONS = 32;
private static final int REQUEST_HEADER = Long.BYTES + 2 * Integer.BYTES;
private static final long CLOSE_GRACE = TimeUnit.MILLISECONDS.toNanos(1500);
private final DataInputStream input;
private final DataOutputStream output;
private final ConcurrentMap<Integer, Session> sessions = new ConcurrentHashMap<>();
// Closing drivers still count towards the cap until their Connection.close returns.
private final Set<Session> live = ConcurrentHashMap.newKeySet();
// Reserve before large writes and encodings, not while JDBC executes. This keeps
// frame copies and encoding temporaries within the 192 MiB JVM's headroom.
private final Semaphore largeReplies = new Semaphore(1, true);
private volatile List<String> settings;
private final AtomicBoolean stopping = new AtomicBoolean();
MultiplexBridge(DataInputStream input, DataOutputStream output) {
this.input = input;
this.output = output;
}
private static ThreadFactory daemon(String name) {
return action -> {
var thread = new Thread(action, name);
thread.setDaemon(true);
return thread;
};
}
private static final class Session {
final int id;
final OpenIdeaJdbc jdbc = new OpenIdeaJdbc();
final AtomicReference<OpenIdeaJdbc.Work> active = new AtomicReference<>();
final ExecutorService worker = Executors.newSingleThreadExecutor(daemon("jdbc-session"));
// A driver may hold Statement.cancel indefinitely. Keep it off the reader and
// confine the outstanding calls to this connection.
final ExecutorService canceller = new ThreadPoolExecutor(1, 1, 0, TimeUnit.MILLISECONDS,
new ArrayBlockingQueue<>(1), daemon("jdbc-cancel"), new ThreadPoolExecutor.DiscardPolicy());
Session(int id) { this.id = id; }
void cancel(OpenIdeaJdbc.Work work) {
var statement = work.requestCancel();
if (statement != null) canceller.execute(() -> OpenIdeaJdbc.Work.cancelStatement(statement));
}
}
private void send(long id, ByteArrayOutputStream payload) throws IOException {
synchronized (output) {
if (stopping.get()) return;
output.writeLong(id);
OpenIdeaJdbc.send(output, payload);
}
}
private static ByteArrayOutputStream status(String error) throws IOException {
var bytes = new ByteArrayOutputStream();
var result = new DataOutputStream(bytes);
result.writeBoolean(error == null);
if (error == null) {
OpenIdeaJdbc.header(result);
OpenIdeaJdbc.end(result, false, -1);
} else {
OpenIdeaJdbc.text(result, error);
}
return bytes;
}
private void retire(Session session) {
if (session == null || !sessions.remove(session.id, session)) return;
var work = session.active.get();
if (work != null) session.cancel(work);
session.worker.execute(() -> {
try { session.jdbc.close(); }
catch (SQLException | RuntimeException ignored) {}
finally { live.remove(session); }
});
session.worker.shutdown();
session.canceller.shutdown();
}
private Connection connect(List<String> options) throws Exception {
if (!options.get(0).equals("org.duckdb.DuckDBDriver")) return OpenIdeaJdbc.connect(options);
// A second DuckDB login would create a different unnamed in-memory database.
// Call duplicate on the service worker so it never races another operation
// on the same JDBC Connection.
Session service = sessions.get(SERVICE);
if (service == null) throw new SQLException("The DuckDB service connection is unavailable");
return service.worker.submit(() -> {
Connection source = service.jdbc.connection;
return (Connection) source.getClass().getMethod("duplicate").invoke(source);
}).get();
}
private synchronized void request(long id, int connection, List<String> fields) throws IOException {
if (stopping.get()) return;
String op = fields.get(0);
Session session = sessions.get(connection);
if (op.equals("close")) {
if (connection == SERVICE || fields.size() != 1) {
send(id, status("Invalid JDBC console close request"));
} else {
retire(session); // Retire the ID before acknowledging, even if the driver is busy.
send(id, status(null));
}
return;
}
boolean open = op.equals("open");
List<String> options = settings;
if (open) {
boolean valid = connection == SERVICE
? fields.size() >= 6 && fields.size() % 2 == 0
: fields.size() == 1 && options != null;
if (!valid || session != null) {
send(id, status("Invalid JDBC connection open request"));
return;
}
if (live.size() >= MAX_CONNECTIONS) {
send(id, status("JDBC connection limit reached. Close a console or wait for its connection to finish closing, then try again."));
return;
}
if (connection == SERVICE) options = List.copyOf(fields.subList(1, fields.size()));
session = new Session(connection);
sessions.put(connection, session);
live.add(session);
} else if (session == null) {
send(id, status("JDBC connection is closed"));
return;
}
var work = new OpenIdeaJdbc.Work(id);
if (!session.active.compareAndSet(null, work)) {
send(id, status("The JDBC connection is already executing a request"));
return;
}
try {
schedule(session, work, fields, open, options);
} catch (RejectedExecutionException closed) {
session.active.compareAndSet(work, null);
send(id, status("JDBC connection is closed"));
}
}
private void schedule(Session session, OpenIdeaJdbc.Work work, List<String> fields,
boolean open, List<String> options) {
session.worker.execute(() -> {
try (var buffer = new ReplyBuffer(largeReplies)) {
var answer = session.jdbc.reply(work, fields,
args -> session.id == SERVICE ? OpenIdeaJdbc.connect(args) : connect(options), buffer);
if (open) {
if (session.jdbc.connection == null) retire(session);
else if (session.id == SERVICE) settings = options;
}
session.active.compareAndSet(work, null);
send(work.id, answer);
} catch (Throwable fatal) {
abort();
}
});
}
private void abort() {
if (!stopping.compareAndSet(false, true)) return;
// The reader may be blocked on stdin and the worker cannot join itself.
var closer = new Thread(() -> {
try { closeSessions(); }
finally { Runtime.getRuntime().halt(1); }
}, "jdbc-broken-pipe");
closer.setDaemon(false);
closer.start();
}
private void closeSessions() {
List<Session> remaining;
synchronized (this) { remaining = List.copyOf(live); }
for (Session session : remaining) retire(session);
long deadline = System.nanoTime() + CLOSE_GRACE;
for (Session session : remaining) {
long wait = deadline - System.nanoTime();
if (wait <= 0) break;
try { session.worker.awaitTermination(wait, TimeUnit.NANOSECONDS); }
catch (InterruptedException e) { Thread.currentThread().interrupt(); break; }
}
}
void run() throws IOException {
try {
while (!stopping.get()) {
long id;
try { id = input.readLong(); } catch (EOFException eof) { return; }
int connection = input.readInt();
int count = input.readInt();
if (count == 0) {
Session session = sessions.get(connection);
var work = session == null ? null : session.active.get();
if (work != null && work.id == id) session.cancel(work);
send(id, null);
} else {
request(id, connection, OpenIdeaJdbc.readFields(input, count, REQUEST_HEADER));
}
}
} finally {
if (stopping.compareAndSet(false, true)) closeSessions();
}
}
}
+75 -26
Переглянути файл
@@ -11,8 +11,6 @@ import java.util.concurrent.atomic.AtomicReference;
public final class OpenIdeaJdbc {
static final int LIMIT = 16 * 1024 * 1024;
final DataInputStream input = new DataInputStream(new BufferedInputStream(System.in));
final DataOutputStream output = new DataOutputStream(new BufferedOutputStream(System.out));
Connection connection;
boolean catalogs;
boolean namespaceKnown;
@@ -23,6 +21,7 @@ public final class OpenIdeaJdbc {
if (available < 0 || (value != null && value.length() > available))
throw new IOException("JDBC result exceeds 16 MiB; select fewer or smaller values");
if (value == null) { out.writeInt(-1); return; }
ReplyBuffer.beforeEncoding(out, Integer.BYTES + 3 * value.length());
byte[] data = value.getBytes(StandardCharsets.UTF_8);
if (data.length > available) throw new IOException("JDBC result exceeds 16 MiB; select fewer or smaller values");
out.writeInt(data.length);
@@ -61,7 +60,7 @@ public final class OpenIdeaJdbc {
}
}
void open(List<String> a, DataOutputStream out) throws Exception {
static Connection connect(List<String> a) throws Exception {
String className = a.get(0), url = a.get(1);
Driver driver = Class.forName(className).asSubclass(Driver.class).getConstructor().newInstance();
var props = new Properties();
@@ -80,6 +79,7 @@ public final class OpenIdeaJdbc {
}
props.setProperty("duckdb.read_only", "true");
}
Connection connection;
try { connection = driver.connect(url, props); }
catch (SQLException e) {
if (!duckDbReadOnly) throw e;
@@ -89,12 +89,33 @@ public final class OpenIdeaJdbc {
if (readOnly && !duckDbReadOnly) {
try { connection.setReadOnly(true); }
catch (SQLException | UnsupportedOperationException e) {
try { connection.close(); } catch (SQLException ignored) {}
throw new ReadOnlyUnavailable("The JDBC driver rejected Read-only. Check the driver settings and database account privileges.");
}
}
var m = connection.getMetaData();
header(out, "version", "quote");
row(out, m.getDatabaseProductName() + " " + m.getDatabaseProductVersion(), m.getIdentifierQuoteString());
return connection;
}
@FunctionalInterface
interface OpenConnection {
Connection open(List<String> args) throws Exception;
}
private void open(List<String> args, DataOutputStream out, OpenConnection opener) throws Exception {
Connection opened = opener.open(args);
try {
var m = opened.getMetaData();
header(out, "version", "quote");
row(out, m.getDatabaseProductName() + " " + m.getDatabaseProductVersion(), m.getIdentifierQuoteString());
connection = opened;
} catch (Exception | LinkageError failure) {
try { opened.close(); } catch (SQLException ignored) {}
throw failure;
}
}
void close() throws SQLException {
if (connection != null) connection.close();
}
static String pattern(DatabaseMetaData m, String literal) throws SQLException {
@@ -210,6 +231,7 @@ public final class OpenIdeaJdbc {
if (t == Types.BINARY || t == Types.VARBINARY || t == Types.LONGVARBINARY || t == Types.BLOB) {
byte[] b = rs.getBytes(c);
if (b != null && b.length > (LIMIT - out.size()) / 2) throw new IOException("JDBC binary value exceeds the result limit");
if (b != null) ReplyBuffer.beforeEncoding(out, Integer.BYTES + 2 + 2 * b.length);
text(out, b == null ? null : "0x" + HexFormat.of().formatHex(b));
} else {
text(out, rs.getString(c));
@@ -241,15 +263,25 @@ public final class OpenIdeaJdbc {
cancelled = true;
st = statement;
}
cancelStatement(st);
}
synchronized Statement requestCancel() {
if (cancelled) return null;
cancelled = true;
return statement;
}
static void cancelStatement(Statement st) {
if (st != null) {
try { st.cancel(); } catch (SQLException | UnsupportedOperationException ignored) {}
}
}
}
static List<String> readFields(DataInputStream in, int count) throws IOException {
static List<String> readFields(DataInputStream in, int count, int headerBytes) throws IOException {
if (count < 1 || count > 8192) throw new IOException("Invalid JDBC field count");
int remaining = LIMIT - Long.BYTES - Integer.BYTES;
int remaining = LIMIT - headerBytes;
var fields = new ArrayList<String>(count);
for (int i = 0; i < count; i++) {
remaining -= Integer.BYTES;
@@ -263,14 +295,18 @@ public final class OpenIdeaJdbc {
return fields;
}
ByteArrayOutputStream reply(Work work, List<String> a) throws IOException {
var buffer = new ByteArrayOutputStream();
var reply = new DataOutputStream(buffer);
ByteArrayOutputStream reply(Work work, List<String> a, OpenConnection opener) throws IOException {
return reply(work, a, opener, new ByteArrayOutputStream());
}
ByteArrayOutputStream reply(Work work, List<String> a, OpenConnection opener,
ByteArrayOutputStream buffer) throws IOException {
var reply = ReplyBuffer.writer(buffer);
String op = a.remove(0);
try {
reply.writeBoolean(true);
switch (op) {
case "open" -> open(a, reply);
case "open" -> open(a, reply, opener);
case "schemas" -> schemas(reply);
case "tables", "columns", "schemaColumns" -> metadata(op, a, reply);
case "namespace" -> {
@@ -327,8 +363,9 @@ public final class OpenIdeaJdbc {
}
if (!op.equals("query") && !op.equals("page")) end(reply, false, -1);
} catch (Exception | LinkageError e) {
buffer = new ByteArrayOutputStream();
reply = new DataOutputStream(buffer);
if (buffer instanceof ReplyBuffer bounded) bounded.reset();
else buffer = new ByteArrayOutputStream();
reply = ReplyBuffer.writer(buffer);
reply.writeBoolean(false);
if ((e instanceof ClassNotFoundException || e instanceof NoClassDefFoundError)
&& e.getMessage() != null && e.getMessage().matches("[A-Za-z0-9_.$/]+")) {
@@ -349,14 +386,15 @@ public final class OpenIdeaJdbc {
return buffer;
}
synchronized void send(ByteArrayOutputStream reply) throws IOException {
output.writeInt(reply == null ? 0 : reply.size());
if (reply != null) reply.writeTo(output);
output.flush();
static void send(DataOutputStream output, ByteArrayOutputStream reply) throws IOException {
synchronized (output) {
output.writeInt(reply == null ? 0 : reply.size());
if (reply != null) reply.writeTo(output);
output.flush();
}
}
void run() throws IOException {
System.setOut(System.err);
void run(DataInputStream input, DataOutputStream output) throws IOException {
var active = new AtomicReference<Work>();
var worker = Executors.newSingleThreadExecutor(r -> {
var thread = new Thread(r, "jdbc-session");
@@ -371,17 +409,17 @@ public final class OpenIdeaJdbc {
if (count == 0) {
var work = active.get();
if (work != null && work.id == id) work.cancel();
send(null); // Acknowledge even a cancel that raced with a completed request.
send(output, null); // Acknowledge even a cancel that raced with a completed request.
continue;
}
var fields = readFields(input, count);
var fields = readFields(input, count, Long.BYTES + Integer.BYTES);
var work = new Work(id);
if (!active.compareAndSet(null, work)) throw new IOException("Overlapping JDBC requests");
worker.execute(() -> {
try {
var result = reply(work, fields);
var result = reply(work, fields, OpenIdeaJdbc::connect);
active.compareAndSet(work, null);
send(result);
send(output, result);
} catch (Throwable fatal) {
// Without a complete frame the parent must discard this session.
Runtime.getRuntime().halt(1);
@@ -394,8 +432,19 @@ public final class OpenIdeaJdbc {
}
public static void main(String[] args) throws Exception {
var input = new DataInputStream(new BufferedInputStream(System.in));
boolean multiplex = args.length == 1 && args[0].equals("--multiplex");
// PrintStream swallows broken pipe errors. The multiplexed writer needs
// the failure so it can close all peers and terminate the transport.
OutputStream wire = multiplex ? new FileOutputStream(FileDescriptor.out) : System.out;
var output = new DataOutputStream(new BufferedOutputStream(wire));
System.setOut(System.err);
if (multiplex) {
new MultiplexBridge(input, output).run();
return;
}
var bridge = new OpenIdeaJdbc();
try { bridge.run(); }
finally { if (bridge.connection != null) bridge.connection.close(); }
try { bridge.run(input, output); }
finally { bridge.close(); }
}
}
+83
Переглянути файл
@@ -0,0 +1,83 @@
package ai.openidea.jdbc;
import java.io.*;
import java.util.Arrays;
import java.util.Objects;
import java.util.concurrent.Semaphore;
/** Small replies have their own bounded buffer. Only one large reply is encoded at a time. */
final class ReplyBuffer extends ByteArrayOutputStream {
private static final int SMALL = 64 * 1024;
private static final String BUDGET_ERROR =
"JDBC result exceeds the concurrent reply budget. Select fewer or smaller values.";
private final Semaphore budget;
private boolean reserved;
ReplyBuffer(Semaphore budget) { this.budget = budget; }
private static final class Writer extends DataOutputStream {
final ReplyBuffer buffer;
Writer(ReplyBuffer buffer) {
super(buffer);
this.buffer = buffer;
}
}
static DataOutputStream writer(ByteArrayOutputStream buffer) {
return buffer instanceof ReplyBuffer bounded ? new Writer(bounded) : new DataOutputStream(buffer);
}
static void beforeEncoding(DataOutputStream output, int bound) {
if (output instanceof Writer writer) {
// A field this size may already own a large value from the driver. Do not
// retain it while waiting behind another large frame.
writer.buffer.reserve((long) writer.buffer.count + bound, bound <= SMALL);
}
}
private void reserve(long size, boolean wait) {
if (reserved || size <= SMALL) return;
try {
if (wait) budget.acquire();
else if (!budget.tryAcquire()) throw new UncheckedIOException(new IOException(BUDGET_ERROR));
reserved = true;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new UncheckedIOException(new IOException("JDBC reply interrupted", e));
}
}
private void grow(int extra) {
if (extra > OpenIdeaJdbc.LIMIT - count)
throw new UncheckedIOException(new IOException("JDBC result exceeds 16 MiB"));
int needed = count + extra;
reserve(needed, true);
if (needed > buf.length) {
int limit = reserved ? OpenIdeaJdbc.LIMIT : SMALL;
buf = Arrays.copyOf(buf, Math.min(limit, Math.max(needed, buf.length * 2)));
}
}
@Override public synchronized void write(int value) {
grow(1);
buf[count++] = (byte) value;
}
@Override public synchronized void write(byte[] data, int offset, int size) {
Objects.checkFromIndexSize(offset, size, data.length);
grow(size);
System.arraycopy(data, offset, buf, count, size);
count += size;
}
@Override public synchronized void reset() {
super.reset();
if (reserved) {
buf = new byte[32];
reserved = false;
budget.release();
}
}
@Override public void close() { reset(); }
}
+118
Переглянути файл
@@ -0,0 +1,118 @@
package ai.openidea.jdbc;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Comparator;
import java.util.concurrent.TimeUnit;
/** Exercises the production frames with a supplied DuckDB JDBC distribution. */
public final class DuckDbSelfTest {
private static final class Bridge implements AutoCloseable {
private final Process child;
private final DataInputStream in;
private final DataOutputStream out;
private long id = 1;
Bridge(String java) throws IOException {
child = SelfTest.start(java, true);
in = new DataInputStream(child.getInputStream());
out = new DataOutputStream(child.getOutputStream());
}
SelfTest.Tagged request(int connection, int status, String... fields) throws IOException {
long current = id++;
SelfTest.sendOn(out, current, connection, fields);
return SelfTest.expect(in, current, status);
}
void open(String url) throws IOException {
request(0, 1, "open", "org.duckdb.DuckDBDriver", url, "", "", "false");
}
void execute(int connection, String sql) throws IOException {
request(connection, 1, "query", sql, "0", "2");
}
String value(int connection, String sql) throws IOException {
var message = request(connection, 1, "query", sql, "0", "2");
try (var value = new DataInputStream(new ByteArrayInputStream(message.data()))) {
assert value.readBoolean();
assert value.readInt() == 1;
text(value); // Column label.
text(value); // JDBC type.
assert value.readBoolean();
return text(value);
}
}
@Override public void close() throws Exception {
try {
out.close();
if (!child.waitFor(5, TimeUnit.SECONDS))
throw new AssertionError("JDBC process did not close its connections on EOF");
assert child.exitValue() == 0 : new String(child.getErrorStream().readAllBytes(), StandardCharsets.UTF_8);
} finally {
if (child.isAlive()) child.destroyForcibly().waitFor();
in.close();
}
}
}
private static String text(DataInputStream in) throws IOException {
int size = in.readInt();
return size == -1 ? null : new String(in.readNBytes(size), StandardCharsets.UTF_8);
}
public static void main(String[] args) throws Exception {
var java = Path.of(System.getProperty("java.home"), "bin", "java").toString();
try (var bridge = new Bridge(java)) {
bridge.open("jdbc:duckdb:");
bridge.request(1, 1, "open");
bridge.request(2, 1, "open");
bridge.execute(1, "CREATE TABLE durable(i INTEGER)");
bridge.execute(1, "INSERT INTO durable VALUES (41)");
assert bridge.value(2, "SELECT i FROM durable").equals("41");
bridge.execute(1, "CREATE TEMP TABLE private_table(i INTEGER)");
bridge.execute(1, "INSERT INTO private_table VALUES (7)");
assert bridge.value(1, "SELECT i FROM private_table").equals("7");
bridge.request(2, 0, "query", "SELECT i FROM private_table", "0", "2");
bridge.execute(1, "ATTACH ':memory:' AS attached_catalog");
bridge.execute(1, "USE attached_catalog");
assert bridge.value(1, "SELECT current_database()").equals("attached_catalog");
assert !bridge.value(2, "SELECT current_database()").equals("attached_catalog");
bridge.execute(1, "CREATE TABLE shared_catalog(i INTEGER)");
bridge.execute(1, "INSERT INTO shared_catalog VALUES (9)");
assert bridge.value(2, "SELECT i FROM attached_catalog.main.shared_catalog").equals("9");
bridge.request(1, 1, "close");
assert bridge.value(2, "SELECT i FROM durable").equals("41");
bridge.request(3, 1, "open");
assert bridge.value(3, "SELECT i FROM attached_catalog.main.shared_catalog").equals("9");
}
var fixture = Files.createTempDirectory("openidea-jdbc-duckdb-");
var url = "jdbc:duckdb:" + fixture.resolve("fixture.duckdb");
try {
try (var bridge = new Bridge(java)) {
bridge.open(url);
bridge.request(1, 1, "open");
bridge.request(2, 1, "open");
bridge.execute(1, "CREATE TABLE durable(i INTEGER)");
bridge.execute(1, "INSERT INTO durable VALUES (42)");
assert bridge.value(2, "SELECT i FROM durable").equals("42");
bridge.request(1, 1, "close");
}
try (var reopened = new Bridge(java)) {
reopened.open(url);
assert reopened.value(0, "SELECT i FROM durable").equals("42");
}
} finally {
try (var paths = Files.walk(fixture)) {
for (var path : paths.sorted(Comparator.reverseOrder()).toList()) Files.delete(path);
}
}
}
}
+287 -6
Переглянути файл
@@ -3,16 +3,21 @@ package ai.openidea.jdbc;
import java.io.*;
import java.lang.reflect.Proxy;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.sql.*;
import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.Logger;
/** Drives the bridge over its actual pipes with a deterministic JDBC driver. */
public class SelfTest {
public static class Fixture implements Driver {
private static final CountDownLatch releaseCancellation = new CountDownLatch(1);
private static final String LARGE_CELL = "x".repeat(16 * 1024);
private boolean readonly;
private boolean dropped;
private int changes;
@@ -42,8 +47,11 @@ public class SelfTest {
});
return proxy(Connection.class, (p, m, a) -> switch (m.getName()) {
case "setReadOnly" -> { readonly = (boolean) a[0]; yield null; }
case "getMetaData" -> meta;
case "close" -> null;
case "getMetaData" -> {
if (path.equals("fail-metadata")) throw new SQLException("private bootstrap detail");
yield meta;
}
case "close" -> { System.err.println("connection closed"); yield null; }
case "createStatement" -> statement();
case "isClosed" -> false;
case "isValid" -> !dropped;
@@ -64,12 +72,43 @@ public class SelfTest {
});
}
static ResultSet largeRows(boolean fail) {
int[] rows = {0};
var metadata = proxy(ResultSetMetaData.class, (p, m, a) -> switch (m.getName()) {
case "getColumnCount" -> 1;
case "getColumnLabel" -> "payload";
case "getColumnTypeName" -> "VARCHAR";
case "getColumnType" -> Types.VARCHAR;
default -> throw new SQLFeatureNotSupportedException();
});
return proxy(ResultSet.class, (p, m, a) -> switch (m.getName()) {
case "next" -> {
if (++rows[0] == 6 && fail) throw new SQLException("large result failed while reading");
yield rows[0] <= 990;
}
case "getMetaData" -> metadata;
case "getString" -> LARGE_CELL;
case "close" -> null;
default -> throw new SQLFeatureNotSupportedException();
});
}
Statement statement() {
var stop = new CountDownLatch(1);
var slowCancel = new AtomicBoolean();
boolean[] failLargeRows = {false};
return proxy(Statement.class, (p, m, a) -> switch (m.getName()) {
case "execute" -> {
String sql = (String) a[0];
if (sql.equals("wait") || sql.equals("ignore cancel")) {
if (sql.equals("large rows") || sql.equals("large error")) {
failLargeRows[0] = sql.equals("large error");
System.err.println("large query started");
yield true;
}
if (sql.equals("write marker")) Files.writeString(started, "once\n", StandardOpenOption.APPEND);
if (sql.equals("release cancel gate")) releaseCancellation.countDown();
if (sql.equals("wait for cancel gate")) slowCancel.set(true);
if (sql.equals("wait") || sql.equals("ignore cancel") || slowCancel.get()) {
if (started != null) java.nio.file.Files.writeString(started, "started");
System.err.println("statement started");
if (sql.equals("ignore cancel")) Thread.sleep(60_000);
@@ -81,7 +120,16 @@ public class SelfTest {
changes++;
yield false;
}
case "cancel" -> { stop.countDown(); yield null; }
case "cancel" -> {
if (slowCancel.get()) {
System.err.println("cancel entered");
if (!releaseCancellation.await(15, TimeUnit.SECONDS))
throw new SQLException("cancel gate timed out");
}
stop.countDown();
yield null;
}
case "getResultSet" -> largeRows(failLargeRows[0]);
case "getUpdateCount" -> changes;
case "close" -> null;
default -> throw new SQLFeatureNotSupportedException();
@@ -114,6 +162,236 @@ public class SelfTest {
return bytes;
}
static void sendOn(DataOutputStream out, long id, int connection, String... fields) throws IOException {
out.writeLong(id);
out.writeInt(connection);
out.writeInt(fields.length);
for (String field : fields) {
byte[] data = field.getBytes(StandardCharsets.UTF_8);
out.writeInt(data.length);
out.write(data);
}
out.flush();
}
record Tagged(long id, byte[] data) {
int status() { return data.length == 0 ? -1 : data[0]; }
}
static Tagged tagged(DataInputStream in) throws IOException {
return new Tagged(in.readLong(), reply(in));
}
static Tagged expect(DataInputStream in, long id, int status) throws IOException {
var message = tagged(in);
assert message.id() == id && message.status() == status
: "Expected reply " + id + "/" + status + ", got " + message.id() + "/" + message.status();
return message;
}
static Process start(String java, boolean multiplex, String... jvmOptions) throws IOException {
var command = new ArrayList<String>();
command.add(java);
command.addAll(List.of(jvmOptions));
command.addAll(List.of("--enable-native-access=ALL-UNNAMED", "-cp", System.getProperty("java.class.path"),
OpenIdeaJdbc.class.getName()));
if (multiplex) command.add("--multiplex");
return new ProcessBuilder(command).start();
}
static void multiplex(String java) throws Exception {
var child = start(java, true);
try (var out = new DataOutputStream(child.getOutputStream());
var in = new DataInputStream(child.getInputStream());
var log = child.errorReader()) {
sendOn(out, 100, 0, "open", Fixture.class.getName(), "jdbc:fixture:", "", "", "false");
try {
expect(in, 100, 1);
} catch (IOException e) {
throw new AssertionError("The bridge did not accept the multiplex bootstrap frame", e);
}
sendOn(out, 101, 1, "open");
expect(in, 101, 1);
sendOn(out, 102, 2, "open");
expect(in, 102, 1);
sendOn(out, 103, 1, "query", "wait for cancel gate", "0", "2");
assert log.lines().anyMatch("statement started"::equals);
sendOn(out, 104, 1, "query", "overlap", "0", "2");
expect(in, 104, 0);
sendOn(out, 103, 2); // Wrong connection must not cancel the active request.
expect(in, 103, -1);
sendOn(out, 105, 2, "query", "independent console", "0", "2");
expect(in, 105, 1);
sendOn(out, 103, 1);
expect(in, 103, -1);
assert log.lines().anyMatch("cancel entered"::equals);
sendOn(out, 106, 0, "schemaColumns", "app");
expect(in, 106, 1); // The driver is still withholding the cancellation response.
sendOn(out, 107, 1, "close");
expect(in, 107, 1);
sendOn(out, 108, 1, "query", "retired", "0", "2");
expect(in, 108, 0);
sendOn(out, 109, 2, "query", "release cancel gate", "0", "2");
var first = tagged(in);
var second = tagged(in);
var statuses = Map.of(first.id(), first.status(), second.id(), second.status());
assert statuses.equals(Map.of(103L, 0, 109L, 1)) : statuses;
assert log.lines().anyMatch("connection closed"::equals);
sendOn(out, 110, 2, "query", "after sibling close", "0", "2");
expect(in, 110, 1);
sendOn(out, 111, 0, "valid");
assert new String(expect(in, 111, 1).data(), StandardCharsets.UTF_8).contains("true");
} finally {
child.destroyForcibly().waitFor();
}
}
static void capacity(String java) throws Exception {
var child = start(java, true);
try (var out = new DataOutputStream(child.getOutputStream());
var in = new DataInputStream(child.getInputStream());
var log = child.errorReader()) {
sendOn(out, 200, 0, "open", Fixture.class.getName(), "jdbc:fixture:fail-metadata", "", "", "false");
var failure = new String(expect(in, 200, 0).data(), StandardCharsets.UTF_8);
assert failure.contains("JDBC connection failed") && !failure.contains("private bootstrap detail");
assert log.lines().anyMatch("connection closed"::equals);
sendOn(out, 201, 0, "open", Fixture.class.getName(), "jdbc:fixture:", "", "", "false");
expect(in, 201, 1);
for (int i = 1; i <= 31; i++) {
sendOn(out, 201 + i, i, "open");
expect(in, 201 + i, 1);
}
sendOn(out, 300, 32, "open");
var full = new String(expect(in, 300, 0).data(), StandardCharsets.UTF_8);
assert full.contains("Close") && full.contains("try again") : full;
sendOn(out, 301, 31, "query", "survives admission failure", "0", "2");
expect(in, 301, 1);
sendOn(out, 302, 1, "close");
expect(in, 302, 1);
sendOn(out, 303, 1, "query", "retired", "0", "2");
expect(in, 303, 0);
assert log.lines().anyMatch("connection closed"::equals);
boolean reopened = false;
for (int attempt = 0; attempt < 20; attempt++) {
int id = 33 + attempt;
sendOn(out, 304 + attempt, id, "open");
var response = tagged(in);
assert response.id() == 304 + attempt;
if (response.status() == 1) {
reopened = true;
break;
}
assert response.status() == 0;
Thread.sleep(5);
}
assert reopened : "A closed console did not release its connection slot";
sendOn(out, 330, 0, "valid");
expect(in, 330, 1);
} finally {
child.destroyForcibly().waitFor();
}
}
static void brokenStreams(String java) throws Exception {
var marker = Files.createTempFile("openidea-jdbc-write-", ".txt");
try {
for (boolean breakOutput : new boolean[]{false, true}) {
Files.writeString(marker, "");
var child = start(java, true);
try (var out = new DataOutputStream(child.getOutputStream());
var in = new DataInputStream(child.getInputStream());
var log = child.errorReader()) {
sendOn(out, 400, 0, "open", Fixture.class.getName(), "jdbc:fixture:" + marker, "", "", "false");
expect(in, 400, 1);
sendOn(out, 401, 1, "open");
expect(in, 401, 1);
if (breakOutput) in.close();
sendOn(out, 402, 1, "query", "write marker", "0", "2");
if (!breakOutput) {
expect(in, 402, 1);
out.writeLong(403);
out.writeInt(1);
out.writeInt(1);
out.writeInt(8);
out.writeByte(0); // A truncated field, not a clean EOF between frames.
out.close();
}
assert child.waitFor(5, TimeUnit.SECONDS) : "Broken JDBC pipe did not terminate (stdout=" + breakOutput + ")";
assert child.exitValue() != 0;
long closed = log.lines().filter("connection closed"::equals).count();
assert closed == 2 : "Broken stdout=" + breakOutput + " closed " + closed + " connections";
assert Files.readAllLines(marker).equals(List.of("once")) : "JDBC write was replayed";
} finally {
child.destroyForcibly().waitFor();
}
}
} finally {
Files.delete(marker);
}
}
static void boundedReplies(String java) throws Exception {
var child = start(java, true, "-Xmx192m");
try (var out = new DataOutputStream(child.getOutputStream());
var in = new DataInputStream(child.getInputStream());
var log = child.errorReader()) {
sendOn(out, 500, 0, "open", Fixture.class.getName(), "jdbc:fixture:", "", "", "false");
expect(in, 500, 1);
int largeQueries = 16;
for (int i = 1; i <= largeQueries + 1; i++) {
sendOn(out, 500 + i, i, "open");
expect(in, 500 + i, 1);
}
for (int i = 1; i <= largeQueries; i++)
sendOn(out, 600 + i, i, "query", "large rows", "0", "1000");
for (int i = 0; i < largeQueries; i++)
assert log.lines().anyMatch("large query started"::equals);
sendOn(out, 700, largeQueries + 1, "query", "small reply", "0", "1");
sendOn(out, 701, largeQueries + 1); // Stale cancel still produces its tagged acknowledgement.
// Back up stdout while the workers assemble their responses. The parent
// drains the payloads in place rather than retaining the test data.
Thread.sleep(300);
Set<Long> replies = new HashSet<>();
int smallAt = -1, ackAt = -1;
for (int i = 0; i < largeQueries + 2; i++) {
long id = in.readLong();
int length = in.readInt();
assert replies.add(id);
if (id == 701) {
assert length == 0;
ackAt = i;
continue;
}
assert length > 0 && length <= OpenIdeaJdbc.LIMIT;
assert in.readBoolean() : "JDBC result did not finish: " + id;
in.skipNBytes(length - 1);
if (id == 700) {
assert length < 1024;
smallAt = i;
} else {
assert id > 600 && id <= 600 + largeQueries && length > 15 * 1024 * 1024;
}
}
assert smallAt >= 0 && smallAt < largeQueries + 1;
assert ackAt >= 0 && ackAt < largeQueries + 1;
sendOn(out, 702, 0, "valid");
expect(in, 702, 1);
sendOn(out, 703, 1, "query", "large error", "0", "1000");
expect(in, 703, 0);
sendOn(out, 704, 2, "query", "large rows", "0", "1000");
assert in.readLong() == 704;
int length = in.readInt();
assert length > 15 * 1024 * 1024 && in.readBoolean();
in.skipNBytes(length - 1); // The failed encoding released its reply reservation.
} finally {
child.destroyForcibly().waitFor();
}
}
public static void main(String[] args) throws Exception {
var boundary = new DataOutputStream(OutputStream.nullOutputStream());
OpenIdeaJdbc.text(boundary, "x".repeat(OpenIdeaJdbc.LIMIT - 14));
@@ -124,8 +402,7 @@ public class SelfTest {
throw new AssertionError("Oversized reply accepted");
} catch (IOException expected) {}
var java = Path.of(System.getProperty("java.home"), "bin", "java").toString();
var child = new ProcessBuilder(java, "-cp", System.getProperty("java.class.path"),
OpenIdeaJdbc.class.getName()).start();
var child = start(java, false);
try (var out = new DataOutputStream(child.getOutputStream());
var in = new DataInputStream(child.getInputStream());
var log = child.errorReader()) {
@@ -163,5 +440,9 @@ public class SelfTest {
} finally {
child.destroyForcibly().waitFor();
}
multiplex(java);
capacity(java);
brokenStreams(java);
boundedReplies(java);
}
}
+1 -1
Переглянути файл
@@ -134,7 +134,7 @@ async fn ensure_server(
}
let (local, build) = match local_server(state, version, &os, &arch, &probe.installed, progress.clone()).await? {
LocalServer::Installed(bin) => return Ok(bin),
LocalServer::Binary(local, build) => (local, build),
LocalServer::Binary { path, build, .. } => (path, build),
};
if let Some(bin) = probe.installed.iter().find(|b| b.ends_with(&format!("/{build}/{SERVER_BIN}"))) {
return Ok(bin.clone());
+49 -28
Переглянути файл
@@ -73,6 +73,7 @@ pub struct Connection {
idle_policy: Option<RemoteIdlePolicy>,
pub target: RemoteTarget,
pub root: String,
pub display_name: String,
pub host: String,
/// The server's `std::env::consts::OS`: where the project's commands run.
pub os: String,
@@ -520,8 +521,8 @@ fn server_path(path: &str) -> bool {
/// What [`local_server`] settled on.
pub(crate) enum LocalServer {
/// A server binary on this machine and its [`build_id`].
Binary(std::path::PathBuf, String),
/// A server binary on this machine. Release downloads may have a reusable archive.
Binary { path: std::path::PathBuf, build: String, release_hash: Option<blake3::Hash> },
/// No binary available (offline): this build of the version already on the host.
Installed(String),
}
@@ -537,10 +538,10 @@ pub(crate) async fn local_server(
) -> IdeResult<LocalServer> {
// This version's server: this build, or the release download (kept per version, so an
// upgraded app never reuses an older one).
let local = match local_server_binary(os, arch) {
Some(local) => local,
let (local, release) = match local_server_binary(os, arch) {
Some(local) => (local, false),
None => match download_server(state, version, os, arch, progress).await {
Ok(local) => local,
Ok(local) => (local, true),
// Offline: any build of this version already on the host will do, then a server put
// in the old unversioned place by hand.
Err(e) => {
@@ -563,7 +564,7 @@ pub(crate) async fn local_server(
e.message,
local.display()
);
local
(local, false)
}
None => {
return Err(IdeError::unavailable(format!(
@@ -580,13 +581,14 @@ pub(crate) async fn local_server(
},
};
// One folder per build, so a rebuilt server of the same version is installed again.
let build = tokio::task::spawn_blocking({
let hash = tokio::task::spawn_blocking({
let local = local.clone();
move || build_id(&local)
move || binary_hash(&local)
})
.await
.map_err(|e| IdeError::internal(e.to_string()))??;
Ok(LocalServer::Binary(local, build))
let build = hash.to_hex()[..16].to_owned();
Ok(LocalServer::Binary { path: local, build, release_hash: release.then_some(hash) })
}
/// Makes sure this version of the server is installed on the host; returns its path.
@@ -603,10 +605,11 @@ async fn ensure_server(state: &AppState, session: &ide_ssh::Session, progress: A
let mut lines = probe.lines().map(str::trim).filter(|l| !l.is_empty());
let (os, arch) = platform(lines.next().unwrap_or_default());
let installed: Vec<String> = lines.map(str::to_owned).collect();
let (local, build) = match local_server(state, version, &os, &arch, &installed, progress.clone()).await? {
LocalServer::Installed(bin) => return Ok(bin),
LocalServer::Binary(local, build) => (local, build),
};
let (local, build, release_hash) =
match local_server(state, version, &os, &arch, &installed, progress.clone()).await? {
LocalServer::Installed(bin) => return Ok(bin),
LocalServer::Binary { path, build, release_hash } => (path, build, release_hash),
};
if let Some(bin) = installed.iter().find(|b| b.ends_with(&format!("/{build}/openidea-server"))) {
return Ok(bin.to_string());
}
@@ -623,9 +626,20 @@ async fn ensure_server(state: &AppState, session: &ide_ssh::Session, progress: A
);
let started = std::time::Instant::now();
progress(RemoteStage::Uploading, Some(0.0));
session
.put_with_progress(&tmp, &tokio::fs::read(&local).await?, &|f| progress(RemoteStage::Uploading, Some(f)))
.await?;
let archive = if let Some(hash) = release_hash {
let local = local.clone();
tokio::task::spawn_blocking(move || ide_tools::server::matching_archive(&local, hash))
.await
.map_err(|e| IdeError::internal(e.to_string()))?
} else {
None
};
let report = |f| progress(RemoteStage::Uploading, Some(f));
if let Some(archive) = archive {
session.put_gzip_with_progress(&tmp, &archive, &report).await?;
} else {
session.put_with_progress(&tmp, &tokio::fs::read(&local).await?, &report).await?;
}
tracing::info!("installed openidea-server on {} in {:?}", session.label(), started.elapsed());
let q = ide_ssh::shell::quote;
// Older builds of this version go (a running one keeps its open file).
@@ -645,21 +659,21 @@ async fn ensure_server(state: &AppState, session: &ide_ssh::Session, progress: A
Ok(remote_bin)
}
/// A short content hash of the server binary (cached per path, size and time).
fn build_id(path: &std::path::Path) -> IdeResult<String> {
static CACHE: Mutex<Option<(std::path::PathBuf, u64, std::time::SystemTime, String)>> = Mutex::new(None);
/// The content hash of the server binary (cached per path, size and time).
fn binary_hash(path: &std::path::Path) -> IdeResult<blake3::Hash> {
static CACHE: Mutex<Option<(std::path::PathBuf, u64, std::time::SystemTime, blake3::Hash)>> = Mutex::new(None);
let meta = std::fs::metadata(path)?;
let modified = meta.modified()?;
if let Some((p, len, time, id)) = &*CACHE.lock()
if let Some((p, len, time, hash)) = &*CACHE.lock()
&& p == path
&& *len == meta.len()
&& *time == modified
{
return Ok(id.clone());
return Ok(*hash);
}
let id = blake3::hash(&std::fs::read(path)?).to_hex()[..16].to_owned();
*CACHE.lock() = Some((path.to_path_buf(), meta.len(), modified, id.clone()));
Ok(id)
let hash = blake3::Hasher::new().update_reader(std::fs::File::open(path)?)?.finalize();
*CACHE.lock() = Some((path.to_path_buf(), meta.len(), modified, hash));
Ok(hash)
}
/// File › Remote Development: opens `path` on `target` (an SSH host, a WSL distribution, or a
@@ -794,6 +808,7 @@ pub async fn remote_connect(
idle_policy: info.idle_policy,
target: target.clone(),
root: root.clone(),
display_name: project.display_name.clone(),
host: host.clone(),
os: info.os.clone(),
server_version: info.version.clone(),
@@ -817,6 +832,7 @@ pub async fn remote_connect(
}
state.host.close_project(&label);
state.host.mcp_reports.set_remote(&label, std::path::PathBuf::from(&connection.root));
crate::window_groups::notify_changed(window.app_handle());
let weak = Arc::downgrade(&connection);
let peer = connection.peer.clone();
let auth_plugins = state.plugins.clone();
@@ -1187,6 +1203,7 @@ pub async fn remote_stop_forwarding(
pub fn remote_disconnect(window: Window, state: State<'_, AppState>) {
state.host.mcp_reports.remove_remote(AppState::owner_window(window.label()));
state.remote_dev.disconnect(AppState::owner_window(window.label()));
crate::window_groups::notify_changed(window.app_handle());
}
/// Stops the persistent `openidea-server` daemon for this window's remote project,
@@ -1215,11 +1232,14 @@ pub async fn remote_stop_backend(window: Window, state: State<'_, AppState>) ->
c.stopping.store(false, Ordering::Release);
}
result?;
let mut connections = state.remote_dev.windows.lock();
if connections.get(&label).is_some_and(|current| Arc::ptr_eq(current, &c)) {
connections.remove(&label);
state.host.mcp_reports.remove_remote(&label);
{
let mut connections = state.remote_dev.windows.lock();
if connections.get(&label).is_some_and(|current| Arc::ptr_eq(current, &c)) {
connections.remove(&label);
state.host.mcp_reports.remove_remote(&label);
}
}
crate::window_groups::notify_changed(window.app_handle());
Ok(())
}
@@ -1549,6 +1569,7 @@ mod tests {
idle_policy: None,
target,
root: root.into(),
display_name: "app".into(),
host: "host".into(),
os: "linux".into(),
server_version: env!("CARGO_PKG_VERSION").into(),
+1 -1
Переглянути файл
@@ -230,7 +230,7 @@ pub(crate) async fn ensure_server(
}
let (local, build) = match local_server(state, version, &os, &arch, &probe.installed, progress.clone()).await? {
LocalServer::Installed(bin) => return Ok(bin),
LocalServer::Binary(local, build) => (local, build),
LocalServer::Binary { path, build, .. } => (path, build),
};
if let Some(bin) = probe.installed.iter().find(|b| b.ends_with(&format!("/{build}/{SERVER_BIN}"))) {
return Ok(bin.clone());
+8 -1
Переглянути файл
@@ -3,7 +3,8 @@
//! Driven by `show_system_notification` from the notification store. Honour
//! global `[notifications].systemNotifications`; suppressed while any window is
//! active. Click focuses the window that raised the toast — balloon actions stay
//! in the IDE.
//! in the IDE. On macOS a click only activates the app: tracking clicks there costs
//! a waiting thread per toast.
use parking_lot::Mutex;
use std::collections::HashMap;
@@ -55,6 +56,12 @@ pub fn init(app: &AppHandle) {
if STATE.ready.swap(true, Ordering::AcqRel) {
return;
}
// macOS: with an action handler the plugin parks a thread per toast until it is clicked,
// so ignored toasts pile up threads and NSUserNotificationCenter CPU. A click on a toast
// already brings the app forward there, so leave the handler out.
if cfg!(target_os = "macos") {
return;
}
let handle = app.clone();
if let Err(e) = app.notification().on_action(move |performed| {
if performed.action_id() != "tap" {
+88 -20
Переглянути файл
@@ -16,6 +16,11 @@ mod frames;
type Group = ide_workspace::window_groups::WindowGroup;
fn is_project_window(app: &AppHandle, label: &str) -> bool {
let state = app.state::<AppState>();
state.remote_dev.get(label).is_some() || state.project(label).is_ok_and(|p| !p.light)
}
#[derive(Clone, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct WindowTab {
@@ -23,6 +28,8 @@ pub struct WindowTab {
pub name: String,
pub root: Option<ide_core::IpcPath>,
pub current: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub remote_host: Option<String>,
}
pub fn current(app: &AppHandle, caller: &str) -> Vec<WindowTab> {
@@ -34,25 +41,43 @@ pub fn current(app: &AppHandle, caller: &str) -> Vec<WindowTab> {
.iter()
.filter_map(|label| {
let window = app.get_webview_window(label)?;
let project = host.project(label).ok();
let name = project.as_ref().map(|p| ide_host::ops::project::info(p).display_name).unwrap_or_else(|| {
// Taken its launch but not finished opening: name the tab after that project.
state
.pending(label)
.and_then(|launch| launch.project)
.and_then(|p| p.file_name().map(|n| n.to_string_lossy().into_owned()))
.unwrap_or_else(|| window.title().unwrap_or_default())
});
Some(WindowTab {
label: label.clone(),
name,
root: project.map(|p| p.root.clone().into()),
current: label == caller,
})
let (name, root, remote_host) = if let Some(c) = host.remote_dev.get(label) {
let loc = crate::remote_dev::remote_location(&c.target, &c.root);
(c.display_name.clone(), Some(PathBuf::from(loc).into()), Some(c.host.clone()))
} else if let Ok(p) = host.project(label) {
(ide_host::ops::project::info(&p).display_name, Some(p.root.clone().into()), None)
} else if let Some(launch) = state.pending(label) {
if let Some(remote) = launch.remote {
let loc = crate::remote_dev::remote_location(&remote.target, &remote.path);
let name = remote
.path
.trim_end_matches('/')
.rsplit('/')
.next()
.filter(|s| !s.is_empty())
.map(str::to_owned)
.unwrap_or_else(|| window.title().unwrap_or_default());
(name, Some(PathBuf::from(loc).into()), None)
} else {
let name = launch
.project
.as_ref()
.and_then(|p| p.file_name().map(|n| n.to_string_lossy().into_owned()))
.unwrap_or_else(|| window.title().unwrap_or_default());
(name, launch.project, None)
}
} else {
(window.title().unwrap_or_default(), None, None)
};
Some(WindowTab { label: label.clone(), name, root, current: label == caller, remote_host })
})
.collect()
}
pub(crate) fn notify_changed(app: &AppHandle) {
changed(app);
}
fn changed(app: &AppHandle) {
app.state::<AppState>().sink.emit(IdeEvent::WindowGroupsChanged);
}
@@ -116,10 +141,9 @@ pub fn join(app: &AppHandle, anchor: &str, new_window: &str) -> IdeResult<()> {
}
pub fn merge(app: &AppHandle, caller: &str) -> IdeResult<()> {
let members = windows::project_window_labels(app)
.into_iter()
.filter(|label| app.state::<AppState>().project(label).is_ok_and(|p| !p.light))
.collect::<Vec<_>>();
let all_windows = windows::project_window_labels(app);
let members =
ide_workspace::window_groups::merge_candidates(&all_windows, caller, |label| is_project_window(app, label));
if members.len() < 2 || !members.iter().any(|label| label == caller) {
return Err(IdeError::invalid("Open at least two project windows to create a window group"));
}
@@ -129,7 +153,51 @@ pub fn merge(app: &AppHandle, caller: &str) -> IdeResult<()> {
window.set_fullscreen(false).map_err(|e| IdeError::internal(e.to_string()))?;
}
}
app.state::<WindowsState>().groups.lock().merge(members, caller)?;
// If a member is currently grouped with a window outside `members` (e.g. a non-project
// window), separate it from that native/frame group before merging.
let state = app.state::<WindowsState>();
let member_set: HashSet<&str> = members.iter().map(String::as_str).collect();
let (split_members, leftover_survivors): (Vec<String>, Vec<String>) = {
let groups = state.groups.lock();
let mut split = Vec::new();
let mut survivors = Vec::new();
for group in groups.groups() {
let has_in = group.members.iter().any(|m| member_set.contains(m.as_str()));
let has_out = group.members.iter().any(|m| !member_set.contains(m.as_str()));
if has_in && has_out {
for m in &group.members {
if member_set.contains(m.as_str()) {
split.push(m.clone());
}
}
if member_set.contains(group.selected.as_str())
&& let Some(survivor) = group.members.iter().find(|m| !member_set.contains(m.as_str()))
{
survivors.push(survivor.clone());
}
}
}
(split, survivors)
};
#[cfg(target_os = "macos")]
{
let _ = &leftover_survivors;
for label in &split_members {
if let Some(window) = app.get_webview_window(label) {
crate::macos::move_tab_to_new_window(&window).map_err(|e| IdeError::internal(e.to_string()))?;
}
}
}
#[cfg(not(target_os = "macos"))]
{
let _ = &split_members;
for label in &leftover_survivors {
if let Some(window) = app.get_webview_window(label) {
let _ = window.show();
}
}
}
state.groups.lock().merge(members, caller)?;
select(app, caller, caller)
}
+5
Переглянути файл
@@ -126,11 +126,13 @@ db_execute trusted project_host bin
db_execute_stream trusted project_host bindings async
db_explain trusted project_host bindings async
db_export_file always desktop bindings async
db_finish_console_transaction trusted project_host bindings async
db_finish_transaction trusted project_host bindings async
db_history trusted project_host bindings async
db_jdbc_driver_classes trusted project_host bindings async
db_jdbc_drivers trusted project_host bindings sync
db_object_ddl trusted project_host bindings async
db_release_console trusted project_host bindings async
db_release_result trusted project_host bindings sync
db_remove_history trusted project_host bindings async
db_remove_jdbc_driver trusted project_host bindings sync
@@ -146,6 +148,7 @@ db_schema_objects trusted project_host bin
db_schemas trusted project_host bindings async
db_server_version trusted desktop bindings async
db_session_context trusted project_host bindings async
db_set_console_manual_commit trusted project_host bindings async
db_set_manual_commit trusted project_host bindings async
db_set_password trusted project_host bindings async
db_set_ssh_secret trusted project_host bindings async
@@ -601,6 +604,8 @@ remove_recent always project_host bin
remove_recent_project always desktop bindings sync
replace_in_files trusted project_host bindings async
replace_preview trusted project_host bindings async
ruff_fix trusted project_host bindings async
ruff_fix_text trusted project_host bindings async
run_application_build trusted project_host bindings async
run_application_publish trusted project_host bindings async
run_apply_settings trusted project_host bindings async
Loaded 100 of 253 files, more files were not shown because too many files have changed in this diff. Show more