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
2 changes: 1 addition & 1 deletion .github/workflows/plugins-release-rust-sdk.yml
Original file line number Diff line number Diff line change
Expand Up @@ -70,4 +70,4 @@ jobs:
asset="lithe-plugin-sdk-rust-$VERSION.crate"
gh release create "$TAG" "dist/$asset" "dist/$asset.sha256" \
--title "Rust plugin SDK $VERSION" \
--notes "Official Rust plugin SDK $VERSION for Lithe plugin backends. Requires Rust 1.87 or newer and depends only on serde_json and base64. Depend on the tag through Git, or pin the archive by its SHA-256 (\`$asset.sha256\`) and vendor the unpacked crate; see shared/plugins/sdk/rust/README.md."
--notes "Official Rust plugin SDK $VERSION for Lithe plugin backends. Requires Rust 1.87 or newer and uses serde, serde_json and base64. Depend on the tag through Git, or pin the archive by its SHA-256 (\`$asset.sha256\`) and vendor the unpacked crate; see shared/plugins/sdk/rust/README.md."
4 changes: 2 additions & 2 deletions shared/plugins/reference/domains/toolchains.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
| 激活事件 | 不需要。提供者由宿主的第一次查询唤起,不需要页面或启动事件 |
| 后端启动 | 提供者的后端只能是包内可执行文件(`packaged`),或包内运行时(`runtime` 加 `packagedRuntime`),不能依赖需要发现的运行时 |
| 桌面端 | 声明 `toolDefinitions`;未声明 `toolchainProviders`,见“桌面端现状” |
| 官方 SDK | 官方 SDK 都还没有实现 `litheToolchains`,提供者后端要自己处理 `toolchains/query` |
| 官方 SDK | [Rust SDK](../../sdk/rust/README.md#toolchain-providers) 提供类型化的 `toolchains/query`、能力协商和取消处理。Go、Node 和 Java 后端自行处理该协议 |

### 两条安装来源

Expand Down Expand Up @@ -203,7 +203,7 @@ A plugin can tell Lithe what a tool (a JDK, Maven, Node, Go and so on) looks lik
| Activation | None needed. The host's first query starts a provider; no page or startup event is needed |
| Backend launch | The provider's backend must be `packaged`, or `runtime` with `packagedRuntime`, and must not depend on a discovered runtime |
| Desktop | Declares `toolDefinitions`; does not declare `toolchainProviders`. See "Desktop status" |
| Official SDKs | None of the official SDKs implements `litheToolchains` yet; a provider backend handles `toolchains/query` itself |
| Official SDKs | The [Rust SDK](../../sdk/rust/README.md#toolchain-providers) handles typed `toolchains/query`, negotiation, and cancellation. Go, Node, and Java backends handle the protocol directly |

### Two installation routes

Expand Down
1 change: 1 addition & 0 deletions shared/plugins/sdk/e2e/plugin_sdk/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
pub mod backend;
pub mod keymap;
pub mod native_build;
pub mod toolchains;
pub mod vcs;

use lithe_core::execute_json;
Expand Down
82 changes: 82 additions & 0 deletions shared/plugins/sdk/e2e/plugin_sdk/toolchains.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
//! Drives a Rust SDK toolchain query over Core's actual transport and decoder.

use super::{core, Fixture, Session, WAIT};
use serde_json::json;
use std::fs;

pub fn run(executable: &str) {
let fixture = Fixture::new("rust-toolchain");
let workspace = fixture.workspace();
let state = fixture.root.join("state");
fs::create_dir_all(&workspace).unwrap();
fs::create_dir_all(&state).unwrap();
let plugin_id = "org.example.sdk-toolchain";
let manifest = json!({
"schemaVersion": 0, "pluginAPIVersion": 0,
"id": plugin_id, "displayName": "SDK toolchain fixture", "version": "1.0.0",
"requires": {"backend": 0, "toolchainProviders": 0},
"vendor": {"id": "org.example", "displayName": "Fixture publisher", "signatureRequirement": "publisherPackage"},
"permissions": ["backend.launch", "toolchains.provide"],
"toolchainProviders": [{"id": "fixture", "displayName": "SDK fixture", "tools": ["fixture-runtime"]}],
"backend": {"launch": {"kind": "packaged", "path": "bin/sample-backend"}, "arguments": ["--state", "${stateDir}"]},
});
let registry = json!({"plugins": [{"manifest": manifest}]});
let validated = core("toolchains.registry", registry.clone());
assert_eq!(validated["status"], "ok", "{validated}");
assert_eq!(
validated["registry"]["providers"][0]["provider"]["id"],
"fixture"
);
let started = core(
"lsp.startServer",
json!({
"providerId": format!("pluginBackend:{plugin_id}"), "pluginId": plugin_id,
"executablePath": executable, "arguments": ["--state", state],
"rootUri": format!("file://{}/", workspace.display()), "workingDirectory": workspace,
"toolchainProviders": ["fixture"], "initializeTimeoutMilliseconds": WAIT.as_millis() as u64,
"requestTimeoutMilliseconds": WAIT.as_millis() as u64, "shutdownTimeoutMilliseconds": 5000,
}),
);
let mut session = Session {
id: started["sessionId"].as_str().expect("session ID").into(),
plugin_id: plugin_id.into(),
events: Vec::new(),
};
let negotiated = session.await_event("toolchain provider negotiation", |event| {
event["type"] == "toolchainProviders"
});
assert_eq!(negotiated["result"]["providers"], json!(["fixture"]));
session.await_event("session ready", |event| {
event["type"] == "stateChanged" && event["state"] == "ready"
});

let operation = "sdk-toolchain-query";
let params = json!({
"operationID": operation, "generation": 3, "providerID": "fixture",
"authority": {"kind": "local"}, "context": null, "workspace": null,
"tools": ["fixture-runtime"],
});
core(
"lsp.toolchainRequest",
json!({
"sessionId": session.id, "operationId": operation, "params": params,
"timeoutMilliseconds": 5000,
}),
);
let completed = session.completion(operation);
assert!(completed.get("error").is_none(), "{completed}");
let wire = &completed["result"]["value"];
let decoded = core(
"toolchains.decodeReply",
json!({
"registry": registry, "pluginID": plugin_id, "currentGeneration": 3,
"request": {"jsonrpc": "2.0", "id": wire["id"], "method": "toolchains/query", "params": params},
"response": wire["response"], "platform": "macos", "filesystem": [],
}),
);
assert_eq!(decoded["status"], "ok", "{decoded}");
assert_eq!(decoded["snapshot"]["installations"], json!([]));
assert_eq!(decoded["snapshot"]["statements"], json!([]));
assert_eq!(decoded["snapshot"]["watch"], json!([]));
session.stop();
}
8 changes: 8 additions & 0 deletions shared/plugins/sdk/e2e/plugin_sdk_rust.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,14 @@

mod plugin_sdk;

#[test]
fn the_rust_sdk_toolchain_provider_negotiates_and_answers_through_core() {
let Some(executable) = std::env::var_os("LITHE_PLUGIN_SDK_RUST_SAMPLE") else {
return;
};
plugin_sdk::toolchains::run(&executable.to_string_lossy());
}

#[test]
fn the_rust_sdk_import_provider_reads_a_selected_source_through_core() {
let Some(executable) = std::env::var_os("LITHE_PLUGIN_SDK_RUST_SAMPLE") else {
Expand Down
2 changes: 2 additions & 0 deletions shared/plugins/sdk/rust/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

30 changes: 29 additions & 1 deletion shared/plugins/sdk/rust/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,12 @@ next to the SDK and changes with it:
relayed by Core, with the `Caller` a function called that way sees.
- **`litheKeymapImport`**: independently negotiated shortcut import providers
reading only explicitly selected source snapshots.
- **`litheToolchains`**: [typed toolchain discovery providers](#toolchain-providers).
- **`litheLogging`**: typed diagnostics, required at initialization; see
[Logging](#logging).

The SDK owns the wire format, negotiation, cancellation, and error mapping.
Your code supplies only handlers. It depends on `serde_json` and `base64`, runs
Your code supplies only handlers. It depends on `serde`, `serde_json` and `base64`, runs
every call on a thread of its own, and needs Rust 1.87 or newer.

This SDK has no build provider or VCS provider API; write build providers with
Expand All @@ -40,6 +41,33 @@ installation there, although the Core end-to-end tests still drive the protocol.
Which host services a session may call is reported at run time; see
[Host services](#host-services).

## Toolchain providers

Declare the same provider ID in the manifest's
[`toolchainProviders`](../../contract/v1/toolchains/README.md#provider-backend-negotiation)
and via `Backend::toolchain_provider`. The host offers the IDs it recognizes at
initialization. The SDK selects registered IDs in the offer and routes each
query to that handler:

```rust
use lithe_plugin_sdk::{toolchains::ToolchainQueryResult, Backend};

let mut backend = Backend::new("version-manager");
backend.toolchain_provider("manager", |_query, cancellation| {
cancellation.check()?;
// Read this manager's own data for query.tools and query.workspace.
Ok(ToolchainQueryResult::default())
}).expect("valid provider ID");
```

Handlers return installations, version statements and watch paths. An empty
result is valid. Set a statement's `installation` to `None` for an unmet
requirement. Use `ToolchainQueryError` for a query failure and check the
cancellation token during potentially long scans. The host observes native
filesystem facts, and Core validates the returned candidates with those facts.
The desktop does not yet declare this capability. The Rust SDK end-to-end test
runs the protocol through Core.

## Shortcut import providers

Declare `keymap_import_provider(id, handler)` before listening. The host
Expand Down
11 changes: 11 additions & 0 deletions shared/plugins/sdk/rust/examples/sample-backend/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
//! (`files.nextChange`), answers its command with a message in the window
//! it ran in, and lists the open workspaces when they change.

use lithe_plugin_sdk::toolchains::{ToolchainQueryError, ToolchainQueryResult};
use lithe_plugin_sdk::{
BackendHandle, Cancelled, Context, FunctionError, PluginError, SdkError, Value,
};
Expand Down Expand Up @@ -46,6 +47,16 @@ fn main() {
Ok(json!({"bindings": [{"commandID": "find-next", "keys": [{"key": "f3", "modifiers": []}]}]}))
}).expect("valid fixture provider");

backend
.toolchain_provider("fixture", |query, cancellation| {
cancellation.check()?;
if query.tools != ["fixture-runtime"] {
return Err(ToolchainQueryError::InvalidParams);
}
Ok(ToolchainQueryResult::default())
})
.expect("valid toolchain fixture provider");

let notes = Arc::clone(&state);
backend
.function("note.save", move |params, context| {
Expand Down
1 change: 1 addition & 0 deletions shared/plugins/sdk/rust/plugin-sdk/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,6 @@ rust-version.workspace = true
publish = false

[dependencies]
serde = { version = "1", features = ["derive"] }
serde_json.workspace = true
base64 = "0.22"
Loading