Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions rust/contracts/rust-core-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -3462,10 +3462,11 @@ operation. See the [provider execution contract](../../shared/plugins/contract/v
`lsp.toolchainRequest` accepts `{ sessionId, operationId?, params,
timeoutMilliseconds? }` and returns `{ operationId }`. `lsp.startServer` takes
`toolchainProviders`, the manifest's provider IDs; only a plugin-owned session
with some offers `capabilities.experimental.litheToolchains: { versions: [0],
providers }`. A backend that answers `{ version: 0, providers }` with a non-empty,
with some offers `capabilities.experimental.litheToolchains: { versions: [0, 1],
providers }`. A backend answers
`{ version, providers }` with its manifest's `toolchainProviders` version. A non-empty,
duplicate-free subset of the offer emits a `toolchainProviders` runtime event
with `result: { providers }`; any other answer enables none. A request whose
with `result: { providers }`; an unsupported version or invalid subset enables none. A request whose
`params.providerID` was not negotiated is `not_supported` with details
`plugin.toolchain.providerUnavailable`, and nothing is written. The
`requestCompleted` event carries `result.value: { id, response }`: the JSON-RPC
Expand Down
24 changes: 24 additions & 0 deletions rust/crates/core/src/tests/toolchain_definitions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -460,6 +460,30 @@ fn production_toolchain_fixtures_require_explicit_host_capabilities() {
}
}

#[test]
fn toolchain_provider_version_one_is_not_admitted_by_a_legacy_only_host() {
let mut manifest: Value = serde_json::from_str(include_str!(concat!(
env!("CARGO_MANIFEST_DIR"),
"/../../../shared/plugins/contract/v1/fixtures/toolchains/toolchain-provider.plugin.json"
)))
.unwrap();
manifest["requires"]["toolchainProviders"] = json!(1);
let legacy = validate_command(json!({
"manifest": manifest,
"hostCapabilities": {"backend": [0], "toolchainProviders": [0]}
}))
.unwrap();
assert_eq!(legacy["status"], "rejected");
assert_eq!(legacy["error"]["code"], "plugin.api.unsupported");
assert_eq!(legacy["error"]["field"], "requires.toolchainProviders");
let current = validate_command(json!({
"manifest": manifest,
"hostCapabilities": {"backend": [0], "toolchainProviders": [0, 1]}
}))
.unwrap();
assert_eq!(current["status"], "ok", "{current}");
}

