Skip to content

Commit a58e07e

Browse files
authored
feat(debug): tcpAnnounced 公告解析命令与 target.directory 程序绑定 (#47)
* feat(debug): tcpAnnounced 公告解析命令与 target.directory 程序绑定 - 新增 debug.adapters.readAnnouncement:宿主把 tcpAnnounced 适配器的输出逐行交给 Core, 第一行含 prefix 的输出是公告,前缀之后是 port(连 127.0.0.1)或带回环主机的 host:port (IPv6 加方括号);返回 none、announced 或 invalid(malformed、notLoopback), 非回环地址一律拒绝。用例在 rust/fixtures/debug/adapter-announcements-v1.json。 - targetBindings.program 新增来源 target.directory:target.path 所在的目录,供 Delve 这类按包构建再调试的适配器使用;路径没有所在目录时以 debug.target.invalid (字段 target.path)拒绝。schema 枚举、契约 README、参考页、指南同步更新。 - tcpAnnounced 端点校验抽成 DebugEndpoint::is_announced,清单校验和新命令共用。 - rust-core-api.md 写明宿主怎样读公告,并去掉已删除的 macOS 宿主的传输说明; 模块说明去掉过时的 API level 4。 * docs(plugins): 更新记录填入 PR 编号 #47
1 parent e811068 commit a58e07e

19 files changed

Lines changed: 948 additions & 30 deletions

File tree

‎rust/contracts/rust-core-api.md‎

Lines changed: 28 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -445,6 +445,7 @@ or removing a command fails until the table changes in the same commit.
445445
| `debug.adapters.startArguments` | Check one debug start against a plugin's `debugAdapters[]` entry and return its DAP launch arguments |
446446
| `debug.validateAdapterEndpoint` | Validate an IDE-to-DAP TCP endpoint and classify whether remote consent is required; performs no DNS or network I/O |
447447
| `debug.adapters.executablePlan` | Say where to look for the program a launch debugs: the user's setting and the adapter's candidate paths |
448+
| `debug.adapters.readAnnouncement` | Read whether one output line of a `tcpAnnounced` adapter announces its endpoint, and accept only a loopback one; reads no process output and opens no socket |
448449
| `debug.transport.policy` | Return the default byte-stream deadlines, queue budgets and the session `initialize` deadline; creates no state |
449450
| `debug.transport.handle` | Apply one platform event to an IDE-to-adapter byte-stream lifecycle and return the effects the platform runs next |
450451
| `debug.transport.release` | Forget the lifecycle of a stopped byte stream once the platform dropped its handles |
@@ -2384,7 +2385,8 @@ bounded best-effort drain of queued frames (including disconnect) for up to one
23842385
second before closing; this is local write completion, not a remote acknowledgement.
23852386
Failure and explicit transport abort close immediately. There is no automatic reconnect or request
23862387
replay. Proxy/tunnel implementations and plugin `tcpPort` / `tcpAnnounced`
2387-
process hosting are not enabled by this API.
2388+
process hosting are not enabled by this API; `tcpAnnounced` hosting reads its
2389+
endpoint through `debug.adapters.readAnnouncement`.
23882390

23892391
The `debug.transport.*` commands hold the lifecycle rules of that byte stream
23902392
so every platform network layer shares one rule set. They are separate from the
@@ -4055,9 +4057,27 @@ only `launch: { kind: "backend", function, timeoutMilliseconds }` with empty
40554057
`requiredDirectories` and no `resolveParams`: the server's own session asks
40564058
the backend with the directories of its start, so resolving the adapter needs
40574059
no `workspaceStateDirectory`, `logDirectory` or `temporaryDirectory`. Core validates every declared
4058-
`transport`, but a host starts only the transports it implements: the macOS host
4059-
runs `stdio` and refuses `tcpPort` and `tcpAnnounced` before starting the
4060-
process, with `plugin.launch.unsupportedTransport`.
4060+
`transport`, but a host starts only the transports it implements and refuses
4061+
the others before starting the process, with `plugin.launch.unsupportedTransport`.
4062+
4063+
`debug.adapters.readAnnouncement` accepts exactly `{ endpoint, stream, line }`:
4064+
the plan's `debugAdapter.endpoint` of a `tcpAnnounced` adapter (`stream`,
4065+
`prefix`, `value`), the stream one line of the adapter's output came from
4066+
(`stdout` or `stderr`), and that line without its line break. A line on another
4067+
stream, or without the prefix, returns `{ status: "none" }`. Otherwise the line
4068+
is the announcement: the rest after the prefix's first occurrence, without
4069+
surrounding whitespace, returns `{ status: "announced", host, port }` when it is
4070+
a port from 1 to 65535 in decimal digits (`value: "port"`, host `127.0.0.1`) or
4071+
`host:port` / `[ipv6]:port` with a loopback host (`value: "hostPort"`; host as
4072+
written, without brackets). It returns `{ status: "invalid", reason:
4073+
"malformed" }` for any other text and `{ status: "invalid", reason:
4074+
"notLoopback" }` for a well-formed host that is not `localhost`, 127.0.0.0/8 or
4075+
`::1`. An endpoint that is not a valid `tcpAnnounced` endpoint, an unknown
4076+
stream or field fails with `invalid_request`. The host feeds the declared
4077+
stream to this command from the transport's `discoverEndpoint` effect until an
4078+
answer other than `none`, then reports `endpointResolved` for `announced` or
4079+
fails with `invalidEndpoint`; the discovery deadline bounds the wait. Cases
4080+
live in `rust/fixtures/debug/adapter-announcements-v1.json`.
40614081

