дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-11-29 13:52:36 +02:00
Порівняти коміти
361
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
25911a96fc | ||
|
|
dfea6d2c1e | ||
|
|
b9a25462ea | ||
|
|
04e68f6a12 | ||
|
|
4cfc794f60 | ||
|
|
8105dfd41a | ||
|
|
fca497d246 | ||
|
|
5cb73c5fd1 | ||
|
|
2b435c8440 | ||
|
|
db266643aa | ||
|
|
4812d28614 | ||
|
|
7c9f343ca4 | ||
|
|
d815a8ef44 | ||
|
|
d22c42e471 | ||
|
|
a111b32e11 | ||
|
|
f7141f6515 | ||
|
|
2d14368d2c | ||
|
|
5cbc4134a1 | ||
|
|
5a92145ad9 | ||
|
|
4354839584 | ||
|
|
e1a1becadd | ||
|
|
ad685ea19e | ||
|
|
5fb8f21c60 | ||
|
|
68abe345cc | ||
|
|
32381cc740 | ||
|
|
d897236bd7 | ||
|
|
68e3adde99 | ||
|
|
b5aa21e791 | ||
|
|
652798bc53 | ||
|
|
85e417001a | ||
|
|
8488eda54e | ||
|
|
d02a3592b0 | ||
|
|
439b7940a8 | ||
|
|
de92f3b367 | ||
|
|
5b904f7896 | ||
|
|
511d3f21bb | ||
|
|
972f18331e | ||
|
|
77e669c189 | ||
|
|
f2641b9697 | ||
|
|
3811dfb512 | ||
|
|
9e2da77162 | ||
|
|
3a89b94624 | ||
|
|
df40f0befe | ||
|
|
f151498e07 | ||
|
|
d959a2a583 | ||
|
|
7ab456b1e7 | ||
|
|
f8a9b204c6 | ||
|
|
be7a0cfa5b | ||
|
|
f40b645c8e | ||
|
|
e4ec1978d8 | ||
|
|
10242d2e58 | ||
|
|
fad9135f7a | ||
|
|
703b19b526 | ||
|
|
c3de09be78 | ||
|
|
6b61b15f00 | ||
|
|
19948c1426 | ||
|
|
e30ae3f6b8 | ||
|
|
9ee8f67e9f | ||
|
|
5b486f1588 | ||
|
|
6f8e8501c6 | ||
|
|
27c7323c0b | ||
|
|
41cb8f993e | ||
|
|
6e37a1a977 | ||
|
|
e99fcb0c49 | ||
|
|
2f31544d04 | ||
|
|
cbcd84f1d2 | ||
|
|
a3a56ab10d | ||
|
|
3961f38f46 | ||
|
|
4c5f4fa1e1 | ||
|
|
90734775b9 | ||
|
|
b53915e4b6 | ||
|
|
d361d7239a | ||
|
|
77a03ac197 | ||
|
|
f28a11d043 | ||
|
|
cdb4f9ab15 | ||
|
|
c709844c04 | ||
|
|
2cce84ad2c | ||
|
|
91dcd1b7eb | ||
|
|
3d275d5a3d | ||
|
|
cc49827793 | ||
|
|
7b3813f9e2 | ||
|
|
ebc6dc86f1 | ||
|
|
0ae1628678 | ||
|
|
dc8c45c77c | ||
|
|
e5f93b8526 | ||
|
|
73ba36381c | ||
|
|
3bc75e1de0 | ||
|
|
633bef2e69 | ||
|
|
9aa0718cf9 | ||
|
|
836a4405d6 | ||
|
|
952bd0b24b | ||
|
|
ac5e4b7259 | ||
|
|
2ea7d6c41b | ||
|
|
16e5cb5763 | ||
|
|
611440f77f | ||
|
|
482143769f | ||
|
|
176859987b | ||
|
|
6cdd52d31a | ||
|
|
90a0fd9901 | ||
|
|
9d92f47f94 | ||
|
|
68abd00a7f | ||
|
|
4c01ce4443 | ||
|
|
9da53322bc | ||
|
|
720b18861c | ||
|
|
802d9d26e2 | ||
|
|
fb97cdac03 | ||
|
|
caf909cab3 | ||
|
|
c88a4f403f | ||
|
|
98f163da75 | ||
|
|
5952e36d8b | ||
|
|
ad56613901 | ||
|
|
3fae4c0417 | ||
|
|
99fdea5c9a | ||
|
|
8aeac949b5 | ||
|
|
fa625d8cc7 | ||
|
|
b7b5bd5c50 | ||
|
|
2174a7278a | ||
|
|
7bbc12382e | ||
|
|
4fb1cae917 | ||
|
|
23bbed8bfe | ||
|
|
1880ac541c | ||
|
|
d698b50361 | ||
|
|
d5ba63e333 | ||
|
|
8108b440a6 | ||
|
|
4401ed3119 | ||
|
|
dbbdc4a085 | ||
|
|
85456e6930 | ||
|
|
b4d2859277 | ||
|
|
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 | ||
|
|
7ecccb3b75 | ||
|
|
7cbf17b10e | ||
|
|
cb0d02620d | ||
|
|
d6ca43cba4 | ||
|
|
165d4f7d76 | ||
|
|
5785ebadd8 | ||
|
|
0c67a4eea2 | ||
|
|
5e2deed81e | ||
|
|
cae7c05fb1 | ||
|
|
be83458161 | ||
|
|
661124d0d4 | ||
|
|
0dae111b2d | ||
|
|
61d269045b | ||
|
|
266d85fa1a | ||
|
|
f964d79e10 | ||
|
|
4a3eacff62 | ||
|
|
aebc2fe02d | ||
|
|
9b63aa9526 | ||
|
|
df07073886 | ||
|
|
3433ee951b | ||
|
|
8f5b281486 | ||
|
|
43aee8058c | ||
|
|
4016c3c905 | ||
|
|
e6cb7df653 | ||
|
|
2a26c82357 | ||
|
|
66f0bce92f | ||
|
|
dfbd13e2af | ||
|
|
944b57dead | ||
|
|
5bcb37492f | ||
|
|
d5bde9af67 | ||
|
|
5b3e2b7a3d | ||
|
|
dbb6fa51c3 | ||
|
|
3d1769ef00 | ||
|
|
c966429f92 | ||
|
|
dfcc05dd41 | ||
|
|
d41feefc07 | ||
|
|
f0fe910017 | ||
|
|
b932220b41 | ||
|
|
bcad8f61cb | ||
|
|
2cdcb888cf | ||
|
|
9ed0fd9fa7 | ||
|
|
fe76dc4573 | ||
|
|
45a75f782a | ||
|
|
bd1fd011e4 | ||
|
|
b44015b2ce | ||
|
|
0cce0a9840 | ||
|
|
db8224f74e | ||
|
|
b075f5de2a | ||
|
|
3240164840 | ||
|
|
f70f362a3d | ||
|
|
806bb4c78d | ||
|
|
57094bc285 | ||
|
|
a5e0c41663 | ||
|
|
77071238a0 | ||
|
|
64097d3c20 | ||
|
|
cf0e57e5df | ||
|
|
703cf23296 | ||
|
|
a88073d6fb | ||
|
|
4b5745c1b6 | ||
|
|
4667c81e6b | ||
|
|
cea9d863f9 | ||
|
|
5fa953eddd | ||
|
|
031f1acd07 | ||
|
|
add23fe97f | ||
|
|
3d2b0946de | ||
|
|
6c7282b442 | ||
|
|
1f79a7f805 | ||
|
|
3d1eaf71e4 | ||
|
|
138209c627 | ||
|
|
b283d352b7 | ||
|
|
f7f9dabe2b | ||
|
|
787d4fbcfa | ||
|
|
3fbd0e05a5 | ||
|
|
2d021a3414 | ||
|
|
cd7582c5e5 | ||
|
|
d16b852054 | ||
|
|
06223d9bd7 | ||
|
|
dcd81d601b | ||
|
|
762ebecd86 | ||
|
|
fd4efff6e3 | ||
|
|
8968974f42 | ||
|
|
5f083ae47c | ||
|
|
83b14b4329 | ||
|
|
74eefd6116 | ||
|
|
a96c70f2a7 | ||
|
|
304503b9f1 | ||
|
|
06cf8fb16a | ||
|
|
521e00d075 | ||
|
|
b4cad6ec1b |
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"
|
||||
@@ -3,7 +3,8 @@ name: Homebrew
|
||||
# Updates the cask in the project tap, l0ng-ai/homebrew-tap (scripts/homebrew-cask.ts), so
|
||||
# `brew install --cask l0ng-ai/tap/openidea` installs the new release. Release runs it after
|
||||
# publishing; run it by hand to write the cask of an existing tag again. Skipped for prereleases
|
||||
# and without the HOMEBREW_TAP_TOKEN secret (contents: write on l0ng-ai/homebrew-tap).
|
||||
# and without the HOMEBREW_TAP_DEPLOY_KEY secret (the private half of a write deploy key on
|
||||
# l0ng-ai/homebrew-tap).
|
||||
on:
|
||||
workflow_call:
|
||||
inputs:
|
||||
@@ -27,17 +28,17 @@ jobs:
|
||||
env:
|
||||
TAG: ${{ inputs.tag }}
|
||||
TAP: l0ng-ai/homebrew-tap
|
||||
HOMEBREW_TAP_TOKEN: ${{ secrets.HOMEBREW_TAP_TOKEN }}
|
||||
HOMEBREW_TAP_DEPLOY_KEY: ${{ secrets.HOMEBREW_TAP_DEPLOY_KEY }}
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
steps:
|
||||
- name: Check tag and token
|
||||
- name: Check tag and deploy key
|
||||
id: check
|
||||
run: |
|
||||
if [[ ! "$TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
|
||||
echo "::notice::$TAG is not a stable release: the cask stays as is"
|
||||
echo "skip=true" >> "$GITHUB_OUTPUT"
|
||||
elif [ -z "$HOMEBREW_TAP_TOKEN" ]; then
|
||||
echo "::notice::HOMEBREW_TAP_TOKEN unset: not updating the cask for $TAG"
|
||||
elif [ -z "$HOMEBREW_TAP_DEPLOY_KEY" ]; then
|
||||
echo "::notice::HOMEBREW_TAP_DEPLOY_KEY unset: not updating the cask for $TAG"
|
||||
echo "skip=true" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
- uses: actions/checkout@v5
|
||||
@@ -47,7 +48,7 @@ jobs:
|
||||
if: steps.check.outputs.skip != 'true'
|
||||
with:
|
||||
repository: ${{ env.TAP }}
|
||||
token: ${{ secrets.HOMEBREW_TAP_TOKEN }}
|
||||
ssh-key: ${{ secrets.HOMEBREW_TAP_DEPLOY_KEY }}
|
||||
path: tap
|
||||
- uses: actions/setup-node@v5
|
||||
if: steps.check.outputs.skip != 'true'
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -179,7 +179,7 @@ jobs:
|
||||
with: { tag: "${{ github.event.inputs.tag || github.ref_name }}" }
|
||||
secrets: inherit
|
||||
|
||||
# The cask in l0ng-ai/homebrew-tap; skipped for prereleases and without HOMEBREW_TAP_TOKEN.
|
||||
# The cask in l0ng-ai/homebrew-tap; skipped for prereleases and without HOMEBREW_TAP_DEPLOY_KEY.
|
||||
homebrew:
|
||||
needs: publish
|
||||
uses: ./.github/workflows/homebrew.yml
|
||||
|
||||
Створено
+269
-198
File diff suppressed because it is too large.
Load diff
+3
-2
@@ -5,7 +5,7 @@ members = ["crates/*", "src-tauri"]
|
||||
exclude = ["sdk", "plugins"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.1.53"
|
||||
version = "0.1.55"
|
||||
edition = "2024"
|
||||
rust-version = "1.96"
|
||||
license = "Apache-2.0"
|
||||
@@ -24,6 +24,7 @@ ide-jsonrpc = { path = "crates/ide-jsonrpc" }
|
||||
ide-lsp = { path = "crates/ide-lsp" }
|
||||
ide-dap = { path = "crates/ide-dap" }
|
||||
ide-vcs = { path = "crates/ide-vcs" }
|
||||
ide-github = { path = "crates/ide-github" }
|
||||
ide-terminal = { path = "crates/ide-terminal" }
|
||||
ide-run = { path = "crates/ide-run" }
|
||||
ide-workspace = { path = "crates/ide-workspace" }
|
||||
@@ -108,7 +109,7 @@ jupyter-zmq-client = { version = "=2.0.0", default-features = false, features =
|
||||
jupyter-protocol = "=2.0.3"
|
||||
zeromq = { version = "0.6", default-features = false, features = ["tokio-runtime", "tcp-transport"] }
|
||||
lsp-types = "0.97"
|
||||
gix = { version = "0.89", default-features = false }
|
||||
gix = { version = "0.90", default-features = false }
|
||||
portable-pty = "0.9"
|
||||
reqwest = { version = "0.13", default-features = false, features = ["rustls-no-provider", "http2", "charset", "socks", "gzip", "deflate", "brotli"] }
|
||||
rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12", "logging"] }
|
||||
|
||||
@@ -25,7 +25,7 @@ pub(crate) async fn run(shared: &Arc<Shared>, spec: &ProviderSpec, model: Option
|
||||
Err(err)
|
||||
if !prefer_stored
|
||||
&& crate::provider::is_copilot_provider(&spec.id)
|
||||
&& crate::provider::has_unconfigured_copilot_ambient_token(&spec.env)
|
||||
&& crate::provider::has_unconfigured_copilot_ambient_token(&spec.env, &shared.paths.project_root)
|
||||
&& super::auth_required(0, &err) =>
|
||||
{
|
||||
let retry = run_once(shared, spec, true, model).await;
|
||||
|
||||
@@ -283,6 +283,20 @@ impl AgentCatalogs {
|
||||
}
|
||||
}
|
||||
|
||||
/// Clears a failed discovery cooldown so a fresh sign-in can immediately load models.
|
||||
pub(crate) fn clear_failed_cooldown(&self, shared: &Shared, provider: &str) {
|
||||
let key = Self::key(shared, provider);
|
||||
let mut state = self.state.lock();
|
||||
if let Some(entry) = state.entries.get_mut(&key)
|
||||
&& entry.flight.is_none()
|
||||
&& entry.error.is_some()
|
||||
{
|
||||
entry.completed = None;
|
||||
entry.retry_at_ms = None;
|
||||
entry.error = None;
|
||||
}
|
||||
}
|
||||
|
||||
fn snapshot(&self, shared: &Shared, provider: &str, entry: &Entry) -> AgentModelCatalog {
|
||||
let catalog = entry.catalog.clone().unwrap_or_default();
|
||||
let model_failure = entry.requested_model.as_ref().and_then(|model| entry.model_failures.get(model));
|
||||
@@ -613,6 +627,40 @@ impl crate::AgentManager {
|
||||
let spec = self.shared.spec(provider).ok_or_else(|| IdeError::invalid(format!("unknown agent {provider}")))?;
|
||||
Ok(self.shared.paths.catalogs.request(&self.shared, spec, force, model).0)
|
||||
}
|
||||
|
||||
/// Probes Copilot's model catalog for a staged `account` selection (`""` = Copilot CLI
|
||||
/// default) without mutating `models.json` or broadcasting to active sessions before Apply.
|
||||
pub async fn preview_copilot_models(&self, account: &str, model: Option<&str>) -> IdeResult<AgentModelCatalog> {
|
||||
let mut spec = provider::load(self.shared.paths.custom_agents_dir.as_deref(), self.shared.env_secrets())
|
||||
.into_iter()
|
||||
.find(|p| p.id == "copilot")
|
||||
.ok_or_else(|| IdeError::not_found("unknown agent 'copilot'"))?;
|
||||
spec.env.retain(|(name, _)| name != provider::COPILOT_GITHUB_ACCOUNT_ENV);
|
||||
let account = account.trim();
|
||||
if !account.is_empty() {
|
||||
spec.env.push((provider::COPILOT_GITHUB_ACCOUNT_ENV.into(), account.to_owned()));
|
||||
}
|
||||
match discover(&self.shared, spec, model).await {
|
||||
Ok(found) => Ok(AgentModelCatalog {
|
||||
provider: "copilot".into(),
|
||||
config: self.shared.config_for_new_task(found.config, "copilot"),
|
||||
thought_levels: self.shared.thought_levels_for_new_task(found.levels, "copilot"),
|
||||
refreshing: false,
|
||||
refreshed_at_ms: Some(self.shared.paths.catalogs.epoch_ms()),
|
||||
retry_at_ms: None,
|
||||
error: None,
|
||||
}),
|
||||
Err(error) => Ok(AgentModelCatalog {
|
||||
provider: "copilot".into(),
|
||||
config: Vec::new(),
|
||||
thought_levels: BTreeMap::new(),
|
||||
refreshing: false,
|
||||
refreshed_at_ms: None,
|
||||
retry_at_ms: None,
|
||||
error: Some(error),
|
||||
}),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn discover(
|
||||
|
||||
@@ -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};
|
||||
|
||||
@@ -54,6 +54,21 @@ pub(crate) fn bypass_approvals(config: &[AgentConfigOption]) -> bool {
|
||||
.any(|category| selected(category).zip(bypass_value(category)).is_some_and(|(value, bypass)| bypass(value)))
|
||||
}
|
||||
|
||||
/// Canonical snapshot of approval-bearing config options (`mode`, `permissions`, `approval`)
|
||||
/// so auto-resume can refuse to run silently if permission policy drifted while closed.
|
||||
pub(crate) fn approval_fingerprint(config: &[AgentConfigOption]) -> Option<String> {
|
||||
let mut parts: Vec<String> = config
|
||||
.iter()
|
||||
.filter(|o| matches!(o.category.as_deref(), Some("mode" | "permissions" | "approval")))
|
||||
.filter_map(|o| Some(format!("{}={}", o.id, o.current.as_deref()?)))
|
||||
.collect();
|
||||
if parts.is_empty() {
|
||||
return None;
|
||||
}
|
||||
parts.sort();
|
||||
Some(parts.join(";"))
|
||||
}
|
||||
|
||||
/// For an option of `category` that can approve everything, what tells its approving values.
|
||||
fn bypass_value(category: &str) -> Option<fn(&str) -> bool> {
|
||||
match category {
|
||||
@@ -278,11 +293,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 +688,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 +698,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());
|
||||
|
||||
+1738
-253
File diff suppressed because it is too large.
Load diff
@@ -49,6 +49,74 @@ pub struct AgentCapabilities {
|
||||
pub context_usage: bool,
|
||||
}
|
||||
|
||||
/// Why `AgentManager` is shutting down its live tasks.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub enum AgentShutdownReason {
|
||||
WindowClose,
|
||||
#[default]
|
||||
Quit,
|
||||
Restart,
|
||||
BackendUpgrade,
|
||||
BackendStop,
|
||||
}
|
||||
|
||||
/// Why an in-flight turn stopped before completing.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum InterruptionReason {
|
||||
WindowClose,
|
||||
Quit,
|
||||
Restart,
|
||||
BackendUpgrade,
|
||||
BackendStop,
|
||||
UnexpectedExit,
|
||||
NetworkTimeout,
|
||||
}
|
||||
|
||||
impl From<AgentShutdownReason> for InterruptionReason {
|
||||
fn from(reason: AgentShutdownReason) -> Self {
|
||||
match reason {
|
||||
AgentShutdownReason::WindowClose => Self::WindowClose,
|
||||
AgentShutdownReason::Quit => Self::Quit,
|
||||
AgentShutdownReason::Restart => Self::Restart,
|
||||
AgentShutdownReason::BackendUpgrade => Self::BackendUpgrade,
|
||||
AgentShutdownReason::BackendStop => Self::BackendStop,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Recovery metadata recorded when an active turn was interrupted before finishing.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AgentInterrupted {
|
||||
pub reason: InterruptionReason,
|
||||
pub at_ms: f64,
|
||||
#[serde(default, skip_serializing_if = "is_false")]
|
||||
pub was_waiting_for_input: bool,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub approval_mode: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "is_false")]
|
||||
pub auto_resume_once: bool,
|
||||
}
|
||||
|
||||
/// Summary returned when reconciling interrupted tasks for a connected project window.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AgentRecoveryReport {
|
||||
/// Unique identifier of this `AgentManager` process incarnation.
|
||||
pub instance_id: String,
|
||||
/// `true` on the first reconciliation of this `AgentManager` incarnation.
|
||||
pub first_reconcile: bool,
|
||||
/// Task IDs automatically resumed during this reconciliation.
|
||||
pub auto_resumed: Vec<String>,
|
||||
/// Task IDs remaining in `Interrupted` (`Ask to resume`).
|
||||
pub interrupted: Vec<String>,
|
||||
}
|
||||
|
||||
fn is_false(b: &bool) -> bool {
|
||||
!*b
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum Isolation {
|
||||
@@ -117,6 +185,16 @@ pub struct AgentTask {
|
||||
// Boxed so that `AgentEvent::Task` stays within clippy's `large_enum_variant` bound on Windows.
|
||||
#[serde(default)]
|
||||
pub stats: Box<AgentSessionStats>,
|
||||
/// Set when the task's last active turn was interrupted (window close, restart, crash, or
|
||||
/// expired network retry window) and has not been resumed or dismissed yet.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub interrupted: Option<Box<AgentInterrupted>>,
|
||||
/// Persisted unseen reply / input / failure state across window closes and remote reattaches.
|
||||
#[serde(default, skip_serializing_if = "is_false")]
|
||||
pub unread: bool,
|
||||
/// Per-session recovery / network auto-retry window override in minutes (`0` = Off; `None` = inherit global).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub recovery_window_mins: Option<u32>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
|
||||
@@ -159,6 +237,9 @@ pub struct AgentRetry {
|
||||
/// When the next attempt starts (ms since the epoch).
|
||||
pub retry_at_ms: f64,
|
||||
pub error: Option<String>,
|
||||
/// Set when OpenIDEA holds an active turn in `Waiting for network` until `deadline_ms`.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub deadline_ms: Option<f64>,
|
||||
}
|
||||
|
||||
/// Token pricing (Credits per 1M tokens) and context window capacity for one tier.
|
||||
@@ -255,6 +336,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 +354,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 +381,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 +391,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,
|
||||
}
|
||||
|
||||
@@ -511,6 +609,9 @@ pub enum AgentEntry {
|
||||
/// Sent into a running turn rather than starting one.
|
||||
#[serde(default)]
|
||||
steered: bool,
|
||||
/// Set when this turn was started automatically or via 1-click Resume to recover an interrupted turn.
|
||||
#[serde(default)]
|
||||
recovery: Option<InterruptionReason>,
|
||||
},
|
||||
Agent {
|
||||
text: String,
|
||||
@@ -547,6 +648,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>,
|
||||
@@ -623,6 +727,9 @@ pub struct AgentProvider {
|
||||
pub command_read_only_reason: Option<AgentCommandReadOnlyReason>,
|
||||
/// Whether the command was found (on `PATH`).
|
||||
pub installed: bool,
|
||||
/// Whether OpenIDEA can run this agent's sign-in flow directly in an embedded terminal.
|
||||
#[serde(default)]
|
||||
pub can_sign_in: bool,
|
||||
/// The built-in command can be owned by a global npm package.
|
||||
#[serde(default)]
|
||||
pub can_check_cli_update: bool,
|
||||
@@ -647,6 +754,34 @@ pub enum AgentCommandReadOnlyReason {
|
||||
CustomAgent,
|
||||
}
|
||||
|
||||
/// An authenticated `github.com` account stored in GitHub CLI (`gh`).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct GhAuthAccount {
|
||||
pub login: String,
|
||||
pub active: bool,
|
||||
}
|
||||
|
||||
/// GitHub Copilot's default sign-in status alongside the accounts available through `gh`.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct CopilotAuthStatus {
|
||||
pub authenticated: bool,
|
||||
pub login: Option<String>,
|
||||
pub auth_type: Option<String>,
|
||||
pub status_message: Option<String>,
|
||||
pub gh_installed: bool,
|
||||
pub gh_accounts: Vec<GhAuthAccount>,
|
||||
}
|
||||
|
||||
/// Output and completion of an interactive sign-in PTY started by the IDE.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
#[serde(tag = "type", rename_all = "camelCase")]
|
||||
pub enum AgentLoginEvent {
|
||||
Output { data: String },
|
||||
Exited { code: Option<i32> },
|
||||
}
|
||||
|
||||
/// Where an agent comes from.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(tag = "kind", rename_all = "camelCase")]
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
@@ -1481,14 +1489,13 @@ fn stop_reason(turn: &Value, last_error: Option<Value>, rate_limits: Option<&Val
|
||||
let e = turn.get("error").filter(|e| !e.is_null()).cloned().or(last_error).unwrap_or(json!({}));
|
||||
let message = translate::error_message(&e);
|
||||
return match translate::classify(&e, rate_limits) {
|
||||
Failure::Refusal => Ok(json!({ "stopReason": "refusal" })),
|
||||
Failure::UsageLimit(resets) => Err(ResponseError {
|
||||
code: codes::INTERNAL_ERROR,
|
||||
message,
|
||||
data: Some(json!({ "openidea": { "usageLimit": { "resetsAtMs": resets } } })),
|
||||
}),
|
||||
Failure::Auth => Err(error(AUTH_REQUIRED, format!("Codex authentication failed: {message}"))),
|
||||
Failure::Other => Err(error(codes::INTERNAL_ERROR, message)),
|
||||
Failure::Refusal | Failure::Other => Err(error(codes::INTERNAL_ERROR, message)),
|
||||
};
|
||||
}
|
||||
_ => "end_turn",
|
||||
|
||||
@@ -455,6 +455,90 @@ fn failures_are_classified() {
|
||||
assert_eq!(stop_reason(&json!({"status": "interrupted"}), None, None).unwrap(), json!({"stopReason": "cancelled"}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_turns_preserve_codex_error_diagnostics() {
|
||||
let policy = json!({
|
||||
"message": "This content was flagged for possible cybersecurity risk.",
|
||||
"additionalDetails": "Contact support if this is unexpected.",
|
||||
"codexErrorInfo": "cyberPolicy"
|
||||
});
|
||||
let expected = "This content was flagged for possible cybersecurity risk.\nContact support if this is unexpected.\nCodex error: cyberPolicy";
|
||||
for (turn_error, last_error) in [(policy.clone(), None), (Value::Null, Some(policy.clone()))] {
|
||||
let failure = stop_reason(&json!({ "status": "failed", "error": turn_error }), last_error, None).unwrap_err();
|
||||
assert_eq!(failure.code, codes::INTERNAL_ERROR);
|
||||
assert_eq!(failure.message, expected);
|
||||
}
|
||||
// A completed turn's own error wins over an older error notification.
|
||||
let failure = stop_reason(
|
||||
&json!({ "status": "failed", "error": policy }),
|
||||
Some(json!({ "message": "An earlier retry failed.", "codexErrorInfo": "other" })),
|
||||
None,
|
||||
)
|
||||
.unwrap_err();
|
||||
assert_eq!(failure.message, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_turn_diagnostics_include_string_and_structured_error_codes() {
|
||||
for (value, expected) in [
|
||||
(
|
||||
json!({ "message": "Context is full.", "codexErrorInfo": "contextWindowExceeded" }),
|
||||
"Context is full.\nCodex error: contextWindowExceeded",
|
||||
),
|
||||
(
|
||||
json!({ "message": "The stream disconnected.", "codexErrorInfo": { "responseStreamDisconnected": { "httpStatusCode": 502 } } }),
|
||||
"The stream disconnected.\nCodex error: responseStreamDisconnected (HTTP 502)",
|
||||
),
|
||||
(
|
||||
json!({ "message": "Failed\nbecause", "additionalDetails": "because", "codexErrorInfo": null }),
|
||||
"Failed\nbecause",
|
||||
),
|
||||
(
|
||||
json!({ "message": " ", "additionalDetails": " Details ", "codexErrorInfo": "cyberPolicy" }),
|
||||
"Codex failed\nDetails\nCodex error: cyberPolicy",
|
||||
),
|
||||
(json!({ "message": "Failed", "codexErrorInfo": "" }), "Failed"),
|
||||
(json!({}), "Codex failed"),
|
||||
] {
|
||||
assert_eq!(error_message(&value), expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn policy_failure_is_forwarded_over_acp_with_its_original_diagnostics() {
|
||||
for notification_only in [false, true] {
|
||||
let mut transcript = load(Scenario::UsageLimit.file());
|
||||
let policy = json!({
|
||||
"message": "This content was flagged for possible cybersecurity risk.",
|
||||
"additionalDetails": "Contact support if this is unexpected.",
|
||||
"codexErrorInfo": "cyberPolicy"
|
||||
});
|
||||
for (out, frame) in &mut transcript.frames {
|
||||
if *out {
|
||||
continue;
|
||||
}
|
||||
match frame["method"].as_str() {
|
||||
Some("error") => frame["params"]["error"] = policy.clone(),
|
||||
Some("turn/completed") => {
|
||||
frame["params"]["turn"]["error"] = if notification_only { Value::Null } else { policy.clone() }
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let (results, _client, _frames, _meta, _codex) = replay_transcript(Scenario::Simple, transcript).await;
|
||||
match result(&results, "prompt") {
|
||||
Err(RpcError::Server { code, message, .. }) => {
|
||||
assert_eq!(*code, codes::INTERNAL_ERROR);
|
||||
assert_eq!(
|
||||
message,
|
||||
"This content was flagged for possible cybersecurity risk.\nContact support if this is unexpected.\nCodex error: cyberPolicy"
|
||||
);
|
||||
}
|
||||
response => panic!("the failed turn must reach the task as an error, got {response:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn approvals_offer_what_codex_offers_and_always_a_decline() {
|
||||
let params = json!({"availableDecisions": ["accept",
|
||||
@@ -2000,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());
|
||||
}
|
||||
|
||||
@@ -740,7 +740,7 @@ pub(super) enum Failure {
|
||||
UsageLimit(Option<f64>),
|
||||
/// Signed out or refused.
|
||||
Auth,
|
||||
/// The model declined.
|
||||
/// The server blocked the turn under a safety policy.
|
||||
Refusal,
|
||||
Other,
|
||||
}
|
||||
@@ -780,13 +780,27 @@ fn resets_at(rate_limits: Option<&Value>) -> Option<f64> {
|
||||
exhausted.map(|s| s * 1000.0)
|
||||
}
|
||||
|
||||
/// The text a failed turn reports: codex's message, with its details.
|
||||
/// The text a failed turn reports: Codex's message, details and diagnostic code.
|
||||
pub(super) fn error_message(error: &Value) -> String {
|
||||
let message = error.get("message").and_then(Value::as_str).unwrap_or("Codex failed").trim();
|
||||
match error.get("additionalDetails").and_then(Value::as_str).map(str::trim).filter(|d| !d.is_empty()) {
|
||||
Some(details) if !message.contains(details) => format!("{message}\n{details}"),
|
||||
_ => message.to_owned(),
|
||||
let original =
|
||||
error.get("message").and_then(Value::as_str).map(str::trim).filter(|m| !m.is_empty()).unwrap_or("Codex failed");
|
||||
let mut message = original.to_owned();
|
||||
if let Some(details) =
|
||||
error.get("additionalDetails").and_then(Value::as_str).map(str::trim).filter(|d| !d.is_empty())
|
||||
&& !original.contains(details)
|
||||
{
|
||||
message.push('\n');
|
||||
message.push_str(details);
|
||||
}
|
||||
let info = error.get("codexErrorInfo").unwrap_or(&Value::Null);
|
||||
let code = info.as_str().or_else(|| info.as_object()?.keys().next().map(String::as_str));
|
||||
if let Some(code) = code.map(str::trim).filter(|c| !c.is_empty()) {
|
||||
message.push_str(&format!("\nCodex error: {code}"));
|
||||
if let Some(status) = info.get(code).and_then(|details| details.get("httpStatusCode")).and_then(Value::as_u64) {
|
||||
message.push_str(&format!(" (HTTP {status})"));
|
||||
}
|
||||
}
|
||||
message
|
||||
}
|
||||
|
||||
/// One choice of an approval: what ACP shows and what codex gets back.
|
||||
|
||||
@@ -114,7 +114,7 @@ pub(crate) fn is_missing_binary_error(err: &std::io::Error) -> bool {
|
||||
pub(crate) async fn discover(spec: ProviderSpec, cwd: PathBuf) -> Result<Discovered, DiscoverError> {
|
||||
tokio::time::timeout(DISCOVER_TIMEOUT, async move {
|
||||
let prefer_stored = crate::provider::prefer_stored_copilot_auth();
|
||||
let has_ambient = crate::provider::has_unconfigured_copilot_ambient_token(&spec.env);
|
||||
let has_ambient = crate::provider::has_unconfigured_copilot_ambient_token(&spec.env, &cwd);
|
||||
match discover_once(spec.clone(), cwd.clone(), prefer_stored).await {
|
||||
Err(err)
|
||||
if !prefer_stored
|
||||
@@ -185,6 +185,78 @@ async fn discover_once(spec: ProviderSpec, cwd: PathBuf, strip_ambient: bool) ->
|
||||
res
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub(crate) struct CliAuthStatus {
|
||||
pub authenticated: bool,
|
||||
pub login: Option<String>,
|
||||
pub auth_type: Option<String>,
|
||||
pub status_message: Option<String>,
|
||||
}
|
||||
|
||||
/// Queries `auth.getStatus` on Copilot's headless server (ignoring any IDE-selected `gh`
|
||||
/// account override so the UI can show what the "Default" account resolves to).
|
||||
pub(crate) async fn probe_auth_status(mut spec: ProviderSpec, cwd: PathBuf) -> Option<CliAuthStatus> {
|
||||
spec.env.retain(|(name, _)| name != crate::provider::COPILOT_GITHUB_ACCOUNT_ENV);
|
||||
tokio::time::timeout(Duration::from_secs(8), async move {
|
||||
let prefer_stored = crate::provider::prefer_stored_copilot_auth();
|
||||
let has_ambient = crate::provider::has_unconfigured_copilot_ambient_token(&spec.env, &cwd);
|
||||
let first = probe_auth_once(spec.clone(), cwd.clone(), prefer_stored).await;
|
||||
if !prefer_stored
|
||||
&& has_ambient
|
||||
&& first.as_ref().is_none_or(|s| !s.authenticated)
|
||||
&& let Some(retry) = probe_auth_once(spec, cwd, true).await
|
||||
{
|
||||
if retry.authenticated {
|
||||
crate::provider::mark_prefer_stored_copilot_auth();
|
||||
}
|
||||
return Some(retry);
|
||||
}
|
||||
first
|
||||
})
|
||||
.await
|
||||
.ok()
|
||||
.flatten()
|
||||
}
|
||||
|
||||
async fn probe_auth_once(spec: ProviderSpec, cwd: PathBuf, strip_ambient: bool) -> Option<CliAuthStatus> {
|
||||
let launch = tokio::task::spawn_blocking({
|
||||
let cwd = cwd.clone();
|
||||
move || spec.resolve_for_launch_with_copilot_env(&cwd, strip_ambient)
|
||||
})
|
||||
.await
|
||||
.ok()?
|
||||
.ok()?;
|
||||
let cwd = dunce::canonicalize(&cwd).unwrap_or(cwd);
|
||||
let args = headless_args(&launch.args);
|
||||
let peer = Peer::spawn_framed(
|
||||
&launch.command,
|
||||
&args,
|
||||
&cwd,
|
||||
&launch.env,
|
||||
Arc::new(ide_jsonrpc::NoopHandler),
|
||||
Box::new(|_| {}),
|
||||
Framing::ContentLength,
|
||||
)
|
||||
.ok()?;
|
||||
let res = async {
|
||||
handshake(&peer).await.ok()?;
|
||||
let auth: Value = peer.request("auth.getStatus", json!({}), None).await.ok()?;
|
||||
let authenticated = auth.get("isAuthenticated").and_then(Value::as_bool).unwrap_or(false);
|
||||
let str_field = |key: &str| {
|
||||
auth.get(key).and_then(Value::as_str).map(str::trim).filter(|s| !s.is_empty()).map(str::to_owned)
|
||||
};
|
||||
Some(CliAuthStatus {
|
||||
authenticated,
|
||||
login: str_field("login"),
|
||||
auth_type: str_field("authType"),
|
||||
status_message: str_field("statusMessage"),
|
||||
})
|
||||
}
|
||||
.await;
|
||||
peer.kill();
|
||||
res
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(super) fn attach(
|
||||
client: Arc<dyn Handler>,
|
||||
@@ -450,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}"))),
|
||||
@@ -465,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",
|
||||
@@ -583,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();
|
||||
@@ -663,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();
|
||||
@@ -998,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> {
|
||||
|
||||
@@ -2,7 +2,10 @@
|
||||
//! `<config>/agents/<id>.toml` (written by hand, or by installing one from the ACP
|
||||
//! Registry, see `registry`).
|
||||
|
||||
use crate::{AcpImportOutcome, AgentCommandReadOnlyReason, AgentProvider, AgentSource, CustomAgentInput, EnvSecrets};
|
||||
use crate::{
|
||||
AcpImportOutcome, AgentCommandReadOnlyReason, AgentProvider, AgentSource, CustomAgentInput, EnvSecrets,
|
||||
GhAuthAccount,
|
||||
};
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
@@ -73,7 +76,7 @@ const BUILTIN: &[(&str, &str, Driver, &[&str], &str)] = &[
|
||||
"GitHub Copilot",
|
||||
Driver::Copilot,
|
||||
&["copilot", "--headless", "--no-auto-update", "--stdio"],
|
||||
"Run `copilot` in a terminal and sign in.",
|
||||
"Run `copilot login` in a terminal.",
|
||||
),
|
||||
("cursor", "Cursor", Driver::Acp, &["cursor-agent", "acp"], "Run `cursor-agent login` in a terminal."),
|
||||
("opencode", "OpenCode", Driver::Acp, &["opencode", "acp"], "Run `opencode auth login` in a terminal."),
|
||||
@@ -151,12 +154,26 @@ impl ProviderSpec {
|
||||
cwd: &Path,
|
||||
strip_ambient_tokens: bool,
|
||||
) -> Result<Self, String> {
|
||||
let account = is_copilot_provider(&self.id).then(|| copilot_github_account(&self.env)).flatten();
|
||||
let is_copilot = is_copilot_provider(&self.id);
|
||||
let account = is_copilot.then(|| copilot_github_account(&self.env)).flatten();
|
||||
let explicit_copilot_token =
|
||||
self.env.iter().any(|(name, value)| name == "COPILOT_GITHUB_TOKEN" && !value.is_empty());
|
||||
let mut resolved = self.resolve_for_launch_base(cwd, strip_ambient_tokens || account.is_some());
|
||||
if let Some(account) = account {
|
||||
let token = github_token_for_account(&account)?;
|
||||
// Keep any project-scoped `GH_TOKEN` untouched so `gh` commands inside Copilot's
|
||||
// shell use the project's GitHub account while `COPILOT_GITHUB_TOKEN` bills `account`.
|
||||
resolved.env.retain(|(name, _)| !AMBIENT_COPILOT_AUTH_VARS.contains(&name.as_str()));
|
||||
resolved.env.push(("COPILOT_GITHUB_TOKEN".into(), token));
|
||||
} else if is_copilot
|
||||
&& !strip_ambient_tokens
|
||||
&& !explicit_copilot_token
|
||||
&& ide_core::project_env::github_token(cwd).is_some()
|
||||
&& let Some(default_token) = default_github_token()
|
||||
{
|
||||
// A project-scoped `GH_TOKEN` targets repository/PR commands, not Copilot model
|
||||
// billing: pin `COPILOT_GITHUB_TOKEN` to the user's global `gh` account when present.
|
||||
resolved.env.push(("COPILOT_GITHUB_TOKEN".into(), default_token));
|
||||
}
|
||||
Ok(resolved)
|
||||
}
|
||||
@@ -166,7 +183,7 @@ impl ProviderSpec {
|
||||
self.command = crate::native::newest_install(&self.command);
|
||||
}
|
||||
if is_copilot_provider(&self.id) {
|
||||
self.env = sanitized_copilot_env(&self.env, strip_ambient_tokens);
|
||||
self.env = sanitized_copilot_env(&self.env, cwd, strip_ambient_tokens);
|
||||
self.env.retain(|(name, _)| name != COPILOT_GITHUB_ACCOUNT_ENV);
|
||||
}
|
||||
let program = ide_jsonrpc::resolve_spawn_program(&self.command, &self.env);
|
||||
@@ -176,6 +193,80 @@ impl ProviderSpec {
|
||||
.into_owned();
|
||||
self
|
||||
}
|
||||
|
||||
/// Resolves the executable, arguments, and environment to run this agent's interactive
|
||||
/// sign-in flow directly in an IDE PTY without shell quoting.
|
||||
pub(crate) fn login_launch(&self, cwd: &Path, terminal_auth_args: Option<&[String]>) -> Option<LoginLaunch> {
|
||||
let search = ide_core::tool_path::search_path();
|
||||
let resolve_exe = |cmd: &str, env: &[(String, String)]| -> Option<PathBuf> {
|
||||
let spawned = ide_jsonrpc::resolve_spawn_program(cmd, env);
|
||||
let candidate =
|
||||
if spawned.components().count() > 1 && !spawned.is_absolute() { cwd.join(&spawned) } else { spawned };
|
||||
if candidate.is_absolute() && is_executable(&candidate) {
|
||||
return Some(candidate);
|
||||
}
|
||||
ide_core::tool_path::find_command(&candidate.to_string_lossy(), &search, cwd)
|
||||
};
|
||||
|
||||
if let Some((separate_cmd, separate_args)) = match self.id.as_str() {
|
||||
"claude-acp" => Some(("claude", &[][..])),
|
||||
"codex-acp" => Some(("codex", &["login"][..])),
|
||||
"vibe" => Some(("vibe", &[][..])),
|
||||
_ => None,
|
||||
} {
|
||||
let program = resolve_exe(separate_cmd, &self.env)?;
|
||||
return Some(LoginLaunch {
|
||||
program,
|
||||
args: separate_args.iter().map(|s| (*s).to_owned()).collect(),
|
||||
env: self.env.iter().cloned().collect(),
|
||||
});
|
||||
}
|
||||
|
||||
if let Some(builtin) = builtin_spec(&self.id) {
|
||||
let args = terminal_auth_args
|
||||
.filter(|_| matches!(self.source, AgentSource::Registry { .. }))
|
||||
.map(<[String]>::to_vec)
|
||||
.or_else(|| builtin_login_args(&builtin))?;
|
||||
let resolved = self.clone().resolve_for_launch_base(cwd, true);
|
||||
let program = resolve_exe(&resolved.command, &resolved.env)?;
|
||||
let mut env: BTreeMap<String, String> = resolved.env.into_iter().collect();
|
||||
if is_copilot_provider(&self.id) {
|
||||
for key in AMBIENT_COPILOT_AUTH_VARS {
|
||||
env.insert(key.to_owned(), String::new());
|
||||
}
|
||||
}
|
||||
return Some(LoginLaunch { program, args, env });
|
||||
}
|
||||
|
||||
let args = terminal_auth_args?.to_vec();
|
||||
let resolved = self.clone().resolve_for_launch_base(cwd, true);
|
||||
let program = resolve_exe(&resolved.command, &resolved.env)?;
|
||||
Some(LoginLaunch { program, args, env: resolved.env.into_iter().collect() })
|
||||
}
|
||||
|
||||
pub(crate) fn can_sign_in(&self, cwd: &Path, terminal_auth_args: Option<&[String]>) -> bool {
|
||||
self.login_launch(cwd, terminal_auth_args).is_some()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct LoginLaunch {
|
||||
pub program: PathBuf,
|
||||
pub args: Vec<String>,
|
||||
pub env: BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
fn builtin_login_args(builtin: &ProviderSpec) -> Option<Vec<String>> {
|
||||
let prefix = format!("Run `{}", builtin.command);
|
||||
let rest = builtin.login_hint.strip_prefix(&prefix)?.strip_prefix([' ', '`']);
|
||||
match rest {
|
||||
Some(after_space) if builtin.login_hint[prefix.len()..].starts_with(' ') => {
|
||||
let (args, _) = after_space.split_once('`')?;
|
||||
Some(args.split_whitespace().map(str::to_owned).collect())
|
||||
}
|
||||
Some(_) => Some(Vec::new()),
|
||||
None => None,
|
||||
}
|
||||
}
|
||||
|
||||
const AMBIENT_COPILOT_AUTH_VARS: [&str; 3] = ["COPILOT_GITHUB_TOKEN", "GH_TOKEN", "GITHUB_TOKEN"];
|
||||
@@ -194,16 +285,26 @@ pub(crate) fn copilot_github_account(env: &[(String, String)]) -> Option<String>
|
||||
.map(str::to_owned)
|
||||
}
|
||||
|
||||
fn find_gh_executable() -> Option<PathBuf> {
|
||||
ide_core::tool_path::find_gh_executable()
|
||||
}
|
||||
|
||||
fn is_valid_github_login(account: &str) -> bool {
|
||||
let bytes = account.as_bytes();
|
||||
!bytes.is_empty()
|
||||
&& bytes.len() <= 39
|
||||
&& bytes[0].is_ascii_alphanumeric()
|
||||
&& bytes.iter().all(|b| b.is_ascii_alphanumeric() || *b == b'-' || *b == b'_')
|
||||
}
|
||||
|
||||
fn github_token_for_account(account: &str) -> Result<String, String> {
|
||||
let path = ide_core::process::shell_env()
|
||||
.find(|(name, _)| name == "PATH")
|
||||
.map(|(_, value)| value)
|
||||
.or_else(|| ide_core::process::host_var_os("PATH"));
|
||||
let program = path
|
||||
.as_deref()
|
||||
.and_then(|path| ide_core::process::find_executable("gh", path))
|
||||
if !is_valid_github_login(account) {
|
||||
return Err(format!("Invalid GitHub account login: {account}"));
|
||||
}
|
||||
let program = find_gh_executable()
|
||||
.ok_or_else(|| "GitHub CLI (`gh`) is required to select a Copilot GitHub account".to_owned())?;
|
||||
let mut command = std::process::Command::new(program);
|
||||
ide_core::process::prepare(&mut command);
|
||||
command.args(["auth", "token", "--hostname", "github.com", "--user", account]).envs(ide_core::process::shell_env());
|
||||
for name in AMBIENT_COPILOT_AUTH_VARS {
|
||||
command.env_remove(name);
|
||||
@@ -229,6 +330,140 @@ fn github_token_for_account(account: &str) -> Result<String, String> {
|
||||
Ok(token.to_owned())
|
||||
}
|
||||
|
||||
/// Interactive `gh auth login` launch for adding/switching GitHub CLI accounts in-IDE,
|
||||
/// with ambient `GITHUB_TOKEN` / `GH_TOKEN` cleared so `gh` does not refuse to run.
|
||||
pub fn gh_login_launch() -> IdeResult<LoginLaunch> {
|
||||
let program = find_gh_executable().ok_or_else(|| IdeError::unavailable("GitHub CLI (`gh`) is not installed"))?;
|
||||
let mut env = BTreeMap::new();
|
||||
for key in AMBIENT_COPILOT_AUTH_VARS {
|
||||
env.insert(key.to_owned(), String::new());
|
||||
}
|
||||
Ok(LoginLaunch {
|
||||
program,
|
||||
args: vec!["auth".into(), "login".into(), "--hostname".into(), "github.com".into()],
|
||||
env,
|
||||
})
|
||||
}
|
||||
|
||||
/// Returns `(gh_installed, authenticated_accounts)` for `github.com` from `gh auth status`,
|
||||
/// ignoring ambient token environment variables so keyring accounts remain visible.
|
||||
pub fn gh_authenticated_accounts() -> (bool, Vec<GhAuthAccount>) {
|
||||
let Some(program) = find_gh_executable() else {
|
||||
return (false, Vec::new());
|
||||
};
|
||||
let run_gh = |args: &[&str]| -> Option<std::process::Output> {
|
||||
let mut command = std::process::Command::new(&program);
|
||||
ide_core::process::prepare(&mut command);
|
||||
command
|
||||
.args(args)
|
||||
.envs(ide_core::process::shell_env())
|
||||
.env("GH_PROMPT_DISABLED", "1")
|
||||
.env("GH_NO_UPDATE_NOTIFIER", "1")
|
||||
.env("NO_COLOR", "1");
|
||||
for name in AMBIENT_COPILOT_AUTH_VARS {
|
||||
command.env_remove(name);
|
||||
}
|
||||
command.output().ok()
|
||||
};
|
||||
if let Some(output) = run_gh(&["auth", "status", "--json", "hosts"]) {
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
if let Some(accounts) = parse_gh_auth_status_json(&stdout) {
|
||||
return (true, accounts);
|
||||
}
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
if !stderr.contains("unknown flag: --json") {
|
||||
return (true, Vec::new());
|
||||
}
|
||||
}
|
||||
let fallback = run_gh(&["auth", "status", "--hostname", "github.com"])
|
||||
.map(|out| format!("{}\n{}", String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr)))
|
||||
.map(|text| parse_gh_auth_status_text(&text))
|
||||
.unwrap_or_default();
|
||||
(true, fallback)
|
||||
}
|
||||
|
||||
fn parse_gh_auth_status_json(text: &str) -> Option<Vec<GhAuthAccount>> {
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct Entry {
|
||||
#[serde(default)]
|
||||
state: Option<String>,
|
||||
#[serde(default)]
|
||||
active: bool,
|
||||
#[serde(default)]
|
||||
login: String,
|
||||
#[serde(default)]
|
||||
token_source: Option<String>,
|
||||
}
|
||||
#[derive(Deserialize)]
|
||||
struct Response {
|
||||
#[serde(default)]
|
||||
hosts: BTreeMap<String, Vec<Entry>>,
|
||||
}
|
||||
let parsed: Response = serde_json::from_str(text.trim()).ok()?;
|
||||
let mut accounts: Vec<GhAuthAccount> = Vec::new();
|
||||
if let Some(entries) = parsed.hosts.get("github.com") {
|
||||
for entry in entries {
|
||||
let login = entry.login.trim();
|
||||
if login.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if entry.state.as_deref().is_some_and(|s| s != "success") {
|
||||
continue;
|
||||
}
|
||||
// Tokens from the environment (`GH_TOKEN`, `GITHUB_TOKEN`, …) are not keyring accounts.
|
||||
if entry.token_source.as_deref().is_some_and(|source| source.ends_with("_TOKEN") || source == "env") {
|
||||
continue;
|
||||
}
|
||||
if let Some(existing) = accounts.iter_mut().find(|a| a.login == login) {
|
||||
existing.active |= entry.active;
|
||||
} else {
|
||||
accounts.push(GhAuthAccount { login: login.to_owned(), active: entry.active });
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(accounts)
|
||||
}
|
||||
|
||||
fn parse_gh_auth_status_text(text: &str) -> Vec<GhAuthAccount> {
|
||||
let mut accounts: Vec<GhAuthAccount> = Vec::new();
|
||||
let mut current: Option<usize> = None;
|
||||
for line in text.lines() {
|
||||
let trimmed = line.trim();
|
||||
if let Some((_, rest)) = trimmed.split_once("Logged in to github.com account ") {
|
||||
let login = rest.split_whitespace().next().unwrap_or("").trim();
|
||||
current = None;
|
||||
if !login.is_empty() && !rest.contains("_TOKEN") {
|
||||
if let Some(idx) = accounts.iter().position(|a| a.login == login) {
|
||||
current = Some(idx);
|
||||
} else {
|
||||
accounts.push(GhAuthAccount { login: login.to_owned(), active: false });
|
||||
current = Some(accounts.len() - 1);
|
||||
}
|
||||
}
|
||||
} else if trimmed.starts_with("- Active account: true")
|
||||
&& let Some(idx) = current
|
||||
{
|
||||
accounts[idx].active = true;
|
||||
}
|
||||
}
|
||||
accounts
|
||||
}
|
||||
|
||||
fn default_github_token() -> Option<String> {
|
||||
let program = find_gh_executable()?;
|
||||
let mut command = std::process::Command::new(program);
|
||||
ide_core::process::prepare(&mut command);
|
||||
command.args(["auth", "token", "--hostname", "github.com"]).envs(ide_core::process::shell_env());
|
||||
for name in AMBIENT_COPILOT_AUTH_VARS {
|
||||
command.env_remove(name);
|
||||
}
|
||||
let output = command.output().ok().filter(|out| out.status.success())?;
|
||||
let token = String::from_utf8(output.stdout).ok()?;
|
||||
let token = token.trim();
|
||||
(!token.is_empty()).then(|| token.to_owned())
|
||||
}
|
||||
|
||||
pub(crate) fn prefer_stored_copilot_auth() -> bool {
|
||||
PREFER_STORED_COPILOT_AUTH.load(std::sync::atomic::Ordering::Acquire)
|
||||
}
|
||||
@@ -237,18 +472,17 @@ pub(crate) fn mark_prefer_stored_copilot_auth() {
|
||||
PREFER_STORED_COPILOT_AUTH.store(true, std::sync::atomic::Ordering::Release);
|
||||
}
|
||||
|
||||
pub(crate) fn has_unconfigured_copilot_ambient_token(spec_env: &[(String, String)]) -> bool {
|
||||
pub(crate) fn has_unconfigured_copilot_ambient_token(spec_env: &[(String, String)], cwd: &Path) -> bool {
|
||||
AMBIENT_COPILOT_AUTH_VARS.iter().any(|&key| {
|
||||
!spec_env.iter().any(|(k, v)| k == key && !v.is_empty())
|
||||
&& ambient_copilot_env_value(key).is_some_and(|v| !v.is_empty())
|
||||
&& ambient_copilot_env_value(key, cwd).is_some_and(|v| !v.is_empty())
|
||||
})
|
||||
}
|
||||
|
||||
fn ambient_copilot_env_value(key: &str) -> Option<String> {
|
||||
ide_core::process::shell_env()
|
||||
.find(|(k, _)| *k == key)
|
||||
.map(|(_, v)| v.to_string_lossy().into_owned())
|
||||
.or_else(|| ide_core::process::host_var_os(key).map(|v| v.to_string_lossy().into_owned()))
|
||||
fn ambient_copilot_env_value(key: &str, cwd: &Path) -> Option<String> {
|
||||
ide_core::process::host_var_os_in(cwd, key).map(|v| v.to_string_lossy().into_owned()).or_else(|| {
|
||||
ide_core::process::shell_env().find(|(k, _)| *k == key).map(|(_, v)| v.to_string_lossy().into_owned())
|
||||
})
|
||||
}
|
||||
|
||||
/// Builds child environment overrides for `copilot`:
|
||||
@@ -259,9 +493,10 @@ fn ambient_copilot_env_value(key: &str) -> Option<String> {
|
||||
/// while preserving any token explicitly configured in OpenIDEA's agent `spec_env`.
|
||||
pub(crate) fn sanitized_copilot_env(
|
||||
spec_env: &[(String, String)],
|
||||
cwd: &Path,
|
||||
strip_ambient_tokens: bool,
|
||||
) -> Vec<(String, String)> {
|
||||
sanitize_copilot_env_with(spec_env, strip_ambient_tokens, ambient_copilot_env_value)
|
||||
sanitize_copilot_env_with(spec_env, strip_ambient_tokens, |key| ambient_copilot_env_value(key, cwd))
|
||||
}
|
||||
|
||||
pub(crate) fn sanitize_copilot_env_with(
|
||||
@@ -389,6 +624,7 @@ pub(crate) fn describe(spec: &ProviderSpec) -> AgentProvider {
|
||||
command_editable: reason.is_none(),
|
||||
command_read_only_reason: reason,
|
||||
installed: installed(&spec.command),
|
||||
can_sign_in: spec.can_sign_in(Path::new("."), None),
|
||||
can_check_cli_update: spec.source == AgentSource::Builtin && crate::cli_update::package(&spec.id).is_some(),
|
||||
env: spec.env.iter().cloned().collect(),
|
||||
config: vec![],
|
||||
@@ -901,6 +1137,22 @@ mod tests {
|
||||
assert_eq!(reset.env, custom.env);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_builtin_login_hint_yields_the_arguments_sign_in_runs() {
|
||||
// Sign In runs the arguments in the hint's backticks: rewording a hint must keep that form.
|
||||
for spec in builtins() {
|
||||
if matches!(spec.id.as_str(), "claude-acp" | "codex-acp" | "vibe") {
|
||||
continue;
|
||||
}
|
||||
assert!(builtin_login_args(&spec).is_some(), "{}: {}", spec.id, spec.login_hint);
|
||||
}
|
||||
let args = |id: &str| builtin_login_args(&builtin_spec(id).unwrap()).unwrap();
|
||||
assert_eq!(args("copilot"), ["login"]);
|
||||
assert_eq!(args("goose"), ["configure"]);
|
||||
assert_eq!(args("hermes"), ["model"]);
|
||||
assert!(args("qwen").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn login_hints_cover_all_builtin_commands_and_preserve_separate_login_tools() {
|
||||
for spec in builtins() {
|
||||
@@ -1160,12 +1412,12 @@ mod tests {
|
||||
"copilot",
|
||||
BTreeMap::from([
|
||||
("REGISTRY_SETTING".into(), "kept".into()),
|
||||
(COPILOT_GITHUB_ACCOUNT_ENV.into(), "dengliu_microsoft".into()),
|
||||
(COPILOT_GITHUB_ACCOUNT_ENV.into(), "alice-work".into()),
|
||||
]),
|
||||
)
|
||||
.unwrap();
|
||||
let spec = load(Some(dir.path()), None).into_iter().find(|spec| spec.id == "copilot").unwrap();
|
||||
assert_eq!(copilot_github_account(&spec.env).as_deref(), Some("dengliu_microsoft"));
|
||||
assert_eq!(copilot_github_account(&spec.env).as_deref(), Some("alice-work"));
|
||||
|
||||
set_builtin_env(dir.path(), None, "copilot", BTreeMap::from([("REGISTRY_SETTING".into(), "changed".into())]))
|
||||
.unwrap_err();
|
||||
@@ -1174,7 +1426,7 @@ mod tests {
|
||||
#[test]
|
||||
fn launch_metadata_never_passes_the_github_account_control_to_copilot() {
|
||||
let mut spec = builtin_spec("copilot").unwrap();
|
||||
spec.env.push((COPILOT_GITHUB_ACCOUNT_ENV.into(), "dengliu_microsoft".into()));
|
||||
spec.env.push((COPILOT_GITHUB_ACCOUNT_ENV.into(), "alice-work".into()));
|
||||
let resolved = spec.resolve_for_launch(Path::new("."));
|
||||
assert!(resolved.env.iter().all(|(name, _)| name != COPILOT_GITHUB_ACCOUNT_ENV));
|
||||
}
|
||||
@@ -1458,4 +1710,68 @@ mod tests {
|
||||
vec![("GITHUB_TOKEN".into(), String::new()), ("GH_TOKEN".into(), "github_pat_custom".into())]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_gh_auth_status_json_and_text_without_ambient_token_entries() {
|
||||
let raw = r#"{
|
||||
"hosts": {
|
||||
"github.com": [
|
||||
{"state": "failed", "active": true, "login": "bad", "tokenSource": "GITHUB_TOKEN"},
|
||||
{"state": "success", "active": true, "login": "alice", "tokenSource": "keyring"},
|
||||
{"state": "success", "active": false, "login": "alice-work", "tokenSource": "keyring"},
|
||||
{"state": "success", "active": false, "login": "env_user", "tokenSource": "GH_TOKEN"}
|
||||
],
|
||||
"ghe.example.com": [
|
||||
{"state": "success", "active": true, "login": "corp", "tokenSource": "keyring"}
|
||||
]
|
||||
}
|
||||
}"#;
|
||||
assert_eq!(
|
||||
parse_gh_auth_status_json(raw),
|
||||
Some(vec![
|
||||
GhAuthAccount { login: "alice".into(), active: true },
|
||||
GhAuthAccount { login: "alice-work".into(), active: false },
|
||||
])
|
||||
);
|
||||
|
||||
let text = "\
|
||||
github.com
|
||||
✓ Logged in to github.com account env_user (GH_TOKEN)
|
||||
- Active account: true
|
||||
✓ Logged in to github.com account alice (keyring)
|
||||
- Active account: false
|
||||
✓ Logged in to github.com account alice-work (keyring)
|
||||
- Active account: true
|
||||
";
|
||||
assert_eq!(
|
||||
parse_gh_auth_status_text(text),
|
||||
vec![
|
||||
GhAuthAccount { login: "alice".into(), active: false },
|
||||
GhAuthAccount { login: "alice-work".into(), active: true },
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn login_launch_resolves_paths_with_spaces_and_clears_ambient_copilot_tokens() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let app_support = dir.path().join("Application Support/copilot");
|
||||
std::fs::create_dir_all(&app_support).unwrap();
|
||||
let bin = app_support.join(if cfg!(windows) { "copilot.cmd" } else { "copilot" });
|
||||
std::fs::write(&bin, "#!/bin/sh\n").unwrap();
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
std::fs::set_permissions(&bin, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
}
|
||||
let mut spec = builtin_spec("copilot").unwrap();
|
||||
spec.command = bin.to_string_lossy().into_owned();
|
||||
spec.source = AgentSource::Registry { version: "1.0.115".into(), update: None };
|
||||
let launch = spec.login_launch(dir.path(), None).unwrap();
|
||||
assert_eq!(launch.program, bin);
|
||||
assert_eq!(launch.args, ["login"]);
|
||||
assert_eq!(launch.env.get("GITHUB_TOKEN").map(String::as_str), Some(""));
|
||||
assert_eq!(launch.env.get("GH_TOKEN").map(String::as_str), Some(""));
|
||||
assert_eq!(launch.env.get("COPILOT_GITHUB_TOKEN").map(String::as_str), Some(""));
|
||||
}
|
||||
}
|
||||
@@ -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('.')
|
||||
@@ -443,7 +467,15 @@ fn write_atomic(path: &Path, bytes: &[u8]) -> std::io::Result<()> {
|
||||
|
||||
/// Installs (or updates to) the registry's current version of `id`, streaming progress
|
||||
/// through `emit`, and points the agent file at it.
|
||||
pub fn install(paths: &RegistryPaths, id: &str, cancel: &CancellationToken, emit: Emit) -> IdeResult<()> {
|
||||
/// Installs agent `id`; an npm package retries against the public npm registry when the
|
||||
/// configured one misses it only with `public_npm_fallback`.
|
||||
pub fn install(
|
||||
paths: &RegistryPaths,
|
||||
id: &str,
|
||||
public_npm_fallback: bool,
|
||||
cancel: &CancellationToken,
|
||||
emit: Emit,
|
||||
) -> IdeResult<()> {
|
||||
let id = canonical_id(id);
|
||||
// The saved index is what the user picked from; fetch only when there is none.
|
||||
let text = match fs::read_to_string(&paths.cache_file) {
|
||||
@@ -455,9 +487,14 @@ pub fn install(paths: &RegistryPaths, id: &str, cancel: &CancellationToken, emit
|
||||
.iter()
|
||||
.find(|e| e.id == id)
|
||||
.ok_or_else(|| IdeError::not_found(format!("{id} is not in the ACP Registry")))?;
|
||||
install_entry(paths, entry, Platform::current(), &on_path, cancel, emit)
|
||||
let npm_installer =
|
||||
move |p: &Package, entry: &Entry, dir: &Path, platform, cancel: &CancellationToken, emit: Emit| {
|
||||
install_npm(p, entry, dir, platform, public_npm_fallback, cancel, emit)
|
||||
};
|
||||
install_entry_with(paths, entry, Platform::current(), &on_path, &npm_installer, cancel, emit)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn install_entry(
|
||||
paths: &RegistryPaths,
|
||||
entry: &Entry,
|
||||
@@ -466,7 +503,10 @@ fn install_entry(
|
||||
cancel: &CancellationToken,
|
||||
emit: Emit,
|
||||
) -> IdeResult<()> {
|
||||
install_entry_with(paths, entry, platform, on_path, &install_npm, cancel, emit)
|
||||
let npm_installer = |p: &Package, entry: &Entry, dir: &Path, platform, cancel: &CancellationToken, emit: Emit| {
|
||||
install_npm(p, entry, dir, platform, true, cancel, emit)
|
||||
};
|
||||
install_entry_with(paths, entry, platform, on_path, &npm_installer, cancel, emit)
|
||||
}
|
||||
|
||||
type NpmInstaller = dyn Fn(&Package, &Entry, &Path, Platform, &CancellationToken, Emit) -> IdeResult<PathBuf>;
|
||||
@@ -663,20 +703,23 @@ fn install_npm(
|
||||
entry: &Entry,
|
||||
dir: &Path,
|
||||
platform: Platform,
|
||||
public_fallback: bool,
|
||||
cancel: &CancellationToken,
|
||||
emit: Emit,
|
||||
) -> IdeResult<PathBuf> {
|
||||
let (name, _) = split_npm_spec(&p.package);
|
||||
let npm = which::which("npm").map_err(|_| IdeError::unavailable(format!("npm is required to install {name}")))?;
|
||||
install_npm_with(&npm, p, entry, dir, platform, cancel, emit)
|
||||
install_npm_with(&npm, p, entry, dir, platform, public_fallback, cancel, emit)
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn install_npm_with(
|
||||
npm: &Path,
|
||||
p: &Package,
|
||||
entry: &Entry,
|
||||
dir: &Path,
|
||||
platform: Platform,
|
||||
public_fallback: bool,
|
||||
cancel: &CancellationToken,
|
||||
emit: Emit,
|
||||
) -> IdeResult<PathBuf> {
|
||||
@@ -704,6 +747,7 @@ fn install_npm_with(
|
||||
},
|
||||
&specs,
|
||||
false,
|
||||
public_fallback,
|
||||
cancel,
|
||||
emit,
|
||||
)?;
|
||||
@@ -1004,7 +1048,7 @@ mod tests {
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn npm_registry_agent_retries_against_public_npmjs_on_mirror_miss() {
|
||||
fn npm_registry_agent_retries_against_public_npmjs_on_mirror_miss_unless_registries_are_configured_only() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let install_dir = dir.path().join("acme/1.2.0");
|
||||
fs::create_dir_all(&install_dir).unwrap();
|
||||
@@ -1043,8 +1087,8 @@ esac
|
||||
]}"#;
|
||||
let entry = parse(index).unwrap().remove(0);
|
||||
let pkg = entry.distribution.npx.as_ref().unwrap();
|
||||
let exe =
|
||||
install_npm_with(&npm, pkg, &entry, &install_dir, MAC_ARM, &CancellationToken::new(), &|_| {}).unwrap();
|
||||
let exe = install_npm_with(&npm, pkg, &entry, &install_dir, MAC_ARM, true, &CancellationToken::new(), &|_| {})
|
||||
.unwrap();
|
||||
let calls: Vec<String> = fs::read_to_string(&log).unwrap().lines().map(str::to_owned).collect();
|
||||
assert_eq!(calls.len(), 2, "{calls:?}");
|
||||
assert!(!calls[0].contains("--registry="), "{calls:?}");
|
||||
@@ -1052,6 +1096,15 @@ esac
|
||||
assert!(calls[1].contains("--@acme:registry=https://registry.npmjs.org/"), "{calls:?}");
|
||||
assert_eq!(exe, install_dir.join("node_modules/.bin/agent-acp"));
|
||||
assert!(exe.is_file());
|
||||
// Only the configured registries: the miss is the error, and npmjs is never asked.
|
||||
let only = dir.path().join("acme-only/1.2.0");
|
||||
fs::create_dir_all(&only).unwrap();
|
||||
let err =
|
||||
install_npm_with(&npm, pkg, &entry, &only, MAC_ARM, false, &CancellationToken::new(), &|_| {}).unwrap_err();
|
||||
let calls: Vec<String> = fs::read_to_string(&log).unwrap().lines().map(str::to_owned).collect();
|
||||
assert_eq!(calls.len(), 3, "{calls:?}");
|
||||
assert!(!calls[2].contains("--registry="), "{calls:?}");
|
||||
assert!(err.message.contains("notarget"), "{err:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1183,7 +1236,7 @@ esac
|
||||
write_atomic(&p.cache_file, index.as_bytes()).unwrap();
|
||||
let spec = provider::load(Some(&p.agents_dir), None).into_iter().find(|s| s.id == "copilot").unwrap();
|
||||
assert_eq!(spec.name, "GitHub Copilot");
|
||||
assert_eq!(spec.login_hint, "Run `copilot` in a terminal and sign in.");
|
||||
assert_eq!(spec.login_hint, "Run `copilot login` in a terminal.");
|
||||
assert_eq!(spec.source, AgentSource::Registry { version: "1.0.104".into(), update: None });
|
||||
|
||||
let mut providers = vec![provider::describe(&spec)];
|
||||
@@ -1275,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(),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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;
|
||||
@@ -611,6 +645,7 @@ mod tests {
|
||||
sent_ms: Some(sent),
|
||||
done_ms: None,
|
||||
steered: false,
|
||||
recovery: None,
|
||||
};
|
||||
let mut t = Timeline::default();
|
||||
t.push(user(1.0));
|
||||
@@ -632,6 +667,7 @@ mod tests {
|
||||
sent_ms: Some(sent),
|
||||
done_ms: None,
|
||||
steered,
|
||||
recovery: None,
|
||||
};
|
||||
let mut t = Timeline::default();
|
||||
t.push(user(1.0, false));
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "ide-android"
|
||||
description = "Android devices and logcat for the Logcat tool window, driven through the adb CLI"
|
||||
description = "Android devices and iOS Simulators and their logs for the Logcat tool window, driven through adb and simctl"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
@@ -8,6 +8,7 @@ license.workspace = true
|
||||
[dependencies]
|
||||
ide-core.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
specta.workspace = true
|
||||
which = "8"
|
||||
|
||||
|
||||
@@ -0,0 +1,199 @@
|
||||
//! iOS Simulators and their unified log, driven through `xcrun simctl` (macOS only).
|
||||
//!
|
||||
//! A simulator's log is followed with `simctl spawn <udid> log stream --style ndjson`
|
||||
//! and parsed into the same [`LogcatLine`] the Android log uses, so the Logcat tool
|
||||
//! window shows both with one level filter and one filter language.
|
||||
|
||||
use crate::model::{LogcatLevel, LogcatLine};
|
||||
use crate::process;
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use std::process::Command;
|
||||
use std::time::Duration;
|
||||
|
||||
const LIST: Duration = Duration::from_secs(20);
|
||||
const BATCH_IDLE: Duration = Duration::from_millis(60);
|
||||
const BATCH_MAX: usize = 300;
|
||||
|
||||
/// A booted simulator, as `simctl list devices booted -j` reports it.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct BootedSimulator {
|
||||
pub udid: String,
|
||||
pub name: String,
|
||||
/// e.g. `iOS 27.0`.
|
||||
pub runtime: String,
|
||||
}
|
||||
|
||||
/// Booted simulators; empty off macOS or without Xcode, so nothing iOS-related shows there.
|
||||
pub fn booted_simulators() -> IdeResult<Vec<BootedSimulator>> {
|
||||
if !cfg!(target_os = "macos") {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let mut cmd = Command::new("xcrun");
|
||||
cmd.args(["simctl", "list", "devices", "booted", "-j"]);
|
||||
match process::run(cmd, LIST, None) {
|
||||
Ok(out) if out.success => Ok(parse_simulators(&out.stdout)),
|
||||
// No Xcode (only the Command Line Tools, or none): there are no simulators.
|
||||
_ => Ok(Vec::new()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Parses `simctl list devices -j`, keeping booted devices.
|
||||
pub fn parse_simulators(json: &str) -> Vec<BootedSimulator> {
|
||||
#[derive(Deserialize)]
|
||||
struct List {
|
||||
devices: std::collections::BTreeMap<String, Vec<Device>>,
|
||||
}
|
||||
#[derive(Deserialize)]
|
||||
struct Device {
|
||||
udid: String,
|
||||
name: String,
|
||||
state: String,
|
||||
}
|
||||
let Ok(list) = serde_json::from_str::<List>(json) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let mut out = Vec::new();
|
||||
for (runtime, devices) in list.devices {
|
||||
// "com.apple.CoreSimulator.SimRuntime.iOS-27-0" → "iOS 27.0"
|
||||
let short = runtime.rsplit('.').next().unwrap_or(&runtime);
|
||||
let runtime = short.split_once('-').map_or(short.to_owned(), |(os, v)| format!("{os} {}", v.replace('-', ".")));
|
||||
for d in devices.into_iter().filter(|d| d.state == "Booted") {
|
||||
out.push(BootedSimulator { udid: d.udid, name: d.name, runtime: runtime.clone() });
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Message type of the unified log → the logcat level the window filters and colors by.
|
||||
fn level(message_type: &str) -> LogcatLevel {
|
||||
match message_type {
|
||||
"Debug" => LogcatLevel::Debug,
|
||||
"Info" | "Default" => LogcatLevel::Info,
|
||||
"Error" => LogcatLevel::Error,
|
||||
"Fault" => LogcatLevel::Fatal,
|
||||
_ => LogcatLevel::Verbose,
|
||||
}
|
||||
}
|
||||
|
||||
/// One NDJSON entry of `log stream --style ndjson`; `None` for anything that is not a
|
||||
/// log message (activities, the trailing "terminated" notice). Unknown fields are ignored.
|
||||
pub fn parse_ndjson(line: &str) -> Option<LogcatLine> {
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct Entry {
|
||||
event_type: String,
|
||||
#[serde(default)]
|
||||
message_type: String,
|
||||
#[serde(default)]
|
||||
timestamp: String,
|
||||
#[serde(default)]
|
||||
process_image_path: String,
|
||||
#[serde(rename = "processID", default)]
|
||||
pid: i64,
|
||||
#[serde(rename = "threadID", default)]
|
||||
tid: i64,
|
||||
#[serde(default)]
|
||||
subsystem: String,
|
||||
#[serde(default)]
|
||||
category: String,
|
||||
#[serde(default)]
|
||||
event_message: String,
|
||||
}
|
||||
let e: Entry = serde_json::from_str(line).ok()?;
|
||||
if e.event_type != "logEvent" {
|
||||
return None;
|
||||
}
|
||||
let process = e.process_image_path.rsplit('/').next().unwrap_or_default();
|
||||
let tag = match (e.subsystem.is_empty(), e.category.is_empty()) {
|
||||
(true, _) => process.to_owned(),
|
||||
(false, true) => format!("{process} ({})", e.subsystem),
|
||||
(false, false) => format!("{process} ({}:{})", e.subsystem, e.category),
|
||||
};
|
||||
// "2026-11-29 14:39:31.696480+0900" → "11-29 14:39:31.696", logcat's shape.
|
||||
let time = e.timestamp.get(5..23).unwrap_or(&e.timestamp).to_owned();
|
||||
Some(LogcatLine {
|
||||
time,
|
||||
pid: e.pid as i32,
|
||||
tid: e.tid as i32,
|
||||
level: level(&e.message_type),
|
||||
tag,
|
||||
message: e.event_message,
|
||||
})
|
||||
}
|
||||
|
||||
/// Follows simulator `udid`'s log until `cancel` fires or the simulator shuts down.
|
||||
pub fn simulator_log(
|
||||
udid: &str,
|
||||
cancel: &CancellationToken,
|
||||
on_batch: &mut dyn FnMut(Vec<LogcatLine>),
|
||||
) -> IdeResult<()> {
|
||||
let mut cmd = Command::new("xcrun");
|
||||
cmd.args(["simctl", "spawn", udid, "log", "stream", "--style", "ndjson", "--level", "debug"]);
|
||||
match process::stream_batched(cmd, cancel, BATCH_IDLE, BATCH_MAX, parse_ndjson, on_batch) {
|
||||
Ok((ok, _)) if ok || cancel.is_cancelled() => Ok(()),
|
||||
// `log stream` is killed when the simulator shuts down: that is an end, not a failure.
|
||||
Ok((_, stderr)) if stderr.iter().any(|l| l.contains("terminated with signal")) => Ok(()),
|
||||
Ok((_, stderr)) => Err(IdeError::unavailable(format!("log stream on {udid} stopped: {}", stderr.join("\n")))),
|
||||
Err(e) if e.kind == ide_core::error::ErrorKind::Cancelled => Ok(()),
|
||||
Err(e) => Err(e),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const ENTRY: &str = r#"{"timezoneName":"","messageType":"Error","eventType":"logEvent","source":null,"subsystem":"com.apple.network","category":"endpoint","threadID":90176044,"processImagePath":"\/usr\/libexec\/remindd","timestamp":"2026-11-29 14:39:31.696480+0900","eventMessage":"endpoint has nothing to cleanup","processID":64339,"someFutureField":{"x":[1,2]}}"#;
|
||||
|
||||
#[test]
|
||||
fn parses_an_entry_and_ignores_unknown_fields() {
|
||||
let line = parse_ndjson(ENTRY).unwrap();
|
||||
assert_eq!(line.time, "11-29 14:39:31.696");
|
||||
assert_eq!(line.pid, 64339);
|
||||
assert_eq!(line.tid, 90176044);
|
||||
assert_eq!(line.level, LogcatLevel::Error);
|
||||
assert_eq!(line.tag, "remindd (com.apple.network:endpoint)");
|
||||
assert_eq!(line.message, "endpoint has nothing to cleanup");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_a_multi_line_message_whole() {
|
||||
let entry = r#"{"eventType":"logEvent","messageType":"Default","processImagePath":"/a/MyApp","processID":7,"eventMessage":"first\nsecond"}"#;
|
||||
let line = parse_ndjson(entry).unwrap();
|
||||
assert_eq!(line.message, "first\nsecond");
|
||||
assert_eq!(line.tag, "MyApp");
|
||||
assert_eq!(line.level, LogcatLevel::Info);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn skips_what_is_not_a_log_message() {
|
||||
assert!(parse_ndjson(r#"{"eventType":"activityCreateEvent","eventMessage":"x"}"#).is_none());
|
||||
assert!(parse_ndjson("Child process terminated with signal 15: Terminated").is_none());
|
||||
assert!(parse_ndjson("").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maps_message_types_to_levels() {
|
||||
assert_eq!(level("Debug"), LogcatLevel::Debug);
|
||||
assert_eq!(level("Info"), LogcatLevel::Info);
|
||||
assert_eq!(level("Default"), LogcatLevel::Info);
|
||||
assert_eq!(level("Error"), LogcatLevel::Error);
|
||||
assert_eq!(level("Fault"), LogcatLevel::Fatal);
|
||||
assert_eq!(level("Signpost"), LogcatLevel::Verbose);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_booted_simulators() {
|
||||
let json = r#"{"devices":{"com.apple.CoreSimulator.SimRuntime.iOS-27-0":[
|
||||
{"udid":"A","name":"iPhone Air","state":"Booted","isAvailable":true},
|
||||
{"udid":"B","name":"iPhone 18","state":"Shutdown"}]}}"#;
|
||||
assert_eq!(
|
||||
parse_simulators(json),
|
||||
vec![BootedSimulator { udid: "A".into(), name: "iPhone Air".into(), runtime: "iOS 27.0".into() }]
|
||||
);
|
||||
assert!(parse_simulators("not json").is_empty());
|
||||
}
|
||||
}
|
||||
@@ -7,9 +7,11 @@
|
||||
//!
|
||||
//! Every function blocks; callers run them off the UI / command threads.
|
||||
|
||||
mod ios;
|
||||
mod model;
|
||||
mod process;
|
||||
|
||||
pub use ios::{BootedSimulator, booted_simulators, parse_ndjson, parse_simulators, simulator_log};
|
||||
pub use model::*;
|
||||
|
||||
use ide_core::process::{own_group, prepare};
|
||||
|
||||
@@ -29,6 +29,7 @@ pub use up_to_date::{menu_up_to_date, record_menu_build};
|
||||
|
||||
use crate::process::{self, Stream};
|
||||
use crate::{BuildModel, maven};
|
||||
use ide_core::build_jobs::append_default_jobs;
|
||||
use ide_core::settings::CMakeProfile;
|
||||
use ide_core::{CancellationToken, Diagnostic, IdeError, IdeResult, Pos, Range, Severity};
|
||||
use parse::{ColUnit, Format, OutputParser, RawMessage};
|
||||
@@ -420,7 +421,8 @@ fn cargo_steps(dir: &Path, kind: BuildKind) -> Vec<BuildStep> {
|
||||
}
|
||||
|
||||
/// CLion's Build Project for a CMake project: configures the build directory when it has no
|
||||
/// `CMakeCache.txt` yet, then `cmake --build` (`--clean-first` to rebuild). The directory and
|
||||
/// `CMakeCache.txt` yet, then `cmake --build` (`--clean-first` to rebuild), one job per
|
||||
/// logical CPU unless the profile's build arguments choose a count. The directory and
|
||||
/// options come from the CMake profile; without one, a configured directory of the project
|
||||
/// (the first by name), else `build`, as the generated run configurations use.
|
||||
fn cmake_steps(dir: &Path, kind: BuildKind, profile: Option<&CMakeProfile>) -> Vec<BuildStep> {
|
||||
@@ -458,6 +460,7 @@ fn cmake_steps(dir: &Path, kind: BuildKind, profile: Option<&CMakeProfile>) -> V
|
||||
build.args.push("--clean-first".into());
|
||||
}
|
||||
build.args.extend(profile.map(|p| p.build_args.clone()).unwrap_or_default());
|
||||
append_default_jobs(&mut build.args);
|
||||
build.env = env;
|
||||
steps.push(build);
|
||||
steps
|
||||
@@ -1508,14 +1511,15 @@ mod tests {
|
||||
let cm = tmp.path().join("cm");
|
||||
write(&cm, "CMakeLists.txt", "project(app)");
|
||||
let args = |p: &BuildPlan| p.steps.iter().map(|s| s.args.join(" ")).collect::<Vec<_>>();
|
||||
let jobs = format!("-j {}", ide_core::build_jobs::default_jobs());
|
||||
let p =
|
||||
plan(&cm, &BuildModel::default(), BuildKind::Build, None, None, None, &CancellationToken::new()).unwrap();
|
||||
assert_eq!(p.system, BuildSystem::CMake);
|
||||
assert_eq!(
|
||||
args(&p),
|
||||
[
|
||||
"-S . -B build -DCMAKE_BUILD_TYPE=Debug -DCMAKE_EXPORT_COMPILE_COMMANDS=ON",
|
||||
"--build build --config Debug"
|
||||
"-S . -B build -DCMAKE_BUILD_TYPE=Debug -DCMAKE_EXPORT_COMPILE_COMMANDS=ON".to_owned(),
|
||||
format!("--build build --config Debug {jobs}"),
|
||||
],
|
||||
"an unconfigured project is configured first"
|
||||
);
|
||||
@@ -1524,7 +1528,7 @@ mod tests {
|
||||
plan(&cm, &BuildModel::default(), BuildKind::Rebuild, None, None, None, &CancellationToken::new()).unwrap();
|
||||
assert_eq!(
|
||||
args(&p),
|
||||
["--build cmake-build-release --config Debug --clean-first"],
|
||||
[format!("--build cmake-build-release --config Debug --clean-first {jobs}")],
|
||||
"a configured directory is reused"
|
||||
);
|
||||
let profile = CMakeProfile {
|
||||
|
||||
@@ -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"))],
|
||||
|
||||
@@ -5,8 +5,10 @@
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use std::collections::BTreeMap;
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Mutex;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
pub const SETTINGS_FILES: &[&str] = &["settings.gradle.kts", "settings.gradle"];
|
||||
pub const BUILD_FILES: &[&str] = &["build.gradle.kts", "build.gradle"];
|
||||
@@ -227,9 +229,41 @@ pub fn build_dir(root: &Path) -> Option<PathBuf> {
|
||||
build_dirs(root).into_iter().next()
|
||||
}
|
||||
|
||||
/// How long [`cached_build_dirs`] reuses a walk. Project roots, content roots and the index
|
||||
/// ask for the builds many times while a project opens; on a network share each walk is
|
||||
/// thousands of round trips. A build file changing in a project calls [`forget_build_dirs`].
|
||||
const BUILD_DIRS_TTL: Duration = Duration::from_secs(30);
|
||||
|
||||
type BuildDirsCache = HashMap<PathBuf, (Instant, Vec<PathBuf>)>;
|
||||
|
||||
static BUILD_DIRS: Mutex<Option<BuildDirsCache>> = Mutex::new(None);
|
||||
|
||||
/// Walks for builds now; the result also refreshes [`cached_build_dirs`].
|
||||
fn build_dirs(root: &Path) -> Vec<PathBuf> {
|
||||
let markers: Vec<_> = SETTINGS_FILES.iter().chain(BUILD_FILES).copied().collect();
|
||||
ide_core::project_roots::discover(root, &markers)
|
||||
let dirs = ide_core::project_roots::discover(root, &markers);
|
||||
let now = Instant::now();
|
||||
let mut guard = BUILD_DIRS.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let map = guard.get_or_insert_with(HashMap::new);
|
||||
map.retain(|_, (at, _)| now.duration_since(*at) < BUILD_DIRS_TTL);
|
||||
map.insert(root.to_path_buf(), (now, dirs.clone()));
|
||||
dirs
|
||||
}
|
||||
|
||||
fn cached_build_dirs(root: &Path) -> Vec<PathBuf> {
|
||||
let cached = BUILD_DIRS.lock().unwrap_or_else(|e| e.into_inner()).as_ref().and_then(|m| m.get(root)).cloned();
|
||||
match cached {
|
||||
Some((at, dirs)) if at.elapsed() < BUILD_DIRS_TTL => dirs,
|
||||
_ => build_dirs(root),
|
||||
}
|
||||
}
|
||||
|
||||
/// Forgets the discovered Gradle builds of `root`, and of folders above or below it
|
||||
/// (after a build or settings script appeared, changed or was removed there).
|
||||
pub fn forget_build_dirs(root: &Path) {
|
||||
if let Some(map) = BUILD_DIRS.lock().unwrap_or_else(|e| e.into_inner()).as_mut() {
|
||||
map.retain(|dir, _| !dir.starts_with(root) && !root.starts_with(dir));
|
||||
}
|
||||
}
|
||||
|
||||
fn wrapper(dir: &Path) -> String {
|
||||
@@ -506,10 +540,23 @@ pub fn linked_project_key(root: &Path, dir: &str) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// Linked build identities without reading their scripts (also used by index hot paths).
|
||||
/// Linked build identities without reading their scripts, as of now (a sync, a build).
|
||||
pub(crate) fn linked_dirs(root: &Path, settings: &ide_core::settings::GradleSettings) -> Vec<String> {
|
||||
linked_dirs_from(root, settings, build_dirs)
|
||||
}
|
||||
|
||||
/// [`linked_dirs`] for hot paths (project and index roots): discovered builds are reused for a while.
|
||||
pub(crate) fn linked_dirs_cached(root: &Path, settings: &ide_core::settings::GradleSettings) -> Vec<String> {
|
||||
linked_dirs_from(root, settings, cached_build_dirs)
|
||||
}
|
||||
|
||||
fn linked_dirs_from(
|
||||
root: &Path,
|
||||
settings: &ide_core::settings::GradleSettings,
|
||||
discover: fn(&Path) -> Vec<PathBuf>,
|
||||
) -> Vec<String> {
|
||||
match &settings.linked_projects {
|
||||
None => build_dirs(root).iter().map(|dir| rel(root, dir)).collect(),
|
||||
None => discover(root).iter().map(|dir| rel(root, dir)).collect(),
|
||||
Some(dirs) => {
|
||||
let mut out = Vec::new();
|
||||
for dir in dirs {
|
||||
@@ -1047,6 +1094,27 @@ pub(crate) fn has_war_plugin(script: &str) -> bool {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn discovered_builds_are_reused_until_forgotten() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let root = temp.path();
|
||||
std::fs::create_dir_all(root.join("a")).unwrap();
|
||||
std::fs::write(root.join("a/settings.gradle"), "").unwrap();
|
||||
assert_eq!(super::cached_build_dirs(root), vec![root.join("a")]);
|
||||
std::fs::create_dir_all(root.join("b")).unwrap();
|
||||
std::fs::write(root.join("b/build.gradle"), "").unwrap();
|
||||
// A walk per call is thousands of round trips on a network share.
|
||||
assert_eq!(super::cached_build_dirs(root), vec![root.join("a")]);
|
||||
super::forget_build_dirs(&root.join("b"));
|
||||
assert_eq!(super::cached_build_dirs(root), vec![root.join("a"), root.join("b")]);
|
||||
// A sync sees a new build at once, and so does every later lookup.
|
||||
std::fs::create_dir_all(root.join("c")).unwrap();
|
||||
std::fs::write(root.join("c/build.gradle"), "").unwrap();
|
||||
let all = vec![root.join("a"), root.join("b"), root.join("c")];
|
||||
assert_eq!(super::build_dirs(root), all);
|
||||
assert_eq!(super::cached_build_dirs(root), all);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_linkage_discovers_all_shallow_builds() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -129,7 +129,7 @@ pub fn gradle_external_roots(
|
||||
cache_dir: &Path,
|
||||
settings: &ide_core::settings::GradleSettings,
|
||||
) -> Vec<PathBuf> {
|
||||
let builds = gradle::linked_dirs(root, settings);
|
||||
let builds = gradle::linked_dirs_cached(root, settings);
|
||||
let dirs: Vec<String> = builds
|
||||
.iter()
|
||||
.flat_map(|dir| {
|
||||
@@ -171,7 +171,7 @@ pub fn gradle_source_roots(
|
||||
cache_dir: &Path,
|
||||
settings: &ide_core::settings::GradleSettings,
|
||||
) -> Vec<(PathBuf, gradle::ReportedRoot, PathBuf)> {
|
||||
let reported = gradle::linked_dirs(root, settings)
|
||||
let reported = gradle::linked_dirs_cached(root, settings)
|
||||
.iter()
|
||||
.flat_map(|dir| sync::reported_gradle_projects(&gradle::cache_dir(cache_dir, dir)).as_ref().clone())
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
|
||||
@@ -27,4 +27,4 @@ libc = "0.2"
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
dirs.workspace = true
|
||||
tracing.workspace = true
|
||||
windows-sys = { version = "0.61", features = ["Wdk_System_SystemServices", "Win32_Foundation", "Win32_Globalization", "Win32_Security", "Win32_System_Console", "Win32_System_Diagnostics_ToolHelp", "Win32_System_IO", "Win32_System_JobObjects", "Win32_System_LibraryLoader", "Win32_System_Registry", "Win32_System_SystemInformation", "Win32_System_Threading"] }
|
||||
windows-sys = { version = "0.61", features = ["Wdk_System_SystemServices", "Win32_Foundation", "Win32_Globalization", "Win32_Security", "Win32_System_Console", "Win32_System_Diagnostics_ToolHelp", "Win32_System_IO", "Win32_System_JobObjects", "Win32_System_LibraryLoader", "Win32_System_Registry", "Win32_Storage_FileSystem", "Win32_System_SystemInformation", "Win32_System_Threading"] }
|
||||
@@ -0,0 +1,74 @@
|
||||
//! Parallelism for build tools whose default is one compiler process at a time.
|
||||
//!
|
||||
//! `cmake --build` with a Makefile generator (the default) compiles one file at a
|
||||
//! time unless it is given `-j N`; the IDE asks for one job per logical CPU. A count
|
||||
//! the user wrote into the build arguments is left alone.
|
||||
|
||||
/// Jobs a native build tool gets when the user did not choose a count.
|
||||
pub fn default_jobs() -> usize {
|
||||
std::thread::available_parallelism().map_or(1, |jobs| jobs.get())
|
||||
}
|
||||
|
||||
/// Appends `-j <jobs>` unless `args` already carries the user's own count. The count
|
||||
/// goes before a `--` separator, so cmake's own options stay cmake's and the native
|
||||
/// build tool's options stay last.
|
||||
pub fn append_default_jobs(args: &mut Vec<String>) {
|
||||
if args.iter().any(|arg| is_jobs_flag(arg)) {
|
||||
return;
|
||||
}
|
||||
let jobs = default_jobs().to_string();
|
||||
let at = args.iter().position(|arg| arg == "--").unwrap_or(args.len());
|
||||
args.splice(at..at, ["-j".to_owned(), jobs]);
|
||||
}
|
||||
|
||||
/// `-j`, `-j8`, `--parallel`, `--parallel=8`, `--jobs`, `--jobs=8`.
|
||||
fn is_jobs_flag(arg: &str) -> bool {
|
||||
let count = |rest: &str| rest.chars().all(|c| c.is_ascii_digit());
|
||||
arg.strip_prefix("-j").is_some_and(count)
|
||||
|| arg.strip_prefix("--parallel=").is_some_and(count)
|
||||
|| arg.strip_prefix("--jobs=").is_some_and(count)
|
||||
|| arg == "--parallel"
|
||||
|| arg == "--jobs"
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn args_of(values: &[&str]) -> Vec<String> {
|
||||
values.iter().map(|value| (*value).to_owned()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_default_is_one_job_per_logical_cpu() {
|
||||
let expected = std::thread::available_parallelism().map_or(1, |jobs| jobs.get());
|
||||
assert_eq!(default_jobs(), expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_build_without_a_count_gets_one() {
|
||||
let mut argv = args_of(&["--build", "build", "--config", "Debug"]);
|
||||
append_default_jobs(&mut argv);
|
||||
assert_eq!(argv, args_of(&["--build", "build", "--config", "Debug", "-j", &default_jobs().to_string()]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_count_the_user_chose_is_left_alone() {
|
||||
let own: [&[&str]; 6] =
|
||||
[&["-j", "2"], &["-j8"], &["-j", "2"], &["--parallel", "2"], &["--parallel=2"], &["--jobs=2"]];
|
||||
for flags in own {
|
||||
let mut argv = args_of(&["--build", "build"]);
|
||||
argv.extend(flags.iter().map(|value| (*value).to_owned()));
|
||||
let expected = argv.clone();
|
||||
append_default_jobs(&mut argv);
|
||||
assert_eq!(argv, expected, "the build arguments set the count");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_count_stays_before_native_build_tool_options() {
|
||||
let mut argv = args_of(&["--build", "build", "--", "VERBOSE=1"]);
|
||||
append_default_jobs(&mut argv);
|
||||
assert_eq!(argv, args_of(&["--build", "build", "-j", &default_jobs().to_string(), "--", "VERBOSE=1"]));
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -296,6 +302,12 @@ pub struct SmartKeysSettings {
|
||||
pub simultaneous_tag_editing: bool,
|
||||
/// Reformat on paste: `none` | `indentBlock` | `indentEachLine`.
|
||||
pub reformat_on_paste: String,
|
||||
/// Advanced Settings: Copy/Cut without a selection copies the whole caret lines.
|
||||
pub copy_line_when_no_selection: bool,
|
||||
/// Advanced Settings: Copy selects the lines copied without a selection.
|
||||
pub select_copied_line: bool,
|
||||
/// Advanced Settings: linewise paste `above` the caret | `caret` | `trim` at mid-line.
|
||||
pub line_paste_mode: String,
|
||||
pub escape_on_paste: bool,
|
||||
pub smart_indent: bool,
|
||||
/// Enter › Insert documentation comment stub: Enter after `/**` closes the comment.
|
||||
@@ -316,6 +328,9 @@ impl Default for SmartKeysSettings {
|
||||
semicolon_at_statement_end: true,
|
||||
simultaneous_tag_editing: true,
|
||||
reformat_on_paste: "indentEachLine".into(),
|
||||
copy_line_when_no_selection: true,
|
||||
select_copied_line: true,
|
||||
line_paste_mode: "above".into(),
|
||||
escape_on_paste: true,
|
||||
smart_indent: true,
|
||||
insert_doc_stub: true,
|
||||
@@ -486,6 +501,16 @@ pub struct LanguageCodeStyle {
|
||||
/// SQL › Case › Identifiers (unquoted names): `upper` | `lower` | `keep`.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub identifier_case: Option<String>,
|
||||
/// Java: organize imports switches to a wildcard import once this many
|
||||
/// classes of one package are used (jdtls `starThreshold`; IDEA's default
|
||||
/// 5; unset keeps the language server's default).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub class_count_to_use_import_with_star: Option<u32>,
|
||||
/// Java: organize imports switches to a wildcard static import once this
|
||||
/// many statically imported names are used (jdtls `staticStarThreshold`;
|
||||
/// IDEA's default 3; unset keeps the language server's default).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub names_count_to_use_static_import_with_star: Option<u32>,
|
||||
/// JavaScript / TypeScript › Punctuation › Semicolons: `ignore` | `insert` | `remove`.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub semicolons: Option<String>,
|
||||
@@ -495,6 +520,19 @@ pub struct LanguageCodeStyle {
|
||||
/// JavaScript / TypeScript › Spaces, by tsserver format option (`insertSpaceAfterCommaDelimiter`).
|
||||
#[serde(skip_serializing_if = "BTreeMap::is_empty")]
|
||||
pub spaces: BTreeMap<String, bool>,
|
||||
/// JavaScript / TypeScript › Imports › Import paths:
|
||||
/// `shortest` | `relative` | `non-relative` | `project-relative`.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub import_module_specifier: Option<String>,
|
||||
/// JavaScript / TypeScript › Imports › Import path ending: `auto` | `minimal` | `index` | `js`.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub import_module_specifier_ending: Option<String>,
|
||||
/// JavaScript / TypeScript › Imports › Do not auto-import from (globs).
|
||||
#[serde(skip_serializing_if = "Vec::is_empty")]
|
||||
pub auto_import_file_exclude_patterns: Vec<String>,
|
||||
/// JavaScript / TypeScript › Imports › Do not auto-import specifiers matching (regexes).
|
||||
#[serde(skip_serializing_if = "Vec::is_empty")]
|
||||
pub auto_import_specifier_exclude_regexes: Vec<String>,
|
||||
}
|
||||
|
||||
/// Editor › Code Style (General tab + per-language overrides).
|
||||
@@ -552,6 +590,25 @@ pub struct EncodingSettings {
|
||||
pub native_to_ascii: bool,
|
||||
/// Create UTF-8 files: `never` (no BOM) | `always` (with BOM) | `windows` (with BOM on Windows).
|
||||
pub utf8_bom: String,
|
||||
/// Encoding (WHATWG label) of a file or of the files in a folder, by its path
|
||||
/// relative to the project with `/` separators. The status bar's choice is kept here.
|
||||
#[serde(deserialize_with = "labels")]
|
||||
#[specta(type = BTreeMap<String, String>)]
|
||||
pub mappings: BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
/// A hand-edited entry that is not a label is left out, rather than failing the whole settings file.
|
||||
fn labels<'de, D: serde::Deserializer<'de>>(d: D) -> Result<BTreeMap<String, String>, D::Error> {
|
||||
let serde_json::Value::Object(entries) = serde_json::Value::deserialize(d)? else {
|
||||
return Ok(BTreeMap::new());
|
||||
};
|
||||
Ok(entries
|
||||
.into_iter()
|
||||
.filter_map(|(path, label)| match label {
|
||||
serde_json::Value::String(label) => Some((path, label)),
|
||||
_ => None,
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
impl Default for EncodingSettings {
|
||||
@@ -562,10 +619,30 @@ impl Default for EncodingSettings {
|
||||
properties: "iso-8859-1".into(),
|
||||
native_to_ascii: false,
|
||||
utf8_bom: "never".into(),
|
||||
mappings: BTreeMap::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod encoding_mappings_tests {
|
||||
use super::EncodingSettings;
|
||||
|
||||
#[test]
|
||||
fn encoding_mappings_keep_the_entries_that_are_labels() {
|
||||
let json = serde_json::json!({
|
||||
"project": "gbk",
|
||||
"mappings": { "src/main/java": "iso-8859-15", "count": 5, "nested": { "a": "utf-8" } },
|
||||
});
|
||||
let settings: EncodingSettings = serde_json::from_value(json).unwrap();
|
||||
assert_eq!(settings.project, "gbk");
|
||||
assert_eq!(settings.mappings.into_iter().collect::<Vec<_>>(), [("src/main/java".into(), "iso-8859-15".into())]);
|
||||
let not_a_table: EncodingSettings = serde_json::from_value(serde_json::json!({ "mappings": 5 })).unwrap();
|
||||
assert!(not_a_table.mappings.is_empty());
|
||||
assert!(EncodingSettings::default().mappings.is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod auto_import_tests {
|
||||
use super::{AutoImportSettings, ImportsOnPaste};
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
//! feature crates depend on `ide-core` and never on each other's internals.
|
||||
//! All IPC-facing types derive `specta::Type`, which generates `src/bindings.ts`.
|
||||
|
||||
pub mod build_jobs;
|
||||
pub mod cli_process;
|
||||
pub mod editor_settings;
|
||||
pub mod error;
|
||||
@@ -18,6 +19,7 @@ pub mod ipc_path;
|
||||
pub mod java_runtime;
|
||||
pub mod jsonc;
|
||||
pub mod memory;
|
||||
pub mod network_path;
|
||||
pub mod output_encoding;
|
||||
pub mod output_rate;
|
||||
pub mod platform;
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
//! Whether a path is on a network file system, where every stat is a round trip to a server.
|
||||
|
||||
use std::path::{Component, Path, Prefix};
|
||||
|
||||
/// A UNC path (`\\server\share`, `\\wsl.localhost\…`) or a drive letter mapped to a network
|
||||
/// share (`Z:\`). Always `false` off Windows: there a mount point is not visible in the path.
|
||||
pub fn is_network_path(path: &Path) -> bool {
|
||||
match path.components().next() {
|
||||
Some(Component::Prefix(prefix)) => match prefix.kind() {
|
||||
Prefix::UNC(..) | Prefix::VerbatimUNC(..) => true,
|
||||
Prefix::Disk(letter) | Prefix::VerbatimDisk(letter) => is_remote_drive(letter),
|
||||
_ => false,
|
||||
},
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn is_remote_drive(letter: u8) -> bool {
|
||||
use windows_sys::Win32::Storage::FileSystem::GetDriveTypeW;
|
||||
/// `DRIVE_REMOTE` (WindowsProgramming).
|
||||
const DRIVE_REMOTE: u32 = 4;
|
||||
let root = [u16::from(letter), u16::from(b':'), u16::from(b'\\'), 0];
|
||||
// SAFETY: `root` is a NUL-terminated wide string that outlives the call.
|
||||
unsafe { GetDriveTypeW(root.as_ptr()) == DRIVE_REMOTE }
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
fn is_remote_drive(_letter: u8) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::is_network_path;
|
||||
use std::path::Path;
|
||||
|
||||
#[test]
|
||||
fn unc_paths_are_on_the_network() {
|
||||
if cfg!(windows) {
|
||||
assert!(is_network_path(Path::new(r"\\server\share\repo")));
|
||||
assert!(is_network_path(Path::new(r"\\?\UNC\server\share\repo")));
|
||||
assert!(is_network_path(Path::new(r"\\wsl.localhost\Ubuntu\home")));
|
||||
}
|
||||
assert!(!is_network_path(Path::new("relative/path")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_local_directory_is_not() {
|
||||
let dir = std::env::temp_dir();
|
||||
assert!(!is_network_path(&dir), "{}", dir.display());
|
||||
}
|
||||
}
|
||||
@@ -14,10 +14,33 @@ pub type Changes = Arc<Vec<(OsString, Option<OsString>)>>;
|
||||
|
||||
struct Entry {
|
||||
root: PathBuf,
|
||||
direnv: Vec<(OsString, Option<OsString>)>,
|
||||
github_token: Option<OsString>,
|
||||
changes: Changes,
|
||||
loading: bool,
|
||||
}
|
||||
|
||||
impl Entry {
|
||||
fn new(root: PathBuf) -> Self {
|
||||
Self { root, direnv: Vec::new(), github_token: None, changes: Changes::default(), loading: false }
|
||||
}
|
||||
|
||||
fn rebuild(&mut self) {
|
||||
let mut combined = Vec::with_capacity(self.direnv.len() + usize::from(self.github_token.is_some()));
|
||||
if let Some(token) = &self.github_token {
|
||||
combined.push(("GH_TOKEN".into(), Some(token.clone())));
|
||||
}
|
||||
// `.envrc` entries override the project GitHub token when both define `GH_TOKEN`.
|
||||
combined.retain(|(k, _)| !self.direnv.iter().any(|(dk, _)| dk == k));
|
||||
combined.extend(self.direnv.iter().cloned());
|
||||
self.changes = Arc::new(combined);
|
||||
}
|
||||
|
||||
fn is_idle_empty(&self) -> bool {
|
||||
!self.loading && self.direnv.is_empty() && self.github_token.is_none()
|
||||
}
|
||||
}
|
||||
|
||||
static ENTRIES: Mutex<Vec<Entry>> = Mutex::new(Vec::new());
|
||||
static SETTLED: Condvar = Condvar::new();
|
||||
|
||||
@@ -31,35 +54,103 @@ pub fn begin_loading(root: &Path) {
|
||||
let mut entries = entries();
|
||||
match entries.iter_mut().find(|e| e.root == root) {
|
||||
Some(entry) => entry.loading = true,
|
||||
None => entries.push(Entry { root: root.to_path_buf(), changes: Changes::default(), loading: true }),
|
||||
None => {
|
||||
let mut entry = Entry::new(root.to_path_buf());
|
||||
entry.loading = true;
|
||||
entries.push(entry);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What children started in `root` (or below it) get on top of the IDE's own environment
|
||||
/// (`None`: removed). Ends a [`begin_loading`].
|
||||
/// What children started in `root` (or below it) get from direnv on top of the IDE's own
|
||||
/// environment (`None`: removed). Ends a [`begin_loading`].
|
||||
pub fn set(root: &Path, changes: Vec<(OsString, Option<OsString>)>) {
|
||||
let mut entries = entries();
|
||||
let changes = Arc::new(changes);
|
||||
match entries.iter_mut().find(|e| e.root == root) {
|
||||
Some(entry) => {
|
||||
entry.changes = changes;
|
||||
match entries.iter_mut().position(|e| e.root == root) {
|
||||
Some(idx) => {
|
||||
let entry = &mut entries[idx];
|
||||
entry.direnv = changes;
|
||||
entry.loading = false;
|
||||
entry.rebuild();
|
||||
if entry.is_idle_empty() {
|
||||
entries.remove(idx);
|
||||
}
|
||||
}
|
||||
None => entries.push(Entry { root: root.to_path_buf(), changes, loading: false }),
|
||||
None if !changes.is_empty() => {
|
||||
let mut entry = Entry::new(root.to_path_buf());
|
||||
entry.direnv = changes;
|
||||
entry.rebuild();
|
||||
entries.push(entry);
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
SETTLED.notify_all();
|
||||
}
|
||||
|
||||
/// Ends a [`begin_loading`] that read nothing new (an error): the last environment stays.
|
||||
pub fn settle(root: &Path) {
|
||||
if let Some(entry) = entries().iter_mut().find(|e| e.root == root) {
|
||||
entry.loading = false;
|
||||
let mut entries = entries();
|
||||
if let Some(idx) = entries.iter().position(|e| e.root == root) {
|
||||
entries[idx].loading = false;
|
||||
if entries[idx].is_idle_empty() {
|
||||
entries.remove(idx);
|
||||
}
|
||||
}
|
||||
SETTLED.notify_all();
|
||||
}
|
||||
|
||||
/// `root` has no environment of its own any more (closed, or not trusted).
|
||||
/// `root` has no direnv environment of its own any more (no `.envrc`, closed, or not trusted).
|
||||
/// Preserves any project-scoped GitHub token until [`remove_all`] or [`set_github_token`].
|
||||
pub fn remove(root: &Path) {
|
||||
let mut entries = entries();
|
||||
if let Some(idx) = entries.iter().position(|e| e.root == root) {
|
||||
let entry = &mut entries[idx];
|
||||
entry.direnv.clear();
|
||||
entry.loading = false;
|
||||
entry.rebuild();
|
||||
if entry.is_idle_empty() {
|
||||
entries.remove(idx);
|
||||
}
|
||||
}
|
||||
SETTLED.notify_all();
|
||||
}
|
||||
|
||||
/// Sets or clears the project-scoped `GH_TOKEN` injected for children started in `root`
|
||||
/// (unless overridden by `root`'s direnv `.envrc`). Returns whether the effective token changed.
|
||||
pub fn set_github_token(root: &Path, token: Option<OsString>) -> bool {
|
||||
let token = token.filter(|t| !t.is_empty());
|
||||
let mut entries = entries();
|
||||
match entries.iter().position(|e| e.root == root) {
|
||||
Some(idx) => {
|
||||
if entries[idx].github_token == token {
|
||||
return false;
|
||||
}
|
||||
let entry = &mut entries[idx];
|
||||
entry.github_token = token;
|
||||
entry.rebuild();
|
||||
if entry.is_idle_empty() {
|
||||
entries.remove(idx);
|
||||
}
|
||||
true
|
||||
}
|
||||
None => {
|
||||
let Some(token) = token else { return false };
|
||||
let mut entry = Entry::new(root.to_path_buf());
|
||||
entry.github_token = Some(token);
|
||||
entry.rebuild();
|
||||
entries.push(entry);
|
||||
true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The project-scoped `GH_TOKEN` configured for the innermost project holding `dir`, if any.
|
||||
pub fn github_token(dir: &Path) -> Option<OsString> {
|
||||
find(&entries(), dir).and_then(|e| e.github_token.clone())
|
||||
}
|
||||
|
||||
/// Removes both direnv and project GitHub token entries for `root` (project closed or untrusted).
|
||||
pub fn remove_all(root: &Path) {
|
||||
entries().retain(|e| e.root != root);
|
||||
SETTLED.notify_all();
|
||||
}
|
||||
@@ -135,4 +226,26 @@ mod tests {
|
||||
assert_eq!(*for_dir(root), [change("NEW", Some("2"))]);
|
||||
remove(root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn github_token_survives_direnv_absence_and_yields_to_explicit_envrc_override() {
|
||||
let root = Path::new("/openidea-test-env/gh-project");
|
||||
let worktrees = Path::new("/openidea-test-env/gh-project.worktrees");
|
||||
assert!(set_github_token(root, Some("gho_work".into())));
|
||||
assert!(!set_github_token(root, Some("gho_work".into())), "idempotent");
|
||||
assert!(set_github_token(worktrees, Some("gho_work".into())));
|
||||
remove(root); // no `.envrc` in `root`
|
||||
assert_eq!(*for_dir(&root.join("src")), [change("GH_TOKEN", Some("gho_work"))]);
|
||||
assert_eq!(*for_dir(&worktrees.join("task-1")), [change("GH_TOKEN", Some("gho_work"))]);
|
||||
assert_eq!(github_token(&worktrees.join("task-1")), Some("gho_work".into()));
|
||||
|
||||
// An explicit `.envrc` GH_TOKEN overrides the project GitHub account token.
|
||||
set(root, vec![change("GH_TOKEN", Some("gho_from_envrc")), change("FOO", Some("bar"))]);
|
||||
assert_eq!(*for_dir(root), [change("GH_TOKEN", Some("gho_from_envrc")), change("FOO", Some("bar"))]);
|
||||
|
||||
remove_all(root);
|
||||
remove_all(worktrees);
|
||||
assert!(for_dir(root).is_empty());
|
||||
assert!(for_dir(worktrees).is_empty());
|
||||
}
|
||||
}
|
||||
@@ -52,6 +52,8 @@ pub struct Settings {
|
||||
/// Per language server, by name (`rust-analyzer`): launch and protocol
|
||||
/// options on top of the language definition, or a server defined here.
|
||||
pub language_servers: BTreeMap<String, LanguageServerSettings>,
|
||||
/// Languages & Frameworks › JSON Schema Mappings: schemas for JSON and YAML files.
|
||||
pub json_schemas: Vec<JsonSchemaMapping>,
|
||||
/// Tools › Download sources: a mirror prefix for the release archives the installer fetches.
|
||||
pub tool_downloads: ToolDownloadSettings,
|
||||
/// Editor › Inspections profiles.
|
||||
@@ -78,6 +80,8 @@ pub struct Settings {
|
||||
pub file_colors: FileColorSettings,
|
||||
/// Database › Query Execution, Languages & Frameworks › SQL Resolution Scopes.
|
||||
pub database: DatabaseSettings,
|
||||
/// Settings › Settings Sync (global only, never synced itself).
|
||||
pub settings_sync: SettingsSyncSettings,
|
||||
/// Plugin settings (`[contributes.settings]`): plugin id → its values by key.
|
||||
#[specta(type = BTreeMap<String, BTreeMap<String, specta_typescript::Unknown>>)]
|
||||
pub plugins: BTreeMap<String, serde_json::Map<String, serde_json::Value>>,
|
||||
@@ -99,6 +103,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,
|
||||
@@ -120,6 +138,19 @@ pub struct AgentSettings {
|
||||
#[serde(deserialize_with = "or_default")]
|
||||
#[specta(type = NewTaskApprovals)]
|
||||
pub new_task_approvals: NewTaskApprovals,
|
||||
/// How long an in-flight turn hit by a transient network outage waits and probes for
|
||||
/// connectivity before degrading to a manual Resume prompt.
|
||||
#[serde(deserialize_with = "or_default")]
|
||||
#[specta(type = NetworkRetryWindow)]
|
||||
pub network_retry_window: NetworkRetryWindow,
|
||||
/// What opening a project does with tasks interrupted when OpenIDEA closed or restarted.
|
||||
/// User settings only.
|
||||
#[serde(deserialize_with = "or_default")]
|
||||
#[specta(type = ResumeInterruptedPolicy)]
|
||||
pub resume_interrupted: ResumeInterruptedPolicy,
|
||||
/// Warn before closing a local window whose project still has running agent tasks.
|
||||
/// User settings only.
|
||||
pub confirm_terminate_on_close: bool,
|
||||
/// Settings new tasks of an agent start with: agent id → option id → value.
|
||||
#[serde(deserialize_with = "agent_defaults")]
|
||||
#[specta(type = BTreeMap<String, BTreeMap<String, String>>)]
|
||||
@@ -145,12 +176,23 @@ 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,
|
||||
send_with: SendKey::Enter,
|
||||
while_running: WhileRunning::Queue,
|
||||
new_task_approvals: NewTaskApprovals::Bypass,
|
||||
network_retry_window: NetworkRetryWindow::Hour1,
|
||||
resume_interrupted: ResumeInterruptedPolicy::Ask,
|
||||
confirm_terminate_on_close: true,
|
||||
defaults: BTreeMap::new(),
|
||||
mcp_servers: BTreeMap::new(),
|
||||
skills: BTreeMap::new(),
|
||||
@@ -338,6 +380,49 @@ pub enum NewTaskApprovals {
|
||||
Ask,
|
||||
}
|
||||
|
||||
/// Default auto-retry window for transient network outages during an active agent turn.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
pub enum NetworkRetryWindow {
|
||||
#[serde(rename = "off")]
|
||||
Off,
|
||||
#[serde(rename = "15m")]
|
||||
Minutes15,
|
||||
#[default]
|
||||
#[serde(rename = "1h")]
|
||||
Hour1,
|
||||
#[serde(rename = "4h")]
|
||||
Hours4,
|
||||
#[serde(rename = "24h")]
|
||||
Hours24,
|
||||
}
|
||||
|
||||
impl NetworkRetryWindow {
|
||||
pub fn minutes(self) -> u32 {
|
||||
match self {
|
||||
Self::Off => 0,
|
||||
Self::Minutes15 => 15,
|
||||
Self::Hour1 => 60,
|
||||
Self::Hours4 => 240,
|
||||
Self::Hours24 => 1440,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How interrupted agent tasks are handled when a project reopens.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum ResumeInterruptedPolicy {
|
||||
/// Show Interrupted markers, banner and balloon; wait for the user to click Resume.
|
||||
#[default]
|
||||
Ask,
|
||||
/// Auto-resume tasks interrupted by an IDE restart or backend upgrade within 15 minutes.
|
||||
Restart,
|
||||
/// Auto-resume tasks interrupted by close, quit or restart within the session recovery window.
|
||||
Window,
|
||||
/// Settle quietly to Ready with no Interrupted markers or balloons.
|
||||
Off,
|
||||
}
|
||||
|
||||
/// Which folders without an open window the MCP server still serves tools for.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
@@ -432,6 +517,53 @@ pub struct ToolDownloadSettings {
|
||||
/// commas or whitespace and tried in order before the official host; empty keeps every
|
||||
/// download on its official host.
|
||||
pub github_mirror: String,
|
||||
/// Package registries only as configured (a company Nexus or Artifactory): npm and pnpm
|
||||
/// installs and update checks never retry against the public npm registry, and the IDE
|
||||
/// fetches nothing from public package registries itself (the JUnit Platform launcher from
|
||||
/// Maven Central, dependency version completion from Maven Central, npm, PyPI and
|
||||
/// crates.io). Off by default.
|
||||
pub configured_registries_only: bool,
|
||||
}
|
||||
|
||||
/// Settings › Settings Sync: the Git repository the IDE settings sync through, and what syncs.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct SettingsSyncSettings {
|
||||
/// Clone URL (a secret GitHub Gist's works too, though anyone with its link can read it);
|
||||
/// empty = sync off.
|
||||
pub repository: String,
|
||||
/// Sync on startup and after the settings change, besides Sync Now.
|
||||
pub auto: bool,
|
||||
pub appearance: bool,
|
||||
/// Editor settings, color schemes, code style, inspections and spelling.
|
||||
pub editor: bool,
|
||||
pub keymaps: bool,
|
||||
/// Every other setting that is not machine-specific.
|
||||
pub other: bool,
|
||||
/// Live, file and postfix templates.
|
||||
pub templates: bool,
|
||||
pub macros: bool,
|
||||
/// Tool window layouts and view options.
|
||||
pub ui: bool,
|
||||
/// The list of installed plugins: missing ones are offered, never installed or removed.
|
||||
pub plugins: bool,
|
||||
}
|
||||
|
||||
impl Default for SettingsSyncSettings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
repository: String::new(),
|
||||
auto: true,
|
||||
appearance: true,
|
||||
editor: true,
|
||||
keymaps: true,
|
||||
other: true,
|
||||
templates: true,
|
||||
macros: true,
|
||||
ui: true,
|
||||
plugins: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Absent profiles retain automatic discovery for existing projects.
|
||||
@@ -585,8 +717,10 @@ impl Default for Settings {
|
||||
mcp_server: McpServerSettings::default(),
|
||||
agent_security: AgentSecuritySettings::default(),
|
||||
scopes: Vec::new(),
|
||||
json_schemas: Vec::new(),
|
||||
file_colors: FileColorSettings::default(),
|
||||
database: DatabaseSettings::default(),
|
||||
settings_sync: SettingsSyncSettings::default(),
|
||||
plugins: BTreeMap::new(),
|
||||
}
|
||||
}
|
||||
@@ -606,6 +740,17 @@ pub struct NamedScope {
|
||||
pub pattern: String,
|
||||
}
|
||||
|
||||
/// A schema for the JSON and YAML files matching `files`; wins over a built-in SchemaStore mapping.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct JsonSchemaMapping {
|
||||
pub name: String,
|
||||
/// A URL, or a file path relative to the project.
|
||||
pub schema: String,
|
||||
/// Project-relative paths or glob patterns (`config/*.json`, `**/*.app.yaml`).
|
||||
pub files: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct FileColorSettings {
|
||||
@@ -834,6 +979,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.
|
||||
@@ -852,6 +999,8 @@ pub struct AppearanceSettings {
|
||||
pub widescreen_tool_windows: bool,
|
||||
/// Each tool window keeps its own size; off, the windows of a side share one.
|
||||
pub remember_tool_window_sizes: bool,
|
||||
/// Tool window shortcuts hide an open unfocused window right away instead of focusing it first.
|
||||
pub toggle_tool_windows_on_shortcut: bool,
|
||||
/// View › Appearance › Toolbar; hidden leaves IDEA's compact window header.
|
||||
pub show_main_toolbar: bool,
|
||||
pub show_status_bar: bool,
|
||||
@@ -973,6 +1122,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(),
|
||||
@@ -985,6 +1135,7 @@ impl Default for AppearanceSettings {
|
||||
show_tool_window_badges: true,
|
||||
widescreen_tool_windows: false,
|
||||
remember_tool_window_sizes: false,
|
||||
toggle_tool_windows_on_shortcut: false,
|
||||
show_main_toolbar: true,
|
||||
show_status_bar: true,
|
||||
navigation_bar: NavigationBarPosition::StatusBar,
|
||||
@@ -1367,6 +1518,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 {
|
||||
@@ -1395,6 +1548,7 @@ impl Default for ExternalFormatterSettings {
|
||||
.collect(),
|
||||
prefer: false,
|
||||
run_on_save: false,
|
||||
fix_on_save: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1420,6 +1574,15 @@ pub struct PythonSettings {
|
||||
/// Folders the user added to an interpreter's `sys.path` (All Interpreters › Show Paths),
|
||||
/// by interpreter executable; absolute or `~/`.
|
||||
pub interpreter_paths: BTreeMap<String, Vec<String>>,
|
||||
/// 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 {
|
||||
@@ -1432,6 +1595,9 @@ impl Default for PythonSettings {
|
||||
hide_other_project_interpreters: false,
|
||||
show_interpreter_paths: true,
|
||||
interpreter_paths: BTreeMap::new(),
|
||||
test_runner: "auto".into(),
|
||||
profiler: "auto".into(),
|
||||
show_plots_in_tool_window: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1913,6 +2079,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() };
|
||||
@@ -1946,6 +2122,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}}"#] {
|
||||
@@ -2107,6 +2296,21 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn toggle_tool_windows_on_shortcut_defaults_off_and_round_trips() {
|
||||
let old: Settings = serde_json::from_str(r#"{"appearance":{"showToolWindowNames":true}}"#).unwrap();
|
||||
assert!(!old.appearance.toggle_tool_windows_on_shortcut);
|
||||
assert!(!Settings::default().appearance.toggle_tool_windows_on_shortcut);
|
||||
for enabled in [true, false] {
|
||||
let mut settings = Settings::default();
|
||||
settings.appearance.toggle_tool_windows_on_shortcut = enabled;
|
||||
let json = serde_json::to_value(&settings).unwrap();
|
||||
assert_eq!(json["appearance"]["toggleToolWindowsOnShortcut"], enabled);
|
||||
let restored: Settings = serde_json::from_value(json).unwrap();
|
||||
assert_eq!(restored.appearance.toggle_tool_windows_on_shortcut, enabled);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn double_click_opens_diff_is_unset_by_default_and_round_trips() {
|
||||
let old: Settings = serde_json::from_str(r#"{"vcs":{"commit":{"nonModal":true}}}"#).unwrap();
|
||||
|
||||
@@ -73,6 +73,38 @@ pub fn find_command(command: &str, search: &OsStr, root: &Path) -> Option<PathBu
|
||||
dirs.into_iter().find_map(|dir| names.iter().map(|name| dir.join(name)).find(|p| is_executable(p)))
|
||||
}
|
||||
|
||||
const GH_FALLBACK_PATHS: &[&str] = if cfg!(windows) {
|
||||
&[r"C:\Program Files\GitHub CLI\gh.exe"]
|
||||
} else {
|
||||
&["/opt/homebrew/bin/gh", "/usr/local/bin/gh", "/usr/bin/gh", "/snap/bin/gh"]
|
||||
};
|
||||
|
||||
/// Locates `gh` across `OPENIDEA_GH`, [`search_path`] (which includes IDE-managed tools
|
||||
/// only when installed, then the user's `PATH`), and standard OS install locations.
|
||||
pub fn find_gh_executable() -> Option<PathBuf> {
|
||||
let explicit = std::env::var_os("OPENIDEA_GH").map(PathBuf::from);
|
||||
find_gh_in(explicit.as_deref(), &search_path(), GH_FALLBACK_PATHS)
|
||||
}
|
||||
|
||||
/// Locates a pre-installed `gh` outside [`search_path`] (`OPENIDEA_GH`, Windows Program Files,
|
||||
/// Linux Snap) so tool detection reports it as available without prompting for a duplicate install.
|
||||
pub fn find_gh_outside_search_path() -> Option<PathBuf> {
|
||||
if let Some(explicit) = std::env::var_os("OPENIDEA_GH").map(PathBuf::from).filter(|p| is_executable(p)) {
|
||||
return Some(explicit);
|
||||
}
|
||||
GH_FALLBACK_PATHS.iter().map(PathBuf::from).find(|p| is_executable(p))
|
||||
}
|
||||
|
||||
pub fn find_gh_in(explicit: Option<&Path>, search: &OsStr, fallbacks: &[&str]) -> Option<PathBuf> {
|
||||
if let Some(explicit) = explicit.filter(|p| is_executable(p)) {
|
||||
return Some(explicit.to_path_buf());
|
||||
}
|
||||
if let Some(found) = find_command("gh", search, Path::new("")) {
|
||||
return Some(found);
|
||||
}
|
||||
fallbacks.iter().map(PathBuf::from).find(|p| is_executable(p))
|
||||
}
|
||||
|
||||
fn is_executable(path: &Path) -> bool {
|
||||
let Ok(metadata) = path.metadata() else { return false };
|
||||
#[cfg(unix)]
|
||||
|
||||
@@ -25,6 +25,17 @@ pub struct VcsSettings {
|
||||
pub issue_navigation: Vec<IssueLink>,
|
||||
/// Directory Mappings: repository roots added to or excluded from the detected ones.
|
||||
pub mappings: VcsMappings,
|
||||
/// Settings › Version Control › GitHub: per-project GitHub CLI account selection.
|
||||
pub github: GithubSettings,
|
||||
}
|
||||
|
||||
/// Settings › Version Control › GitHub (`vcs.github`).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct GithubSettings {
|
||||
/// GitHub CLI (`gh`) account login on `github.com` explicitly chosen for this project.
|
||||
/// Empty means automatic (`gh`'s own active account, with no `GH_TOKEN` injected).
|
||||
pub account: String,
|
||||
}
|
||||
|
||||
/// Directory Mappings on top of repository detection. Paths are relative to the project
|
||||
@@ -68,6 +79,7 @@ impl Default for VcsSettings {
|
||||
shelf: ShelfSettings::default(),
|
||||
issue_navigation: Vec::new(),
|
||||
mappings: VcsMappings::default(),
|
||||
github: GithubSettings::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -131,6 +143,9 @@ impl Default for GitAnnotateSettings {
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct GitSettings {
|
||||
/// Git integration on: off, the IDE finds no repositories and runs no git at all
|
||||
/// (no status, log, blame, fetch, clone or agent worktrees), and hides its Git UI.
|
||||
pub enabled: bool,
|
||||
pub annotate: GitAnnotateSettings,
|
||||
/// Show blame after the current editor line.
|
||||
pub inline_blame: bool,
|
||||
@@ -189,6 +204,7 @@ pub struct GitSettings {
|
||||
impl Default for GitSettings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
enabled: true,
|
||||
annotate: GitAnnotateSettings::default(),
|
||||
inline_blame: false,
|
||||
inline_blame_clickable: true,
|
||||
@@ -238,6 +254,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,
|
||||
@@ -279,6 +297,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,
|
||||
@@ -390,13 +409,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")]
|
||||
@@ -587,10 +617,14 @@ pub struct TerminalSettings {
|
||||
pub mouse_reporting: bool,
|
||||
pub copy_on_selection: bool,
|
||||
pub paste_on_middle_click: bool,
|
||||
/// Right-click pastes instead of opening the context menu (Ctrl or Shift + right-click still opens it).
|
||||
pub right_click_paste: bool,
|
||||
pub override_ide_shortcuts: bool,
|
||||
pub shell_integration: bool,
|
||||
pub highlight_hyperlinks: bool,
|
||||
pub highlight_selection: bool,
|
||||
/// Highlights typed commands the IDE recognises; Run Highlighted Command runs them with it.
|
||||
pub run_commands_using_ide: bool,
|
||||
pub option_as_meta: bool,
|
||||
/// Escape moves focus to the editor instead of reaching the shell.
|
||||
pub escape_to_editor: bool,
|
||||
@@ -623,10 +657,12 @@ impl Default for TerminalSettings {
|
||||
mouse_reporting: true,
|
||||
copy_on_selection: false,
|
||||
paste_on_middle_click: true,
|
||||
right_click_paste: false,
|
||||
override_ide_shortcuts: true,
|
||||
shell_integration: true,
|
||||
highlight_hyperlinks: true,
|
||||
highlight_selection: true,
|
||||
run_commands_using_ide: true,
|
||||
option_as_meta: false,
|
||||
escape_to_editor: false,
|
||||
cursor_shape: "block".into(),
|
||||
@@ -716,6 +752,24 @@ 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 git_defaults_enabled_and_can_be_disabled() {
|
||||
let missing: GitSettings = serde_json::from_str("{}").unwrap();
|
||||
let off: GitSettings = serde_json::from_str(r#"{"enabled":false}"#).unwrap();
|
||||
assert!(missing.enabled);
|
||||
assert!(!off.enabled);
|
||||
}
|
||||
|
||||
#[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(),
|
||||
|
||||
@@ -391,9 +391,10 @@ pub const DEBUGPY_MISSING: &str = "debugpy is not installed";
|
||||
/// `PYTHONPATH`. Neither: an `unavailable` error naming the interpreter.
|
||||
pub async fn prepare_debugpy(spec: &mut AdapterSpec) -> IdeResult<()> {
|
||||
let (command, cwd) = (spec.command.clone(), spec.cwd.clone());
|
||||
let Some(python) = tokio::task::spawn_blocking(move || resolve_binary(&command, &cwd)).await.ok().flatten() else {
|
||||
let Some(python) = tokio::task::spawn_blocking(move || debugpy_python(&command, &cwd)).await.ok().flatten() else {
|
||||
return Ok(()); // Reported as a missing adapter when it is started.
|
||||
};
|
||||
spec.command = python.to_string_lossy().into_owned();
|
||||
let mut probe = Command::new(&python);
|
||||
probe.current_dir(&spec.cwd);
|
||||
ide_core::process::prepare(probe.as_std_mut());
|
||||
@@ -426,6 +427,46 @@ pub async fn prepare_debugpy(spec: &mut AdapterSpec) -> IdeResult<()> {
|
||||
)))
|
||||
}
|
||||
|
||||
/// The interpreter `<python> -m debugpy.adapter` runs with. On Windows a bare `python3` (the
|
||||
/// built-in `python.toml`'s) or `python` may name an App Execution Alias in `WindowsApps`,
|
||||
/// which only opens the Store unless the Store's Python is installed: every match on `PATH`
|
||||
/// of the command, then `python`, then the `py` launcher, the first that is no alias or runs.
|
||||
fn debugpy_python(command: &str, cwd: &Path) -> Option<PathBuf> {
|
||||
let found = resolve_binary(command, cwd);
|
||||
if !cfg!(windows) || !matches!(command, "python3" | "python") {
|
||||
return found;
|
||||
}
|
||||
let pathext = std::env::var("PATHEXT").ok();
|
||||
let dirs = search_dirs(cwd);
|
||||
let mut candidates: Vec<PathBuf> = Vec::new();
|
||||
for name in [command, "python", "py"] {
|
||||
for dir in &dirs {
|
||||
if let Some(p) = find_binary_in(name, cwd, std::slice::from_ref(dir), true, pathext.as_deref())
|
||||
&& !candidates.contains(&p)
|
||||
{
|
||||
candidates.push(p);
|
||||
}
|
||||
}
|
||||
}
|
||||
let runs = |p: &Path| {
|
||||
let mut c = std::process::Command::new(p);
|
||||
ide_core::process::prepare(&mut c);
|
||||
c.arg("--version").stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null());
|
||||
c.status().is_ok_and(|s| s.success())
|
||||
};
|
||||
pick_python(candidates, runs).or(found)
|
||||
}
|
||||
|
||||
/// The first candidate that is no App Execution Alias, or is one that `runs`.
|
||||
fn pick_python(candidates: Vec<PathBuf>, runs: impl Fn(&Path) -> bool) -> Option<PathBuf> {
|
||||
candidates.into_iter().find(|p| !is_app_execution_alias(p) || runs(p))
|
||||
}
|
||||
|
||||
/// A Windows App Execution Alias (`%LOCALAPPDATA%\Microsoft\WindowsApps\python3.exe`).
|
||||
fn is_app_execution_alias(path: &Path) -> bool {
|
||||
path.parent().and_then(Path::file_name).is_some_and(|d| d.eq_ignore_ascii_case("WindowsApps"))
|
||||
}
|
||||
|
||||
/// GDB's DAP interpreter (`-i dap`) shipped in GDB 14; older ones exit with
|
||||
/// "Interpreter `dap' unrecognized".
|
||||
const GDB_MIN_MAJOR: u32 = 14;
|
||||
@@ -859,6 +900,34 @@ async fn connect_with_retries(
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Windows: a Store alias on `PATH` before the real interpreter is skipped unless it runs
|
||||
/// (the Store's Python is installed), so the Python Debug Server starts the real one.
|
||||
#[test]
|
||||
fn debugpy_skips_store_aliases_that_do_not_run() {
|
||||
let alias = PathBuf::from("C:/Users/me/AppData/Local/Microsoft/WindowsApps/python3.exe");
|
||||
let real = PathBuf::from("C:/Program Files/Python313/python.exe");
|
||||
assert!(is_app_execution_alias(&alias) && !is_app_execution_alias(&real));
|
||||
let both = vec![alias.clone(), real.clone()];
|
||||
assert_eq!(pick_python(both.clone(), |_| false), Some(real.clone()));
|
||||
assert_eq!(pick_python(both, |_| true), Some(alias.clone()));
|
||||
assert_eq!(pick_python(vec![alias], |_| false), None);
|
||||
}
|
||||
|
||||
/// 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": {}})));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
//! Machine code of a native program (DAP `disassemble`), for the Disassembly view.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
use specta::Type;
|
||||
|
||||
/// The most instructions one request asks for.
|
||||
pub const MAX_INSTRUCTIONS: u32 = 1000;
|
||||
|
||||
/// One disassembled instruction.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Instruction {
|
||||
/// Address as the adapter writes it (`0x5555…`); also a memory reference for the next request.
|
||||
pub address: String,
|
||||
/// The instruction in the adapter's syntax (`mov -0x28(%rbp),%rax`).
|
||||
pub instruction: String,
|
||||
/// Its machine code as hex (`488b45d8`), when the adapter sends it.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub bytes: Option<String>,
|
||||
/// The function it belongs to, when the adapter names it (often on the first instruction only).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub symbol: Option<String>,
|
||||
}
|
||||
|
||||
/// `disassemble`'s instructions in order; `None` for the padding adapters put where there is no
|
||||
/// code (`presentationHint: "invalid"`, or no address).
|
||||
pub(crate) fn instructions(body: &Value) -> Vec<Option<Instruction>> {
|
||||
let text = |i: &Value, k: &str| i.get(k).and_then(Value::as_str).filter(|s| !s.is_empty()).map(str::to_owned);
|
||||
let Some(list) = body.get("instructions").and_then(Value::as_array) else { return Vec::new() };
|
||||
list.iter()
|
||||
.map(|i| {
|
||||
if i.get("presentationHint").and_then(Value::as_str) == Some("invalid") {
|
||||
return None;
|
||||
}
|
||||
Some(Instruction {
|
||||
address: text(i, "address")?,
|
||||
instruction: text(i, "instruction").unwrap_or_default(),
|
||||
bytes: text(i, "instructionBytes"),
|
||||
symbol: text(i, "symbol"),
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A memory reference or address as a number (`0x7ffd…` or decimal).
|
||||
pub(crate) fn address(reference: &str) -> Option<u128> {
|
||||
let r = reference.trim();
|
||||
match r.strip_prefix("0x").or_else(|| r.strip_prefix("0X")) {
|
||||
Some(hex) => u128::from_str_radix(hex, 16).ok(),
|
||||
None => r.parse().ok(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the instruction at `index` is the one at `reference`. References that are not
|
||||
/// addresses cannot be checked and pass.
|
||||
pub(crate) fn at_index(instructions: &[Option<Instruction>], reference: &str, index: usize) -> bool {
|
||||
let Some(want) = address(reference) else { return instructions.len() > index };
|
||||
instructions.get(index).and_then(Option::as_ref).and_then(|i| address(&i.address)) == Some(want)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn reads_gdbs_instructions() {
|
||||
// GDB 17.1 at the reporter-style C fixture's loop line.
|
||||
let body = json!({"instructions": [
|
||||
{"address": "0x5555555551f5", "instruction": "mov -0x2c(%rbp),%eax", "instructionBytes": "8b45d4", "line": 14},
|
||||
{"address": "0x5555555551f8", "instruction": "cltq", "instructionBytes": "4898", "symbol": "sum"},
|
||||
]});
|
||||
let got = instructions(&body);
|
||||
assert_eq!(
|
||||
got[0],
|
||||
Some(Instruction {
|
||||
address: "0x5555555551f5".into(),
|
||||
instruction: "mov -0x2c(%rbp),%eax".into(),
|
||||
bytes: Some("8b45d4".into()),
|
||||
symbol: None,
|
||||
})
|
||||
);
|
||||
assert_eq!(got[1].as_ref().unwrap().symbol.as_deref(), Some("sum"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn padding_is_not_an_instruction() {
|
||||
let body = json!({"instructions": [
|
||||
{"address": "0xfff0", "instruction": "", "presentationHint": "invalid"},
|
||||
{"instruction": "??"},
|
||||
{"address": "0x10000", "instruction": "nop"},
|
||||
]});
|
||||
let got = instructions(&body);
|
||||
assert_eq!((got[0].is_none(), got[1].is_none(), got[2].is_some()), (true, true, true));
|
||||
assert!(instructions(&json!({})).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn finds_the_reference_by_its_address() {
|
||||
let list = instructions(&json!({"instructions": [
|
||||
{"address": "0x00001000", "instruction": "push %rbp"},
|
||||
{"address": "0x1001", "instruction": "mov %rsp,%rbp"},
|
||||
]}));
|
||||
assert!(at_index(&list, "0x1001", 1));
|
||||
assert!(at_index(&list, "4097", 1));
|
||||
assert!(at_index(&list, "0X1000", 0));
|
||||
assert!(!at_index(&list, "0x1001", 0));
|
||||
assert!(!at_index(&list, "0x1001", 2));
|
||||
assert!(at_index(&list, "frame-3", 1), "opaque references cannot be checked");
|
||||
assert_eq!(address("0xffffffffffffffff1"), Some(0xffffffffffffffff1));
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,8 @@ pub mod adapter;
|
||||
pub mod attach;
|
||||
mod cargo;
|
||||
pub mod connection;
|
||||
mod debugpy;
|
||||
mod disassembly;
|
||||
mod exception_classes;
|
||||
pub mod jdwp;
|
||||
mod js_cdp;
|
||||
@@ -19,12 +21,14 @@ mod js_debug;
|
||||
mod jvm_memory;
|
||||
pub mod kotlin;
|
||||
pub mod kotlin_lsp;
|
||||
mod memory;
|
||||
mod session;
|
||||
mod stream_trace;
|
||||
pub mod unity;
|
||||
|
||||
use adapter::{AdapterLauncher, AdapterSpec, ProcessLauncher};
|
||||
use adapter::{AdapterIo, AdapterLauncher, AdapterSpec, ProcessLauncher};
|
||||
use connection::{Connection, DapError};
|
||||
pub use disassembly::{Instruction, MAX_INSTRUCTIONS};
|
||||
pub use exception_classes::{ExceptionClassBreakpoint, ExceptionClassSupport};
|
||||
use futures::future::join_all;
|
||||
use ide_core::{DebugSessionId, IdeError, IdeResult, RunId, SharedSink};
|
||||
@@ -32,6 +36,7 @@ use ide_language::LanguageRegistry;
|
||||
pub use js_cdp::JsResponseRule;
|
||||
pub use js_debug::JsResponseBody;
|
||||
pub use jvm_memory::*;
|
||||
pub use memory::{MAX_READ, MemoryBlock};
|
||||
use parking_lot::Mutex;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Value, json};
|
||||
@@ -44,6 +49,11 @@ use std::sync::{Arc, Weak};
|
||||
use std::time::Duration;
|
||||
pub use stream_trace::{TracePhase, TraceProgress, TraceRun, TraceUnavailable};
|
||||
|
||||
/// The adapter name of a notebook kernel's own debugger (see [`DebugManager::start_over`]).
|
||||
pub const NOTEBOOK_ADAPTER: &str = "jupyter-kernel";
|
||||
/// How a notebook cell's breakpoints are keyed: `vscode-notebook-cell:<notebook>#<cell>`.
|
||||
pub const NOTEBOOK_CELL_SCHEME: &str = "vscode-notebook-cell:";
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct LaunchConfig {
|
||||
@@ -153,6 +163,12 @@ pub struct DebugCapabilities {
|
||||
/// A stream chain can be traced while the program runs it ([`DebugManager::stream_trace`]).
|
||||
/// Can change during the session, like `jvm_instances`.
|
||||
pub stream_trace: bool,
|
||||
/// The program's raw memory can be read ([`DebugManager::read_memory`]): the Memory View.
|
||||
pub read_memory: bool,
|
||||
/// The program's machine code can be disassembled ([`DebugManager::disassemble`]): the Disassembly view.
|
||||
pub disassemble: bool,
|
||||
/// Steps can move by one instruction ([`DebugManager::step_instruction`]).
|
||||
pub instruction_stepping: bool,
|
||||
}
|
||||
|
||||
/// Result of [`DebugManager::redefine_classes`].
|
||||
@@ -219,6 +235,10 @@ pub struct StackFrame {
|
||||
pub column: u32,
|
||||
/// `subtle` frames (library/generated) are collapsed in the UI.
|
||||
pub presentation_hint: Option<String>,
|
||||
/// The frame's program counter, for [`DebugManager::disassemble`] (DAP `instructionPointerReference`).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub instruction_pointer_reference: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
@@ -243,6 +263,10 @@ pub struct Variable {
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
#[specta(optional)]
|
||||
pub lazy: bool,
|
||||
/// Where the value points to or is stored, for [`DebugManager::read_memory`] (DAP `memoryReference`).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub memory_reference: Option<String>,
|
||||
}
|
||||
|
||||
/// A completion the adapter offers for an expression (DAP `completions`).
|
||||
@@ -605,6 +629,11 @@ pub(crate) fn frame_from(f: &Value) -> StackFrame {
|
||||
line: (f.get("line").and_then(Value::as_u64).unwrap_or(0) as u32).saturating_sub(1),
|
||||
column: (f.get("column").and_then(Value::as_u64).unwrap_or(0) as u32).saturating_sub(1),
|
||||
presentation_hint: hint,
|
||||
instruction_pointer_reference: f
|
||||
.get("instructionPointerReference")
|
||||
.and_then(Value::as_str)
|
||||
.filter(|r| !r.is_empty())
|
||||
.map(str::to_owned),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -681,6 +710,9 @@ pub(crate) fn capabilities_from(caps: &Value) -> DebugCapabilities {
|
||||
js_page: false,
|
||||
live_evaluate: false,
|
||||
stream_trace: false,
|
||||
read_memory: has("supportsReadMemoryRequest"),
|
||||
disassemble: has("supportsDisassembleRequest"),
|
||||
instruction_stepping: has("supportsSteppingGranularity"),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -769,9 +801,15 @@ pub(crate) fn variable_from(v: &Value) -> Variable {
|
||||
variables_reference: v.get("variablesReference").and_then(Value::as_i64).unwrap_or(0),
|
||||
evaluate_name: s("evaluateName"),
|
||||
lazy: v.pointer("/presentationHint/lazy").and_then(Value::as_bool).unwrap_or(false),
|
||||
memory_reference: memory_reference(v),
|
||||
}
|
||||
}
|
||||
|
||||
/// A variable's or evaluation result's `memoryReference`.
|
||||
fn memory_reference(v: &Value) -> Option<String> {
|
||||
v.get("memoryReference").and_then(Value::as_str).filter(|r| !r.is_empty()).map(str::to_owned)
|
||||
}
|
||||
|
||||
async fn session_variables(session: &Session, reference: i64) -> IdeResult<Vec<Variable>> {
|
||||
let body =
|
||||
session.conn.request_timeout("variables", json!({ "variablesReference": reference }), REQUEST_TIMEOUT).await?;
|
||||
@@ -795,6 +833,7 @@ async fn resolve_in(session: &Session, variable: Variable) -> IdeResult<Variable
|
||||
value: value.value,
|
||||
variables_reference: value.variables_reference,
|
||||
lazy: value.lazy,
|
||||
memory_reference: value.memory_reference.or(variable.memory_reference),
|
||||
},
|
||||
_ => variable,
|
||||
})
|
||||
@@ -900,7 +939,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 +1047,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 +1063,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 +1115,52 @@ impl DebugManager {
|
||||
spec,
|
||||
port,
|
||||
exception_classes,
|
||||
cancel,
|
||||
None,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Starts an `attach` session named `name` over `io`: a debugger reached without an
|
||||
/// adapter process, such as a notebook kernel's over its control channel
|
||||
/// ([`NOTEBOOK_ADAPTER`]). `arguments` is the `attach` request's. `notebook_cells`, the
|
||||
/// prefix of a notebook's cell URIs, gives the session that notebook's cell breakpoints.
|
||||
pub async fn start_over(
|
||||
&self,
|
||||
io: AdapterIo,
|
||||
name: String,
|
||||
adapter: String,
|
||||
arguments: Value,
|
||||
owner: SessionOwner,
|
||||
notebook_cells: Option<String>,
|
||||
) -> IdeResult<DebugSessionId> {
|
||||
let spec = AdapterSpec {
|
||||
adapter: adapter.clone(),
|
||||
command: String::new(),
|
||||
args: Vec::new(),
|
||||
transport: adapter::Transport::Stdio,
|
||||
install_hint: None,
|
||||
cwd: PathBuf::new(),
|
||||
env: Vec::new(),
|
||||
server_host: None,
|
||||
connect: None,
|
||||
pinned: None,
|
||||
resolve_lazy_variables: false,
|
||||
};
|
||||
let cancel = ide_core::CancellationToken::new();
|
||||
self.start_session(
|
||||
DebugSessionId::next(),
|
||||
owner,
|
||||
name,
|
||||
adapter,
|
||||
None,
|
||||
"attach".into(),
|
||||
arguments,
|
||||
spec,
|
||||
None,
|
||||
None,
|
||||
cancel,
|
||||
Some((io, notebook_cells)),
|
||||
)
|
||||
.await
|
||||
}
|
||||
@@ -1086,6 +1195,8 @@ impl DebugManager {
|
||||
spec,
|
||||
port,
|
||||
None,
|
||||
ide_core::CancellationToken::new(),
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.map(|_| ())
|
||||
@@ -1104,11 +1215,26 @@ impl DebugManager {
|
||||
spec: AdapterSpec,
|
||||
reuse_port: Option<u16>,
|
||||
exception_classes: Option<Arc<dyn ide_jvm_inspect::ExceptionClassBreakpoints>>,
|
||||
cancel: ide_core::CancellationToken,
|
||||
connected: Option<(AdapterIo, Option<String>)>,
|
||||
) -> 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, notebook_cells) = match connected {
|
||||
Some((io, cells)) => (io, cells),
|
||||
None => (
|
||||
tokio::select! {
|
||||
biased;
|
||||
_ = cancel.cancelled() => return Err(IdeError::cancelled()),
|
||||
io = self.launcher.launch(spec.clone(), reuse_port) => io?,
|
||||
},
|
||||
None,
|
||||
),
|
||||
};
|
||||
let launch_after_configuration = io.launch_after_configuration && request == "launch";
|
||||
let stderr = io.stderr.clone();
|
||||
let (conn, incoming) = {
|
||||
@@ -1120,6 +1246,7 @@ impl DebugManager {
|
||||
.flatten();
|
||||
let mut session = Session::new(id, owner, name, adapter_name, parent, request, conn, spec, io.port, io.child);
|
||||
session.exception_classes = exception_classes;
|
||||
session.notebook_cells = notebook_cells;
|
||||
session.run = take_run_link(&mut arguments);
|
||||
let session = Arc::new(session);
|
||||
if let Some(launch_type) = arguments.get("type").and_then(Value::as_str) {
|
||||
@@ -1129,6 +1256,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 +1281,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 +1289,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");
|
||||
@@ -1212,7 +1366,7 @@ impl DebugManager {
|
||||
"supportsProgressReporting": true,
|
||||
// kotlin-lsp sends `invalidated` either way.
|
||||
"supportsInvalidatedEvent": is_kotlin_lsp,
|
||||
"supportsMemoryReferences": false,
|
||||
"supportsMemoryReferences": true,
|
||||
"supportsArgsCanBeInterpretedByShell": false,
|
||||
}),
|
||||
INIT_TIMEOUT,
|
||||
@@ -1316,6 +1470,7 @@ impl DebugManager {
|
||||
.map(|b| b.lines.iter().map(|(p, b)| (p.clone(), b.clone())).collect::<Vec<_>>())
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.filter(|(path, _)| s.takes(path))
|
||||
.partition(|(_, b)| b.iter().any(|b| b.enabled));
|
||||
let sent = join_all(files.iter().map(|(path, bps)| s.send_breakpoints(path, bps, None))).await;
|
||||
// Breakpoint states follow the owner's first session.
|
||||
@@ -1545,7 +1700,7 @@ impl DebugManager {
|
||||
breakpoints: Vec<Breakpoint>,
|
||||
) -> IdeResult<Vec<BreakpointState>> {
|
||||
let mut result: Option<Vec<BreakpointState>> = None;
|
||||
for s in self.configured_sessions(owner) {
|
||||
for s in self.configured_sessions(owner).into_iter().filter(|s| s.takes(&path)) {
|
||||
match s.send_breakpoints(&path, &breakpoints, None).await {
|
||||
Ok(states) => {
|
||||
result.get_or_insert(states);
|
||||
@@ -1669,6 +1824,7 @@ impl DebugManager {
|
||||
variables_reference: body.get("variablesReference").and_then(Value::as_i64).unwrap_or(0),
|
||||
evaluate_name: evaluate_name.or(Some(name)),
|
||||
lazy: false,
|
||||
memory_reference: memory_reference(&body),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1806,6 +1962,7 @@ impl DebugManager {
|
||||
variables_reference: body.get("variablesReference").and_then(Value::as_i64).unwrap_or(0),
|
||||
evaluate_name: Some(expression),
|
||||
lazy: body.pointer("/presentationHint/lazy").and_then(Value::as_bool).unwrap_or(false),
|
||||
memory_reference: memory_reference(&body),
|
||||
};
|
||||
if !session.spec.resolve_lazy_variables {
|
||||
return Ok(result);
|
||||
@@ -1897,6 +2054,22 @@ impl DebugManager {
|
||||
}
|
||||
|
||||
pub async fn step(&self, s: DebugSessionId, thread_id: i64, kind: StepKind) -> IdeResult<()> {
|
||||
self.step_with(s, thread_id, kind, json!({ "threadId": thread_id })).await
|
||||
}
|
||||
|
||||
/// Step Over / Into Instruction: a step by one machine instruction (DAP `granularity`).
|
||||
pub async fn step_instruction(&self, s: DebugSessionId, thread_id: i64, kind: StepKind) -> IdeResult<()> {
|
||||
let session = self.session(s)?;
|
||||
if !session.supports("supportsSteppingGranularity") {
|
||||
return Err(IdeError::unavailable(format!(
|
||||
"debug adapter `{}` cannot step by instruction",
|
||||
session.adapter
|
||||
)));
|
||||
}
|
||||
self.step_with(s, thread_id, kind, json!({ "threadId": thread_id, "granularity": "instruction" })).await
|
||||
}
|
||||
|
||||
async fn step_with(&self, s: DebugSessionId, thread_id: i64, kind: StepKind, args: Value) -> IdeResult<()> {
|
||||
let command = match kind {
|
||||
StepKind::Over => "next",
|
||||
StepKind::Into => "stepIn",
|
||||
@@ -1908,7 +2081,7 @@ impl DebugManager {
|
||||
quirks.step_sent();
|
||||
}
|
||||
let ticket = session.suspended.ticket();
|
||||
let sent = session.conn.request_timeout(command, json!({ "threadId": thread_id }), REQUEST_TIMEOUT).await;
|
||||
let sent = session.conn.request_timeout(command, args, REQUEST_TIMEOUT).await;
|
||||
step_settled(&session, sent)?;
|
||||
// A step runs its thread; other threads stopped by their own events stay stopped.
|
||||
session.finish_resume(ticket, thread_id, false);
|
||||
@@ -2062,6 +2235,74 @@ impl DebugManager {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `count` bytes (at most [`MAX_READ`]) from `offset` bytes after `memory_reference`, which
|
||||
/// comes from a variable, an evaluation result or an earlier read's address.
|
||||
pub async fn read_memory(
|
||||
&self,
|
||||
s: DebugSessionId,
|
||||
memory_reference: String,
|
||||
offset: i64,
|
||||
count: u32,
|
||||
) -> IdeResult<MemoryBlock> {
|
||||
let session = self.session(s)?;
|
||||
if !session.supports("supportsReadMemoryRequest") {
|
||||
return Err(IdeError::unavailable(format!("debug adapter `{}` cannot read memory", session.adapter)));
|
||||
}
|
||||
let count = count.min(MAX_READ);
|
||||
let body = session
|
||||
.conn
|
||||
.request_timeout(
|
||||
"readMemory",
|
||||
json!({ "memoryReference": memory_reference, "offset": offset, "count": count }),
|
||||
REQUEST_TIMEOUT,
|
||||
)
|
||||
.await?;
|
||||
memory::memory_block(&body, count)
|
||||
}
|
||||
|
||||
/// `count` instructions (at most [`MAX_INSTRUCTIONS`]) from `before` instructions ahead of
|
||||
/// `memory_reference` (a frame's instruction pointer or an instruction's address). Adapters that
|
||||
/// cannot disassemble backwards start at the reference instead.
|
||||
pub async fn disassemble(
|
||||
&self,
|
||||
s: DebugSessionId,
|
||||
memory_reference: String,
|
||||
before: u32,
|
||||
count: u32,
|
||||
) -> IdeResult<Vec<Instruction>> {
|
||||
let session = self.session(s)?;
|
||||
if !session.supports("supportsDisassembleRequest") {
|
||||
return Err(IdeError::unavailable(format!("debug adapter `{}` cannot disassemble", session.adapter)));
|
||||
}
|
||||
let count = count.clamp(1, MAX_INSTRUCTIONS);
|
||||
let before = before.min(count - 1);
|
||||
let request = |offset: i64, count: u32| {
|
||||
session.conn.request_timeout(
|
||||
"disassemble",
|
||||
json!({
|
||||
"memoryReference": memory_reference,
|
||||
"offset": 0,
|
||||
"instructionOffset": offset,
|
||||
"instructionCount": count,
|
||||
"resolveSymbols": true,
|
||||
}),
|
||||
REQUEST_TIMEOUT,
|
||||
)
|
||||
};
|
||||
if before > 0 {
|
||||
// GDB (up to 17 at least) answers a negative instruction offset with the instructions after
|
||||
// the reference, or fails: only an answer with the reference in its place is used.
|
||||
if let Ok(body) = request(-i64::from(before), count).await {
|
||||
let instructions = disassembly::instructions(&body);
|
||||
if disassembly::at_index(&instructions, &memory_reference, before as usize) {
|
||||
return Ok(instructions.into_iter().flatten().collect());
|
||||
}
|
||||
}
|
||||
}
|
||||
let body = request(0, count - before).await?;
|
||||
Ok(disassembly::instructions(&body).into_iter().flatten().collect())
|
||||
}
|
||||
|
||||
pub fn capabilities(&self, s: DebugSessionId) -> IdeResult<DebugCapabilities> {
|
||||
Ok(session_capabilities(&*self.session(s)?))
|
||||
}
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
//! Raw memory of a native program (DAP `readMemory`), for the Memory View.
|
||||
|
||||
use base64::Engine;
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
use specta::Type;
|
||||
|
||||
/// The most bytes one read asks for: a few pages of the view, never a whole mapping.
|
||||
pub const MAX_READ: u32 = 64 * 1024;
|
||||
|
||||
/// Answer of `readMemory`: `data` starts at `address`; the `unreadable_bytes` after it could not be read.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct MemoryBlock {
|
||||
/// Address of the first byte, as the adapter writes it (`0x7ffd…`; may be wider than 53 bits).
|
||||
pub address: String,
|
||||
pub data: Vec<u8>,
|
||||
pub unreadable_bytes: u32,
|
||||
}
|
||||
|
||||
/// `readMemory`'s body for a read of `count` bytes. Adapters leave `data` out (or empty) when
|
||||
/// nothing could be read; the bytes asked for then count as unreadable.
|
||||
pub(crate) fn memory_block(body: &Value, count: u32) -> IdeResult<MemoryBlock> {
|
||||
let address = match body.get("address") {
|
||||
Some(Value::String(a)) if !a.is_empty() => a.clone(),
|
||||
Some(Value::Number(n)) => n.to_string(),
|
||||
_ => return Err(IdeError::internal("the debug adapter answered readMemory without an address")),
|
||||
};
|
||||
let mut data = match body.get("data").and_then(Value::as_str) {
|
||||
Some(b64) if !b64.is_empty() => base64::engine::general_purpose::STANDARD
|
||||
.decode(b64)
|
||||
.map_err(|e| IdeError::internal(format!("the debug adapter sent memory that is not base64: {e}")))?,
|
||||
_ => Vec::new(),
|
||||
};
|
||||
data.truncate(count as usize);
|
||||
// At most the rest of what was asked for (the data is never more than that).
|
||||
let rest = count - data.len() as u32;
|
||||
let unreadable_bytes = match body.get("unreadableBytes").and_then(Value::as_u64) {
|
||||
Some(n) => n.min(u64::from(rest)) as u32,
|
||||
None if data.is_empty() => count,
|
||||
None => 0,
|
||||
};
|
||||
Ok(MemoryBlock { address, data, unreadable_bytes })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn decodes_the_bytes_and_keeps_the_address_as_written() {
|
||||
// The reporter's `&msg[0]` (#5921): "Hello, World!\n" and its terminator.
|
||||
let body = json!({"address": "0x000000016FDFE9A0", "data": "SGVsbG8sIFdvcmxkIQoA"});
|
||||
let block = memory_block(&body, 15).unwrap();
|
||||
assert_eq!(block.address, "0x000000016FDFE9A0");
|
||||
assert_eq!(block.data, b"Hello, World!\n\0");
|
||||
assert_eq!(block.unreadable_bytes, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_data_is_unreadable_not_empty() {
|
||||
let block = memory_block(&json!({"address": "0x0"}), 256).unwrap();
|
||||
assert!(block.data.is_empty());
|
||||
assert_eq!(block.unreadable_bytes, 256);
|
||||
let block = memory_block(&json!({"address": "0x0", "data": "", "unreadableBytes": 16}), 256).unwrap();
|
||||
assert_eq!(block.unreadable_bytes, 16);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_partial_read_reports_the_rest_as_unreadable() {
|
||||
let block = memory_block(&json!({"address": "0x1000", "data": "AAEC", "unreadableBytes": 13}), 16).unwrap();
|
||||
assert_eq!((block.data.as_slice(), block.unreadable_bytes), (&[0u8, 1, 2][..], 13));
|
||||
// Counts that disagree with the request are clamped to it.
|
||||
let block = memory_block(&json!({"address": "0x1000", "data": "AAEC", "unreadableBytes": 99}), 16).unwrap();
|
||||
assert_eq!(block.unreadable_bytes, 13);
|
||||
let block = memory_block(&json!({"address": "0x1000", "data": "AAECAw=="}), 2).unwrap();
|
||||
assert_eq!((block.data.as_slice(), block.unreadable_bytes), (&[0u8, 1][..], 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_answers_without_an_address_or_with_bad_data() {
|
||||
assert!(memory_block(&json!({"data": "AA=="}), 1).is_err());
|
||||
assert!(memory_block(&json!({"address": "0x10", "data": "not base64!"}), 1).is_err());
|
||||
assert_eq!(memory_block(&json!({"address": 4096, "data": "AA=="}), 1).unwrap().address, "4096");
|
||||
}
|
||||
}
|
||||
@@ -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).
|
||||
@@ -123,6 +125,8 @@ pub(crate) struct Session {
|
||||
pub stream_tracer: parking_lot::Mutex<Option<Arc<dyn ide_jvm_inspect::StreamTracer>>>,
|
||||
/// Given at start: the class breakpoints must be armed before `configurationDone`.
|
||||
pub(crate) exception_classes: Option<Arc<dyn ide_jvm_inspect::ExceptionClassBreakpoints>>,
|
||||
/// A notebook kernel's session: the prefix of its notebook's cell URIs (`…/a.ipynb#`).
|
||||
pub(crate) notebook_cells: Option<String>,
|
||||
/// Held from `setExceptionBreakpoints`, which drops the class breakpoints, until they are
|
||||
/// armed again, so that the last list armed is the manager's.
|
||||
pub(crate) exception_turn: tokio::sync::Mutex<()>,
|
||||
@@ -316,6 +320,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)]
|
||||
@@ -339,6 +344,7 @@ impl Session {
|
||||
run: None,
|
||||
stream_tracer: parking_lot::Mutex::new(None),
|
||||
exception_classes: None,
|
||||
notebook_cells: None,
|
||||
exception_turn: tokio::sync::Mutex::default(),
|
||||
stream_trace: parking_lot::Mutex::new(None),
|
||||
stream_trace_done: parking_lot::Mutex::new(None),
|
||||
@@ -422,6 +428,14 @@ impl Session {
|
||||
|
||||
/// Sends the breakpoints of one file (disabled ones omitted, plus an optional
|
||||
/// temporary line) and returns verification states aligned with `breakpoints`.
|
||||
/// Whether this session gets the breakpoints of `path`: a notebook cell's go only to the
|
||||
/// session of that notebook's kernel, which knows the cell's code.
|
||||
pub(crate) fn takes(&self, path: &Path) -> bool {
|
||||
let path = path.to_string_lossy();
|
||||
!path.starts_with(crate::NOTEBOOK_CELL_SCHEME)
|
||||
|| self.notebook_cells.as_deref().is_some_and(|cells| path.starts_with(cells))
|
||||
}
|
||||
|
||||
pub async fn send_breakpoints(
|
||||
&self,
|
||||
path: &Path,
|
||||
@@ -854,6 +868,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);
|
||||
|
||||
@@ -6,6 +6,7 @@ mod stream_trace;
|
||||
|
||||
use super::*;
|
||||
use crate::adapter::{AdapterIo, LaunchFuture};
|
||||
use base64::Engine;
|
||||
use ide_core::IdeEvent;
|
||||
use ide_core::event::DebugEvent;
|
||||
use ide_jsonrpc::framing;
|
||||
@@ -195,6 +196,21 @@ struct Script {
|
||||
accept: &'static [&'static str],
|
||||
/// Requests of the adapter's own answered with a body and followed by events.
|
||||
custom: Option<fn(&Value) -> Option<CustomReply>>,
|
||||
/// Advertise `supportsReadMemoryRequest`: memory below 0x1010 reads as its low address byte,
|
||||
/// memory from there on is unmapped.
|
||||
read_memory: bool,
|
||||
/// Advertise `supportsDisassembleRequest` and `supportsSteppingGranularity`, disassembling like
|
||||
/// this adapter: 4-byte instructions from 0x1000 to 0x1100, nothing mapped around them.
|
||||
disassemble: Option<FakeDisassembler>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq)]
|
||||
enum FakeDisassembler {
|
||||
/// Negative instruction offsets work; unmapped places are `invalid` padding.
|
||||
Lldb,
|
||||
/// GDB 17: disassembles `instructionOffset + instructionCount` instructions from the reference and
|
||||
/// drops the first `instructionOffset` of them, the way a Python slice does.
|
||||
Gdb,
|
||||
}
|
||||
|
||||
/// The answer to a request of the adapter's own: the response body, then events (name, body).
|
||||
@@ -242,6 +258,8 @@ impl Default for Script {
|
||||
empty_thread_responses: 0,
|
||||
accept: &[],
|
||||
custom: None,
|
||||
read_memory: false,
|
||||
disassemble: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -328,6 +346,9 @@ async fn fake_adapter<S: AsyncRead + AsyncWrite + Unpin + Send + 'static>(stream
|
||||
"supportsDataBreakpoints": true,
|
||||
"supportsStepInTargetsRequest": true,
|
||||
"supportsRestartFrame": true,
|
||||
"supportsReadMemoryRequest": script.read_memory,
|
||||
"supportsDisassembleRequest": script.disassemble.is_some(),
|
||||
"supportsSteppingGranularity": script.disassemble.is_some(),
|
||||
"exceptionBreakpointFilters": [
|
||||
{"filter": "raised", "label": "Raised"},
|
||||
{"filter": "uncaught", "label": "Uncaught", "default": true, "description": "Uncaught exceptions"},
|
||||
@@ -570,7 +591,58 @@ async fn fake_adapter<S: AsyncRead + AsyncWrite + Unpin + Send + 'static>(stream
|
||||
]})
|
||||
),
|
||||
},
|
||||
"evaluate" if msg["arguments"]["expression"] == "&msg[0]" => ok!(
|
||||
msg,
|
||||
json!({"result": "0x1000 \"Hello\"", "type": "char *", "variablesReference": 1, "memoryReference": "0x1000"})
|
||||
),
|
||||
"evaluate" => ok!(msg, json!({"result": "42", "type": "int", "variablesReference": 0})),
|
||||
"readMemory" => {
|
||||
let args = &msg["arguments"];
|
||||
let reference = args["memoryReference"].as_str().unwrap().trim_start_matches("0x");
|
||||
let start = i64::from_str_radix(reference, 16).unwrap() + args["offset"].as_i64().unwrap_or(0);
|
||||
let count = args["count"].as_i64().unwrap();
|
||||
const END: i64 = 0x1010;
|
||||
if start >= END {
|
||||
send!(
|
||||
json!({"type": "response", "request_seq": msg["seq"], "command": "readMemory", "success": false, "message": format!("Cannot access memory at address {start:#x}")})
|
||||
);
|
||||
} else {
|
||||
let bytes: Vec<u8> = (start..(start + count).min(END)).map(|a| a as u8).collect();
|
||||
ok!(
|
||||
msg,
|
||||
json!({"address": format!("{start:#x}"), "data": base64::engine::general_purpose::STANDARD.encode(&bytes), "unreadableBytes": count - bytes.len() as i64})
|
||||
);
|
||||
}
|
||||
}
|
||||
"disassemble" => {
|
||||
let args = &msg["arguments"];
|
||||
let reference = args["memoryReference"].as_str().unwrap().trim_start_matches("0x");
|
||||
let pc = i64::from_str_radix(reference, 16).unwrap() + args["offset"].as_i64().unwrap_or(0);
|
||||
let (offset, count) =
|
||||
(args["instructionOffset"].as_i64().unwrap(), args["instructionCount"].as_i64().unwrap());
|
||||
let insn = |a: i64| {
|
||||
if (0x1000..0x1100).contains(&a) {
|
||||
json!({"address": format!("{a:#x}"), "instruction": format!("insn {}", (a - 0x1000) / 4), "instructionBytes": "90909090"})
|
||||
} else {
|
||||
json!({"address": format!("{a:#x}"), "instruction": "", "presentationHint": "invalid"})
|
||||
}
|
||||
};
|
||||
let addresses: Option<Vec<i64>> = match script.disassemble.unwrap() {
|
||||
FakeDisassembler::Lldb => Some((0..count).map(|i| pc + 4 * (offset + i)).collect()),
|
||||
FakeDisassembler::Gdb if offset + count < 0 => None,
|
||||
FakeDisassembler::Gdb => {
|
||||
let all: Vec<i64> = (0..offset + count).map(|i| pc + 4 * i).collect();
|
||||
let from = if offset >= 0 { offset } else { (all.len() as i64 + offset).max(0) };
|
||||
Some(all[from as usize..].to_vec())
|
||||
}
|
||||
};
|
||||
match addresses {
|
||||
Some(a) => ok!(msg, json!({"instructions": a.into_iter().map(insn).collect::<Vec<_>>()})),
|
||||
None => send!(
|
||||
json!({"type": "response", "request_seq": msg["seq"], "command": "disassemble", "success": false, "message": "Argument 'count' should be an non-negative integer."})
|
||||
),
|
||||
}
|
||||
}
|
||||
"completions" => ok!(
|
||||
msg,
|
||||
json!({"targets": [
|
||||
@@ -1952,6 +2024,146 @@ async fn function_and_data_breakpoints_are_stored_and_sent() {
|
||||
h.manager.stop(id).await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn memory_view_reads_memory_from_a_reference() {
|
||||
let h = harness(Script { read_memory: true, ..Script::default() });
|
||||
let id = h.start(config()).await.unwrap();
|
||||
h.wait_event(|e| matches!(e, DebugEvent::Stopped { .. })).await;
|
||||
assert_eq!(
|
||||
h.request("initialize")["arguments"]["supportsMemoryReferences"],
|
||||
true,
|
||||
"adapters only send references when asked"
|
||||
);
|
||||
assert!(h.manager.capabilities(id).unwrap().read_memory);
|
||||
|
||||
let pointer = h.manager.evaluate_in(id, Some(10), "&msg[0]".into(), Some("watch".into())).await.unwrap();
|
||||
assert_eq!(pointer.memory_reference.as_deref(), Some("0x1000"));
|
||||
let plain = h.manager.evaluate(id, Some(10), "n".into()).await.unwrap();
|
||||
assert_eq!(plain.memory_reference, None);
|
||||
|
||||
let block = h.manager.read_memory(id, "0x1000".into(), 0, 8).await.unwrap();
|
||||
assert_eq!(block, MemoryBlock { address: "0x1000".into(), data: (0..8).collect(), unreadable_bytes: 0 });
|
||||
assert_eq!(h.request("readMemory")["arguments"], json!({"memoryReference": "0x1000", "offset": 0, "count": 8}));
|
||||
|
||||
// Paging back and forth goes through `offset` on the same reference; the end of the mapping
|
||||
// comes back as unreadable bytes.
|
||||
let block = h.manager.read_memory(id, "0x1000".into(), 8, 16).await.unwrap();
|
||||
assert_eq!((block.address.as_str(), block.data.len(), block.unreadable_bytes), ("0x1008", 8, 8));
|
||||
assert_eq!(block.data[0], 0x08);
|
||||
|
||||
// Unmapped memory is the adapter's error, and the session goes on.
|
||||
let err = h.manager.read_memory(id, "0x1000".into(), 0x20, 16).await.unwrap_err();
|
||||
assert!(err.to_string().contains("Cannot access memory at address 0x1020"), "{err}");
|
||||
assert!(!h.manager.threads(id).await.unwrap().is_empty());
|
||||
|
||||
let _ = h.manager.read_memory(id, "0x1000".into(), 0, u32::MAX).await;
|
||||
let last = h.log.lock().iter().rev().find(|m| m["command"] == "readMemory").cloned().unwrap();
|
||||
assert_eq!(last["arguments"]["count"], MAX_READ, "one read never asks for more than a few pages");
|
||||
h.manager.stop(id).await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn memory_view_says_when_the_adapter_cannot_read_memory() {
|
||||
let h = harness(Script::default());
|
||||
let id = h.start(config()).await.unwrap();
|
||||
h.wait_event(|e| matches!(e, DebugEvent::Stopped { .. })).await;
|
||||
assert!(!h.manager.capabilities(id).unwrap().read_memory);
|
||||
let err = h.manager.read_memory(id, "0x1000".into(), 0, 16).await.unwrap_err();
|
||||
assert_eq!(err.kind, ide_core::error::ErrorKind::Unavailable);
|
||||
assert!(err.to_string().contains("debug adapter `debugpy` cannot read memory"), "{err}");
|
||||
assert!(!h.commands().iter().any(|c| c == "readMemory"), "nothing is sent to an adapter without support");
|
||||
h.manager.stop(id).await.unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn variables_keep_their_memory_reference() {
|
||||
let v = variable_from(
|
||||
&json!({"name": "words", "value": "0x4010", "variablesReference": 3, "memoryReference": "0x4010"}),
|
||||
);
|
||||
assert_eq!(v.memory_reference.as_deref(), Some("0x4010"));
|
||||
assert_eq!(variable_from(&json!({"name": "n", "value": "1", "memoryReference": ""})).memory_reference, None);
|
||||
let json = serde_json::to_value(variable_from(&json!({"name": "n", "value": "1"}))).unwrap();
|
||||
assert!(json.get("memoryReference").is_none(), "absent, not null, for the UI's optional field");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn disassembly_reads_instructions_around_the_instruction_pointer() {
|
||||
let h = harness(Script { disassemble: Some(FakeDisassembler::Lldb), ..Script::default() });
|
||||
let id = h.start(config()).await.unwrap();
|
||||
h.wait_event(|e| matches!(e, DebugEvent::Stopped { .. })).await;
|
||||
let caps = h.manager.capabilities(id).unwrap();
|
||||
assert!(caps.disassemble && caps.instruction_stepping);
|
||||
|
||||
let list = h.manager.disassemble(id, "0x1010".into(), 2, 5).await.unwrap();
|
||||
let addresses: Vec<&str> = list.iter().map(|i| i.address.as_str()).collect();
|
||||
assert_eq!(addresses, ["0x1008", "0x100c", "0x1010", "0x1014", "0x1018"]);
|
||||
assert_eq!((list[2].instruction.as_str(), list[2].bytes.as_deref()), ("insn 4", Some("90909090")));
|
||||
assert_eq!(
|
||||
requests(&h, "disassemble")[0],
|
||||
json!({"memoryReference": "0x1010", "offset": 0, "instructionOffset": -2, "instructionCount": 5, "resolveSymbols": true})
|
||||
);
|
||||
|
||||
// Before the first mapped instruction the adapter pads; the padding is not shown.
|
||||
let list = h.manager.disassemble(id, "0x1004".into(), 4, 6).await.unwrap();
|
||||
let addresses: Vec<&str> = list.iter().map(|i| i.address.as_str()).collect();
|
||||
assert_eq!(addresses, ["0x1000", "0x1004", "0x1008"]);
|
||||
|
||||
let _ = h.manager.disassemble(id, "0x1000".into(), 0, u32::MAX).await;
|
||||
assert_eq!(requests(&h, "disassemble").last().unwrap()["instructionCount"], MAX_INSTRUCTIONS);
|
||||
h.manager.stop(id).await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn disassembly_starts_at_the_instruction_pointer_when_the_adapter_cannot_go_back() {
|
||||
let h = harness(Script { disassemble: Some(FakeDisassembler::Gdb), ..Script::default() });
|
||||
let id = h.start(config()).await.unwrap();
|
||||
h.wait_event(|e| matches!(e, DebugEvent::Stopped { .. })).await;
|
||||
// GDB's answer to "4 before" leaves out the instruction pointer; the view asks again from it.
|
||||
let list = h.manager.disassemble(id, "0x1010".into(), 4, 10).await.unwrap();
|
||||
assert_eq!(list.first().map(|i| i.address.as_str()), Some("0x1010"));
|
||||
assert_eq!(list.len(), 6);
|
||||
let offsets: Vec<Value> = requests(&h, "disassemble").iter().map(|r| r["instructionOffset"].clone()).collect();
|
||||
assert_eq!(offsets, [json!(-4), json!(0)]);
|
||||
h.manager.stop(id).await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn instruction_steps_send_the_granularity_and_line_steps_do_not() {
|
||||
let h = harness(Script { disassemble: Some(FakeDisassembler::Lldb), ..Script::default() });
|
||||
let id = h.start(config()).await.unwrap();
|
||||
h.wait_event(|e| matches!(e, DebugEvent::Stopped { .. })).await;
|
||||
h.manager.step_instruction(id, 1, StepKind::Into).await.unwrap();
|
||||
assert_eq!(requests(&h, "stepIn").last().unwrap(), &json!({"threadId": 1, "granularity": "instruction"}));
|
||||
h.manager.step(id, 1, StepKind::Over).await.unwrap();
|
||||
assert_eq!(requests(&h, "next").last().unwrap(), &json!({"threadId": 1}));
|
||||
h.manager.stop(id).await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn disassembly_and_instruction_steps_say_when_the_adapter_cannot() {
|
||||
let h = harness(Script::default());
|
||||
let id = h.start(config()).await.unwrap();
|
||||
h.wait_event(|e| matches!(e, DebugEvent::Stopped { .. })).await;
|
||||
let caps = h.manager.capabilities(id).unwrap();
|
||||
assert!(!caps.disassemble && !caps.instruction_stepping);
|
||||
let err = h.manager.disassemble(id, "0x1000".into(), 0, 16).await.unwrap_err();
|
||||
assert_eq!(err.kind, ide_core::error::ErrorKind::Unavailable);
|
||||
assert!(err.to_string().contains("debug adapter `debugpy` cannot disassemble"), "{err}");
|
||||
let err = h.manager.step_instruction(id, 1, StepKind::Over).await.unwrap_err();
|
||||
assert_eq!(err.kind, ide_core::error::ErrorKind::Unavailable);
|
||||
let sent = h.commands();
|
||||
assert!(!sent.iter().any(|c| c == "disassemble" || c == "next"), "nothing is sent to an adapter without support");
|
||||
h.manager.stop(id).await.unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn frames_keep_their_instruction_pointer() {
|
||||
let f = frame_from(&json!({"id": 1, "name": "atoi", "line": 0, "instructionPointerReference": "0x7ffff7c4a2e0"}));
|
||||
assert_eq!(f.instruction_pointer_reference.as_deref(), Some("0x7ffff7c4a2e0"));
|
||||
let json = serde_json::to_value(frame_from(&json!({"id": 1, "name": "main"}))).unwrap();
|
||||
assert!(json.get("instructionPointerReference").is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn smart_step_into_and_reset_frame() {
|
||||
let h = harness(Script::default());
|
||||
@@ -3791,3 +4003,19 @@ async fn stop_detaches_from_an_attached_program() {
|
||||
assert!(!h.commands().contains(&"terminate".to_owned()));
|
||||
assert_eq!(h.request("disconnect")["arguments"]["terminateDebuggee"], false);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cell_breakpoints_go_only_to_their_notebooks_kernel_session() {
|
||||
use crate::jvm_memory::test_support::bare_session_of;
|
||||
use std::path::Path;
|
||||
let (a, b) = ("vscode-notebook-cell:/p/a.ipynb#c1", "vscode-notebook-cell:/p/b.ipynb#c1");
|
||||
let mut kernel = bare_session_of(crate::NOTEBOOK_ADAPTER, "attach");
|
||||
std::sync::Arc::get_mut(&mut kernel.session).unwrap().notebook_cells =
|
||||
Some("vscode-notebook-cell:/p/a.ipynb#".into());
|
||||
let python = bare_session_of("debugpy", "launch");
|
||||
assert!(kernel.session.takes(Path::new(a)));
|
||||
assert!(!kernel.session.takes(Path::new(b)), "another notebook's cells");
|
||||
assert!(kernel.session.takes(Path::new("/p/lib.py")), "files the cells may call");
|
||||
assert!(!python.session.takes(Path::new(a)));
|
||||
assert!(python.session.takes(Path::new("/p/lib.py")));
|
||||
}
|
||||
@@ -1,11 +1,12 @@
|
||||
//! Drives real debug adapters against tiny programs (one per language), checking the
|
||||
//! launch templates and the IDEA-parity features: line / method breakpoints, Smart Step
|
||||
//! Into, Reset Frame, Force Step Over, Force Run to Cursor and Set Value.
|
||||
//! Into, Reset Frame, Force Step Over, Force Run to Cursor, Set Value, the Memory View and the Disassembly view.
|
||||
//!
|
||||
//! Ignored by default (needs the adapters installed). Run with
|
||||
//! `OPENIDEA_DAP_FIXTURES=<dir> cargo test -p ide-dap --test real_adapters -- --ignored --nocapture`
|
||||
//! where `<dir>` holds `py/app.py`, `node/app.js`, `go/demo` (built with `-N -l`),
|
||||
//! `rust/target/debug/demo` and `c/main`. Adapters not found on `PATH` are skipped.
|
||||
//! `rust/target/debug/demo` and `c/main` (whose loop function also has a `char msg[]` local, for
|
||||
//! the Memory View). Adapters not found on `PATH` are skipped.
|
||||
|
||||
use ide_core::event::DebugEvent;
|
||||
use ide_core::{DebugSessionId, IdeEvent, SharedSink};
|
||||
@@ -280,6 +281,78 @@ async fn scenario(case: &Case) -> Result<Vec<String>, String> {
|
||||
let caps = m.capabilities(s).map_err(|e| e.message)?;
|
||||
report.push(format!("capabilities: {caps:?}"));
|
||||
|
||||
// Memory View: the bytes at an address expression (the C fixture's `msg`), and an unmapped address.
|
||||
if caps.read_memory {
|
||||
match m.evaluate_in(s, Some(top.id), "&msg[0]".into(), Some("watch".into())).await {
|
||||
Ok(v) => match v.memory_reference {
|
||||
Some(r) => match m.read_memory(s, r.clone(), 0, 16).await {
|
||||
Ok(b) => report.push(format!(
|
||||
"memory view `&msg[0]` ({r}): {} = {:02x?} {:?}, {} unreadable",
|
||||
b.address,
|
||||
b.data,
|
||||
String::from_utf8_lossy(&b.data),
|
||||
b.unreadable_bytes
|
||||
)),
|
||||
Err(e) => report.push(format!("memory view `&msg[0]`: FAILED {}", e.message)),
|
||||
},
|
||||
None => report.push(format!("memory view `&msg[0]` = {}: no memory reference", v.value)),
|
||||
},
|
||||
Err(e) => report.push(format!("memory view `&msg[0]`: not evaluated ({})", e.message)),
|
||||
}
|
||||
match m.read_memory(s, "0x0".into(), 0, 16).await {
|
||||
Ok(b) => report.push(format!("memory view 0x0: {} bytes, {} unreadable", b.data.len(), b.unreadable_bytes)),
|
||||
Err(e) => report.push(format!("memory view 0x0: error `{}`", e.message)),
|
||||
}
|
||||
} else {
|
||||
report.push("memory view: readMemory not supported".into());
|
||||
}
|
||||
|
||||
// Disassembly: the instructions around the stop's instruction pointer, then two instruction steps,
|
||||
// which stay on the loop line and inside the instructions shown.
|
||||
let address = |a: &str| u128::from_str_radix(a.trim_start_matches("0x"), 16).ok();
|
||||
match (caps.disassemble, top.instruction_pointer_reference.clone()) {
|
||||
(true, Some(pc)) => match m.disassemble(s, pc.clone(), 8, 24).await {
|
||||
Ok(list) => {
|
||||
let shown = |a: &str| list.iter().position(|i| address(&i.address) == address(a));
|
||||
match shown(&pc) {
|
||||
Some(at) => report.push(format!(
|
||||
"disassembly at {pc}: {} instructions, the instruction pointer is #{at}: `{}` ({:?})",
|
||||
list.len(),
|
||||
list[at].instruction,
|
||||
list[at].bytes
|
||||
)),
|
||||
None => report.push(format!("disassembly at {pc}: FAILED, not among {list:?}")),
|
||||
}
|
||||
if caps.instruction_stepping {
|
||||
let mut steps = vec![pc];
|
||||
for _ in 0..2 {
|
||||
let seen = run.seen();
|
||||
m.step_instruction(s, thread, StepKind::Over).await.map_err(|e| e.message)?;
|
||||
run.stopped_after(seen).await.ok_or("no stop after step over instruction")?;
|
||||
let f = run.top(s, thread).await;
|
||||
if f.line != case.loop_line {
|
||||
report.push(format!(
|
||||
"step over instruction: left the loop line for {}:{}",
|
||||
f.name,
|
||||
f.line + 1
|
||||
));
|
||||
}
|
||||
steps.push(f.instruction_pointer_reference.unwrap_or_default());
|
||||
}
|
||||
let all = steps.iter().all(|a| shown(a).is_some());
|
||||
report.push(format!("step over instruction: {} (all shown: {all})", steps.join(" -> ")));
|
||||
} else {
|
||||
report.push("instruction stepping: not supported".into());
|
||||
}
|
||||
}
|
||||
Err(e) => report.push(format!("disassembly at {pc}: FAILED {}", e.message)),
|
||||
},
|
||||
(true, None) => report.push("disassembly: the top frame has no instruction pointer".into()),
|
||||
(false, _) => report.push("disassembly: not supported".into()),
|
||||
}
|
||||
// Instruction steps resumed the thread: frame ids from before them may be gone.
|
||||
let top = run.top(s, thread).await;
|
||||
|
||||
// Set Value on the first local that is an integer.
|
||||
let scopes = m.scopes(s, top.id).await.map_err(|e| e.message)?;
|
||||
for scope in scopes.iter().filter(|sc| !sc.expensive) {
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
|
||||
@@ -221,19 +287,56 @@ impl ClickhousePool {
|
||||
}
|
||||
|
||||
/// `max_rows`: the rows the server may send (the skipped ones included).
|
||||
fn request(&self, client: &Client, query_id: &str, max_rows: usize, session: &Session) -> RequestBuilder {
|
||||
fn request(
|
||||
&self,
|
||||
client: &Client,
|
||||
query_id: &str,
|
||||
max_rows: usize,
|
||||
session: &Session,
|
||||
workspace_bytes: Option<usize>,
|
||||
) -> RequestBuilder {
|
||||
let mut request = client
|
||||
.post(self.0.endpoint.clone())
|
||||
.basic_auth(&self.0.user, Some(&self.0.password))
|
||||
.header(reqwest::header::CONTENT_TYPE, "text/plain; charset=utf-8")
|
||||
.query(&self.0.settings)
|
||||
.query(&[("query_id", query_id), ("default_format", FORMAT)]);
|
||||
if workspace_bytes.is_some() && !session.strict_read_only {
|
||||
let settings: Vec<_> = self
|
||||
.0
|
||||
.settings
|
||||
.iter()
|
||||
.filter(|(name, _)| !matches!(name.as_str(), "read_overflow_mode" | "timeout_overflow_mode"))
|
||||
.collect();
|
||||
request = request.query(&settings);
|
||||
} else {
|
||||
request = request.query(&self.0.settings);
|
||||
}
|
||||
if !session.strict_read_only {
|
||||
request = request.query(&[
|
||||
("output_format_json_quote_denormals", "1".into()),
|
||||
("max_result_rows", max_rows.saturating_add(1).to_string()),
|
||||
("result_overflow_mode", "break".into()),
|
||||
]);
|
||||
if let Some(bytes) = workspace_bytes {
|
||||
request = request.query(&[
|
||||
("max_result_rows", max_rows.to_string()),
|
||||
("result_overflow_mode", "throw".into()),
|
||||
("read_overflow_mode", "throw".into()),
|
||||
("timeout_overflow_mode", "throw".into()),
|
||||
]);
|
||||
for (name, value) in [
|
||||
("max_result_bytes", bytes),
|
||||
("max_execution_time", 20),
|
||||
("cancel_http_readonly_queries_on_client_close", 1),
|
||||
("max_rows_to_read", 1_000_000),
|
||||
("max_bytes_to_read", 268_435_456),
|
||||
] {
|
||||
if !self.0.settings.iter().any(|(setting, _)| setting == name) {
|
||||
request = request.query(&[(name, value)]);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
request = request.query(&[
|
||||
("output_format_json_quote_denormals", "1".into()),
|
||||
("max_result_rows", max_rows.saturating_add(1).to_string()),
|
||||
("result_overflow_mode", "break".into()),
|
||||
]);
|
||||
}
|
||||
}
|
||||
if let Some(session_id) = &session.id {
|
||||
request = request.query(&[("session_id", session_id.as_str()), ("session_timeout", "3600")]);
|
||||
@@ -261,22 +364,70 @@ 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, None).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 +440,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_prefix(response).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 +453,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 +484,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(
|
||||
@@ -345,6 +496,66 @@ impl ClickhousePool {
|
||||
}
|
||||
}
|
||||
|
||||
/// Dedicated workspace sessions consume the response before any grid truncation or formatting.
|
||||
pub(crate) async fn workspace_rows(
|
||||
&self,
|
||||
sql: &str,
|
||||
max_rows: usize,
|
||||
max_bytes: usize,
|
||||
cancel: &CancellationToken,
|
||||
mut consume: impl FnMut(&[u8]) -> IdeResult<()>,
|
||||
) -> IdeResult<()> {
|
||||
let mut slot = self.session(&self.0.session, cancel).await?;
|
||||
let state = slot.as_mut().expect("session was initialized");
|
||||
let mut stateless;
|
||||
let session = if self.0.use_http_session {
|
||||
state
|
||||
} else {
|
||||
stateless = state.clone();
|
||||
drop(slot);
|
||||
&mut stateless
|
||||
};
|
||||
let client = self.client()?;
|
||||
let query_id = uuid::Uuid::new_v4().to_string();
|
||||
let request = self.request(&client, &query_id, max_rows, session, Some(max_bytes)).body(sql.to_owned());
|
||||
let fetch = async {
|
||||
let mut response = request.send().await.map_err(http_error)?;
|
||||
let status = response.status();
|
||||
let metadata = |name: &str| response.headers().get(name).and_then(|v| v.to_str().ok());
|
||||
let code = metadata("X-ClickHouse-Exception-Code").map(str::to_owned);
|
||||
if !status.is_success() || code.as_deref().is_some_and(|code| code != "0") {
|
||||
let body = response_prefix(response).await.map_err(http_error)?;
|
||||
return Err(self.server_error(status, code.as_deref(), &body));
|
||||
}
|
||||
if metadata("X-ClickHouse-Format").is_some_and(|format| format != FORMAT) {
|
||||
return Err(IdeError::invalid("ClickHouse did not return the workspace response format"));
|
||||
}
|
||||
let mut received = 0;
|
||||
while let Some(chunk) = response.chunk().await.map_err(http_error)? {
|
||||
received += chunk.len();
|
||||
if received > max_bytes {
|
||||
return Err(IdeError::invalid("Workspace input exceeds the source byte limit"));
|
||||
}
|
||||
consume(&chunk)?;
|
||||
}
|
||||
Ok(())
|
||||
};
|
||||
let result = tokio::select! {
|
||||
biased;
|
||||
() = cancel.cancelled() => Err(IdeError::cancelled()),
|
||||
() = self.0.closed.cancelled() => Err(IdeError::cancelled()),
|
||||
() = tokio::time::sleep(Duration::from_secs(25)) =>
|
||||
Err(IdeError::new(ErrorKind::TimedOut, "Workspace ClickHouse source read timed out")),
|
||||
result = fetch => result,
|
||||
};
|
||||
if result.is_ok() {
|
||||
session.initialized = true;
|
||||
} else {
|
||||
let _ = self.kill(&client, &query_id, session).await;
|
||||
}
|
||||
result.map_err(|e| self.redact_error(e))
|
||||
}
|
||||
|
||||
async fn kill(&self, client: &Client, query_id: &str, session: &Session) -> IdeResult<()> {
|
||||
let mut request = client
|
||||
.post(self.0.endpoint.clone())
|
||||
@@ -361,7 +572,7 @@ impl ClickhousePool {
|
||||
.get("X-ClickHouse-Exception-Code")
|
||||
.and_then(|value| value.to_str().ok())
|
||||
.map(str::to_owned);
|
||||
let body = response.bytes().await.map_err(http_error)?;
|
||||
let body = response_prefix(response).await.map_err(http_error)?;
|
||||
if status.is_success() && !code.as_deref().is_some_and(|code| code != "0") && !body.starts_with(b"Code:") {
|
||||
Ok(())
|
||||
} else {
|
||||
@@ -390,6 +601,17 @@ impl ClickhousePool {
|
||||
}
|
||||
}
|
||||
|
||||
async fn response_prefix(mut response: reqwest::Response) -> Result<Vec<u8>, reqwest::Error> {
|
||||
const LIMIT: usize = 16_384;
|
||||
let mut body = Vec::new();
|
||||
while body.len() < LIMIT {
|
||||
let Some(chunk) = response.chunk().await? else { break };
|
||||
let remaining = LIMIT - body.len();
|
||||
body.extend_from_slice(&chunk[..chunk.len().min(remaining)]);
|
||||
}
|
||||
Ok(body)
|
||||
}
|
||||
|
||||
type DecodedResult = (Vec<ResultColumn>, Vec<Vec<Option<String>>>, bool);
|
||||
|
||||
/// Decodes a streamed [`FORMAT`] body. Reads past the first `skip` rows unparsed (a later
|
||||
@@ -596,6 +818,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 +1061,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 +1192,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 +1529,84 @@ 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() {
|
||||
assert_stateless_requests_overlap(false).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn stateless_workspace_reads_do_not_block_queries() {
|
||||
assert_stateless_requests_overlap(true).await;
|
||||
}
|
||||
|
||||
async fn assert_stateless_requests_overlap(workspace: bool) {
|
||||
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::Clickhouse(pool) = Pool::connect(&source, None, None).await.unwrap() else { unreachable!() };
|
||||
let cancel = CancellationToken::new();
|
||||
let first = async {
|
||||
if workspace {
|
||||
pool.workspace_rows("SELECT 1", 1, 1024, &cancel, |_| Ok(())).await
|
||||
} else {
|
||||
pool.execute("SELECT 1", 1, &cancel).await.map(drop)
|
||||
}
|
||||
};
|
||||
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(|_| ()),
|
||||
}
|
||||
}
|
||||
@@ -1329,6 +1330,71 @@ impl Pool {
|
||||
Ok(conn.finish_read_only(owned, result).await?.1)
|
||||
}
|
||||
|
||||
pub(crate) async fn read_workspace_postgres(
|
||||
&self,
|
||||
request: &crate::workspace_input::WorkspaceInputRequest,
|
||||
selection: Option<&[&str]>,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<crate::workspace_input::WorkspaceInput> {
|
||||
let Pool::Postgres(pool) = self else {
|
||||
return Err(IdeError::internal("Expected a PostgreSQL workspace connection"));
|
||||
};
|
||||
let mut conn = tokio::select! {
|
||||
biased;
|
||||
() = cancel.cancelled() => return Err(IdeError::cancelled()),
|
||||
result = pool.get() => result?,
|
||||
};
|
||||
let mut backend = None;
|
||||
let read = async {
|
||||
if conn.options.read_only == PgReadOnly::Transaction {
|
||||
conn.start_read_only().await?;
|
||||
} else {
|
||||
sqlx::raw_sql("BEGIN READ ONLY").execute(&mut **conn).await.map_err(db_err)?;
|
||||
}
|
||||
let row = sqlx::raw_sql(
|
||||
"SELECT pg_catalog.pg_backend_pid(), pg_catalog.current_setting('transaction_read_only') = 'on'",
|
||||
)
|
||||
.fetch_one(&mut **conn)
|
||||
.await
|
||||
.map_err(db_err)?;
|
||||
backend = Some(row.try_get::<i32, _>(0).map_err(db_err)?);
|
||||
if !row.try_get::<bool, _>(1).map_err(db_err)? {
|
||||
return Err(IdeError::new(
|
||||
ErrorKind::PermissionDenied,
|
||||
"Workspace PostgreSQL transaction is not read-only",
|
||||
));
|
||||
}
|
||||
crate::workspace_input::read_postgres(&mut conn, request, selection).await
|
||||
};
|
||||
let result = tokio::select! {
|
||||
biased;
|
||||
() = cancel.cancelled() => Err(IdeError::cancelled()),
|
||||
() = tokio::time::sleep(Duration::from_secs(30)) =>
|
||||
Err(IdeError::new(ErrorKind::TimedOut, "Workspace PostgreSQL source read timed out")),
|
||||
result = read => result,
|
||||
};
|
||||
if result.is_ok() {
|
||||
// Do not send a PID-based cancel once a pooler may have released this backend.
|
||||
let rollback =
|
||||
tokio::time::timeout(Duration::from_secs(3), sqlx::raw_sql("ROLLBACK").execute(&mut **conn)).await;
|
||||
if matches!(rollback, Ok(Ok(_))) {
|
||||
conn.in_transaction = false;
|
||||
} else {
|
||||
conn.conn.take();
|
||||
}
|
||||
} else {
|
||||
if let Some(pid) = backend {
|
||||
let _ = tokio::time::timeout(
|
||||
Duration::from_secs(3),
|
||||
self.cancel_query(format!("SELECT pg_catalog.pg_cancel_backend({pid})")),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
conn.conn.take();
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/// Runs one statement and keeps at most `max_rows` rows. Cancelling stops
|
||||
/// the statement on the server (PostgreSQL, MySQL) and drops the connection.
|
||||
pub async fn execute(&self, sql: &str, max_rows: usize, cancel: &CancellationToken) -> IdeResult<QueryResult> {
|
||||
|
||||
@@ -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']));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
use super::{DbJdbcDriver, JdbcPool};
|
||||
use crate::source::{DUCKDB_URL, duck_lake_path};
|
||||
use crate::{DataSource, DbDuckLake, DbDuckLakeKind, DbManager, Pool};
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
|
||||
const DUCKDB_CLASS: &str = "org.duckdb.DuckDBDriver";
|
||||
|
||||
impl DbManager {
|
||||
pub fn approve_ducklake_source(&self, source: &DataSource) -> IdeResult<()> {
|
||||
if source.duck_lake.is_none() {
|
||||
return Err(IdeError::invalid("Expected a DuckLake data source"));
|
||||
}
|
||||
source.validate_duck_lake()?;
|
||||
self.duck_lake_driver(&source.jdbc_driver)?.validate()?;
|
||||
if source.global {
|
||||
return Ok(());
|
||||
}
|
||||
self.record_jdbc_approval(source)
|
||||
}
|
||||
|
||||
fn duck_lake_driver(&self, id: &str) -> IdeResult<DbJdbcDriver> {
|
||||
let driver = self.jdbc_driver_by_id(id)?;
|
||||
driver.require_vendor("duckdb")?;
|
||||
if driver.class_name != DUCKDB_CLASS {
|
||||
return Err(IdeError::invalid("Select a DuckDB driver profile with the official DuckDB JDBC driver class"));
|
||||
}
|
||||
Ok(driver)
|
||||
}
|
||||
|
||||
/// Creates a lake in a new directory through a separate, disposable JDBC session.
|
||||
pub async fn create_ducklake(&self, jdbc_driver: &str, directory: &str) -> IdeResult<()> {
|
||||
duck_lake_path(directory, false)?;
|
||||
let driver = self.duck_lake_driver(jdbc_driver)?;
|
||||
let fields = duck_lake_fields("create", directory.to_owned(), "");
|
||||
let pool = JdbcPool::open(driver, self.jdbc_registry()?.with_file_name("jdbc"), fields).await?;
|
||||
pool.close().await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) async fn open_ducklake(&self, source: &DataSource, lake: &DbDuckLake, testing: bool) -> IdeResult<Pool> {
|
||||
source.validate_duck_lake()?;
|
||||
self.check_jdbc_project_approval(source, testing)?;
|
||||
let driver = self.duck_lake_driver(&source.jdbc_driver)?;
|
||||
let cache = self.jdbc_registry()?.with_file_name("jdbc");
|
||||
let (mode, value) = match lake.kind {
|
||||
DbDuckLakeKind::Secret => ("secret", lake.value.clone()),
|
||||
DbDuckLakeKind::File => {
|
||||
let path = self.root.join(&lake.value);
|
||||
let value = path.to_str().ok_or_else(|| IdeError::invalid("Invalid DuckLake catalog file path"))?;
|
||||
duck_lake_path(value, false)?;
|
||||
("file", value.to_owned())
|
||||
}
|
||||
};
|
||||
let fields = duck_lake_fields(mode, value, lake.data_path.as_deref().unwrap_or_default());
|
||||
JdbcPool::open(driver, cache, fields).await.map(Box::new).map(Pool::Jdbc)
|
||||
}
|
||||
}
|
||||
|
||||
fn duck_lake_fields(mode: &str, value: String, data_path: &str) -> Vec<String> {
|
||||
vec![
|
||||
"openDuckLake".into(),
|
||||
DUCKDB_CLASS.into(),
|
||||
DUCKDB_URL.into(),
|
||||
String::new(),
|
||||
String::new(),
|
||||
(mode != "create").to_string(),
|
||||
mode.into(),
|
||||
value,
|
||||
data_path.to_owned(),
|
||||
]
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn ordinary_jdbc_rejects_a_ducklake_even_with_a_file_url() {
|
||||
let source = DataSource {
|
||||
driver: crate::DbDriver::Jdbc,
|
||||
url: "jdbc:duckdb:existing.duckdb".into(),
|
||||
duck_lake: Some(DbDuckLake {
|
||||
kind: DbDuckLakeKind::File,
|
||||
value: "catalog.ducklake".into(),
|
||||
data_path: None,
|
||||
}),
|
||||
..Default::default()
|
||||
};
|
||||
let driver = DbJdbcDriver {
|
||||
id: "duckdb".into(),
|
||||
name: "DuckDB".into(),
|
||||
vendor: Some("duckdb".into()),
|
||||
jars: vec![],
|
||||
class_name: DUCKDB_CLASS.into(),
|
||||
url_template: DUCKDB_URL.into(),
|
||||
};
|
||||
let error = JdbcPool::connect(&source, None, driver, Default::default())
|
||||
.await
|
||||
.err()
|
||||
.expect("ordinary JDBC must reject DuckLake fields before opening a connection");
|
||||
assert_eq!(error.message, "DuckLake catalogs require a DuckLake connection");
|
||||
}
|
||||
}
|
||||
@@ -2,21 +2,22 @@
|
||||
//! 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;
|
||||
mod ducklake;
|
||||
|
||||
use bridge::Bridge;
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
@@ -79,6 +80,13 @@ pub fn jdbc_driver_classes(jars: &[String]) -> IdeResult<Vec<String>> {
|
||||
}
|
||||
|
||||
impl DbJdbcDriver {
|
||||
fn require_vendor(&self, vendor: &str) -> IdeResult<()> {
|
||||
if self.vendor.as_deref() != Some(vendor) {
|
||||
return Err(IdeError::invalid("The JDBC driver profile is not associated with this data source type"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate(&self) -> IdeResult<()> {
|
||||
if self.id.is_empty()
|
||||
|| self.name.trim().is_empty()
|
||||
@@ -138,6 +146,30 @@ impl DbManager {
|
||||
self.update_jdbc_driver(id, None)
|
||||
}
|
||||
|
||||
fn record_jdbc_approval(&self, source: &DataSource) -> IdeResult<()> {
|
||||
let (path, fingerprint) = self.jdbc_approval(source)?;
|
||||
persist_local(&path, fingerprint.as_bytes())
|
||||
}
|
||||
|
||||
fn jdbc_driver_by_id(&self, id: &str) -> IdeResult<DbJdbcDriver> {
|
||||
self.jdbc_drivers()?
|
||||
.into_iter()
|
||||
.find(|d| d.id == id)
|
||||
.ok_or_else(|| IdeError::invalid("Select an installed JDBC driver profile"))
|
||||
}
|
||||
|
||||
fn check_jdbc_project_approval(&self, source: &DataSource, testing: bool) -> IdeResult<()> {
|
||||
if !testing && !source.global {
|
||||
let (path, expected) = self.jdbc_approval(source)?;
|
||||
if std::fs::read_to_string(path).ok().as_deref() != Some(&expected) {
|
||||
return Err(IdeError::invalid(
|
||||
"Review this project's JDBC URL and properties, then save the data source before connecting",
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn jdbc_approval(&self, source: &DataSource) -> IdeResult<(PathBuf, String)> {
|
||||
let registry = self.jdbc_registry()?;
|
||||
let key = serde_json::to_vec(&(&self.root, &source.id)).map_err(|e| IdeError::internal(e.to_string()))?;
|
||||
@@ -150,7 +182,10 @@ impl DbManager {
|
||||
&source.options,
|
||||
))
|
||||
.map_err(|e| IdeError::internal(e.to_string()))?;
|
||||
if self.jdbc_password_isolated(source) {
|
||||
if let Some(lake) = &source.duck_lake {
|
||||
settings.extend_from_slice(b"\0ducklake\0");
|
||||
serde_json::to_writer(&mut settings, lake).map_err(|e| IdeError::internal(e.to_string()))?;
|
||||
} else if self.jdbc_password_isolated(source) {
|
||||
settings.extend_from_slice(b"\0jdbc-password");
|
||||
}
|
||||
Ok((
|
||||
@@ -164,8 +199,70 @@ impl DbManager {
|
||||
if source.driver != crate::DbDriver::Jdbc || source.plugin_owner.is_some() {
|
||||
return Err(IdeError::invalid("Expected a user-managed JDBC data source"));
|
||||
}
|
||||
let (path, fingerprint) = self.jdbc_approval(source)?;
|
||||
persist_local(&path, fingerprint.as_bytes())
|
||||
if source.duck_lake.is_some() {
|
||||
return self.approve_ducklake_source(source);
|
||||
}
|
||||
self.record_jdbc_approval(source)
|
||||
}
|
||||
|
||||
/// A workspace uses only the selected host driver and a fresh in-memory database.
|
||||
pub(crate) async fn workspace_engine(&self, profile: &str) -> IdeResult<JdbcPool> {
|
||||
let driver = self
|
||||
.jdbc_drivers()?
|
||||
.into_iter()
|
||||
.find(|driver| {
|
||||
driver.id == profile
|
||||
&& driver.vendor.as_deref() == Some("duckdb")
|
||||
&& driver.class_name == "org.duckdb.DuckDBDriver"
|
||||
})
|
||||
.ok_or_else(|| IdeError::invalid("Choose an installed DuckDB JDBC driver for the workspace"))?;
|
||||
let source = DataSource { url: "jdbc:duckdb:".into(), ..Default::default() };
|
||||
JdbcPool::connect(&source, None, driver, self.jdbc_registry()?.with_file_name("jdbc")).await
|
||||
}
|
||||
|
||||
pub(crate) async fn prepare_workspace_duckdb_source(
|
||||
&self,
|
||||
source: &DataSource,
|
||||
) -> IdeResult<WorkspaceDuckDbSource> {
|
||||
let driver = self.approved_jdbc_driver(source, false)?;
|
||||
if driver.vendor.as_deref() != Some("duckdb") || driver.class_name != "org.duckdb.DuckDBDriver" {
|
||||
return Err(IdeError::invalid("Choose a saved DuckDB source with an installed DuckDB driver"));
|
||||
}
|
||||
let target = source.url.strip_prefix("jdbc:duckdb:").unwrap_or_default();
|
||||
let mut parts = target.split(';');
|
||||
let filename = parts.next().unwrap_or_default();
|
||||
let cache = self.jdbc_registry()?.with_file_name("jdbc");
|
||||
let path = cache.join("files").join(filename);
|
||||
if filename.is_empty()
|
||||
|| filename.starts_with([':', ' '])
|
||||
|| filename.starts_with("memory:")
|
||||
|| filename.starts_with("md:")
|
||||
|| filename.contains("://")
|
||||
|| !tokio::fs::metadata(path).await.is_ok_and(|m| m.is_file())
|
||||
{
|
||||
return Err(IdeError::invalid("Choose an existing local DuckDB database file as the workspace source"));
|
||||
}
|
||||
let limits = [
|
||||
("enable_external_access", "false"),
|
||||
("allow_unsigned_extensions", "false"),
|
||||
("autoinstall_known_extensions", "false"),
|
||||
("autoload_known_extensions", "false"),
|
||||
("memory_limit", "96MiB"),
|
||||
("threads", "1"),
|
||||
("temp_directory", ""),
|
||||
("max_temp_directory_size", "0B"),
|
||||
];
|
||||
let protected = |name: &str| limits.iter().any(|(key, _)| name.trim().eq_ignore_ascii_case(key));
|
||||
if parts.any(|option| protected(option.split('=').next().unwrap_or_default())) {
|
||||
return Err(IdeError::invalid("DuckDB Workspace source URL changes a workspace read limit"));
|
||||
}
|
||||
let mut target = source.clone();
|
||||
target.read_only = true;
|
||||
target.properties.retain(|property| !protected(&property.name));
|
||||
target
|
||||
.properties
|
||||
.extend(limits.map(|(name, value)| crate::DbProperty { name: name.into(), value: value.into() }));
|
||||
Ok(WorkspaceDuckDbSource { target, driver, cache })
|
||||
}
|
||||
|
||||
pub(crate) async fn open_pool(
|
||||
@@ -174,200 +271,111 @@ impl DbManager {
|
||||
password: Option<&str>,
|
||||
testing: bool,
|
||||
) -> IdeResult<crate::Pool> {
|
||||
if let Some(lake) = &source.duck_lake {
|
||||
return self.open_ducklake(source, lake, testing).await;
|
||||
}
|
||||
if source.driver != crate::DbDriver::Jdbc {
|
||||
return crate::Pool::connect(source, password, Some(&self.root)).await;
|
||||
}
|
||||
if source.plugin_owner.is_some() {
|
||||
return Err(IdeError::invalid("Plugins cannot start custom JDBC drivers"));
|
||||
}
|
||||
if !testing && !source.global {
|
||||
let (path, expected) = self.jdbc_approval(source)?;
|
||||
if std::fs::read_to_string(path).ok().as_deref() != Some(&expected) {
|
||||
return Err(IdeError::invalid(
|
||||
"Review this project's JDBC URL and properties, then save the data source before connecting",
|
||||
));
|
||||
}
|
||||
}
|
||||
let driver = self
|
||||
.jdbc_drivers()?
|
||||
.into_iter()
|
||||
.find(|d| d.id == source.jdbc_driver)
|
||||
.ok_or_else(|| IdeError::invalid("Select an installed JDBC driver profile"))?;
|
||||
if !source.vendor.is_empty() && driver.vendor.as_deref() != Some(source.vendor.as_str()) {
|
||||
return Err(IdeError::invalid("The JDBC driver profile is not associated with this data source type"));
|
||||
}
|
||||
let driver = self.approved_jdbc_driver(source, testing)?;
|
||||
JdbcPool::connect(source, password, driver, self.jdbc_registry()?.with_file_name("jdbc"))
|
||||
.await
|
||||
.map(Box::new)
|
||||
.map(crate::Pool::Jdbc)
|
||||
}
|
||||
|
||||
fn approved_jdbc_driver(&self, source: &DataSource, testing: bool) -> IdeResult<DbJdbcDriver> {
|
||||
if source.plugin_owner.is_some() {
|
||||
return Err(IdeError::invalid("Plugins cannot start custom JDBC drivers"));
|
||||
}
|
||||
self.check_jdbc_project_approval(source, testing)?;
|
||||
let driver = self.jdbc_driver_by_id(&source.jdbc_driver)?;
|
||||
if !source.vendor.is_empty() {
|
||||
driver.require_vendor(&source.vendor)?;
|
||||
}
|
||||
Ok(driver)
|
||||
}
|
||||
}
|
||||
|
||||
struct Bridge {
|
||||
stop: tokio::sync::oneshot::Sender<()>,
|
||||
exited: tokio::task::JoinHandle<()>,
|
||||
sequence: u64,
|
||||
input: ChildStdin,
|
||||
output: ChildStdout,
|
||||
pub(crate) struct WorkspaceDuckDbSource {
|
||||
target: DataSource,
|
||||
driver: DbJdbcDriver,
|
||||
cache: PathBuf,
|
||||
}
|
||||
|
||||
impl WorkspaceDuckDbSource {
|
||||
pub(crate) async fn connect(self, password: Option<&str>) -> IdeResult<JdbcPool> {
|
||||
JdbcPool::connect(&self.target, password, self.driver, self.cache).await
|
||||
}
|
||||
}
|
||||
|
||||
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,
|
||||
@@ -375,10 +383,12 @@ impl JdbcPool {
|
||||
driver: DbJdbcDriver,
|
||||
cache: PathBuf,
|
||||
) -> IdeResult<Self> {
|
||||
driver.validate()?;
|
||||
if source.duck_lake.is_some() {
|
||||
return Err(IdeError::invalid("DuckLake catalogs require a DuckLake connection"));
|
||||
}
|
||||
let mut fields = vec![
|
||||
"open".to_string(),
|
||||
driver.class_name,
|
||||
driver.class_name.clone(),
|
||||
source.url.clone(),
|
||||
source.user.clone(),
|
||||
password.unwrap_or_default().to_owned(),
|
||||
@@ -390,35 +400,93 @@ impl JdbcPool {
|
||||
}
|
||||
fields.extend([p.name.clone(), p.value.clone()]);
|
||||
}
|
||||
Self::open(driver, cache, fields).await
|
||||
}
|
||||
|
||||
async fn open(driver: DbJdbcDriver, cache: PathBuf, fields: Vec<String>) -> IdeResult<Self> {
|
||||
driver.validate()?;
|
||||
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(&fields[2]),
|
||||
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 +507,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 +539,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 +746,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 +755,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 +773,134 @@ 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 mut schemas = pool.metadata(&["schemas", archive]).await?;
|
||||
// DuckDB JDBC 1.1.3 also lists these system schemas for attached catalogs.
|
||||
schemas.retain(|row| !matches!(row[0].as_deref(), Some("information_schema" | "pg_catalog")));
|
||||
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]
|
||||
|
||||
+520
-106
@@ -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};
|
||||
@@ -24,14 +25,17 @@ pub mod sql;
|
||||
pub mod tools;
|
||||
mod watch;
|
||||
pub use watch::SourcesWatch;
|
||||
pub mod workspace;
|
||||
pub mod workspace_input;
|
||||
|
||||
pub use catalog::{CatalogDatabase, CatalogSchema, SourceCatalog};
|
||||
pub use conn::{Held, Pool, QueryResult, ResultColumn, TruncatedCell};
|
||||
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,
|
||||
DataSource, DbColor, DbDriver, DbDuckLake, DbDuckLakeKind, DbExternalTunnel, DbIntrospection, DbOptions,
|
||||
DbProperty, DbSchemaSelection, DbSnowflake, DbSnowflakeAuth, DbSourceFolder, DbSsh, DbSshAuth, DbSslMode, DbTxMode,
|
||||
DbVisibilityChange,
|
||||
};
|
||||
pub use sql::{CellValue, DbRowEdit, SortKey};
|
||||
|
||||
@@ -42,7 +46,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 +150,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)]
|
||||
@@ -157,6 +165,10 @@ pub struct ColumnInfo {
|
||||
pub nullable: bool,
|
||||
pub default: Option<String>,
|
||||
pub primary_key: bool,
|
||||
/// `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)]
|
||||
@@ -166,16 +178,91 @@ 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>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
/// 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, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[serde(rename = "DbTableDetails")]
|
||||
pub struct TableDetails {
|
||||
/// The table's comment; `None` when it has none, or the engine keeps no comments.
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub comment: Option<String>,
|
||||
pub columns: Vec<ColumnInfo>,
|
||||
pub indexes: Vec<IndexInfo>,
|
||||
pub foreign_keys: Vec<ForeignKey>,
|
||||
pub triggers: Vec<TriggerInfo>,
|
||||
/// The role owning the table (PostgreSQL); `None` where the schema owns its tables.
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub owner: Option<String>,
|
||||
/// The table's tablespace, the database's default one when it names none (PostgreSQL).
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub tablespace: Option<String>,
|
||||
/// The table access method (PostgreSQL's `heap`, …); `None` for a partitioned table, and on
|
||||
/// the engines without one.
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub access_method: Option<String>,
|
||||
/// The storage parameters set on the table, as `(name, value)`: PostgreSQL's reloptions,
|
||||
/// its TOAST table's prefixed `toast.`. `None` on the engines without any.
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub storage_options: Option<Vec<(String, String)>>,
|
||||
/// The partition key (`RANGE (created)`); `None` when the table isn't partitioned.
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub partitioning: Option<String>,
|
||||
/// Whether the table is logged, unlogged or temporary (PostgreSQL).
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub persistence: Option<DbPersistence>,
|
||||
}
|
||||
|
||||
/// Whether a table's changes are written to the write-ahead log, and whether it outlives the session.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum DbPersistence {
|
||||
Permanent,
|
||||
Unlogged,
|
||||
Temporary,
|
||||
}
|
||||
|
||||
impl DbPersistence {
|
||||
/// PostgreSQL's `pg_class.relpersistence`.
|
||||
fn from_catalog(v: &str) -> Option<Self> {
|
||||
match v {
|
||||
"p" => Some(Self::Permanent),
|
||||
"u" => Some(Self::Unlogged),
|
||||
"t" => Some(Self::Temporary),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One object privilege on a table: `grantee` may run `privilege` (`SELECT`, …), granted
|
||||
@@ -200,6 +287,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)]
|
||||
@@ -289,12 +380,39 @@ pub struct DbManager {
|
||||
sessions: Mutex<HashMap<String, Session>>,
|
||||
/// Result pages read on from where the previous page stopped, not by running the statement again.
|
||||
cursors: conn::Cursors,
|
||||
workspace_run: tokio::sync::Mutex<()>,
|
||||
/// The data sources as last read from disk, for [`DbManager::reconcile_sources`]
|
||||
/// (`None` until [`DbManager::watch_sources`]).
|
||||
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.
|
||||
@@ -312,6 +430,25 @@ async fn catalog_rows(pool: &Pool, q: &str) -> IdeResult<Vec<Vec<Option<String>>
|
||||
}
|
||||
}
|
||||
|
||||
/// One [`sql::table_properties`] row into `details`.
|
||||
fn read_table_properties(details: &mut TableDetails, row: Vec<Option<String>>) {
|
||||
let mut it = row.into_iter().map(|v| v.filter(|v| !v.is_empty()));
|
||||
let mut next = || it.next().flatten();
|
||||
details.owner = next();
|
||||
details.tablespace = next();
|
||||
details.access_method = next();
|
||||
details.storage_options = Some(
|
||||
next()
|
||||
.unwrap_or_default()
|
||||
.lines()
|
||||
.filter_map(|o| o.split_once('='))
|
||||
.map(|(name, value)| (name.to_owned(), value.to_owned()))
|
||||
.collect(),
|
||||
);
|
||||
details.partitioning = next();
|
||||
details.persistence = next().as_deref().and_then(DbPersistence::from_catalog);
|
||||
}
|
||||
|
||||
fn flag(v: &Option<String>) -> bool {
|
||||
matches!(v.as_deref(), Some("1" | "t" | "true" | "YES"))
|
||||
}
|
||||
@@ -368,6 +505,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)),
|
||||
@@ -376,6 +548,13 @@ pub fn split_target(target: &str) -> (&str, Option<&str>) {
|
||||
}
|
||||
}
|
||||
|
||||
fn reject_duck_lake_password(password: Option<&str>) -> IdeResult<()> {
|
||||
if password.is_some_and(|p| !p.is_empty()) {
|
||||
return Err(IdeError::invalid("DuckLake uses a catalog file or named secret without a JDBC or SSH password"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Says which leg failed when the database is unreachable from the SSH host.
|
||||
fn through_tunnel(e: IdeError, source: &DataSource, via: Option<&str>) -> IdeError {
|
||||
let Some(via) = via.filter(|_| e.kind == ErrorKind::Io) else { return e };
|
||||
@@ -406,12 +585,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 {
|
||||
@@ -451,6 +625,7 @@ impl DbManager {
|
||||
on_disk: Mutex::default(),
|
||||
sessions: Mutex::default(),
|
||||
cursors: conn::Cursors::default(),
|
||||
workspace_run: tokio::sync::Mutex::new(()),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -534,13 +709,16 @@ impl DbManager {
|
||||
/// Saves the data source list, preserving connections when only visibility rules change.
|
||||
/// Global ones (`global`) go to the app-wide list, the others to the project's.
|
||||
pub async fn save_sources(&self, mut sources: Vec<DataSource>) -> IdeResult<()> {
|
||||
for source in &sources {
|
||||
source.validate_duck_lake()?;
|
||||
}
|
||||
if sources.iter().any(|s| s.global && s.plugin_owner.is_some()) {
|
||||
return Err(IdeError::invalid("plugin-owned data sources must stay project-scoped"));
|
||||
}
|
||||
let old = {
|
||||
let _guard = plugin::EDIT.lock();
|
||||
let old = self.sources().unwrap_or_default();
|
||||
for source in sources.iter_mut().filter(|s| s.driver == DbDriver::Jdbc) {
|
||||
for source in sources.iter_mut().filter(|s| s.driver == DbDriver::Jdbc && s.duck_lake.is_none()) {
|
||||
// Retain the credential scope even when URL-only settings supplied the old authenticator.
|
||||
if let Some(settings) = old.iter().find(|s| s.id == source.id).and_then(Self::non_password_snowflake) {
|
||||
source.snowflake = Some(settings);
|
||||
@@ -560,6 +738,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 {
|
||||
@@ -577,7 +767,7 @@ impl DbManager {
|
||||
}
|
||||
}
|
||||
// Made global or project-level: its saved passwords move along.
|
||||
Some(n) if n.global != o.global => {
|
||||
Some(n) if n.global != o.global && n.duck_lake.is_none() && o.duck_lake.is_none() => {
|
||||
for k in &keys {
|
||||
if let Some(p) = self.store_of(&o).get(k) {
|
||||
self.store_of(n).set(k, &p)?;
|
||||
@@ -659,6 +849,9 @@ impl DbManager {
|
||||
/// the data source saves passwords (`None` forgets it).
|
||||
pub async fn set_password(&self, id: &str, password: Option<String>, save: bool) -> IdeResult<()> {
|
||||
let source = self.sources()?.into_iter().find(|s| s.id == id);
|
||||
if source.as_ref().is_some_and(|s| s.duck_lake.is_some()) {
|
||||
return reject_duck_lake_password(password.as_deref());
|
||||
}
|
||||
let (store, key) = match source.as_ref() {
|
||||
Some(source) => (self.store_of(source), self.password_key(source)),
|
||||
None => (&self.saved_passwords, id.to_owned()),
|
||||
@@ -669,7 +862,11 @@ impl DbManager {
|
||||
/// [`DbManager::set_password`] for the SSH password / key passphrase.
|
||||
/// A data source using an SSH configuration sets that configuration's secret.
|
||||
pub async fn set_ssh_secret(&self, id: &str, secret: Option<String>, save: bool) -> IdeResult<()> {
|
||||
let config = self.sources()?.into_iter().find(|s| s.id == id).and_then(|s| s.ssh).map(|s| s.config);
|
||||
let source = self.sources()?.into_iter().find(|s| s.id == id);
|
||||
if source.as_ref().is_some_and(|s| s.duck_lake.is_some()) {
|
||||
return reject_duck_lake_password(secret.as_deref());
|
||||
}
|
||||
let config = source.and_then(|s| s.ssh).map(|s| s.config);
|
||||
if let Some(c) = config.filter(|c| !c.trim().is_empty()) {
|
||||
let save = self.ssh.config(&c).map(|c| c.save_secret).unwrap_or(save);
|
||||
return self.ssh.set_secret(&c, secret, save);
|
||||
@@ -714,6 +911,9 @@ impl DbManager {
|
||||
}
|
||||
|
||||
async fn password(&self, source: &DataSource) -> Option<String> {
|
||||
if source.duck_lake.is_some() {
|
||||
return None;
|
||||
}
|
||||
match self
|
||||
.secret(source, self.password_key(source), source.driver != DbDriver::Sqlite && source.save_password)
|
||||
.await
|
||||
@@ -822,6 +1022,10 @@ impl DbManager {
|
||||
purpose: route::RouteUse,
|
||||
) -> IdeResult<String> {
|
||||
let source = &source.resolved()?;
|
||||
if source.duck_lake.is_some() {
|
||||
reject_duck_lake_password(password.as_deref())?;
|
||||
reject_duck_lake_password(ssh_secret.as_deref())?;
|
||||
}
|
||||
let password = match password {
|
||||
Some(p) => Some(p),
|
||||
None => self.password(source).await,
|
||||
@@ -950,12 +1154,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());
|
||||
@@ -994,12 +1216,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")),
|
||||
};
|
||||
@@ -1095,19 +1318,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
|
||||
@@ -1119,11 +1377,12 @@ impl DbManager {
|
||||
let nullable = flag(&it.next().flatten());
|
||||
let default = it.next().flatten();
|
||||
let primary_key = flag(&it.next().flatten());
|
||||
Some(ColumnInfo { name, data_type, nullable, default, primary_key })
|
||||
let comment = it.next().flatten().filter(|c| !c.is_empty());
|
||||
Some(ColumnInfo { name, data_type, nullable, default, primary_key, comment })
|
||||
})
|
||||
.collect();
|
||||
if driver == DbDriver::Jdbc {
|
||||
return Ok(TableDetails { columns, indexes: vec![], foreign_keys: vec![], triggers: vec![] });
|
||||
return Ok(TableDetails { columns, ..Default::default() });
|
||||
}
|
||||
let mut indexes: Vec<IndexInfo> = Vec::new();
|
||||
for r in pool.rows(&sql::indexes(driver, schema, table), MAX_META_ROWS).await? {
|
||||
@@ -1134,7 +1393,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) {
|
||||
@@ -1175,7 +1439,28 @@ impl DbManager {
|
||||
Some(TriggerInfo { name, timing, events })
|
||||
})
|
||||
.collect();
|
||||
Ok(TableDetails { columns, indexes, foreign_keys, triggers })
|
||||
let comment = match sql::table_comment(driver, schema, table) {
|
||||
Some(q) => pool.rows(&q, 1).await.map_or_else(
|
||||
|e| {
|
||||
tracing::warn!("table comment: {}", e.message);
|
||||
None
|
||||
},
|
||||
|rows| rows.into_iter().next().and_then(|r| r.into_iter().next().flatten()).filter(|c| !c.is_empty()),
|
||||
),
|
||||
None => None,
|
||||
};
|
||||
let mut details = TableDetails { comment, columns, indexes, foreign_keys, triggers, ..Default::default() };
|
||||
if let Some(q) = sql::table_properties(driver, schema, table) {
|
||||
match catalog_rows(pool, &q).await {
|
||||
Ok(rows) => {
|
||||
if let Some(row) = rows.into_iter().next() {
|
||||
read_table_properties(&mut details, row);
|
||||
}
|
||||
}
|
||||
Err(e) => tracing::warn!("table properties: {}", e.message),
|
||||
}
|
||||
}
|
||||
Ok(details)
|
||||
}
|
||||
|
||||
/// The object privileges granted on `table`; empty, without a query, on the engines
|
||||
@@ -1385,10 +1670,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" {
|
||||
@@ -1409,6 +1697,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<_>>();
|
||||
@@ -1422,7 +1711,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))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1470,6 +1770,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;
|
||||
@@ -1511,13 +1812,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));
|
||||
}
|
||||
}
|
||||
@@ -1538,7 +1852,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),
|
||||
@@ -1560,12 +1889,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) {
|
||||
@@ -1598,9 +1949,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.
|
||||
@@ -1619,18 +1996,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,
|
||||
@@ -1639,8 +2019,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`).
|
||||
@@ -1653,13 +2034,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) {
|
||||
@@ -1667,7 +2066,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,
|
||||
@@ -1703,44 +2102,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
|
||||
@@ -1773,23 +2137,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)]
|
||||
@@ -1804,18 +2182,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())
|
||||
}
|
||||
@@ -132,6 +136,7 @@ pub(crate) async fn table_details(pool: &SnowflakePool, schema: &str, table: &st
|
||||
nullable: yes(r.get("null?")),
|
||||
default: r.get("default").filter(|d| !d.is_empty()).map(str::to_owned),
|
||||
primary_key: yes(r.get("primary key")),
|
||||
comment: r.get("comment").filter(|c| !c.is_empty()).map(str::to_owned),
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
@@ -140,7 +145,16 @@ pub(crate) async fn table_details(pool: &SnowflakePool, schema: &str, table: &st
|
||||
Ok(keys) => foreign_keys(&keys),
|
||||
Err(_) => Vec::new(),
|
||||
};
|
||||
Ok(TableDetails { columns, indexes: Vec::new(), foreign_keys, triggers: Vec::new() })
|
||||
// `LIKE` matches without case and with wildcards: the exact name picks the row.
|
||||
let like = format!("SHOW TABLES LIKE {} IN SCHEMA {}", quote_literal(DRIVER, table), schema_path(pool, schema));
|
||||
let comment = match show(pool, &like).await {
|
||||
Ok(shown) => shown
|
||||
.records()
|
||||
.find(|r| r.get("name") == Some(table))
|
||||
.and_then(|r| r.get("comment").filter(|c| !c.is_empty()).map(str::to_owned)),
|
||||
Err(_) => None,
|
||||
};
|
||||
Ok(TableDetails { comment, columns, foreign_keys, ..Default::default() })
|
||||
}
|
||||
|
||||
fn foreign_keys(shown: &Shown) -> Vec<ForeignKey> {
|
||||
@@ -228,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));
|
||||
@@ -437,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,18 @@
|
||||
//! 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 DUCKDB_URL: &str = "jdbc:duckdb:";
|
||||
pub(crate) const FOLDERS_FILE: &str = "data-source-folders.toml";
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
@@ -304,6 +307,25 @@ pub struct DbExternalTunnel {
|
||||
pub arguments: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum DbDuckLakeKind {
|
||||
File,
|
||||
Secret,
|
||||
}
|
||||
|
||||
/// How to open an existing DuckLake catalog read-only through DuckDB.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct DbDuckLake {
|
||||
pub kind: DbDuckLakeKind,
|
||||
/// A local catalog file or an existing DuckDB secret name.
|
||||
pub value: String,
|
||||
/// An existing local data directory overriding the catalog's data path.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub data_path: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase", default)]
|
||||
pub struct DataSource {
|
||||
@@ -344,6 +366,8 @@ pub struct DataSource {
|
||||
pub properties: Vec<DbProperty>,
|
||||
/// Snowflake settings (`None`: not a Snowflake data source, or all defaults).
|
||||
pub snowflake: Option<DbSnowflake>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub duck_lake: Option<DbDuckLake>,
|
||||
/// Stored app-wide and listed in every project. Implied by the file it is read from,
|
||||
/// so not written to it.
|
||||
pub global: bool,
|
||||
@@ -384,6 +408,7 @@ impl Default for DataSource {
|
||||
introspection: DbIntrospection::default(),
|
||||
properties: Vec::new(),
|
||||
snowflake: None,
|
||||
duck_lake: None,
|
||||
global: false,
|
||||
plugin_owner: None,
|
||||
plugin_source_id: None,
|
||||
@@ -511,7 +536,69 @@ pub fn parse_url(raw: &str) -> IdeResult<ParsedUrl> {
|
||||
Ok(parsed)
|
||||
}
|
||||
|
||||
pub(crate) fn duck_lake_path(value: &str, relative: bool) -> IdeResult<&Path> {
|
||||
let path = Path::new(value);
|
||||
if value.trim().is_empty()
|
||||
|| value.contains(['\0', '\r', '\n'])
|
||||
|| value.starts_with("//")
|
||||
|| value.starts_with('\\')
|
||||
|| (!path.is_absolute() && (!relative || value.starts_with('/') || value.contains(':')))
|
||||
{
|
||||
return Err(IdeError::invalid("Choose a local DuckLake path on the database host"));
|
||||
}
|
||||
Ok(path)
|
||||
}
|
||||
|
||||
impl DataSource {
|
||||
pub(crate) fn validate_duck_lake(&self) -> IdeResult<()> {
|
||||
let Some(lake) = &self.duck_lake else { return Ok(()) };
|
||||
if self.driver != DbDriver::Jdbc
|
||||
|| self.vendor != "duckdb"
|
||||
|| self.url != DUCKDB_URL
|
||||
|| self.url_only
|
||||
|| !self.read_only
|
||||
|| self.plugin_owner.is_some()
|
||||
{
|
||||
return Err(IdeError::invalid("Existing DuckLake catalogs require a read-only DuckDB JDBC data source"));
|
||||
}
|
||||
if !self.user.is_empty()
|
||||
|| self.save_password
|
||||
|| self.ssh.is_some()
|
||||
|| self.external_tunnel.is_some()
|
||||
|| !self.properties.is_empty()
|
||||
{
|
||||
return Err(IdeError::invalid(
|
||||
"DuckLake uses its catalog file or named secret without JDBC credentials, properties or tunnels",
|
||||
));
|
||||
}
|
||||
if self.options.transaction != DbTxMode::Auto
|
||||
|| !self.options.default_schema.is_empty()
|
||||
|| !self.options.time_zone.is_empty()
|
||||
|| !self.options.startup_script.is_empty()
|
||||
{
|
||||
return Err(IdeError::invalid("DuckLake does not use JDBC session overrides"));
|
||||
}
|
||||
match lake.kind {
|
||||
DbDuckLakeKind::File => {
|
||||
duck_lake_path(&lake.value, true)?;
|
||||
}
|
||||
DbDuckLakeKind::Secret => {
|
||||
let mut chars = lake.value.bytes();
|
||||
if !chars.next().is_some_and(|c| c.is_ascii_alphabetic() || c == b'_')
|
||||
|| !chars.all(|c| c.is_ascii_alphanumeric() || c == b'_')
|
||||
{
|
||||
return Err(IdeError::invalid(
|
||||
"Enter an existing DuckLake secret name using letters, digits or underscores",
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(path) = lake.data_path.as_deref().filter(|path| !path.is_empty()) {
|
||||
duck_lake_path(path, false)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn select_database(&mut self, database: Option<&str>) {
|
||||
if let Some(db) = database {
|
||||
// The configured schema belongs to the configured database.
|
||||
@@ -534,6 +621,7 @@ impl DataSource {
|
||||
/// database, user, SSL and driver properties come from the URL (properties
|
||||
/// of the Advanced tab still apply after the URL's).
|
||||
pub fn resolved(&self) -> IdeResult<DataSource> {
|
||||
self.validate_duck_lake()?;
|
||||
if self.driver == DbDriver::Jdbc {
|
||||
if !self.url.starts_with("jdbc:") {
|
||||
return Err(IdeError::invalid("Enter a JDBC URL starting with jdbc:"));
|
||||
@@ -697,6 +785,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 +914,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()
|
||||
}
|
||||
|
||||
+250
-41
@@ -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)
|
||||
),
|
||||
}
|
||||
@@ -145,7 +151,8 @@ const SNOWFLAKE_TYPE: &str = "CASE WHEN data_type = 'NUMBER' THEN 'NUMBER(' || n
|
||||
WHEN data_type = 'TEXT' THEN 'VARCHAR(' || character_maximum_length || ')' \
|
||||
WHEN data_type LIKE 'TIME%' THEN data_type || '(' || datetime_precision || ')' ELSE data_type END";
|
||||
|
||||
/// Rows: `name, type, nullable (YES/NO or 0/1), default, is_pk (0/1)`.
|
||||
/// Rows: `name, type, nullable (YES/NO or 0/1), default, is_pk (0/1)`, and the column's
|
||||
/// comment on the engines that keep one (PostgreSQL, MySQL, Oracle, ClickHouse).
|
||||
pub fn columns(driver: DbDriver, schema: &str, table: &str) -> String {
|
||||
let (s, t) = (quote_literal(driver, schema), quote_literal(driver, table));
|
||||
match driver {
|
||||
@@ -153,7 +160,7 @@ pub fn columns(driver: DbDriver, schema: &str, table: &str) -> String {
|
||||
DbDriver::Clickhouse => format!(
|
||||
"SELECT name, type, CASE WHEN startsWith(type, 'Nullable(') \
|
||||
OR startsWith(type, 'LowCardinality(Nullable(') THEN 'YES' ELSE 'NO' END, \
|
||||
if(default_kind = '', NULL, default_expression), is_in_primary_key \
|
||||
if(default_kind = '', NULL, default_expression), is_in_primary_key, comment \
|
||||
FROM system.columns WHERE database = {s} AND table = {t} ORDER BY position"
|
||||
),
|
||||
DbDriver::Sqlite => format!(
|
||||
@@ -166,13 +173,14 @@ pub fn columns(driver: DbDriver, schema: &str, table: &str) -> String {
|
||||
JOIN information_schema.key_column_usage k ON k.constraint_name = tc.constraint_name \
|
||||
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 \
|
||||
AND tc.table_name = c.table_name AND k.column_name = c.column_name) THEN 1 ELSE 0 END, \
|
||||
col_description(format('%I.%I', c.table_schema, c.table_name)::regclass, c.ordinal_position::int) \
|
||||
FROM information_schema.columns c WHERE c.table_schema = {s} AND c.table_name = {t} \
|
||||
ORDER BY c.ordinal_position"
|
||||
),
|
||||
DbDriver::Mysql => format!(
|
||||
"SELECT column_name, column_type, is_nullable, column_default, \
|
||||
CASE WHEN column_key = 'PRI' THEN 1 ELSE 0 END \
|
||||
CASE WHEN column_key = 'PRI' THEN 1 ELSE 0 END, column_comment \
|
||||
FROM information_schema.columns WHERE table_schema = {s} AND table_name = {t} \
|
||||
ORDER BY ordinal_position"
|
||||
),
|
||||
@@ -192,8 +200,10 @@ pub fn columns(driver: DbDriver, schema: &str, table: &str) -> String {
|
||||
),
|
||||
DbDriver::Oracle => format!(
|
||||
"SELECT c.column_name, c.data_type, DECODE(c.nullable, 'Y', 'YES', 'NO'), c.data_default, \
|
||||
CASE WHEN k.column_name IS NOT NULL THEN 1 ELSE 0 END \
|
||||
CASE WHEN k.column_name 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 (SELECT kc.column_name FROM all_constraints con \
|
||||
JOIN all_cons_columns kc ON kc.owner = con.owner AND kc.table_name = con.table_name \
|
||||
AND kc.constraint_name = con.constraint_name \
|
||||
@@ -204,7 +214,53 @@ pub fn columns(driver: DbDriver, schema: &str, table: &str) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// Rows: `index name, unique (0/1), column` (one row per indexed column, in order).
|
||||
/// One row, one column: the table's comment (`NULL` or empty for none). `None` for the
|
||||
/// engines whose comments the IDE doesn't read here (Snowflake reads it with `SHOW`).
|
||||
pub fn table_comment(driver: DbDriver, schema: &str, table: &str) -> Option<String> {
|
||||
let (s, t) = (quote_literal(driver, schema), quote_literal(driver, table));
|
||||
match driver {
|
||||
DbDriver::Postgres => Some(format!(
|
||||
"SELECT obj_description(c.oid, 'pg_class') FROM pg_class c \
|
||||
JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = {s} AND c.relname = {t}"
|
||||
)),
|
||||
// A view's `table_comment` is the word `VIEW`.
|
||||
DbDriver::Mysql => Some(format!(
|
||||
"SELECT CASE WHEN table_type = 'VIEW' THEN NULL ELSE table_comment END \
|
||||
FROM information_schema.tables WHERE table_schema = {s} AND table_name = {t}"
|
||||
)),
|
||||
DbDriver::Oracle => {
|
||||
Some(format!("SELECT comments FROM all_tab_comments WHERE owner = {s} AND table_name = {t}"))
|
||||
}
|
||||
DbDriver::Clickhouse => Some(format!("SELECT comment FROM system.tables WHERE database = {s} AND name = {t}")),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// One row: `owner, tablespace, access method, storage options (name=value per line),
|
||||
/// partition key, persistence (p/u/t)` of a table. `None` for the engines whose tables have none
|
||||
/// of these the IDE reads (all but PostgreSQL).
|
||||
pub fn table_properties(driver: DbDriver, schema: &str, table: &str) -> Option<String> {
|
||||
let (s, t) = (quote_literal(driver, schema), quote_literal(driver, table));
|
||||
match driver {
|
||||
// `reltablespace` 0 is the database's default tablespace; the TOAST table's options are
|
||||
// set as `toast.name`.
|
||||
DbDriver::Postgres => Some(format!(
|
||||
"SELECT pg_get_userbyid(c.relowner), COALESCE(ts.spcname, (SELECT dt.spcname FROM pg_database d \
|
||||
JOIN pg_tablespace dt ON dt.oid = d.dattablespace WHERE d.datname = current_database())), \
|
||||
am.amname, array_to_string(array_cat(c.reloptions, \
|
||||
(SELECT array_agg('toast.' || o) FROM unnest(tc.reloptions) o)), chr(10)), \
|
||||
pg_get_partkeydef(c.oid), c.relpersistence \
|
||||
FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace \
|
||||
LEFT JOIN pg_class tc ON tc.oid = c.reltoastrelid \
|
||||
LEFT JOIN pg_tablespace ts ON ts.oid = c.reltablespace LEFT JOIN pg_am am ON am.oid = c.relam \
|
||||
WHERE n.nspname = {s} AND c.relname = {t} AND c.relkind IN ('r', 'p')"
|
||||
)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// 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.
|
||||
@@ -219,11 +275,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 \
|
||||
@@ -231,12 +290,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 \
|
||||
@@ -244,7 +305,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"
|
||||
@@ -275,7 +338,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",
|
||||
@@ -286,7 +349,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'",
|
||||
@@ -299,7 +362,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') \
|
||||
@@ -310,7 +373,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')",
|
||||
@@ -325,7 +388,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')",
|
||||
@@ -335,7 +398,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'",
|
||||
@@ -346,8 +409,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 \
|
||||
@@ -632,21 +697,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"
|
||||
)
|
||||
@@ -669,6 +735,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));
|
||||
@@ -748,7 +835,12 @@ pub fn sqlite_trigger_event(sql: &str) -> (String, String) {
|
||||
pub fn postgres_legacy(sql: &str) -> Option<String> {
|
||||
let legacy = sql
|
||||
.replace("CASE WHEN p.prokind = 'p' THEN 'procedure' ELSE 'function' END", "'function'")
|
||||
.replace("p.prokind IN ('f', 'p')", "NOT p.proisagg AND NOT p.proiswindow");
|
||||
.replace("p.prokind IN ('f', 'p')", "NOT p.proisagg AND NOT p.proiswindow")
|
||||
// Table access methods (PostgreSQL 12) and partitioned tables (10).
|
||||
.replace(" LEFT JOIN pg_am am ON am.oid = c.relam", "")
|
||||
.replace("am.amname", "NULL")
|
||||
.replace("pg_get_partkeydef(c.oid)", "NULL")
|
||||
.replace("c.relkind IN ('r', 'p')", "c.relkind = 'r'");
|
||||
(legacy != sql).then_some(legacy)
|
||||
}
|
||||
|
||||
@@ -908,6 +1000,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`).
|
||||
@@ -917,6 +1021,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
|
||||
@@ -933,9 +1038,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
|
||||
}
|
||||
@@ -956,6 +1083,40 @@ mod tests {
|
||||
assert_eq!(quote_literal(DbDriver::Mysql, "it's \\"), "'it''s \\\\'");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn comments_are_read_where_the_engine_keeps_them() {
|
||||
assert!(columns(DbDriver::Postgres, "public", "t").contains("col_description("));
|
||||
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"));
|
||||
assert!(table_comment(DbDriver::Oracle, "S", "T").unwrap().contains("all_tab_comments"));
|
||||
assert!(table_comment(DbDriver::Clickhouse, "db", "t").unwrap().contains("system.tables"));
|
||||
for driver in [DbDriver::Sqlite, DbDriver::SqlServer, DbDriver::Snowflake] {
|
||||
assert_eq!(table_comment(driver, "s", "t"), None);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clickhouse_escapes_backslashes_and_delimiters() {
|
||||
let driver = DbDriver::Clickhouse;
|
||||
@@ -973,6 +1134,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(')"));
|
||||
@@ -1088,6 +1250,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"));
|
||||
@@ -1164,8 +1327,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')"));
|
||||
@@ -1254,12 +1419,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!(
|
||||
@@ -1268,12 +1434,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;
|
||||
@@ -1355,5 +1562,7 @@ mod tests {
|
||||
let routines = postgres_legacy(&routines(pg, "s").unwrap()).unwrap();
|
||||
assert!(!routines.contains("prokind") && routines.contains("NOT p.proisagg"));
|
||||
assert_eq!(postgres_legacy(&indexes(pg, "s", "t")), None);
|
||||
let properties = postgres_legacy(&table_properties(pg, "s", "t").unwrap()).unwrap();
|
||||
assert!(!properties.contains("relam") && !properties.contains("partkeydef"), "{properties}");
|
||||
}
|
||||
}
|
||||
@@ -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");
|
||||
|
||||
@@ -0,0 +1,579 @@
|
||||
//! A read-only equality join of explicitly selected source tables on the project host.
|
||||
use crate::jdbc::JdbcPool;
|
||||
use crate::workspace_input::{
|
||||
self, WorkspaceInput, WorkspaceInputColumn, WorkspaceInputLimits, WorkspaceInputRequest, WorkspaceInputType,
|
||||
};
|
||||
use crate::{DbDriver, DbManager, QueryResult, sql};
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use std::io::{BufWriter, Write};
|
||||
use std::time::{Duration, Instant};
|
||||
use tempfile::{NamedTempFile, TempPath};
|
||||
|
||||
const MAX_TABLES: usize = 8;
|
||||
const MAX_RESULT_ROWS: usize = 100_000;
|
||||
const MAX_RESULT_COLUMNS: usize = 256;
|
||||
const WORKSPACE_INPUT_LIMITS: WorkspaceInputLimits =
|
||||
WorkspaceInputLimits { max_rows: 100_000, max_cell_bytes: 1_048_576, max_bytes: 16_777_216 };
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase", rename = "DbWorkspaceJoinRelation")]
|
||||
pub struct WorkspaceJoinRelation {
|
||||
pub source_id: String,
|
||||
pub database: String,
|
||||
pub schema: String,
|
||||
pub table: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase", rename = "DbWorkspaceJoinColumn")]
|
||||
pub struct WorkspaceJoinColumn {
|
||||
pub relation: u32,
|
||||
pub column: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase", rename = "DbWorkspaceJoinCondition")]
|
||||
pub struct WorkspaceJoinCondition {
|
||||
/// The right relation is the next table in the chain.
|
||||
pub left: WorkspaceJoinColumn,
|
||||
pub right_column: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase", rename = "DbWorkspaceJoinProjection")]
|
||||
pub struct WorkspaceJoinProjection {
|
||||
pub relation: u32,
|
||||
/// None expands this relation's columns in source order.
|
||||
pub column: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase", rename = "DbWorkspaceJoinPlan")]
|
||||
pub struct WorkspaceJoinPlan {
|
||||
pub tables: Vec<WorkspaceJoinRelation>,
|
||||
pub joins: Vec<WorkspaceJoinCondition>,
|
||||
/// None expands all relations in FROM/JOIN order.
|
||||
pub projection: Option<Vec<WorkspaceJoinProjection>>,
|
||||
}
|
||||
|
||||
fn validate_plan(
|
||||
table_count: usize,
|
||||
joins: &[WorkspaceJoinCondition],
|
||||
projection: Option<&[WorkspaceJoinProjection]>,
|
||||
) -> IdeResult<()> {
|
||||
if !(2..=MAX_TABLES).contains(&table_count) || joins.len() + 1 != table_count {
|
||||
return Err(IdeError::invalid("A workspace JOIN needs 2 to 8 tables and one equality per JOIN"));
|
||||
}
|
||||
let valid_column = |name: &str| !name.is_empty() && name.len() <= 255 && !name.contains('\0');
|
||||
for (index, link) in joins.iter().enumerate() {
|
||||
if link.left.relation as usize > index || !valid_column(&link.left.column) || !valid_column(&link.right_column)
|
||||
{
|
||||
return Err(IdeError::invalid("Each JOIN must compare a column of its new table with an earlier table"));
|
||||
}
|
||||
}
|
||||
if let Some(projection) = projection
|
||||
&& (projection.is_empty()
|
||||
|| projection.len() > MAX_RESULT_COLUMNS
|
||||
|| projection.iter().any(|item| {
|
||||
item.relation as usize >= table_count || item.column.as_deref().is_some_and(|name| !valid_column(name))
|
||||
}))
|
||||
{
|
||||
return Err(IdeError::invalid("Invalid workspace SELECT columns"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
struct StagedTable {
|
||||
path: TempPath,
|
||||
longest_row: usize,
|
||||
columns: Vec<WorkspaceInputColumn>,
|
||||
}
|
||||
|
||||
impl WorkspaceInputType {
|
||||
fn is_integer(self) -> bool {
|
||||
use WorkspaceInputType::*;
|
||||
matches!(self, Int8 | Int16 | Int32 | Int64 | UInt8 | UInt16 | UInt32 | UInt64)
|
||||
}
|
||||
|
||||
fn duckdb_type(self) -> String {
|
||||
use WorkspaceInputType::*;
|
||||
match self {
|
||||
Boolean => "BOOLEAN",
|
||||
Int8 => "TINYINT",
|
||||
Int16 => "SMALLINT",
|
||||
Int32 => "INTEGER",
|
||||
Int64 => "BIGINT",
|
||||
UInt8 => "UTINYINT",
|
||||
UInt16 => "USMALLINT",
|
||||
UInt32 => "UINTEGER",
|
||||
UInt64 => "UBIGINT",
|
||||
Float32 => "FLOAT",
|
||||
Float64 => "DOUBLE",
|
||||
Decimal { precision, scale } => return format!("DECIMAL({precision},{scale})"),
|
||||
Text => "VARCHAR",
|
||||
Date => "DATE",
|
||||
Time => "TIME",
|
||||
Timestamp => "TIMESTAMP",
|
||||
TimestampTz => "TIMESTAMPTZ",
|
||||
Uuid => "UUID",
|
||||
}
|
||||
.into()
|
||||
}
|
||||
}
|
||||
|
||||
fn stage(input: WorkspaceInput, cancel: &CancellationToken) -> IdeResult<StagedTable> {
|
||||
let mut file = NamedTempFile::new()?;
|
||||
let mut longest_row = 1;
|
||||
{
|
||||
let mut out = BufWriter::new(file.as_file_mut());
|
||||
for row in input.rows {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
if row.len() != input.columns.len() {
|
||||
return Err(IdeError::invalid("Incomplete workspace input row"));
|
||||
}
|
||||
let mut bytes = row.len(); // separators and newline
|
||||
for (column, cell) in row.into_iter().enumerate() {
|
||||
if column > 0 {
|
||||
out.write_all(b",")?;
|
||||
}
|
||||
bytes += 2; // quotes or the NULL marker
|
||||
if let Some(value) = cell {
|
||||
bytes += value.len();
|
||||
out.write_all(b"\"")?;
|
||||
let mut pieces = value.split('"');
|
||||
out.write_all(pieces.next().unwrap_or_default().as_bytes())?;
|
||||
for piece in pieces {
|
||||
bytes += 1;
|
||||
out.write_all(b"\"\"")?;
|
||||
out.write_all(piece.as_bytes())?;
|
||||
}
|
||||
out.write_all(b"\"")?;
|
||||
} else {
|
||||
out.write_all(br"\N")?;
|
||||
}
|
||||
}
|
||||
longest_row = longest_row.max(bytes);
|
||||
out.write_all(b"\n")?;
|
||||
}
|
||||
out.flush()?;
|
||||
}
|
||||
Ok(StagedTable { path: file.into_temp_path(), longest_row, columns: input.columns })
|
||||
}
|
||||
|
||||
impl StagedTable {
|
||||
fn quoted_path(&self) -> IdeResult<String> {
|
||||
self.path
|
||||
.to_str()
|
||||
.map(|p| sql::quote_literal(DbDriver::Jdbc, p))
|
||||
.ok_or_else(|| IdeError::invalid("The workspace temporary directory needs a UTF-8 path"))
|
||||
}
|
||||
|
||||
fn scan(&self, path: &str) -> String {
|
||||
// Synthetic column names also preserve case-distinct names from the source.
|
||||
let columns = self
|
||||
.columns
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, c)| format!("'c{i}':'{}'", c.data_type.duckdb_type()))
|
||||
.collect::<Vec<_>>()
|
||||
.join(",");
|
||||
let line = self.longest_row;
|
||||
// The single-threaded reader only needs one complete CSV record per buffer.
|
||||
let buffer = line.max(64 * 1024);
|
||||
format!(
|
||||
r#"read_csv({path},columns={{{columns}}},auto_detect=false,header=false,delim=',',quote='"',escape='"',nullstr='\N',allow_quoted_nulls=false,parallel=false,max_line_size={line},buffer_size={buffer})"#
|
||||
)
|
||||
}
|
||||
|
||||
fn column(&self, name: &str) -> IdeResult<usize> {
|
||||
self.columns
|
||||
.iter()
|
||||
.position(|c| c.name == name)
|
||||
.ok_or_else(|| IdeError::invalid(format!("Unknown workspace column: {name}")))
|
||||
}
|
||||
}
|
||||
|
||||
fn staging_columns<'a>(
|
||||
table_count: usize,
|
||||
joins: &'a [WorkspaceJoinCondition],
|
||||
projection: Option<&'a [WorkspaceJoinProjection]>,
|
||||
) -> Vec<Option<Vec<&'a str>>> {
|
||||
let Some(projection) = projection else {
|
||||
return vec![None; table_count];
|
||||
};
|
||||
let mut columns: Vec<Option<Vec<&str>>> = vec![Some(Vec::new()); table_count];
|
||||
for item in projection {
|
||||
let selected = &mut columns[item.relation as usize];
|
||||
match (&item.column, selected) {
|
||||
(Some(name), Some(selected)) => selected.push(name),
|
||||
(None, selected) => *selected = None,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
for (index, link) in joins.iter().enumerate() {
|
||||
if let Some(selected) = &mut columns[link.left.relation as usize] {
|
||||
selected.push(&link.left.column);
|
||||
}
|
||||
if let Some(selected) = &mut columns[index + 1] {
|
||||
selected.push(&link.right_column);
|
||||
}
|
||||
}
|
||||
for selected in columns.iter_mut().flatten() {
|
||||
selected.sort_unstable();
|
||||
selected.dedup();
|
||||
}
|
||||
columns
|
||||
}
|
||||
|
||||
fn result_projection(
|
||||
tables: &[StagedTable],
|
||||
selection: Option<&[WorkspaceJoinProjection]>,
|
||||
) -> IdeResult<Vec<(usize, usize)>> {
|
||||
let mut fields = Vec::new();
|
||||
match selection {
|
||||
Some(selection) => {
|
||||
for item in selection {
|
||||
let relation = item.relation as usize;
|
||||
let table = &tables[relation];
|
||||
match &item.column {
|
||||
Some(name) => fields.push((relation, table.column(name)?)),
|
||||
None => fields.extend((0..table.columns.len()).map(|column| (relation, column))),
|
||||
}
|
||||
}
|
||||
}
|
||||
None => {
|
||||
for (relation, table) in tables.iter().enumerate() {
|
||||
fields.extend((0..table.columns.len()).map(|column| (relation, column)));
|
||||
}
|
||||
}
|
||||
}
|
||||
if fields.len() > MAX_RESULT_COLUMNS {
|
||||
return Err(IdeError::invalid("Workspace result exceeds 256 columns"));
|
||||
}
|
||||
Ok(fields)
|
||||
}
|
||||
|
||||
async fn join(
|
||||
engine: &JdbcPool,
|
||||
tables: &[StagedTable],
|
||||
joins: &[WorkspaceJoinCondition],
|
||||
selection: Option<&[WorkspaceJoinProjection]>,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<QueryResult> {
|
||||
use std::fmt::Write as _;
|
||||
let fields = result_projection(tables, selection)?;
|
||||
let names = fields.iter().map(|(relation, column)| format!("r{relation}.c{column}")).collect::<Vec<_>>().join(", ");
|
||||
let paths = tables.iter().map(StagedTable::quoted_path).collect::<IdeResult<Vec<_>>>()?;
|
||||
let mut query = format!("SELECT {names} FROM {} r0", tables[0].scan(&paths[0]));
|
||||
for (index, condition) in joins.iter().enumerate() {
|
||||
let left_relation = condition.left.relation as usize;
|
||||
let right_relation = index + 1;
|
||||
let left = &tables[left_relation];
|
||||
let right = &tables[right_relation];
|
||||
let li = left.column(&condition.left.column)?;
|
||||
let ri = right.column(&condition.right_column)?;
|
||||
let (a, b) = (left.columns[li].data_type, right.columns[ri].data_type);
|
||||
// DuckDB compares mixed integer widths and signs exactly, up to BIGINT against UBIGINT.
|
||||
if a != b && !(a.is_integer() && b.is_integer()) {
|
||||
return Err(IdeError::invalid("Choose integer join columns or columns of the same type and precision"));
|
||||
}
|
||||
write!(
|
||||
query,
|
||||
" INNER JOIN {} r{right_relation} ON r{left_relation}.c{li}=r{right_relation}.c{ri}",
|
||||
right.scan(&paths[right_relation]),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
write!(query, " LIMIT {}", MAX_RESULT_ROWS + 1).unwrap();
|
||||
for setting in [
|
||||
"SET threads=1",
|
||||
"SET memory_limit='96MiB'",
|
||||
"SET temp_directory=''",
|
||||
"SET max_temp_directory_size='0B'",
|
||||
&format!("SET allowed_paths=[{}]", paths.join(",")),
|
||||
"SET enable_external_access=false",
|
||||
"SET lock_configuration=true",
|
||||
] {
|
||||
engine.query(setting, 0, 0, cancel).await?;
|
||||
}
|
||||
let mut result = engine.query(&query, 0, MAX_RESULT_ROWS, cancel).await?;
|
||||
if result.has_more {
|
||||
return Err(IdeError::invalid("Workspace result exceeds 100,000 rows"));
|
||||
}
|
||||
if result.columns.len() != fields.len() {
|
||||
return Err(IdeError::invalid("Unexpected workspace result columns"));
|
||||
}
|
||||
for (display, (relation, column)) in result.columns.iter_mut().zip(fields) {
|
||||
display.name.clone_from(&tables[relation].columns[column].name);
|
||||
}
|
||||
result.statement.clear();
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn two_table_join(keys: [&str; 2]) -> WorkspaceJoinCondition {
|
||||
WorkspaceJoinCondition {
|
||||
left: WorkspaceJoinColumn { relation: 0, column: keys[0].into() },
|
||||
right_column: keys[1].into(),
|
||||
}
|
||||
}
|
||||
|
||||
impl DbManager {
|
||||
#[cfg(test)]
|
||||
pub(crate) async fn workspace_join_pair_for_test(
|
||||
&self,
|
||||
driver: &str,
|
||||
tables: [&WorkspaceInputRequest; 2],
|
||||
keys: [&str; 2],
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<QueryResult> {
|
||||
let joins = [two_table_join(keys)];
|
||||
validate_plan(tables.len(), &joins, None)?;
|
||||
self.execute_workspace_join(driver, &tables, &joins, None, cancel).await
|
||||
}
|
||||
|
||||
/// The caller retains the bounded result for paging. Reading another page never reruns the sources.
|
||||
pub async fn workspace_join(
|
||||
&self,
|
||||
driver: &str,
|
||||
plan: WorkspaceJoinPlan,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<QueryResult> {
|
||||
validate_plan(plan.tables.len(), &plan.joins, plan.projection.as_deref())?;
|
||||
let tables: Vec<_> = plan
|
||||
.tables
|
||||
.into_iter()
|
||||
.map(|table| WorkspaceInputRequest {
|
||||
source_id: table.source_id,
|
||||
database: table.database,
|
||||
schema: table.schema,
|
||||
table: table.table,
|
||||
limits: WORKSPACE_INPUT_LIMITS,
|
||||
})
|
||||
.collect();
|
||||
let tables: Vec<_> = tables.iter().collect();
|
||||
self.execute_workspace_join(driver, &tables, &plan.joins, plan.projection.as_deref(), cancel).await
|
||||
}
|
||||
|
||||
async fn execute_workspace_join(
|
||||
&self,
|
||||
driver: &str,
|
||||
tables: &[&WorkspaceInputRequest],
|
||||
joins: &[WorkspaceJoinCondition],
|
||||
projection: Option<&[WorkspaceJoinProjection]>,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<QueryResult> {
|
||||
let _run =
|
||||
self.workspace_run.try_lock().map_err(|_| IdeError::invalid("A workspace query is already running"))?;
|
||||
let start = Instant::now();
|
||||
let child = cancel.child_token();
|
||||
let run = async {
|
||||
let cancel = &child;
|
||||
let mut prepared = Vec::with_capacity(tables.len());
|
||||
for table in tables {
|
||||
let input = tokio::select! {
|
||||
biased;
|
||||
() = cancel.cancelled() => return Err(IdeError::cancelled()),
|
||||
input = workspace_input::prepare_table(self, table) => input?,
|
||||
};
|
||||
prepared.push(input);
|
||||
}
|
||||
let selection = staging_columns(tables.len(), joins, projection);
|
||||
let mut staged = Vec::with_capacity(tables.len());
|
||||
let engine = tokio::select! {
|
||||
biased;
|
||||
() = cancel.cancelled() => return Err(IdeError::cancelled()),
|
||||
engine = self.workspace_engine(driver) => engine?,
|
||||
};
|
||||
let result = async {
|
||||
let mut remaining_rows = 200_000;
|
||||
let mut remaining_bytes = 32 * 1024 * 1024;
|
||||
for (mut table, columns) in prepared.into_iter().zip(&selection) {
|
||||
let limits = &mut table.request.limits;
|
||||
limits.max_rows = limits.max_rows.min(remaining_rows);
|
||||
limits.max_bytes = limits.max_bytes.min(remaining_bytes);
|
||||
let input = workspace_input::read_prepared_table(self, table, columns.as_deref(), cancel).await?;
|
||||
remaining_rows -= input.rows.len();
|
||||
remaining_bytes -= input.bytes;
|
||||
let cancellation = cancel.clone();
|
||||
let table = tokio::task::spawn_blocking(move || stage(input, &cancellation))
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(e.to_string()))??;
|
||||
staged.push(table);
|
||||
}
|
||||
join(&engine, &staged, joins, projection, cancel).await
|
||||
}
|
||||
.await;
|
||||
// Windows cannot remove a staged file while the JDBC process still has it open.
|
||||
engine.close().await;
|
||||
drop(staged);
|
||||
let mut result = result?;
|
||||
result.elapsed_ms = start.elapsed().as_secs_f64() * 1000.0;
|
||||
Ok(result)
|
||||
};
|
||||
tokio::pin!(run);
|
||||
let stopped = tokio::select! {
|
||||
biased;
|
||||
() = cancel.cancelled() => IdeError::cancelled(),
|
||||
result = &mut run => return result,
|
||||
() = tokio::time::sleep(Duration::from_secs(90)) => IdeError::new(ide_core::error::ErrorKind::TimedOut, "Workspace query timed out"),
|
||||
};
|
||||
child.cancel();
|
||||
// Let the source or JDBC bridge deliver cancellation before dropping its connection.
|
||||
let _ = tokio::time::timeout(Duration::from_secs(15), run).await;
|
||||
Err(stopped)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::DbJdbcDriver;
|
||||
|
||||
fn input(values: &[(&str, Option<&str>)]) -> WorkspaceInput {
|
||||
WorkspaceInput {
|
||||
columns: vec![
|
||||
WorkspaceInputColumn {
|
||||
name: "key".into(),
|
||||
data_type: WorkspaceInputType::Decimal { precision: 32, scale: 6 },
|
||||
},
|
||||
WorkspaceInputColumn { name: "text".into(), data_type: WorkspaceInputType::Text },
|
||||
],
|
||||
rows: values.iter().map(|(k, v)| vec![Some(k.to_string()), v.map(str::to_owned)]).collect(),
|
||||
bytes: 0,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn workspace_join_chain_links_must_target_an_earlier_table() -> IdeResult<()> {
|
||||
let first = two_table_join(["key", "key"]);
|
||||
let second = two_table_join(["key", "id"]);
|
||||
let links = [first, second];
|
||||
validate_plan(3, &links, None)?;
|
||||
let over_limit: Vec<_> = (0..8).map(|_| two_table_join(["key", "key"])).collect();
|
||||
assert!(validate_plan(9, &over_limit, None).is_err());
|
||||
validate_plan(8, &over_limit[..7], None)?;
|
||||
assert!(validate_plan(4, &links, None).is_err());
|
||||
assert!(validate_plan(3, &links, Some(&[])).is_err());
|
||||
let invalid = WorkspaceJoinProjection { relation: 3, column: None };
|
||||
assert!(validate_plan(3, &links, Some(&[invalid])).is_err());
|
||||
let mut links = links;
|
||||
links[0].left.relation = 1;
|
||||
assert!(validate_plan(3, &links, None).is_err());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn staging_preserves_null_and_csv_text_and_removes_the_file_on_drop() -> IdeResult<()> {
|
||||
let cancel = CancellationToken::new();
|
||||
let table = stage(input(&[("1", None), ("2", Some("")), ("3", Some("a,\"b\"\nc"))]), &cancel)?;
|
||||
let path = table.path.to_path_buf();
|
||||
assert_eq!(std::fs::read_to_string(&path)?, "\"1\",\\N\n\"2\",\"\"\n\"3\",\"a,\"\"b\"\"\nc\"\n");
|
||||
drop(table);
|
||||
assert!(!path.exists());
|
||||
cancel.cancel();
|
||||
assert!(stage(input(&[("1", None)]), &cancel).is_err());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore = "requires DUCKDB_JDBC_JAR and Java 17+"]
|
||||
async fn workspace_engine_joins_exact_keys_nulls_and_empty_inputs() -> IdeResult<()> {
|
||||
let tmp = tempfile::tempdir()?;
|
||||
let root = tmp.path();
|
||||
let db = DbManager::new(
|
||||
root.join("project"),
|
||||
root.join("passwords"),
|
||||
root.join("history"),
|
||||
std::sync::Arc::new(ide_ssh::SshManager::new(root.join("ssh"))),
|
||||
)
|
||||
.with_global_sources(root.join("global"));
|
||||
db.save_jdbc_driver(DbJdbcDriver {
|
||||
id: "duck".into(),
|
||||
name: "DuckDB".into(),
|
||||
vendor: Some("duckdb".into()),
|
||||
jars: vec![std::env::var("DUCKDB_JDBC_JAR").expect("driver fixture")],
|
||||
class_name: "org.duckdb.DuckDBDriver".into(),
|
||||
url_template: "jdbc:duckdb:".into(),
|
||||
})?;
|
||||
let cancel = CancellationToken::new();
|
||||
let mut signed = input(&[("-1", None), ("9007199254740993", None), ("9223372036854775807", None)]);
|
||||
signed.columns[0].data_type = WorkspaceInputType::Int64;
|
||||
let mut unsigned = input(&[
|
||||
("18446744073709551615", None),
|
||||
("9007199254740992", None),
|
||||
("9007199254740993", None),
|
||||
("9223372036854775807", None),
|
||||
]);
|
||||
unsigned.columns[0].data_type = WorkspaceInputType::UInt64;
|
||||
let tables = [stage(signed, &cancel)?, stage(unsigned, &cancel)?];
|
||||
let engine = db.workspace_engine("duck").await?;
|
||||
let output = join(&engine, &tables, &[two_table_join(["key", "key"])], None, &cancel).await?;
|
||||
let mut matches: Vec<_> = output.rows.iter().map(|row| (row[0].as_deref(), row[2].as_deref())).collect();
|
||||
matches.sort_unstable();
|
||||
assert_eq!(
|
||||
matches,
|
||||
[
|
||||
(Some("9007199254740993"), Some("9007199254740993")),
|
||||
(Some("9223372036854775807"), Some("9223372036854775807")),
|
||||
]
|
||||
);
|
||||
engine.close().await;
|
||||
let wide = "a,\n\"b\"".repeat(32 * 1024);
|
||||
let left = stage(input(&[("0", None), ("1", Some(&wide)), ("2", Some("short"))]), &cancel)?;
|
||||
let right = stage(input(&[("1", Some(&wide))]), &cancel)?;
|
||||
let engine = db.workspace_engine("duck").await?;
|
||||
let output = join(&engine, &[left, right], &[two_table_join(["key", "key"])], None, &cancel).await?;
|
||||
assert_eq!(output.rows.len(), 1);
|
||||
assert_eq!(output.rows[0][1].as_deref(), Some(wide.as_str()));
|
||||
assert_eq!(output.rows[0][3].as_deref(), Some(wide.as_str()));
|
||||
engine.close().await;
|
||||
for empty in [false, true] {
|
||||
let left =
|
||||
stage(input(&[("9007199254740993.000001", None), ("9007199254740993.000002", Some(""))]), &cancel)?;
|
||||
let mut right =
|
||||
input(&[("9007199254740993.000001", Some("a,\"b\"\nc")), ("9007199254740993.000002", Some(r"\N"))]);
|
||||
if empty {
|
||||
right.rows.clear();
|
||||
}
|
||||
let engine = db.workspace_engine("duck").await?;
|
||||
let right = stage(right, &cancel)?;
|
||||
let output = join(&engine, &[left, right], &[two_table_join(["key", "key"])], None, &cancel).await?;
|
||||
assert_eq!(
|
||||
output.columns.iter().map(|c| c.name.as_str()).collect::<Vec<_>>(),
|
||||
["key", "text", "key", "text"]
|
||||
);
|
||||
let mut rows = output.rows;
|
||||
rows.sort();
|
||||
if empty {
|
||||
assert!(rows.is_empty());
|
||||
} else {
|
||||
assert_eq!(rows.len(), 2);
|
||||
assert_eq!(
|
||||
rows[0],
|
||||
[
|
||||
Some("9007199254740993.000001".into()),
|
||||
None,
|
||||
Some("9007199254740993.000001".into()),
|
||||
Some("a,\"b\"\nc".into())
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
rows[1],
|
||||
[
|
||||
Some("9007199254740993.000002".into()),
|
||||
Some("".into()),
|
||||
Some("9007199254740993.000002".into()),
|
||||
Some(r"\N".into())
|
||||
]
|
||||
);
|
||||
}
|
||||
engine.close().await;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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(())
|
||||
}
|
||||
+134
@@ -0,0 +1,134 @@
|
||||
#!/usr/bin/env bash
|
||||
# Requires Docker, curl and Cargo. To exercise the JOIN and its cancellation as well
|
||||
# as source reads, install Java 17+ and set DUCKDB_JDBC_JAR to an absolute JAR path.
|
||||
# Usage: bash crates/ide-db/tests/fixtures/workspace.sh [command args...]
|
||||
set -euo pipefail
|
||||
|
||||
cd "$(dirname "$0")/../../../.."
|
||||
fixtures=$(mktemp -d "${TMPDIR:-/tmp}/openidea-workspace.XXXXXXXX")
|
||||
pg=
|
||||
ch=
|
||||
cleanup() {
|
||||
if [[ -n "$ch" ]]; then docker stop -t 2 "$ch" >/dev/null || true; fi
|
||||
if [[ -n "$pg" ]]; then docker stop -t 2 "$pg" >/dev/null || true; fi
|
||||
rm -f "$fixtures/users.xml"
|
||||
rmdir "$fixtures"
|
||||
}
|
||||
trap cleanup EXIT
|
||||
trap 'exit 130' INT
|
||||
trap 'exit 143' TERM
|
||||
|
||||
cat > "$fixtures/users.xml" <<'XML'
|
||||
<clickhouse>
|
||||
<profiles>
|
||||
<workspace_strict>
|
||||
<readonly>1</readonly>
|
||||
<max_threads>1</max_threads>
|
||||
<max_memory_usage>134217728</max_memory_usage>
|
||||
<max_rows_to_read>100000</max_rows_to_read>
|
||||
<max_execution_time>20</max_execution_time>
|
||||
</workspace_strict>
|
||||
<workspace_break>
|
||||
<readonly>1</readonly>
|
||||
<result_overflow_mode>break</result_overflow_mode>
|
||||
</workspace_break>
|
||||
<workspace_cap>
|
||||
<readonly>1</readonly>
|
||||
<max_result_rows>2</max_result_rows>
|
||||
</workspace_cap>
|
||||
</profiles>
|
||||
<users>
|
||||
<fixture_writer>
|
||||
<no_password/>
|
||||
<networks><ip>::/0</ip></networks>
|
||||
<profile>default</profile>
|
||||
<quota>default</quota>
|
||||
</fixture_writer>
|
||||
<fixture_strict>
|
||||
<no_password/>
|
||||
<networks><ip>::/0</ip></networks>
|
||||
<profile>workspace_strict</profile>
|
||||
<quota>default</quota>
|
||||
</fixture_strict>
|
||||
<fixture_break>
|
||||
<no_password/>
|
||||
<networks><ip>::/0</ip></networks>
|
||||
<profile>workspace_break</profile>
|
||||
<quota>default</quota>
|
||||
</fixture_break>
|
||||
<fixture_cap>
|
||||
<no_password/>
|
||||
<networks><ip>::/0</ip></networks>
|
||||
<profile>workspace_cap</profile>
|
||||
<quota>default</quota>
|
||||
</fixture_cap>
|
||||
</users>
|
||||
</clickhouse>
|
||||
XML
|
||||
chmod 644 "$fixtures/users.xml"
|
||||
|
||||
pg=$(docker run --rm -d -p 127.0.0.1::5432 --cpus 1 --memory 320m \
|
||||
--tmpfs /var/lib/postgresql/data:rw,size=128m \
|
||||
-e POSTGRES_HOST_AUTH_METHOD=trust postgres:17-alpine)
|
||||
ch=$(docker run --rm -d -p 127.0.0.1::8123 --cpus 1 --memory 1536m \
|
||||
--tmpfs /var/lib/clickhouse --tmpfs /var/log/clickhouse-server \
|
||||
--mount "type=bind,source=$fixtures/users.xml,target=/etc/clickhouse-server/users.d/workspace-fixture.xml,readonly" \
|
||||
clickhouse/clickhouse-server:25.8.12.129)
|
||||
WORKSPACE_PG_PORT=$(docker port "$pg" 5432/tcp | sed 's/^127\.0\.0\.1://')
|
||||
WORKSPACE_CH_PORT=$(docker port "$ch" 8123/tcp | sed 's/^127\.0\.0\.1://')
|
||||
export WORKSPACE_PG_PORT WORKSPACE_CH_PORT
|
||||
ch_http="http://127.0.0.1:$WORKSPACE_CH_PORT"
|
||||
|
||||
ready() {
|
||||
for ((attempt = 0; attempt < 45; ++attempt)); do
|
||||
if "$@" >/dev/null 2>&1; then return 0; fi
|
||||
sleep 1
|
||||
done
|
||||
printf 'Workspace fixture did not become ready: %s\n' "$1" >&2
|
||||
return 1
|
||||
}
|
||||
ready docker exec "$pg" pg_isready -h 127.0.0.1 -U postgres
|
||||
ready curl -fsS --max-time 1 "$ch_http/ping"
|
||||
|
||||
docker exec -i "$pg" psql -h 127.0.0.1 -U postgres -Xq -v ON_ERROR_STOP=1 <<'SQL'
|
||||
CREATE TABLE "exact data" ("exact key" numeric(32,6), id bigint, ts timestamp(6) with time zone, label text);
|
||||
INSERT INTO "exact data" VALUES
|
||||
(100000000000000000001.000001, 9007199254740993, '2025-01-03 07:05:06.123456+03', E'a,b"c\nd'),
|
||||
(100000000000000000002.000001, 9007199254740994, NULL, ''),
|
||||
(NULL, 9007199254740995, NULL, NULL);
|
||||
CREATE TABLE "empty data" (LIKE "exact data");
|
||||
CREATE TABLE "unsupported data" (payload jsonb);
|
||||
CREATE VIEW "fixture view" AS SELECT * FROM "exact data";
|
||||
SQL
|
||||
|
||||
ch_sql() {
|
||||
curl -fsS --max-time 5 --user fixture_writer: --data-binary "$1" "$ch_http/"
|
||||
}
|
||||
ch_sql "CREATE TABLE default.\"exact data\" (
|
||||
\"exact key\" Nullable(Decimal(32,6)), id Int64, ts Nullable(DateTime64(6, 'Europe/Moscow')), label Nullable(String)
|
||||
) ENGINE=Memory"
|
||||
ch_sql "INSERT INTO default.\"exact data\" VALUES
|
||||
(100000000000000000001.000001, 9007199254740993, '2025-01-03 07:05:06.123456', 'a,b\"c\\nd'),
|
||||
(100000000000000000002.000001, 9007199254740994, NULL, ''),
|
||||
(NULL, 9007199254740995, NULL, NULL)"
|
||||
ch_sql 'CREATE TABLE default."empty data" AS default."exact data" ENGINE=Memory'
|
||||
ch_sql 'CREATE TABLE default."unsupported data" (payload Array(String)) ENGINE=Memory'
|
||||
ch_sql 'CREATE VIEW default."fixture view" AS SELECT * FROM default."exact data"'
|
||||
ch_sql 'CREATE TABLE default."unsigned data" (id UInt64) ENGINE=Memory'
|
||||
ch_sql 'INSERT INTO default."unsigned data" VALUES (9007199254740992), (9007199254740993), (18446744073709551615)'
|
||||
|
||||
ch_sql 'CREATE TABLE default."overflow data" (id Int64) ENGINE=Memory'
|
||||
ch_sql 'INSERT INTO default."overflow data" VALUES (1), (2), (3), (4), (5)'
|
||||
|
||||
export WORKSPACE_CH_USER=fixture_writer
|
||||
if (( $# > 0 )); then
|
||||
"$@"
|
||||
else
|
||||
test_name=workspace_input::tests::native_workspace_sources_are_exact_and_fail_on_limits
|
||||
cargo test --locked -p ide-db --lib "$test_name" -- --ignored
|
||||
WORKSPACE_CH_USER=fixture_strict cargo test --locked -p ide-db --lib "$test_name" -- --ignored
|
||||
cargo test --locked -p ide-db --lib clickhouse_workspace_refuses_truncated_reads -- --ignored
|
||||
if [[ -n "${DUCKDB_JDBC_JAR:-}" ]]; then
|
||||
WORKSPACE_CH_USER=fixture_strict cargo test --locked -p ide-db --lib workspace_join_chains_four_live_engines -- --ignored
|
||||
fi
|
||||
fi
|
||||
@@ -1,5 +1,7 @@
|
||||
use ide_core::{CancellationToken, IdeResult};
|
||||
use ide_db::{DataSource, DbDriver, DbJdbcDriver, DbManager, DbProperty, SortKey};
|
||||
use ide_db::{
|
||||
ConsoleId, DataSource, DbDriver, DbDuckLake, DbDuckLakeKind, DbJdbcDriver, DbManager, DbProperty, SortKey,
|
||||
};
|
||||
use std::{path::Path, sync::Arc};
|
||||
|
||||
fn manager(dir: &Path) -> DbManager {
|
||||
@@ -8,6 +10,158 @@ fn manager(dir: &Path) -> DbManager {
|
||||
.with_global_sources(dir.join("global"))
|
||||
}
|
||||
|
||||
fn duck_lake_source(catalog: &str) -> DataSource {
|
||||
DataSource {
|
||||
id: "lake".into(),
|
||||
name: "DuckLake".into(),
|
||||
driver: DbDriver::Jdbc,
|
||||
vendor: "duckdb".into(),
|
||||
jdbc_driver: "duck".into(),
|
||||
url: "jdbc:duckdb:".into(),
|
||||
read_only: true,
|
||||
duck_lake: Some(DbDuckLake { kind: DbDuckLakeKind::File, value: catalog.into(), data_path: None }),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn duck_lake_driver(jar: String) -> DbJdbcDriver {
|
||||
DbJdbcDriver {
|
||||
id: "duck".into(),
|
||||
name: "DuckDB".into(),
|
||||
vendor: Some("duckdb".into()),
|
||||
jars: vec![jar],
|
||||
class_name: "org.duckdb.DuckDBDriver".into(),
|
||||
url_template: "jdbc:duckdb:".into(),
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn duck_lake_settings_are_validated_and_covered_by_project_approval() -> IdeResult<()> {
|
||||
let tmp = tempfile::tempdir()?;
|
||||
let jar = tmp.path().join("fixture.jar");
|
||||
std::fs::write(&jar, [])?;
|
||||
let db = manager(tmp.path());
|
||||
let profile = duck_lake_driver(jar.display().to_string());
|
||||
let source = duck_lake_source("lake/catalog.ducklake");
|
||||
let mut other_profile = profile.clone();
|
||||
other_profile.class_name = "test.NotDuckDB".into();
|
||||
db.save_jdbc_driver(other_profile)?;
|
||||
assert!(db.approve_ducklake_source(&source).is_err());
|
||||
let directory = tmp.path().join("create");
|
||||
assert!(db.create_ducklake("duck", directory.to_str().unwrap()).await.is_err());
|
||||
assert!(!directory.exists());
|
||||
db.save_jdbc_driver(profile)?;
|
||||
assert!(db.approve_ducklake_source(&DataSource { duck_lake: None, ..source.clone() }).is_err());
|
||||
|
||||
let mut invalid_secret = source.clone();
|
||||
invalid_secret.duck_lake =
|
||||
Some(DbDuckLake { kind: DbDuckLakeKind::Secret, value: "key=value".into(), data_path: None });
|
||||
let mut data_path = source.clone();
|
||||
data_path.duck_lake.as_mut().unwrap().data_path = Some("s3://example/ducklake".into());
|
||||
let mut scripted = source.clone();
|
||||
scripted.options.startup_script = "CREATE TABLE t (n int)".into();
|
||||
for invalid in [
|
||||
invalid_secret,
|
||||
data_path,
|
||||
scripted,
|
||||
DataSource { driver: DbDriver::Sqlite, ..source.clone() },
|
||||
DataSource { url: "jdbc:duckdb:unrelated.duckdb".into(), ..source.clone() },
|
||||
DataSource { read_only: false, ..source.clone() },
|
||||
DataSource { save_password: true, ..source.clone() },
|
||||
DataSource {
|
||||
properties: vec![DbProperty { name: "access_mode".into(), value: "READ_WRITE".into() }],
|
||||
..source.clone()
|
||||
},
|
||||
] {
|
||||
assert!(invalid.resolved().is_err());
|
||||
assert!(db.save_sources(vec![invalid.clone()]).await.is_err());
|
||||
assert!(db.approve_ducklake_source(&invalid).is_err());
|
||||
}
|
||||
assert!(db.sources()?.is_empty());
|
||||
|
||||
db.approve_ducklake_source(&DataSource { global: true, ..source.clone() })?;
|
||||
db.save_sources(vec![source.clone()]).await?;
|
||||
assert_eq!(db.source("lake")?, source);
|
||||
let err = db.pool("lake").await.err().expect("global validation must not approve a project connection");
|
||||
assert!(err.message.contains("Review this project"));
|
||||
assert!(db.set_password("lake", Some("unused".into()), true).await.is_err());
|
||||
assert!(db.test(&source, Some("unused".into()), None).await.is_err());
|
||||
db.approve_ducklake_source(&source)?;
|
||||
let mut changed = source;
|
||||
changed.duck_lake.as_mut().unwrap().value = "another/catalog.ducklake".into();
|
||||
db.save_sources(vec![changed]).await?;
|
||||
let err = db.pool("lake").await.err().expect("new catalog path must be approved");
|
||||
assert!(err.message.contains("Review this project"));
|
||||
assert!(serde_json::from_value::<DbDuckLake>(serde_json::json!({"kind":"create", "value":"lake"})).is_err());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore = "requires DUCKDB_JDBC_JAR, DuckLake extension access, and Java 17+"]
|
||||
async fn duck_lake_creates_only_explicitly_and_reopens_read_only() -> IdeResult<()> {
|
||||
let tmp = tempfile::tempdir()?;
|
||||
let db = manager(tmp.path());
|
||||
let jar = std::env::var("DUCKDB_JDBC_JAR").expect("DUCKDB_JDBC_JAR");
|
||||
db.save_jdbc_driver(duck_lake_driver(jar))?;
|
||||
let source = duck_lake_source("lake's files/catalog.ducklake");
|
||||
let directory = tmp.path().join("project").join("lake's files");
|
||||
let path = directory.to_str().unwrap();
|
||||
db.save_sources(vec![source.clone()]).await?;
|
||||
let err = db.test(&source, None, None).await.expect_err("Test must not create a missing catalog");
|
||||
assert!(err.message.contains("does not exist"), "{}", err.message);
|
||||
assert!(!directory.exists());
|
||||
db.approve_ducklake_source(&source)?;
|
||||
assert!(db.pool("lake").await.is_err());
|
||||
assert!(!directory.exists());
|
||||
|
||||
db.create_ducklake("duck", path).await?;
|
||||
assert!(directory.join("catalog.ducklake").is_file());
|
||||
let err = db.create_ducklake("duck", path).await.expect_err("Create must reject an existing directory");
|
||||
assert!(err.message.contains("already exists"), "{}", err.message);
|
||||
assert!(db.test(&source, None, None).await?.contains("DuckDB"));
|
||||
|
||||
let db = manager(tmp.path());
|
||||
assert_eq!(db.source("lake")?, source);
|
||||
let cancel = CancellationToken::new();
|
||||
let console = ConsoleId::new("window", "/lake.sql");
|
||||
for scope in [None, Some(console)] {
|
||||
let result = db
|
||||
.execute_in_console(
|
||||
"lake",
|
||||
"SELECT readonly FROM duckdb_databases() WHERE database_name = current_database() AND type = 'ducklake'",
|
||||
0,
|
||||
1,
|
||||
&cancel,
|
||||
None,
|
||||
scope,
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(result.rows, [vec![Some("true".into())]]);
|
||||
assert!(
|
||||
db.execute_in_console("lake", "CREATE TABLE main.rejected(id INTEGER)", 0, 1, &cancel, None, scope)
|
||||
.await
|
||||
.is_err(),
|
||||
"the attached catalog must be read-only"
|
||||
);
|
||||
}
|
||||
assert!(db.schemas("lake").await?.contains(&"main".into()));
|
||||
assert!(db.tables("lake", "main").await?.is_empty());
|
||||
let databases = db.databases("lake").await?;
|
||||
assert_eq!(databases.current, "openidea_lake");
|
||||
assert!(databases.names.contains(&databases.current));
|
||||
let catalog = db.database_catalog("lake", &databases.current).await?;
|
||||
assert!(catalog.iter().any(|schema| schema.name == "main" && schema.tables.is_empty()));
|
||||
db.release_target_console(console, Some("lake")).await?;
|
||||
db.disconnect("lake").await;
|
||||
|
||||
let global = DataSource { id: "global-lake".into(), global: true, ..source };
|
||||
db.approve_ducklake_source(&global)?;
|
||||
db.save_sources(vec![global]).await?;
|
||||
assert!(db.schemas("global-lake").await?.contains(&"main".into()));
|
||||
db.disconnect("global-lake").await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn jdbc_profiles_persist_and_project_files_cannot_start_drivers() -> IdeResult<()> {
|
||||
let tmp = tempfile::tempdir()?;
|
||||
@@ -122,9 +276,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 +311,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 +399,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;
|
||||
@@ -239,19 +432,39 @@ async fn duckdb_named_memory_lives_until_disconnect() -> IdeResult<()> {
|
||||
vendor: "duckdb".into(),
|
||||
global: true,
|
||||
jdbc_driver: "duck".into(),
|
||||
url: "jdbc:duckdb:".into(),
|
||||
..Default::default()
|
||||
};
|
||||
let cancel = CancellationToken::new();
|
||||
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())]]);
|
||||
db.disconnect("test").await;
|
||||
assert!(!db.tables("test", "main").await?.iter().any(|table| table.name == "session_items"));
|
||||
db.disconnect("test").await;
|
||||
for url in ["jdbc:duckdb:", "jdbc:duckdb:memory:default"] {
|
||||
source.url = url.into();
|
||||
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;
|
||||
}
|
||||
|
||||
source.read_only = true;
|
||||
for url in ["jdbc:duckdb:", "jdbc:duckdb::memory:"] {
|
||||
for url in ["jdbc:duckdb:", "jdbc:duckdb::memory:", "jdbc:duckdb:memory:default"] {
|
||||
source.url = url.into();
|
||||
let err = db.test(&source, None, None).await.unwrap_err();
|
||||
assert!(err.message.contains("existing database file"), "{}", err.message);
|
||||
@@ -259,6 +472,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 +731,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<()> {
|
||||
|
||||
@@ -40,7 +40,8 @@ async fn create_schemas(db: &DbManager) {
|
||||
format!("DROP DATABASE IF EXISTS `{s}`"),
|
||||
format!("CREATE DATABASE `{s}` CHARACTER SET utf8mb4 COLLATE utf8mb4_bin"),
|
||||
format!(
|
||||
"CREATE TABLE `{s}`.`用户` (id INT PRIMARY KEY, name VARCHAR(20) COLLATE utf8mb4_bin, raw VARBINARY(4))"
|
||||
"CREATE TABLE `{s}`.`用户` (id INT PRIMARY KEY, name VARCHAR(20) COLLATE utf8mb4_bin COMMENT '名字', \
|
||||
raw VARBINARY(4)) COMMENT = '用户表'"
|
||||
),
|
||||
format!("CREATE INDEX `名字` ON `{s}`.`用户` (name)"),
|
||||
format!("INSERT INTO `{s}`.`用户` VALUES (1, 'ann', 0xCAFE)"),
|
||||
@@ -56,9 +57,13 @@ 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"]);
|
||||
assert_eq!(d.comment.as_deref(), Some("用户表"));
|
||||
let comments: Vec<_> = d.columns.iter().map(|c| c.comment.as_deref()).collect();
|
||||
assert_eq!(comments, [None, Some("名字"), None]);
|
||||
assert!(d.indexes.iter().any(|i| i.name == "名字"), "{:?}", d.indexes);
|
||||
assert!(db.ddl("m", s, "用户").await?.contains("CREATE TABLE `用户`"));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
use ide_core::{CancellationToken, IdeResult, error::ErrorKind};
|
||||
use ide_db::{ConsoleId, DataSource, DbDriver, DbManager, QueryResult};
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
const TARGET: &str = "fixture";
|
||||
const A: ConsoleId<'static> = ConsoleId::new("main", "a.sql");
|
||||
const B: ConsoleId<'static> = ConsoleId::new("main", "b.sql");
|
||||
const C: ConsoleId<'static> = ConsoleId::new("other", "a.sql");
|
||||
|
||||
async fn run(db: &DbManager, console: ConsoleId<'_>, sql: &str, token: &CancellationToken) -> IdeResult<QueryResult> {
|
||||
db.execute_in_console(TARGET, sql, 0, 10, token, Some("public"), Some(console)).await
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore = "requires a disposable local PostgreSQL fixture with OPENIDEA_PG_CONSOLE_PORT and console_fixture db/user"]
|
||||
async fn console_transactions_have_independent_commit_stop_and_release() -> IdeResult<()> {
|
||||
let dir = tempfile::tempdir()?;
|
||||
let root = dir.path();
|
||||
let ssh = Arc::new(ide_ssh::SshManager::new(root.join("ssh-passwords.json")));
|
||||
let db = DbManager::new(root.into(), root.join("passwords.json"), root.join("history.json"), ssh);
|
||||
db.save_sources(vec![DataSource {
|
||||
id: TARGET.into(),
|
||||
name: "Local PostgreSQL".into(),
|
||||
driver: DbDriver::Postgres,
|
||||
host: "127.0.0.1".into(),
|
||||
port: Some(std::env::var("OPENIDEA_PG_CONSOLE_PORT").expect("disposable fixture port").parse().unwrap()),
|
||||
user: "console_fixture".into(),
|
||||
database: "console_fixture".into(),
|
||||
..Default::default()
|
||||
}])
|
||||
.await?;
|
||||
let cancel = CancellationToken::new();
|
||||
let observer = db.pool(TARGET).await?;
|
||||
db.execute(TARGET, "CREATE TABLE public.console_tx (id int PRIMARY KEY)", 0, &cancel).await?;
|
||||
for console in [A, B, C] {
|
||||
assert!(db.set_postgres_console_manual(TARGET, console, true).await?);
|
||||
assert!(!db.set_postgres_console_manual(TARGET, console, true).await?);
|
||||
}
|
||||
run(&db, A, "INSERT INTO public.console_tx VALUES (1)", &cancel).await?;
|
||||
let status = "SELECT pg_backend_pid(), txid_current(), count(*) FROM public.console_tx";
|
||||
let a = run(&db, A, status, &cancel).await?.rows;
|
||||
let b = run(&db, B, status, &cancel).await?.rows;
|
||||
assert_ne!(a[0][0], b[0][0]);
|
||||
assert_ne!(a[0][1], b[0][1]);
|
||||
assert_eq!(a[0][2].as_deref(), Some("1"));
|
||||
assert_eq!(b[0][2].as_deref(), Some("0"));
|
||||
let error = run(&db, C, "SELECT 1", &cancel).await.unwrap_err();
|
||||
assert_eq!(error.kind, ErrorKind::Unavailable);
|
||||
assert!(error.message.contains("Commit or roll back"));
|
||||
let rows = "SELECT id FROM public.console_tx ORDER BY id";
|
||||
assert!(observer.rows(rows, 10).await?.is_empty());
|
||||
run(&db, B, "INSERT INTO public.console_tx VALUES (2)", &cancel).await?;
|
||||
db.finish_postgres_console_transaction(TARGET, B, true).await?;
|
||||
assert_eq!(observer.rows(rows, 10).await?, [[Some("2".into())]]);
|
||||
db.release_target_console(A, Some("other-target")).await?;
|
||||
let retained =
|
||||
db.read_console_row(TARGET, rows, 0, &cancel, Some("public"), Some(A.expecting_manual(Some(true)))).await?;
|
||||
assert_eq!(retained.rows, [[Some("1".into())]]);
|
||||
let a_after_b = run(&db, A, status, &cancel).await?.rows;
|
||||
assert_eq!(&a_after_b[0][..2], &a[0][..2]);
|
||||
assert_eq!(a_after_b[0][2].as_deref(), Some("2"));
|
||||
println!("Separate backend/transaction IDs: A {:?}, B {:?}; observer sees only B's committed row", a[0], b[0]);
|
||||
|
||||
run(&db, B, "INSERT INTO public.console_tx VALUES (3)", &cancel).await?;
|
||||
let stop = CancellationToken::new();
|
||||
let slow = "SELECT pg_sleep(8) AS scoped_manual_a";
|
||||
let mut a_slow = std::pin::pin!(run(&db, A, slow, &stop));
|
||||
let active = async {
|
||||
loop {
|
||||
let rows = observer.rows(
|
||||
"SELECT pid FROM pg_stat_activity WHERE state = 'active' AND query = 'SELECT pg_sleep(8) AS scoped_manual_a'",
|
||||
1,
|
||||
).await?;
|
||||
if !rows.is_empty() {
|
||||
return IdeResult::Ok(());
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(30)).await;
|
||||
}
|
||||
};
|
||||
tokio::select! {
|
||||
result = &mut a_slow => panic!("A ended before observer saw it: {result:?}"),
|
||||
observed = tokio::time::timeout(Duration::from_secs(3), active) => observed.expect("A reached PostgreSQL")?,
|
||||
}
|
||||
let waiting = CancellationToken::new();
|
||||
let still_running = async {
|
||||
let (waited, ()) = tokio::join!(run(&db, A, "SELECT 1", &waiting), async {
|
||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||
waiting.cancel();
|
||||
});
|
||||
assert_eq!(waited.unwrap_err().kind, ErrorKind::Cancelled);
|
||||
let b = run(&db, B, rows, &cancel).await?;
|
||||
assert_eq!(b.rows, [[Some("2".into())], [Some("3".into())]]);
|
||||
IdeResult::Ok(())
|
||||
};
|
||||
tokio::select! {
|
||||
result = &mut a_slow => panic!("A ended before B finished: {result:?}"),
|
||||
result = tokio::time::timeout(Duration::from_secs(2), still_running) => result.expect("B did not wait for A")?,
|
||||
}
|
||||
stop.cancel();
|
||||
let error = tokio::time::timeout(Duration::from_secs(4), &mut a_slow).await.expect("A stopped").unwrap_err();
|
||||
assert_eq!(error.kind, ErrorKind::Cancelled);
|
||||
assert_eq!(observer.rows(rows, 10).await?, [[Some("2".into())]]);
|
||||
db.finish_postgres_console_transaction(TARGET, B, true).await?;
|
||||
assert_eq!(observer.rows(rows, 10).await?, [[Some("2".into())], [Some("3".into())]]);
|
||||
|
||||
run(&db, A, "INSERT INTO public.console_tx VALUES (4)", &cancel).await?;
|
||||
db.release_console(A).await?;
|
||||
let stale = run(&db, A.expecting_manual(Some(true)), "INSERT INTO public.console_tx VALUES (5)", &cancel)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(stale.kind, ErrorKind::OutOfSync);
|
||||
let stale_commit = db.finish_postgres_console_transaction(TARGET, A, true).await.unwrap_err();
|
||||
assert_eq!(stale_commit.kind, ErrorKind::OutOfSync);
|
||||
assert_eq!(run(&db, C, rows, &cancel).await?.rows, [[Some("2".into())], [Some("3".into())]]);
|
||||
db.finish_postgres_console_transaction(TARGET, C, false).await?;
|
||||
db.disconnect(TARGET).await;
|
||||
println!(
|
||||
"Stop A rolled back only A. B committed afterward, and releasing A rolled back its next transaction and freed a slot."
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
//! `OPENIDEA_TEST_POSTGRES=host:port:user:password` names a throwaway server.
|
||||
|
||||
use ide_core::{CancellationToken, IdeResult};
|
||||
use ide_db::{DataSource, DbDriver, DbManager};
|
||||
use ide_db::{DataSource, DbDriver, DbManager, DbPersistence};
|
||||
|
||||
fn server() -> Option<(String, u16, String, String)> {
|
||||
endpoint("OPENIDEA_TEST_POSTGRES")
|
||||
@@ -338,6 +338,8 @@ async fn table_details_routines_and_completion_on_older_catalogs() -> IdeResult<
|
||||
"CREATE TABLE oi_meta.lines (n INT PRIMARY KEY, o_region INT, o_id INT, \
|
||||
FOREIGN KEY (o_region, o_id) REFERENCES oi_meta.orders (region, id))",
|
||||
"CREATE INDEX lines_order ON oi_meta.lines (o_id, o_region)",
|
||||
"COMMENT ON TABLE oi_meta.orders IS 'Customer''s orders'",
|
||||
"COMMENT ON COLUMN oi_meta.orders.note IS 'Free text'",
|
||||
"CREATE FUNCTION oi_meta.twice(v INT) RETURNS INT AS 'SELECT v * 2' LANGUAGE sql",
|
||||
] {
|
||||
db.execute("p", stmt, 10, &c).await?;
|
||||
@@ -350,6 +352,13 @@ async fn table_details_routines_and_completion_on_older_catalogs() -> IdeResult<
|
||||
assert_eq!(details.foreign_keys[0].columns, ["o_region", "o_id"]);
|
||||
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);
|
||||
let key = orders.indexes.iter().find(|i| i.unique).expect("primary key index");
|
||||
assert_eq!(key.columns, ["region", "id"]);
|
||||
|
||||
@@ -384,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<_>>(),
|
||||
@@ -414,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(())
|
||||
}
|
||||
@@ -780,6 +813,75 @@ async fn table_grants_expand_the_acl_per_grantee() -> IdeResult<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Modify Table's properties: owner, tablespace, access method, storage options (the TOAST
|
||||
/// table's too), partition key and persistence, read again after the statements it runs.
|
||||
#[tokio::test]
|
||||
async fn table_details_read_the_storage_properties() -> IdeResult<()> {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let Some(db) = manager(&tmp).await else { return Ok(()) };
|
||||
let c = CancellationToken::new();
|
||||
for stmt in [
|
||||
"DROP SCHEMA IF EXISTS oi_props CASCADE",
|
||||
"DROP ROLE IF EXISTS oi_props_owner",
|
||||
"CREATE ROLE oi_props_owner",
|
||||
"CREATE SCHEMA oi_props",
|
||||
"CREATE UNLOGGED TABLE oi_props.bulk (id INT, v TEXT) WITH (fillfactor = 70, toast.autovacuum_enabled = false)",
|
||||
"CREATE TABLE oi_props.events (id INT, at DATE) PARTITION BY RANGE (at)",
|
||||
"CREATE VIEW oi_props.recent AS SELECT 1 AS n",
|
||||
] {
|
||||
db.execute("p", stmt, 10, &c).await?;
|
||||
}
|
||||
let owner = db.execute("p", "SELECT current_user", 1, &c).await?.rows[0][0].clone().unwrap();
|
||||
let default_tablespace = db
|
||||
.execute(
|
||||
"p",
|
||||
"SELECT t.spcname FROM pg_database d JOIN pg_tablespace t ON t.oid = d.dattablespace \
|
||||
WHERE d.datname = current_database()",
|
||||
1,
|
||||
&c,
|
||||
)
|
||||
.await?
|
||||
.rows[0][0]
|
||||
.clone();
|
||||
let options = |pairs: &[(&str, &str)]| Some(pairs.iter().map(|(k, v)| ((*k).into(), (*v).into())).collect());
|
||||
|
||||
let bulk = db.table_details("p", "oi_props", "bulk").await?;
|
||||
assert_eq!(bulk.owner.as_deref(), Some(owner.as_str()));
|
||||
assert_eq!(bulk.tablespace, default_tablespace);
|
||||
assert_eq!(bulk.access_method.as_deref(), Some("heap"));
|
||||
assert_eq!(bulk.storage_options, options(&[("fillfactor", "70"), ("toast.autovacuum_enabled", "false")]));
|
||||
assert_eq!(bulk.partitioning, None);
|
||||
assert_eq!(bulk.persistence, Some(DbPersistence::Unlogged));
|
||||
|
||||
let events = db.table_details("p", "oi_props", "events").await?;
|
||||
assert_eq!(events.partitioning.as_deref(), Some("RANGE (at)"));
|
||||
assert_eq!(events.storage_options, options(&[]));
|
||||
assert_eq!(events.persistence, Some(DbPersistence::Permanent));
|
||||
// A view has none of a table's storage.
|
||||
let recent = db.table_details("p", "oi_props", "recent").await?;
|
||||
assert_eq!((recent.owner, recent.storage_options, recent.persistence), (None, None, None));
|
||||
|
||||
// The statements Modify Table generates (objects.ts `tablePropertiesSql`).
|
||||
for stmt in [
|
||||
"alter table oi_props.bulk set logged;",
|
||||
"alter table oi_props.bulk reset (toast.autovacuum_enabled);",
|
||||
"alter table oi_props.bulk set (fillfactor = 50, autovacuum_enabled = false);",
|
||||
"alter table oi_props.bulk set tablespace pg_default;",
|
||||
"alter table oi_props.bulk owner to oi_props_owner;",
|
||||
] {
|
||||
db.execute("p", stmt, 10, &c).await?;
|
||||
}
|
||||
let bulk = db.table_details("p", "oi_props", "bulk").await?;
|
||||
assert_eq!(bulk.owner.as_deref(), Some("oi_props_owner"));
|
||||
assert_eq!(bulk.tablespace.as_deref(), Some("pg_default"));
|
||||
assert_eq!(bulk.storage_options, options(&[("fillfactor", "50"), ("autovacuum_enabled", "false")]));
|
||||
assert_eq!(bulk.persistence, Some(DbPersistence::Permanent));
|
||||
for stmt in ["DROP SCHEMA oi_props CASCADE", "DROP ROLE oi_props_owner"] {
|
||||
db.execute("p", stmt, 10, &c).await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Completion reads the default schema in full: 52,000 columns there passed the cap shared with
|
||||
/// the other schemas, and the tables sorting last lost theirs (#6118).
|
||||
#[tokio::test]
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -423,11 +423,25 @@ pub struct CapabilityInfo {
|
||||
pub optional: bool,
|
||||
/// Currently granted.
|
||||
pub granted: bool,
|
||||
/// The plugin's own explanation (`[capabilities.reasons]`), shown below `description`.
|
||||
#[serde(default)]
|
||||
pub reason: Option<String>,
|
||||
/// `reason` translated by the plugin's `locales/<tag>.json`, by language tag.
|
||||
#[serde(default)]
|
||||
pub reason_locales: std::collections::BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
impl CapabilityInfo {
|
||||
pub fn new(cap: &Capability, optional: bool, granted: bool) -> Self {
|
||||
Self { id: cap.to_string(), risk: cap.risk(), description: cap.describe(), optional, granted }
|
||||
Self {
|
||||
id: cap.to_string(),
|
||||
risk: cap.risk(),
|
||||
description: cap.describe(),
|
||||
optional,
|
||||
granted,
|
||||
reason: None,
|
||||
reason_locales: Default::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -29,12 +29,14 @@ use crate::capability::Capability;
|
||||
use crate::plugin_point::PointDecl;
|
||||
use crate::resolve::Dependency;
|
||||
use serde::Deserialize;
|
||||
use std::collections::BTreeSet;
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
|
||||
pub const MANIFEST_FILE: &str = "plugin.toml";
|
||||
/// The plugin API (engine) version this host implements.
|
||||
pub const ENGINE_VERSION: &str = "1.18.0";
|
||||
pub const ENGINE_VERSION: &str = "1.19.0";
|
||||
/// The longest `[capabilities.reasons]` entry, in characters: a sentence or two.
|
||||
pub const MAX_CAPABILITY_REASON: usize = 500;
|
||||
/// The 0.1 API, still accepted for contribution-only packages and 0.1 components.
|
||||
pub const LEGACY_API: &str = "0.1";
|
||||
/// Marketplace categories, in the order they are shown.
|
||||
@@ -49,11 +51,15 @@ pub struct Manifest {
|
||||
pub name: String,
|
||||
pub version: String,
|
||||
pub description: String,
|
||||
/// Markdown file for Settings › Plugins › Overview (`description-file`).
|
||||
pub description_file: Option<PathBuf>,
|
||||
pub authors: Vec<String>,
|
||||
pub homepage: Option<String>,
|
||||
pub license: Option<String>,
|
||||
/// Release notes of this version (Settings › Plugins › What's New).
|
||||
pub change_notes: Option<String>,
|
||||
/// Markdown file for Settings › Plugins › What's New (`change-notes-file`).
|
||||
pub change_notes_file: Option<PathBuf>,
|
||||
/// Marketplace categories as declared (see [`Manifest::categories`]).
|
||||
pub declared_categories: Vec<String>,
|
||||
/// SVG shown in Settings › Plugins and the marketplace.
|
||||
@@ -80,6 +86,10 @@ pub struct Manifest {
|
||||
pub struct Capabilities {
|
||||
pub required: Vec<Capability>,
|
||||
pub optional: Vec<Capability>,
|
||||
/// `[capabilities.reasons]` (API 1.19): the plugin's own words on why it asks for a
|
||||
/// declared capability, keyed by the capability as printed (`net:127.0.0.1`). Shown
|
||||
/// below the host's description, never instead of it.
|
||||
pub reasons: BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
impl Capabilities {
|
||||
@@ -90,6 +100,11 @@ impl Capabilities {
|
||||
pub fn is_optional(&self, cap: &Capability) -> bool {
|
||||
self.optional.contains(cap) && !self.required.contains(cap)
|
||||
}
|
||||
|
||||
/// The plugin's explanation of `cap`, if it gave one.
|
||||
pub fn reason(&self, cap: &Capability) -> Option<&str> {
|
||||
self.reasons.get(&cap.to_string()).map(String::as_str)
|
||||
}
|
||||
}
|
||||
|
||||
/// When a plugin's code is instantiated (plan 4.4). Contributions are live
|
||||
@@ -195,6 +210,8 @@ struct Raw {
|
||||
#[serde(default)]
|
||||
description: String,
|
||||
#[serde(default)]
|
||||
description_file: Option<PathBuf>,
|
||||
#[serde(default)]
|
||||
authors: Vec<String>,
|
||||
#[serde(default)]
|
||||
homepage: Option<String>,
|
||||
@@ -203,6 +220,8 @@ struct Raw {
|
||||
#[serde(default)]
|
||||
change_notes: Option<String>,
|
||||
#[serde(default)]
|
||||
change_notes_file: Option<PathBuf>,
|
||||
#[serde(default)]
|
||||
categories: Vec<String>,
|
||||
#[serde(default)]
|
||||
icon: Option<PathBuf>,
|
||||
@@ -243,6 +262,8 @@ struct RawCapabilities {
|
||||
required: Vec<String>,
|
||||
#[serde(default)]
|
||||
optional: Vec<String>,
|
||||
#[serde(default)]
|
||||
reasons: BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
impl Manifest {
|
||||
@@ -271,8 +292,18 @@ impl Manifest {
|
||||
Ok(out)
|
||||
};
|
||||
let capabilities = match (raw.capabilities, raw.permissions) {
|
||||
(Some(c), _) => Capabilities { required: parse_caps(c.required)?, optional: parse_caps(c.optional)? },
|
||||
(None, Some(p)) => Capabilities { required: parse_caps(p)?, optional: Vec::new() },
|
||||
(Some(c), _) => {
|
||||
let mut reasons = BTreeMap::new();
|
||||
for (key, text) in c.reasons {
|
||||
// Keyed as the capability prints, so `net:Example.com` finds `net:example.com`.
|
||||
let cap: Capability = key.parse().map_err(|e| format!("capabilities.reasons: {e}"))?;
|
||||
reasons.insert(cap.to_string(), text);
|
||||
}
|
||||
Capabilities { required: parse_caps(c.required)?, optional: parse_caps(c.optional)?, reasons }
|
||||
}
|
||||
(None, Some(p)) => {
|
||||
Capabilities { required: parse_caps(p)?, optional: Vec::new(), reasons: BTreeMap::new() }
|
||||
}
|
||||
(None, None) => Capabilities::default(),
|
||||
};
|
||||
let activation = match raw.activation {
|
||||
@@ -286,10 +317,12 @@ impl Manifest {
|
||||
name: raw.name,
|
||||
version: raw.version,
|
||||
description: raw.description,
|
||||
description_file: raw.description_file,
|
||||
authors: raw.authors,
|
||||
homepage: raw.homepage,
|
||||
license: raw.license,
|
||||
change_notes: raw.change_notes,
|
||||
change_notes_file: raw.change_notes_file,
|
||||
declared_categories: raw.categories,
|
||||
icon: raw.icon,
|
||||
icon_dark: raw.icon_dark,
|
||||
@@ -347,6 +380,27 @@ impl Manifest {
|
||||
self.needs_api("`icon`", 2)?;
|
||||
check_relative(icon, "icon")?;
|
||||
}
|
||||
if let Some(path) = &self.description_file {
|
||||
self.needs_api("`description-file`", 18)?;
|
||||
check_relative(path, "description-file")?;
|
||||
}
|
||||
if let Some(path) = &self.change_notes_file {
|
||||
self.needs_api("`change-notes-file`", 18)?;
|
||||
check_relative(path, "change-notes-file")?;
|
||||
}
|
||||
if !self.capabilities.reasons.is_empty() {
|
||||
self.needs_api("`capabilities.reasons`", 19)?;
|
||||
}
|
||||
for (key, text) in &self.capabilities.reasons {
|
||||
if !self.capabilities.all().any(|c| c.to_string() == *key) {
|
||||
return Err(format!("capabilities.reasons: {key:?} is not under `required` or `optional`"));
|
||||
}
|
||||
if text.trim().is_empty() || text.chars().count() > MAX_CAPABILITY_REASON {
|
||||
return Err(format!(
|
||||
"capabilities.reasons: the reason for {key:?} must be 1 to {MAX_CAPABILITY_REASON} characters"
|
||||
));
|
||||
}
|
||||
}
|
||||
for cap in self.capabilities.required.iter().chain(&self.capabilities.optional) {
|
||||
if matches!(
|
||||
cap,
|
||||
@@ -762,6 +816,33 @@ required = [\"lsp:phoxite\"]
|
||||
assert_eq!(m.capabilities.optional, [Capability::BuildRead]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn capability_reasons_explain_declared_capabilities_from_api_1_19() {
|
||||
let caps = "[capabilities]\nrequired = [\"net:Example.com\"]\noptional = [\"clipboard.read\"]\n\
|
||||
[capabilities.reasons]\n\"net:Example.com\" = \"Fetches the schema.\"\n\
|
||||
\"clipboard.read\" = \"Imports a log you copied.\"\n";
|
||||
assert!(err(&format!("{}{caps}", BASE.replace("^1.2", "^1.18"))).contains("new in plugin API 1.19"));
|
||||
let src = |caps: &str| format!("{}{caps}", BASE.replace("^1.2", "^1.19"));
|
||||
let m = Manifest::parse(&src(caps)).unwrap();
|
||||
// Keyed as the capability prints.
|
||||
assert_eq!(m.capabilities.reason(&Capability::Net("example.com".into())), Some("Fetches the schema."));
|
||||
assert_eq!(m.capabilities.reason(&Capability::ClipboardRead), Some("Imports a log you copied."));
|
||||
assert_eq!(m.capabilities.reason(&Capability::ProjectRead), None);
|
||||
|
||||
let undeclared =
|
||||
"[capabilities]\nrequired = [\"project.read\"]\n[capabilities.reasons]\n\"project.write\" = \"x\"\n";
|
||||
assert!(err(&src(undeclared)).contains("not under `required` or `optional`"));
|
||||
let invalid = "[capabilities]\nrequired = [\"project.read\"]\n[capabilities.reasons]\n\"teleport\" = \"x\"\n";
|
||||
assert!(err(&src(invalid)).contains("capabilities.reasons"));
|
||||
let empty = "[capabilities]\nrequired = [\"project.read\"]\n[capabilities.reasons]\n\"project.read\" = \" \"\n";
|
||||
assert!(err(&src(empty)).contains("1 to 500 characters"));
|
||||
let long = format!(
|
||||
"[capabilities]\nrequired = [\"project.read\"]\n[capabilities.reasons]\n\"project.read\" = \"{}\"\n",
|
||||
"x".repeat(MAX_CAPABILITY_REASON + 1)
|
||||
);
|
||||
assert!(err(&src(&long)).contains("1 to 500 characters"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_clipboard_read_capability_needs_api_1_11() {
|
||||
let caps = "[capabilities]\noptional = [\"clipboard.read\"]\n";
|
||||
@@ -1005,4 +1086,27 @@ mod net_ask_api_tests {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn doc_files_require_api_1_18_and_relative_paths() {
|
||||
for field in ["description-file", "change-notes-file"] {
|
||||
for engine in ["^1.17", "^1.18"] {
|
||||
let manifest = format!(
|
||||
"id = 'test'\nname = 'Test'\nversion = '0.1.0'\nengines.openidea = '{engine}'\n{field} = 'docs.md'\n"
|
||||
);
|
||||
let parsed = Manifest::parse(&manifest);
|
||||
if engine == "^1.18" {
|
||||
parsed.unwrap();
|
||||
} else {
|
||||
assert!(parsed.unwrap_err().contains("new in plugin API 1.18"), "{field} {engine}");
|
||||
}
|
||||
}
|
||||
for bad in ["../escape.md", "/abs/path.md"] {
|
||||
let manifest = format!(
|
||||
"id = 'test'\nname = 'Test'\nversion = '0.1.0'\nengines.openidea = '^1.18'\n{field} = '{bad}'\n"
|
||||
);
|
||||
assert!(Manifest::parse(&manifest).unwrap_err().contains("relative path"), "{field} {bad}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -27,6 +27,7 @@ use crate::MANIFEST_FILE;
|
||||
use base64::Engine as _;
|
||||
use ed25519_dalek::{Signature, Signer, SigningKey, VerifyingKey};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::BTreeMap;
|
||||
use std::io::{Read, Write};
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
|
||||
@@ -331,6 +332,9 @@ pub struct IndexEntry {
|
||||
pub version: String,
|
||||
#[serde(default)]
|
||||
pub description: String,
|
||||
/// Localized descriptions keyed by BCP 47 language tag (e.g. `zh-CN`).
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
pub description_locales: BTreeMap<String, String>,
|
||||
#[serde(default)]
|
||||
pub authors: Vec<String>,
|
||||
pub publisher: String,
|
||||
@@ -358,6 +362,9 @@ pub struct IndexEntry {
|
||||
/// This version's release notes (the manifest's `change-notes`).
|
||||
#[serde(default)]
|
||||
pub notes: Option<String>,
|
||||
/// Localized release notes keyed by BCP 47 language tag (e.g. `zh-CN`).
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
pub notes_locales: BTreeMap<String, String>,
|
||||
/// Downloads of the plugin's packages, as counted by whoever serves them.
|
||||
#[serde(default)]
|
||||
pub downloads: Option<u64>,
|
||||
@@ -715,6 +722,7 @@ mod tests {
|
||||
name: id.into(),
|
||||
version: "1.0.0".into(),
|
||||
description: String::new(),
|
||||
description_locales: BTreeMap::new(),
|
||||
authors: Vec::new(),
|
||||
publisher: publisher.into(),
|
||||
download: format!("https://example.com/{id}.oiplugin"),
|
||||
@@ -725,6 +733,7 @@ mod tests {
|
||||
icon: None,
|
||||
homepage: None,
|
||||
notes: None,
|
||||
notes_locales: BTreeMap::new(),
|
||||
downloads: None,
|
||||
featured: false,
|
||||
suggest: Vec::new(),
|
||||
|
||||
@@ -12,4 +12,3 @@ serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
specta.workspace = true
|
||||
tracing.workspace = true
|
||||
which = "8"
|
||||
@@ -16,30 +16,15 @@ use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
use std::sync::OnceLock;
|
||||
use std::time::Duration;
|
||||
|
||||
/// API calls normally answer within a few seconds.
|
||||
const QUICK: Duration = Duration::from_secs(60);
|
||||
|
||||
/// Locates the gh executable once per process (GUI apps on macOS have a minimal `PATH`).
|
||||
/// Locates the gh executable (GUI apps on macOS have a minimal `PATH`, and the IDE can
|
||||
/// install or remove a managed copy in its tools directory at runtime).
|
||||
pub fn gh_executable() -> Option<PathBuf> {
|
||||
static GH: OnceLock<Option<PathBuf>> = OnceLock::new();
|
||||
GH.get_or_init(|| {
|
||||
if let Some(explicit) = std::env::var_os("OPENIDEA_GH").map(PathBuf::from).filter(|p| p.is_file()) {
|
||||
return Some(explicit);
|
||||
}
|
||||
if let Ok(found) = which::which("gh") {
|
||||
return Some(found);
|
||||
}
|
||||
let candidates: &[&str] = if cfg!(windows) {
|
||||
&[r"C:\Program Files\GitHub CLI\gh.exe"]
|
||||
} else {
|
||||
&["/opt/homebrew/bin/gh", "/usr/local/bin/gh", "/usr/bin/gh", "/snap/bin/gh"]
|
||||
};
|
||||
candidates.iter().map(PathBuf::from).find(|p| p.is_file())
|
||||
})
|
||||
.clone()
|
||||
ide_core::tool_path::find_gh_executable()
|
||||
}
|
||||
|
||||
fn command(root: &Path, args: &[&str]) -> IdeResult<Command> {
|
||||
@@ -126,7 +111,17 @@ pub fn availability(root: &Path) -> GhAvailability {
|
||||
let login = login.ok().and_then(Result::ok).map(|l| l.trim().to_owned()).filter(|l| !l.is_empty());
|
||||
match repo {
|
||||
Ok(Ok(out)) if out.success => match parse_repo(&out.stdout) {
|
||||
Ok(repo) => GhAvailability::Ready { repo, login },
|
||||
Ok(repo) => {
|
||||
// The login above is github.com's; an Enterprise repository has its own.
|
||||
let login = match url_host(&repo.url).filter(|h| !h.eq_ignore_ascii_case("github.com")) {
|
||||
Some(host) => run(root, &["api", "--hostname", host, "user", "--jq", ".login"])
|
||||
.ok()
|
||||
.map(|l| l.trim().to_owned())
|
||||
.filter(|l| !l.is_empty()),
|
||||
None => login,
|
||||
};
|
||||
GhAvailability::Ready { repo, login }
|
||||
}
|
||||
Err(e) => GhAvailability::Error { message: format!("unexpected gh output: {e}") },
|
||||
},
|
||||
Ok(Ok(out)) => classify_failure(if out.stderr.trim().is_empty() { &out.stdout } else { &out.stderr }),
|
||||
@@ -301,6 +296,10 @@ pub struct GhApiRequest {
|
||||
pub body: Option<String>,
|
||||
/// Follow REST `Link` pages; the result is the array of all pages (`--slurp`).
|
||||
pub paginate: bool,
|
||||
/// The repository's GitHub host (`ghe.example.com`); none: gh's default host. `gh api`
|
||||
/// doesn't take the host from the remote as `gh pr` does.
|
||||
#[serde(default)]
|
||||
pub host: Option<String>,
|
||||
}
|
||||
|
||||
const METHODS: &[&str] = &["GET", "POST", "PATCH", "PUT", "DELETE"];
|
||||
@@ -316,6 +315,13 @@ pub fn api_args(req: &GhApiRequest) -> IdeResult<Vec<String>> {
|
||||
return Err(IdeError::invalid(format!("not a GitHub API endpoint: {endpoint}")));
|
||||
}
|
||||
let mut args: Vec<String> = vec!["api".into(), "--method".into(), method, endpoint.into()];
|
||||
if let Some(host) = req.host.as_deref().map(str::trim).filter(|h| !h.is_empty()) {
|
||||
if !is_host(host) {
|
||||
return Err(IdeError::invalid(format!("not a GitHub host: {host}")));
|
||||
}
|
||||
args.push("--hostname".into());
|
||||
args.push(host.into());
|
||||
}
|
||||
if req.body.is_some() {
|
||||
args.push("--input".into());
|
||||
args.push("-".into());
|
||||
@@ -327,14 +333,45 @@ pub fn api_args(req: &GhApiRequest) -> IdeResult<Vec<String>> {
|
||||
Ok(args)
|
||||
}
|
||||
|
||||
/// `host` or `host:port`, as gh's `--hostname` takes it.
|
||||
fn is_host(host: &str) -> bool {
|
||||
let (name, port) = host.split_once(':').unwrap_or((host, "1"));
|
||||
!name.is_empty()
|
||||
&& !name.starts_with(['-', '.'])
|
||||
&& name.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'.')
|
||||
&& !port.is_empty()
|
||||
&& port.bytes().all(|b| b.is_ascii_digit())
|
||||
}
|
||||
|
||||
/// The host of a repository URL from gh (`https://ghe.example.com/o/r` → `ghe.example.com`).
|
||||
pub fn url_host(url: &str) -> Option<&str> {
|
||||
let rest = url.split_once("://")?.1;
|
||||
let host = rest.split('/').next()?;
|
||||
let host = host.rsplit_once('@').map_or(host, |(_, h)| h);
|
||||
is_host(host).then_some(host)
|
||||
}
|
||||
|
||||
/// Runs `req`; returns the response body (JSON text, empty for `204 No Content`).
|
||||
pub fn api(root: &Path, req: &GhApiRequest) -> IdeResult<String> {
|
||||
let args = api_args(req)?;
|
||||
let refs: Vec<&str> = args.iter().map(String::as_str).collect();
|
||||
let out = process::run_with_input(command(root, &refs)?, req.body.as_deref(), QUICK, None)?;
|
||||
let mut args = api_args(req)?;
|
||||
let run = |args: &[String]| {
|
||||
let refs: Vec<&str> = args.iter().map(String::as_str).collect();
|
||||
process::run_with_input(command(root, &refs)?, req.body.as_deref(), QUICK, None)
|
||||
};
|
||||
let mut out = run(&args)?;
|
||||
// Recent gh refuses plain-text bodies with terminal escape sequences (coloured Actions job
|
||||
// logs) unless allowed; older gh lacks the flag. Only a GET is safe to send twice.
|
||||
if !out.success && req.method.eq_ignore_ascii_case("GET") && refused_escape_sequences(&out.stderr) {
|
||||
args.insert(1, "--allow-escape-sequences".into());
|
||||
out = run(&args)?;
|
||||
}
|
||||
if out.success { Ok(out.stdout) } else { Err(failure(&out.stderr, &out.stdout)) }
|
||||
}
|
||||
|
||||
fn refused_escape_sequences(stderr: &str) -> bool {
|
||||
stderr.contains("--allow-escape-sequences")
|
||||
}
|
||||
|
||||
/// Revisions to diff a pull request's files with, present in the local repository.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
@@ -386,3 +423,46 @@ pub fn prepare_diff(
|
||||
let files = repo.diff_files(&base, head_oid)?;
|
||||
Ok(PrDiffRevisions { base, head: head_oid.to_owned(), files, root: ide_core::IpcPath(repo.root().to_path_buf()) })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn recognises_gh_refusing_escape_sequences() {
|
||||
// gh 2.104's message for a coloured Actions job log.
|
||||
assert!(super::refused_escape_sequences(
|
||||
"the response contains terminal escape sequences; pass --allow-escape-sequences to output it anyway\n"
|
||||
));
|
||||
assert!(!super::refused_escape_sequences("gh: Not Found (HTTP 404)"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gh_executable_picks_up_newly_installed_binary_without_restart() {
|
||||
let dir = std::env::temp_dir().join(format!("openidea-gh-test-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let search = std::env::join_paths([&dir]).unwrap();
|
||||
assert_eq!(ide_core::tool_path::find_gh_in(None, &search, &[]), None);
|
||||
|
||||
let gh = dir.join(if cfg!(windows) { "gh.exe" } else { "gh" });
|
||||
std::fs::write(&gh, "#!/bin/sh\n").unwrap();
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
std::fs::set_permissions(&gh, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
}
|
||||
assert_eq!(ide_core::tool_path::find_gh_in(None, &search, &[]), Some(gh.clone()));
|
||||
|
||||
let explicit = dir.join(if cfg!(windows) { "custom-gh.exe" } else { "custom-gh" });
|
||||
std::fs::write(&explicit, "#!/bin/sh\n").unwrap();
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
std::fs::set_permissions(&explicit, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
}
|
||||
assert_eq!(ide_core::tool_path::find_gh_in(Some(&explicit), &search, &[]), Some(explicit));
|
||||
|
||||
std::fs::remove_file(&gh).unwrap();
|
||||
assert_eq!(ide_core::tool_path::find_gh_in(None, &search, &[]), None);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
}
|
||||
@@ -101,14 +101,28 @@ fn list_arguments() {
|
||||
|
||||
#[test]
|
||||
fn api_arguments() {
|
||||
let req =
|
||||
GhApiRequest { method: "post".into(), endpoint: "graphql".into(), body: Some("{}".into()), paginate: false };
|
||||
let req = GhApiRequest {
|
||||
method: "post".into(),
|
||||
endpoint: "graphql".into(),
|
||||
body: Some("{}".into()),
|
||||
paginate: false,
|
||||
host: None,
|
||||
};
|
||||
assert_eq!(api_args(&req).unwrap(), ["api", "--method", "POST", "graphql", "--input", "-"]);
|
||||
let ghe = GhApiRequest { host: Some("ghe.example.com:8443".into()), ..req.clone() };
|
||||
assert_eq!(
|
||||
api_args(&ghe).unwrap(),
|
||||
["api", "--method", "POST", "graphql", "--hostname", "ghe.example.com:8443", "--input", "-"]
|
||||
);
|
||||
for bad in ["--x", "evil.example/x", "a b", ".x", "h:", "h:8x"] {
|
||||
assert!(api_args(&GhApiRequest { host: Some(bad.into()), ..req.clone() }).is_err(), "{bad}");
|
||||
}
|
||||
let req = GhApiRequest {
|
||||
method: "GET".into(),
|
||||
endpoint: "repos/{owner}/{repo}/labels".into(),
|
||||
body: None,
|
||||
paginate: true,
|
||||
host: Some(" ".into()),
|
||||
};
|
||||
assert_eq!(
|
||||
api_args(&req).unwrap(),
|
||||
@@ -119,3 +133,11 @@ fn api_arguments() {
|
||||
}
|
||||
assert!(api_args(&GhApiRequest { method: "TRACE".into(), ..req }).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repository_url_hosts() {
|
||||
assert_eq!(url_host("https://ghe.example.com/acme/app"), Some("ghe.example.com"));
|
||||
assert_eq!(url_host("https://github.com/o/r"), Some("github.com"));
|
||||
assert_eq!(url_host("https://[email protected]:8443/o/r"), Some("ghe.example.com:8443"));
|
||||
assert_eq!(url_host("ghe.example.com/o/r"), None);
|
||||
}
|
||||
@@ -28,6 +28,7 @@ ide-syntax.workspace = true
|
||||
ide-search.workspace = true
|
||||
ide-lsp.workspace = true
|
||||
ide-vcs.workspace = true
|
||||
ide-github.workspace = true
|
||||
ide-dap.workspace = true
|
||||
ide-heap.workspace = true
|
||||
ide-jvm-attach.workspace = true
|
||||
@@ -76,6 +77,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
|
||||
|
||||
@@ -22,7 +22,9 @@
|
||||
mod templates;
|
||||
|
||||
use ide_extension::{Manifest, validate_plugin_id};
|
||||
use ide_host::plugins::{PluginHost, market_href_reachable_from, plugin_icon, read_market_url, resolve_market_href};
|
||||
use ide_host::plugins::{
|
||||
PluginHost, market_href_reachable_from, plugin_docs, plugin_icon, read_market_url, resolve_market_href,
|
||||
};
|
||||
use ide_plugin::{Limits, PluginEngine};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, ExitCode};
|
||||
@@ -641,12 +643,15 @@ fn cmd_index(args: &[String]) -> Result<(), String> {
|
||||
Some(wasm) => engine.check_component(&engine.compile(&scratch.join(wasm))?)?,
|
||||
None => None,
|
||||
};
|
||||
let pkg = ide_extension::Package::new(m.clone(), scratch.clone());
|
||||
let docs = plugin_docs(&pkg)?;
|
||||
let file = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
|
||||
Ok::<_, String>(IndexEntry {
|
||||
id: m.id.clone(),
|
||||
name: m.name.clone(),
|
||||
version: m.version.clone(),
|
||||
description: m.description.clone(),
|
||||
description: docs.description,
|
||||
description_locales: docs.description_locales,
|
||||
authors: m.authors.clone(),
|
||||
publisher: signer,
|
||||
download: base.map_or_else(|| file.clone(), |b| format!("{b}/{file}")),
|
||||
@@ -654,9 +659,10 @@ fn cmd_index(args: &[String]) -> Result<(), String> {
|
||||
capabilities: m.capabilities.all().map(|c| c.to_string()).collect(),
|
||||
engine: package::engine_requirement(&m.engine, built_for.as_ref()),
|
||||
categories: m.categories(),
|
||||
icon: plugin_icon(&ide_extension::Package::new(m.clone(), scratch.clone()))?,
|
||||
icon: plugin_icon(&pkg)?,
|
||||
homepage: m.homepage.clone().filter(|h| !h.trim().is_empty()),
|
||||
notes: m.change_notes.clone().filter(|n| !n.trim().is_empty()),
|
||||
notes: docs.change_notes.filter(|n| !n.trim().is_empty()),
|
||||
notes_locales: docs.change_notes_locales,
|
||||
downloads: None,
|
||||
featured: false,
|
||||
suggest: Vec::new(),
|
||||
@@ -1078,6 +1084,62 @@ mod tests {
|
||||
assert!(index.plugins[0].icon.as_ref().expect("icon").light.contains("<rect"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_validates_markdown_doc_files_and_index_carries_localized_docs() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let t = tmp.path();
|
||||
let key = t.join("acme.key");
|
||||
std::fs::write(&key, PublisherKey::from_seed([7; 32]).seed_base64()).unwrap();
|
||||
let src = t.join("src");
|
||||
let vars = templates::Vars { id: "acme.docs", name: "Docs", sdk: None };
|
||||
for (rel, content) in templates::render(templates::Template::Theme, &vars) {
|
||||
let path = src.join(rel);
|
||||
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
std::fs::write(path, content).unwrap();
|
||||
}
|
||||
let manifest = std::fs::read_to_string(src.join("plugin.toml"))
|
||||
.unwrap()
|
||||
.replace("engines.openidea = \"^1.0\"", "engines.openidea = \"^1.18\"");
|
||||
std::fs::write(
|
||||
src.join("plugin.toml"),
|
||||
format!("description-file = \"description.md\"\nchange-notes-file = \"CHANGELOG.md\"\n{manifest}"),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
// Missing md file fails `check`.
|
||||
let err = check(&src).unwrap_err();
|
||||
assert!(err.contains("no such file"), "{err}");
|
||||
|
||||
// Valid English + zh-CN md files pass `check`, `pack`, and `index`.
|
||||
std::fs::write(src.join("description.md"), "# English\n\n- Fast\n").unwrap();
|
||||
std::fs::write(src.join("description.zh-CN.md"), "# 中文\n\n- 快速\n").unwrap();
|
||||
std::fs::write(src.join("CHANGELOG.md"), "## 0.1.0\n\n- First release\n").unwrap();
|
||||
std::fs::write(src.join("CHANGELOG.zh-CN.md"), "## 0.1.0\n\n- 首次发布\n").unwrap();
|
||||
check(&src).unwrap();
|
||||
|
||||
let out = t.join("out");
|
||||
std::fs::create_dir_all(&out).unwrap();
|
||||
let (src_str, key_str) = (src.to_string_lossy().into_owned(), key.to_string_lossy().into_owned());
|
||||
let package = out.join("acme.docs-0.1.0.oiplugin").to_string_lossy().into_owned();
|
||||
cmd_pack(&strings(&[&src_str, "--key", &key_str, "--publisher", "acme", "--out", &package])).unwrap();
|
||||
cmd_index(&strings(&[out.to_str().unwrap(), "--publisher", "acme", "--key", &key_str])).unwrap();
|
||||
let index = Index::parse(&std::fs::read_to_string(out.join("index.json")).unwrap()).unwrap();
|
||||
let entry = &index.plugins[0];
|
||||
assert!(entry.description.contains("# English"));
|
||||
assert_eq!(entry.description_locales.get("zh-CN").map(String::as_str), Some("# 中文\n\n- 快速\n"));
|
||||
assert_eq!(entry.notes.as_deref(), Some("## 0.1.0\n\n- First release\n"));
|
||||
assert_eq!(entry.notes_locales.get("zh-CN").map(String::as_str), Some("## 0.1.0\n\n- 首次发布\n"));
|
||||
|
||||
// Invalid extension fails `check`.
|
||||
std::fs::write(src.join("notes.txt"), "plain").unwrap();
|
||||
let bad = std::fs::read_to_string(src.join("plugin.toml"))
|
||||
.unwrap()
|
||||
.replace("change-notes-file = \"CHANGELOG.md\"", "change-notes-file = \"notes.txt\"");
|
||||
std::fs::write(src.join("plugin.toml"), bad).unwrap();
|
||||
let err = check(&src).unwrap_err();
|
||||
assert!(err.contains(".md or .markdown"), "{err}");
|
||||
}
|
||||
|
||||
/// `cargo test` of a new Rust plugin (its own tests against the mock host) with this SDK.
|
||||
#[test]
|
||||
fn the_command_template_builds_against_the_sdk() {
|
||||
|
||||
@@ -406,8 +406,14 @@ pub async fn serve(
|
||||
|
||||
let result = loop {
|
||||
tokio::select! {
|
||||
_ = shutdown.cancelled() => break Ok(()),
|
||||
_ = terminate.recv() => break Ok(()),
|
||||
_ = shutdown.cancelled() => {
|
||||
host.set_agent_shutdown_reason(ide_agent::AgentShutdownReason::BackendStop);
|
||||
break Ok(());
|
||||
}
|
||||
_ = terminate.recv() => {
|
||||
host.set_agent_shutdown_reason(ide_agent::AgentShutdownReason::BackendUpgrade);
|
||||
break Ok(());
|
||||
}
|
||||
_ = async {
|
||||
match &active {
|
||||
Some(peer) => { peer.closed().await; }
|
||||
@@ -445,6 +451,7 @@ pub async fn serve(
|
||||
if busy {
|
||||
let _ = stream.write_u8(BUSY).await;
|
||||
} else if stream.write_u8(RETIRING).await.is_ok() {
|
||||
host.set_agent_shutdown_reason(ide_agent::AgentShutdownReason::BackendUpgrade);
|
||||
retiring = Some(stream);
|
||||
break Ok(());
|
||||
}
|
||||
|
||||
@@ -82,6 +82,11 @@ impl Environment {
|
||||
}
|
||||
}
|
||||
|
||||
/// True on `openidea-server`, where the backend runs on a remote/headless host rather than the desktop shell.
|
||||
pub fn is_remote(&self) -> bool {
|
||||
self.project_env
|
||||
}
|
||||
|
||||
/// A trusted project at `root` opened or became trusted: loads its direnv environment in
|
||||
/// the background, unless another window of it already did. Its language servers wait.
|
||||
pub(crate) fn direnv_opened(&self, root: &Path, sink: &SharedSink) {
|
||||
@@ -415,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;
|
||||
}
|
||||
|
||||
@@ -261,6 +261,12 @@ fn supports_external_format(language: &LanguageConfig, tool: ExternalFormatter)
|
||||
}
|
||||
}
|
||||
|
||||
/// The entry of the formatters' language lists that covers `language`. MDX was part of Markdown
|
||||
/// and follows its entry, so lists saved before it had its own language keep formatting it.
|
||||
fn formatter_language(language: &str) -> &str {
|
||||
if language == "mdx" { "markdown" } else { language }
|
||||
}
|
||||
|
||||
/// The external formatter of a file, for a language with an external formatter.
|
||||
/// `forced` names the tool (Reformat with Prettier, oxfmt, Biome, Ruff, or Black). Ruff is
|
||||
/// the base formatter for Python, replaced by Black when configured or selected; Biome,
|
||||
@@ -295,7 +301,8 @@ fn external_tool(
|
||||
)))
|
||||
};
|
||||
}
|
||||
let enabled = |tool| settings.formatter(tool).languages.iter().any(|l| l == language.id.as_str());
|
||||
let id = formatter_language(language.id.as_str());
|
||||
let enabled = |tool| settings.formatter(tool).languages.iter().any(|l| l == id);
|
||||
if language.formatter.as_ref().is_some_and(|f| f.tool == "ruff") {
|
||||
return Ok(if enabled(Black) && (settings.black.prefer || black_configured(file)) {
|
||||
Some(Black)
|
||||
@@ -473,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,
|
||||
@@ -897,6 +993,24 @@ mod tests {
|
||||
external_tool(forced, language.as_ref(), file, settings)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mdx_follows_the_markdown_entry_of_saved_language_lists() {
|
||||
// Saved before MDX had its own language: the whole list, with no `mdx` in it.
|
||||
let old: ide_core::settings::Settings = serde_json::from_str(
|
||||
r#"{"languages":{"prettier":{"languages":["markdown","css"]},"oxfmt":{"languages":["css"]}}}"#,
|
||||
)
|
||||
.unwrap();
|
||||
let file = Path::new("/project/docs/intro.mdx");
|
||||
assert_eq!(tool(None, "mdx", file, &old.languages).unwrap(), Some(Prettier));
|
||||
let mut no_markdown = old.languages.clone();
|
||||
no_markdown.prettier.languages.retain(|l| l != "markdown");
|
||||
assert_eq!(tool(None, "mdx", file, &no_markdown).unwrap(), None);
|
||||
let mut oxfmt = old.languages.clone();
|
||||
oxfmt.oxfmt.languages.push("markdown".into());
|
||||
oxfmt.oxfmt.prefer = true;
|
||||
assert_eq!(tool(None, "mdx", file, &oxfmt).unwrap(), Some(Oxfmt));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_settings_use_ruff_for_python_and_prettier_for_the_web() {
|
||||
let settings = LanguagesSettings::default();
|
||||
@@ -1300,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();
|
||||
|
||||
@@ -0,0 +1,340 @@
|
||||
//! Project-scoped GitHub CLI (`gh`) account selection and opt-in `GH_TOKEN` injection.
|
||||
//!
|
||||
//! Each project may pin a GitHub login in `vcs.github.account` (`.openidea/settings.toml`) or
|
||||
//! leave it empty (`Automatic`). `Automatic` leaves `gh`'s own behaviour untouched—no `GH_TOKEN`
|
||||
//! is injected into [`ide_core::project_env`] and opening a project makes no GitHub API calls.
|
||||
//! When the user inspects GitHub settings or Pull Requests with multiple `gh` keyring accounts,
|
||||
//! OpenIDEA probes the repository remote (`owner/repo`) to suggest a matching non-active account
|
||||
//! ("Use <login> for this project"). Only when an account is explicitly chosen does OpenIDEA
|
||||
//! resolve its token into [`ide_core::project_env`] (for both `project.root` and `.worktrees`).
|
||||
|
||||
use crate::Project;
|
||||
use ide_agent::GhAuthAccount;
|
||||
use ide_core::cli_process::{CliTool, Decoding};
|
||||
use parking_lot::Mutex;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
use std::sync::LazyLock;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
const AMBIENT_GH_VARS: [&str; 3] = ["COPILOT_GITHUB_TOKEN", "GH_TOKEN", "GITHUB_TOKEN"];
|
||||
const GH_TOOL: CliTool = CliTool::new("gh", Decoding::Utf8Lossy);
|
||||
const LOCAL_TIMEOUT: Duration = Duration::from_secs(5);
|
||||
const PROBE_TIMEOUT: Duration = Duration::from_secs(6);
|
||||
const CACHE_TTL: Duration = Duration::from_secs(10 * 60);
|
||||
|
||||
/// GitHub CLI accounts available on this machine and which one applies to the project.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct GhProjectAccountStatus {
|
||||
pub gh_installed: bool,
|
||||
pub accounts: Vec<GhAuthAccount>,
|
||||
/// Value of `vcs.github.account` (`""` = Automatic).
|
||||
pub configured_account: String,
|
||||
/// Account login currently used (`configured_account` if signed in, else `gh`'s active account).
|
||||
pub effective_account: Option<String>,
|
||||
/// Non-active `gh` account with access to this project's GitHub remote when `configured_account` is empty.
|
||||
pub suggested_account: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct CachedAutoAccount {
|
||||
login: Option<String>,
|
||||
at: Instant,
|
||||
}
|
||||
|
||||
type AutoCacheMap = HashMap<(String, Vec<String>), CachedAutoAccount>;
|
||||
static AUTO_CACHE: LazyLock<Mutex<AutoCacheMap>> = LazyLock::new(|| Mutex::new(HashMap::new()));
|
||||
|
||||
pub(crate) fn is_valid_github_login(login: &str) -> bool {
|
||||
let bytes = login.as_bytes();
|
||||
!bytes.is_empty()
|
||||
&& bytes.len() <= 39
|
||||
&& bytes[0].is_ascii_alphanumeric()
|
||||
&& bytes.iter().all(|b| b.is_ascii_alphanumeric() || *b == b'-' || *b == b'_')
|
||||
}
|
||||
|
||||
fn find_gh_executable() -> Option<PathBuf> {
|
||||
ide_core::tool_path::find_gh_executable()
|
||||
}
|
||||
|
||||
fn clean_gh_command(program: &Path, args: &[&str]) -> Command {
|
||||
let mut cmd = Command::new(program);
|
||||
cmd.current_dir(std::env::temp_dir())
|
||||
.args(args)
|
||||
.env("GH_PROMPT_DISABLED", "1")
|
||||
.env("GH_NO_UPDATE_NOTIFIER", "1")
|
||||
.env("NO_COLOR", "1")
|
||||
.env("CLICOLOR", "0");
|
||||
// Strip ambient tokens by setting empty then removing after `prepare`: `CliTool::run` calls
|
||||
// `ide_core::process::prepare`, which skips keys already present in `cmd.get_envs()`.
|
||||
for key in AMBIENT_GH_VARS {
|
||||
cmd.env_remove(key);
|
||||
}
|
||||
cmd
|
||||
}
|
||||
|
||||
fn gh_token_for_account(program: &Path, login: &str) -> Option<String> {
|
||||
if !is_valid_github_login(login) {
|
||||
return None;
|
||||
}
|
||||
let cmd = clean_gh_command(program, &["auth", "token", "--hostname", "github.com", "--user", login]);
|
||||
let out = GH_TOOL.run(cmd, LOCAL_TIMEOUT, None).ok().filter(|o| o.success)?;
|
||||
let token = out.stdout.trim();
|
||||
(!token.is_empty()).then(|| token.to_owned())
|
||||
}
|
||||
|
||||
/// Access level of an account for a specific `owner/repo` on `github.com`.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
|
||||
enum RepoAccess {
|
||||
None = 0,
|
||||
Read = 1,
|
||||
Push = 2,
|
||||
}
|
||||
|
||||
fn probe_repo_access(program: &Path, token: &str, owner: &str, name: &str) -> RepoAccess {
|
||||
let endpoint = format!("repos/{owner}/{name}");
|
||||
let mut cmd =
|
||||
clean_gh_command(program, &["api", "--hostname", "github.com", &endpoint, "--jq", ".permissions.push"]);
|
||||
cmd.env("GH_TOKEN", token);
|
||||
let Ok(out) = GH_TOOL.run(cmd, PROBE_TIMEOUT, None) else {
|
||||
return RepoAccess::None;
|
||||
};
|
||||
if !out.success {
|
||||
return RepoAccess::None;
|
||||
}
|
||||
if out.stdout.trim() == "true" { RepoAccess::Push } else { RepoAccess::Read }
|
||||
}
|
||||
|
||||
fn pick_best_account(candidates: &[(GhAuthAccount, RepoAccess)]) -> Option<(&GhAuthAccount, bool)> {
|
||||
let active_access =
|
||||
candidates.iter().find(|(a, _)| a.active).map(|(_, access)| *access).unwrap_or(RepoAccess::None);
|
||||
// Prefer higher RepoAccess; break ties in favor of the globally active account.
|
||||
let (best, best_access) = candidates.iter().max_by_key(|(acc, access)| (*access, acc.active))?;
|
||||
if *best_access == RepoAccess::None {
|
||||
// Nobody could reach the repo (offline or SSO required): keep the active account.
|
||||
return candidates.iter().find(|(a, _)| a.active).or_else(|| candidates.first()).map(|(a, _)| (a, false));
|
||||
}
|
||||
let auto_detected = !best.active && *best_access > active_access;
|
||||
Some((best, auto_detected))
|
||||
}
|
||||
|
||||
/// Parses `github.com` `(owner, repo)` from HTTPS, SSH, or SCP-style remote URLs.
|
||||
pub(crate) fn parse_github_owner_repo(url: &str) -> Option<(String, String)> {
|
||||
let url = url.trim();
|
||||
let path = if let Some(rest) =
|
||||
url.strip_prefix("https://github.com/").or_else(|| url.strip_prefix("http://github.com/"))
|
||||
{
|
||||
rest
|
||||
} else if let Some(rest) = url.strip_prefix("ssh://") {
|
||||
rest.strip_prefix("[email protected]/").or_else(|| rest.strip_prefix("github.com/"))?
|
||||
} else {
|
||||
url.strip_prefix("[email protected]:")?
|
||||
};
|
||||
let path = path.trim_matches('/');
|
||||
let (owner, rest) = path.split_once('/')?;
|
||||
let repo = rest.split('/').next()?;
|
||||
let repo = repo.strip_suffix(".git").unwrap_or(repo);
|
||||
if owner.is_empty() || repo.is_empty() {
|
||||
return None;
|
||||
}
|
||||
Some((owner.to_owned(), repo.to_owned()))
|
||||
}
|
||||
|
||||
fn primary_github_repo(project: &Project) -> Option<(String, String)> {
|
||||
let repos = project.repos();
|
||||
let mut ordered = Vec::new();
|
||||
if let Some(primary) = repos.primary() {
|
||||
ordered.push(primary);
|
||||
}
|
||||
for repo in repos.all() {
|
||||
if ordered.first().is_none_or(|p| p.root() != repo.root()) {
|
||||
ordered.push(repo);
|
||||
}
|
||||
}
|
||||
for repo in ordered {
|
||||
let Ok(mut remotes) = repo.remotes() else { continue };
|
||||
remotes.sort_by_key(|r| r.name != "origin");
|
||||
for remote in remotes {
|
||||
let url = remote.resolved_url.as_deref().unwrap_or(&remote.url);
|
||||
if let Some(coords) = parse_github_owner_repo(url) {
|
||||
return Some(coords);
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn auto_detect_account(program: &Path, accounts: &[GhAuthAccount], owner: &str, repo: &str) -> Option<(String, bool)> {
|
||||
// Fast path: the repository owner matches one of the signed-in accounts directly.
|
||||
if let Some(matched) = accounts.iter().find(|a| a.login.eq_ignore_ascii_case(owner)) {
|
||||
return Some((matched.login.clone(), !matched.active));
|
||||
}
|
||||
let key_repo = format!("{}/{}", owner.to_ascii_lowercase(), repo.to_ascii_lowercase());
|
||||
let key_logins: Vec<String> = accounts.iter().map(|a| format!("{}:{}", a.login, a.active)).collect();
|
||||
let cache_key = (key_repo, key_logins);
|
||||
if let Some(cached) = AUTO_CACHE.lock().get(&cache_key).cloned()
|
||||
&& cached.at.elapsed() < CACHE_TTL
|
||||
{
|
||||
if let Some(login) = cached.login {
|
||||
let is_active = accounts.iter().any(|a| a.login == login && a.active);
|
||||
return Some((login, !is_active));
|
||||
}
|
||||
return None;
|
||||
}
|
||||
|
||||
let tokens: Vec<(GhAuthAccount, Option<String>)> =
|
||||
accounts.iter().map(|acc| (acc.clone(), gh_token_for_account(program, &acc.login))).collect();
|
||||
let results: Vec<(GhAuthAccount, RepoAccess)> = std::thread::scope(|s| {
|
||||
let handles: Vec<_> = tokens
|
||||
.into_iter()
|
||||
.map(|(acc, token)| {
|
||||
s.spawn(move || {
|
||||
let access = match token {
|
||||
Some(tok) => probe_repo_access(program, &tok, owner, repo),
|
||||
None => RepoAccess::None,
|
||||
};
|
||||
(acc, access)
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
handles.into_iter().filter_map(|h| h.join().ok()).collect()
|
||||
});
|
||||
let picked = pick_best_account(&results).map(|(acc, auto)| (acc.login.clone(), auto));
|
||||
AUTO_CACHE
|
||||
.lock()
|
||||
.insert(cache_key, CachedAutoAccount { login: picked.as_ref().map(|(l, _)| l.clone()), at: Instant::now() });
|
||||
picked
|
||||
}
|
||||
|
||||
/// Resolves global status when no project is open.
|
||||
pub fn global_status(configured_account: String) -> GhProjectAccountStatus {
|
||||
let configured_account = configured_account.trim().to_owned();
|
||||
let (gh_installed, accounts) = ide_agent::gh_authenticated_accounts();
|
||||
let effective_account = if !configured_account.is_empty() {
|
||||
accounts.iter().any(|a| a.login == configured_account).then(|| configured_account.clone())
|
||||
} else {
|
||||
accounts.iter().find(|a| a.active).or_else(|| accounts.first()).map(|a| a.login.clone())
|
||||
};
|
||||
GhProjectAccountStatus { gh_installed, accounts, configured_account, effective_account, suggested_account: None }
|
||||
}
|
||||
|
||||
/// Applies the project's explicit `vcs.github.account` setting to [`ide_core::project_env`]
|
||||
/// without making any network requests. `Automatic` (`""`) clears any injected `GH_TOKEN` so
|
||||
/// processes use `gh`'s own behaviour.
|
||||
pub fn apply_to_project(project: &Project) {
|
||||
if project.light || !project.is_trusted() {
|
||||
clear_project_env(project);
|
||||
return;
|
||||
}
|
||||
let configured_account = project.settings.effective().vcs.github.account.trim().to_owned();
|
||||
if configured_account.is_empty() {
|
||||
set_project_token(project, None);
|
||||
return;
|
||||
}
|
||||
let token = find_gh_executable().and_then(|program| gh_token_for_account(&program, &configured_account));
|
||||
set_project_token(project, token);
|
||||
}
|
||||
|
||||
/// Applies the project's explicit account setting and returns the full account status,
|
||||
/// probing the project's GitHub remote to suggest a matching non-active `gh` account when
|
||||
/// `vcs.github.account` is `Automatic` (`""`) and multiple `gh` accounts are signed in.
|
||||
pub fn project_status(project: &Project) -> GhProjectAccountStatus {
|
||||
let configured_account = project.settings.effective().vcs.github.account.trim().to_owned();
|
||||
if project.light || !project.is_trusted() {
|
||||
clear_project_env(project);
|
||||
return GhProjectAccountStatus { configured_account, ..GhProjectAccountStatus::default() };
|
||||
}
|
||||
apply_to_project(project);
|
||||
let Some(program) = find_gh_executable() else {
|
||||
return GhProjectAccountStatus { configured_account, ..GhProjectAccountStatus::default() };
|
||||
};
|
||||
let (gh_installed, accounts) = ide_agent::gh_authenticated_accounts();
|
||||
let active_login = accounts.iter().find(|a| a.active).or_else(|| accounts.first()).map(|a| a.login.clone());
|
||||
|
||||
let effective_account = if !configured_account.is_empty() {
|
||||
accounts.iter().any(|a| a.login == configured_account).then(|| configured_account.clone())
|
||||
} else {
|
||||
active_login
|
||||
};
|
||||
|
||||
let suggested_account = if configured_account.is_empty() && accounts.len() >= 2 {
|
||||
primary_github_repo(project)
|
||||
.and_then(|(owner, repo)| auto_detect_account(&program, &accounts, &owner, &repo))
|
||||
.and_then(|(login, non_active_match)| non_active_match.then_some(login))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
GhProjectAccountStatus { gh_installed, accounts, configured_account, effective_account, suggested_account }
|
||||
}
|
||||
|
||||
fn set_project_token(project: &Project, token: Option<String>) {
|
||||
let os_tok = token.map(std::ffi::OsString::from);
|
||||
let changed_root = ide_core::project_env::set_github_token(&project.root, os_tok.clone());
|
||||
let changed_wt = ide_core::project_env::set_github_token(project.agents.worktrees_dir(), os_tok);
|
||||
if changed_root || changed_wt {
|
||||
project.agents.notify_mcp_servers_changed();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn clear_project_env(project: &Project) {
|
||||
ide_core::project_env::remove_all(&project.root);
|
||||
ide_core::project_env::remove_all(project.agents.worktrees_dir());
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn parses_github_owner_repo_across_https_ssh_and_scp_remotes() {
|
||||
assert_eq!(
|
||||
parse_github_owner_repo("https://github.com/l0ng-ai/openidea.git"),
|
||||
Some(("l0ng-ai".into(), "openidea".into()))
|
||||
);
|
||||
assert_eq!(
|
||||
parse_github_owner_repo("[email protected]:acme-corp/payments.git"),
|
||||
Some(("acme-corp".into(), "payments".into()))
|
||||
);
|
||||
assert_eq!(parse_github_owner_repo("ssh://[email protected]/alice/demo/"), Some(("alice".into(), "demo".into())));
|
||||
assert_eq!(parse_github_owner_repo("https://gitlab.com/foo/bar.git"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validates_github_logins_against_flag_injection() {
|
||||
assert!(is_valid_github_login("alice"));
|
||||
assert!(is_valid_github_login("alice-work"));
|
||||
assert!(is_valid_github_login("l0ng-ai"));
|
||||
assert!(!is_valid_github_login(""));
|
||||
assert!(!is_valid_github_login("--hostname"));
|
||||
assert!(!is_valid_github_login("bad space"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn picks_account_with_push_or_private_access_and_preserves_active_on_ties() {
|
||||
let personal = GhAuthAccount { login: "alice".into(), active: true };
|
||||
let work = GhAuthAccount { login: "alice-work".into(), active: false };
|
||||
|
||||
// Private org repo: personal gets 404 (None), work gets Push -> auto-detects work.
|
||||
let private_org = vec![(personal.clone(), RepoAccess::None), (work.clone(), RepoAccess::Push)];
|
||||
let (picked, auto) = pick_best_account(&private_org).unwrap();
|
||||
assert_eq!(picked.login, "alice-work");
|
||||
assert!(auto);
|
||||
|
||||
// Public org repo: personal gets Read, work gets Push -> auto-detects work.
|
||||
let public_org = vec![(personal.clone(), RepoAccess::Read), (work.clone(), RepoAccess::Push)];
|
||||
let (picked, auto) = pick_best_account(&public_org).unwrap();
|
||||
assert_eq!(picked.login, "alice-work");
|
||||
assert!(auto);
|
||||
|
||||
// Third-party public repo: both get Read -> keeps active personal account without auto flag.
|
||||
let oss = vec![(personal.clone(), RepoAccess::Read), (work.clone(), RepoAccess::Read)];
|
||||
let (picked, auto) = pick_best_account(&oss).unwrap();
|
||||
assert_eq!(picked.login, "alice");
|
||||
assert!(!auto);
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
|
||||
@@ -12,6 +12,7 @@ pub mod diagnostics_store;
|
||||
mod direnv;
|
||||
pub mod environment;
|
||||
mod formatter;
|
||||
pub mod github_auth;
|
||||
mod java_runtime;
|
||||
mod kotlin_bridge;
|
||||
pub mod mcp;
|
||||
@@ -124,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.
|
||||
@@ -137,6 +139,8 @@ pub struct Host {
|
||||
pub web: ide_web::WebServer,
|
||||
/// The HTTP proxy's saved password (see `proxy.rs`).
|
||||
proxy_password: ide_ssh::secrets::SecretFile,
|
||||
/// Tokens of the Jupyter servers notebooks run on, by server base URL.
|
||||
jupyter_tokens: ide_ssh::secrets::SecretFile,
|
||||
/// The proxy password when it could not be saved (no credential store).
|
||||
proxy_session_password: Mutex<Option<String>>,
|
||||
/// Values of agents' and MCP servers' environment variables and headers (see `agent_secrets.rs`).
|
||||
@@ -151,6 +155,8 @@ pub struct Host {
|
||||
project_requests: RwLock<HashMap<String, Vec<RequestId>>>,
|
||||
/// Shutdowns of projects closed with [`Host::close_project_detached`].
|
||||
closing: parking_lot::Mutex<Vec<DetachedClose>>,
|
||||
/// Why this host's agents are shutting down when [`Host::shutdown`] runs.
|
||||
agent_shutdown_reason: parking_lot::Mutex<ide_agent::AgentShutdownReason>,
|
||||
/// One open at a time per window (see [`Host::opening`]).
|
||||
open_locks: parking_lot::Mutex<HashMap<String, Arc<parking_lot::Mutex<()>>>>,
|
||||
}
|
||||
@@ -166,6 +172,7 @@ struct ShutdownWork {
|
||||
lsp: Option<Arc<ide_lsp::LspManager>>,
|
||||
debug: Option<(Arc<ide_dap::DebugManager>, String, Option<std::path::PathBuf>)>,
|
||||
agents: Vec<Arc<ide_agent::AgentManager>>,
|
||||
agent_reason: ide_agent::AgentShutdownReason,
|
||||
terminals: Option<ide_terminal::DetachedTerminals>,
|
||||
processes: Option<ide_run::DetachedProcessKills>,
|
||||
retired: Option<Arc<Project>>,
|
||||
@@ -233,6 +240,7 @@ impl Host {
|
||||
trust: std::sync::Arc::new(trust::TrustStore::load(&config_dir, &data_dir)),
|
||||
mcp_approvals: Arc::new(trust::McpServerApprovals::load(&data_dir)),
|
||||
proxy_password: ide_ssh::secrets::SecretFile::new(data_dir.join("proxy-password.json")),
|
||||
jupyter_tokens: ide_ssh::secrets::SecretFile::new(data_dir.join("jupyter-tokens.json")),
|
||||
proxy_session_password: Mutex::default(),
|
||||
agent_secrets: Arc::new(agent_secrets::AgentSecrets::new(&data_dir)),
|
||||
remote: Arc::new(ide_remote::RemoteService::new(ssh.clone(), data_dir.join("remote"))),
|
||||
@@ -254,6 +262,7 @@ impl Host {
|
||||
heap_requests: Default::default(),
|
||||
rebase_editors: Default::default(),
|
||||
java_build: Default::default(),
|
||||
metrics_sampler: Default::default(),
|
||||
languages,
|
||||
syntax,
|
||||
config_dir,
|
||||
@@ -267,6 +276,7 @@ impl Host {
|
||||
requests: Default::default(),
|
||||
project_requests: RwLock::default(),
|
||||
closing: Default::default(),
|
||||
agent_shutdown_reason: parking_lot::Mutex::new(ide_agent::AgentShutdownReason::Quit),
|
||||
open_locks: Default::default(),
|
||||
};
|
||||
host.apply_proxy();
|
||||
@@ -353,13 +363,18 @@ impl Host {
|
||||
}
|
||||
}
|
||||
|
||||
/// Records the shutdown reason reported on interrupted agent turns when [`Self::shutdown`] runs.
|
||||
pub fn set_agent_shutdown_reason(&self, reason: ide_agent::AgentShutdownReason) {
|
||||
*self.agent_shutdown_reason.lock() = reason;
|
||||
}
|
||||
|
||||
/// Closes `window`'s project and waits until its language servers, kernels and
|
||||
/// debug sessions have shut down. Never call this on the UI event-loop thread:
|
||||
/// the shutdown runs on the async runtime, whose workers may themselves be
|
||||
/// waiting for the event loop (IPC responses, window queries). Use
|
||||
/// [`Self::close_project_detached`] there.
|
||||
pub fn close_project(&self, window: &str) {
|
||||
if let Some(shutdown) = self.begin_close(window) {
|
||||
if let Some(shutdown) = self.begin_close(window, ide_agent::AgentShutdownReason::WindowClose) {
|
||||
self.wait_blocking(shutdown.handle);
|
||||
}
|
||||
}
|
||||
@@ -368,7 +383,12 @@ impl Host {
|
||||
/// the window; its workers finish shutting down in the background, and
|
||||
/// [`Self::shutdown_notebooks_on_exit`] waits for them before the process exits.
|
||||
pub fn close_project_detached(&self, window: &str) {
|
||||
if let Some(shutdown) = self.begin_close(window) {
|
||||
self.close_project_detached_with(window, ide_agent::AgentShutdownReason::WindowClose);
|
||||
}
|
||||
|
||||
/// Like [`Self::close_project_detached`], recording `reason` on any interrupted agent turn.
|
||||
pub fn close_project_detached_with(&self, window: &str, reason: ide_agent::AgentShutdownReason) {
|
||||
if let Some(shutdown) = self.begin_close(window, reason) {
|
||||
let mut closing = self.closing.lock();
|
||||
closing.retain(|entry| !entry.handle.is_finished());
|
||||
closing.push(shutdown);
|
||||
@@ -378,18 +398,26 @@ impl Host {
|
||||
/// Detaches the project from `window` synchronously so the caller (including the UI
|
||||
/// event-loop thread) never blocks on disk I/O or process shutdown, and returns the
|
||||
/// background handle that stops its workers, agents, terminals and processes.
|
||||
fn begin_close(&self, window: &str) -> Option<DetachedClose> {
|
||||
fn begin_close(&self, window: &str, agent_reason: ide_agent::AgentShutdownReason) -> Option<DetachedClose> {
|
||||
self.mcp_reports.forget_window(window);
|
||||
self.mcp_requests.forget_window(window);
|
||||
self.mcp_agent_runs.forget_window(window);
|
||||
self.debugger.forget_breakpoints(self.owner_window(window));
|
||||
self.external_logs.write().remove(self.owner_window(window));
|
||||
for request in self.project_requests.write().remove(self.owner_window(window)).unwrap_or_default() {
|
||||
let owner = self.owner_window(window);
|
||||
let (project, requests) = {
|
||||
// A request registering after the drain must not resolve the old project.
|
||||
let mut project_requests = self.project_requests.write();
|
||||
let mut projects = self.projects.write();
|
||||
(projects.remove(window), project_requests.remove(owner).unwrap_or_default())
|
||||
};
|
||||
for request in requests {
|
||||
self.cancel_request(request);
|
||||
}
|
||||
// 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)?;
|
||||
let project = project?;
|
||||
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);
|
||||
@@ -419,6 +447,7 @@ impl Host {
|
||||
self.environment.project_closed();
|
||||
if self.windows_for_root(&project.root).is_empty() {
|
||||
self.environment.direnv_closed(&project.root);
|
||||
crate::github_auth::clear_project_env(&project);
|
||||
}
|
||||
}
|
||||
if let Some(bridge) = &project.kotlin_bridge {
|
||||
@@ -448,6 +477,7 @@ impl Host {
|
||||
// Debug sessions under the root belong to windows: a project served without one starts none.
|
||||
debug: Some((self.debugger.clone(), window.to_owned(), (!background).then(|| project.root.clone()))),
|
||||
agents: vec![project.agents.clone()],
|
||||
agent_reason,
|
||||
terminals: Some(terminals),
|
||||
processes: Some(processes),
|
||||
retired: Some(project),
|
||||
@@ -475,9 +505,10 @@ impl Host {
|
||||
}
|
||||
let agents = (!work.agents.is_empty()).then(|| {
|
||||
let agents = work.agents;
|
||||
let reason = work.agent_reason;
|
||||
std::thread::spawn(move || {
|
||||
for manager in agents {
|
||||
manager.shutdown();
|
||||
manager.shutdown_with(reason);
|
||||
}
|
||||
})
|
||||
});
|
||||
@@ -568,6 +599,10 @@ impl Host {
|
||||
/// kernels and agents, but no longer than [`EXIT_SHUTDOWN_WAIT`], so a runtime worker
|
||||
/// stuck on the event loop cannot keep the process from exiting.
|
||||
pub fn shutdown_notebooks_on_exit(&self) {
|
||||
self.shutdown_notebooks_on_exit_with(ide_agent::AgentShutdownReason::Quit);
|
||||
}
|
||||
|
||||
pub fn shutdown_notebooks_on_exit_with(&self, agent_reason: ide_agent::AgentShutdownReason) {
|
||||
let projects = self.projects();
|
||||
let mut pending: Vec<_> = self.closing.lock().drain(..).map(|entry| entry.handle).collect();
|
||||
if !projects.is_empty() {
|
||||
@@ -577,6 +612,7 @@ impl Host {
|
||||
lsp: None,
|
||||
debug: None,
|
||||
agents: projects.iter().map(|project| project.agents.clone()).collect(),
|
||||
agent_reason,
|
||||
terminals: None,
|
||||
processes: None,
|
||||
retired: None,
|
||||
@@ -646,6 +682,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();
|
||||
@@ -664,7 +701,8 @@ impl Host {
|
||||
}
|
||||
project.documents.clear_workspace_edit_history();
|
||||
project.notebooks.stop_admission();
|
||||
project.agents.shutdown();
|
||||
let reason = *self.agent_shutdown_reason.lock();
|
||||
project.agents.shutdown_with(reason);
|
||||
}
|
||||
let stop_processes = async {
|
||||
for project in &projects {
|
||||
@@ -701,6 +739,12 @@ impl Host {
|
||||
self.requests.begin(id)
|
||||
}
|
||||
|
||||
/// Settings › Tools › Download Mirrors › Use only the configured package registries: nothing
|
||||
/// is fetched from public package registries the user's tools weren't pointed at.
|
||||
pub fn configured_registries_only(&self) -> bool {
|
||||
self.global_settings.effective().tool_downloads.configured_registries_only
|
||||
}
|
||||
|
||||
pub fn begin_project_request(&self, window: &str, id: RequestId) -> CancellationToken {
|
||||
let token = self.begin_project_read_request(window, id);
|
||||
if self.project(window).is_ok_and(|p| !p.is_trusted()) {
|
||||
@@ -754,6 +798,25 @@ impl Host {
|
||||
let exe = self.global_settings.read_effective(|s| s.vcs.git.executable.trim().to_owned());
|
||||
ide_vcs::set_default_git_executable((!exe.is_empty()).then(|| Path::new(&exe)));
|
||||
}
|
||||
|
||||
/// Settings › Version Control › Git › Enable Git integration, as it applies to `window`
|
||||
/// (its project's effective value, the global one without a project).
|
||||
pub fn git_enabled(&self, window: &str) -> bool {
|
||||
match self.project(window) {
|
||||
Ok(project) => project.git_enabled(),
|
||||
Err(_) => self.global_settings.read_effective(|s| s.vcs.git.enabled),
|
||||
}
|
||||
}
|
||||
|
||||
/// Fails while Git integration is switched off for `window`: commands that start git
|
||||
/// outside the project's repositories (clone, init, an external log) check it first.
|
||||
pub fn ensure_git_enabled(&self, window: &str) -> IdeResult<()> {
|
||||
if self.git_enabled(window) {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(ide_core::IdeError::unavailable("Git integration is disabled in Settings › Version Control › Git"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -778,4 +841,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;
|
||||
}
|
||||
}
|
||||
}
|
||||
Loaded 100 of 1674 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Заблокувати користувача