feat: add __wasm/rust-wasm-plugins-examples/
This commit is contained in:
23
README.md
23
README.md
@@ -5,7 +5,6 @@ Simple Rust Tests
|
||||
Project or files:
|
||||
```
|
||||
.
|
||||
├── README_2.md
|
||||
├── __alloc
|
||||
│ └── zeroizing-alloc-demo
|
||||
├── __args
|
||||
@@ -18,8 +17,8 @@ Project or files:
|
||||
│ └── zstd-demo
|
||||
├── __concurrent
|
||||
│ ├── arc-swap
|
||||
│ ├── async-fn-resumed-after-completion
|
||||
│ ├── async_study
|
||||
│ ├── async-fn-resumed-after-completion
|
||||
│ ├── crossbeam_n_parking_lot
|
||||
│ ├── glommio
|
||||
│ ├── green-threads
|
||||
@@ -78,7 +77,7 @@ Project or files:
|
||||
│ └── sqlx
|
||||
├── __diff
|
||||
│ ├── diffy
|
||||
│ └── prettydiff
|
||||
│ ├── prettydiff
|
||||
├── __enclave
|
||||
│ └── virt_enclave
|
||||
├── __err
|
||||
@@ -90,9 +89,9 @@ Project or files:
|
||||
├── __ffi
|
||||
│ ├── abi_stable_crates
|
||||
│ ├── c
|
||||
│ ├── c2
|
||||
│ ├── c_export
|
||||
│ ├── c_layout
|
||||
│ ├── c2
|
||||
│ ├── calltoc
|
||||
│ ├── cpp
|
||||
│ ├── dotalib
|
||||
@@ -103,7 +102,7 @@ Project or files:
|
||||
├── __fs
|
||||
│ ├── crypt4ghfs-rust
|
||||
│ ├── fuse
|
||||
│ └── fuser
|
||||
│ ├── fuser
|
||||
├── __gui
|
||||
│ ├── druid
|
||||
│ ├── gtk
|
||||
@@ -177,8 +176,8 @@ Project or files:
|
||||
│ ├── ngrok-demo
|
||||
│ ├── pcap
|
||||
│ ├── quinn
|
||||
│ ├── rust-rawsock-demo
|
||||
│ ├── rust_tcp
|
||||
│ ├── rust-rawsock-demo
|
||||
│ ├── s2n_quic
|
||||
│ ├── socket2
|
||||
│ ├── tcp
|
||||
@@ -223,10 +222,10 @@ Project or files:
|
||||
│ ├── sshrs
|
||||
│ └── xshell
|
||||
├── __shuttle
|
||||
│ └── hatter-test
|
||||
│ ├── hatter-test
|
||||
├── __std
|
||||
│ ├── async-fn
|
||||
│ ├── async_await
|
||||
│ ├── async-fn
|
||||
│ ├── into
|
||||
│ ├── iter
|
||||
│ ├── misc
|
||||
@@ -261,14 +260,15 @@ Project or files:
|
||||
│ ├── deno_rust_wasm_qr_decode
|
||||
│ ├── extism
|
||||
│ ├── js-wasm
|
||||
│ ├── rust-wasm-plugins-examples
|
||||
│ ├── wasi
|
||||
│ ├── wasm
|
||||
│ ├── wasmtime
|
||||
│ ├── wasmtime-serde-demo
|
||||
│ └── wit-bindgen-sample
|
||||
├── __web
|
||||
│ ├── actix-web
|
||||
│ ├── actix_rustls
|
||||
│ ├── actix-web
|
||||
│ ├── alibabacloundfn
|
||||
│ ├── hyper_rustls
|
||||
│ ├── hyperrs
|
||||
@@ -282,8 +282,9 @@ Project or files:
|
||||
│ ├── tide
|
||||
│ └── warp
|
||||
├── build_readme.rs -> scripts/build_readme_rs/src/main.rs
|
||||
├── README_2.md
|
||||
├── scripts
|
||||
│ └── build_readme_rs
|
||||
│ ├── build_readme_rs
|
||||
└── single_file_tests
|
||||
├── 99.rs
|
||||
├── chain.rs
|
||||
@@ -307,6 +308,6 @@ Project or files:
|
||||
├── vec.rs
|
||||
└── while.rs
|
||||
|
||||
279 directories, 38 files
|
||||
280 directories, 38 files
|
||||
```
|
||||
|
||||
|
||||
3
__wasm/rust-wasm-plugins-examples/.gitignore
vendored
Normal file
3
__wasm/rust-wasm-plugins-examples/.gitignore
vendored
Normal file
@@ -0,0 +1,3 @@
|
||||
target/
|
||||
work/
|
||||
.cargo/
|
||||
2664
__wasm/rust-wasm-plugins-examples/Cargo.lock
generated
Normal file
2664
__wasm/rust-wasm-plugins-examples/Cargo.lock
generated
Normal file
File diff suppressed because it is too large
Load Diff
8
__wasm/rust-wasm-plugins-examples/Cargo.toml
Normal file
8
__wasm/rust-wasm-plugins-examples/Cargo.toml
Normal file
@@ -0,0 +1,8 @@
|
||||
[workspace]
|
||||
resolver = "3"
|
||||
members = ["host", "plugin"]
|
||||
|
||||
# This will create smaller Wasm files
|
||||
[profile.release]
|
||||
strip = "debuginfo"
|
||||
lto = true
|
||||
201
__wasm/rust-wasm-plugins-examples/LICENSE-APACHE
Normal file
201
__wasm/rust-wasm-plugins-examples/LICENSE-APACHE
Normal file
@@ -0,0 +1,201 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "{}"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright {yyyy} {name of copyright owner}
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
19
__wasm/rust-wasm-plugins-examples/LICENSE-MIT
Normal file
19
__wasm/rust-wasm-plugins-examples/LICENSE-MIT
Normal file
@@ -0,0 +1,19 @@
|
||||
Copyright (c) Individual contributors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
70
__wasm/rust-wasm-plugins-examples/README.md
Normal file
70
__wasm/rust-wasm-plugins-examples/README.md
Normal file
@@ -0,0 +1,70 @@
|
||||
Rust Wasm Plugins Example
|
||||
=========================
|
||||
|
||||
A Great Fit
|
||||
-----------
|
||||
|
||||
You've probably heard that [Wasm](https://web.dev/explore/webassembly) (WebAssembly) can be a great way to support plugins in your application. Plugin authors can write them in any Wasm-compatible language and you're off to the races with your choice among various excellent and safe Wasm runtimes for Rust, including ones optimized for embedded environments (e.g. [wasmi](https://github.com/wasmi-labs/wasmi)).
|
||||
|
||||
Not So Easy
|
||||
-----------
|
||||
|
||||
Unfortunately, you're going to find out (in early 2025, when this is written) that examples of this often-mentioned use case are hard to come by, and that so much of the documentation is irrelevant, confusing, incomplete, or just out of date, as things have been moving quite quickly in the Wasm world.
|
||||
|
||||
If you've read Surma's [Rust to WebAssembly the hard way](https://surma.dev/things/rust-to-webassembly/) (highly recommended starting point!) then you might feel quite confident in your ability to build `.wasm` modules, load them into Rust, call functions in them, and expose functions to them. But the hard way becomes a dead end as you realize something quite critical: Wasm only supports the transfer of just primitive numeric types, namely integers and floats (and not even unsigned integers). This is an intentional and understandable design choice to keep Wasm lean and mean and agnostic to any specific implementation.
|
||||
|
||||
But this means that if you want to transfer something as basic as a string or a vector then you'll have to delve deep into the the Wasm memory model.
|
||||
|
||||
People have come up with various solutions for Rust, from piggy-backing on [std::ffi::CString](https://doc.rust-lang.org/std/ffi/struct.CString.html) to exposing custom malloc/free functions to the Wasm module. But not only are these solutions painful, they would obviously need to be ported to every language we want to support, each with its own string and array models. There was, and still is, a need for some kind of standard, built on top of Wasm, that would support higher-level constructs in a portable way.
|
||||
|
||||
The Temporary Solutions
|
||||
-----------------------
|
||||
|
||||
It took some time for the community to rally around one. For a while, a promising proposal was Wasm Interfaces (WAI). This was [pioneered by Wasmer](https://github.com/wasmerio/wai), where the [documentation](https://docs.wasmer.io/wai) still points to it as "the" solution (early 2025). As usual in the Wasm world, even that documentation can only take you so far. None of it actually mentions hosting WAI in Rust! And it only shows importing interfaces, not exporting them, though I have managed to learn how to handle exports by delving into the WAI tooling source code. The idea behind
|
||||
WAI is that you describe your interface in a [`.wai` file](https://github.com/wasmerio/wai/blob/main/WAI.md) and use tooling (e.g. macros) to generate the boilerplate code for clients and hosts, a lot like how things work with RPC protocols (e.g. protobufs).
|
||||
|
||||
WAI had not been widely adopted, however it does work and is also quite straightforward. We won't be using it in this example, but it's useful to be aware of its existence.
|
||||
|
||||
Also check out [Extism](https://extism.org/), a more comprehensive attempt to fill in the gap.
|
||||
|
||||
The Consensus Solution
|
||||
----------------------
|
||||
|
||||
But the consensus now seems to be around the [Wasm Component Model](https://component-model.bytecodealliance.org/), which expands on the WAI proposal with proper namespacing, resources, and richer custom data types. The Component Model is actually part of WASI, and indeed is being used to provide the WASI extensions. So, what's [WASI](https://wasi.dev/)? It's an initiative by the community to deliver a set of common APIs on top of Wasm for accessing streams, like files and stdout/stderr, network sockets, and eventually threads. I say "eventually" because WASI is still very much a work in progress. As of now (early 2025) we just got "preview 2" of it. Luckily, Rust can target "wasip2", meaning that it can be used to create the latest and greatest Components. Though, note that wasip2 does produce larger minimal `.wasm` files than WAI due to the inclusion of the machinery for the Component Model.
|
||||
|
||||
Like WAI, the Component Model relies on an interface definition file, [`.wit`](https://component-model.bytecodealliance.org/design/wit.html). And [Wasmtime](https://wasmtime.dev/) has the tooling for it! Yay! So, are we finally off to the races with our plugin system?
|
||||
|
||||
Not so fast. Again, finding examples and straightforward documentation is not easy. Wasmtime is a very comprehensive and performative implementation, but it's also designed by committee and has a lot of contributors. And due to the fast-moving nature of these things, what you find might not represent what is actually going on or what you should be using.
|
||||
|
||||
Finally We Get to the Point
|
||||
---------------------------
|
||||
|
||||
All that to say, that's why I created this repository. It's intended to be a minimal and straightforward example of how to build plugins in Rust (as Components) and how to host them in your application using Wasmtime and its WIT tooling. Well, at least for early 2025... As of now it does not demonstrate the more advanced features of WIT, such as custom data types, but I might add those in the future.
|
||||
|
||||
How to Build and Run
|
||||
--------------------
|
||||
|
||||
There are two crates here, a plugin, which builds into a wasip2 `.wasm`, and a host, which can be built into any Rust target architecure.
|
||||
|
||||
```sh
|
||||
rustup target add wasm32-wasip2
|
||||
git clone https://github.com/tliron/rust-wasm-plugins-examples.git
|
||||
cd rust-wasm-plugins-examples
|
||||
./run.sh
|
||||
```
|
||||
|
||||
Things to See
|
||||
-------------
|
||||
|
||||
* [Rust to WebAssembly the hard way](https://surma.dev/things/rust-to-webassembly/) by Surma
|
||||
* [Plugins with Rust and WASI Preview 2](https://benw.is/posts/plugins-with-rust-and-wasi) by Ben Wishovich
|
||||
|
||||
License
|
||||
-------
|
||||
|
||||
Like much of the Rust ecosystem, licensed under your choice of either of
|
||||
|
||||
* [Apache License, Version 2.0](LICENSE-APACHE)
|
||||
* [MIT license](LICENSE-MIT)
|
||||
|
||||
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.
|
||||
@@ -0,0 +1,26 @@
|
||||
// Note that names *cannot* use underscores, but *can* use dashes
|
||||
// (In Rust the dashes are converted to underscores, as usual)
|
||||
// They also can't use numeric digits for some reason!
|
||||
|
||||
// A package can include more than one "world"
|
||||
// (=component, or plugin type for us),
|
||||
|
||||
package acme:plugins@1.0.0;
|
||||
|
||||
// This is what the host will expose to our plugins
|
||||
interface host {
|
||||
log: func(message: string);
|
||||
}
|
||||
|
||||
// This is what our plugins will expose to the host
|
||||
interface prettify-plugin {
|
||||
prettify: func(content: string) -> string;
|
||||
}
|
||||
|
||||
// We can create additional worlds per plugin type
|
||||
// You can import/export more than one interface
|
||||
// (as well as individual functions, types, and resources)
|
||||
world prettify {
|
||||
import host;
|
||||
export prettify-plugin;
|
||||
}
|
||||
22
__wasm/rust-wasm-plugins-examples/host/Cargo.toml
Normal file
22
__wasm/rust-wasm-plugins-examples/host/Cargo.toml
Normal file
@@ -0,0 +1,22 @@
|
||||
[package]
|
||||
edition = "2021"
|
||||
|
||||
name = "host"
|
||||
description = "Rust Wasm Plugins Example"
|
||||
version = "0.0.1"
|
||||
rust-version = "1.84"
|
||||
|
||||
license = "MIT OR Apache-2.0"
|
||||
repository = "https://github.com/tliron/rust-wasm-plugins-example"
|
||||
documentation = "https://github.com/tliron/rust-wasm-plugins-example"
|
||||
authors = ["Tal Liron"]
|
||||
|
||||
readme = "../README.md"
|
||||
|
||||
categories = ["wasm"] # https://crates.io/category_slugs
|
||||
keywords = ["wasm", "wasi", "wit", "wasmtime", "examples"]
|
||||
|
||||
[dependencies]
|
||||
anyhow = "1.0.97"
|
||||
wasmtime = "31.0.0"
|
||||
wasmtime-wasi = "31.0.0"
|
||||
3
__wasm/rust-wasm-plugins-examples/host/src/bindings.rs
Normal file
3
__wasm/rust-wasm-plugins-examples/host/src/bindings.rs
Normal file
@@ -0,0 +1,3 @@
|
||||
#![allow(missing_docs)]
|
||||
|
||||
wasmtime::component::bindgen!(in "../assets/wit/acme-plugins.wit");
|
||||
41
__wasm/rust-wasm-plugins-examples/host/src/host.rs
Normal file
41
__wasm/rust-wasm-plugins-examples/host/src/host.rs
Normal file
@@ -0,0 +1,41 @@
|
||||
use super::bindings::acme::plugins::host;
|
||||
|
||||
use wasmtime_wasi::{IoView, ResourceTable, WasiCtx, WasiCtxBuilder, WasiView};
|
||||
|
||||
//
|
||||
// Host
|
||||
//
|
||||
|
||||
/// Plugins host.
|
||||
pub struct Host {
|
||||
wasi: WasiCtx,
|
||||
resources: ResourceTable,
|
||||
}
|
||||
|
||||
impl Host {
|
||||
/// Constructor.
|
||||
pub fn new() -> Self {
|
||||
let wasi = WasiCtxBuilder::new().inherit_stdout().build();
|
||||
Self { wasi, resources: ResourceTable::new() }
|
||||
}
|
||||
}
|
||||
|
||||
// We need to implement WasiView for wasmtime_wasi::add_to_linker_sync
|
||||
impl WasiView for Host {
|
||||
fn ctx(&mut self) -> &mut WasiCtx {
|
||||
&mut self.wasi
|
||||
}
|
||||
}
|
||||
|
||||
impl IoView for Host {
|
||||
fn table(&mut self) -> &mut ResourceTable {
|
||||
&mut self.resources
|
||||
}
|
||||
}
|
||||
|
||||
// Our exposed Host functions
|
||||
impl host::Host for Host {
|
||||
fn log(&mut self, message: String) {
|
||||
println!("log: {}", message);
|
||||
}
|
||||
}
|
||||
11
__wasm/rust-wasm-plugins-examples/host/src/main.rs
Normal file
11
__wasm/rust-wasm-plugins-examples/host/src/main.rs
Normal file
@@ -0,0 +1,11 @@
|
||||
mod bindings;
|
||||
mod host;
|
||||
mod prettify;
|
||||
|
||||
use prettify::*;
|
||||
|
||||
pub fn main() {
|
||||
let mut prettify = Prettify::new("target/wasm32-wasip2/release/plugin.wasm").unwrap();
|
||||
let r = prettify.prettify("We will prettify this with a plugin").unwrap();
|
||||
println!("{}", r);
|
||||
}
|
||||
55
__wasm/rust-wasm-plugins-examples/host/src/prettify.rs
Normal file
55
__wasm/rust-wasm-plugins-examples/host/src/prettify.rs
Normal file
@@ -0,0 +1,55 @@
|
||||
use super::{bindings, host::*};
|
||||
|
||||
use {
|
||||
anyhow::Context,
|
||||
std::path,
|
||||
wasmtime::{component::*, Engine, Store},
|
||||
};
|
||||
|
||||
//
|
||||
// Prettify
|
||||
//
|
||||
|
||||
/// Prettify plugin.
|
||||
pub struct Prettify {
|
||||
store: Store<Host>,
|
||||
prettify: bindings::Prettify,
|
||||
}
|
||||
|
||||
// Wasmtime uses Anyhow for most of its errors
|
||||
// But you could potentially wrap it in your own "PluginError" or similar using .map_err
|
||||
// For this example we used .context
|
||||
|
||||
impl Prettify {
|
||||
/// Constructor.
|
||||
pub fn new<PathT>(module: PathT) -> Result<Self, anyhow::Error>
|
||||
where
|
||||
PathT: AsRef<path::Path>,
|
||||
{
|
||||
let engine = Engine::default();
|
||||
|
||||
// Component
|
||||
let component = Component::from_file(&engine, module).context("load component")?;
|
||||
|
||||
// Linker
|
||||
let mut linker = Linker::new(&engine);
|
||||
wasmtime_wasi::add_to_linker_sync(&mut linker).context("link WASI")?;
|
||||
bindings::Prettify::add_to_linker(&mut linker, |state: &mut Host| state).context("link plugin host")?;
|
||||
|
||||
// Store
|
||||
let mut store = Store::new(&engine, Host::new());
|
||||
|
||||
// Bindings
|
||||
let prettify =
|
||||
bindings::Prettify::instantiate(&mut store, &component, &linker).context("instantiate bindings")?;
|
||||
|
||||
Ok(Self { store, prettify })
|
||||
}
|
||||
|
||||
// We'll create convenience wrappers to make calling functions ergonomic:
|
||||
|
||||
/// Prettify.
|
||||
pub fn prettify(&mut self, name: &str) -> Result<String, anyhow::Error> {
|
||||
self.prettify.acme_plugins_prettify_plugin().call_prettify(&mut self.store, name)
|
||||
}
|
||||
}
|
||||
23
__wasm/rust-wasm-plugins-examples/plugin/Cargo.toml
Normal file
23
__wasm/rust-wasm-plugins-examples/plugin/Cargo.toml
Normal file
@@ -0,0 +1,23 @@
|
||||
[package]
|
||||
edition = "2021"
|
||||
|
||||
name = "plugin"
|
||||
description = "Rust Wasm Plugins Example"
|
||||
version = "0.0.1"
|
||||
rust-version = "1.84"
|
||||
|
||||
license = "MIT OR Apache-2.0"
|
||||
repository = "https://github.com/tliron/rust-wasm-plugins-example"
|
||||
documentation = "https://github.com/tliron/rust-wasm-plugins-example"
|
||||
authors = ["Tal Liron"]
|
||||
|
||||
readme = "../README.md"
|
||||
|
||||
categories = ["wasm"]
|
||||
keywords = ["wasm", "wasi", "wit", "wasmtime", "examples"]
|
||||
|
||||
[dependencies]
|
||||
wit-bindgen = "0.41.0"
|
||||
|
||||
[lib]
|
||||
crate-type = ["cdylib"]
|
||||
8
__wasm/rust-wasm-plugins-examples/plugin/src/bindings.rs
Normal file
8
__wasm/rust-wasm-plugins-examples/plugin/src/bindings.rs
Normal file
@@ -0,0 +1,8 @@
|
||||
// Note that we are using the full notation of the macro in order
|
||||
// to add some options that allow the bindings to live in this independent file
|
||||
|
||||
wit_bindgen::generate!({
|
||||
path: "../assets/wit/acme-plugins.wit",
|
||||
default_bindings_module: "crate::bindings",
|
||||
pub_export_macro: true,
|
||||
});
|
||||
2
__wasm/rust-wasm-plugins-examples/plugin/src/lib.rs
Normal file
2
__wasm/rust-wasm-plugins-examples/plugin/src/lib.rs
Normal file
@@ -0,0 +1,2 @@
|
||||
mod bindings;
|
||||
mod quote_prettify;
|
||||
@@ -0,0 +1,21 @@
|
||||
use super::bindings::{acme::plugins::host, export, exports::acme::plugins::prettify_plugin};
|
||||
|
||||
// This is our implementation of the "prettify" plugin type
|
||||
// (=WIT world)
|
||||
|
||||
// We shall make the content pretty by quoting all words
|
||||
|
||||
// Gorgeous!
|
||||
|
||||
pub struct QuotePrettifyPlugin;
|
||||
|
||||
export!(QuotePrettifyPlugin);
|
||||
|
||||
impl prettify_plugin::Guest for QuotePrettifyPlugin {
|
||||
fn prettify(content: String) -> String {
|
||||
host::log("thank you for using the quote prettify plugin!");
|
||||
let words = content.split(" ");
|
||||
let words: Vec<String> = words.map(|word| format!("{:?}", word)).collect();
|
||||
words.join(" ")
|
||||
}
|
||||
}
|
||||
4
__wasm/rust-wasm-plugins-examples/run.sh
Executable file
4
__wasm/rust-wasm-plugins-examples/run.sh
Executable file
@@ -0,0 +1,4 @@
|
||||
#!/bin/bash
|
||||
|
||||
cargo build --package=plugin --target=wasm32-wasip2 --release
|
||||
cargo run --package=host
|
||||
2
__wasm/rust-wasm-plugins-examples/rustfmt.toml
Normal file
2
__wasm/rust-wasm-plugins-examples/rustfmt.toml
Normal file
@@ -0,0 +1,2 @@
|
||||
max_width = 120
|
||||
use_small_heuristics = "Max"
|
||||
Reference in New Issue
Block a user