дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-11-29 05:52:23 +02:00
Порівняти коміти
144
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
ba880dac06 | ||
|
|
0b1a675fab | ||
|
|
0b06d3313f | ||
|
|
ddaee1f5ce | ||
|
|
623f1fa4e7 | ||
|
|
79f6476d52 | ||
|
|
bd396485c2 | ||
|
|
c04d9381be | ||
|
|
45f6366b92 | ||
|
|
fb0b2d6a5f | ||
|
|
ddea7e5ec5 | ||
|
|
3747a8a63f | ||
|
|
0a8fea1876 | ||
|
|
ccc0eb1f54 | ||
|
|
54dadc4605 | ||
|
|
6fba4671e6 | ||
|
|
d5058b930b | ||
|
|
44aab11296 | ||
|
|
fcd24885c1 | ||
|
|
4b3717618f | ||
|
|
8fd5ee382d | ||
|
|
3a3b2e424a | ||
|
|
b9d0e28f7a | ||
|
|
53627ea2e9 | ||
|
|
55366a2a31 | ||
|
|
0b9610fe69 | ||
|
|
43e3575eb2 | ||
|
|
bc4a422424 | ||
|
|
7ccaa10496 | ||
|
|
b5e45ca98b | ||
|
|
6faff1b1a8 | ||
|
|
1edfa9180b | ||
|
|
b15c56cdb0 | ||
|
|
91ff5c8a15 | ||
|
|
929b6837f9 | ||
|
|
d1af5f656a | ||
|
|
604e9348f2 | ||
|
|
9592b9ee1b | ||
|
|
c658b3eb88 | ||
|
|
cc5d9d95e4 | ||
|
|
75a15b7eed | ||
|
|
b2998cb37a | ||
|
|
5c131edb7e | ||
|
|
bb8906edb8 | ||
|
|
2e3b087db7 | ||
|
|
0c5f1ffabf | ||
|
|
0a9055b40d | ||
|
|
8776bf536f | ||
|
|
9cc781717d | ||
|
|
8f1e95e5a2 | ||
|
|
e49c634064 | ||
|
|
4e82599c49 | ||
|
|
e08de6771d | ||
|
|
d31a22b5dd | ||
|
|
cead5f08f7 | ||
|
|
1fc9a9f5d5 | ||
|
|
11a8152988 | ||
|
|
10b459268e | ||
|
|
382c22cfc3 | ||
|
|
7bb69e353d | ||
|
|
988f93be46 | ||
|
|
494dd61193 | ||
|
|
cbabb5e9b5 | ||
|
|
75997ae0ee | ||
|
|
81df8f2649 | ||
|
|
26992ec4ce | ||
|
|
2c22574be0 | ||
|
|
93368d4379 | ||
|
|
14741101bd | ||
|
|
db60deede5 | ||
|
|
ab2a7767c7 | ||
|
|
49c917880d | ||
|
|
f0db09aca5 | ||
|
|
979cce1175 | ||
|
|
faa7571038 | ||
|
|
264bf6969f | ||
|
|
66e17df216 | ||
|
|
4ff5739854 | ||
|
|
a0c03447a0 | ||
|
|
c4e0900485 | ||
|
|
a42f13edc2 | ||
|
|
18d6041f2f | ||
|
|
15c5e921df | ||
|
|
bc64188c38 | ||
|
|
a3c819e064 | ||
|
|
1f2e92b433 | ||
|
|
8dfca955a5 | ||
|
|
91aba61c97 | ||
|
|
1fb4135b5b | ||
|
|
24598e0dae | ||
|
|
2436ad6fe9 | ||
|
|
c2c6931f0e | ||
|
|
2e0c8dd527 | ||
|
|
f4be752dda | ||
|
|
a52a639b8e | ||
|
|
1b0bf4d741 | ||
|
|
13597e40a1 | ||
|
|
aa1aa91b0d | ||
|
|
032a3b0453 | ||
|
|
07750ad984 | ||
|
|
ba38f070d9 | ||
|
|
c77f4db777 | ||
|
|
d3067c8d3a | ||
|
|
7bf2702565 | ||
|
|
65c45ffe05 | ||
|
|
84b528f0cd | ||
|
|
8621764813 | ||
|
|
22e1c4b927 | ||
|
|
e2817656e8 | ||
|
|
306c71290c | ||
|
|
51ccb68b72 | ||
|
|
2e965810e9 | ||
|
|
31b70cf0ac | ||
|
|
d0989e2a4b | ||
|
|
d96ed8d154 | ||
|
|
6b41870368 | ||
|
|
660becbaa4 | ||
|
|
a0afc478c1 | ||
|
|
07a88c6fa4 | ||
|
|
46bd6fad3c | ||
|
|
f64dbe65b4 | ||
|
|
e2a5a5db81 | ||
|
|
6eb7abff9f | ||
|
|
b46112fe0b | ||
|
|
4507dc172d | ||
|
|
8442c0c339 | ||
|
|
8ffe3bd230 | ||
|
|
1babff55fc | ||
|
|
2ad95150eb | ||
|
|
fe3e647abb | ||
|
|
62cc6768fe | ||
|
|
2e93422270 | ||
|
|
3a1353cc0e | ||
|
|
c5eab0a4a3 | ||
|
|
581c8cf025 | ||
|
|
807c447792 | ||
|
|
217693a56f | ||
|
|
557295b1df | ||
|
|
7c674e70e5 | ||
|
|
1602a5d010 | ||
|
|
a6d135d66f | ||
|
|
924bf6d3b9 | ||
|
|
318c227b0c | ||
|
|
2ce7621abb |
No files matched your search
@@ -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"
|
||||
@@ -30,6 +30,7 @@ on:
|
||||
- "src/ui/**"
|
||||
- "src/editor/api.ts"
|
||||
- "src/editor/navigationProviders.ts"
|
||||
- "src/editor/refactorProviders.ts"
|
||||
- "src/editor/relatedProviders.ts"
|
||||
- "src/editor/core/cm/cornerInset.ts"
|
||||
- "src/editor/core/cm/iconArea.ts"
|
||||
@@ -39,6 +40,7 @@ on:
|
||||
- "src/editor/lsp/hint.ts"
|
||||
- "src/editor/lsp/lsp.ts"
|
||||
- "src/editor/lsp/positions.ts"
|
||||
- "src/editor/lsp/snippet.ts"
|
||||
- "src/bindings.ts"
|
||||
- "src/styles/tokens.css"
|
||||
- "src/test/setup.ts"
|
||||
@@ -106,7 +108,7 @@ jobs:
|
||||
# ide-lsp/dap/run/sdk/tools.
|
||||
unused='^crates/(ide-agent|ide-analysis|ide-android|ide-cli|ide-clipboard|ide-coverage|ide-db|ide-docker|ide-fonts|ide-github|ide-http|ide-mcp|ide-notebook|ide-profiler|ide-scaffold|ide-spell|ide-ssh|ide-vcs|ide-web)/'
|
||||
# The workflow's paths, less those handled per language below.
|
||||
smoke='^(crates/|Cargo\.(toml|lock)$|src/features/(run|debugger|build|build-tools)/|src/platform/|src/workbench/|src/ui/|src/editor/(api|navigationProviders|relatedProviders|core/cm/(cornerInset|iconArea)|lsp/(availability|diagnostics|files|hint|lsp|positions))\.ts$|src/bindings\.ts$|src/styles/tokens\.css$|src/test/setup\.ts$|src-tauri/icons/128x128\.png$|smoke/|vite\.config\.ts$|tsconfig\.json$|package\.json$|pnpm-(lock|workspace)\.yaml$|patches/|\.github/workflows/language-smoke\.yml$|\.github/tool-versions\.env$)'
|
||||
smoke='^(crates/|Cargo\.(toml|lock)$|src/features/(run|debugger|build|build-tools)/|src/platform/|src/workbench/|src/ui/|src/editor/(api|navigationProviders|refactorProviders|relatedProviders|core/cm/(cornerInset|iconArea)|lsp/(availability|diagnostics|files|hint|lsp|positions|snippet))\.ts$|src/bindings\.ts$|src/styles/tokens\.css$|src/test/setup\.ts$|src-tauri/icons/128x128\.png$|smoke/|vite\.config\.ts$|tsconfig\.json$|package\.json$|pnpm-(lock|workspace)\.yaml$|patches/|\.github/workflows/language-smoke\.yml$|\.github/tool-versions\.env$)'
|
||||
langs=""
|
||||
while read -r f; do
|
||||
case "$f" in
|
||||
|
||||
Створено
+50
-48
@@ -4154,7 +4154,7 @@ checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
|
||||
|
||||
[[package]]
|
||||
name = "ide-agent"
|
||||
version = "0.1.54"
|
||||
version = "0.1.55"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"blake3",
|
||||
@@ -4182,7 +4182,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-analysis"
|
||||
version = "0.1.54"
|
||||
version = "0.1.55"
|
||||
dependencies = [
|
||||
"ast-grep-core",
|
||||
"ide-core",
|
||||
@@ -4194,7 +4194,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-android"
|
||||
version = "0.1.54"
|
||||
version = "0.1.55"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"serde",
|
||||
@@ -4205,7 +4205,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-build"
|
||||
version = "0.1.54"
|
||||
version = "0.1.55"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"chardetng",
|
||||
@@ -4223,7 +4223,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-cli"
|
||||
version = "0.1.54"
|
||||
version = "0.1.55"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"serde",
|
||||
@@ -4237,7 +4237,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-clipboard"
|
||||
version = "0.1.54"
|
||||
version = "0.1.55"
|
||||
dependencies = [
|
||||
"gtk",
|
||||
"objc2 0.6.5",
|
||||
@@ -4248,7 +4248,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-command"
|
||||
version = "0.1.54"
|
||||
version = "0.1.55"
|
||||
dependencies = [
|
||||
"heck 0.5.0",
|
||||
"proc-macro2",
|
||||
@@ -4259,7 +4259,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-core"
|
||||
version = "0.1.54"
|
||||
version = "0.1.55"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"dirs 6.0.0",
|
||||
@@ -4281,7 +4281,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-coverage"
|
||||
version = "0.1.54"
|
||||
version = "0.1.55"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-run",
|
||||
@@ -4294,7 +4294,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-dap"
|
||||
version = "0.1.54"
|
||||
version = "0.1.55"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"futures",
|
||||
@@ -4323,7 +4323,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-db"
|
||||
version = "0.1.54"
|
||||
version = "0.1.55"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"bb8",
|
||||
@@ -4362,7 +4362,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-docker"
|
||||
version = "0.1.54"
|
||||
version = "0.1.55"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"serde",
|
||||
@@ -4375,7 +4375,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-drag-out"
|
||||
version = "0.1.54"
|
||||
version = "0.1.55"
|
||||
dependencies = [
|
||||
"gtk",
|
||||
"objc2 0.6.5",
|
||||
@@ -4389,7 +4389,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-extension"
|
||||
version = "0.1.54"
|
||||
version = "0.1.55"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"blake3",
|
||||
@@ -4409,7 +4409,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-flutter"
|
||||
version = "0.1.54"
|
||||
version = "0.1.55"
|
||||
dependencies = [
|
||||
"ide-android",
|
||||
"ide-core",
|
||||
@@ -4420,7 +4420,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-fonts"
|
||||
version = "0.1.54"
|
||||
version = "0.1.55"
|
||||
dependencies = [
|
||||
"objc2-core-foundation",
|
||||
"objc2-core-text",
|
||||
@@ -4432,7 +4432,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-github"
|
||||
version = "0.1.54"
|
||||
version = "0.1.55"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-vcs",
|
||||
@@ -4444,7 +4444,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-heap"
|
||||
version = "0.1.54"
|
||||
version = "0.1.55"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"ide-core",
|
||||
@@ -4463,7 +4463,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-host"
|
||||
version = "0.1.54"
|
||||
version = "0.1.55"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"blake3",
|
||||
@@ -4519,6 +4519,7 @@ dependencies = [
|
||||
"ide-workspace",
|
||||
"ignore",
|
||||
"jsonschema",
|
||||
"notify",
|
||||
"parking_lot 0.12.5",
|
||||
"quick-xml 0.42.0",
|
||||
"regex-lite",
|
||||
@@ -4544,7 +4545,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-http"
|
||||
version = "0.1.54"
|
||||
version = "0.1.55"
|
||||
dependencies = [
|
||||
"hyper-util",
|
||||
"ide-core",
|
||||
@@ -4563,7 +4564,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-index"
|
||||
version = "0.1.54"
|
||||
version = "0.1.55"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"criterion",
|
||||
@@ -4586,7 +4587,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jdwp"
|
||||
version = "0.1.54"
|
||||
version = "0.1.55"
|
||||
dependencies = [
|
||||
"ide-jvm-inspect",
|
||||
"proptest",
|
||||
@@ -4598,7 +4599,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jsonrpc"
|
||||
version = "0.1.54"
|
||||
version = "0.1.55"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"ide-core",
|
||||
@@ -4614,7 +4615,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jvm-attach"
|
||||
version = "0.1.54"
|
||||
version = "0.1.55"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"tempfile",
|
||||
@@ -4623,7 +4624,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jvm-inspect"
|
||||
version = "0.1.54"
|
||||
version = "0.1.55"
|
||||
dependencies = [
|
||||
"futures",
|
||||
"serde",
|
||||
@@ -4634,7 +4635,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-language"
|
||||
version = "0.1.54"
|
||||
version = "0.1.55"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"criterion",
|
||||
@@ -4693,7 +4694,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-lsp"
|
||||
version = "0.1.54"
|
||||
version = "0.1.55"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"dunce",
|
||||
@@ -4723,7 +4724,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-mcp"
|
||||
version = "0.1.54"
|
||||
version = "0.1.55"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"dunce",
|
||||
@@ -4742,7 +4743,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-notebook"
|
||||
version = "0.1.54"
|
||||
version = "0.1.55"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-vfs",
|
||||
@@ -4763,7 +4764,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-plugin"
|
||||
version = "0.1.54"
|
||||
version = "0.1.55"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dunce",
|
||||
@@ -4785,7 +4786,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-profiler"
|
||||
version = "0.1.54"
|
||||
version = "0.1.55"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-jvm-attach",
|
||||
@@ -4799,7 +4800,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-remote"
|
||||
version = "0.1.54"
|
||||
version = "0.1.55"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"futures",
|
||||
@@ -4819,7 +4820,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-run"
|
||||
version = "0.1.54"
|
||||
version = "0.1.55"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"encoding_rs",
|
||||
@@ -4844,7 +4845,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-scaffold"
|
||||
version = "0.1.54"
|
||||
version = "0.1.55"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-tools",
|
||||
@@ -4860,7 +4861,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-sdk"
|
||||
version = "0.1.54"
|
||||
version = "0.1.55"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"dirs 6.0.0",
|
||||
@@ -4886,7 +4887,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-search"
|
||||
version = "0.1.54"
|
||||
version = "0.1.55"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"encoding_rs",
|
||||
@@ -4907,7 +4908,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-spell"
|
||||
version = "0.1.54"
|
||||
version = "0.1.55"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"parking_lot 0.12.5",
|
||||
@@ -4920,7 +4921,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-ssh"
|
||||
version = "0.1.54"
|
||||
version = "0.1.55"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"flate2",
|
||||
@@ -4945,7 +4946,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-streams"
|
||||
version = "0.1.54"
|
||||
version = "0.1.55"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-language",
|
||||
@@ -4958,7 +4959,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-syntax"
|
||||
version = "0.1.54"
|
||||
version = "0.1.55"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-language",
|
||||
@@ -4973,7 +4974,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-terminal"
|
||||
version = "0.1.54"
|
||||
version = "0.1.55"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"libc",
|
||||
@@ -4987,7 +4988,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-text"
|
||||
version = "0.1.54"
|
||||
version = "0.1.55"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"ide-core",
|
||||
@@ -5000,8 +5001,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-tools"
|
||||
version = "0.1.54"
|
||||
version = "0.1.55"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"flate2",
|
||||
"hex",
|
||||
"http",
|
||||
@@ -5023,7 +5025,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-vcs"
|
||||
version = "0.1.54"
|
||||
version = "0.1.55"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dunce",
|
||||
@@ -5045,7 +5047,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-vfs"
|
||||
version = "0.1.54"
|
||||
version = "0.1.55"
|
||||
dependencies = [
|
||||
"chardetng",
|
||||
"dunce",
|
||||
@@ -5072,7 +5074,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-web"
|
||||
version = "0.1.54"
|
||||
version = "0.1.55"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"ide-core",
|
||||
@@ -5088,7 +5090,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-workspace"
|
||||
version = "0.1.54"
|
||||
version = "0.1.55"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dunce",
|
||||
@@ -6727,7 +6729,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "openidea"
|
||||
version = "0.1.54"
|
||||
version = "0.1.55"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"blake3",
|
||||
|
||||
+1
-1
@@ -5,7 +5,7 @@ members = ["crates/*", "src-tauri"]
|
||||
exclude = ["sdk", "plugins"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.1.54"
|
||||
version = "0.1.55"
|
||||
edition = "2024"
|
||||
rust-version = "1.96"
|
||||
license = "Apache-2.0"
|
||||
|
||||
@@ -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());
|
||||
|
||||
+785
-239
File diff suppressed because it is too large.
Load diff
@@ -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,
|
||||
}
|
||||
|
||||
@@ -547,6 +564,9 @@ pub enum AgentEntry {
|
||||
started_ms: Option<f64>,
|
||||
#[serde(default)]
|
||||
ended_ms: Option<f64>,
|
||||
/// The command an `execute` call runs, from its structured input; `None` when the agent gave none.
|
||||
#[serde(default)]
|
||||
command: Option<String>,
|
||||
},
|
||||
Plan {
|
||||
items: Vec<AgentPlanItem>,
|
||||
|
||||
@@ -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: &[],
|
||||
},
|
||||
];
|
||||
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
|
||||
@@ -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());
|
||||
}
|
||||
|
||||
@@ -522,6 +522,7 @@ impl CopilotShim {
|
||||
"session/set_config_option" => self.set_config(¶ms).await,
|
||||
"session/prompt" => self.prompt(¶ms, false).await,
|
||||
"_openidea/steer" => self.prompt(¶ms, true).await,
|
||||
"_openidea/context_usage" => self.context_usage(¶ms).await,
|
||||
"_openidea/stop_task" => self.stop_task(¶ms).await,
|
||||
"session/close" => self.close_session(¶ms).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();
|
||||
|
||||
@@ -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() }]
|
||||
);
|
||||
}
|
||||
@@ -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> {
|
||||
|
||||
@@ -189,6 +189,11 @@ fn parse(text: &str) -> IdeResult<Vec<Entry>> {
|
||||
/// `github/copilot-cli` publishes standalone archives and `SHA256SUMS.txt` on every GitHub
|
||||
/// release. Supplying them installs Copilot without Node.js, npm, `~/.npmrc`, or mirror lag.
|
||||
fn add_copilot_release_binaries(entry: &mut Entry, release_base: &str) {
|
||||
let sys_root = if cfg!(target_os = "linux") { Some(Path::new("/")) } else { None };
|
||||
add_copilot_release_binaries_with_root(entry, release_base, sys_root);
|
||||
}
|
||||
|
||||
fn add_copilot_release_binaries_with_root(entry: &mut Entry, release_base: &str, sys_root: Option<&Path>) {
|
||||
let tag = format!("v{}", entry.version.trim_start_matches('v'));
|
||||
let base = format!("{}/{}", release_base.trim_end_matches('/'), tag);
|
||||
let sha256_url = format!("{base}/SHA256SUMS.txt");
|
||||
@@ -196,9 +201,12 @@ fn add_copilot_release_binaries(entry: &mut Entry, release_base: &str) {
|
||||
Some(p) => (p.args.clone(), p.env.clone()),
|
||||
None => (vec!["--acp".into()], BTreeMap::new()),
|
||||
};
|
||||
let linux = if cfg!(target_env = "musl") { "linuxmusl" } else { "linux" };
|
||||
let linux_arm = format!("copilot-{linux}-arm64.tar.gz");
|
||||
let linux_x64 = format!("copilot-{linux}-x64.tar.gz");
|
||||
let linux_arm = format!(
|
||||
"copilot-{}-arm64.tar.gz",
|
||||
sys_root.map_or("linux", |root| copilot_linux_variant_at(root, Arch::Arm64))
|
||||
);
|
||||
let linux_x64 =
|
||||
format!("copilot-{}-x64.tar.gz", sys_root.map_or("linux", |root| copilot_linux_variant_at(root, Arch::X64)));
|
||||
let targets = [
|
||||
("darwin-aarch64", "copilot-darwin-arm64.tar.gz", "./copilot"),
|
||||
("darwin-x86_64", "copilot-darwin-x64.tar.gz", "./copilot"),
|
||||
@@ -219,6 +227,22 @@ fn add_copilot_release_binaries(entry: &mut Entry, release_base: &str) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Picks `linux` (glibc) or `linuxmusl` from the host's runtime dynamic linker rather than
|
||||
/// `cfg!(target_env = "musl")`: `openidea-server` on Linux is built as static musl so it runs
|
||||
/// on every distro, while Copilot's Linux archives dynamically link glibc or musl.
|
||||
fn copilot_linux_variant_at(root: &Path, arch: Arch) -> &'static str {
|
||||
let (glibc_rel, musl_rel) = match arch {
|
||||
Arch::Arm64 => ("lib/ld-linux-aarch64.so.1", "lib/ld-musl-aarch64.so.1"),
|
||||
Arch::X64 => ("lib64/ld-linux-x86-64.so.2", "lib/ld-musl-x86_64.so.1"),
|
||||
};
|
||||
let glibc = root.join(glibc_rel);
|
||||
let has_musl_name = |p: PathBuf| p.file_name().is_some_and(|n| n.to_string_lossy().contains("musl"));
|
||||
let points_to_musl =
|
||||
fs::read_link(&glibc).is_ok_and(has_musl_name) || fs::canonicalize(&glibc).is_ok_and(has_musl_name);
|
||||
let has_glibc = glibc.exists() && !points_to_musl;
|
||||
if !has_glibc && root.join(musl_rel).exists() { "linuxmusl" } else { "linux" }
|
||||
}
|
||||
|
||||
fn safe_segment(s: &str) -> bool {
|
||||
!s.is_empty()
|
||||
&& !s.starts_with('.')
|
||||
@@ -1304,4 +1328,96 @@ esac
|
||||
assert!(npm_bin.is_file());
|
||||
assert_eq!(CustomAgent::read(&p.agent_file("copilot")).unwrap().command, npm_bin.to_string_lossy());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selects_copilot_linux_archive_from_runtime_dynamic_linker() {
|
||||
let index = r#"{"agents":[
|
||||
{"id":"github-copilot-cli","name":"Copilot","version":"1.0.116",
|
||||
"distribution":{"npx":{"package":"@github/[email protected]","args":["--acp"]}}}
|
||||
]}"#;
|
||||
let archives_for = |root: &Path| -> (String, String) {
|
||||
let mut entry = parse(index).unwrap().remove(0);
|
||||
entry.distribution.binary.clear();
|
||||
add_copilot_release_binaries_with_root(&mut entry, "https://example.invalid/releases", Some(root));
|
||||
(
|
||||
entry.distribution.binary["linux-x86_64"].archive.clone(),
|
||||
entry.distribution.binary["linux-aarch64"].archive.clone(),
|
||||
)
|
||||
};
|
||||
let touch = |path: PathBuf| {
|
||||
fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
fs::write(path, b"").unwrap();
|
||||
};
|
||||
|
||||
// 1. Non-FHS root (neither loader present) defaults to glibc archives.
|
||||
let empty = tempfile::tempdir().unwrap();
|
||||
assert_eq!(
|
||||
archives_for(empty.path()),
|
||||
(
|
||||
"https://example.invalid/releases/v1.0.116/copilot-linux-x64.tar.gz".into(),
|
||||
"https://example.invalid/releases/v1.0.116/copilot-linux-arm64.tar.gz".into(),
|
||||
)
|
||||
);
|
||||
|
||||
// 2. Standard glibc host (and glibc host with musl-tools also installed) uses `copilot-linux-*`,
|
||||
// even when `openidea-server` itself is compiled for `*-unknown-linux-musl`.
|
||||
let glibc = tempfile::tempdir().unwrap();
|
||||
touch(glibc.path().join("lib64/ld-linux-x86-64.so.2"));
|
||||
touch(glibc.path().join("lib/ld-linux-aarch64.so.1"));
|
||||
assert_eq!(
|
||||
archives_for(glibc.path()),
|
||||
(
|
||||
"https://example.invalid/releases/v1.0.116/copilot-linux-x64.tar.gz".into(),
|
||||
"https://example.invalid/releases/v1.0.116/copilot-linux-arm64.tar.gz".into(),
|
||||
)
|
||||
);
|
||||
touch(glibc.path().join("lib/ld-musl-x86_64.so.1"));
|
||||
touch(glibc.path().join("lib/ld-musl-aarch64.so.1"));
|
||||
assert_eq!(
|
||||
archives_for(glibc.path()),
|
||||
(
|
||||
"https://example.invalid/releases/v1.0.116/copilot-linux-x64.tar.gz".into(),
|
||||
"https://example.invalid/releases/v1.0.116/copilot-linux-arm64.tar.gz".into(),
|
||||
)
|
||||
);
|
||||
|
||||
// 3. musl-only host (e.g. Alpine) uses `copilot-linuxmusl-*`.
|
||||
let musl = tempfile::tempdir().unwrap();
|
||||
touch(musl.path().join("lib/ld-musl-x86_64.so.1"));
|
||||
touch(musl.path().join("lib/ld-musl-aarch64.so.1"));
|
||||
assert_eq!(
|
||||
archives_for(musl.path()),
|
||||
(
|
||||
"https://example.invalid/releases/v1.0.116/copilot-linuxmusl-x64.tar.gz".into(),
|
||||
"https://example.invalid/releases/v1.0.116/copilot-linuxmusl-arm64.tar.gz".into(),
|
||||
)
|
||||
);
|
||||
|
||||
// 4. Alpine `libc6-compat` / `gcompat` symlinking `ld-linux` to `ld-musl` still picks `linuxmusl`.
|
||||
#[cfg(unix)]
|
||||
{
|
||||
fs::create_dir_all(musl.path().join("lib64")).unwrap();
|
||||
std::os::unix::fs::symlink("../lib/ld-musl-x86_64.so.1", musl.path().join("lib64/ld-linux-x86-64.so.2"))
|
||||
.unwrap();
|
||||
std::os::unix::fs::symlink("ld-musl-aarch64.so.1", musl.path().join("lib/ld-linux-aarch64.so.1")).unwrap();
|
||||
assert_eq!(
|
||||
archives_for(musl.path()),
|
||||
(
|
||||
"https://example.invalid/releases/v1.0.116/copilot-linuxmusl-x64.tar.gz".into(),
|
||||
"https://example.invalid/releases/v1.0.116/copilot-linuxmusl-arm64.tar.gz".into(),
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
let parsed = parse(index).unwrap().remove(0);
|
||||
let expected_x64 = format!("copilot-{}-x64.tar.gz", copilot_linux_variant_at(Path::new("/"), Arch::X64));
|
||||
assert!(
|
||||
parsed.distribution.binary["linux-x86_64"].archive.ends_with(&expected_x64),
|
||||
"unexpected linux-x86_64 archive: {}",
|
||||
parsed.distribution.binary["linux-x86_64"].archive
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -32,7 +32,7 @@ pub fn widens_access(params: &Value) -> bool {
|
||||
tool.and_then(|t| t.pointer("/rawInput/networkApprovalContext")).is_some_and(|c| !c.is_null())
|
||||
}
|
||||
|
||||
fn command_from_value(val: &Value) -> Option<String> {
|
||||
pub(crate) fn command_from_value(val: &Value) -> Option<String> {
|
||||
match val {
|
||||
Value::String(s) => {
|
||||
let trimmed = s.trim();
|
||||
|
||||
@@ -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(),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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"}));
|
||||
@@ -642,15 +647,144 @@ async fn saved_conversation_reads_do_not_start_or_load_the_agent() {
|
||||
mgr.shutdown();
|
||||
let restored_agent = Arc::new(FakeAgent::default());
|
||||
let restored = manager(tmp.path(), restored_agent.clone());
|
||||
// Listing the tasks leaves the conversation on disk until something asks for it.
|
||||
assert_eq!(restored.subscribe_as("view", Arc::new(|_| {})).len(), 1);
|
||||
assert!(!restored.task(&task.id).unwrap().state.lock().history.is_loaded());
|
||||
assert!(!restored.entries(&task.id, None).unwrap().is_empty());
|
||||
assert!(restored.task(&task.id).unwrap().state.lock().history.is_loaded());
|
||||
assert!(restored_agent.calls.lock().is_empty());
|
||||
assert!(restored.entries("missing-task", None).is_err());
|
||||
assert!(restored.entries(&task.id, Some("missing-subagent".into())).is_err());
|
||||
restored.task(&task.id).unwrap().state.lock().conversation = Conversation::default();
|
||||
restored.task(&task.id).unwrap().state.lock().history.conversation = Conversation::default();
|
||||
assert!(restored.entries(&task.id, None).unwrap().is_empty());
|
||||
restored.shutdown();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn an_archived_task_keeps_no_command_list_and_completes_the_known_one() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
project_root: None,
|
||||
prompt: text("hello"),
|
||||
provider: "claude".into(),
|
||||
config: Vec::new(),
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::NeedsInput).await;
|
||||
let names = |list: Vec<AgentCommand>| list.into_iter().map(|c| c.name).collect::<Vec<_>>();
|
||||
let snapshot = |mgr: &AgentManager| mgr.task(&task.id).unwrap().state.lock().snapshot();
|
||||
assert!(names(snapshot(&mgr).commands).contains(&"review".to_owned()));
|
||||
|
||||
mgr.archive(&task.id).unwrap();
|
||||
assert!(snapshot(&mgr).commands.is_empty());
|
||||
assert!(names(mgr.commands("claude", Some(&task.id)).await.unwrap()).contains(&"review".to_owned()));
|
||||
mgr.shutdown();
|
||||
|
||||
// A list saved with an archived task (by an earlier version) isn't read back.
|
||||
let other = tempfile::tempdir().unwrap();
|
||||
std::fs::create_dir_all(other.path().join("store")).unwrap();
|
||||
let name = format!("{}.json", task.id);
|
||||
let mut file: Value =
|
||||
serde_json::from_slice(&std::fs::read(tmp.path().join("store").join(&name)).unwrap()).unwrap();
|
||||
assert_eq!(file["task"]["status"], json!("archived"));
|
||||
file["task"]["commands"] = json!([{"name": "old", "description": "Old", "hint": null}]);
|
||||
std::fs::write(other.path().join("store").join(&name), serde_json::to_vec(&file).unwrap()).unwrap();
|
||||
let restored = manager(other.path(), Arc::new(FakeAgent::default()));
|
||||
assert!(snapshot(&restored).commands.is_empty());
|
||||
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();
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
project_root: None,
|
||||
prompt: text("Keep this"),
|
||||
provider: "claude".into(),
|
||||
config: Vec::new(),
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::NeedsInput).await;
|
||||
mgr.shutdown();
|
||||
// In a store of its own: a late save of the first manager can't touch it.
|
||||
let name = format!("{}.json", task.id);
|
||||
let mut file: Value =
|
||||
serde_json::from_slice(&std::fs::read(tmp.path().join("store").join(&name)).unwrap()).unwrap();
|
||||
file["entries"].as_array_mut().unwrap().push(json!({"type": "no-such-entry"}));
|
||||
let damaged = serde_json::to_vec(&file).unwrap();
|
||||
let other = tempfile::tempdir().unwrap();
|
||||
std::fs::create_dir_all(other.path().join("store")).unwrap();
|
||||
let path = other.path().join("store").join(&name);
|
||||
std::fs::write(&path, &damaged).unwrap();
|
||||
|
||||
let restored = manager(other.path(), Arc::new(FakeAgent::default()));
|
||||
// The task is listed from its own fields; its conversation shows empty.
|
||||
assert_eq!(restored.subscribe_as("view", Arc::new(|_| {})).len(), 1);
|
||||
assert!(restored.entries(&task.id, None).unwrap().is_empty());
|
||||
restored.rename(&task.id, "Renamed").unwrap();
|
||||
restored.shutdown();
|
||||
assert_eq!(std::fs::read(&path).unwrap(), damaged);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn an_ephemeral_task_is_not_saved_and_asks_for_an_unsaved_session() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
@@ -1198,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.
|
||||
@@ -1479,9 +1614,9 @@ async fn saving_a_large_task_does_not_hold_up_readers() {
|
||||
let path = task_file(tmp.path(), &task.id);
|
||||
for i in 0..24 {
|
||||
let text = format!("output {i}: \"quoted\"\n").repeat(40_000);
|
||||
handle.state.lock().conversation.main.push(AgentEntry::Agent { text });
|
||||
handle.state.lock().history.conversation.main.push(AgentEntry::Agent { text });
|
||||
}
|
||||
let entries = handle.state.lock().conversation.main.entries.clone();
|
||||
let entries = handle.state.lock().history.conversation.main.entries.clone();
|
||||
let started = std::time::Instant::now();
|
||||
let json = serde_json::to_vec(&entries).unwrap();
|
||||
let serialising = started.elapsed();
|
||||
@@ -1574,7 +1709,7 @@ async fn concurrent_saves_keep_the_newest_state_of_each_task() {
|
||||
let task = idle_task(&mgr, name).await;
|
||||
let handle = mgr.task(&task.id).unwrap();
|
||||
// Long enough that a save takes a while between the copy and the write.
|
||||
handle.state.lock().conversation.main.push(AgentEntry::Agent { text: "text ".repeat(60_000) });
|
||||
handle.state.lock().history.conversation.main.push(AgentEntry::Agent { text: "text ".repeat(60_000) });
|
||||
tasks.push((name, handle, task_file(tmp.path(), &task.id)));
|
||||
}
|
||||
// "<name> <n>", n growing with every change made under the state lock.
|
||||
@@ -1708,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() {
|
||||
@@ -2684,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!({}));
|
||||
@@ -2693,7 +3006,7 @@ async fn startup_warnings_survive_replay_and_restart_without_failing_the_task()
|
||||
mgr.shutdown();
|
||||
let restored = manager(tmp.path(), agent);
|
||||
let handle = restored.task(&task.id).unwrap();
|
||||
assert_eq!(handle.state.lock().conversation.main.entries.iter().filter(|entry| matches!(entry, AgentEntry::Error {message} if message == "Project MCP config is disabled until trusted.")).count(), 1);
|
||||
assert_eq!(handle.state.lock().history.conversation.main.entries.iter().filter(|entry| matches!(entry, AgentEntry::Error {message} if message == "Project MCP config is disabled until trusted.")).count(), 1);
|
||||
restored.shutdown();
|
||||
}
|
||||
|
||||
@@ -2720,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(¶ms))
|
||||
let epoch = handle.shared.shutdown_epoch();
|
||||
tokio::task::spawn_blocking(move || handle.ask_permission(¶ms, epoch))
|
||||
};
|
||||
wait_for(&mgr, &task.id, AgentStatus::NeedsInput).await;
|
||||
assert!(!asking.is_finished());
|
||||
@@ -2789,13 +3103,13 @@ async fn forks_rollbacks_and_steering() {
|
||||
"state": {"state": "idle", "stopReason": "end_turn"}}),
|
||||
);
|
||||
}
|
||||
handle.state.lock().conversation.main.entries.insert(0, AgentEntry::Agent { text: "Welcome".into() });
|
||||
handle.state.lock().history.conversation.main.entries.insert(0, AgentEntry::Agent { text: "Welcome".into() });
|
||||
let rewinds = agent.calls.lock().iter().filter(|c| c.starts_with("_openidea/rollback")).count();
|
||||
let first = mgr.rollback(&task.id, 0, false).await.unwrap().unwrap();
|
||||
assert_eq!(first.text, "again");
|
||||
assert!(mgr.entries(&task.id, None).unwrap().is_empty());
|
||||
assert!(mgr.task(&task.id).unwrap().state.lock().session_id.is_none());
|
||||
assert!(handle.state.lock().conversation.saved_subagents().is_empty());
|
||||
assert!(handle.state.lock().history.conversation.saved_subagents().is_empty());
|
||||
assert!(handle.state.lock().task.usage.is_none());
|
||||
assert_eq!(agent.calls.lock().iter().filter(|c| c.starts_with("_openidea/rollback")).count(), rewinds);
|
||||
mgr.shutdown();
|
||||
@@ -4369,6 +4683,7 @@ fn a_running_tools_output_is_sent_as_appends() {
|
||||
diffs: Vec::new(),
|
||||
started_ms: Some(1.0),
|
||||
ended_ms: None,
|
||||
command: None,
|
||||
};
|
||||
let running = |output| call(AgentToolStatus::Running, output);
|
||||
let event = |streamed: &mut Streamed, session: Session, i, entry: &AgentEntry| {
|
||||
@@ -4950,7 +5265,7 @@ async fn rolling_back_to_a_message_puts_back_the_files_as_it_was_sent() {
|
||||
Isolation::Worktree => None,
|
||||
};
|
||||
assert_eq!(read("later.txt").as_deref(), later, "{case}");
|
||||
assert_eq!(mgr.task(&task.id).unwrap().state.lock().turns.len(), 1, "{case}");
|
||||
assert_eq!(mgr.task(&task.id).unwrap().state.lock().history.turns.len(), 1, "{case}");
|
||||
|
||||
// Without `files` they stay; the first message takes the task back to its start.
|
||||
one_turn(&mgr, &task.id, Some("retry"), || write("a.txt", "again\n")).await;
|
||||
@@ -4958,7 +5273,7 @@ async fn rolling_back_to_a_message_puts_back_the_files_as_it_was_sent() {
|
||||
assert_eq!(read("a.txt").as_deref(), Some("again\n"), "{case}");
|
||||
mgr.rollback(&task.id, 0, true).await.unwrap();
|
||||
assert_eq!(read("a.txt").as_deref(), Some("base\n"), "{case}");
|
||||
assert!(mgr.task(&task.id).unwrap().state.lock().turns.is_empty(), "{case}");
|
||||
assert!(mgr.task(&task.id).unwrap().state.lock().history.turns.is_empty(), "{case}");
|
||||
let left = std::fs::read_dir(repo.dir.join("store").join(format!("{}.turn", task.id)));
|
||||
assert!(left.map_or(true, |mut d| d.next().is_none()), "{case}: no copies left");
|
||||
mgr.delete(&task.id, true).await.unwrap();
|
||||
@@ -4979,7 +5294,7 @@ async fn a_message_sent_before_turns_were_recorded_cannot_take_the_files_back()
|
||||
one_turn(&mgr, &task.id, Some("more"), || repo.write("a.txt", "base\nturn 1\nturn 2\n")).await;
|
||||
one_turn(&mgr, &task.id, Some("last"), || repo.write("a.txt", "base\nturn 1\nturn 2\nturn 3\n")).await;
|
||||
// As a task saved with its last turn's record only.
|
||||
mgr.task(&task.id).unwrap().state.lock().turns[1] = None;
|
||||
mgr.task(&task.id).unwrap().state.lock().history.turns[1] = None;
|
||||
assert!(mgr.rollback(&task.id, 1, true).await.is_err());
|
||||
assert_eq!(turn_starts(&mgr.entries(&task.id, None).unwrap()).len(), 3, "nothing changed");
|
||||
assert_eq!(repo.read("a.txt"), "base\nturn 1\nturn 2\nturn 3\n");
|
||||
@@ -5007,7 +5322,7 @@ async fn rolling_back_to_first_message_without_turn_record_checks_before_changin
|
||||
{
|
||||
let handle = mgr.task(&task.id).unwrap();
|
||||
let mut s = handle.state.lock();
|
||||
s.turns[0] = None;
|
||||
s.history.turns[0] = None;
|
||||
s.saved = None;
|
||||
}
|
||||
assert!(mgr.rollback(&task.id, 0, true).await.is_err());
|
||||
|
||||
@@ -91,6 +91,7 @@ impl Timeline {
|
||||
diffs: Vec::new(),
|
||||
started_ms: Some(crate::now_ms()),
|
||||
ended_ms: None,
|
||||
command: None,
|
||||
};
|
||||
let index = match self.tools.get(&id) {
|
||||
Some(&i) => {
|
||||
@@ -154,7 +155,7 @@ impl Timeline {
|
||||
}
|
||||
|
||||
fn merge_tool(&mut self, index: usize, update: &Value) {
|
||||
let AgentEntry::Tool { title, kind, status, locations: locs, output, images, diffs, ended_ms, .. } =
|
||||
let AgentEntry::Tool { title, kind, status, locations: locs, output, images, diffs, ended_ms, command, .. } =
|
||||
&mut self.entries[index]
|
||||
else {
|
||||
return;
|
||||
@@ -171,6 +172,11 @@ impl Timeline {
|
||||
*ended_ms = Some(crate::now_ms());
|
||||
}
|
||||
}
|
||||
if let Some(raw) = update.pointer("/rawInput/command").or_else(|| update.pointer("/rawInput/cmd"))
|
||||
&& let Some(cmd) = crate::security::command_from_value(raw)
|
||||
{
|
||||
*command = Some(crate::shell_script(&cmd).unwrap_or(cmd));
|
||||
}
|
||||
if update.get("locations").is_some_and(Value::is_array) {
|
||||
*locs = locations(update.get("locations"));
|
||||
}
|
||||
@@ -471,6 +477,34 @@ mod tests {
|
||||
assert!(matches!(&t.entries[0], AgentEntry::Question { chosen: Some(answer), .. } if answer == "One"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_execute_call_keeps_the_command_from_its_structured_input() {
|
||||
let mut t = Timeline::default();
|
||||
let command = |t: &Timeline, i: usize| match &t.entries[i] {
|
||||
AgentEntry::Tool { command, .. } => command.clone(),
|
||||
_ => panic!(),
|
||||
};
|
||||
t.apply(&json!({"sessionUpdate": "tool_call", "toolCallId": "a", "title": "Run command", "kind": "execute",
|
||||
"rawInput": {"command": "python hello_world.py"}}));
|
||||
assert_eq!(command(&t, 0).as_deref(), Some("python hello_world.py"));
|
||||
// An argv array whose shell wraps the script, sent with a later update.
|
||||
t.apply(&json!({"sessionUpdate": "tool_call", "toolCallId": "b", "title": "Run command", "kind": "execute"}));
|
||||
assert_eq!(command(&t, 1), None);
|
||||
t.apply(&json!({"sessionUpdate": "tool_call_update", "toolCallId": "b",
|
||||
"rawInput": {"cmd": ["bash", "-lc", "cargo test -p ide-agent"]}}));
|
||||
assert_eq!(command(&t, 1).as_deref(), Some("cargo test -p ide-agent"));
|
||||
// One shell line, unwrapped as the permission card does.
|
||||
t.apply(&json!({"sessionUpdate": "tool_call", "toolCallId": "c", "kind": "execute",
|
||||
"rawInput": {"command": "/bin/zsh -lc 'node hello.js'"}}));
|
||||
assert_eq!(command(&t, 2).as_deref(), Some("node hello.js"));
|
||||
// A later update without one keeps it; tasks saved before the field load without it.
|
||||
t.apply(&json!({"sessionUpdate": "tool_call_update", "toolCallId": "c", "status": "completed"}));
|
||||
assert_eq!(command(&t, 2).as_deref(), Some("node hello.js"));
|
||||
let mut old = serde_json::to_value(&t.entries[2]).unwrap();
|
||||
old.as_object_mut().unwrap().remove("command");
|
||||
assert!(matches!(serde_json::from_value(old).unwrap(), AgentEntry::Tool { command: None, .. }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tool_images_survive_updates_text_truncation_and_serialization() {
|
||||
use base64::Engine;
|
||||
|
||||
@@ -323,7 +323,8 @@ mod tests {
|
||||
"exclude": [path(&root.join("node_modules"))],
|
||||
})
|
||||
);
|
||||
let a = root.join("packages/a");
|
||||
// Chained joins: the configurations name native paths, `packages/a` would mix separators on Windows.
|
||||
let a = root.join("packages").join("a");
|
||||
assert_eq!(
|
||||
copy(1),
|
||||
json!({
|
||||
@@ -336,14 +337,14 @@ mod tests {
|
||||
"exclude": [path(&a.join("node_modules"))],
|
||||
})
|
||||
);
|
||||
let b = root.join("packages/b");
|
||||
let b = root.join("packages").join("b");
|
||||
assert_eq!(
|
||||
copy(2),
|
||||
json!({
|
||||
"extends": path(&b.join("tsconfig.json")),
|
||||
"compilerOptions": {
|
||||
"outDir": path(&scratch.join("2")), "tsBuildInfoFile": s("2.tsbuildinfo"),
|
||||
"declarationDir": path(&scratch.join("2")), "outFile": path(&scratch.join("2/out.js")),
|
||||
"declarationDir": path(&scratch.join("2")), "outFile": path(&scratch.join("2").join("out.js")),
|
||||
},
|
||||
"references": [{"path": s("1.json")}],
|
||||
"exclude": [path(&b.join("node_modules")), path(&root.join("dist"))],
|
||||
|
||||
@@ -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());
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -91,12 +91,14 @@ fn plan(root: &Path, model: &BuildModel, cancel: &CancellationToken) -> IdeResul
|
||||
|
||||
/// Run the project's configured wrapper/settings/JDK and lifecycle, with an output
|
||||
/// redirector loaded before Maven calculates its lifecycle execution plans.
|
||||
/// Builds the Kotlin libraries; `on_progress` gets Maven's progress (message, fraction 0..1).
|
||||
pub fn build(
|
||||
root: &Path,
|
||||
model: &BuildModel,
|
||||
bundle: &Path,
|
||||
generation: &Path,
|
||||
cancel: &CancellationToken,
|
||||
on_progress: &(dyn Fn(&str, Option<f32>) + Sync),
|
||||
) -> IdeResult<Outcome> {
|
||||
std::fs::create_dir_all(generation)?;
|
||||
let mut plan = plan(root, model, cancel)?;
|
||||
@@ -124,10 +126,10 @@ pub fn build(
|
||||
for step in &plan.steps {
|
||||
let mut reactor = plan.clone();
|
||||
reactor.steps = vec![step.clone()];
|
||||
let result = compile::run(root, &reactor, cancel, &|event| {
|
||||
if let BuildEvent::Output { text, .. } = event {
|
||||
tracing::debug!("kotlin bridge: {}", text.trim_end());
|
||||
}
|
||||
let result = compile::run(root, &reactor, cancel, &|event| match event {
|
||||
BuildEvent::Output { text, .. } => tracing::debug!("kotlin bridge: {}", text.trim_end()),
|
||||
BuildEvent::Progress { message, fraction } => on_progress(&message, fraction),
|
||||
_ => {}
|
||||
})?;
|
||||
messages.extend(result.messages);
|
||||
}
|
||||
@@ -456,6 +458,7 @@ mod tests {
|
||||
Path::new("unused.jar"),
|
||||
&directory.path().join("private"),
|
||||
&CancellationToken::new(),
|
||||
&|_, _| {},
|
||||
)
|
||||
.err()
|
||||
.unwrap();
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,13 +13,34 @@ use std::sync::Arc;
|
||||
|
||||
/// What a built-in MCP tool asks the project window for. `AgentRun` runs `command` (a shell
|
||||
/// line) in the Run tool window's agent tab `name`, on pipes, answered once the process
|
||||
/// started or failed to.
|
||||
/// started or failed to. `RunConfiguration` starts a run configuration (a serialized
|
||||
/// `RunConfig`, its before launch tasks already done) in the Run tool window as the user's
|
||||
/// Run would, answered the same way.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
#[serde(tag = "type", rename_all = "camelCase", rename_all_fields = "camelCase")]
|
||||
pub enum McpUiRequest {
|
||||
Confirm { client: String, tool: String, subject: String, project: String, detail: Option<String> },
|
||||
OpenFile { path: crate::IpcPath, line: Option<u32>, column: Option<u32> },
|
||||
AgentRun { name: String, command: String, cwd: crate::IpcPath, env: BTreeMap<String, String> },
|
||||
Confirm {
|
||||
client: String,
|
||||
tool: String,
|
||||
subject: String,
|
||||
project: String,
|
||||
detail: Option<String>,
|
||||
},
|
||||
OpenFile {
|
||||
path: crate::IpcPath,
|
||||
line: Option<u32>,
|
||||
column: Option<u32>,
|
||||
},
|
||||
AgentRun {
|
||||
name: String,
|
||||
command: String,
|
||||
cwd: crate::IpcPath,
|
||||
env: BTreeMap<String, String>,
|
||||
},
|
||||
RunConfiguration {
|
||||
#[specta(type = specta_typescript::Unknown)]
|
||||
config: serde_json::Value,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
@@ -27,6 +48,10 @@ pub enum McpUiRequest {
|
||||
pub enum IdeEvent {
|
||||
/// Project data source settings changed; reload the Database tree.
|
||||
DbSourcesChanged,
|
||||
/// A Python run saved a matplotlib figure for the Plots tool window (a PNG file).
|
||||
PlotAdded {
|
||||
path: String,
|
||||
},
|
||||
McpRequest {
|
||||
id: u32,
|
||||
request: McpUiRequest,
|
||||
|
||||
@@ -99,6 +99,20 @@ pub struct AgentSettings {
|
||||
pub smooth_text: bool,
|
||||
/// Conversations and the composer expand to the full width of the pane instead of staying in a centred column.
|
||||
pub fit_window_width: bool,
|
||||
/// Chat text follows the interface font (Appearance › Use custom font).
|
||||
pub chat_use_ui_font: bool,
|
||||
/// Chat text family when it does not follow the interface font.
|
||||
pub chat_font_family: String,
|
||||
/// Covers characters the chat font lacks.
|
||||
pub chat_font_fallback: String,
|
||||
pub chat_font_size: u32,
|
||||
/// Code in chat follows the built-in code font.
|
||||
pub code_use_default_font: bool,
|
||||
/// Code family when it does not follow the built-in code font.
|
||||
pub code_font_family: String,
|
||||
/// Covers characters the code font lacks.
|
||||
pub code_font_fallback: String,
|
||||
pub code_font_size: u32,
|
||||
#[serde(deserialize_with = "or_default")]
|
||||
#[specta(type = ThinkingDisplay)]
|
||||
pub thinking: ThinkingDisplay,
|
||||
@@ -145,6 +159,14 @@ impl Default for AgentSettings {
|
||||
show_cost: false,
|
||||
smooth_text: true,
|
||||
fit_window_width: false,
|
||||
chat_use_ui_font: true,
|
||||
chat_font_family: "Inter".into(),
|
||||
chat_font_fallback: String::new(),
|
||||
chat_font_size: 13,
|
||||
code_use_default_font: true,
|
||||
code_font_family: "JetBrains Mono".into(),
|
||||
code_font_fallback: String::new(),
|
||||
code_font_size: 13,
|
||||
thinking: ThinkingDisplay::Auto,
|
||||
tool_calls: ToolCallDisplay::Grouped,
|
||||
expand_tool_output: false,
|
||||
@@ -840,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.
|
||||
@@ -979,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(),
|
||||
@@ -1373,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 {
|
||||
@@ -1401,6 +1428,7 @@ impl Default for ExternalFormatterSettings {
|
||||
.collect(),
|
||||
prefer: false,
|
||||
run_on_save: false,
|
||||
fix_on_save: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1429,6 +1457,12 @@ pub struct PythonSettings {
|
||||
/// Default test runner (Settings › Python › Testing): `auto` (pytest when the project uses
|
||||
/// it, else unittest), `pytest` or `unittest`.
|
||||
pub test_runner: String,
|
||||
/// What Profile runs Python under (Settings › Python › Profiler): `auto` (py-spy where it
|
||||
/// is installed and samples without root, else cProfile), `cprofile` or `py-spy`.
|
||||
pub profiler: String,
|
||||
/// Show matplotlib figures of Python runs in the Plots tool window (the IDE sets `MPLBACKEND`
|
||||
/// unless the run sets it); off: matplotlib's own window.
|
||||
pub show_plots_in_tool_window: bool,
|
||||
}
|
||||
|
||||
impl Default for PythonSettings {
|
||||
@@ -1442,6 +1476,8 @@ impl Default for PythonSettings {
|
||||
show_interpreter_paths: true,
|
||||
interpreter_paths: BTreeMap::new(),
|
||||
test_runner: "auto".into(),
|
||||
profiler: "auto".into(),
|
||||
show_plots_in_tool_window: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1923,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() };
|
||||
@@ -1956,6 +2002,19 @@ mod tests {
|
||||
assert_eq!(json["appearance"]["smoothScrolling"], false);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn database_output_destination_defaults_and_round_trips() {
|
||||
let old: Settings = serde_json::from_str(r#"{"database":{"inEditorResults":true}}"#).unwrap();
|
||||
assert_eq!(old.database.output_destination, DatabaseOutputDestination::DatabaseOutput);
|
||||
assert!(old.database.in_editor_results);
|
||||
|
||||
let services: Settings = serde_json::from_str(r#"{"database":{"outputDestination":"services"}}"#).unwrap();
|
||||
assert_eq!(services.database.output_destination, DatabaseOutputDestination::Services);
|
||||
let saved = serde_json::to_value(&services).unwrap();
|
||||
assert_eq!(saved["database"]["outputDestination"], "services");
|
||||
assert_eq!(serde_json::from_value::<Settings>(saved).unwrap().database, services.database);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn window_close_settings_default_off_and_round_trip() {
|
||||
for old in [r#"{}"#, r#"{"general":{"confirmExit":false}}"#] {
|
||||
|
||||
@@ -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,
|
||||
@@ -402,13 +405,24 @@ impl Default for LogLevelColors {
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct DatabaseSettings {
|
||||
/// A console's result sets show under the statements that produced them, in the editor,
|
||||
/// instead of in the Services view's result tabs.
|
||||
/// instead of in the output window's result tabs.
|
||||
pub in_editor_results: bool,
|
||||
/// The tool window that receives SQL query output and plans.
|
||||
pub output_destination: DatabaseOutputDestination,
|
||||
/// Languages & Frameworks › SQL Resolution Scopes: the data source SQL in a file or folder
|
||||
/// resolves against (completion, inspections, navigation), most specific path first.
|
||||
pub resolution_scopes: Vec<SqlResolutionScope>,
|
||||
}
|
||||
|
||||
/// Database › Query Output: where SQL results open.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum DatabaseOutputDestination {
|
||||
#[default]
|
||||
DatabaseOutput,
|
||||
Services,
|
||||
}
|
||||
|
||||
/// One row of SQL Resolution Scopes.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
@@ -728,6 +742,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();
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "ide-coverage"
|
||||
description = "Run with Coverage: coverage-tool launch plans (cargo-llvm-cov, vitest / jest / c8, coverage.py, go test, JaCoCo) and report parsers (lcov, Go cover profiles, JaCoCo XML)"
|
||||
description = "Run with Coverage: coverage-tool launch plans (cargo-llvm-cov, vitest / jest / c8, coverage.py, go test, JaCoCo) and report parsers (lcov, Go cover profiles, JaCoCo and Cobertura XML, SimpleCov, coverage.py data)"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
@@ -0,0 +1,174 @@
|
||||
//! Cobertura XML reports (`coverage xml` of coverage.py, and many other tools):
|
||||
//!
|
||||
//! ```xml
|
||||
//! <coverage>
|
||||
//! <sources><source>/home/runner/work/app/app</source></sources>
|
||||
//! <packages><package name="calc"><classes>
|
||||
//! <class filename="src/calc/__init__.py">
|
||||
//! <methods/>
|
||||
//! <lines>
|
||||
//! <line number="2" hits="1" branch="true" condition-coverage="50% (1/2)"/>
|
||||
//! ```
|
||||
//!
|
||||
//! A relative `filename` belongs to the first `<source>` it exists under, else to the
|
||||
//! first `<source>` (whose path may be another machine's; the importer relocates it).
|
||||
//! Lines repeated under `<methods>` are skipped so their hits don't count twice.
|
||||
|
||||
use crate::Accumulator;
|
||||
use quick_xml::events::{BytesStart, Event};
|
||||
use quick_xml::{Reader, XmlVersion};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
fn attr(e: &BytesStart, name: &str) -> Option<String> {
|
||||
e.attributes()
|
||||
.flatten()
|
||||
.find(|a| a.key.as_ref() == name)
|
||||
.and_then(|a| a.normalized_value(XmlVersion::Implicit1_0).ok())
|
||||
.map(Into::into)
|
||||
}
|
||||
|
||||
/// `"50% (1/2)"` → `(1, 2)`.
|
||||
fn conditions(text: &str) -> Option<(u32, u32)> {
|
||||
let (_, rest) = text.split_once('(')?;
|
||||
let (covered, total) = rest.trim_end_matches(')').split_once('/')?;
|
||||
Some((covered.trim().parse().ok()?, total.trim().parse().ok()?))
|
||||
}
|
||||
|
||||
/// `sources` pairs each `<source>` with whether it exists here (asked once: another
|
||||
/// machine's `/home/…` is slow to look up on macOS).
|
||||
fn resolve(filename: &str, sources: &[(PathBuf, bool)], base: &Path) -> PathBuf {
|
||||
let p = Path::new(filename);
|
||||
if p.has_root() {
|
||||
return p.to_path_buf();
|
||||
}
|
||||
sources
|
||||
.iter()
|
||||
.filter(|(_, here)| *here)
|
||||
.map(|(s, _)| s.join(p))
|
||||
.find(|c| c.is_file())
|
||||
.unwrap_or_else(|| sources.first().map_or_else(|| base.join(p), |(s, _)| s.join(p)))
|
||||
}
|
||||
|
||||
/// Relative sources (and filenames without sources) resolve against `base`.
|
||||
pub(crate) fn parse(xml: &str, base: &Path) -> Result<Accumulator, quick_xml::Error> {
|
||||
let mut reader = Reader::from_str(xml);
|
||||
let mut acc = Accumulator::default();
|
||||
let mut sources: Vec<(PathBuf, bool)> = Vec::new();
|
||||
let mut source: Option<String> = None;
|
||||
let mut file: Option<PathBuf> = None;
|
||||
let mut in_methods = false;
|
||||
loop {
|
||||
match reader.read_event()? {
|
||||
Event::Start(e) if e.name().as_ref() == "methods" => in_methods = true,
|
||||
Event::Start(e) | Event::Empty(e) => match e.name().as_ref() {
|
||||
"source" => source = Some(String::new()),
|
||||
"class" => {
|
||||
let path = resolve(&attr(&e, "filename").unwrap_or_default(), &sources, base);
|
||||
acc.file(&path);
|
||||
file = Some(path);
|
||||
}
|
||||
"line" if !in_methods => {
|
||||
let Some(path) = &file else { continue };
|
||||
let Some(number) = attr(&e, "number").and_then(|n| n.parse::<u32>().ok()) else { continue };
|
||||
let line = number.saturating_sub(1);
|
||||
acc.line(path, line, attr(&e, "hits").and_then(|h| h.parse().ok()).unwrap_or(0));
|
||||
if attr(&e, "branch").as_deref() == Some("true")
|
||||
&& let Some((covered, total)) = attr(&e, "condition-coverage").as_deref().and_then(conditions)
|
||||
{
|
||||
acc.has_branches = true;
|
||||
for i in 0..total {
|
||||
acc.branch(path, line, i.to_string(), i < covered);
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
},
|
||||
Event::Text(t) => {
|
||||
if let Some(s) = &mut source {
|
||||
s.push_str(t.as_ref());
|
||||
}
|
||||
}
|
||||
Event::GeneralRef(r) => {
|
||||
if let Some(s) = &mut source {
|
||||
s.push('&');
|
||||
s.push_str(r.as_ref());
|
||||
s.push(';');
|
||||
}
|
||||
}
|
||||
Event::End(e) => match e.name().as_ref() {
|
||||
"source" => {
|
||||
let raw = source.take().unwrap_or_default();
|
||||
let text = quick_xml::escape::unescape(raw.trim()).map(|t| t.into_owned()).unwrap_or(raw);
|
||||
if !text.is_empty() {
|
||||
let path = Path::new(&text);
|
||||
// Joining a drive-less foreign root on Windows would add the checkout's drive.
|
||||
let dir = if path.has_root() { path.to_path_buf() } else { base.join(path) };
|
||||
let here = dir.is_dir();
|
||||
sources.push((dir, here));
|
||||
}
|
||||
}
|
||||
"methods" => in_methods = false,
|
||||
"class" => file = None,
|
||||
_ => {}
|
||||
},
|
||||
Event::Eof => break,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Ok(acc)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn reads_lines_branches_and_skips_method_lines() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let second = tmp.path().join("b&c");
|
||||
std::fs::create_dir_all(&second).unwrap();
|
||||
std::fs::write(second.join("m.py"), "").unwrap();
|
||||
let xml = format!(
|
||||
r#"<?xml version="1.0" ?>
|
||||
<!DOCTYPE coverage SYSTEM "http://cobertura.sourceforge.net/xml/coverage-04.dtd">
|
||||
<coverage><sources><source>/elsewhere/a</source><source>{}</source></sources>
|
||||
<packages><package name="p"><classes>
|
||||
<class name="m" filename="m.py">
|
||||
<methods><method name="f"><lines><line number="2" hits="5"/></lines></method></methods>
|
||||
<lines>
|
||||
<line number="1" hits="1"/>
|
||||
<line number="2" hits="5" branch="true" condition-coverage="50% (1/2)" missing-branches="3"/>
|
||||
<line number="3" hits="0"/>
|
||||
</lines>
|
||||
</class>
|
||||
<class name="n" filename="n.py"><lines><line number="1" hits="0"/></lines></class>
|
||||
<class name="abs" filename="/abs/x.py"><lines><line number="7" hits="2"/></lines></class>
|
||||
</classes></package></packages></coverage>"#,
|
||||
tmp.path().join("b&c").display()
|
||||
);
|
||||
let suite = parse(&xml, tmp.path()).unwrap().finish("Cobertura");
|
||||
assert!(suite.has_branches);
|
||||
assert_eq!(suite.files.len(), 3);
|
||||
let file = |path: &Path| suite.files.iter().find(|f| f.path.as_ref() as &Path == path).unwrap();
|
||||
// `m.py` exists under the second source; `n.py` falls back to the first.
|
||||
let m = file(&second.join("m.py"));
|
||||
assert_eq!(file(Path::new("/elsewhere/a/n.py")).lines[0].hits, 0);
|
||||
assert_eq!(
|
||||
m.lines.iter().map(|l| (l.line, l.hits, l.branches_total, l.branches_covered)).collect::<Vec<_>>(),
|
||||
[(0, 1, 0, 0), (1, 5, 2, 1), (2, 0, 0, 0)]
|
||||
);
|
||||
assert!(m.lines[1].partial());
|
||||
assert_eq!(file(Path::new("/abs/x.py")).lines[0].line, 6);
|
||||
assert!(parse("<coverage><packages></coverage>", Path::new("/root")).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn filenames_without_sources_resolve_against_the_base() {
|
||||
let xml = r#"<coverage><packages><package><classes><class filename="a/b.py"><lines><line number="1" hits="1"/></lines></class></classes></package></packages></coverage>"#;
|
||||
let suite = parse(xml, Path::new("/root")).unwrap().finish("Cobertura");
|
||||
assert_eq!(suite.files[0].path.as_ref() as &Path, Path::new("/root/a/b.py"));
|
||||
assert!(!suite.has_branches);
|
||||
assert_eq!(conditions("100% (4/4)"), Some((4, 4)));
|
||||
assert_eq!(conditions("100%"), None);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,281 @@
|
||||
//! coverage.py data files (`.coverage`, and `.coverage.*` of parallel runs): SQLite databases of
|
||||
//! executed lines and arcs. Which lines are statements, excluded or branches only comes from
|
||||
//! analysing the source, so coverage.py in the project's interpreter combines the data into a
|
||||
//! scratch file (`[paths]` of the project's configuration applies) and writes Cobertura XML.
|
||||
|
||||
use crate::{CoverageSuite, cobertura};
|
||||
use ide_core::cli_process::{CliTool, Decoding};
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use std::ffi::OsStr;
|
||||
use std::io::Read;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
use std::time::Duration;
|
||||
|
||||
const COVERAGE_PY: CliTool = CliTool::new("coverage.py", Decoding::ToolOutput);
|
||||
/// Analysing a large project's sources takes a while; a `[run] plugins` that hangs must not
|
||||
/// block the import for good.
|
||||
const TIMEOUT: Duration = Duration::from_secs(600);
|
||||
/// Files of the combined data (`relative_files` keeps them relative to the directory it ran in).
|
||||
const MEASURED: &str = "import sys, json, coverage\n\
|
||||
d = coverage.CoverageData(sys.argv[1]); d.read(); print(json.dumps(sorted(d.measured_files())))";
|
||||
/// The files coverage.py reads its configuration from, in the directory it runs in.
|
||||
const CONFIG_FILES: [&str; 4] = [".coveragerc", "setup.cfg", "tox.ini", "pyproject.toml"];
|
||||
|
||||
/// Whether `path` is an SQLite database (coverage.py 5+ data).
|
||||
pub fn is_data_file(path: &Path) -> bool {
|
||||
let mut head = [0u8; 16];
|
||||
std::fs::File::open(path).and_then(|mut f| f.read_exact(&mut head)).is_ok() && &head == b"SQLite format 3\0"
|
||||
}
|
||||
|
||||
/// `path`, or every `.coverage.*` file next to it when it is one of a parallel run's.
|
||||
fn inputs(path: &Path) -> Vec<PathBuf> {
|
||||
let parallel = path.file_name().and_then(|n| n.to_str()).is_some_and(|n| n.starts_with(".coverage."));
|
||||
let mut files: Vec<PathBuf> = match (parallel, path.parent()) {
|
||||
(true, Some(dir)) => std::fs::read_dir(dir)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.flatten()
|
||||
.map(|e| e.path())
|
||||
.filter(|p| {
|
||||
p.file_name().and_then(|n| n.to_str()).is_some_and(|n| n.starts_with(".coverage.")) && is_data_file(p)
|
||||
})
|
||||
.collect(),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
if files.is_empty() {
|
||||
files.push(path.to_path_buf());
|
||||
}
|
||||
files.sort();
|
||||
files
|
||||
}
|
||||
|
||||
/// Where coverage.py ran: the nearest directory of `path` inside `root` with a coverage.py
|
||||
/// configuration file (a monorepo's `backend/pyproject.toml`), else `root`.
|
||||
fn run_dir(path: &Path, root: &Path) -> PathBuf {
|
||||
path.ancestors()
|
||||
.skip(1)
|
||||
.take_while(|d| d.starts_with(root))
|
||||
.find(|d| CONFIG_FILES.iter().any(|f| d.join(f).is_file()))
|
||||
.unwrap_or(root)
|
||||
.to_path_buf()
|
||||
}
|
||||
|
||||
/// Runs `python -W ignore <args>` in `dir` and returns its stdout. Python warnings are
|
||||
/// ignored so `PYTHONWARNINGS=error` can't turn coverage.py's warnings into failures.
|
||||
fn python(python: &Path, dir: &Path, args: &[&OsStr]) -> IdeResult<String> {
|
||||
let mut cmd = Command::new(python);
|
||||
cmd.current_dir(dir).args(["-W", "ignore"]).args(args);
|
||||
let out = COVERAGE_PY.run(cmd, TIMEOUT, None)?;
|
||||
if out.success {
|
||||
return Ok(out.stdout);
|
||||
}
|
||||
let text = if out.stderr.trim().is_empty() { out.stdout } else { out.stderr };
|
||||
let text = text.trim();
|
||||
if text.contains("No module named coverage") {
|
||||
return Err(IdeError::unavailable(format!(
|
||||
"Reading a .coverage data file needs coverage.py in the project's interpreter ({}). Install it, or import the output of `coverage xml`.",
|
||||
python.display()
|
||||
)));
|
||||
}
|
||||
if text.contains("no such option") {
|
||||
return Err(IdeError::unavailable(format!(
|
||||
"Reading a .coverage data file needs coverage.py 6.3 or later in the project's interpreter ({}): {text}",
|
||||
python.display()
|
||||
)));
|
||||
}
|
||||
Err(IdeError::invalid(format!("coverage.py could not read the data: {text}")))
|
||||
}
|
||||
|
||||
/// Reads the data file at `path` with `python`'s coverage.py, run where the project's coverage.py
|
||||
/// configuration is; `out` holds the scratch files. Blocking.
|
||||
pub(crate) fn import(path: &Path, root: &Path, python_path: &Path, out: &Path) -> IdeResult<CoverageSuite> {
|
||||
let dir = run_dir(path, root);
|
||||
let data = out.join(".coverage");
|
||||
let xml = out.join("coverage.xml");
|
||||
let coverage = |args: &[&OsStr]| {
|
||||
let mut all: Vec<&OsStr> = vec!["-m".as_ref(), "coverage".as_ref()];
|
||||
all.extend(args);
|
||||
python(python_path, &dir, &all)
|
||||
};
|
||||
let inputs = inputs(path);
|
||||
let mut args: Vec<&OsStr> = vec!["combine".as_ref(), "--keep".as_ref(), "--data-file".as_ref(), data.as_ref()];
|
||||
args.extend(inputs.iter().map(|p| p.as_os_str()));
|
||||
coverage(&args)?;
|
||||
// `-i`: report what has source here instead of failing on the first file that has none.
|
||||
// `--fail-under=0`: a `[report] fail_under` the data misses must not fail the import.
|
||||
coverage(&[
|
||||
"xml".as_ref(),
|
||||
"-i".as_ref(),
|
||||
"--fail-under=0".as_ref(),
|
||||
"--data-file".as_ref(),
|
||||
data.as_ref(),
|
||||
"-o".as_ref(),
|
||||
xml.as_ref(),
|
||||
])?;
|
||||
let text = std::fs::read_to_string(&xml)?;
|
||||
let mut acc = cobertura::parse(&text, &dir).map_err(|e| IdeError::invalid(format!("{}: {e}", xml.display())))?;
|
||||
// The files the report left out (no source here): listed without lines.
|
||||
let measured = python(python_path, &dir, &["-c".as_ref(), MEASURED.as_ref(), data.as_ref()])?;
|
||||
let measured: Vec<PathBuf> = serde_json::from_str(measured.trim())
|
||||
.map_err(|e| IdeError::invalid(format!("coverage.py listed the measured files unreadably: {e}")))?;
|
||||
for file in measured {
|
||||
acc.file(&dir.join(file));
|
||||
}
|
||||
Ok(acc.finish("coverage.py"))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn finds_the_files_of_a_parallel_run() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let db = |name: &str| {
|
||||
let p = tmp.path().join(name);
|
||||
std::fs::write(&p, b"SQLite format 3\0rest").unwrap();
|
||||
p
|
||||
};
|
||||
let a = db(".coverage.host.1.x");
|
||||
let b = db(".coverage.host.2.y");
|
||||
let single = db(".coverage");
|
||||
std::fs::write(tmp.path().join(".coverage.notes"), "text").unwrap();
|
||||
std::fs::write(tmp.path().join(".coveragerc"), "[run]\n").unwrap();
|
||||
assert!(is_data_file(&a) && !is_data_file(&tmp.path().join(".coveragerc")));
|
||||
assert_eq!(inputs(&a), [a.clone(), b]);
|
||||
assert_eq!(inputs(&single), [single]);
|
||||
}
|
||||
|
||||
/// Two parallel runs recorded on another machine (`…/ci/app`), mapped by the project's `[paths]`.
|
||||
/// Needs coverage.py in `python3`; skipped without it.
|
||||
#[test]
|
||||
fn combines_parallel_data_with_the_projects_paths() {
|
||||
let has_coverage = Command::new("python3").args(["-m", "coverage", "--version"]).output();
|
||||
if !has_coverage.is_ok_and(|o| o.status.success()) {
|
||||
eprintln!("skipped: no coverage.py in python3");
|
||||
return;
|
||||
}
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
// coverage.py reports real paths (`/private/var/…` for macOS's `/var/…`).
|
||||
let base = tmp.path().canonicalize().unwrap();
|
||||
let ci = base.join("ci/app");
|
||||
let root = base.join("project");
|
||||
let calc = "def sign(n):\n if n < 0:\n return -1\n return 1\n";
|
||||
for dir in [&ci, &root] {
|
||||
std::fs::create_dir_all(dir).unwrap();
|
||||
std::fs::write(dir.join("calc.py"), calc).unwrap();
|
||||
}
|
||||
std::fs::write(ci.join("gone.py"), "x = 1\n").unwrap();
|
||||
std::fs::write(ci.join("neg.py"), "import calc, gone\ncalc.sign(-1)\n").unwrap();
|
||||
std::fs::write(ci.join("pos.py"), "import calc\ncalc.sign(1)\n").unwrap();
|
||||
for script in ["neg.py", "pos.py"] {
|
||||
let ok = Command::new("python3")
|
||||
.current_dir(&ci)
|
||||
.args(["-m", "coverage", "run", "--branch", "--parallel-mode", script])
|
||||
.status()
|
||||
.unwrap();
|
||||
assert!(ok.success());
|
||||
}
|
||||
let data = root.join("data");
|
||||
std::fs::create_dir_all(&data).unwrap();
|
||||
for e in std::fs::read_dir(&ci).unwrap().flatten() {
|
||||
if e.file_name().to_string_lossy().starts_with(".coverage.") {
|
||||
std::fs::rename(e.path(), data.join(e.file_name())).unwrap();
|
||||
}
|
||||
}
|
||||
std::fs::remove_dir_all(&ci).unwrap();
|
||||
std::fs::write(root.join(".coveragerc"), "[paths]\nsource =\n ./\n */ci/app/\n").unwrap();
|
||||
let first = std::fs::read_dir(&data).unwrap().flatten().next().unwrap().path();
|
||||
let out = base.join("out");
|
||||
std::fs::create_dir_all(&out).unwrap();
|
||||
let suite = import(&first, &root, Path::new("python3"), &out).unwrap();
|
||||
|
||||
let calc = suite.files.iter().find(|f| f.path.as_ref() as &Path == root.join("calc.py")).unwrap();
|
||||
// Both runs together take both branches of line 2.
|
||||
assert_eq!((calc.lines_total, calc.lines_covered, calc.branches_total, calc.branches_covered), (4, 4, 2, 2));
|
||||
// The scripts and `gone.py` have no source in the project: listed without lines.
|
||||
let empty: Vec<&str> = suite
|
||||
.files
|
||||
.iter()
|
||||
.filter(|f| f.lines.is_empty())
|
||||
.filter_map(|f| (f.path.as_ref() as &Path).file_name()?.to_str())
|
||||
.collect();
|
||||
assert_eq!(empty, ["gone.py", "neg.py", "pos.py"]);
|
||||
// They keep the recorded path, so the import notification counts them as not in the project.
|
||||
assert!(suite.files.iter().filter(|f| f.lines.is_empty()).all(|f| (f.path.as_ref() as &Path).starts_with(&ci)));
|
||||
assert_eq!(std::fs::read_dir(&data).unwrap().count(), 2, "the user's data files are kept");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn runs_where_the_coverage_configuration_is() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
std::fs::create_dir_all(root.join("backend/reports")).unwrap();
|
||||
std::fs::create_dir_all(root.join("data")).unwrap();
|
||||
std::fs::write(root.join("backend/pyproject.toml"), "").unwrap();
|
||||
assert_eq!(run_dir(&root.join("backend/reports/.coverage"), root), root.join("backend"));
|
||||
assert_eq!(run_dir(&root.join("data/.coverage"), root), root);
|
||||
// A data file outside the project runs in the project.
|
||||
assert_eq!(run_dir(Path::new("/elsewhere/.coverage"), root), root);
|
||||
}
|
||||
|
||||
/// A stand-in interpreter that prints `stderr` and exits with `code`.
|
||||
#[cfg(unix)]
|
||||
fn fake_python(dir: &Path, stderr: &str, code: i32) -> PathBuf {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let p = dir.join("python");
|
||||
std::fs::write(&p, format!("#!/bin/sh\necho '{stderr}' >&2\nexit {code}\n")).unwrap();
|
||||
std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
p
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn reports_why_coverage_py_failed() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let data = tmp.path().join(".coverage");
|
||||
let err = |stderr: &str| {
|
||||
let python = fake_python(tmp.path(), stderr, 1);
|
||||
import(&data, tmp.path(), &python, tmp.path()).unwrap_err().to_string()
|
||||
};
|
||||
assert!(err("No module named coverage").contains("needs coverage.py in the project's interpreter"));
|
||||
assert!(err("no such option: --data-file").contains("needs coverage.py 6.3 or later"));
|
||||
assert!(err("No usable data files").contains("coverage.py could not read the data: No usable data files"));
|
||||
}
|
||||
|
||||
/// A monorepo member's data recorded with `relative_files`, below its `fail_under`, with
|
||||
/// coverage.py's warnings turned off. Needs coverage.py in `python3`; skipped without it.
|
||||
#[test]
|
||||
fn reads_a_members_relative_data_below_fail_under() {
|
||||
let has_coverage = Command::new("python3").args(["-m", "coverage", "--version"]).output();
|
||||
if !has_coverage.is_ok_and(|o| o.status.success()) {
|
||||
eprintln!("skipped: no coverage.py in python3");
|
||||
return;
|
||||
}
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path().canonicalize().unwrap();
|
||||
let member = root.join("backend");
|
||||
std::fs::create_dir_all(member.join("app")).unwrap();
|
||||
std::fs::write(
|
||||
member.join("pyproject.toml"),
|
||||
"[tool.coverage.run]\nrelative_files = true\nbranch = true\ndisable_warnings = [\"couldnt-parse\"]\n\
|
||||
[tool.coverage.report]\nfail_under = 90\n",
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::write(member.join("app/x.py"), "def f(n):\n if n:\n return 1\n return 2\n").unwrap();
|
||||
std::fs::write(member.join("t.py"), "from app import x\nx.f(1)\n").unwrap();
|
||||
let ok = Command::new("python3").current_dir(&member).args(["-m", "coverage", "run", "t.py"]).status().unwrap();
|
||||
assert!(ok.success());
|
||||
std::fs::remove_file(member.join("t.py")).unwrap();
|
||||
let out = root.join("out");
|
||||
std::fs::create_dir_all(&out).unwrap();
|
||||
let suite = import(&member.join(".coverage"), &root, Path::new("python3"), &out).unwrap();
|
||||
|
||||
let x = suite.files.iter().find(|f| f.path.as_ref() as &Path == member.join("app/x.py")).unwrap();
|
||||
assert_eq!((x.lines_total, x.lines_covered, x.branches_total, x.branches_covered), (4, 3, 2, 1));
|
||||
// `t.py` has no source any more and its warning is off: still listed, without lines.
|
||||
let t = suite.files.iter().find(|f| f.path.as_ref() as &Path == member.join("t.py")).unwrap();
|
||||
assert!(t.lines.is_empty());
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,10 @@
|
||||
//! "Import a report collected in CI from disk": the format is sniffed from the
|
||||
//! content (lcov, Go cover profile, JaCoCo XML, SimpleCov resultset) and paths recorded on another
|
||||
//! content (lcov, Go cover profile, JaCoCo or Cobertura XML, SimpleCov resultset) and paths recorded on another
|
||||
//! machine are mapped into the project by their longest existing suffix.
|
||||
|
||||
use crate::{Accumulator, CoverageSuite, goprofile, jacoco, lcov, simplecov};
|
||||
use crate::{Accumulator, CoverageSuite, cobertura, goprofile, jacoco, lcov, simplecov};
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
@@ -11,13 +12,19 @@ pub(crate) enum Format {
|
||||
Lcov,
|
||||
GoProfile,
|
||||
Jacoco,
|
||||
Cobertura,
|
||||
SimpleCov,
|
||||
}
|
||||
|
||||
pub(crate) fn detect(text: &str) -> Option<Format> {
|
||||
let head = text.trim_start_matches('\u{feff}').trim_start();
|
||||
if head.starts_with('<') {
|
||||
return head.contains("<report").then_some(Format::Jacoco);
|
||||
// The root element, after any prolog or DOCTYPE naming it.
|
||||
return match (head.find("<report"), head.find("<coverage")) {
|
||||
(Some(r), c) if c.is_none_or(|c| r < c) => Some(Format::Jacoco),
|
||||
(_, Some(_)) => Some(Format::Cobertura),
|
||||
_ => None,
|
||||
};
|
||||
}
|
||||
if head.starts_with('{') {
|
||||
return head.contains("\"coverage\"").then_some(Format::SimpleCov);
|
||||
@@ -39,6 +46,9 @@ pub fn import(path: &Path, root: &Path) -> IdeResult<CoverageSuite> {
|
||||
let (module, module_dir) = go_module_for(root, &text);
|
||||
goprofile::parse(&text, &module, &module_dir).finish("go test -cover")
|
||||
}
|
||||
Some(Format::Cobertura) => cobertura::parse(&text, root)
|
||||
.map_err(|e| IdeError::invalid(format!("{}: {e}", path.display())))?
|
||||
.finish("Cobertura"),
|
||||
Some(Format::Jacoco) => {
|
||||
// A report inside the project (`<module>/target/site/jacoco/…`) knows its module.
|
||||
let module = jacoco::module_dir(path);
|
||||
@@ -53,18 +63,24 @@ pub fn import(path: &Path, root: &Path) -> IdeResult<CoverageSuite> {
|
||||
.map_err(|e| IdeError::invalid(format!("{}: {e}", path.display())))?;
|
||||
acc.finish("JaCoCo")
|
||||
}
|
||||
None if text.starts_with("!coverage.py: This is a private format") => {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"{} is coverage.py 4 data, which current coverage.py can't read. Import the output of `coverage xml` instead.",
|
||||
path.display()
|
||||
)));
|
||||
}
|
||||
None => {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"{} is not an lcov tracefile, Go cover profile, JaCoCo XML report or SimpleCov resultset",
|
||||
"{} is not an lcov tracefile, Go cover profile, JaCoCo or Cobertura XML report or SimpleCov resultset",
|
||||
path.display()
|
||||
)));
|
||||
}
|
||||
};
|
||||
let mut dirs = HashMap::new();
|
||||
for f in &mut suite.files {
|
||||
let p: &Path = f.path.as_ref();
|
||||
if !p.exists()
|
||||
&& let Some(found) = relocate(p, root)
|
||||
{
|
||||
let present = p.parent().is_none_or(|d| dir_exists(d, &mut dirs)) && p.exists();
|
||||
if !present && let Some(found) = relocate(p, root) {
|
||||
f.path = found.into();
|
||||
}
|
||||
}
|
||||
@@ -72,6 +88,24 @@ pub fn import(path: &Path, root: &Path) -> IdeResult<CoverageSuite> {
|
||||
Ok(suite)
|
||||
}
|
||||
|
||||
/// Reads a coverage.py data file (see [`crate::is_data_file`]) with the coverage.py of `python`,
|
||||
/// run in `root`; `out` is an empty scratch directory. Blocking.
|
||||
pub fn import_data(path: &Path, root: &Path, python: &Path, out: &Path) -> IdeResult<CoverageSuite> {
|
||||
crate::coveragepy::import(path, root, python, out)
|
||||
}
|
||||
|
||||
/// Whether `dir` exists, without asking again below a directory known to be missing: every
|
||||
/// lookup under macOS's `/home` (autofs) takes tens of milliseconds, and CI reports
|
||||
/// (`/home/runner/work/…`) name thousands of files there.
|
||||
fn dir_exists(dir: &Path, known: &mut HashMap<PathBuf, bool>) -> bool {
|
||||
if let Some(&e) = known.get(dir) {
|
||||
return e;
|
||||
}
|
||||
let e = dir.parent().is_none_or(|p| dir_exists(p, known)) && dir.is_dir();
|
||||
known.insert(dir.to_path_buf(), e);
|
||||
e
|
||||
}
|
||||
|
||||
/// `/home/runner/work/app/app/src/lib.rs` → `<root>/src/lib.rs`: the longest suffix of
|
||||
/// `path` that exists under `root`.
|
||||
pub(crate) fn relocate(path: &Path, root: &Path) -> Option<PathBuf> {
|
||||
@@ -129,12 +163,30 @@ mod tests {
|
||||
detect("<?xml version=\"1.0\"?><!DOCTYPE report><report name=\"x\"></report>"),
|
||||
Some(Format::Jacoco)
|
||||
);
|
||||
assert_eq!(detect("<?xml version=\"1.0\"?><coverage/>"), None);
|
||||
assert_eq!(detect("<?xml version=\"1.0\"?><coverage/>"), Some(Format::Cobertura));
|
||||
assert_eq!(
|
||||
detect("<?xml version=\"1.0\"?><!DOCTYPE coverage SYSTEM \"x.dtd\"><coverage/>"),
|
||||
Some(Format::Cobertura)
|
||||
);
|
||||
assert_eq!(detect("<?xml version=\"1.0\"?><html/>"), None);
|
||||
assert_eq!(detect("{\"RSpec\": {\"coverage\": {}}}"), Some(Format::SimpleCov));
|
||||
assert_eq!(detect("{\"name\": \"package.json\"}"), None);
|
||||
assert_eq!(detect("hello"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_directories_are_looked_up_once() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mut known = HashMap::new();
|
||||
assert!(dir_exists(tmp.path(), &mut known));
|
||||
let gone = tmp.path().join("gone");
|
||||
assert!(!dir_exists(&gone.join("a/b"), &mut known));
|
||||
std::fs::create_dir_all(gone.join("a/c")).unwrap();
|
||||
// Known to be missing, so its subdirectories are not looked up.
|
||||
assert!(!dir_exists(&gone.join("a/c"), &mut known));
|
||||
assert_eq!(known.get(&gone), Some(&false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn imports_ci_simplecov_with_foreign_paths() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
@@ -168,8 +220,75 @@ mod tests {
|
||||
assert!(import(&tmp.path().join("missing"), &root).is_err());
|
||||
std::fs::write(&report, "nothing").unwrap();
|
||||
assert!(import(&report, &root).is_err());
|
||||
std::fs::write(&report, "!coverage.py: This is a private format, don't read it directly!{\"lines\":{}}")
|
||||
.unwrap();
|
||||
assert!(import(&report, &root).unwrap_err().to_string().contains("coverage.py 4 data"));
|
||||
}
|
||||
|
||||
/// `coverage xml` (coverage.py 7.17, `--branch`) of a project checked out on a CI runner.
|
||||
#[test]
|
||||
fn imports_coverage_py_xml_with_foreign_sources() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path().join("app");
|
||||
std::fs::create_dir_all(root.join("src/calc")).unwrap();
|
||||
std::fs::write(root.join("src/calc/__init__.py"), "").unwrap();
|
||||
let report = tmp.path().join("coverage.xml");
|
||||
std::fs::write(&report, COVERAGE_PY_XML).unwrap();
|
||||
let suite = import(&report, &root).unwrap();
|
||||
assert_eq!(suite.runner, "Cobertura");
|
||||
assert!(suite.has_branches);
|
||||
let calc = suite.files.iter().find(|f| f.path.as_ref() as &Path == root.join("src/calc/__init__.py")).unwrap();
|
||||
assert_eq!((calc.lines_total, calc.lines_covered, calc.branches_total, calc.branches_covered), (8, 5, 4, 2));
|
||||
assert_eq!(calc.lines.iter().filter(|l| l.partial()).map(|l| l.line).collect::<Vec<_>>(), [1, 3]);
|
||||
// The test file is not in this checkout: it keeps the runner's path.
|
||||
assert!(
|
||||
suite.files.iter().any(|f| f.path.as_ref() as &Path == Path::new("/home/runner/work/app/app/test_calc.py"))
|
||||
);
|
||||
}
|
||||
|
||||
const COVERAGE_PY_XML: &str = r#"<?xml version="1.0" ?>
|
||||
<coverage version="7.17.5" timestamp="1795754882920" lines-valid="13" lines-covered="10" line-rate="0.7692" branches-valid="4" branches-covered="2" branch-rate="0.5" complexity="0">
|
||||
<!-- Generated by coverage.py: https://coverage.readthedocs.io/en/7.17.5 -->
|
||||
<!-- Based on https://raw.githubusercontent.com/cobertura/web/master/htdocs/xml/coverage-04.dtd -->
|
||||
<sources>
|
||||
<source>/home/runner/work/app/app</source>
|
||||
</sources>
|
||||
<packages>
|
||||
<package name="." line-rate="1" branch-rate="1" complexity="0">
|
||||
<classes>
|
||||
<class name="test_calc.py" filename="test_calc.py" complexity="0" line-rate="1" branch-rate="1">
|
||||
<methods/>
|
||||
<lines>
|
||||
<line number="1" hits="1"/>
|
||||
<line number="2" hits="1"/>
|
||||
<line number="3" hits="1"/>
|
||||
<line number="6" hits="1"/>
|
||||
<line number="7" hits="1"/>
|
||||
</lines>
|
||||
</class>
|
||||
</classes>
|
||||
</package>
|
||||
<package name="src.calc" line-rate="0.625" branch-rate="0.5" complexity="0">
|
||||
<classes>
|
||||
<class name="__init__.py" filename="src/calc/__init__.py" complexity="0" line-rate="0.625" branch-rate="0.5">
|
||||
<methods/>
|
||||
<lines>
|
||||
<line number="1" hits="1"/>
|
||||
<line number="2" hits="1" branch="true" condition-coverage="50% (1/2)" missing-branches="3"/>
|
||||
<line number="3" hits="0"/>
|
||||
<line number="4" hits="1" branch="true" condition-coverage="50% (1/2)" missing-branches="5"/>
|
||||
<line number="5" hits="0"/>
|
||||
<line number="6" hits="1"/>
|
||||
<line number="13" hits="1"/>
|
||||
<line number="14" hits="0"/>
|
||||
</lines>
|
||||
</class>
|
||||
</classes>
|
||||
</package>
|
||||
</packages>
|
||||
</coverage>
|
||||
"#;
|
||||
|
||||
#[test]
|
||||
fn imports_go_profiles_of_nested_modules() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -16,6 +16,8 @@
|
||||
//!
|
||||
//! Lines in the model are 0-based, like every IPC coordinate.
|
||||
|
||||
mod cobertura;
|
||||
mod coveragepy;
|
||||
mod goprofile;
|
||||
mod import;
|
||||
mod jacoco;
|
||||
@@ -23,7 +25,8 @@ mod lcov;
|
||||
mod plan;
|
||||
mod simplecov;
|
||||
|
||||
pub use import::import;
|
||||
pub use coveragepy::is_data_file;
|
||||
pub use import::{import, import_data};
|
||||
pub use plan::prepare;
|
||||
|
||||
use ide_core::{IdeError, IdeResult, IpcPath};
|
||||
|
||||
@@ -326,7 +326,8 @@ fn python(config: &RunConfig, dir: &Path, out: &Path, py: wrap::PythonCommand) -
|
||||
argv.extend(py.target.iter().cloned());
|
||||
let report = CoverageReportSpec::Exported {
|
||||
runner: s("coverage.py"),
|
||||
argv: with(&["-m", "coverage", "lcov", "-o", &path(&lcov)]),
|
||||
// `--fail-under=0`: a `[report] fail_under` the run misses must not lose its report.
|
||||
argv: with(&["-m", "coverage", "lcov", "--fail-under=0", "-o", &path(&lcov)]),
|
||||
cwd: dir.to_path_buf().into(),
|
||||
env: config.env.clone(),
|
||||
lcov: lcov.into(),
|
||||
|
||||
@@ -859,6 +859,21 @@ async fn connect_with_retries(
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// A user's `languages/python.toml` `[debugger]` is the one debugpy runs with: no other
|
||||
/// language (a template one) declares debugpy before Python.
|
||||
#[test]
|
||||
fn debugpy_comes_from_the_python_language() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let python = include_str!("../../../languages/python.toml").replace(
|
||||
"args = [\"-m\", \"debugpy.adapter\"]",
|
||||
"args = [\"-X\", \"frozen_modules=off\", \"-m\", \"debugpy.adapter\"]",
|
||||
);
|
||||
assert!(python.contains("frozen_modules"));
|
||||
std::fs::write(dir.path().join("python.toml"), python).unwrap();
|
||||
let languages = LanguageRegistry::load(Some(dir.path())).unwrap();
|
||||
assert_eq!(find_config(&languages, "debugpy").unwrap().args[0], "-X");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adapters_run_on_the_tool_search_path() {
|
||||
let search = ide_core::tool_path::search_path();
|
||||
|
||||
@@ -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)]
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
//! Python Debug Server (`attach` with `listen`): the program connects with its own debugpy,
|
||||
//! which may differ from the IDE's adapter. Nothing in the protocol compares them.
|
||||
|
||||
use crate::session::Session;
|
||||
use ide_core::IdeError;
|
||||
use ide_core::event::DebugEvent;
|
||||
use serde_json::{Value, json};
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
pub(crate) fn listens(adapter: &str, request: &str, arguments: &Value) -> bool {
|
||||
adapter == "debugpy" && request == "attach" && arguments.get("listen").is_some()
|
||||
}
|
||||
|
||||
/// debugpy's adapter leaves an `attach` whose port is taken unanswered (it only logs the error),
|
||||
/// which would wait for the program forever: find out before starting it. Listening again right
|
||||
/// after a program ended races the previous adapter, which still listens until its shutdown ends.
|
||||
pub(crate) async fn require_free_port(arguments: &Value) -> Result<(), IdeError> {
|
||||
// ponytail: polls; waiting on the previous session's shutdown would report a taken port sooner.
|
||||
const RELEASE: Duration = Duration::from_secs(5);
|
||||
let listen = &arguments["listen"];
|
||||
let host = listen["host"].as_str().unwrap_or("127.0.0.1");
|
||||
let Some(port) = listen["port"].as_u64().and_then(|p| u16::try_from(p).ok()) else { return Ok(()) };
|
||||
let deadline = tokio::time::Instant::now() + RELEASE;
|
||||
loop {
|
||||
match std::net::TcpListener::bind((host, port)) {
|
||||
Ok(_) => return Ok(()),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::AddrInUse && tokio::time::Instant::now() < deadline => {
|
||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||
}
|
||||
Err(e) => return Err(IdeError::unavailable(format!("Cannot listen on {host}:{port}: {e}"))),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// On the program's first stop: warns in the Debug console when its debugpy is not the adapter's.
|
||||
/// Evaluated in the stopped frame as a hover: without a frame, debugpy before 1.8 runs the
|
||||
/// expression as a statement and prints its value into the program's output.
|
||||
pub(crate) async fn check_version(s: Arc<Session>, thread: i64) {
|
||||
const WAIT: Duration = Duration::from_secs(5);
|
||||
let request = |command: &'static str, arguments: Value| s.conn.request_timeout(command, arguments, WAIT);
|
||||
let Ok(info) = request("debugpySystemInfo", json!({})).await else { return };
|
||||
let Some(ide) = info.pointer("/debugpy/version").and_then(Value::as_str) else { return };
|
||||
let Ok(trace) = request("stackTrace", json!({ "threadId": thread, "levels": 1 })).await else { return };
|
||||
let Some(frame) = trace.pointer("/stackFrames/0/id").and_then(Value::as_i64) else { return };
|
||||
let expression = json!({ "expression": "__import__('debugpy').__version__", "frameId": frame, "context": "hover" });
|
||||
let Ok(reply) = request("evaluate", expression).await else { return };
|
||||
let Some(program) = reply.get("result").and_then(Value::as_str) else { return };
|
||||
if let Some(warning) = version_warning(ide, program) {
|
||||
s.emit(DebugEvent::Output { category: "console".into(), output: warning });
|
||||
}
|
||||
}
|
||||
|
||||
fn version_warning(ide: &str, program: &str) -> Option<String> {
|
||||
let program = program.trim_matches(|c| c == '\'' || c == '"');
|
||||
(program != ide).then(|| {
|
||||
format!(
|
||||
"The program uses debugpy {program}, the IDE's debugger debugpy {ide}. If breakpoints or stepping \
|
||||
misbehave, install the same version where the program runs: pip install debugpy=={ide}\n"
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn warns_only_when_versions_differ() {
|
||||
assert_eq!(version_warning("1.8.22", "'1.8.22'"), None);
|
||||
assert_eq!(version_warning("1.8.22", "1.8.22"), None);
|
||||
let w = version_warning("1.8.22", "'1.8.0'").unwrap();
|
||||
assert!(w.contains("debugpy 1.8.0") && w.ends_with("pip install debugpy==1.8.22\n"), "{w}");
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn a_taken_port_is_reported_before_the_adapter_starts() {
|
||||
let taken = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap();
|
||||
let port = taken.local_addr().unwrap().port();
|
||||
let listen = json!({"listen": {"host": "127.0.0.1", "port": port}});
|
||||
let e = require_free_port(&listen).await.unwrap_err();
|
||||
assert!(e.to_string().contains(&format!("Cannot listen on 127.0.0.1:{port}")), "{e}");
|
||||
drop(taken);
|
||||
assert!(require_free_port(&listen).await.is_ok());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_address_the_machine_lacks_is_reported_at_once() {
|
||||
// 192.0.2.0/24 is reserved for documentation, never a local address.
|
||||
let started = std::time::Instant::now();
|
||||
let e = require_free_port(&json!({"listen": {"host": "192.0.2.1", "port": 5678}})).await.unwrap_err();
|
||||
assert!(e.to_string().contains("Cannot listen on 192.0.2.1:5678"), "{e}");
|
||||
assert!(started.elapsed() < Duration::from_secs(1));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn waits_for_the_previous_adapter_to_release_the_port() {
|
||||
let previous = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap();
|
||||
let port = previous.local_addr().unwrap().port();
|
||||
let released = tokio::spawn(async move {
|
||||
tokio::time::sleep(Duration::from_millis(300)).await;
|
||||
drop(previous);
|
||||
});
|
||||
require_free_port(&json!({"listen": {"host": "127.0.0.1", "port": port}})).await.unwrap();
|
||||
released.await.unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_debugpy_listen_attaches_check() {
|
||||
assert!(listens("debugpy", "attach", &json!({"listen": {"port": 5678}})));
|
||||
assert!(!listens("debugpy", "attach", &json!({"connect": {"port": 5678}})));
|
||||
assert!(!listens("debugpy", "launch", &json!({"listen": {}})));
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,7 @@ pub mod adapter;
|
||||
pub mod attach;
|
||||
mod cargo;
|
||||
pub mod connection;
|
||||
mod debugpy;
|
||||
mod exception_classes;
|
||||
pub mod jdwp;
|
||||
mod js_cdp;
|
||||
@@ -900,7 +901,27 @@ 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?;
|
||||
}
|
||||
// An IDE-side marker (never sent to the adapter): the session is a Flutter
|
||||
// one regardless of what the working directory holds.
|
||||
let force_flutter =
|
||||
@@ -988,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 },
|
||||
@@ -1004,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());
|
||||
@@ -1052,6 +1077,7 @@ impl DebugManager {
|
||||
spec,
|
||||
port,
|
||||
exception_classes,
|
||||
cancel,
|
||||
)
|
||||
.await
|
||||
}
|
||||
@@ -1086,6 +1112,7 @@ impl DebugManager {
|
||||
spec,
|
||||
port,
|
||||
None,
|
||||
ide_core::CancellationToken::new(),
|
||||
)
|
||||
.await
|
||||
.map(|_| ())
|
||||
@@ -1104,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) = {
|
||||
@@ -1129,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();
|
||||
@@ -1139,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(),
|
||||
@@ -1149,14 +1197,28 @@ impl DebugManager {
|
||||
});
|
||||
tokio::spawn(session::event_loop(self.me.clone(), session.clone(), incoming));
|
||||
|
||||
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");
|
||||
|
||||
@@ -75,6 +75,8 @@ pub(crate) struct Session {
|
||||
pub jdwp_port: std::sync::OnceLock<u16>,
|
||||
/// The attach goes through the listen-mode relay of [`crate::jdwp::listen_for_jvm`].
|
||||
pub listen_relay: AtomicBool,
|
||||
/// A Python Debug Server session whose program's debugpy version is checked on its first stop.
|
||||
pub(crate) debugpy_version_unchecked: AtomicBool,
|
||||
pub suspended: Suspension,
|
||||
/// Pids signalled for the current stop: the reported pid and everything it started (an
|
||||
/// adapter may report the launcher shell, whose child is the program).
|
||||
@@ -316,6 +318,7 @@ impl Session {
|
||||
jvm_pid: AtomicI64::new(0),
|
||||
jdwp_port: std::sync::OnceLock::new(),
|
||||
listen_relay: AtomicBool::new(false),
|
||||
debugpy_version_unchecked: AtomicBool::new(false),
|
||||
suspended: Suspension::default(),
|
||||
stop_pids: parking_lot::Mutex::new(Vec::new()),
|
||||
#[cfg(windows)]
|
||||
@@ -854,6 +857,11 @@ async fn on_event(mgr: &Arc<DebugManager>, s: &Arc<Session>, event: &str, mut bo
|
||||
all_threads_stopped: all,
|
||||
});
|
||||
});
|
||||
if let Some(thread) = int("threadId")
|
||||
&& s.debugpy_version_unchecked.swap(false, Ordering::AcqRel)
|
||||
{
|
||||
tokio::spawn(crate::debugpy::check_version(s.clone(), thread));
|
||||
}
|
||||
}
|
||||
"continued" => {
|
||||
let all = body.get("allThreadsContinued").and_then(Value::as_bool);
|
||||
|
||||
@@ -127,7 +127,10 @@ mod tests {
|
||||
fn schema(name: &str, tables: &[&str]) -> CatalogSchema {
|
||||
CatalogSchema {
|
||||
name: name.into(),
|
||||
tables: tables.iter().map(|t| TableInfo { name: (*t).into(), kind: DbTableKind::Table }).collect(),
|
||||
tables: tables
|
||||
.iter()
|
||||
.map(|t| TableInfo { name: (*t).into(), kind: DbTableKind::Table, comment: None })
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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] {
|
||||
|
||||
@@ -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(|_| ()),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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']));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
@@ -457,82 +426,91 @@ impl JdbcPool {
|
||||
self.request(&["page", sql, &offset.to_string(), &limit.min(i32::MAX as u64).to_string()], sql, cancel).await
|
||||
}
|
||||
|
||||
/// Introspection on this connection. `catalogs` lists live catalogs with the current one marked.
|
||||
/// `schemas`, `tables`, `schemaColumns`, and `columns` accept a final catalog argument.
|
||||
pub(crate) async fn metadata(&self, fields: &[&str]) -> IdeResult<Vec<Vec<Option<String>>>> {
|
||||
Ok(self.request(fields, "", &CancellationToken::new()).await?.rows)
|
||||
}
|
||||
|
||||
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")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -655,7 +633,7 @@ impl DbManager {
|
||||
}
|
||||
}
|
||||
|
||||
/// The bridge's `schemaColumns` rows (table, name, type, nullable, default) by table.
|
||||
/// The bridge's `schemaColumns` rows (table, name, type, nullable, default, comment) by table.
|
||||
fn schema_columns(rows: Vec<Vec<Option<String>>>) -> HashMap<String, Vec<crate::CompletionColumn>> {
|
||||
let mut by_table: HashMap<String, Vec<crate::CompletionColumn>> = HashMap::new();
|
||||
for row in rows {
|
||||
@@ -664,12 +642,15 @@ fn schema_columns(rows: Vec<Vec<Option<String>>>) -> HashMap<String, Vec<crate::
|
||||
let data_type = it.next().flatten().unwrap_or_default();
|
||||
let nullable = it.next().flatten().as_deref() != Some("0");
|
||||
let has_default = it.next().flatten().is_some();
|
||||
// Bridges built before the comment column send five fields.
|
||||
let comment = it.next().flatten().filter(|c| !c.trim().is_empty());
|
||||
by_table.entry(table).or_default().push(crate::CompletionColumn {
|
||||
name,
|
||||
data_type,
|
||||
nullable,
|
||||
primary_key: false,
|
||||
has_default,
|
||||
comment,
|
||||
});
|
||||
}
|
||||
by_table
|
||||
@@ -679,85 +660,132 @@ 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>| {
|
||||
vec![Some(t.into()), Some(n.into()), Some("INT".into()), Some(null.into()), def.map(Into::into)]
|
||||
};
|
||||
let by_table = schema_columns(vec![
|
||||
row("orders", "id", "0", None),
|
||||
row("orders", "note", "1", Some("'none'")),
|
||||
row("items", "sku", "1", None),
|
||||
vec![None, Some("orphan".into())],
|
||||
]);
|
||||
let mut commented = row("orders", "note", "1", Some("'none'"));
|
||||
commented.push(Some("free text".into()));
|
||||
let mut blank = row("items", "sku", "1", None);
|
||||
blank.push(Some(" ".into()));
|
||||
let by_table =
|
||||
schema_columns(vec![row("orders", "id", "0", None), commented, blank, vec![None, Some("orphan".into())]]);
|
||||
let orders = &by_table["orders"];
|
||||
assert_eq!(orders.iter().map(|c| c.name.as_str()).collect::<Vec<_>>(), ["id", "note"]);
|
||||
assert_eq!((orders[0].nullable, orders[0].has_default), (false, false));
|
||||
assert_eq!((orders[1].nullable, orders[1].has_default), (true, true));
|
||||
assert_eq!((orders[0].comment.as_deref(), orders[1].comment.as_deref()), (None, Some("free text")));
|
||||
assert_eq!(by_table["items"][0].comment, None);
|
||||
assert_eq!(by_table["items"].len(), 1);
|
||||
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]));
|
||||
#[ignore = "requires DUCKDB_JDBC_JAR and a local Java 17+ runtime"]
|
||||
async fn duckdb_live_catalog_metadata_is_scoped_to_the_requested_namespace() -> IdeResult<()> {
|
||||
let tmp = tempfile::tempdir()?;
|
||||
let source = DataSource { url: "jdbc:duckdb:".into(), ..Default::default() };
|
||||
let driver = DbJdbcDriver {
|
||||
id: "duckdb".into(),
|
||||
name: "DuckDB".into(),
|
||||
vendor: None,
|
||||
jars: vec![std::env::var("DUCKDB_JDBC_JAR").expect("DUCKDB_JDBC_JAR")],
|
||||
class_name: "org.duckdb.DuckDBDriver".into(),
|
||||
url_template: String::new(),
|
||||
};
|
||||
let pool = JdbcPool::connect(&source, None, driver, tmp.path().join("jdbc")).await?;
|
||||
let stop = CancellationToken::new();
|
||||
let path = |file| tmp.path().join(file).to_string_lossy().replace('\'', "''");
|
||||
let archive = "archive.db:1";
|
||||
for sql in [
|
||||
"SET threads = 1".into(),
|
||||
"CREATE TABLE memory.main.dupe (root_only INT)".into(),
|
||||
format!("ATTACH '{}' AS first", path("first.duckdb")),
|
||||
format!(r#"ATTACH '{}' AS "archive.db:1""#, path("archive.duckdb")),
|
||||
"CREATE TABLE first.main.dupe (first_only INT PRIMARY KEY)".into(),
|
||||
r#"CREATE TABLE "archive.db:1".main.dupe (archive_only INT)"#.into(),
|
||||
r#"CREATE SCHEMA "archive.db:1"."qa_%""#.into(),
|
||||
r#"CREATE SCHEMA "archive.db:1".qaSimilar"#.into(),
|
||||
r#"CREATE TABLE "archive.db:1"."qa_%"."t_%""q" (quoted_only INT PRIMARY KEY)"#.into(),
|
||||
r#"COMMENT ON TABLE "archive.db:1"."qa_%"."t_%""q" IS 'Archive table'"#.into(),
|
||||
r#"COMMENT ON COLUMN "archive.db:1"."qa_%"."t_%""q".quoted_only IS 'In the archive'"#.into(),
|
||||
r#"CREATE TABLE "archive.db:1".qaSimilar."t_%""q" (wrong_schema INT)"#.into(),
|
||||
r#"COMMENT ON TABLE "archive.db:1".qaSimilar."t_%""q" IS 'Wrong schema table'"#.into(),
|
||||
r#"COMMENT ON COLUMN "archive.db:1".qaSimilar."t_%""q".wrong_schema IS 'Outside the schema'"#.into(),
|
||||
] {
|
||||
pool.query(&sql, 0, 1, &stop).await?;
|
||||
}
|
||||
}
|
||||
|
||||
#[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 catalogs = pool.metadata(&["catalogs"]).await?;
|
||||
assert!(catalogs.contains(&vec![Some("memory".into()), Some("1".into())]));
|
||||
assert!(catalogs.contains(&vec![Some("first".into()), Some("0".into())]));
|
||||
assert!(catalogs.contains(&vec![Some(archive.into()), Some("0".into())]));
|
||||
let schemas = pool.metadata(&["schemas", archive]).await?;
|
||||
assert_eq!(schemas, ["main", "qaSimilar", "qa_%"].map(|schema| vec![Some(schema.into())]));
|
||||
let tables = pool.metadata(&["tables", "qa_%", archive]).await?;
|
||||
assert_eq!(tables.len(), 1);
|
||||
assert_eq!(tables[0][0].as_deref(), Some(r#"t_%"q"#));
|
||||
assert_eq!(tables[0][2].as_deref(), Some("Archive table"));
|
||||
|
||||
for (catalog, column, primary) in
|
||||
[("memory", "root_only", "0"), ("first", "first_only", "1"), (archive, "archive_only", "0")]
|
||||
{
|
||||
let columns = pool.metadata(&["columns", "main", "dupe", catalog]).await?;
|
||||
assert_eq!(columns.len(), 1);
|
||||
assert_eq!(columns[0][0].as_deref(), Some(column));
|
||||
assert_eq!(columns[0][4].as_deref(), Some(primary));
|
||||
}
|
||||
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);
|
||||
let quoted = pool.metadata(&["columns", "qa_%", r#"t_%"q"#, archive]).await?;
|
||||
assert_eq!(quoted.len(), 1);
|
||||
assert_eq!(quoted[0][0].as_deref(), Some("quoted_only"));
|
||||
assert_eq!(quoted[0][4].as_deref(), Some("1"));
|
||||
let all = schema_columns(pool.metadata(&["schemaColumns", "qa_%", archive]).await?);
|
||||
assert_eq!(all.len(), 1);
|
||||
assert_eq!(all[r#"t_%"q"#][0].name, "quoted_only");
|
||||
assert_eq!(all[r#"t_%"q"#][0].comment.as_deref(), Some("In the archive"));
|
||||
|
||||
pool.query("USE first", 0, 1, &stop).await?;
|
||||
let catalogs = pool.metadata(&["catalogs"]).await?;
|
||||
assert!(catalogs.contains(&vec![Some("first".into()), Some("1".into())]));
|
||||
let legacy = pool.metadata(&["columns", "main", "dupe"]).await?;
|
||||
assert_eq!(legacy[0][0].as_deref(), Some("first_only"));
|
||||
pool.query("USE memory", 0, 1, &stop).await?;
|
||||
pool.query("DETACH first", 0, 1, &stop).await?;
|
||||
let catalogs = pool.metadata(&["catalogs"]).await?;
|
||||
assert!(!catalogs.iter().any(|r| r[0].as_deref() == Some("first")));
|
||||
assert!(pool.metadata(&["schemas", "first"]).await?.is_empty());
|
||||
assert!(pool.metadata(&["tables", "main", "first"]).await?.is_empty());
|
||||
assert!(pool.metadata(&["columns", "main", "dupe", "first"]).await?.is_empty());
|
||||
pool.close().await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
+387
-98
@@ -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};
|
||||
@@ -31,7 +32,7 @@ pub use history::HistoryEntry;
|
||||
pub use plan::{PlanNode, PlanProperty};
|
||||
pub use source::{
|
||||
DataSource, DbColor, DbDriver, DbExternalTunnel, DbIntrospection, DbOptions, DbProperty, DbSchemaSelection,
|
||||
DbSnowflake, DbSnowflakeAuth, DbSsh, DbSshAuth, DbSslMode, DbTxMode, DbVisibilityChange,
|
||||
DbSnowflake, DbSnowflakeAuth, DbSourceFolder, DbSsh, DbSshAuth, DbSslMode, DbTxMode, DbVisibilityChange,
|
||||
};
|
||||
pub use sql::{CellValue, DbRowEdit, SortKey};
|
||||
|
||||
@@ -42,7 +43,7 @@ use parking_lot::Mutex;
|
||||
use secrets::SecretStore;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use std::collections::HashMap;
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
@@ -146,6 +147,10 @@ pub struct SchemaObject {
|
||||
pub struct TableInfo {
|
||||
pub name: String,
|
||||
pub kind: DbTableKind,
|
||||
/// The table's or view's comment; `None` when it has none, or the engine keeps no comments.
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub comment: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
@@ -170,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)]
|
||||
@@ -208,6 +237,10 @@ pub struct CompletionColumn {
|
||||
pub primary_key: bool,
|
||||
/// Has a default (or is generated): optional in INSERT.
|
||||
pub has_default: bool,
|
||||
/// The column's comment; `None` when it has none, or the engine keeps no comments.
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub comment: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
@@ -302,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.
|
||||
@@ -376,6 +435,41 @@ fn tunnel_target(source: &DataSource) -> (&str, u16) {
|
||||
(if source.host.trim().is_empty() { "localhost" } else { source.host.trim() }, port)
|
||||
}
|
||||
|
||||
fn is_duckdb(source: &DataSource) -> bool {
|
||||
const PREFIX: &str = "jdbc:duckdb:";
|
||||
source.driver == DbDriver::Jdbc
|
||||
&& (source.vendor == "duckdb"
|
||||
|| source.url.trim().get(..PREFIX.len()).is_some_and(|url| url.eq_ignore_ascii_case(PREFIX)))
|
||||
}
|
||||
|
||||
async fn duckdb_catalog(pool: &Pool, database: &str) -> IdeResult<Vec<CatalogSchema>> {
|
||||
// List empty schemas too and put all schema names before the bounded table rows.
|
||||
const MAX_CATALOG_ROWS: usize = 20_000;
|
||||
let name = sql::quote_literal(DbDriver::Jdbc, database);
|
||||
let query = format!(
|
||||
"SELECT schema_name AS schema, NULL::VARCHAR AS name, NULL::VARCHAR AS kind, NULL::VARCHAR AS comment \
|
||||
FROM system.main.duckdb_schemas() WHERE database_name = {name} \
|
||||
UNION ALL \
|
||||
SELECT table_schema, table_name, lower(table_type), table_comment \
|
||||
FROM system.information_schema.tables WHERE table_catalog = {name} \
|
||||
ORDER BY name NULLS FIRST, schema LIMIT {MAX_CATALOG_ROWS}"
|
||||
);
|
||||
let mut schemas = BTreeMap::<String, Vec<TableInfo>>::new();
|
||||
for row in pool.rows(&query, MAX_CATALOG_ROWS).await? {
|
||||
let mut values = row.into_iter();
|
||||
let Some(Some(schema)) = values.next() else { continue };
|
||||
let tables = schemas.entry(schema).or_default();
|
||||
if let Some(Some(name)) = values.next() {
|
||||
tables.push(TableInfo {
|
||||
name,
|
||||
kind: DbTableKind::from_catalog(values.next().flatten().as_deref()),
|
||||
comment: values.next().flatten().filter(|comment| !comment.is_empty()),
|
||||
});
|
||||
}
|
||||
}
|
||||
Ok(schemas.into_iter().map(|(name, tables)| CatalogSchema { name, tables }).collect())
|
||||
}
|
||||
|
||||
pub fn split_target(target: &str) -> (&str, Option<&str>) {
|
||||
match target.split_once(':') {
|
||||
Some((id, db)) if !db.is_empty() => (id, Some(db)),
|
||||
@@ -414,12 +508,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 {
|
||||
@@ -568,6 +657,18 @@ impl DbManager {
|
||||
None => {}
|
||||
}
|
||||
source::save(&self.root, &project)?;
|
||||
if let Ok(mut folders) = source::load_folders(&self.root) {
|
||||
let known: std::collections::HashSet<&str> = sources.iter().map(|source| source.id.as_str()).collect();
|
||||
let mut changed = false;
|
||||
for folder in &mut folders {
|
||||
let before = folder.sources.len();
|
||||
folder.sources.retain(|id| known.contains(id.as_str()));
|
||||
changed |= folder.sources.len() != before;
|
||||
}
|
||||
if changed {
|
||||
source::save_folders(&self.root, &folders)?;
|
||||
}
|
||||
}
|
||||
old
|
||||
};
|
||||
for o in old {
|
||||
@@ -958,12 +1059,30 @@ impl DbManager {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The databases of the server of data source `id` (PostgreSQL), the connected one first.
|
||||
/// What databases this data source can see, including DuckDB's live attachments.
|
||||
pub async fn databases(&self, id: &str) -> IdeResult<Databases> {
|
||||
let id = split_target(id).0;
|
||||
let introspection = self.source(id)?.introspection;
|
||||
let source = self.source(id)?;
|
||||
let introspection = &source.introspection;
|
||||
let system = introspection.show_system;
|
||||
let pool = self.pool(id).await?;
|
||||
if let Pool::Jdbc(p) = &*pool
|
||||
&& is_duckdb(&source)
|
||||
{
|
||||
let mut current = String::new();
|
||||
let mut names = Vec::new();
|
||||
for mut row in p.metadata(&["catalogs"]).await? {
|
||||
if let [Some(name), active] = row.as_mut_slice() {
|
||||
if active.as_deref() == Some("1") {
|
||||
current = name.clone();
|
||||
names.insert(0, std::mem::take(name));
|
||||
} else if system || name != "system" {
|
||||
names.push(std::mem::take(name));
|
||||
}
|
||||
}
|
||||
}
|
||||
return Ok(Databases { current, names });
|
||||
}
|
||||
if pool.driver() == DbDriver::SqlServer {
|
||||
let first =
|
||||
|rows: Vec<Vec<Option<String>>>| rows.into_iter().filter_map(|r| r.into_iter().next().flatten());
|
||||
@@ -1002,12 +1121,13 @@ impl DbManager {
|
||||
Ok(Databases { current, names })
|
||||
}
|
||||
|
||||
/// The schemas of `database` of data source `id` with their tables and views (Snowflake):
|
||||
/// what completion needs to follow `database.schema.table` without the tree being opened.
|
||||
/// The result is also saved ([`DbManager::saved_catalog`]) for the next run.
|
||||
/// The schemas of `database` with their tables and views for qualified SQL completion.
|
||||
/// Snowflake's result is also saved ([`DbManager::saved_catalog`]) for the next run.
|
||||
pub async fn database_catalog(&self, id: &str, database: &str) -> IdeResult<Vec<CatalogSchema>> {
|
||||
let id = split_target(id).0;
|
||||
let schemas = match &*self.pool(id).await? {
|
||||
let pool = self.pool(id).await?;
|
||||
let schemas = match &*pool {
|
||||
Pool::Jdbc(_) if is_duckdb(&self.source(id)?) => return duckdb_catalog(&pool, database).await,
|
||||
Pool::Snowflake(p) => snowflake::meta::catalog(p, database).await?,
|
||||
_ => return Err(IdeError::invalid("this data source does not list other databases")),
|
||||
};
|
||||
@@ -1103,19 +1223,54 @@ impl DbManager {
|
||||
.filter_map(|r| {
|
||||
let mut it = r.into_iter();
|
||||
let name = it.next().flatten()?;
|
||||
Some(TableInfo { name, kind: DbTableKind::from_catalog(it.next().flatten().as_deref()) })
|
||||
Some(TableInfo {
|
||||
name,
|
||||
kind: DbTableKind::from_catalog(it.next().flatten().as_deref()),
|
||||
comment: it.next().flatten().filter(|comment| !comment.is_empty()),
|
||||
})
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
async fn duckdb_catalog_pool(&self, id: &str) -> IdeResult<Arc<Pool>> {
|
||||
let source = self.source(id)?;
|
||||
if id != source.id || source.driver != DbDriver::Jdbc || source.vendor != "duckdb" {
|
||||
return Err(IdeError::invalid("Catalog browsing requires a DuckDB data source"));
|
||||
}
|
||||
self.pool(id).await
|
||||
}
|
||||
|
||||
pub async fn catalog_table_details(
|
||||
&self,
|
||||
id: &str,
|
||||
catalog: &str,
|
||||
schema: &str,
|
||||
table: &str,
|
||||
) -> IdeResult<TableDetails> {
|
||||
let pool = self.duckdb_catalog_pool(id).await?;
|
||||
Self::table_details_on(&pool, Some(catalog), schema, table).await
|
||||
}
|
||||
|
||||
pub async fn table_details(&self, id: &str, schema: &str, table: &str) -> IdeResult<TableDetails> {
|
||||
let pool = self.pool(id).await?;
|
||||
if let Pool::Snowflake(p) = &*pool {
|
||||
Self::table_details_on(&pool, None, schema, table).await
|
||||
}
|
||||
|
||||
async fn table_details_on(
|
||||
pool: &Pool,
|
||||
catalog: Option<&str>,
|
||||
schema: &str,
|
||||
table: &str,
|
||||
) -> IdeResult<TableDetails> {
|
||||
if let Pool::Snowflake(p) = pool {
|
||||
return snowflake::meta::table_details(p, schema, table).await;
|
||||
}
|
||||
let driver = pool.driver();
|
||||
let rows = match &*pool {
|
||||
Pool::Jdbc(p) => p.metadata(&["columns", schema, table]).await?,
|
||||
let rows = match pool {
|
||||
Pool::Jdbc(p) => match catalog {
|
||||
Some(catalog) => p.metadata(&["columns", schema, table, catalog]).await?,
|
||||
None => p.metadata(&["columns", schema, table]).await?,
|
||||
},
|
||||
_ => pool.rows(&sql::columns(driver, schema, table), MAX_META_ROWS).await?,
|
||||
};
|
||||
let columns = rows
|
||||
@@ -1149,7 +1304,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) {
|
||||
@@ -1410,10 +1570,13 @@ impl DbManager {
|
||||
}
|
||||
DbDriver::Postgres => {
|
||||
let rel = pool.rows(&sql::postgres_relation(schema, name), 1).await?.into_iter().next();
|
||||
let (oid, kind) = match rel.as_deref() {
|
||||
Some([Some(oid), Some(kind)]) => {
|
||||
(oid.parse::<u32>().map_err(|e| IdeError::invalid(e.to_string()))?, kind.clone())
|
||||
}
|
||||
let (oid, kind, owner, comment) = match rel.as_deref() {
|
||||
Some([Some(oid), Some(kind), owner, comment]) => (
|
||||
oid.parse::<u32>().map_err(|e| IdeError::invalid(e.to_string()))?,
|
||||
kind.clone(),
|
||||
owner.clone(),
|
||||
comment.clone(),
|
||||
),
|
||||
_ => return Err(missing()),
|
||||
};
|
||||
if kind == "v" || kind == "m" {
|
||||
@@ -1434,6 +1597,7 @@ impl DbManager {
|
||||
data_type: it.next().flatten().unwrap_or_default(),
|
||||
not_null: flag(&it.next().flatten()),
|
||||
default: it.next().flatten(),
|
||||
comment: it.next().flatten(),
|
||||
})
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
@@ -1447,7 +1611,18 @@ impl DbManager {
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let indexes = cells(pool.rows(&sql::postgres_ddl_indexes(oid), MAX_META_ROWS).await?, 0);
|
||||
Ok(sql::postgres_table_ddl(schema, name, &columns, &constraints, &indexes))
|
||||
let grants = pool
|
||||
.rows(&sql::postgres_ddl_grants(oid), MAX_META_ROWS)
|
||||
.await?
|
||||
.into_iter()
|
||||
.filter_map(|r| {
|
||||
let mut it = r.into_iter();
|
||||
Some((it.next().flatten()?, it.next().flatten()?, flag(&it.next().flatten())))
|
||||
})
|
||||
.collect();
|
||||
let triggers = cells(pool.rows(&sql::postgres_ddl_triggers(oid), MAX_META_ROWS).await?, 0);
|
||||
let extras = sql::DdlExtras { comment, owner, grants, triggers };
|
||||
Ok(sql::postgres_table_ddl(schema, name, &columns, &constraints, &indexes, &extras))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1495,6 +1670,7 @@ impl DbManager {
|
||||
nullable: flag(&Some(next())),
|
||||
primary_key: flag(&Some(next())),
|
||||
has_default: flag(&Some(next())),
|
||||
comment: Some(next()).filter(|c| !c.trim().is_empty()),
|
||||
};
|
||||
if name.is_empty() || column.name.is_empty() {
|
||||
continue;
|
||||
@@ -1536,13 +1712,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));
|
||||
}
|
||||
}
|
||||
@@ -1563,7 +1752,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),
|
||||
@@ -1585,12 +1789,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) {
|
||||
@@ -1623,9 +1849,35 @@ impl DbManager {
|
||||
cancel: &CancellationToken,
|
||||
schema: Option<&str>,
|
||||
) -> IdeResult<Vec<PlanNode>> {
|
||||
let driver = self.pool(id).await?.driver();
|
||||
if driver == DbDriver::Jdbc {
|
||||
return Err(IdeError::invalid("Custom JDBC execution plans are unsupported"));
|
||||
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 pool = self.pool(id).await?;
|
||||
let driver = pool.driver();
|
||||
if let Pool::Jdbc(jdbc) = &*pool {
|
||||
if self.source(id)?.vendor != "duckdb" || !jdbc.version.starts_with("DuckDB ") {
|
||||
return Err(IdeError::invalid("Custom JDBC execution plans are unsupported"));
|
||||
}
|
||||
let sql = statement.trim().trim_end_matches(';');
|
||||
if sql.contains(';') {
|
||||
// The driver can execute a whole script. Have DuckDB count its statements before prefixing EXPLAIN.
|
||||
let literal = sql::quote_literal(driver, sql);
|
||||
let check = format!("SELECT json_array_length(json_serialize_plan({literal}), '$.plans')");
|
||||
let result = self.run(id, &check, 0, 1, cancel, schema, console).await?;
|
||||
if result.rows.first().and_then(|r| r.first()).and_then(Option::as_deref) != Some("1") {
|
||||
return Err(IdeError::invalid("Choose one statement to explain"));
|
||||
}
|
||||
}
|
||||
let result = self.run(id, &format!("EXPLAIN (FORMAT JSON) {sql}"), 0, 3, cancel, schema, console).await?;
|
||||
return plan::duckdb(&result);
|
||||
}
|
||||
if driver == DbDriver::Oracle {
|
||||
// EXPLAIN PLAN writes PLAN_TABLE; the plan is read (and cleaned up) separately.
|
||||
@@ -1644,18 +1896,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,
|
||||
@@ -1664,8 +1919,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`).
|
||||
@@ -1678,13 +1934,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) {
|
||||
@@ -1692,7 +1966,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,
|
||||
@@ -1728,44 +2002,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
|
||||
@@ -1798,23 +2037,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)]
|
||||
@@ -1829,18 +2082,54 @@ impl DbManager {
|
||||
limit: u64,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<TablePage> {
|
||||
let details = self.table_details(id, schema, table).await?;
|
||||
let pool = self.pool(id).await?;
|
||||
let mut result = if let Pool::Jdbc(p) = &*pool {
|
||||
Self::table_page_on(&pool, None, schema, table, filter, sort, offset, limit, cancel).await
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub async fn catalog_table_page(
|
||||
&self,
|
||||
id: &str,
|
||||
catalog: &str,
|
||||
schema: &str,
|
||||
table: &str,
|
||||
filter: Option<&str>,
|
||||
sort: &[SortKey],
|
||||
offset: u64,
|
||||
limit: u64,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<TablePage> {
|
||||
let pool = self.duckdb_catalog_pool(id).await?;
|
||||
Self::table_page_on(&pool, Some(catalog), schema, table, filter, sort, offset, limit, cancel).await
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
async fn table_page_on(
|
||||
pool: &Pool,
|
||||
catalog: Option<&str>,
|
||||
schema: &str,
|
||||
table: &str,
|
||||
filter: Option<&str>,
|
||||
sort: &[SortKey],
|
||||
offset: u64,
|
||||
limit: u64,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<TablePage> {
|
||||
let details = Self::table_details_on(pool, catalog, schema, table).await?;
|
||||
let mut result = if let Pool::Jdbc(p) = pool {
|
||||
let q = &p.identifier_quote;
|
||||
let names = [schema, table].into_iter().chain(sort.iter().map(|k| k.column.as_str()));
|
||||
let names =
|
||||
catalog.into_iter().chain((catalog.is_some() || !schema.is_empty()).then_some(schema)).chain([table]);
|
||||
if q.is_empty()
|
||||
&& names.into_iter().any(|name| !name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_'))
|
||||
&& names
|
||||
.clone()
|
||||
.chain(sort.iter().map(|k| k.column.as_str()))
|
||||
.any(|name| !name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_'))
|
||||
{
|
||||
return Err(IdeError::invalid("This JDBC driver cannot quote the selected identifier"));
|
||||
}
|
||||
let quote = |s: &str| format!("{q}{}{q}", s.replace(q, &format!("{q}{q}")));
|
||||
let name = if schema.is_empty() { quote(table) } else { format!("{}.{}", quote(schema), quote(table)) };
|
||||
let name = names.map(quote).collect::<Vec<_>>().join(".");
|
||||
let sql = sql::table_select(&name, filter, sort, quote);
|
||||
p.page(&sql, offset, limit, cancel).await?
|
||||
} else {
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -90,6 +90,54 @@ fn prop(name: &str, value: impl Into<String>) -> PlanProperty {
|
||||
PlanProperty { name: name.to_owned(), value: value.into() }
|
||||
}
|
||||
|
||||
fn json_property(name: &str, value: &Value) -> PlanProperty {
|
||||
let as_text = |v: &Value| v.as_str().map_or_else(|| v.to_string(), str::to_owned);
|
||||
let text = match value {
|
||||
Value::Array(items) => items.iter().map(as_text).collect::<Vec<_>>().join(", "),
|
||||
other => as_text(other),
|
||||
};
|
||||
prop(name, text)
|
||||
}
|
||||
|
||||
/// DuckDB's explain_output may request the physical plan, the optimized logical plan, or all three.
|
||||
pub(crate) fn duckdb(result: &QueryResult) -> IdeResult<Vec<PlanNode>> {
|
||||
#[derive(Deserialize)]
|
||||
struct Operator {
|
||||
name: String,
|
||||
#[serde(default)]
|
||||
children: Vec<Operator>,
|
||||
#[serde(default)]
|
||||
extra_info: serde_json::Map<String, Value>,
|
||||
}
|
||||
|
||||
fn append(node: Operator, parent: Option<u32>, out: &mut Vec<PlanNode>) {
|
||||
let index = out.len() as u32;
|
||||
let properties = node.extra_info.iter().map(|(k, v)| json_property(k, v)).collect();
|
||||
let params = ["Table", "Conditions", "Filters", "Projections"]
|
||||
.iter()
|
||||
.find_map(|key| node.extra_info.get(*key).map(|v| json_property(key, v).value))
|
||||
.unwrap_or_default();
|
||||
out.push(PlanNode { parent, operation: node.name.trim().to_owned(), params, properties });
|
||||
for child in node.children {
|
||||
append(child, Some(index), out);
|
||||
}
|
||||
}
|
||||
|
||||
let json = ["physical_plan", "logical_opt", "logical_plan"]
|
||||
.iter()
|
||||
.find_map(|kind| {
|
||||
result.rows.iter().find(|r| r.first().and_then(Option::as_deref) == Some(*kind))?.get(1)?.as_deref()
|
||||
})
|
||||
.ok_or_else(|| IdeError::invalid("DuckDB returned no execution plan"))?;
|
||||
let roots: Vec<Operator> =
|
||||
serde_json::from_str(json).map_err(|e| IdeError::invalid(format!("DuckDB plan: {e}")))?;
|
||||
let mut out = Vec::new();
|
||||
for root in roots {
|
||||
append(root, None, &mut out);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// SQLite rows: `id, parent, notused, detail` (`SCAN o`, `SEARCH c USING INTEGER PRIMARY KEY (rowid=?)`).
|
||||
fn sqlite(rows: &[Vec<Option<String>>]) -> Vec<PlanNode> {
|
||||
let mut ids: Vec<String> = Vec::new();
|
||||
@@ -149,18 +197,7 @@ fn postgres(node: &Value, parent: Option<u32>, out: &mut Vec<PlanNode>) {
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter(|(k, _)| k.as_str() != "Plans")
|
||||
.map(|(k, v)| {
|
||||
let value = match v {
|
||||
Value::String(s) => s.clone(),
|
||||
Value::Array(a) => a
|
||||
.iter()
|
||||
.map(|x| x.as_str().map_or_else(|| x.to_string(), str::to_owned))
|
||||
.collect::<Vec<_>>()
|
||||
.join(", "),
|
||||
other => other.to_string(),
|
||||
};
|
||||
prop(k, value)
|
||||
})
|
||||
.map(|(k, v)| json_property(k, v))
|
||||
.collect();
|
||||
let me = out.len() as u32;
|
||||
out.push(PlanNode { parent, operation, params: params.join(" "), properties });
|
||||
@@ -287,6 +324,25 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duckdb_prefers_the_physical_plan_and_preserves_operator_details() {
|
||||
let physical = r#"[{"name":"PROJECTION","extra_info":{"Projections":["a","b"]},"children":[{"name":"SEQ_SCAN ","extra_info":{"Table":"items"}}]}]"#;
|
||||
let rows = result(
|
||||
&["explain_key", "explain_value"],
|
||||
vec![vec![Some("logical_opt"), Some("[]")], vec![Some("physical_plan"), Some(physical)]],
|
||||
);
|
||||
let nodes = duckdb(&rows).unwrap();
|
||||
assert_eq!(nodes.len(), 2);
|
||||
assert_eq!((nodes[0].parent, nodes[0].params.as_str()), (None, "a, b"));
|
||||
assert_eq!(
|
||||
(nodes[1].parent, nodes[1].operation.as_str(), nodes[1].params.as_str()),
|
||||
(Some(0), "SEQ_SCAN", "items")
|
||||
);
|
||||
assert_eq!(nodes[1].properties, [prop("Table", "items")]);
|
||||
assert!(duckdb(&result(&[], vec![])).is_err());
|
||||
assert!(duckdb(&result(&[], vec![vec![Some("physical_plan"), Some("invalid")]])).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explains_per_dialect() {
|
||||
assert_eq!(explain_statement(DbDriver::Sqlite, "select 1;"), "EXPLAIN QUERY PLAN select 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 {
|
||||
|
||||
@@ -113,7 +113,11 @@ pub(crate) async fn tables(pool: &SnowflakePool, schema: &str) -> IdeResult<Vec<
|
||||
Ok(shown
|
||||
.records()
|
||||
.filter_map(|r| {
|
||||
Some(TableInfo { name: r.get("name")?.to_owned(), kind: table_kind(r.get("kind").unwrap_or("TABLE")) })
|
||||
Some(TableInfo {
|
||||
name: r.get("name")?.to_owned(),
|
||||
kind: table_kind(r.get("kind").unwrap_or("TABLE")),
|
||||
comment: r.get("comment").filter(|comment| !comment.is_empty()).map(str::to_owned),
|
||||
})
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
@@ -238,7 +242,11 @@ pub(crate) async fn catalog(pool: &SnowflakePool, database: &str) -> IdeResult<V
|
||||
let (Some(&index), Some(name)) = (at.get(r.get("schema_name").unwrap_or_default()), r.get("name")) else {
|
||||
continue;
|
||||
};
|
||||
out[index].tables.push(TableInfo { name: name.to_owned(), kind: table_kind(r.get("kind").unwrap_or("TABLE")) });
|
||||
out[index].tables.push(TableInfo {
|
||||
name: name.to_owned(),
|
||||
kind: table_kind(r.get("kind").unwrap_or("TABLE")),
|
||||
comment: r.get("comment").filter(|comment| !comment.is_empty()).map(str::to_owned),
|
||||
});
|
||||
}
|
||||
for schema in &mut out {
|
||||
schema.tables.sort_by(|a, b| a.name.cmp(&b.name));
|
||||
@@ -447,6 +455,7 @@ pub(crate) async fn completion(pool: &SnowflakePool) -> IdeResult<Vec<Completion
|
||||
primary_key: false,
|
||||
has_default: r.get("default").is_some_and(|d| !d.is_empty())
|
||||
|| r.get("autoincrement").is_some_and(|a| !a.is_empty()),
|
||||
comment: r.get("comment").filter(|c| !c.trim().is_empty()).map(str::to_owned),
|
||||
});
|
||||
}
|
||||
Ok(tables)
|
||||
|
||||
@@ -1,15 +1,17 @@
|
||||
//! Data sources: per-project connection settings in `.openidea/data-sources.toml`, and
|
||||
//! global ones (IDEA's Make Global: listed in every project) in `data-sources.toml` of the
|
||||
//! app data directory. Passwords never go there: saved ones live in [`crate::secrets`],
|
||||
//! app data directory. Project folder grouping is in `.openidea/data-source-folders.toml`.
|
||||
//! Passwords never go there: saved ones live in [`crate::secrets`],
|
||||
//! the others only in memory for the session.
|
||||
|
||||
use ide_core::{IdeError, IdeResult, IpcPath, project_dir};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use std::collections::BTreeMap;
|
||||
use std::collections::{BTreeMap, HashSet};
|
||||
use std::path::Path;
|
||||
|
||||
pub(crate) const FILE: &str = "data-sources.toml";
|
||||
pub(crate) const FOLDERS_FILE: &str = "data-source-folders.toml";
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
@@ -697,6 +699,108 @@ fn write(path: &Path, sources: &[DataSource]) -> IdeResult<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A user folder grouping data sources in one project's Database tree.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct DbSourceFolder {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
/// Reserved for nested folders; the first UI version only creates root folders.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub parent: Option<String>,
|
||||
pub order: i32,
|
||||
pub sources: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
struct SourceFoldersFile {
|
||||
#[serde(default = "folders_version")]
|
||||
version: u32,
|
||||
#[serde(default, rename = "folder")]
|
||||
folders: Vec<DbSourceFolder>,
|
||||
}
|
||||
|
||||
fn folders_version() -> u32 {
|
||||
1
|
||||
}
|
||||
|
||||
/// The project's data source folders and their members.
|
||||
pub fn load_folders(root: &Path) -> IdeResult<Vec<DbSourceFolder>> {
|
||||
let path = project_dir::path(root, FOLDERS_FILE);
|
||||
let text = match std::fs::read_to_string(&path) {
|
||||
Ok(text) => text,
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
|
||||
Err(e) => return Err(e.into()),
|
||||
};
|
||||
let file: SourceFoldersFile =
|
||||
toml::from_str(&text).map_err(|e| IdeError::invalid(format!("{}: {e}", path.display())))?;
|
||||
if file.version > 1 {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"{}: folder format version {} is newer than this OpenIDEA",
|
||||
path.display(),
|
||||
file.version
|
||||
)));
|
||||
}
|
||||
Ok(file.folders)
|
||||
}
|
||||
|
||||
/// Replaces the project's data source folders after validating ids, parents and memberships.
|
||||
pub fn save_folders(root: &Path, folders: &[DbSourceFolder]) -> IdeResult<()> {
|
||||
validate_folders(folders)?;
|
||||
let path = project_dir::path(root, FOLDERS_FILE);
|
||||
if let Some(dir) = path.parent() {
|
||||
std::fs::create_dir_all(dir)?;
|
||||
}
|
||||
let file = SourceFoldersFile { version: folders_version(), folders: folders.to_vec() };
|
||||
let text = toml::to_string_pretty(&file).map_err(|e| IdeError::internal(e.to_string()))?;
|
||||
let tmp = path.with_file_name(format!(".{FOLDERS_FILE}.{}.tmp", uuid::Uuid::new_v4()));
|
||||
std::fs::write(&tmp, text)?;
|
||||
if let Err(e) = std::fs::rename(&tmp, &path) {
|
||||
let _ = std::fs::remove_file(&tmp);
|
||||
return Err(e.into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_folders(folders: &[DbSourceFolder]) -> IdeResult<()> {
|
||||
let mut ids = HashSet::new();
|
||||
let mut members = HashSet::new();
|
||||
for folder in folders {
|
||||
if folder.id.trim().is_empty() || folder.name.trim().is_empty() {
|
||||
return Err(IdeError::invalid("every data source folder needs an id and a name"));
|
||||
}
|
||||
if !ids.insert(folder.id.as_str()) {
|
||||
return Err(IdeError::invalid(format!("duplicate data source folder id '{}'", folder.id)));
|
||||
}
|
||||
for source in &folder.sources {
|
||||
if source.is_empty() {
|
||||
return Err(IdeError::invalid(format!("folder '{}' has an empty data source id", folder.name)));
|
||||
}
|
||||
if !members.insert(source.as_str()) {
|
||||
return Err(IdeError::invalid(format!("data source '{source}' belongs to more than one folder")));
|
||||
}
|
||||
}
|
||||
}
|
||||
for folder in folders {
|
||||
let mut seen = HashSet::new();
|
||||
let mut parent = folder.parent.as_deref();
|
||||
while let Some(id) = parent {
|
||||
if id == folder.id || !seen.insert(id) {
|
||||
return Err(IdeError::invalid(format!("data source folder '{}' has a parent cycle", folder.name)));
|
||||
}
|
||||
parent =
|
||||
folders.iter().find(|candidate| candidate.id == id).and_then(|candidate| candidate.parent.as_deref());
|
||||
if parent.is_none() && !folders.iter().any(|candidate| candidate.id == id) {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"data source folder '{}' has an unknown parent '{id}'",
|
||||
folder.name
|
||||
)));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Credential store access. Blocking (may show an OS prompt): call off the async runtime.
|
||||
/// Keys are data source ids; [`secrets::ssh_key`] names the SSH password / passphrase.
|
||||
#[cfg(test)]
|
||||
@@ -724,6 +828,38 @@ mod tests {
|
||||
assert!(save(tmp.path(), &[DataSource::default()]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn source_folders_round_trip_and_reject_invalid_memberships() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let folders = vec![
|
||||
DbSourceFolder {
|
||||
id: "prod".into(),
|
||||
name: "Production".into(),
|
||||
parent: None,
|
||||
order: 0,
|
||||
sources: vec!["pg".into(), "mysql".into()],
|
||||
},
|
||||
DbSourceFolder { id: "empty".into(), name: "Empty".into(), parent: None, order: 1, sources: vec![] },
|
||||
];
|
||||
save_folders(tmp.path(), &folders).unwrap();
|
||||
assert_eq!(load_folders(tmp.path()).unwrap(), folders);
|
||||
|
||||
let duplicate = vec![
|
||||
DbSourceFolder { sources: vec!["pg".into()], ..folders[0].clone() },
|
||||
DbSourceFolder { id: "other".into(), sources: vec!["pg".into()], ..folders[1].clone() },
|
||||
];
|
||||
assert!(save_folders(tmp.path(), &duplicate).is_err());
|
||||
|
||||
let cycle = vec![
|
||||
DbSourceFolder { parent: Some("b".into()), ..folders[0].clone() },
|
||||
DbSourceFolder { id: "b".into(), parent: Some("prod".into()), ..folders[1].clone() },
|
||||
];
|
||||
assert!(save_folders(tmp.path(), &cycle).is_err());
|
||||
|
||||
let missing = vec![DbSourceFolder { parent: Some("missing".into()), ..folders[0].clone() }];
|
||||
assert!(save_folders(tmp.path(), &missing).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_configs_written_before_the_new_settings() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
|
||||
+172
-35
@@ -95,46 +95,52 @@ pub fn schemas(driver: DbDriver, system: bool) -> &'static str {
|
||||
}
|
||||
}
|
||||
|
||||
/// Rows: `name, kind` where kind is `table`, `view` or `materialized view`.
|
||||
/// Rows: `name, kind, comment` where kind is `table`, `view` or `materialized view`.
|
||||
pub fn tables(driver: DbDriver, schema: &str) -> String {
|
||||
match driver {
|
||||
DbDriver::Jdbc => unreachable!("JDBC introspection uses DatabaseMetaData"),
|
||||
DbDriver::Clickhouse => format!(
|
||||
"SELECT name, CASE engine WHEN 'View' THEN 'view' WHEN 'MaterializedView' THEN 'materialized view' \
|
||||
WHEN 'WindowView' THEN 'view' ELSE 'table' END FROM system.tables \
|
||||
WHEN 'WindowView' THEN 'view' ELSE 'table' END, comment FROM system.tables \
|
||||
WHERE database = {} AND is_temporary = 0 ORDER BY name",
|
||||
quote_literal(driver, schema)
|
||||
),
|
||||
DbDriver::Sqlite => format!(
|
||||
"SELECT name, type FROM {}.sqlite_master WHERE type IN ('table', 'view') \
|
||||
"SELECT name, type, NULL FROM {}.sqlite_master WHERE type IN ('table', 'view') \
|
||||
AND name NOT LIKE 'sqlite\\_%' ESCAPE '\\' ORDER BY name",
|
||||
quote_ident(driver, schema)
|
||||
),
|
||||
DbDriver::Snowflake => format!(
|
||||
"SELECT table_name, CASE table_type WHEN 'VIEW' THEN 'view' WHEN 'MATERIALIZED VIEW' THEN 'materialized view' \
|
||||
ELSE 'table' END FROM information_schema.tables WHERE table_schema = {} ORDER BY 1",
|
||||
ELSE 'table' END, comment FROM information_schema.tables WHERE table_schema = {} ORDER BY 1",
|
||||
quote_literal(driver, schema)
|
||||
),
|
||||
DbDriver::Oracle => format!(
|
||||
"SELECT table_name, 'table' FROM all_tables WHERE owner = {} \
|
||||
UNION ALL SELECT view_name, 'view' FROM all_views WHERE owner = {} ORDER BY 1",
|
||||
quote_literal(driver, schema),
|
||||
"SELECT table_name, CASE WHEN table_type = 'VIEW' THEN 'view' ELSE 'table' END, comments \
|
||||
FROM all_tab_comments WHERE owner = {} ORDER BY 1",
|
||||
quote_literal(driver, schema)
|
||||
),
|
||||
DbDriver::Postgres => format!(
|
||||
"SELECT c.relname, CASE c.relkind WHEN 'v' THEN 'view' WHEN 'm' THEN 'materialized view' ELSE 'table' END \
|
||||
"SELECT c.relname, CASE c.relkind WHEN 'v' THEN 'view' WHEN 'm' THEN 'materialized view' ELSE 'table' END, \
|
||||
obj_description(c.oid, 'pg_class') \
|
||||
FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace \
|
||||
WHERE n.nspname = {} AND c.relkind IN ('r', 'v', 'm', 'p', 'f') ORDER BY 1",
|
||||
quote_literal(driver, schema)
|
||||
),
|
||||
DbDriver::Mysql => format!(
|
||||
"SELECT table_name, CASE WHEN table_type LIKE '%VIEW%' THEN 'view' ELSE 'table' END \
|
||||
"SELECT table_name, CASE WHEN table_type LIKE '%VIEW%' THEN 'view' ELSE 'table' END, \
|
||||
CASE WHEN table_type LIKE '%VIEW%' THEN NULL ELSE NULLIF(table_comment, '') END \
|
||||
FROM information_schema.tables WHERE table_schema = {} ORDER BY 1",
|
||||
quote_literal(driver, schema)
|
||||
),
|
||||
DbDriver::SqlServer => format!(
|
||||
"SELECT TABLE_NAME, CASE WHEN TABLE_TYPE LIKE '%VIEW%' THEN 'view' ELSE 'table' END \
|
||||
FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = {} ORDER BY 1",
|
||||
"SELECT t.TABLE_NAME, CASE WHEN t.TABLE_TYPE LIKE '%VIEW%' THEN 'view' ELSE 'table' END, \
|
||||
CAST(ep.value AS nvarchar(max)) \
|
||||
FROM INFORMATION_SCHEMA.TABLES t \
|
||||
LEFT JOIN sys.extended_properties ep \
|
||||
ON ep.major_id = OBJECT_ID(QUOTENAME(t.TABLE_SCHEMA) + '.' + QUOTENAME(t.TABLE_NAME)) \
|
||||
AND ep.minor_id = 0 AND ep.name = 'MS_Description' \
|
||||
WHERE t.TABLE_SCHEMA = {} ORDER BY 1",
|
||||
quote_literal(driver, schema)
|
||||
),
|
||||
}
|
||||
@@ -230,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.
|
||||
@@ -245,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 \
|
||||
@@ -257,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 \
|
||||
@@ -270,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"
|
||||
@@ -301,7 +315,7 @@ pub fn completion_columns(driver: DbDriver, scope: CompletionScope) -> String {
|
||||
"SELECT c.database, c.table, CASE t.engine WHEN 'View' THEN 'view' \
|
||||
WHEN 'MaterializedView' THEN 'materialized view' WHEN 'WindowView' THEN 'view' ELSE 'table' END, \
|
||||
c.name, c.type, CASE WHEN startsWith(c.type, 'Nullable(') \
|
||||
OR startsWith(c.type, 'LowCardinality(Nullable(') THEN 'YES' ELSE 'NO' END, c.is_in_primary_key, 1 \
|
||||
OR startsWith(c.type, 'LowCardinality(Nullable(') THEN 'YES' ELSE 'NO' END, c.is_in_primary_key, 1, c.comment \
|
||||
FROM system.columns c JOIN system.tables t ON t.database = c.database AND t.name = c.table \
|
||||
WHERE lower(c.database) NOT IN ('system', 'information_schema') AND t.is_temporary = 0",
|
||||
"c.database",
|
||||
@@ -312,7 +326,7 @@ pub fn completion_columns(driver: DbDriver, scope: CompletionScope) -> String {
|
||||
CASE WHEN p.pk > 0 THEN 1 ELSE 0 END, \
|
||||
CASE WHEN p.dflt_value IS NOT NULL THEN 1 \
|
||||
WHEN p.pk = 1 AND upper(p.type) = 'INTEGER' \
|
||||
AND (SELECT count(*) FROM pragma_table_info(m.name) k WHERE k.pk > 0) = 1 THEN 1 ELSE 0 END \
|
||||
AND (SELECT count(*) FROM pragma_table_info(m.name) k WHERE k.pk > 0) = 1 THEN 1 ELSE 0 END, NULL \
|
||||
FROM sqlite_master m JOIN pragma_table_info(m.name) p \
|
||||
WHERE m.type IN ('table', 'view') AND m.name NOT LIKE 'sqlite\\_%' ESCAPE '\\'",
|
||||
"'main'",
|
||||
@@ -325,7 +339,7 @@ pub fn completion_columns(driver: DbDriver, scope: CompletionScope) -> String {
|
||||
AND a.attnum = ANY(i.indkey)) THEN 1 ELSE 0 END, \
|
||||
CASE WHEN a.atthasdef OR EXISTS (SELECT 1 FROM pg_depend d WHERE d.refclassid = 'pg_class'::regclass \
|
||||
AND d.refobjid = c.oid AND d.refobjsubid = a.attnum AND d.classid = 'pg_class'::regclass \
|
||||
AND d.deptype = 'i') THEN 1 ELSE 0 END \
|
||||
AND d.deptype = 'i') THEN 1 ELSE 0 END, col_description(c.oid, a.attnum) \
|
||||
FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace JOIN pg_attribute a ON a.attrelid = c.oid \
|
||||
WHERE c.relkind IN ('r', 'v', 'm', 'p', 'f') AND a.attnum > 0 AND NOT a.attisdropped \
|
||||
AND n.nspname NOT IN ('pg_catalog', 'information_schema') \
|
||||
@@ -336,7 +350,7 @@ pub fn completion_columns(driver: DbDriver, scope: CompletionScope) -> String {
|
||||
DbDriver::Mysql => (
|
||||
"SELECT c.table_schema, c.table_name, CASE WHEN t.table_type LIKE '%VIEW%' THEN 'view' ELSE 'table' END, \
|
||||
c.column_name, c.column_type, c.is_nullable, CASE WHEN c.column_key = 'PRI' THEN 1 ELSE 0 END, \
|
||||
CASE WHEN c.column_default IS NOT NULL OR c.extra LIKE '%auto_increment%' THEN 1 ELSE 0 END \
|
||||
CASE WHEN c.column_default IS NOT NULL OR c.extra LIKE '%auto_increment%' THEN 1 ELSE 0 END, c.column_comment \
|
||||
FROM information_schema.columns c JOIN information_schema.tables t \
|
||||
ON t.table_schema = c.table_schema AND t.table_name = c.table_name \
|
||||
WHERE c.table_schema NOT IN ('information_schema', 'mysql', 'performance_schema', 'sys')",
|
||||
@@ -351,7 +365,7 @@ pub fn completion_columns(driver: DbDriver, scope: CompletionScope) -> String {
|
||||
AND k.TABLE_SCHEMA = tc.TABLE_SCHEMA AND k.TABLE_NAME = tc.TABLE_NAME \
|
||||
WHERE tc.CONSTRAINT_TYPE = 'PRIMARY KEY' AND tc.TABLE_SCHEMA = c.TABLE_SCHEMA \
|
||||
AND tc.TABLE_NAME = c.TABLE_NAME AND k.COLUMN_NAME = c.COLUMN_NAME) THEN 1 ELSE 0 END, \
|
||||
CASE WHEN c.COLUMN_DEFAULT IS NOT NULL THEN 1 ELSE 0 END \
|
||||
CASE WHEN c.COLUMN_DEFAULT IS NOT NULL THEN 1 ELSE 0 END, NULL \
|
||||
FROM INFORMATION_SCHEMA.COLUMNS c JOIN INFORMATION_SCHEMA.TABLES t \
|
||||
ON t.TABLE_SCHEMA = c.TABLE_SCHEMA AND t.TABLE_NAME = c.TABLE_NAME \
|
||||
WHERE c.TABLE_SCHEMA NOT IN ('sys', 'INFORMATION_SCHEMA')",
|
||||
@@ -361,7 +375,7 @@ pub fn completion_columns(driver: DbDriver, scope: CompletionScope) -> String {
|
||||
DbDriver::Snowflake => (
|
||||
"SELECT c.table_schema, c.table_name, CASE t.table_type WHEN 'VIEW' THEN 'view' \
|
||||
WHEN 'MATERIALIZED VIEW' THEN 'materialized view' ELSE 'table' END, c.column_name, c.data_type, \
|
||||
c.is_nullable, 0, CASE WHEN c.column_default IS NOT NULL THEN 1 ELSE 0 END \
|
||||
c.is_nullable, 0, CASE WHEN c.column_default IS NOT NULL THEN 1 ELSE 0 END, c.comment \
|
||||
FROM information_schema.columns c JOIN information_schema.tables t \
|
||||
ON t.table_schema = c.table_schema AND t.table_name = c.table_name \
|
||||
WHERE c.table_schema <> 'INFORMATION_SCHEMA'",
|
||||
@@ -372,8 +386,10 @@ pub fn completion_columns(driver: DbDriver, scope: CompletionScope) -> String {
|
||||
"SELECT c.owner, c.table_name, CASE WHEN v.view_name IS NOT NULL THEN 'view' ELSE 'table' END, \
|
||||
c.column_name, c.data_type, DECODE(c.nullable, 'Y', 'YES', 'NO'), \
|
||||
CASE WHEN k.column_name IS NOT NULL THEN 1 ELSE 0 END, \
|
||||
CASE WHEN c.data_default IS NOT NULL THEN 1 ELSE 0 END \
|
||||
CASE WHEN c.data_default IS NOT NULL THEN 1 ELSE 0 END, cc.comments \
|
||||
FROM all_tab_columns c \
|
||||
LEFT JOIN all_col_comments cc ON cc.owner = c.owner AND cc.table_name = c.table_name \
|
||||
AND cc.column_name = c.column_name \
|
||||
LEFT JOIN all_views v ON v.owner = c.owner AND v.view_name = c.table_name \
|
||||
LEFT JOIN (SELECT con.owner, con.table_name, kc.column_name FROM all_constraints con \
|
||||
JOIN all_cons_columns kc ON kc.owner = con.owner AND kc.table_name = con.table_name \
|
||||
@@ -658,21 +674,22 @@ pub fn sqlite_ddl(schema: &str, name: &str) -> String {
|
||||
)
|
||||
}
|
||||
|
||||
/// Rows: `oid, relkind` of a PostgreSQL relation.
|
||||
/// Rows: `oid, relkind, owner, comment` of a PostgreSQL relation.
|
||||
pub fn postgres_relation(schema: &str, name: &str) -> String {
|
||||
format!(
|
||||
"SELECT c.oid::text, c.relkind::text FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace \
|
||||
"SELECT c.oid::text, c.relkind::text, pg_get_userbyid(c.relowner), obj_description(c.oid, 'pg_class') \
|
||||
FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace \
|
||||
WHERE n.nspname = {} AND c.relname = {}",
|
||||
quote_literal(DbDriver::Postgres, schema),
|
||||
quote_literal(DbDriver::Postgres, name)
|
||||
)
|
||||
}
|
||||
|
||||
/// Rows: `name, type, not null (0/1), default` of relation `oid`.
|
||||
/// Rows: `name, type, not null (0/1), default, comment` of relation `oid`.
|
||||
pub fn postgres_ddl_columns(oid: u32) -> String {
|
||||
format!(
|
||||
"SELECT a.attname, format_type(a.atttypid, a.atttypmod), CASE WHEN a.attnotnull THEN 1 ELSE 0 END, \
|
||||
pg_get_expr(d.adbin, d.adrelid) FROM pg_attribute a \
|
||||
pg_get_expr(d.adbin, d.adrelid), col_description(a.attrelid, a.attnum) FROM pg_attribute a \
|
||||
LEFT JOIN pg_attrdef d ON d.adrelid = a.attrelid AND d.adnum = a.attnum \
|
||||
WHERE a.attrelid = {oid} AND a.attnum > 0 AND NOT a.attisdropped ORDER BY a.attnum"
|
||||
)
|
||||
@@ -695,6 +712,27 @@ pub fn postgres_ddl_indexes(oid: u32) -> String {
|
||||
)
|
||||
}
|
||||
|
||||
/// Rows: `grantee` (`PUBLIC` for everyone), privileges (`insert, select`), grantable (0/1) of
|
||||
/// the privileges relation `oid` grants beyond its owner's. A relation whose ACL was never
|
||||
/// changed (`relacl` null) grants none.
|
||||
pub fn postgres_ddl_grants(oid: u32) -> String {
|
||||
format!(
|
||||
"SELECT CASE WHEN a.grantee = 0 THEN 'PUBLIC' ELSE pg_get_userbyid(a.grantee) END, \
|
||||
string_agg(lower(a.privilege_type), ', ' ORDER BY a.privilege_type), \
|
||||
CASE WHEN a.is_grantable THEN 1 ELSE 0 END \
|
||||
FROM pg_class c CROSS JOIN LATERAL aclexplode(c.relacl) a \
|
||||
WHERE c.oid = {oid} AND a.grantee <> c.relowner GROUP BY 1, 3 ORDER BY 1, 3"
|
||||
)
|
||||
}
|
||||
|
||||
/// Rows: `CREATE TRIGGER …` of the user triggers of relation `oid`.
|
||||
pub fn postgres_ddl_triggers(oid: u32) -> String {
|
||||
format!(
|
||||
"SELECT pg_get_triggerdef(oid, true) FROM pg_trigger WHERE tgrelid = {oid} AND NOT tgisinternal \
|
||||
ORDER BY tgname"
|
||||
)
|
||||
}
|
||||
|
||||
/// Rows: `name, timing, events` of the triggers of a table (SQLite: `name, sql`).
|
||||
pub fn triggers(driver: DbDriver, schema: &str, table: &str) -> String {
|
||||
let (s, t) = (quote_literal(driver, schema), quote_literal(driver, table));
|
||||
@@ -934,6 +972,18 @@ pub struct DdlColumn {
|
||||
pub data_type: String,
|
||||
pub not_null: bool,
|
||||
pub default: Option<String>,
|
||||
pub comment: Option<String>,
|
||||
}
|
||||
|
||||
/// What [`postgres_table_ddl`] adds after `create table` so the script rebuilds the table.
|
||||
#[derive(Default)]
|
||||
pub struct DdlExtras {
|
||||
pub comment: Option<String>,
|
||||
pub owner: Option<String>,
|
||||
/// `grantee` (`PUBLIC` for everyone), privileges (`insert, select`), with grant option.
|
||||
pub grants: Vec<(String, String, bool)>,
|
||||
/// `CREATE TRIGGER …` statements.
|
||||
pub triggers: Vec<String>,
|
||||
}
|
||||
|
||||
/// `create table` of a PostgreSQL table from its catalog (the server has no `SHOW CREATE`).
|
||||
@@ -943,6 +993,7 @@ pub fn postgres_table_ddl(
|
||||
columns: &[DdlColumn],
|
||||
constraints: &[(String, String)],
|
||||
indexes: &[String],
|
||||
extras: &DdlExtras,
|
||||
) -> String {
|
||||
let d = DbDriver::Postgres;
|
||||
let mut items: Vec<String> = columns
|
||||
@@ -959,9 +1010,31 @@ pub fn postgres_table_ddl(
|
||||
})
|
||||
.collect();
|
||||
items.extend(constraints.iter().map(|(name, def)| format!(" constraint {} {def}", quote_ident(d, name))));
|
||||
let mut out = format!("create table {}\n(\n{}\n);\n", qualified(d, schema, table), items.join(",\n"));
|
||||
for i in indexes {
|
||||
out.push_str(&format!("\n{i};\n"));
|
||||
let target = qualified(d, schema, table);
|
||||
let mut out = format!("create table {target}\n(\n{}\n);\n", items.join(",\n"));
|
||||
// The order a script runs in: comments, owner and privileges, then indexes and triggers.
|
||||
if let Some(comment) = &extras.comment {
|
||||
out.push_str(&format!("\ncomment on table {target} is {};\n", quote_literal(d, comment)));
|
||||
}
|
||||
for c in columns {
|
||||
if let Some(comment) = &c.comment {
|
||||
let column = format!("{target}.{}", quote_ident(d, &c.name));
|
||||
out.push_str(&format!("\ncomment on column {column} is {};\n", quote_literal(d, comment)));
|
||||
}
|
||||
}
|
||||
if let Some(owner) = &extras.owner {
|
||||
out.push_str(&format!("\nalter table {target}\n owner to {};\n", quote_ident(d, owner)));
|
||||
}
|
||||
if !extras.grants.is_empty() {
|
||||
out.push('\n');
|
||||
}
|
||||
for (grantee, privileges, grantable) in &extras.grants {
|
||||
let to = if grantee == "PUBLIC" { "public".to_owned() } else { quote_ident(d, grantee) };
|
||||
let option = if *grantable { " with grant option" } else { "" };
|
||||
out.push_str(&format!("grant {privileges} on {target} to {to}{option};\n"));
|
||||
}
|
||||
for statement in indexes.iter().chain(&extras.triggers) {
|
||||
out.push_str(&format!("\n{};\n", statement.trim_end().trim_end_matches(';')));
|
||||
}
|
||||
out
|
||||
}
|
||||
@@ -988,6 +1061,24 @@ mod tests {
|
||||
assert!(columns(DbDriver::Mysql, "db", "t").contains("column_comment"));
|
||||
assert!(columns(DbDriver::Oracle, "S", "T").contains("all_col_comments"));
|
||||
assert!(columns(DbDriver::Clickhouse, "db", "t").contains("is_in_primary_key, comment"));
|
||||
assert!(tables(DbDriver::Postgres, "public").contains("obj_description(c.oid, 'pg_class')"));
|
||||
assert!(tables(DbDriver::Mysql, "db").contains("table_comment"));
|
||||
assert!(tables(DbDriver::Oracle, "S").contains("all_tab_comments"));
|
||||
assert!(tables(DbDriver::Clickhouse, "db").contains("END, comment FROM system.tables"));
|
||||
assert!(tables(DbDriver::SqlServer, "dbo").contains("sys.extended_properties"));
|
||||
// Completion (the hover card of a table or column) carries them too, as the ninth field.
|
||||
let completion = |driver| completion_columns(driver, CompletionScope::All);
|
||||
assert!(completion(DbDriver::Postgres).contains("col_description(c.oid, a.attnum)"));
|
||||
assert!(completion(DbDriver::Mysql).contains("ELSE 0 END, c.column_comment"));
|
||||
assert!(
|
||||
completion(DbDriver::Oracle).contains("cc.comments")
|
||||
&& completion(DbDriver::Oracle).contains("all_col_comments")
|
||||
);
|
||||
assert!(completion(DbDriver::Clickhouse).contains("c.is_in_primary_key, 1, c.comment"));
|
||||
assert!(completion(DbDriver::Snowflake).contains("ELSE 0 END, c.comment"));
|
||||
for driver in [DbDriver::Sqlite, DbDriver::SqlServer] {
|
||||
assert!(completion(driver).contains("ELSE 0 END, NULL"), "{driver:?}");
|
||||
}
|
||||
let pg = table_comment(DbDriver::Postgres, "public", "o'rders").unwrap();
|
||||
assert!(pg.contains("obj_description(c.oid, 'pg_class')") && pg.contains("'o''rders'"), "{pg}");
|
||||
assert!(table_comment(DbDriver::Mysql, "db", "t").unwrap().contains("table_comment"));
|
||||
@@ -1015,6 +1106,7 @@ mod tests {
|
||||
assert_eq!(current_schema(driver), Some("SELECT currentDatabase()"));
|
||||
let relations = tables(driver, "event's\\db");
|
||||
assert!(relations.contains("WHEN 'MaterializedView' THEN 'materialized view'"));
|
||||
assert!(relations.contains(r"END, comment FROM system.tables"));
|
||||
assert!(relations.contains(r"WHERE database = 'event''s\\db' AND is_temporary = 0"));
|
||||
let fields = columns(driver, "default", "events");
|
||||
assert!(fields.starts_with("SELECT name, type, CASE WHEN startsWith(type, 'Nullable(')"));
|
||||
@@ -1130,6 +1222,7 @@ mod tests {
|
||||
#[test]
|
||||
fn sqlserver_introspection_queries() {
|
||||
assert!(tables(DbDriver::SqlServer, "dbo").contains("INFORMATION_SCHEMA.TABLES"));
|
||||
assert!(tables(DbDriver::SqlServer, "dbo").contains("sys.extended_properties"));
|
||||
assert!(columns(DbDriver::SqlServer, "dbo", "t").contains("INFORMATION_SCHEMA.COLUMNS"));
|
||||
assert!(indexes(DbDriver::SqlServer, "dbo", "t").contains("sys.indexes"));
|
||||
assert!(foreign_keys(DbDriver::SqlServer).contains("sys.foreign_key_columns"));
|
||||
@@ -1206,8 +1299,10 @@ mod tests {
|
||||
assert_eq!(DbDriver::Oracle.default_port(), Some(1521));
|
||||
assert!(schemas(DbDriver::Oracle, true).contains("all_users"));
|
||||
assert!(schemas(DbDriver::Oracle, false).contains("'MDSYS'"));
|
||||
assert!(tables(DbDriver::Oracle, "hr").contains("all_tables"));
|
||||
assert!(tables(DbDriver::Oracle, "hr").contains("all_views"));
|
||||
let relations = tables(DbDriver::Oracle, "hr");
|
||||
assert!(relations.contains("all_tab_comments"));
|
||||
assert!(relations.contains("table_type = 'VIEW'"));
|
||||
assert!(relations.contains("comments"));
|
||||
let cols = columns(DbDriver::Oracle, "hr", "employees");
|
||||
assert!(cols.contains("all_tab_columns"));
|
||||
assert!(cols.contains("DECODE(c.nullable, 'Y', 'YES', 'NO')"));
|
||||
@@ -1296,12 +1391,13 @@ mod tests {
|
||||
#[test]
|
||||
fn postgres_ddl() {
|
||||
let cols = [
|
||||
DdlColumn { name: "id".into(), data_type: "integer".into(), not_null: true, default: None },
|
||||
DdlColumn { name: "id".into(), data_type: "integer".into(), not_null: true, default: None, comment: None },
|
||||
DdlColumn {
|
||||
name: "name".into(),
|
||||
data_type: "character varying(40)".into(),
|
||||
not_null: false,
|
||||
default: Some("'x'::character varying".into()),
|
||||
comment: None,
|
||||
},
|
||||
];
|
||||
assert_eq!(
|
||||
@@ -1310,12 +1406,53 @@ mod tests {
|
||||
"t",
|
||||
&cols,
|
||||
&[("t_pkey".into(), "PRIMARY KEY (id)".into())],
|
||||
&["CREATE INDEX t_name ON public.t USING btree (name)".into()]
|
||||
&["CREATE INDEX t_name ON public.t USING btree (name)".into()],
|
||||
&DdlExtras::default(),
|
||||
),
|
||||
"create table \"public\".\"t\"\n(\n \"id\" integer not null,\n \"name\" character varying(40) default 'x'::character varying,\n constraint \"t_pkey\" PRIMARY KEY (id)\n);\n\nCREATE INDEX t_name ON public.t USING btree (name);\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn postgres_ddl_rebuilds_comments_owner_grants_and_triggers() {
|
||||
let cols = [
|
||||
DdlColumn { name: "id".into(), data_type: "integer".into(), not_null: true, default: None, comment: None },
|
||||
DdlColumn {
|
||||
name: "note".into(),
|
||||
data_type: "text".into(),
|
||||
not_null: false,
|
||||
default: None,
|
||||
comment: Some("what's this".into()),
|
||||
},
|
||||
];
|
||||
let extras = DdlExtras {
|
||||
comment: Some("Orders".into()),
|
||||
owner: Some("app owner".into()),
|
||||
grants: vec![("PUBLIC".into(), "select".into(), false), ("reader".into(), "insert, select".into(), true)],
|
||||
triggers: vec![
|
||||
"CREATE TRIGGER t_audit AFTER INSERT ON public.t FOR EACH ROW EXECUTE FUNCTION audit()".into(),
|
||||
],
|
||||
};
|
||||
assert_eq!(
|
||||
postgres_table_ddl(
|
||||
"public",
|
||||
"t",
|
||||
&cols,
|
||||
&[],
|
||||
&["CREATE INDEX t_note ON public.t USING btree (note)".into()],
|
||||
&extras
|
||||
),
|
||||
"create table \"public\".\"t\"\n(\n \"id\" integer not null,\n \"note\" text\n);\n\
|
||||
\ncomment on table \"public\".\"t\" is 'Orders';\n\
|
||||
\ncomment on column \"public\".\"t\".\"note\" is 'what''s this';\n\
|
||||
\nalter table \"public\".\"t\"\n owner to \"app owner\";\n\
|
||||
\ngrant select on \"public\".\"t\" to public;\n\
|
||||
grant insert, select on \"public\".\"t\" to \"reader\" with grant option;\n\
|
||||
\nCREATE INDEX t_note ON public.t USING btree (note);\n\
|
||||
\nCREATE TRIGGER t_audit AFTER INSERT ON public.t FOR EACH ROW EXECUTE FUNCTION audit();\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn snowflake_quotes_names_and_reads_its_information_schema() {
|
||||
let driver = DbDriver::Snowflake;
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
//! Data source files edited outside the Database tool window (by hand, by a coding
|
||||
//! agent, by `git checkout`) are picked up while the project is open, as IDEA does
|
||||
//! Data source and data source folder files edited outside the Database tool window
|
||||
//! (by hand, by a coding agent, by `git checkout`) are picked up while the project is open, as IDEA does
|
||||
//! for `dataSources.xml`. The project file tree's watcher is no help here: it never
|
||||
//! reports a modification inside a gitignored `.openidea/`.
|
||||
|
||||
use crate::source::FILE;
|
||||
use crate::source::{FILE, FOLDERS_FILE};
|
||||
use ide_core::{IdeError, IdeResult, project_dir};
|
||||
use notify::{RecommendedWatcher, RecursiveMode, Watcher};
|
||||
use parking_lot::Mutex;
|
||||
@@ -15,8 +15,8 @@ use std::time::Duration;
|
||||
/// the files are read.
|
||||
const SETTLE: Duration = Duration::from_millis(200);
|
||||
|
||||
/// Watches `<root>/.openidea/data-sources.toml` and `<global>/data-sources.toml`;
|
||||
/// stops when dropped.
|
||||
/// Watches `<root>/.openidea/data-sources.toml`, `data-source-folders.toml` and
|
||||
/// `<global>/data-sources.toml`; stops when dropped.
|
||||
pub struct SourcesWatch {
|
||||
_watcher: Arc<Mutex<RecommendedWatcher>>,
|
||||
}
|
||||
@@ -29,7 +29,7 @@ impl SourcesWatch {
|
||||
let (tx, rx) = mpsc::channel::<()>();
|
||||
let relevant = {
|
||||
let config = config.clone();
|
||||
move |p: &Path| p.file_name().is_some_and(|n| n == FILE) || p == config
|
||||
move |p: &Path| p.file_name().is_some_and(|n| n == FILE || n == FOLDERS_FILE) || p == config
|
||||
};
|
||||
let watcher = notify::recommended_watcher(move |res: notify::Result<notify::Event>| {
|
||||
if let Ok(e) = res
|
||||
@@ -131,6 +131,10 @@ mod tests {
|
||||
std::fs::write(project.join(".openidea/data-sources.toml"), "").unwrap();
|
||||
assert!(wait_for(&count, seen + 1), "project file");
|
||||
|
||||
let seen = count.load(Ordering::SeqCst);
|
||||
std::fs::write(project.join(".openidea/data-source-folders.toml"), "").unwrap();
|
||||
assert!(wait_for(&count, seen + 1), "project folders file");
|
||||
|
||||
let seen = count.load(Ordering::SeqCst);
|
||||
std::fs::write(global.join("data-sources.toml"), "").unwrap();
|
||||
assert!(wait_for(&count, seen + 1), "global file");
|
||||
|
||||
@@ -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(())
|
||||
}
|
||||
@@ -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 {
|
||||
@@ -122,9 +122,12 @@ async fn duckdb_custom_driver_through_database_manager() -> IdeResult<()> {
|
||||
let db = manager(tmp.path());
|
||||
let c = CancellationToken::new();
|
||||
db.execute("test", "create table items(id int primary key, label varchar)", 1, &c).await?;
|
||||
db.execute("test", "comment on table items is 'Local items'", 1, &c).await?;
|
||||
db.execute("test", "insert into items values (1, NULL), (2, 'row')", 1, &c).await?;
|
||||
assert!(db.schemas("test").await?.iter().any(|v| v == "main"));
|
||||
assert!(db.tables("test", "main").await?.iter().any(|v| v.name == "items"));
|
||||
let tables = db.tables("test", "main").await?;
|
||||
let items = tables.iter().find(|table| table.name == "items").expect("items");
|
||||
assert_eq!(items.comment.as_deref(), Some("Local items"));
|
||||
let details = db.table_details("test", "main", "items").await?;
|
||||
assert_eq!(details.columns.len(), 2);
|
||||
let result = db.execute("test", "select id, label from items order by id", 1, &c).await?;
|
||||
@@ -154,6 +157,40 @@ async fn duckdb_custom_driver_through_database_manager() -> IdeResult<()> {
|
||||
assert!(!last.has_more);
|
||||
let past = db.table_page("test", "main", "items", None, &sort, 2, 1, &c).await?.result;
|
||||
assert!(past.rows.is_empty() && !past.has_more);
|
||||
let path = tmp.path().join("attachment.duckdb");
|
||||
let path = ide_db::sql::quote_literal(DbDriver::Jdbc, &path.to_string_lossy());
|
||||
let catalog = "archive.db:'1";
|
||||
let quoted = ide_db::sql::quote_ident(DbDriver::Jdbc, catalog);
|
||||
for statement in [
|
||||
format!("ATTACH {path} AS {quoted}"),
|
||||
format!("CREATE SCHEMA {quoted}.empty"),
|
||||
format!("CREATE TABLE {quoted}.main.items(remote_only INTEGER)"),
|
||||
format!("COMMENT ON TABLE {quoted}.main.items IS 'Archived items'"),
|
||||
format!("CREATE VIEW {quoted}.main.remote_view AS SELECT * FROM {quoted}.main.items"),
|
||||
format!("COMMENT ON VIEW {quoted}.main.remote_view IS 'Archived view'"),
|
||||
] {
|
||||
db.execute("test", &statement, 1, &c).await?;
|
||||
}
|
||||
let databases = db.databases("test").await?;
|
||||
assert_eq!(databases.current, "local");
|
||||
assert!(databases.names.iter().any(|name| name == catalog));
|
||||
let schemas = db.database_catalog("test", catalog).await?;
|
||||
assert!(schemas.iter().any(|schema| schema.name == "empty" && schema.tables.is_empty()));
|
||||
let main = schemas.iter().find(|schema| schema.name == "main").expect("main");
|
||||
assert_eq!(
|
||||
main.tables.iter().map(|table| (table.name.as_str(), table.kind, table.comment.as_deref())).collect::<Vec<_>>(),
|
||||
[
|
||||
("items", ide_db::DbTableKind::Table, Some("Archived items")),
|
||||
("remote_view", ide_db::DbTableKind::View, Some("Archived view")),
|
||||
]
|
||||
);
|
||||
assert!(db.saved_catalog("test").await?.is_none());
|
||||
db.execute("test", &format!("USE {quoted}"), 1, &c).await?;
|
||||
assert_eq!(db.databases("test").await?.current, catalog);
|
||||
db.execute("test", "USE local", 1, &c).await?;
|
||||
db.execute("test", &format!("DETACH {quoted}"), 1, &c).await?;
|
||||
assert!(!db.databases("test").await?.names.iter().any(|name| name == catalog));
|
||||
assert!(db.database_catalog("test", catalog).await?.is_empty());
|
||||
db.disconnect("test").await;
|
||||
let reopened = manager(tmp.path());
|
||||
assert_eq!(reopened.execute("test", "select count(*) from items", 1, &c).await?.rows, [vec![Some("2".into())]]);
|
||||
@@ -208,9 +245,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;
|
||||
@@ -246,6 +285,21 @@ async fn duckdb_named_memory_lives_until_disconnect() -> IdeResult<()> {
|
||||
db.save_sources(vec![source.clone()]).await?;
|
||||
db.execute("test", "create table session_items as select 42 as id", 1, &cancel).await?;
|
||||
assert_eq!(db.execute("test", "select id from session_items", 1, &cancel).await?.rows, [vec![Some("42".into())]]);
|
||||
let join = "SELECT a.id FROM session_items a JOIN session_items b ON a.id = b.id";
|
||||
let nodes = db.explain("test", join, &cancel, None).await?;
|
||||
let join_node = nodes.iter().position(|n| n.operation == "HASH_JOIN").expect("physical join");
|
||||
assert_eq!(nodes.iter().filter(|n| n.parent == Some(join_node as u32)).count(), 2);
|
||||
assert!(nodes[join_node].properties.iter().any(|p| p.name == "Conditions" && p.value.contains("id")));
|
||||
let batch = db.explain("test", "SELECT 1; SELECT 2", &cancel, None).await.unwrap_err();
|
||||
assert!(batch.message.contains("one statement"));
|
||||
assert!(!db.explain("test", "SELECT ';' AS delimiter", &cancel, None).await?.is_empty());
|
||||
db.execute("test", "SET explain_output = 'optimized_only'", 1, &cancel).await?;
|
||||
assert!(!db.explain("test", "SELECT id FROM session_items", &cancel, None).await?.is_empty());
|
||||
db.explain("test", "INSERT INTO session_items VALUES (43)", &cancel, None).await?;
|
||||
assert_eq!(
|
||||
db.execute("test", "SELECT count(*) FROM session_items", 1, &cancel).await?.rows,
|
||||
[vec![Some("1".into())]]
|
||||
);
|
||||
db.disconnect("test").await;
|
||||
assert!(!db.tables("test", "main").await?.iter().any(|table| table.name == "session_items"));
|
||||
db.disconnect("test").await;
|
||||
@@ -259,6 +313,161 @@ 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_named_catalog_page_uses_the_source_session_and_exact_names() -> 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".into(),
|
||||
driver: DbDriver::Jdbc,
|
||||
vendor: "duckdb".into(),
|
||||
global: true,
|
||||
jdbc_driver: "duck".into(),
|
||||
url: "jdbc:duckdb:".into(),
|
||||
..Default::default()
|
||||
}])
|
||||
.await?;
|
||||
|
||||
let stop = CancellationToken::new();
|
||||
let file = tmp.path().join("attachment.duckdb");
|
||||
let file = ide_db::sql::quote_literal(DbDriver::Jdbc, &file.to_string_lossy());
|
||||
let catalog = r#"archive.db:with/"quote"#;
|
||||
let schema = "some.schema_%";
|
||||
let table = r#"same."table"#;
|
||||
let quote = |name: &str| ide_db::sql::quote_ident(DbDriver::Jdbc, name);
|
||||
let base_table = format!("memory.{}.{}", quote(schema), quote(table));
|
||||
let attached_table = format!("{}.{}.{}", quote(catalog), quote(schema), quote(table));
|
||||
db.execute_in_console(
|
||||
"test",
|
||||
&format!("ATTACH {file} AS {}", quote(catalog)),
|
||||
0,
|
||||
1,
|
||||
&stop,
|
||||
None,
|
||||
Some(ConsoleId::new("window", "/attach.sql")),
|
||||
)
|
||||
.await?;
|
||||
for statement in [
|
||||
"SET threads = 1".into(),
|
||||
format!("CREATE SCHEMA memory.{}", quote(schema)),
|
||||
format!("CREATE SCHEMA {}.{}", quote(catalog), quote(schema)),
|
||||
format!("CREATE TABLE {base_table} (base_only INTEGER PRIMARY KEY)"),
|
||||
format!("CREATE TABLE {attached_table} (attached_only INTEGER PRIMARY KEY)"),
|
||||
format!("INSERT INTO {base_table} VALUES (3)"),
|
||||
format!("INSERT INTO {attached_table} VALUES (42), (41)"),
|
||||
] {
|
||||
db.execute("test", &statement, 1, &stop).await?;
|
||||
}
|
||||
|
||||
let details = db.catalog_table_details("test", catalog, schema, table).await?;
|
||||
assert_eq!(details.columns.len(), 1);
|
||||
assert_eq!(details.columns[0].name, "attached_only");
|
||||
assert!(details.columns[0].primary_key);
|
||||
let sort = [SortKey { column: "attached_only".into(), descending: true }];
|
||||
let attached = db.catalog_table_page("test", catalog, schema, table, None, &sort, 0, 1, &stop).await?;
|
||||
assert_eq!(attached.result.rows, [vec![Some("42".into())]]);
|
||||
assert!(attached.result.has_more);
|
||||
assert_eq!(db.connected(), ["test"]);
|
||||
|
||||
db.execute("test", &format!("USE {}.{}", quote(catalog), quote(schema)), 1, &stop).await?;
|
||||
let initial = db.catalog_table_page("test", "memory", schema, table, None, &[], 0, 1, &stop).await?;
|
||||
assert_eq!(initial.result.rows, [vec![Some("3".into())]]);
|
||||
assert_eq!(initial.details.columns[0].name, "base_only");
|
||||
assert_eq!(db.databases("test").await?.current, catalog);
|
||||
db.execute("test", "USE memory", 1, &stop).await?;
|
||||
db.execute("test", &format!("DETACH {}", quote(catalog)), 1, &stop).await?;
|
||||
assert!(db.catalog_table_page("test", catalog, schema, table, None, &[], 0, 1, &stop).await.is_err());
|
||||
assert_eq!(db.connected(), ["test"]);
|
||||
db.disconnect("test").await;
|
||||
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 +572,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<()> {
|
||||
|
||||
@@ -57,6 +57,7 @@ async fn assert_metadata_is_text(db: &DbManager) -> IdeResult<()> {
|
||||
assert!(schemas.iter().any(|n| n == s), "{s} missing from {schemas:?}");
|
||||
let tables = db.tables("m", s).await?;
|
||||
assert_eq!(tables.iter().map(|t| t.name.as_str()).collect::<Vec<_>>(), ["用户"], "tables of {s}");
|
||||
assert_eq!(tables[0].comment.as_deref(), Some("用户表"));
|
||||
let d = db.table_details("m", s, "用户").await?;
|
||||
let cols: Vec<_> = d.columns.iter().map(|c| c.name.as_str()).collect();
|
||||
assert_eq!(cols, ["id", "name", "raw"]);
|
||||
|
||||
@@ -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(())
|
||||
}
|
||||
@@ -353,6 +353,9 @@ async fn table_details_routines_and_completion_on_older_catalogs() -> IdeResult<
|
||||
assert_eq!(details.foreign_keys[0].ref_columns, ["region", "id"]);
|
||||
let orders = db.table_details("p", "oi_meta", "orders").await?;
|
||||
assert_eq!(orders.comment.as_deref(), Some("Customer's orders"));
|
||||
let listed = db.tables("p", "oi_meta").await?;
|
||||
let listed_orders = listed.iter().find(|table| table.name == "orders").expect("orders in the table list");
|
||||
assert_eq!(listed_orders.comment.as_deref(), Some("Customer's orders"));
|
||||
let comments: Vec<_> = orders.columns.iter().map(|c| c.comment.as_deref()).collect();
|
||||
assert_eq!(comments, [None, None, Some("Free text")]);
|
||||
assert_eq!(details.comment, None);
|
||||
@@ -390,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<_>>(),
|
||||
@@ -420,7 +425,29 @@ async fn opening_a_table_reads_multi_column_keys_in_order() -> IdeResult<()> {
|
||||
db.execute("p", "CREATE SEQUENCE oi_keys.seq", 10, &c).await?;
|
||||
let objects = db.schema_objects("p", "oi_keys").await?;
|
||||
assert_eq!(objects.sequences.len(), 1);
|
||||
assert!(db.ddl("p", "oi_keys", "refs").await?.contains("FOREIGN KEY"));
|
||||
let plain = db.ddl("p", "oi_keys", "refs").await?;
|
||||
assert!(plain.contains("FOREIGN KEY"), "{plain}");
|
||||
assert!(plain.contains("\n owner to "), "{plain}");
|
||||
assert!(!plain.contains("comment on") && !plain.contains("grant ") && !plain.contains("TRIGGER"), "{plain}");
|
||||
// Comments, privileges and triggers come back too, so the script rebuilds the table.
|
||||
for statement in [
|
||||
"COMMENT ON TABLE oi_keys.refs IS 'Refs'",
|
||||
"COMMENT ON COLUMN oi_keys.refs.x IS 'it''s x'",
|
||||
"GRANT SELECT, INSERT ON oi_keys.refs TO PUBLIC",
|
||||
"CREATE FUNCTION oi_keys.touch() RETURNS trigger LANGUAGE plpgsql AS 'BEGIN RETURN NEW; END'",
|
||||
"CREATE TRIGGER refs_touch BEFORE UPDATE ON oi_keys.refs FOR EACH ROW EXECUTE FUNCTION oi_keys.touch()",
|
||||
] {
|
||||
db.execute("p", statement, 10, &c).await?;
|
||||
}
|
||||
let full = db.ddl("p", "oi_keys", "refs").await?;
|
||||
for part in [
|
||||
"comment on table \"oi_keys\".\"refs\" is 'Refs';",
|
||||
"comment on column \"oi_keys\".\"refs\".\"x\" is 'it''s x';",
|
||||
"grant insert, select on \"oi_keys\".\"refs\" to public;",
|
||||
"CREATE TRIGGER refs_touch BEFORE UPDATE ON oi_keys.refs FOR EACH ROW EXECUTE FUNCTION oi_keys.touch();",
|
||||
] {
|
||||
assert!(full.contains(part), "{part}\n{full}");
|
||||
}
|
||||
db.execute("p", "DROP SCHEMA oi_keys CASCADE", 10, &c).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -27,18 +27,24 @@ const QUICK: Duration = Duration::from_secs(20);
|
||||
/// Stop / restart wait for the container's grace period (10 s by default).
|
||||
const LIFECYCLE: Duration = Duration::from_secs(90);
|
||||
|
||||
/// Locates the docker executable once per process. GUI apps on macOS start with a
|
||||
/// minimal `PATH`, so the usual install locations are probed after the lookup.
|
||||
/// Locates the docker executable. GUI apps on macOS start with a minimal `PATH`, so
|
||||
/// the login/reloaded `PATH` and usual install locations are probed after the lookup.
|
||||
/// Only a found path is cached, so installing Docker while the backend runs is picked up.
|
||||
pub fn docker_executable() -> Option<PathBuf> {
|
||||
static DOCKER: OnceLock<Option<PathBuf>> = OnceLock::new();
|
||||
DOCKER
|
||||
.get_or_init(|| {
|
||||
if let Some(explicit) = std::env::var_os("OPENIDEA_DOCKER").map(PathBuf::from).filter(|p| p.is_file()) {
|
||||
return Some(explicit);
|
||||
}
|
||||
if let Ok(found) = which::which("docker") {
|
||||
return Some(found);
|
||||
}
|
||||
if let Some(explicit) = std::env::var_os("OPENIDEA_DOCKER").map(PathBuf::from).filter(|p| p.is_file()) {
|
||||
return Some(explicit);
|
||||
}
|
||||
static DOCKER: OnceLock<PathBuf> = OnceLock::new();
|
||||
if let Some(cached) = DOCKER.get().filter(|p| p.is_file()) {
|
||||
return Some(cached.clone());
|
||||
}
|
||||
let found = which::which("docker")
|
||||
.ok()
|
||||
.or_else(|| {
|
||||
let path = ide_core::process::host_var_os("PATH")?;
|
||||
which::which_in("docker", Some(path), ".").ok()
|
||||
})
|
||||
.or_else(|| {
|
||||
let home = std::env::var_os(if cfg!(windows) { "USERPROFILE" } else { "HOME" }).map(PathBuf::from);
|
||||
let mut candidates: Vec<PathBuf> = if cfg!(windows) {
|
||||
vec![PathBuf::from(r"C:\Program Files\Docker\Docker\resources\bin\docker.exe")]
|
||||
@@ -60,8 +66,11 @@ pub fn docker_executable() -> Option<PathBuf> {
|
||||
candidates.push(home.join(".docker/bin/docker"));
|
||||
}
|
||||
candidates.into_iter().find(|p| p.is_file())
|
||||
})
|
||||
.clone()
|
||||
});
|
||||
if let Some(ref path) = found {
|
||||
let _ = DOCKER.set(path.clone());
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
/// Environment for docker command lines a run configuration launches: the endpoint's
|
||||
|
||||
@@ -76,6 +76,7 @@ tracing.workspace = true
|
||||
url = "2"
|
||||
tracing-subscriber.workspace = true
|
||||
parking_lot.workspace = true
|
||||
notify.workspace = true
|
||||
dunce.workspace = true
|
||||
dirs.workspace = true
|
||||
uuid.workspace = true
|
||||
|
||||
@@ -420,12 +420,11 @@ pub(crate) fn run_command(
|
||||
}
|
||||
// A process it started in the background may keep the pipes open: the command is done.
|
||||
if let Some(status) = child.try_wait().map_err(|e| e.to_string())? {
|
||||
// Read what it wrote until the pipes close, for at most a second: a busy machine may
|
||||
// deliver its last lines (often the error) well after the exit.
|
||||
let deadline = Instant::now() + Duration::from_secs(1);
|
||||
while let Ok(line) = rx.recv_timeout(Duration::from_millis(100)) {
|
||||
while let Ok(line) = rx.recv_timeout(deadline.saturating_duration_since(Instant::now())) {
|
||||
on_line(line);
|
||||
if Instant::now() > deadline {
|
||||
break;
|
||||
}
|
||||
}
|
||||
break status;
|
||||
}
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
use ide_build::kotlin_bridge::{self, Outcome, ProjectLibraries};
|
||||
use ide_core::event::NotifyLevel;
|
||||
use ide_core::{CancellationToken, Diagnostic, IdeEvent, Pos, Range, Severity, SharedSink};
|
||||
use ide_core::{CancellationToken, Diagnostic, IdeEvent, Pos, Range, Severity, SharedSink, TaskId};
|
||||
use ide_lsp::LspManager;
|
||||
use ide_workspace::SettingsStore;
|
||||
use ide_workspace::documents::DocumentObserver;
|
||||
@@ -223,9 +223,15 @@ impl KotlinBridge {
|
||||
let staging = directory.clone();
|
||||
let root = self.root.clone();
|
||||
let token = cancel.clone();
|
||||
let result =
|
||||
tokio::task::spawn_blocking(move || kotlin_bridge::build(&root, &model, &bundle, &staging, &token))
|
||||
.await;
|
||||
// The build runs Maven over the Kotlin modules, which can take a minute: it shows in
|
||||
// the status bar and can be stopped there (the next saved change builds again).
|
||||
let task = BuildTask::start(self.sink.clone(), &cancel);
|
||||
let progress = task.reporter();
|
||||
let result = tokio::task::spawn_blocking(move || {
|
||||
kotlin_bridge::build(&root, &model, &bundle, &staging, &token, &progress)
|
||||
})
|
||||
.await;
|
||||
drop(task);
|
||||
if !self.revision.lock().current(generation) || self.lifetime.is_cancelled() {
|
||||
remove_directory(directory).await;
|
||||
continue;
|
||||
@@ -306,6 +312,58 @@ impl KotlinBridge {
|
||||
}
|
||||
}
|
||||
|
||||
/// The status bar's background task for one bridge build; ends when dropped.
|
||||
struct BuildTask {
|
||||
id: TaskId,
|
||||
sink: SharedSink,
|
||||
_cancel: ide_core::task::CancelHandle,
|
||||
}
|
||||
|
||||
impl BuildTask {
|
||||
const TITLE: &str = "Compiling Kotlin for Java";
|
||||
|
||||
fn start(sink: SharedSink, cancel: &CancellationToken) -> Self {
|
||||
let id = TaskId::next();
|
||||
let cancel = cancel.clone();
|
||||
let handle = ide_core::task::on_cancel(id, move || cancel.cancel());
|
||||
let task = Self { id, sink, _cancel: handle };
|
||||
task.emit(None, None, false);
|
||||
task
|
||||
}
|
||||
|
||||
fn emit(&self, message: Option<String>, fraction: Option<f32>, done: bool) {
|
||||
self.sink.emit(IdeEvent::Task {
|
||||
id: self.id,
|
||||
title: Self::TITLE.into(),
|
||||
message,
|
||||
fraction,
|
||||
done,
|
||||
cancellable: !done,
|
||||
});
|
||||
}
|
||||
|
||||
/// Forwards Maven's progress to the task.
|
||||
fn reporter(&self) -> impl Fn(&str, Option<f32>) + Send + Sync + 'static {
|
||||
let (id, sink) = (self.id, self.sink.clone());
|
||||
move |message: &str, fraction| {
|
||||
sink.emit(IdeEvent::Task {
|
||||
id,
|
||||
title: Self::TITLE.into(),
|
||||
message: Some(message.to_owned()),
|
||||
fraction,
|
||||
done: false,
|
||||
cancellable: true,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for BuildTask {
|
||||
fn drop(&mut self) {
|
||||
self.emit(None, None, true);
|
||||
}
|
||||
}
|
||||
|
||||
/// The error text of a failed bridge build, and whether to notify about it. Compiler errors
|
||||
/// in the user's own Kotlin already show in its editor and stay in Problems; only a build
|
||||
/// that failed without one (Maven itself, a missing plugin) is worth a notification.
|
||||
@@ -369,6 +427,41 @@ impl DocumentObserver for KotlinBridge {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_build_shows_as_a_cancellable_background_task() {
|
||||
let events = Arc::new(Mutex::new(Vec::new()));
|
||||
let sink: SharedSink = Arc::new({
|
||||
let events = events.clone();
|
||||
move |e: IdeEvent| events.lock().push(e)
|
||||
});
|
||||
let cancel = CancellationToken::new();
|
||||
let task = BuildTask::start(sink, &cancel);
|
||||
let progress = task.reporter();
|
||||
progress("Building app 1.0 [2/3]", Some(0.5));
|
||||
assert!(ide_core::task::cancel(task.id), "the status bar can stop it");
|
||||
assert!(cancel.is_cancelled());
|
||||
drop(task);
|
||||
let seen: Vec<_> = events
|
||||
.lock()
|
||||
.iter()
|
||||
.map(|e| match e {
|
||||
IdeEvent::Task { title, message, fraction, done, cancellable, .. } => {
|
||||
assert_eq!(title, "Compiling Kotlin for Java");
|
||||
(message.clone(), *fraction, *done, *cancellable)
|
||||
}
|
||||
other => panic!("{other:?}"),
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(
|
||||
seen,
|
||||
[
|
||||
(None, None, false, true),
|
||||
(Some("Building app 1.0 [2/3]".into()), Some(0.5), false, true),
|
||||
(None, None, true, false),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn target_package_directory_does_not_trigger() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -125,6 +125,7 @@ pub struct Host {
|
||||
pub(crate) rebase_editors: Arc<ops::vcs::RebaseEditors>,
|
||||
/// The IDE's Java build: resident javac processes shared by every window's launches.
|
||||
pub(crate) java_build: Arc<ide_build::jbuild::JavaBuildService>,
|
||||
pub(crate) metrics_sampler: Mutex<ops::host_metrics::HostMetricsSampler>,
|
||||
/// SSH connections of Settings › SSH Configurations.
|
||||
pub ssh: Arc<ide_ssh::SshManager>,
|
||||
/// SFTP deployment, remote file editing and runs on run targets.
|
||||
@@ -255,6 +256,7 @@ impl Host {
|
||||
heap_requests: Default::default(),
|
||||
rebase_editors: Default::default(),
|
||||
java_build: Default::default(),
|
||||
metrics_sampler: Default::default(),
|
||||
languages,
|
||||
syntax,
|
||||
config_dir,
|
||||
@@ -391,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);
|
||||
@@ -648,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();
|
||||
@@ -786,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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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).
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -38,6 +38,11 @@ impl Requests {
|
||||
let _ = pending.answer.send(error.map_or(Ok(allow), Err));
|
||||
Ok(())
|
||||
}
|
||||
/// Whether `window` answers requests (a project loaded for MCP alone has no window).
|
||||
pub(super) fn window_ready(&self, window: &str) -> bool {
|
||||
self.0.lock().ready.contains(window)
|
||||
}
|
||||
|
||||
pub(super) async fn ask(&self, call: &Call, request: McpUiRequest) -> IdeResult<()> {
|
||||
let id = super::tool::request_id().0;
|
||||
let (tx, rx) = oneshot::channel();
|
||||
|
||||
@@ -15,8 +15,9 @@ use ide_core::{IdeError, IdeResult, RunId, Severity};
|
||||
use ide_run::{OutputChunk, RunConfig};
|
||||
use parking_lot::Mutex;
|
||||
use serde_json::{Map, Value, json};
|
||||
use std::collections::HashSet;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::path::Path;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::sync::{Arc, LazyLock};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
@@ -286,6 +287,79 @@ workingDirectory, envs).",
|
||||
/// not the user's own runs.
|
||||
static STARTED: LazyLock<Mutex<HashSet<RunId>>> = LazyLock::new(Default::default);
|
||||
|
||||
/// Run configuration parameter naming the `execute_run_configuration` call a start belongs to.
|
||||
pub const CONFIG_RUN_PARAM: &str = "mcp.configRun";
|
||||
|
||||
/// The `execute_run_configuration` calls waiting for the Run tool window to start their run.
|
||||
struct ConfigLaunch {
|
||||
output: Arc<Mutex<OutputCollector>>,
|
||||
started: Option<Result<ide_run::RunInfo, String>>,
|
||||
}
|
||||
static LAUNCHES: LazyLock<Mutex<HashMap<u64, ConfigLaunch>>> = LazyLock::new(Default::default);
|
||||
static NEXT_LAUNCH: AtomicU64 = AtomicU64::new(1);
|
||||
|
||||
/// The Run tool window's start of an `execute_run_configuration` run: its output also goes to
|
||||
/// the call's output file, and the call learns the run it started.
|
||||
pub(crate) struct ConfigRunLaunch {
|
||||
token: u64,
|
||||
output: Arc<Mutex<OutputCollector>>,
|
||||
}
|
||||
|
||||
/// The call `config` was started for (its first start only; a rerun from the tab is the user's).
|
||||
pub(crate) fn config_run_launch(config: &RunConfig) -> Option<ConfigRunLaunch> {
|
||||
let token = config.extras.params.get(CONFIG_RUN_PARAM)?.parse().ok()?;
|
||||
let launches = LAUNCHES.lock();
|
||||
let launch = launches.get(&token).filter(|l| l.started.is_none())?;
|
||||
Some(ConfigRunLaunch { token, output: launch.output.clone() })
|
||||
}
|
||||
|
||||
impl ConfigRunLaunch {
|
||||
pub(crate) fn wrap_output(&self, on_output: crate::ops::Emit<OutputChunk>) -> crate::ops::Emit<OutputChunk> {
|
||||
let output = self.output.clone();
|
||||
Arc::new(move |chunk: OutputChunk| {
|
||||
// As JetBrains skips `ProcessOutputType.SYSTEM` (`Process finished…`).
|
||||
if let OutputChunk::Stdout { text } | OutputChunk::Stderr { text } = &chunk {
|
||||
output.lock().append(text);
|
||||
}
|
||||
on_output(chunk);
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn started(&self, result: &IdeResult<ide_run::RunInfo>) {
|
||||
if let Some(launch) = LAUNCHES.lock().get_mut(&self.token) {
|
||||
launch.started = Some(result.clone().map_err(|e| e.message));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Starts `config` in the Run tool window, as the user's Run would: a tab with its console and
|
||||
/// Stop. Its before launch tasks already ran.
|
||||
async fn start_in_run_window(
|
||||
call: &Call,
|
||||
mut config: RunConfig,
|
||||
output: Arc<Mutex<OutputCollector>>,
|
||||
) -> IdeResult<ide_run::RunInfo> {
|
||||
struct Forget(u64);
|
||||
impl Drop for Forget {
|
||||
fn drop(&mut self) {
|
||||
LAUNCHES.lock().remove(&self.0);
|
||||
}
|
||||
}
|
||||
let token = NEXT_LAUNCH.fetch_add(1, Ordering::Relaxed);
|
||||
LAUNCHES.lock().insert(token, ConfigLaunch { output, started: None });
|
||||
let _forget = Forget(token);
|
||||
config.extras.params.insert(CONFIG_RUN_PARAM.into(), token.to_string());
|
||||
let config = serde_json::to_value(&config).map_err(|e| IdeError::invalid(e.to_string()))?;
|
||||
let asked = call.ask(ide_core::event::McpUiRequest::RunConfiguration { config }).await;
|
||||
let started = LAUNCHES.lock().get_mut(&token).and_then(|l| l.started.take());
|
||||
match (asked, started) {
|
||||
(_, Some(Ok(info))) => Ok(info),
|
||||
(_, Some(Err(message))) => Err(IdeError::invalid(message)),
|
||||
(Err(e), None) => Err(e),
|
||||
(Ok(()), None) => Err(IdeError::invalid("the run did not start")),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn started_by_mcp(id: RunId) -> bool {
|
||||
STARTED.lock().contains(&id)
|
||||
}
|
||||
@@ -753,9 +827,9 @@ Behavior:
|
||||
|
||||
Returns the execution result including current output snapshot, optional exit code, and optional `fullOutputPath`.
|
||||
In OpenIDEA the user is asked first for every call; `programArguments` replace the configuration's \
|
||||
arguments (appended to a command that is one shell line, such as `npm run dev`); the run does not appear in the Run \
|
||||
tool window: while it is still running, the result carries `runId`, which `stop_run` stops; output files are private \
|
||||
and deleted after a day.",
|
||||
arguments (appended to a command that is one shell line, such as `npm run dev`); the run appears in the Run tool \
|
||||
window like a run the user started, with its console and Stop; while it is still running, the result carries `runId`, \
|
||||
which `stop_run` stops; output files are private and deleted after a day.",
|
||||
|call| async move {
|
||||
let target = execution_target(
|
||||
call.opt_str("configurationName")?,
|
||||
@@ -811,9 +885,15 @@ one by one",
|
||||
};
|
||||
let collector = Arc::new(Mutex::new(OutputCollector::create(&config.name)?));
|
||||
let output_path = collector.lock().path.clone();
|
||||
let sink = collector.clone();
|
||||
let emit = process_output(move |text| sink.lock().append(text));
|
||||
let info = match crate::ops::run::run_start(&call.host(), call.window(), config, emit, None).await {
|
||||
let started = if call.has_window() {
|
||||
start_in_run_window(&call, config, collector.clone()).await
|
||||
} else {
|
||||
// A project loaded for MCP alone has no Run tool window to show it in.
|
||||
let sink = collector.clone();
|
||||
let emit = process_output(move |text| sink.lock().append(text));
|
||||
crate::ops::run::run_start(&call.host(), call.window(), config, emit, None).await
|
||||
};
|
||||
let info = match started {
|
||||
Ok(info) => info,
|
||||
Err(e) => {
|
||||
let _ = std::fs::remove_file(&output_path);
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
pub(crate) mod agent;
|
||||
mod agent_tools;
|
||||
mod build;
|
||||
mod configs;
|
||||
pub(crate) mod configs;
|
||||
mod output;
|
||||
mod process;
|
||||
mod targets;
|
||||
|
||||
@@ -70,6 +70,10 @@ impl Call {
|
||||
pub async fn ask(&self, request: ide_core::event::McpUiRequest) -> IdeResult<()> {
|
||||
self.host.mcp_requests.ask(self, request).await
|
||||
}
|
||||
/// Whether the project has a window to show what the tool starts (not one loaded for MCP alone).
|
||||
pub fn has_window(&self) -> bool {
|
||||
self.host.mcp_requests.window_ready(&self.window)
|
||||
}
|
||||
/// Asks the user before a tool changes the project or starts a process, unless brave mode
|
||||
/// is on — read from the IDE's own settings only, which a project's settings can't set.
|
||||
pub async fn confirm(&self, subject: &str, detail: Option<String>) -> IdeResult<()> {
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
//! Project-incarnation notebook ownership and whole-batch execution admission.
|
||||
use crate::ops::Channel;
|
||||
use base64::Engine;
|
||||
use ide_core::error::ErrorKind;
|
||||
use ide_core::{CancellationToken, IdeError, IdeEvent, IdeResult, IpcPath, SharedSink};
|
||||
use ide_notebook::kernel::{KernelManager, KernelOutput};
|
||||
use ide_notebook::{NotebookDocument, NotebookEdit, NotebookSnapshot};
|
||||
use parking_lot::Mutex;
|
||||
use serde::Serialize;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::path::{Path, PathBuf};
|
||||
@@ -28,6 +29,31 @@ pub struct NotebookOutputEvent {
|
||||
pub changed_cells: Vec<String>,
|
||||
}
|
||||
|
||||
/// One row of the Jupyter Variables tool window.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
pub struct NotebookVariable {
|
||||
pub name: String,
|
||||
#[serde(rename = "type")]
|
||||
pub type_name: String,
|
||||
pub value: String,
|
||||
}
|
||||
|
||||
const VARIABLES: &str = include_str!("notebook_variables.py");
|
||||
|
||||
/// The rows from the `user_expressions` of the variables request.
|
||||
fn parse_variables(reply: &serde_json::Value) -> IdeResult<Vec<NotebookVariable>> {
|
||||
let rows = &reply["rows"];
|
||||
if rows["status"] != "ok" {
|
||||
let reason = rows["evalue"].as_str().unwrap_or("no result");
|
||||
return Err(IdeError::unavailable(format!("could not read the kernel's variables: {reason}")));
|
||||
}
|
||||
// The value is a base64 str, so its text/plain is that text in quotes.
|
||||
let text = rows["data"]["text/plain"].as_str().unwrap_or_default().trim_matches(['\'', '"']);
|
||||
let bad = |error: String| IdeError::unavailable(format!("could not read the kernel's variables: {error}"));
|
||||
let json = base64::engine::general_purpose::STANDARD.decode(text).map_err(|e| bad(e.to_string()))?;
|
||||
serde_json::from_slice(&json).map_err(|e| bad(e.to_string()))
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Registry {
|
||||
stopped: bool,
|
||||
@@ -323,6 +349,19 @@ impl NotebookService {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The variables of the notebook's running kernel; `None` when no kernel runs.
|
||||
pub async fn variables(&self, id: &str) -> IdeResult<Option<Vec<NotebookVariable>>> {
|
||||
let document = self.resolve(id)?;
|
||||
if document.state.lock().active.is_some() {
|
||||
return Err(IdeError::unavailable("notebook is running"));
|
||||
}
|
||||
let expressions = HashMap::from([("rows".to_owned(), "_openidea_variables()".to_owned())]);
|
||||
match self.kernels.inspect(&document.path, VARIABLES, expressions).await? {
|
||||
Some(reply) => parse_variables(&reply).map(Some),
|
||||
None => Ok(None),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn admit(
|
||||
&self,
|
||||
id: &str,
|
||||
@@ -588,6 +627,21 @@ mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn variables_are_decoded_from_the_user_expression() {
|
||||
let rows = r#"[{"name": "x", "type": "int", "value": "1"}]"#;
|
||||
let text = format!("'{}'", base64::engine::general_purpose::STANDARD.encode(rows));
|
||||
let reply = json!({"rows": {"status": "ok", "data": {"text/plain": text}, "metadata": {}}});
|
||||
assert_eq!(
|
||||
parse_variables(&reply).unwrap(),
|
||||
vec![NotebookVariable { name: "x".into(), type_name: "int".into(), value: "1".into() }]
|
||||
);
|
||||
let failed =
|
||||
json!({"rows": {"status": "error", "ename": "NameError", "evalue": "name 'get_ipython' is not defined"}});
|
||||
assert!(parse_variables(&failed).unwrap_err().message.contains("get_ipython"));
|
||||
assert!(parse_variables(&json!({})).is_err());
|
||||
}
|
||||
|
||||
fn fixture() -> (tempfile::TempDir, Arc<NotebookService>, NotebookSnapshot) {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("session.ipynb");
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
# Run silently on a notebook's kernel by the Jupyter Variables tool window; the IDE then
|
||||
# evaluates `_openidea_variables()` as a user expression. Same rows as the Python Console's.
|
||||
def _openidea_variables():
|
||||
import base64
|
||||
import json
|
||||
import reprlib
|
||||
import types
|
||||
|
||||
shell = get_ipython() # noqa: F821 -- defined in every IPython namespace
|
||||
short = reprlib.Repr()
|
||||
short.maxstring = short.maxother = 200
|
||||
rows = []
|
||||
for name, value in list(shell.user_ns.items()):
|
||||
if name.startswith("_") or name in shell.user_ns_hidden or isinstance(value, types.ModuleType):
|
||||
continue
|
||||
try:
|
||||
text = short.repr(value)
|
||||
except Exception as error: # a broken __repr__ must not hide the other variables
|
||||
text = "<repr failed: %s>" % type(error).__name__
|
||||
rows.append({"name": name, "type": type(value).__name__, "value": text})
|
||||
rows.sort(key=lambda row: row["name"])
|
||||
# Base64 so the expression's text/plain (a str repr) needs no unescaping.
|
||||
return base64.b64encode(json.dumps(rows).encode()).decode()
|
||||
@@ -404,8 +404,9 @@ pub async fn agent_commands(
|
||||
host.project(window)?.agents.commands(&provider, task.as_deref()).await
|
||||
}
|
||||
|
||||
/// Entries of `task`'s conversation, or of its subagent `subagent`'s. Async so a long
|
||||
/// conversation is cloned and serialised off the main thread.
|
||||
/// Entries of `task`'s conversation, or of its subagent `subagent`'s. On the blocking pool:
|
||||
/// the first read of a saved conversation parses its task file, and a long one is cloned
|
||||
/// and serialised.
|
||||
#[command(trust = always)]
|
||||
pub async fn agent_entries(
|
||||
host: &Host,
|
||||
@@ -413,7 +414,8 @@ pub async fn agent_entries(
|
||||
task: String,
|
||||
subagent: Option<String>,
|
||||
) -> IdeResult<Vec<AgentEntry>> {
|
||||
host.project(window)?.agents.entries(&task, subagent)
|
||||
let agents = host.project(window)?.agents.clone();
|
||||
host.blocking(move || agents.entries(&task, subagent)).await
|
||||
}
|
||||
|
||||
/// Sessions of the project on this machine that no task holds yet, newest first.
|
||||
|
||||
@@ -3,7 +3,7 @@ use crate::Host;
|
||||
use ide_command::command;
|
||||
|
||||
use super::blocking;
|
||||
use ide_core::{IdeResult, IpcPath};
|
||||
use ide_core::{IdeError, IdeResult, IpcPath};
|
||||
use ide_coverage::{CoveragePrepared, CoverageReportSpec, CoverageSuite};
|
||||
use ide_run::RunConfig;
|
||||
|
||||
@@ -35,9 +35,30 @@ pub async fn coverage_collect(host: &Host, window: &str, report: CoverageReportS
|
||||
/// with paths mapped into this project.
|
||||
#[command(trust = always)]
|
||||
pub async fn coverage_import(host: &Host, window: &str, path: IpcPath) -> IdeResult<CoverageSuite> {
|
||||
// Also reads a SimpleCov resultset.
|
||||
let root = host.project(window)?.root.clone();
|
||||
blocking(move || ide_coverage::import(&path, &root)).await
|
||||
// Also reads Cobertura XML, a SimpleCov resultset and coverage.py data files.
|
||||
let project = host.project(window)?;
|
||||
let (root, cache, config_dir) =
|
||||
(project.root.clone(), project.cache_dir.join("coverage-import"), host.config_dir.clone());
|
||||
let trusted = project.require_trust();
|
||||
blocking(move || {
|
||||
if !ide_coverage::is_data_file(&path) {
|
||||
return ide_coverage::import(&path, &root);
|
||||
}
|
||||
// coverage.py analyses the sources with the project's interpreter: that runs project code.
|
||||
trusted.map_err(|_| {
|
||||
IdeError::unavailable(
|
||||
"Reading a .coverage data file runs the project's Python. Trust the project, or import the output of `coverage xml`.",
|
||||
)
|
||||
})?;
|
||||
let python = super::sdk::effective_python(&config_dir, &project, path.parent()).ok_or_else(|| {
|
||||
IdeError::unavailable(
|
||||
"Reading a .coverage data file needs the project's Python interpreter. Choose one, or import the output of `coverage xml`.",
|
||||
)
|
||||
})?;
|
||||
let out = ide_run::wrap::new_output_dir(&cache, KEEP_RUNS)?;
|
||||
ide_coverage::import_data(&path, &root, &python, &out)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
ide_command::domain!(coverage: coverage_collect, coverage_import, coverage_prepare);
|
||||
@@ -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, 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;
|
||||
@@ -75,6 +75,20 @@ pub async fn db_save_sources(host: &Host, window: &str, sources: Vec<DataSource>
|
||||
sources_changed(host, window)
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub fn db_source_folders(host: &Host, window: &str) -> IdeResult<Vec<DbSourceFolder>> {
|
||||
// The project's user-created folders and their data source members.
|
||||
ide_db::source::load_folders(&host.project(window)?.root)
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub fn db_save_source_folders(host: &Host, window: &str, folders: Vec<DbSourceFolder>) -> IdeResult<()> {
|
||||
// Replaces the project's data source folders; only grouping changes, never a source.
|
||||
let root = host.project(window)?.root.clone();
|
||||
ide_db::source::save_folders(&root, &folders)?;
|
||||
sources_changed(host, window)
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub async fn db_save_source_visibility(
|
||||
host: &Host,
|
||||
@@ -187,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.
|
||||
@@ -293,6 +329,20 @@ pub async fn db_table_details(
|
||||
db.table_details(&id, &schema, &table).await
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub async fn db_catalog_table_details(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
id: String,
|
||||
catalog: String,
|
||||
schema: String,
|
||||
table: String,
|
||||
) -> IdeResult<TableDetails> {
|
||||
// Columns and keys in an attached DuckDB catalog on the source session.
|
||||
let db = host.project(window)?.db.clone();
|
||||
db.catalog_table_details(&id, &catalog, &schema, &table).await
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub async fn db_table_grants(
|
||||
host: &Host,
|
||||
@@ -334,6 +384,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,
|
||||
@@ -342,11 +410,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
|
||||
}
|
||||
@@ -404,21 +474,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,
|
||||
@@ -428,10 +512,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
|
||||
}
|
||||
@@ -444,11 +530,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(
|
||||
@@ -461,11 +559,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() })
|
||||
@@ -489,19 +598,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) => {
|
||||
@@ -552,6 +671,41 @@ pub async fn db_table_page(
|
||||
result
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[command(trust = trusted)]
|
||||
pub async fn db_catalog_table_page(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
request: RequestId,
|
||||
id: String,
|
||||
catalog: String,
|
||||
schema: String,
|
||||
table: String,
|
||||
filter: Option<String>,
|
||||
sort: Vec<SortKey>,
|
||||
offset: u32,
|
||||
limit: u32,
|
||||
) -> IdeResult<TablePage> {
|
||||
// One read-only page from the explicit DuckDB catalog on the source session.
|
||||
let db = host.project(window)?.db.clone();
|
||||
let cancel = host.begin_request(request);
|
||||
let result = db
|
||||
.catalog_table_page(
|
||||
&id,
|
||||
&catalog,
|
||||
&schema,
|
||||
&table,
|
||||
filter.as_deref(),
|
||||
&sort,
|
||||
offset.into(),
|
||||
limit.max(1).into(),
|
||||
&cancel,
|
||||
)
|
||||
.await;
|
||||
host.end_request(request);
|
||||
result
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub async fn db_apply_edits(
|
||||
host: &Host,
|
||||
@@ -612,7 +766,16 @@ pub fn db_consoles(host: &Host, id: String, create: bool) -> IdeResult<Vec<IpcPa
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// `<dataDir>/consoles/db/<id>`: `<id>` for the default database, `<id>.<database>` for the others.
|
||||
/// The project view root for every data source's query consoles (`<dataDir>/consoles/db`).
|
||||
#[command(trust = always)]
|
||||
pub fn db_consoles_dir(host: &Host) -> IdeResult<IpcPath> {
|
||||
let dir = host.data_dir.join("consoles").join("db");
|
||||
std::fs::create_dir_all(&dir)?;
|
||||
Ok(dir.into())
|
||||
}
|
||||
|
||||
/// `<dataDir>/consoles/db/<id>`: `<id>` for the default database,
|
||||
/// `<id>.<database>` for the others.
|
||||
fn console_dir(host: &Host, id: &str) -> IdeResult<PathBuf> {
|
||||
let (source, database) = ide_db::split_target(id);
|
||||
if source.is_empty() || !source.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_') {
|
||||
@@ -670,9 +833,12 @@ ide_command::domain!(
|
||||
db_connect,
|
||||
db_connected,
|
||||
db_console_path,
|
||||
db_consoles_dir,
|
||||
db_consoles,
|
||||
db_create_database,
|
||||
db_database_catalog,
|
||||
db_catalog_table_details,
|
||||
db_catalog_table_page,
|
||||
db_databases,
|
||||
db_ddl,
|
||||
db_disconnect,
|
||||
@@ -681,6 +847,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,
|
||||
@@ -689,9 +856,11 @@ 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,
|
||||
db_save_source_folders,
|
||||
db_save_source_visibility,
|
||||
db_save_sources,
|
||||
db_saved_catalog,
|
||||
@@ -699,8 +868,10 @@ 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,
|
||||
db_sources,
|
||||
db_statements,
|
||||
db_table_details,
|
||||
@@ -740,6 +911,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();
|
||||
@@ -756,6 +999,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 } => {
|
||||
@@ -777,7 +1022,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())]]);
|
||||
}
|
||||
|
||||
@@ -793,10 +1039,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();
|
||||
@@ -817,7 +1065,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);
|
||||
@@ -825,7 +1074,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()));
|
||||
|
||||
@@ -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"));
|
||||
@@ -60,7 +62,8 @@ pub async fn debug_start(host: &Host, window: &str, config: LaunchConfig) -> Ide
|
||||
python.as_deref(),
|
||||
config.cwd.as_deref(),
|
||||
);
|
||||
super::python::prepare_debug(&mut config, &paths)?;
|
||||
let plots = super::plots::prepare(host, &project);
|
||||
super::python::prepare_debug(&mut config, &paths, plots.as_ref())?;
|
||||
}
|
||||
let label = window;
|
||||
let (sink, flush_output) = output::coalescing_sink(host.window_sink(label));
|
||||
@@ -149,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);
|
||||
|
||||
@@ -1,9 +1,14 @@
|
||||
//! Docker run configurations: the environment their `docker` command line runs with; and Docker
|
||||
//! connections through an SSH configuration, tunnelled with the IDE's own SSH client.
|
||||
//! Services tool window › Docker (`ide-docker`) and Docker run configurations: run on the
|
||||
//! project host (`Host` locally, `openidea-server` in a remote window), with SSH connections
|
||||
//! tunnelled through the host's own SSH client.
|
||||
use super::Channel;
|
||||
use crate::Host;
|
||||
use ide_command::command;
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use ide_docker::DockerEndpoint;
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult, RequestId};
|
||||
use ide_docker::{
|
||||
ComposeOp, ContainerOp, DockerContainerStats, DockerEndpoint, DockerEvent, DockerImageLayer, DockerLogLine,
|
||||
DockerObject, DockerProcessList, DockerRegistry, DockerSettings, DockerSnapshot, PruneTarget, RegistryAuth,
|
||||
};
|
||||
use ide_ssh::Tunnel;
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
|
||||
@@ -54,6 +59,242 @@ pub async fn disconnect(host: &Host, endpoint: &DockerEndpoint) {
|
||||
host.ssh.release(id);
|
||||
}
|
||||
|
||||
/// Runs a cancellable docker command (`request` → `cancel_request`) off the async workers.
|
||||
async fn cancellable<T: Send + 'static>(
|
||||
host: &Host,
|
||||
request: RequestId,
|
||||
f: impl FnOnce(&CancellationToken) -> IdeResult<T> + Send + 'static,
|
||||
) -> IdeResult<T> {
|
||||
let cancel = host.begin_request(request);
|
||||
let result = host.blocking(move || f(&cancel)).await;
|
||||
host.end_request(request);
|
||||
result
|
||||
}
|
||||
|
||||
/// Closes the connection's SSH tunnel and, when nothing else uses it, its SSH connection
|
||||
/// (Services › Disconnect); other endpoints keep nothing open.
|
||||
#[command(trust = always)]
|
||||
pub async fn docker_disconnect(host: &Host, endpoint: DockerEndpoint) -> IdeResult<()> {
|
||||
disconnect(host, &endpoint).await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Availability plus containers, images, volumes and networks.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn docker_snapshot(host: &Host, endpoint: DockerEndpoint) -> IdeResult<DockerSnapshot> {
|
||||
let endpoint = resolve(host, endpoint).await?;
|
||||
host.blocking(move || Ok(ide_docker::snapshot(&endpoint))).await
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub async fn docker_container_op(
|
||||
host: &Host,
|
||||
endpoint: DockerEndpoint,
|
||||
ids: Vec<String>,
|
||||
op: ContainerOp,
|
||||
) -> IdeResult<()> {
|
||||
let endpoint = resolve(host, endpoint).await?;
|
||||
host.blocking(move || ide_docker::container_op(&endpoint, &ids, op)).await
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub async fn docker_remove(
|
||||
host: &Host,
|
||||
endpoint: DockerEndpoint,
|
||||
object: DockerObject,
|
||||
ids: Vec<String>,
|
||||
force: bool,
|
||||
) -> IdeResult<()> {
|
||||
let endpoint = resolve(host, endpoint).await?;
|
||||
host.blocking(move || ide_docker::remove(&endpoint, object, &ids, force)).await
|
||||
}
|
||||
|
||||
/// Pretty-printed `docker inspect` JSON.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn docker_inspect(
|
||||
host: &Host,
|
||||
endpoint: DockerEndpoint,
|
||||
object: DockerObject,
|
||||
id: String,
|
||||
) -> IdeResult<String> {
|
||||
let endpoint = resolve(host, endpoint).await?;
|
||||
host.blocking(move || ide_docker::inspect(&endpoint, object, &id)).await
|
||||
}
|
||||
|
||||
/// Layers of an image (`docker image history`).
|
||||
#[command(trust = trusted)]
|
||||
pub async fn docker_image_history(
|
||||
host: &Host,
|
||||
endpoint: DockerEndpoint,
|
||||
id: String,
|
||||
) -> IdeResult<Vec<DockerImageLayer>> {
|
||||
let endpoint = resolve(host, endpoint).await?;
|
||||
host.blocking(move || ide_docker::image_history(&endpoint, &id)).await
|
||||
}
|
||||
|
||||
/// Processes running inside a container (`docker top`).
|
||||
#[command(trust = trusted)]
|
||||
pub async fn docker_container_top(host: &Host, endpoint: DockerEndpoint, id: String) -> IdeResult<DockerProcessList> {
|
||||
let endpoint = resolve(host, endpoint).await?;
|
||||
host.blocking(move || ide_docker::container_top(&endpoint, &id)).await
|
||||
}
|
||||
|
||||
/// One-shot resource usage snapshot of a running container (`docker stats --no-stream`).
|
||||
#[command(trust = trusted)]
|
||||
pub async fn docker_container_stats(
|
||||
host: &Host,
|
||||
endpoint: DockerEndpoint,
|
||||
id: String,
|
||||
) -> IdeResult<DockerContainerStats> {
|
||||
let endpoint = resolve(host, endpoint).await?;
|
||||
host.blocking(move || ide_docker::container_stats(&endpoint, &id)).await
|
||||
}
|
||||
|
||||
/// Disk usage per volume name (`docker system df -v`).
|
||||
#[command(trust = trusted)]
|
||||
pub async fn docker_volume_sizes(host: &Host, endpoint: DockerEndpoint) -> IdeResult<BTreeMap<String, String>> {
|
||||
let endpoint = resolve(host, endpoint).await?;
|
||||
host.blocking(move || ide_docker::volume_sizes(&endpoint)).await
|
||||
}
|
||||
|
||||
/// Streams a container's log lines, in batches, until it stops or the request is cancelled.
|
||||
#[command(trust = trusted)]
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub async fn docker_logs(
|
||||
host: &Host,
|
||||
request: RequestId,
|
||||
endpoint: DockerEndpoint,
|
||||
id: String,
|
||||
tail: u32,
|
||||
follow: bool,
|
||||
timestamps: bool,
|
||||
on_lines: Channel<Vec<DockerLogLine>>,
|
||||
) -> IdeResult<()> {
|
||||
let endpoint = resolve(host, endpoint).await?;
|
||||
cancellable(host, request, move |cancel| {
|
||||
ide_docker::logs(&endpoint, &id, tail, follow, timestamps, cancel, &|lines| {
|
||||
let _ = on_lines.send(lines);
|
||||
})
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Follows `docker events` until the daemon goes away or the request is cancelled.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn docker_events(
|
||||
host: &Host,
|
||||
request: RequestId,
|
||||
endpoint: DockerEndpoint,
|
||||
on_event: Channel<DockerEvent>,
|
||||
) -> IdeResult<()> {
|
||||
let endpoint = resolve(host, endpoint).await?;
|
||||
cancellable(host, request, move |cancel| {
|
||||
ide_docker::watch_events(&endpoint, cancel, &|e| {
|
||||
let _ = on_event.send(e);
|
||||
})
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// `docker pull`, logging in first when a saved registry with a password serves the image.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn docker_pull(
|
||||
host: &Host,
|
||||
request: RequestId,
|
||||
endpoint: DockerEndpoint,
|
||||
reference: String,
|
||||
on_output: Channel<String>,
|
||||
) -> IdeResult<()> {
|
||||
let endpoint = resolve(host, endpoint).await?;
|
||||
let data_dir = host.data_dir.clone();
|
||||
cancellable(host, request, move |cancel| {
|
||||
let auth = ide_docker::auth_for(&data_dir, &reference);
|
||||
ide_docker::pull(&endpoint, &reference, auth.as_ref(), cancel, &|line| {
|
||||
let _ = on_output.send(line);
|
||||
})
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub async fn docker_prune(
|
||||
host: &Host,
|
||||
request: RequestId,
|
||||
endpoint: DockerEndpoint,
|
||||
target: PruneTarget,
|
||||
on_output: Channel<String>,
|
||||
) -> IdeResult<()> {
|
||||
let endpoint = resolve(host, endpoint).await?;
|
||||
cancellable(host, request, move |cancel| {
|
||||
ide_docker::prune(&endpoint, target, cancel, &|line| {
|
||||
let _ = on_output.send(line);
|
||||
})
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// `docker compose` start / stop / restart / down of a project found through labels.
|
||||
#[command(trust = trusted)]
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub async fn docker_compose_op(
|
||||
host: &Host,
|
||||
request: RequestId,
|
||||
endpoint: DockerEndpoint,
|
||||
project: String,
|
||||
files: Vec<String>,
|
||||
working_dir: Option<String>,
|
||||
op: ComposeOp,
|
||||
on_output: Channel<String>,
|
||||
) -> IdeResult<()> {
|
||||
let endpoint = resolve(host, endpoint).await?;
|
||||
cancellable(host, request, move |cancel| {
|
||||
ide_docker::compose_op(&endpoint, &project, &files, working_dir.as_deref(), op, cancel, &|line| {
|
||||
let _ = on_output.send(line);
|
||||
})
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Docker connections and registries of the project host.
|
||||
#[command(trust = always)]
|
||||
pub async fn docker_settings(host: &Host) -> IdeResult<DockerSettings> {
|
||||
let data_dir = host.data_dir.clone();
|
||||
host.blocking(move || Ok(ide_docker::load_settings(&data_dir))).await
|
||||
}
|
||||
|
||||
#[command(trust = always)]
|
||||
pub async fn docker_save_settings(host: &Host, settings: DockerSettings) -> IdeResult<()> {
|
||||
let data_dir = host.data_dir.clone();
|
||||
host.blocking(move || ide_docker::save_settings(&data_dir, &settings)).await
|
||||
}
|
||||
|
||||
/// Saves (`None`: forgets) a registry's password.
|
||||
#[command(trust = always)]
|
||||
pub async fn docker_set_registry_password(host: &Host, id: String, password: Option<String>) -> IdeResult<()> {
|
||||
let data_dir = host.data_dir.clone();
|
||||
host.blocking(move || ide_docker::set_registry_password(&data_dir, &id, password.as_deref())).await
|
||||
}
|
||||
|
||||
/// Test login to `registry` (`password`, else the saved one) through `endpoint`'s daemon.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn docker_registry_login(
|
||||
host: &Host,
|
||||
endpoint: DockerEndpoint,
|
||||
registry: DockerRegistry,
|
||||
password: Option<String>,
|
||||
) -> IdeResult<String> {
|
||||
let endpoint = resolve(host, endpoint).await?;
|
||||
let data_dir = host.data_dir.clone();
|
||||
host.blocking(move || {
|
||||
let password = password
|
||||
.or_else(|| ide_docker::registry_password(&data_dir, ®istry.id))
|
||||
.ok_or_else(|| IdeError::invalid("enter the registry password"))?;
|
||||
let auth = RegistryAuth { address: registry.address, username: registry.username, password };
|
||||
ide_docker::login(&endpoint, &auth)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Environment for a Docker run configuration's command line: selects `endpoint`'s
|
||||
/// daemon and puts the docker executable on `PATH`.
|
||||
#[command(trust = always)]
|
||||
@@ -64,4 +305,25 @@ pub async fn docker_run_env(host: &Host, endpoint: DockerEndpoint) -> IdeResult<
|
||||
host.blocking(move || Ok(ide_docker::run_env(&endpoint))).await
|
||||
}
|
||||
|
||||
ide_command::domain!(docker: docker_run_env);
|
||||
ide_command::domain!(
|
||||
docker:
|
||||
docker_compose_op,
|
||||
docker_container_op,
|
||||
docker_container_stats,
|
||||
docker_container_top,
|
||||
docker_disconnect,
|
||||
docker_events,
|
||||
docker_image_history,
|
||||
docker_inspect,
|
||||
docker_logs,
|
||||
docker_prune,
|
||||
docker_pull,
|
||||
docker_registry_login,
|
||||
docker_remove,
|
||||
docker_run_env,
|
||||
docker_save_settings,
|
||||
docker_set_registry_password,
|
||||
docker_settings,
|
||||
docker_snapshot,
|
||||
docker_volume_sizes,
|
||||
);
|
||||
@@ -0,0 +1,264 @@
|
||||
//! Host resource metrics (`host_metrics`, `host_end_process`) for the Remote Host
|
||||
//! Resources status bar widget and popover dashboard.
|
||||
|
||||
use crate::Host;
|
||||
use ide_command::command;
|
||||
use ide_core::IdeResult;
|
||||
use ide_workspace::memory::{self, CpuSampler, MemoryCategory, MemoryRoot, ProcessMemory, ProcessTable};
|
||||
use ide_workspace::system::SystemSampler;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use std::collections::HashSet;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct HostMetricsSampler {
|
||||
system: SystemSampler,
|
||||
cpu: CpuSampler,
|
||||
}
|
||||
|
||||
/// One process outside OpenIDEA's own process tree on the host (read-only in the UI).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct HostProcess {
|
||||
pub pid: u32,
|
||||
pub name: String,
|
||||
pub cpu_percent: Option<f32>,
|
||||
pub memory_bytes: Option<u64>,
|
||||
}
|
||||
|
||||
/// Snapshot of host-wide CPU, memory, network, disk and process usage.
|
||||
#[derive(Clone, Debug, Default, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct HostMetrics {
|
||||
/// Overall CPU utilization across all logical cores (`0..=100`); `null` on the first sample.
|
||||
pub cpu_percent: Option<f32>,
|
||||
/// Logical CPU cores available to this host or container.
|
||||
pub cpu_cores: u32,
|
||||
/// Unix 1m, 5m, 15m load averages; `null` on Windows.
|
||||
pub load_average: Option<[f32; 3]>,
|
||||
/// Host or container memory in use, in bytes.
|
||||
pub memory_used_bytes: Option<u64>,
|
||||
/// Total physical (or container limit) memory, in bytes.
|
||||
pub memory_total_bytes: Option<u64>,
|
||||
/// Bytes/s received across non-loopback network interfaces; `null` on the first sample or unsupported OS.
|
||||
pub net_rx_bytes_per_sec: Option<f64>,
|
||||
/// Bytes/s sent across non-loopback network interfaces; `null` on the first sample or unsupported OS.
|
||||
pub net_tx_bytes_per_sec: Option<f64>,
|
||||
/// Bytes/s read from block storage; `null` on the first sample or unsupported OS.
|
||||
pub disk_read_bytes_per_sec: Option<f64>,
|
||||
/// Bytes/s written to block storage; `null` on the first sample or unsupported OS.
|
||||
pub disk_write_bytes_per_sec: Option<f64>,
|
||||
/// Free bytes available to the user on the project volume (or `$HOME` fallback).
|
||||
pub disk_available_bytes: Option<u64>,
|
||||
/// Total capacity in bytes of the project volume (or `$HOME` fallback).
|
||||
pub disk_total_bytes: Option<u64>,
|
||||
/// Uptime of the backend process in milliseconds.
|
||||
pub uptime_ms: f64,
|
||||
/// OpenIDEA backend, language servers, runs, terminals, debug adapters and agents (`includeProcesses = true`).
|
||||
pub processes: Vec<ProcessMemory>,
|
||||
/// Highest-usage processes on the host outside OpenIDEA's own process tree (`includeProcesses = true`).
|
||||
pub external_processes: Vec<HostProcess>,
|
||||
}
|
||||
|
||||
const MAX_EXTERNAL_PROCESSES: usize = 5;
|
||||
const MIN_EXTERNAL_CPU_PERCENT: f32 = 0.5;
|
||||
const MIN_EXTERNAL_MEMORY_BYTES: u64 = 32 << 20;
|
||||
|
||||
fn project_name(root: &Path) -> String {
|
||||
root.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| root.display().to_string())
|
||||
}
|
||||
|
||||
fn process_root(pid: u32, label: String, kind: &str) -> MemoryRoot {
|
||||
MemoryRoot { pid, category: MemoryCategory::Process, label, detail: Some(kind.into()), with_children: true }
|
||||
}
|
||||
|
||||
fn volume_path(host: &Host, window: &str) -> PathBuf {
|
||||
if let Ok(p) = host.project(window) {
|
||||
return p.root.clone();
|
||||
}
|
||||
if let Some(p) = host.projects().into_iter().next() {
|
||||
return p.root.clone();
|
||||
}
|
||||
dirs::home_dir().unwrap_or_else(|| host.data_dir.clone())
|
||||
}
|
||||
|
||||
fn disk_space(path: &Path) -> Option<(u64, u64)> {
|
||||
#[cfg(unix)]
|
||||
#[allow(clippy::unnecessary_cast)]
|
||||
{
|
||||
let stat = rustix::fs::statvfs(path).ok()?;
|
||||
let frsize = stat.f_frsize as u64;
|
||||
let total = (stat.f_blocks as u64).saturating_mul(frsize);
|
||||
let avail = (stat.f_bavail as u64).saturating_mul(frsize);
|
||||
(total > 0).then_some((avail.min(total), total))
|
||||
}
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use std::os::windows::ffi::OsStrExt;
|
||||
let wide: Vec<u16> = path.as_os_str().encode_wide().chain(std::iter::once(0)).collect();
|
||||
let (mut avail, mut total, mut free) = (0u64, 0u64, 0u64);
|
||||
// SAFETY: `wide` is NUL-terminated and all three u64 out-pointers are writable.
|
||||
let ok = unsafe {
|
||||
windows_sys::Win32::Storage::FileSystem::GetDiskFreeSpaceExW(
|
||||
wide.as_ptr(),
|
||||
&mut avail,
|
||||
&mut total,
|
||||
&mut free,
|
||||
)
|
||||
};
|
||||
(ok != 0 && total > 0).then_some((avail.min(total), total))
|
||||
}
|
||||
#[cfg(not(any(unix, windows)))]
|
||||
{
|
||||
let _ = path;
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn collect_roots(host: &Host) -> Vec<MemoryRoot> {
|
||||
let mut roots = Vec::new();
|
||||
for p in host.projects() {
|
||||
for s in p.lsp.servers() {
|
||||
if let Some(pid) = s.pid {
|
||||
roots.push(MemoryRoot {
|
||||
pid,
|
||||
category: MemoryCategory::LanguageServer,
|
||||
label: s.name,
|
||||
detail: Some(project_name(s.root.as_ref())),
|
||||
with_children: true,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
for r in host.processes.list().into_iter().filter(|r| r.running) {
|
||||
if let Some(pid) = r.pid {
|
||||
roots.push(process_root(pid, r.name, "Run"));
|
||||
}
|
||||
}
|
||||
for t in host.terminals.list() {
|
||||
if let Some(pid) = t.pid {
|
||||
roots.push(process_root(pid, t.title, "Terminal"));
|
||||
}
|
||||
}
|
||||
roots
|
||||
}
|
||||
|
||||
fn resource_share(p: &HostProcess, cores: u32, total_memory: Option<u64>) -> f64 {
|
||||
let cpu_share = p.cpu_percent.map(|c| c as f64 / (cores.max(1) as f64 * 100.0)).unwrap_or(0.0);
|
||||
let mem_share = match (p.memory_bytes, total_memory.filter(|&t| t > 0)) {
|
||||
(Some(b), Some(t)) => b as f64 / t as f64,
|
||||
_ => 0.0,
|
||||
};
|
||||
cpu_share.max(mem_share)
|
||||
}
|
||||
|
||||
/// Snapshot of host-wide resource counters (CPU, memory, network, disk) and, when
|
||||
/// `include_processes` is true, the process breakdown of OpenIDEA and top host processes.
|
||||
#[command(trust = always)]
|
||||
pub async fn host_metrics(host: &Arc<Host>, window: &str, include_processes: bool) -> IdeResult<HostMetrics> {
|
||||
let disk_target = volume_path(host, window);
|
||||
let roots = if include_processes { collect_roots(host) } else { Vec::new() };
|
||||
let h = host.clone();
|
||||
host.blocking(move || {
|
||||
let table = include_processes.then(ProcessTable::snapshot);
|
||||
let (disk_available_bytes, disk_total_bytes) = match disk_space(&disk_target) {
|
||||
Some((a, t)) => (Some(a), Some(t)),
|
||||
None => (None, None),
|
||||
};
|
||||
let uptime_ms =
|
||||
ide_workspace::process::process_age().unwrap_or_else(ide_workspace::process::uptime).as_secs_f64() * 1000.0;
|
||||
|
||||
let mut sampler = h.metrics_sampler.lock();
|
||||
let rates = sampler.system.sample();
|
||||
|
||||
let (processes, external_processes) = if let Some(table) = table {
|
||||
sampler.cpu.retain(&table);
|
||||
let me = std::process::id();
|
||||
let processes =
|
||||
memory::attribute(&table, me, &roots, memory::footprint_bytes, |pid| sampler.cpu.percent(pid));
|
||||
let claimed: HashSet<u32> = table.tree(me).into_iter().collect();
|
||||
let mut external: Vec<HostProcess> = table
|
||||
.entries()
|
||||
.filter(|e| e.pid != 0 && !claimed.contains(&e.pid))
|
||||
.filter_map(|e| {
|
||||
let cpu_percent = sampler.cpu.percent(e.pid);
|
||||
let memory_bytes = memory::fast_resident_bytes(e.pid);
|
||||
let active = cpu_percent.unwrap_or(0.0) >= MIN_EXTERNAL_CPU_PERCENT
|
||||
|| memory_bytes.unwrap_or(0) >= MIN_EXTERNAL_MEMORY_BYTES;
|
||||
active.then(|| HostProcess { pid: e.pid, name: e.name.clone(), cpu_percent, memory_bytes })
|
||||
})
|
||||
.collect();
|
||||
external.sort_by(|a, b| {
|
||||
resource_share(b, rates.cpu_cores, rates.memory_total_bytes)
|
||||
.total_cmp(&resource_share(a, rates.cpu_cores, rates.memory_total_bytes))
|
||||
.then_with(|| b.memory_bytes.unwrap_or(0).cmp(&a.memory_bytes.unwrap_or(0)))
|
||||
.then_with(|| a.pid.cmp(&b.pid))
|
||||
});
|
||||
external.truncate(MAX_EXTERNAL_PROCESSES);
|
||||
(processes, external)
|
||||
} else {
|
||||
(Vec::new(), Vec::new())
|
||||
};
|
||||
|
||||
Ok(HostMetrics {
|
||||
cpu_percent: rates.cpu_percent,
|
||||
cpu_cores: rates.cpu_cores,
|
||||
load_average: rates.load_average,
|
||||
memory_used_bytes: rates.memory_used_bytes,
|
||||
memory_total_bytes: rates.memory_total_bytes,
|
||||
net_rx_bytes_per_sec: rates.net_rx_bytes_per_sec,
|
||||
net_tx_bytes_per_sec: rates.net_tx_bytes_per_sec,
|
||||
disk_read_bytes_per_sec: rates.disk_read_bytes_per_sec,
|
||||
disk_write_bytes_per_sec: rates.disk_write_bytes_per_sec,
|
||||
disk_available_bytes,
|
||||
disk_total_bytes,
|
||||
uptime_ms,
|
||||
processes,
|
||||
external_processes,
|
||||
})
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Ends a child process started by this OpenIDEA host (language server, run, terminal,
|
||||
/// debug adapter or agent) and its descendants; refuses processes outside this host's tree.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn host_end_process(host: &Arc<Host>, pid: u32) -> IdeResult<bool> {
|
||||
host.blocking(move || Ok(memory::end_process_tree(std::process::id(), pid, Duration::from_secs(3)))).await
|
||||
}
|
||||
|
||||
ide_command::domain!(host_metrics: host_metrics, host_end_process);
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::HostConfig;
|
||||
|
||||
#[tokio::test]
|
||||
async fn collects_light_and_detailed_host_metrics() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let host = Arc::new(Host::new(HostConfig::for_test(dir.path())));
|
||||
|
||||
let light = host_metrics(&host, "main", false).await.unwrap();
|
||||
assert!(light.cpu_cores >= 1);
|
||||
assert!(light.processes.is_empty());
|
||||
assert!(light.external_processes.is_empty());
|
||||
if cfg!(any(unix, windows)) {
|
||||
let avail = light.disk_available_bytes.expect("disk_available_bytes");
|
||||
let total = light.disk_total_bytes.expect("disk_total_bytes");
|
||||
assert!(total > 0 && avail <= total, "{avail} / {total}");
|
||||
}
|
||||
|
||||
let detailed = host_metrics(&host, "main", true).await.unwrap();
|
||||
assert!(!detailed.processes.is_empty());
|
||||
assert_eq!(detailed.processes[0].label, "Backend");
|
||||
assert!(detailed.external_processes.len() <= MAX_EXTERNAL_PROCESSES);
|
||||
|
||||
// Refuses to terminate the backend itself or PID 1.
|
||||
assert!(!host_end_process(&host, std::process::id()).await.unwrap());
|
||||
assert!(!host_end_process(&host, 1).await.unwrap());
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
@@ -1881,6 +1898,29 @@ pub async fn lsp_snapshot_diagnostics(
|
||||
result
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub async fn lsp_snapshot_completion(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
path: std::path::PathBuf,
|
||||
text: String,
|
||||
pos: Pos,
|
||||
request: RequestId,
|
||||
) -> IdeResult<Vec<CompletionItem>> {
|
||||
let project = host.project(window)?;
|
||||
if !path.is_absolute() || path.file_name().is_none() {
|
||||
return Err(IdeError::invalid("a text snapshot requires 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 cancel = host.begin_project_read_request(window, request);
|
||||
let result = project.lsp.snapshot_completion(&path, &language, &text, pos, &cancel).await;
|
||||
host.end_request(request);
|
||||
result
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub async fn lsp_inlay_hints(host: &Host, window: &str, doc: DocId, range: Range) -> IdeResult<Vec<InlayHint>> {
|
||||
let lsp = host.project(window)?.lsp.clone();
|
||||
@@ -3236,6 +3276,9 @@ 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,
|
||||
lsp_goto,
|
||||
|
||||
@@ -19,6 +19,7 @@ pub mod flutter;
|
||||
pub mod fs;
|
||||
pub mod heap;
|
||||
pub mod history;
|
||||
pub mod host_metrics;
|
||||
pub mod http;
|
||||
pub mod java;
|
||||
pub mod jvm_icons;
|
||||
@@ -26,7 +27,9 @@ pub mod lsp;
|
||||
pub mod maven_placeholder;
|
||||
pub mod nav;
|
||||
pub mod notebook;
|
||||
mod plots;
|
||||
pub mod project;
|
||||
pub mod pytest_fixtures;
|
||||
mod python;
|
||||
pub mod python_stubs;
|
||||
pub mod refactor;
|
||||
@@ -93,6 +96,7 @@ ide_command::domains!(
|
||||
fs: crate::ops::fs,
|
||||
heap: crate::ops::heap,
|
||||
history: crate::ops::history,
|
||||
host_metrics: crate::ops::host_metrics,
|
||||
http: crate::ops::http,
|
||||
java: crate::ops::java,
|
||||
jvm_icons: crate::ops::jvm_icons,
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
use super::blocking;
|
||||
use super::pytest_fixtures::{PytestFixtureAt, PytestFixtureUsages, fixture_at, fixture_usages, rename_fixture};
|
||||
use super::python_stubs::{
|
||||
PythonStubLinks, counterpart_candidates, match_declarations, module_name, site_packages, stub_path,
|
||||
};
|
||||
use crate::Host;
|
||||
use crate::Project;
|
||||
use ide_command::command;
|
||||
use ide_core::{DocId, IdeResult, IpcPath, LanguageId, Location, Pos};
|
||||
use ide_core::{DocId, IdeResult, IpcPath, LanguageId, Location, Pos, RequestId, WorkspaceEdit};
|
||||
use ide_index::{ExtensionCount, FileMatch, IndexStatus, SymbolFilter, SymbolMatch};
|
||||
use ide_language::{CSS_VARIABLE, FileReference, WebReference};
|
||||
use ide_workspace::file_refs::{self, PathCompletion};
|
||||
@@ -478,6 +479,78 @@ pub async fn nav_python_stubs(host: &Host, window: &str, doc: DocId) -> IdeResul
|
||||
.await
|
||||
}
|
||||
|
||||
/// pytest fixtures at `pos` of a Python document: the definition pytest uses for the fixture
|
||||
/// named there (a test's parameter, a `usefixtures` / `getfixturevalue` string), and the
|
||||
/// fixtures visible where a fixture name goes, for completion.
|
||||
#[command(trust = always)]
|
||||
pub async fn nav_pytest_fixtures(host: &Host, window: &str, doc: DocId, pos: Pos) -> IdeResult<PytestFixtureAt> {
|
||||
let project = host.project(window)?;
|
||||
let syntax = host.syntax();
|
||||
blocking(move || {
|
||||
let snap = project.documents.snapshot(doc)?;
|
||||
if snap.large || snap.language.as_str() != "python" {
|
||||
return Ok(Default::default());
|
||||
}
|
||||
Ok(fixture_at(&project, &syntax, &snap.path, &snap.text, pos))
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Find Usages of the pytest fixture at `pos` (its definition, or a place asking for it): every
|
||||
/// test and fixture parameter, `usefixtures` and `getfixturevalue` string that gets it.
|
||||
/// None when `pos` names no fixture. Cancellable.
|
||||
#[command(trust = always)]
|
||||
pub async fn nav_pytest_fixture_usages(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
doc: DocId,
|
||||
pos: Pos,
|
||||
request: RequestId,
|
||||
) -> IdeResult<Option<PytestFixtureUsages>> {
|
||||
let project = host.project(window)?;
|
||||
let syntax = host.syntax();
|
||||
let token = host.begin_request(request);
|
||||
let result = blocking(move || {
|
||||
let snap = project.documents.snapshot(doc)?;
|
||||
if snap.large || snap.language.as_str() != "python" {
|
||||
return Ok(None);
|
||||
}
|
||||
fixture_usages(&project, &syntax, &snap.path, &snap.text, pos, &|| token.is_cancelled())
|
||||
})
|
||||
.await;
|
||||
host.end_request(request);
|
||||
result
|
||||
}
|
||||
|
||||
/// Rename of the pytest fixture at `pos`: its definition, every place that gets it and the
|
||||
/// uses of those parameters in their functions. Cancellable.
|
||||
#[command(trust = always)]
|
||||
pub async fn nav_pytest_fixture_rename(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
doc: DocId,
|
||||
pos: Pos,
|
||||
new_name: String,
|
||||
request: RequestId,
|
||||
) -> IdeResult<WorkspaceEdit> {
|
||||
let project = host.project(window)?;
|
||||
let syntax = host.syntax();
|
||||
let token = host.begin_request(request);
|
||||
let result = blocking(move || {
|
||||
let snap = project.documents.snapshot(doc)?;
|
||||
let mut edit =
|
||||
rename_fixture(&project, &syntax, &snap.path, &snap.text, pos, &new_name, &|| token.is_cancelled())?;
|
||||
if token.is_cancelled() {
|
||||
return Err(ide_core::IdeError::cancelled());
|
||||
}
|
||||
project.documents.prepare_workspace_edit(&mut edit)?;
|
||||
Ok(edit)
|
||||
})
|
||||
.await;
|
||||
host.end_request(request);
|
||||
result
|
||||
}
|
||||
|
||||
ide_command::domain!(
|
||||
nav:
|
||||
find_dirs,
|
||||
@@ -491,6 +564,9 @@ ide_command::domain!(
|
||||
mark_recent,
|
||||
nav_index_definitions,
|
||||
nav_inheritance,
|
||||
nav_pytest_fixture_rename,
|
||||
nav_pytest_fixture_usages,
|
||||
nav_pytest_fixtures,
|
||||
nav_python_stubs,
|
||||
nav_resolve_module,
|
||||
path_completions,
|
||||
|
||||
@@ -93,6 +93,18 @@ pub async fn notebook_interrupt(host: &Host, window: &str, id: String) -> IdeRes
|
||||
.map_err(|error| IdeError::internal(error.to_string()))?
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub async fn notebook_variables(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
id: String,
|
||||
) -> IdeResult<Option<Vec<crate::notebook::NotebookVariable>>> {
|
||||
let notebooks = host.project(window)?.notebooks.clone();
|
||||
tokio::spawn(async move { notebooks.variables(&id).await })
|
||||
.await
|
||||
.map_err(|error| IdeError::internal(error.to_string()))?
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[command(trust = trusted)]
|
||||
pub async fn notebook_execute(
|
||||
@@ -162,4 +174,5 @@ ide_command::domain!(
|
||||
notebook_restart,
|
||||
notebook_save,
|
||||
notebook_undo,
|
||||
notebook_variables,
|
||||
);
|
||||
@@ -0,0 +1,66 @@
|
||||
//! The Plots tool window: matplotlib figures that Python runs and debug sessions save (see
|
||||
//! [`ide_run::plots`]) reach the window as [`IdeEvent::PlotAdded`].
|
||||
use crate::Host;
|
||||
use crate::project::Project;
|
||||
use ide_core::IdeEvent;
|
||||
use ide_run::plots::Plots;
|
||||
use notify::{RecursiveMode, Watcher};
|
||||
use std::io;
|
||||
use std::path::Path;
|
||||
|
||||
/// The backend and plots folder for a Python run of `project`, installed and watched on first use;
|
||||
/// `None` when Settings › Python turns the tool window off.
|
||||
pub(crate) fn prepare(host: &Host, project: &Project) -> Option<Plots> {
|
||||
if !project.settings.effective().languages.python.show_plots_in_tool_window {
|
||||
return None;
|
||||
}
|
||||
let plots = Plots { backend: host.local_data_dir.join("matplotlib-backend"), dir: project.cache_dir.join("plots") };
|
||||
match ide_run::plots::install(&plots.backend).and_then(|()| watch(project, &plots.dir)) {
|
||||
Ok(()) => Some(plots),
|
||||
Err(e) => {
|
||||
tracing::warn!("cannot set up the Plots tool window in {}: {e}", plots.dir.display());
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn watch(project: &Project, dir: &Path) -> io::Result<()> {
|
||||
let mut slot = project.plots_watch.lock();
|
||||
if slot.is_some() {
|
||||
return Ok(());
|
||||
}
|
||||
// Figures of an earlier session are not shown again.
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
std::fs::create_dir_all(dir)?;
|
||||
let sink = project.sink.clone();
|
||||
// Every event of a finished PNG is sent (create, rename, modify); the window keeps each path once.
|
||||
let mut watcher = notify::recommended_watcher(move |res: notify::Result<notify::Event>| {
|
||||
for path in res.map(|e| e.paths).unwrap_or_default() {
|
||||
if is_plot(&path) && path.is_file() {
|
||||
sink.emit(IdeEvent::PlotAdded { path: path.to_string_lossy().into_owned() });
|
||||
}
|
||||
}
|
||||
})
|
||||
.map_err(io::Error::other)?;
|
||||
watcher.watch(dir, RecursiveMode::NonRecursive).map_err(io::Error::other)?;
|
||||
*slot = Some(watcher);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A finished figure: the backend writes `.<name>.png` first, then renames it.
|
||||
fn is_plot(path: &Path) -> bool {
|
||||
path.extension().is_some_and(|e| e == "png")
|
||||
&& path.file_name().is_some_and(|n| !n.to_string_lossy().starts_with('.'))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn only_finished_pngs_are_plots() {
|
||||
assert!(is_plot(Path::new("/c/plots/1-2-0.png")));
|
||||
assert!(!is_plot(Path::new("/c/plots/.1-2-0.png")));
|
||||
assert!(!is_plot(Path::new("/c/plots/notes.txt")));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,464 @@
|
||||
//! pytest fixtures across files: the modules a test file sees, nearest first (the file, its
|
||||
//! `conftest.py` files up to the project root, the modules `pytest_plugins` names, installed
|
||||
//! plugins' `pytest11` entry points, pytest's own `_pytest` package), for Go to Declaration
|
||||
//! and completion of fixture names.
|
||||
|
||||
use super::python_stubs::site_packages;
|
||||
use crate::Project;
|
||||
use ide_core::{FileEdit, IdeError, IdeResult, IpcPath, LanguageId, Location, Pos, Range, TextEdit, WorkspaceEdit};
|
||||
use ide_language::{PytestModule, Syntax, resolve_fixture, visible_fixtures};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{Arc, LazyLock, Mutex};
|
||||
use std::time::SystemTime;
|
||||
|
||||
#[derive(Clone, Debug, Default, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PytestFixtureAt {
|
||||
/// The fixture name at the position, and the definition pytest uses for it.
|
||||
pub reference: Option<PytestFixtureReference>,
|
||||
/// At a place a fixture name goes (a test's parameters, a `usefixtures` string): the
|
||||
/// fixtures visible there, nearest first.
|
||||
pub completions: Option<Vec<PytestFixtureItem>>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PytestFixtureReference {
|
||||
pub name: String,
|
||||
pub range: Range,
|
||||
/// None when no visible module defines it (`request`, a fixture from a hook).
|
||||
pub definition: Option<Location>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PytestFixtureItem {
|
||||
pub name: String,
|
||||
/// The file defining it.
|
||||
pub path: IpcPath,
|
||||
}
|
||||
|
||||
/// Fixtures at `pos` of the Python document `path` / `text`.
|
||||
pub(crate) fn fixture_at(project: &Project, syntax: &Syntax, path: &Path, text: &str, pos: Pos) -> PytestFixtureAt {
|
||||
let own = syntax.pytest_module(&python(), text);
|
||||
let usage = own.use_at(pos).cloned();
|
||||
let slot = own.slot_at(pos).cloned();
|
||||
if usage.is_none() && slot.is_none() {
|
||||
return PytestFixtureAt::default();
|
||||
}
|
||||
let layers = Scope::new(project).layers(project, syntax, path, Arc::new(own));
|
||||
let modules: Vec<&PytestModule> = layers.iter().map(|(_, m)| m.as_ref()).collect();
|
||||
let reference = usage.map(|u| {
|
||||
let found = resolve_fixture(&modules, &u.name, u.class.as_deref(), u.in_fixture.as_deref() == Some(&u.name));
|
||||
PytestFixtureReference {
|
||||
definition: found.map(|(l, f)| Location {
|
||||
path: IpcPath::from(layers[l].0.clone()),
|
||||
range: modules[l].fixtures[f].selection,
|
||||
uri: None,
|
||||
}),
|
||||
name: u.name,
|
||||
range: u.range,
|
||||
}
|
||||
});
|
||||
let completions = slot.map(|s| {
|
||||
visible_fixtures(&modules, s.class.as_deref())
|
||||
.into_iter()
|
||||
// `_name` fixtures are internal, as `pytest --fixtures` hides them.
|
||||
.filter(|&(l, f)| !modules[l].fixtures[f].name.starts_with('_'))
|
||||
.map(|(l, f)| PytestFixtureItem {
|
||||
name: modules[l].fixtures[f].name.clone(),
|
||||
path: IpcPath::from(layers[l].0.clone()),
|
||||
})
|
||||
.collect()
|
||||
});
|
||||
PytestFixtureAt { reference, completions }
|
||||
}
|
||||
|
||||
fn python() -> LanguageId {
|
||||
LanguageId::new("python")
|
||||
}
|
||||
|
||||
type Layer = (PathBuf, Arc<PytestModule>);
|
||||
|
||||
/// What every file of the project sees after its own `conftest.py` files: the folders
|
||||
/// `pytest_plugins` modules are found in, installed plugins and pytest's own modules.
|
||||
struct Scope {
|
||||
search: Vec<PathBuf>,
|
||||
tail: Vec<PathBuf>,
|
||||
}
|
||||
|
||||
impl Scope {
|
||||
fn new(project: &Project) -> Self {
|
||||
let packages = interpreter_site_packages(project);
|
||||
let mut search = super::python::paths(project);
|
||||
search.extend(packages.iter().cloned());
|
||||
// `pytest_plugins = ["pytester"]` names pytest's own optional plugins by their short name.
|
||||
search.extend(packages.iter().map(|p| p.join("_pytest")));
|
||||
let mut tail = Vec::new();
|
||||
for packages in &packages {
|
||||
tail.extend(
|
||||
entry_point_modules(packages).iter().filter_map(|m| module_file(m, std::slice::from_ref(packages))),
|
||||
);
|
||||
}
|
||||
for packages in &packages {
|
||||
tail.extend(builtin_modules(&packages.join("_pytest")));
|
||||
}
|
||||
Self { search, tail }
|
||||
}
|
||||
|
||||
/// The modules `path` sees, nearest first, `own` being its own: its `conftest.py` files up to
|
||||
/// the project root, the modules their `pytest_plugins` name, then installed plugins and pytest.
|
||||
fn layers(&self, project: &Project, syntax: &Syntax, path: &Path, own: Arc<PytestModule>) -> Vec<Layer> {
|
||||
let mut out: Vec<Layer> = vec![(path.to_path_buf(), own)];
|
||||
let mut dir = path.parent();
|
||||
while let Some(d) = dir.filter(|d| d.starts_with(&project.root)) {
|
||||
let conftest = d.join("conftest.py");
|
||||
if conftest != path
|
||||
&& let Some(m) = module_of(project, syntax, &conftest)
|
||||
{
|
||||
out.push((conftest, m));
|
||||
}
|
||||
dir = d.parent();
|
||||
}
|
||||
let named: Vec<String> = out.iter().flat_map(|(_, m)| m.plugins.clone()).collect();
|
||||
let extra =
|
||||
named.iter().filter_map(|module| module_file(module, &self.search)).chain(self.tail.iter().cloned());
|
||||
for file in extra.collect::<Vec<_>>() {
|
||||
if !out.iter().any(|(p, _)| *p == file)
|
||||
&& let Some(m) = module_of(project, syntax, &file)
|
||||
{
|
||||
out.push((file, m));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// A fixture definition: its file and the range of its name there.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
struct Definition {
|
||||
name: String,
|
||||
path: PathBuf,
|
||||
selection: Range,
|
||||
}
|
||||
|
||||
/// Where pytest finds the fixture `u` asks for, seen from `layers`.
|
||||
fn definition_of(layers: &[Layer], u: &ide_language::PytestFixtureUse) -> Option<Definition> {
|
||||
let modules: Vec<&PytestModule> = layers.iter().map(|(_, m)| m.as_ref()).collect();
|
||||
let (l, f) = resolve_fixture(&modules, &u.name, u.class.as_deref(), u.in_fixture.as_deref() == Some(&u.name))?;
|
||||
Some(Definition { name: u.name.clone(), path: layers[l].0.clone(), selection: modules[l].fixtures[f].selection })
|
||||
}
|
||||
|
||||
/// The fixture at `pos` of `path`: the one defined there, or the one a test asks for there.
|
||||
fn target_at(
|
||||
project: &Project,
|
||||
syntax: &Syntax,
|
||||
scope: &Scope,
|
||||
path: &Path,
|
||||
own: &Arc<PytestModule>,
|
||||
pos: Pos,
|
||||
) -> Option<Definition> {
|
||||
if let Some(f) = own.definition_at(pos) {
|
||||
let fixture = &own.fixtures[f];
|
||||
return Some(Definition { name: fixture.name.clone(), path: path.to_path_buf(), selection: fixture.selection });
|
||||
}
|
||||
let usage = own.use_at(pos)?;
|
||||
definition_of(&scope.layers(project, syntax, path, own.clone()), usage)
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PytestFixtureUsages {
|
||||
pub name: String,
|
||||
pub definition: Location,
|
||||
/// Defined in the project (not by a plugin or pytest): it may be renamed.
|
||||
pub in_project: bool,
|
||||
/// Every place that gets this fixture: parameters, `usefixtures` and `getfixturevalue` strings.
|
||||
pub usages: Vec<Location>,
|
||||
}
|
||||
|
||||
struct Usage {
|
||||
path: PathBuf,
|
||||
use_: ide_language::PytestFixtureUse,
|
||||
}
|
||||
|
||||
/// The fixture at `pos` of the Python document `path` / `text` and every place that gets it.
|
||||
pub(crate) fn fixture_usages(
|
||||
project: &Project,
|
||||
syntax: &Syntax,
|
||||
path: &Path,
|
||||
text: &str,
|
||||
pos: Pos,
|
||||
cancelled: &dyn Fn() -> bool,
|
||||
) -> IdeResult<Option<PytestFixtureUsages>> {
|
||||
let Some((target, usages)) = usages_of(project, syntax, path, text, pos, cancelled)? else { return Ok(None) };
|
||||
Ok(Some(PytestFixtureUsages {
|
||||
name: target.name.clone(),
|
||||
in_project: is_project_file(project, &target.path),
|
||||
definition: Location { path: IpcPath::from(target.path), range: target.selection, uri: None },
|
||||
usages: usages
|
||||
.into_iter()
|
||||
.map(|u| Location { path: IpcPath::from(u.path), range: u.use_.range, uri: None })
|
||||
.collect(),
|
||||
}))
|
||||
}
|
||||
|
||||
/// Rename of the fixture at `pos`: its definition (the `name=` string, else the function name),
|
||||
/// every place that gets it, and the uses of a renamed parameter in its function's body.
|
||||
pub(crate) fn rename_fixture(
|
||||
project: &Project,
|
||||
syntax: &Syntax,
|
||||
path: &Path,
|
||||
text: &str,
|
||||
pos: Pos,
|
||||
new_name: &str,
|
||||
cancelled: &dyn Fn() -> bool,
|
||||
) -> IdeResult<WorkspaceEdit> {
|
||||
let Some((target, usages)) = usages_of(project, syntax, path, text, pos, cancelled)? else {
|
||||
return Err(IdeError::invalid("No pytest fixture here"));
|
||||
};
|
||||
if !is_project_file(project, &target.path) {
|
||||
return Err(IdeError::invalid("The fixture is defined outside the project"));
|
||||
}
|
||||
let mut by_file: Vec<(PathBuf, Vec<TextEdit>)> = Vec::new();
|
||||
let mut edit = |file: &Path, range: Range| {
|
||||
let edits = match by_file.iter_mut().find(|(p, _)| p == file) {
|
||||
Some((_, edits)) => edits,
|
||||
None => {
|
||||
by_file.push((file.to_path_buf(), Vec::new()));
|
||||
&mut by_file.last_mut().expect("just pushed").1
|
||||
}
|
||||
};
|
||||
if !edits.iter().any(|e| e.range == range) {
|
||||
edits.push(TextEdit { range, new_text: new_name.to_owned() });
|
||||
}
|
||||
};
|
||||
edit(&target.path, target.selection);
|
||||
for u in &usages {
|
||||
edit(&u.path, u.use_.range);
|
||||
for &r in &u.use_.body {
|
||||
edit(&u.path, r);
|
||||
}
|
||||
}
|
||||
let files = by_file
|
||||
.into_iter()
|
||||
.map(|(p, mut edits)| {
|
||||
edits.sort_by_key(|e| e.range);
|
||||
FileEdit::Edit { path: IpcPath::from(p), edits, version: None }
|
||||
})
|
||||
.collect();
|
||||
Ok(WorkspaceEdit { files, preconditions: Vec::new() })
|
||||
}
|
||||
|
||||
fn usages_of(
|
||||
project: &Project,
|
||||
syntax: &Syntax,
|
||||
path: &Path,
|
||||
text: &str,
|
||||
pos: Pos,
|
||||
cancelled: &dyn Fn() -> bool,
|
||||
) -> IdeResult<Option<(Definition, Vec<Usage>)>> {
|
||||
let own = Arc::new(syntax.pytest_module(&python(), text));
|
||||
if own.definition_at(pos).is_none() && own.use_at(pos).is_none() {
|
||||
return Ok(None);
|
||||
}
|
||||
let scope = Scope::new(project);
|
||||
let Some(target) = target_at(project, syntax, &scope, path, &own, pos) else { return Ok(None) };
|
||||
let mut files = candidate_files(project, &target.path);
|
||||
if !files.iter().any(|f| f == path) && path.starts_with(&project.root) {
|
||||
files.push(path.to_path_buf());
|
||||
}
|
||||
let mut usages = Vec::new();
|
||||
for file in files {
|
||||
if cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
let module = if file == path { Some(own.clone()) } else { module_of(project, syntax, &file) };
|
||||
let Some(module) = module else { continue };
|
||||
if !module.uses.iter().any(|u| u.name == target.name) {
|
||||
continue;
|
||||
}
|
||||
let layers = scope.layers(project, syntax, &file, module.clone());
|
||||
for u in module.uses.iter().filter(|u| u.name == target.name) {
|
||||
if definition_of(&layers, u).as_ref() == Some(&target) {
|
||||
usages.push(Usage { path: file.clone(), use_: u.clone() });
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(Some((target, usages)))
|
||||
}
|
||||
|
||||
/// The files that may get a fixture defined in `definition`: that test module alone, the test
|
||||
/// modules and `conftest.py` files below a `conftest.py`, all of the project's for a plugin's.
|
||||
fn candidate_files(project: &Project, definition: &Path) -> Vec<PathBuf> {
|
||||
let in_project = is_project_file(project, definition);
|
||||
let is_conftest = definition.file_name().is_some_and(|n| n == "conftest.py");
|
||||
if in_project && !is_conftest {
|
||||
return vec![definition.to_path_buf()];
|
||||
}
|
||||
let dir = if in_project { definition.parent().unwrap_or(&project.root) } else { &project.root };
|
||||
let mut files = project.index.files_matching(dir, is_test_file, MAX_FILES).unwrap_or_default();
|
||||
files.sort();
|
||||
files
|
||||
}
|
||||
|
||||
const MAX_FILES: usize = 20_000;
|
||||
|
||||
/// A file of the project's own code: below its root, not in an installed package (a
|
||||
/// virtualenv inside the project holds pytest and its plugins).
|
||||
fn is_project_file(project: &Project, path: &Path) -> bool {
|
||||
path.starts_with(&project.root) && !path.components().any(|c| c.as_os_str() == "site-packages")
|
||||
}
|
||||
|
||||
/// `test_*.py`, `*_test.py` and `conftest.py`: the files pytest collects or loads.
|
||||
fn is_test_file(rel: &Path) -> bool {
|
||||
let Some(name) = rel.file_name().and_then(|n| n.to_str()) else { return false };
|
||||
let Some(stem) = name.strip_suffix(".py") else { return false };
|
||||
stem == "conftest" || stem.starts_with("test_") || stem.ends_with("_test")
|
||||
}
|
||||
|
||||
/// The `site-packages` of the project's interpreter: its virtualenv's, else its install prefix's.
|
||||
fn interpreter_site_packages(project: &Project) -> Vec<PathBuf> {
|
||||
let settings = project.settings.effective();
|
||||
let Some(python) = ide_sdk::apply::python_interpreter(&project.root, &settings) else { return Vec::new() };
|
||||
let prefix = ide_sdk::venv_of(&python).or_else(|| python.parent()?.parent().map(Path::to_path_buf));
|
||||
prefix.map(|p| site_packages(&p)).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// `pkg.mod` → `pkg/mod.py` or `pkg/mod/__init__.py` in the first folder that has it.
|
||||
fn module_file(module: &str, search: &[PathBuf]) -> Option<PathBuf> {
|
||||
let rel: PathBuf = module.split('.').collect();
|
||||
search.iter().find_map(|base| {
|
||||
let file = base.join(&rel).with_extension("py");
|
||||
let package = base.join(&rel).join("__init__.py");
|
||||
[file, package].into_iter().find(|p| p.is_file())
|
||||
})
|
||||
}
|
||||
|
||||
/// The modules of the `[pytest11]` entry points of the distributions in `site_packages`.
|
||||
fn entry_point_modules(site_packages: &Path) -> Vec<String> {
|
||||
let Ok(entries) = std::fs::read_dir(site_packages) else { return Vec::new() };
|
||||
let mut out = Vec::new();
|
||||
for entry in entries.flatten() {
|
||||
if !entry.file_name().to_string_lossy().ends_with(".dist-info") {
|
||||
continue;
|
||||
}
|
||||
let Ok(text) = std::fs::read_to_string(entry.path().join("entry_points.txt")) else { continue };
|
||||
out.extend(pytest11_modules(&text));
|
||||
}
|
||||
out.sort();
|
||||
out
|
||||
}
|
||||
|
||||
/// The modules of the `[pytest11]` section of an `entry_points.txt` (`name = module:attr`).
|
||||
fn pytest11_modules(text: &str) -> Vec<String> {
|
||||
let mut section = "";
|
||||
let mut out = Vec::new();
|
||||
for line in text.lines().map(str::trim) {
|
||||
if let Some(name) = line.strip_prefix('[').and_then(|l| l.strip_suffix(']')) {
|
||||
section = name;
|
||||
} else if section == "pytest11"
|
||||
&& let Some((_, value)) = line.split_once('=')
|
||||
{
|
||||
let module = value.trim().split(':').next().unwrap_or_default().trim();
|
||||
if !module.is_empty() {
|
||||
out.push(module.to_owned());
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// pytest's own plugins that are off unless `pytest_plugins` names them.
|
||||
const OPTIONAL_BUILTINS: [&str; 2] = ["pytester.py", "pytester_assertions.py"];
|
||||
|
||||
/// pytest's own modules that may define fixtures: `_pytest/*.py`, one level of subpackages.
|
||||
fn builtin_modules(dir: &Path) -> Vec<PathBuf> {
|
||||
let mut out = Vec::new();
|
||||
let Ok(entries) = std::fs::read_dir(dir) else { return out };
|
||||
for entry in entries.flatten() {
|
||||
let path = entry.path();
|
||||
if OPTIONAL_BUILTINS.iter().any(|name| entry.file_name() == *name) {
|
||||
continue;
|
||||
}
|
||||
if path.extension().is_some_and(|e| e == "py") {
|
||||
out.push(path);
|
||||
} else if path.is_dir() {
|
||||
out.extend(
|
||||
std::fs::read_dir(&path)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.flatten()
|
||||
.map(|e| e.path())
|
||||
.filter(|p| p.extension().is_some_and(|e| e == "py")),
|
||||
);
|
||||
}
|
||||
}
|
||||
out.sort();
|
||||
out
|
||||
}
|
||||
|
||||
/// A parsed file and the modification time and length it was read at.
|
||||
type Cached = (SystemTime, u64, Arc<PytestModule>);
|
||||
|
||||
/// The fixtures of a file: from its open editor, else from disk, parsed once per modification.
|
||||
fn module_of(project: &Project, syntax: &Syntax, path: &Path) -> Option<Arc<PytestModule>> {
|
||||
if let Some(text) = project.documents.text_of(path) {
|
||||
return Some(Arc::new(syntax.pytest_module(&python(), &text)));
|
||||
}
|
||||
static CACHE: LazyLock<Mutex<HashMap<PathBuf, Cached>>> = LazyLock::new(Default::default);
|
||||
let meta = std::fs::metadata(path).ok().filter(|m| m.is_file())?;
|
||||
if meta.len() > ide_vfs::LARGE_FILE_THRESHOLD {
|
||||
return None;
|
||||
}
|
||||
let stamp = (meta.modified().ok()?, meta.len());
|
||||
if let Some((time, len, m)) = CACHE.lock().ok()?.get(path)
|
||||
&& (*time, *len) == stamp
|
||||
{
|
||||
return Some(m.clone());
|
||||
}
|
||||
let text = std::fs::read_to_string(path).ok()?;
|
||||
let module = Arc::new(syntax.pytest_module(&python(), &ide_text::normalize_line_endings(&text)));
|
||||
CACHE.lock().ok()?.insert(path.to_path_buf(), (stamp.0, stamp.1, module.clone()));
|
||||
Some(module)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_files_are_the_ones_pytest_loads() {
|
||||
for (rel, expected) in [
|
||||
("tests/test_a.py", true),
|
||||
("a_test.py", true),
|
||||
("pkg/conftest.py", true),
|
||||
("pkg/helpers.py", false),
|
||||
("test_data.json", false),
|
||||
] {
|
||||
assert_eq!(is_test_file(Path::new(rel)), expected, "{rel}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_pytest11_entry_points() {
|
||||
let text =
|
||||
"[console_scripts]\nx = a:b\n\n[pytest11]\nmock = pytest_mock\nasyncio = pytest_asyncio.plugin:main\n";
|
||||
assert_eq!(pytest11_modules(text), ["pytest_mock", "pytest_asyncio.plugin"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn finds_module_files_and_packages() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
std::fs::create_dir_all(dir.path().join("pkg/sub")).unwrap();
|
||||
std::fs::write(dir.path().join("pkg/fixtures.py"), "").unwrap();
|
||||
std::fs::write(dir.path().join("pkg/sub/__init__.py"), "").unwrap();
|
||||
let search = [dir.path().to_path_buf()];
|
||||
assert_eq!(module_file("pkg.fixtures", &search), Some(dir.path().join("pkg/fixtures.py")));
|
||||
assert_eq!(module_file("pkg.sub", &search), Some(dir.path().join("pkg/sub/__init__.py")));
|
||||
assert_eq!(module_file("pkg.none", &search), None);
|
||||
}
|
||||
}
|
||||
@@ -52,29 +52,43 @@ pub(super) fn debug_python(config: &LaunchConfig) -> Option<String> {
|
||||
extra.get("python")?.as_str().map(str::to_owned)
|
||||
}
|
||||
|
||||
pub(super) fn prepare_debug(config: &mut LaunchConfig, paths: &[PathBuf]) -> IdeResult<()> {
|
||||
/// Adds the project's import paths, and the Plots tool window's backend (`plots`), to a debugpy
|
||||
/// launch's environment.
|
||||
pub(super) fn prepare_debug(
|
||||
config: &mut LaunchConfig,
|
||||
paths: &[PathBuf],
|
||||
plots: Option<&ide_run::plots::Plots>,
|
||||
) -> IdeResult<()> {
|
||||
// Adapter-specific env takes precedence over the common launch fields in DAP.
|
||||
let mut extra: Option<serde_json::Value> = config.extra_json.as_deref().and_then(|s| serde_json::from_str(s).ok());
|
||||
// A custom adapter may run on another host; local paths are not portable.
|
||||
if extra.as_ref().is_some_and(|e| e.get("debugServer").is_some()) {
|
||||
return Ok(());
|
||||
}
|
||||
let plots = plots.filter(|_| !config.env.contains_key("MPLBACKEND"));
|
||||
if let Some(env) = extra.as_mut().and_then(|e| e.get_mut("env")) {
|
||||
if env.is_null() {
|
||||
*env = serde_json::json!({});
|
||||
}
|
||||
if !env.is_object() {
|
||||
let Some(object) = env.as_object_mut() else {
|
||||
return Ok(());
|
||||
};
|
||||
let mut vars: BTreeMap<String, String> =
|
||||
object.iter().filter_map(|(k, v)| Some((k.clone(), v.as_str()?.to_owned()))).collect();
|
||||
let inherit = !vars.contains_key("PYTHONPATH");
|
||||
ide_run::python_path::extend(&mut vars, paths, inherit)?;
|
||||
if let Some(plots) = plots {
|
||||
ide_run::plots::add(&mut vars, plots, true)?;
|
||||
}
|
||||
let mut vars = BTreeMap::new();
|
||||
if let Some(value) = env.get("PYTHONPATH").and_then(|v| v.as_str()) {
|
||||
vars.insert("PYTHONPATH".into(), value.to_owned());
|
||||
for (key, value) in vars {
|
||||
object.insert(key, serde_json::json!(value));
|
||||
}
|
||||
ide_run::python_path::extend(&mut vars, paths, env.get("PYTHONPATH").is_none())?;
|
||||
env["PYTHONPATH"] = serde_json::json!(vars["PYTHONPATH"]);
|
||||
config.extra_json = extra.map(|e| e.to_string());
|
||||
} else {
|
||||
ide_run::python_path::extend(&mut config.env, paths, true)?;
|
||||
if let Some(plots) = plots {
|
||||
ide_run::plots::add(&mut config.env, plots, true)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -97,11 +111,11 @@ mod tests {
|
||||
extra_json: Some(serde_json::json!({"env": null, "debugServer": "remote:5678"}).to_string()),
|
||||
};
|
||||
let before = config.extra_json.clone();
|
||||
prepare_debug(&mut config, std::slice::from_ref(&root)).unwrap();
|
||||
prepare_debug(&mut config, std::slice::from_ref(&root), None).unwrap();
|
||||
assert_eq!(config.extra_json, before);
|
||||
assert!(config.env.is_empty());
|
||||
config.extra_json = Some(serde_json::json!({"env": null}).to_string());
|
||||
prepare_debug(&mut config, std::slice::from_ref(&root)).unwrap();
|
||||
prepare_debug(&mut config, std::slice::from_ref(&root), None).unwrap();
|
||||
let value: serde_json::Value = serde_json::from_str(config.extra_json.as_deref().unwrap()).unwrap();
|
||||
let paths = std::env::split_paths(value["env"]["PYTHONPATH"].as_str().unwrap()).collect::<Vec<_>>();
|
||||
assert_eq!(paths[0], root);
|
||||
@@ -123,7 +137,7 @@ mod tests {
|
||||
env: vars.clone(),
|
||||
extra_json: extra.then(|| serde_json::json!({"env": vars}).to_string()),
|
||||
};
|
||||
prepare_debug(&mut config, std::slice::from_ref(&root)).unwrap();
|
||||
prepare_debug(&mut config, std::slice::from_ref(&root), None).unwrap();
|
||||
let vars: BTreeMap<String, String> = if extra {
|
||||
let value: serde_json::Value = serde_json::from_str(config.extra_json.as_deref().unwrap()).unwrap();
|
||||
serde_json::from_value(value["env"].clone()).unwrap()
|
||||
|
||||
@@ -6,8 +6,9 @@ use ide_command::command;
|
||||
use ide_core::{FileEdit, IdeResult, RequestId, WorkspaceEdit};
|
||||
use ide_language::Syntax;
|
||||
use ide_lsp::types::FileRenameEdits;
|
||||
use ide_workspace::file_moves::moved_path;
|
||||
use ide_workspace::roots::{ProjectRoots, RootKind};
|
||||
use ide_workspace::Documents;
|
||||
use ide_workspace::file_moves::{moved_path, read_text};
|
||||
use ide_workspace::roots::{PYTHON_FILES, ProjectRoots, RootKind, SourceFolder};
|
||||
use ide_workspace::{FileMove, UndoOutcome};
|
||||
use parking_lot::Mutex;
|
||||
use std::path::{Path, PathBuf};
|
||||
@@ -18,7 +19,8 @@ fn pairs(moves: &[FileMove]) -> Vec<(PathBuf, PathBuf)> {
|
||||
moves.iter().map(|m| (m.from.to_path_buf(), m.to.to_path_buf())).collect()
|
||||
}
|
||||
|
||||
/// `workspace/willRenameFiles` on every interested server (before the move). Cancellable.
|
||||
/// `workspace/willRenameFiles` on every interested server (before the move), plus the
|
||||
/// Python import updates the IDE makes itself. Cancellable.
|
||||
#[command(trust = always)]
|
||||
pub async fn refactor_file_move_edits(
|
||||
host: &Host,
|
||||
@@ -28,46 +30,72 @@ pub async fn refactor_file_move_edits(
|
||||
) -> IdeResult<FileRenameEdits> {
|
||||
let project = host.project(window)?;
|
||||
let token = host.begin_request(request);
|
||||
let result = project.lsp.will_rename_files(&pairs(&moves), token.clone()).await;
|
||||
host.end_request(request);
|
||||
let mut result = result?;
|
||||
let syntax = host.syntax();
|
||||
blocking(move || {
|
||||
// basedpyright has no `workspace/willRenameFiles`; a Python server that answered wins.
|
||||
if !result.edit.files.iter().any(|f| matches!(f, FileEdit::Edit { path, .. } if is_python(path))) {
|
||||
let python = python_import_edits(&project, &syntax, &moves, &|| token.is_cancelled());
|
||||
result.edit.files.extend(python.files);
|
||||
}
|
||||
project.documents.prepare_workspace_edit(&mut result.edit)?;
|
||||
Ok(result)
|
||||
})
|
||||
.await
|
||||
let result = async {
|
||||
let mut result = project.lsp.will_rename_files(&pairs(&moves), token.clone()).await?;
|
||||
blocking(move || {
|
||||
// basedpyright has no `workspace/willRenameFiles`; a Python server that answered wins.
|
||||
if !result.edit.files.iter().any(|f| matches!(f, FileEdit::Edit { path, .. } if is_python(path))) {
|
||||
let python = python_import_edits(
|
||||
&project.root,
|
||||
&project.roots(),
|
||||
&project.exclude_globs(),
|
||||
&project.documents,
|
||||
&syntax,
|
||||
&moves,
|
||||
&|| token.is_cancelled(),
|
||||
);
|
||||
result.edit.files.extend(python.files);
|
||||
}
|
||||
if token.is_cancelled() {
|
||||
return Err(ide_core::IdeError::cancelled());
|
||||
}
|
||||
project.documents.prepare_workspace_edit(&mut result.edit)?;
|
||||
Ok(result)
|
||||
})
|
||||
.await
|
||||
}
|
||||
.await;
|
||||
host.end_request(request);
|
||||
result
|
||||
}
|
||||
|
||||
fn is_python(path: &Path) -> bool {
|
||||
path.extension().is_some_and(|e| e == "py" || e == "pyi")
|
||||
}
|
||||
|
||||
/// The dotted name of a Python module file or package folder, from its project's Python roots
|
||||
/// (`src/a/b.py` → `a.b` in a `src` layout).
|
||||
fn python_module(root: &Path, roots: &ProjectRoots, path: &Path, is_dir: bool) -> Option<String> {
|
||||
let rel = path.strip_prefix(root).ok()?.to_string_lossy().replace('\\', "/");
|
||||
let base = roots
|
||||
.root_for(&rel)
|
||||
.filter(|r| matches!(r.kind, RootKind::Source | RootKind::Test))
|
||||
.map_or("", |r| r.path.as_str());
|
||||
/// The folders Python imports modules from: source and test roots of Python projects (or marked
|
||||
/// by the user), else the project root. Other languages' roots (`frontend/src`) don't count.
|
||||
fn python_root<'a>(roots: &'a ProjectRoots, rel: &str) -> &'a str {
|
||||
let python = |r: &&SourceFolder| {
|
||||
matches!(r.kind, RootKind::Source | RootKind::Test)
|
||||
&& r.detected_from.as_deref().is_none_or(|f| PYTHON_FILES.iter().any(|p| f.rsplit('/').next() == Some(*p)))
|
||||
};
|
||||
let inside = |r: &&SourceFolder| r.path.is_empty() || rel == r.path || rel.starts_with(&format!("{}/", r.path));
|
||||
roots.roots.iter().filter(python).filter(inside).max_by_key(|r| r.path.len()).map_or("", |r| r.path.as_str())
|
||||
}
|
||||
|
||||
fn rel_path(root: &Path, path: &Path) -> Option<String> {
|
||||
Some(path.strip_prefix(root).ok()?.to_string_lossy().replace('\\', "/"))
|
||||
}
|
||||
|
||||
/// The dotted name of a Python module file or package folder and the root it is imported from
|
||||
/// (`src/a/b.py` → `a.b` from `src` in a `src` layout).
|
||||
fn python_module(root: &Path, roots: &ProjectRoots, path: &Path, is_dir: bool) -> Option<(String, String)> {
|
||||
let rel = rel_path(root, path)?;
|
||||
let base = python_root(roots, &rel);
|
||||
let inner = if base.is_empty() { rel.as_str() } else { rel.strip_prefix(base)?.trim_start_matches('/') };
|
||||
let inner = if is_dir { inner } else { inner.strip_suffix(".py").or_else(|| inner.strip_suffix(".pyi"))? };
|
||||
let inner = inner.strip_suffix("/__init__").unwrap_or(inner);
|
||||
let valid = |s: &str| {
|
||||
s.chars().next().is_some_and(|c| !c.is_ascii_digit()) && s.chars().all(|c| c == '_' || c.is_alphanumeric())
|
||||
};
|
||||
(!inner.is_empty() && inner.split('/').all(valid)).then(|| inner.replace('/', "."))
|
||||
(!inner.is_empty() && inner.split('/').all(valid)).then(|| (inner.replace('/', "."), base.to_owned()))
|
||||
}
|
||||
|
||||
/// The package relative imports in `file` start from.
|
||||
fn python_package(root: &Path, roots: &ProjectRoots, file: &Path) -> String {
|
||||
let Some(module) = python_module(root, roots, file, false) else { return String::new() };
|
||||
let Some((module, _)) = python_module(root, roots, file, false) else { return String::new() };
|
||||
if file.file_stem().is_some_and(|s| s == "__init__") {
|
||||
module
|
||||
} else {
|
||||
@@ -75,52 +103,91 @@ fn python_package(root: &Path, roots: &ProjectRoots, file: &Path) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `dir` holds Python modules (a package or namespace package), at any depth.
|
||||
fn has_python(dir: &Path) -> bool {
|
||||
let Ok(entries) = std::fs::read_dir(dir) else { return false };
|
||||
entries.flatten().any(|e| {
|
||||
let path = e.path();
|
||||
let name = e.file_name();
|
||||
let name = name.to_string_lossy();
|
||||
if e.file_type().is_ok_and(|t| t.is_dir()) {
|
||||
!name.starts_with('.') && !matches!(name.as_ref(), "node_modules" | "__pycache__") && has_python(&path)
|
||||
} else {
|
||||
is_python(&path)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Import updates in the project's Python files for `moves` (paths before the move).
|
||||
fn python_import_edits(
|
||||
project: &crate::project::Project,
|
||||
root: &Path,
|
||||
roots: &ProjectRoots,
|
||||
excludes: &[String],
|
||||
documents: &Documents,
|
||||
syntax: &Syntax,
|
||||
moves: &[FileMove],
|
||||
cancelled: &(dyn Fn() -> bool + Sync),
|
||||
) -> WorkspaceEdit {
|
||||
let root = &project.root;
|
||||
let roots = project.roots();
|
||||
let renames: Vec<(String, String)> = moves
|
||||
.iter()
|
||||
.filter_map(|m| {
|
||||
let is_dir = m.from.is_dir();
|
||||
if !is_dir && (!is_python(&m.from) || m.from.file_stem().is_some_and(|s| s == "__init__")) {
|
||||
return None;
|
||||
}
|
||||
let old = python_module(root, &roots, &m.from, is_dir)?;
|
||||
let new = python_module(root, &roots, &m.to, is_dir)?;
|
||||
(old != new).then_some((old, new))
|
||||
})
|
||||
.collect();
|
||||
// (old, new, root the old module is imported from)
|
||||
let mut renames: Vec<(String, String, String)> = Vec::new();
|
||||
for m in moves {
|
||||
let is_dir = m.from.is_dir();
|
||||
let module = if is_dir {
|
||||
has_python(&m.from)
|
||||
} else {
|
||||
let stub_only = m.from.extension().is_some_and(|e| e == "pyi")
|
||||
&& !moves.iter().any(|o| *o.from == m.from.with_extension("py"));
|
||||
// A stub may describe a compiled module that stays where it is.
|
||||
is_python(&m.from) && !stub_only && m.from.file_stem().is_some_and(|s| s != "__init__")
|
||||
};
|
||||
if !module {
|
||||
continue;
|
||||
}
|
||||
let (Some((old, base)), Some((new, _))) =
|
||||
(python_module(root, roots, &m.from, is_dir), python_module(root, roots, &m.to, is_dir))
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
if old != new && !renames.iter().any(|r| r.0 == old) {
|
||||
renames.push((old, new, base));
|
||||
}
|
||||
}
|
||||
if renames.is_empty() {
|
||||
return WorkspaceEdit::default();
|
||||
}
|
||||
let names: Vec<&str> = renames.iter().map(|(old, _)| old.rsplit('.').next().unwrap_or(old)).collect();
|
||||
// `import utils` in `backend/app.py` means `backend/utils.py`, not `backend/tests/utils.py`.
|
||||
let shadowed = |base: &str, module: &str| {
|
||||
let p = root.join(base).join(module.replace('.', "/"));
|
||||
p.with_extension("py").is_file() || p.with_extension("pyi").is_file() || p.is_dir()
|
||||
};
|
||||
let names: Vec<&str> = renames.iter().map(|(old, ..)| old.rsplit('.').next().unwrap_or(old)).collect();
|
||||
let found: Mutex<Vec<(PathBuf, Vec<ide_core::TextEdit>)>> = Mutex::new(Vec::new());
|
||||
ide_vfs::walk_files(root, &project.exclude_globs(), |path| {
|
||||
ide_vfs::walk_files(root, excludes, |path| {
|
||||
if cancelled() || !is_python(path) {
|
||||
return;
|
||||
}
|
||||
let moved = moved_path(path, moves);
|
||||
let text = match project.documents.text_of(path) {
|
||||
Some(t) => t,
|
||||
None => match std::fs::read_to_string(path) {
|
||||
Ok(t) => t,
|
||||
Err(_) => return,
|
||||
},
|
||||
};
|
||||
if moved == path && !names.iter().any(|n| text.contains(n)) {
|
||||
return;
|
||||
if moved == path {
|
||||
let Ok(bytes) = std::fs::read(path) else { return };
|
||||
let raw = String::from_utf8_lossy(&bytes);
|
||||
if !names.iter().any(|n| raw.contains(n)) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
// Through the documents layer: unsaved edits, BOM and encodings as the edits will see them.
|
||||
let Ok(text) = read_text(documents, path) else { return };
|
||||
let Some(rel) = rel_path(root, path) else { return };
|
||||
let base = python_root(roots, &rel);
|
||||
let visible: Vec<(String, String)> = renames
|
||||
.iter()
|
||||
.filter(|(old, _, from)| from == base || !shadowed(base, old))
|
||||
.map(|(old, new, _)| (old.clone(), new.clone()))
|
||||
.collect();
|
||||
let edits = syntax.python_import_edits(
|
||||
&text,
|
||||
&python_package(root, &roots, path),
|
||||
&python_package(root, &roots, &moved),
|
||||
&renames,
|
||||
&python_package(root, roots, path),
|
||||
&python_package(root, roots, &moved),
|
||||
&visible,
|
||||
);
|
||||
if !edits.is_empty() {
|
||||
found.lock().push((path.to_path_buf(), edits));
|
||||
@@ -213,7 +280,6 @@ ide_command::domain!(
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use ide_workspace::roots::SourceFolder;
|
||||
|
||||
#[test]
|
||||
fn python_module_names_follow_the_roots() {
|
||||
@@ -223,7 +289,7 @@ mod tests {
|
||||
vec![folder("src", RootKind::Source), folder("tests", RootKind::Test)],
|
||||
&Default::default(),
|
||||
);
|
||||
let name = |p: &str, dir| python_module(root, &roots, &root.join(p), dir);
|
||||
let name = |p: &str, dir| python_module(root, &roots, &root.join(p), dir).map(|(m, _)| m);
|
||||
assert_eq!(name("src/tasks/models.py", false).as_deref(), Some("tasks.models"));
|
||||
assert_eq!(name("src/tasks/__init__.py", false).as_deref(), Some("tasks"));
|
||||
assert_eq!(name("src/tasks", true).as_deref(), Some("tasks"));
|
||||
@@ -234,4 +300,54 @@ mod tests {
|
||||
assert_eq!(python_package(root, &roots, &root.join("src/tasks/cli.py")), "tasks");
|
||||
assert_eq!(python_package(root, &roots, &root.join("src/tasks/__init__.py")), "tasks");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn python_imports_in_a_mixed_project() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
let write = |p: &str, text: &str| {
|
||||
let path = root.join(p);
|
||||
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
std::fs::write(path, text).unwrap();
|
||||
};
|
||||
write("backend/pyproject.toml", "[project]\nname = \"b\"\n");
|
||||
write("backend/utils.py", "");
|
||||
write("backend/app.py", "import utils\nfrom api import routes\n");
|
||||
write("backend/api/__init__.py", "");
|
||||
write("backend/api/routes.py", "");
|
||||
write("backend/bom.py", "\u{feff}from api import routes\n");
|
||||
write("backend/tests/utils.py", "");
|
||||
write("backend/tests/test_a.py", "import utils\n");
|
||||
write("backend/native/_ext.pyi", "");
|
||||
write("backend/uses_ext.py", "from native import _ext\n");
|
||||
write("frontend/package.json", "{}");
|
||||
write("frontend/src/api/index.js", "");
|
||||
let roots = ProjectRoots::compute(ide_workspace::roots::detect(root), &Default::default());
|
||||
let documents = Documents::new(
|
||||
std::sync::Arc::new(|_| {}),
|
||||
Box::new(|_: &Path, _: Option<&str>| ide_core::LanguageId::new("python")),
|
||||
);
|
||||
let edits = |from: &str, to: &str| {
|
||||
let moves = vec![FileMove { from: root.join(from).into(), to: root.join(to).into() }];
|
||||
let edit = python_import_edits(root, &roots, &[], &documents, &Syntax::new(), &moves, &|| false);
|
||||
edit.files
|
||||
.into_iter()
|
||||
.filter_map(|f| match f {
|
||||
FileEdit::Edit { path, edits, .. } => Some((rel_path(root, &path).unwrap(), edits)),
|
||||
_ => None,
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
// Not Python: a JavaScript folder of the same name.
|
||||
assert!(edits("frontend/src/api", "frontend/src/client").is_empty());
|
||||
// Same-named modules of different roots.
|
||||
let files = edits("backend/tests/utils.py", "backend/tests/helpers.py");
|
||||
assert_eq!(files.iter().map(|f| f.0.as_str()).collect::<Vec<_>>(), ["backend/tests/test_a.py"]);
|
||||
// A BOM doesn't shift the edit.
|
||||
let files = edits("backend/api", "backend/web");
|
||||
assert_eq!(files.iter().map(|f| f.0.as_str()).collect::<Vec<_>>(), ["backend/app.py", "backend/bom.py"]);
|
||||
assert_eq!(files[1].1[0].range.start, ide_core::Pos { line: 0, col: 5 });
|
||||
// A stub without its module.
|
||||
assert!(edits("backend/native/_ext.pyi", "backend/native/_ext2.pyi").is_empty());
|
||||
}
|
||||
}
|
||||
@@ -334,10 +334,19 @@ pub async fn run_start(
|
||||
Some(agent) => agent.wrap_output(on_output),
|
||||
None => on_output,
|
||||
};
|
||||
// `execute_run_configuration` asked the Run tool window to start it.
|
||||
let mcp = crate::mcp::run::configs::config_run_launch(&config);
|
||||
let on_output = match &mcp {
|
||||
Some(mcp) => mcp.wrap_output(on_output),
|
||||
None => on_output,
|
||||
};
|
||||
let result = start_inner(host, window, config, on_output, agent.as_ref(), &cancel).await;
|
||||
if let Some(agent) = &agent {
|
||||
agent.started(&result);
|
||||
}
|
||||
if let Some(mcp) = &mcp {
|
||||
mcp.started(&result);
|
||||
}
|
||||
if let Some(id) = request {
|
||||
host.end_request(id);
|
||||
}
|
||||
@@ -429,6 +438,7 @@ async fn start_inner(
|
||||
encoding: Some(settings.console.encoding).filter(|e| !e.trim().is_empty()),
|
||||
python_paths: Vec::new(),
|
||||
ruby_reporter: None,
|
||||
plots: None,
|
||||
},
|
||||
sink,
|
||||
Box::new(move |c| on_output(c)),
|
||||
@@ -445,6 +455,7 @@ async fn start_inner(
|
||||
python_paths: Vec::new(),
|
||||
// A folder on this machine: not in the container.
|
||||
ruby_reporter: None,
|
||||
plots: None,
|
||||
};
|
||||
project.require_trust()?;
|
||||
return host.processes.start(
|
||||
@@ -493,7 +504,7 @@ async fn start_inner(
|
||||
}
|
||||
// A Python configuration pointing at a missing interpreter fails in the depth of
|
||||
// process spawn otherwise; name the cause and the fix like PyCharm's "Invalid SDK".
|
||||
let is_python = matches!(config.kind.as_str(), "python" | "pytest" | "unittest" | "django-test");
|
||||
let is_python = matches!(config.kind.as_str(), "python" | "pytest" | "unittest" | "doctest" | "django-test");
|
||||
if is_python && Path::new(&config.command).components().count() > 1 {
|
||||
let cwd = project.root.join(config.cwd.as_deref().unwrap_or(Path::new("")));
|
||||
let executable = ide_core::project_roots::resolve(&cwd, Path::new(&config.command));
|
||||
@@ -542,6 +553,7 @@ async fn start_inner(
|
||||
encoding: Some(encoding).filter(|e| !e.trim().is_empty()),
|
||||
python_paths,
|
||||
ruby_reporter: ruby_reporter_dir(host, &config),
|
||||
plots: if is_python { super::plots::prepare(host, &project) } else { None },
|
||||
};
|
||||
project.require_trust()?;
|
||||
if config.kind == "go" && matches!(config.args.first().map(String::as_str), Some("mod" | "work")) {
|
||||
|
||||
@@ -432,7 +432,8 @@ pub async fn sdk_python_package_index(
|
||||
result
|
||||
}
|
||||
|
||||
/// Installs (`uninstall = false`) or removes a package; output streams through `on_output`.
|
||||
/// Installs (`uninstall = false`, in editable mode with `editable`) or removes a package; output
|
||||
/// streams through `on_output`.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[command(trust = outside_restricted)]
|
||||
pub async fn sdk_python_pip(
|
||||
@@ -442,6 +443,7 @@ pub async fn sdk_python_pip(
|
||||
requirement: String,
|
||||
uninstall: bool,
|
||||
upgrade: bool,
|
||||
editable: bool,
|
||||
request: RequestId,
|
||||
on_output: Channel<String>,
|
||||
) -> IdeResult<()> {
|
||||
@@ -455,7 +457,15 @@ pub async fn sdk_python_pip(
|
||||
if uninstall {
|
||||
ide_sdk::python::uninstall_package(&python, &requirement, &cancel, &send)
|
||||
} else {
|
||||
ide_sdk::python::install_package(&python, &requirement, upgrade, project_root.as_deref(), &cancel, &send)
|
||||
ide_sdk::python::install_package(
|
||||
&python,
|
||||
&requirement,
|
||||
upgrade,
|
||||
editable,
|
||||
project_root.as_deref(),
|
||||
&cancel,
|
||||
&send,
|
||||
)
|
||||
}
|
||||
})
|
||||
.await;
|
||||
|
||||
@@ -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,
|
||||
@@ -85,6 +87,8 @@ pub struct Project {
|
||||
pub(crate) git_metadata: Option<Arc<ide_vcs::MetadataWatch>>,
|
||||
/// Picks up data sources edited on disk outside the Database tool window.
|
||||
_db_sources_watch: Option<ide_db::SourcesWatch>,
|
||||
/// The Plots tool window's folder watch, started by the first Python run ([`crate::ops::plots`]).
|
||||
pub(crate) plots_watch: Mutex<Option<notify::RecommendedWatcher>>,
|
||||
/// A LightEdit window's loose files ([`Host::open_light`]): global settings only,
|
||||
/// nothing indexed, no language servers, repositories or project services.
|
||||
pub light: bool,
|
||||
@@ -211,6 +215,8 @@ impl Host {
|
||||
crate::ts_code_style::configure(cfg, server_root, &effective);
|
||||
ide_sdk::apply::configure_vue_module_resolution(cfg, &data_dir);
|
||||
ide_sdk::apply::configure_path_aliases(cfg, server_root, &data_dir);
|
||||
let css_modules = ide_tools::managed_npm_plugin(&data_dir, "css-modules-kit");
|
||||
ide_sdk::apply::configure_css_modules(cfg, server_root, css_modules.as_deref());
|
||||
// After the global plugins: they keep the IDE's copies.
|
||||
ide_sdk::apply::configure_tsconfig_plugins(cfg, server_root, &data_dir);
|
||||
let container_python = effective.languages.python.run_target().is_some();
|
||||
@@ -362,8 +368,13 @@ impl Host {
|
||||
}
|
||||
{
|
||||
let settings = settings.clone();
|
||||
let data_dir = self.local_data_dir.clone();
|
||||
lsp.set_servers_hook(Box::new(move |language, defined| {
|
||||
ide_sdk::apply::language_servers(language.as_str(), defined, &settings.effective())
|
||||
let mut servers = ide_sdk::apply::language_servers(language.as_str(), defined, &settings.effective());
|
||||
if language.as_str() == "css" && ide_tools::managed_npm_plugin(&data_dir, "css-modules-kit").is_none() {
|
||||
ide_sdk::apply::drop_css_modules_route(&mut servers);
|
||||
}
|
||||
servers
|
||||
}));
|
||||
}
|
||||
{
|
||||
@@ -664,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(),
|
||||
@@ -706,6 +718,7 @@ impl Host {
|
||||
_scratch_watcher: scratch_watcher,
|
||||
git_metadata,
|
||||
_db_sources_watch: db_sources_watch,
|
||||
plots_watch: Mutex::default(),
|
||||
files_events_active,
|
||||
light: false,
|
||||
});
|
||||
@@ -935,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(),
|
||||
@@ -976,6 +990,7 @@ impl Host {
|
||||
_scratch_watcher: None,
|
||||
git_metadata: None,
|
||||
_db_sources_watch: None,
|
||||
plots_watch: Mutex::default(),
|
||||
files_events_active: Arc::new(AtomicBool::new(false)),
|
||||
light: true,
|
||||
root: dir,
|
||||
@@ -1044,9 +1059,8 @@ fn db_sources_watch(
|
||||
let Some(db) = weak.upgrade() else { return };
|
||||
let sink = sink.clone();
|
||||
runtime.spawn(async move {
|
||||
if db.reconcile_sources().await {
|
||||
sink.emit(IdeEvent::DbSourcesChanged);
|
||||
}
|
||||
db.reconcile_sources().await;
|
||||
sink.emit(IdeEvent::DbSourcesChanged);
|
||||
});
|
||||
}))
|
||||
.inspect_err(|e| tracing::warn!("{}", e.message))
|
||||
|
||||
@@ -364,6 +364,7 @@ pub fn client_accepts(event: &IdeEvent, trusted: bool) -> bool {
|
||||
| IdeEvent::UpdateAvailable { .. } => false,
|
||||
IdeEvent::McpRequest { .. } | IdeEvent::McpRequestClosed { .. } => trusted,
|
||||
IdeEvent::DbSourcesChanged
|
||||
| IdeEvent::PlotAdded { .. }
|
||||
| IdeEvent::ProjectTrustChanged { .. }
|
||||
| IdeEvent::Direnv { .. }
|
||||
| IdeEvent::FlutterDevices { .. }
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -9,12 +9,15 @@ async fn new_query_consoles_are_numbered_after_the_default_one() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let base = tmp.path();
|
||||
let host = Arc::new(Host::new(common::host_config(base)));
|
||||
let root = base.join("data/consoles/db/pg");
|
||||
let names = |paths: Vec<ide_core::IpcPath>| -> Vec<String> {
|
||||
paths.iter().map(|p| p.0.file_name().unwrap().to_string_lossy().into_owned()).collect()
|
||||
};
|
||||
assert!(db::db_consoles(&host, "pg".into(), false).unwrap().is_empty());
|
||||
// The first new console is the default one, then console_1, console_2…
|
||||
assert_eq!(names(db::db_consoles(&host, "pg".into(), true).unwrap()), ["console.sql"]);
|
||||
let first = db::db_consoles(&host, "pg".into(), true).unwrap();
|
||||
assert_eq!(names(first.clone()), ["console.sql"]);
|
||||
assert_eq!(first[0].0, root.join("console.sql"));
|
||||
assert_eq!(names(db::db_consoles(&host, "pg".into(), true).unwrap()), ["console.sql", "console_1.sql"]);
|
||||
let all = db::db_consoles(&host, "pg".into(), true).unwrap();
|
||||
assert_eq!(names(all.clone()), ["console.sql", "console_1.sql", "console_2.sql"]);
|
||||
@@ -26,3 +29,13 @@ async fn new_query_consoles_are_numbered_after_the_default_one() {
|
||||
assert!(db::db_consoles(&host, "pg:other".into(), false).unwrap().is_empty());
|
||||
assert!(db::db_consoles(&host, "../x".into(), true).is_err());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn consoles_root_is_the_directory_listed_in_the_project_view() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let base = tmp.path();
|
||||
let host = Arc::new(Host::new(common::host_config(base)));
|
||||
let root = db::db_consoles_dir(&host).unwrap();
|
||||
assert_eq!(root.0, base.join("data/consoles/db"));
|
||||
assert!(root.0.is_dir());
|
||||
}
|
||||
@@ -731,6 +731,73 @@ 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>>> {
|
||||
let started = Arc::new(std::sync::Mutex::new(Vec::new()));
|
||||
let (host, events, out) = (h.host.clone(), h.events.clone(), started.clone());
|
||||
tokio::spawn(async move {
|
||||
let mut handled = std::collections::HashSet::new();
|
||||
loop {
|
||||
let request = events.lock().unwrap().iter().find_map(|e| match e {
|
||||
IdeEvent::McpRequest { id, request: ide_core::event::McpUiRequest::RunConfiguration { config } }
|
||||
if !handled.contains(id) =>
|
||||
{
|
||||
Some((*id, config.clone()))
|
||||
}
|
||||
_ => None,
|
||||
});
|
||||
let Some((id, config)) = request else {
|
||||
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
|
||||
continue;
|
||||
};
|
||||
handled.insert(id);
|
||||
let config: ide_run::RunConfig = serde_json::from_value(config).unwrap();
|
||||
out.lock().unwrap().push(config.clone());
|
||||
let result =
|
||||
ide_host::ops::run::run_start(&host, "main", config, ide_host::ops::Channel::new(|_| {}), None).await;
|
||||
let error = result.err().map(|e| e.message);
|
||||
let _ = host.mcp_requests.answer("main", id, error.is_none(), error);
|
||||
}
|
||||
});
|
||||
started
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn execute_reports_output_exit_code_and_requires_confirmation() {
|
||||
let h = Harness::new();
|
||||
@@ -765,6 +832,7 @@ async fn execute_reports_output_exit_code_and_requires_confirmation() {
|
||||
assert!(error.contains("denied by the user"));
|
||||
assert!(h.host.processes.list().is_empty());
|
||||
h.events.lock().unwrap().clear();
|
||||
let tabs = config_run_window(&h);
|
||||
let run = h.json("execute_run_configuration", json!({"configurationName":"MCP test","timeout":10000}));
|
||||
let allow = async {
|
||||
let id = h.request().await;
|
||||
@@ -773,6 +841,39 @@ async fn execute_reports_output_exit_code_and_requires_confirmation() {
|
||||
let (result, ()) = tokio::join!(run, allow);
|
||||
assert_eq!(result["exitCode"], 7);
|
||||
assert!(result["output"].as_str().unwrap().contains("captured-output"));
|
||||
// It ran in a Run tool window tab, as the user's Run would.
|
||||
let tabs = tabs.lock().unwrap();
|
||||
assert_eq!(tabs.len(), 1);
|
||||
assert_eq!(tabs[0].name, "MCP test");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_project_without_a_window_runs_a_configuration_on_its_own() {
|
||||
let h = Harness::new();
|
||||
h.trust().await;
|
||||
let config = ide_run::RunConfig {
|
||||
id: "test".into(),
|
||||
name: "MCP test".into(),
|
||||
kind: "shell".into(),
|
||||
command: if cfg!(windows) { "echo windowless& exit 3" } else { "echo windowless; exit 3" }.into(),
|
||||
args: vec![],
|
||||
cwd: None,
|
||||
env: Default::default(),
|
||||
detected: false,
|
||||
is_test: false,
|
||||
debug_adapter: None,
|
||||
allow_parallel: false,
|
||||
extras: Default::default(),
|
||||
};
|
||||
ide_run::save_user_configs(&h.root, &[config]).unwrap();
|
||||
h.host
|
||||
.global_settings
|
||||
.set(ide_workspace::SettingsScope::Global, "mcpServer.runWithoutConfirmation", json!(true))
|
||||
.unwrap();
|
||||
let result = h.json("execute_run_configuration", json!({"configurationName":"MCP test","timeout":10000})).await;
|
||||
assert_eq!(result["exitCode"], 3, "{result}");
|
||||
assert!(result["output"].as_str().unwrap().contains("windowless"));
|
||||
assert!(!h.events.lock().unwrap().iter().any(|e| matches!(e, IdeEvent::McpRequest { .. })), "nothing asked");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
@@ -795,6 +896,7 @@ async fn a_configuration_left_running_is_stopped_by_its_run_id() {
|
||||
};
|
||||
ide_run::save_user_configs(&h.root, &[config]).unwrap();
|
||||
h.host.mcp_requests.set_ready("main", true);
|
||||
let _tabs = config_run_window(&h);
|
||||
let run = h.json("execute_run_configuration", json!({"configurationName":"Server","waitForExit":false}));
|
||||
let allow = async {
|
||||
let id = h.request().await;
|
||||
|
||||
@@ -429,9 +429,10 @@ fn gutter_actions_see_the_editors_window_project() {
|
||||
assert_eq!(actions.len(), 1);
|
||||
actions[0].1.argument.clone().unwrap()
|
||||
};
|
||||
// The outer project's window: the file is its, though the inner project holds it too.
|
||||
assert_eq!(argument(Some(&outer)), outer.to_string_lossy());
|
||||
assert_eq!(argument(Some(&inner)), inner.to_string_lossy());
|
||||
// The outer project's window: the file is its, though the inner project holds it too. Compared
|
||||
// as paths: the plugin sees Windows paths `/`-separated.
|
||||
assert_eq!(Path::new(&argument(Some(&outer))), outer);
|
||||
assert_eq!(Path::new(&argument(Some(&inner))), inner);
|
||||
// No window, or a root that is no open project: no invoking project.
|
||||
assert_eq!(argument(None), "gutter");
|
||||
assert_eq!(argument(Some(&tmp.path().join("elsewhere"))), "gutter");
|
||||
|
||||
@@ -52,7 +52,8 @@ fn the_plugins_configuration_completes_only_the_argument_under_the_caret() {
|
||||
let config = "plugin:test.run-anything:tasks";
|
||||
// Not provided until its program is approved.
|
||||
assert!(p.run_configuration_complete("main", &root, config, "arguments", "b", 1).is_err());
|
||||
p.choose_program(ID, "process:task", Some(&root), Some(Path::new("/bin/echo"))).unwrap();
|
||||
// Any approved executable will do; the test binary exists on every host.
|
||||
p.choose_program(ID, "process:task", Some(&root), Some(&std::env::current_exe().unwrap())).unwrap();
|
||||
assert!(p.run_detection().detect(&root).iter().any(|c| c.id == config));
|
||||
let complete = |text: &str, caret: u32| -> Vec<(String, String, u32, u32)> {
|
||||
p.run_configuration_complete("main", &root, config, "arguments", text, caret)
|
||||
|
||||
@@ -5,7 +5,7 @@ mod common;
|
||||
|
||||
use ide_core::{Pos, RequestId};
|
||||
use ide_host::{Host, ops};
|
||||
use ide_search::{ReplaceEvent, ReplaceSummary, ReplaceTarget, SearchQuery};
|
||||
use ide_search::{ReplaceEvent, ReplaceSummary, ReplaceTarget, SearchQuery, SearchScope};
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
fn query(pattern: &str, is_regex: bool) -> SearchQuery {
|
||||
@@ -145,9 +145,10 @@ async fn replace_all_covers_matches_past_the_limit() {
|
||||
async fn replace_all_saves_open_buffers_without_unsaved_changes() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(temp.path()).unwrap();
|
||||
let root = base.join("project");
|
||||
let scope = base.join("scope");
|
||||
let root = scope.join("project");
|
||||
std::fs::create_dir_all(&root).unwrap();
|
||||
for name in ["previewed.txt", "edited.txt", "closed.txt", "stale.txt"] {
|
||||
for name in ["previewed.txt", "edited.txt", "closed.txt"] {
|
||||
std::fs::write(root.join(name), "TOKEN\n").unwrap();
|
||||
}
|
||||
let host = Host::new(common::host_config(&base));
|
||||
@@ -157,14 +158,18 @@ async fn replace_all_saves_open_buffers_without_unsaved_changes() {
|
||||
project.documents.open(&root.join("previewed.txt")).unwrap();
|
||||
let edited = project.documents.open(&root.join("edited.txt")).unwrap().id;
|
||||
project.documents.replace_all(edited, "TOKEN\nmore\n").unwrap();
|
||||
// Open and clean, but changed on disk before the watcher reported it.
|
||||
let stale = project.documents.open(&root.join("stale.txt")).unwrap().id;
|
||||
std::fs::write(root.join("stale.txt"), "TOKEN\nexternal\n").unwrap();
|
||||
// Search the parent folder so Replace All also covers a clean buffer outside the project watch.
|
||||
let stale_path = scope.join("stale.txt");
|
||||
std::fs::write(&stale_path, "TOKEN\n").unwrap();
|
||||
let stale = project.documents.open(&stale_path).unwrap().id;
|
||||
std::fs::write(&stale_path, "TOKEN\nexternal\n").unwrap();
|
||||
let mut search = query("TOKEN", false);
|
||||
search.scope = SearchScope::Directory { path: scope.into() };
|
||||
ops::search::replace_in_files(
|
||||
&host,
|
||||
"main",
|
||||
RequestId::next(),
|
||||
query("TOKEN", false),
|
||||
search,
|
||||
"DONE".into(),
|
||||
false,
|
||||
vec![],
|
||||
@@ -178,7 +183,8 @@ async fn replace_all_saves_open_buffers_without_unsaved_changes() {
|
||||
assert_eq!(disk("closed.txt"), "DONE\n");
|
||||
assert_eq!(disk("edited.txt"), "TOKEN\n", "unsaved edits stay unsaved");
|
||||
assert_eq!(project.documents.text_snapshot(edited).unwrap().text, "DONE\nmore\n");
|
||||
assert_eq!(disk("stale.txt"), "TOKEN\nexternal\n", "the external change is kept");
|
||||
assert_eq!(std::fs::read_to_string(&stale_path).unwrap(), "TOKEN\nexternal\n", "the external change is kept");
|
||||
assert_eq!(project.documents.text_snapshot(stale).unwrap().text, "DONE\n");
|
||||
assert!(project.documents.is_dirty(stale).unwrap(), "the replacement stays unsaved");
|
||||
host.close_project("main");
|
||||
}
|
||||
|
||||
@@ -80,14 +80,23 @@ async fn serves_projects_files_documents_search_and_runs() {
|
||||
assert_eq!(opened["name"], "demo");
|
||||
assert_eq!(opened["trusted"], false);
|
||||
invoke(&peer, "index_status", json!({})).await.unwrap();
|
||||
let metrics = invoke(&peer, "host_metrics", json!({ "includeProcesses": true })).await.unwrap();
|
||||
assert!(metrics["cpuCores"].as_u64().unwrap() >= 1);
|
||||
assert_eq!(metrics["processes"][0]["label"], "Backend");
|
||||
assert_eq!(invoke(&peer, "lsp_servers", json!({})).await.unwrap(), json!([]));
|
||||
invoke(&peer, "lsp_resend_diagnostics", json!({})).await.unwrap();
|
||||
let files = invoke(&peer, "find_files", json!({"query": "main", "limit": 10})).await.unwrap();
|
||||
assert!(files.is_array());
|
||||
for command in
|
||||
["build_sync", "run_start", "sdk_locate_tools", "notebook_execute", "debug_start", "agent_refresh_models"]
|
||||
{
|
||||
let error = invoke(&peer, command, json!({})).await.unwrap_err();
|
||||
for (command, args) in [
|
||||
("build_sync", json!({})),
|
||||
("run_start", json!({})),
|
||||
("sdk_locate_tools", json!({})),
|
||||
("notebook_execute", json!({})),
|
||||
("debug_start", json!({})),
|
||||
("agent_refresh_models", json!({})),
|
||||
("host_end_process", json!({ "pid": 1 })),
|
||||
] {
|
||||
let error = invoke(&peer, command, args).await.unwrap_err();
|
||||
assert!(error.message.contains("Restricted Mode"), "{command}: {error:?}");
|
||||
}
|
||||
let call = Invoke { window: "unknown".into(), cmd: "coverage_collect".into(), args: json!({}) };
|
||||
@@ -271,6 +280,9 @@ async fn serves_projects_files_documents_search_and_runs() {
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(env["DOCKER_HOST"], "unix:///run/user/1/docker.sock");
|
||||
// Services › Docker commands are served by the project host too.
|
||||
assert!(Dispatcher::standard().commands().contains(&"docker_snapshot"));
|
||||
assert_eq!(invoke(&peer, "docker_settings", json!({})).await.unwrap()["connections"], json!([]));
|
||||
|
||||
// Real project-host ignore writes travel through the remote command dispatcher.
|
||||
assert!(Dispatcher::standard().commands().contains(&"vcs_add_to_ignore"));
|
||||
@@ -391,6 +403,8 @@ async fn local_deployment_runs_on_the_project_host() {
|
||||
"http_curl",
|
||||
"http_environment_file",
|
||||
"http_variable_definitions",
|
||||
"db_source_folders",
|
||||
"db_save_source_folders",
|
||||
"db_sources",
|
||||
"db_save_sources",
|
||||
"db_set_password",
|
||||
@@ -420,6 +434,7 @@ async fn local_deployment_runs_on_the_project_host() {
|
||||
"db_table_page",
|
||||
"db_apply_edits",
|
||||
"db_console_path",
|
||||
"db_consoles_dir",
|
||||
"db_consoles",
|
||||
"ssh_test",
|
||||
"ssh_set_secret",
|
||||
|
||||
@@ -29,7 +29,9 @@ pub use syntax::{
|
||||
set_external_syntax, shift_pos, shift_range,
|
||||
};
|
||||
pub use syntax::{
|
||||
MethodBody, PhpAlignment, PythonClassFacts, PythonFacts, PythonMethodFacts, PythonSuppression, bundler_aliases,
|
||||
MethodBody, PhpAlignment, PytestFixture, PytestFixtureSlot, PytestFixtureUse, PytestFixtureUseKind, PytestModule,
|
||||
PythonClassFacts, PythonFacts, PythonMethodFacts, PythonSuppression, bundler_aliases, resolve_fixture,
|
||||
visible_fixtures,
|
||||
};
|
||||
|
||||
/// Parsed form of `languages/<id>.toml`. Backend-only; the UI gets [`LanguageInfo`].
|
||||
|
||||
@@ -89,12 +89,42 @@ fn has_toml_table(file: &Path, table: &str) -> bool {
|
||||
table.split('.').try_fold(&value, |v, key| v.get(key)).is_some_and(toml::Value::is_table)
|
||||
}
|
||||
|
||||
/// `file` parses as JSON and has the dotted `key` with a value other than `null`:
|
||||
/// an object (`eslintConfig`) or a dependency's version (`dependencies.tailwindcss`).
|
||||
/// `file` parses as JSON (with comments: `tsconfig.json`) and has the dotted `key` with a value
|
||||
/// other than `null` or `false`: an object (`eslintConfig`), a dependency's version
|
||||
/// (`dependencies.tailwindcss`) or a switch that is on (`cmkOptions.enabled`).
|
||||
fn has_json_key(file: &Path, key: &str) -> bool {
|
||||
let Ok(text) = std::fs::read_to_string(file) else { return false };
|
||||
let Ok(value) = serde_json::from_str::<serde_json::Value>(&text) else { return false };
|
||||
key.split('.').try_fold(&value, |v, key| v.get(key)).is_some_and(|v| !v.is_null())
|
||||
json_key(file, key, 0).is_some_and(|v| !v.is_null() && v != serde_json::Value::Bool(false))
|
||||
}
|
||||
|
||||
/// The dotted `key` of the JSON `file`. A tsconfig.json / jsconfig.json without it inherits it
|
||||
/// through `extends` from a local file (`./base`, `../tsconfig.base.json`), the first one defining
|
||||
/// it winning, as CSS Modules Kit reads `cmkOptions`.
|
||||
fn json_key(file: &Path, key: &str, depth: usize) -> Option<serde_json::Value> {
|
||||
// ponytail: package `extends` (`@tsconfig/node20`) are not resolved; only local files.
|
||||
const MAX_DEPTH: usize = 8;
|
||||
let text = std::fs::read_to_string(file).ok()?;
|
||||
let value = serde_json::from_str::<serde_json::Value>(&ide_core::jsonc::strip(&text)).ok()?;
|
||||
if let Some(v) = key.split('.').try_fold(&value, |v, key| v.get(key)) {
|
||||
return Some(v.clone());
|
||||
}
|
||||
let name = file.file_name()?.to_string_lossy();
|
||||
if depth >= MAX_DEPTH || !(name.starts_with("tsconfig") || name.starts_with("jsconfig")) {
|
||||
return None;
|
||||
}
|
||||
let extends = match value.get("extends")? {
|
||||
serde_json::Value::String(s) => vec![s.as_str()],
|
||||
serde_json::Value::Array(a) => a.iter().filter_map(serde_json::Value::as_str).collect(),
|
||||
_ => return None,
|
||||
};
|
||||
extends.into_iter().filter(|e| e.starts_with("./") || e.starts_with("../")).find_map(|e| {
|
||||
let base = file.parent()?.join(e);
|
||||
let base = if base.is_file() {
|
||||
base
|
||||
} else {
|
||||
base.with_file_name(format!("{}.json", base.file_name()?.to_string_lossy()))
|
||||
};
|
||||
json_key(&base, key, depth + 1)
|
||||
})
|
||||
}
|
||||
|
||||
/// `path` is (or, after its creation or removal, was) a root marker of the
|
||||
@@ -191,6 +221,28 @@ mod tests {
|
||||
std::fs::write(dir.join("package.json"), r#"{"eslintConfig": null}"#).unwrap();
|
||||
assert!(!has_marker(dir, "package.json#eslintConfig"));
|
||||
assert!(is_marker_path(&dir.join("package.json"), marker));
|
||||
// tsconfig.json is JSON with comments; a switch that is off is no marker.
|
||||
let cmk = "tsconfig.json#cmkOptions.enabled";
|
||||
let tsconfig =
|
||||
|enabled: &str| format!("{{\n // CSS Modules Kit\n \"cmkOptions\": {{ \"enabled\": {enabled} }},\n}}");
|
||||
std::fs::write(dir.join("tsconfig.json"), tsconfig("true")).unwrap();
|
||||
assert!(has_marker(dir, cmk));
|
||||
std::fs::write(dir.join("tsconfig.json"), tsconfig("false")).unwrap();
|
||||
assert!(!has_marker(dir, cmk));
|
||||
// Inherited through a local `extends`, which the file itself can turn off.
|
||||
std::fs::create_dir_all(dir.join("app")).unwrap();
|
||||
std::fs::write(dir.join("tsconfig.json"), tsconfig("true")).unwrap();
|
||||
std::fs::write(dir.join("app/tsconfig.json"), r#"{ "extends": ["@tsconfig/strictest", "../tsconfig"] }"#)
|
||||
.unwrap();
|
||||
assert!(has_marker(&dir.join("app"), cmk));
|
||||
std::fs::write(
|
||||
dir.join("app/tsconfig.json"),
|
||||
r#"{ "extends": "../tsconfig.json", "cmkOptions": { "enabled": false } }"#,
|
||||
)
|
||||
.unwrap();
|
||||
assert!(!has_marker(&dir.join("app"), cmk));
|
||||
std::fs::write(dir.join("app/tsconfig.json"), r#"{ "extends": "./tsconfig.json" }"#).unwrap();
|
||||
assert!(!has_marker(&dir.join("app"), cmk), "a cycle ends");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
Loaded 100 of 645 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Заблокувати користувача