/// Launches, tool references, and executable candidates belong to the base
/// contract, so naming them in `requires` is refused.
#[test]
Expand Down
111 changes: 96 additions & 15 deletions rust/crates/core/src/tests/toolchain_queries.rs
Original file line number Diff line number Diff line change
Expand Up @@ -236,26 +236,107 @@ fn toolchain_queries_refuse_mismatched_rpc_and_operation_generations() {

#[test]
fn toolchain_queries_keep_every_error_mapping_unique_and_validate_the_pair() {
let mut numbers = std::collections::BTreeSet::new();
for mut response in error_responses() {
for version in [0, 1] {
let mut numbers = std::collections::BTreeSet::new();
for mut response in error_responses(version) {
let mut value = input();
value["registry"]["plugins"][1]["manifest"]["requires"]["toolchainProviders"] =
json!(version);
response["id"] = value["request"]["id"].clone();
response["error"]["data"]["operationID"] =
value["request"]["params"]["operationID"].clone();
value["response"] = response;
let error = query::decode(&value, validated_manifest_json).unwrap_err();
assert_eq!(
Some(error.code()),
value["response"]["error"]["data"]["code"].as_str()
);
let number = query::rpc_code_for_version(error.code(), version).unwrap();
assert_eq!(value["response"]["error"]["code"], number);
assert!(numbers.insert(number));
if version == 0 {
assert_eq!(query::rpc_code(error.code()), Some(number));
} else if (-32099..=-32000).contains(&number) {
use lithe_plugin_rpc::codes;
for host_or_relay in [
codes::HOST_PERMISSION_DENIED,
codes::HOST_CONTEXT_EXPIRED,
codes::HOST_AUTHORITY_UNSUPPORTED,
codes::HOST_VERSION_CONFLICT,
codes::HOST_LIMIT_EXCEEDED,
codes::HOST_TIMEOUT,
codes::HOST_NOT_FOUND,
codes::HOST_READ_ONLY,
codes::HOST_UNSUPPORTED_OPTION,
codes::HOST_PRECONDITION_FAILED,
codes::HOST_BUSY,
codes::HOST_RATE_LIMITED,
codes::HOST_LANGUAGE_SERVER_UNAVAILABLE,
codes::HOST_LANGUAGE_SERVER_ERROR,
codes::HOST_METHOD_NOT_DECLARED,
codes::HOST_TOOL_UNRESOLVED,
codes::HOST_FOREIGN_CONTRIBUTION,
codes::NOT_DECLARED,
codes::NOT_EXPORTED,
codes::PROVIDER_DISABLED,
codes::VERSION_MISMATCH,
codes::CALL_CYCLE,
codes::DEPTH_EXCEEDED,
codes::TOO_MANY_CALLS,
codes::PAYLOAD_TOO_LARGE,
codes::PROVIDER_UNAVAILABLE,
codes::FAILED,
codes::INVALID_RESULT,
codes::HOST_REMOTE_DISCONNECTED,
codes::HOST_PLATFORM_UNAVAILABLE,
codes::HOST_ALREADY_EXISTS,
codes::HOST_DISK_CHANGED,
] {
assert_ne!(
number,
lithe_plugin_rpc::host_rpc_code(host_or_relay),
"version 1 toolchain code {number} collides with {host_or_relay}"
);
}
}
value["response"]["error"]["code"] = json!(-1);
assert_eq!(
query::decode(&value, validated_manifest_json)
.unwrap_err()
.code(),
"plugin.toolchain.invalidReply"
);
}
}
assert_eq!(
query::rpc_code_for_version("plugin.toolchain.timeout", 2),
None
);
}

#[test]
fn toolchain_queries_bind_error_numbers_to_the_declared_capability_version() {
let fixture: Value = serde_json::from_str(include_str!(
"../../../../fixtures/toolchains/error-code-versions.json"
))
.unwrap();
for case in fixture["cases"].as_array().unwrap() {
let mut value = input();
response["id"] = value["request"]["id"].clone();
response["error"]["data"]["operationID"] =
value["request"]["params"]["operationID"].clone();
value["response"] = response;
let error = query::decode(&value, validated_manifest_json).unwrap_err();
assert_eq!(
Some(error.code()),
value["response"]["error"]["data"]["code"].as_str()
);
let number = query::rpc_code(error.code()).unwrap();
assert!(numbers.insert(number));
value["response"]["error"]["code"] = json!(-1);
value["registry"]["plugins"][1]["manifest"]["requires"]["toolchainProviders"] =
case["version"].clone();
value["response"] = json!({
"jsonrpc": "2.0", "id": value["request"]["id"],
"error": {"code": case["number"], "message": "Fixture diagnostic.", "data": {
"code": case["code"], "operationID": "query-1", "providerID": "mise"
}}
});
assert_eq!(
query::decode(&value, validated_manifest_json)
.unwrap_err()
.code(),
"plugin.toolchain.invalidReply"
case["expected"].as_str().unwrap(),
"{}",
case["name"]
);
}
}
Expand Down
12 changes: 9 additions & 3 deletions rust/crates/core/src/tests/toolchain_vectors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -73,13 +73,14 @@ pub(super) fn query_response() -> Value {
/// test pairing each reply with its decoded code checks the mapping itself.
/// Ids and operation IDs are distinct placeholders; tests rewrite both to match
/// the request they answer.
pub(super) fn error_responses() -> Vec<Value> {
pub(super) fn error_responses(version: u32) -> Vec<Value> {
assert!(matches!(version, 0 | 1));
const FAILURES: [(i64, &str); 11] = [
(-32601, "methodUnavailable"),
(-32602, "invalidParams"),
(-32800, "cancelled"),
(-32070, "permissionDenied"),
(-32071, "authorityUnsupported"),
(-32082, "permissionDenied"),
(-32083, "authorityUnsupported"),
(-32072, "timeout"),
(-32073, "providerUnavailable"),
(-32074, "invalidReply"),
Expand All @@ -91,6 +92,11 @@ pub(super) fn error_responses() -> Vec<Value> {
.iter()
.zip(100..)
.map(|(&(number, name), id)| {
let number = match (version, number) {
(0, -32082) => -32070,
(0, -32083) => -32071,
_ => number,
};
json!({"jsonrpc":"2.0","id":id,"error":{"code":number,"message":"Fixture diagnostic.",
"data":{"code":format!("plugin.toolchain.{name}"),"operationID":format!("query-{id}"),"providerID":"mise"}}})
})
Expand Down
20 changes: 11 additions & 9 deletions rust/crates/lsp-client/src/toolchain_provider.rs
Original file line number Diff line number Diff line change
Expand Up @@ -83,21 +83,23 @@ mod tests {
assert_eq!(key, "litheToolchains");
assert_eq!(
offer,
json!({ "versions": [0], "providers": ["asdf", "mise"] })
json!({ "versions": [0, 1], "providers": ["asdf", "mise"] })
);
}

#[test]
fn negotiation_accepts_only_a_complete_subset_of_the_offer() {
assert_eq!(
negotiate(
&answer(json!({ "version": 0, "providers": ["mise"], "future": true })),
&offered()
),
Some(vec!["mise".to_string()])
);
for version in [0, 1] {
assert_eq!(
negotiate(
&answer(json!({ "version": version, "providers": ["mise"], "future": true })),
&offered()
),
Some(vec!["mise".to_string()])
);
}
for rejected in [
json!({ "version": 1, "providers": ["mise"] }),
json!({ "version": 2, "providers": ["mise"] }),
json!({ "version": 0 }),
json!({ "version": 0, "providers": [] }),
json!({ "version": 0, "providers": "mise" }),
Expand Down
2 changes: 1 addition & 1 deletion rust/crates/lsp-engine/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3598,7 +3598,7 @@ fn a_query_reaches_only_a_selected_provider_and_returns_the_raw_response() {
.expect("initialize should have been written");
assert_eq!(
initialize["params"]["capabilities"]["experimental"]["litheToolchains"],
json!({ "versions": [0], "providers": ["mise"] })
json!({ "versions": [0, 1], "providers": ["mise"] })
);
let event = harness
.await_event(|event| event.kind == "toolchainProviders")
Expand Down
4 changes: 3 additions & 1 deletion rust/crates/plugin-model/src/capabilities.rs
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,8 @@ pub const PLUGIN_FUNCTIONS: &str = "pluginFunctions";
/// `audience` that place a tool in the settings list.
pub const TOOL_DEFINITIONS: &str = "toolDefinitions";
/// Backend facts that can influence the executable selected for a defined tool.
/// Version 1 gives permission and authority failures distinct JSON-RPC numbers,
/// leaving version 0's published error mapping unchanged.
pub const TOOLCHAIN_PROVIDERS: &str = "toolchainProviders";
/// `outputLinkMatchers[]`: patterns that turn console output into links; see
/// `lithe_plugin_output_links`.
Expand Down Expand Up @@ -149,7 +151,7 @@ pub const SUPPORTED_CAPABILITIES: &[(&str, &[u32])] = &[
(SETTINGS, &[0]),
(SOURCE_SETTINGS, &[0, 1]),
(TOOL_DEFINITIONS, &[0, 1]),
(TOOLCHAIN_PROVIDERS, &[0]),
(TOOLCHAIN_PROVIDERS, &[0, 1]),
(UI, &[0]),
(VCS_PROVIDERS, &[0]),
];
Expand Down
3 changes: 2 additions & 1 deletion rust/crates/plugin-rpc/src/failures.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,8 @@ pub fn host_rpc_code(code: &str) -> i64 {
// must tell the provider's error from Core's by the number alone.
codes::FAILED => -32070,
codes::INVALID_RESULT => -32071,
// -32072 to -32077 are the toolchain provider protocol's.
// Toolchains own -32072..=-32077 and, since capability version 1,
// -32082/-32083. Only legacy version 0 overlaps -32070/-32071.
codes::HOST_REMOTE_DISCONNECTED => -32078,
codes::HOST_PLATFORM_UNAVAILABLE => -32079,
codes::HOST_ALREADY_EXISTS => -32080,
Expand Down
3 changes: 2 additions & 1 deletion rust/crates/toolchain/src/definitions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -802,7 +802,8 @@ pub fn registry(input: &Value, validate_manifest: ManifestValidator) -> Validati
definitions.push(json!({"pluginID":plugin_id,"definition":normalized}));
}
for provider in optional_list(&manifest, "toolchainProviders", 8)? {
providers.push(json!({"pluginID":plugin_id,"provider":provider}));
providers.push(json!({"pluginID":plugin_id,
"version":manifest["requires"]["toolchainProviders"],"provider":provider}));
}
if definitions.len() > 512 || providers.len() > 256 {
return Err(invalid(
Expand Down
34 changes: 26 additions & 8 deletions rust/crates/toolchain/src/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -219,14 +219,27 @@ fn object_keys(
Ok(())
}

/// Maps each query error to one stable JSON-RPC number without transport work.
/// Maps a query error to the published version 0 number without transport work.
/// New callers with a manifest version use [`rpc_code_for_version`].
pub fn rpc_code(code: &str) -> Option<i64> {
rpc_code_for_version(code, 0)
}

/// Maps a stable query error using the manifest's `toolchainProviders` version.
/// Unknown versions or error names have no mapping. Version 0 retains its
/// published numbers; version 1 no longer overlaps relayed function failures.
pub fn rpc_code_for_version(code: &str, version: u32) -> Option<i64> {
if !matches!(version, 0 | 1) {
return None;
}
Some(match code {
"plugin.toolchain.methodUnavailable" => -32601,
INVALID => -32602,
"plugin.toolchain.cancelled" => -32800,
"plugin.toolchain.permissionDenied" => -32070,
"plugin.toolchain.authorityUnsupported" => -32071,
"plugin.toolchain.permissionDenied" if version == 0 => -32070,
"plugin.toolchain.permissionDenied" => -32082,
"plugin.toolchain.authorityUnsupported" if version == 0 => -32071,
"plugin.toolchain.authorityUnsupported" => -32083,
"plugin.toolchain.timeout" => -32072,
"plugin.toolchain.providerUnavailable" => -32073,
REPLY => -32074,
Expand All @@ -237,7 +250,7 @@ pub fn rpc_code(code: &str) -> Option<i64> {
})
}

fn error_reply(response: &Value, params: &Params) -> Validation<Value> {
fn error_reply(response: &Value, params: &Params, version: u32) -> Validation<Value> {
let error = &response["error"];
object_keys(
error,
Expand All @@ -253,7 +266,7 @@ fn error_reply(response: &Value, params: &Params) -> Validation<Value> {
REPLY,
)?;
let code = data["code"].as_str().unwrap_or("");
if rpc_code(code) != error["code"].as_i64()
if rpc_code_for_version(code, version) != error["code"].as_i64()
|| data["operationID"] != params.operation_id
|| data["providerID"] != params.provider_id
|| !error["message"]
Expand All @@ -274,8 +287,8 @@ fn error_reply(response: &Value, params: &Params) -> Validation<Value> {
Some(-32601) => "plugin.toolchain.methodUnavailable",
Some(-32602) => INVALID,
Some(-32800) => "plugin.toolchain.cancelled",
Some(-32070) => "plugin.toolchain.permissionDenied",
Some(-32071) => "plugin.toolchain.authorityUnsupported",
Some(-32070 | -32082) => "plugin.toolchain.permissionDenied",
Some(-32071 | -32083) => "plugin.toolchain.authorityUnsupported",
Some(-32072) => "plugin.toolchain.timeout",
Some(-32073) => "plugin.toolchain.providerUnavailable",
Some(-32074) => REPLY,
Expand Down Expand Up @@ -835,6 +848,11 @@ pub fn decode(input: &Value, validate_manifest: ManifestValidator) -> Validation
"The enabled provider is not in the revalidated registry.",
)
})?;
// The registry is rebuilt from complete validated manifests above. Neither
// an error number nor provider-owned response data can choose its version.
let provider_version = provider["version"]
.as_u64()
.expect("validated toolchain capability version") as u32;
let provider = &provider["provider"];
let declared: BTreeSet<&str> = provider["tools"]
.as_array()
Expand Down Expand Up @@ -885,7 +903,7 @@ pub fn decode(input: &Value, validate_manifest: ManifestValidator) -> Validation
));
}
if response.get("error").is_some() {
return error_reply(response, params);
return error_reply(response, params, provider_version);
}
let reply: Reply = serde_json::from_value(response["result"].clone()).map_err(|_| {
reject(
Expand Down
19 changes: 19 additions & 0 deletions rust/fixtures/toolchains/error-code-versions.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"cases": [
{"name":"legacy permission", "version":0, "number":-32070, "code":"plugin.toolchain.permissionDenied", "expected":"plugin.toolchain.permissionDenied"},
{"name":"legacy authority", "version":0, "number":-32071, "code":"plugin.toolchain.authorityUnsupported", "expected":"plugin.toolchain.authorityUnsupported"},
{"name":"version 1 permission", "version":1, "number":-32082, "code":"plugin.toolchain.permissionDenied", "expected":"plugin.toolchain.permissionDenied"},
{"name":"version 1 authority", "version":1, "number":-32083, "code":"plugin.toolchain.authorityUnsupported", "expected":"plugin.toolchain.authorityUnsupported"},
{"name":"legacy rejects new permission number", "version":0, "number":-32082, "code":"plugin.toolchain.permissionDenied", "expected":"plugin.toolchain.invalidReply"},
{"name":"legacy rejects new authority number", "version":0, "number":-32083, "code":"plugin.toolchain.authorityUnsupported", "expected":"plugin.toolchain.invalidReply"},
{"name":"version 1 rejects host alreadyExists number", "version":1, "number":-32080, "code":"plugin.toolchain.permissionDenied", "expected":"plugin.toolchain.invalidReply"},
{"name":"version 1 rejects host diskChanged number", "version":1, "number":-32081, "code":"plugin.toolchain.authorityUnsupported", "expected":"plugin.toolchain.invalidReply"},
{"name":"version 1 rejects legacy permission number", "version":1, "number":-32070, "code":"plugin.toolchain.permissionDenied", "expected":"plugin.toolchain.invalidReply"},
{"name":"version 1 rejects legacy authority number", "version":1, "number":-32071, "code":"plugin.toolchain.authorityUnsupported", "expected":"plugin.toolchain.invalidReply"},
{"name":"legacy rejects relayed function failure", "version":0, "number":-32070, "code":"plugin.function.failed", "expected":"plugin.toolchain.invalidReply"},
{"name":"version 1 rejects relayed function failure", "version":1, "number":-32070, "code":"plugin.function.failed", "expected":"plugin.toolchain.invalidReply"},
{"name":"legacy rejects relayed invalid result", "version":0, "number":-32071, "code":"plugin.function.invalidResult", "expected":"plugin.toolchain.invalidReply"},
{"name":"version 1 rejects relayed invalid result", "version":1, "number":-32071, "code":"plugin.function.invalidResult", "expected":"plugin.toolchain.invalidReply"},
{"name":"unknown capability version", "version":2, "number":-32082, "code":"plugin.toolchain.permissionDenied", "expected":"plugin.api.unsupported"}
]
}
Loading
Loading