дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-11-29 13:52:36 +02:00
Порівняти коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
1e3d555c25 | ||
|
|
fe87cc59e8 |
No files matched your search
@@ -1,13 +0,0 @@
|
||||
# Nextest runs tests in separate processes. These three tests write the same Windows clipboard.
|
||||
[test-groups.windows-clipboard]
|
||||
max-threads = 1
|
||||
|
||||
[[profile.default.overrides]]
|
||||
filter = '''
|
||||
package(=ide-clipboard) & (
|
||||
test(=tests::text_reads_on_one_thread_do_not_corrupt_the_heap)
|
||||
| test(=tests::text_reads_taking_turns_do_not_corrupt_the_heap)
|
||||
| test(=tests::concurrent_text_reads_do_not_corrupt_the_heap)
|
||||
)
|
||||
'''
|
||||
test-group = "windows-clipboard"
|
||||
@@ -30,7 +30,6 @@ 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"
|
||||
@@ -108,7 +107,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|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$)'
|
||||
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|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
|
||||
|
||||
Створено
+49
-69
@@ -4154,7 +4154,7 @@ checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
|
||||
|
||||
[[package]]
|
||||
name = "ide-agent"
|
||||
version = "0.1.55"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"blake3",
|
||||
@@ -4182,7 +4182,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-analysis"
|
||||
version = "0.1.55"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"ast-grep-core",
|
||||
"ide-core",
|
||||
@@ -4194,11 +4194,10 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-android"
|
||||
version = "0.1.55"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"specta",
|
||||
"tempfile",
|
||||
"which",
|
||||
@@ -4206,7 +4205,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-build"
|
||||
version = "0.1.55"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"chardetng",
|
||||
@@ -4224,7 +4223,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-cli"
|
||||
version = "0.1.55"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"serde",
|
||||
@@ -4238,7 +4237,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-clipboard"
|
||||
version = "0.1.55"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"gtk",
|
||||
"objc2 0.6.5",
|
||||
@@ -4249,7 +4248,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-command"
|
||||
version = "0.1.55"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"heck 0.5.0",
|
||||
"proc-macro2",
|
||||
@@ -4260,7 +4259,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-core"
|
||||
version = "0.1.55"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"dirs 6.0.0",
|
||||
@@ -4282,7 +4281,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-coverage"
|
||||
version = "0.1.55"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-run",
|
||||
@@ -4295,7 +4294,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-dap"
|
||||
version = "0.1.55"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"futures",
|
||||
@@ -4324,7 +4323,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-db"
|
||||
version = "0.1.55"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"bb8",
|
||||
@@ -4363,7 +4362,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-docker"
|
||||
version = "0.1.55"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"serde",
|
||||
@@ -4376,7 +4375,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-drag-out"
|
||||
version = "0.1.55"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"gtk",
|
||||
"objc2 0.6.5",
|
||||
@@ -4390,7 +4389,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-extension"
|
||||
version = "0.1.55"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"blake3",
|
||||
@@ -4410,7 +4409,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-flutter"
|
||||
version = "0.1.55"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"ide-android",
|
||||
"ide-core",
|
||||
@@ -4421,7 +4420,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-fonts"
|
||||
version = "0.1.55"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"objc2-core-foundation",
|
||||
"objc2-core-text",
|
||||
@@ -4433,7 +4432,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-github"
|
||||
version = "0.1.55"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-vcs",
|
||||
@@ -4445,7 +4444,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-heap"
|
||||
version = "0.1.55"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"ide-core",
|
||||
@@ -4464,7 +4463,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-host"
|
||||
version = "0.1.55"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"blake3",
|
||||
@@ -4491,7 +4490,6 @@ dependencies = [
|
||||
"ide-docker",
|
||||
"ide-extension",
|
||||
"ide-flutter",
|
||||
"ide-github",
|
||||
"ide-heap",
|
||||
"ide-http",
|
||||
"ide-index",
|
||||
@@ -4547,15 +4545,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-http"
|
||||
version = "0.1.55"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"http",
|
||||
"hyper-util",
|
||||
"ide-core",
|
||||
"ide-vfs",
|
||||
"objc2-cf-network",
|
||||
"objc2-core-foundation",
|
||||
"parking_lot 0.12.5",
|
||||
"reqwest",
|
||||
"rustls",
|
||||
@@ -4570,7 +4564,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-index"
|
||||
version = "0.1.55"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"criterion",
|
||||
@@ -4593,7 +4587,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jdwp"
|
||||
version = "0.1.55"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"ide-jvm-inspect",
|
||||
"proptest",
|
||||
@@ -4605,7 +4599,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jsonrpc"
|
||||
version = "0.1.55"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"ide-core",
|
||||
@@ -4621,7 +4615,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jvm-attach"
|
||||
version = "0.1.55"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"tempfile",
|
||||
@@ -4630,7 +4624,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jvm-inspect"
|
||||
version = "0.1.55"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"futures",
|
||||
"serde",
|
||||
@@ -4641,7 +4635,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-language"
|
||||
version = "0.1.55"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"criterion",
|
||||
@@ -4700,7 +4694,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-lsp"
|
||||
version = "0.1.55"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"dunce",
|
||||
@@ -4730,7 +4724,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-mcp"
|
||||
version = "0.1.55"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"dunce",
|
||||
@@ -4749,24 +4743,20 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-notebook"
|
||||
version = "0.1.55"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"futures",
|
||||
"ide-core",
|
||||
"ide-http",
|
||||
"ide-vfs",
|
||||
"jupyter-protocol",
|
||||
"jupyter-zmq-client",
|
||||
"libc",
|
||||
"parking_lot 0.12.5",
|
||||
"reqwest",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"specta",
|
||||
"specta-typescript",
|
||||
"tempfile",
|
||||
"tokio",
|
||||
"tokio-tungstenite",
|
||||
"uuid",
|
||||
"windows-sys 0.61.2",
|
||||
"zeromq",
|
||||
@@ -4774,7 +4764,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-plugin"
|
||||
version = "0.1.55"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dunce",
|
||||
@@ -4796,7 +4786,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-profiler"
|
||||
version = "0.1.55"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-jvm-attach",
|
||||
@@ -4810,7 +4800,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-remote"
|
||||
version = "0.1.55"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"futures",
|
||||
@@ -4830,9 +4820,8 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-run"
|
||||
version = "0.1.55"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dunce",
|
||||
"encoding_rs",
|
||||
"ide-build",
|
||||
@@ -4856,7 +4845,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-scaffold"
|
||||
version = "0.1.55"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-tools",
|
||||
@@ -4872,7 +4861,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-sdk"
|
||||
version = "0.1.55"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"dirs 6.0.0",
|
||||
@@ -4898,7 +4887,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-search"
|
||||
version = "0.1.55"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"encoding_rs",
|
||||
@@ -4919,7 +4908,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-spell"
|
||||
version = "0.1.55"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"parking_lot 0.12.5",
|
||||
@@ -4932,7 +4921,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-ssh"
|
||||
version = "0.1.55"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"flate2",
|
||||
@@ -4957,7 +4946,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-streams"
|
||||
version = "0.1.55"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-language",
|
||||
@@ -4970,7 +4959,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-syntax"
|
||||
version = "0.1.55"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-language",
|
||||
@@ -4985,7 +4974,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-terminal"
|
||||
version = "0.1.55"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"libc",
|
||||
@@ -4999,7 +4988,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-text"
|
||||
version = "0.1.55"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"ide-core",
|
||||
@@ -5012,9 +5001,8 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-tools"
|
||||
version = "0.1.55"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"flate2",
|
||||
"hex",
|
||||
"http",
|
||||
@@ -5036,7 +5024,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-vcs"
|
||||
version = "0.1.55"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dunce",
|
||||
@@ -5058,7 +5046,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-vfs"
|
||||
version = "0.1.55"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"chardetng",
|
||||
"dunce",
|
||||
@@ -5085,7 +5073,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-web"
|
||||
version = "0.1.55"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"ide-core",
|
||||
@@ -5101,7 +5089,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-workspace"
|
||||
version = "0.1.55"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dunce",
|
||||
@@ -6332,15 +6320,6 @@ dependencies = [
|
||||
"objc2-quartz-core 0.3.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "objc2-cf-network"
|
||||
version = "0.3.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4b4c9e30e636e2cd7d7414f320af2e0aa86f686adfc6f1bbe50b92366e4309c8"
|
||||
dependencies = [
|
||||
"objc2-core-foundation",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "objc2-cloud-kit"
|
||||
version = "0.2.2"
|
||||
@@ -6749,7 +6728,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "openidea"
|
||||
version = "0.1.55"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"blake3",
|
||||
@@ -6769,6 +6748,7 @@ dependencies = [
|
||||
"ide-drag-out",
|
||||
"ide-extension",
|
||||
"ide-fonts",
|
||||
"ide-github",
|
||||
"ide-host",
|
||||
"ide-http",
|
||||
"ide-jsonrpc",
|
||||
|
||||
+1
-2
@@ -5,7 +5,7 @@ members = ["crates/*", "src-tauri"]
|
||||
exclude = ["sdk", "plugins"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.1.55"
|
||||
version = "0.1.54"
|
||||
edition = "2024"
|
||||
rust-version = "1.96"
|
||||
license = "Apache-2.0"
|
||||
@@ -24,7 +24,6 @@ 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" }
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
//! the agent reports them over ACP.
|
||||
|
||||
use crate::model::{
|
||||
AgentCommand, AgentCommandChoice, AgentCommandSource, AgentConfigOption, AgentConfigValue, AgentConfigVia,
|
||||
AgentCost, AgentLimit, AgentModelPricing, AgentTokens, AgentUsage,
|
||||
AgentCommand, AgentCommandSource, AgentConfigOption, AgentConfigValue, AgentConfigVia, AgentCost, AgentLimit,
|
||||
AgentModelPricing, AgentTokens, AgentUsage,
|
||||
};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
@@ -54,21 +54,6 @@ 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 {
|
||||
@@ -293,30 +278,11 @@ 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()
|
||||
@@ -688,7 +654,6 @@ 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);
|
||||
}
|
||||
@@ -698,30 +663,13 @@ 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": "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"}
|
||||
]
|
||||
}}
|
||||
{"name": "/init", "description": "Write CLAUDE.md", "input": null}
|
||||
]}),
|
||||
"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());
|
||||
|
||||
+183
-1376
File diff suppressed because it is too large.
Load diff
@@ -49,74 +49,6 @@ 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 {
|
||||
@@ -185,16 +117,6 @@ 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)]
|
||||
@@ -237,9 +159,6 @@ 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.
|
||||
@@ -336,14 +255,6 @@ 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 {
|
||||
@@ -354,9 +265,6 @@ 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)]
|
||||
@@ -381,9 +289,6 @@ 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)]
|
||||
@@ -391,16 +296,13 @@ 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`), or `"credits"` for AI-credit billing.
|
||||
/// ISO 4217 code, e.g. `USD`.
|
||||
pub currency: String,
|
||||
}
|
||||
|
||||
@@ -609,9 +511,6 @@ 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,
|
||||
|
||||
@@ -8,69 +8,43 @@ 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, choices: &[] },
|
||||
BuiltinCommandSpec { name: "plan", description: "Turn plan mode on or off.", hint: None },
|
||||
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, AgentCommandChoice, AgentCommandSource};
|
||||
use crate::{AgentCommand, AgentCommandSource};
|
||||
use commands::{BuiltinCommand, ParsedCommand};
|
||||
use ide_jsonrpc::{Framing, Handler, Peer, RpcError, codes};
|
||||
use parking_lot::Mutex;
|
||||
@@ -47,14 +47,6 @@ pub(crate) fn builtin_commands() -> Vec<AgentCommand> {
|
||||
description: command.description.to_owned(),
|
||||
hint: command.hint.map(str::to_owned),
|
||||
source: AgentCommandSource::Command,
|
||||
choices: command
|
||||
.choices
|
||||
.iter()
|
||||
.map(|(name, description)| AgentCommandChoice {
|
||||
name: (*name).to_owned(),
|
||||
description: (*description).to_owned(),
|
||||
})
|
||||
.collect(),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
@@ -2084,11 +2084,6 @@ fn skills_become_commands_with_their_invocation_names() {
|
||||
let commands = crate::config::commands_of(&update, "codex");
|
||||
assert!(commands.iter().all(|c| c.source == crate::AgentCommandSource::Skill));
|
||||
assert_eq!(commands[0].name, "$review");
|
||||
let builtins = builtin_commands();
|
||||
let goal = builtins.iter().find(|c| c.name == "goal").unwrap();
|
||||
assert_eq!(goal.choices.iter().map(|c| c.name.as_str()).collect::<Vec<_>>(), ["clear", "pause", "resume"]);
|
||||
let mcp = builtins.iter().find(|c| c.name == "mcp").unwrap();
|
||||
assert_eq!(mcp.choices.iter().map(|c| c.name.as_str()).collect::<Vec<_>>(), ["reconnect"]);
|
||||
assert!(skill_commands(&json!({"data": []})).unwrap()["availableCommands"].as_array().unwrap().is_empty());
|
||||
assert!(skill_commands(&json!({})).is_none());
|
||||
}
|
||||
|
||||
@@ -522,7 +522,6 @@ 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}"))),
|
||||
@@ -538,7 +537,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, "contextUsage": true } },
|
||||
"_meta": { "openidea": { "steer": true, "backgroundTasks": true } },
|
||||
},
|
||||
"agentInfo": {
|
||||
"name": "copilot",
|
||||
@@ -656,47 +655,12 @@ 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();
|
||||
@@ -771,152 +735,25 @@ 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 let Some(update) = usage_update {
|
||||
self.send_update(session_id, update);
|
||||
}
|
||||
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 }));
|
||||
}
|
||||
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();
|
||||
@@ -1233,21 +1070,6 @@ 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,11 +1,6 @@
|
||||
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;
|
||||
@@ -448,38 +443,6 @@ 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();
|
||||
@@ -832,275 +795,3 @@ 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,22 +2,11 @@
|
||||
//! 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::{BTreeMap, HashMap, HashSet};
|
||||
use std::collections::{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 {
|
||||
@@ -29,11 +18,6 @@ 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)]
|
||||
@@ -62,29 +46,6 @@ 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();
|
||||
@@ -278,75 +239,36 @@ impl EventTranslator {
|
||||
}
|
||||
}
|
||||
"session.usage_info" => {
|
||||
let used = u32_of(data, "currentTokens");
|
||||
let limit = u32_of(data, "tokenLimit").filter(|&n| n > 0).or(fallback_limit);
|
||||
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);
|
||||
if let (Some(used), Some(size)) = (used, limit) {
|
||||
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)));
|
||||
self.last_used_tokens = Some(used);
|
||||
out.updates.push((
|
||||
main_session.to_owned(),
|
||||
json!({ "sessionUpdate": "usage_update", "used": used, "size": 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 = 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) {
|
||||
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)) {
|
||||
self.last_used_tokens = Some(used);
|
||||
out.updates.push((main_session.to_owned(), self.usage_update(used, size)));
|
||||
out.updates.push((
|
||||
main_session.to_owned(),
|
||||
json!({ "sessionUpdate": "usage_update", "used": used, "size": 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" {
|
||||
@@ -620,34 +542,11 @@ 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": input,
|
||||
"input": hint.map(|h| json!({ "hint": h })),
|
||||
}));
|
||||
}
|
||||
for skill in skills_res.and_then(|v| v.get("skills")).and_then(Value::as_array).into_iter().flatten() {
|
||||
@@ -674,252 +573,9 @@ 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> {
|
||||
|
||||
@@ -209,7 +209,6 @@ impl Frontmatter {
|
||||
source,
|
||||
description: truncate(&description),
|
||||
hint: self.get("argument-hint").filter(|h| !h.is_empty()).map(str::to_owned),
|
||||
choices: Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -914,7 +913,6 @@ 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(),
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -940,7 +938,6 @@ mod tests {
|
||||
description: description.into(),
|
||||
hint: None,
|
||||
source: AgentCommandSource::Command,
|
||||
choices: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -67,8 +67,6 @@ struct FakeAgent {
|
||||
forks: Mutex<Vec<Value>>,
|
||||
/// The content blocks of each `session/prompt`.
|
||||
prompts: Mutex<Vec<Value>>,
|
||||
/// Queued errors returned on the next `session/prompt` calls before succeeding.
|
||||
prompt_errors: Mutex<VecDeque<(i64, String)>>,
|
||||
}
|
||||
|
||||
impl FakeAgent {
|
||||
@@ -200,11 +198,7 @@ impl Handler for FakeAgent {
|
||||
}
|
||||
"session/new" => {
|
||||
if self.hold_session_new.load(Ordering::Acquire) {
|
||||
let peer = self.latest();
|
||||
let deadline = std::time::Instant::now() + Duration::from_secs(5);
|
||||
while !peer.is_closed() && std::time::Instant::now() < deadline {
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
std::thread::sleep(Duration::from_secs(5));
|
||||
}
|
||||
if self.empty_config.load(Ordering::Acquire) {
|
||||
return Ok(json!({"sessionId": "s1"}));
|
||||
@@ -273,9 +267,6 @@ impl Handler for FakeAgent {
|
||||
}
|
||||
"session/prompt" => {
|
||||
self.prompts.lock().push(params.get("prompt").cloned().unwrap_or(Value::Null));
|
||||
if let Some(err) = self.prompt_errors.lock().pop_front() {
|
||||
return Err(err);
|
||||
}
|
||||
// `!` commands run since the last message come first; the message follows.
|
||||
let first = match params.pointer("/prompt/0/text").and_then(Value::as_str) {
|
||||
Some(t) if t.starts_with("<bash-input>") => 1,
|
||||
@@ -286,10 +277,6 @@ impl Handler for FakeAgent {
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or_default()
|
||||
.to_owned();
|
||||
if text.starts_with("The previous turn was interrupted because ") {
|
||||
self.say(&session, "resumed cleanly");
|
||||
return Ok(json!({"stopReason": "end_turn"}));
|
||||
}
|
||||
if text.starts_with("<send_user_message_question_reply>") {
|
||||
self.say(&session, "answer received");
|
||||
return Ok(json!({"stopReason": "end_turn"}));
|
||||
@@ -470,9 +457,8 @@ impl Handler for FakeAgent {
|
||||
return Ok(json!({ "stopReason": "end_turn" }));
|
||||
}
|
||||
if text == "wait" {
|
||||
// Works until cancelled or the client closes the connection.
|
||||
let peer = self.latest();
|
||||
while !peer.is_closed() && !self.calls.lock().iter().any(|c| c == "session/cancel") {
|
||||
// Works until cancelled.
|
||||
while !self.calls.lock().iter().any(|c| c == "session/cancel") {
|
||||
std::thread::sleep(Duration::from_millis(5));
|
||||
}
|
||||
return Ok(json!({"stopReason": "cancelled"}));
|
||||
@@ -653,7 +639,7 @@ async fn saved_conversation_reads_do_not_start_or_load_the_agent() {
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::NeedsInput).await;
|
||||
shut_down(&mgr, &agent).await;
|
||||
mgr.shutdown();
|
||||
let restored_agent = Arc::new(FakeAgent::default());
|
||||
let restored = manager(tmp.path(), restored_agent.clone());
|
||||
// Listing the tasks leaves the conversation on disk until something asks for it.
|
||||
@@ -672,8 +658,7 @@ async fn saved_conversation_reads_do_not_start_or_load_the_agent() {
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn an_archived_task_keeps_no_command_list_and_completes_the_known_one() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
project_root: None,
|
||||
@@ -694,7 +679,7 @@ async fn an_archived_task_keeps_no_command_list_and_completes_the_known_one() {
|
||||
mgr.archive(&task.id).unwrap();
|
||||
assert!(snapshot(&mgr).commands.is_empty());
|
||||
assert!(names(mgr.commands("claude", Some(&task.id)).await.unwrap()).contains(&"review".to_owned()));
|
||||
shut_down(&mgr, &agent).await;
|
||||
mgr.shutdown();
|
||||
|
||||
// A list saved with an archived task (by an earlier version) isn't read back.
|
||||
let other = tempfile::tempdir().unwrap();
|
||||
@@ -710,66 +695,6 @@ async fn an_archived_task_keeps_no_command_list_and_completes_the_known_one() {
|
||||
restored.shutdown();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn archiving_a_task_keeps_the_permission_answer_that_is_settling() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
let shut_down = ShutDown(&mgr);
|
||||
let (published, mut requests) = tokio::sync::mpsc::unbounded_channel();
|
||||
mgr.subscribe_as(
|
||||
"",
|
||||
Arc::new(move |event| {
|
||||
if let AgentEvent::Entry { task, entry: AgentEntry::Permission { id, chosen: None, .. }, .. } = event {
|
||||
let _ = published.send((task, id));
|
||||
}
|
||||
}),
|
||||
);
|
||||
let task = mgr
|
||||
.create(NewAgentTask { prompt: text("hello"), provider: "claude".into(), ..Default::default() })
|
||||
.await
|
||||
.unwrap();
|
||||
// The status becomes visible before the request has enqueued its initial delivery.
|
||||
let (owner, permission) = tokio::time::timeout(Duration::from_secs(5), requests.recv())
|
||||
.await
|
||||
.expect("permission request was never published")
|
||||
.unwrap();
|
||||
assert_eq!(owner, task.id);
|
||||
let handle = mgr.task(&task.id).unwrap();
|
||||
let answered = |e: &AgentEntry| matches!(e, AgentEntry::Permission { chosen: Some(name), .. } if name == "Allow");
|
||||
|
||||
let status_at_answer = tokio::task::block_in_place(|| {
|
||||
// Pause delivery of the changed entry so archive runs before the reply handler returns.
|
||||
let _delivery = handle.dirty.lock();
|
||||
mgr.respond(&task.id, permission, Some("yes".into())).unwrap();
|
||||
let deadline = std::time::Instant::now() + Duration::from_secs(5);
|
||||
let status = loop {
|
||||
let s = handle.state.lock();
|
||||
if s.history.conversation.main.entries.iter().any(answered) {
|
||||
break s.task.status;
|
||||
}
|
||||
drop(s);
|
||||
assert!(std::time::Instant::now() < deadline, "permission answer was never recorded");
|
||||
std::thread::sleep(Duration::from_millis(1));
|
||||
};
|
||||
mgr.archive(&task.id).unwrap();
|
||||
status
|
||||
});
|
||||
tokio::time::timeout(Duration::from_secs(5), async {
|
||||
while handle.state.lock().busy {
|
||||
tokio::time::sleep(Duration::from_millis(5)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("the archived turn did not finish");
|
||||
drop(shut_down);
|
||||
|
||||
let restored = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
assert_eq!(restored.task(&task.id).unwrap().state.lock().task.status, AgentStatus::Archived);
|
||||
assert!(restored.entries(&task.id, None).unwrap().iter().any(answered));
|
||||
assert_eq!(status_at_answer, AgentStatus::Running, "the recorded answer must finish the wait for input");
|
||||
restored.shutdown();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_conversation_that_cannot_be_read_is_never_saved_over() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
@@ -788,7 +713,7 @@ async fn a_conversation_that_cannot_be_read_is_never_saved_over() {
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::NeedsInput).await;
|
||||
shut_down(&mgr, &agent).await;
|
||||
mgr.shutdown();
|
||||
// In a store of its own: a late save of the first manager can't touch it.
|
||||
let name = format!("{}.json", task.id);
|
||||
let mut file: Value =
|
||||
@@ -827,7 +752,7 @@ async fn an_ephemeral_task_is_not_saved_and_asks_for_an_unsaved_session() {
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::NeedsInput).await;
|
||||
assert_eq!(agent.calls.lock().iter().any(|c| c == "ephemeral"), ephemeral);
|
||||
shut_down(&mgr, &agent).await;
|
||||
mgr.shutdown();
|
||||
// The caller never deleted it (its window closed): only a saved task comes back.
|
||||
let restored = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
assert_eq!(restored.task(&task.id).is_ok(), !ephemeral);
|
||||
@@ -1356,7 +1281,6 @@ async fn builtin_commands_only_fill_verified_gaps_and_preserve_advertised_metada
|
||||
description: "Agent supplied description".into(),
|
||||
hint: Some("instructions".into()),
|
||||
source: AgentCommandSource::Command,
|
||||
choices: Vec::new(),
|
||||
};
|
||||
mgr.task(&task.id).unwrap().state.lock().task.commands = vec![advertised.clone()];
|
||||
// The task's provider wins over the caller's provider; metadata is not replaced.
|
||||
@@ -1389,19 +1313,6 @@ async fn wait_for(mgr: &AgentManager, id: &str, status: AgentStatus) {
|
||||
panic!("task never reached {status:?} (is {s:?})");
|
||||
}
|
||||
|
||||
/// Shuts `mgr` down and waits until `agent` has seen each of its connections end. A fake still
|
||||
/// waiting for an answer holds a blocking thread until its side reads that end; a test that
|
||||
/// returned first would drop the runtime, and the drop waits for that thread forever.
|
||||
async fn shut_down(mgr: &AgentManager, agent: &FakeAgent) {
|
||||
mgr.shutdown();
|
||||
let servers = agent.servers.lock().clone();
|
||||
for server in servers {
|
||||
tokio::time::timeout(Duration::from_secs(5), server.closed())
|
||||
.await
|
||||
.expect("the agent's side of the connection closes");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_task_runs_asks_for_permission_and_survives_a_restart() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
@@ -1880,185 +1791,6 @@ async fn shutdown_skips_rewriting_untouched_restored_tasks() {
|
||||
assert_eq!(saved_title(&dirty_path).as_deref(), Some("updated"));
|
||||
}
|
||||
|
||||
/// Closing a project while a turn is in flight must not let the killed turn wake up and
|
||||
/// mark the persisted task as `Failed` with "The agent process exited.".
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn shutdown_during_running_turn_does_not_mark_task_failed() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
prompt: text("wait"),
|
||||
provider: "claude".into(),
|
||||
isolation: Isolation::Local,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Running).await;
|
||||
for _ in 0..500 {
|
||||
if agent.calls.lock().iter().any(|c| c == "session/prompt") {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(5)).await;
|
||||
}
|
||||
assert!(agent.calls.lock().iter().any(|c| c == "session/prompt"));
|
||||
|
||||
mgr.shutdown();
|
||||
// Wait past TURN_GRACE so any unguarded Task::run continuation would have settled and failed.
|
||||
tokio::time::sleep(TURN_GRACE * 3).await;
|
||||
|
||||
let path = task_file(tmp.path(), &task.id);
|
||||
assert_eq!(saved_task(&path).map(|(status, _)| status), Some(serde_json::to_value(AgentStatus::Ready).unwrap()));
|
||||
|
||||
let restored = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
let restored_task = restored.task(&task.id).unwrap();
|
||||
assert_eq!(restored_task.state.lock().task.status, AgentStatus::Ready);
|
||||
assert_eq!(restored_task.state.lock().task.error, None);
|
||||
let entries = restored.entries(&task.id, None).unwrap();
|
||||
assert!(
|
||||
!entries.iter().any(|e| matches!(e, AgentEntry::Error { .. })),
|
||||
"shutdown must not append an exit error entry: {entries:?}"
|
||||
);
|
||||
assert!(
|
||||
entries.iter().any(|e| matches!(e, AgentEntry::User { text, done_ms: None, .. } if text == "wait")),
|
||||
"interrupted turn must not stamp a bogus completion timestamp: {entries:?}"
|
||||
);
|
||||
|
||||
restored.prompt(&task.id, text("again"), false).await.unwrap();
|
||||
wait_for(&restored, &task.id, AgentStatus::Ready).await;
|
||||
restored.shutdown();
|
||||
}
|
||||
|
||||
/// Shutting down while `open_session` is still mid-handshake kills the connecting peer
|
||||
/// immediately and leaves the task `Ready` rather than failing or leaking the process.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn shutdown_during_session_open_kills_connecting_peer_without_failing() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
agent.hold_session_new.store(true, Ordering::Release);
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
prompt: text("again"),
|
||||
provider: "claude".into(),
|
||||
isolation: Isolation::Local,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
for _ in 0..500 {
|
||||
if agent.calls.lock().iter().any(|c| c == "session/new") {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(5)).await;
|
||||
}
|
||||
assert!(agent.calls.lock().iter().any(|c| c == "session/new"));
|
||||
|
||||
mgr.shutdown();
|
||||
tokio::time::sleep(TURN_GRACE * 3).await;
|
||||
|
||||
assert!(agent.latest().is_closed(), "shutdown must kill the in-flight connecting peer");
|
||||
let handle = mgr.task(&task.id).unwrap();
|
||||
assert!(handle.live.lock().is_none(), "opening peer must not be published after shutdown");
|
||||
assert_eq!(handle.state.lock().task.status, AgentStatus::Ready);
|
||||
assert_eq!(handle.state.lock().task.error, None);
|
||||
|
||||
let restored = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
let restored_task = restored.task(&task.id).unwrap();
|
||||
assert_eq!(restored_task.state.lock().task.status, AgentStatus::Ready);
|
||||
assert_eq!(restored_task.state.lock().task.error, None);
|
||||
let entries = restored.entries(&task.id, None).unwrap();
|
||||
assert!(
|
||||
!entries.iter().any(|e| matches!(e, AgentEntry::Error { .. })),
|
||||
"shutdown during session open must not record an error: {entries:?}"
|
||||
);
|
||||
restored.shutdown();
|
||||
}
|
||||
|
||||
/// Shutting down while the agent is blocked on a permission prompt settles the pending
|
||||
/// permission as Cancelled and leaves the task `Ready` without an exit error.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn shutdown_during_permission_request_settles_without_failing() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
prompt: text("decide"),
|
||||
provider: "claude".into(),
|
||||
isolation: Isolation::Local,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::NeedsInput).await;
|
||||
|
||||
shut_down(&mgr, &agent).await;
|
||||
tokio::time::sleep(TURN_GRACE * 3).await;
|
||||
|
||||
let restored = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
let restored_task = restored.task(&task.id).unwrap();
|
||||
assert_eq!(restored_task.state.lock().task.status, AgentStatus::Ready);
|
||||
assert_eq!(restored_task.state.lock().task.error, None);
|
||||
let entries = restored.entries(&task.id, None).unwrap();
|
||||
assert!(
|
||||
!entries.iter().any(|e| matches!(e, AgentEntry::Error { .. })),
|
||||
"shutdown during permission prompt must not append an exit error: {entries:?}"
|
||||
);
|
||||
assert!(
|
||||
entries.iter().any(|e| matches!(e, AgentEntry::Permission { chosen: Some(c), .. } if c == "Cancelled")),
|
||||
"unanswered permission should be settled as Cancelled: {entries:?}"
|
||||
);
|
||||
restored.shutdown();
|
||||
}
|
||||
|
||||
/// Revoking and restoring project trust calls `shutdown()` on a manager that stays in use;
|
||||
/// interrupting a running turn must leave the manager ready to accept later prompts.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn manager_can_run_new_turns_after_shutdown_replaces_an_interrupted_turn() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
prompt: text("wait"),
|
||||
provider: "claude".into(),
|
||||
isolation: Isolation::Local,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Running).await;
|
||||
for _ in 0..500 {
|
||||
if agent.calls.lock().iter().any(|c| c == "session/prompt") {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(5)).await;
|
||||
}
|
||||
|
||||
mgr.shutdown();
|
||||
tokio::time::sleep(TURN_GRACE * 3).await;
|
||||
|
||||
let handle = mgr.task(&task.id).unwrap();
|
||||
assert_eq!(handle.state.lock().task.status, AgentStatus::Ready);
|
||||
assert!(!handle.state.lock().busy);
|
||||
|
||||
mgr.prompt(&task.id, text("again"), false).await.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
let entries = mgr.entries(&task.id, None).unwrap();
|
||||
assert!(
|
||||
entries.iter().any(|e| matches!(e, AgentEntry::Agent { text } if text == "second turn")),
|
||||
"follow-up turn on the same manager after shutdown should succeed: {entries:?}"
|
||||
);
|
||||
assert!(
|
||||
!entries.iter().any(|e| matches!(e, AgentEntry::Error { .. })),
|
||||
"no stale shutdown error should appear: {entries:?}"
|
||||
);
|
||||
mgr.shutdown();
|
||||
}
|
||||
|
||||
/// Archiving saves the task as it is, including changes nobody asked to be saved.
|
||||
#[tokio::test]
|
||||
async fn archiving_saves_the_task_before_it_returns() {
|
||||
@@ -3035,7 +2767,7 @@ async fn startup_warnings_survive_replay_and_restart_without_failing_the_task()
|
||||
let handle = mgr.task(&task.id).unwrap();
|
||||
handle.replaying.store(true, Ordering::Release);
|
||||
handle.turn_started.store(false, Ordering::Release);
|
||||
let client = Client::new(&handle, handle.shared.shutdown_epoch(), None);
|
||||
let client = Client::new(&handle, None);
|
||||
client.on_notification(WARNING_NOTIFICATION, json!({"message": "Project MCP config is disabled until trusted."}));
|
||||
client.on_notification(WARNING_NOTIFICATION, json!({"message": " "}));
|
||||
client.on_notification(WARNING_NOTIFICATION, json!({}));
|
||||
@@ -3071,8 +2803,7 @@ async fn persistent_project_trust_needs_confirmation_even_with_bypass() {
|
||||
let asking = {
|
||||
let handle = handle.clone();
|
||||
let params = params.clone();
|
||||
let epoch = handle.shared.shutdown_epoch();
|
||||
tokio::task::spawn_blocking(move || handle.ask_permission(¶ms, epoch))
|
||||
tokio::task::spawn_blocking(move || handle.ask_permission(¶ms))
|
||||
};
|
||||
wait_for(&mgr, &task.id, AgentStatus::NeedsInput).await;
|
||||
assert!(!asking.is_finished());
|
||||
@@ -3640,7 +3371,7 @@ fn retry_updates_become_a_countdown() {
|
||||
json!({"sessionUpdate": RETRY_UPDATE, "attempt": 2, "maxRetries": 10, "retryDelayMs": 1500, "error": ""});
|
||||
assert_eq!(
|
||||
retry_of(&update, 1000.0),
|
||||
Some(AgentRetry { attempt: 2, max_retries: Some(10), retry_at_ms: 2500.0, error: None, deadline_ms: None })
|
||||
Some(AgentRetry { attempt: 2, max_retries: Some(10), retry_at_ms: 2500.0, error: None })
|
||||
);
|
||||
assert_eq!(retry_of(&json!({"sessionUpdate": RETRY_UPDATE}), 0.0), None, "no attempt");
|
||||
}
|
||||
@@ -6324,477 +6055,3 @@ async fn workspace_roots_go_to_agents_that_take_them() {
|
||||
assert_eq!(mgr.shared.additional_directories(&takes, &worktree, Some(&api)), vec![web]);
|
||||
assert!(mgr.shared.additional_directories(&init(json!({})), &api, None).is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn shutdown_reasons_mark_only_in_flight_tasks_interrupted_and_keep_idle_tasks_clean() {
|
||||
for (shutdown_reason, expected) in [
|
||||
(AgentShutdownReason::WindowClose, InterruptionReason::WindowClose),
|
||||
(AgentShutdownReason::Quit, InterruptionReason::Quit),
|
||||
(AgentShutdownReason::Restart, InterruptionReason::Restart),
|
||||
(AgentShutdownReason::BackendUpgrade, InterruptionReason::BackendUpgrade),
|
||||
(AgentShutdownReason::BackendStop, InterruptionReason::BackendStop),
|
||||
] {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
let idle = mgr
|
||||
.create(NewAgentTask { prompt: text("again"), provider: "claude".into(), ..Default::default() })
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &idle.id, AgentStatus::Ready).await;
|
||||
mgr.mark_read(&idle.id).unwrap();
|
||||
|
||||
let active = mgr
|
||||
.create(NewAgentTask { prompt: text("wait"), provider: "claude".into(), ..Default::default() })
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &active.id, AgentStatus::Running).await;
|
||||
|
||||
mgr.shutdown_with(shutdown_reason);
|
||||
|
||||
let reopened = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
let tasks = reopened.subscribe_as("", Arc::new(|_| {}));
|
||||
let restored_idle = tasks.iter().find(|t| t.id == idle.id).unwrap();
|
||||
assert_eq!(restored_idle.status, AgentStatus::Ready);
|
||||
assert!(restored_idle.interrupted.is_none(), "idle keepalive task must not become interrupted");
|
||||
assert!(!restored_idle.unread);
|
||||
|
||||
let restored_active = tasks.iter().find(|t| t.id == active.id).unwrap();
|
||||
assert_eq!(restored_active.status, AgentStatus::Ready);
|
||||
assert!(restored_active.unread);
|
||||
let intr = restored_active.interrupted.as_deref().expect("active task marked interrupted");
|
||||
assert_eq!(intr.reason, expected);
|
||||
assert!(!intr.was_waiting_for_input);
|
||||
reopened.shutdown();
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn unexpected_exit_on_disk_tags_interrupted_lazily_without_rewriting_untouched_files() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let store = tmp.path().join("store");
|
||||
std::fs::create_dir_all(&store).unwrap();
|
||||
let crashed_running = json!({
|
||||
"task": {
|
||||
"id": "crash-run",
|
||||
"title": "Refactor auth",
|
||||
"provider": "claude",
|
||||
"model": "big",
|
||||
"status": "running",
|
||||
"isolation": "local",
|
||||
"cwd": tmp.path(),
|
||||
"branch": null,
|
||||
"base": null,
|
||||
"baseCommit": null,
|
||||
"error": null,
|
||||
"createdMs": 100.0,
|
||||
"updatedMs": 250.0,
|
||||
"config": [{"id": "mode", "name": "Mode", "category": "mode", "current": "ask", "via": "mode", "values": []}],
|
||||
"commands": [],
|
||||
"usage": null,
|
||||
"queue": [],
|
||||
"capabilities": {},
|
||||
"resetsMs": null,
|
||||
"retry": null
|
||||
},
|
||||
"sessionId": "s1",
|
||||
"entries": [
|
||||
{"type": "user", "text": "refactor", "attachments": [], "sentMs": 100.0, "doneMs": null, "steered": false},
|
||||
{"type": "tool", "id": "t1", "title": "cargo check", "kind": "execute", "status": "running", "locations": [], "output": null, "diffs": []}
|
||||
],
|
||||
"wanted": []
|
||||
});
|
||||
let crashed_input = json!({
|
||||
"task": {
|
||||
"id": "crash-input",
|
||||
"title": "Needs approval",
|
||||
"provider": "claude",
|
||||
"model": "big",
|
||||
"status": "needsInput",
|
||||
"isolation": "local",
|
||||
"cwd": tmp.path(),
|
||||
"branch": null,
|
||||
"base": null,
|
||||
"baseCommit": null,
|
||||
"error": null,
|
||||
"createdMs": 100.0,
|
||||
"updatedMs": 300.0,
|
||||
"config": [],
|
||||
"commands": [],
|
||||
"usage": null,
|
||||
"queue": [],
|
||||
"capabilities": {},
|
||||
"resetsMs": null,
|
||||
"retry": null
|
||||
},
|
||||
"sessionId": "s2",
|
||||
"entries": [],
|
||||
"wanted": []
|
||||
});
|
||||
let run_path = store.join("crash-run.json");
|
||||
let input_path = store.join("crash-input.json");
|
||||
let raw_run = serde_json::to_vec(&crashed_running).unwrap();
|
||||
std::fs::write(&run_path, &raw_run).unwrap();
|
||||
std::fs::write(&input_path, serde_json::to_vec(&crashed_input).unwrap()).unwrap();
|
||||
|
||||
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
// Conversations stay lazy on disk during startup.
|
||||
assert!(!mgr.task("crash-run").unwrap().state.lock().history.is_loaded());
|
||||
let tasks = mgr.subscribe_as("", Arc::new(|_| {}));
|
||||
let r = tasks.iter().find(|t| t.id == "crash-run").unwrap();
|
||||
assert_eq!(r.status, AgentStatus::Ready);
|
||||
assert!(r.unread);
|
||||
assert_eq!(r.interrupted.as_ref().unwrap().reason, InterruptionReason::UnexpectedExit);
|
||||
assert!(!r.interrupted.as_ref().unwrap().was_waiting_for_input);
|
||||
assert_eq!(r.interrupted.as_ref().unwrap().approval_mode.as_deref(), Some("mode=ask"));
|
||||
|
||||
let inp = tasks.iter().find(|t| t.id == "crash-input").unwrap();
|
||||
assert_eq!(inp.interrupted.as_ref().unwrap().reason, InterruptionReason::UnexpectedExit);
|
||||
assert!(inp.interrupted.as_ref().unwrap().was_waiting_for_input);
|
||||
|
||||
// Shutting down without touching the task does not eagerly load or rewrite its conversation file.
|
||||
mgr.shutdown();
|
||||
assert_eq!(std::fs::read(&run_path).unwrap(), raw_run);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn manual_resume_appends_recovery_turn_drains_queue_and_dismiss_clears_state() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
let task = mgr
|
||||
.create(NewAgentTask { prompt: text("wait"), provider: "claude".into(), ..Default::default() })
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Running).await;
|
||||
// Queue a follow-up message before window close.
|
||||
mgr.prompt(&task.id, text("again"), false).await.unwrap();
|
||||
mgr.shutdown_with(AgentShutdownReason::WindowClose);
|
||||
|
||||
let agent2 = Arc::new(FakeAgent::default());
|
||||
let mgr2 = manager(tmp.path(), agent2.clone());
|
||||
let resumed = mgr2.resume_all_interrupted().unwrap();
|
||||
assert_eq!(resumed, vec![task.id.clone()]);
|
||||
wait_for(&mgr2, &task.id, AgentStatus::Ready).await;
|
||||
|
||||
let snap = mgr2.task(&task.id).unwrap().state.lock().snapshot();
|
||||
assert!(snap.interrupted.is_none());
|
||||
assert!(snap.queue.is_empty(), "queued message drained after continuation turn");
|
||||
let entries = mgr2.entries(&task.id, None).unwrap();
|
||||
assert!(entries.iter().any(|e| matches!(
|
||||
e,
|
||||
AgentEntry::User { steered: false, recovery: Some(InterruptionReason::WindowClose), .. }
|
||||
)));
|
||||
assert!(entries.iter().any(|e| matches!(e, AgentEntry::Agent { text } if text == "resumed cleanly")));
|
||||
assert!(entries.iter().any(|e| matches!(e, AgentEntry::Agent { text } if text == "second turn")));
|
||||
|
||||
// Dismissing an interrupted task clears its interrupted & unread state without sending a prompt.
|
||||
let task2 = mgr2
|
||||
.create(NewAgentTask { prompt: text("wait"), provider: "claude".into(), ..Default::default() })
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr2, &task2.id, AgentStatus::Running).await;
|
||||
mgr2.shutdown_with(AgentShutdownReason::Quit);
|
||||
|
||||
let mgr3 = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
mgr3.dismiss_interrupted(&task2.id).unwrap();
|
||||
let snap2 = mgr3.task(&task2.id).unwrap().state.lock().snapshot();
|
||||
assert!(snap2.interrupted.is_none());
|
||||
assert!(!snap2.unread);
|
||||
mgr3.shutdown();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn interrupted_during_starting_before_session_new_resumes_original_prompt_without_duplicate() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let slow_agent = Arc::new(FakeAgent::default());
|
||||
slow_agent.hold_session_new.store(true, Ordering::Release);
|
||||
let mgr = manager(tmp.path(), slow_agent);
|
||||
let task = mgr
|
||||
.create(NewAgentTask { prompt: text("again"), provider: "claude".into(), ..Default::default() })
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Starting).await;
|
||||
mgr.shutdown_with(AgentShutdownReason::Restart);
|
||||
|
||||
let fast_agent = Arc::new(FakeAgent::default());
|
||||
let mgr2 = manager(tmp.path(), fast_agent.clone());
|
||||
mgr2.resume(&task.id).unwrap();
|
||||
wait_for(&mgr2, &task.id, AgentStatus::Ready).await;
|
||||
|
||||
let entries = mgr2.entries(&task.id, None).unwrap();
|
||||
let user_entries: Vec<_> = entries.iter().filter(|e| matches!(e, AgentEntry::User { .. })).collect();
|
||||
assert_eq!(user_entries.len(), 1, "original unsent prompt replayed without duplicating user entries");
|
||||
assert!(matches!(user_entries[0], AgentEntry::User { text, recovery: None, .. } if text == "again"));
|
||||
assert!(entries.iter().any(|e| matches!(e, AgentEntry::Agent { text } if text == "second turn")));
|
||||
mgr2.shutdown();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn explicit_user_cancel_settles_to_plain_ready_without_interrupted_marker() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
let task = mgr
|
||||
.create(NewAgentTask { prompt: text("wait"), provider: "claude".into(), ..Default::default() })
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Running).await;
|
||||
mgr.cancel(&task.id, None).unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
|
||||
let snap = mgr.task(&task.id).unwrap().state.lock().snapshot();
|
||||
assert!(snap.interrupted.is_none());
|
||||
assert!(!snap.unread);
|
||||
mgr.shutdown();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn reconcile_interrupted_enforces_policies_one_shot_flag_and_all_safety_guardrails() {
|
||||
use ide_core::settings::{NetworkRetryWindow, ResumeInterruptedPolicy};
|
||||
|
||||
// 1. Ask policy leaves regular interrupted tasks waiting, except one-shot auto_resume_once.
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
// Initialize git repo so worktree isolation works cleanly.
|
||||
std::process::Command::new("git").args(["init", "-b", "main"]).current_dir(tmp.path()).output().unwrap();
|
||||
std::fs::write(tmp.path().join("README.md"), "hi\n").unwrap();
|
||||
std::process::Command::new("git").args(["add", "."]).current_dir(tmp.path()).output().unwrap();
|
||||
std::process::Command::new("git")
|
||||
.args(["-c", "user.name=Test", "-c", "[email protected]", "commit", "-m", "init"])
|
||||
.current_dir(tmp.path())
|
||||
.output()
|
||||
.unwrap();
|
||||
|
||||
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
let wt_one_shot = mgr
|
||||
.create(NewAgentTask {
|
||||
prompt: text("wait"),
|
||||
provider: "claude".into(),
|
||||
isolation: Isolation::Worktree,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
let wt_manual = mgr
|
||||
.create(NewAgentTask {
|
||||
prompt: text("wait"),
|
||||
provider: "claude".into(),
|
||||
isolation: Isolation::Worktree,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
let needs_perm = mgr
|
||||
.create(NewAgentTask {
|
||||
prompt: text("decide"),
|
||||
provider: "claude".into(),
|
||||
isolation: Isolation::Worktree,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &wt_one_shot.id, AgentStatus::Running).await;
|
||||
wait_for(&mgr, &wt_manual.id, AgentStatus::Running).await;
|
||||
wait_for(&mgr, &needs_perm.id, AgentStatus::NeedsInput).await;
|
||||
|
||||
// Arm one-shot auto-resume on BOTH wt_one_shot and needs_perm; needs_perm must STILL refuse auto-resume!
|
||||
mgr.set_auto_resume_once(&[wt_one_shot.id.clone(), needs_perm.id.clone()], true);
|
||||
mgr.shutdown_with(AgentShutdownReason::WindowClose);
|
||||
|
||||
let mgr2 = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
mgr2.set_recovery_settings_hook(Arc::new(|| (NetworkRetryWindow::Hour1, ResumeInterruptedPolicy::Ask)));
|
||||
let report = mgr2.reconcile_interrupted();
|
||||
assert!(report.first_reconcile);
|
||||
assert_eq!(report.auto_resumed, vec![wt_one_shot.id.clone()]);
|
||||
assert!(report.interrupted.contains(&wt_manual.id));
|
||||
assert!(report.interrupted.contains(&needs_perm.id), "NeedsInput task must never auto-resume");
|
||||
// Second call on the same AgentManager instance is idempotent.
|
||||
let second = mgr2.reconcile_interrupted();
|
||||
assert!(!second.first_reconcile);
|
||||
assert!(second.auto_resumed.is_empty());
|
||||
wait_for(&mgr2, &wt_one_shot.id, AgentStatus::Ready).await;
|
||||
mgr2.shutdown();
|
||||
|
||||
// 2. Shared Local checkout contention: two interrupted Local tasks sharing cwd refuse auto-resume
|
||||
// even under Window policy, while isolated Worktree tasks auto-resume.
|
||||
let mgr3 = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
let local_a = mgr3
|
||||
.create(NewAgentTask {
|
||||
prompt: text("wait"),
|
||||
provider: "claude".into(),
|
||||
isolation: Isolation::Local,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
let local_b = mgr3
|
||||
.create(NewAgentTask {
|
||||
prompt: text("wait"),
|
||||
provider: "claude".into(),
|
||||
isolation: Isolation::Local,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr3, &local_a.id, AgentStatus::Running).await;
|
||||
wait_for(&mgr3, &local_b.id, AgentStatus::Running).await;
|
||||
mgr3.shutdown_with(AgentShutdownReason::Restart);
|
||||
|
||||
let mgr4 = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
mgr4.set_recovery_settings_hook(Arc::new(|| (NetworkRetryWindow::Hour1, ResumeInterruptedPolicy::Restart)));
|
||||
let contention_report = mgr4.reconcile_interrupted();
|
||||
assert!(
|
||||
!contention_report.auto_resumed.contains(&local_a.id) && !contention_report.auto_resumed.contains(&local_b.id),
|
||||
"two local tasks sharing a checkout must not race via auto-resume"
|
||||
);
|
||||
assert!(contention_report.interrupted.contains(&local_a.id));
|
||||
assert!(contention_report.interrupted.contains(&local_b.id));
|
||||
|
||||
// 3. Permission-mode drift exclusion: changing approval config blocks silent auto-resume.
|
||||
mgr4.dismiss_interrupted(&local_b.id).unwrap();
|
||||
{
|
||||
let handle = mgr4.task(&local_a.id).unwrap();
|
||||
{
|
||||
let mut s = handle.state.lock();
|
||||
if let Some(mode) = s.task.config.iter_mut().find(|o| o.category.as_deref() == Some("mode")) {
|
||||
mode.current = Some("bypass".into());
|
||||
} else {
|
||||
s.task.config.push(AgentConfigOption {
|
||||
id: "mode".into(),
|
||||
name: "Mode".into(),
|
||||
description: None,
|
||||
category: Some("mode".into()),
|
||||
current: Some("bypass".into()),
|
||||
default_value: None,
|
||||
via: AgentConfigVia::Mode,
|
||||
values: Vec::new(),
|
||||
});
|
||||
}
|
||||
}
|
||||
handle.persist();
|
||||
}
|
||||
mgr4.shutdown();
|
||||
|
||||
let mgr5 = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
mgr5.set_recovery_settings_hook(Arc::new(|| (NetworkRetryWindow::Hour1, ResumeInterruptedPolicy::Window)));
|
||||
let drift_report = mgr5.reconcile_interrupted();
|
||||
assert!(!drift_report.auto_resumed.contains(&local_a.id), "drifted approval mode must not auto-resume silently");
|
||||
mgr5.shutdown();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn transient_network_outage_probes_with_zero_prompts_and_auto_resumes_when_online() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
agent.prompt_errors.lock().push_back((codes::INTERNAL_ERROR, "network error: connection reset by peer".into()));
|
||||
|
||||
let online = Arc::new(AtomicBool::new(false));
|
||||
let probe_calls = Arc::new(AtomicU32::new(0));
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
mgr.set_network_probe_delays(40, 80);
|
||||
mgr.set_network_probe({
|
||||
let online = online.clone();
|
||||
let probe_calls = probe_calls.clone();
|
||||
move |_| {
|
||||
probe_calls.fetch_add(1, Ordering::SeqCst);
|
||||
online.load(Ordering::SeqCst)
|
||||
}
|
||||
});
|
||||
|
||||
let task = mgr
|
||||
.create(NewAgentTask { prompt: text("hello"), provider: "claude".into(), ..Default::default() })
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
// Wait until the task enters `Waiting for network` (`retry.deadline_ms.is_some()`).
|
||||
let deadline = tokio::time::Instant::now() + Duration::from_secs(5);
|
||||
loop {
|
||||
let snap = mgr.task(&task.id).unwrap().state.lock().snapshot();
|
||||
if snap.retry.as_ref().is_some_and(|r| r.deadline_ms.is_some()) {
|
||||
assert_eq!(snap.status, AgentStatus::Running);
|
||||
assert!(mgr.has_live_work(), "remote daemon must treat network-retry wait as live work");
|
||||
break;
|
||||
}
|
||||
assert!(tokio::time::Instant::now() < deadline, "did not enter network wait: {snap:?}");
|
||||
tokio::time::sleep(Duration::from_millis(15)).await;
|
||||
}
|
||||
|
||||
// Let several offline probes run: zero extra `session/prompt` calls may happen while offline.
|
||||
while probe_calls.load(Ordering::SeqCst) < 2 {
|
||||
tokio::time::sleep(Duration::from_millis(20)).await;
|
||||
}
|
||||
assert_eq!(agent.prompts.lock().len(), 1, "must not spend tokens or send prompts while offline");
|
||||
|
||||
// Restore connectivity and poke network (simulating browser `online` event).
|
||||
online.store(true, Ordering::SeqCst);
|
||||
mgr.poke_network();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
|
||||
let snap = mgr.task(&task.id).unwrap().state.lock().snapshot();
|
||||
assert!(snap.interrupted.is_none());
|
||||
assert!(snap.retry.is_none());
|
||||
assert_eq!(agent.prompts.lock().len(), 2);
|
||||
let entries = mgr.entries(&task.id, None).unwrap();
|
||||
assert!(entries.iter().any(|e| matches!(
|
||||
e,
|
||||
AgentEntry::User { steered: false, recovery: Some(InterruptionReason::NetworkTimeout), .. }
|
||||
)));
|
||||
assert!(entries.iter().any(|e| matches!(e, AgentEntry::Agent { text } if text == "resumed cleanly")));
|
||||
mgr.shutdown();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn network_outage_window_off_or_expired_degrades_to_interrupted_and_auth_errors_fail_fast() {
|
||||
use ide_core::settings::{NetworkRetryWindow, ResumeInterruptedPolicy};
|
||||
|
||||
// 1. Turning per-session recovery window to Off (`Some(0)`) during a network wait degrades immediately to Interrupted.
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
agent.prompt_errors.lock().push_back((codes::INTERNAL_ERROR, "ENOTFOUND api.anthropic.com".into()));
|
||||
let mgr = manager(tmp.path(), agent);
|
||||
mgr.set_network_probe_delays(500, 1000);
|
||||
mgr.set_network_probe(|_| false);
|
||||
|
||||
let task = mgr
|
||||
.create(NewAgentTask { prompt: text("hello"), provider: "claude".into(), ..Default::default() })
|
||||
.await
|
||||
.unwrap();
|
||||
let deadline = tokio::time::Instant::now() + Duration::from_secs(5);
|
||||
while !mgr.task(&task.id).unwrap().state.lock().snapshot().retry.as_ref().is_some_and(|r| r.deadline_ms.is_some()) {
|
||||
assert!(tokio::time::Instant::now() < deadline);
|
||||
tokio::time::sleep(Duration::from_millis(15)).await;
|
||||
}
|
||||
|
||||
mgr.set_recovery_window(&task.id, Some(0)).unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
let snap = mgr.task(&task.id).unwrap().state.lock().snapshot();
|
||||
assert_eq!(snap.interrupted.as_ref().unwrap().reason, InterruptionReason::NetworkTimeout);
|
||||
|
||||
// 2. Global `NetworkRetryWindow::Off` skips waiting and immediately marks NetworkTimeout Interrupted.
|
||||
let agent2 = Arc::new(FakeAgent::default());
|
||||
agent2.prompt_errors.lock().push_back((codes::INTERNAL_ERROR, "503 Service Unavailable".into()));
|
||||
let mgr2 = manager(tmp.path(), agent2);
|
||||
mgr2.set_recovery_settings_hook(Arc::new(|| (NetworkRetryWindow::Off, ResumeInterruptedPolicy::Ask)));
|
||||
let task2 = mgr2
|
||||
.create(NewAgentTask { prompt: text("hello"), provider: "claude".into(), ..Default::default() })
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr2, &task2.id, AgentStatus::Ready).await;
|
||||
let snap2 = mgr2.task(&task2.id).unwrap().state.lock().snapshot();
|
||||
assert_eq!(snap2.interrupted.as_ref().unwrap().reason, InterruptionReason::NetworkTimeout);
|
||||
|
||||
// 3. Non-network 401/400 errors fail fast to Failed without entering network retry.
|
||||
let agent3 = Arc::new(FakeAgent::default());
|
||||
agent3.prompt_errors.lock().push_back((codes::INTERNAL_ERROR, "400 Bad Request: invalid model parameter".into()));
|
||||
let mgr3 = manager(tmp.path(), agent3);
|
||||
let task3 = mgr3
|
||||
.create(NewAgentTask { prompt: text("hello"), provider: "claude".into(), ..Default::default() })
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr3, &task3.id, AgentStatus::Failed).await;
|
||||
let snap3 = mgr3.task(&task3.id).unwrap().state.lock().snapshot();
|
||||
assert!(snap3.interrupted.is_none());
|
||||
|
||||
mgr.shutdown();
|
||||
mgr2.shutdown();
|
||||
mgr3.shutdown();
|
||||
}
|
||||
@@ -645,7 +645,6 @@ mod tests {
|
||||
sent_ms: Some(sent),
|
||||
done_ms: None,
|
||||
steered: false,
|
||||
recovery: None,
|
||||
};
|
||||
let mut t = Timeline::default();
|
||||
t.push(user(1.0));
|
||||
@@ -667,7 +666,6 @@ 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 iOS Simulators and their logs for the Logcat tool window, driven through adb and simctl"
|
||||
description = "Android devices and logcat for the Logcat tool window, driven through the adb CLI"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
@@ -8,7 +8,6 @@ license.workspace = true
|
||||
[dependencies]
|
||||
ide-core.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
specta.workspace = true
|
||||
which = "8"
|
||||
|
||||
|
||||
@@ -1,199 +0,0 @@
|
||||
//! 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,11 +7,9 @@
|
||||
//!
|
||||
//! 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,7 +29,6 @@ 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};
|
||||
@@ -421,8 +420,7 @@ 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), one job per
|
||||
/// logical CPU unless the profile's build arguments choose a count. The directory and
|
||||
/// `CMakeCache.txt` yet, then `cmake --build` (`--clean-first` to rebuild). 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> {
|
||||
@@ -460,7 +458,6 @@ 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
|
||||
@@ -1511,15 +1508,14 @@ 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".to_owned(),
|
||||
format!("--build build --config Debug {jobs}"),
|
||||
"-S . -B build -DCMAKE_BUILD_TYPE=Debug -DCMAKE_EXPORT_COMPILE_COMMANDS=ON",
|
||||
"--build build --config Debug"
|
||||
],
|
||||
"an unconfigured project is configured first"
|
||||
);
|
||||
@@ -1528,7 +1524,7 @@ mod tests {
|
||||
plan(&cm, &BuildModel::default(), BuildKind::Rebuild, None, None, None, &CancellationToken::new()).unwrap();
|
||||
assert_eq!(
|
||||
args(&p),
|
||||
[format!("--build cmake-build-release --config Debug --clean-first {jobs}")],
|
||||
["--build cmake-build-release --config Debug --clean-first"],
|
||||
"a configured directory is reused"
|
||||
);
|
||||
let profile = CMakeProfile {
|
||||
|
||||
@@ -5,10 +5,8 @@
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
use std::collections::BTreeMap;
|
||||
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"];
|
||||
@@ -229,41 +227,9 @@ 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();
|
||||
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));
|
||||
}
|
||||
ide_core::project_roots::discover(root, &markers)
|
||||
}
|
||||
|
||||
fn wrapper(dir: &Path) -> String {
|
||||
@@ -540,23 +506,10 @@ pub fn linked_project_key(root: &Path, dir: &str) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// Linked build identities without reading their scripts, as of now (a sync, a build).
|
||||
/// Linked build identities without reading their scripts (also used by index hot paths).
|
||||
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 => discover(root).iter().map(|dir| rel(root, dir)).collect(),
|
||||
None => build_dirs(root).iter().map(|dir| rel(root, dir)).collect(),
|
||||
Some(dirs) => {
|
||||
let mut out = Vec::new();
|
||||
for dir in dirs {
|
||||
@@ -1094,27 +1047,6 @@ 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,16 +46,6 @@ 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 {
|
||||
@@ -701,8 +691,17 @@ impl JavaBuild<'_> {
|
||||
let out = model::output_root(self.cache, &top.key());
|
||||
let step = match top {
|
||||
Reactor::Maven(top) => {
|
||||
let selection = maven_project_selection(changed.iter().map(|(p, _, _)| *p));
|
||||
let mut extra = vec!["-q".to_owned(), "-pl".to_owned(), selection];
|
||||
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(",")];
|
||||
extra.push("resources:resources".into());
|
||||
if changed.iter().any(|(_, test, _)| *test) {
|
||||
extra.push("resources:testResources".into());
|
||||
|
||||
@@ -11,50 +11,6 @@ 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())?;
|
||||
@@ -183,10 +139,7 @@ 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)) => {
|
||||
let output = build_output_tail(&self.events.lock().unwrap());
|
||||
panic!("unsupported: {reason}\n{output}");
|
||||
}
|
||||
Ok(Built::Unsupported(reason)) => panic!("unsupported: {reason}"),
|
||||
Err(e) => panic!("{e:?}"),
|
||||
}
|
||||
}
|
||||
@@ -257,7 +210,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 t:app"), "{steps:?}");
|
||||
assert!(steps[0].contains("resources:resources") && steps[0].contains("-pl 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.
|
||||
|
||||
@@ -129,7 +129,7 @@ pub fn gradle_external_roots(
|
||||
cache_dir: &Path,
|
||||
settings: &ide_core::settings::GradleSettings,
|
||||
) -> Vec<PathBuf> {
|
||||
let builds = gradle::linked_dirs_cached(root, settings);
|
||||
let builds = gradle::linked_dirs(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_cached(root, settings)
|
||||
let reported = gradle::linked_dirs(root, settings)
|
||||
.iter()
|
||||
.flat_map(|dir| sync::reported_gradle_projects(&gradle::cache_dir(cache_dir, dir)).as_ref().clone())
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
@@ -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_Storage_FileSystem", "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_System_SystemInformation", "Win32_System_Threading"] }
|
||||
@@ -1,74 +0,0 @@
|
||||
//! 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"]));
|
||||
}
|
||||
}
|
||||
@@ -302,12 +302,6 @@ 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.
|
||||
@@ -328,9 +322,6 @@ 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,
|
||||
|
||||
@@ -4,7 +4,6 @@
|
||||
//! 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;
|
||||
@@ -19,7 +18,6 @@ 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;
|
||||
|
||||
@@ -1,53 +0,0 @@
|
||||
//! 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());
|
||||
}
|
||||
}
|
||||
@@ -52,8 +52,6 @@ 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.
|
||||
@@ -80,8 +78,6 @@ 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>>,
|
||||
@@ -138,19 +134,6 @@ 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>>)]
|
||||
@@ -190,9 +173,6 @@ impl Default for AgentSettings {
|
||||
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(),
|
||||
@@ -380,49 +360,6 @@ 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")]
|
||||
@@ -525,47 +462,6 @@ pub struct ToolDownloadSettings {
|
||||
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.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
@@ -717,10 +613,8 @@ 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(),
|
||||
}
|
||||
}
|
||||
@@ -740,17 +634,6 @@ 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 {
|
||||
@@ -979,8 +862,6 @@ 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.
|
||||
@@ -999,8 +880,6 @@ 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,
|
||||
@@ -1122,7 +1001,6 @@ 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(),
|
||||
@@ -1135,7 +1013,6 @@ 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,
|
||||
@@ -2122,19 +1999,6 @@ 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}}"#] {
|
||||
@@ -2296,21 +2160,6 @@ 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();
|
||||
|
||||
@@ -143,9 +143,6 @@ 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,
|
||||
@@ -204,7 +201,6 @@ pub struct GitSettings {
|
||||
impl Default for GitSettings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
enabled: true,
|
||||
annotate: GitAnnotateSettings::default(),
|
||||
inline_blame: false,
|
||||
inline_blame_clickable: true,
|
||||
@@ -409,24 +405,13 @@ 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 output window's result tabs.
|
||||
/// instead of in the Services view'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")]
|
||||
@@ -617,14 +602,10 @@ 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,
|
||||
@@ -657,12 +638,10 @@ 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(),
|
||||
@@ -762,14 +741,6 @@ mod tests {
|
||||
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,115 +0,0 @@
|
||||
//! 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));
|
||||
}
|
||||
}
|
||||
@@ -13,7 +13,6 @@ pub mod attach;
|
||||
mod cargo;
|
||||
pub mod connection;
|
||||
mod debugpy;
|
||||
mod disassembly;
|
||||
mod exception_classes;
|
||||
pub mod jdwp;
|
||||
mod js_cdp;
|
||||
@@ -21,14 +20,12 @@ 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::{AdapterIo, AdapterLauncher, AdapterSpec, ProcessLauncher};
|
||||
use adapter::{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};
|
||||
@@ -36,7 +33,6 @@ 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};
|
||||
@@ -49,11 +45,6 @@ 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 {
|
||||
@@ -163,12 +154,6 @@ 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`].
|
||||
@@ -235,10 +220,6 @@ 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)]
|
||||
@@ -263,10 +244,6 @@ 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`).
|
||||
@@ -629,11 +606,6 @@ 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),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -710,9 +682,6 @@ 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"),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -801,15 +770,9 @@ 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?;
|
||||
@@ -833,7 +796,6 @@ 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,
|
||||
})
|
||||
@@ -1116,51 +1078,6 @@ impl DebugManager {
|
||||
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
|
||||
}
|
||||
@@ -1196,7 +1113,6 @@ impl DebugManager {
|
||||
port,
|
||||
None,
|
||||
ide_core::CancellationToken::new(),
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.map(|_| ())
|
||||
@@ -1216,7 +1132,6 @@ impl DebugManager {
|
||||
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}`")));
|
||||
@@ -1224,16 +1139,10 @@ impl DebugManager {
|
||||
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 io = tokio::select! {
|
||||
biased;
|
||||
_ = cancel.cancelled() => return Err(IdeError::cancelled()),
|
||||
io = self.launcher.launch(spec.clone(), reuse_port) => io?,
|
||||
};
|
||||
let launch_after_configuration = io.launch_after_configuration && request == "launch";
|
||||
let stderr = io.stderr.clone();
|
||||
@@ -1246,7 +1155,6 @@ 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) {
|
||||
@@ -1366,7 +1274,7 @@ impl DebugManager {
|
||||
"supportsProgressReporting": true,
|
||||
// kotlin-lsp sends `invalidated` either way.
|
||||
"supportsInvalidatedEvent": is_kotlin_lsp,
|
||||
"supportsMemoryReferences": true,
|
||||
"supportsMemoryReferences": false,
|
||||
"supportsArgsCanBeInterpretedByShell": false,
|
||||
}),
|
||||
INIT_TIMEOUT,
|
||||
@@ -1470,7 +1378,6 @@ 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.
|
||||
@@ -1700,7 +1607,7 @@ impl DebugManager {
|
||||
breakpoints: Vec<Breakpoint>,
|
||||
) -> IdeResult<Vec<BreakpointState>> {
|
||||
let mut result: Option<Vec<BreakpointState>> = None;
|
||||
for s in self.configured_sessions(owner).into_iter().filter(|s| s.takes(&path)) {
|
||||
for s in self.configured_sessions(owner) {
|
||||
match s.send_breakpoints(&path, &breakpoints, None).await {
|
||||
Ok(states) => {
|
||||
result.get_or_insert(states);
|
||||
@@ -1824,7 +1731,6 @@ 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),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1962,7 +1868,6 @@ 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);
|
||||
@@ -2054,22 +1959,6 @@ 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",
|
||||
@@ -2081,7 +1970,7 @@ impl DebugManager {
|
||||
quirks.step_sent();
|
||||
}
|
||||
let ticket = session.suspended.ticket();
|
||||
let sent = session.conn.request_timeout(command, args, REQUEST_TIMEOUT).await;
|
||||
let sent = session.conn.request_timeout(command, json!({ "threadId": thread_id }), 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);
|
||||
@@ -2235,74 +2124,6 @@ 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)?))
|
||||
}
|
||||
|
||||
@@ -1,88 +0,0 @@
|
||||
//! 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");
|
||||
}
|
||||
}
|
||||
@@ -125,8 +125,6 @@ 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<()>,
|
||||
@@ -344,7 +342,6 @@ 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),
|
||||
@@ -428,14 +425,6 @@ 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,
|
||||
|
||||
@@ -6,7 +6,6 @@ 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;
|
||||
@@ -196,21 +195,6 @@ 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).
|
||||
@@ -258,8 +242,6 @@ impl Default for Script {
|
||||
empty_thread_responses: 0,
|
||||
accept: &[],
|
||||
custom: None,
|
||||
read_memory: false,
|
||||
disassemble: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -346,9 +328,6 @@ 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"},
|
||||
@@ -591,58 +570,7 @@ 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": [
|
||||
@@ -2024,146 +1952,6 @@ 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());
|
||||
@@ -4003,19 +3791,3 @@ 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,12 +1,11 @@
|
||||
//! 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, Set Value, the Memory View and the Disassembly view.
|
||||
//! Into, Reset Frame, Force Step Over, Force Run to Cursor and Set Value.
|
||||
//!
|
||||
//! 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` (whose loop function also has a `char msg[]` local, for
|
||||
//! the Memory View). Adapters not found on `PATH` are skipped.
|
||||
//! `rust/target/debug/demo` and `c/main`. Adapters not found on `PATH` are skipped.
|
||||
|
||||
use ide_core::event::DebugEvent;
|
||||
use ide_core::{DebugSessionId, IdeEvent, SharedSink};
|
||||
@@ -281,78 +280,6 @@ 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) {
|
||||
|
||||
@@ -1,13 +1,11 @@
|
||||
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, MutexGuard};
|
||||
use tokio::sync::Mutex;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct ClickhousePool(Arc<State>);
|
||||
@@ -20,17 +18,11 @@ struct State {
|
||||
database: String,
|
||||
settings: Vec<(String, String)>,
|
||||
read_only: bool,
|
||||
connect_timeout: Duration,
|
||||
startup_statements: Vec<String>,
|
||||
use_http_session: bool,
|
||||
session: SessionSlot,
|
||||
console_sessions: parking_lot::Mutex<HashMap<(String, String), Arc<SessionSlot>>>,
|
||||
session: Mutex<Session>,
|
||||
closed: CancellationToken,
|
||||
}
|
||||
|
||||
type SessionSlot = Mutex<Option<Session>>;
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
#[derive(Default)]
|
||||
struct Session {
|
||||
id: Option<String>,
|
||||
initialized: bool,
|
||||
@@ -40,7 +32,6 @@ 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 {
|
||||
@@ -53,7 +44,6 @@ 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") {
|
||||
@@ -67,14 +57,6 @@ 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 {
|
||||
@@ -107,7 +89,6 @@ 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")));
|
||||
@@ -155,126 +136,79 @@ impl ClickhousePool {
|
||||
database: database.into(),
|
||||
settings,
|
||||
read_only: source.read_only,
|
||||
connect_timeout: timeout,
|
||||
startup_statements: setup.statements,
|
||||
use_http_session,
|
||||
session: Mutex::new(None),
|
||||
console_sessions: parking_lot::Mutex::new(HashMap::new()),
|
||||
session: Mutex::new(Session {
|
||||
id: use_http_session.then(|| uuid::Uuid::new_v4().to_string()),
|
||||
..Session::default()
|
||||
}),
|
||||
closed: CancellationToken::new(),
|
||||
}));
|
||||
let cancel = CancellationToken::new();
|
||||
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,
|
||||
};
|
||||
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"));
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
*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);
|
||||
// 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())
|
||||
};
|
||||
tokio::pin!(initialize);
|
||||
tokio::select! {
|
||||
result = &mut initialize => {
|
||||
if result.is_err() {
|
||||
pool.close();
|
||||
}
|
||||
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();
|
||||
}
|
||||
|
||||
@@ -287,56 +221,19 @@ 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,
|
||||
workspace_bytes: Option<usize>,
|
||||
) -> RequestBuilder {
|
||||
fn request(&self, client: &Client, query_id: &str, max_rows: usize, session: &Session) -> 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 {
|
||||
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()),
|
||||
]);
|
||||
}
|
||||
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")]);
|
||||
@@ -364,70 +261,22 @@ 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 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, 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 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 client = self.client()?;
|
||||
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 started = Instant::now();
|
||||
let fetch = async {
|
||||
let mut response = request.send().await.map_err(request_error)?;
|
||||
let mut response = request.send().await.map_err(http_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);
|
||||
@@ -440,11 +289,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_prefix(response).await.map_err(request_error)?;
|
||||
let body = response.bytes().await.map_err(http_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(request_error)?;
|
||||
let body = response.bytes().await.map_err(http_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",
|
||||
@@ -453,7 +302,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(request_error)? {
|
||||
while let Some(chunk) = response.chunk().await.map_err(http_error)? {
|
||||
reader.push(&chunk)?;
|
||||
}
|
||||
reader.finish().map_err(|error| self.redact_error(error))?
|
||||
@@ -484,7 +333,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(
|
||||
@@ -496,66 +345,6 @@ 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())
|
||||
@@ -572,7 +361,7 @@ impl ClickhousePool {
|
||||
.get("X-ClickHouse-Exception-Code")
|
||||
.and_then(|value| value.to_str().ok())
|
||||
.map(str::to_owned);
|
||||
let body = response_prefix(response).await.map_err(http_error)?;
|
||||
let body = response.bytes().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 {
|
||||
@@ -601,17 +390,6 @@ 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
|
||||
@@ -818,13 +596,6 @@ 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 {
|
||||
@@ -1061,71 +832,6 @@ 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;
|
||||
@@ -1192,90 +898,6 @@ 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();
|
||||
@@ -1529,84 +1151,6 @@ 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,7 +1000,6 @@ 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(|_| ()),
|
||||
}
|
||||
}
|
||||
@@ -1330,71 +1329,6 @@ 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,7 +30,6 @@ pub(crate) struct Key {
|
||||
target: String,
|
||||
statement: String,
|
||||
schema: Option<String>,
|
||||
console: Option<(String, String)>,
|
||||
}
|
||||
|
||||
impl Key {
|
||||
@@ -39,14 +38,8 @@ 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.
|
||||
@@ -193,14 +186,6 @@ 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) {
|
||||
|
||||
@@ -1,416 +0,0 @@
|
||||
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']));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,103 +0,0 @@
|
||||
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,22 +2,21 @@
|
||||
//! can run driver-specific initialization. A project source may connect only with the
|
||||
//! settings its user last accepted in the dialog; the approval lives outside the project.
|
||||
use crate::local_settings::persist_local;
|
||||
use crate::{ConsoleId, DataSource, DbManager, QueryResult, ResultColumn};
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult, error::ErrorKind};
|
||||
use crate::{DataSource, DbManager, QueryResult, ResultColumn};
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use std::collections::HashMap;
|
||||
use std::io::{Cursor, Read};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use std::process::Stdio;
|
||||
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::timeout;
|
||||
use tokio::time::{Instant as Deadline, timeout_at};
|
||||
|
||||
mod bridge;
|
||||
mod ducklake;
|
||||
|
||||
use bridge::Bridge;
|
||||
const LIMIT: usize = 16 * 1024 * 1024;
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
@@ -80,13 +79,6 @@ 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()
|
||||
@@ -146,30 +138,6 @@ 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()))?;
|
||||
@@ -182,10 +150,7 @@ impl DbManager {
|
||||
&source.options,
|
||||
))
|
||||
.map_err(|e| IdeError::internal(e.to_string()))?;
|
||||
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) {
|
||||
if self.jdbc_password_isolated(source) {
|
||||
settings.extend_from_slice(b"\0jdbc-password");
|
||||
}
|
||||
Ok((
|
||||
@@ -199,70 +164,8 @@ impl DbManager {
|
||||
if source.driver != crate::DbDriver::Jdbc || source.plugin_owner.is_some() {
|
||||
return Err(IdeError::invalid("Expected a user-managed JDBC data source"));
|
||||
}
|
||||
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 })
|
||||
let (path, fingerprint) = self.jdbc_approval(source)?;
|
||||
persist_local(&path, fingerprint.as_bytes())
|
||||
}
|
||||
|
||||
pub(crate) async fn open_pool(
|
||||
@@ -271,109 +174,198 @@ 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;
|
||||
}
|
||||
let driver = self.approved_jdbc_driver(source, testing)?;
|
||||
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"));
|
||||
}
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
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>>,
|
||||
struct Bridge {
|
||||
stop: tokio::sync::oneshot::Sender<()>,
|
||||
exited: tokio::task::JoinHandle<()>,
|
||||
sequence: u64,
|
||||
input: ChildStdin,
|
||||
output: ChildStdout,
|
||||
}
|
||||
|
||||
pub struct JdbcPool {
|
||||
bridge: Arc<Bridge>,
|
||||
service: Session,
|
||||
consoles: parking_lot::Mutex<ConsoleSessions>,
|
||||
shared_connection: bool,
|
||||
bridge: Mutex<Option<Bridge>>,
|
||||
closed: CancellationToken,
|
||||
pub(crate) version: String,
|
||||
pub(crate) identifier_quote: String,
|
||||
}
|
||||
|
||||
/// Dropped futures and uncertain transport errors retire the connection they were using.
|
||||
struct ActiveRequest<'a> {
|
||||
pool: &'a JdbcPool,
|
||||
session: &'a Session,
|
||||
completed: bool,
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for ActiveRequest<'_> {
|
||||
fn drop(&mut self) {
|
||||
if !self.completed {
|
||||
self.pool.retire(self.session);
|
||||
// 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)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 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))
|
||||
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)
|
||||
};
|
||||
path.starts_with("file:")
|
||||
&& (path == "file::memory:" || option("mode") == Some("memory"))
|
||||
&& option("cache") != Some("shared")
|
||||
// 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")),
|
||||
}
|
||||
}
|
||||
|
||||
impl JdbcPool {
|
||||
@@ -383,12 +375,10 @@ impl JdbcPool {
|
||||
driver: DbJdbcDriver,
|
||||
cache: PathBuf,
|
||||
) -> IdeResult<Self> {
|
||||
if source.duck_lake.is_some() {
|
||||
return Err(IdeError::invalid("DuckLake catalogs require a DuckLake connection"));
|
||||
}
|
||||
driver.validate()?;
|
||||
let mut fields = vec![
|
||||
"open".to_string(),
|
||||
driver.class_name.clone(),
|
||||
driver.class_name,
|
||||
source.url.clone(),
|
||||
source.user.clone(),
|
||||
password.unwrap_or_default().to_owned(),
|
||||
@@ -400,93 +390,35 @@ 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 data = timeout(Duration::from_secs(30), bridge.exchange(0, &args, &cancel, &cancel))
|
||||
let result = tokio::time::timeout(Duration::from_secs(30), pool.request(&args, "", &cancel))
|
||||
.await
|
||||
.map_err(|_| IdeError::new(ErrorKind::TimedOut, "JDBC connection timed out"))??;
|
||||
let result = decode(&data.ok_or_else(IdeError::cancelled)?, "", 0.)?;
|
||||
.map_err(|_| IdeError::new(ide_core::error::ErrorKind::TimedOut, "JDBC connection timed out"))??;
|
||||
let mut metadata = result.rows.into_iter().next().unwrap_or_default().into_iter();
|
||||
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(),
|
||||
})
|
||||
pool.version = metadata.next().flatten().unwrap_or_else(|| "Connected".into());
|
||||
pool.identifier_quote = metadata.next().flatten().unwrap_or_default().trim().into();
|
||||
Ok(pool)
|
||||
}
|
||||
|
||||
pub(crate) async fn close(&self) {
|
||||
self.bridge.close().await;
|
||||
self.closed.cancel();
|
||||
if let Some(bridge) = self.bridge.lock().await.take() {
|
||||
bridge.close().await;
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn is_closed(&self) -> bool {
|
||||
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();
|
||||
}
|
||||
self.closed.is_cancelled()
|
||||
}
|
||||
|
||||
pub(crate) async fn query(
|
||||
@@ -507,21 +439,7 @@ impl JdbcPool {
|
||||
cancel: &CancellationToken,
|
||||
schema: Option<&str>,
|
||||
) -> IdeResult<QueryResult> {
|
||||
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),
|
||||
self.request(
|
||||
&["query", sql, &skip.to_string(), &max.min(i32::MAX as usize).to_string(), schema.unwrap_or_default()],
|
||||
sql,
|
||||
cancel,
|
||||
@@ -539,91 +457,82 @@ 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> {
|
||||
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
|
||||
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
|
||||
{
|
||||
return result;
|
||||
// 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;
|
||||
}
|
||||
active.completed = true;
|
||||
result
|
||||
}
|
||||
|
||||
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.
|
||||
/// Keep-alive: checks the session (any SQL would be dialect-specific) and closes a dead one.
|
||||
pub(crate) async fn ping(&self) -> IdeResult<()> {
|
||||
let _service = self.service.opened.lock().await;
|
||||
if self.service.retired.is_cancelled() || self.session_valid(&self.service).await {
|
||||
if self.session_valid().await {
|
||||
return Ok(());
|
||||
}
|
||||
self.retire(&self.service);
|
||||
Err(IdeError::new(ErrorKind::Io, "JDBC connection was lost"))
|
||||
self.close().await;
|
||||
Err(IdeError::new(ide_core::error::ErrorKind::Io, "JDBC connection was lost"))
|
||||
}
|
||||
|
||||
/// 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();
|
||||
let Ok(Ok(Some(data))) = timeout(Duration::from_secs(10), self.exchange(session, &["valid"], &cancel)).await
|
||||
else {
|
||||
/// 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;
|
||||
}
|
||||
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,
|
||||
};
|
||||
decode(&data, "", 0.).is_ok_and(|result| {
|
||||
result.rows.first().and_then(|row| row.first()).and_then(Option::as_deref) == Some("true")
|
||||
})
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -773,33 +682,6 @@ 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>| {
|
||||
@@ -822,85 +704,65 @@ mod tests {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[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?;
|
||||
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]));
|
||||
}
|
||||
}
|
||||
|
||||
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));
|
||||
#[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 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(())
|
||||
let (mut peer, mut output) = tokio::io::duplex(4);
|
||||
peer.write_u32(0).await.unwrap();
|
||||
let error = exchange(&mut sink, &mut output, encode(1, &["query"]).unwrap(), &cancel).await.unwrap_err();
|
||||
assert_eq!(error.message, cancel_timeout().message);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
+105
-454
@@ -8,7 +8,6 @@ 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};
|
||||
@@ -25,17 +24,14 @@ 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, DbDuckLake, DbDuckLakeKind, DbExternalTunnel, DbIntrospection, DbOptions,
|
||||
DbProperty, DbSchemaSelection, DbSnowflake, DbSnowflakeAuth, DbSourceFolder, DbSsh, DbSshAuth, DbSslMode, DbTxMode,
|
||||
DbVisibilityChange,
|
||||
DataSource, DbColor, DbDriver, DbExternalTunnel, DbIntrospection, DbOptions, DbProperty, DbSchemaSelection,
|
||||
DbSnowflake, DbSnowflakeAuth, DbSourceFolder, DbSsh, DbSshAuth, DbSslMode, DbTxMode, DbVisibilityChange,
|
||||
};
|
||||
pub use sql::{CellValue, DbRowEdit, SortKey};
|
||||
|
||||
@@ -46,7 +42,7 @@ use parking_lot::Mutex;
|
||||
use secrets::SecretStore;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
use std::collections::HashMap;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
@@ -178,33 +174,9 @@ pub struct IndexInfo {
|
||||
pub name: String,
|
||||
pub unique: bool,
|
||||
pub columns: Vec<String>,
|
||||
/// The key this index enforces; such an index is dropped with its constraint, not `drop index`.
|
||||
/// `None` for a plain index, and on engines that don't tell.
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub key: Option<DbKeyKind>,
|
||||
}
|
||||
|
||||
/// A table key backed by an index.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum DbKeyKind {
|
||||
Primary,
|
||||
Unique,
|
||||
}
|
||||
|
||||
impl DbKeyKind {
|
||||
/// The [`sql::indexes`] key column: `p` (primary key), `u` (unique constraint).
|
||||
fn from_catalog(v: Option<&str>) -> Option<Self> {
|
||||
match v {
|
||||
Some("p") => Some(Self::Primary),
|
||||
Some("u") => Some(Self::Unique),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[serde(rename = "DbTableDetails")]
|
||||
pub struct TableDetails {
|
||||
@@ -216,53 +188,6 @@ pub struct TableDetails {
|
||||
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
|
||||
@@ -380,39 +305,12 @@ 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>>>,
|
||||
}
|
||||
|
||||
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.",
|
||||
)
|
||||
}
|
||||
type Session = Arc<tokio::sync::Mutex<Option<Held>>>;
|
||||
|
||||
const MAX_META_ROWS: usize = 100_000;
|
||||
/// Completion columns of the default schema, which are read without the shared cap.
|
||||
@@ -430,25 +328,6 @@ 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"))
|
||||
}
|
||||
@@ -505,41 +384,6 @@ 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)),
|
||||
@@ -548,13 +392,6 @@ 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 };
|
||||
@@ -585,7 +422,12 @@ 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 _ = session.rollback_and_release().await;
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
impl DbManager {
|
||||
@@ -625,7 +467,6 @@ impl DbManager {
|
||||
on_disk: Mutex::default(),
|
||||
sessions: Mutex::default(),
|
||||
cursors: conn::Cursors::default(),
|
||||
workspace_run: tokio::sync::Mutex::new(()),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -709,16 +550,13 @@ 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 && s.duck_lake.is_none()) {
|
||||
for source in sources.iter_mut().filter(|s| s.driver == DbDriver::Jdbc) {
|
||||
// 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);
|
||||
@@ -767,7 +605,7 @@ impl DbManager {
|
||||
}
|
||||
}
|
||||
// Made global or project-level: its saved passwords move along.
|
||||
Some(n) if n.global != o.global && n.duck_lake.is_none() && o.duck_lake.is_none() => {
|
||||
Some(n) if n.global != o.global => {
|
||||
for k in &keys {
|
||||
if let Some(p) = self.store_of(&o).get(k) {
|
||||
self.store_of(n).set(k, &p)?;
|
||||
@@ -849,9 +687,6 @@ 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()),
|
||||
@@ -862,11 +697,7 @@ 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 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);
|
||||
let config = self.sources()?.into_iter().find(|s| s.id == id).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);
|
||||
@@ -911,9 +742,6 @@ 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
|
||||
@@ -1022,10 +850,6 @@ 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,
|
||||
@@ -1154,30 +978,12 @@ impl DbManager {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// What databases this data source can see, including DuckDB's live attachments.
|
||||
/// The databases of the server of data source `id` (PostgreSQL), the connected one first.
|
||||
pub async fn databases(&self, id: &str) -> IdeResult<Databases> {
|
||||
let id = split_target(id).0;
|
||||
let source = self.source(id)?;
|
||||
let introspection = &source.introspection;
|
||||
let introspection = self.source(id)?.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());
|
||||
@@ -1216,13 +1022,12 @@ impl DbManager {
|
||||
Ok(Databases { current, names })
|
||||
}
|
||||
|
||||
/// 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.
|
||||
/// 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.
|
||||
pub async fn database_catalog(&self, id: &str, database: &str) -> IdeResult<Vec<CatalogSchema>> {
|
||||
let id = split_target(id).0;
|
||||
let pool = self.pool(id).await?;
|
||||
let schemas = match &*pool {
|
||||
Pool::Jdbc(_) if is_duckdb(&self.source(id)?) => return duckdb_catalog(&pool, database).await,
|
||||
let schemas = match &*self.pool(id).await? {
|
||||
Pool::Snowflake(p) => snowflake::meta::catalog(p, database).await?,
|
||||
_ => return Err(IdeError::invalid("this data source does not list other databases")),
|
||||
};
|
||||
@@ -1327,45 +1132,14 @@ impl DbManager {
|
||||
.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?;
|
||||
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 {
|
||||
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) => match catalog {
|
||||
Some(catalog) => p.metadata(&["columns", schema, table, catalog]).await?,
|
||||
None => p.metadata(&["columns", schema, table]).await?,
|
||||
},
|
||||
let rows = match &*pool {
|
||||
Pool::Jdbc(p) => p.metadata(&["columns", schema, table]).await?,
|
||||
_ => pool.rows(&sql::columns(driver, schema, table), MAX_META_ROWS).await?,
|
||||
};
|
||||
let columns = rows
|
||||
@@ -1382,7 +1156,13 @@ impl DbManager {
|
||||
})
|
||||
.collect();
|
||||
if driver == DbDriver::Jdbc {
|
||||
return Ok(TableDetails { columns, ..Default::default() });
|
||||
return Ok(TableDetails {
|
||||
comment: None,
|
||||
columns,
|
||||
indexes: vec![],
|
||||
foreign_keys: vec![],
|
||||
triggers: vec![],
|
||||
});
|
||||
}
|
||||
let mut indexes: Vec<IndexInfo> = Vec::new();
|
||||
for r in pool.rows(&sql::indexes(driver, schema, table), MAX_META_ROWS).await? {
|
||||
@@ -1393,12 +1173,7 @@ 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],
|
||||
key: DbKeyKind::from_catalog(it.next().flatten().as_deref()),
|
||||
}),
|
||||
_ => indexes.push(IndexInfo { name, unique: flag(&unique), columns: vec![col] }),
|
||||
}
|
||||
}
|
||||
let fk_rows = if matches!(driver, DbDriver::Clickhouse | DbDriver::Snowflake) {
|
||||
@@ -1449,18 +1224,7 @@ impl DbManager {
|
||||
),
|
||||
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)
|
||||
Ok(TableDetails { comment, columns, indexes, foreign_keys, triggers })
|
||||
}
|
||||
|
||||
/// The object privileges granted on `table`; empty, without a query, on the engines
|
||||
@@ -1812,26 +1576,13 @@ 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) {
|
||||
if let Some(console) = console {
|
||||
self.finish_postgres_console_transaction(id, console, false).await?;
|
||||
} else {
|
||||
self.finish_transaction(id, false).await?;
|
||||
}
|
||||
self.finish_transaction(id, false).await?;
|
||||
return Err(IdeError::invalid(error));
|
||||
}
|
||||
}
|
||||
@@ -1852,22 +1603,7 @@ impl DbManager {
|
||||
cancel: &CancellationToken,
|
||||
schema: Option<&str>,
|
||||
) -> IdeResult<QueryResult> {
|
||||
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 r = self.run(id, statement, skip, max_rows, cancel, schema).await;
|
||||
let ran = match &r {
|
||||
Ok(_) => true,
|
||||
Err(e) => !matches!(e.kind, ErrorKind::Cancelled | ErrorKind::PermissionDenied),
|
||||
@@ -1889,34 +1625,12 @@ impl DbManager {
|
||||
cancel: &CancellationToken,
|
||||
schema: Option<&str>,
|
||||
) -> IdeResult<QueryResult> {
|
||||
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
|
||||
self.run_paged(id, statement, row, 1, cancel, schema, 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.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));
|
||||
self.cursors.release(&conn::CursorKey::new(id, statement, schema));
|
||||
}
|
||||
|
||||
fn remember_statement(&self, id: &str, statement: &str) {
|
||||
@@ -1949,35 +1663,9 @@ impl DbManager {
|
||||
cancel: &CancellationToken,
|
||||
schema: Option<&str>,
|
||||
) -> IdeResult<Vec<PlanNode>> {
|
||||
self.explain_in_console(id, statement, cancel, schema, None).await
|
||||
}
|
||||
|
||||
pub async fn explain_in_console(
|
||||
&self,
|
||||
id: &str,
|
||||
statement: &str,
|
||||
cancel: &CancellationToken,
|
||||
schema: Option<&str>,
|
||||
console: Option<ConsoleId<'_>>,
|
||||
) -> IdeResult<Vec<PlanNode>> {
|
||||
let 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);
|
||||
let driver = self.pool(id).await?.driver();
|
||||
if driver == DbDriver::Jdbc {
|
||||
return Err(IdeError::invalid("Custom JDBC execution plans are unsupported"));
|
||||
}
|
||||
if driver == DbDriver::Oracle {
|
||||
// EXPLAIN PLAN writes PLAN_TABLE; the plan is read (and cleaned up) separately.
|
||||
@@ -1996,21 +1684,18 @@ 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, None).await?;
|
||||
let result = self.run(id, &plan::oracle_plan_query(&plan_id), 0, MAX_META_ROWS, cancel, None).await?;
|
||||
let nodes = plan::parse(driver, &result);
|
||||
let _ = self.run(id, &plan::oracle_plan_cleanup(&plan_id), 0, 0, cancel, None, None).await;
|
||||
let _ = self.run(id, &plan::oracle_plan_cleanup(&plan_id), 0, 0, cancel, None).await;
|
||||
return nodes;
|
||||
}
|
||||
let result = self
|
||||
.run(id, &plan::explain_statement(driver, statement), 0, MAX_META_ROWS, cancel, schema, console)
|
||||
.await?;
|
||||
let result =
|
||||
self.run(id, &plan::explain_statement(driver, statement), 0, MAX_META_ROWS, cancel, schema).await?;
|
||||
plan::parse(driver, &result)
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
async fn run(
|
||||
&self,
|
||||
id: &str,
|
||||
@@ -2019,9 +1704,8 @@ 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, console, true).await
|
||||
self.run_paged(id, statement, skip, max_rows, cancel, schema, true).await
|
||||
}
|
||||
|
||||
/// `paging`: whether the page may continue a cursor of `statement` (see `conn::cursor`).
|
||||
@@ -2034,31 +1718,13 @@ impl DbManager {
|
||||
max_rows: usize,
|
||||
cancel: &CancellationToken,
|
||||
schema: Option<&str>,
|
||||
console: Option<ConsoleId<'_>>,
|
||||
paging: bool,
|
||||
) -> IdeResult<QueryResult> {
|
||||
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());
|
||||
}
|
||||
let pool = self.pool(id).await?;
|
||||
if let Pool::Jdbc(p) = &*pool {
|
||||
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());
|
||||
return p.query_in_schema(statement, skip, max_rows, cancel, schema).await;
|
||||
}
|
||||
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) {
|
||||
@@ -2066,7 +1732,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).with_console(console);
|
||||
let key = conn::CursorKey::new(id, statement, schema);
|
||||
let started = std::time::Instant::now();
|
||||
let page = match self.cursors.resume(&key, skip, max_rows, cancel, protected).await {
|
||||
Some(page) => page,
|
||||
@@ -2102,9 +1768,44 @@ impl DbManager {
|
||||
if pool.driver() == DbDriver::Clickhouse {
|
||||
return Err(IdeError::invalid("ClickHouse manual transactions are unsupported"));
|
||||
}
|
||||
session
|
||||
.execute(&pool, &connection.console_transactions.capacity, statement, skip, max_rows, cancel, schema)
|
||||
.await
|
||||
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
|
||||
}
|
||||
|
||||
/// Switches `id` between auto-commit and manual commit. Leaving manual
|
||||
@@ -2137,37 +1838,23 @@ impl DbManager {
|
||||
}
|
||||
let session = self.sessions.lock().get(id).cloned();
|
||||
let Some(session) = session else { return Ok(()) };
|
||||
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?;
|
||||
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;
|
||||
}
|
||||
Ok(false)
|
||||
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()),
|
||||
if let Err(e) = conn.restore_default().await {
|
||||
conn.discard().await;
|
||||
return Err(e);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
@@ -2182,54 +1869,18 @@ impl DbManager {
|
||||
limit: u64,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<TablePage> {
|
||||
let details = self.table_details(id, schema, table).await?;
|
||||
let pool = self.pool(id).await?;
|
||||
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 mut result = if let Pool::Jdbc(p) = &*pool {
|
||||
let q = &p.identifier_quote;
|
||||
let names =
|
||||
catalog.into_iter().chain((catalog.is_some() || !schema.is_empty()).then_some(schema)).chain([table]);
|
||||
let names = [schema, table].into_iter().chain(sort.iter().map(|k| k.column.as_str()));
|
||||
if q.is_empty()
|
||||
&& names
|
||||
.clone()
|
||||
.chain(sort.iter().map(|k| k.column.as_str()))
|
||||
.any(|name| !name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_'))
|
||||
&& names.into_iter().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 = names.map(quote).collect::<Vec<_>>().join(".");
|
||||
let name = if schema.is_empty() { quote(table) } else { format!("{}.{}", quote(schema), quote(table)) };
|
||||
let sql = sql::table_select(&name, filter, sort, quote);
|
||||
p.page(&sql, offset, limit, cancel).await?
|
||||
} else {
|
||||
|
||||
@@ -1,202 +0,0 @@
|
||||
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,54 +90,6 @@ 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();
|
||||
@@ -197,7 +149,18 @@ fn postgres(node: &Value, parent: Option<u32>, out: &mut Vec<PlanNode>) {
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter(|(k, _)| k.as_str() != "Plans")
|
||||
.map(|(k, v)| json_property(k, v))
|
||||
.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)
|
||||
})
|
||||
.collect();
|
||||
let me = out.len() as u32;
|
||||
out.push(PlanNode { parent, operation, params: params.join(" "), properties });
|
||||
@@ -324,25 +287,6 @@ 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,7 +55,6 @@ 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>,
|
||||
}
|
||||
|
||||
@@ -212,7 +211,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, console_transactions: Default::default() })
|
||||
Ok(Connection { pool, route })
|
||||
}
|
||||
|
||||
async fn close_target(&self, id: &str, slot: Arc<ConnectionSlot>) {
|
||||
@@ -224,46 +223,10 @@ 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 {
|
||||
|
||||
@@ -154,7 +154,7 @@ pub(crate) async fn table_details(pool: &SnowflakePool, schema: &str, table: &st
|
||||
.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() })
|
||||
Ok(TableDetails { comment, columns, indexes: Vec::new(), foreign_keys, triggers: Vec::new() })
|
||||
}
|
||||
|
||||
fn foreign_keys(shown: &Shown) -> Vec<ForeignKey> {
|
||||
|
||||
@@ -11,7 +11,6 @@ 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)]
|
||||
@@ -307,25 +306,6 @@ 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 {
|
||||
@@ -366,8 +346,6 @@ 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,
|
||||
@@ -408,7 +386,6 @@ impl Default for DataSource {
|
||||
introspection: DbIntrospection::default(),
|
||||
properties: Vec::new(),
|
||||
snowflake: None,
|
||||
duck_lake: None,
|
||||
global: false,
|
||||
plugin_owner: None,
|
||||
plugin_source_id: None,
|
||||
@@ -536,69 +513,7 @@ 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.
|
||||
@@ -621,7 +536,6 @@ 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:"));
|
||||
|
||||
@@ -26,49 +26,6 @@ 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;
|
||||
@@ -177,12 +134,6 @@ 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;
|
||||
}
|
||||
@@ -203,7 +154,7 @@ pub fn split(text: &str, driver: DbDriver) -> Vec<SqlStatement> {
|
||||
state = State::LineComment;
|
||||
i += 1;
|
||||
}
|
||||
'#' if mysql || clickhouse => state = State::LineComment,
|
||||
'#' if mysql => 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;
|
||||
@@ -465,15 +416,6 @@ 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()
|
||||
}
|
||||
|
||||
@@ -236,31 +236,7 @@ pub fn table_comment(driver: DbDriver, schema: &str, table: &str) -> Option<Stri
|
||||
}
|
||||
}
|
||||
|
||||
/// 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).
|
||||
/// Rows: `index name, unique (0/1), column` (one row per indexed column, in order).
|
||||
// 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.
|
||||
@@ -275,14 +251,11 @@ 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, CASE il.origin WHEN 'pk' THEN 'p' WHEN 'u' THEN 'u' END \
|
||||
FROM pragma_index_list({t}, {s}) il \
|
||||
"SELECT il.name, il.\"unique\", ii.name 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, \
|
||||
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 \
|
||||
"SELECT i.relname, CASE WHEN ix.indisunique THEN 1 ELSE 0 END, a.attname \
|
||||
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 \
|
||||
@@ -290,14 +263,12 @@ 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, \
|
||||
CASE WHEN index_name = 'PRIMARY' THEN 'p' WHEN non_unique = 0 THEN 'u' END \
|
||||
"SELECT index_name, CASE WHEN non_unique = 0 THEN 1 ELSE 0 END, column_name \
|
||||
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, \
|
||||
CASE WHEN i.is_primary_key = 1 THEN 'p' WHEN i.is_unique_constraint = 1 THEN 'u' END \
|
||||
"SELECT i.name, CASE WHEN i.is_unique = 1 THEN 1 ELSE 0 END, c.name \
|
||||
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 \
|
||||
@@ -305,9 +276,7 @@ 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 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')) \
|
||||
"SELECT i.index_name, CASE WHEN i.uniqueness = 'UNIQUE' THEN 1 ELSE 0 END, ic.column_name \
|
||||
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"
|
||||
@@ -835,12 +804,7 @@ 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")
|
||||
// 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'");
|
||||
.replace("p.prokind IN ('f', 'p')", "NOT p.proisagg AND NOT p.proiswindow");
|
||||
(legacy != sql).then_some(legacy)
|
||||
}
|
||||
|
||||
@@ -1562,7 +1526,5 @@ 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,579 +0,0 @@
|
||||
//! 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, ConsoleId, DataSource, DbDriver, DbManager, DbRowEdit, DbSslMode, SortKey, sql};
|
||||
use ide_db::{CellValue, DataSource, DbDriver, DbManager, DbRowEdit, DbSslMode, SortKey, sql};
|
||||
use std::sync::Arc;
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
@@ -134,93 +134,3 @@ 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
@@ -1,134 +0,0 @@
|
||||
#!/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,7 +1,5 @@
|
||||
use ide_core::{CancellationToken, IdeResult};
|
||||
use ide_db::{
|
||||
ConsoleId, DataSource, DbDriver, DbDuckLake, DbDuckLakeKind, DbJdbcDriver, DbManager, DbProperty, SortKey,
|
||||
};
|
||||
use ide_db::{DataSource, DbDriver, DbJdbcDriver, DbManager, DbProperty, SortKey};
|
||||
use std::{path::Path, sync::Arc};
|
||||
|
||||
fn manager(dir: &Path) -> DbManager {
|
||||
@@ -10,158 +8,6 @@ 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()?;
|
||||
@@ -276,12 +122,9 @@ 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"));
|
||||
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"));
|
||||
assert!(db.tables("test", "main").await?.iter().any(|v| v.name == "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?;
|
||||
@@ -311,40 +154,6 @@ 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())]]);
|
||||
@@ -399,11 +208,9 @@ 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 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);
|
||||
}
|
||||
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);
|
||||
}
|
||||
assert!(!reopened.tables("test", "main").await?.iter().any(|table| table.name == "added"));
|
||||
reopened.disconnect("test").await;
|
||||
@@ -432,39 +239,19 @@ 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();
|
||||
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;
|
||||
}
|
||||
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;
|
||||
|
||||
source.read_only = true;
|
||||
for url in ["jdbc:duckdb:", "jdbc:duckdb::memory:", "jdbc:duckdb:memory:default"] {
|
||||
for url in ["jdbc:duckdb:", "jdbc:duckdb::memory:"] {
|
||||
source.url = url.into();
|
||||
let err = db.test(&source, None, None).await.unwrap_err();
|
||||
assert!(err.message.contains("existing database file"), "{}", err.message);
|
||||
@@ -472,161 +259,6 @@ 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<()> {
|
||||
@@ -731,72 +363,6 @@ 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<()> {
|
||||
|
||||
@@ -1,122 +0,0 @@
|
||||
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, DbPersistence};
|
||||
use ide_db::{DataSource, DbDriver, DbManager};
|
||||
|
||||
fn server() -> Option<(String, u16, String, String)> {
|
||||
endpoint("OPENIDEA_TEST_POSTGRES")
|
||||
@@ -393,8 +393,6 @@ 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<_>>(),
|
||||
@@ -813,75 +811,6 @@ 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, DbKeyKind, DbManager, DbOptions, DbProperty, DbRowEdit, DbSchemaSelection,
|
||||
DbTableKind, DbVisibilityChange, QueryResult, SortKey,
|
||||
CellValue, DataSource, DbDriver, DbManager, DbOptions, DbProperty, DbRowEdit, DbSchemaSelection, DbTableKind,
|
||||
DbVisibilityChange, QueryResult, SortKey,
|
||||
};
|
||||
|
||||
async fn setup() -> (tempfile::TempDir, DbManager) {
|
||||
@@ -47,7 +47,6 @@ 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();
|
||||
@@ -65,32 +64,6 @@ 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;
|
||||
|
||||
@@ -423,25 +423,11 @@ 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,
|
||||
reason: None,
|
||||
reason_locales: Default::default(),
|
||||
}
|
||||
Self { id: cap.to_string(), risk: cap.risk(), description: cap.describe(), optional, granted }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -29,14 +29,12 @@ use crate::capability::Capability;
|
||||
use crate::plugin_point::PointDecl;
|
||||
use crate::resolve::Dependency;
|
||||
use serde::Deserialize;
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::collections::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.19.0";
|
||||
/// The longest `[capabilities.reasons]` entry, in characters: a sentence or two.
|
||||
pub const MAX_CAPABILITY_REASON: usize = 500;
|
||||
pub const ENGINE_VERSION: &str = "1.18.0";
|
||||
/// 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.
|
||||
@@ -51,15 +49,11 @@ 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.
|
||||
@@ -86,10 +80,6 @@ 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 {
|
||||
@@ -100,11 +90,6 @@ 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
|
||||
@@ -210,8 +195,6 @@ struct Raw {
|
||||
#[serde(default)]
|
||||
description: String,
|
||||
#[serde(default)]
|
||||
description_file: Option<PathBuf>,
|
||||
#[serde(default)]
|
||||
authors: Vec<String>,
|
||||
#[serde(default)]
|
||||
homepage: Option<String>,
|
||||
@@ -220,8 +203,6 @@ 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>,
|
||||
@@ -262,8 +243,6 @@ struct RawCapabilities {
|
||||
required: Vec<String>,
|
||||
#[serde(default)]
|
||||
optional: Vec<String>,
|
||||
#[serde(default)]
|
||||
reasons: BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
impl Manifest {
|
||||
@@ -292,18 +271,8 @@ impl Manifest {
|
||||
Ok(out)
|
||||
};
|
||||
let capabilities = match (raw.capabilities, raw.permissions) {
|
||||
(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() }
|
||||
}
|
||||
(Some(c), _) => Capabilities { required: parse_caps(c.required)?, optional: parse_caps(c.optional)? },
|
||||
(None, Some(p)) => Capabilities { required: parse_caps(p)?, optional: Vec::new() },
|
||||
(None, None) => Capabilities::default(),
|
||||
};
|
||||
let activation = match raw.activation {
|
||||
@@ -317,12 +286,10 @@ 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,
|
||||
@@ -380,27 +347,6 @@ 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,
|
||||
@@ -816,33 +762,6 @@ 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";
|
||||
@@ -1086,27 +1005,4 @@ 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,7 +27,6 @@ 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};
|
||||
|
||||
@@ -332,9 +331,6 @@ 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,
|
||||
@@ -362,9 +358,6 @@ 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>,
|
||||
@@ -722,7 +715,6 @@ 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"),
|
||||
@@ -733,7 +725,6 @@ mod tests {
|
||||
icon: None,
|
||||
homepage: None,
|
||||
notes: None,
|
||||
notes_locales: BTreeMap::new(),
|
||||
downloads: None,
|
||||
featured: false,
|
||||
suggest: Vec::new(),
|
||||
|
||||
@@ -111,17 +111,7 @@ 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) => {
|
||||
// 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 }
|
||||
}
|
||||
Ok(repo) => 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 }),
|
||||
@@ -296,10 +286,6 @@ 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"];
|
||||
@@ -315,13 +301,6 @@ 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());
|
||||
@@ -333,45 +312,14 @@ 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 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)?;
|
||||
}
|
||||
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)?;
|
||||
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")]
|
||||
@@ -426,15 +374,6 @@ pub fn prepare_diff(
|
||||
|
||||
#[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()));
|
||||
|
||||
@@ -101,28 +101,14 @@ fn list_arguments() {
|
||||
|
||||
#[test]
|
||||
fn api_arguments() {
|
||||
let req = GhApiRequest {
|
||||
method: "post".into(),
|
||||
endpoint: "graphql".into(),
|
||||
body: Some("{}".into()),
|
||||
paginate: false,
|
||||
host: None,
|
||||
};
|
||||
let req =
|
||||
GhApiRequest { method: "post".into(), endpoint: "graphql".into(), body: Some("{}".into()), paginate: false };
|
||||
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(),
|
||||
@@ -133,11 +119,3 @@ 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,7 +28,6 @@ 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
|
||||
|
||||
@@ -22,9 +22,7 @@
|
||||
mod templates;
|
||||
|
||||
use ide_extension::{Manifest, validate_plugin_id};
|
||||
use ide_host::plugins::{
|
||||
PluginHost, market_href_reachable_from, plugin_docs, plugin_icon, read_market_url, resolve_market_href,
|
||||
};
|
||||
use ide_host::plugins::{PluginHost, market_href_reachable_from, plugin_icon, read_market_url, resolve_market_href};
|
||||
use ide_plugin::{Limits, PluginEngine};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, ExitCode};
|
||||
@@ -643,15 +641,12 @@ 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: docs.description,
|
||||
description_locales: docs.description_locales,
|
||||
description: m.description.clone(),
|
||||
authors: m.authors.clone(),
|
||||
publisher: signer,
|
||||
download: base.map_or_else(|| file.clone(), |b| format!("{b}/{file}")),
|
||||
@@ -659,10 +654,9 @@ 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(&pkg)?,
|
||||
icon: plugin_icon(&ide_extension::Package::new(m.clone(), scratch.clone()))?,
|
||||
homepage: m.homepage.clone().filter(|h| !h.trim().is_empty()),
|
||||
notes: docs.change_notes.filter(|n| !n.trim().is_empty()),
|
||||
notes_locales: docs.change_notes_locales,
|
||||
notes: m.change_notes.clone().filter(|n| !n.trim().is_empty()),
|
||||
downloads: None,
|
||||
featured: false,
|
||||
suggest: Vec::new(),
|
||||
@@ -1084,62 +1078,6 @@ 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,14 +406,8 @@ pub async fn serve(
|
||||
|
||||
let result = loop {
|
||||
tokio::select! {
|
||||
_ = 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(());
|
||||
}
|
||||
_ = shutdown.cancelled() => break Ok(()),
|
||||
_ = terminate.recv() => break Ok(()),
|
||||
_ = async {
|
||||
match &active {
|
||||
Some(peer) => { peer.closed().await; }
|
||||
@@ -451,7 +445,6 @@ 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(());
|
||||
}
|
||||
|
||||
@@ -420,11 +420,12 @@ 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(deadline.saturating_duration_since(Instant::now())) {
|
||||
while let Ok(line) = rx.recv_timeout(Duration::from_millis(100)) {
|
||||
on_line(line);
|
||||
if Instant::now() > deadline {
|
||||
break;
|
||||
}
|
||||
}
|
||||
break status;
|
||||
}
|
||||
|
||||
@@ -139,8 +139,6 @@ 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`).
|
||||
@@ -155,8 +153,6 @@ 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<()>>>>,
|
||||
}
|
||||
@@ -172,7 +168,6 @@ 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>>,
|
||||
@@ -240,7 +235,6 @@ 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"))),
|
||||
@@ -276,7 +270,6 @@ 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();
|
||||
@@ -363,18 +356,13 @@ 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, ide_agent::AgentShutdownReason::WindowClose) {
|
||||
if let Some(shutdown) = self.begin_close(window) {
|
||||
self.wait_blocking(shutdown.handle);
|
||||
}
|
||||
}
|
||||
@@ -383,12 +371,7 @@ 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) {
|
||||
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) {
|
||||
if let Some(shutdown) = self.begin_close(window) {
|
||||
let mut closing = self.closing.lock();
|
||||
closing.retain(|entry| !entry.handle.is_finished());
|
||||
closing.push(shutdown);
|
||||
@@ -398,25 +381,18 @@ 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, agent_reason: ide_agent::AgentShutdownReason) -> Option<DetachedClose> {
|
||||
fn begin_close(&self, window: &str) -> 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));
|
||||
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 {
|
||||
for request in self.project_requests.write().remove(self.owner_window(window)).unwrap_or_default() {
|
||||
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 = project?;
|
||||
let project = self.projects.write().remove(window)?;
|
||||
project.closed.cancel();
|
||||
if let Some(plugins) = self.plugin_host() {
|
||||
if self.windows_for_root(&project.root).is_empty() {
|
||||
@@ -477,7 +453,6 @@ 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),
|
||||
@@ -505,10 +480,9 @@ 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_with(reason);
|
||||
manager.shutdown();
|
||||
}
|
||||
})
|
||||
});
|
||||
@@ -599,10 +573,6 @@ 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() {
|
||||
@@ -612,7 +582,6 @@ impl Host {
|
||||
lsp: None,
|
||||
debug: None,
|
||||
agents: projects.iter().map(|project| project.agents.clone()).collect(),
|
||||
agent_reason,
|
||||
terminals: None,
|
||||
processes: None,
|
||||
retired: None,
|
||||
@@ -701,8 +670,7 @@ impl Host {
|
||||
}
|
||||
project.documents.clear_workspace_edit_history();
|
||||
project.notebooks.stop_admission();
|
||||
let reason = *self.agent_shutdown_reason.lock();
|
||||
project.agents.shutdown_with(reason);
|
||||
project.agents.shutdown();
|
||||
}
|
||||
let stop_processes = async {
|
||||
for project in &projects {
|
||||
@@ -798,25 +766,6 @@ 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)]
|
||||
|
||||
@@ -251,7 +251,6 @@ fn git_status() -> Tool {
|
||||
Returns porcelain-style index/worktree status codes and summary counters.
|
||||
By default all Git repositories are returned.",
|
||||
|call| async move {
|
||||
call.host.ensure_git_enabled(&call.window)?;
|
||||
let include_untracked = call.flag("includeUntracked", true)?;
|
||||
let include_ignored = call.flag("includeIgnored", false)?;
|
||||
let page = Page::of(&call, STATUS_DEFAULT_LIMIT)?;
|
||||
@@ -361,7 +360,6 @@ By default all Git repositories are returned.",
|
||||
|
||||
fn git_diff() -> Tool {
|
||||
Tool::new("git_diff", "Read a Git diff for a file or the working tree. staged=true compares the index with HEAD; otherwise compares disk with the index. Unsaved editor text is not part of this diff.", |call| async move {
|
||||
call.host.ensure_git_enabled(&call.window)?;
|
||||
let wanted = call.opt_str("repositoryPathRelativeToProject")?;
|
||||
let path = wanted.as_deref().map(|p| call.resolve_inside(p)).transpose()?.unwrap_or_else(|| call.root().to_path_buf());
|
||||
let root = find_git_root(call.root(), &path).ok_or_else(|| IdeError::not_found("No git repository found"))?;
|
||||
|
||||
@@ -9,21 +9,12 @@ use std::path::Path;
|
||||
|
||||
/// Prefix of Open Recent item ids; the rest of the id is the project path.
|
||||
pub const RECENT_PREFIX: &str = "recent:";
|
||||
/// Item id of the local-projects section header in Open Recent.
|
||||
pub const RECENT_LOCAL_ID: &str = "recent.local";
|
||||
/// Prefix of remote host section header ids in Open Recent.
|
||||
pub const RECENT_SECTION_PREFIX: &str = "recent.section:";
|
||||
/// Prefix of items the frontend lists ([`MenuConfig::dynamic`]): `dyn:<action>` or `dyn:<action>|<arg>`.
|
||||
pub const DYNAMIC_PREFIX: &str = "dyn:";
|
||||
/// Action run for an Open Recent entry (argument: the project path).
|
||||
pub const OPEN_RECENT_ACTION: &str = "file.openRecentProject";
|
||||
pub const MAX_RECENT: usize = 15;
|
||||
|
||||
/// Whether `id` names a non-interactive Open Recent placeholder or section header.
|
||||
pub fn is_recent_placeholder(id: &str) -> bool {
|
||||
id == "recent.none" || id == RECENT_LOCAL_ID || id.starts_with(RECENT_SECTION_PREFIX)
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Os {
|
||||
Mac,
|
||||
@@ -245,9 +236,7 @@ pub fn spec(os: Os) -> Vec<Entry> {
|
||||
act("remote.stopBackend", "Stop Remote Backend"),
|
||||
act("remote.reloadEnvironment", "Reload Environment"),
|
||||
SEP,
|
||||
act("file.saveAs", "Save As…"),
|
||||
act("file.save", "Save All"),
|
||||
act("templates.saveFileAsTemplate", "Save File as Template…"),
|
||||
act("file.reloadAllFromDisk", "Reload All from Disk"),
|
||||
sub("fileProperties", "File Properties", vec![act("file.toggleReadOnly", "Make File Read-only / Writable")]),
|
||||
SEP,
|
||||
@@ -262,7 +251,6 @@ pub fn spec(os: Os) -> Vec<Entry> {
|
||||
act("file.exportSettings", "Export Settings…"),
|
||||
act("file.importSettings", "Import Settings…"),
|
||||
act("file.importJetBrainsSettings", "Import Settings from JetBrains IDE…"),
|
||||
act("file.syncSettings", "Sync Settings Now"),
|
||||
],
|
||||
),
|
||||
sub(
|
||||
@@ -686,7 +674,6 @@ pub fn spec(os: Os) -> Vec<Entry> {
|
||||
act("vcs.pull", "Pull…"),
|
||||
act("vcs.fetch", "Fetch"),
|
||||
act("vcs.unshallow", "Fetch Full History"),
|
||||
act("vcs.lfsPull", "Pull LFS Objects"),
|
||||
SEP,
|
||||
// Operation items (Abort Merge, Continue Rebase…) are enabled only while it is in progress.
|
||||
act("vcs.merge", "Merge…"),
|
||||
@@ -704,14 +691,6 @@ pub fn spec(os: Os) -> Vec<Entry> {
|
||||
SEP,
|
||||
act("vcs.newWorktree", "New Worktree…"),
|
||||
act("vcs.worktrees", "Worktrees…"),
|
||||
sub(
|
||||
"gitSubmodules",
|
||||
"Submodules",
|
||||
vec![
|
||||
act("vcs.initSubmodules", "Initialize Submodules"),
|
||||
act("vcs.syncSubmodules", "Sync Submodule URLs"),
|
||||
],
|
||||
),
|
||||
SEP,
|
||||
act("vcs.showLog", "Show Git Log"),
|
||||
sub(
|
||||
@@ -760,10 +739,6 @@ pub fn spec(os: Os) -> Vec<Entry> {
|
||||
act("github.createPullRequest", "Create Pull Request…"),
|
||||
act("github.checkoutPullRequest", "Checkout Pull Request…"),
|
||||
act("github.openInBrowser", "Open on GitHub"),
|
||||
SEP,
|
||||
act("github.createGist", "Create Gist…"),
|
||||
act("github.shareProject", "Share Project on GitHub"),
|
||||
act("github.actions.show", "GitHub Actions"),
|
||||
],
|
||||
),
|
||||
act("vcs.manageRemotes", "Manage Remotes…"),
|
||||
@@ -947,27 +922,12 @@ pub fn route(spec: &[Entry], id: &str) -> Option<MenuRoute> {
|
||||
|
||||
/// `entries` without the action `id` (and a separator it leaves doubled or trailing).
|
||||
pub fn without_action(entries: Vec<Entry>, id: &str) -> Vec<Entry> {
|
||||
without(entries, &|e| e == id)
|
||||
}
|
||||
|
||||
/// `entries` without the submenus and actions [`MenuConfig::hidden`] lists.
|
||||
pub fn without_hidden(entries: Vec<Entry>, config: &MenuConfig) -> Vec<Entry> {
|
||||
if config.hidden.is_empty() {
|
||||
return entries;
|
||||
}
|
||||
without(entries, &|id| config.hidden.iter().any(|h| h == id))
|
||||
}
|
||||
|
||||
/// `entries` without the actions and submenus whose id `drop` matches, and the separators
|
||||
/// left dangling.
|
||||
fn without(entries: Vec<Entry>, drop: &dyn Fn(&str) -> bool) -> Vec<Entry> {
|
||||
let mut out: Vec<Entry> = Vec::with_capacity(entries.len());
|
||||
for e in entries {
|
||||
match e {
|
||||
Entry::Action { id: a, .. } if drop(a) => {}
|
||||
Entry::Submenu { id: sid, .. } if drop(sid) => {}
|
||||
Entry::Action { id: a, .. } if a == id => {}
|
||||
Entry::Submenu { id: sid, label, children } => {
|
||||
out.push(Entry::Submenu { id: sid, label, children: without(children, drop) })
|
||||
out.push(Entry::Submenu { id: sid, label, children: without_action(children, id) })
|
||||
}
|
||||
Entry::Separator if matches!(out.last(), None | Some(Entry::Separator)) => {}
|
||||
e => out.push(e),
|
||||
@@ -1011,9 +971,6 @@ pub struct MenuConfig {
|
||||
/// Ids of the toggle actions currently on.
|
||||
#[serde(default)]
|
||||
pub checked: Vec<String>,
|
||||
/// Ids of submenus and actions left out of the menu (the Git menu while Git integration is off).
|
||||
#[serde(default)]
|
||||
pub hidden: Vec<String>,
|
||||
}
|
||||
|
||||
/// An item of a frontend-listed menu slot.
|
||||
@@ -1129,107 +1086,33 @@ pub struct RemoteRecent {
|
||||
pub opened_at_ms: f64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct RecentSection {
|
||||
pub id: String,
|
||||
pub label: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct RecentItem {
|
||||
pub path: String,
|
||||
pub label: String,
|
||||
pub section: Option<RecentSection>,
|
||||
}
|
||||
|
||||
fn parse_remote_recent(r: &RemoteRecent) -> (RecentSection, String) {
|
||||
const SCHEMES: [(&str, &str, &str); 3] =
|
||||
[("ssh://", "ssh", "SSH"), ("wsl://", "wsl", "WSL"), ("devcontainer://", "devContainer", "Dev Container")];
|
||||
for (prefix, kind, kind_label) in SCHEMES {
|
||||
if let Some(rest) = r.location.strip_prefix(prefix)
|
||||
&& let Some(slash) = rest.find('/')
|
||||
&& slash > 0
|
||||
{
|
||||
let remote_path = &rest[slash..];
|
||||
let (host, shown_path) = match r.detail.strip_suffix(remote_path).and_then(|h| h.strip_suffix(':')) {
|
||||
Some(host) if !host.is_empty() => (host, remote_path),
|
||||
_ => r.detail.split_once(':').unwrap_or((&rest[..slash], remote_path)),
|
||||
};
|
||||
return (
|
||||
RecentSection {
|
||||
id: format!("{RECENT_SECTION_PREFIX}{kind}:{host}"),
|
||||
label: format!("{kind_label} · {host}"),
|
||||
},
|
||||
format!("{} — {shown_path}", r.name),
|
||||
);
|
||||
}
|
||||
}
|
||||
let (host, shown_path) = r.detail.split_once(':').unwrap_or((r.detail.as_str(), r.detail.as_str()));
|
||||
(
|
||||
RecentSection { id: format!("{RECENT_SECTION_PREFIX}remote:{host}"), label: host.to_owned() },
|
||||
format!("{} — {shown_path}", r.name),
|
||||
)
|
||||
}
|
||||
|
||||
/// The local and remote recent projects, grouped by host in MRU order when remote projects exist.
|
||||
/// The local and remote recent projects, most recently opened first.
|
||||
pub fn recent_items(
|
||||
recent: &[ide_workspace::RecentProject],
|
||||
remote: &[RemoteRecent],
|
||||
home: Option<&Path>,
|
||||
) -> Vec<RecentItem> {
|
||||
enum Candidate<'a> {
|
||||
Local { path: String, label: String },
|
||||
Remote(&'a RemoteRecent),
|
||||
}
|
||||
|
||||
let local = recent.iter().map(|p| {
|
||||
let shown = match home.and_then(|h| p.path.strip_prefix(h).ok()) {
|
||||
Some(rest) => format!("~/{}", rest.display()),
|
||||
None => p.path.display().to_string(),
|
||||
};
|
||||
(
|
||||
p.opened_at_ms,
|
||||
Candidate::Local {
|
||||
path: p.path.to_string_lossy().into_owned(), label: format!("{} — {shown}", p.name)
|
||||
},
|
||||
)
|
||||
let item =
|
||||
RecentItem { path: p.path.to_string_lossy().into_owned(), label: format!("{} — {shown}", p.name) };
|
||||
(p.opened_at_ms, item)
|
||||
});
|
||||
let remote_candidates = remote.iter().map(|r| (r.opened_at_ms, Candidate::Remote(r)));
|
||||
let mut items: Vec<(f64, Candidate<'_>)> = local.chain(remote_candidates).collect();
|
||||
let remote = remote.iter().map(|r| {
|
||||
(r.opened_at_ms, RecentItem { path: r.location.clone(), label: format!("{} — {}", r.name, r.detail) })
|
||||
});
|
||||
let mut items: Vec<(f64, RecentItem)> = local.chain(remote).collect();
|
||||
// Stable: the local list's own order holds among equal times.
|
||||
items.sort_by(|a, b| b.0.total_cmp(&a.0));
|
||||
items.truncate(MAX_RECENT);
|
||||
|
||||
let has_remote = items.iter().any(|(_, c)| matches!(c, Candidate::Remote(_)));
|
||||
if !has_remote {
|
||||
return items
|
||||
.into_iter()
|
||||
.filter_map(|(_, c)| match c {
|
||||
Candidate::Local { path, label } => Some(RecentItem { path, label, section: None }),
|
||||
Candidate::Remote(_) => None,
|
||||
})
|
||||
.collect();
|
||||
}
|
||||
|
||||
let mut groups: Vec<(String, Vec<RecentItem>)> = Vec::new();
|
||||
for (_, candidate) in items {
|
||||
let (section, path, label) = match candidate {
|
||||
Candidate::Local { path, label } => {
|
||||
(RecentSection { id: RECENT_LOCAL_ID.into(), label: "Local".into() }, path, label)
|
||||
}
|
||||
Candidate::Remote(r) => {
|
||||
let (section, label) = parse_remote_recent(r);
|
||||
(section, r.location.clone(), label)
|
||||
}
|
||||
};
|
||||
let item = RecentItem { path, label, section: Some(section.clone()) };
|
||||
if let Some((_, members)) = groups.iter_mut().find(|(id, _)| *id == section.id) {
|
||||
members.push(item);
|
||||
} else {
|
||||
groups.push((section.id, vec![item]));
|
||||
}
|
||||
}
|
||||
groups.into_iter().flat_map(|(_, members)| members).collect()
|
||||
items.into_iter().take(MAX_RECENT).map(|(_, item)| item).collect()
|
||||
}
|
||||
|
||||
/// A menu entry for a menu bar drawn by the frontend (Windows title bar).
|
||||
@@ -1318,30 +1201,13 @@ pub fn model(spec: &[Entry], recent: &[RecentItem], config: &MenuConfig) -> Vec<
|
||||
Entry::RecentProjects if recent.is_empty() => {
|
||||
out.push(MenuNode::Placeholder { id: "recent.none".into(), label: "No Recent Projects".into() })
|
||||
}
|
||||
Entry::RecentProjects => {
|
||||
let mut current_section: Option<&str> = None;
|
||||
for r in recent {
|
||||
if let Some(sec) = &r.section
|
||||
&& current_section != Some(sec.id.as_str())
|
||||
{
|
||||
if current_section.is_some() {
|
||||
out.push(MenuNode::Separator);
|
||||
}
|
||||
out.push(MenuNode::Placeholder {
|
||||
id: sec.id.clone(),
|
||||
label: config.label(&sec.id, &sec.label),
|
||||
});
|
||||
current_section = Some(sec.id.as_str());
|
||||
}
|
||||
out.push(MenuNode::Action {
|
||||
id: OPEN_RECENT_ACTION.into(),
|
||||
label: r.label.clone(),
|
||||
hint: None,
|
||||
arg: Some(r.path.clone()),
|
||||
checked: None,
|
||||
});
|
||||
}
|
||||
}
|
||||
Entry::RecentProjects => out.extend(recent.iter().map(|r| MenuNode::Action {
|
||||
id: OPEN_RECENT_ACTION.into(),
|
||||
label: r.label.clone(),
|
||||
hint: None,
|
||||
arg: Some(r.path.clone()),
|
||||
checked: None,
|
||||
})),
|
||||
}
|
||||
}
|
||||
out
|
||||
|
||||
@@ -3,7 +3,7 @@ use crate::ops::Channel;
|
||||
use base64::Engine;
|
||||
use ide_core::error::ErrorKind;
|
||||
use ide_core::{CancellationToken, IdeError, IdeEvent, IdeResult, IpcPath, SharedSink};
|
||||
use ide_notebook::kernel::{KernelManager, KernelOutput, KernelTarget};
|
||||
use ide_notebook::kernel::{KernelManager, KernelOutput};
|
||||
use ide_notebook::{NotebookDocument, NotebookEdit, NotebookSnapshot};
|
||||
use parking_lot::Mutex;
|
||||
use serde::{Deserialize, Serialize};
|
||||
@@ -45,12 +45,11 @@ fn parse_variables(reply: &serde_json::Value) -> IdeResult<Vec<NotebookVariable>
|
||||
let rows = &reply["rows"];
|
||||
if rows["status"] != "ok" {
|
||||
let reason = rows["evalue"].as_str().unwrap_or("no result");
|
||||
return Err(IdeError::new(ErrorKind::Protocol, format!("could not read the kernel's variables: {reason}")));
|
||||
return Err(IdeError::unavailable(format!("could not read the kernel's variables: {reason}")));
|
||||
}
|
||||
// The value is a base64 str, so its text/plain is that text in quotes.
|
||||
let text = rows["data"]["text/plain"].as_str().unwrap_or_default().trim_matches(['\'', '"']);
|
||||
let bad =
|
||||
|error: String| IdeError::new(ErrorKind::Protocol, format!("could not read the kernel's variables: {error}"));
|
||||
let bad = |error: String| IdeError::unavailable(format!("could not read the kernel's variables: {error}"));
|
||||
let json = base64::engine::general_purpose::STANDARD.decode(text).map_err(|e| bad(e.to_string()))?;
|
||||
serde_json::from_slice(&json).map_err(|e| bad(e.to_string()))
|
||||
}
|
||||
@@ -356,49 +355,13 @@ impl NotebookService {
|
||||
if document.state.lock().active.is_some() {
|
||||
return Err(IdeError::unavailable("notebook is running"));
|
||||
}
|
||||
let expressions = HashMap::from([("rows".to_owned(), r#"globals().pop("_openidea_variables")()"#.to_owned())]);
|
||||
let expressions = HashMap::from([("rows".to_owned(), "_openidea_variables()".to_owned())]);
|
||||
match self.kernels.inspect(&document.path, VARIABLES, expressions).await? {
|
||||
Some(reply) => parse_variables(&reply).map(Some),
|
||||
None => Ok(None),
|
||||
}
|
||||
}
|
||||
|
||||
/// Opens the debugger of the notebook's kernel, starting `target` first (or replacing a
|
||||
/// kernel of another target). Also returns the notebook's code cells as (URI, source), read
|
||||
/// when called, and the prefix of its cell URIs: what Debug Cell needs (see
|
||||
/// `ide_notebook::kernel::debug`).
|
||||
pub(crate) async fn debugger(
|
||||
&self,
|
||||
id: &str,
|
||||
target: KernelTarget,
|
||||
cancel: CancellationToken,
|
||||
) -> IdeResult<(ide_notebook::kernel::KernelDebugger, impl Fn() -> Vec<(String, String)> + Send + 'static, String)>
|
||||
{
|
||||
let document = self.resolve(id)?;
|
||||
if document.state.lock().active.is_some() {
|
||||
return Err(IdeError::unavailable("notebook is running"));
|
||||
}
|
||||
// The drop-down's kernel, which may not be the one running yet.
|
||||
tokio::select! {
|
||||
biased;
|
||||
_ = cancel.cancelled() => return Err(IdeError::cancelled()),
|
||||
result = self.kernels.start(&document.path, target) => result?,
|
||||
}
|
||||
let debugger = self.kernels.debugger(&document.path)?;
|
||||
let prefix = ide_lsp::cell_uri(&document.path, "");
|
||||
// Read again on each use: cells are added and edited while the session runs.
|
||||
let cells = move || {
|
||||
let Ok(snapshot) = snapshot(&document) else { return Vec::new() };
|
||||
snapshot
|
||||
.cells
|
||||
.into_iter()
|
||||
.filter(|cell| cell.cell_type == "code")
|
||||
.map(|cell| (ide_lsp::cell_uri(&document.path, &cell.id), cell.source))
|
||||
.collect()
|
||||
};
|
||||
Ok((debugger, cells, prefix))
|
||||
}
|
||||
|
||||
pub(crate) fn admit(
|
||||
&self,
|
||||
id: &str,
|
||||
@@ -411,7 +374,7 @@ impl NotebookService {
|
||||
pub(crate) async fn execute(
|
||||
self: &Arc<Self>,
|
||||
admission: ExecutionAdmission,
|
||||
target: KernelTarget,
|
||||
python: PathBuf,
|
||||
on_output: Channel<NotebookOutputEvent>,
|
||||
) -> IdeResult<NotebookSnapshot> {
|
||||
let document = admission.guard.document.clone();
|
||||
@@ -420,7 +383,7 @@ impl NotebookService {
|
||||
tokio::spawn(async move {
|
||||
let ExecutionAdmission { guard, generation, plan } = admission;
|
||||
let result =
|
||||
service.run_batch(document.clone(), generation, plan, target, guard.batch.clone(), on_output).await;
|
||||
service.run_batch(document.clone(), generation, plan, python, guard.batch.clone(), on_output).await;
|
||||
drop(guard);
|
||||
match result {
|
||||
Ok(()) => snapshot(&document),
|
||||
@@ -436,7 +399,7 @@ impl NotebookService {
|
||||
document: Arc<ManagedDocument>,
|
||||
generation: u64,
|
||||
plan: Vec<(String, String)>,
|
||||
target: KernelTarget,
|
||||
python: PathBuf,
|
||||
batch: Arc<Batch>,
|
||||
on_output: Channel<NotebookOutputEvent>,
|
||||
) -> IdeResult<()> {
|
||||
@@ -464,7 +427,7 @@ impl NotebookService {
|
||||
.kernels
|
||||
.execute(
|
||||
&document.path,
|
||||
target.clone(),
|
||||
&python,
|
||||
&source,
|
||||
batch.cancel.clone(),
|
||||
Arc::new(move |output: KernelOutput| {
|
||||
|
||||
@@ -1,9 +1,7 @@
|
||||
# Run silently on a notebook's kernel by the Jupyter Variables tool window. The IDE then
|
||||
# evaluates `globals().pop("_openidea_variables")()` as a user expression, which also takes
|
||||
# the function back out of the notebook's namespace. Same rows as the Python Console's.
|
||||
# Run silently on a notebook's kernel by the Jupyter Variables tool window; the IDE then
|
||||
# evaluates `_openidea_variables()` as a user expression. Same rows as the Python Console's.
|
||||
def _openidea_variables():
|
||||
import base64
|
||||
import collections
|
||||
import json
|
||||
import reprlib
|
||||
import types
|
||||
@@ -11,33 +9,15 @@ def _openidea_variables():
|
||||
shell = get_ipython() # noqa: F821 -- defined in every IPython namespace
|
||||
short = reprlib.Repr()
|
||||
short.maxstring = short.maxother = 200
|
||||
limit = short.maxother
|
||||
items = 100
|
||||
containers = (dict, list, tuple, set, frozenset, collections.deque)
|
||||
|
||||
def value_text(value):
|
||||
# reprlib shortens the exact builtin types itself; for anything else it builds the
|
||||
# full repr() and then cuts it. That is right for a subclass's own repr (a namedtuple,
|
||||
# an OrderedDict, a defaultdict), but costs seconds and gigabytes for a big one.
|
||||
kind = type(value)
|
||||
if isinstance(value, (str, bytes, bytearray)) and kind is not str and len(value) > limit:
|
||||
return repr(value[:limit]) + "..."
|
||||
if isinstance(value, containers) and kind not in containers and len(value) > items:
|
||||
return "<%s len=%d>" % (kind.__name__, len(value))
|
||||
return short.repr(value)
|
||||
|
||||
rows = []
|
||||
for name, value in list(shell.user_ns.items()):
|
||||
if name.startswith("_") or name in shell.user_ns_hidden:
|
||||
if name.startswith("_") or name in shell.user_ns_hidden or isinstance(value, types.ModuleType):
|
||||
continue
|
||||
try:
|
||||
if isinstance(value, types.ModuleType):
|
||||
continue
|
||||
kind = type(value).__name__
|
||||
text = value_text(value)
|
||||
except Exception as error: # a broken __repr__ or __class__ must not hide the other variables
|
||||
kind, text = "?", "<unavailable: %s>" % type(error).__name__
|
||||
rows.append({"name": name, "type": kind, "value": text})
|
||||
text = short.repr(value)
|
||||
except Exception as error: # a broken __repr__ must not hide the other variables
|
||||
text = "<repr failed: %s>" % type(error).__name__
|
||||
rows.append({"name": name, "type": type(value).__name__, "value": text})
|
||||
rows.sort(key=lambda row: row["name"])
|
||||
# Base64 so the expression's text/plain (a str repr) needs no unescaping.
|
||||
return base64.b64encode(json.dumps(rows).encode()).decode()
|
||||
@@ -7,10 +7,10 @@ use ide_agent::registry::{AgentRegistry, RegistryPaths};
|
||||
use ide_agent::{
|
||||
AcpImportOutcome, AgentAcceptOutcome, AgentChange, AgentChanges, AgentChangesView, AgentCliOffer,
|
||||
AgentCliUpdateResult, AgentCommand, AgentContextUsage, AgentEntry, AgentEvent, AgentLoginEvent, AgentModelCatalog,
|
||||
AgentProbe, AgentPrompt, AgentProvider, AgentQueued, AgentRecoveryReport, AgentSkillMode, AgentSkillPolicy,
|
||||
AgentSkillState, AgentTask, CopilotAuthStatus, CustomAgentInput, ExternalSession, InstallRemoteSkillRequest,
|
||||
LoginLaunch, McpExternalSource, McpImportSelection, McpProbeResult, McpScope, McpServer, McpServerInput,
|
||||
McpTransport, NewAgentTask, RemoteSkillBrowseResult, RemoteSkillPreview, SkillsPolicy,
|
||||
AgentProbe, AgentPrompt, AgentProvider, AgentQueued, AgentSkillMode, AgentSkillPolicy, AgentSkillState, AgentTask,
|
||||
CopilotAuthStatus, CustomAgentInput, ExternalSession, InstallRemoteSkillRequest, LoginLaunch, McpExternalSource,
|
||||
McpImportSelection, McpProbeResult, McpScope, McpServer, McpServerInput, McpTransport, NewAgentTask,
|
||||
RemoteSkillBrowseResult, RemoteSkillPreview, SkillsPolicy,
|
||||
};
|
||||
use ide_command::command;
|
||||
use ide_core::error::ErrorKind;
|
||||
@@ -144,18 +144,12 @@ fn prepare_login_launch_env(
|
||||
env: &mut std::collections::BTreeMap<String, String>,
|
||||
host_has: impl Fn(&str) -> bool,
|
||||
) {
|
||||
let has_non_empty = |env: &std::collections::BTreeMap<String, String>, key: &str| {
|
||||
env.get(key).is_some_and(|v| !v.is_empty()) || host_has(key)
|
||||
};
|
||||
// Skip `gh`'s `termenv` OSC 11 background-color probe during interactive login (`gh auth login`
|
||||
// renders no markdown); if an OSC 11 reply arrives late over a PTY or SSH link, `survey` aborts
|
||||
// with `unexpected escape sequence from terminal: ['\x1b' ']']`.
|
||||
if target_is_gh && !has_non_empty(env, "GLAMOUR_STYLE") {
|
||||
env.insert("GLAMOUR_STYLE".into(), "notty".into());
|
||||
}
|
||||
if !is_remote {
|
||||
return;
|
||||
}
|
||||
let has_non_empty = |env: &std::collections::BTreeMap<String, String>, key: &str| {
|
||||
env.get(key).is_some_and(|v| !v.is_empty()) || host_has(key)
|
||||
};
|
||||
// `openidea-server` spawns sign-in commands in a real PTY even inside WSL, dev containers,
|
||||
// and `--web`, where `SSH_*` variables are absent; mark the session remote so CLIs such as
|
||||
// `copilot login` choose OAuth device-code sign-in over a remote-only loopback server.
|
||||
@@ -616,74 +610,6 @@ pub fn agent_cancel(host: &Host, window: &str, task: String, subagent: Option<St
|
||||
host.project(window)?.agents.cancel(&task, subagent)
|
||||
}
|
||||
|
||||
/// Resumes an interrupted task with a continuation turn (or immediately wakes a task waiting
|
||||
/// in the transient network outage retry loop).
|
||||
#[command(trust = trusted)]
|
||||
pub async fn agent_resume_task(host: &Host, window: &str, task: String) -> IdeResult<()> {
|
||||
host.require_trust(window)?;
|
||||
let agents = host.project(window)?.agents.clone();
|
||||
host.blocking(move || agents.resume(&task)).await
|
||||
}
|
||||
|
||||
/// Resumes all interrupted tasks in the project and returns their IDs.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn agent_resume_all_interrupted(host: &Host, window: &str) -> IdeResult<Vec<String>> {
|
||||
host.require_trust(window)?;
|
||||
let agents = host.project(window)?.agents.clone();
|
||||
host.blocking(move || agents.resume_all_interrupted()).await
|
||||
}
|
||||
|
||||
/// Clears a task's interrupted state without sending a continuation prompt.
|
||||
#[command(trust = always)]
|
||||
pub async fn agent_dismiss_interrupted(host: &Host, window: &str, task: String) -> IdeResult<()> {
|
||||
let agents = host.project(window)?.agents.clone();
|
||||
host.blocking(move || agents.dismiss_interrupted(&task)).await
|
||||
}
|
||||
|
||||
/// Marks a task as read (`unread = false`) when viewed by the user.
|
||||
#[command(trust = always)]
|
||||
pub async fn agent_mark_read(host: &Host, window: &str, task: String) -> IdeResult<()> {
|
||||
let agents = host.project(window)?.agents.clone();
|
||||
host.blocking(move || agents.mark_read(&task)).await
|
||||
}
|
||||
|
||||
/// Overrides the recovery / network auto-retry window (`None` = global default,
|
||||
/// `Some(0)` = Off / Ask, `Some(minutes)` = override) for `task`.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn agent_set_recovery_window(host: &Host, window: &str, task: String, minutes: Option<u32>) -> IdeResult<()> {
|
||||
host.require_trust(window)?;
|
||||
let agents = host.project(window)?.agents.clone();
|
||||
host.blocking(move || agents.set_recovery_window(&task, minutes)).await
|
||||
}
|
||||
|
||||
/// Arms or clears the one-shot auto-resume flag on active/interrupted tasks before window close.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn agent_set_auto_resume_once(host: &Host, window: &str, tasks: Vec<String>, enabled: bool) -> IdeResult<()> {
|
||||
host.require_trust(window)?;
|
||||
let agents = host.project(window)?.agents.clone();
|
||||
host.blocking(move || {
|
||||
agents.set_auto_resume_once(&tasks, enabled);
|
||||
Ok(())
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Wakes any task waiting in the transient network outage loop so reachability is probed now.
|
||||
#[command(trust = always)]
|
||||
pub fn agent_poke_network(host: &Host, window: &str) -> IdeResult<()> {
|
||||
host.project(window)?.agents.poke_network();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Reconciles interrupted tasks once per `AgentManager` incarnation according to the user's
|
||||
/// recovery policy and safety guardrails.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn agent_reconcile_interrupted(host: &Host, window: &str) -> IdeResult<AgentRecoveryReport> {
|
||||
host.require_trust(window)?;
|
||||
let agents = host.project(window)?.agents.clone();
|
||||
host.blocking(move || Ok(agents.reconcile_interrupted())).await
|
||||
}
|
||||
|
||||
/// Stops one of the task's background tasks.
|
||||
#[command(trust = always)]
|
||||
pub async fn agent_stop_background(host: &Host, window: &str, task: String, background: String) -> IdeResult<()> {
|
||||
@@ -1676,36 +1602,25 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn prepare_login_launch_env_marks_remote_sessions_for_device_code_auth() {
|
||||
let mut desktop_agent_env = std::collections::BTreeMap::new();
|
||||
prepare_login_launch_env(false, false, &mut desktop_agent_env, |_| false);
|
||||
assert!(desktop_agent_env.is_empty());
|
||||
|
||||
let mut desktop_gh_env = std::collections::BTreeMap::new();
|
||||
prepare_login_launch_env(false, true, &mut desktop_gh_env, |_| false);
|
||||
assert_eq!(desktop_gh_env.get("GLAMOUR_STYLE").map(String::as_str), Some("notty"));
|
||||
assert!(!desktop_gh_env.contains_key("REMOTE_CONTAINERS"));
|
||||
assert!(!desktop_gh_env.contains_key("GH_BROWSER"));
|
||||
let mut desktop_env = std::collections::BTreeMap::new();
|
||||
prepare_login_launch_env(false, true, &mut desktop_env, |_| false);
|
||||
assert!(desktop_env.is_empty());
|
||||
|
||||
let mut remote_agent_env = std::collections::BTreeMap::new();
|
||||
prepare_login_launch_env(true, false, &mut remote_agent_env, |_| false);
|
||||
assert_eq!(remote_agent_env.get("REMOTE_CONTAINERS").map(String::as_str), Some("1"));
|
||||
assert!(!remote_agent_env.contains_key("GH_BROWSER"));
|
||||
assert!(!remote_agent_env.contains_key("GLAMOUR_STYLE"));
|
||||
|
||||
let mut remote_gh_env = std::collections::BTreeMap::new();
|
||||
prepare_login_launch_env(true, true, &mut remote_gh_env, |_| false);
|
||||
assert_eq!(remote_gh_env.get("REMOTE_CONTAINERS").map(String::as_str), Some("1"));
|
||||
assert_eq!(remote_gh_env.get("GH_BROWSER").map(String::as_str), Some("true"));
|
||||
assert_eq!(remote_gh_env.get("GLAMOUR_STYLE").map(String::as_str), Some("notty"));
|
||||
|
||||
// Preserves existing SSH/remote indicators, browser settings, and GLAMOUR_STYLE.
|
||||
// Preserves existing SSH/remote indicators and explicit browser settings.
|
||||
let mut ssh_env = std::collections::BTreeMap::new();
|
||||
prepare_login_launch_env(true, true, &mut ssh_env, |k| {
|
||||
matches!(k, "SSH_CONNECTION" | "BROWSER" | "GLAMOUR_STYLE")
|
||||
});
|
||||
prepare_login_launch_env(true, true, &mut ssh_env, |k| matches!(k, "SSH_CONNECTION" | "BROWSER"));
|
||||
assert!(!ssh_env.contains_key("REMOTE_CONTAINERS"));
|
||||
assert!(!ssh_env.contains_key("GH_BROWSER"));
|
||||
assert!(!ssh_env.contains_key("GLAMOUR_STYLE"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1724,7 +1639,6 @@ ide_command::domain!(
|
||||
agent_copilot_auth_status,
|
||||
agent_create,
|
||||
agent_delete,
|
||||
agent_dismiss_interrupted,
|
||||
agent_entries,
|
||||
agent_external_sessions,
|
||||
agent_fork,
|
||||
@@ -1734,7 +1648,6 @@ ide_command::domain!(
|
||||
agent_hermes_profiles,
|
||||
agent_import_session,
|
||||
agent_login_spawn,
|
||||
agent_mark_read,
|
||||
agent_mcp_discover_sources,
|
||||
agent_mcp_import,
|
||||
agent_mcp_import_selected,
|
||||
@@ -1744,31 +1657,25 @@ ide_command::domain!(
|
||||
agent_mcp_save_json,
|
||||
agent_mcp_set_enabled,
|
||||
agent_mcp_test,
|
||||
agent_poke_network,
|
||||
agent_preview_copilot_models,
|
||||
agent_probe,
|
||||
agent_prompt,
|
||||
agent_providers,
|
||||
agent_reconcile_interrupted,
|
||||
agent_refresh_models,
|
||||
agent_registry_install,
|
||||
agent_registry_list,
|
||||
agent_registry_remove,
|
||||
agent_rename,
|
||||
agent_respond,
|
||||
agent_resume_all_interrupted,
|
||||
agent_resume_task,
|
||||
agent_rollback,
|
||||
agent_rollback_changes,
|
||||
agent_send_queued_now,
|
||||
agent_set_additional_args,
|
||||
agent_set_auto_resume_once,
|
||||
agent_set_command,
|
||||
agent_shell,
|
||||
agent_set_config,
|
||||
agent_set_env,
|
||||
agent_set_mcp_overrides,
|
||||
agent_set_recovery_window,
|
||||
agent_set_skill_overrides,
|
||||
agent_skills_browse,
|
||||
agent_skills_install,
|
||||
|
||||
@@ -5,38 +5,16 @@
|
||||
use super::Channel;
|
||||
use crate::Host;
|
||||
use ide_command::command;
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult, IpcPath, RequestId};
|
||||
use ide_core::{IdeError, IdeResult, IpcPath, RequestId};
|
||||
use ide_db::split::SqlStatement;
|
||||
use ide_db::workspace::WorkspaceJoinPlan;
|
||||
use ide_db::{
|
||||
CompletionModel, ConsoleId, DataSource, Databases, DbObjectKind, DbRowEdit, DbSourceFolder, DbVisibilityChange,
|
||||
HistoryEntry, PlanNode, QueryResult, SchemaObjects, SortKey, TableDetails, TableGrant, TableInfo, TablePage,
|
||||
CompletionModel, DataSource, Databases, DbObjectKind, DbRowEdit, DbSourceFolder, DbVisibilityChange, HistoryEntry,
|
||||
PlanNode, QueryResult, SchemaObjects, SortKey, TableDetails, TableGrant, TableInfo, TablePage,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub async fn db_workspace_join(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
request: RequestId,
|
||||
driver: String,
|
||||
plan: WorkspaceJoinPlan,
|
||||
) -> IdeResult<QueryResult> {
|
||||
let cancel = host.begin_project_request(window, request);
|
||||
let result = async {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
let db = host.project(window)?.db.clone();
|
||||
db.workspace_join(&driver, plan, &cancel).await
|
||||
}
|
||||
.await;
|
||||
host.end_request(request);
|
||||
result
|
||||
}
|
||||
|
||||
/// One statement of a console run.
|
||||
#[derive(Clone, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
@@ -55,11 +33,6 @@ pub enum ExecutionEvent {
|
||||
Done { error: Option<IdeError> },
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub fn db_approve_ducklake_source(host: &Host, window: &str, source: DataSource) -> IdeResult<()> {
|
||||
host.project(window)?.db.approve_ducklake_source(&source)
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub fn db_approve_jdbc_source(host: &Host, window: &str, source: DataSource) -> IdeResult<()> {
|
||||
host.project(window)?.db.approve_jdbc_source(&source)
|
||||
@@ -102,12 +75,6 @@ pub async fn db_save_sources(host: &Host, window: &str, sources: Vec<DataSource>
|
||||
sources_changed(host, window)
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub async fn db_create_ducklake(host: &Host, window: &str, jdbc_driver: String, directory: String) -> IdeResult<()> {
|
||||
let db = host.project(window)?.db.clone();
|
||||
db.create_ducklake(&jdbc_driver, &directory).await
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub fn db_source_folders(host: &Host, window: &str) -> IdeResult<Vec<DbSourceFolder>> {
|
||||
// The project's user-created folders and their data source members.
|
||||
@@ -234,28 +201,6 @@ pub async fn db_finish_transaction(host: &Host, window: &str, id: String, commit
|
||||
db.finish_transaction(&id, commit).await
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub async fn db_set_console_manual_commit(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
id: String,
|
||||
console: String,
|
||||
manual: bool,
|
||||
) -> IdeResult<bool> {
|
||||
host.project(window)?.db.set_postgres_console_manual(&id, ConsoleId::new(window, &console), manual).await
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub async fn db_finish_console_transaction(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
id: String,
|
||||
console: String,
|
||||
commit: bool,
|
||||
) -> IdeResult<()> {
|
||||
host.project(window)?.db.finish_postgres_console_transaction(&id, ConsoleId::new(window, &console), commit).await
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub async fn db_disconnect(host: &Host, window: &str, id: String, whole_source: Option<bool>) -> IdeResult<()> {
|
||||
// A source-level Deactivate includes databases still opening in the background.
|
||||
@@ -362,20 +307,6 @@ pub async fn db_table_details(
|
||||
db.table_details(&id, &schema, &table).await
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub async fn db_catalog_table_details(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
id: String,
|
||||
catalog: String,
|
||||
schema: String,
|
||||
table: String,
|
||||
) -> IdeResult<TableDetails> {
|
||||
// Columns and keys in an attached DuckDB catalog on the source session.
|
||||
let db = host.project(window)?.db.clone();
|
||||
db.catalog_table_details(&id, &catalog, &schema, &table).await
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub async fn db_table_grants(
|
||||
host: &Host,
|
||||
@@ -417,24 +348,6 @@ pub async fn db_object_ddl(
|
||||
db.object_ddl(&id, &schema, kind, &name).await
|
||||
}
|
||||
|
||||
fn console_request<'a>(
|
||||
host: &Host,
|
||||
window: &'a str,
|
||||
request: RequestId,
|
||||
path: Option<&'a str>,
|
||||
manual: Option<bool>,
|
||||
) -> IdeResult<(CancellationToken, Option<ConsoleId<'a>>)> {
|
||||
match path {
|
||||
Some(path) => Ok((
|
||||
host.begin_project_request(window, request),
|
||||
Some(ConsoleId::new(window, path).expecting_manual(manual)),
|
||||
)),
|
||||
None if manual.is_some() => Err(IdeError::invalid("Console transaction mode requires a console")),
|
||||
None => Ok((host.begin_request(request), None)),
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[command(trust = trusted)]
|
||||
pub async fn db_explain(
|
||||
host: &Host,
|
||||
@@ -443,13 +356,11 @@ pub async fn db_explain(
|
||||
id: String,
|
||||
statement: String,
|
||||
schema: Option<String>,
|
||||
#[default] console: Option<String>,
|
||||
#[default] console_manual: Option<bool>,
|
||||
) -> IdeResult<Vec<PlanNode>> {
|
||||
// Explain Plan: the execution plan of `statement` on `id`, without running it.
|
||||
let db = host.project(window)?.db.clone();
|
||||
let (cancel, console) = console_request(host, window, request, console.as_deref(), console_manual)?;
|
||||
let result = db.explain_in_console(&id, &statement, &cancel, schema.as_deref(), console).await;
|
||||
let cancel = host.begin_request(request);
|
||||
let result = db.explain(&id, &statement, &cancel, schema.as_deref()).await;
|
||||
host.end_request(request);
|
||||
result
|
||||
}
|
||||
@@ -507,35 +418,21 @@ pub async fn db_execute(
|
||||
schema: Option<String>,
|
||||
// Cells longer than this many UTF-16 units come back cut (`truncated` lists them); none: whole.
|
||||
#[default] cell_limit: Option<u32>,
|
||||
#[default] console: Option<String>,
|
||||
#[default] console_manual: Option<bool>,
|
||||
) -> IdeResult<Vec<StatementOutcome>> {
|
||||
let mut outcomes = Vec::new();
|
||||
let limits = Limits { skip, max_rows, cell_limit };
|
||||
execute_statements(
|
||||
host,
|
||||
window,
|
||||
request,
|
||||
&id,
|
||||
statements,
|
||||
limits,
|
||||
schema.as_deref(),
|
||||
console.as_deref(),
|
||||
console_manual,
|
||||
|event| {
|
||||
if let ExecutionEvent::Completed { outcome, .. } = event {
|
||||
outcomes.push(outcome);
|
||||
}
|
||||
Ok(())
|
||||
},
|
||||
)
|
||||
execute_statements(host, window, request, &id, statements, limits, schema.as_deref(), |event| {
|
||||
if let ExecutionEvent::Completed { outcome, .. } = event {
|
||||
outcomes.push(outcome);
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.await?;
|
||||
Ok(outcomes)
|
||||
}
|
||||
|
||||
/// Row `row` (from 0) of the result of `statement`, whole: what a page of a run with a
|
||||
/// `cell_limit` shows cut short.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[command(trust = trusted)]
|
||||
pub async fn db_result_row(
|
||||
host: &Host,
|
||||
@@ -545,12 +442,10 @@ pub async fn db_result_row(
|
||||
statement: SqlStatement,
|
||||
row: u32,
|
||||
schema: Option<String>,
|
||||
#[default] console: Option<String>,
|
||||
#[default] console_manual: Option<bool>,
|
||||
) -> IdeResult<QueryResult> {
|
||||
let db = host.project(window)?.db.clone();
|
||||
let (cancel, console) = console_request(host, window, request, console.as_deref(), console_manual)?;
|
||||
let result = db.read_console_row(&id, &statement.text, row as usize, &cancel, schema.as_deref(), console).await;
|
||||
let cancel = host.begin_request(request);
|
||||
let result = db.read_row(&id, &statement.text, row as usize, &cancel, schema.as_deref()).await;
|
||||
host.end_request(request);
|
||||
result
|
||||
}
|
||||
@@ -563,23 +458,11 @@ pub fn db_release_result(
|
||||
id: String,
|
||||
statement: String,
|
||||
schema: Option<String>,
|
||||
#[default] console: Option<String>,
|
||||
) -> IdeResult<()> {
|
||||
let console = console.as_deref().map(|path| ConsoleId::new(window, path));
|
||||
host.project(window)?.db.release_console_result(&id, &statement, schema.as_deref(), console);
|
||||
host.project(window)?.db.release_result(&id, &statement, schema.as_deref());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub async fn db_release_console(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
console: String,
|
||||
#[default] id: Option<String>,
|
||||
) -> IdeResult<()> {
|
||||
host.project(window)?.db.release_target_console(ConsoleId::new(window, &console), id.as_deref()).await
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[command(trust = trusted)]
|
||||
pub async fn db_execute_stream(
|
||||
@@ -592,22 +475,11 @@ pub async fn db_execute_stream(
|
||||
schema: Option<String>,
|
||||
#[default] cell_limit: Option<u32>,
|
||||
on_progress: Channel<ExecutionEvent>,
|
||||
#[default] console: Option<String>,
|
||||
#[default] console_manual: Option<bool>,
|
||||
) -> IdeResult<()> {
|
||||
let limits = Limits { skip: 0, max_rows, cell_limit };
|
||||
let result = execute_statements(
|
||||
host,
|
||||
window,
|
||||
request,
|
||||
&id,
|
||||
statements,
|
||||
limits,
|
||||
schema.as_deref(),
|
||||
console.as_deref(),
|
||||
console_manual,
|
||||
|event| on_progress.send(event),
|
||||
)
|
||||
let result = execute_statements(host, window, request, &id, statements, limits, schema.as_deref(), |event| {
|
||||
on_progress.send(event)
|
||||
})
|
||||
.await;
|
||||
// The invocation reply can reach the viewer before a large result frame.
|
||||
on_progress.send(ExecutionEvent::Done { error: result.err() })
|
||||
@@ -631,29 +503,19 @@ async fn execute_statements(
|
||||
statements: Vec<SqlStatement>,
|
||||
Limits { skip, max_rows, cell_limit }: Limits,
|
||||
schema: Option<&str>,
|
||||
console: Option<&str>,
|
||||
console_manual: Option<bool>,
|
||||
mut emit: impl FnMut(ExecutionEvent) -> IdeResult<()>,
|
||||
) -> IdeResult<()> {
|
||||
let db = host.project(window)?.db.clone();
|
||||
let (cancel, console) = console_request(host, window, request, console, console_manual)?;
|
||||
let cancel = host.begin_request(request);
|
||||
let result = async {
|
||||
db.validate_console_script(id, &statements, console).await?;
|
||||
db.validate_script(id, &statements).await?;
|
||||
for (index, statement) in statements.into_iter().enumerate() {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
emit(ExecutionEvent::Started { index: index as u32 })?;
|
||||
let outcome = match db
|
||||
.execute_in_console(
|
||||
id,
|
||||
&statement.text,
|
||||
skip as usize,
|
||||
max_rows.max(1) as usize,
|
||||
&cancel,
|
||||
schema,
|
||||
console,
|
||||
)
|
||||
.execute_from(id, &statement.text, skip as usize, max_rows.max(1) as usize, &cancel, schema)
|
||||
.await
|
||||
{
|
||||
Ok(mut result) => {
|
||||
@@ -704,41 +566,6 @@ pub async fn db_table_page(
|
||||
result
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[command(trust = trusted)]
|
||||
pub async fn db_catalog_table_page(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
request: RequestId,
|
||||
id: String,
|
||||
catalog: String,
|
||||
schema: String,
|
||||
table: String,
|
||||
filter: Option<String>,
|
||||
sort: Vec<SortKey>,
|
||||
offset: u32,
|
||||
limit: u32,
|
||||
) -> IdeResult<TablePage> {
|
||||
// One read-only page from the explicit DuckDB catalog on the source session.
|
||||
let db = host.project(window)?.db.clone();
|
||||
let cancel = host.begin_request(request);
|
||||
let result = db
|
||||
.catalog_table_page(
|
||||
&id,
|
||||
&catalog,
|
||||
&schema,
|
||||
&table,
|
||||
filter.as_deref(),
|
||||
&sort,
|
||||
offset.into(),
|
||||
limit.max(1).into(),
|
||||
&cancel,
|
||||
)
|
||||
.await;
|
||||
host.end_request(request);
|
||||
result
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub async fn db_apply_edits(
|
||||
host: &Host,
|
||||
@@ -862,7 +689,6 @@ pub async fn server_version(host: &Host, window: &str, id: &str) -> IdeResult<u3
|
||||
ide_command::domain!(
|
||||
db:
|
||||
db_apply_edits,
|
||||
db_workspace_join,
|
||||
db_completion,
|
||||
db_connect,
|
||||
db_connected,
|
||||
@@ -870,10 +696,7 @@ ide_command::domain!(
|
||||
db_consoles_dir,
|
||||
db_consoles,
|
||||
db_create_database,
|
||||
db_create_ducklake,
|
||||
db_database_catalog,
|
||||
db_catalog_table_details,
|
||||
db_catalog_table_page,
|
||||
db_databases,
|
||||
db_ddl,
|
||||
db_disconnect,
|
||||
@@ -882,17 +705,14 @@ ide_command::domain!(
|
||||
db_execute_stream,
|
||||
db_explain,
|
||||
db_finish_transaction,
|
||||
db_finish_console_transaction,
|
||||
db_history,
|
||||
db_jdbc_driver_classes,
|
||||
db_jdbc_drivers,
|
||||
db_approve_ducklake_source,
|
||||
db_approve_jdbc_source,
|
||||
db_save_jdbc_driver,
|
||||
db_remove_jdbc_driver,
|
||||
db_object_ddl,
|
||||
db_release_result,
|
||||
db_release_console,
|
||||
db_result_row,
|
||||
db_remove_history,
|
||||
db_retain_catalog,
|
||||
@@ -904,7 +724,6 @@ ide_command::domain!(
|
||||
db_schemas,
|
||||
db_session_context,
|
||||
db_set_manual_commit,
|
||||
db_set_console_manual_commit,
|
||||
db_set_password,
|
||||
db_set_ssh_secret,
|
||||
db_source_folders,
|
||||
@@ -947,190 +766,6 @@ mod tests {
|
||||
host
|
||||
}
|
||||
|
||||
fn workspace_test_plan() -> WorkspaceJoinPlan {
|
||||
use ide_db::workspace::{WorkspaceJoinColumn, WorkspaceJoinCondition, WorkspaceJoinRelation};
|
||||
let relation = |id: &str| WorkspaceJoinRelation {
|
||||
source_id: id.into(),
|
||||
database: "default".into(),
|
||||
schema: "default".into(),
|
||||
table: "items".into(),
|
||||
};
|
||||
WorkspaceJoinPlan {
|
||||
tables: vec![relation("left"), relation("right")],
|
||||
joins: vec![WorkspaceJoinCondition {
|
||||
left: WorkspaceJoinColumn { relation: 0, column: "id".into() },
|
||||
right_column: "id".into(),
|
||||
}],
|
||||
projection: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn workspace_join_respects_an_early_cancel() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let host = host_with_sqlite(&temp).await;
|
||||
let request = RequestId(1);
|
||||
host.cancel_request(request);
|
||||
let error = db_workspace_join(&host, "main", request, "no driver installed".into(), workspace_test_plan())
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(error.kind, ide_core::error::ErrorKind::Cancelled);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn workspace_join_cannot_resolve_a_project_after_its_requests_are_drained() {
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let host = host_with_sqlite(&temp).await;
|
||||
let window = "main";
|
||||
let active = host.begin_project_request(window, RequestId(1));
|
||||
std::thread::scope(|threads| {
|
||||
// Hold close at heap cleanup, which follows cancellation of registered requests.
|
||||
let heap = host.heap_windows.lock();
|
||||
let close = threads.spawn(|| host.close_project_detached(window));
|
||||
let deadline = Instant::now() + Duration::from_secs(3);
|
||||
while !active.is_cancelled() && Instant::now() < deadline {
|
||||
std::thread::sleep(Duration::from_millis(5));
|
||||
}
|
||||
let drained = active.is_cancelled();
|
||||
let detached = host.project(window).is_err();
|
||||
drop(heap);
|
||||
close.join().unwrap();
|
||||
|
||||
assert!(drained, "close did not reach the cancellation step");
|
||||
assert!(detached, "close drained its requests while the old project was still available");
|
||||
});
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
#[ignore = "requires DUCKDB_JDBC_JAR and Java 17+"]
|
||||
async fn workspace_join_stops_when_its_project_closes() {
|
||||
use std::time::Duration;
|
||||
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let host = host_with_sqlite(&temp).await;
|
||||
let window = "main";
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let sources = ["left", "right"].map(|id| DataSource {
|
||||
id: id.into(),
|
||||
name: format!("ClickHouse fixture {id}"),
|
||||
driver: DbDriver::Clickhouse,
|
||||
host: "127.0.0.1".into(),
|
||||
port: Some(listener.local_addr().unwrap().port()),
|
||||
..Default::default()
|
||||
});
|
||||
db_save_sources(&host, window, sources.into()).await.unwrap();
|
||||
host.project(window)
|
||||
.unwrap()
|
||||
.db
|
||||
.save_jdbc_driver(ide_db::DbJdbcDriver {
|
||||
id: "duck".into(),
|
||||
name: "DuckDB".into(),
|
||||
vendor: Some("duckdb".into()),
|
||||
jars: vec![std::env::var("DUCKDB_JDBC_JAR").expect("official JDBC fixture")],
|
||||
class_name: "org.duckdb.DuckDBDriver".into(),
|
||||
url_template: "jdbc:duckdb:".into(),
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
for (request, close_project) in [(RequestId(2), false), (RequestId(3), true)] {
|
||||
let join = db_workspace_join(&host, window, request, "duck".into(), workspace_test_plan());
|
||||
tokio::pin!(join);
|
||||
// Accept the source connection and leave it open without replying.
|
||||
let (socket, _) = tokio::select! {
|
||||
result = &mut join => panic!("workspace ended before reaching the source: {result:?}"),
|
||||
peer = tokio::time::timeout(Duration::from_secs(15), listener.accept()) => peer.unwrap().unwrap(),
|
||||
};
|
||||
if close_project {
|
||||
host.close_project_detached(window);
|
||||
} else {
|
||||
host.cancel_request(request);
|
||||
}
|
||||
let stopped = tokio::time::timeout(Duration::from_secs(3), &mut join).await;
|
||||
if stopped.is_err() {
|
||||
host.cancel_request(request);
|
||||
let _ = tokio::time::timeout(Duration::from_secs(5), &mut join).await;
|
||||
}
|
||||
let error = stopped.expect("workspace JOIN did not stop after cancellation").unwrap_err();
|
||||
assert_eq!(error.kind, ide_core::error::ErrorKind::Cancelled);
|
||||
assert!(!host.project_requests.read().values().flatten().any(|entry| *entry == request));
|
||||
drop(socket);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
#[ignore = "requires a disposable loopback PostgreSQL fixture with OPENIDEA_PG_CONSOLE_PORT"]
|
||||
async fn postgres_console_commands_keep_commit_result_reads_and_release_scoped() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let host = host_with_sqlite(&temp).await;
|
||||
let window = "main";
|
||||
let id = "postgres";
|
||||
db_save_sources(
|
||||
&host,
|
||||
window,
|
||||
vec![DataSource {
|
||||
id: id.into(),
|
||||
name: "Local PostgreSQL".into(),
|
||||
driver: DbDriver::Postgres,
|
||||
host: "127.0.0.1".into(),
|
||||
port: Some(std::env::var("OPENIDEA_PG_CONSOLE_PORT").unwrap().parse().unwrap()),
|
||||
user: "console_fixture".into(),
|
||||
database: "console_fixture".into(),
|
||||
..Default::default()
|
||||
}],
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let run = async |request, sql: &str, console: Option<&str>| {
|
||||
let outcomes = db_execute(
|
||||
&host,
|
||||
window,
|
||||
RequestId(request),
|
||||
id.into(),
|
||||
ide_db::split::split(sql, DbDriver::Postgres),
|
||||
0,
|
||||
10,
|
||||
Some("public".into()),
|
||||
None,
|
||||
console.map(str::to_owned),
|
||||
console.map(|_| true),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(outcomes[0].error.is_none(), "{:?}", outcomes[0].error);
|
||||
outcomes.into_iter().next().unwrap().result.unwrap()
|
||||
};
|
||||
run(1, "CREATE TABLE public.host_console_tx (id integer PRIMARY KEY)", None).await;
|
||||
for console in ["/a.sql", "/b.sql"] {
|
||||
assert!(db_set_console_manual_commit(&host, window, id.into(), console.into(), true).await.unwrap());
|
||||
}
|
||||
run(2, "INSERT INTO public.host_console_tx VALUES (1)", Some("/a.sql")).await;
|
||||
run(3, "INSERT INTO public.host_console_tx VALUES (2)", Some("/b.sql")).await;
|
||||
db_finish_console_transaction(&host, window, id.into(), "/b.sql".into(), true).await.unwrap();
|
||||
let select = "SELECT id FROM public.host_console_tx ORDER BY id";
|
||||
assert_eq!(run(4, select, None).await.rows, [[Some("2".into())]]);
|
||||
let statement = ide_db::split::split(select, DbDriver::Postgres).pop().unwrap();
|
||||
let retained = db_result_row(
|
||||
&host,
|
||||
window,
|
||||
RequestId(5),
|
||||
id.into(),
|
||||
statement,
|
||||
0,
|
||||
Some("public".into()),
|
||||
Some("/a.sql".into()),
|
||||
Some(true),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(retained.rows, [[Some("1".into())]]);
|
||||
db_release_console(&host, window, "/a.sql".into(), Some(id.into())).await.unwrap();
|
||||
assert_eq!(run(6, select, None).await.rows, [[Some("2".into())]]);
|
||||
let error = db_finish_console_transaction(&host, window, id.into(), "/a.sql".into(), true).await.unwrap_err();
|
||||
assert_eq!(error.kind, ide_core::error::ErrorKind::OutOfSync);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn a_reporting_error_stops_the_batch_and_releases_the_request() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
@@ -1147,8 +782,6 @@ mod tests {
|
||||
statements,
|
||||
Limits { skip: 0, max_rows: 10, cell_limit: None },
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
|event| match event {
|
||||
ExecutionEvent::Started { index: 0 } => Ok(()),
|
||||
ExecutionEvent::Completed { index: 0, outcome } => {
|
||||
@@ -1170,8 +803,7 @@ mod tests {
|
||||
"SELECT 99 AS n UNION ALL SELECT count(*) FROM items ORDER BY n DESC",
|
||||
DbDriver::Sqlite,
|
||||
);
|
||||
let outcomes =
|
||||
db_execute(&host, window, RequestId(2), id.into(), query, 1, 10, None, None, None, None).await.unwrap();
|
||||
let outcomes = db_execute(&host, window, RequestId(2), id.into(), query, 1, 10, None, None).await.unwrap();
|
||||
assert_eq!(outcomes[0].result.as_ref().unwrap().rows, vec![vec![Some("0".into())]]);
|
||||
}
|
||||
|
||||
@@ -1187,12 +819,10 @@ mod tests {
|
||||
),
|
||||
DbDriver::Sqlite,
|
||||
);
|
||||
db_execute(&host, window, RequestId(1), id.into(), setup, 0, 10, None, None, None, None).await.unwrap();
|
||||
db_execute(&host, window, RequestId(1), id.into(), setup, 0, 10, None, None).await.unwrap();
|
||||
|
||||
let query = || ide_db::split::split("SELECT n, body FROM docs ORDER BY n", DbDriver::Sqlite);
|
||||
let capped = db_execute(&host, window, RequestId(2), id.into(), query(), 0, 10, None, Some(100), None, None)
|
||||
.await
|
||||
.unwrap();
|
||||
let capped = db_execute(&host, window, RequestId(2), id.into(), query(), 0, 10, None, Some(100)).await.unwrap();
|
||||
let page = capped[0].result.as_ref().unwrap();
|
||||
// The page no longer carries more than the limit of each cell.
|
||||
let size: usize = page.rows.iter().flatten().flatten().map(String::len).sum();
|
||||
@@ -1213,8 +843,7 @@ mod tests {
|
||||
// The row of a cut cell, read alone and without a limit, is the whole value.
|
||||
for row in [1, 2] {
|
||||
let statement = query().remove(0);
|
||||
let one =
|
||||
db_result_row(&host, window, RequestId(3), id.into(), statement, row, None, None, None).await.unwrap();
|
||||
let one = db_result_row(&host, window, RequestId(3), id.into(), statement, row, None).await.unwrap();
|
||||
assert!(one.truncated.is_empty());
|
||||
let full = one.rows[0][1].clone().unwrap();
|
||||
assert_eq!(full.encode_utf16().count(), whole as usize);
|
||||
@@ -1222,8 +851,7 @@ mod tests {
|
||||
}
|
||||
|
||||
// Without a limit nothing is cut or listed.
|
||||
let all =
|
||||
db_execute(&host, window, RequestId(4), id.into(), query(), 0, 10, None, None, None, None).await.unwrap();
|
||||
let all = db_execute(&host, window, RequestId(4), id.into(), query(), 0, 10, None, None).await.unwrap();
|
||||
let all = all[0].result.as_ref().unwrap();
|
||||
assert!(all.truncated.is_empty());
|
||||
assert_eq!(all.rows[2][1].as_deref(), Some(wide.as_str()));
|
||||
|
||||
@@ -62,16 +62,8 @@ pub async fn debug_start(host: &Host, window: &str, config: LaunchConfig) -> Ide
|
||||
python.as_deref(),
|
||||
config.cwd.as_deref(),
|
||||
);
|
||||
let conda = super::python::conda_prefix(&host.config_dir, &project, python.as_deref(), config.cwd.as_deref());
|
||||
let plots = super::plots::prepare(host, &project).await;
|
||||
// The debuggee inherits the IDE's environment as a run started in its folder does.
|
||||
let dir = config.cwd.as_deref().map(|c| c.to_path_buf()).unwrap_or_else(|| project.root.clone());
|
||||
super::python::prepare_debug(
|
||||
&mut config,
|
||||
&paths,
|
||||
plots.as_ref().map(|p| (p, dir.as_path())),
|
||||
conda.as_deref(),
|
||||
)?;
|
||||
let plots = super::plots::prepare(host, &project);
|
||||
super::python::prepare_debug(&mut config, &paths, plots.as_ref())?;
|
||||
}
|
||||
let label = window;
|
||||
let (sink, flush_output) = output::coalescing_sink(host.window_sink(label));
|
||||
@@ -515,17 +507,6 @@ pub async fn debug_step(host: &Host, session: DebugSessionId, thread_id: i64, ki
|
||||
host.debugger.step(session, thread_id, kind).await
|
||||
}
|
||||
|
||||
/// Step Over / Into Instruction: a step by one machine instruction.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn debug_step_instruction(
|
||||
host: &Host,
|
||||
session: DebugSessionId,
|
||||
thread_id: i64,
|
||||
kind: StepKind,
|
||||
) -> IdeResult<()> {
|
||||
host.debugger.step_instruction(session, thread_id, kind).await
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub async fn debug_run_to(
|
||||
host: &Host,
|
||||
@@ -568,32 +549,6 @@ pub async fn debug_evaluate_in(
|
||||
host.debugger.evaluate_in(session, frame_id, expression, context).await
|
||||
}
|
||||
|
||||
/// Memory View: `count` bytes from `offset` bytes after `memory_reference` (a variable's,
|
||||
/// an evaluation result's or an earlier read's address).
|
||||
#[command(trust = trusted)]
|
||||
pub async fn debug_read_memory(
|
||||
host: &Host,
|
||||
session: DebugSessionId,
|
||||
memory_reference: String,
|
||||
offset: i64,
|
||||
count: u32,
|
||||
) -> IdeResult<ide_dap::MemoryBlock> {
|
||||
host.debugger.read_memory(session, memory_reference, offset, count).await
|
||||
}
|
||||
|
||||
/// Disassembly view: `count` instructions from `before` instructions ahead of `memory_reference`
|
||||
/// (a frame's instruction pointer or an instruction's address).
|
||||
#[command(trust = trusted)]
|
||||
pub async fn debug_disassemble(
|
||||
host: &Host,
|
||||
session: DebugSessionId,
|
||||
memory_reference: String,
|
||||
before: u32,
|
||||
count: u32,
|
||||
) -> IdeResult<Vec<ide_dap::Instruction>> {
|
||||
host.debugger.disassemble(session, memory_reference, before, count).await
|
||||
}
|
||||
|
||||
/// Last known verification states of a file's breakpoints (refetch on `breakpointsChanged`).
|
||||
#[command(trust = trusted)]
|
||||
pub fn debug_breakpoint_states(host: &Host, path: PathBuf) -> IdeResult<Vec<BreakpointState>> {
|
||||
@@ -1103,7 +1058,6 @@ ide_command::domain!(
|
||||
debug_capabilities,
|
||||
debug_completions,
|
||||
debug_data_breakpoint_info,
|
||||
debug_disassemble,
|
||||
debug_evaluate,
|
||||
debug_evaluate_in,
|
||||
debug_exception_filters,
|
||||
@@ -1121,7 +1075,6 @@ ide_command::domain!(
|
||||
debug_jvm_thread_dump,
|
||||
debug_listen_for_jvm,
|
||||
debug_pause,
|
||||
debug_read_memory,
|
||||
debug_redefine_classes,
|
||||
debug_replace_breakpoints,
|
||||
debug_resolve_variable,
|
||||
@@ -1142,7 +1095,6 @@ ide_command::domain!(
|
||||
debug_step,
|
||||
debug_step_in_target,
|
||||
debug_step_in_targets,
|
||||
debug_step_instruction,
|
||||
debug_stop,
|
||||
debug_threads,
|
||||
debug_unity_processes,
|
||||
|
||||
@@ -56,20 +56,6 @@ pub async fn doc_save_as(host: &Host, window: &str, doc: DocId, path: PathBuf) -
|
||||
.await
|
||||
}
|
||||
|
||||
/// Copies the current buffer, including unsaved edits, without changing the source; false for the source itself.
|
||||
#[command(trust = always)]
|
||||
pub async fn doc_copy_as(host: &Host, window: &str, doc: DocId, path: PathBuf) -> IdeResult<bool> {
|
||||
let project = host.project(window)?;
|
||||
host.blocking(move || {
|
||||
let copied = project.documents.copy_as(doc, &path)?;
|
||||
if let Some(dir) = path.parent().filter(|_| project.light) {
|
||||
project.watch_light_dir(dir);
|
||||
}
|
||||
Ok(copied)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Applies a CodeMirror change set; returns the new version. Rejects with
|
||||
/// `outOfSync` when `base_version` is stale; the UI then calls `doc_snapshot`.
|
||||
#[command(trust = always, desktop_body = async)]
|
||||
@@ -155,7 +141,6 @@ mod tests;
|
||||
ide_command::domain!(
|
||||
doc:
|
||||
doc_close,
|
||||
doc_copy_as,
|
||||
doc_edit,
|
||||
doc_open,
|
||||
doc_open_untitled,
|
||||
|
||||
@@ -111,36 +111,6 @@ async fn dirty_document_keeps_edits_and_warns_once() {
|
||||
assert!(f.document_events().is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn save_as_copies_the_current_buffer_and_leaves_the_source_on_disk() {
|
||||
let f = Fixture::new();
|
||||
let original = f.open(&f.path).await;
|
||||
doc_edit(
|
||||
&f.host,
|
||||
"main",
|
||||
original.id,
|
||||
original.version,
|
||||
ChangeSet { changes: vec![TextChange { from: 0, to: 0, insert: "local ".into() }] },
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let target = f.outside.with_extension("copy.txt");
|
||||
std::fs::write(&target, "old\n").unwrap();
|
||||
|
||||
assert!(doc_copy_as(&f.host, "main", original.id, target.clone()).await.unwrap());
|
||||
|
||||
assert_eq!(std::fs::read_to_string(&f.path).unwrap(), "original\n");
|
||||
assert_eq!(std::fs::read_to_string(&target).unwrap(), "local original\n");
|
||||
let source = f.project.documents.snapshot(original.id).unwrap();
|
||||
assert_eq!(source.path, f.path);
|
||||
assert_eq!(source.text, "local original\n");
|
||||
assert!(source.dirty);
|
||||
let copy = f.open(&target).await;
|
||||
assert_ne!(copy.id, original.id);
|
||||
assert_eq!(copy.text, "local original\n");
|
||||
assert!(!copy.dirty);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn deleted_document_keeps_its_buffer_and_other_documents_still_reload() {
|
||||
let f = Fixture::new();
|
||||
|
||||
@@ -158,28 +158,24 @@ pub async fn fs_read_dir(host: &Host, window: &str, path: PathBuf) -> IdeResult<
|
||||
// Runs on the blocking pool: on a network share (`\\wsl.localhost`) every stat is slow.
|
||||
let project = host.project(window);
|
||||
host.blocking(move || {
|
||||
let Ok(p) = project else { return ide_vfs::read_dir(&path, &[]) };
|
||||
// An attached project's folders follow its own exclusions.
|
||||
let root = p.root_of(&path);
|
||||
let globs = p.exclude_globs_in(&root);
|
||||
// `read_dir` matches relative to the enclosing repository: re-anchor
|
||||
// root patterns (`/build`) when the project is a repo subfolder. The
|
||||
// watcher already found the project folder's repository; on a network
|
||||
// share each `.git` probe up the tree is a round trip.
|
||||
let repo = if root == p.root && p.watcher.root() == p.root {
|
||||
p.watcher.repo_root().map(Path::to_path_buf)
|
||||
} else {
|
||||
root.ancestors().find(|d| d.join(".git").exists()).map(Path::to_path_buf)
|
||||
};
|
||||
let excludes =
|
||||
match repo.as_deref().and_then(|r| root.strip_prefix(r).ok()).filter(|rel| !rel.as_os_str().is_empty()) {
|
||||
Some(rel) => {
|
||||
let rel = rel.to_string_lossy().replace('\\', "/");
|
||||
globs.into_iter().map(|g| if g.starts_with('/') { format!("/{rel}{g}") } else { g }).collect()
|
||||
let excludes = project
|
||||
.map(|p| {
|
||||
// An attached project's folders follow its own exclusions.
|
||||
let root = p.root_of(&path);
|
||||
let globs = p.exclude_globs_in(&root);
|
||||
// `read_dir` matches relative to the enclosing repository: re-anchor
|
||||
// root patterns (`/build`) when the project is a repo subfolder.
|
||||
let repo = root.ancestors().find(|d| d.join(".git").exists());
|
||||
match repo.and_then(|r| root.strip_prefix(r).ok()).filter(|rel| !rel.as_os_str().is_empty()) {
|
||||
Some(rel) => {
|
||||
let rel = rel.to_string_lossy().replace('\\', "/");
|
||||
globs.into_iter().map(|g| if g.starts_with('/') { format!("/{rel}{g}") } else { g }).collect()
|
||||
}
|
||||
None => globs,
|
||||
}
|
||||
None => globs,
|
||||
};
|
||||
p.watcher.read_dir(&path, &excludes)
|
||||
})
|
||||
.unwrap_or_default();
|
||||
ide_vfs::read_dir(&path, &excludes)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
@@ -1,292 +0,0 @@
|
||||
//! GitHub pull requests (`ide-github`, through the `gh` CLI) for the project of the window.
|
||||
//!
|
||||
//! Runs on the project host (`Host` locally, `openidea-server` in a remote window) so remote
|
||||
//! SSH / WSL / dev-container projects use the remote host's `gh` CLI, repository, and
|
||||
//! project-scoped `GH_TOKEN`.
|
||||
|
||||
use super::{Channel, blocking};
|
||||
use crate::Host;
|
||||
use ide_command::command;
|
||||
use ide_core::{IdeError, IdeResult, RequestId};
|
||||
use ide_github::{
|
||||
CreatePullRequest, GhAccountRepos, GhApiRequest, GhAvailability, PrDiffRevisions, PrListQuery, PrReviewComment,
|
||||
PullRequestDetails, PullRequestSummary, ReviewEvent,
|
||||
};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// The working directory of gh: the project repository `repo` names, else the project's
|
||||
/// primary repository (a folder holding several repositories is not one itself).
|
||||
fn root(host: &Host, window: &str, repo: Option<PathBuf>) -> IdeResult<PathBuf> {
|
||||
let project = host.project(window)?;
|
||||
if !project.git_enabled() {
|
||||
return Err(IdeError::unavailable("Git integration is disabled in Settings › Version Control › Git"));
|
||||
}
|
||||
let repos = project.repos();
|
||||
match repo {
|
||||
Some(at) => match repos.at_root(&at) {
|
||||
Some(r) => Ok(r.root().to_path_buf()),
|
||||
None => Err(IdeError::unavailable(format!("{} is not a git repository of the project", at.display()))),
|
||||
},
|
||||
None => Ok(repos.primary().map_or_else(|| project.root.clone(), |r| r.root().to_path_buf())),
|
||||
}
|
||||
}
|
||||
|
||||
/// Emits `VcsChanged` after operations that move HEAD or refs (checkout, push).
|
||||
fn vcs_changed(host: &Host, window: &str, root: &Path) {
|
||||
if let Ok(p) = host.project(window) {
|
||||
p.sink.emit(ide_core::IdeEvent::VcsChanged { root: ide_core::IpcPath(root.to_path_buf()) });
|
||||
}
|
||||
}
|
||||
|
||||
/// The repositories of the account gh is signed in to ("Get from Version Control" › GitHub); needs no project.
|
||||
#[command(trust = outside_restricted)]
|
||||
pub async fn gh_account_repos() -> IdeResult<GhAccountRepos> {
|
||||
blocking(|| Ok(ide_github::account_repositories())).await
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub async fn gh_availability(host: &Host, window: &str, repo: Option<PathBuf>) -> IdeResult<GhAvailability> {
|
||||
let project = host.project(window)?;
|
||||
let root = root(host, window, repo)?;
|
||||
blocking(move || {
|
||||
crate::github_auth::apply_to_project(&project);
|
||||
Ok(ide_github::availability(&root))
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub async fn gh_pr_list(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
repo: Option<PathBuf>,
|
||||
query: PrListQuery,
|
||||
) -> IdeResult<Vec<PullRequestSummary>> {
|
||||
let root = root(host, window, repo)?;
|
||||
blocking(move || ide_github::list(&root, &query)).await
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub async fn gh_pr_view(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
repo: Option<PathBuf>,
|
||||
number: u32,
|
||||
) -> IdeResult<PullRequestDetails> {
|
||||
let root = root(host, window, repo)?;
|
||||
blocking(move || ide_github::view(&root, number)).await
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub async fn gh_pr_review_comments(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
repo: Option<PathBuf>,
|
||||
number: u32,
|
||||
) -> IdeResult<Vec<PrReviewComment>> {
|
||||
let root = root(host, window, repo)?;
|
||||
blocking(move || ide_github::review_comments(&root, number)).await
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub async fn gh_pr_checkout(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
repo: Option<PathBuf>,
|
||||
request: RequestId,
|
||||
number: u32,
|
||||
on_output: Channel<String>,
|
||||
) -> IdeResult<()> {
|
||||
let root = root(host, window, repo)?;
|
||||
let cancel = host.begin_request(request);
|
||||
let dir = root.clone();
|
||||
let result = blocking(move || {
|
||||
ide_github::checkout(&dir, number, &cancel, &|line| {
|
||||
let _ = on_output.send(line);
|
||||
})
|
||||
})
|
||||
.await;
|
||||
host.end_request(request);
|
||||
vcs_changed(host, window, &root);
|
||||
result
|
||||
}
|
||||
|
||||
/// Creates a pull request from the current branch (pushing it first when asked); returns its URL.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn gh_pr_create(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
repo: Option<PathBuf>,
|
||||
request: RequestId,
|
||||
pr: CreatePullRequest,
|
||||
on_output: Channel<String>,
|
||||
) -> IdeResult<String> {
|
||||
let root = root(host, window, repo)?;
|
||||
let git = host.project(window)?.git_executable();
|
||||
let cancel = host.begin_request(request);
|
||||
let dir = root.clone();
|
||||
let result = blocking(move || {
|
||||
ide_vcs::with_git_executable(git.as_deref(), || {
|
||||
ide_github::create(&dir, &pr, &cancel, &|line| {
|
||||
let _ = on_output.send(line);
|
||||
})
|
||||
})
|
||||
})
|
||||
.await;
|
||||
host.end_request(request);
|
||||
vcs_changed(host, window, &root);
|
||||
result
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub async fn gh_pr_review(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
repo: Option<PathBuf>,
|
||||
number: u32,
|
||||
event: ReviewEvent,
|
||||
body: String,
|
||||
) -> IdeResult<()> {
|
||||
let root = root(host, window, repo)?;
|
||||
blocking(move || ide_github::submit_review(&root, number, event, &body)).await
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub async fn gh_pr_comment(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
repo: Option<PathBuf>,
|
||||
number: u32,
|
||||
body: String,
|
||||
) -> IdeResult<()> {
|
||||
let root = root(host, window, repo)?;
|
||||
blocking(move || ide_github::add_comment(&root, number, &body)).await
|
||||
}
|
||||
|
||||
/// A GitHub GraphQL / REST call through `gh api`; returns the response body.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn gh_api(host: &Host, window: &str, repo: Option<PathBuf>, request: GhApiRequest) -> IdeResult<String> {
|
||||
let root = root(host, window, repo)?;
|
||||
blocking(move || ide_github::api(&root, &request)).await
|
||||
}
|
||||
|
||||
/// Fetches what is missing to diff a pull request locally; returns the revisions to compare.
|
||||
#[command(trust = trusted)]
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub async fn gh_pr_prepare_diff(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
repo: Option<PathBuf>,
|
||||
request: RequestId,
|
||||
number: u32,
|
||||
head_oid: String,
|
||||
base_oid: String,
|
||||
base_ref: String,
|
||||
name_with_owner: String,
|
||||
on_output: Channel<String>,
|
||||
) -> IdeResult<PrDiffRevisions> {
|
||||
let root = root(host, window, repo)?;
|
||||
let git = host.project(window)?.git_executable();
|
||||
let cancel = host.begin_request(request);
|
||||
let result = blocking(move || {
|
||||
let output = |line: String| {
|
||||
let _ = on_output.send(line);
|
||||
};
|
||||
ide_vcs::with_git_executable(git.as_deref(), || {
|
||||
ide_github::prepare_diff(&root, number, &head_oid, &base_oid, &base_ref, &name_with_owner, &cancel, &output)
|
||||
})
|
||||
})
|
||||
.await;
|
||||
host.end_request(request);
|
||||
result
|
||||
}
|
||||
|
||||
ide_command::domain!(
|
||||
github:
|
||||
gh_account_repos,
|
||||
gh_api,
|
||||
gh_availability,
|
||||
gh_pr_checkout,
|
||||
gh_pr_comment,
|
||||
gh_pr_create,
|
||||
gh_pr_list,
|
||||
gh_pr_prepare_diff,
|
||||
gh_pr_review,
|
||||
gh_pr_review_comments,
|
||||
gh_pr_view,
|
||||
);
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::root;
|
||||
use crate::catalogue::TrustClass;
|
||||
use crate::rpc::Dispatcher;
|
||||
use crate::{Host, HostConfig};
|
||||
use ide_core::error::ErrorKind;
|
||||
use ide_workspace::SettingsScope;
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
|
||||
fn test_host(base: &Path) -> Host {
|
||||
Host::new(HostConfig {
|
||||
config_dir: base.join("config"),
|
||||
data_dir: base.join("data"),
|
||||
local_data_dir: base.join("local"),
|
||||
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
|
||||
syntax: Arc::default(),
|
||||
sink_for: Box::new(|_| Arc::new(|_| {})),
|
||||
owner: |w| w,
|
||||
runtime: tokio::runtime::Handle::current(),
|
||||
project_environment: false,
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn registers_github_commands_on_the_remote_rpc_dispatcher() {
|
||||
let dispatcher = Dispatcher::standard();
|
||||
assert_eq!(dispatcher.trust("gh_account_repos"), Some(TrustClass::OutsideRestricted));
|
||||
for name in [
|
||||
"gh_api",
|
||||
"gh_availability",
|
||||
"gh_pr_checkout",
|
||||
"gh_pr_comment",
|
||||
"gh_pr_create",
|
||||
"gh_pr_list",
|
||||
"gh_pr_prepare_diff",
|
||||
"gh_pr_review",
|
||||
"gh_pr_review_comments",
|
||||
"gh_pr_view",
|
||||
] {
|
||||
assert_eq!(dispatcher.trust(name), Some(TrustClass::Trusted), "{name}");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn authorizes_account_repos_without_a_project_and_scopes_repo_lookup_to_project() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let host = test_host(dir.path());
|
||||
assert!(host.authorize("main", TrustClass::OutsideRestricted).is_ok());
|
||||
let err = host.authorize("main", TrustClass::Trusted).unwrap_err();
|
||||
assert_eq!(err.kind, ErrorKind::NotFound);
|
||||
|
||||
let proj_dir = dir.path().join("repo");
|
||||
std::fs::create_dir_all(&proj_dir).unwrap();
|
||||
host.open_project("main", &proj_dir).unwrap();
|
||||
assert_eq!(root(&host, "main", None).unwrap(), dunce::canonicalize(&proj_dir).unwrap());
|
||||
let outsider = root(&host, "main", Some(dir.path().join("other"))).unwrap_err();
|
||||
assert_eq!(outsider.kind, ErrorKind::Unavailable);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn refuses_gh_while_git_integration_is_off() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let host = test_host(dir.path());
|
||||
let proj_dir = dir.path().join("repo");
|
||||
std::fs::create_dir_all(&proj_dir).unwrap();
|
||||
host.global_settings.set(SettingsScope::Global, "vcs.git.enabled", serde_json::json!(false)).unwrap();
|
||||
host.open_project("main", &proj_dir).unwrap();
|
||||
let err = root(&host, "main", None).unwrap_err();
|
||||
assert_eq!(err.kind, ErrorKind::Unavailable);
|
||||
assert!(err.message.contains("Git integration is disabled"), "{}", err.message);
|
||||
}
|
||||
}
|
||||
@@ -1,40 +0,0 @@
|
||||
//! iOS Simulators for Xcode projects, through `xcrun simctl` on the project host.
|
||||
use crate::Host;
|
||||
use ide_command::command;
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use ide_run::simulator::{self, IosSimulator};
|
||||
|
||||
async fn blocking<T: Send + 'static>(f: impl FnOnce() -> IdeResult<T> + Send + 'static) -> IdeResult<T> {
|
||||
tokio::task::spawn_blocking(f).await.map_err(|e| IdeError::internal(e.to_string()))?
|
||||
}
|
||||
|
||||
/// The available iOS simulators, booted first; `None` outside macOS or when the project has no
|
||||
/// Xcode project or workspace at its root. Asked again whenever the chooser opens: `simctl` has
|
||||
/// no change feed, and one listing takes a fraction of a second.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn ios_simulators(host: &Host, window: &str) -> IdeResult<Option<Vec<IosSimulator>>> {
|
||||
let root = host.project(window)?.root.clone();
|
||||
if !cfg!(target_os = "macos") || !simulator::is_xcode_project(&root) {
|
||||
return Ok(None);
|
||||
}
|
||||
blocking(simulator::list).await.map(Some)
|
||||
}
|
||||
|
||||
/// Boots a simulator; returns once it is booted.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn ios_simulator_boot(_host: &Host, udid: String) -> IdeResult<()> {
|
||||
blocking(move || simulator::boot(&udid)).await
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub async fn ios_simulator_shutdown(_host: &Host, udid: String) -> IdeResult<()> {
|
||||
blocking(move || simulator::shutdown(&udid)).await
|
||||
}
|
||||
|
||||
/// Opens Simulator.app.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn ios_simulator_open_app(_host: &Host) -> IdeResult<()> {
|
||||
blocking(simulator::open_app).await
|
||||
}
|
||||
|
||||
ide_command::domain!(ios: ios_simulators, ios_simulator_boot, ios_simulator_shutdown, ios_simulator_open_app);
|
||||
@@ -84,7 +84,7 @@ pub(crate) async fn resolve_launch(
|
||||
let build = policy != BuildPolicy::NoBuild;
|
||||
let full = policy == BuildPolicy::Rebuild;
|
||||
let build_kind = if full { compile::BuildKind::Rebuild } else { compile::BuildKind::Build };
|
||||
let (model, external, mut delegated, is_maven, non_java, served, needs_cleanup) = {
|
||||
let (model, external, mut delegated, is_maven, non_java, served) = {
|
||||
let scope = scope.clone();
|
||||
let launches = launches.clone();
|
||||
let module = module.clone();
|
||||
@@ -95,11 +95,16 @@ pub(crate) async fn resolve_launch(
|
||||
let non_java = build && compile::launch_has_non_java_sources(root, &model, &module, test);
|
||||
let is_maven = is_maven_module(root, &model, &module);
|
||||
let served = served_by_service(root, &model, &scope.settings, &module);
|
||||
let needs_cleanup = build && is_maven && cache::needs_cleanup(root, &scope.cache, &model, &module, test);
|
||||
let delegated =
|
||||
build && delegates_to_external_build(is_maven, policy, non_java, needs_cleanup, prefer_maven);
|
||||
let delegated = build
|
||||
&& delegates_to_external_build(
|
||||
is_maven,
|
||||
policy,
|
||||
non_java,
|
||||
cache::has_record(root, &scope.cache, &module),
|
||||
prefer_maven,
|
||||
);
|
||||
let external = non_java || delegated;
|
||||
(std::sync::Arc::new(model), external, delegated, is_maven, non_java, served, needs_cleanup)
|
||||
(std::sync::Arc::new(model), external, delegated, is_maven, non_java, served)
|
||||
})
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(e.to_string()))?
|
||||
@@ -112,7 +117,7 @@ pub(crate) async fn resolve_launch(
|
||||
// the launch debugs with java-debug, whose HotSwap reloads what jdtls compiles (ecj's
|
||||
// classes differ from javac's: lambda names). jdtls keeps building for its diagnostics
|
||||
// either way.
|
||||
if served && !non_java && !debug && !needs_cleanup {
|
||||
if served && !non_java && !debug {
|
||||
let built = {
|
||||
let (service, data_dir, scope, model, module, cancel, events) = (
|
||||
host.java_build.clone(),
|
||||
@@ -801,7 +806,7 @@ fn joining_launches(
|
||||
is_maven,
|
||||
o.policy,
|
||||
compile::launch_has_non_java_sources(root, model, &o.module, test),
|
||||
is_maven && cache::needs_cleanup(root, cache_dir, model, &o.module, test),
|
||||
cache::has_record(root, cache_dir, &o.module),
|
||||
prefer_maven,
|
||||
)
|
||||
})
|
||||
@@ -815,10 +820,10 @@ fn delegates_to_external_build(
|
||||
is_maven: bool,
|
||||
policy: BuildPolicy,
|
||||
non_java: bool,
|
||||
needs_cleanup: bool,
|
||||
has_record: bool,
|
||||
prefer_maven: bool,
|
||||
) -> bool {
|
||||
is_maven && (prefer_maven || policy == BuildPolicy::Rebuild || non_java || needs_cleanup)
|
||||
is_maven && (prefer_maven || policy == BuildPolicy::Rebuild || non_java || has_record)
|
||||
}
|
||||
|
||||
fn same_entry(a: &str, b: &str, windows: bool) -> bool {
|
||||
@@ -1283,54 +1288,6 @@ mod tests {
|
||||
assert!(!delegates_to_external_build(false, BuildPolicy::Automatic, false, false, true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shared_builds_do_not_join_plain_java_launches_only_because_of_legacy_null_records() {
|
||||
use std::{fs, sync::Arc};
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
let cache_dir = root.join("cache");
|
||||
fs::write(
|
||||
root.join("pom.xml"),
|
||||
concat!(
|
||||
"<project><groupId>sample</groupId><artifactId>root</artifactId><version>1</version>",
|
||||
"<packaging>pom</packaging><modules><module>leader</module><module>plain</module>",
|
||||
"<module>dirty</module></modules></project>",
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
for name in ["leader", "plain", "dirty"] {
|
||||
let module = root.join(name);
|
||||
fs::create_dir_all(module.join("src/main/java")).unwrap();
|
||||
fs::write(module.join("src/main/java/Main.java"), "class Main {}").unwrap();
|
||||
fs::write(
|
||||
module.join("pom.xml"),
|
||||
format!(
|
||||
"<project><groupId>sample</groupId><artifactId>{name}</artifactId><version>1</version></project>"
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
let records = cache_dir.join("java-launch/records").join(name);
|
||||
fs::create_dir_all(&records).unwrap();
|
||||
fs::write(records.join("main.json"), b"null").unwrap();
|
||||
}
|
||||
fs::create_dir_all(root.join("dirty/target/classes")).unwrap();
|
||||
fs::write(root.join("dirty/target/classes/Old.class"), "old-output").unwrap();
|
||||
let model = ide_build::load(root, &cache_dir, None);
|
||||
let waiting = ["plain", "dirty"]
|
||||
.into_iter()
|
||||
.map(|name| {
|
||||
Arc::new(cache::WaitingLaunch {
|
||||
module: root.join(name),
|
||||
test: false,
|
||||
policy: BuildPolicy::Automatic,
|
||||
events: None,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let joined = joining_launches(root, &cache_dir, &model, &root.join("leader"), false, waiting, false);
|
||||
assert_eq!(joined.iter().map(|launch| &launch.module).collect::<Vec<_>>(), [&root.join("dirty")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn successful_external_compilation_does_not_erase_scoped_jdt_errors() {
|
||||
for (failure, expected) in
|
||||
|
||||
@@ -1,6 +1,4 @@
|
||||
//! Immutable Maven outputs retained in the project cache, including across close/reopen.
|
||||
mod delegation;
|
||||
|
||||
use ide_build::compile::{self, BuildEvent, LaunchFingerprint};
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult};
|
||||
use ide_run::BuildPolicy;
|
||||
@@ -129,14 +127,8 @@ fn record_path(root: &Path, cache: &Path, module: &Path, test: bool) -> Option<P
|
||||
}))
|
||||
}
|
||||
|
||||
pub(super) fn needs_cleanup(
|
||||
root: &Path,
|
||||
cache: &Path,
|
||||
model: &ide_build::BuildModel,
|
||||
module: &Path,
|
||||
test: bool,
|
||||
) -> bool {
|
||||
delegation::required(root, cache, model, module, test)
|
||||
pub(super) fn has_record(root: &Path, cache: &Path, module: &Path) -> bool {
|
||||
[false, true].into_iter().any(|test| record_path(root, cache, module, test).is_some_and(|record| record.is_file()))
|
||||
}
|
||||
|
||||
/// Where the build of a launch streams its console, messages and progress: the run
|
||||
@@ -241,8 +233,6 @@ struct Pending {
|
||||
record: PathBuf,
|
||||
before: Option<LaunchFingerprint>,
|
||||
previous: Option<Outputs>,
|
||||
non_java: bool,
|
||||
cleanup: bool,
|
||||
}
|
||||
|
||||
/// Owned by Project: running JVMs may still load superseded outputs until it drops.
|
||||
@@ -306,13 +296,13 @@ impl Session {
|
||||
// clean rebuild that replaces JDT's error-stub classes.
|
||||
let policy = if rebuild_on_jdt_errors { BuildPolicy::Rebuild } else { policy };
|
||||
let mut joined = Vec::new();
|
||||
let mut rebuild = policy == BuildPolicy::Rebuild || lead.cleanup;
|
||||
let mut rebuild = policy == BuildPolicy::Rebuild;
|
||||
let mut sinks: Vec<LaunchEvents> = events.into_iter().collect();
|
||||
for member in members {
|
||||
if let Err(pending) =
|
||||
self.prepare(root, model, &member.module, test, BuildPolicy::Make, &local_repo, cancel)?
|
||||
{
|
||||
rebuild |= member.rebuild_on_jdt_errors || pending.cleanup;
|
||||
rebuild |= member.rebuild_on_jdt_errors;
|
||||
sinks.extend(member.events);
|
||||
joined.push(pending);
|
||||
}
|
||||
@@ -376,9 +366,6 @@ impl Session {
|
||||
let snapshots = self.cache.join("java-launch/snapshots");
|
||||
let mut before = fingerprint(root, model, module, test, local_repo, cancel)?;
|
||||
let previous = fs::read(&record).ok().and_then(|bytes| serde_json::from_slice::<Outputs>(&bytes).ok());
|
||||
let non_java = compile::launch_has_non_java_sources(root, model, module, test);
|
||||
let needs_cleanup = needs_cleanup(root, &self.cache, model, module, test);
|
||||
let cleanup = needs_cleanup && !non_java;
|
||||
// Timestamp-incremental builders (Maven, the Kotlin plugin) skip sources whose
|
||||
// mtime did not advance. An external edit that preserves both length and mtime
|
||||
// invalidates the fingerprint but would still compile to nothing below, and the
|
||||
@@ -401,7 +388,6 @@ impl Session {
|
||||
}
|
||||
if let Some(outputs) = previous.as_ref()
|
||||
&& policy != BuildPolicy::Rebuild
|
||||
&& !cleanup
|
||||
&& let Some(maven) = &model.maven
|
||||
&& outputs.reusable(
|
||||
&before,
|
||||
@@ -419,18 +405,14 @@ impl Session {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
// Preserve build ownership independently of the reusable snapshot. In particular,
|
||||
// a plain Java build that fails must not force delegation after the user disables it.
|
||||
delegation::remember(root, &self.cache, module, test, non_java || needs_cleanup)?;
|
||||
match fs::remove_file(&record) {
|
||||
Ok(()) => {}
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
|
||||
Err(e) => return Err(e.into()),
|
||||
}
|
||||
// Retain a non-reusable record even on failure, so removing the final mixed
|
||||
// source still delegates to Maven to clean its old classes on the next launch.
|
||||
fs::create_dir_all(record.parent().unwrap())?;
|
||||
fs::write(&record, b"null")?;
|
||||
if let Some(previous) = &previous {
|
||||
self.unreferenced.push(previous.snapshot.clone());
|
||||
}
|
||||
Ok(Err(Pending { module: module.to_path_buf(), record, before, previous, non_java, cleanup }))
|
||||
Ok(Err(Pending { module: module.to_path_buf(), record, before, previous }))
|
||||
}
|
||||
|
||||
/// Copies the built outputs of a prepared module into a new snapshot and records it
|
||||
@@ -505,10 +487,6 @@ impl Session {
|
||||
write_record(&pending.record, &outputs)?;
|
||||
self.unreferenced.retain(|path| path != &outputs.snapshot);
|
||||
}
|
||||
if outputs.failure.is_none() && authoritative {
|
||||
let mixed = pending.non_java || compile::launch_has_non_java_sources(root, model, &pending.module, test);
|
||||
delegation::cleaned(root, &self.cache, &pending.module, test, mixed)?;
|
||||
}
|
||||
Ok(outputs)
|
||||
}
|
||||
}
|
||||
@@ -531,7 +509,7 @@ fn fingerprint(
|
||||
}
|
||||
}
|
||||
|
||||
fn write_record(record: &Path, outputs: &impl Serialize) -> IdeResult<()> {
|
||||
fn write_record(record: &Path, outputs: &Outputs) -> IdeResult<()> {
|
||||
fs::create_dir_all(record.parent().unwrap())?;
|
||||
let mut file = tempfile::NamedTempFile::new_in(record.parent().unwrap())?;
|
||||
serde_json::to_writer(file.as_file_mut(), outputs).map_err(|e| IdeError::internal(e.to_string()))?;
|
||||
@@ -552,7 +530,7 @@ impl Drop for Session {
|
||||
}
|
||||
|
||||
/// Clears the fingerprint of every launch record under `cache`, so no snapshot matches the
|
||||
/// sources any more. Delegation ownership is stored separately and is not invalidated.
|
||||
/// sources any more. The records stay: their modules keep delegating to Maven.
|
||||
fn forget_reusable_snapshots(cache: &Path) -> std::io::Result<()> {
|
||||
let records = cache.join("java-launch/records");
|
||||
if !records.try_exists()? {
|
||||
@@ -631,231 +609,6 @@ fn sweep(cache: &Path) -> std::io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod delegation_tests {
|
||||
use super::*;
|
||||
|
||||
fn fixture(root: &Path, mixed: bool) -> ide_build::BuildModel {
|
||||
fs::write(
|
||||
root.join("pom.xml"),
|
||||
r#"<project><groupId>sample</groupId><artifactId>app</artifactId><version>1</version></project>"#,
|
||||
)
|
||||
.unwrap();
|
||||
fs::create_dir_all(root.join("src/main/java")).unwrap();
|
||||
fs::write(root.join("src/main/java/Main.java"), "java-source").unwrap();
|
||||
if mixed {
|
||||
fs::create_dir_all(root.join("src/main/kotlin")).unwrap();
|
||||
fs::write(root.join("src/main/kotlin/Extra.kt"), "mixed-source").unwrap();
|
||||
}
|
||||
// A synthetic Maven wrapper: no JDK, Maven installation or network required.
|
||||
#[cfg(windows)]
|
||||
fs::write(root.join("mvnw.cmd"), concat!(
|
||||
"@echo off\r\necho %*>>calls\r\n",
|
||||
"if exist fail-build exit /b 1\r\n",
|
||||
"for %%a in (%*) do if \"%%a\"==\"clean\" if exist target rmdir /s /q target\r\n",
|
||||
"if not exist target\\classes mkdir target\\classes\r\n",
|
||||
"copy /y src\\main\\java\\Main.java target\\classes\\Main.class >nul\r\n",
|
||||
"if exist src\\main\\kotlin\\Extra.kt copy /y src\\main\\kotlin\\Extra.kt target\\classes\\Extra.class >nul\r\n",
|
||||
"if exist edit-during-build echo changed>>src\\main\\java\\Main.java\r\n",
|
||||
"if exist block-record (\r\n",
|
||||
"if not exist cache\\java-launch\\records mkdir cache\\java-launch\\records\r\n",
|
||||
"if exist cache\\java-launch\\records\\main.json del /q cache\\java-launch\\records\\main.json\r\n",
|
||||
"mkdir cache\\java-launch\\records\\main.json\r\n",
|
||||
")\r\n",
|
||||
"exit /b 0\r\n",
|
||||
)).unwrap();
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let script = root.join("mvnw");
|
||||
fs::write(&script, concat!(
|
||||
"#!/bin/sh\nset -e\nprintf '%s\\n' \"$*\" >> calls\n",
|
||||
"if [ -f fail-build ]; then exit 1; fi\n",
|
||||
"for arg in \"$@\"; do if [ \"$arg\" = clean ]; then rm -rf target; fi; done\n",
|
||||
"mkdir -p target/classes\ncp src/main/java/Main.java target/classes/Main.class\n",
|
||||
"if [ -f src/main/kotlin/Extra.kt ]; then cp src/main/kotlin/Extra.kt target/classes/Extra.class; fi\n",
|
||||
"if [ -f edit-during-build ]; then echo changed >> src/main/java/Main.java; fi\n",
|
||||
"if [ -f block-record ]; then\n",
|
||||
"mkdir -p cache/java-launch/records\nrm -f cache/java-launch/records/main.json\n",
|
||||
"mkdir cache/java-launch/records/main.json\nfi\n",
|
||||
)).unwrap();
|
||||
fs::set_permissions(script, fs::Permissions::from_mode(0o755)).unwrap();
|
||||
}
|
||||
ide_build::load(root, &root.join("cache"), None)
|
||||
}
|
||||
|
||||
fn legacy(root: &Path, test: bool, bytes: &[u8]) {
|
||||
let record = record_path(root, &root.join("cache"), root, test).unwrap();
|
||||
fs::create_dir_all(record.parent().unwrap()).unwrap();
|
||||
fs::write(record, bytes).unwrap();
|
||||
}
|
||||
|
||||
fn calls(root: &Path) -> Vec<String> {
|
||||
fs::read_to_string(root.join("calls")).unwrap_or_default().lines().map(str::to_owned).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_record_publication_keeps_new_and_previous_snapshots_until_session_drop() {
|
||||
for has_previous in [false, true] {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
let model = fixture(root, false);
|
||||
let cache = root.join("cache");
|
||||
let cancel = CancellationToken::new();
|
||||
let mut session = Session::new(cache.clone());
|
||||
if has_previous {
|
||||
session.build(root, &model, root, BuildOptions::default(), None, &cancel).unwrap();
|
||||
}
|
||||
fs::write(root.join("src/main/java/Main.java"), "edited-java-source").unwrap();
|
||||
fs::write(root.join("block-record"), "").unwrap();
|
||||
let error = session.build(root, &model, root, BuildOptions::default(), None, &cancel).unwrap_err();
|
||||
// Reach publication, rather than accepting an earlier wrapper/build failure.
|
||||
assert!(!error.message.starts_with("Build failed:"), "{error:?}");
|
||||
assert!(cache.join("java-launch/records/main.json").is_dir());
|
||||
assert_eq!(session.unreferenced.len(), if has_previous { 2 } else { 1 });
|
||||
let snapshots = session.unreferenced.clone();
|
||||
assert_eq!(
|
||||
fs::read_to_string(snapshots.last().unwrap().join("0/Main.class")).unwrap(),
|
||||
"edited-java-source"
|
||||
);
|
||||
assert!(snapshots.iter().all(|p| p.join("0/Main.class").is_file()));
|
||||
drop(session);
|
||||
assert!(snapshots.iter().all(|p| !p.exists()));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn null_record_without_outputs_does_not_keep_delegation() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
let cache = root.join("cache");
|
||||
let model = fixture(root, false);
|
||||
legacy(root, false, b"null");
|
||||
assert!(!needs_cleanup(root, &cache, &model, root, false));
|
||||
// The IDE's Java builder may produce outputs afterwards: migration must stick.
|
||||
fs::create_dir_all(root.join("target/classes")).unwrap();
|
||||
fs::write(root.join("target/classes/Main.class"), "java-output").unwrap();
|
||||
assert!(!needs_cleanup(root, &cache, &model, root, false));
|
||||
assert!(calls(root).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plain_java_failures_and_unpublished_snapshots_do_not_require_maven() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
let model = fixture(root, false);
|
||||
let cache = root.join("cache");
|
||||
let cancel = CancellationToken::new();
|
||||
let mut session = Session::new(cache.clone());
|
||||
fs::write(root.join("fail-build"), "").unwrap();
|
||||
assert!(session.build(root, &model, root, BuildOptions::default(), None, &cancel).is_err());
|
||||
assert!(!needs_cleanup(root, &cache, &model, root, false));
|
||||
fs::remove_file(root.join("fail-build")).unwrap();
|
||||
fs::write(root.join("edit-during-build"), "").unwrap();
|
||||
let outputs = session.build(root, &model, root, BuildOptions::default(), None, &cancel).unwrap();
|
||||
assert!(outputs.fingerprint.is_none());
|
||||
assert!(!cache.join("java-launch/records/main.json").exists());
|
||||
assert!(!needs_cleanup(root, &cache, &model, root, false));
|
||||
// A valid snapshot is also not a reason to override the user's build preference.
|
||||
fs::remove_file(root.join("edit-during-build")).unwrap();
|
||||
session.build(root, &model, root, BuildOptions::default(), None, &cancel).unwrap();
|
||||
assert!(cache.join("java-launch/records/main.json").is_file());
|
||||
assert!(!needs_cleanup(root, &cache, &model, root, false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn legacy_null_or_damaged_records_with_outputs_are_cleaned_once() {
|
||||
for bytes in [b"null".as_slice(), b"{invalid".as_slice()] {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
let model = fixture(root, false);
|
||||
let cache = root.join("cache");
|
||||
legacy(root, false, bytes);
|
||||
fs::create_dir_all(root.join("target/classes")).unwrap();
|
||||
fs::write(root.join("target/classes/Old.class"), "unknown-old-output").unwrap();
|
||||
assert!(needs_cleanup(root, &cache, &model, root, false));
|
||||
let mut session = Session::new(cache.clone());
|
||||
session.build(root, &model, root, BuildOptions::default(), None, &CancellationToken::new()).unwrap();
|
||||
drop(session);
|
||||
assert!(!root.join("target/classes/Old.class").exists());
|
||||
assert!(!needs_cleanup(root, &cache, &model, root, false));
|
||||
assert_eq!(calls(root).len(), 1);
|
||||
assert!(calls(root)[0].contains("clean"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_legacy_reusable_snapshot_cannot_skip_pending_cleanup() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
let model = fixture(root, false);
|
||||
let cache = root.join("cache");
|
||||
let cancel = CancellationToken::new();
|
||||
let mut session = Session::new(cache.clone());
|
||||
let before = session.build(root, &model, root, BuildOptions::default(), None, &cancel).unwrap();
|
||||
// Simulate a successful record written before ownership was tracked separately.
|
||||
fs::remove_file(cache.join("java-launch/delegation/main.json")).unwrap();
|
||||
assert!(needs_cleanup(root, &cache, &model, root, false));
|
||||
let after = session.build(root, &model, root, BuildOptions::default(), None, &cancel).unwrap();
|
||||
assert_ne!(before.snapshot, after.snapshot);
|
||||
assert_eq!(calls(root).len(), 2);
|
||||
assert!(calls(root)[1].contains("clean"));
|
||||
assert!(!needs_cleanup(root, &cache, &model, root, false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mixed_cleanup_survives_failure_and_reopen_then_releases_delegation() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
let model = fixture(root, true);
|
||||
let cache = root.join("cache");
|
||||
let cancel = CancellationToken::new();
|
||||
let mut session = Session::new(cache.clone());
|
||||
session.build(root, &model, root, BuildOptions::default(), None, &cancel).unwrap();
|
||||
assert!(root.join("target/classes/Extra.class").is_file());
|
||||
fs::remove_file(root.join("src/main/kotlin/Extra.kt")).unwrap();
|
||||
fs::write(root.join("fail-build"), "").unwrap();
|
||||
assert!(session.build(root, &model, root, BuildOptions::default(), None, &cancel).is_err());
|
||||
drop(session);
|
||||
assert!(needs_cleanup(root, &cache, &model, root, false));
|
||||
fs::remove_file(root.join("fail-build")).unwrap();
|
||||
let mut session = Session::new(cache.clone());
|
||||
session.build(root, &model, root, BuildOptions::default(), None, &cancel).unwrap();
|
||||
assert!(!root.join("target/classes/Extra.class").exists());
|
||||
assert!(!needs_cleanup(root, &cache, &model, root, false));
|
||||
assert_eq!(calls(root).len(), 3);
|
||||
assert!(calls(root)[1..].iter().all(|call| call.contains("clean")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_cleanup_does_not_force_a_main_launch_and_a_clean_test_build_releases_both_modes() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
let model = fixture(root, false);
|
||||
let cache = root.join("cache");
|
||||
legacy(root, true, b"null");
|
||||
fs::create_dir_all(root.join("target/test-classes")).unwrap();
|
||||
fs::write(root.join("target/test-classes/OldTest.class"), "old-test-output").unwrap();
|
||||
assert!(!needs_cleanup(root, &cache, &model, root, false));
|
||||
assert!(needs_cleanup(root, &cache, &model, root, true));
|
||||
delegation::remember(root, &cache, root, false, true).unwrap();
|
||||
let mut session = Session::new(cache.clone());
|
||||
session
|
||||
.build(
|
||||
root,
|
||||
&model,
|
||||
root,
|
||||
BuildOptions { test: true, ..Default::default() },
|
||||
None,
|
||||
&CancellationToken::new(),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(!needs_cleanup(root, &cache, &model, root, false));
|
||||
assert!(!needs_cleanup(root, &cache, &model, root, true));
|
||||
assert!(!root.join("target/test-classes/OldTest.class").exists());
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(test, unix))]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -1111,7 +864,7 @@ mod tests {
|
||||
// Build › Rebuild cleans the outputs and compiles again.
|
||||
fs::remove_file(root.join("target/classes/Stale.class")).unwrap();
|
||||
session.forget_reusable_snapshots();
|
||||
assert!(needs_cleanup(root, &root.join("cache"), &model, root, false));
|
||||
assert!(has_record(root, &root.join("cache"), root));
|
||||
let next = session.build(root, &model, root, BuildOptions::default(), None, &cancel).unwrap();
|
||||
assert_ne!(next.snapshot, first.snapshot);
|
||||
assert!(!next.snapshot.join("0/Stale.class").exists());
|
||||
@@ -1190,7 +943,7 @@ mod tests {
|
||||
assert_ne!(rebuilt.snapshot, updated.snapshot);
|
||||
fs::write(root.join("src/main/kotlin/broken"), "broken").unwrap();
|
||||
assert!(build().is_err());
|
||||
assert!(!cache.join("java-launch/records/main.json").exists());
|
||||
assert_eq!(fs::read(cache.join("java-launch/records/main.json")).unwrap(), b"null");
|
||||
fs::remove_file(root.join("src/main/kotlin/broken")).unwrap();
|
||||
assert_ne!(rebuilt.snapshot, build().unwrap().snapshot, "a failed build invalidates success");
|
||||
cancel.cancel();
|
||||
@@ -1344,16 +1097,11 @@ mod tests {
|
||||
let model = fixture(root);
|
||||
let script = root.join("mvnw");
|
||||
let mut text = fs::read_to_string(&script).unwrap();
|
||||
// Snapshot invalidation no longer writes a null record or creates its parent.
|
||||
// Arrange a publish failure independently of that earlier implementation detail.
|
||||
text.push_str("mkdir -p cache/java-launch/records\nrm -f cache/java-launch/records/main.json\nmkdir cache/java-launch/records/main.json\n");
|
||||
text.push_str("rm cache/java-launch/records/main.json\nmkdir cache/java-launch/records/main.json\n");
|
||||
fs::write(script, text).unwrap();
|
||||
let cache = root.join("cache");
|
||||
let mut session = Session::new(cache.clone());
|
||||
let error =
|
||||
session.build(root, &model, root, BuildOptions::default(), None, &CancellationToken::new()).unwrap_err();
|
||||
assert!(!error.message.starts_with("Build failed:"), "{error:?}");
|
||||
assert!(cache.join("java-launch/records/main.json").is_dir());
|
||||
assert!(session.build(root, &model, root, BuildOptions::default(), None, &CancellationToken::new()).is_err());
|
||||
assert_eq!(session.unreferenced.len(), 1);
|
||||
let snapshot = session.unreferenced[0].clone();
|
||||
assert!(snapshot.join("0/Main.class").is_file());
|
||||
@@ -1375,7 +1123,7 @@ mod tests {
|
||||
let outputs =
|
||||
session.build(root, &model, root, BuildOptions::default(), None, &CancellationToken::new()).unwrap();
|
||||
assert!(outputs.fingerprint.is_none());
|
||||
assert!(!cache.join("java-launch/records/main.json").exists());
|
||||
assert_eq!(fs::read(cache.join("java-launch/records/main.json")).unwrap(), b"null");
|
||||
assert!(outputs.snapshot.join("0/Main.class").is_file());
|
||||
drop(session);
|
||||
assert!(!outputs.snapshot.exists());
|
||||
@@ -1517,9 +1265,9 @@ mod tests {
|
||||
let first = session.build(root, &model, root, BuildOptions::default(), None, &cancel).unwrap();
|
||||
fs::remove_file(root.join("src/main/kotlin/Main.kt")).unwrap();
|
||||
assert!(!compile::launch_has_non_java_sources(root, &model, root, false));
|
||||
assert!(needs_cleanup(root, &cache, &model, root, false));
|
||||
assert!(has_record(root, &cache, root));
|
||||
assert!(session.build(root, &model, root, BuildOptions::default(), None, &cancel).is_err());
|
||||
assert!(needs_cleanup(root, &cache, &model, root, false));
|
||||
assert!(has_record(root, &cache, root));
|
||||
fs::write(root.join("src/main/kotlin/Main.kt"), "restored").unwrap();
|
||||
let restored = session.build(root, &model, root, BuildOptions::default(), None, &cancel).unwrap();
|
||||
assert_ne!(first.snapshot, restored.snapshot);
|
||||
|
||||
@@ -1,81 +0,0 @@
|
||||
//! Build ownership is independent of whether a launch snapshot can be reused.
|
||||
use super::{record_path, write_record};
|
||||
use ide_build::{BuildModel, compile};
|
||||
use ide_core::IdeResult;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::fs;
|
||||
use std::io::ErrorKind;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct State {
|
||||
/// External outputs may contain classes that JDT cannot remove after the final
|
||||
/// Kotlin/Groovy/Scala source is deleted. Only a successful clean clears this.
|
||||
needs_cleanup: bool,
|
||||
}
|
||||
|
||||
fn state_path(root: &Path, cache: &Path, module: &Path, test: bool) -> Option<PathBuf> {
|
||||
Some(cache.join("java-launch/delegation").join(module.strip_prefix(root).ok()?).join(if test {
|
||||
"test.json"
|
||||
} else {
|
||||
"main.json"
|
||||
}))
|
||||
}
|
||||
|
||||
/// A test launch also uses main outputs; a main launch does not use test outputs.
|
||||
pub(super) fn required(root: &Path, cache: &Path, model: &BuildModel, module: &Path, test: bool) -> bool {
|
||||
mode_required(root, cache, model, module, false) || (test && mode_required(root, cache, model, module, true))
|
||||
}
|
||||
|
||||
fn mode_required(root: &Path, cache: &Path, model: &BuildModel, module: &Path, test: bool) -> bool {
|
||||
let Some(state) = state_path(root, cache, module, test) else { return false };
|
||||
match fs::read(&state) {
|
||||
Ok(bytes) => {
|
||||
// A damaged ownership marker must not silently abandon pending cleanup.
|
||||
return serde_json::from_slice::<State>(&bytes).map_or(true, |state| state.needs_cleanup);
|
||||
}
|
||||
Err(e) if e.kind() == ErrorKind::NotFound => {}
|
||||
Err(_) => return true,
|
||||
}
|
||||
let Some(record) = record_path(root, cache, module, test).filter(|p| p.is_file()) else { return false };
|
||||
let Some(maven) = &model.maven else { return false };
|
||||
// Old records (including `null`) did not record why Maven owned the outputs.
|
||||
// If outputs remain, clean once rather than guessing that they are all Java.
|
||||
// Persist even a negative migration: subsequent JDT output must not turn an
|
||||
// already ignored legacy record back into a reason to delegate.
|
||||
let needs_cleanup = compile::maven_launch_output_dirs(root, maven, module, test).iter().any(|dir| dir.is_dir());
|
||||
let publish = || -> std::io::Result<()> {
|
||||
fs::create_dir_all(state.parent().unwrap())?;
|
||||
let mut file = tempfile::NamedTempFile::new_in(state.parent().unwrap())?;
|
||||
serde_json::to_writer(file.as_file_mut(), &State { needs_cleanup })?;
|
||||
// Another launch may already have migrated or started building this mode.
|
||||
file.persist_noclobber(&state).map_err(|e| e.error)?;
|
||||
Ok(())
|
||||
};
|
||||
match publish() {
|
||||
Ok(()) => needs_cleanup,
|
||||
Err(e) if e.kind() == ErrorKind::AlreadyExists => mode_required(root, cache, model, module, test),
|
||||
Err(error) => {
|
||||
tracing::warn!(%error, path = %record.display(), "Cannot migrate Java launch delegation state");
|
||||
needs_cleanup
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Called before invalidating a snapshot or running an external build. A plain
|
||||
/// Java failure records `false`; it must not override a later delegateBuild=false.
|
||||
pub(super) fn remember(root: &Path, cache: &Path, module: &Path, test: bool, needs_cleanup: bool) -> IdeResult<()> {
|
||||
if let Some(path) = state_path(root, cache, module, test) {
|
||||
write_record(&path, &State { needs_cleanup })?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn cleaned(root: &Path, cache: &Path, module: &Path, test: bool, mixed: bool) -> IdeResult<()> {
|
||||
remember(root, cache, module, test, mixed)?;
|
||||
if test && !mixed {
|
||||
// A clean test build includes the main outputs and their reactor dependencies.
|
||||
remember(root, cache, module, false, false)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -846,7 +846,7 @@ pub async fn lsp_library_sources(
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub async fn lsp_resolve_class_file(host: &Host, window: &str, path: std::path::PathBuf) -> IdeResult<String> {
|
||||
// Opens compiled classes through JDT as decompiled class documents.
|
||||
// Opens compiled classes through JDT, with project source taking priority on disk.
|
||||
let archive = ide_vfs::split_archive_path(&path);
|
||||
host.project(window)?.lsp.java_class_file(&path, archive).await
|
||||
}
|
||||
|
||||
@@ -17,31 +17,27 @@ pub mod docker;
|
||||
pub mod env;
|
||||
pub mod flutter;
|
||||
pub mod fs;
|
||||
pub mod github;
|
||||
pub mod heap;
|
||||
pub mod history;
|
||||
pub mod host_metrics;
|
||||
pub mod http;
|
||||
pub mod ios;
|
||||
pub mod java;
|
||||
pub mod jvm_icons;
|
||||
pub mod lsp;
|
||||
pub mod maven_placeholder;
|
||||
pub mod nav;
|
||||
pub mod notebook;
|
||||
pub mod plots;
|
||||
mod plots;
|
||||
pub mod project;
|
||||
pub mod pytest_fixtures;
|
||||
mod python;
|
||||
pub mod python_stubs;
|
||||
pub mod refactor;
|
||||
pub mod routes;
|
||||
pub mod rst;
|
||||
pub mod run;
|
||||
pub mod scaffold;
|
||||
pub mod sdk;
|
||||
pub mod search;
|
||||
pub mod settings_sync;
|
||||
pub mod spell;
|
||||
pub mod ssh;
|
||||
pub mod stream_trace;
|
||||
@@ -51,7 +47,6 @@ pub mod thread_dump;
|
||||
pub mod tools;
|
||||
pub mod vcs;
|
||||
pub mod web;
|
||||
pub mod xcode_bsp;
|
||||
|
||||
use crate::Host;
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
@@ -99,12 +94,10 @@ ide_command::domains!(
|
||||
env: crate::ops::env,
|
||||
flutter: crate::ops::flutter,
|
||||
fs: crate::ops::fs,
|
||||
github: crate::ops::github,
|
||||
heap: crate::ops::heap,
|
||||
history: crate::ops::history,
|
||||
host_metrics: crate::ops::host_metrics,
|
||||
http: crate::ops::http,
|
||||
ios: crate::ops::ios,
|
||||
java: crate::ops::java,
|
||||
jvm_icons: crate::ops::jvm_icons,
|
||||
lsp: crate::ops::lsp,
|
||||
@@ -112,7 +105,6 @@ ide_command::domains!(
|
||||
mcp_reports: crate::mcp::reports,
|
||||
nav: crate::ops::nav,
|
||||
notebook: crate::ops::notebook,
|
||||
plots: crate::ops::plots,
|
||||
plugins_commands: crate::plugins::commands,
|
||||
plugins_commit: crate::plugins::commit,
|
||||
plugins_index_ops: crate::plugins::index_ops,
|
||||
@@ -121,7 +113,6 @@ ide_command::domains!(
|
||||
plugins_views: crate::plugins::views,
|
||||
project: crate::ops::project,
|
||||
refactor: crate::ops::refactor,
|
||||
rst: crate::ops::rst,
|
||||
run: crate::ops::run,
|
||||
run_commands: crate::ops::run::commands,
|
||||
scaffold: crate::ops::scaffold,
|
||||
@@ -139,7 +130,6 @@ ide_command::domains!(
|
||||
vcs: crate::ops::vcs,
|
||||
vcs_commands: crate::ops::vcs::commands,
|
||||
web: crate::ops::web,
|
||||
xcode_bsp: crate::ops::xcode_bsp,
|
||||
);
|
||||
|
||||
/// A blocking task that panicked or was cancelled, as the error a command returns.
|
||||
|
||||
@@ -1,17 +1,12 @@
|
||||
use super::blocking;
|
||||
use super::pytest_fixtures::{
|
||||
PytestFixtureAt, PytestFixtureRename, PytestFixtureTarget, PytestFixtureUsages, fixture_at, fixture_target,
|
||||
fixture_usages, rename_fixture,
|
||||
};
|
||||
use super::pytest_fixtures::{PytestFixtureAt, PytestFixtureUsages, fixture_at, fixture_usages, rename_fixture};
|
||||
use super::python_stubs::{
|
||||
PythonStubLinks, counterpart_candidates, interpreter_site_packages, match_declarations, module_name, site_packages,
|
||||
stub_path,
|
||||
PythonStubLinks, counterpart_candidates, match_declarations, module_name, site_packages, stub_path,
|
||||
};
|
||||
use crate::Host;
|
||||
use crate::Project;
|
||||
use ide_command::command;
|
||||
use ide_core::{DocId, IdeResult, IpcPath, LanguageId, Location, Pos, RequestId};
|
||||
use ide_index::python_library::{PythonImportCandidate, PythonLibraries};
|
||||
use ide_core::{DocId, IdeResult, IpcPath, LanguageId, Location, Pos, RequestId, WorkspaceEdit};
|
||||
use ide_index::{ExtensionCount, FileMatch, IndexStatus, SymbolFilter, SymbolMatch};
|
||||
use ide_language::{CSS_VARIABLE, FileReference, WebReference};
|
||||
use ide_workspace::file_refs::{self, PathCompletion};
|
||||
@@ -501,41 +496,6 @@ pub async fn nav_pytest_fixtures(host: &Host, window: &str, doc: DocId, pos: Pos
|
||||
.await
|
||||
}
|
||||
|
||||
static PYTHON_LIBRARIES: std::sync::LazyLock<PythonLibraries> = std::sync::LazyLock::new(Default::default);
|
||||
|
||||
/// Imports that bind `name` from the packages installed in the interpreter of the Python document
|
||||
/// `doc` (its workspace member's, else the project's): PyCharm's "Import this name" for library
|
||||
/// symbols, which basedpyright offers for the project and the standard library only. The first
|
||||
/// request indexes the interpreter's `site-packages` in the background, and a change there
|
||||
/// re-indexes it; a request waits for the index until cancelled.
|
||||
#[command(trust = always)]
|
||||
pub async fn nav_python_library_imports(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
doc: DocId,
|
||||
name: String,
|
||||
request: RequestId,
|
||||
) -> IdeResult<Vec<PythonImportCandidate>> {
|
||||
let project = host.project(window)?;
|
||||
let syntax = host.syntax();
|
||||
let config_dir = host.config_dir.clone();
|
||||
let token = host.begin_request(request);
|
||||
let result = blocking(move || {
|
||||
let snap = project.documents.snapshot(doc)?;
|
||||
if snap.language.as_str() != "python" {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let Some(python) = super::sdk::effective_python(&config_dir, &project, Some(&snap.path)) else {
|
||||
return Ok(Vec::new());
|
||||
};
|
||||
let roots = interpreter_site_packages(&python);
|
||||
Ok(PYTHON_LIBRARIES.index(&roots, &syntax, &token).map(|index| index.candidates(&name)).unwrap_or_default())
|
||||
})
|
||||
.await;
|
||||
host.end_request(request);
|
||||
result
|
||||
}
|
||||
|
||||
/// Find Usages of the pytest fixture at `pos` (its definition, or a place asking for it): every
|
||||
/// test and fixture parameter, `usefixtures` and `getfixturevalue` string that gets it.
|
||||
/// None when `pos` names no fixture. Cancellable.
|
||||
@@ -562,30 +522,8 @@ pub async fn nav_pytest_fixture_usages(
|
||||
result
|
||||
}
|
||||
|
||||
/// The pytest fixture at `pos` (its definition, a place asking for it, or a read of such a
|
||||
/// parameter in a function body), without searching the project: what Rename renames.
|
||||
#[command(trust = always)]
|
||||
pub async fn nav_pytest_fixture_target(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
doc: DocId,
|
||||
pos: Pos,
|
||||
) -> IdeResult<Option<PytestFixtureTarget>> {
|
||||
let project = host.project(window)?;
|
||||
let syntax = host.syntax();
|
||||
blocking(move || {
|
||||
let snap = project.documents.snapshot(doc)?;
|
||||
if snap.large || snap.language.as_str() != "python" {
|
||||
return Ok(None);
|
||||
}
|
||||
Ok(fixture_target(&project, &syntax, &snap.path, &snap.text, pos))
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Rename of the pytest fixture at `pos`: its definition, every place that gets it and the
|
||||
/// reads of those parameters in their functions; or the parameter or fixture the new name
|
||||
/// would clash with. Cancellable.
|
||||
/// uses of those parameters in their functions. Cancellable.
|
||||
#[command(trust = always)]
|
||||
pub async fn nav_pytest_fixture_rename(
|
||||
host: &Host,
|
||||
@@ -594,19 +532,19 @@ pub async fn nav_pytest_fixture_rename(
|
||||
pos: Pos,
|
||||
new_name: String,
|
||||
request: RequestId,
|
||||
) -> IdeResult<PytestFixtureRename> {
|
||||
) -> IdeResult<WorkspaceEdit> {
|
||||
let project = host.project(window)?;
|
||||
let syntax = host.syntax();
|
||||
let token = host.begin_request(request);
|
||||
let result = blocking(move || {
|
||||
let snap = project.documents.snapshot(doc)?;
|
||||
let mut renamed =
|
||||
let mut edit =
|
||||
rename_fixture(&project, &syntax, &snap.path, &snap.text, pos, &new_name, &|| token.is_cancelled())?;
|
||||
if token.is_cancelled() {
|
||||
return Err(ide_core::IdeError::cancelled());
|
||||
}
|
||||
project.documents.prepare_workspace_edit(&mut renamed.edit)?;
|
||||
Ok(renamed)
|
||||
project.documents.prepare_workspace_edit(&mut edit)?;
|
||||
Ok(edit)
|
||||
})
|
||||
.await;
|
||||
host.end_request(request);
|
||||
@@ -627,10 +565,8 @@ ide_command::domain!(
|
||||
nav_index_definitions,
|
||||
nav_inheritance,
|
||||
nav_pytest_fixture_rename,
|
||||
nav_pytest_fixture_target,
|
||||
nav_pytest_fixture_usages,
|
||||
nav_pytest_fixtures,
|
||||
nav_python_library_imports,
|
||||
nav_python_stubs,
|
||||
nav_resolve_module,
|
||||
path_completions,
|
||||
|
||||
@@ -4,7 +4,6 @@ pub use crate::notebook::NotebookOutputEvent;
|
||||
use crate::ops::Channel;
|
||||
use ide_command::command;
|
||||
use ide_core::{IdeError, IdeResult, RequestId};
|
||||
use ide_notebook::kernel::{KernelSpec, KernelTarget, RemoteKernel, kernel_specs, normalize_server_url};
|
||||
use ide_notebook::{NotebookEdit, NotebookSnapshot};
|
||||
use std::path::PathBuf;
|
||||
|
||||
@@ -123,23 +122,8 @@ pub async fn notebook_execute(
|
||||
let _request = RequestGuard { host, request, cancel: cancel.clone() };
|
||||
// Reserve the WHOLE batch and capture source before asynchronous discovery.
|
||||
let admission = project.notebooks.admit(&id, cells, cancel.clone())?;
|
||||
let target = kernel_target(host, &project, python, &cancel).await?;
|
||||
project.notebooks.execute(admission, target, on_output).await
|
||||
}
|
||||
|
||||
/// The kernel the notebook's drop-down chose: an interpreter (the project's when `None`) or
|
||||
/// `<server>#<kernel spec>` of a saved Jupyter server.
|
||||
async fn kernel_target(
|
||||
host: &Host,
|
||||
project: &crate::Project,
|
||||
python: Option<String>,
|
||||
cancel: &ide_core::CancellationToken,
|
||||
) -> IdeResult<KernelTarget> {
|
||||
let selected = match python {
|
||||
Some(path) if path.trim().is_empty() => return Err(IdeError::invalid("select a Python interpreter")),
|
||||
Some(kernel) if kernel.starts_with("http://") || kernel.starts_with("https://") => {
|
||||
return Ok(KernelTarget::Remote(remote_kernel(host, &kernel)?));
|
||||
}
|
||||
Some(path) => PathBuf::from(path),
|
||||
None => {
|
||||
let root = project.root.clone();
|
||||
@@ -158,92 +142,8 @@ async fn kernel_target(
|
||||
};
|
||||
// Do not canonicalize this path: resolving a venv symlink to base Python
|
||||
// changes sys.prefix and executes in the wrong environment.
|
||||
Ok(KernelTarget::Local(if selected.is_absolute() { selected } else { project.root.join(selected) }))
|
||||
}
|
||||
|
||||
/// Debug Cell: a debug session named `name` on the notebook's kernel, starting the kernel
|
||||
/// when none runs. The caller then runs the cell; ending the session leaves the kernel and
|
||||
/// its state running.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn notebook_debug_start(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
id: String,
|
||||
python: Option<String>,
|
||||
name: String,
|
||||
just_my_code: bool,
|
||||
) -> IdeResult<ide_core::DebugSessionId> {
|
||||
host.require_trust(window)?;
|
||||
let project = host.project(window)?;
|
||||
let cancel = project.closed.child_token();
|
||||
let target = kernel_target(host, &project, python, &cancel).await?;
|
||||
let (debugger, cells, notebook_cells) = project.notebooks.debugger(&id, target, cancel).await?;
|
||||
let (reader, writer) = tokio::io::split(ide_notebook::kernel::debug::dap_stream(debugger, cells));
|
||||
let io = ide_dap::adapter::AdapterIo {
|
||||
launch_after_configuration: false,
|
||||
reader: Box::new(reader),
|
||||
writer: Box::new(writer),
|
||||
child: None,
|
||||
port: None,
|
||||
stderr: Default::default(),
|
||||
program_output: None,
|
||||
};
|
||||
let owner = ide_dap::SessionOwner::new(host.owner_window(window), host.window_sink(window));
|
||||
let arguments = serde_json::json!({ "justMyCode": just_my_code });
|
||||
host.debugger.start_over(io, name, ide_dap::NOTEBOOK_ADAPTER.into(), arguments, owner, Some(notebook_cells)).await
|
||||
}
|
||||
|
||||
/// A kernel choice on a Jupyter server, `<server base URL>#<kernel spec>`, with its saved token.
|
||||
fn remote_kernel(host: &Host, choice: &str) -> IdeResult<RemoteKernel> {
|
||||
let (base, spec) = choice
|
||||
.split_once('#')
|
||||
.filter(|(_, spec)| !spec.is_empty())
|
||||
.ok_or_else(|| IdeError::invalid("select a kernel of the Jupyter server"))?;
|
||||
let token = host.jupyter_tokens.get(base).ok_or_else(|| {
|
||||
IdeError::unavailable(format!("connect to the Jupyter server {base} again: its token is not saved"))
|
||||
})?;
|
||||
Ok(RemoteKernel { base: base.to_owned(), token, spec: spec.to_owned() })
|
||||
}
|
||||
|
||||
/// A Jupyter server notebooks can run on.
|
||||
#[derive(serde::Serialize, specta::Type)]
|
||||
pub struct JupyterServer {
|
||||
/// Base URL, ending in `/`.
|
||||
pub url: String,
|
||||
pub kernels: Vec<KernelSpec>,
|
||||
}
|
||||
|
||||
/// Checks `url` and `token` against the server and saves them. A `?token=` in the URL
|
||||
/// (as JupyterLab prints it) is used when `token` is empty.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn jupyter_server_add(host: &Host, window: &str, url: String, token: String) -> IdeResult<JupyterServer> {
|
||||
host.require_trust(window)?;
|
||||
let (url, in_url) = normalize_server_url(&url)?;
|
||||
let token = if token.trim().is_empty() { in_url.unwrap_or_default() } else { token.trim().to_owned() };
|
||||
let kernels = kernel_specs(&url, &token).await?;
|
||||
host.jupyter_tokens.set(&url, &token)?;
|
||||
Ok(JupyterServer { url, kernels })
|
||||
}
|
||||
|
||||
/// The saved servers and their kernel specs; a server that cannot be reached has none.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn jupyter_servers(host: &Host, window: &str) -> IdeResult<Vec<JupyterServer>> {
|
||||
host.require_trust(window)?;
|
||||
let servers = host.jupyter_tokens.keys().into_iter().map(|url| async move {
|
||||
let kernels = match host.jupyter_tokens.get(&url) {
|
||||
Some(token) => kernel_specs(&url, &token).await.unwrap_or_default(),
|
||||
None => Vec::new(),
|
||||
};
|
||||
JupyterServer { url, kernels }
|
||||
});
|
||||
Ok(futures::future::join_all(servers).await)
|
||||
}
|
||||
|
||||
#[command(trust = always)]
|
||||
pub fn jupyter_server_remove(host: &Host, window: &str, url: String) -> IdeResult<()> {
|
||||
let _ = window;
|
||||
host.jupyter_tokens.delete(&url);
|
||||
Ok(())
|
||||
let python = if selected.is_absolute() { selected } else { project.root.join(selected) };
|
||||
project.notebooks.execute(admission, python, on_output).await
|
||||
}
|
||||
|
||||
struct RequestGuard<'a> {
|
||||
@@ -262,12 +162,8 @@ impl Drop for RequestGuard<'_> {
|
||||
|
||||
ide_command::domain!(
|
||||
notebook:
|
||||
jupyter_server_add,
|
||||
jupyter_server_remove,
|
||||
jupyter_servers,
|
||||
notebook_cell_docs,
|
||||
notebook_close,
|
||||
notebook_debug_start,
|
||||
notebook_edit,
|
||||
notebook_execute,
|
||||
notebook_get,
|
||||
|
||||
@@ -2,35 +2,23 @@
|
||||
//! [`ide_run::plots`]) reach the window as [`IdeEvent::PlotAdded`].
|
||||
use crate::Host;
|
||||
use crate::project::Project;
|
||||
use ide_command::command;
|
||||
use ide_core::{IdeEvent, IdeResult, SharedSink};
|
||||
use ide_core::IdeEvent;
|
||||
use ide_run::plots::Plots;
|
||||
use notify::{RecommendedWatcher, RecursiveMode, Watcher};
|
||||
use notify::{RecursiveMode, Watcher};
|
||||
use std::io;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use std::path::Path;
|
||||
|
||||
/// The backend and plots folder for a Python run of `project`, installed and watched on first use
|
||||
/// (off the async runtime: the first use empties the folder); `None` when Settings › Python turns
|
||||
/// the tool window off.
|
||||
pub(crate) async fn prepare(host: &Host, project: &Arc<Project>) -> Option<Plots> {
|
||||
/// The backend and plots folder for a Python run of `project`, installed and watched on first use;
|
||||
/// `None` when Settings › Python turns the tool window off.
|
||||
pub(crate) fn prepare(host: &Host, project: &Project) -> Option<Plots> {
|
||||
if !project.settings.effective().languages.python.show_plots_in_tool_window {
|
||||
return None;
|
||||
}
|
||||
let plots = Plots { backend: host.local_data_dir.join("matplotlib-backend"), dir: project.cache_dir.join("plots") };
|
||||
let (project, target) = (project.clone(), plots.clone());
|
||||
let ready = super::blocking_value(move || {
|
||||
ide_run::plots::install(&target.backend).and_then(|()| watch(&project, &target.dir))
|
||||
})
|
||||
.await;
|
||||
match ready {
|
||||
Ok(Ok(())) => Some(plots),
|
||||
Ok(Err(e)) => {
|
||||
tracing::warn!("cannot set up the Plots tool window in {}: {e}", plots.dir.display());
|
||||
None
|
||||
}
|
||||
match ide_run::plots::install(&plots.backend).and_then(|()| watch(project, &plots.dir)) {
|
||||
Ok(()) => Some(plots),
|
||||
Err(e) => {
|
||||
tracing::warn!("cannot set up the Plots tool window: {}", e.message);
|
||||
tracing::warn!("cannot set up the Plots tool window in {}: {e}", plots.dir.display());
|
||||
None
|
||||
}
|
||||
}
|
||||
@@ -44,13 +32,8 @@ fn watch(project: &Project, dir: &Path) -> io::Result<()> {
|
||||
// Figures of an earlier session are not shown again.
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
std::fs::create_dir_all(dir)?;
|
||||
*slot = Some(watch_dir(dir, project.sink.clone())?);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Sends `PlotAdded` for each finished figure in `dir`. A file can be reported more than once
|
||||
/// (created, renamed, modified); the window lists each path once.
|
||||
fn watch_dir(dir: &Path, sink: SharedSink) -> io::Result<RecommendedWatcher> {
|
||||
let sink = project.sink.clone();
|
||||
// Every event of a finished PNG is sent (create, rename, modify); the window keeps each path once.
|
||||
let mut watcher = notify::recommended_watcher(move |res: notify::Result<notify::Event>| {
|
||||
for path in res.map(|e| e.paths).unwrap_or_default() {
|
||||
if is_plot(&path) && path.is_file() {
|
||||
@@ -60,7 +43,8 @@ fn watch_dir(dir: &Path, sink: SharedSink) -> io::Result<RecommendedWatcher> {
|
||||
})
|
||||
.map_err(io::Error::other)?;
|
||||
watcher.watch(dir, RecursiveMode::NonRecursive).map_err(io::Error::other)?;
|
||||
Ok(watcher)
|
||||
*slot = Some(watcher);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A finished figure: the backend writes `.<name>.png` first, then renames it.
|
||||
@@ -69,32 +53,9 @@ fn is_plot(path: &Path) -> bool {
|
||||
&& path.file_name().is_some_and(|n| !n.to_string_lossy().starts_with('.'))
|
||||
}
|
||||
|
||||
/// Deletes figures the Plots tool window dropped; only figures in this project's plots folder.
|
||||
#[command(trust = always)]
|
||||
pub async fn plots_delete(host: &Host, window: &str, paths: Vec<PathBuf>) -> IdeResult<()> {
|
||||
let dir = host.project(window)?.cache_dir.join("plots");
|
||||
super::blocking_value(move || delete(&dir, &paths)).await
|
||||
}
|
||||
|
||||
/// Paths are compared canonicalized: the watcher reports real paths, and the cache folder may be
|
||||
/// reached through a symlink.
|
||||
fn delete(dir: &Path, paths: &[PathBuf]) {
|
||||
let Ok(dir) = dunce::canonicalize(dir) else { return };
|
||||
let in_dir = |p: &Path| p.parent().and_then(|d| dunce::canonicalize(d).ok()).is_some_and(|d| d == dir);
|
||||
for path in paths.iter().filter(|p| is_plot(p) && in_dir(p)) {
|
||||
let _ = std::fs::remove_file(path);
|
||||
}
|
||||
}
|
||||
|
||||
ide_command::domain!(
|
||||
plots:
|
||||
plots_delete,
|
||||
);
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
#[test]
|
||||
fn only_finished_pngs_are_plots() {
|
||||
@@ -102,45 +63,4 @@ mod tests {
|
||||
assert!(!is_plot(Path::new("/c/plots/.1-2-0.png")));
|
||||
assert!(!is_plot(Path::new("/c/plots/notes.txt")));
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn deletes_only_finished_figures_in_the_plots_folder_through_a_symlink() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let real = tmp.path().join("real");
|
||||
std::fs::create_dir_all(real.join("plots")).unwrap();
|
||||
std::fs::create_dir_all(real.join("other")).unwrap();
|
||||
std::os::unix::fs::symlink(&real, tmp.path().join("link")).unwrap();
|
||||
let files = [real.join("plots/1-2-0.png"), real.join("plots/.1-2-1.png"), real.join("other/1-2-2.png")];
|
||||
for f in &files {
|
||||
std::fs::write(f, b"png").unwrap();
|
||||
}
|
||||
let reported: Vec<_> = files.iter().map(|f| dunce::canonicalize(f).unwrap()).collect();
|
||||
delete(&tmp.path().join("link/plots"), &reported);
|
||||
assert_eq!(files.map(|f| f.exists()), [false, true, true]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reports_a_figure_once_it_is_renamed_into_place() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let dir = dunce::canonicalize(tmp.path()).unwrap();
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
let sink: SharedSink = Arc::new(move |e: IdeEvent| {
|
||||
let _ = tx.send(e);
|
||||
});
|
||||
let _watch = watch_dir(&dir, sink).unwrap();
|
||||
std::fs::write(dir.join(".1-2-0.png"), b"png").unwrap();
|
||||
std::fs::rename(dir.join(".1-2-0.png"), dir.join("1-2-0.png")).unwrap();
|
||||
let deadline = Instant::now() + Duration::from_secs(10);
|
||||
let mut seen = Vec::new();
|
||||
while Instant::now() < deadline {
|
||||
if let Ok(IdeEvent::PlotAdded { path }) = rx.recv_timeout(Duration::from_millis(200)) {
|
||||
seen.push(path);
|
||||
} else if !seen.is_empty() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
assert!(!seen.is_empty(), "no PlotAdded event");
|
||||
assert!(seen.iter().all(|p| p.ends_with("1-2-0.png") && !p.ends_with(".1-2-0.png")), "{seen:?}");
|
||||
}
|
||||
}
|
||||
@@ -149,8 +149,7 @@ pub fn settings_set(
|
||||
|
||||
/// Effective source / test / resource / excluded roots of the window's project:
|
||||
/// auto-detected from build files, overridden by Settings › Project Structure.
|
||||
/// Off the UI thread: Gradle source roots may walk the project for builds, slow on a share.
|
||||
#[command(trust = always, desktop_body = spawn)]
|
||||
#[command(trust = always)]
|
||||
pub fn project_roots(host: &Host, window: &str) -> IdeResult<ide_workspace::ProjectRoots> {
|
||||
Ok(host.project(window)?.roots())
|
||||
}
|
||||
@@ -437,13 +436,8 @@ pub fn set_settings(
|
||||
}
|
||||
});
|
||||
}
|
||||
// Directory Mappings and Enable Git integration change which repositories the project has.
|
||||
if key == "vcs"
|
||||
|| key == "vcs.mappings"
|
||||
|| key.starts_with("vcs.mappings.")
|
||||
|| key == "vcs.git"
|
||||
|| key == "vcs.git.enabled"
|
||||
{
|
||||
// Directory Mappings change which repositories the project has.
|
||||
if key == "vcs" || key == "vcs.mappings" || key.starts_with("vcs.mappings.") {
|
||||
let affected = affected();
|
||||
host.runtime.spawn_blocking(move || {
|
||||
for project in affected {
|
||||
@@ -498,10 +492,7 @@ pub fn set_settings(
|
||||
|| key.starts_with("inspections.")
|
||||
|| key == "files"
|
||||
|| key == "files.composeFileOverrides"
|
||||
|| key.starts_with("files.composeFileOverrides.")
|
||||
// JSON Schema Mappings reach the JSON and YAML servers as settings.
|
||||
|| key == "jsonSchemas"
|
||||
|| key.starts_with("jsonSchemas.");
|
||||
|| key.starts_with("files.composeFileOverrides.");
|
||||
let toolchain = ["languages", "tools", "languageServers", "projectStructure"]
|
||||
.iter()
|
||||
.any(|k| key == *k || key.starts_with(&format!("{k}.")));
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
//! plugins' `pytest11` entry points, pytest's own `_pytest` package), for Go to Declaration
|
||||
//! and completion of fixture names.
|
||||
|
||||
use super::python_stubs::interpreter_site_packages as python_site_packages;
|
||||
use super::python_stubs::site_packages;
|
||||
use crate::Project;
|
||||
use ide_core::{FileEdit, IdeError, IdeResult, IpcPath, LanguageId, Location, Pos, Range, TextEdit, WorkspaceEdit};
|
||||
use ide_language::{PytestModule, Syntax, resolve_fixture, visible_fixtures};
|
||||
@@ -133,62 +133,8 @@ impl Scope {
|
||||
out.push((file, m));
|
||||
}
|
||||
}
|
||||
// A fixture imported into a project module is that module's own, right after it.
|
||||
let mut layers = Vec::with_capacity(out.len());
|
||||
for (file, m) in out {
|
||||
let imported =
|
||||
if is_project_file(project, &file) { self.imported(project, syntax, &file, &m) } else { Vec::new() };
|
||||
layers.push((file, m));
|
||||
layers.extend(imported);
|
||||
}
|
||||
layers
|
||||
out
|
||||
}
|
||||
|
||||
/// The fixtures `module` (the file `path`) imports, one layer per module imported from, each
|
||||
/// named as it is bound here.
|
||||
fn imported(&self, project: &Project, syntax: &Syntax, path: &Path, module: &PytestModule) -> Vec<Layer> {
|
||||
let mut out: Vec<(PathBuf, PytestModule)> = Vec::new();
|
||||
for import in &module.imports {
|
||||
let Some(file) = import_file(&import.module, path, &self.search) else { continue };
|
||||
let Some(from) = module_of(project, syntax, &file) else { continue };
|
||||
let picked = from.fixtures.iter().filter(|f| f.class.is_none()).filter_map(|f| {
|
||||
let star = import.name == "*" && !f.function.starts_with('_');
|
||||
if !star && f.function != import.name {
|
||||
return None;
|
||||
}
|
||||
// pytest takes the name a fixture is bound to, unless `name=` gives one.
|
||||
let name = if f.by_argument || star { f.name.clone() } else { import.alias.clone() };
|
||||
Some(ide_language::PytestFixture { name, ..f.clone() })
|
||||
});
|
||||
let picked: Vec<_> = picked.collect();
|
||||
if picked.is_empty() {
|
||||
continue;
|
||||
}
|
||||
match out.iter_mut().find(|(p, _)| *p == file) {
|
||||
Some((_, m)) => m.fixtures.extend(picked),
|
||||
None => out.push((file, PytestModule { fixtures: picked, ..Default::default() })),
|
||||
}
|
||||
}
|
||||
out.into_iter().map(|(p, m)| (p, Arc::new(m))).collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// The file of `module` imported from `path`: relative (`.fixtures`, `..`) from its folder, else
|
||||
/// from the import search path.
|
||||
fn import_file(module: &str, path: &Path, search: &[PathBuf]) -> Option<PathBuf> {
|
||||
let rest = module.trim_start_matches('.');
|
||||
let dots = module.len() - rest.len();
|
||||
if dots == 0 {
|
||||
return module_file(module, search);
|
||||
}
|
||||
let mut base = path.parent()?;
|
||||
for _ in 1..dots {
|
||||
base = base.parent()?;
|
||||
}
|
||||
if rest.is_empty() {
|
||||
return Some(base.join("__init__.py")).filter(|p| p.is_file());
|
||||
}
|
||||
module_file(rest, &[base.to_path_buf()])
|
||||
}
|
||||
|
||||
/// A fixture definition: its file and the range of its name there.
|
||||
@@ -197,30 +143,16 @@ struct Definition {
|
||||
name: String,
|
||||
path: PathBuf,
|
||||
selection: Range,
|
||||
/// Named by its function (no `name=`): renaming it renames the function.
|
||||
function_name: bool,
|
||||
}
|
||||
|
||||
impl Definition {
|
||||
fn of(path: &Path, fixture: &ide_language::PytestFixture) -> Self {
|
||||
Self {
|
||||
name: fixture.name.clone(),
|
||||
path: path.to_path_buf(),
|
||||
selection: fixture.selection,
|
||||
function_name: !fixture.by_argument,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Where pytest finds the fixture `u` asks for, seen from `layers`.
|
||||
fn definition_of(layers: &[Layer], u: &ide_language::PytestFixtureUse) -> Option<Definition> {
|
||||
let modules: Vec<&PytestModule> = layers.iter().map(|(_, m)| m.as_ref()).collect();
|
||||
let (l, f) = resolve_fixture(&modules, &u.name, u.class.as_deref(), u.in_fixture.as_deref() == Some(&u.name))?;
|
||||
Some(Definition::of(&layers[l].0, &modules[l].fixtures[f]))
|
||||
Some(Definition { name: u.name.clone(), path: layers[l].0.clone(), selection: modules[l].fixtures[f].selection })
|
||||
}
|
||||
|
||||
/// The fixture at `pos` of `path` and the range of its name there: the one defined there, the
|
||||
/// one a test asks for there, or the one whose parameter a function body reads there.
|
||||
/// The fixture at `pos` of `path`: the one defined there, or the one a test asks for there.
|
||||
fn target_at(
|
||||
project: &Project,
|
||||
syntax: &Syntax,
|
||||
@@ -228,50 +160,13 @@ fn target_at(
|
||||
path: &Path,
|
||||
own: &Arc<PytestModule>,
|
||||
pos: Pos,
|
||||
) -> Option<(Definition, Range)> {
|
||||
) -> Option<Definition> {
|
||||
if let Some(f) = own.definition_at(pos) {
|
||||
let fixture = &own.fixtures[f];
|
||||
return Some((Definition::of(path, fixture), fixture.selection));
|
||||
return Some(Definition { name: fixture.name.clone(), path: path.to_path_buf(), selection: fixture.selection });
|
||||
}
|
||||
let (usage, range) = own.use_or_read_at(pos)?;
|
||||
Some((definition_of(&scope.layers(project, syntax, path, own.clone()), usage)?, range))
|
||||
}
|
||||
|
||||
/// The pytest fixture at a position, found without searching the project (for Rename to
|
||||
/// decide what it renames before asking for the new name).
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PytestFixtureTarget {
|
||||
pub name: String,
|
||||
/// The name at the position: a definition, a place asking for the fixture, or a read of
|
||||
/// such a parameter in a function body.
|
||||
pub range: Range,
|
||||
pub definition: Location,
|
||||
/// Defined in the project (not by a plugin or pytest): it may be renamed.
|
||||
pub in_project: bool,
|
||||
/// Named by its function (no `name=`): Python code may refer to the function too.
|
||||
pub function_name: bool,
|
||||
}
|
||||
|
||||
pub(crate) fn fixture_target(
|
||||
project: &Project,
|
||||
syntax: &Syntax,
|
||||
path: &Path,
|
||||
text: &str,
|
||||
pos: Pos,
|
||||
) -> Option<PytestFixtureTarget> {
|
||||
let own = Arc::new(syntax.pytest_module(&python(), text));
|
||||
if own.definition_at(pos).is_none() && own.use_or_read_at(pos).is_none() {
|
||||
return None;
|
||||
}
|
||||
let (target, range) = target_at(project, syntax, &Scope::new(project), path, &own, pos)?;
|
||||
Some(PytestFixtureTarget {
|
||||
name: target.name.clone(),
|
||||
range,
|
||||
in_project: is_project_file(project, &target.path),
|
||||
function_name: target.function_name,
|
||||
definition: Location { path: IpcPath::from(target.path), range: target.selection, uri: None },
|
||||
})
|
||||
let usage = own.use_at(pos)?;
|
||||
definition_of(&scope.layers(project, syntax, path, own.clone()), usage)
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
@@ -279,6 +174,8 @@ pub(crate) fn fixture_target(
|
||||
pub struct PytestFixtureUsages {
|
||||
pub name: String,
|
||||
pub definition: Location,
|
||||
/// Defined in the project (not by a plugin or pytest): it may be renamed.
|
||||
pub in_project: bool,
|
||||
/// Every place that gets this fixture: parameters, `usefixtures` and `getfixturevalue` strings.
|
||||
pub usages: Vec<Location>,
|
||||
}
|
||||
@@ -286,12 +183,9 @@ pub struct PytestFixtureUsages {
|
||||
struct Usage {
|
||||
path: PathBuf,
|
||||
use_: ide_language::PytestFixtureUse,
|
||||
/// The modules its file sees, as `Scope::layers` gives them.
|
||||
layers: Arc<Vec<Layer>>,
|
||||
}
|
||||
|
||||
/// The fixture at `pos` of the Python document `path` / `text` (a definition or a place asking
|
||||
/// for it) and every place that gets it.
|
||||
/// The fixture at `pos` of the Python document `path` / `text` and every place that gets it.
|
||||
pub(crate) fn fixture_usages(
|
||||
project: &Project,
|
||||
syntax: &Syntax,
|
||||
@@ -300,14 +194,10 @@ pub(crate) fn fixture_usages(
|
||||
pos: Pos,
|
||||
cancelled: &dyn Fn() -> bool,
|
||||
) -> IdeResult<Option<PytestFixtureUsages>> {
|
||||
let own = Arc::new(syntax.pytest_module(&python(), text));
|
||||
// Find Usages on a read in a body stays the language server's (the parameter's uses).
|
||||
if own.definition_at(pos).is_none() && own.use_at(pos).is_none() {
|
||||
return Ok(None);
|
||||
}
|
||||
let Some((target, usages)) = usages_of(project, syntax, path, own, pos, cancelled)? else { return Ok(None) };
|
||||
let Some((target, usages)) = usages_of(project, syntax, path, text, pos, cancelled)? else { return Ok(None) };
|
||||
Ok(Some(PytestFixtureUsages {
|
||||
name: target.name.clone(),
|
||||
in_project: is_project_file(project, &target.path),
|
||||
definition: Location { path: IpcPath::from(target.path), range: target.selection, uri: None },
|
||||
usages: usages
|
||||
.into_iter()
|
||||
@@ -316,17 +206,8 @@ pub(crate) fn fixture_usages(
|
||||
}))
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PytestFixtureRename {
|
||||
pub edit: WorkspaceEdit,
|
||||
/// A parameter or fixture that already has the new name, which the rename would clash with
|
||||
/// (the edit is empty then).
|
||||
pub clash: Option<Location>,
|
||||
}
|
||||
|
||||
/// Rename of the fixture at `pos`: its definition (the `name=` string, else the function name),
|
||||
/// every place that gets it, and the reads of a renamed parameter in its function's body.
|
||||
/// every place that gets it, and the uses of a renamed parameter in its function's body.
|
||||
pub(crate) fn rename_fixture(
|
||||
project: &Project,
|
||||
syntax: &Syntax,
|
||||
@@ -335,17 +216,13 @@ pub(crate) fn rename_fixture(
|
||||
pos: Pos,
|
||||
new_name: &str,
|
||||
cancelled: &dyn Fn() -> bool,
|
||||
) -> IdeResult<PytestFixtureRename> {
|
||||
let own = Arc::new(syntax.pytest_module(&python(), text));
|
||||
let Some((target, usages)) = usages_of(project, syntax, path, own, pos, cancelled)? else {
|
||||
) -> IdeResult<WorkspaceEdit> {
|
||||
let Some((target, usages)) = usages_of(project, syntax, path, text, pos, cancelled)? else {
|
||||
return Err(IdeError::invalid("No pytest fixture here"));
|
||||
};
|
||||
if !is_project_file(project, &target.path) {
|
||||
return Err(IdeError::invalid("The fixture is defined outside the project"));
|
||||
}
|
||||
if let Some(clash) = clash(project, syntax, &target, &usages, new_name) {
|
||||
return Ok(PytestFixtureRename { edit: WorkspaceEdit::default(), clash: Some(clash) });
|
||||
}
|
||||
let mut by_file: Vec<(PathBuf, Vec<TextEdit>)> = Vec::new();
|
||||
let mut edit = |file: &Path, range: Range| {
|
||||
let edits = match by_file.iter_mut().find(|(p, _)| p == file) {
|
||||
@@ -373,53 +250,25 @@ pub(crate) fn rename_fixture(
|
||||
FileEdit::Edit { path: IpcPath::from(p), edits, version: None }
|
||||
})
|
||||
.collect();
|
||||
Ok(PytestFixtureRename { edit: WorkspaceEdit { files, preconditions: Vec::new() }, clash: None })
|
||||
}
|
||||
|
||||
/// Where `new_name` is already taken: a name a function that gets the fixture already uses
|
||||
/// (a parameter, a name in its body), a fixture of that name a place that gets it sees (an
|
||||
/// override in a lower conftest, a class's own fixture), or another fixture of the definition's scope.
|
||||
fn clash(
|
||||
project: &Project,
|
||||
syntax: &Syntax,
|
||||
target: &Definition,
|
||||
usages: &[Usage],
|
||||
new_name: &str,
|
||||
) -> Option<Location> {
|
||||
for u in usages {
|
||||
if u.use_.taken.iter().any(|p| p == new_name) {
|
||||
return Some(Location { path: IpcPath::from(u.path.clone()), range: u.use_.range, uri: None });
|
||||
}
|
||||
}
|
||||
for u in usages {
|
||||
let modules: Vec<&PytestModule> = u.layers.iter().map(|(_, m)| m.as_ref()).collect();
|
||||
if let Some((l, f)) = resolve_fixture(&modules, new_name, u.use_.class.as_deref(), false) {
|
||||
return Some(Location {
|
||||
path: IpcPath::from(u.layers[l].0.clone()),
|
||||
range: modules[l].fixtures[f].selection,
|
||||
uri: None,
|
||||
});
|
||||
}
|
||||
}
|
||||
let module = module_of(project, syntax, &target.path)?;
|
||||
let class = module.fixtures.iter().find(|f| f.selection == target.selection)?.class.clone();
|
||||
let other = module.fixtures.iter().find(|f| f.name == new_name && f.class == class)?;
|
||||
Some(Location { path: IpcPath::from(target.path.clone()), range: other.selection, uri: None })
|
||||
Ok(WorkspaceEdit { files, preconditions: Vec::new() })
|
||||
}
|
||||
|
||||
fn usages_of(
|
||||
project: &Project,
|
||||
syntax: &Syntax,
|
||||
path: &Path,
|
||||
own: Arc<PytestModule>,
|
||||
text: &str,
|
||||
pos: Pos,
|
||||
cancelled: &dyn Fn() -> bool,
|
||||
) -> IdeResult<Option<(Definition, Vec<Usage>)>> {
|
||||
let own = Arc::new(syntax.pytest_module(&python(), text));
|
||||
if own.definition_at(pos).is_none() && own.use_at(pos).is_none() {
|
||||
return Ok(None);
|
||||
}
|
||||
let scope = Scope::new(project);
|
||||
let Some((target, _)) = target_at(project, syntax, &scope, path, &own, pos) else { return Ok(None) };
|
||||
let patterns = test_file_patterns(&project.root);
|
||||
let mut files = candidate_files(project, &target.path, &patterns);
|
||||
if !files.iter().any(|f| f == path) && is_project_file(project, path) {
|
||||
let Some(target) = target_at(project, syntax, &scope, path, &own, pos) else { return Ok(None) };
|
||||
let mut files = candidate_files(project, &target.path);
|
||||
if !files.iter().any(|f| f == path) && path.starts_with(&project.root) {
|
||||
files.push(path.to_path_buf());
|
||||
}
|
||||
let mut usages = Vec::new();
|
||||
@@ -432,58 +281,26 @@ fn usages_of(
|
||||
if !module.uses.iter().any(|u| u.name == target.name) {
|
||||
continue;
|
||||
}
|
||||
let layers = Arc::new(scope.layers(project, syntax, &file, module.clone()));
|
||||
let layers = scope.layers(project, syntax, &file, module.clone());
|
||||
for u in module.uses.iter().filter(|u| u.name == target.name) {
|
||||
if definition_of(&layers, u).as_ref() == Some(&target) {
|
||||
usages.push(Usage { path: file.clone(), use_: u.clone(), layers: layers.clone() });
|
||||
usages.push(Usage { path: file.clone(), use_: u.clone() });
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(Some((target, usages)))
|
||||
}
|
||||
|
||||
/// Where the files that may get a fixture are.
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
enum Searched<'a> {
|
||||
/// A test module's fixtures are its own.
|
||||
Itself,
|
||||
/// A `conftest.py`'s: the test files below its folder; any other module's (one that
|
||||
/// `pytest_plugins` loads or a conftest imports) and a plugin's: the whole project's.
|
||||
Below(&'a Path),
|
||||
}
|
||||
|
||||
fn searched<'a>(root: &'a Path, definition: &'a Path, in_project: bool, patterns: &[String]) -> Searched<'a> {
|
||||
let name = definition.file_name().and_then(|n| n.to_str()).unwrap_or_default();
|
||||
match () {
|
||||
_ if !in_project => Searched::Below(root),
|
||||
_ if name == "conftest.py" => Searched::Below(definition.parent().unwrap_or(root)),
|
||||
_ if is_test_module(name, patterns) => Searched::Itself,
|
||||
_ => Searched::Below(root),
|
||||
}
|
||||
}
|
||||
|
||||
/// The files that may get a fixture defined in `definition`, from the file index (or the disk,
|
||||
/// while the index is still being built).
|
||||
fn candidate_files(project: &Project, definition: &Path, patterns: &[String]) -> Vec<PathBuf> {
|
||||
let dir = match searched(&project.root, definition, is_project_file(project, definition), patterns) {
|
||||
Searched::Itself => return vec![definition.to_path_buf()],
|
||||
Searched::Below(dir) => dir,
|
||||
};
|
||||
let wanted = |rel: &Path| rel.file_name().and_then(|n| n.to_str()).is_some_and(|n| is_test_file(n, patterns));
|
||||
let mut files = project.index.files_matching(dir, wanted, MAX_FILES).unwrap_or_else(|| {
|
||||
ignore::WalkBuilder::new(dir)
|
||||
.build()
|
||||
.flatten()
|
||||
.map(|e| e.into_path())
|
||||
.filter(|p| p.strip_prefix(dir).is_ok_and(wanted))
|
||||
.take(MAX_FILES)
|
||||
.collect()
|
||||
});
|
||||
files.retain(|f| is_project_file(project, f));
|
||||
// A module `pytest_plugins` loads is searched too (it may use its own fixtures).
|
||||
if is_project_file(project, definition) && !files.iter().any(|f| f == definition) {
|
||||
files.push(definition.to_path_buf());
|
||||
/// The files that may get a fixture defined in `definition`: that test module alone, the test
|
||||
/// modules and `conftest.py` files below a `conftest.py`, all of the project's for a plugin's.
|
||||
fn candidate_files(project: &Project, definition: &Path) -> Vec<PathBuf> {
|
||||
let in_project = is_project_file(project, definition);
|
||||
let is_conftest = definition.file_name().is_some_and(|n| n == "conftest.py");
|
||||
if in_project && !is_conftest {
|
||||
return vec![definition.to_path_buf()];
|
||||
}
|
||||
let dir = if in_project { definition.parent().unwrap_or(&project.root) } else { &project.root };
|
||||
let mut files = project.index.files_matching(dir, is_test_file, MAX_FILES).unwrap_or_default();
|
||||
files.sort();
|
||||
files
|
||||
}
|
||||
@@ -496,134 +313,19 @@ fn is_project_file(project: &Project, path: &Path) -> bool {
|
||||
path.starts_with(&project.root) && !path.components().any(|c| c.as_os_str() == "site-packages")
|
||||
}
|
||||
|
||||
/// The test modules pytest collects (`python_files`, default `test_*.py` and `*_test.py`) and
|
||||
/// `conftest.py`, which it loads.
|
||||
fn is_test_file(name: &str, patterns: &[String]) -> bool {
|
||||
name == "conftest.py" || is_test_module(name, patterns)
|
||||
}
|
||||
|
||||
fn is_test_module(name: &str, patterns: &[String]) -> bool {
|
||||
patterns.iter().any(|p| glob_match(p, name))
|
||||
}
|
||||
|
||||
/// `python_files` from the project's pytest configuration (the first of `pytest.toml`,
|
||||
/// `.pytest.toml`, `pytest.ini`, `.pytest.ini`, `pyproject.toml`, `tox.ini`, `setup.cfg` that
|
||||
/// pytest takes), else pytest's default.
|
||||
fn test_file_patterns(root: &Path) -> Vec<String> {
|
||||
let read = |name: &str| std::fs::read_to_string(root.join(name)).ok();
|
||||
// `Some(value)` when the file is the configuration; `value` is None without `python_files`.
|
||||
let from_ini = |text: String, section: &str, always: bool| -> Option<Option<String>> {
|
||||
let mut found: Option<Option<String>> = always.then_some(None);
|
||||
let (mut inside, mut continued) = (false, false);
|
||||
for raw in text.lines() {
|
||||
let line = raw.trim();
|
||||
if continued && raw.starts_with([' ', '\t']) && !line.is_empty() {
|
||||
if !line.starts_with(['#', ';'])
|
||||
&& let Some(Some(value)) = &mut found
|
||||
{
|
||||
value.push(' ');
|
||||
value.push_str(line);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
continued = false;
|
||||
if let Some(name) = line.strip_prefix('[').and_then(|l| l.strip_suffix(']')) {
|
||||
inside = name == section;
|
||||
if inside && found.is_none() {
|
||||
found = Some(None);
|
||||
}
|
||||
} else if inside
|
||||
&& let Some((key, value)) = line.split_once('=')
|
||||
&& key.trim() == "python_files"
|
||||
{
|
||||
found = Some(Some(value.trim().to_owned()));
|
||||
continued = true;
|
||||
}
|
||||
}
|
||||
found
|
||||
};
|
||||
let from_toml = |text: String, tables: &[&[&str]], always: bool| -> Option<Option<String>> {
|
||||
let table = text.parse::<toml::Table>().ok()?;
|
||||
let options = tables.iter().find_map(|path| {
|
||||
let mut at = table.get(path[0])?;
|
||||
for key in &path[1..] {
|
||||
at = at.get(*key)?;
|
||||
}
|
||||
Some(at)
|
||||
});
|
||||
let Some(options) = options else { return always.then_some(None) };
|
||||
Some(match options.get("python_files") {
|
||||
Some(toml::Value::String(s)) => Some(s.clone()),
|
||||
Some(toml::Value::Array(a)) => Some(a.iter().filter_map(|v| v.as_str()).collect::<Vec<_>>().join(" ")),
|
||||
_ => None,
|
||||
})
|
||||
};
|
||||
// The first file pytest takes, in its order; a pytest.toml or pytest.ini counts even when empty.
|
||||
let pytest_toml = |t: String| from_toml(t, &[&["pytest"]], true);
|
||||
let pytest_ini = |t: String| from_ini(t, "pytest", true);
|
||||
let configured = read("pytest.toml")
|
||||
.and_then(pytest_toml)
|
||||
.or_else(|| read(".pytest.toml").and_then(pytest_toml))
|
||||
.or_else(|| read("pytest.ini").and_then(pytest_ini))
|
||||
.or_else(|| read(".pytest.ini").and_then(pytest_ini))
|
||||
.or_else(|| {
|
||||
read("pyproject.toml")
|
||||
.and_then(|t| from_toml(t, &[&["tool", "pytest", "ini_options"], &["tool", "pytest"]], false))
|
||||
})
|
||||
.or_else(|| read("tox.ini").and_then(|t| from_ini(t, "pytest", false)))
|
||||
.or_else(|| read("setup.cfg").and_then(|t| from_ini(t, "tool:pytest", false)))
|
||||
.flatten();
|
||||
match configured {
|
||||
Some(value) if !value.trim().is_empty() => value.split_whitespace().map(str::to_owned).collect(),
|
||||
_ => vec!["test_*.py".to_owned(), "*_test.py".to_owned()],
|
||||
}
|
||||
}
|
||||
|
||||
/// `fnmatch` with `*`, `?` and `[…]` / `[!…]` (ranges too), as pytest matches `python_files`
|
||||
/// against a file name.
|
||||
fn glob_match(pattern: &str, name: &str) -> bool {
|
||||
/// The class at the start of `p` (after `[`): whether it matches `c`, and its length with `]`.
|
||||
fn class(p: &[char], c: char) -> Option<(bool, usize)> {
|
||||
let negated = p.first() == Some(&'!');
|
||||
let mut i = usize::from(negated);
|
||||
let mut hit = false;
|
||||
// A `]` right after `[` or `[!` is a member.
|
||||
let start = i;
|
||||
while i < p.len() && (p[i] != ']' || i == start) {
|
||||
if i + 2 < p.len() && p[i + 1] == '-' && p[i + 2] != ']' {
|
||||
hit |= p[i] <= c && c <= p[i + 2];
|
||||
i += 3;
|
||||
} else {
|
||||
hit |= p[i] == c;
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
(i < p.len()).then_some((hit != negated, i + 1))
|
||||
}
|
||||
fn go(p: &[char], n: &[char]) -> bool {
|
||||
match p.split_first() {
|
||||
None => n.is_empty(),
|
||||
Some(('*', rest)) => (0..=n.len()).any(|i| go(rest, &n[i..])),
|
||||
Some(('?', rest)) => !n.is_empty() && go(rest, &n[1..]),
|
||||
Some(('[', rest))
|
||||
if let Some(&c) = n.first()
|
||||
&& let Some((hit, len)) = class(rest, c) =>
|
||||
{
|
||||
hit && go(&rest[len..], &n[1..])
|
||||
}
|
||||
Some((c, rest)) => n.first() == Some(c) && go(rest, &n[1..]),
|
||||
}
|
||||
}
|
||||
let p: Vec<char> = pattern.chars().collect();
|
||||
let n: Vec<char> = name.chars().collect();
|
||||
go(&p, &n)
|
||||
/// `test_*.py`, `*_test.py` and `conftest.py`: the files pytest collects or loads.
|
||||
fn is_test_file(rel: &Path) -> bool {
|
||||
let Some(name) = rel.file_name().and_then(|n| n.to_str()) else { return false };
|
||||
let Some(stem) = name.strip_suffix(".py") else { return false };
|
||||
stem == "conftest" || stem.starts_with("test_") || stem.ends_with("_test")
|
||||
}
|
||||
|
||||
/// The `site-packages` of the project's interpreter: its virtualenv's, else its install prefix's.
|
||||
fn interpreter_site_packages(project: &Project) -> Vec<PathBuf> {
|
||||
let settings = project.settings.effective();
|
||||
let Some(python) = ide_sdk::apply::python_interpreter(&project.root, &settings) else { return Vec::new() };
|
||||
python_site_packages(&python)
|
||||
let prefix = ide_sdk::venv_of(&python).or_else(|| python.parent()?.parent().map(Path::to_path_buf));
|
||||
prefix.map(|p| site_packages(&p)).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// `pkg.mod` → `pkg/mod.py` or `pkg/mod/__init__.py` in the first folder that has it.
|
||||
@@ -730,71 +432,15 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_files_are_the_ones_pytest_loads() {
|
||||
let default = vec!["test_*.py".to_owned(), "*_test.py".to_owned()];
|
||||
for (name, expected) in [
|
||||
("test_a.py", true),
|
||||
for (rel, expected) in [
|
||||
("tests/test_a.py", true),
|
||||
("a_test.py", true),
|
||||
("conftest.py", true),
|
||||
("helpers.py", false),
|
||||
("test_a.json", false),
|
||||
("pkg/conftest.py", true),
|
||||
("pkg/helpers.py", false),
|
||||
("test_data.json", false),
|
||||
] {
|
||||
assert_eq!(is_test_file(name, &default), expected, "{name}");
|
||||
assert_eq!(is_test_file(Path::new(rel)), expected, "{rel}");
|
||||
}
|
||||
let custom = vec!["check_*.py".to_owned(), "tests.py".to_owned()];
|
||||
assert!(is_test_file("check_cli.py", &custom) && is_test_file("tests.py", &custom));
|
||||
assert!(!is_test_file("test_a.py", &custom));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_python_files_from_the_first_pytest_configuration() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
assert_eq!(test_file_patterns(dir.path()), ["test_*.py", "*_test.py"]);
|
||||
std::fs::write(dir.path().join("setup.cfg"), "[tool:pytest]\npython_files = check_*.py\n").unwrap();
|
||||
assert_eq!(test_file_patterns(dir.path()), ["check_*.py"]);
|
||||
std::fs::write(
|
||||
dir.path().join("pyproject.toml"),
|
||||
"[tool.pytest.ini_options]\npython_files = [\"tests.py\", \"t_*.py\"]\n",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(test_file_patterns(dir.path()), ["tests.py", "t_*.py"]);
|
||||
// A pytest.ini section without python_files means pytest's default, even with the others.
|
||||
std::fs::write(dir.path().join("pytest.ini"), "[pytest]\naddopts = -q\n").unwrap();
|
||||
assert_eq!(test_file_patterns(dir.path()), ["test_*.py", "*_test.py"]);
|
||||
// pytest.toml comes first, its options in `[pytest]`.
|
||||
std::fs::write(dir.path().join("pytest.toml"), "[pytest]\npython_files = [\"spec_*.py\"]\n").unwrap();
|
||||
assert_eq!(test_file_patterns(dir.path()), ["spec_*.py"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_python_files_written_over_several_lines_and_in_any_pytest_table() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
std::fs::write(
|
||||
dir.path().join("setup.cfg"),
|
||||
"[tool:pytest]\npython_files =\n check_*.py\n t_*.py\nx = 1\n",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(test_file_patterns(dir.path()), ["check_*.py", "t_*.py"]);
|
||||
// An empty pytest.ini still is the configuration: pytest's default.
|
||||
std::fs::write(dir.path().join("pytest.ini"), "").unwrap();
|
||||
assert_eq!(test_file_patterns(dir.path()), ["test_*.py", "*_test.py"]);
|
||||
std::fs::remove_file(dir.path().join("pytest.ini")).unwrap();
|
||||
// pytest 9's `[tool.pytest]` with native lists.
|
||||
std::fs::write(dir.path().join("pyproject.toml"), "[tool.pytest]\npython_files = [\"it_*.py\"]\n").unwrap();
|
||||
assert_eq!(test_file_patterns(dir.path()), ["it_*.py"]);
|
||||
assert!(glob_match("test_[ab].py", "test_a.py") && !glob_match("test_[!ab].py", "test_a.py"));
|
||||
assert!(glob_match("test_[!ab].py", "test_c.py") && !glob_match("test_[ab].py", "test_c.py"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fixture_is_searched_where_pytest_lets_tests_see_it() {
|
||||
let root = Path::new("/p");
|
||||
let default = vec!["test_*.py".to_owned(), "*_test.py".to_owned()];
|
||||
let at = |path: &'static str, in_project: bool| searched(root, Path::new(path), in_project, &default);
|
||||
assert_eq!(at("/p/tests/test_a.py", true), Searched::Itself);
|
||||
assert_eq!(at("/p/tests/conftest.py", true), Searched::Below(Path::new("/p/tests")));
|
||||
// A module that `pytest_plugins` loads, or that a conftest imports.
|
||||
assert_eq!(at("/p/tests/fixtures.py", true), Searched::Below(root));
|
||||
assert_eq!(at("/p/.venv/lib/python3.12/site-packages/_pytest/tmpdir.py", false), Searched::Below(root));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -30,7 +30,13 @@ pub(super) fn with_user_paths(
|
||||
command: Option<&str>,
|
||||
near: Option<&Path>,
|
||||
) -> Vec<PathBuf> {
|
||||
if let Some(python) = launch_python(config_dir, project, command, near) {
|
||||
let named = command
|
||||
.filter(|c| ide_sdk::apply::is_python_command(c))
|
||||
.map(PathBuf::from)
|
||||
.filter(|p| p.is_absolute() && p.is_file())
|
||||
.map(|p| ide_core::project_roots::resolve(&project.root, &p));
|
||||
let python = named.or_else(|| super::sdk::effective_python(config_dir, project, near));
|
||||
if let Some(python) = python {
|
||||
for path in ide_sdk::apply::interpreter_user_paths(&python, &project.settings.effective()) {
|
||||
if !paths.contains(&path) {
|
||||
paths.push(path);
|
||||
@@ -40,40 +46,18 @@ pub(super) fn with_user_paths(
|
||||
paths
|
||||
}
|
||||
|
||||
/// The interpreter a launch uses: `command` when it names a Python executable, else the
|
||||
/// interpreter of the project or workspace member at `near`.
|
||||
fn launch_python(config_dir: &Path, project: &Project, command: Option<&str>, near: Option<&Path>) -> Option<PathBuf> {
|
||||
let named = command
|
||||
.filter(|c| ide_sdk::apply::is_python_command(c))
|
||||
.map(PathBuf::from)
|
||||
.filter(|p| p.is_absolute() && p.is_file())
|
||||
.map(|p| ide_core::project_roots::resolve(&project.root, &p));
|
||||
named.or_else(|| super::sdk::effective_python(config_dir, project, near))
|
||||
}
|
||||
|
||||
/// The conda environment of the interpreter a launch uses ([`launch_python`]), to activate.
|
||||
pub(super) fn conda_prefix(
|
||||
config_dir: &Path,
|
||||
project: &Project,
|
||||
command: Option<&str>,
|
||||
near: Option<&Path>,
|
||||
) -> Option<PathBuf> {
|
||||
ide_sdk::apply::conda_env_prefix(&launch_python(config_dir, project, command, near)?)
|
||||
}
|
||||
|
||||
/// The interpreter a debugpy launch names (`"python": "<executable>"`), if it names one.
|
||||
pub(super) fn debug_python(config: &LaunchConfig) -> Option<String> {
|
||||
let extra: serde_json::Value = serde_json::from_str(config.extra_json.as_deref()?).ok()?;
|
||||
extra.get("python")?.as_str().map(str::to_owned)
|
||||
}
|
||||
|
||||
/// Adds the project's import paths, and the Plots tool window's backend (`plots`, with the folder
|
||||
/// the debuggee starts in), to a debugpy launch's environment.
|
||||
/// Adds the project's import paths, and the Plots tool window's backend (`plots`), to a debugpy
|
||||
/// launch's environment.
|
||||
pub(super) fn prepare_debug(
|
||||
config: &mut LaunchConfig,
|
||||
paths: &[PathBuf],
|
||||
plots: Option<(&ide_run::plots::Plots, &Path)>,
|
||||
conda: Option<&Path>,
|
||||
plots: Option<&ide_run::plots::Plots>,
|
||||
) -> IdeResult<()> {
|
||||
// Adapter-specific env takes precedence over the common launch fields in DAP.
|
||||
let mut extra: Option<serde_json::Value> = config.extra_json.as_deref().and_then(|s| serde_json::from_str(s).ok());
|
||||
@@ -92,27 +76,18 @@ pub(super) fn prepare_debug(
|
||||
let mut vars: BTreeMap<String, String> =
|
||||
object.iter().filter_map(|(k, v)| Some((k.clone(), v.as_str()?.to_owned()))).collect();
|
||||
let inherit = !vars.contains_key("PYTHONPATH");
|
||||
let user_set: std::collections::HashSet<String> = vars.keys().cloned().collect();
|
||||
ide_run::python_path::extend(&mut vars, paths, inherit)?;
|
||||
if let Some(prefix) = conda {
|
||||
// debugpy hands this env to the debuggee: PATH must keep the inherited entries.
|
||||
ide_run::python_path::activate_conda(&mut vars, prefix, true, |k| user_set.contains(k))?;
|
||||
}
|
||||
if let Some((plots, dir)) = plots {
|
||||
ide_run::plots::add(&mut vars, plots, Some(dir))?;
|
||||
if let Some(plots) = plots {
|
||||
ide_run::plots::add(&mut vars, plots, true)?;
|
||||
}
|
||||
for (key, value) in vars {
|
||||
object.insert(key, serde_json::json!(value));
|
||||
}
|
||||
config.extra_json = extra.map(|e| e.to_string());
|
||||
} else {
|
||||
let user_set: std::collections::HashSet<String> = config.env.keys().cloned().collect();
|
||||
ide_run::python_path::extend(&mut config.env, paths, true)?;
|
||||
if let Some(prefix) = conda {
|
||||
ide_run::python_path::activate_conda(&mut config.env, prefix, true, |k| user_set.contains(k))?;
|
||||
}
|
||||
if let Some((plots, dir)) = plots {
|
||||
ide_run::plots::add(&mut config.env, plots, Some(dir))?;
|
||||
if let Some(plots) = plots {
|
||||
ide_run::plots::add(&mut config.env, plots, true)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
@@ -122,36 +97,6 @@ pub(super) fn prepare_debug(
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn debug_activates_the_interpreters_conda_environment() {
|
||||
let root = std::env::temp_dir().join("project");
|
||||
let prefix = std::env::temp_dir().join("miniforge3").join("envs").join("ds");
|
||||
let mut config = LaunchConfig {
|
||||
name: "Python".into(),
|
||||
adapter: "debugpy".into(),
|
||||
request: "launch".into(),
|
||||
program: None,
|
||||
args: vec![],
|
||||
cwd: None,
|
||||
env: BTreeMap::new(),
|
||||
// A PYTHONPATH of its own must not cut PATH down to the environment's folders.
|
||||
extra_json: Some(
|
||||
serde_json::json!({"env": {"CONDA_DEFAULT_ENV": "mine", "PYTHONPATH": "src"}}).to_string(),
|
||||
),
|
||||
};
|
||||
prepare_debug(&mut config, std::slice::from_ref(&root), None, Some(&prefix)).unwrap();
|
||||
let value: serde_json::Value = serde_json::from_str(config.extra_json.as_deref().unwrap()).unwrap();
|
||||
let env = &value["env"];
|
||||
assert_eq!(env["CONDA_PREFIX"], prefix.to_string_lossy().as_ref());
|
||||
assert_eq!(env["CONDA_DEFAULT_ENV"], "mine");
|
||||
let path = env.as_object().unwrap().iter().find(|(k, _)| k.eq_ignore_ascii_case("PATH")).unwrap().1;
|
||||
let path: Vec<_> = std::env::split_paths(path.as_str().unwrap()).collect();
|
||||
assert!(path[0].starts_with(&prefix), "{path:?}");
|
||||
let inherited = ide_run::system_env().into_iter().find(|(k, _)| k.eq_ignore_ascii_case("PATH")).unwrap().1;
|
||||
let system = std::env::split_paths(&inherited).next().unwrap();
|
||||
assert!(path.contains(&system), "{path:?} lacks {system:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn debug_preserves_remote_paths_and_handles_null_env() {
|
||||
let root = std::env::temp_dir().join("project");
|
||||
@@ -166,11 +111,11 @@ mod tests {
|
||||
extra_json: Some(serde_json::json!({"env": null, "debugServer": "remote:5678"}).to_string()),
|
||||
};
|
||||
let before = config.extra_json.clone();
|
||||
prepare_debug(&mut config, std::slice::from_ref(&root), None, None).unwrap();
|
||||
prepare_debug(&mut config, std::slice::from_ref(&root), None).unwrap();
|
||||
assert_eq!(config.extra_json, before);
|
||||
assert!(config.env.is_empty());
|
||||
config.extra_json = Some(serde_json::json!({"env": null}).to_string());
|
||||
prepare_debug(&mut config, std::slice::from_ref(&root), None, None).unwrap();
|
||||
prepare_debug(&mut config, std::slice::from_ref(&root), None).unwrap();
|
||||
let value: serde_json::Value = serde_json::from_str(config.extra_json.as_deref().unwrap()).unwrap();
|
||||
let paths = std::env::split_paths(value["env"]["PYTHONPATH"].as_str().unwrap()).collect::<Vec<_>>();
|
||||
assert_eq!(paths[0], root);
|
||||
@@ -192,7 +137,7 @@ mod tests {
|
||||
env: vars.clone(),
|
||||
extra_json: extra.then(|| serde_json::json!({"env": vars}).to_string()),
|
||||
};
|
||||
prepare_debug(&mut config, std::slice::from_ref(&root), None, None).unwrap();
|
||||
prepare_debug(&mut config, std::slice::from_ref(&root), None).unwrap();
|
||||
let vars: BTreeMap<String, String> = if extra {
|
||||
let value: serde_json::Value = serde_json::from_str(config.extra_json.as_deref().unwrap()).unwrap();
|
||||
serde_json::from_value(value["env"].clone()).unwrap()
|
||||
@@ -202,50 +147,4 @@ mod tests {
|
||||
assert_eq!(std::env::split_paths(&vars["PYTHONPATH"]).collect::<Vec<_>>(), [root, vendor]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn debug_adds_the_plots_backend_to_the_launch_env_unless_it_sets_one() {
|
||||
let root = std::env::temp_dir().join("project");
|
||||
if ide_core::process::host_var_os_in(&root, "MPLBACKEND").is_some() {
|
||||
eprintln!("skipped: this machine sets MPLBACKEND");
|
||||
return;
|
||||
}
|
||||
let plots = ide_run::plots::Plots { backend: root.join("backend"), dir: root.join("plots") };
|
||||
let launch = |extra: serde_json::Value, env: BTreeMap<String, String>| LaunchConfig {
|
||||
name: "Python".into(),
|
||||
adapter: "debugpy".into(),
|
||||
request: "launch".into(),
|
||||
program: Some("main.py".into()),
|
||||
args: vec![],
|
||||
cwd: None,
|
||||
env,
|
||||
extra_json: Some(extra.to_string()),
|
||||
};
|
||||
let env_of = |config: &LaunchConfig| -> serde_json::Value {
|
||||
serde_json::from_str::<serde_json::Value>(config.extra_json.as_deref().unwrap()).unwrap()["env"].clone()
|
||||
};
|
||||
|
||||
// The launch's own variables stay as they are, other values included.
|
||||
let mut config = launch(serde_json::json!({"env": {"DEBUG": "1", "LEVEL": 3}}), BTreeMap::new());
|
||||
prepare_debug(&mut config, std::slice::from_ref(&root), Some((&plots, &root)), None).unwrap();
|
||||
let env = env_of(&config);
|
||||
assert_eq!((env["DEBUG"].as_str(), env["LEVEL"].as_i64()), (Some("1"), Some(3)));
|
||||
assert_eq!(env["MPLBACKEND"], "module://openidea_matplotlib_backend");
|
||||
assert_eq!(env["OPENIDEA_PLOTS_DIR"], plots.dir.to_string_lossy().as_ref());
|
||||
let path: Vec<_> = std::env::split_paths(env["PYTHONPATH"].as_str().unwrap()).collect();
|
||||
// A PYTHONPATH this machine sets follows.
|
||||
assert_eq!(path[..2], [plots.backend.clone(), root.clone()]);
|
||||
|
||||
// A backend the launch names, in either environment field, is kept.
|
||||
let mut config = launch(serde_json::json!({"env": {"MPLBACKEND": "Agg"}}), BTreeMap::new());
|
||||
prepare_debug(&mut config, std::slice::from_ref(&root), Some((&plots, &root)), None).unwrap();
|
||||
let env = env_of(&config);
|
||||
assert_eq!(env["MPLBACKEND"], "Agg");
|
||||
assert!(env.get("OPENIDEA_PLOTS_DIR").is_none());
|
||||
let own = BTreeMap::from([("MPLBACKEND".into(), "TkAgg".into())]);
|
||||
let mut config = launch(serde_json::json!({}), own);
|
||||
prepare_debug(&mut config, std::slice::from_ref(&root), Some((&plots, &root)), None).unwrap();
|
||||
assert_eq!(config.env["MPLBACKEND"], "TkAgg");
|
||||
assert!(!config.env.contains_key("OPENIDEA_PLOTS_DIR"));
|
||||
}
|
||||
}
|
||||
@@ -56,19 +56,6 @@ pub(crate) fn site_packages(venv: &Path) -> Vec<PathBuf> {
|
||||
out
|
||||
}
|
||||
|
||||
/// The `site-packages` of the interpreter `python`, found on disk without running it: in the
|
||||
/// environment holding its `bin` / `Scripts` folder (a virtualenv, a conda environment, an install
|
||||
/// prefix), else in its own folder (a conda environment on Windows keeps `python.exe` at its root).
|
||||
pub(crate) fn interpreter_site_packages(python: &Path) -> Vec<PathBuf> {
|
||||
let home = python.parent();
|
||||
[home.and_then(Path::parent), home]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.map(site_packages)
|
||||
.find(|p| !p.is_empty())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The dotted module of a Python file, from the innermost `search` folder holding it
|
||||
/// (`src/a/b.py` → `a.b`, `site-packages/a/__init__.py` → `a`).
|
||||
pub(crate) fn module_name(path: &Path, search: &[PathBuf]) -> Option<String> {
|
||||
@@ -240,20 +227,4 @@ mod tests {
|
||||
links.iter().map(|l| (l.name.as_str(), l.range.start.line, l.target.start.line)).collect();
|
||||
assert_eq!(names, [("f", 0, 2), ("C", 4, 5), ("C.__init__", 5, 6), ("C.m", 6, 7)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn interpreter_site_packages_of_venvs_and_conda_environments() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let unix = dir.path().join("envs/langchain");
|
||||
std::fs::create_dir_all(unix.join("lib/python3.13/site-packages")).unwrap();
|
||||
assert_eq!(interpreter_site_packages(&unix.join("bin/python")), [unix.join("lib/python3.13/site-packages")]);
|
||||
// Windows: `.venv\Scripts\python.exe`, and conda's `<env>\python.exe`.
|
||||
let venv = dir.path().join(".venv");
|
||||
std::fs::create_dir_all(venv.join("Lib/site-packages")).unwrap();
|
||||
assert_eq!(interpreter_site_packages(&venv.join("Scripts/python.exe")), [venv.join("Lib/site-packages")]);
|
||||
let conda = dir.path().join("miniconda/envs/data");
|
||||
std::fs::create_dir_all(conda.join("Lib/site-packages")).unwrap();
|
||||
assert_eq!(interpreter_site_packages(&conda.join("python.exe")), [conda.join("Lib/site-packages")]);
|
||||
assert!(interpreter_site_packages(&dir.path().join("nowhere/bin/python")).is_empty());
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Web framework routes, source side: the project's files that could declare a route
|
||||
//! (Spring's Java and Kotlin, Flask's and FastAPI's Python), with their text. The UI owns
|
||||
//! the parsers and the index they feed, so this side stays a cheap scan.
|
||||
//! Spring Web mappings, source side: the project's Java and Kotlin files that could
|
||||
//! declare a route, with their text. The UI owns the annotation parser and the index
|
||||
//! it feeds, so this side stays a cheap scan.
|
||||
|
||||
use crate::Host;
|
||||
use ide_core::IdeResult;
|
||||
@@ -24,42 +24,26 @@ pub struct RouteSource {
|
||||
pub text: String,
|
||||
}
|
||||
|
||||
/// Which files a framework's routes can live in, and words one of which such a file names.
|
||||
#[derive(Clone, Copy)]
|
||||
pub(crate) struct RouteFiles {
|
||||
extensions: &'static [&'static str],
|
||||
words: &'static [&'static str],
|
||||
/// The files Spring mappings can live in: Java and Kotlin sources.
|
||||
fn declares_mappings(path: &Path) -> bool {
|
||||
matches!(path.extension().and_then(|e| e.to_str()), Some("java" | "kt" | "kts"))
|
||||
}
|
||||
|
||||
/// Spring mappings: Java and Kotlin sources that name a mapping annotation.
|
||||
pub(crate) const SPRING: RouteFiles = RouteFiles { extensions: &["java", "kt", "kts"], words: &["Mapping"] };
|
||||
/// Flask and FastAPI routes: Python sources that import either (blueprints, routers and the
|
||||
/// modules registering them all do).
|
||||
pub(crate) const PYTHON: RouteFiles = RouteFiles { extensions: &["py"], words: &["flask", "fastapi"] };
|
||||
|
||||
impl RouteFiles {
|
||||
fn declares_routes(&self, path: &Path) -> bool {
|
||||
path.extension().and_then(|e| e.to_str()).is_some_and(|e| self.extensions.contains(&e))
|
||||
// Installed packages (a virtualenv the ignore rules don't cover) declare their own examples.
|
||||
&& !path.components().any(|c| c.as_os_str() == "site-packages")
|
||||
}
|
||||
}
|
||||
|
||||
/// Files under `root` whose text names a route: `ignore` rules and `excludes`
|
||||
/// Files under `root` whose text names a mapping: `ignore` rules and `excludes`
|
||||
/// decide what counts, and the UI ranks the matches itself.
|
||||
pub(crate) fn sources_in(root: &Path, excludes: &[String], kind: RouteFiles) -> Vec<RouteSource> {
|
||||
pub(crate) fn sources_in(root: &Path, excludes: &[String]) -> Vec<RouteSource> {
|
||||
let found: Mutex<Vec<RouteSource>> = Mutex::new(Vec::new());
|
||||
let bytes = AtomicUsize::new(0);
|
||||
ide_vfs::walk_files(root, excludes, |path| {
|
||||
if !kind.declares_routes(path) || bytes.load(Ordering::Relaxed) >= MAX_BYTES {
|
||||
if !declares_mappings(path) || bytes.load(Ordering::Relaxed) >= MAX_BYTES {
|
||||
return;
|
||||
}
|
||||
if std::fs::metadata(path).map_or(true, |m| m.len() > MAX_FILE_BYTES) {
|
||||
return;
|
||||
}
|
||||
let Ok(text) = std::fs::read_to_string(path) else { return };
|
||||
// Only a file that names a mapping annotation (or imports the framework) is worth parsing.
|
||||
if !kind.words.iter().any(|w| text.contains(w)) {
|
||||
// Only a file that names a mapping annotation is worth parsing.
|
||||
if !text.contains("Mapping") {
|
||||
return;
|
||||
}
|
||||
let Ok(mut found) = found.lock() else { return };
|
||||
@@ -86,31 +70,17 @@ fn scan_roots(root: &Path, content_roots: Vec<PathBuf>) -> Vec<PathBuf> {
|
||||
/// Every mapping source of the project, for the request-path index. Walks the whole tree,
|
||||
/// so it runs on the blocking pool.
|
||||
pub async fn spring_route_sources(host: &Host, window: &str) -> IdeResult<Vec<RouteSource>> {
|
||||
route_sources(host, window, SPRING, "spring").await
|
||||
}
|
||||
|
||||
/// Every Flask / FastAPI source of the project, for the request-path index.
|
||||
pub async fn python_route_sources(host: &Host, window: &str) -> IdeResult<Vec<RouteSource>> {
|
||||
route_sources(host, window, PYTHON, "python").await
|
||||
}
|
||||
|
||||
async fn route_sources(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
kind: RouteFiles,
|
||||
label: &'static str,
|
||||
) -> IdeResult<Vec<RouteSource>> {
|
||||
let project = host.project(window)?;
|
||||
host.blocking(move || {
|
||||
let mut out = Vec::new();
|
||||
for root in scan_roots(&project.root, project.content_roots()) {
|
||||
out.extend(sources_in(&root, &project.search_excludes_in(&root), kind));
|
||||
out.extend(sources_in(&root, &project.search_excludes_in(&root)));
|
||||
}
|
||||
out.sort_by(|a, b| a.path.cmp(&b.path));
|
||||
out.dedup_by(|a, b| a.path == b.path);
|
||||
match out.len() {
|
||||
0 => tracing::debug!("{label} routes: no route source under {:?}", project.root),
|
||||
n => tracing::info!("{label} routes: {n} route sources under {:?}", project.root),
|
||||
0 => tracing::warn!("spring routes: no mapping source under {:?}", project.root),
|
||||
n => tracing::info!("spring routes: {n} mapping sources under {:?}", project.root),
|
||||
}
|
||||
Ok(out)
|
||||
})
|
||||
@@ -136,28 +106,10 @@ mod tests {
|
||||
for (name, expected) in
|
||||
[("A.java", true), ("B.kt", true), ("C.kts", true), ("D.txt", false), ("pom.xml", false), ("noext", false)]
|
||||
{
|
||||
assert_eq!(SPRING.declares_routes(Path::new(name)), expected, "{name}");
|
||||
assert_eq!(declares_mappings(Path::new(name)), expected, "{name}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn python_sources_that_import_flask_or_fastapi_are_read_outside_installed_packages() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let write = |rel: &str, text: &str| {
|
||||
let path = tmp.path().join(rel);
|
||||
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
std::fs::write(path, text).unwrap();
|
||||
};
|
||||
write("app.py", "from flask import Flask\n");
|
||||
write("api/routers/items.py", "from fastapi import APIRouter\n");
|
||||
write("util.py", "import os\n");
|
||||
write("venv/lib/python3.12/site-packages/flask/app.py", "import flask\n");
|
||||
let files = sources_in(tmp.path(), &[], PYTHON);
|
||||
assert_eq!(files.len(), 2, "{:?}", files.iter().map(|f| &f.path).collect::<Vec<_>>());
|
||||
assert!(files[0].path.ends_with("api/routers/items.py"), "{:?}", files[0].path);
|
||||
assert!(files[1].path.ends_with("app.py"), "{:?}", files[1].path);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn files_that_name_no_mapping_are_left_out() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
@@ -165,7 +117,7 @@ mod tests {
|
||||
std::fs::write(tmp.path().join("src/Ctl.java"), "class Ctl { @GetMapping(\"/a\") void a() {} }").unwrap();
|
||||
std::fs::write(tmp.path().join("src/Plain.java"), "class Plain { void a() {} }").unwrap();
|
||||
std::fs::write(tmp.path().join("src/Notes.txt"), "@GetMapping(\"/a\")").unwrap();
|
||||
let files = sources_in(tmp.path(), &[], SPRING);
|
||||
let files = sources_in(tmp.path(), &[]);
|
||||
assert_eq!(files.len(), 1, "{:?}", files.iter().map(|f| &f.path).collect::<Vec<_>>());
|
||||
assert!(files[0].path.ends_with("src/Ctl.java"), "{:?}", files[0].path);
|
||||
assert!(files[0].text.contains("@GetMapping"));
|
||||
@@ -178,7 +130,7 @@ mod tests {
|
||||
std::fs::create_dir_all(tmp.path().join("build")).unwrap();
|
||||
std::fs::write(tmp.path().join("module/src/A.java"), "@RequestMapping(\"/a\")").unwrap();
|
||||
std::fs::write(tmp.path().join("build/B.java"), "@RequestMapping(\"/b\")").unwrap();
|
||||
let files = sources_in(tmp.path(), &["build/**".to_owned()], SPRING);
|
||||
let files = sources_in(tmp.path(), &["build/**".to_owned()]);
|
||||
assert_eq!(files.len(), 1, "{:?}", files.iter().map(|f| &f.path).collect::<Vec<_>>());
|
||||
assert!(files[0].path.ends_with("module/src/A.java"), "{:?}", files[0].path);
|
||||
}
|
||||
|
||||
@@ -1,156 +0,0 @@
|
||||
//! The reStructuredText preview: docutils, in the project's Python interpreter, turns the
|
||||
//! edited text into HTML, with everything that reads past the document turned off.
|
||||
|
||||
use crate::Host;
|
||||
use crate::ops::blocking;
|
||||
use ide_command::command;
|
||||
use ide_core::cli_process::{CliTool, Decoding, Input};
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult, RequestId};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
use std::time::Duration;
|
||||
|
||||
const RENDER: &str = include_str!("rst_render.py");
|
||||
/// What the script prints when docutils can't be imported.
|
||||
const NO_DOCUTILS: &str = "no-docutils";
|
||||
const TIMEOUT: Duration = Duration::from_secs(15);
|
||||
|
||||
/// `text`, the reStructuredText file `path` as edited, as the HTML body of its preview, with
|
||||
/// docutils' problems inline. Runs the project's Python interpreter, so needs a trusted project.
|
||||
/// Cancelling `request` (the text changed again) stops the interpreter.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn rst_preview(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
request: RequestId,
|
||||
path: PathBuf,
|
||||
text: String,
|
||||
) -> IdeResult<String> {
|
||||
host.require_trust(window)?;
|
||||
let project = host.project(window)?;
|
||||
let config_dir = host.config_dir.clone();
|
||||
let cancel = host.begin_project_request(window, request);
|
||||
let result = blocking(move || {
|
||||
let python = super::sdk::effective_python(&config_dir, &project, path.parent()).ok_or_else(|| {
|
||||
IdeError::unavailable("Choose a Python interpreter for the project to preview reStructuredText.")
|
||||
})?;
|
||||
render(&python, &path, &text, Some(&cancel))
|
||||
})
|
||||
.await;
|
||||
host.end_request(request);
|
||||
result
|
||||
}
|
||||
|
||||
fn render(python: &Path, path: &Path, text: &str, cancel: Option<&CancellationToken>) -> IdeResult<String> {
|
||||
// `-c` puts the working directory first on `sys.path`: an empty one shadows nothing.
|
||||
let dir = tempfile::Builder::new()
|
||||
.prefix("openidea-rst-")
|
||||
.tempdir()
|
||||
.map_err(|e| IdeError::internal(format!("cannot create a folder to run docutils in: {e}")))?;
|
||||
let mut cmd = Command::new(python);
|
||||
// `-E`: `PYTHONPATH` and the like don't apply. The file name only appears in docutils'
|
||||
// messages: nothing is read relative to it.
|
||||
cmd.arg("-E").arg("-c").arg(RENDER).arg(path.file_name().unwrap_or(path.as_os_str()));
|
||||
cmd.current_dir(dir.path());
|
||||
let out = CliTool::new("Python", Decoding::Utf8Lossy).run_with_input(
|
||||
cmd,
|
||||
Some(Input::Threaded(text)),
|
||||
TIMEOUT,
|
||||
cancel,
|
||||
)?;
|
||||
if out.success {
|
||||
return Ok(out.stdout);
|
||||
}
|
||||
if out.stdout == NO_DOCUTILS {
|
||||
return Err(IdeError::unavailable(format!(
|
||||
"docutils is not installed for {}. Install it to preview reStructuredText.",
|
||||
python.display()
|
||||
)));
|
||||
}
|
||||
let last = out.stderr.lines().rev().find(|l| !l.trim().is_empty()).unwrap_or("docutils failed");
|
||||
Err(IdeError::internal(last.trim().to_owned()))
|
||||
}
|
||||
|
||||
ide_command::domain!(rst: rst_preview);
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn python() -> Option<PathBuf> {
|
||||
["python3", "python"].into_iter().map(PathBuf::from).find(|p| Command::new(p).arg("--version").output().is_ok())
|
||||
}
|
||||
|
||||
fn has_docutils(python: &Path) -> bool {
|
||||
Command::new(python).args(["-c", "import docutils"]).status().is_ok_and(|s| s.success())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn renders_without_reading_past_the_document() {
|
||||
let Some(python) = python().filter(|p| has_docutils(p)) else {
|
||||
eprintln!("skipped: no Python with docutils");
|
||||
return;
|
||||
};
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let secret = dir.path().join("secret.txt");
|
||||
std::fs::write(&secret, "TOP-SECRET").unwrap();
|
||||
let text = format!(
|
||||
"Title\n=====\n\n*hi* ünï\n\n.. include:: {0}\n\n.. raw:: html\n\n <script>x()</script>\n\n\
|
||||
.. csv-table::\n :file: {0}\n\n.. image:: pic.png\n :scale: 50\n",
|
||||
secret.display()
|
||||
);
|
||||
let html = render(&python, &dir.path().join("doc.rst"), &text, None).unwrap();
|
||||
assert!(html.contains("<em>hi</em> ünï"), "{html}");
|
||||
assert!(!html.contains("TOP-SECRET"), "{html}");
|
||||
assert!(!html.contains("<script>"), "{html}");
|
||||
assert!(html.contains(""include" directive disabled"), "{html}");
|
||||
assert!(html.contains(""raw" directive disabled"), "{html}");
|
||||
assert!(html.contains(r#"src="pic.png""#), "{html}");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn says_when_docutils_is_missing() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let Some(python) = python() else {
|
||||
eprintln!("skipped: no Python");
|
||||
return;
|
||||
};
|
||||
// A stand-in interpreter whose `import docutils` fails, wherever docutils is installed.
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let fake = dir.path().join("python");
|
||||
let blocker = dir.path().join("block");
|
||||
std::fs::create_dir(&blocker).unwrap();
|
||||
std::fs::write(blocker.join("docutils.py"), "raise ImportError('blocked')\n").unwrap();
|
||||
// Drops `-E`, which would ignore the `PYTHONPATH` that blocks docutils.
|
||||
let script = format!(
|
||||
"#!/bin/sh\n[ \"$1\" = -E ] && shift\nPYTHONPATH='{}' exec '{}' \"$@\"\n",
|
||||
blocker.display(),
|
||||
python.display()
|
||||
);
|
||||
std::fs::write(&fake, script).unwrap();
|
||||
std::fs::set_permissions(&fake, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
let error = render(&fake, Path::new("doc.rst"), "x", None).unwrap_err();
|
||||
assert!(error.to_string().contains("docutils is not installed"), "{error}");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn cancelling_stops_the_interpreter() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let slow = dir.path().join("python");
|
||||
std::fs::write(&slow, "#!/bin/sh\nsleep 30\n").unwrap();
|
||||
std::fs::set_permissions(&slow, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
let cancel = CancellationToken::new();
|
||||
let later = cancel.clone();
|
||||
std::thread::spawn(move || {
|
||||
std::thread::sleep(Duration::from_millis(200));
|
||||
later.cancel();
|
||||
});
|
||||
let started = std::time::Instant::now();
|
||||
let error = render(&slow, Path::new("doc.rst"), "x", Some(&cancel)).unwrap_err();
|
||||
assert_eq!(error.kind, ide_core::error::ErrorKind::Cancelled);
|
||||
assert!(started.elapsed() < Duration::from_secs(5));
|
||||
}
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
# Renders the reStructuredText on stdin (argv[1] names the file in messages) to the HTML body of its
|
||||
# preview on stdout. Nothing is read past the document: no included files, raw HTML, URLs
|
||||
# or docutils.conf, and no image is opened to size it. Problems show inline.
|
||||
import sys
|
||||
|
||||
try:
|
||||
import docutils.core
|
||||
except ImportError:
|
||||
sys.stdout.write("no-docutils")
|
||||
sys.exit(3)
|
||||
|
||||
source = sys.stdin.buffer.read().decode("utf-8", "replace")
|
||||
parts = docutils.core.publish_parts(
|
||||
source,
|
||||
source_path=sys.argv[1],
|
||||
writer_name="html5",
|
||||
settings_overrides={
|
||||
"_disable_config": True,
|
||||
"file_insertion_enabled": False,
|
||||
"raw_enabled": False,
|
||||
"image_loading": "link",
|
||||
"embed_stylesheet": False,
|
||||
"math_output": "MathML",
|
||||
"syntax_highlight": "none",
|
||||
"report_level": 2,
|
||||
"halt_level": 5,
|
||||
"warning_stream": False,
|
||||
"traceback": True,
|
||||
},
|
||||
)
|
||||
sys.stdout.buffer.write(parts["html_body"].encode("utf-8"))
|
||||
@@ -4,7 +4,7 @@ use ide_command::command;
|
||||
use ide_core::remote_settings::RunTargetKind;
|
||||
use ide_core::{IdeError, IdeResult, RunId};
|
||||
use ide_run::{OutputChunk, RunAttach, RunConfig, RunInfo, StartOptions};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
@@ -439,8 +439,6 @@ async fn start_inner(
|
||||
python_paths: Vec::new(),
|
||||
ruby_reporter: None,
|
||||
plots: None,
|
||||
capture_junit_reports: false,
|
||||
conda_prefix: None,
|
||||
},
|
||||
sink,
|
||||
Box::new(move |c| on_output(c)),
|
||||
@@ -450,10 +448,6 @@ async fn start_inner(
|
||||
if target.kind != RunTargetKind::Ssh {
|
||||
// A local run of the docker CLI: the command is resolved in the container, and
|
||||
// this machine's toolchains and `PYTHONPATH` don't apply.
|
||||
let mut config = config;
|
||||
if ide_run::is_python_kind(&config.kind) {
|
||||
container_python_path(&mut config.env, &super::python::paths(&project), &project.root);
|
||||
}
|
||||
let config = container::prepare(host, &project.root, target, config).await?;
|
||||
let encoding = settings.console.encoding;
|
||||
let options = StartOptions {
|
||||
@@ -462,8 +456,6 @@ async fn start_inner(
|
||||
// A folder on this machine: not in the container.
|
||||
ruby_reporter: None,
|
||||
plots: None,
|
||||
capture_junit_reports: false,
|
||||
conda_prefix: None,
|
||||
};
|
||||
project.require_trust()?;
|
||||
return host.processes.start(
|
||||
@@ -475,11 +467,7 @@ async fn start_inner(
|
||||
);
|
||||
}
|
||||
let out = on_output.clone();
|
||||
let debugpy = container::ide_debugpy(&host.data_dir);
|
||||
return host
|
||||
.remote
|
||||
.run(&settings, &project.root, &config, debugpy.as_deref(), sink.clone(), Box::new(move |c| out(c)))
|
||||
.await;
|
||||
return host.remote.run(&settings, &project.root, &config, sink.clone(), Box::new(move |c| out(c))).await;
|
||||
}
|
||||
let mut config = config;
|
||||
let (root, settings, fallback) = settings_for(host, &project, &mut config)?;
|
||||
@@ -516,7 +504,7 @@ async fn start_inner(
|
||||
}
|
||||
// A Python configuration pointing at a missing interpreter fails in the depth of
|
||||
// process spawn otherwise; name the cause and the fix like PyCharm's "Invalid SDK".
|
||||
let is_python = ide_run::is_python_kind(&config.kind);
|
||||
let is_python = matches!(config.kind.as_str(), "python" | "pytest" | "unittest" | "doctest" | "django-test");
|
||||
if is_python && Path::new(&config.command).components().count() > 1 {
|
||||
let cwd = project.root.join(config.cwd.as_deref().unwrap_or(Path::new("")));
|
||||
let executable = ide_core::project_roots::resolve(&cwd, Path::new(&config.command));
|
||||
@@ -540,15 +528,6 @@ async fn start_inner(
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(e.to_string()))??;
|
||||
}
|
||||
if config.kind == "xcode" {
|
||||
let (dir, cache) = (run_dir.clone(), project.cache_dir.clone());
|
||||
config = host
|
||||
.blocking(move || {
|
||||
ide_run::xcode::prepare(&dir, &cache, &mut config)?;
|
||||
Ok(config)
|
||||
})
|
||||
.await?;
|
||||
}
|
||||
if config.kind == "go" && config.extras.params.get("scope").is_some_and(|s| s == "file") {
|
||||
let root = project.root.clone();
|
||||
config = host
|
||||
@@ -558,17 +537,7 @@ async fn start_inner(
|
||||
})
|
||||
.await?;
|
||||
}
|
||||
if config.kind == "xcode-test" {
|
||||
let bundles = project.cache_dir.join("xcresult");
|
||||
config = host
|
||||
.blocking(move || {
|
||||
ide_run::xcode::prepare_test(&mut config, &bundles)?;
|
||||
Ok(config)
|
||||
})
|
||||
.await?;
|
||||
}
|
||||
let mut python_paths = if *root != project.root { vec![root.clone()] } else { super::python::paths(&project) };
|
||||
let mut conda_prefix = None;
|
||||
if is_python {
|
||||
let near = ide_run::scope::owner(&project.root, &config);
|
||||
python_paths = super::python::with_user_paths(
|
||||
@@ -578,16 +547,13 @@ async fn start_inner(
|
||||
Some(&config.command),
|
||||
Some(&near),
|
||||
);
|
||||
conda_prefix = super::python::conda_prefix(&host.config_dir, &project, Some(&config.command), Some(&near));
|
||||
}
|
||||
let encoding = settings.console.encoding;
|
||||
let options = StartOptions {
|
||||
encoding: Some(encoding).filter(|e| !e.trim().is_empty()),
|
||||
python_paths,
|
||||
ruby_reporter: ruby_reporter_dir(host, &config),
|
||||
plots: if is_python { super::plots::prepare(host, &project).await } else { None },
|
||||
capture_junit_reports: config.is_test && config.extras.test_runner.as_deref() == Some("jvm"),
|
||||
conda_prefix,
|
||||
plots: if is_python { super::plots::prepare(host, &project) } else { None },
|
||||
};
|
||||
project.require_trust()?;
|
||||
if config.kind == "go" && matches!(config.args.first().map(String::as_str), Some("mod" | "work")) {
|
||||
@@ -726,18 +692,6 @@ pub use commands::*;
|
||||
#[cfg(test)]
|
||||
mod ownership_tests {
|
||||
use super::*;
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn source_roots_go_on_the_container_pythonpath() {
|
||||
let root = Path::new("/p");
|
||||
let mut env = std::collections::BTreeMap::from([("PYTHONPATH".to_owned(), "/opt/extra".to_owned())]);
|
||||
container_python_path(&mut env, &[root.into(), root.join("src"), "/home/u/lib".into()], root);
|
||||
assert_eq!(env["PYTHONPATH"], "/p:/p/src:/opt/extra", "outside the project: not mounted");
|
||||
let mut none = std::collections::BTreeMap::new();
|
||||
container_python_path(&mut none, &["/elsewhere".into()], root);
|
||||
assert!(none.is_empty());
|
||||
}
|
||||
#[test]
|
||||
fn unlinked_builds_do_not_reappear_as_detected_application_configs() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
@@ -900,63 +854,12 @@ mod ownership_tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// The file here of a path a run in a container of `target` printed (`/app/main.py`, a
|
||||
/// `site-packages` module in a traceback): in a folder of the project the container mounts,
|
||||
/// or, when `target` is the project interpreter's, in the copy of its libraries. `None`: no
|
||||
/// such file.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn run_container_path(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
path: String,
|
||||
target: String,
|
||||
) -> IdeResult<Option<ide_core::IpcPath>> {
|
||||
host.require_trust(window)?;
|
||||
let project = host.project(window)?;
|
||||
let settings = project.settings.effective();
|
||||
let Some(run_target) =
|
||||
settings.run_targets.iter().find(|t| t.id == target && t.kind != RunTargetKind::Ssh).cloned()
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
let snapshots = crate::ops::sdk::container_python::snapshots_of(host, &project.root, &settings, &target);
|
||||
let (root, data_dir) = (project.root.clone(), host.data_dir.clone());
|
||||
host.blocking(move || {
|
||||
if !path.starts_with('/') {
|
||||
return Ok(None);
|
||||
}
|
||||
let library = snapshots
|
||||
.and_then(|dir| ide_sdk::container_python::current(&dir))
|
||||
.and_then(|(dir, snapshot)| ide_sdk::container_python::snapshot_file(&dir, &snapshot, &path));
|
||||
let file = library.filter(|f| f.is_file()).or_else(|| {
|
||||
let mounts = container::mounts(&data_dir, &root, &run_target).ok()?;
|
||||
ide_remote::docker::mounted_file(&path, &mounts).filter(|f| f.is_file())
|
||||
});
|
||||
Ok(file.map(Into::into))
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// The project's source roots on `PYTHONPATH` in a container, as a local run gets them:
|
||||
/// they are mounted with the project, and `container::prepare` maps their paths. The
|
||||
/// container's separator is `:`, whatever this machine's is.
|
||||
fn container_python_path(env: &mut std::collections::BTreeMap<String, String>, roots: &[PathBuf], root: &Path) {
|
||||
let mut paths: Vec<String> =
|
||||
roots.iter().filter(|p| p.starts_with(root)).map(|p| p.to_string_lossy().into_owned()).collect();
|
||||
if paths.is_empty() {
|
||||
return;
|
||||
}
|
||||
paths.extend(env.get("PYTHONPATH").cloned());
|
||||
env.insert("PYTHONPATH".into(), paths.join(":"));
|
||||
}
|
||||
|
||||
ide_command::domain!(
|
||||
run:
|
||||
run_apply_settings,
|
||||
run_attach,
|
||||
run_close_stdin,
|
||||
run_configs,
|
||||
run_container_path,
|
||||
run_list,
|
||||
run_resize,
|
||||
run_save_configs,
|
||||
|
||||
@@ -22,23 +22,6 @@ pub async fn run_dotnet_resolve(host: &Host, window: &str, config: RunConfig, de
|
||||
Ok(config)
|
||||
}
|
||||
|
||||
/// The tests of an `xcodebuild test` result bundle, as `xcresulttool` reports them (JSON).
|
||||
#[command(trust = trusted)]
|
||||
pub async fn run_xcode_test_results(host: &Host, window: &str, bundle: std::path::PathBuf) -> IdeResult<String> {
|
||||
host.require_trust(window)?;
|
||||
if bundle.extension().is_none_or(|e| e != "xcresult") {
|
||||
return Err(IdeError::invalid("Not an Xcode result bundle"));
|
||||
}
|
||||
let mut cmd = tokio::process::Command::new("xcrun");
|
||||
cmd.args(["xcresulttool", "get", "test-results", "tests", "--compact", "--path"]).arg(&bundle);
|
||||
ide_core::process::prepare(cmd.as_std_mut());
|
||||
let out = cmd.output().await?;
|
||||
if !out.status.success() {
|
||||
return Err(IdeError::internal(String::from_utf8_lossy(&out.stderr).trim().to_owned()));
|
||||
}
|
||||
String::from_utf8(out.stdout).map_err(|e| IdeError::internal(e.to_string()))
|
||||
}
|
||||
|
||||
fn application_cache(project: &crate::project::Project, id: &str) -> std::path::PathBuf {
|
||||
use std::hash::{Hash, Hasher};
|
||||
let mut hash = std::collections::hash_map::DefaultHasher::new();
|
||||
@@ -194,23 +177,18 @@ pub async fn run_gradle_init_script(name: String, text: String) -> IdeResult<Str
|
||||
.map_err(|e| IdeError::internal(e.to_string()))?
|
||||
}
|
||||
|
||||
/// Results from the JUnit XML reports (Surefire, Failsafe, Gradle) changed by `run`.
|
||||
/// Without a run id, read reports in `module` written since `since_ms` (Unix epoch, ms).
|
||||
/// Results from the JUnit XML reports (Surefire, Failsafe, Gradle) of the module at
|
||||
/// `module` (relative to the project root) written since `since_ms` (Unix epoch, ms).
|
||||
#[command(trust = trusted)]
|
||||
pub async fn run_test_reports(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
module: Option<std::path::PathBuf>,
|
||||
since_ms: f64,
|
||||
run: Option<ide_core::RunId>,
|
||||
) -> IdeResult<Vec<ide_run::junit::TestCaseReport>> {
|
||||
let root = host.project(window)?.root.clone();
|
||||
let since = std::time::UNIX_EPOCH + std::time::Duration::from_millis(since_ms.max(0.0) as u64);
|
||||
if let Some(run) = run {
|
||||
let processes = host.processes.clone();
|
||||
return crate::ops::blocking_value(move || processes.test_reports(run, &root, since)).await;
|
||||
}
|
||||
let dir = module.map(|m| root.join(m)).unwrap_or(root);
|
||||
let since = std::time::UNIX_EPOCH + std::time::Duration::from_millis(since_ms.max(0.0) as u64);
|
||||
tokio::task::spawn_blocking(move || ide_run::junit::read_reports(&ide_run::junit::report_dirs(&dir), since))
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(e.to_string()))
|
||||
@@ -448,7 +426,6 @@ ide_command::domain!(
|
||||
run_application_build,
|
||||
run_application_publish,
|
||||
run_dotnet_resolve,
|
||||
run_xcode_test_results,
|
||||
run_env_files,
|
||||
run_gradle_init_script,
|
||||
run_gradle_jvm_args_script,
|
||||
|
||||
@@ -6,15 +6,16 @@ use ide_core::remote_settings::{RunTarget, RunTargetKind};
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use ide_docker::DockerEndpoint;
|
||||
use ide_remote::docker::{
|
||||
ComposeService, ContainerDebug, ContainerRun, DEBUG_BOOTSTRAP, DEBUG_BOOTSTRAP_NAME, compose_container_root,
|
||||
compose_service, container_config, container_name, default_container_root,
|
||||
ContainerDebug, ContainerRun, DEBUG_BOOTSTRAP, DEBUG_BOOTSTRAP_NAME, compose_container_root, container_config,
|
||||
container_name, default_container_root,
|
||||
};
|
||||
use ide_remote::target::DEBUG_PARAM;
|
||||
use ide_run::RunConfig;
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{LazyLock, Mutex};
|
||||
use std::time::SystemTime;
|
||||
|
||||
/// Set by the Debug action on a configuration that runs on a container target: the
|
||||
/// program starts under debugpy and waits for the debugger.
|
||||
const DEBUG_PARAM: &str = "containerDebug";
|
||||
|
||||
/// `config` rewritten to run in a new container of `target`'s image or service.
|
||||
pub(super) async fn prepare(host: &Host, root: &Path, target: RunTarget, config: RunConfig) -> IdeResult<RunConfig> {
|
||||
@@ -38,7 +39,6 @@ pub(super) async fn prepare(host: &Host, root: &Path, target: RunTarget, config:
|
||||
})?;
|
||||
let container_root = container_root(&endpoint, &root, &target)?;
|
||||
let file_env = env_files(&root, &config)?;
|
||||
let (service_env, service_ports) = server_context(&data_dir, &root, &target, &config);
|
||||
let name = container_name(&config.id, &unique());
|
||||
let debugging = if debug { Some(Debugging::prepare(&data_dir)?) } else { None };
|
||||
container_config(
|
||||
@@ -50,8 +50,6 @@ pub(super) async fn prepare(host: &Host, root: &Path, target: RunTarget, config:
|
||||
docker: &docker.to_string_lossy(),
|
||||
endpoint_env: &ide_docker::run_env(&endpoint),
|
||||
file_env: &file_env,
|
||||
service_env: &service_env,
|
||||
service_ports: &service_ports,
|
||||
name: &name,
|
||||
user: user(&root, &target),
|
||||
debug: debugging.as_ref().map(|d| ContainerDebug {
|
||||
@@ -88,79 +86,6 @@ pub(crate) fn container_root(endpoint: &DockerEndpoint, root: &Path, target: &Ru
|
||||
})
|
||||
}
|
||||
|
||||
/// Compose files `docker compose` reads when a target names none.
|
||||
const DEFAULT_COMPOSE_FILES: [&str; 8] = [
|
||||
"compose.yaml",
|
||||
"compose.yml",
|
||||
"docker-compose.yaml",
|
||||
"docker-compose.yml",
|
||||
"compose.override.yaml",
|
||||
"compose.override.yml",
|
||||
"docker-compose.override.yaml",
|
||||
"docker-compose.override.yml",
|
||||
];
|
||||
|
||||
type Mounts = Vec<(PathBuf, String)>;
|
||||
/// The modification times of the Compose files a result was read with.
|
||||
type Stamp = Vec<Option<SystemTime>>;
|
||||
|
||||
/// `docker compose config` per project and target, until a Compose file changes.
|
||||
type ServiceCache = HashMap<(PathBuf, String), (Stamp, ComposeService)>;
|
||||
static COMPOSE_SERVICES: LazyLock<Mutex<ServiceCache>> = LazyLock::new(Default::default);
|
||||
|
||||
/// The folders of the project a container of `target` mounts: `(folder here, folder in
|
||||
/// the container)`. A Compose service's come from `docker compose config` (cached).
|
||||
pub(crate) fn mounts(data_dir: &Path, root: &Path, target: &RunTarget) -> IdeResult<Mounts> {
|
||||
match target.container_root.trim() {
|
||||
"" if target.kind == RunTargetKind::Compose => {}
|
||||
"" => return Ok(vec![(root.to_path_buf(), default_container_root(root))]),
|
||||
folder => return Ok(vec![(root.to_path_buf(), folder.to_owned())]),
|
||||
}
|
||||
Ok(compose_service_of(data_dir, root, target)?.mounts.into_iter().map(|(s, t)| (PathBuf::from(s), t)).collect())
|
||||
}
|
||||
|
||||
/// What `docker compose config` says of `target`'s service (cached until a Compose file changes).
|
||||
fn compose_service_of(data_dir: &Path, root: &Path, target: &RunTarget) -> IdeResult<ComposeService> {
|
||||
let files: Vec<PathBuf> = if target.compose_files.iter().all(|f| f.trim().is_empty()) {
|
||||
DEFAULT_COMPOSE_FILES.iter().map(|f| root.join(f)).collect()
|
||||
} else {
|
||||
target.compose_files.iter().map(|f| root.join(f.trim())).collect()
|
||||
};
|
||||
let stamp: Stamp = files.iter().map(|f| std::fs::metadata(f).and_then(|m| m.modified()).ok()).collect();
|
||||
let key = (root.to_path_buf(), format!("{}\0{}\0{}", target.id, target.service, target.compose_files.join(";")));
|
||||
let cache = || COMPOSE_SERVICES.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if let Some((seen, service)) = cache().get(&key)
|
||||
&& *seen == stamp
|
||||
{
|
||||
return Ok(service.clone());
|
||||
}
|
||||
let json = ide_docker::compose_config(&endpoint(data_dir, target)?, root, &target.compose_files)?;
|
||||
let service = compose_service(&json, target.service.trim())?;
|
||||
cache().insert(key, (stamp, service.clone()));
|
||||
Ok(service)
|
||||
}
|
||||
|
||||
/// Variables a development server in the container finds besides the configuration's: the
|
||||
/// Compose service's `environment` (and published ports), and the `.env` / `.flaskenv` of the
|
||||
/// folder it runs in. Best effort: a Compose file `docker compose config` can't read gives none.
|
||||
fn server_context(
|
||||
data_dir: &Path,
|
||||
root: &Path,
|
||||
target: &RunTarget,
|
||||
config: &RunConfig,
|
||||
) -> (BTreeMap<String, String>, Vec<(u16, u16)>) {
|
||||
let service = if target.kind == RunTargetKind::Compose {
|
||||
compose_service_of(data_dir, root, target).unwrap_or_default()
|
||||
} else {
|
||||
ComposeService::default()
|
||||
};
|
||||
let cwd = config.cwd.as_ref().map_or(root.to_path_buf(), |c| root.join(c));
|
||||
let dotenv: Vec<PathBuf> = [".env", ".flaskenv"].iter().map(|f| cwd.join(f)).filter(|f| f.is_file()).collect();
|
||||
let mut env = ide_run::envfile::load(&dotenv, &BTreeMap::new()).unwrap_or_default();
|
||||
env.extend(service.environment);
|
||||
(env, service.ports)
|
||||
}
|
||||
|
||||
/// What a debug run mounts and publishes.
|
||||
struct Debugging {
|
||||
port: u16,
|
||||
@@ -174,18 +99,14 @@ impl Debugging {
|
||||
let bootstrap_dir = data_dir.join("container-debug");
|
||||
std::fs::create_dir_all(&bootstrap_dir)?;
|
||||
std::fs::write(bootstrap_dir.join(DEBUG_BOOTSTRAP_NAME), DEBUG_BOOTSTRAP)?;
|
||||
Ok(Self { port: free_port()?, bootstrap_dir, debugpy: ide_debugpy(data_dir) })
|
||||
// The managed install the local debugger falls back to (`ide_dap::adapter::prepare_debugpy`).
|
||||
let tools = ide_dap::adapter::tools_root().unwrap_or_else(|| ide_tools::tools_dir(data_dir));
|
||||
let lib = ide_tools::python_lib_dir(&tools, ide_dap::adapter::DEBUGPY_TOOL);
|
||||
let debugpy = lib.join("debugpy").join("__init__.py").is_file().then_some(lib);
|
||||
Ok(Self { port: free_port()?, bootstrap_dir, debugpy })
|
||||
}
|
||||
}
|
||||
|
||||
/// The managed install the local debugger falls back to (`ide_dap::adapter::prepare_debugpy`):
|
||||
/// the folder holding the `debugpy` package, when it is installed.
|
||||
pub(super) fn ide_debugpy(data_dir: &Path) -> Option<PathBuf> {
|
||||
let tools = ide_dap::adapter::tools_root().unwrap_or_else(|| ide_tools::tools_dir(data_dir));
|
||||
let lib = ide_tools::python_lib_dir(&tools, ide_dap::adapter::DEBUGPY_TOOL);
|
||||
lib.join("debugpy").join("__init__.py").is_file().then_some(lib)
|
||||
}
|
||||
|
||||
/// A port nobody listens on here: debugpy listens on the same port in the container,
|
||||
/// published on the loopback interface.
|
||||
fn free_port() -> IdeResult<u16> {
|
||||
|
||||
@@ -377,7 +377,6 @@ pub async fn sdk_python_hatch_envs(host: &Host, window: &str, request: RequestId
|
||||
|
||||
/// Creates a Python environment and streams its output through `on_output`.
|
||||
/// With Pipenv, `install_packages` also installs the packages declared in the project's `Pipfile`.
|
||||
/// With venv / uv, `system_site_packages` lets the environment see the base interpreter's packages.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[command(trust = outside_restricted)]
|
||||
pub async fn sdk_python_create_venv(
|
||||
@@ -387,14 +386,13 @@ pub async fn sdk_python_create_venv(
|
||||
base: PathBuf,
|
||||
location: PathBuf,
|
||||
install_packages: bool,
|
||||
system_site_packages: bool,
|
||||
request: RequestId,
|
||||
on_output: Channel<String>,
|
||||
) -> IdeResult<Sdk> {
|
||||
host.require_trust_if_project(window)?;
|
||||
let cancel = host.begin_project_request(window, request);
|
||||
let result = blocking(move || {
|
||||
ide_sdk::python::create_venv(tool, &base, &location, install_packages, system_site_packages, &cancel, &|line| {
|
||||
ide_sdk::python::create_venv(tool, &base, &location, install_packages, &cancel, &|line| {
|
||||
let _ = on_output.send(line);
|
||||
})
|
||||
})
|
||||
@@ -434,8 +432,7 @@ pub async fn sdk_python_package_index(
|
||||
result
|
||||
}
|
||||
|
||||
/// Installs (`uninstall = false`, in editable mode with `editable`) or removes a package; output
|
||||
/// streams through `on_output`.
|
||||
/// Installs (`uninstall = false`) or removes a package; output streams through `on_output`.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[command(trust = outside_restricted)]
|
||||
pub async fn sdk_python_pip(
|
||||
@@ -445,7 +442,6 @@ pub async fn sdk_python_pip(
|
||||
requirement: String,
|
||||
uninstall: bool,
|
||||
upgrade: bool,
|
||||
editable: bool,
|
||||
request: RequestId,
|
||||
on_output: Channel<String>,
|
||||
) -> IdeResult<()> {
|
||||
@@ -459,15 +455,7 @@ pub async fn sdk_python_pip(
|
||||
if uninstall {
|
||||
ide_sdk::python::uninstall_package(&python, &requirement, &cancel, &send)
|
||||
} else {
|
||||
ide_sdk::python::install_package(
|
||||
&python,
|
||||
&requirement,
|
||||
upgrade,
|
||||
editable,
|
||||
project_root.as_deref(),
|
||||
&cancel,
|
||||
&send,
|
||||
)
|
||||
ide_sdk::python::install_package(&python, &requirement, upgrade, project_root.as_deref(), &cancel, &send)
|
||||
}
|
||||
})
|
||||
.await;
|
||||
|
||||
Loaded 100 of 1128 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Заблокувати користувача