дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-05 09:41:34 +02:00
Terminal output (native PTY and SSH channels) went through an unbounded channel, so a slow UI or link let a chatty command buffer its whole output in memory. A 16 MiB byte budget now gates the terminal producers (blocking past the high-water mark; remote feeds use block_in_place), and DAP's outgoing queue is bounded at 256 bodies. DAP's incoming queue stays unbounded so a handler awaiting a response behind an event burst still gets it; covered by a_handler_awaiting_a_request_still_gets_its_response_behind_an_event_burst. No output is dropped. Co-authored-by: akbar1214 <[email protected]>
425 рядки
17 KiB
Rust
425 рядки
17 KiB
Rust
//! One DAP wire connection: `Content-Length` framing (shared with LSP via
|
|
//! `ide_jsonrpc::framing`), sequence numbers, request/response correlation,
|
|
//! and delivery of events and reverse requests to the session task.
|
|
//!
|
|
//! DAP is not JSON-RPC: every message is `{seq, type, ...}` where `type` is
|
|
//! `request` (`command`, `arguments`), `response` (`request_seq`, `success`,
|
|
//! `command`, `message`, `body`) or `event` (`event`, `body`).
|
|
|
|
use ide_jsonrpc::framing;
|
|
use parking_lot::Mutex;
|
|
use serde_json::{Value, json};
|
|
use std::collections::HashMap;
|
|
use std::sync::Arc;
|
|
use std::sync::atomic::{AtomicBool, AtomicI64, Ordering};
|
|
use std::time::Duration;
|
|
use tokio::io::{AsyncRead, AsyncWrite, BufReader};
|
|
use tokio::sync::{mpsc, oneshot};
|
|
|
|
#[derive(Debug, Clone)]
|
|
pub enum DapError {
|
|
/// The adapter answered `success: false`.
|
|
Failed {
|
|
command: String,
|
|
message: String,
|
|
},
|
|
Closed,
|
|
Timeout(String),
|
|
Protocol(String),
|
|
}
|
|
|
|
impl std::fmt::Display for DapError {
|
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
match self {
|
|
Self::Failed { command, message } => write!(f, "{command} failed: {message}"),
|
|
Self::Closed => f.write_str("debug adapter connection closed"),
|
|
Self::Timeout(command) => write!(f, "debug adapter did not answer `{command}` in time"),
|
|
Self::Protocol(m) => write!(f, "invalid debug adapter message: {m}"),
|
|
}
|
|
}
|
|
}
|
|
|
|
impl From<DapError> for ide_core::IdeError {
|
|
fn from(e: DapError) -> Self {
|
|
use ide_core::error::ErrorKind;
|
|
let kind = match e {
|
|
DapError::Closed => ErrorKind::Unavailable,
|
|
DapError::Failed { .. } => ErrorKind::InvalidInput,
|
|
DapError::Timeout(_) | DapError::Protocol(_) => ErrorKind::Protocol,
|
|
};
|
|
ide_core::IdeError::new(kind, e.to_string())
|
|
}
|
|
}
|
|
|
|
/// Adapter-initiated traffic, delivered in arrival order.
|
|
#[derive(Debug)]
|
|
pub enum Incoming {
|
|
Event {
|
|
event: String,
|
|
body: Value,
|
|
},
|
|
/// Reverse request (`runInTerminal`, `startDebugging`); answer with [`Connection::respond`].
|
|
Request {
|
|
seq: i64,
|
|
command: String,
|
|
arguments: Value,
|
|
},
|
|
/// The transport is gone; always the last message.
|
|
Closed,
|
|
}
|
|
|
|
/// Bounded outgoing queue: an adapter that stops reading its input holds back `send`
|
|
/// instead of the IDE accumulating unbounded messages. The incoming queue stays unbounded:
|
|
/// the event loop awaits requests while handling events (`stopped` restores breakpoints), so
|
|
/// a reader parked on a full queue would never read the response that loop waits for.
|
|
const OUT_CAPACITY: usize = 256;
|
|
|
|
type Pending = HashMap<i64, (String, oneshot::Sender<Result<Value, DapError>>)>;
|
|
|
|
struct Inner {
|
|
out: mpsc::Sender<Vec<u8>>,
|
|
pending: Mutex<Pending>,
|
|
seq: AtomicI64,
|
|
closed: AtomicBool,
|
|
cancel: ide_core::CancellationToken,
|
|
}
|
|
|
|
impl Inner {
|
|
fn close(&self) {
|
|
self.closed.store(true, Ordering::Release);
|
|
for (_, (_, tx)) in std::mem::take(&mut *self.pending.lock()) {
|
|
let _ = tx.send(Err(DapError::Closed));
|
|
}
|
|
}
|
|
}
|
|
|
|
/// A connected adapter. Cloning shares the connection.
|
|
#[derive(Clone)]
|
|
pub struct Connection {
|
|
inner: Arc<Inner>,
|
|
}
|
|
|
|
impl Connection {
|
|
/// Starts reader/writer tasks over `reader`/`writer`. Must be called inside a Tokio runtime.
|
|
pub fn start<R, W>(reader: R, writer: W) -> (Self, mpsc::UnboundedReceiver<Incoming>)
|
|
where
|
|
R: AsyncRead + Unpin + Send + 'static,
|
|
W: AsyncWrite + Unpin + Send + 'static,
|
|
{
|
|
Self::start_with_output(reader, writer, Box::new(|_| {}))
|
|
}
|
|
|
|
/// [`start`](Self::start) that hands lines outside the protocol (an adapter's
|
|
/// own output on stdout, decoded) to `on_output`.
|
|
pub fn start_with_output<R, W>(
|
|
reader: R,
|
|
mut writer: W,
|
|
on_output: Box<dyn Fn(String) + Send + Sync>,
|
|
) -> (Self, mpsc::UnboundedReceiver<Incoming>)
|
|
where
|
|
R: AsyncRead + Unpin + Send + 'static,
|
|
W: AsyncWrite + Unpin + Send + 'static,
|
|
{
|
|
let (out_tx, mut out_rx) = mpsc::channel::<Vec<u8>>(OUT_CAPACITY);
|
|
let (in_tx, in_rx) = mpsc::unbounded_channel();
|
|
let inner = Arc::new(Inner {
|
|
out: out_tx,
|
|
pending: Mutex::new(HashMap::new()),
|
|
seq: AtomicI64::new(1),
|
|
closed: false.into(),
|
|
cancel: ide_core::CancellationToken::new(),
|
|
});
|
|
|
|
let weak = Arc::downgrade(&inner);
|
|
let cancel = inner.cancel.clone();
|
|
tokio::spawn(async move {
|
|
loop {
|
|
let body = tokio::select! {
|
|
body = out_rx.recv() => body,
|
|
_ = cancel.cancelled() => None,
|
|
};
|
|
let Some(body) = body else { break };
|
|
if let Err(e) = framing::write_message(&mut writer, &body).await {
|
|
tracing::debug!("dap write failed: {e}");
|
|
if let Some(inner) = weak.upgrade() {
|
|
inner.close();
|
|
}
|
|
break;
|
|
}
|
|
}
|
|
let _ = tokio::io::AsyncWriteExt::shutdown(&mut writer).await;
|
|
});
|
|
|
|
let reader_inner = inner.clone();
|
|
tokio::spawn(async move {
|
|
let mut reader = BufReader::new(reader);
|
|
let mut noise = |line: &[u8]| {
|
|
let text = ide_jsonrpc::output::decode(line);
|
|
tracing::warn!("dap: output outside the protocol: {text}");
|
|
on_output(text);
|
|
};
|
|
loop {
|
|
let msg = tokio::select! {
|
|
msg = framing::read_message_or_noise(&mut reader, &mut noise) => msg,
|
|
_ = reader_inner.cancel.cancelled() => break,
|
|
};
|
|
match msg {
|
|
Ok(Some(body)) => dispatch(&reader_inner, &in_tx, &body),
|
|
Ok(None) => break,
|
|
Err(e) => {
|
|
tracing::warn!("dap read failed: {e}");
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
reader_inner.close();
|
|
let _ = in_tx.send(Incoming::Closed);
|
|
});
|
|
|
|
(Self { inner }, in_rx)
|
|
}
|
|
|
|
/// Drops the transport; pending requests fail and the incoming stream ends.
|
|
pub fn close(&self) {
|
|
self.inner.close();
|
|
self.inner.cancel.cancel();
|
|
}
|
|
|
|
pub fn is_closed(&self) -> bool {
|
|
self.inner.closed.load(Ordering::Acquire)
|
|
}
|
|
|
|
async fn send(&self, value: &Value) -> Result<(), DapError> {
|
|
if self.is_closed() {
|
|
return Err(DapError::Closed);
|
|
}
|
|
let body = serde_json::to_vec(value).map_err(|e| DapError::Protocol(e.to_string()))?;
|
|
tracing::trace!(target: "ide_dap::wire", "--> {}", String::from_utf8_lossy(&body));
|
|
self.inner.out.send(body).await.map_err(|_| DapError::Closed)
|
|
}
|
|
|
|
/// Sends a request and returns a receiver for its response body, without waiting.
|
|
pub async fn send_request(
|
|
&self,
|
|
command: &str,
|
|
arguments: Value,
|
|
) -> Result<oneshot::Receiver<Result<Value, DapError>>, DapError> {
|
|
let seq = self.inner.seq.fetch_add(1, Ordering::Relaxed);
|
|
let (tx, rx) = oneshot::channel();
|
|
self.inner.pending.lock().insert(seq, (command.to_owned(), tx));
|
|
let mut msg = json!({ "seq": seq, "type": "request", "command": command });
|
|
if !arguments.is_null() {
|
|
msg["arguments"] = arguments;
|
|
}
|
|
if let Err(e) = self.send(&msg).await {
|
|
self.inner.pending.lock().remove(&seq);
|
|
return Err(e);
|
|
}
|
|
Ok(rx)
|
|
}
|
|
|
|
/// Sends a request and waits for the response body (`null` when absent).
|
|
pub async fn request(&self, command: &str, arguments: Value) -> Result<Value, DapError> {
|
|
let rx = self.send_request(command, arguments).await?;
|
|
rx.await.unwrap_or(Err(DapError::Closed))
|
|
}
|
|
|
|
pub async fn request_timeout(&self, command: &str, arguments: Value, timeout: Duration) -> Result<Value, DapError> {
|
|
match tokio::time::timeout(timeout, self.request(command, arguments)).await {
|
|
Ok(r) => r,
|
|
Err(_) => Err(DapError::Timeout(command.to_owned())),
|
|
}
|
|
}
|
|
|
|
/// Answers a reverse request.
|
|
pub async fn respond(
|
|
&self,
|
|
request_seq: i64,
|
|
command: &str,
|
|
result: Result<Value, String>,
|
|
) -> Result<(), DapError> {
|
|
let seq = self.inner.seq.fetch_add(1, Ordering::Relaxed);
|
|
let mut msg = json!({
|
|
"seq": seq,
|
|
"type": "response",
|
|
"request_seq": request_seq,
|
|
"command": command,
|
|
"success": result.is_ok(),
|
|
});
|
|
match result {
|
|
Ok(body) if !body.is_null() => msg["body"] = body,
|
|
Ok(_) => {}
|
|
Err(message) => msg["message"] = Value::String(message),
|
|
}
|
|
self.send(&msg).await
|
|
}
|
|
}
|
|
|
|
fn dispatch(inner: &Inner, incoming: &mpsc::UnboundedSender<Incoming>, body: &[u8]) {
|
|
tracing::trace!(target: "ide_dap::wire", "<-- {}", String::from_utf8_lossy(body));
|
|
let Some(msg) = parse_message(body) else { return };
|
|
match msg.get("type").and_then(Value::as_str) {
|
|
Some("response") => {
|
|
let Some(request_seq) = msg.get("request_seq").and_then(Value::as_i64) else {
|
|
tracing::warn!("dap: response without request_seq");
|
|
return;
|
|
};
|
|
let Some((command, tx)) = inner.pending.lock().remove(&request_seq) else {
|
|
tracing::debug!("dap: response for unknown request {request_seq}");
|
|
return;
|
|
};
|
|
let result = if msg.get("success").and_then(Value::as_bool).unwrap_or(false) {
|
|
Ok(msg.get("body").cloned().unwrap_or(Value::Null))
|
|
} else {
|
|
Err(DapError::Failed { command, message: error_message(&msg) })
|
|
};
|
|
let _ = tx.send(result);
|
|
}
|
|
Some("event") => {
|
|
let event = msg.get("event").and_then(Value::as_str).unwrap_or_default().to_owned();
|
|
let body = msg.get("body").cloned().unwrap_or(Value::Null);
|
|
let _ = incoming.send(Incoming::Event { event, body });
|
|
}
|
|
Some("request") => {
|
|
let seq = msg.get("seq").and_then(Value::as_i64).unwrap_or_default();
|
|
let command = msg.get("command").and_then(Value::as_str).unwrap_or_default().to_owned();
|
|
let arguments = msg.get("arguments").cloned().unwrap_or(Value::Null);
|
|
let _ = incoming.send(Incoming::Request { seq, command, arguments });
|
|
}
|
|
other => tracing::warn!("dap: unknown message type {other:?}"),
|
|
}
|
|
}
|
|
|
|
/// A message body as JSON. Some adapters pass the debuggee's output through as it was
|
|
/// written: netcoredbg on Windows embeds console output in the ANSI code page (GBK on a
|
|
/// Chinese system), which isn't valid UTF-8 and made the whole `output` event unparsable,
|
|
/// so every line with non-ASCII text went missing. Such a body is decoded like other tool
|
|
/// output (UTF-8, else the system code page) before parsing.
|
|
fn parse_message(body: &[u8]) -> Option<Value> {
|
|
let error = match serde_json::from_slice(body) {
|
|
Ok(v) => return Some(v),
|
|
Err(e) => e,
|
|
};
|
|
if std::str::from_utf8(body).is_err()
|
|
&& let Ok(v) = serde_json::from_str(&ide_core::output_encoding::decode_tool_output(body))
|
|
{
|
|
return Some(v);
|
|
}
|
|
tracing::warn!("dap: unparsable message: {error}");
|
|
None
|
|
}
|
|
|
|
/// `message`, or the formatted `body.error` (`{format, variables}`) when present.
|
|
fn error_message(msg: &Value) -> String {
|
|
if let Some(err) = msg.pointer("/body/error")
|
|
&& let Some(format) = err.get("format").and_then(Value::as_str)
|
|
{
|
|
let mut text = format.to_owned();
|
|
if let Some(vars) = err.get("variables").and_then(Value::as_object) {
|
|
for (k, v) in vars {
|
|
let v = v.as_str().map(str::to_owned).unwrap_or_else(|| v.to_string());
|
|
text = text.replace(&format!("{{{k}}}"), &v);
|
|
}
|
|
}
|
|
return text;
|
|
}
|
|
msg.get("message").and_then(Value::as_str).unwrap_or("request failed").to_owned()
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[tokio::test]
|
|
async fn a_handler_awaiting_a_request_still_gets_its_response_behind_an_event_burst() {
|
|
// The event loop handles `stopped` by sending `setBreakpoints` and awaiting the reply
|
|
// while the adapter keeps printing: the reply arrives behind thousands of events.
|
|
let (client_in, mut adapter_out) = tokio::io::duplex(64 * 1024);
|
|
let (client_out, adapter_in) = tokio::io::duplex(64 * 1024);
|
|
let (conn, mut incoming) = Connection::start(client_in, client_out);
|
|
let adapter = tokio::spawn(async move {
|
|
let event =
|
|
|seq: i64, event: &str| json!({"seq": seq, "type": "event", "event": event, "body": {"output": "x"}});
|
|
framing::write_message(&mut adapter_out, event(0, "stopped").to_string().as_bytes()).await.unwrap();
|
|
for i in 1..=5000 {
|
|
framing::write_message(&mut adapter_out, event(i, "output").to_string().as_bytes()).await.unwrap();
|
|
}
|
|
let mut requests = BufReader::new(adapter_in);
|
|
let request = framing::read_message(&mut requests).await.unwrap().unwrap();
|
|
let request: Value = serde_json::from_slice(&request).unwrap();
|
|
let response = json!({"seq": 5001, "type": "response", "request_seq": request["seq"], "success": true, "command": request["command"], "body": {"breakpoints": []}});
|
|
framing::write_message(&mut adapter_out, response.to_string().as_bytes()).await.unwrap();
|
|
adapter_out
|
|
});
|
|
let Some(Incoming::Event { event, .. }) = incoming.recv().await else { panic!("no event") };
|
|
assert_eq!(event, "stopped");
|
|
let reply = tokio::time::timeout(Duration::from_secs(10), conn.request("setBreakpoints", json!({})))
|
|
.await
|
|
.expect("the reader stalled behind the events")
|
|
.unwrap();
|
|
assert_eq!(reply, json!({"breakpoints": []}));
|
|
let _ = adapter.await;
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn outgoing_commands_are_backpressured_when_the_adapter_is_slow() {
|
|
let (writer, _unread_peer) = tokio::io::duplex(32 * 1024);
|
|
let (reader, _idle_peer) = tokio::io::duplex(32 * 1024);
|
|
// Nobody reads the writer's pipe, so it fills and the writer task stalls.
|
|
let (conn, _incoming) = Connection::start(reader, writer);
|
|
let producer_conn = conn.clone();
|
|
let sent = Arc::new(std::sync::atomic::AtomicUsize::new(0));
|
|
let count = sent.clone();
|
|
let producer = tokio::spawn(async move {
|
|
for i in 0..2000 {
|
|
let body = json!({"seq": i, "type": "event", "event": "output", "body": {"output": "x"}});
|
|
if producer_conn.send(&body).await.is_err() {
|
|
break;
|
|
}
|
|
count.fetch_add(1, Ordering::Relaxed);
|
|
}
|
|
});
|
|
tokio::time::sleep(Duration::from_millis(100)).await;
|
|
assert!(sent.load(Ordering::Relaxed) < 2000);
|
|
// The bounded queue held `send` back; closing cancels the writer task.
|
|
conn.close();
|
|
producer.abort();
|
|
}
|
|
|
|
#[test]
|
|
fn parses_output_events_with_non_utf8_text() {
|
|
// "中文" in GBK inside an output event, as netcoredbg sends it on a Chinese Windows.
|
|
let mut body = br#"{"seq":5,"type":"event","event":"output","body":{"category":"stdout","output":""#.to_vec();
|
|
body.extend_from_slice(&[0xd6, 0xd0, 0xce, 0xc4]);
|
|
body.extend_from_slice(br#"\n"}}"#);
|
|
let msg = parse_message(&body).expect("parsed");
|
|
assert_eq!(msg["event"], "output");
|
|
let output = msg["body"]["output"].as_str().unwrap();
|
|
assert!(output.ends_with('\n'));
|
|
// Off Windows (UTF-8 code page) the bytes decode lossily; the line still arrives.
|
|
#[cfg(not(windows))]
|
|
assert!(output.starts_with(char::REPLACEMENT_CHARACTER));
|
|
assert!(parse_message(b"{not json").is_none());
|
|
}
|
|
|
|
#[test]
|
|
fn formats_structured_errors() {
|
|
let msg =
|
|
json!({"message": "x", "body": {"error": {"format": "cannot find {file}", "variables": {"file": "a.py"}}}});
|
|
assert_eq!(error_message(&msg), "cannot find a.py");
|
|
assert_eq!(error_message(&json!({"message": "nope"})), "nope");
|
|
}
|
|
|
|
#[test]
|
|
fn a_failed_launch_response_keeps_delves_too_old_error_verbatim() {
|
|
// The UI's repair offer keys off this exact wording (`missingAdapter`), so the
|
|
// conversion to the IPC error must not fold it into a generic message.
|
|
let message = "Failed to launch /p/api: Version of Delve is too old for Go version go1.27.0 \
|
|
(maximum supported version 1.26, suppress this error with --check-go-version=false)";
|
|
let e = ide_core::IdeError::from(DapError::Failed { command: "launch".into(), message: message.into() });
|
|
assert_eq!(e.kind, ide_core::error::ErrorKind::InvalidInput);
|
|
assert_eq!(e.message, format!("launch failed: {message}"));
|
|
assert!(e.message.contains("Version of Delve is too old for Go version go1.27.0"));
|
|
}
|
|
}
|