дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-06 18:17:15 +02:00
Порівняти коміти
18
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
9661981d59 | ||
|
|
3278eab0c8 | ||
|
|
71bfc70996 | ||
|
|
1e6ab2ecff | ||
|
|
0f0e3e73e7 | ||
|
|
a2498f096a | ||
|
|
494d1a9bf5 | ||
|
|
417ecfed50 | ||
|
|
94653b487d | ||
|
|
a5473e896a | ||
|
|
8483c355c8 | ||
|
|
8d2d2d27e6 | ||
|
|
72db7ecb97 | ||
|
|
406cf4e474 | ||
|
|
bc019ace9d | ||
|
|
55c9787996 | ||
|
|
5b1e4a31f2 | ||
|
|
f3582403f3 |
No files matched your search
@@ -51,6 +51,8 @@ pub struct AdapterSpec {
|
||||
pub pinned: Option<ProgramPin>,
|
||||
/// See [`DebuggerConfig::resolve_lazy_variables`].
|
||||
pub resolve_lazy_variables: bool,
|
||||
/// Connect to the one lldb-dap server every such session shares ([`crate::lldb_server`]).
|
||||
pub shared: bool,
|
||||
}
|
||||
|
||||
/// Built-in adapters used when no language definition names `adapter`.
|
||||
@@ -193,6 +195,7 @@ pub fn resolve(config: &DebuggerConfig, cwd: PathBuf) -> AdapterSpec {
|
||||
connect: config.connect.clone(),
|
||||
pinned: config.pinned.clone(),
|
||||
resolve_lazy_variables: config.resolve_lazy_variables,
|
||||
shared: false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -298,7 +301,7 @@ fn managed_dirs(root: &Path) -> Vec<PathBuf> {
|
||||
/// The `PATH` an adapter runs with, unless its launch sets one: the search path language servers
|
||||
/// get, so what it starts in turn (js-debug's wrapper runs `node`, Delve runs `go build`) is
|
||||
/// found like Run finds it, even when the login shell's `PATH` didn't reach the app.
|
||||
fn adapter_path(env: &[(String, String)], cwd: &Path) -> Option<std::ffi::OsString> {
|
||||
pub(crate) fn adapter_path(env: &[(String, String)], cwd: &Path) -> Option<std::ffi::OsString> {
|
||||
let own = env.iter().any(|(k, _)| if cfg!(windows) { k.eq_ignore_ascii_case("PATH") } else { k == "PATH" });
|
||||
(!own).then(|| ide_core::tool_path::search_path_in(cwd))
|
||||
}
|
||||
@@ -744,6 +747,18 @@ impl AdapterLauncher for ProcessLauncher {
|
||||
.ok_or_else(|| missing(&spec))?
|
||||
}
|
||||
};
|
||||
#[cfg(target_os = "macos")]
|
||||
if spec.shared && spec.transport == Transport::Stdio && spec.connect.is_none() && spec.args.is_empty() {
|
||||
match crate::lldb_server::connect(&spec, &binary).await {
|
||||
Ok(Some(io)) => return Ok(io),
|
||||
Ok(None) => {}
|
||||
Err(e) => tracing::warn!(
|
||||
target: "ide_dap::adapter",
|
||||
"no shared lldb-dap server ({}); starting one for this session",
|
||||
e.message
|
||||
),
|
||||
}
|
||||
}
|
||||
let launch_after_configuration =
|
||||
if spec.adapter == "gdb" { prepare_gdb(&spec, &binary).await? } else { false };
|
||||
let base_args = substitute_root(&spec.args, &spec.cwd);
|
||||
@@ -891,7 +906,7 @@ fn is_port_race(err: &IdeError) -> bool {
|
||||
|| message.contains("exited before accepting connections")
|
||||
}
|
||||
|
||||
fn pump_lines<R: AsyncRead + Unpin + Send + 'static>(
|
||||
pub(crate) fn pump_lines<R: AsyncRead + Unpin + Send + 'static>(
|
||||
stream: R,
|
||||
name: String,
|
||||
sink: Arc<parking_lot::Mutex<Vec<String>>>,
|
||||
|
||||
@@ -103,6 +103,7 @@ pub(crate) fn bare_session_of(name: &str, request: &str) -> BareSession {
|
||||
connect: None,
|
||||
pinned: None,
|
||||
resolve_lazy_variables: false,
|
||||
shared: false,
|
||||
};
|
||||
let session = Session::new(
|
||||
DebugSessionId(1),
|
||||
|
||||
@@ -21,6 +21,8 @@ mod js_debug;
|
||||
mod jvm_memory;
|
||||
pub mod kotlin;
|
||||
pub mod kotlin_lsp;
|
||||
#[cfg(target_os = "macos")]
|
||||
mod lldb_server;
|
||||
mod memory;
|
||||
pub mod native;
|
||||
mod session;
|
||||
@@ -516,6 +518,7 @@ fn is_native(adapter: &str) -> bool {
|
||||
/// `extra_json` key naming the run whose JVM an attach debugs; IDE-side, never sent to the
|
||||
/// adapter.
|
||||
pub const RUN_LINK: &str = "__openideaRun";
|
||||
const XCODE_ATTACH: &str = "__openideaXcodeAttach";
|
||||
|
||||
fn take_run_link(arguments: &mut Value) -> Option<RunId> {
|
||||
let run = arguments.as_object_mut()?.remove(RUN_LINK)?;
|
||||
@@ -1203,6 +1206,7 @@ impl DebugManager {
|
||||
connect: None,
|
||||
pinned: None,
|
||||
resolve_lazy_variables: false,
|
||||
shared: false,
|
||||
};
|
||||
let cancel = ide_core::CancellationToken::new();
|
||||
self.start_session(
|
||||
@@ -1269,7 +1273,7 @@ impl DebugManager {
|
||||
parent: Option<DebugSessionId>,
|
||||
request: String,
|
||||
mut arguments: Value,
|
||||
spec: AdapterSpec,
|
||||
mut spec: AdapterSpec,
|
||||
reuse_port: Option<u16>,
|
||||
exception_classes: Option<Arc<dyn ide_jvm_inspect::ExceptionClassBreakpoints>>,
|
||||
cancel: ide_core::CancellationToken,
|
||||
@@ -1278,6 +1282,13 @@ impl DebugManager {
|
||||
if request != "launch" && request != "attach" {
|
||||
return Err(IdeError::invalid(format!("request must be `launch` or `attach`, got `{request}`")));
|
||||
}
|
||||
// Xcode Debug attaches to the app its run launched: a shared lldb-dap server keeps the
|
||||
// system libraries it parsed, so the next attach skips that (#6665 E7).
|
||||
let xcode_attach = arguments.as_object_mut().and_then(|args| args.remove(XCODE_ATTACH));
|
||||
spec.shared = xcode_attach == Some(Value::Bool(true))
|
||||
&& adapter_name == "lldb-dap"
|
||||
&& request == "attach"
|
||||
&& arguments.get(RUN_LINK).is_some();
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
|
||||
@@ -0,0 +1,408 @@
|
||||
//! Cache one lldb-dap server for successive attaches to Xcode runs (#6665 E7).
|
||||
//!
|
||||
//! An iOS app loads about 550 system libraries before its first line runs, and a fresh lldb-dap
|
||||
//! parses all of their symbol tables (about 5 million symbols) on each attach: 1.5 s on an idle
|
||||
//! Mac, far more under load. A server keeps the modules it parsed, so later sessions skip that
|
||||
//! and reach a breakpoint about as fast as Run reaches the same line. LLDB's own on-disk index
|
||||
//! cache would serve the first session too, but Xcode 27.1's lldb crashes on cached symbols.
|
||||
//!
|
||||
//! The server holds about 1 GB, so it ends once no session has been connected for
|
||||
//! [`IDLE_TIMEOUT`]; the next Debug then starts cold, as every Debug did before. A shell holds
|
||||
//! it and ends it when its stdin closes: when the IDE quits or crashes, when the server idles
|
||||
//! out, or when a server for another lldb-dap or environment replaces it.
|
||||
|
||||
use crate::adapter::{AdapterIo, AdapterSpec, adapter_path, pump_lines};
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use std::ffi::OsString;
|
||||
use std::fs::Permissions;
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::pin::Pin;
|
||||
use std::process::Stdio;
|
||||
use std::sync::{Arc, LazyLock};
|
||||
use std::task::{Context, Poll};
|
||||
use std::time::{Duration, Instant};
|
||||
use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};
|
||||
use tokio::net::UnixStream;
|
||||
use tokio::process::{Child, Command};
|
||||
|
||||
/// What a server was started with: a session reuses it only when its own start would match.
|
||||
#[derive(PartialEq)]
|
||||
struct Key {
|
||||
binary: PathBuf,
|
||||
cwd: PathBuf,
|
||||
cwd_env: Vec<(OsString, Option<OsString>)>,
|
||||
}
|
||||
|
||||
struct Server {
|
||||
key: Key,
|
||||
socket: PathBuf,
|
||||
/// Recent stderr for the active connection.
|
||||
stderr: Arc<parking_lot::Mutex<Vec<String>>>,
|
||||
idle: Arc<Idle>,
|
||||
/// The shell holding the server; dropping it closes its stdin, which ends the server.
|
||||
_holder: Child,
|
||||
_socket_dir: tempfile::TempDir,
|
||||
}
|
||||
|
||||
/// When the last session disconnected, or `None` while a session owns the server.
|
||||
type Idle = parking_lot::Mutex<Option<Instant>>;
|
||||
|
||||
type Slot = tokio::sync::Mutex<Option<Server>>;
|
||||
|
||||
static SERVER: LazyLock<Slot> = LazyLock::new(Default::default);
|
||||
|
||||
/// How long a server with no session stays up.
|
||||
const IDLE_TIMEOUT: Duration = Duration::from_secs(10 * 60);
|
||||
/// How long a new server may take to listen.
|
||||
const START_TIMEOUT: Duration = Duration::from_secs(15);
|
||||
/// A connection to a running server; a server that does not take it is replaced.
|
||||
const PROBE_TIMEOUT: Duration = Duration::from_millis(500);
|
||||
|
||||
/// Starts the server and ends it when the shell's stdin closes (`read` sees EOF) or when the
|
||||
/// server exits on its own (`wait`), so a `binary` without `--connection` fails at once.
|
||||
const HOLDER: &str = "exec 3<&0\n\
|
||||
\"$0\" --connection \"$1\" </dev/null >/dev/null &\n\
|
||||
server=$!\n\
|
||||
(read _ <&3; kill \"$server\" 2>/dev/null) &\n\
|
||||
watcher=$!\n\
|
||||
wait \"$server\"\n\
|
||||
result=$?\n\
|
||||
kill \"$watcher\" 2>/dev/null\n\
|
||||
wait \"$watcher\" 2>/dev/null\n\
|
||||
exit \"$result\"\n";
|
||||
|
||||
/// A connection to the shared server of `binary`, started first when there is none.
|
||||
pub async fn connect(spec: &AdapterSpec, binary: &Path) -> IdeResult<Option<AdapterIo>> {
|
||||
connect_to(&SERVER, spec, binary, IDLE_TIMEOUT).await
|
||||
}
|
||||
|
||||
async fn connect_to(
|
||||
slot: &'static Slot,
|
||||
spec: &AdapterSpec,
|
||||
binary: &Path,
|
||||
idle_timeout: Duration,
|
||||
) -> IdeResult<Option<AdapterIo>> {
|
||||
// The server gets the environment a per-session lldb-dap would: the project's (its Xcode's
|
||||
// `DEVELOPER_DIR`, from `cwd`), the adapter's search path and the spec's own variables.
|
||||
let mut cmd = Command::new("/bin/sh");
|
||||
cmd.current_dir(&spec.cwd);
|
||||
if let Some(path) = adapter_path(&spec.env, &spec.cwd) {
|
||||
cmd.env("PATH", path);
|
||||
}
|
||||
cmd.envs(spec.env.iter().map(|(k, v)| (k, v)));
|
||||
ide_core::process::prepare(cmd.as_std_mut());
|
||||
let mut env: Vec<_> = cmd.as_std().get_envs().map(|(k, v)| (k.to_owned(), v.map(|v| v.to_owned()))).collect();
|
||||
env.sort();
|
||||
let key = Key { binary: binary.to_path_buf(), cwd: spec.cwd.clone(), cwd_env: env };
|
||||
|
||||
let mut server = slot.lock().await;
|
||||
// A concurrent launch uses its own adapter. Replacing the cached process here would
|
||||
// disconnect the ongoing session, and concurrent sessions would share its stderr.
|
||||
if server.as_ref().is_some_and(|running| running.idle.lock().is_none()) {
|
||||
return Ok(None);
|
||||
}
|
||||
if let Some(running) = server.as_ref().filter(|s| s.key == key)
|
||||
&& let Ok(Ok(stream)) = tokio::time::timeout(PROBE_TIMEOUT, UnixStream::connect(&running.socket)).await
|
||||
{
|
||||
running.stderr.lock().clear();
|
||||
return Ok(Some(io(stream, running.stderr.clone(), lease(&running.idle))));
|
||||
}
|
||||
*server = None;
|
||||
let socket_dir = tempfile::Builder::new()
|
||||
.permissions(Permissions::from_mode(0o700))
|
||||
.tempdir()
|
||||
.map_err(|e| IdeError::unavailable(format!("cannot create the lldb-dap socket directory: {e}")))?;
|
||||
let socket = socket_dir.path().join("dap.sock");
|
||||
let mut uri = OsString::from("accept://");
|
||||
uri.push(&socket);
|
||||
ide_core::process::own_group(cmd.as_std_mut());
|
||||
cmd.arg("-c").arg(HOLDER).arg(binary).arg(uri).stdin(Stdio::piped()).stdout(Stdio::null()).stderr(Stdio::piped());
|
||||
let mut holder = cmd.spawn().map_err(|e| IdeError::unavailable(format!("failed to start lldb-dap: {e}")))?;
|
||||
let stderr = Arc::new(parking_lot::Mutex::new(Vec::new()));
|
||||
if let Some(err) = holder.stderr.take() {
|
||||
pump_lines(err, spec.adapter.clone(), stderr.clone(), None);
|
||||
}
|
||||
let stream = connect_when_ready(&socket, &mut holder).await?;
|
||||
let idle = Arc::new(Idle::default());
|
||||
let first = lease(&idle);
|
||||
tokio::spawn(end_when_idle(slot, idle.clone(), idle_timeout));
|
||||
*server = Some(Server { key, socket, stderr: stderr.clone(), idle, _holder: holder, _socket_dir: socket_dir });
|
||||
Ok(Some(io(stream, stderr, first)))
|
||||
}
|
||||
|
||||
async fn connect_when_ready(socket: &Path, holder: &mut Child) -> IdeResult<UnixStream> {
|
||||
let deadline = Instant::now() + START_TIMEOUT;
|
||||
loop {
|
||||
let error = match UnixStream::connect(socket).await {
|
||||
Ok(stream) => return Ok(stream),
|
||||
Err(error) => error,
|
||||
};
|
||||
if let Ok(Some(status)) = holder.try_wait() {
|
||||
return Err(IdeError::unavailable(format!("debug adapter exited before accepting connections ({status})")));
|
||||
}
|
||||
if Instant::now() >= deadline {
|
||||
return Err(IdeError::unavailable(format!("could not connect to lldb-dap: {error}")));
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(50)).await;
|
||||
}
|
||||
}
|
||||
|
||||
/// A session's hold on the server, released when its connection's both halves are gone.
|
||||
struct Lease(Arc<Idle>);
|
||||
|
||||
fn lease(idle: &Arc<Idle>) -> Arc<Lease> {
|
||||
*idle.lock() = None;
|
||||
Arc::new(Lease(idle.clone()))
|
||||
}
|
||||
|
||||
impl Drop for Lease {
|
||||
fn drop(&mut self) {
|
||||
*self.0.lock() = Some(Instant::now());
|
||||
}
|
||||
}
|
||||
|
||||
/// Ends the server in `slot` once no session has been connected to it for `timeout`; returns
|
||||
/// early when another server took its place.
|
||||
async fn end_when_idle(slot: &'static Slot, idle: Arc<Idle>, timeout: Duration) {
|
||||
loop {
|
||||
let since = *idle.lock();
|
||||
let wait = since.map_or(timeout, |at| (at + timeout).saturating_duration_since(Instant::now()));
|
||||
tokio::time::sleep(wait.max(Duration::from_millis(10))).await;
|
||||
let mut server = slot.lock().await;
|
||||
if !server.as_ref().is_some_and(|s| Arc::ptr_eq(&s.idle, &idle)) {
|
||||
return;
|
||||
}
|
||||
if idle.lock().is_some_and(|at| at.elapsed() >= timeout) {
|
||||
*server = None;
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One half of a session's connection, holding the session's [`Lease`].
|
||||
struct Leased<T> {
|
||||
inner: T,
|
||||
_lease: Arc<Lease>,
|
||||
}
|
||||
|
||||
impl<T: AsyncRead + Unpin> AsyncRead for Leased<T> {
|
||||
fn poll_read(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>) -> Poll<std::io::Result<()>> {
|
||||
Pin::new(&mut self.inner).poll_read(cx, buf)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: AsyncWrite + Unpin> AsyncWrite for Leased<T> {
|
||||
fn poll_write(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8]) -> Poll<std::io::Result<usize>> {
|
||||
Pin::new(&mut self.inner).poll_write(cx, buf)
|
||||
}
|
||||
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
|
||||
Pin::new(&mut self.inner).poll_flush(cx)
|
||||
}
|
||||
fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
|
||||
Pin::new(&mut self.inner).poll_shutdown(cx)
|
||||
}
|
||||
}
|
||||
|
||||
/// A session's streams. When the server dies the session's connection closes and the session
|
||||
/// ends with the server's last stderr lines, whichever session started it.
|
||||
fn io(stream: UnixStream, stderr: Arc<parking_lot::Mutex<Vec<String>>>, lease: Arc<Lease>) -> AdapterIo {
|
||||
let (r, w) = stream.into_split();
|
||||
AdapterIo {
|
||||
launch_after_configuration: false,
|
||||
reader: Box::new(Leased { inner: r, _lease: lease.clone() }),
|
||||
writer: Box::new(Leased { inner: w, _lease: lease }),
|
||||
// The server is not the session's to stop.
|
||||
child: None,
|
||||
port: None,
|
||||
stderr,
|
||||
program_output: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use tokio::io::AsyncReadExt;
|
||||
|
||||
/// A stand-in for lldb-dap's server mode: it parses `--connection accept:///path`,
|
||||
/// records each start in `starts`, and answers every connection with its pid and the
|
||||
/// `DEVELOPER_DIR` it was started with.
|
||||
fn fake_lldb_dap(dir: &Path) -> Option<PathBuf> {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
std::process::Command::new("python3").arg("-c").arg("").status().ok()?.success().then_some(())?;
|
||||
let path = dir.join("lldb-dap");
|
||||
let log = dir.join("starts");
|
||||
std::fs::write(
|
||||
&path,
|
||||
format!(
|
||||
"#!/usr/bin/env python3\nimport os, socket, sys\n\
|
||||
assert sys.argv[1] == '--connection'\n\
|
||||
open({:?}, 'a').write('start\\n')\n\
|
||||
path = sys.argv[2][len('accept://'):]\n\
|
||||
s = socket.socket(socket.AF_UNIX)\n\
|
||||
s.bind(path); s.listen()\n\
|
||||
while True:\n c, _ = s.accept(); c.sendall(f\"{{os.getpid()}} {{os.environ.get('DEVELOPER_DIR', '')}}\".encode()); c.close()\n",
|
||||
log.to_string_lossy(),
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
Some(path)
|
||||
}
|
||||
|
||||
/// The server's pid and `DEVELOPER_DIR`; the session's connection is closed afterwards.
|
||||
async fn server_of(io: AdapterIo) -> (i32, String) {
|
||||
let mut reader = io.reader;
|
||||
let mut text = String::new();
|
||||
reader.read_to_string(&mut text).await.unwrap();
|
||||
let (pid, dir) = text.split_once(' ').unwrap();
|
||||
(pid.parse().unwrap(), dir.to_owned())
|
||||
}
|
||||
|
||||
fn spec(dir: &Path) -> AdapterSpec {
|
||||
AdapterSpec {
|
||||
adapter: "lldb-dap".into(),
|
||||
command: "lldb-dap".into(),
|
||||
args: Vec::new(),
|
||||
transport: crate::adapter::Transport::Stdio,
|
||||
install_hint: None,
|
||||
cwd: dir.to_path_buf(),
|
||||
env: Vec::new(),
|
||||
server_host: None,
|
||||
connect: None,
|
||||
pinned: None,
|
||||
resolve_lazy_variables: false,
|
||||
shared: true,
|
||||
}
|
||||
}
|
||||
|
||||
fn slot() -> &'static Slot {
|
||||
Box::leak(Box::default())
|
||||
}
|
||||
|
||||
fn starts(dir: &Path) -> usize {
|
||||
std::fs::read_to_string(dir.join("starts")).unwrap_or_default().lines().count()
|
||||
}
|
||||
|
||||
fn alive(pid: i32) -> bool {
|
||||
unsafe { libc::kill(pid, 0) == 0 }
|
||||
}
|
||||
|
||||
async fn until_gone(pid: i32) -> bool {
|
||||
for _ in 0..150 {
|
||||
if !alive(pid) {
|
||||
return true;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(20)).await;
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
const LONG: Duration = Duration::from_secs(600);
|
||||
|
||||
/// Sessions share one server; it outlives them, and goes when its holder does (the IDE quits).
|
||||
#[tokio::test]
|
||||
async fn sessions_share_one_server_that_ends_with_its_holder() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let Some(binary) = fake_lldb_dap(dir.path()) else { return };
|
||||
let slot = slot();
|
||||
let first = connect_to(slot, &spec(dir.path()), &binary, LONG).await.unwrap().unwrap();
|
||||
assert!(first.child.is_none(), "a session must not stop the shared server");
|
||||
let first_stderr = first.stderr.clone();
|
||||
let (pid, _) = server_of(first).await;
|
||||
let second = connect_to(slot, &spec(dir.path()), &binary, LONG).await.unwrap().unwrap();
|
||||
assert!(Arc::ptr_eq(&second.stderr, &first_stderr), "every session sees the server's errors");
|
||||
assert_eq!(server_of(second).await.0, pid, "the second session reuses the server");
|
||||
assert_eq!(starts(dir.path()), 1);
|
||||
|
||||
// Another lldb-dap (the selected Xcode changed) gets its own server; the old one ends.
|
||||
let other_dir = tempfile::tempdir().unwrap();
|
||||
let other = fake_lldb_dap(other_dir.path()).unwrap();
|
||||
let (other_pid, _) =
|
||||
server_of(connect_to(slot, &spec(other_dir.path()), &other, LONG).await.unwrap().unwrap()).await;
|
||||
assert_ne!(other_pid, pid);
|
||||
assert!(until_gone(pid).await, "the replaced server is still running");
|
||||
*slot.lock().await = None;
|
||||
assert!(until_gone(other_pid).await, "the server outlived its holder");
|
||||
}
|
||||
|
||||
/// The server gets the session's environment, and a session with another Xcode
|
||||
/// (`DEVELOPER_DIR`) does not reuse a server started for a different one.
|
||||
#[tokio::test]
|
||||
async fn a_server_is_reused_only_with_the_same_environment() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let Some(binary) = fake_lldb_dap(dir.path()) else { return };
|
||||
let slot = slot();
|
||||
let with = |xcode: &str| AdapterSpec { env: vec![("DEVELOPER_DIR".into(), xcode.into())], ..spec(dir.path()) };
|
||||
let (a, dir_a) = server_of(connect_to(slot, &with("/Xcode-a"), &binary, LONG).await.unwrap().unwrap()).await;
|
||||
assert_eq!(dir_a, "/Xcode-a");
|
||||
let (b, dir_b) = server_of(connect_to(slot, &with("/Xcode-b"), &binary, LONG).await.unwrap().unwrap()).await;
|
||||
assert_eq!(dir_b, "/Xcode-b");
|
||||
assert_ne!(a, b);
|
||||
assert_eq!(server_of(connect_to(slot, &with("/Xcode-b"), &binary, LONG).await.unwrap().unwrap()).await.0, b);
|
||||
*slot.lock().await = None;
|
||||
assert!(until_gone(b).await);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn concurrent_attaches_leave_the_active_server_alone() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let other = tempfile::tempdir().unwrap();
|
||||
let Some(binary) = fake_lldb_dap(dir.path()) else { return };
|
||||
let slot = slot();
|
||||
let first = connect_to(slot, &spec(dir.path()), &binary, LONG).await.unwrap().unwrap();
|
||||
for cwd in [dir.path(), other.path()] {
|
||||
assert!(connect_to(slot, &spec(cwd), &binary, LONG).await.unwrap().is_none());
|
||||
}
|
||||
assert_eq!(starts(dir.path()), 1);
|
||||
let (first_pid, _) = server_of(first).await;
|
||||
assert!(alive(first_pid));
|
||||
|
||||
let replacement = connect_to(slot, &spec(other.path()), &binary, LONG).await.unwrap().unwrap();
|
||||
let (replacement_pid, _) = server_of(replacement).await;
|
||||
assert_ne!(first_pid, replacement_pid, "changing only the working directory replaces an idle server");
|
||||
assert!(until_gone(first_pid).await);
|
||||
*slot.lock().await = None;
|
||||
assert!(until_gone(replacement_pid).await);
|
||||
}
|
||||
|
||||
/// The server ends once no session has been connected for the idle timeout; a connected
|
||||
/// session, or a new one within the timeout, keeps it.
|
||||
#[tokio::test]
|
||||
async fn an_idle_server_ends_and_the_next_session_starts_another() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let Some(binary) = fake_lldb_dap(dir.path()) else { return };
|
||||
let slot = slot();
|
||||
let idle = Duration::from_millis(400);
|
||||
let held = connect_to(slot, &spec(dir.path()), &binary, idle).await.unwrap().unwrap();
|
||||
tokio::time::sleep(idle * 2).await;
|
||||
let (pid, _) = server_of(held).await;
|
||||
assert!(alive(pid), "a connected session keeps the server");
|
||||
|
||||
tokio::time::sleep(idle / 4).await;
|
||||
assert_eq!(server_of(connect_to(slot, &spec(dir.path()), &binary, idle).await.unwrap().unwrap()).await.0, pid);
|
||||
assert_eq!(starts(dir.path()), 1, "a session within the timeout reuses the server");
|
||||
|
||||
assert!(until_gone(pid).await, "the idle server is still running");
|
||||
let (next, _) = server_of(connect_to(slot, &spec(dir.path()), &binary, idle).await.unwrap().unwrap()).await;
|
||||
assert_ne!(next, pid);
|
||||
assert_eq!(starts(dir.path()), 2);
|
||||
*slot.lock().await = None;
|
||||
assert!(until_gone(next).await);
|
||||
}
|
||||
|
||||
/// An lldb-dap without server mode fails at once, so the caller can start it as before.
|
||||
#[tokio::test]
|
||||
async fn an_lldb_dap_without_server_mode_fails_fast() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let binary = dir.path().join("lldb-dap");
|
||||
std::fs::write(&binary, "#!/bin/sh\necho \"unknown option $1\" >&2\nexit 1\n").unwrap();
|
||||
std::fs::set_permissions(&binary, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
let started = std::time::Instant::now();
|
||||
let e = connect_to(slot(), &spec(dir.path()), &binary, LONG).await.err().unwrap();
|
||||
assert!(started.elapsed() < Duration::from_secs(5), "{:?}", started.elapsed());
|
||||
assert!(e.message.contains("exited before accepting connections"), "{}", e.message);
|
||||
}
|
||||
}
|
||||
@@ -4044,6 +4044,52 @@ async fn stop_ends_a_native_program_a_run_started_for_the_debugger() {
|
||||
assert_eq!(h.request("disconnect")["arguments"]["terminateDebuggee"], false);
|
||||
}
|
||||
|
||||
/// Xcode Debug's attach goes to the shared lldb-dap server, which keeps the system libraries
|
||||
/// parsed by earlier sessions (#6665 E7); other sessions start their own adapter.
|
||||
#[tokio::test]
|
||||
async fn only_an_lldb_dap_attach_to_a_run_shares_the_server() {
|
||||
struct CaptureLauncher {
|
||||
inner: FakeLauncher,
|
||||
shared: Arc<parking_lot::Mutex<Vec<bool>>>,
|
||||
}
|
||||
impl AdapterLauncher for CaptureLauncher {
|
||||
fn launch(&self, spec: AdapterSpec, reuse: Option<u16>) -> LaunchFuture {
|
||||
self.shared.lock().push(spec.shared);
|
||||
self.inner.launch(spec, reuse)
|
||||
}
|
||||
}
|
||||
let shared: Arc<parking_lot::Mutex<Vec<bool>>> = Arc::default();
|
||||
let launcher = CaptureLauncher {
|
||||
inner: FakeLauncher { log: Arc::default(), script: Script::default() },
|
||||
shared: shared.clone(),
|
||||
};
|
||||
let manager = DebugManager::with_launcher(Arc::new(LanguageRegistry::from_configs(Vec::new())), Arc::new(launcher));
|
||||
let session = |adapter: &str, request: &str, linked: bool, xcode: bool| LaunchConfig {
|
||||
adapter: adapter.into(),
|
||||
request: request.into(),
|
||||
extra_json: Some(
|
||||
if linked {
|
||||
json!({ RUN_LINK: 7, XCODE_ATTACH: xcode, "pid": 4242 })
|
||||
} else {
|
||||
json!({ XCODE_ATTACH: xcode, "pid": 4242 })
|
||||
}
|
||||
.to_string(),
|
||||
),
|
||||
..config()
|
||||
};
|
||||
for launch in [
|
||||
session("lldb-dap", "attach", true, true),
|
||||
session("lldb-dap", "attach", true, false),
|
||||
session("lldb-dap", "attach", false, true),
|
||||
session("lldb-dap", "launch", true, true),
|
||||
session("debugpy", "attach", true, true),
|
||||
] {
|
||||
let (owner, _) = recording_owner("main");
|
||||
manager.start(launch, owner).await.unwrap();
|
||||
}
|
||||
assert_eq!(*shared.lock(), [true, false, false, false, false]);
|
||||
}
|
||||
|
||||
/// LLDB leaves a breakpoint it can't bind unverified without a reason: say what may be wrong
|
||||
/// (#6665 E1b: Xcode's debug info had `/tmp/…` for a project under `/private/tmp`).
|
||||
#[tokio::test]
|
||||
|
||||
@@ -157,6 +157,15 @@ pub struct TableInfo {
|
||||
pub comment: Option<String>,
|
||||
}
|
||||
|
||||
/// Non-secret identity of an already-connected data source target.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ConnectedSourceInfo {
|
||||
pub source_id: String,
|
||||
pub name: String,
|
||||
pub driver: DbDriver,
|
||||
pub database: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[serde(rename = "DbColumnInfo")]
|
||||
@@ -1299,15 +1308,49 @@ impl DbManager {
|
||||
}
|
||||
}
|
||||
|
||||
/// Lists non-secret metadata for every currently connected source target on this project/window.
|
||||
/// Never allocates a pool, connects a source, or reads credentials.
|
||||
pub fn connected_sources(&self) -> Vec<ConnectedSourceInfo> {
|
||||
let connected = self.connected();
|
||||
if connected.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
let sources: std::collections::HashMap<String, DataSource> =
|
||||
self.sources().unwrap_or_default().into_iter().map(|s| (s.id.clone(), s)).collect();
|
||||
let mut out: Vec<ConnectedSourceInfo> = connected
|
||||
.into_iter()
|
||||
.filter_map(|source_id| {
|
||||
let (base_id, db_suffix) = split_target(&source_id);
|
||||
let source = sources.get(base_id)?.resolved().ok()?;
|
||||
let database =
|
||||
db_suffix.map(str::to_owned).or_else(|| (!source.database.is_empty()).then_some(source.database));
|
||||
Some(ConnectedSourceInfo { source_id, name: source.name, driver: source.driver, database })
|
||||
})
|
||||
.collect();
|
||||
out.sort_by(|a, b| a.source_id.cmp(&b.source_id));
|
||||
out
|
||||
}
|
||||
|
||||
/// Every schema (the Schemas tab picks the ones the tree shows); system schemas
|
||||
/// only with [`DbIntrospection::show_system`].
|
||||
pub async fn schemas(&self, id: &str) -> IdeResult<Vec<String>> {
|
||||
let system = self.source(id)?.introspection.show_system;
|
||||
let pool = self.pool(id).await?;
|
||||
if let Pool::Snowflake(p) = &*pool {
|
||||
Self::schemas_on(&pool, system).await
|
||||
}
|
||||
|
||||
/// Read schemas using an existing connection only. Never opens a connection or prompts for credentials.
|
||||
pub async fn connected_schemas(&self, id: &str) -> IdeResult<Vec<String>> {
|
||||
let system = self.source(id)?.introspection.show_system;
|
||||
let pool = self.connected_pool(id)?;
|
||||
Self::schemas_on(&pool, system).await
|
||||
}
|
||||
|
||||
async fn schemas_on(pool: &Pool, system: bool) -> IdeResult<Vec<String>> {
|
||||
if let Pool::Snowflake(p) = pool {
|
||||
return snowflake::meta::schemas(p, system).await;
|
||||
}
|
||||
let rows = match &*pool {
|
||||
let rows = match pool {
|
||||
Pool::Jdbc(p) => p.metadata(&["schemas"]).await?,
|
||||
_ => pool.rows(sql::schemas(pool.driver(), system), MAX_META_ROWS).await?,
|
||||
};
|
||||
@@ -1316,10 +1359,20 @@ impl DbManager {
|
||||
|
||||
pub async fn tables(&self, id: &str, schema: &str) -> IdeResult<Vec<TableInfo>> {
|
||||
let pool = self.pool(id).await?;
|
||||
if let Pool::Snowflake(p) = &*pool {
|
||||
Self::tables_on(&pool, schema).await
|
||||
}
|
||||
|
||||
/// Read tables using an existing connection only. Never opens a connection or prompts for credentials.
|
||||
pub async fn connected_tables(&self, id: &str, schema: &str) -> IdeResult<Vec<TableInfo>> {
|
||||
let pool = self.connected_pool(id)?;
|
||||
Self::tables_on(&pool, schema).await
|
||||
}
|
||||
|
||||
async fn tables_on(pool: &Pool, schema: &str) -> IdeResult<Vec<TableInfo>> {
|
||||
if let Pool::Snowflake(p) = pool {
|
||||
return snowflake::meta::tables(p, schema).await;
|
||||
}
|
||||
let rows = match &*pool {
|
||||
let rows = match pool {
|
||||
Pool::Jdbc(p) => p.metadata(&["tables", schema]).await?,
|
||||
_ => pool.rows(&sql::tables(pool.driver(), schema), MAX_META_ROWS).await?,
|
||||
};
|
||||
@@ -1337,6 +1390,25 @@ impl DbManager {
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// Executes a SQL statement using an existing connection only (used by extension hosts).
|
||||
/// Respects read-only connections and never opens a disconnected source or prompts for credentials.
|
||||
pub async fn connected_execute(
|
||||
&self,
|
||||
id: &str,
|
||||
statement: &str,
|
||||
max_rows: usize,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<QueryResult> {
|
||||
let pool = self.connected_pool(id)?;
|
||||
if pool.transaction_read_only() {
|
||||
conn::validate_pg_read_only(statement).map_err(IdeError::invalid)?;
|
||||
}
|
||||
if !conn::cursor_statement(statement) {
|
||||
self.cursors.release_target(id);
|
||||
}
|
||||
pool.execute_from(statement, 0, max_rows, cancel).await
|
||||
}
|
||||
|
||||
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" {
|
||||
|
||||
@@ -26,6 +26,8 @@ pub enum Capability {
|
||||
DatabaseSources,
|
||||
/// Read table metadata of connected project sources; never rows or credentials.
|
||||
DatabaseSchema,
|
||||
/// Execute SQL statements against connected project database sources.
|
||||
DatabaseQuery,
|
||||
VcsRead,
|
||||
VcsWrite,
|
||||
/// The Maven / Gradle dependency graph the IDE resolved.
|
||||
@@ -109,6 +111,7 @@ impl Capability {
|
||||
// A trusted project's own files name the programs the IDE starts (its settings, its
|
||||
// build scripts), so writing them is running code.
|
||||
Self::ProjectWrite
|
||||
| Self::DatabaseQuery
|
||||
| Self::IdeCommands
|
||||
| Self::Ipc(_)
|
||||
| Self::Process(_)
|
||||
@@ -134,6 +137,7 @@ impl Capability {
|
||||
Self::ProjectWrite => "Create and change files in the open project".into(),
|
||||
Self::DatabaseSources => "Manage its own database sources and store their passwords in trusted projects".into(),
|
||||
Self::DatabaseSchema => "Read table structures of connected database sources in trusted projects, without rows or passwords".into(),
|
||||
Self::DatabaseQuery => "Execute SQL queries and statements on connected database sources in trusted projects".into(),
|
||||
Self::IdeCommands => "Run any IDE action or other plugins' commands as if you chose them, including running programs, committing and pushing".into(),
|
||||
Self::VcsRead => "Read version control state".into(),
|
||||
Self::VcsWrite => "Change version control state (commit, fetch, checkout)".into(),
|
||||
@@ -294,6 +298,7 @@ impl fmt::Display for Capability {
|
||||
Self::IdeCommands => f.write_str("ide.commands"),
|
||||
Self::DatabaseSources => f.write_str("database.sources"),
|
||||
Self::DatabaseSchema => f.write_str("database.schema"),
|
||||
Self::DatabaseQuery => f.write_str("database.query"),
|
||||
Self::VcsRead => f.write_str("vcs.read"),
|
||||
Self::VcsWrite => f.write_str("vcs.write"),
|
||||
Self::BuildRead => f.write_str("build.read"),
|
||||
@@ -389,6 +394,7 @@ impl FromStr for Capability {
|
||||
"ide.commands" => Self::IdeCommands,
|
||||
"database.sources" => Self::DatabaseSources,
|
||||
"database.schema" => Self::DatabaseSchema,
|
||||
"database.query" => Self::DatabaseQuery,
|
||||
"vcs.read" => Self::VcsRead,
|
||||
"vcs.write" => Self::VcsWrite,
|
||||
"build.read" => Self::BuildRead,
|
||||
@@ -700,6 +706,23 @@ mod database_tests {
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn database_query_is_a_separate_high_risk_grant_requiring_api21() {
|
||||
let cap: Capability = "database.query".parse().unwrap();
|
||||
assert_eq!(cap, Capability::DatabaseQuery);
|
||||
assert_eq!(cap.to_string(), "database.query");
|
||||
assert_eq!(cap.risk(), Risk::High);
|
||||
assert!(!cap.auto_migrates());
|
||||
for other in [Capability::ProjectRead, Capability::DatabaseSources, Capability::DatabaseSchema] {
|
||||
assert!(!other.covers(&cap));
|
||||
}
|
||||
for (api, valid) in [("^1.20", false), ("^1.21", true)] {
|
||||
let text = format!(
|
||||
"id='query'\nname='Query'\nversion='1.0.0'\nengines.openidea='{api}'\n[capabilities]\nrequired=['database.query']"
|
||||
);
|
||||
assert_eq!(crate::Manifest::parse(&text).is_ok(), valid);
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn database_sources_is_a_medium_risk_exact_grant_requiring_api4() {
|
||||
let cap: Capability = "database.sources".parse().unwrap();
|
||||
assert_eq!(cap, Capability::DatabaseSources);
|
||||
|
||||
@@ -430,6 +430,9 @@ impl Manifest {
|
||||
if matches!(cap, Capability::DatabaseSchema) {
|
||||
self.needs_api(&format!("capability `{cap}`"), 20)?;
|
||||
}
|
||||
if matches!(cap, Capability::DatabaseQuery) {
|
||||
self.needs_api(&format!("capability `{cap}`"), 21)?;
|
||||
}
|
||||
if matches!(cap, Capability::Agents) {
|
||||
self.needs_api(&format!("capability `{cap}`"), 18)?;
|
||||
}
|
||||
|
||||
@@ -1756,6 +1756,32 @@ impl PluginApi {
|
||||
}
|
||||
}
|
||||
|
||||
impl PluginApi {
|
||||
fn database_for_client(
|
||||
&self,
|
||||
root: &Path,
|
||||
client: Option<&str>,
|
||||
source_id: Option<&str>,
|
||||
) -> Result<(Arc<crate::Host>, Arc<ide_db::DbManager>), HostError> {
|
||||
let (host, fallback) = self.database_host(root)?;
|
||||
// Connections belong to windows, even when several windows open the same root.
|
||||
// Prefer the invoking window; background calls may use any matching connected instance.
|
||||
let db = client
|
||||
.and_then(|client| host.project(client).ok())
|
||||
.filter(|project| project.root == root)
|
||||
.map(|project| project.db.clone())
|
||||
.or_else(|| {
|
||||
let target = source_id?;
|
||||
host.projects()
|
||||
.into_iter()
|
||||
.find(|project| project.root == root && project.db.is_connected(target))
|
||||
.map(|project| project.db.clone())
|
||||
})
|
||||
.unwrap_or(fallback);
|
||||
Ok((host, db))
|
||||
}
|
||||
}
|
||||
|
||||
impl HostApi for PluginApi {
|
||||
fn database_table_schema(
|
||||
&self,
|
||||
@@ -1766,21 +1792,69 @@ impl HostApi for PluginApi {
|
||||
timeout: Duration,
|
||||
) -> Result<ide_plugin::PluginDatabaseTableSchema, HostError> {
|
||||
self.require_api("database table schema", 20)?;
|
||||
let (host, fallback) = self.database_host(root)?;
|
||||
// Connections belong to windows, even when several windows open the same root.
|
||||
// Prefer the invoking window; background calls may use any connected instance.
|
||||
let db = client
|
||||
let (host, db) = self.database_for_client(root, client, Some(&table.source_id))?;
|
||||
host.runtime.block_on(super::database::table_schema(&db, table, cancel, timeout))
|
||||
}
|
||||
fn database_connected_sources(
|
||||
&self,
|
||||
root: &Path,
|
||||
client: Option<&str>,
|
||||
) -> Result<Vec<ide_plugin::PluginConnectedDataSource>, HostError> {
|
||||
self.require_api("database connected sources", 21)?;
|
||||
let (host, _) = self.database_host(root)?;
|
||||
if let Some(db) = client
|
||||
.and_then(|client| host.project(client).ok())
|
||||
.filter(|project| project.root == root)
|
||||
.map(|project| project.db.clone())
|
||||
.or_else(|| {
|
||||
host.projects()
|
||||
.into_iter()
|
||||
.find(|project| project.root == root && project.db.is_connected(&table.source_id))
|
||||
.map(|project| project.db.clone())
|
||||
})
|
||||
.unwrap_or(fallback);
|
||||
host.runtime.block_on(super::database::table_schema(&db, table, cancel, timeout))
|
||||
{
|
||||
return super::database::connected_sources(&db);
|
||||
}
|
||||
let dbs: Vec<_> = host
|
||||
.projects()
|
||||
.into_iter()
|
||||
.filter(|project| project.root == root)
|
||||
.map(|project| project.db.clone())
|
||||
.collect();
|
||||
super::database::connected_sources_across(&dbs)
|
||||
}
|
||||
fn database_list_schemas(
|
||||
&self,
|
||||
root: &Path,
|
||||
client: Option<&str>,
|
||||
source_id: &str,
|
||||
cancel: &CancellationToken,
|
||||
timeout: Duration,
|
||||
) -> Result<Vec<String>, HostError> {
|
||||
self.require_api("database schema listing", 21)?;
|
||||
let (host, db) = self.database_for_client(root, client, Some(source_id))?;
|
||||
host.runtime.block_on(super::database::list_schemas(&db, source_id, cancel, timeout))
|
||||
}
|
||||
fn database_list_tables(
|
||||
&self,
|
||||
root: &Path,
|
||||
client: Option<&str>,
|
||||
source_id: &str,
|
||||
schema: &str,
|
||||
cancel: &CancellationToken,
|
||||
timeout: Duration,
|
||||
) -> Result<Vec<ide_plugin::PluginDatabaseTableSummary>, HostError> {
|
||||
self.require_api("database table listing", 21)?;
|
||||
let (host, db) = self.database_for_client(root, client, Some(source_id))?;
|
||||
host.runtime.block_on(super::database::list_tables(&db, source_id, schema, cancel, timeout))
|
||||
}
|
||||
fn database_execute_query(
|
||||
&self,
|
||||
root: &Path,
|
||||
client: Option<&str>,
|
||||
source_id: &str,
|
||||
sql: &str,
|
||||
max_rows: Option<u32>,
|
||||
cancel: &CancellationToken,
|
||||
timeout: Duration,
|
||||
) -> Result<ide_plugin::PluginDatabaseQueryResult, HostError> {
|
||||
self.require_api("database query execution", 21)?;
|
||||
let (host, db) = self.database_for_client(root, client, Some(source_id))?;
|
||||
host.runtime.block_on(super::database::execute_query(&db, source_id, sql, max_rows, cancel, timeout))
|
||||
}
|
||||
fn database_upsert(&self, root: &Path, source: ide_plugin::PluginDataSource) -> Result<(), HostError> {
|
||||
let (host, db) = self.database_host(root)?;
|
||||
|
||||
@@ -2,8 +2,11 @@
|
||||
use super::api::PluginApi;
|
||||
use super::{PluginHost, WindowRequest};
|
||||
use ide_core::{CancellationToken, IdeError, IdeEvent, IdeResult};
|
||||
use ide_db::{DataSource, DbDriver, DbProperty};
|
||||
use ide_plugin::{HostError, PluginDataSource};
|
||||
use ide_db::{DataSource, DbDriver, DbProperty, DbTableKind};
|
||||
use ide_plugin::{
|
||||
HostError, PluginConnectedDataSource, PluginDataSource, PluginDatabaseQueryColumn, PluginDatabaseQueryResult,
|
||||
PluginDatabaseTableSummary,
|
||||
};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
@@ -253,6 +256,199 @@ pub(super) async fn table_schema(
|
||||
})
|
||||
}
|
||||
|
||||
fn driver_name(driver: DbDriver) -> &'static str {
|
||||
match driver {
|
||||
DbDriver::Sqlite => "sqlite",
|
||||
DbDriver::Postgres => "postgres",
|
||||
DbDriver::Mysql => "mysql",
|
||||
DbDriver::SqlServer => "sqlServer",
|
||||
DbDriver::Clickhouse => "clickhouse",
|
||||
DbDriver::Oracle => "oracle",
|
||||
DbDriver::Snowflake => "snowflake",
|
||||
DbDriver::Jdbc => "jdbc",
|
||||
}
|
||||
}
|
||||
|
||||
fn table_kind_name(kind: DbTableKind) -> &'static str {
|
||||
match kind {
|
||||
DbTableKind::Table => "table",
|
||||
DbTableKind::View => "view",
|
||||
DbTableKind::MaterializedView => "materializedView",
|
||||
}
|
||||
}
|
||||
|
||||
fn valid_db_ident(value: &str, non_empty: bool) -> bool {
|
||||
(!non_empty || !value.is_empty()) && value.len() <= 4096 && !value.contains('\0')
|
||||
}
|
||||
|
||||
pub(super) fn connected_sources(db: &ide_db::DbManager) -> Result<Vec<PluginConnectedDataSource>, HostError> {
|
||||
Ok(db
|
||||
.connected_sources()
|
||||
.into_iter()
|
||||
.take(4096)
|
||||
.map(|s| PluginConnectedDataSource {
|
||||
source_id: s.source_id,
|
||||
name: s.name,
|
||||
driver: driver_name(s.driver).to_owned(),
|
||||
database: s.database,
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
pub(super) fn connected_sources_across(
|
||||
dbs: &[Arc<ide_db::DbManager>],
|
||||
) -> Result<Vec<PluginConnectedDataSource>, HostError> {
|
||||
let mut by_id = std::collections::BTreeMap::new();
|
||||
for db in dbs {
|
||||
for s in db.connected_sources() {
|
||||
by_id.entry(s.source_id.clone()).or_insert_with(|| PluginConnectedDataSource {
|
||||
source_id: s.source_id,
|
||||
name: s.name,
|
||||
driver: driver_name(s.driver).to_owned(),
|
||||
database: s.database,
|
||||
});
|
||||
if by_id.len() >= 4096 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if by_id.len() >= 4096 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Ok(by_id.into_values().collect())
|
||||
}
|
||||
|
||||
pub(super) async fn list_schemas(
|
||||
db: &ide_db::DbManager,
|
||||
source_id: &str,
|
||||
cancel: &CancellationToken,
|
||||
timeout: Duration,
|
||||
) -> Result<Vec<String>, HostError> {
|
||||
if !valid_db_ident(source_id, true) {
|
||||
return Err(HostError::Invalid("invalid database source id".into()));
|
||||
}
|
||||
if cancel.is_cancelled() {
|
||||
return Err(HostError::Cancelled);
|
||||
}
|
||||
let read = db.connected_schemas(source_id);
|
||||
let mut schemas = tokio::select! {
|
||||
biased;
|
||||
_ = cancel.cancelled() => return Err(HostError::Cancelled),
|
||||
result = tokio::time::timeout(timeout, read) => result
|
||||
.map_err(|_| HostError::Failed("Database schemas request timed out".into()))?.map_err(error)?,
|
||||
};
|
||||
schemas.truncate(4096);
|
||||
Ok(schemas)
|
||||
}
|
||||
|
||||
pub(super) async fn list_tables(
|
||||
db: &ide_db::DbManager,
|
||||
source_id: &str,
|
||||
schema: &str,
|
||||
cancel: &CancellationToken,
|
||||
timeout: Duration,
|
||||
) -> Result<Vec<PluginDatabaseTableSummary>, HostError> {
|
||||
if !valid_db_ident(source_id, true) || !valid_db_ident(schema, false) {
|
||||
return Err(HostError::Invalid("invalid database schema reference".into()));
|
||||
}
|
||||
if cancel.is_cancelled() {
|
||||
return Err(HostError::Cancelled);
|
||||
}
|
||||
let read = db.connected_tables(source_id, schema);
|
||||
let tables = tokio::select! {
|
||||
biased;
|
||||
_ = cancel.cancelled() => return Err(HostError::Cancelled),
|
||||
result = tokio::time::timeout(timeout, read) => result
|
||||
.map_err(|_| HostError::Failed("Database tables request timed out".into()))?.map_err(error)?,
|
||||
};
|
||||
Ok(tables
|
||||
.into_iter()
|
||||
.take(4096)
|
||||
.map(|t| PluginDatabaseTableSummary {
|
||||
name: t.name,
|
||||
kind: table_kind_name(t.kind).to_owned(),
|
||||
comment: t.comment,
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
pub(super) async fn execute_query(
|
||||
db: &ide_db::DbManager,
|
||||
source_id: &str,
|
||||
sql: &str,
|
||||
max_rows: Option<u32>,
|
||||
cancel: &CancellationToken,
|
||||
timeout: Duration,
|
||||
) -> Result<PluginDatabaseQueryResult, HostError> {
|
||||
if !valid_db_ident(source_id, true) {
|
||||
return Err(HostError::Invalid("invalid database source id".into()));
|
||||
}
|
||||
if sql.trim().is_empty() || sql.len() > 262_144 || sql.contains('\0') {
|
||||
return Err(HostError::Invalid("invalid SQL statement".into()));
|
||||
}
|
||||
if cancel.is_cancelled() {
|
||||
return Err(HostError::Cancelled);
|
||||
}
|
||||
let limit = max_rows.unwrap_or(100).clamp(1, 1000) as usize;
|
||||
let query_cancel = cancel.child_token();
|
||||
let timer_cancel = query_cancel.clone();
|
||||
let timed_out = Arc::new(std::sync::atomic::AtomicBool::new(false));
|
||||
let timed_out_flag = timed_out.clone();
|
||||
let timer = tokio::spawn(async move {
|
||||
tokio::time::sleep(timeout).await;
|
||||
timed_out_flag.store(true, std::sync::atomic::Ordering::Release);
|
||||
timer_cancel.cancel();
|
||||
});
|
||||
// Allow a brief grace window after cancelling `query_cancel` so drivers can send server-side
|
||||
// cancel (`pg_cancel_backend` / `KILL QUERY`) and discard the interrupted connection cleanly.
|
||||
let grace = timeout.saturating_add(Duration::from_secs(2));
|
||||
let run = db.connected_execute(source_id, sql, limit, &query_cancel);
|
||||
let outcome = tokio::select! {
|
||||
biased;
|
||||
result = tokio::time::timeout(grace, run) => result,
|
||||
_ = async {
|
||||
cancel.cancelled().await;
|
||||
tokio::time::sleep(Duration::from_secs(2)).await;
|
||||
} => {
|
||||
timer.abort();
|
||||
return Err(HostError::Cancelled);
|
||||
}
|
||||
};
|
||||
timer.abort();
|
||||
let mut result = match outcome {
|
||||
Err(_) => {
|
||||
return Err(if cancel.is_cancelled() {
|
||||
HostError::Cancelled
|
||||
} else {
|
||||
HostError::Failed("Database query execution timed out".into())
|
||||
});
|
||||
}
|
||||
Ok(Ok(result)) => result,
|
||||
Ok(Err(err)) => {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(HostError::Cancelled);
|
||||
}
|
||||
if timed_out.load(std::sync::atomic::Ordering::Acquire) && err.kind == ide_core::error::ErrorKind::Cancelled
|
||||
{
|
||||
return Err(HostError::Failed("Database query execution timed out".into()));
|
||||
}
|
||||
return Err(error(err));
|
||||
}
|
||||
};
|
||||
result.cap_cells(8192);
|
||||
Ok(PluginDatabaseQueryResult {
|
||||
columns: result
|
||||
.columns
|
||||
.into_iter()
|
||||
.map(|c| PluginDatabaseQueryColumn { name: c.name, type_name: c.type_name })
|
||||
.collect(),
|
||||
rows: result.rows,
|
||||
affected: result.affected.and_then(|v| (v.is_finite() && v >= 0.0).then_some(v as u64)),
|
||||
has_more: result.has_more,
|
||||
elapsed_ms: if result.elapsed_ms.is_finite() { result.elapsed_ms.max(0.0) as u64 } else { 0 },
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
@@ -16,8 +16,10 @@ pub struct NavigationFiles {
|
||||
}
|
||||
|
||||
/// Discovery offers at most this many files; larger projects get navigation
|
||||
/// on the first ones instead of none.
|
||||
const MAX_NAVIGATION_FILES: usize = 20_000;
|
||||
/// on the first ones instead of none. As many as one graph covers, so the
|
||||
/// "covers N of M files" notice stays true.
|
||||
const MAX_NAVIGATION_FILES: usize = super::navigation::MAX_FILES;
|
||||
const MAX_INDEX_BATCH: usize = 128;
|
||||
|
||||
/// The first `limit` files by path that `in_scope` accepts, and how many it accepts in all.
|
||||
/// Sorting keeps the covered files the same across index rebuilds.
|
||||
@@ -80,6 +82,15 @@ pub fn plugin_navigation_invalidate(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
struct LoadedNavigationDoc {
|
||||
path: PathBuf,
|
||||
document: Option<ide_core::DocId>,
|
||||
version: Option<u32>,
|
||||
text: String,
|
||||
symbols: Vec<ide_language::SymbolTag>,
|
||||
scope: String,
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub async fn plugin_navigation_index(
|
||||
host: &crate::Host,
|
||||
@@ -88,8 +99,8 @@ pub async fn plugin_navigation_index(
|
||||
paths: Vec<PathBuf>,
|
||||
request: ide_core::RequestId,
|
||||
) -> IdeResult<()> {
|
||||
if paths.len() > 16 {
|
||||
return Err(IdeError::invalid("navigation batches are limited to 16 files"));
|
||||
if paths.len() > MAX_INDEX_BATCH {
|
||||
return Err(IdeError::invalid("navigation batches are limited to 128 files"));
|
||||
}
|
||||
let plugins = plugins.clone();
|
||||
let project = host.project(window)?;
|
||||
@@ -99,33 +110,45 @@ pub async fn plugin_navigation_index(
|
||||
if !project.is_trusted() {
|
||||
return Err(IdeError::unavailable("project is not trusted"));
|
||||
}
|
||||
let extensions = plugins.navigation_extensions(&project.root);
|
||||
let project_roots = project.roots();
|
||||
// A project window group's members are project scope.
|
||||
let mut roots = vec![project.root.clone()];
|
||||
roots.extend(crate::project::workspace_member_roots(&project.root));
|
||||
for path in paths {
|
||||
|
||||
let mut loaded_docs = Vec::with_capacity(paths.len());
|
||||
let mut evict_paths = Vec::new();
|
||||
for raw_path in paths {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
let Ok(path) = ide_plugin::resolve_in_roots(&roots, &path.to_string_lossy()) else {
|
||||
let Ok(path) = ide_plugin::resolve_in_roots(&roots, &raw_path.to_string_lossy()) else {
|
||||
evict_paths.push(raw_path);
|
||||
continue;
|
||||
};
|
||||
let extensions = plugins.navigation_extensions(&project.root);
|
||||
if !path.extension().and_then(|e| e.to_str()).is_some_and(|e| extensions.iter().any(|x| x == e)) {
|
||||
evict_paths.push(path);
|
||||
continue;
|
||||
}
|
||||
let document = project.documents.by_path(&path);
|
||||
let (text, version, language) = if let Some(id) = document {
|
||||
let snapshot = project.documents.text_snapshot(id)?;
|
||||
let Ok(snapshot) = project.documents.text_snapshot(id) else {
|
||||
evict_paths.push(path);
|
||||
continue;
|
||||
};
|
||||
if snapshot.large {
|
||||
evict_paths.push(path);
|
||||
continue;
|
||||
}
|
||||
(snapshot.text, Some(snapshot.version), snapshot.language)
|
||||
} else {
|
||||
let Ok(loaded) = project.documents.load_file_bounded(&path, super::navigation::MAX_DOCUMENT_BYTES)
|
||||
else {
|
||||
evict_paths.push(path);
|
||||
continue;
|
||||
};
|
||||
if loaded.binary || loaded.large {
|
||||
evict_paths.push(path);
|
||||
continue;
|
||||
}
|
||||
let text = loaded.text;
|
||||
@@ -133,23 +156,42 @@ pub async fn plugin_navigation_index(
|
||||
(text, None, language)
|
||||
};
|
||||
if text.len() > crate::plugins::navigation::MAX_DOCUMENT_BYTES {
|
||||
evict_paths.push(path);
|
||||
continue;
|
||||
}
|
||||
let symbols = project
|
||||
.index
|
||||
.symbols_for_text(&path, &text)
|
||||
.unwrap_or_else(|| project.syntax.syntax().tags(&language, &text));
|
||||
let roots = project.roots();
|
||||
let scope = roots
|
||||
let scope = project_roots
|
||||
.roots
|
||||
.iter()
|
||||
.filter(|r| path.starts_with(project.root.join(&r.path)))
|
||||
.max_by_key(|r| r.path.len())
|
||||
.and_then(|r| r.detected_from.as_deref())
|
||||
.unwrap_or("");
|
||||
plugins.index_navigation(
|
||||
.unwrap_or("")
|
||||
.to_owned();
|
||||
loaded_docs.push(LoadedNavigationDoc { path, document, version, text, symbols, scope });
|
||||
}
|
||||
|
||||
if !evict_paths.is_empty() {
|
||||
plugins.invalidate_client_navigation(&project.root, Some(&client), Some(&evict_paths));
|
||||
}
|
||||
|
||||
if !loaded_docs.is_empty() {
|
||||
let snapshots: Vec<_> = loaded_docs
|
||||
.iter()
|
||||
.map(|doc| crate::plugins::navigation::Snapshot {
|
||||
path: &doc.path,
|
||||
version: doc.version,
|
||||
text: &doc.text,
|
||||
symbols: &doc.symbols,
|
||||
scope: &doc.scope,
|
||||
})
|
||||
.collect();
|
||||
if let Err(err) = plugins.index_navigation_batch(
|
||||
&project.root,
|
||||
crate::plugins::navigation::Snapshot { path: &path, version, text: &text, symbols: &symbols, scope },
|
||||
&snapshots,
|
||||
Invocation {
|
||||
command_chain: Vec::new(),
|
||||
client: Some(client.clone()),
|
||||
@@ -158,10 +200,33 @@ pub async fn plugin_navigation_index(
|
||||
selected_paths: Vec::new(),
|
||||
global_settings: false,
|
||||
},
|
||||
)?;
|
||||
Some(&cancel),
|
||||
) {
|
||||
let remaining_paths: Vec<PathBuf> = loaded_docs
|
||||
.into_iter()
|
||||
.filter(|doc| {
|
||||
cancel.is_cancelled()
|
||||
|| doc.document.is_some_and(|id| project.documents.version(id).ok() != doc.version)
|
||||
})
|
||||
.map(|doc| doc.path)
|
||||
.collect();
|
||||
if !remaining_paths.is_empty() {
|
||||
plugins.invalidate_client_navigation(&project.root, Some(&client), Some(&remaining_paths));
|
||||
}
|
||||
return Err(err);
|
||||
}
|
||||
|
||||
// A document edit while WASM was executing must not publish stale ranges.
|
||||
if cancel.is_cancelled() || document.is_some_and(|id| project.documents.version(id).ok() != version) {
|
||||
plugins.invalidate_client_navigation(&project.root, Some(&client), Some(&[path]));
|
||||
let stale_paths: Vec<PathBuf> = loaded_docs
|
||||
.into_iter()
|
||||
.filter(|doc| {
|
||||
cancel.is_cancelled()
|
||||
|| doc.document.is_some_and(|id| project.documents.version(id).ok() != doc.version)
|
||||
})
|
||||
.map(|doc| doc.path)
|
||||
.collect();
|
||||
if !stale_paths.is_empty() {
|
||||
plugins.invalidate_client_navigation(&project.root, Some(&client), Some(&stale_paths));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
|
||||
@@ -15,6 +15,66 @@ pub const MAX_DOCUMENT_BYTES: usize = ide_lsp::MAX_INJECTED_DOCUMENT_BYTES;
|
||||
/// Files one plugin's graph covers per project and window.
|
||||
pub const MAX_FILES: usize = 20_000;
|
||||
const MAX_EDGES: usize = 4096;
|
||||
const MAX_GRAPH_EDGES: usize = 200_000;
|
||||
const MAX_ACTOR_CHUNK: usize = 16;
|
||||
|
||||
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct BatchIndexSummary {
|
||||
pub skipped_invalid: usize,
|
||||
}
|
||||
|
||||
fn edges_are_empty(edges: &Edges) -> bool {
|
||||
edges.definitions.is_empty() && edges.references.is_empty() && edges.aliases.is_empty() && edges.markers.is_empty()
|
||||
}
|
||||
|
||||
fn validate_edges(plugin_id: &str, path: &Path, text: &str, edges: &Edges) -> IdeResult<()> {
|
||||
if edges_are_empty(edges) {
|
||||
return Ok(());
|
||||
}
|
||||
let lines: Vec<_> = text.split('\n').map(|l| l.encode_utf16().count()).collect();
|
||||
let output_bytes = edges
|
||||
.definitions
|
||||
.iter()
|
||||
.chain(&edges.references)
|
||||
.chain(&edges.markers)
|
||||
.map(|a| a.key.len().saturating_add(32))
|
||||
.sum::<usize>()
|
||||
.saturating_add(edges.aliases.iter().map(|a| a.prefix.len() + a.target.len()).sum::<usize>());
|
||||
if output_bytes > MAX_DOCUMENT_BYTES {
|
||||
return Err(IdeError::invalid("document index output is too large"));
|
||||
}
|
||||
if edges.aliases.len() > 256
|
||||
|| edges.aliases.iter().any(|a| {
|
||||
!a.prefix.ends_with('#') || !a.target.ends_with('#') || a.prefix.len() > 1024 || a.target.len() > 1024
|
||||
})
|
||||
|| edges.definitions.len() + edges.references.len() > MAX_EDGES
|
||||
|| edges
|
||||
.definitions
|
||||
.iter()
|
||||
.chain(&edges.references)
|
||||
.any(|a| a.key.is_empty() || a.key.len() > 1024 || !valid_range(&lines, a.range))
|
||||
{
|
||||
return Err(IdeError::invalid(format!("{plugin_id}: invalid navigation anchors in {}", path.display())));
|
||||
}
|
||||
if edges.markers.len() > MAX_EDGES
|
||||
|| edges.markers.iter().any(|a| a.key.is_empty() || a.key.len() > 1024 || !valid_range(&lines, a.range))
|
||||
{
|
||||
return Err(IdeError::invalid(format!("{plugin_id}: invalid navigation markers in {}", path.display())));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn to_index_symbols(symbols: &[SymbolTag]) -> Vec<ide_plugin::indexing::IndexSymbol> {
|
||||
symbols
|
||||
.iter()
|
||||
.map(|s| ide_plugin::indexing::IndexSymbol {
|
||||
name: s.name.clone(),
|
||||
kind: serde_json::to_value(s.kind).ok().and_then(|v| v.as_str().map(str::to_owned)).unwrap_or_default(),
|
||||
container: s.container.clone(),
|
||||
range: s.range,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub struct Snapshot<'a> {
|
||||
pub path: &'a Path,
|
||||
@@ -236,7 +296,6 @@ impl PluginHost {
|
||||
if plugins.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let lines: Vec<_> = text.split('\n').map(|l| l.encode_utf16().count()).collect();
|
||||
for plugin in plugins {
|
||||
// A full graph keeps the files it covers; discovery already told the user
|
||||
// the rest are left out, so they are skipped without running the plugin.
|
||||
@@ -250,64 +309,14 @@ impl PluginHost {
|
||||
self.changed();
|
||||
}
|
||||
let (owned_path, owned_text) = (path.to_string_lossy().into_owned(), text.to_owned());
|
||||
let symbols = symbols
|
||||
.iter()
|
||||
.map(|s| ide_plugin::indexing::IndexSymbol {
|
||||
name: s.name.clone(),
|
||||
kind: serde_json::to_value(s.kind)
|
||||
.ok()
|
||||
.and_then(|v| v.as_str().map(str::to_owned))
|
||||
.unwrap_or_default(),
|
||||
container: s.container.clone(),
|
||||
range: s.range,
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let symbols = to_index_symbols(symbols);
|
||||
let ctx = invocation.clone();
|
||||
let started = std::time::Instant::now();
|
||||
let result = actor.call(None, move |rt| rt.index_document(&owned_path, &owned_text, &symbols, ctx));
|
||||
let edges = self
|
||||
.finish_provider_call(&plugin, &actor, started, result)
|
||||
.ok_or_else(|| IdeError::unavailable("document indexer did not return a result"))?;
|
||||
let output_bytes = edges
|
||||
.definitions
|
||||
.iter()
|
||||
.chain(&edges.references)
|
||||
.chain(&edges.markers)
|
||||
.map(|a| a.key.len().saturating_add(32))
|
||||
.sum::<usize>()
|
||||
.saturating_add(edges.aliases.iter().map(|a| a.prefix.len() + a.target.len()).sum::<usize>());
|
||||
if output_bytes > MAX_DOCUMENT_BYTES {
|
||||
return Err(IdeError::invalid("document index output is too large"));
|
||||
}
|
||||
if edges.aliases.len() > 256
|
||||
|| edges.aliases.iter().any(|a| {
|
||||
!a.prefix.ends_with('#')
|
||||
|| !a.target.ends_with('#')
|
||||
|| a.prefix.len() > 1024
|
||||
|| a.target.len() > 1024
|
||||
})
|
||||
|| edges.definitions.len() + edges.references.len() > MAX_EDGES
|
||||
|| edges
|
||||
.definitions
|
||||
.iter()
|
||||
.chain(&edges.references)
|
||||
.any(|a| a.key.is_empty() || a.key.len() > 1024 || !valid_range(&lines, a.range))
|
||||
{
|
||||
return Err(IdeError::invalid(format!(
|
||||
"{}: invalid navigation anchors in {}",
|
||||
plugin.id(),
|
||||
path.display()
|
||||
)));
|
||||
}
|
||||
if edges.markers.len() > MAX_EDGES
|
||||
|| edges.markers.iter().any(|a| a.key.is_empty() || a.key.len() > 1024 || !valid_range(&lines, a.range))
|
||||
{
|
||||
return Err(IdeError::invalid(format!(
|
||||
"{}: invalid navigation markers in {}",
|
||||
plugin.id(),
|
||||
path.display()
|
||||
)));
|
||||
}
|
||||
validate_edges(plugin.id(), path, text, &edges)?;
|
||||
let mut index = self.navigation.lock();
|
||||
if index.epochs.get(root).copied() != generation {
|
||||
return Err(IdeError::cancelled());
|
||||
@@ -322,16 +331,19 @@ impl PluginHost {
|
||||
if !graph.instance.ptr_eq(&Arc::downgrade(&plugin)) {
|
||||
*graph = Graph { instance: Arc::downgrade(&plugin), ..Default::default() };
|
||||
}
|
||||
graph.remove(path);
|
||||
if edges_are_empty(&edges) {
|
||||
continue;
|
||||
}
|
||||
if graph.files.len() >= MAX_FILES && !graph.files.contains_key(path) {
|
||||
continue;
|
||||
}
|
||||
graph.remove(path);
|
||||
if graph.edges
|
||||
+ edges.definitions.len()
|
||||
+ edges.references.len()
|
||||
+ edges.aliases.len()
|
||||
+ edges.markers.len()
|
||||
> 200_000
|
||||
> MAX_GRAPH_EDGES
|
||||
{
|
||||
return Err(IdeError::unavailable("navigation association limit reached"));
|
||||
}
|
||||
@@ -340,6 +352,191 @@ impl PluginHost {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Index a batch of bounded snapshots in short actor chunks (up to 16 files per call).
|
||||
/// Full graphs skip uncovered files before running the plugin, empty-edge documents are not
|
||||
/// stored, and individual invalid documents are skipped/evicted without failing the batch.
|
||||
pub fn index_navigation_batch(
|
||||
&self,
|
||||
root: &Path,
|
||||
snapshots: &[Snapshot<'_>],
|
||||
invocation: Invocation,
|
||||
cancel: Option<&ide_core::CancellationToken>,
|
||||
) -> IdeResult<BatchIndexSummary> {
|
||||
if snapshots.is_empty() {
|
||||
return Ok(BatchIndexSummary::default());
|
||||
}
|
||||
if !(self.project_policy.read())(root) {
|
||||
return Err(IdeError::unavailable("project is not trusted"));
|
||||
}
|
||||
let mut roots = vec![root.to_path_buf()];
|
||||
roots.extend(crate::project::workspace_member_roots(root));
|
||||
let mut summary = BatchIndexSummary::default();
|
||||
let mut prepared = Vec::with_capacity(snapshots.len());
|
||||
for snap in snapshots {
|
||||
if snap.text.len() > MAX_DOCUMENT_BYTES {
|
||||
tracing::warn!(path = %snap.path.display(), "navigation document is too large");
|
||||
summary.skipped_invalid += 1;
|
||||
continue;
|
||||
}
|
||||
let path = dunce::simplified(snap.path);
|
||||
match ide_plugin::resolve_in_roots(&roots, &path.to_string_lossy()) {
|
||||
Ok(real) if real == path => {
|
||||
let extension = path.extension().and_then(|e| e.to_str()).unwrap_or_default().to_owned();
|
||||
prepared.push((path.to_owned(), extension, snap));
|
||||
}
|
||||
Ok(_) | Err(_) => {
|
||||
tracing::warn!(path = %path.display(), "navigation skipped invalid path");
|
||||
summary.skipped_invalid += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
if prepared.is_empty() {
|
||||
return Ok(summary);
|
||||
}
|
||||
|
||||
let project_key = (root.to_owned(), invocation.client.clone());
|
||||
let generation = self.navigation.lock().epochs.get(root).copied();
|
||||
let plugins: Vec<(Arc<super::LoadedPlugin>, Vec<String>)> = self
|
||||
.plugins
|
||||
.read()
|
||||
.values()
|
||||
.filter(|p| {
|
||||
p.status().is_live()
|
||||
&& p.dev_root.as_deref().is_none_or(|r| r == root)
|
||||
&& p.meta.lock().granted.contains(&Capability::ProjectRead)
|
||||
})
|
||||
.filter_map(|p| declaration(p).map(|d| (p.clone(), d.extensions)))
|
||||
.collect();
|
||||
if plugins.is_empty() {
|
||||
return Ok(summary);
|
||||
}
|
||||
|
||||
for (plugin, exts) in plugins {
|
||||
let matching_indices: Vec<usize> = {
|
||||
let index = self.navigation.lock();
|
||||
let full_graph = index
|
||||
.projects
|
||||
.get(&project_key)
|
||||
.and_then(|g| g.get(plugin.id()))
|
||||
.filter(|g| g.instance.ptr_eq(&Arc::downgrade(&plugin)) && g.files.len() >= MAX_FILES);
|
||||
prepared
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(idx, (path, ext, _))| {
|
||||
if !exts.iter().any(|e| e == ext) {
|
||||
return None;
|
||||
}
|
||||
if full_graph.is_some_and(|g| !g.files.contains_key(path)) {
|
||||
return None;
|
||||
}
|
||||
Some(idx)
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
if matching_indices.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if cancel.is_some_and(ide_core::CancellationToken::is_cancelled) {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
let (actor, activated) = self.ensure_active(&plugin, invocation.client.as_deref())?;
|
||||
if activated {
|
||||
self.changed();
|
||||
}
|
||||
|
||||
for chunk in matching_indices.chunks(MAX_ACTOR_CHUNK) {
|
||||
if cancel.is_some_and(ide_core::CancellationToken::is_cancelled) {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
let items: Vec<_> = chunk
|
||||
.iter()
|
||||
.map(|&idx| {
|
||||
let (ref path, _, snap) = prepared[idx];
|
||||
(idx, path.to_string_lossy().into_owned(), snap.text.to_owned(), to_index_symbols(snap.symbols))
|
||||
})
|
||||
.collect();
|
||||
let ctx = invocation.clone();
|
||||
let chunk_cancel = cancel.cloned();
|
||||
let started = std::time::Instant::now();
|
||||
let result = actor.call(None, move |rt| {
|
||||
let mut out = Vec::with_capacity(items.len());
|
||||
for (idx, owned_path, owned_text, symbols) in items {
|
||||
if chunk_cancel.as_ref().is_some_and(ide_core::CancellationToken::is_cancelled) {
|
||||
return Ok(None);
|
||||
}
|
||||
let edges = rt.index_document(&owned_path, &owned_text, &symbols, ctx.clone())?;
|
||||
out.push((idx, edges));
|
||||
}
|
||||
Ok(Some(out))
|
||||
});
|
||||
let Some(maybe_edges) = self.finish_provider_call(&plugin, &actor, started, result) else {
|
||||
let mut index = self.navigation.lock();
|
||||
if let Some(graph) = index.projects.get_mut(&project_key).and_then(|g| g.get_mut(plugin.id())) {
|
||||
for &idx in chunk {
|
||||
graph.remove(&prepared[idx].0);
|
||||
}
|
||||
}
|
||||
return Err(IdeError::unavailable("document indexer did not return a result"));
|
||||
};
|
||||
let Some(chunk_edges) = maybe_edges else {
|
||||
return Err(IdeError::cancelled());
|
||||
};
|
||||
if cancel.is_some_and(ide_core::CancellationToken::is_cancelled) {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
|
||||
let mut index = self.navigation.lock();
|
||||
if index.epochs.get(root).copied() != generation {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
if index.projects.len() >= 16 && !index.projects.contains_key(&project_key) {
|
||||
return Err(IdeError::unavailable("navigation project limit reached"));
|
||||
}
|
||||
let graph =
|
||||
index.projects.entry(project_key.clone()).or_default().entry(plugin.id().to_owned()).or_default();
|
||||
if !graph.instance.ptr_eq(&Arc::downgrade(&plugin)) {
|
||||
*graph = Graph { instance: Arc::downgrade(&plugin), ..Default::default() };
|
||||
}
|
||||
for (idx, edges) in chunk_edges {
|
||||
let (ref path, _, snap) = prepared[idx];
|
||||
graph.remove(path);
|
||||
if let Err(err) = validate_edges(plugin.id(), path, snap.text, &edges) {
|
||||
tracing::warn!("{err}");
|
||||
summary.skipped_invalid += 1;
|
||||
continue;
|
||||
}
|
||||
if edges_are_empty(&edges) {
|
||||
continue;
|
||||
}
|
||||
if graph.files.len() >= MAX_FILES && !graph.files.contains_key(path) {
|
||||
continue;
|
||||
}
|
||||
let new_edges =
|
||||
edges.definitions.len() + edges.references.len() + edges.aliases.len() + edges.markers.len();
|
||||
if graph.edges + new_edges > MAX_GRAPH_EDGES {
|
||||
tracing::warn!(
|
||||
plugin = %plugin.id(),
|
||||
path = %path.display(),
|
||||
"navigation association limit reached; skipping document"
|
||||
);
|
||||
summary.skipped_invalid += 1;
|
||||
continue;
|
||||
}
|
||||
graph.insert(
|
||||
path.clone(),
|
||||
File {
|
||||
version: snap.version,
|
||||
scope: snap.scope.to_owned(),
|
||||
hash: snapshot_hash(snap.text),
|
||||
edges,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(summary)
|
||||
}
|
||||
|
||||
/// Resolves only current live providers. Disable/reload/trap cannot retain
|
||||
/// navigable stale data, even if a background snapshot finished concurrently.
|
||||
pub fn navigation_at(
|
||||
|
||||
@@ -422,3 +422,156 @@ async fn schema_reads_user_tables_without_rows_or_credentials_and_enforces_grant
|
||||
assert!(db.connected_table_details("user-source", None, "main", "users").await.is_err());
|
||||
assert!(!db.is_connected("user-source"), "schema reads cannot reconnect a disconnected source");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn schema_discovery_and_query_execution_enforce_grants_trust_and_connection_isolation() {
|
||||
let f = Harness::with_timeout(Duration::from_secs(10));
|
||||
f.host.set_project_trust(&f.root, true, false).await.unwrap();
|
||||
let db = f.host.project("main").unwrap().db.clone();
|
||||
db.save_sources(vec![ide_db::DataSource {
|
||||
id: "user-source".into(),
|
||||
name: "User SQLite".into(),
|
||||
driver: ide_db::DbDriver::Sqlite,
|
||||
file: Some(f.root.join("db.sqlite").into()),
|
||||
..Default::default()
|
||||
}])
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
// Disconnected sources are never listed or queried implicitly.
|
||||
let initial_sources: Vec<serde_json::Value> =
|
||||
serde_json::from_str(&f.run("connected-sources", None).unwrap().unwrap()).unwrap();
|
||||
assert!(initial_sources.is_empty());
|
||||
assert!(f.run("list-schemas", Some("user-source")).is_err());
|
||||
assert!(!db.is_connected("user-source"));
|
||||
let q_req = serde_json::json!({
|
||||
"sourceId": "user-source",
|
||||
"sql": "SELECT id, name FROM users ORDER BY id",
|
||||
"maxRows": 1
|
||||
})
|
||||
.to_string();
|
||||
assert!(f.run("execute-query", Some(&q_req)).is_err(), "query execution never connects implicitly");
|
||||
assert!(!db.is_connected("user-source"));
|
||||
|
||||
let cancel = CancellationToken::new();
|
||||
for sql in [
|
||||
"CREATE TABLE users(id INTEGER PRIMARY KEY, name TEXT NOT NULL)",
|
||||
"INSERT INTO users(name) VALUES ('alice'), ('bob')",
|
||||
] {
|
||||
db.execute("user-source", sql, 100, &cancel).await.unwrap();
|
||||
}
|
||||
|
||||
// Window isolation: second window has no connection of its own for discovery or queries.
|
||||
let second_inv = Invocation { client: Some("second".into()), ..f.invocation() };
|
||||
let second_sources: Vec<serde_json::Value> = serde_json::from_str(
|
||||
&f.plugins.run_command(ID, "connected-sources", None, second_inv.clone()).unwrap().unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(second_sources.is_empty(), "a disconnected window cannot see another window's connections");
|
||||
assert!(f.plugins.run_command(ID, "list-schemas", Some("user-source"), second_inv.clone()).is_err());
|
||||
assert!(
|
||||
f.plugins
|
||||
.run_command(ID, "list-tables", Some(r#"{"sourceId":"user-source","schema":"main"}"#), second_inv.clone())
|
||||
.is_err()
|
||||
);
|
||||
assert!(f.plugins.run_command(ID, "execute-query", Some(&q_req), second_inv).is_err());
|
||||
|
||||
// Schema discovery returns only non-secret identity + schemas/tables (never credentials or row data).
|
||||
let sources_json = f.run("connected-sources", None).unwrap().unwrap();
|
||||
let sources: Vec<serde_json::Value> = serde_json::from_str(&sources_json).unwrap();
|
||||
assert_eq!(sources.len(), 1);
|
||||
assert_eq!(sources[0]["sourceId"], "user-source");
|
||||
assert_eq!(sources[0]["driver"], "sqlite");
|
||||
assert!(!sources_json.contains("password") && !sources_json.contains("alice"));
|
||||
|
||||
let schemas: Vec<String> =
|
||||
serde_json::from_str(&f.run("list-schemas", Some("user-source")).unwrap().unwrap()).unwrap();
|
||||
assert!(schemas.iter().any(|s| s == "main"));
|
||||
|
||||
let tables: Vec<serde_json::Value> = serde_json::from_str(
|
||||
&f.run("list-tables", Some(r#"{"sourceId":"user-source","schema":"main"}"#)).unwrap().unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(tables.iter().any(|t| t["name"] == "users" && t["kind"] == "table"));
|
||||
|
||||
// Query execution respects max_rows & has_more and returns rows.
|
||||
let q_res: serde_json::Value =
|
||||
serde_json::from_str(&f.run("execute-query", Some(&q_req)).unwrap().unwrap()).unwrap();
|
||||
assert_eq!(q_res["rows"].as_array().unwrap().len(), 1);
|
||||
assert_eq!(q_res["rows"][0][1], "alice");
|
||||
assert_eq!(q_res["hasMore"], true);
|
||||
|
||||
// Large cells are capped at 8192 UTF-16 code units.
|
||||
let wide_req = serde_json::json!({
|
||||
"sourceId": "user-source",
|
||||
"sql": "SELECT replace(hex(zeroblob(5000)), '0', 'a')",
|
||||
})
|
||||
.to_string();
|
||||
let wide_res: serde_json::Value =
|
||||
serde_json::from_str(&f.run("execute-query", Some(&wide_req)).unwrap().unwrap()).unwrap();
|
||||
assert_eq!(wide_res["rows"][0][0].as_str().unwrap().encode_utf16().count(), 8192);
|
||||
|
||||
// Invalid inputs (empty SQL, NUL bytes) are rejected cleanly.
|
||||
for bad in [
|
||||
serde_json::json!({ "sourceId": "user-source", "sql": " " }),
|
||||
serde_json::json!({ "sourceId": "user-source", "sql": "SELECT 1\0" }),
|
||||
serde_json::json!({ "sourceId": "user\0source", "sql": "SELECT 1" }),
|
||||
] {
|
||||
assert!(f.run("execute-query", Some(&bad.to_string())).is_err(), "{bad}");
|
||||
}
|
||||
|
||||
// DDL/DML affected count works under database.query.
|
||||
let dml_req = serde_json::json!({
|
||||
"sourceId": "user-source",
|
||||
"sql": "UPDATE users SET name = 'charlie' WHERE id = 2",
|
||||
})
|
||||
.to_string();
|
||||
let dml_res: serde_json::Value =
|
||||
serde_json::from_str(&f.run("execute-query", Some(&dml_req)).unwrap().unwrap()).unwrap();
|
||||
assert_eq!(dml_res["affected"], 1);
|
||||
|
||||
// Background calls (client: None) see sources connected in any window of the project.
|
||||
db.disconnect("user-source").await;
|
||||
let second_db = f.host.project("second").unwrap().db.clone();
|
||||
second_db.execute("user-source", "SELECT 1", 1, &cancel).await.unwrap();
|
||||
let bg_sources: Vec<serde_json::Value> = serde_json::from_str(
|
||||
&f.plugins
|
||||
.run_command(ID, "connected-sources", None, Invocation { client: None, ..f.invocation() })
|
||||
.unwrap()
|
||||
.unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(bg_sources.len(), 1);
|
||||
assert_eq!(bg_sources[0]["sourceId"], "user-source");
|
||||
second_db.disconnect("user-source").await;
|
||||
|
||||
// Read-only sources allow SELECT but refuse writes even with database.query granted.
|
||||
db.save_sources(vec![ide_db::DataSource {
|
||||
id: "ro-source".into(),
|
||||
name: "Read-only SQLite".into(),
|
||||
driver: ide_db::DbDriver::Sqlite,
|
||||
file: Some(f.root.join("db.sqlite").into()),
|
||||
read_only: true,
|
||||
..Default::default()
|
||||
}])
|
||||
.await
|
||||
.unwrap();
|
||||
db.execute("ro-source", "SELECT 1", 1, &cancel).await.unwrap();
|
||||
let ro_select = serde_json::json!({ "sourceId": "ro-source", "sql": "SELECT count(*) FROM users" }).to_string();
|
||||
let ro_update =
|
||||
serde_json::json!({ "sourceId": "ro-source", "sql": "UPDATE users SET name = 'blocked'" }).to_string();
|
||||
assert!(f.run("execute-query", Some(&ro_select)).is_ok());
|
||||
assert!(f.run("execute-query", Some(&ro_update)).is_err(), "read-only sources must reject writes");
|
||||
|
||||
// Revoking `database.query` blocks queries while leaving `database.schema` discovery intact.
|
||||
f.plugins.set_capability(ID, "database.query", false).unwrap();
|
||||
let err = f.run("execute-query", Some(&ro_select)).unwrap_err();
|
||||
assert!(err.message.contains("database.query"));
|
||||
assert!(f.run("connected-sources", None).is_ok());
|
||||
|
||||
// Revoking project trust blocks both.
|
||||
f.plugins.set_capability(ID, "database.query", true).unwrap();
|
||||
f.host.set_project_trust(&f.root, false, false).await.unwrap();
|
||||
assert!(f.run("connected-sources", None).is_err());
|
||||
assert!(f.run("execute-query", Some(&ro_select)).is_err());
|
||||
}
|
||||
@@ -394,7 +394,17 @@ fn a_full_graph_keeps_updating_its_files_and_skips_others_without_running_the_pl
|
||||
let f = Fixture::new();
|
||||
let source = f.index("source.idx", SOURCE, &[method()], Some(1), "");
|
||||
for i in 1..MAX_FILES {
|
||||
f.index(&format!("filler/{i}.idx"), "", &[], None, "");
|
||||
let p = f.root.join(format!("filler/{i}.idx"));
|
||||
let txt = format!("def filler:{i}\n");
|
||||
std::fs::create_dir_all(p.parent().unwrap()).unwrap();
|
||||
std::fs::write(&p, &txt).unwrap();
|
||||
f.host
|
||||
.index_navigation(
|
||||
&f.root,
|
||||
Snapshot { path: &p, version: None, text: &txt, symbols: &[], scope: "" },
|
||||
Invocation { workspace_root: Some(f.root.clone()), ..Default::default() },
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
let calls = f.host.info_of("test.indexer").unwrap().stats.calls;
|
||||
let mapping = f.index("mapping.idx", MAPPING, &[], Some(1), "");
|
||||
@@ -403,4 +413,99 @@ fn a_full_graph_keeps_updating_its_files_and_skips_others_without_running_the_pl
|
||||
f.index("source.idx", SOURCE, &[method()], Some(2), "");
|
||||
assert_eq!(f.host.info_of("test.indexer").unwrap().stats.calls, calls + 1, "covered files still update");
|
||||
assert!(f.host.navigation_at(&f.root, &source, 2, Pos::new(1, 5), None, |_| None).is_none());
|
||||
|
||||
// Batch indexing on the same full graph also skips uncovered files before invoking WASM.
|
||||
let calls_before_batch = f.host.info_of("test.indexer").unwrap().stats.calls;
|
||||
std::fs::write(&source, SOURCE).unwrap();
|
||||
f.host
|
||||
.index_navigation_batch(
|
||||
&f.root,
|
||||
&[
|
||||
Snapshot { path: &mapping, version: Some(2), text: MAPPING, symbols: &[], scope: "" },
|
||||
Snapshot { path: &source, version: Some(3), text: SOURCE, symbols: &[], scope: "" },
|
||||
],
|
||||
Invocation { workspace_root: Some(f.root.clone()), ..Default::default() },
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
f.host.info_of("test.indexer").unwrap().stats.calls,
|
||||
calls_before_batch + 1,
|
||||
"batch only invokes WASM for the already-covered file"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_edges_do_not_consume_graph_slots_and_batch_isolates_invalid_documents() {
|
||||
let f = Fixture::new();
|
||||
let source = f.index("src/source.idx", SOURCE, &[method()], Some(1), "app");
|
||||
let mapping = f.index("resources/mapping.idx", MAPPING, &[], Some(1), "app");
|
||||
assert!(f.host.navigation_at(&f.root, &mapping, 1, reference_pos(), None, |_| None).is_some());
|
||||
|
||||
// Re-indexing `source` with empty content evicts its previous anchors cleanly.
|
||||
std::fs::write(&source, "").unwrap();
|
||||
f.host
|
||||
.index_navigation(
|
||||
&f.root,
|
||||
Snapshot { path: &source, version: Some(2), text: "", symbols: &[], scope: "app" },
|
||||
Invocation { workspace_root: Some(f.root.clone()), ..Default::default() },
|
||||
)
|
||||
.unwrap();
|
||||
assert!(f.host.navigation_at(&f.root, &mapping, 1, reference_pos(), None, |_| None).is_none());
|
||||
assert!(f.host.navigation_markers(&f.root, std::slice::from_ref(&mapping), None, |_| None).is_empty());
|
||||
|
||||
// Mixed batch containing 200 empty files, one invalid document, and two valid connected files:
|
||||
// the invalid document is skipped/evicted while valid documents still commit cleanly.
|
||||
let mut empty_paths = Vec::with_capacity(200);
|
||||
for i in 0..200 {
|
||||
let p = f.root.join(format!("empty/E{i}.idx"));
|
||||
std::fs::create_dir_all(p.parent().unwrap()).unwrap();
|
||||
std::fs::write(&p, "// nothing\n").unwrap();
|
||||
empty_paths.push(p);
|
||||
}
|
||||
let bad = f.root.join("batch/bad.idx");
|
||||
let connected_a = f.root.join("batch/source.idx");
|
||||
let connected_b = f.root.join("batch/mapping.idx");
|
||||
std::fs::create_dir_all(bad.parent().unwrap()).unwrap();
|
||||
std::fs::write(&bad, "invalid key\n").unwrap();
|
||||
std::fs::write(&connected_a, SOURCE).unwrap();
|
||||
std::fs::write(&connected_b, MAPPING).unwrap();
|
||||
|
||||
let mut snapshots: Vec<Snapshot<'_>> = empty_paths
|
||||
.iter()
|
||||
.map(|p| Snapshot { path: p, version: None, text: "// nothing\n", symbols: &[], scope: "app" })
|
||||
.collect();
|
||||
snapshots.push(Snapshot { path: &bad, version: Some(1), text: "invalid key\n", symbols: &[], scope: "app" });
|
||||
snapshots.push(Snapshot { path: &connected_a, version: Some(1), text: SOURCE, symbols: &[], scope: "app" });
|
||||
snapshots.push(Snapshot { path: &connected_b, version: Some(1), text: MAPPING, symbols: &[], scope: "app" });
|
||||
|
||||
let summary = f
|
||||
.host
|
||||
.index_navigation_batch(
|
||||
&f.root,
|
||||
&snapshots,
|
||||
Invocation { workspace_root: Some(f.root.clone()), ..Default::default() },
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(summary.skipped_invalid, 1);
|
||||
|
||||
let res = f.host.navigation_at(&f.root, &connected_b, 1, reference_pos(), None, |_| None).unwrap();
|
||||
assert_eq!(res.targets[0].path.0, connected_a);
|
||||
let markers = f.host.navigation_markers(&f.root, &[connected_a.clone(), connected_b.clone()], None, |_| None);
|
||||
assert_eq!(markers.len(), 2);
|
||||
|
||||
// Pre-cancelled batch aborts without publishing or modifying entries.
|
||||
let cancelled_file = f.root.join("batch/cancelled.idx");
|
||||
std::fs::write(&cancelled_file, SOURCE).unwrap();
|
||||
let token = ide_core::CancellationToken::new();
|
||||
token.cancel();
|
||||
let cancelled_res = f.host.index_navigation_batch(
|
||||
&f.root,
|
||||
&[Snapshot { path: &cancelled_file, version: Some(1), text: SOURCE, symbols: &[], scope: "app" }],
|
||||
Invocation { workspace_root: Some(f.root.clone()), ..Default::default() },
|
||||
Some(&token),
|
||||
);
|
||||
assert!(cancelled_res.is_err());
|
||||
assert!(f.host.navigation_markers(&f.root, &[cancelled_file], None, |_| None).is_empty());
|
||||
}
|
||||
@@ -1565,3 +1565,53 @@ async fn remote_browser_export_checkout_options_and_restricted_mode() {
|
||||
.unwrap_err();
|
||||
assert_eq!(del_err.kind, ide_core::error::ErrorKind::Unavailable, "{del_err:?}");
|
||||
}
|
||||
|
||||
/// Update Project in two working copies (issue #7433): the console gets svn's own output for
|
||||
/// each, the files it changed and the revision reached, not only a summary line.
|
||||
#[tokio::test]
|
||||
async fn update_output_of_two_working_copies() {
|
||||
let Some(fx) = fixture() else { return };
|
||||
let seed = fx.checkout("seed");
|
||||
for name in ["a.txt", "gone.txt"] {
|
||||
std::fs::write(seed.join(name), "one\n").unwrap();
|
||||
}
|
||||
fx.svn(&seed, &["add", "-q", "a.txt", "gone.txt"]);
|
||||
fx.svn(&seed, &["commit", "-q", "-m", "seed"]);
|
||||
let project_root = fx.base.join("project");
|
||||
std::fs::create_dir(&project_root).unwrap();
|
||||
let trunk = format!("{}/trunk", fx.url);
|
||||
for name in ["boot", "antd"] {
|
||||
fx.svn(&fx.base, &["checkout", "-q", &trunk, project_root.join(name).to_str().unwrap()]);
|
||||
}
|
||||
std::fs::write(seed.join("a.txt"), "two\n").unwrap();
|
||||
std::fs::write(seed.join("new.txt"), "new\n").unwrap();
|
||||
fx.svn(&seed, &["add", "-q", "new.txt"]);
|
||||
fx.svn(&seed, &["rm", "-q", "gone.txt"]);
|
||||
fx.svn(&seed, &["commit", "-q", "-m", "two"]);
|
||||
|
||||
let host = Host::new(common::host_config(&fx.base)).with_subversion(false);
|
||||
host.trust.decide(&project_root, true, false).unwrap();
|
||||
let project = host.open_project("main", &project_root).unwrap();
|
||||
until("both working copies", || project.backends().len() == 2).await;
|
||||
for name in ["boot", "antd"] {
|
||||
let lines = Arc::new(std::sync::Mutex::new(Vec::<String>::new()));
|
||||
let sink = lines.clone();
|
||||
let channel = ide_host::ops::Channel::new(move |line: String| sink.lock().unwrap().push(line));
|
||||
let op = vcs::RemoteOp::UpdateProjectBranch { rebase: false };
|
||||
let repo = Some(project_root.join(name));
|
||||
vcs::vcs_remote(&host, "main", repo, ide_core::RequestId::next(), op, channel, None).await.unwrap();
|
||||
let lines = lines.lock().unwrap().clone();
|
||||
let changed: Vec<&str> = lines
|
||||
.iter()
|
||||
.filter_map(|l| {
|
||||
l.split_once(char::is_whitespace).filter(|(code, _)| code.len() == 1).map(|(_, p)| p.trim())
|
||||
})
|
||||
.map(|p| p.rsplit(['/', '\\']).next().unwrap())
|
||||
.collect();
|
||||
assert!(lines.iter().any(|l| l.starts_with("Updating ")), "{name}: {lines:?}");
|
||||
for file in ["a.txt", "new.txt", "gone.txt"] {
|
||||
assert!(changed.contains(&file), "{name}: {file} in {lines:?}");
|
||||
}
|
||||
assert!(lines.last().is_some_and(|l| l.starts_with("Updated to revision ")), "{name}: {lines:?}");
|
||||
}
|
||||
}
|
||||
@@ -511,3 +511,41 @@ async fn attach_and_detach_preserve_the_primary_project_session() {
|
||||
assert!(!reopened.is_trusted());
|
||||
host.close_project("main");
|
||||
}
|
||||
|
||||
/// Issue #7433: a member whose folder is gone (its checkout moved up a level) can be removed,
|
||||
/// and the folder it moved to can be attached, under the same name, before or after that.
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn a_member_whose_folder_is_gone_can_be_removed_and_its_new_folder_attached() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(temp.path()).unwrap();
|
||||
let primary = base.join("primary");
|
||||
let moved_to = base.join("sapp");
|
||||
let gone = moved_to.join("sapp");
|
||||
std::fs::create_dir_all(&primary).unwrap();
|
||||
std::fs::create_dir_all(&gone).unwrap();
|
||||
std::fs::write(gone.join("pom.xml"), "<project/>").unwrap();
|
||||
let host = Host::new(common::host_config(&base));
|
||||
for root in [&primary, &gone, &moved_to] {
|
||||
host.trust.decide(root, true, false).unwrap();
|
||||
}
|
||||
let project = host.open_project("main", &primary).unwrap();
|
||||
ops::project::attach_workspace(&host, "main", &gone).unwrap();
|
||||
// The checkout moves up a level: `sapp/sapp` is gone, its files are in `sapp`.
|
||||
std::fs::rename(gone.join("pom.xml"), moved_to.join("pom.xml")).unwrap();
|
||||
std::fs::remove_dir(&gone).unwrap();
|
||||
|
||||
// The folder it moved to, named the same, is attached while the old entry is still there.
|
||||
ops::project::attach_workspace(&host, "main", &moved_to).unwrap();
|
||||
let members = Workspace::load(&primary).unwrap().unwrap().projects;
|
||||
assert_eq!(members, [primary.clone(), gone.clone(), moved_to.clone()]);
|
||||
assert!(ops::project::info(&project).workspace.is_some());
|
||||
|
||||
// Remove from Workspace of the gone member.
|
||||
ops::project::save_workspace(&host, "main", "primary", vec![primary.clone(), moved_to.clone()]).unwrap();
|
||||
assert_eq!(Workspace::load(&primary).unwrap().unwrap().projects, [primary.clone(), moved_to.clone()]);
|
||||
|
||||
// Removed first, then attached again.
|
||||
ops::project::save_workspace(&host, "main", "primary", vec![primary.clone()]).unwrap();
|
||||
ops::project::attach_workspace(&host, "main", &moved_to).unwrap();
|
||||
assert_eq!(Workspace::load(&primary).unwrap().unwrap().projects, [primary, moved_to]);
|
||||
}
|
||||
@@ -1,16 +1,147 @@
|
||||
//! Extract Interface through jdtls' own requests: `java/checkExtractInterfaceStatus` lists the
|
||||
//! members of the file's class an interface can declare and the packages it can go to,
|
||||
//! `java/getRefactorEdit` (`extractInterface`) creates the interface, makes the class implement
|
||||
//! it and uses it where possible. The UI picks the name, package and members and applies the edit.
|
||||
//! Extract Interface through java-analyzer's dialog-driven requests when the server advertises
|
||||
//! them in `capabilities.experimental`, falling back to jdtls' `java/checkExtractInterfaceStatus`
|
||||
//! and `java/getRefactorEdit` (`extractInterface`). The UI picks the name, package and members
|
||||
//! and applies the edit.
|
||||
use super::COMMAND_TIMEOUT;
|
||||
use super::signature::{RefactorEdit, changed};
|
||||
use crate::caps::ServerCaps;
|
||||
use crate::text::DocText;
|
||||
use crate::types::{ExtractInterfaceInfo, InterfaceMember, ProblemSeverity, RefactoringProblem, ServerRefactored};
|
||||
use crate::{LspManager, convert};
|
||||
use crate::{DocSnap, LspManager, Target, convert};
|
||||
use ide_core::{CancellationToken, DocId, IdeError, IdeResult, Pos};
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Value, json};
|
||||
use std::path::Path;
|
||||
|
||||
const FEATURE: &str = "Extract Interface";
|
||||
/// java-analyzer's dialog-driven requests, advertised in `capabilities.experimental`.
|
||||
const JAVA_INFO: &str = "java-analyzer/extractInterfaceInfo";
|
||||
const JAVA_EDIT: &str = "java-analyzer/extractInterface";
|
||||
|
||||
/// A server that advertises the extract-interface pair answers it without JDT internals.
|
||||
fn java_analyzer(caps: &ServerCaps) -> bool {
|
||||
caps.raw["experimental"][JAVA_INFO] == true && caps.raw["experimental"][JAVA_EDIT] == true
|
||||
}
|
||||
|
||||
enum ExtractTarget {
|
||||
JavaAnalyzer(Target),
|
||||
Jdtls(Target),
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct JavaInfo {
|
||||
/// Suggested interface name from java-analyzer (e.g. `Main` for `MainImpl`). Not used as
|
||||
/// `ExtractInterfaceInfo::class_name` because the dialog displays `className` as the source
|
||||
/// class and rejects entering an interface name equal to it.
|
||||
#[allow(dead_code)]
|
||||
#[serde(default)]
|
||||
interface_name: String,
|
||||
#[serde(default)]
|
||||
members: Vec<InterfaceMember>,
|
||||
#[serde(default)]
|
||||
packages: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct JavaResult {
|
||||
edit: Option<lsp_types::WorkspaceEdit>,
|
||||
#[serde(default)]
|
||||
problems: Vec<JavaProblem>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct JavaProblem {
|
||||
severity: JavaSeverity,
|
||||
message: String,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Debug, PartialEq, Eq)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
enum JavaSeverity {
|
||||
Error,
|
||||
Warning,
|
||||
}
|
||||
|
||||
/// jdtls packages are JSON-encoded destination objects; keep the same shape for the dialog.
|
||||
fn java_packages(packages: Vec<String>) -> Vec<String> {
|
||||
packages
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(i, name)| {
|
||||
json!({
|
||||
"displayName": name,
|
||||
"isParentOfSelectedFile": i == 0,
|
||||
})
|
||||
.to_string()
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The dialog sends back the same JSON string it was given; recover the package name.
|
||||
fn java_package(pkg: &Value) -> IdeResult<String> {
|
||||
if let Some(text) = pkg.as_str() {
|
||||
let value: Value = serde_json::from_str(text).map_err(|e| IdeError::invalid(e.to_string()))?;
|
||||
return value
|
||||
.get("displayName")
|
||||
.and_then(Value::as_str)
|
||||
.map(str::to_owned)
|
||||
.ok_or_else(|| IdeError::invalid("No package selected"));
|
||||
}
|
||||
pkg.get("displayName")
|
||||
.and_then(Value::as_str)
|
||||
.map(str::to_owned)
|
||||
.ok_or_else(|| IdeError::invalid("No package selected"))
|
||||
}
|
||||
|
||||
/// Source class/enum/record name at `pos` (falling back to the file stem), since
|
||||
/// `java-analyzer/extractInterfaceInfo` returns the suggested interface name rather than the
|
||||
/// class name that the dialog shows and checks for collisions against.
|
||||
fn class_name_at(text: &DocText, path: &Path, pos: Pos) -> String {
|
||||
if let Some(range) = text.word_range_at(pos) {
|
||||
let start = text.byte_offset(range.start);
|
||||
let end = text.byte_offset(range.end);
|
||||
let ident = &text.as_str()[start..end];
|
||||
let before = text.as_str()[..start].trim_end();
|
||||
let preceded_by_type_kw = ["class", "enum", "record"].iter().any(|kw| {
|
||||
before.strip_suffix(kw).is_some_and(|head| {
|
||||
head.chars().next_back().is_none_or(|c| !(c.is_alphanumeric() || c == '_' || c == '$'))
|
||||
})
|
||||
});
|
||||
if preceded_by_type_kw {
|
||||
return ident.to_owned();
|
||||
}
|
||||
}
|
||||
path.file_stem().and_then(|s| s.to_str()).unwrap_or_default().to_owned()
|
||||
}
|
||||
|
||||
fn java_info_of(info: Option<JavaInfo>, class_name: String) -> IdeResult<ExtractInterfaceInfo> {
|
||||
let info = info.ok_or_else(|| {
|
||||
IdeError::invalid("Place the caret on the name of a top-level class, enum or record with public methods")
|
||||
})?;
|
||||
Ok(ExtractInterfaceInfo { class_name, members: info.members, packages: java_packages(info.packages) })
|
||||
}
|
||||
|
||||
fn java_result_of(
|
||||
answer: JavaResult,
|
||||
convert_edit: impl FnOnce(lsp_types::WorkspaceEdit) -> ide_core::WorkspaceEdit,
|
||||
) -> ServerRefactored {
|
||||
let problems = answer
|
||||
.problems
|
||||
.into_iter()
|
||||
.map(|p| RefactoringProblem {
|
||||
severity: match p.severity {
|
||||
JavaSeverity::Error => ProblemSeverity::Error,
|
||||
JavaSeverity::Warning => ProblemSeverity::Warning,
|
||||
},
|
||||
message: p.message,
|
||||
})
|
||||
.collect();
|
||||
// java-analyzer is stateless: no confirmation token, the client applies what it got.
|
||||
ServerRefactored { problems, edit: answer.edit.map(convert_edit), confirmation: None }
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
@@ -42,6 +173,18 @@ fn info_of(status: Option<Status>) -> IdeResult<ExtractInterfaceInfo> {
|
||||
}
|
||||
|
||||
impl LspManager {
|
||||
async fn extract_interface_target(&self, doc: DocId) -> IdeResult<(DocSnap, ExtractTarget)> {
|
||||
let (snap, targets) = self.doc_targets(doc, FEATURE, |_| true).await?;
|
||||
if let Some(t) = targets.iter().find(|t| java_analyzer(&t.caps())) {
|
||||
return Ok((snap, ExtractTarget::JavaAnalyzer(t.clone())));
|
||||
}
|
||||
let t = targets
|
||||
.into_iter()
|
||||
.find(|t| t.server.name == super::SERVER)
|
||||
.ok_or_else(|| IdeError::unavailable(format!("{FEATURE} needs the Java language server (jdtls)")))?;
|
||||
Ok((snap, ExtractTarget::Jdtls(t)))
|
||||
}
|
||||
|
||||
/// The class of the file at `doc`, its members and the packages for the interface.
|
||||
pub async fn extract_interface_info(
|
||||
&self,
|
||||
@@ -49,14 +192,29 @@ impl LspManager {
|
||||
pos: Pos,
|
||||
cancel: CancellationToken,
|
||||
) -> IdeResult<ExtractInterfaceInfo> {
|
||||
let (snap, t) = self.jdtls_target(doc, FEATURE).await?;
|
||||
let params = Self::signature_context(&snap, &t, pos);
|
||||
let status: Option<Status> =
|
||||
self.call(&t, "java/checkExtractInterfaceStatus", params, Some(&cancel), COMMAND_TIMEOUT).await?;
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
let (snap, target) = self.extract_interface_target(doc).await?;
|
||||
match target {
|
||||
ExtractTarget::JavaAnalyzer(t) => {
|
||||
let params = json!({
|
||||
"textDocument": { "uri": snap.uri },
|
||||
"position": snap.position(&t, pos),
|
||||
});
|
||||
let info: Option<JavaInfo> = self.call(&t, JAVA_INFO, params, Some(&cancel), COMMAND_TIMEOUT).await?;
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
java_info_of(info, class_name_at(&snap.text, &snap.path, pos))
|
||||
}
|
||||
ExtractTarget::Jdtls(t) => {
|
||||
let params = Self::signature_context(&snap, &t, pos);
|
||||
let status: Option<Status> =
|
||||
self.call(&t, "java/checkExtractInterfaceStatus", params, Some(&cancel), COMMAND_TIMEOUT).await?;
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
info_of(status)
|
||||
}
|
||||
}
|
||||
info_of(status)
|
||||
}
|
||||
|
||||
/// Checks extracting `members` into the interface `name` in `package` (a package from
|
||||
@@ -72,40 +230,63 @@ impl LspManager {
|
||||
confirmation: Option<String>,
|
||||
cancel: CancellationToken,
|
||||
) -> IdeResult<ServerRefactored> {
|
||||
let (snap, t) = self.jdtls_target(doc, FEATURE).await?;
|
||||
let mut params = json!({
|
||||
"command": "extractInterface",
|
||||
"context": Self::signature_context(&snap, &t, pos),
|
||||
"options": { "tabSize": 4, "insertSpaces": true },
|
||||
"commandArguments": [members, name, package],
|
||||
});
|
||||
if let Some(token) = confirmation {
|
||||
params["confirmationToken"] = json!(token);
|
||||
let (snap, target) = self.extract_interface_target(doc).await?;
|
||||
match target {
|
||||
ExtractTarget::JavaAnalyzer(t) => {
|
||||
// The server defaults to the class's own package; sending it explicitly is optional.
|
||||
let mut params = json!({
|
||||
"textDocument": { "uri": snap.uri },
|
||||
"position": snap.position(&t, pos),
|
||||
"name": name,
|
||||
"members": members,
|
||||
});
|
||||
if let Ok(package) = java_package(&package) {
|
||||
params["package"] = json!(package);
|
||||
}
|
||||
let answer: JavaResult = self.call(&t, JAVA_EDIT, params, Some(&cancel), COMMAND_TIMEOUT).await?;
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
let conv = self.conv(t.enc());
|
||||
Ok(java_result_of(answer, |e| convert::workspace_edit(&conv, e)))
|
||||
}
|
||||
ExtractTarget::Jdtls(t) => {
|
||||
let mut params = json!({
|
||||
"command": "extractInterface",
|
||||
"context": Self::signature_context(&snap, &t, pos),
|
||||
"options": { "tabSize": 4, "insertSpaces": true },
|
||||
"commandArguments": [members, name, package],
|
||||
});
|
||||
if let Some(token) = confirmation {
|
||||
params["confirmationToken"] = json!(token);
|
||||
}
|
||||
let answer: Option<RefactorEdit> =
|
||||
self.call(&t, "java/getRefactorEdit", params, Some(&cancel), COMMAND_TIMEOUT).await?;
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
// jdtls answers nothing when its checks fail, and reports why in a message of its own.
|
||||
let Some(answer) = answer else {
|
||||
return Ok(ServerRefactored {
|
||||
problems: vec![RefactoringProblem {
|
||||
severity: ProblemSeverity::Fatal,
|
||||
message: "The interface could not be extracted".to_owned(),
|
||||
}],
|
||||
edit: None,
|
||||
confirmation: None,
|
||||
});
|
||||
};
|
||||
let conv = self.conv(t.enc());
|
||||
Ok(changed(answer, |e| convert::workspace_edit(&conv, e)))
|
||||
}
|
||||
}
|
||||
let answer: Option<RefactorEdit> =
|
||||
self.call(&t, "java/getRefactorEdit", params, Some(&cancel), COMMAND_TIMEOUT).await?;
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
// jdtls answers nothing when its checks fail, and reports why in a message of its own.
|
||||
let Some(answer) = answer else {
|
||||
return Ok(ServerRefactored {
|
||||
problems: vec![RefactoringProblem {
|
||||
severity: ProblemSeverity::Fatal,
|
||||
message: "The interface could not be extracted".to_owned(),
|
||||
}],
|
||||
edit: None,
|
||||
confirmation: None,
|
||||
});
|
||||
};
|
||||
let conv = self.conv(t.enc());
|
||||
Ok(changed(answer, |e| convert::workspace_edit(&conv, e)))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::ErrorKind;
|
||||
|
||||
#[test]
|
||||
fn reads_the_members_and_packages() {
|
||||
@@ -125,4 +306,101 @@ mod tests {
|
||||
assert_eq!(serde_json::from_str::<Value>(&info.packages[0]).unwrap()["displayName"], "a");
|
||||
assert!(info_of(None).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn finds_the_server_by_its_capability() {
|
||||
let both = ServerCaps::parse(json!({
|
||||
"experimental": { "java-analyzer/extractInterfaceInfo": true, "java-analyzer/extractInterface": true },
|
||||
}));
|
||||
let info_only = ServerCaps::parse(json!({
|
||||
"experimental": { "java-analyzer/extractInterfaceInfo": true },
|
||||
}));
|
||||
let edit_only = ServerCaps::parse(json!({
|
||||
"experimental": { "java-analyzer/extractInterface": true },
|
||||
}));
|
||||
let disabled = ServerCaps::parse(json!({
|
||||
"experimental": { "java-analyzer/extractInterfaceInfo": false, "java-analyzer/extractInterface": true },
|
||||
}));
|
||||
assert!(java_analyzer(&both));
|
||||
assert!(!java_analyzer(&info_only));
|
||||
assert!(!java_analyzer(&edit_only));
|
||||
assert!(!java_analyzer(&disabled));
|
||||
assert!(!java_analyzer(&ServerCaps::parse(json!({}))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn java_analysis_packages_round_trip_through_the_dialog() {
|
||||
let packages = java_packages(vec!["app".to_owned(), "".to_owned()]);
|
||||
assert_eq!(serde_json::from_str::<Value>(&packages[0]).unwrap()["displayName"], "app");
|
||||
assert_eq!(serde_json::from_str::<Value>(&packages[0]).unwrap()["isParentOfSelectedFile"], true);
|
||||
assert_eq!(serde_json::from_str::<Value>(&packages[1]).unwrap()["isParentOfSelectedFile"], false);
|
||||
assert_eq!(java_package(&json!(packages[0])).unwrap(), "app");
|
||||
assert_eq!(java_package(&json!(packages[1])).unwrap(), "");
|
||||
assert_eq!(java_package(&json!({ "displayName": "com.example" })).unwrap(), "com.example");
|
||||
assert!(java_package(&json!({})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn class_name_at_reads_type_declaration_or_file_stem() {
|
||||
let text = DocText::new(
|
||||
"package app;\n/* 😀 */ public class MainImpl {\n public void hello() {}\n}\nclass Helper {}\npublic record Point(int x) {}\nenum Color { RED }\n",
|
||||
);
|
||||
let path = Path::new("/w/src/app/MainImpl.java");
|
||||
// Line 1: `/* 😀 */ public class MainImpl {` — 😀 is 2 UTF-16 units, so MainImpl starts at col 22.
|
||||
assert_eq!(class_name_at(&text, path, Pos::new(1, 22)), "MainImpl");
|
||||
assert_eq!(class_name_at(&text, path, Pos::new(1, 26)), "MainImpl");
|
||||
assert_eq!(class_name_at(&text, path, Pos::new(1, 30)), "MainImpl");
|
||||
// Caret on a method name falls back to the file stem.
|
||||
assert_eq!(class_name_at(&text, path, Pos::new(2, 16)), "MainImpl");
|
||||
// Non-public top-level class in the same file uses its own name.
|
||||
assert_eq!(class_name_at(&text, path, Pos::new(4, 7)), "Helper");
|
||||
assert_eq!(class_name_at(&text, path, Pos::new(5, 14)), "Point");
|
||||
assert_eq!(class_name_at(&text, path, Pos::new(6, 5)), "Color");
|
||||
// A keyword suffix like `subclass` is not treated as `class`.
|
||||
let fake = DocText::new("int subclass Foo;");
|
||||
assert_eq!(class_name_at(&fake, path, Pos::new(0, 14)), "MainImpl");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn java_analysis_info_reads_handles_and_rejects_null() {
|
||||
let info: JavaInfo = serde_json::from_value(json!({
|
||||
"interfaceName": "Main",
|
||||
"members": [{
|
||||
"name": "hello",
|
||||
"typeName": "void",
|
||||
"parameters": [],
|
||||
"handleIdentifier": "hello()",
|
||||
}],
|
||||
"packages": ["app"],
|
||||
}))
|
||||
.unwrap();
|
||||
let converted = java_info_of(Some(info), "MainImpl".to_owned()).unwrap();
|
||||
// `class_name` stays the source class name so the dialog lets the user name the interface `Main`.
|
||||
assert_eq!(converted.class_name, "MainImpl");
|
||||
assert_eq!(converted.members[0].handle_identifier, "hello()");
|
||||
assert_eq!(serde_json::from_str::<Value>(&converted.packages[0]).unwrap()["displayName"], "app");
|
||||
|
||||
let err = java_info_of(None, "MainImpl".to_owned()).unwrap_err();
|
||||
assert_eq!(err.kind, ErrorKind::InvalidInput);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maps_java_analysis_problems_to_the_refactoring_ui() {
|
||||
let result: JavaResult = serde_json::from_value(json!({
|
||||
"edit": null,
|
||||
"problems": [
|
||||
{ "severity": "error", "message": "Interface already exists" },
|
||||
{ "severity": "warning", "message": "Package-private type referenced" },
|
||||
],
|
||||
}))
|
||||
.unwrap();
|
||||
let mapped = java_result_of(result, |_| ide_core::WorkspaceEdit::default());
|
||||
assert!(mapped.edit.is_none());
|
||||
assert!(mapped.confirmation.is_none());
|
||||
assert_eq!(mapped.problems.len(), 2);
|
||||
assert_eq!(mapped.problems[0].severity, ProblemSeverity::Error);
|
||||
assert_eq!(mapped.problems[0].message, "Interface already exists");
|
||||
assert_eq!(mapped.problems[1].severity, ProblemSeverity::Warning);
|
||||
assert_eq!(mapped.problems[1].message, "Package-private type referenced");
|
||||
}
|
||||
}
|
||||
@@ -10064,3 +10064,171 @@ async fn spring_bean_markers_follow_the_servers_features() {
|
||||
assert_eq!(h.mgr.spring_bean_markers(doc, Default::default()).await.unwrap(), None);
|
||||
assert!(beans.requested("java-analyzer/springBeanMarkers").is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn extract_interface_uses_java_analyzer_when_advertised() {
|
||||
let mut ja_caps = incremental_caps();
|
||||
ja_caps["positionEncoding"] = json!("utf-8");
|
||||
ja_caps["experimental"] = json!({
|
||||
"java-analyzer/extractInterfaceInfo": true,
|
||||
"java-analyzer/extractInterface": true,
|
||||
});
|
||||
let h = harness_configured("java", "java", &[("java-analyzer", ja_caps), ("jdtls", incremental_caps())], |_| {});
|
||||
// "/* 😀 */ " is 9 UTF-16 units (😀 = 2) and 11 UTF-8 bytes (😀 = 4).
|
||||
let (doc, path) =
|
||||
h.open("MainImpl.java", "package app;\n/* 😀 */ public class MainImpl {\n public void hello() {}\n}\n");
|
||||
for name in ["java-analyzer", "jdtls"] {
|
||||
h.wait_status(name, ServerStatus::Ready).await;
|
||||
}
|
||||
let (ja, jdtls) = (h.launcher.state("java-analyzer"), h.launcher.state("jdtls"));
|
||||
eventually(|| !ja.notified("textDocument/didOpen").is_empty()).await;
|
||||
|
||||
// Caret on `MainImpl`: UTF-16 col 22 -> UTF-8 byte col 24.
|
||||
let caret = Pos::new(1, 22);
|
||||
ja.respond(
|
||||
"java-analyzer/extractInterfaceInfo",
|
||||
json!({
|
||||
"interfaceName": "Main",
|
||||
"members": [{
|
||||
"name": "hello",
|
||||
"typeName": "void",
|
||||
"parameters": [],
|
||||
"handleIdentifier": "hello()",
|
||||
}],
|
||||
"packages": ["app"],
|
||||
}),
|
||||
);
|
||||
let info = h.mgr.extract_interface_info(doc, caret, Default::default()).await.unwrap();
|
||||
assert_eq!(info.class_name, "MainImpl");
|
||||
assert_eq!(info.members.len(), 1);
|
||||
assert_eq!(info.members[0].handle_identifier, "hello()");
|
||||
assert_eq!(
|
||||
ja.requested("java-analyzer/extractInterfaceInfo")[0],
|
||||
json!({ "textDocument": { "uri": uri_of(&path) }, "position": { "line": 1, "character": 24 } })
|
||||
);
|
||||
assert!(jdtls.requested("java/checkExtractInterfaceStatus").is_empty());
|
||||
|
||||
// Null info (e.g. caret outside a class name) reports InvalidInput rather than a protocol error.
|
||||
ja.respond("java-analyzer/extractInterfaceInfo", Value::Null);
|
||||
let err = h.mgr.extract_interface_info(doc, Pos::new(0, 0), Default::default()).await.unwrap_err();
|
||||
assert_eq!(err.kind, ide_core::error::ErrorKind::InvalidInput);
|
||||
|
||||
// Edit request sends handles + recovered package and converts CreateFile + TextDocumentEdit.
|
||||
let iface_path = path.with_file_name("Main.java");
|
||||
let iface_uri = uri_of(&iface_path);
|
||||
ja.respond(
|
||||
"java-analyzer/extractInterface",
|
||||
json!({
|
||||
"edit": {
|
||||
"documentChanges": [
|
||||
{ "kind": "create", "uri": iface_uri },
|
||||
{
|
||||
"textDocument": { "uri": iface_uri, "version": null },
|
||||
"edits": [{
|
||||
"range": { "start": { "line": 0, "character": 0 }, "end": { "line": 0, "character": 0 } },
|
||||
"newText": "package app;\n\npublic interface Main {\n void hello();\n}\n",
|
||||
}],
|
||||
},
|
||||
{
|
||||
"textDocument": { "uri": uri_of(&path), "version": null },
|
||||
"edits": [{
|
||||
"range": { "start": { "line": 1, "character": 32 }, "end": { "line": 1, "character": 32 } },
|
||||
"newText": " implements Main",
|
||||
}],
|
||||
},
|
||||
],
|
||||
},
|
||||
"problems": [],
|
||||
}),
|
||||
);
|
||||
let pkg: Value = serde_json::from_str(&info.packages[0]).unwrap();
|
||||
let res = h
|
||||
.mgr
|
||||
.extract_interface(doc, caret, vec!["hello()".into()], "Main".into(), pkg, None, Default::default())
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(res.problems.is_empty());
|
||||
assert!(res.confirmation.is_none());
|
||||
let edit = res.edit.expect("expected workspace edit");
|
||||
assert!(matches!(&edit.files[0], FileEdit::Create { path: p, .. } if p.as_ref() == iface_path.as_path()));
|
||||
// UTF-8 byte col 32 on line 1 (`/* 😀 */ public class MainImpl|`) converts back to UTF-16 col 30.
|
||||
assert!(matches!(
|
||||
&edit.files[2],
|
||||
FileEdit::Edit { edits, .. } if edits[0].range == rng(1, 30, 1, 30) && edits[0].new_text == " implements Main"
|
||||
));
|
||||
assert_eq!(
|
||||
ja.requested("java-analyzer/extractInterface")[0],
|
||||
json!({
|
||||
"textDocument": { "uri": uri_of(&path) },
|
||||
"position": { "line": 1, "character": 24 },
|
||||
"name": "Main",
|
||||
"package": "app",
|
||||
"members": ["hello()"],
|
||||
})
|
||||
);
|
||||
assert!(jdtls.requested("java/getRefactorEdit").is_empty());
|
||||
|
||||
// Pre-cancelled token returns Cancelled without falling back to jdtls.
|
||||
let cancel = CancellationToken::new();
|
||||
cancel.cancel();
|
||||
let err = h.mgr.extract_interface_info(doc, caret, cancel).await.unwrap_err();
|
||||
assert_eq!(err.kind, ide_core::error::ErrorKind::Cancelled);
|
||||
assert!(jdtls.requested("java/checkExtractInterfaceStatus").is_empty());
|
||||
|
||||
h.mgr.shutdown_all().await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn extract_interface_falls_back_to_jdtls_without_capability() {
|
||||
// Older java-analyzer without the experimental capability: route to jdtls instead.
|
||||
let h = harness_configured(
|
||||
"java",
|
||||
"java",
|
||||
&[("java-analyzer", incremental_caps()), ("jdtls", incremental_caps())],
|
||||
|_| {},
|
||||
);
|
||||
let (doc, path) = h.open("Shape.java", "package a;\npublic class Shape { public double area() { return 0; } }\n");
|
||||
for name in ["java-analyzer", "jdtls"] {
|
||||
h.wait_status(name, ServerStatus::Ready).await;
|
||||
}
|
||||
let (ja, jdtls) = (h.launcher.state("java-analyzer"), h.launcher.state("jdtls"));
|
||||
eventually(|| !jdtls.notified("textDocument/didOpen").is_empty()).await;
|
||||
|
||||
jdtls.respond(
|
||||
"java/checkExtractInterfaceStatus",
|
||||
json!({
|
||||
"subTypeName": "Shape",
|
||||
"members": [{ "name": "area", "typeName": "double", "parameters": [], "handleIdentifier": "h1" }],
|
||||
"destinationResponse": { "destinations": [{ "displayName": "a", "isParentOfSelectedFile": true }] },
|
||||
}),
|
||||
);
|
||||
let info = h.mgr.extract_interface_info(doc, Pos::new(1, 13), Default::default()).await.unwrap();
|
||||
assert_eq!(info.class_name, "Shape");
|
||||
assert_eq!(jdtls.requested("java/checkExtractInterfaceStatus").len(), 1);
|
||||
assert!(ja.requested("java-analyzer/extractInterfaceInfo").is_empty());
|
||||
|
||||
jdtls.respond(
|
||||
"java/getRefactorEdit",
|
||||
json!({
|
||||
"edit": { "changes": { uri_of(&path): [] } },
|
||||
}),
|
||||
);
|
||||
let pkg: Value = serde_json::from_str(&info.packages[0]).unwrap();
|
||||
let res = h
|
||||
.mgr
|
||||
.extract_interface(doc, Pos::new(1, 13), vec!["h1".into()], "HasArea".into(), pkg, None, Default::default())
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(res.edit.is_some());
|
||||
assert_eq!(jdtls.requested("java/getRefactorEdit").len(), 1);
|
||||
assert!(ja.requested("java-analyzer/extractInterface").is_empty());
|
||||
h.mgr.shutdown_all().await;
|
||||
|
||||
// Without jdtls and without the capability, reports Unavailable.
|
||||
let h = harness_configured("java", "java", &[("java-analyzer", incremental_caps())], |_| {});
|
||||
let (doc, _) = h.open("Shape.java", "package a;\npublic class Shape {}\n");
|
||||
h.wait_status("java-analyzer", ServerStatus::Ready).await;
|
||||
let err = h.mgr.extract_interface_info(doc, Pos::new(1, 13), Default::default()).await.unwrap_err();
|
||||
assert_eq!(err.kind, ide_core::error::ErrorKind::Unavailable);
|
||||
h.mgr.shutdown_all().await;
|
||||
}
|
||||
@@ -100,6 +100,51 @@ pub trait HostApi: Send + Sync {
|
||||
) -> Result<crate::PluginDatabaseTableSchema, HostError> {
|
||||
Err(HostError::Invalid("Database schema access is unavailable on this host".into()))
|
||||
}
|
||||
/// Lists already-connected project sources; database.schema was checked (API 1.21).
|
||||
fn database_connected_sources(
|
||||
&self,
|
||||
_root: &Path,
|
||||
_client: Option<&str>,
|
||||
) -> Result<Vec<crate::PluginConnectedDataSource>, HostError> {
|
||||
Err(HostError::Invalid("Database schema access is unavailable on this host".into()))
|
||||
}
|
||||
/// Lists schemas of an already-connected project source; database.schema was checked (API 1.21).
|
||||
fn database_list_schemas(
|
||||
&self,
|
||||
_root: &Path,
|
||||
_client: Option<&str>,
|
||||
_source_id: &str,
|
||||
_cancel: &CancellationToken,
|
||||
_timeout: Duration,
|
||||
) -> Result<Vec<String>, HostError> {
|
||||
Err(HostError::Invalid("Database schema access is unavailable on this host".into()))
|
||||
}
|
||||
/// Lists tables and views in a schema of a connected project source; database.schema was checked (API 1.21).
|
||||
fn database_list_tables(
|
||||
&self,
|
||||
_root: &Path,
|
||||
_client: Option<&str>,
|
||||
_source_id: &str,
|
||||
_schema: &str,
|
||||
_cancel: &CancellationToken,
|
||||
_timeout: Duration,
|
||||
) -> Result<Vec<crate::PluginDatabaseTableSummary>, HostError> {
|
||||
Err(HostError::Invalid("Database schema access is unavailable on this host".into()))
|
||||
}
|
||||
/// Executes SQL against an already-connected project source; database.query was checked (API 1.21).
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn database_execute_query(
|
||||
&self,
|
||||
_root: &Path,
|
||||
_client: Option<&str>,
|
||||
_source_id: &str,
|
||||
_sql: &str,
|
||||
_max_rows: Option<u32>,
|
||||
_cancel: &CancellationToken,
|
||||
_timeout: Duration,
|
||||
) -> Result<crate::PluginDatabaseQueryResult, HostError> {
|
||||
Err(HostError::Invalid("Database query execution is unavailable on this host".into()))
|
||||
}
|
||||
/// Creates/replaces this plugin's non-secret project connection settings.
|
||||
fn database_upsert(&self, root: &Path, source: crate::PluginDataSource) -> Result<(), HostError>;
|
||||
/// Removes only an owned data source and its credentials.
|
||||
|
||||
@@ -1307,3 +1307,37 @@ pub struct PluginDatabaseTableSchema {
|
||||
pub indexes: Vec<PluginDatabaseIndex>,
|
||||
pub foreign_keys: Vec<PluginDatabaseForeignKey>,
|
||||
}
|
||||
/// Non-secret identity of an already-connected project data source (API 1.21).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PluginConnectedDataSource {
|
||||
pub source_id: String,
|
||||
pub name: String,
|
||||
pub driver: String,
|
||||
pub database: Option<String>,
|
||||
}
|
||||
/// Summary of a table or view in a connected schema (API 1.21).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PluginDatabaseTableSummary {
|
||||
pub name: String,
|
||||
pub kind: String,
|
||||
pub comment: Option<String>,
|
||||
}
|
||||
/// Column metadata of a query result (API 1.21).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PluginDatabaseQueryColumn {
|
||||
pub name: String,
|
||||
pub type_name: String,
|
||||
}
|
||||
/// Bounded result of executing a SQL statement on a connected source (API 1.21).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PluginDatabaseQueryResult {
|
||||
pub columns: Vec<PluginDatabaseQueryColumn>,
|
||||
pub rows: Vec<Vec<Option<String>>>,
|
||||
pub affected: Option<u64>,
|
||||
pub has_more: bool,
|
||||
pub elapsed_ms: u64,
|
||||
}
|
||||
@@ -3491,6 +3491,114 @@ impl bindings::openidea::plugin::database::Host for StoreData {
|
||||
})
|
||||
.map_err(to_wit))
|
||||
}
|
||||
fn connected_sources(
|
||||
&mut self,
|
||||
project: Resource<ProjectRes>,
|
||||
) -> Fallible<Vec<bindings::openidea::plugin::database::ConnectedSource>> {
|
||||
if let Err(e) = self.require(Capability::DatabaseSchema) {
|
||||
return Ok(Err(e));
|
||||
}
|
||||
let root = self.table.get(&project)?.root.clone();
|
||||
let result = self.host.database_connected_sources(&root, self.client());
|
||||
if result.is_err() {
|
||||
self.grant_io_error_grace();
|
||||
}
|
||||
use bindings::openidea::plugin::database as db;
|
||||
Ok(result
|
||||
.map(|sources| {
|
||||
sources
|
||||
.into_iter()
|
||||
.map(|s| db::ConnectedSource {
|
||||
source_id: s.source_id,
|
||||
name: s.name,
|
||||
driver: s.driver,
|
||||
database: s.database,
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.map_err(to_wit))
|
||||
}
|
||||
fn list_schemas(&mut self, project: Resource<ProjectRes>, source_id: String) -> Fallible<Vec<String>> {
|
||||
if let Err(e) = self.require(Capability::DatabaseSchema) {
|
||||
return Ok(Err(e));
|
||||
}
|
||||
let root = self.table.get(&project)?.root.clone();
|
||||
let result =
|
||||
self.host.database_list_schemas(&root, self.client(), &source_id, &self.cancel.token(), self.io_timeout());
|
||||
if result.is_err() {
|
||||
self.grant_io_error_grace();
|
||||
}
|
||||
Ok(result.map_err(to_wit))
|
||||
}
|
||||
fn list_tables(
|
||||
&mut self,
|
||||
project: Resource<ProjectRes>,
|
||||
source_id: String,
|
||||
schema: String,
|
||||
) -> Fallible<Vec<bindings::openidea::plugin::database::TableSummary>> {
|
||||
if let Err(e) = self.require(Capability::DatabaseSchema) {
|
||||
return Ok(Err(e));
|
||||
}
|
||||
let root = self.table.get(&project)?.root.clone();
|
||||
let result = self.host.database_list_tables(
|
||||
&root,
|
||||
self.client(),
|
||||
&source_id,
|
||||
&schema,
|
||||
&self.cancel.token(),
|
||||
self.io_timeout(),
|
||||
);
|
||||
if result.is_err() {
|
||||
self.grant_io_error_grace();
|
||||
}
|
||||
use bindings::openidea::plugin::database as db;
|
||||
Ok(result
|
||||
.map(|tables| {
|
||||
tables
|
||||
.into_iter()
|
||||
.map(|t| db::TableSummary { name: t.name, kind: t.kind, comment: t.comment })
|
||||
.collect()
|
||||
})
|
||||
.map_err(to_wit))
|
||||
}
|
||||
fn execute_query(
|
||||
&mut self,
|
||||
project: Resource<ProjectRes>,
|
||||
source_id: String,
|
||||
sql: String,
|
||||
max_rows: Option<u32>,
|
||||
) -> Fallible<bindings::openidea::plugin::database::QueryResult> {
|
||||
if let Err(e) = self.require(Capability::DatabaseQuery) {
|
||||
return Ok(Err(e));
|
||||
}
|
||||
let root = self.table.get(&project)?.root.clone();
|
||||
let result = self.host.database_execute_query(
|
||||
&root,
|
||||
self.client(),
|
||||
&source_id,
|
||||
&sql,
|
||||
max_rows,
|
||||
&self.cancel.token(),
|
||||
self.io_timeout(),
|
||||
);
|
||||
if result.is_err() {
|
||||
self.grant_io_error_grace();
|
||||
}
|
||||
use bindings::openidea::plugin::database as db;
|
||||
Ok(result
|
||||
.map(|r| db::QueryResult {
|
||||
columns: r
|
||||
.columns
|
||||
.into_iter()
|
||||
.map(|c| db::QueryColumn { name: c.name, type_name: c.type_name })
|
||||
.collect(),
|
||||
rows: r.rows,
|
||||
affected: r.affected,
|
||||
has_more: r.has_more,
|
||||
elapsed_ms: r.elapsed_ms,
|
||||
})
|
||||
.map_err(to_wit))
|
||||
}
|
||||
fn upsert_source(
|
||||
&mut self,
|
||||
project: Resource<ProjectRes>,
|
||||
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
8fec8f3f93d13050a7d7579ba6e29baf2b8654777971f59087f34f2540fdf23d
|
||||
fbd767ccf69c37807aa8f535197ab9fac47f809ef887ab9fd99c0b2886201ae1
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
9046ec47087a78f8a99f9f57b04178df91c31c7ea2dedf7610ee9ebfb5a2fb9f
|
||||
583b5ee3f495851ca14c378a3a4fe4cfd92be772e5f33a383d4f3b9f935f4b7e
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
69644d5a8240e9407889df1b48400b1c89c6a9e15873dd47dca3015aceaf580b
|
||||
a29fb8d12bc4bb7fdba146706ce941ecfce1e4ddecdbbe1672aac88b1adfb4da
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
7556cd36ed5769f3961abc67a2906c50e8b639f98a7ce631b8b7589c96f60291
|
||||
f99c40e69fba8d835f578dc6d1dc2a078ad774d881ae454e3703d5d150cf2c8d
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
1e83a86f4a3f9ec70a8489e9d172f2a3829d2fa8546ca9c93deec9c05f899483
|
||||
c732a0688e0cfcd71ce8471c4d929e5e5496461e44ef705a2bf468fad62b4ae8
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
ebeb0be05062276fd9b24dae57c72fa58bc35ce054b4639687d4c3280c14300e
|
||||
ee71ad8f7a4c3786c8221188fc117304ac68db6d567093661d4056d83e45cc99
|
||||
@@ -1,12 +1,12 @@
|
||||
id = "test.data-tools"
|
||||
name = "Data tools fixture"
|
||||
version = "0.1.0"
|
||||
engines.openidea = "^1.20"
|
||||
engines.openidea = "^1.21"
|
||||
wasm = "dist/plugin.wasm"
|
||||
activation = ["on-command:*"]
|
||||
[capabilities]
|
||||
required = ["project.read"]
|
||||
optional = ["database.sources", "database.schema"]
|
||||
optional = ["database.sources", "database.schema", "database.query"]
|
||||
|
||||
[[contributes.commands]]
|
||||
id = "upsert"
|
||||
@@ -71,6 +71,22 @@ destructive = false
|
||||
id = "table-schema"
|
||||
title = "Read table schema"
|
||||
|
||||
[[contributes.commands]]
|
||||
id = "connected-sources"
|
||||
title = "Connected sources"
|
||||
|
||||
[[contributes.commands]]
|
||||
id = "list-schemas"
|
||||
title = "List schemas"
|
||||
|
||||
[[contributes.commands]]
|
||||
id = "list-tables"
|
||||
title = "List tables"
|
||||
|
||||
[[contributes.commands]]
|
||||
id = "execute-query"
|
||||
title = "Execute query"
|
||||
|
||||
[[contributes.menus]]
|
||||
menu = "database.table.context"
|
||||
command = "table-schema"
|
||||
@@ -25,6 +25,26 @@ impl Plugin for DataTools {
|
||||
return Ok(Some(serde_json::to_string(&schema).unwrap()));
|
||||
}
|
||||
"sources" => return Ok(Some(serde_json::to_string(&p.data_sources()?).unwrap())),
|
||||
"connected-sources" => return Ok(Some(serde_json::to_string(&p.connected_data_sources()?).unwrap())),
|
||||
"list-schemas" => {
|
||||
let source_id = arg.ok_or("sourceId required")?;
|
||||
return Ok(Some(serde_json::to_string(&p.database_schemas(source_id)?).unwrap()));
|
||||
}
|
||||
"list-tables" => {
|
||||
let value: serde_json::Value = serde_json::from_str(arg.ok_or("sourceId and schema required")?)
|
||||
.map_err(|e| Error::Invalid(e.to_string()))?;
|
||||
let source_id = value["sourceId"].as_str().ok_or("sourceId required")?;
|
||||
let schema = value["schema"].as_str().ok_or("schema required")?;
|
||||
return Ok(Some(serde_json::to_string(&p.database_tables(source_id, schema)?).unwrap()));
|
||||
}
|
||||
"execute-query" => {
|
||||
let value: serde_json::Value = serde_json::from_str(arg.ok_or("query request required")?)
|
||||
.map_err(|e| Error::Invalid(e.to_string()))?;
|
||||
let source_id = value["sourceId"].as_str().ok_or("sourceId required")?;
|
||||
let sql = value["sql"].as_str().ok_or("sql required")?;
|
||||
let max_rows = value["maxRows"].as_u64().map(|n| n as u32);
|
||||
return Ok(Some(serde_json::to_string(&p.database_execute_query(source_id, sql, max_rows)?).unwrap()));
|
||||
}
|
||||
"credential" => p.set_data_source_credential("local", arg.unwrap_or("secret"))?,
|
||||
"connect" => p.connect_data_source(arg.unwrap_or("local"))?,
|
||||
_ => return Err(Error::NotFound(id.into())),
|
||||
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
2a1f38092bb34e9864e9607a08521f8cf7dc74f24ad4bea4c4f7d021b41b34f5
|
||||
33020cf1117fc910e2984a2bd0110924cf5ffdf24ae015bf191762993c06c532
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
0d64b659501e637eac7dc586d2e6bc7db09c7c6ea369dc8b3c6db7dc9b006787
|
||||
9923493b942447f729a8568de02e3d02c3d59b3d7468f569a1ae978adaa3176d
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
f89bc44615d6b340046d9247f0f328a5d22a2ffafdfb34ce9e6356fc6d4b403a
|
||||
d12f681411fda1fed05e537f291705a3ce26faa009044fdf9d0a01b964fc0056
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
008368cbac33887301d5bea31f1f090e0ba785a96ef3edc213da54299686d26d
|
||||
893ce9fe2bb20cd5adc34794ad3ddc1c8779631fecf4d14dfa51290f55eb0377
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
bd66e872b60c7cf3919381257654f21407f86d47d84d884c7e8a357f9ad1b169
|
||||
c5ec51674a2c7556ffd65ac856dbe68e024a6d9361348653b6ff32d31dcf3ff8
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
b4b5b2286bc842d93aaaa49ec13579c21b1c3a3d0d7d44fa6e8e1b1a99e2cb8b
|
||||
9212ac37ebb4e2a4c09afccec3d29ffd4ad6fb77a5444b108dc5381a66b3f3fd
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
7b84a518235f863e893e244c84d3d782049465a3176eb27ea27779c7cdd57c59
|
||||
a0c79f2e2798894eaea06ccbf7c1a80cfb269817563273ede8ade9903b310f78
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
b07a8f999a1c34cf1e437641c52ac9070c62ee933fe615ce490bc74e9eda5d44
|
||||
d2c95eb484ec574031ea01e77e32fca49f5dca0b419a2ed9d6556c3db6810d4c
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
abf565f7c718c6647a5a170131de1abc5e16345a759060640bcdfe732921a9e7
|
||||
82bdefebd3747dcda62acd8e9a11eb9e8ef137fddb0c29c5011c475cb184530b
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
2606ddcd55d3659ca29f2db12bd239124eb580fd96e273e8eacdc1df45be9275
|
||||
5c383892b3c7345d2d230da7c4e5b3f1e1e1899491e0cf3df8ce3b02c41b5154
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
2ec881b3b984095389583c115de6a60dff6c6fef6888682b5113237c9459167e
|
||||
11287c6ce9ad5b964ad730ccfd2ee846c6cc0a671b83f86daad78891e2463aba
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
a7712d7ae6dc79713432a62544571ed25a0f752bdf8cc8de01701958e3853ff7
|
||||
a912aed6c1a64745240d16e6b8e69c7966023d7001ca712ccad32b8d1918e3df
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
0631360ca5b16015bc94cd461e562f37b24e982ac5b6dd6fa78ed87fd4ae0c54
|
||||
76d52287de2178c4f7f19286a6fe387faf9c33d4d84e19dc6d447ad42b858256
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
eecb2014a22c74ebfe5a33ca8ad9ceeef139663f07f0f1216d0f777ac3f3fae2
|
||||
87f6d2121aec400c280cc4c0d1b1cca762c7bad8432b833d0ee2b5b17002c733
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
8f9c04d37ee46cfdcd63fe101b9c84937ad1ea52b8c8051aea73c9e9c5fb9735
|
||||
ed2c0bb9f9f91744b49e3e22240df3bb3a08eda6473013bf16e82946ac113a58
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
cfd459348ed64a64e86660c25db1163ce16a2f0bc9c74fda721f26980d0c16f2
|
||||
e9673042b2e02fa544fdcc1f80a80b05765f3b9d30055668ad537ef59f19a2e2
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
b34cea4bfdafae31c609581a295e20556be3b16b7d3a2a09b3bff0b059d63455
|
||||
bc3e3af1b33eb2dab9d05caddb0c4f60205dbf4513d2afb39034f20e1364c471
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
1e44c2bf968fec294827f666f522e08db6b899431a02b53ca61a1a9aa9c77cd0
|
||||
e19f1b0b2f46fed4ff0069e75fdc66a47cc231dc08c875076ffe4e90177a7228
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
cc2ecd77d2f7521c92496e659f8cd9e461d175d3acaf0740771ec8e3157b844a
|
||||
57cf79449c2e030badd366fad9ba95d38e4988ccb7ff6d597eba250ded2722ff
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
d77719fdf8df15baedfc6de0e9e1b3a14344405892468eda0edba244a63bf8d9
|
||||
bf9bff2aab8b32205131fdc961d084a8ca4b5553bfb52b9690cdb51c2bff43ed
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
55424888269455182c05a6dbd781460fbe51fec3d26116fd3026d593317a07bb
|
||||
ec5994ac7a65203eb036af1ff58275ca543295b41d60644d48b00461a99f9c63
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
30e6598f5d9ab7aa3fb0a26b3e382fc9451c06b8c685c82a7cbf890a55ce3c05
|
||||
cf48e6cd63b356a864e2b89beb2819540e6351854a70c0b258ba5170932c9749
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
7e35c37420037f87f669ad2ff2f3ad6133f36ff7bfcef0a2724fbcda3b036133
|
||||
f61c925836203778feabab5df85ed96a36b4d9a1fca76144e216c9bdb3b80f76
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
08a7c7b6cd212506d3580114f9b57f14cd99e9db4673ee7cb048971815f55295
|
||||
b576ff8d2e7ea172b0fa9f4a666d5f055add50cd2dc522ccf9395768b398e5e2
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
2b0bb4b5932d3c337376a6090bfd5c5af5de7bd42831c419fad9d373c5932191
|
||||
53bb516f95537947d936f5c35598ea0f66c77611058131f7a6518f7c00540e0e
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
056274122bb131ebbfad8adf21600109dec13b3e2b4f46d8f81f0d536646c960
|
||||
83bda60bbf1efbe3912bbe46f4ba25d7ab44f3c85ce41d5b737a840003f58e02
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
aaa370a35257b58871dab1617b452ac2b3cb60a82fd48a7ce94958b69f6791d6
|
||||
eb6887c297f9b5657ceefcbaa57c09fc965d80e48744a67fdbda2e227d24696f
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
fc1177893ee7d40a93463c39711a5d73adf8d8fde954711203aacd57135dff86
|
||||
ecb1a420edc414fe8a18c295f3017b82a5d5161d8a1cfe490a07772cffbaaa6a
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
f09129a6e9ffef541f4883f1667cd6da2a6597ad1b1531a4890766501d51cb07
|
||||
0d0a891f6983ed5c78a77b5349d3e52dbb4494887b9f9b06ac3988e60327e337
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
b1689696bab3922f569a85d857fd78f6f5c8771572cfd73b369c483ef7e67547
|
||||
dec10c81831c059f19d6ef300e2021023f33f1f1df6735d81759fa0ed1cae3aa
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
0f4b225b0311f59cb05276d911e6fff43ce91fd71c4baa1e121b0cb81c99cde5
|
||||
895fb5eb77f553691dd2d99393fa28f61aba371e98487cbbdc47829a839567db
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
6839e5a80f65da81b0e16ca5e86169dd1d3649ba1b1f54c1f01896f19abe2c8f
|
||||
53d83ddf8eae9601576fd59c83999f5da7e5b6317ce84de422eea4ace2408262
|
||||
Бінарний файл не відображається.
Loaded 100 of 250 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Заблокувати користувача