40624082
`debug.adapters.startArguments` accepts `{ manifest, adapterID, request:
40634083
"launch" | "attach", facts: { registration: { generation, currentGeneration },
@@ -4069,7 +4089,10 @@ configuration already sets it. `configuration` is a plugin backend's own DAP
40694089
arguments from `lithe/host/debug/start`, as `debug.decodeBackendConfiguration`
40704090
returned them; each of its keys replaces the argument of the same name, so the
40714091
host sends `arguments` to the adapter unchanged. A `noDebug` or `__` key there is
4072-
refused with `plugin.debug.invalidStart` and `field: "configuration.<key>"`. `program` is filled from `target.path`, or from
4092+
refused with `plugin.debug.invalidStart` and `field: "configuration.<key>"`. `program` is filled from `target.path`; from the directory
4093+
containing `target.path` when the configuration binds it to `target.directory`
4094+
(an adapter such as Delve that builds a package; a path without a directory is
4095+
`debug.target.invalid` with `field: "target.path"`); or from
40734096
`target.executable` (an absolute path the host found) when the configuration
40744097
binds it to `target.executable`. Refusals use the `rejected` shape with
40754098
`debug.provider.stale`, `debug.request.unsupported`, `debug.runtime.stale`, or

‎rust/crates/core/src/protocol/command.rs‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -281,6 +281,9 @@ pub enum DebugCommand {
281281
ValidateAdapterEndpoint,
282282
/// Says where to look for the program a launch debugs (`debug.adapters.executablePlan`).
283283
AdaptersExecutablePlan,
284+
/// Reads whether one output line of a `tcpAnnounced` adapter announces its
285+
/// loopback endpoint (`debug.adapters.readAnnouncement`).
286+
AdaptersReadAnnouncement,
284287
/// Returns the default byte-stream deadlines and queue budgets (`debug.transport.policy`).
285288
TransportPolicy,
286289
/// Applies one platform event to a byte-stream lifecycle and returns the effects to run
@@ -1003,6 +1006,9 @@ impl CoreCommand {
10031006
"debug.adapters.executablePlan" => {
10041007
Some(Self::Debug(DebugCommand::AdaptersExecutablePlan))
10051008
}
1009+
"debug.adapters.readAnnouncement" => {
1010+
Some(Self::Debug(DebugCommand::AdaptersReadAnnouncement))
1011+
}
10061012
"debug.transport.policy" => Some(Self::Debug(DebugCommand::TransportPolicy)),
10071013
"debug.transport.handle" => Some(Self::Debug(DebugCommand::TransportHandle)),
10081014
"debug.transport.release" => Some(Self::Debug(DebugCommand::TransportRelease)),
@@ -1668,6 +1674,7 @@ mod tests {
16681674
"debug.transport.policy",
16691675
"debug.transport.handle",
16701676
"debug.transport.release",
1677+
"debug.adapters.readAnnouncement",
16711678
] {
16721679
assert!(CoreCommand::parse(command).is_some(), "missing {command}");
16731680
}

‎rust/crates/core/src/runtime/dispatcher/debug.rs‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,12 @@ pub(super) fn dispatch(command: DebugCommand, id: Option<String>, payload: Value
1515
Err(error) => CoreResponse::failure(id, error),
1616
}
1717
}
18+
DebugCommand::AdaptersReadAnnouncement => {
19+
match crate::debug::adapters::read_announcement(payload) {
20+
Ok(data) => CoreResponse::success(id, data),
21+
Err(error) => CoreResponse::failure(id, error),
22+
}
23+
}
1824
DebugCommand::TransportPolicy => match crate::debug::transport_policy(payload) {
1925
Ok(data) => CoreResponse::success(id, data),
2026
Err(error) => CoreResponse::failure(id, error),

‎rust/crates/core/src/tests/declarative_plugins.rs‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2049,6 +2049,35 @@ fn debug_start_arguments_need_an_absolute_resolved_executable() {
20492049
}
20502050
}
20512051

2052+
#[test]
2053+
fn debug_start_arguments_bind_program_to_the_directory_of_the_target() {
2054+
// The host sends native paths, and the directory depends on the platform.
2055+
let (path, directory) = if cfg!(windows) {
2056+
(r"C:\work\cmd\app\main.go", r"C:\work\cmd\app")
2057+
} else {
2058+
("/work/cmd/app/main.go", "/work/cmd/app")
2059+
};
2060+
let mut manifest = fixture("debug-adapter.plugin.json");
2061+
manifest["debugAdapters"][0]["configurations"]["launch"]["targetBindings"]["program"] =
2062+
json!("target.directory");
2063+
let launch = lithe_plugin_manifest::debug_start_arguments_command(json!({
2064+
"manifest": manifest,
2065+
"adapterID": "example",
2066+
"request": "launch",
2067+
"facts": {
2068+
"registration": { "generation": 3, "currentGeneration": 3 },
2069+
"target": { "kind": "file", "path": path, "workingDirectory": "/work" },
2070+
},
2071+
}))
2072+
.expect("payload is well formed");
2073+
assert_eq!(launch["status"], "ok", "{launch}");
2074+
// A package debugger builds every file of the directory, not one file.
2075+
assert_eq!(
2076+
launch["arguments"],
2077+
json!({ "stopOnEntry": false, "program": directory, "cwd": "/work" })
2078+
);
2079+
}
2080+
20522081
#[test]
20532082
fn debug_executable_plan_lists_the_configured_path_and_ordered_candidates() {
20542083
let plan = debug_executable_plan(

‎rust/crates/core/src/tests/protocol.rs‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,30 @@ fn debug_adapter_endpoint_validation_crosses_the_json_boundary() {
9696
}
9797
}
9898

99+
#[test]
100+
fn debug_adapter_announcements_cross_the_json_boundary() {
101+
let fixture: Value = serde_json::from_str(include_str!(concat!(
102+
env!("CARGO_MANIFEST_DIR"),
103+
"/../../fixtures/debug/adapter-announcements-v1.json"
104+
)))
105+
.expect("announcement fixture is JSON");
106+
for case in fixture["cases"].as_array().expect("announcement cases") {
107+
let request = serde_json::json!({
108+
"id": "read-announcement", "command": "debug.adapters.readAnnouncement", "payload": case["input"]
109+
});
110+
let response: Value = serde_json::from_str(&execute_json(&request.to_string()))
111+
.expect("announcement response is JSON");
112+
assert_eq!(response["id"], "read-announcement");
113+
match case.get("result") {
114+
Some(result) => {
115+
assert_eq!(response["ok"], true, "{case}");
116+
assert_eq!(response["data"], *result, "{case}");
117+
}
118+
None => assert_eq!(response["error"]["code"], "invalid_request", "{case}"),
119+
}
120+
}
121+
}
122+
99123
#[test]
100124
fn debug_transport_commands_cross_the_json_boundary() {
101125
let call = |command: &str, payload: Value| -> Value {

‎rust/crates/debug/src/adapters.rs‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
//! `debugAdapters[]` of an API level 4 plugin manifest: what a host must know
2-
//! about a debug adapter before starting any process for it.
1+
//! `debugAdapters[]` of a plugin manifest: what a host must know about a
2+
//! debug adapter before starting any process for it.
33
//!
44
//! A declaration names the adapter, how its process is started and reached
55
//! (stdio, a loopback TCP endpoint, or a port the plugin's own language server
@@ -26,6 +26,7 @@ use serde_json::{json, Map, Value};
2626
use std::collections::{BTreeSet, HashSet};
2727
use std::net::IpAddr;
2828

29+
mod announcement;
2930
mod checks;
3031
mod declaration;
3132
mod plan;
@@ -36,6 +37,7 @@ mod validate_adapter;
3637
mod validate_configuration;
3738
mod validate_launch;
3839

40+
pub use announcement::*;
3941
pub(crate) use checks::*;
4042
pub use declaration::*;
4143
pub use plan::*;
@@ -87,6 +89,10 @@ const MAX_EXECUTABLE_CANDIDATE: usize = 1024;
8789
/// resolved, instead of the target's own path.
8890
const TARGET_EXECUTABLE: &str = "target.executable";
8991

92+
/// The `targetBindings.program` source that reads the directory containing the
93+
/// target's path, for adapters that debug a package rather than one file.
94+
const TARGET_DIRECTORY: &str = "target.directory";
95+
9096
/// The target kind of a remote `host:port` the debuggee listens on.
9197
const TARGET_CONNECTION: &str = "connection";
9298

Lines changed: 147 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,147 @@
1+
//! The endpoint a `tcpAnnounced` adapter prints on its own output.
2+
//!
3+
//! The host reads the adapter's output line by line and asks Core about each
4+
//! one until a line announces the endpoint, then connects to it. Core decides
5+
//! which line is the announcement and which endpoints are acceptable, so every
6+
//! platform host reads the same announcements the same way. Core never reads
7+
//! the process output, opens a socket, resolves a name or keeps a clock: the
8+
//! host bounds the wait with the transport's discovery deadline.
9+
10+
use super::*;
11+
use lithe_protocol::{CoreError, ErrorCode};
12+
13+
/// Longest endpoint text after the prefix, in bytes: room for a bracketed IPv6
14+
/// address and a port, with margin.
15+
const MAX_ANNOUNCED_ENDPOINT: usize = 128;
16+
17+
/// Where a `port` announcement listens: adapters that print only a port listen
18+
/// on the IPv4 loopback address.
19+
const ANNOUNCED_PORT_HOST: &str = "127.0.0.1";
20+
21+
/// `debug.adapters.readAnnouncement`: whether one output line of a
22+
/// `tcpAnnounced` adapter announces its endpoint.
23+
///
24+
/// The payload is `{ endpoint, stream, line }`: the `endpoint` of the
25+
/// adapter's launch plan, the stream the line came from, and the line without
26+
/// its line break. A line on another stream, or one without the prefix, is
27+
/// `{ status: "none" }`. A line with the prefix is the announcement: the rest
28+
/// of the line after the prefix's first occurrence, without surrounding
29+
/// whitespace, is `{ status: "announced", host, port }` when it is a loopback
30+
/// endpoint, and `{ status: "invalid", reason }` otherwise. A malformed
31+
/// payload fails with `invalid_request`.
32+
pub fn read_announcement(payload: Value) -> Result<Value, CoreError> {
33+
#[derive(Deserialize)]
34+
#[serde(deny_unknown_fields)]
35+
struct Request {
36+
endpoint: DebugEndpoint,
37+
stream: String,
38+
line: String,
39+
}
40+
let request: Request = serde_json::from_value(payload).map_err(|error| {
41+
CoreError::new(ErrorCode::InvalidRequest, "Invalid announcement request.")
42+
.with_details(error.to_string())
43+
})?;
44+
if !request.endpoint.is_announced() {
45+
return Err(CoreError::new(
46+
ErrorCode::InvalidRequest,
47+
"An announced endpoint names a stream, a one-line prefix, and port or hostPort.",
48+
));
49+
}
50+
if !matches!(request.stream.as_str(), "stdout" | "stderr") {
51+
return Err(CoreError::new(
52+
ErrorCode::InvalidRequest,
53+
"A line comes from stdout or stderr.",
54+
));
55+
}
56+
let endpoint = request.endpoint;
57+
let prefix = endpoint.prefix.as_deref().unwrap_or_default();
58+
if endpoint.stream.as_deref() != Some(request.stream.as_str()) {
59+
return Ok(json!({ "status": "none" }));
60+
}
61+
let Some((_, rest)) = request.line.split_once(prefix) else {
62+
return Ok(json!({ "status": "none" }));
63+
};
64+
let announced = rest.trim();
65+
let parsed = match endpoint.value.as_deref() {
66+
Some("port") => announced_port(announced).map(|port| (ANNOUNCED_PORT_HOST, port)),
67+
_ => announced_host_port(announced),
68+
};
69+
Ok(match parsed {
70+
Err(reason) => json!({ "status": "invalid", "reason": reason }),
71+
Ok((host, port)) => json!({ "status": "announced", "host": host, "port": port }),
72+
})
73+
}
74+
75+
/// Why an announcement is not an endpoint the host may connect to.
76+
type Refusal = &'static str;
77+
78+
/// The text is not a port, or not `host:port` with a valid host.
79+
const MALFORMED: Refusal = "malformed";
80+
81+
/// The text names a host Core cannot tell is this machine.
82+
const NOT_LOOPBACK: Refusal = "notLoopback";
83+
84+
/// A port from 1 to 65535 written in decimal digits only.
85+
fn announced_port(text: &str) -> Result<u16, Refusal> {
86+
if text.is_empty() || text.len() > 5 || !text.bytes().all(|byte| byte.is_ascii_digit()) {
87+
return Err(MALFORMED);
88+
}
89+
match text.parse::<u16>() {
90+
Ok(port) if port >= 1 => Ok(port),
91+
_ => Err(MALFORMED),
92+
}
93+
}
94+
95+
/// `host:port`, or `[address]:port` for IPv6, with a loopback host.
96+
fn announced_host_port(text: &str) -> Result<(&str, u16), Refusal> {
97+
if text.len() > MAX_ANNOUNCED_ENDPOINT {
98+
return Err(MALFORMED);
99+
}
100+
let (host, port) = match text.strip_prefix('[') {
101+
Some(bracketed) => {
102+
let (address, port) = bracketed.split_once("]:").ok_or(MALFORMED)?;
103+
if !address.contains(':') {
104+
return Err(MALFORMED);
105+
}
106+
(address, port)
107+
}
108+
None => {
109+
let (host, port) = text.rsplit_once(':').ok_or(MALFORMED)?;
110+
if host.contains(':') {
111+
return Err(MALFORMED);
112+
}
113+
(host, port)
114+
}
115+
};
116+
let port = announced_port(port)?;
117+
if host_problem(host).is_some() {
118+
return Err(MALFORMED);
119+
}
120+
if !is_loopback_host(host) {
121+
return Err(NOT_LOOPBACK);
122+
}
123+
Ok((host, port))
124+
}
125+
126+
#[cfg(test)]
127+
mod tests {
128+
use super::*;
129+
130+
#[test]
131+
fn announcement_fixtures_match_the_reading() {
132+
let fixture: Value = serde_json::from_str(include_str!(concat!(
133+
env!("CARGO_MANIFEST_DIR"),
134+
"/../../fixtures/debug/adapter-announcements-v1.json"
135+
)))
136+
.expect("announcement fixture is JSON");
137+
let cases = fixture["cases"].as_array().expect("fixture cases");
138+
assert!(!cases.is_empty());
139+
for case in cases {
140+
let result = read_announcement(case["input"].clone());
141+
match case.get("result") {
142+
Some(expected) => assert_eq!(result.expect("a reading"), *expected, "{case}"),
143+
None => assert!(result.is_err(), "{case}"),
144+
}
145+
}
146+
}
147+
}

‎rust/crates/debug/src/adapters/declaration.rs‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -144,7 +144,8 @@ pub struct DebugTargetBindings {
144144
/// Source of the `env` argument: only `target.environment`.
145145
#[serde(default, skip_serializing_if = "Option::is_none")]
146146
pub env: Option<String>,
147-
/// Source of the `program` argument: `target.path` or `target.executable`. Launch only.
147+
/// Source of the `program` argument: `target.path`, `target.directory` (the
148+
/// directory containing `target.path`) or `target.executable`. Launch only.
148149
#[serde(default, skip_serializing_if = "Option::is_none")]
149150
pub program: Option<String>,
150151
/// Source of the `processId` argument: only `target.processID`. Attach only.

‎rust/crates/debug/src/adapters/plan.rs‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,9 @@ pub fn plan(
111111
{
112112
return Err(missing("target.path", "path"));
113113
}
114+
Some(TARGET_DIRECTORY) if target.path.as_deref().and_then(target_directory).is_none() => {
115+
return Err(missing("target.path", "path inside a directory"));
116+
}
114117
_ => {}
115118
}
116119
if bindings.args.is_some()

‎rust/crates/debug/src/adapters/start.rs‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -151,6 +151,11 @@ fn bound_arguments(
151151
};
152152
let program = match bindings.program.as_deref() {
153153
Some(TARGET_EXECUTABLE) => target.executable.clone(),
154+
Some(TARGET_DIRECTORY) => target
155+
.path
156+
.as_deref()
157+
.and_then(target_directory)
158+
.map(str::to_string),
154159
_ => target.path.clone(),
155160
};
156161
bind("program", &bindings.program, program.map(Value::from));
@@ -184,6 +189,15 @@ fn bound_arguments(
184189
})
185190
}
186191

192+
/// The directory that contains a target path, or `None` when the path names
193+
/// no directory, for example a bare file name.
194+
pub(crate) fn target_directory(path: &str) -> Option<&str> {
195+
std::path::Path::new(path)
196+
.parent()
197+
.and_then(std::path::Path::to_str)
198+
.filter(|directory| !directory.is_empty())
199+
}
200+
187201
/// Writes the target's endpoint, and its path mappings when the adapter takes
188202
/// them, to the destinations the binding names.
189203
fn bind_connection(

0 commit comments

Comments
 (0)