crate-plugin-kit
中文版见 README_CN.md
A cargo-based plugin system: install cdylib plugins from crates.io and load them at
runtime. The Rust counterpart of npm-plugin-kit —
"install a plugin, then load it" — moved onto cargo.
$ cargo install my-plugin # the plugin is a cdylib crate
error: there is nothing to install
$ # crate-plugin-kit does this instead:
myapp-plugin-foo 0.1.0
wrapper ~/.myapp/build/myapp-plugin-foo/ cargo build --release
library ~/.myapp/plugins/myapp-plugin-foo/libmyapp_plugin_foo.so
manifest ~/.myapp/plugins/myapp-plugin-foo/myapp-plugin.toml
Features
- 🔌 Runtime loading, zero compile-time coupling — plugins are
cdylibs,dlopened on demand. Nothing is linked into your binary. - 🧩 Generic, not type-erased —
load()hands back a thin*const T, never adyn Trait. No fat-pointer conversion, so no UB at the boundary. - 🏷️ Every host-specific name is configuration — app id, manifest name, crate prefix, entry symbol, wrapper body. This crate hardcodes none of them.
- 📦 Install straight from crates.io — one call, no manual downloads or vendoring.
- 🔨 Build-host by default — installs go through
cargo build, so whatever registry or mirror you already configured just works. - ⚡ Prebuilt accelerator — optionally pull a ready-made cdylib from GitHub Releases, falling back to a local build on any failure.
- 📄 The manifest travels with the code — a plugin's metadata lives in its own repo root and is copied at install time, so it can never drift from the implementation.
- 🔒 Cross-process install lock — two terminals cannot corrupt the store.
- 🚫 Refuses unsafe unloads — unlinking a library that is still loaded is rejected, not attempted. Guessing wrong there is UB.
- 🪶 Zero async — no runtime, no
tokio. Installing is a subprocess, loading isdlopen. - 📚 Fully documented public API —
#![deny(missing_docs)].
Contents
- Why this exists
- Install
- Quick start
- Configuration
- On-disk layout
- How install works
- Prebuilt assets
- Where the manifest comes from
- What it does not do
- Development
- Repository
- License
Why this exists
cargo install only installs bin targets. A crate with crate-type = ["cdylib"] has no
bin, so installing it fails outright:
$ cargo install my-plugin
error: there is nothing to install
Adding a bin target does not help either — cargo install would put that bin in
~/.cargo/bin and still leave the cdylib nowhere useful. And building the plugin crate
directly does not work, because Cargo builds dependencies as rlibs and never emits a cdylib
for them.
So this crate generates a tiny wrapper project instead, which lets the plugin itself stay an ordinary rlib:
plugin crate (an ordinary rlib on crates.io)
│ as a dependency
▼
wrapper project (generated here, ~30 lines, [lib] crate-type = ["cdylib"])
│ cargo build --release
▼
libxxx.so / xxx.dll / libxxx.dylib
│ copied to <data-dir>/plugins/<crate>/
▼
dlopen at runtime
Because the plugin stays an rlib:
- it is an ordinary crate to the rest of the ecosystem;
- it can be unit-tested with a plain
use, without going anywhere neardlopen; - its author writes no
#[no_mangle]at all — the cdylib's shape is generated by the host contract crate'sexport!macro.
Install
Requirements
- Rust 1.88+ to build (this is the MSRV —
libloading0.9 requires 1.88). cargoonPATHat run time, for the default build-host install path. It is not linked in — installs are a subprocess. The prebuilt path does not need it.- Linux, macOS and Windows.
Quick start
use ;
// The `#[repr(C)]` entry struct your contract crate defines.
let mut cfg = new;
cfg.crate_prefix = "myapp-plugin-".into;
cfg.entry_symbol = b"myapp_plugin_entry_v1".to_vec;
cfg.contract_crate = "myapp-plugin".into;
cfg.wrapper_body = "myapp_plugin::export!({crate_ident}::create);\n".into;
let kit = new?;
kit.install?; // installs myapp-plugin-foo
for info in kit.list?
let plugin = kit.load?; // *const MyHostEntry
let entry: *const MyHostEntry = plugin.entry;
name accepts a short name ("foo", the crate prefix is added for you) or a full crate name.
Pass None as the version to take the latest from crates.io.
Configuration
KitConfig
is where every host-specific name lives. This crate hardcodes none of them.
| Field | Meaning |
|---|---|
id |
App id. Data dir becomes ~/.{id}. Also used in the HTTP User-Agent. |
manifest_name |
Plugin manifest filename, e.g. myapp-plugin.toml. |
crate_prefix |
Plugin crate prefix. install("foo") → myapp-plugin-foo. |
entry_symbol |
Exported symbol to look up, e.g. myapp_plugin_entry_v1. |
lib_stem_prefix |
cdylib filename prefix, e.g. myapp_plugin_. |
contract_crate / contract_version |
The host's contract crate — the generated wrapper depends on it. |
wrapper_edition / wrapper_body |
Generated wrapper's edition and src/lib.rs body. {crate_ident} is substituted. |
data_dir |
Override ~/.{id}. Useful for tests. |
lock_timeout |
How long to wait for the install lock. Default 30s. |
prefer_prebuilt |
Try GitHub Releases before falling back to a local build. Default true. |
target_triple |
Override the compile-time target. |
registry |
crates.io base URL. Point it at a mirror if you like. |
local_overrides |
crate name → local path. Becomes the wrapper's [patch.crates-io]. Dev only. |
KitConfig::new(id) fills in conservative defaults; you must at least set crate_prefix,
entry_symbol, lib_stem_prefix, contract_crate and wrapper_body, or the generated
wrapper will not compile.
Why local_overrides is needed
The wrapper lives under <data-dir>/build/, so it cannot see your project's
.cargo/config.toml. To make a wrapper build against a local checkout during development,
the host has to say so explicitly, and this crate writes it into the wrapper's own
[patch.crates-io].
On-disk layout
~/.{id}/
├── plugins/
│ ├── myapp-plugin-foo/
│ │ ├── myapp-plugin.toml ← manifest (written at install time)
│ │ └── libmyapp_plugin_foo.so
│ └── .plugins.json ← install record cache
├── build/ ← generated wrappers
│ └── myapp-plugin-foo/
└── .lock ← cross-process install lock
.plugins.json is a cache, not a source of truth. Lose it or corrupt it and list()
rebuilds from the manifests on disk.
How install works
Two paths. build-host is the default, because it shells out to cargo and therefore
honours whatever registry or mirror the user already configured. The prebuilt path goes to
GitHub, which bypasses all of that — so it is only ever an accelerator.
| Path | What it does | Requires |
|---|---|---|
| build-host (default) | generate wrapper → cargo build --release → copy artifact |
a Rust toolchain |
| prebuilt | download cdylib + manifest from GitHub Releases | the plugin author published assets |
install(name, version)
├─ take the lock at <data-dir>/.lock
├─ normalise the crate name (add the prefix)
├─ resolve the version (query crates.io when None)
├─ drop any previous install directory
├─ [prefer_prebuilt] try prebuilt ── ok ──▶ done
│ └─ unavailable ─┐
└─────────────────────────────────────────────────◄─┘
generate wrapper → cargo metadata → cargo build --release
→ find the cdylib → copy cdylib + manifest → update .plugins.json
If prebuilt is unavailable for any reason — never published, 404, network failure — install
silently falls back to build-host. The two paths are independent, and the cargo one
often succeeds where GitHub is unreachable.
cargo build inherits stdio, so you see its progress. That step can take minutes; swallowing
the output would be a poor experience.
Versions are pinned exactly (=x.y.z), so the version recorded in .plugins.json and the
cdylib that was actually built can never disagree.
Prebuilt assets
Two raw files rather than an archive, which saves pulling in the tar, gzip and zip crates:
{crate}-{version}-{target}.{so|dylib|dll} ← the cdylib
{crate}-{version}-{target}.toml ← the manifest
For example:
myapp-plugin-foo-0.1.0-x86_64-pc-windows-msvc.dll
myapp-plugin-foo-0.1.0-x86_64-pc-windows-msvc.toml
The repository URL comes from the crate's repository field on crates.io — at that point
the plugin is not installed yet, so the registry is the only thing that can be asked.
Where the manifest comes from
The plugin crate ships <manifest_name> at its source root. During a build-host install,
this crate locates the crate source through cargo metadata and copies the file into the
install directory:
cargo metadata --format-version 1 --manifest-path <wrapper>/Cargo.toml
→ find the entry in packages[] whose name matches the plugin crate
→ take the parent of its manifest_path — that is the crate source directory
→ copy <manifest_name> from there
This keeps a single source of truth: a plugin's metadata travels with its code. And detection
at runtime stays a plain file read — no dlopen is needed just to list plugins.
What it does not do
- No ABI validation. It has no idea what is inside
T. Checkingabi_versionis the host contract crate's job. - No
catch_unwindcall sites. A helper is provided (panic::guard), but the contract crate is what knows which calls cross the boundary, so it must wrap them. - No async. Installing starts a
cargo build; loading isdlopen. Both are synchronous. - No source restrictions. No allowlist, no signature checks, no sandbox — the same trust
model as
cargo install.
The dividing line is one question: does the operation need to know what is inside T?
| Operation | Needs T's contents? |
Owner |
|---|---|---|
| install / uninstall / list | no | this crate |
dlopen, look up the symbol, cast to *const T |
no | this crate |
| query crates.io | no | this crate |
validate abi_version |
yes | contract crate |
call command() / name() |
yes | contract crate |
| manage cross-boundary string lifetimes | yes | contract crate |
Development
crate-plugin-kit/
├── Cargo.toml # [package] + single-element [workspace]
├── build.rs # injects the target triple
├── docs/proposal.md # design notes
├── src/
│ ├── lib.rs # public exports + crate docs
│ ├── config.rs # KitConfig / KitPaths
│ ├── error.rs # KitError
│ ├── manifest.rs # manifest schema + read/write
│ ├── store.rs # CratePluginKit<T>
│ ├── loader.rs # generic dlopen, no type erasure
│ ├── lock.rs # cross-process file lock
│ ├── cache.rs # .plugins.json
│ ├── registry.rs # crates.io queries
│ ├── panic.rs # catch_unwind helper
│ └── install/
│ ├── build_host.rs # generated wrapper + cargo build (default)
│ └── prebuilt.rs # GitHub Releases download (accelerator)
└── tests/
├── load.rs # end-to-end: build a cdylib, dlopen it, call across
└── fixtures/toy-plugin/ # the zero-dependency cdylib used by that test
tests/load.rs is the one that matters most: it compiles the fixture into a real
cdylib, copies it into a temporary plugin store, then dlopens it and calls a function
pointer across the boundary. Everything else is file I/O and string derivation.
On rust-toolchain.toml
There deliberately isn't one. Two reasons:
- A pinned channel would override the CI job that tests the MSRV, which is the thing
rust-versioninCargo.tomlactually promises; - pinning an exact version forces contributors to download a whole extra toolchain,
while
rust-versionplus CI already covers the real problem.
The generated wrapper does not get one either — it inherits whatever toolchain you are already using.
Repository
https://github.com/imba97/crate-plugin-kit
License
MIT — see LICENSE.