commit b31187a757a9d7c254cdce6b89094cfea2c750e7 Author: cflmy Date: Thu Nov 26 19:32:14 2026 +0800 sdk: standalone marqdo-plugin-sdk workspace Independent SDK consumer of the Marqdo plugin ABI v1: - public contract pinned to CLI commit 2585915e16906dac75f8571bed02e7f6f868c6bc; - no CLI checkout, native host, loader or worker dependency; - third-party fixture built only with this SDK; - frozen-CLI integration check (Int 42 + tampered digest rejection) against the released 3.0.0-rc.4 archive; - AGENTS rules, README, license and Woodpecker CI. diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..51cd382 --- /dev/null +++ b/.gitignore @@ -0,0 +1,8 @@ +/target +/tests/fixture/target +**/*.rs.bk +__pycache__/ +*.pyc +.DS_Store +frozen/ +*.tar.gz diff --git a/.woodpecker/main.yml b/.woodpecker/main.yml new file mode 100644 index 0000000..fc27d5d --- /dev/null +++ b/.woodpecker/main.yml @@ -0,0 +1,27 @@ +when: + event: [push, pull_request] + +steps: + # The SDK is a leaf workspace: it resolves the public contract from one fixed + # CLI commit, builds the third-party fixture and runs the integration against + # a frozen released CLI (never a CLI checkout). + test: + image: rust:1.100-bookworm + commands: + - rustup component add clippy rustfmt + - apt-get update + - apt-get install -y --no-install-recommends ca-certificates curl python3 + - cargo fmt --all -- --check + - cargo clippy --all-targets --locked -- -D warnings + - cargo test --locked + - cargo build --locked + - cargo build --locked --manifest-path tests/fixture/Cargo.toml + - | + set -eu + version="3.0.0-rc.4" + archive="marqdo-${version}-x86_64-unknown-linux-gnu.tar.gz" + curl -fsSL -o "$archive" \ + "https://git.cflmy.cn/cflmy/marqdo-cli/releases/download/v${version}/${archive}" + mkdir -p frozen + tar -xzf "$archive" -C frozen --strip-components=1 + python3 tools/check_with_frozen_cli.py --marqdo-bin "$PWD/frozen/marqdo" diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..5f50eb2 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,33 @@ +# Marqdo Plugin SDK — contributor/agent rules + +This repository is the **independent SDK consumer** of the Marqdo plugin ABI +v1. Read these rules before changing it. + +1. **One contract authority.** The C header, Rust layout, wire envelope and + error encoding are owned by + [`cflmy/marqdo-cli`](https://git.cflmy.cn/cflmy/marqdo-cli) (`marqdo-plugin-abi`, + `include/marqdo_plugin_abi_v1.h`, `spec/plugin-abi.md`). This repository must + never define a second ABI, a second Value Wire encoder, or a compatibility + path. +2. **Exact contract input.** `marqdo-plugin-abi` is consumed via a Cargo git + `rev` fixed in `Cargo.toml` and `Cargo.lock`. Do not point at a floating + branch, a local `../cli` path, or an unpublished copy. +3. **No execution side.** The SDK must not depend on `libloading`, a host, + worker process management, sandbox or CLI code. It is a leaf; the CLI does + not depend on this repository. +4. **No silent ABI changes.** Layout, buffer ownership, limits and error codes + are frozen at ABI 1.0. A change requires a new CLI contract major and a new + SDK release. +5. **Verify with a frozen CLI.** Build and test with the workspace; for the real + integration use `tools/check_with_frozen_cli.py --marqdo-bin `. Never claim an integration PASS from unit tests alone. +6. **Security wording.** A C ABI is not a sandbox. Do not describe this SDK, + native plugins or the worker transport as isolation. +7. **Update the pin deliberately.** Bumping the CLI contract `rev` is a reviewable + change: update `Cargo.toml` + `Cargo.lock`, rerun the frozen-CLI check, and + record the CLI SHA and SDK SHA in the PR. +8. Keep `cargo fmt`, `cargo clippy --all-targets -D warnings`, `cargo test + --locked` and the fixture build green. + +Architecture decision: `docs/adr/0072-sdk-independent-repository.md` in the CLI +repository. Tracking issue: . diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..37aa2e3 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,194 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[package]] +name = "marqdo-plugin-abi" +version = "3.0.0-rc.4" +source = "git+https://git.cflmy.cn/cflmy/marqdo-cli.git?rev=2585915e16906dac75f8571bed02e7f6f868c6bc#2585915e16906dac75f8571bed02e7f6f868c6bc" +dependencies = [ + "marqdo-value", + "serde", + "serde_json", + "thiserror", +] + +[[package]] +name = "marqdo-plugin-sdk" +version = "3.0.0-rc.4" +dependencies = [ + "marqdo-plugin-abi", + "serde", + "serde_json", +] + +[[package]] +name = "marqdo-span" +version = "3.0.0-rc.4" +source = "git+https://git.cflmy.cn/cflmy/marqdo-cli.git?rev=2585915e16906dac75f8571bed02e7f6f868c6bc#2585915e16906dac75f8571bed02e7f6f868c6bc" +dependencies = [ + "serde", +] + +[[package]] +name = "marqdo-value" +version = "3.0.0-rc.4" +source = "git+https://git.cflmy.cn/cflmy/marqdo-cli.git?rev=2585915e16906dac75f8571bed02e7f6f868c6bc#2585915e16906dac75f8571bed02e7f6f868c6bc" +dependencies = [ + "marqdo-span", + "num-bigint", + "num-traits", + "serde", + "serde_json", +] + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "num-bigint" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367" +dependencies = [ + "num-integer", + "num-traits", + "serde", +] + +[[package]] +name = "num-integer" +version = "0.1.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..da62642 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,18 @@ +[package] +name = "marqdo-plugin-sdk" +description = "Rust SDK for writing Marqdo plugins against the versioned plugin ABI v1" +version = "3.0.0-rc.4" +edition = "2021" +rust-version = "1.89" +license = "Apache-2.0" +repository = "https://git.cflmy.cn/cflmy/marqdo-plugin-sdk" +authors = ["Marqdo contributors"] + +# This repository is its own workspace: it must resolve without the CLI +# checkout. The public contract is consumed from one exact CLI commit. +[workspace] + +[dependencies] +marqdo-plugin-abi = { git = "https://git.cflmy.cn/cflmy/marqdo-cli.git", rev = "2585915e16906dac75f8571bed02e7f6f868c6bc" } +serde = "1" +serde_json = "1" diff --git a/LICENSE-APACHE b/LICENSE-APACHE new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/LICENSE-APACHE @@ -0,0 +1,202 @@ + + 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. diff --git a/README.md b/README.md new file mode 100644 index 0000000..d7ac19a --- /dev/null +++ b/README.md @@ -0,0 +1,66 @@ +# Marqdo Plugin SDK + +Independent Rust SDK for the versioned Marqdo plugin ABI v1. It is the +plugin-developer side of the frozen C contract and contains no native loader, +host, worker process or CLI code. + +This repository is its own Cargo workspace. The public contract is consumed +from exactly one pinned CLI commit (`Cargo.toml` → `marqdo-plugin-abi` git +`rev`); it never uses a relative `../cli` checkout and never duplicates the ABI +or Value Wire encodings. + +## What it provides + +- `mq_plugin_entry!` exporting the required `mq_plugin_entry_v1` symbol; +- safe wrappers over the C layout and buffer ownership rules; +- typed wire helpers (`decode_request`, `int_arg`, `text_arg`, `success`, ...) + that reuse the CLI's single Value Wire encoder through the contract; +- `PluginError`/result-code mapping from the public ABI contract. + +The normative C header +[`include/marqdo_plugin_abi_v1.h`](https://git.cflmy.cn/cflmy/marqdo-cli/blob/master/include/marqdo_plugin_abi_v1.h) +and [`spec/plugin-abi.md`](https://git.cflmy.cn/cflmy/marqdo-cli/blob/master/spec/plugin-abi.md) +remain owned by the CLI repository. This SDK does not define a second protocol. + +## Build + +```bash +cargo build --locked +cargo test --locked +cargo clippy --all-targets -- -D warnings +``` + +## Cross-repository acceptance with a frozen CLI + +The fixture in `tests/fixture` is a third-party plugin built with only this SDK +(no CLI sources, no native host). Build it and invoke it through a released CLI +binary: + +```bash +# from a released archive (CLI + marqdo-provider-worker) +export MARQDO_BIN=/absolute/path/to/marqdo +python3 tools/check_with_frozen_cli.py --marqdo-bin "$MARQDO_BIN" +``` + +The script checks a real `Int 42` result and that a tampered artifact digest is +rejected. It never recompiles the CLI. + +## Security + +A C ABI is not a sandbox. Loading a native plugin requires an explicit trust +decision by the host; `--allow-plugin` is a separate grant. This SDK grants no +capability and does not claim isolation. + +## Versioning + +The SDK version tracks the contract generation, not the CLI product version. +Plugin ABI 1.0 layout, buffer ownership, limits and error codes are frozen; a +definitional change requires the CLI contract owner to publish a new ABI major +and a new SDK release. + +## Related + +- CLI contract producer: +- Architecture decision for this split: + `docs/adr/0072-sdk-independent-repository.md` in the CLI repository +- Tracking issue: diff --git a/src/bytes.rs b/src/bytes.rs new file mode 100644 index 0000000..90b3a4f --- /dev/null +++ b/src/bytes.rs @@ -0,0 +1,156 @@ +//! Safe wrappers around the raw `MqBytes` / `MqOwnedBytes` ABI buffers. +//! +//! Ownership rules (see the canonical header): +//! - [`BytesRef`] is a borrowed, validated view of host input; it is only +//! valid for the call that produced it. +//! - [`HostBuffer`] is plugin output allocated with the host allocator and +//! handed back to the host, which frees it after copying. + +use std::ffi::c_void; +use std::marker::PhantomData; +use std::ptr; + +use marqdo_plugin_abi::abi::{MqBytes, MqHostApi, MqOwnedBytes}; + +use crate::PluginError; + +/// Validated borrowed view of an ABI byte buffer (`MqBytes`). +pub struct BytesRef<'a> { + raw: MqBytes, + _marker: PhantomData<&'a [u8]>, +} + +impl<'a> BytesRef<'a> { + /// Validate a raw borrowed buffer. + /// + /// # Safety + /// + /// If `raw.len > 0`, `raw.data` must point to `raw.len` initialized bytes + /// that stay alive for `'a`. Within the ABI, `'a` must not outlive the + /// call that produced the buffer. + pub unsafe fn from_raw(raw: MqBytes) -> Result { + raw.validate()?; + Ok(Self { + raw, + _marker: PhantomData, + }) + } + + /// The underlying raw ABI view. + pub fn as_raw(&self) -> MqBytes { + self.raw + } + + /// The bytes as a slice (valid for `'a`). + pub fn as_slice(&self) -> &'a [u8] { + if self.raw.len == 0 { + return &[]; + } + // SAFETY: `from_raw` validated the pointer/length pair and `'a` is + // tied to the caller's borrow guarantee. + unsafe { std::slice::from_raw_parts(self.raw.data, self.raw.len) } + } + + /// Length in bytes. + pub fn len(&self) -> usize { + self.raw.len + } + + /// Whether the buffer is empty. + pub fn is_empty(&self) -> bool { + self.raw.len == 0 + } +} + +/// A byte buffer allocated with the host allocator and owned by the host. +/// +/// The plugin writes its response/error wire into a [`HostBuffer`] and +/// transfers ownership through the ABI output parameter. The plugin must +/// never free this buffer itself; the host frees it after copying. +pub struct HostBuffer { + raw: MqOwnedBytes, +} + +impl HostBuffer { + /// The empty buffer `{NULL, 0}`. + pub fn empty() -> Self { + Self { + raw: MqOwnedBytes::EMPTY, + } + } + + /// Allocate a host buffer and copy `bytes` into it. + /// + /// `host` must be the host API table provided to the entry point (the SDK + /// stores it for the plugin lifetime). Returns an out-of-memory error if + /// the host allocator returns NULL. + pub fn copy_from(host: &MqHostApi, bytes: &[u8]) -> Result { + if bytes.is_empty() { + return Ok(Self::empty()); + } + // SAFETY: host alloc/free pointers are non-NULL and valid for the + // plugin lifetime (validated during the entry call). + let pointer = unsafe { (host.alloc)(host.host_data, bytes.len()) }; + if pointer.is_null() { + return Err(PluginError::invoke( + "out_of_memory", + "host allocator returned NULL for a plugin output buffer", + )); + } + // SAFETY: pointer has bytes.len() writable bytes and does not overlap + // the source slice. + unsafe { + ptr::copy_nonoverlapping(bytes.as_ptr(), pointer as *mut u8, bytes.len()); + } + Ok(Self { + raw: MqOwnedBytes::new(pointer as *mut u8, bytes.len()), + }) + } + + /// The raw owner-transfer buffer. + pub fn into_raw(self) -> MqOwnedBytes { + self.raw + } + + /// Length in bytes. + pub fn len(&self) -> usize { + self.raw.len + } + + /// Whether the buffer is empty. + pub fn is_empty(&self) -> bool { + self.raw.len == 0 + } +} + +/// Borrowed view of a capability reply or other host-allocated buffer. +/// +/// The plugin copies what it needs and then must release the buffer with the +/// host allocator; use [`release_host_buffer`]. +/// +/// # Safety +/// +/// `buffer` must be a host-allocated buffer that is still alive; the returned +/// slice must not outlive the release of that buffer. +pub unsafe fn reply_slice<'a>(buffer: MqOwnedBytes) -> &'a [u8] { + if buffer.len == 0 { + return &[]; + } + // SAFETY: host-allocated buffer is initialized for `buffer.len` bytes; the + // caller must not retain the slice beyond the release point. + unsafe { std::slice::from_raw_parts(buffer.data, buffer.len) } +} + +/// Release a host-allocated buffer through the host allocator. +/// +/// # Safety +/// +/// `buffer.data` must be NULL or a pointer returned by the host allocator +/// (`MqHostApi::alloc`) that has not been freed yet. +pub unsafe fn release_host_buffer(host: &MqHostApi, buffer: MqOwnedBytes) { + if buffer.data.is_null() { + return; + } + // SAFETY: alloc/free pair and non-NULL pointer per the caller contract. + unsafe { (host.free)(host.host_data, buffer.data as *mut c_void) }; +} diff --git a/src/call.rs b/src/call.rs new file mode 100644 index 0000000..a484e91 --- /dev/null +++ b/src/call.rs @@ -0,0 +1,115 @@ +//! Per-invocation context passed to plugin handlers. +//! +//! The context is valid only for the duration of one invocation. It exists to +//! carry host capabilities into the plugin: capability requests are answered +//! by the host's authorization layer and can never be escalated by plugin +//! code. Do not cache this value, its raw pointer or any capability token. + +use marqdo_plugin_abi::abi::{ + MqBytes, MqCallContext, MqHostApi, MqOwnedBytes, MAX_CAPABILITY_REPLY_BYTES, +}; +use marqdo_plugin_abi::PluginError; + +use crate::bytes; + +/// Context for one plugin invocation. +pub struct CallContext { + raw: *mut MqCallContext, + host: &'static MqHostApi, +} + +impl CallContext { + /// Wrap the host-provided context pointer. + /// + /// # Safety + /// + /// `raw` must be the context pointer provided by the host for the current + /// invocation, and `host` must be the validated host API table. + pub(crate) unsafe fn new(raw: *mut MqCallContext, host: &'static MqHostApi) -> Self { + Self { raw, host } + } + + /// The host API table of this plugin instance. + pub fn host(&self) -> &'static MqHostApi { + self.host + } + + /// Request an already-authorized host capability for this call. + /// + /// `request` is a UTF-8 JSON capability request; the reply is opaque bytes + /// owned by the host. The SDK copies the reply and releases the host buffer. + pub fn capability_request( + &mut self, + name: &str, + request: &[u8], + ) -> Result, PluginError> { + if self.raw.is_null() { + return Err(PluginError::capability( + "missing_call_context", + "capability request requires an active invocation context", + )); + } + let mut reply = MqOwnedBytes::EMPTY; + // SAFETY: raw context and host table are valid for this invocation. + let code = unsafe { + (self.host.request_capability)( + self.raw, + MqBytes::from_slice(name.as_bytes()), + MqBytes::from_slice(request), + &mut reply, + ) + }; + // SAFETY: host-allocated reply is initialized for `reply.len` bytes. + let reply_bytes = unsafe { reply.to_vec() }; + // SAFETY: the host allocated `reply` with its allocator for us; release + // it exactly once after copying. + unsafe { bytes::release_host_buffer(self.host, reply) }; + let reply_bytes = reply_bytes.map_err(|error| { + PluginError::capability( + "invalid_capability_reply", + "host capability reply violates the buffer contract", + ) + .with_detail(error.to_string()) + })?; + if reply_bytes.len() > MAX_CAPABILITY_REPLY_BYTES { + return Err(PluginError::capability( + "capability_reply_too_large", + format!( + "capability reply is {} bytes, limit is {MAX_CAPABILITY_REPLY_BYTES}", + reply_bytes.len() + ), + )); + } + if code != crate::result_code::OK { + return Err(PluginError::capability( + "capability_request_failed", + format!("host rejected capability request `{name}`"), + ) + .with_detail(format!( + "result code `{}` ({code})", + crate::result_code::name(code) + ))); + } + Ok(reply_bytes) + } + + /// Best-effort structured log through the `log` capability. + pub fn log(&mut self, level: &str, message: &str) -> Result<(), PluginError> { + let request = serde_json::json!({"level": level, "message": message}); + let request = serde_json::to_vec(&request).map_err(|error| { + PluginError::capability("log_encode_failed", "could not encode log request") + .with_detail(error.to_string()) + })?; + let _ = self.capability_request("log", &request)?; + Ok(()) + } +} + +impl std::fmt::Debug for CallContext { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("CallContext") + .field("raw", &self.raw) + .field("host", &(self.host as *const MqHostApi)) + .finish() + } +} diff --git a/src/entry.rs b/src/entry.rs new file mode 100644 index 0000000..84743e5 --- /dev/null +++ b/src/entry.rs @@ -0,0 +1,199 @@ +//! Entry-point plumbing used by [`mq_plugin_entry!`](crate::mq_plugin_entry). +//! +//! These functions are the "runtime" of the SDK macro. They are public so the +//! macro can reference them through `$crate` from a plugin crate, but they are +//! not intended for direct use. + +use std::panic::{catch_unwind, AssertUnwindSafe}; +use std::sync::atomic::{AtomicPtr, Ordering}; + +use marqdo_plugin_abi::abi::{ + check_host_api, result, MqBytes, MqCallContext, MqHostApi, MqOwnedBytes, MqPluginApi, + MqPluginInvoke, ABI_MAJOR, ABI_MINOR, MAX_ERROR_WIRE_BYTES, MAX_EXPORT_NAME_BYTES, + MAX_RESULT_WIRE_BYTES, +}; +use marqdo_plugin_abi::{PluginError, WireResponse}; + +use crate::bytes::{release_host_buffer, HostBuffer}; +use crate::call::CallContext; +use crate::HandlerFn; + +/// Host API table captured by the entry point for the plugin lifetime. +static CURRENT_HOST: AtomicPtr = AtomicPtr::new(std::ptr::null_mut()); + +/// The host API table captured at load time, if a plugin is loaded. +pub(crate) fn current_host() -> Option<&'static MqHostApi> { + let pointer = CURRENT_HOST.load(Ordering::SeqCst); + if pointer.is_null() { + return None; + } + // SAFETY: the pointer was stored from a validated host table and the host + // guarantees it is valid for the plugin lifetime (single-threaded model). + Some(unsafe { &*pointer }) +} + +/// Initialize the ABI tables for the generated entry point. +/// +/// # Safety +/// +/// `host` and `plugin` must be the pointers provided by the host to +/// `mq_plugin_entry_v1` and must satisfy the header contract. +pub unsafe fn initialize( + host: *const MqHostApi, + plugin: *mut MqPluginApi, + metadata: &'static [u8], +) -> i32 { + if plugin.is_null() { + return result::INVALID_ARGUMENT; + } + // SAFETY: host pointer comes from the host and is checked before use. + let negotiated = match unsafe { check_host_api(host) } { + Ok(version) => version, + Err(_) => return result::ABI_MISMATCH, + }; + if negotiated.major != ABI_MAJOR { + return result::ABI_MISMATCH; + } + CURRENT_HOST.store(host as *mut MqHostApi, Ordering::SeqCst); + // SAFETY: plugin table is host-provided, writable and valid for this call. + unsafe { + (*plugin).struct_size = std::mem::size_of::() as u32; + (*plugin).abi_major = ABI_MAJOR; + (*plugin).abi_minor = ABI_MINOR; + (*plugin).plugin_metadata_wire = MqBytes::from_slice(metadata); + } + result::OK +} + +/// Register one export through the host table. +/// +/// # Safety +/// +/// `host` must be the table validated by [`initialize`]; both strings must be +/// valid UTF-8 dotted export names/signatures declared in `plugin.yaml`. +pub unsafe fn register_export( + host: *const MqHostApi, + name: &str, + signature: &str, + invoke: MqPluginInvoke, +) -> i32 { + if host.is_null() || name.is_empty() || name.len() > MAX_EXPORT_NAME_BYTES { + return result::INVALID_ARGUMENT; + } + // SAFETY: host pointer is non-NULL and valid for the plugin lifetime. + let host = unsafe { &*host }; + let signature_wire = match serde_json::to_vec(&serde_json::json!({"signature": signature})) { + Ok(bytes) => bytes, + Err(_) => return result::BAD_WIRE, + }; + // SAFETY: host table was validated; strings outlive the call. + unsafe { + (host.register_function)( + host.host_data, + MqBytes::from_slice(name.as_bytes()), + MqBytes::from_slice(&signature_wire), + invoke, + ) + } +} + +/// Dispatch one invocation to a plugin handler and write the response. +/// +/// # Safety +/// +/// Must be called as the body of a `MqPluginInvoke` callback with the buffers +/// provided by the host for that invocation. +pub unsafe fn dispatch( + handler: HandlerFn, + ctx: *mut MqCallContext, + args: MqBytes, + result_out: *mut MqOwnedBytes, + error_out: *mut MqOwnedBytes, +) -> i32 { + if result_out.is_null() || error_out.is_null() { + return result::INVALID_ARGUMENT; + } + // SAFETY: output pointers are non-NULL host-provided out-parameters. + unsafe { + *result_out = MqOwnedBytes::EMPTY; + *error_out = MqOwnedBytes::EMPTY; + } + let Some(host) = current_host() else { + return result::INTERNAL; + }; + // SAFETY: borrowed request buffer is valid for this callback. + let args_bytes = match unsafe { args.as_slice() } { + Ok(bytes) => bytes.to_vec(), + Err(_) => return result::INVALID_ARGUMENT, + }; + + // SAFETY: context pointer is the host-minted context for this invocation. + let mut context = unsafe { CallContext::new(ctx, host) }; + let outcome = catch_unwind(AssertUnwindSafe(|| handler(&mut context, &args_bytes))); + let response = match outcome { + Ok(Ok(bytes)) => Ok(bytes), + Ok(Err(error)) => Err(error), + Err(_) => Err(PluginError::invoke( + "plugin_panic", + "plugin handler panicked; the panic was caught at the ABI boundary", + )), + }; + + match response { + Ok(bytes) => { + if bytes.len() > MAX_RESULT_WIRE_BYTES { + return write_error( + host, + error_out, + &PluginError::wire( + "result_too_large", + format!( + "plugin result is {} bytes, limit is {MAX_RESULT_WIRE_BYTES}", + bytes.len() + ), + ), + ); + } + match HostBuffer::copy_from(host, &bytes) { + Ok(buffer) => { + // SAFETY: result_out is a valid out-parameter. + unsafe { *result_out = buffer.into_raw() }; + result::OK + } + Err(error) => write_error(host, error_out, &error), + } + } + Err(error) => write_error(host, error_out, &error), + } +} + +fn write_error(host: &'static MqHostApi, error_out: *mut MqOwnedBytes, error: &PluginError) -> i32 { + let encoded = match WireResponse::from_error(error).to_json_bytes() { + Ok(bytes) if bytes.len() <= MAX_ERROR_WIRE_BYTES => bytes, + _ => br#"{"wire_version":1,"kind":"response","error":{"kind":"invoke","code":"plugin_error","message":"plugin failed with an unencodable error"}}"#.to_vec(), + }; + let code = match error.kind { + marqdo_plugin_abi::ErrorKind::Wire => result::BAD_WIRE, + marqdo_plugin_abi::ErrorKind::Capability => result::CAPABILITY, + marqdo_plugin_abi::ErrorKind::Unsupported => result::UNSUPPORTED, + _ => result::INTERNAL, + }; + match HostBuffer::copy_from(host, &encoded) { + Ok(buffer) => { + // SAFETY: error_out is a valid out-parameter. + unsafe { *error_out = buffer.into_raw() }; + code + } + Err(_) => result::OUT_OF_MEMORY, + } +} + +/// Free a host-owned buffer (used by generated code/tests). +/// +/// # Safety +/// +/// `buffer` must have been allocated by the host allocator and not freed yet. +pub unsafe fn free_host_buffer(host: &MqHostApi, buffer: MqOwnedBytes) { + // SAFETY: caller guarantees the alloc/free pair. + unsafe { release_host_buffer(host, buffer) }; +} diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..5833938 --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,143 @@ +//! Rust SDK for writing Marqdo native plugins against plugin ABI v1. +//! +//! The SDK is the plugin-developer side of `include/marqdo_plugin_abi_v1.h`. +//! It hides the raw C layout behind safe wrappers and provides the +//! [`mq_plugin_entry!`] macro that exports the required +//! `mq_plugin_entry_v1` symbol: +//! +//! ``` +//! use marqdo_plugin_sdk::{mq_plugin_entry, CallContext, PluginError, Value}; +//! +//! fn add(_ctx: &mut CallContext, args: &[u8]) -> Result, PluginError> { +//! let request = marqdo_plugin_sdk::wire::decode_request(args)?; +//! let values = request.typed_args()?; +//! let a = marqdo_plugin_sdk::wire::int_arg(&values, "a")?; +//! let b = marqdo_plugin_sdk::wire::int_arg(&values, "b")?; +//! marqdo_plugin_sdk::wire::success(Some(Value::Int((a + b).into()))) +//! } +//! +//! mq_plugin_entry! { +//! name: "demo.solver", +//! version: "0.1.0", +//! exports: { +//! "solver.add" => "($a: Int, $b: Int) -> Int" => add, +//! } +//! } +//! ``` +//! +//! The SDK never depends on host-only crates: it only uses the shared ABI +//! types and the JSON wire envelope from `marqdo-plugin-abi`. Building a +//! plugin does not grant it any capability; authorization is a separate host +//! decision performed before loading. + +#![deny(missing_docs)] + +pub use marqdo_plugin_abi::abi::result as result_code; +pub use marqdo_plugin_abi::abi::{ + MqBytes, MqCallContext, MqHostApi, MqOwnedBytes, MqPluginApi, MqPluginInvoke, ABI_MAJOR, + ABI_MINOR, ABI_VERSION_STRING, ENTRY_SYMBOL, +}; +pub use marqdo_plugin_abi::{PluginError, Value, WireRequest, WireResponse, WIRE_VERSION}; + +pub mod bytes; +pub mod call; +pub mod entry; +pub mod wire; + +pub use bytes::{BytesRef, HostBuffer}; +pub use call::CallContext; +pub use wire::{ + bool_arg, decode_request, error_response, int_arg, response_value, success, success_raw, + text_arg, value_arg, +}; + +/// Plugin handler signature. +/// +/// A handler receives the per-call context (for capability requests and +/// logging) and the raw request envelope bytes, and returns the raw response +/// envelope bytes on success. +/// +/// Use [`wire::decode_request`] and [`wire::success`] to build the response; +/// handlers should never panic: panics are caught by the SDK and converted +/// into a structured error, but the plugin process stays healthy only if the +/// panic does not corrupt plugin state. +pub type HandlerFn = fn(&mut CallContext, &[u8]) -> Result, PluginError>; + +/// Declare a plugin and export `mq_plugin_entry_v1`. +/// +/// ```ignore +/// marqdo_plugin_sdk::mq_plugin_entry! { +/// name: "demo.solver", +/// version: "0.1.0", +/// exports: { +/// "solver.add" => "($a: Int, $b: Int) -> Int" => add, +/// "solver.echo" => "($text: Text) -> Text" => echo, +/// } +/// } +/// ``` +/// +/// Each handler is a path (or non-capturing closure) with the [`HandlerFn`] +/// signature. The macro: +/// - validates the host ABI table (major version and `struct_size`), +/// - reports the plugin ABI version and a metadata envelope, +/// - registers every export and fails the load if registration fails. +#[macro_export] +macro_rules! mq_plugin_entry { + ( + name: $name:literal, + version: $version:literal, + exports: { + $( $export_name:literal => $signature:literal => $handler:expr ),* $(,)? + } + ) => { + /// Marqdo plugin ABI v1 entry point (generated by the SDK macro). + #[unsafe(no_mangle)] + pub unsafe extern "C" fn mq_plugin_entry_v1( + host: *const $crate::MqHostApi, + plugin: *mut $crate::MqPluginApi, + ) -> i32 { + const METADATA: &[u8] = concat!( + "{\"name\":\"", $name, "\",\"version\":\"", $version, "\"}" + ) + .as_bytes(); + let metadata: &'static [u8] = METADATA; + // SAFETY: the host provides the ABI tables per the header contract. + let init = unsafe { $crate::entry::initialize(host, plugin, metadata) }; + if init != 0 { + return init; + } + $( + { + extern "C" fn invoke( + ctx: *mut $crate::MqCallContext, + args: $crate::MqBytes, + result: *mut $crate::MqOwnedBytes, + error: *mut $crate::MqOwnedBytes, + ) -> i32 { + // Expand the user's handler expression in a safe + // context (also required by `macro_metavars_in_unsafe`). + let handler: $crate::HandlerFn = $handler; + // SAFETY: the host owns the invocation buffers; the SDK + // validates them and never retains them. + unsafe { + $crate::entry::dispatch(handler, ctx, args, result, error) + } + } + let export_name: &str = $export_name; + let signature: &str = $signature; + // SAFETY: host table is valid for the plugin lifetime and + // was validated by `initialize`. + let code = + unsafe { $crate::entry::register_export(host, export_name, signature, invoke) }; + if code != 0 { + return code; + } + } + )* + $crate::result_code::OK + } + }; +} + +#[cfg(test)] +mod tests; diff --git a/src/tests.rs b/src/tests.rs new file mode 100644 index 0000000..2483884 --- /dev/null +++ b/src/tests.rs @@ -0,0 +1,245 @@ +//! End-to-end SDK tests: run the macro-generated entry point against a tiny +//! in-process host table and invoke the registered export. + +use std::ffi::c_void; +use std::ptr; + +use marqdo_plugin_abi::abi::{ + result, MqBytes, MqCallContext, MqHostApi, MqOwnedBytes, MqPluginApi, MqPluginInvoke, + ABI_MAJOR, ABI_MINOR, +}; + +use crate::wire; +use crate::{CallContext, PluginError, Value, WireRequest, WireResponse}; + +/// ABI v1 is single-threaded: the generated plugin stores the host table in a +/// process-global. Serialize tests that call the entry point so they do not +/// race (the SDK's own contract, not a test-only limitation). +static ABI_TEST_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(()); + +fn abi_test_lock() -> std::sync::MutexGuard<'static, ()> { + ABI_TEST_LOCK + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) +} + +#[derive(Default)] +struct TestHostState { + registrations: Vec<(String, String, MqPluginInvoke)>, +} + +unsafe extern "C" fn test_alloc(_host_data: *mut c_void, size: usize) -> *mut c_void { + const HEADER: usize = 16; + if size == 0 { + return ptr::null_mut(); + } + let Ok(layout) = std::alloc::Layout::from_size_align(size + HEADER, 16) else { + return ptr::null_mut(); + }; + // SAFETY: non-zero layout. + let base = unsafe { std::alloc::alloc(layout) }; + if base.is_null() { + return ptr::null_mut(); + } + // SAFETY: allocation has room for the header. + unsafe { (base as *mut usize).write(size) }; + // SAFETY: offset within the allocation. + unsafe { base.add(HEADER) as *mut c_void } +} + +unsafe extern "C" fn test_free(_host_data: *mut c_void, pointer: *mut c_void) { + const HEADER: usize = 16; + if pointer.is_null() { + return; + } + // SAFETY: only pointers from test_alloc are freed. + unsafe { + let base = (pointer as *mut u8).sub(HEADER); + let size = (base as *const usize).read(); + std::alloc::dealloc( + base, + std::alloc::Layout::from_size_align_unchecked(size + HEADER, 16), + ); + } +} + +unsafe extern "C" fn test_register( + host_data: *mut c_void, + export_name: MqBytes, + signature_wire: MqBytes, + invoke: MqPluginInvoke, +) -> i32 { + if host_data.is_null() { + return result::INVALID_ARGUMENT; + } + // SAFETY: host_data points at TestHostState for the test. + let state = unsafe { &mut *(host_data as *mut TestHostState) }; + // SAFETY: buffers are valid for this callback. + let name = match unsafe { export_name.as_slice() } { + Ok(bytes) => String::from_utf8_lossy(bytes).into_owned(), + Err(_) => return result::INVALID_ARGUMENT, + }; + // SAFETY: buffers are valid for this callback. + let signature = match unsafe { signature_wire.as_slice() } { + Ok(bytes) => String::from_utf8_lossy(bytes).into_owned(), + Err(_) => return result::INVALID_ARGUMENT, + }; + state.registrations.push((name, signature, invoke)); + result::OK +} + +unsafe extern "C" fn test_capability( + _ctx: *mut MqCallContext, + _name: MqBytes, + _request: MqBytes, + reply: *mut MqOwnedBytes, +) -> i32 { + if !reply.is_null() { + // SAFETY: output pointer is non-NULL. + unsafe { *reply = MqOwnedBytes::EMPTY }; + } + result::UNSUPPORTED +} + +fn add(_ctx: &mut CallContext, args: &[u8]) -> Result, PluginError> { + let request = wire::decode_request(args)?; + let values = request.typed_args()?; + let a = wire::int_arg(&values, "a")?; + let b = wire::int_arg(&values, "b")?; + wire::success(Some(Value::Int((a + b).into()))) +} + +crate::mq_plugin_entry! { + name: "sdk.test", + version: "0.1.0", + exports: { + "test.add" => "($a: Int, $b: Int) -> Int" => add, + } +} + +struct TestHost { + _state: Box, + api: MqHostApi, +} + +fn test_host() -> TestHost { + let mut state = Box::new(TestHostState::default()); + let api = MqHostApi { + struct_size: std::mem::size_of::() as u32, + abi_major: ABI_MAJOR, + abi_minor: ABI_MINOR, + host_data: (&mut *state) as *mut TestHostState as *mut c_void, + alloc: test_alloc, + free: test_free, + register_function: test_register, + request_capability: test_capability, + }; + TestHost { _state: state, api } +} + +#[test] +fn macro_exports_and_registers() { + let _guard = abi_test_lock(); + let host = test_host(); + let mut plugin_api = MqPluginApi::host_initialized(); + // SAFETY: test host table follows the ABI contract. + let code = unsafe { mq_plugin_entry_v1(&host.api as *const MqHostApi, &mut plugin_api) }; + assert_eq!(code, result::OK); + assert_eq!(plugin_api.abi_major, ABI_MAJOR); + assert_eq!(plugin_api.abi_minor, ABI_MINOR); + // SAFETY: metadata is plugin static data valid during the entry call. + let metadata = unsafe { plugin_api.plugin_metadata_wire.as_slice() }.expect("metadata"); + let metadata = String::from_utf8_lossy(metadata); + assert!(metadata.contains("\"name\":\"sdk.test\"")); + assert_eq!(host._state.registrations.len(), 1); + assert_eq!(host._state.registrations[0].0, "test.add"); + assert!(host._state.registrations[0] + .1 + .contains("($a: Int, $b: Int) -> Int")); +} + +#[test] +fn registered_export_roundtrips_wire_request() { + let _guard = abi_test_lock(); + let host = test_host(); + let mut plugin_api = MqPluginApi::host_initialized(); + // SAFETY: test host table follows the ABI contract. + let code = unsafe { mq_plugin_entry_v1(&host.api as *const MqHostApi, &mut plugin_api) }; + assert_eq!(code, result::OK); + + let request = WireRequest::new("test.add") + .with_arg("a", &Value::Int(20_i64.into())) + .with_arg("b", &Value::Int(22_i64.into())); + let request_bytes = request.to_json_bytes().expect("request"); + let (_, _, invoke) = &host._state.registrations[0]; + let mut result_buffer = MqOwnedBytes::EMPTY; + let mut error_buffer = MqOwnedBytes::EMPTY; + // SAFETY: invoke is the SDK callback; null ctx is fine because the handler + // does not request a capability. Buffers are valid out-parameters. + let code = unsafe { + invoke( + ptr::null_mut(), + MqBytes::from_slice(&request_bytes), + &mut result_buffer, + &mut error_buffer, + ) + }; + assert_eq!(code, result::OK); + assert!(error_buffer.is_empty()); + // SAFETY: result buffer was allocated by test_alloc for us. + let response_bytes = unsafe { result_buffer.to_vec() }.expect("result"); + // SAFETY: allocated by test_alloc; release exactly once. + unsafe { test_free(ptr::null_mut(), result_buffer.data as *mut c_void) }; + + let response = WireResponse::from_json_bytes(&response_bytes).expect("response"); + assert_eq!( + response.typed_value().expect("typed"), + Some(Value::Int(42_i64.into())) + ); +} + +#[test] +fn handler_error_is_written_as_error_envelope() { + let _guard = abi_test_lock(); + let host = test_host(); + let mut plugin_api = MqPluginApi::host_initialized(); + // SAFETY: test host table follows the ABI contract. + let code = unsafe { mq_plugin_entry_v1(&host.api as *const MqHostApi, &mut plugin_api) }; + assert_eq!(code, result::OK); + + let request = WireRequest::new("test.add"); // missing arguments + let request_bytes = request.to_json_bytes().expect("request"); + let (_, _, invoke) = &host._state.registrations[0]; + let mut result_buffer = MqOwnedBytes::EMPTY; + let mut error_buffer = MqOwnedBytes::EMPTY; + // SAFETY: invoke is the SDK callback with valid out-parameters. + let code = unsafe { + invoke( + ptr::null_mut(), + MqBytes::from_slice(&request_bytes), + &mut result_buffer, + &mut error_buffer, + ) + }; + assert_ne!(code, result::OK); + assert!(result_buffer.is_empty()); + // SAFETY: error buffer was allocated by test_alloc for us. + let error_bytes = unsafe { error_buffer.to_vec() }.expect("error"); + // SAFETY: allocated by test_alloc; release exactly once. + unsafe { test_free(ptr::null_mut(), error_buffer.data as *mut c_void) }; + let response = WireResponse::from_error_json_bytes(&error_bytes).expect("decode"); + let error = response.into_result().expect_err("error"); + assert_eq!(error.code, "missing_argument"); + assert_eq!(error.kind, marqdo_plugin_abi::ErrorKind::Invoke); +} + +#[test] +fn initialization_rejects_bad_host_major() { + let _guard = abi_test_lock(); + let mut host = test_host(); + host.api.abi_major = 2; + let mut plugin_api = MqPluginApi::host_initialized(); + // SAFETY: intentionally inconsistent host table; entry must reject it. + let code = unsafe { mq_plugin_entry_v1(&host.api as *const MqHostApi, &mut plugin_api) }; + assert_eq!(code, result::ABI_MISMATCH); +} diff --git a/src/wire.rs b/src/wire.rs new file mode 100644 index 0000000..9266abb --- /dev/null +++ b/src/wire.rs @@ -0,0 +1,98 @@ +//! Wire envelope helpers for plugin handlers. +//! +//! The canonical envelope is defined by `marqdo-plugin-abi` and documented in +//! `spec/value-wire.md`: UTF-8 JSON, `wire_version == 1`, type-tagged values. +//! Handlers normally do: +//! +//! ```ignore +//! fn add(ctx: &mut CallContext, args: &[u8]) -> Result, PluginError> { +//! let request = decode_request(args)?; +//! let values = request.typed_args()?; +//! success(Some(Value::Int((int_arg(&values, "a")? + int_arg(&values, "b")?).into()))) +//! } +//! ``` + +use std::collections::BTreeMap; + +use marqdo_plugin_abi::{ + bool_from_value, int_from_value, text_from_value, PluginError, Value, WireRequest, WireResponse, +}; +use serde_json::Value as Json; + +/// Decode and validate a request envelope received from the host. +pub fn decode_request(bytes: &[u8]) -> Result { + WireRequest::from_json_bytes(bytes) +} + +/// Look up a typed argument by name. +pub fn value_arg<'a>( + values: &'a BTreeMap, + name: &str, +) -> Result<&'a Value, PluginError> { + values.get(name).ok_or_else(|| { + PluginError::invoke( + "missing_argument", + format!("required argument `{name}` is missing"), + ) + }) +} + +/// Look up an integer argument (must fit in `i64`). +pub fn int_arg(values: &BTreeMap, name: &str) -> Result { + let value = value_arg(values, name)?; + int_from_value(value).ok_or_else(|| { + PluginError::invoke( + "invalid_argument_type", + format!("argument `{name}` must be an Int"), + ) + }) +} + +/// Look up a text argument. +pub fn text_arg<'a>( + values: &'a BTreeMap, + name: &str, +) -> Result<&'a str, PluginError> { + let value = value_arg(values, name)?; + text_from_value(value).ok_or_else(|| { + PluginError::invoke( + "invalid_argument_type", + format!("argument `{name}` must be Text"), + ) + }) +} + +/// Look up a boolean argument. +pub fn bool_arg(values: &BTreeMap, name: &str) -> Result { + let value = value_arg(values, name)?; + bool_from_value(value).ok_or_else(|| { + PluginError::invoke( + "invalid_argument_type", + format!("argument `{name}` must be Bool"), + ) + }) +} + +/// Encode a successful response envelope. +pub fn success(value: Option) -> Result, PluginError> { + success_raw(value.as_ref().map(marqdo_plugin_abi::to_wire_json)) +} + +/// Encode a successful response with an already-encoded type-tagged value. +pub fn success_raw(value: Option) -> Result, PluginError> { + WireResponse::success_raw(value).to_json_bytes() +} + +/// Encode an error response envelope. +/// +/// The SDK's dispatch layer uses this automatically when a handler returns an +/// error; handlers may also build custom error responses with it. +pub fn error_response(error: &PluginError) -> Result, PluginError> { + WireResponse::from_error(error).to_json_bytes() +} + +/// Decode a response value back into a typed [`Value`] (useful in tests and +/// plugins that compose calls). +pub fn response_value(bytes: &[u8]) -> Result, PluginError> { + WireResponse::from_json_bytes(bytes)?.typed_value() +} diff --git a/tests/fixture/Cargo.lock b/tests/fixture/Cargo.lock new file mode 100644 index 0000000..cb3e084 --- /dev/null +++ b/tests/fixture/Cargo.lock @@ -0,0 +1,201 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[package]] +name = "marqdo-plugin-abi" +version = "3.0.0-rc.4" +source = "git+https://git.cflmy.cn/cflmy/marqdo-cli.git?rev=2585915e16906dac75f8571bed02e7f6f868c6bc#2585915e16906dac75f8571bed02e7f6f868c6bc" +dependencies = [ + "marqdo-value", + "serde", + "serde_json", + "thiserror", +] + +[[package]] +name = "marqdo-plugin-sdk" +version = "3.0.0-rc.4" +dependencies = [ + "marqdo-plugin-abi", + "serde", + "serde_json", +] + +[[package]] +name = "marqdo-sdk-plugin-fixture" +version = "0.1.0" +dependencies = [ + "marqdo-plugin-sdk", +] + +[[package]] +name = "marqdo-span" +version = "3.0.0-rc.4" +source = "git+https://git.cflmy.cn/cflmy/marqdo-cli.git?rev=2585915e16906dac75f8571bed02e7f6f868c6bc#2585915e16906dac75f8571bed02e7f6f868c6bc" +dependencies = [ + "serde", +] + +[[package]] +name = "marqdo-value" +version = "3.0.0-rc.4" +source = "git+https://git.cflmy.cn/cflmy/marqdo-cli.git?rev=2585915e16906dac75f8571bed02e7f6f868c6bc#2585915e16906dac75f8571bed02e7f6f868c6bc" +dependencies = [ + "marqdo-span", + "num-bigint", + "num-traits", + "serde", + "serde_json", +] + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "num-bigint" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367" +dependencies = [ + "num-integer", + "num-traits", + "serde", +] + +[[package]] +name = "num-integer" +version = "0.1.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/tests/fixture/Cargo.toml b/tests/fixture/Cargo.toml new file mode 100644 index 0000000..d833e33 --- /dev/null +++ b/tests/fixture/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "marqdo-sdk-plugin-fixture" +version = "0.1.0" +edition = "2021" +publish = false + +# Independent fixture workspace: a third-party plugin built with only the +# public SDK. It does not see the CLI workspace or the native host sources. +[workspace] + +[lib] +crate-type = ["cdylib"] +path = "src/lib.rs" + +[dependencies] +marqdo-plugin-sdk = { path = "../.." } diff --git a/tests/fixture/call.mq.md b/tests/fixture/call.mq.md new file mode 100644 index 0000000..660f932 --- /dev/null +++ b/tests/fixture/call.mq.md @@ -0,0 +1,5 @@ +## @exec main + +`结果 = sdk.add(a=20, b=22)` + +`return 结果` diff --git a/tests/fixture/src/lib.rs b/tests/fixture/src/lib.rs new file mode 100644 index 0000000..7971631 --- /dev/null +++ b/tests/fixture/src/lib.rs @@ -0,0 +1,33 @@ +//! Minimal third-party plugin built only against the public Rust SDK. +//! +//! It exercises the typed wire helpers (`decode_request`, `int_arg`, +//! `success`) and `Value::Int`/`Value::Text` results. Real negotiation, +//! loading and invocation are performed by a frozen Marqdo CLI in +//! `tools/check_with_frozen_cli.py`. + +use marqdo_plugin_sdk::wire; +use marqdo_plugin_sdk::{mq_plugin_entry, CallContext, PluginError, Value}; + +fn add(_ctx: &mut CallContext, args: &[u8]) -> Result, PluginError> { + let request = wire::decode_request(args)?; + let values = request.typed_args()?; + let a = wire::int_arg(&values, "a")?; + let b = wire::int_arg(&values, "b")?; + wire::success(Some(Value::Int((a + b).into()))) +} + +fn echo_text(_ctx: &mut CallContext, args: &[u8]) -> Result, PluginError> { + let request = wire::decode_request(args)?; + let values = request.typed_args()?; + let text = wire::text_arg(&values, "text")?; + wire::success(Some(Value::text(text))) +} + +mq_plugin_entry! { + name: "sdk.demo", + version: "0.1.0", + exports: { + "sdk.add" => "($a: Int, $b: Int) -> Int" => add, + "sdk.echo" => "($text: Text) -> Text" => echo_text, + } +} diff --git a/tools/check_with_frozen_cli.py b/tools/check_with_frozen_cli.py new file mode 100644 index 0000000..d18fc37 --- /dev/null +++ b/tools/check_with_frozen_cli.py @@ -0,0 +1,172 @@ +#!/usr/bin/env python3 +"""SDK integration check against a frozen Marqdo CLI binary. + +This is the cross-repository acceptance for the independent SDK (issue #13 +§6.3 / S04-S07): + +1. build the plugin fixture with only this repository's public SDK; +2. create a host-specific ``plugin.yaml``; +3. load and invoke the plugin through the *frozen* CLI binary named by + ``--marqdo-bin`` (no CLI checkout, no nested CLI build); +4. reject a tampered artifact digest. + +Usage: + python3 tools/check_with_frozen_cli.py --marqdo-bin /path/to/marqdo +""" + +from __future__ import annotations + +import argparse +import hashlib +import platform +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + +REPO_ROOT = Path(__file__).resolve().parents[1] +FIXTURE = REPO_ROOT / "tests" / "fixture" +CALL_DOC = FIXTURE / "call.mq.md" + + +class GateError(Exception): + pass + + +def run(command: list[str], *, check: bool = True) -> subprocess.CompletedProcess: + result = subprocess.run( + command, cwd=REPO_ROOT, capture_output=True, text=True, check=False + ) + if check and result.returncode != 0: + raise GateError( + f"`{' '.join(command)}` failed with {result.returncode}:\n" + f"{result.stdout}\n{result.stderr}" + ) + return result + + +def host_triple() -> str: + result = run(["rustc", "-vV"]) + for line in result.stdout.splitlines(): + if line.startswith("host: "): + return line[len("host: ") :].strip() + raise GateError("rustc -vV did not report a host triple") + + +def artifact_name() -> str: + system = platform.system() + if system == "Darwin": + return "libmarqdo_sdk_plugin_fixture.dylib" + if system == "Windows": + return "marqdo_sdk_plugin_fixture.dll" + return "libmarqdo_sdk_plugin_fixture.so" + + +def write_manifest( + directory: Path, + digest: str, + triple: str, + artifact: str, + *, + tamper: bool = False, +) -> None: + effective = "0" * 64 if tamper else digest + manifest = f"""plugin: + name: sdk.demo + version: 0.1.0 + abi: "^1.0" + kind: native + exports: + - name: sdk.add + signature: "($a: Int, $b: Int) -> Int" + - name: sdk.echo + signature: "($text: Text) -> Text" + artifacts: + - target: {triple} + file: {artifact} + sha256: "{effective}" +""" + (directory / "plugin.yaml").write_text(manifest, encoding="utf-8") + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument( + "--marqdo-bin", + required=True, + help="frozen `marqdo` executable from a released CLI archive", + ) + parser.add_argument( + "--offline", + action="store_true", + help="pass --offline to cargo (warm registry cache only)", + ) + arguments = parser.parse_args() + offline = ["--offline"] if arguments.offline else [] + binary = Path(arguments.marqdo_bin).resolve() + try: + if not binary.is_file(): + raise GateError(f"frozen CLI binary not found: {binary}") + run( + [ + "cargo", + "build", + "--locked", + *offline, + "--manifest-path", + str(FIXTURE / "Cargo.toml"), + ] + ) + name = artifact_name() + built = FIXTURE / "target" / "debug" / name + if not built.is_file(): + raise GateError(f"fixture artifact not found: {built}") + + with tempfile.TemporaryDirectory(prefix="marqdo-sdk-integration-") as raw: + directory = Path(raw) + artifact = "plugin" + Path(name).suffix + shutil.copyfile(built, directory / artifact) + digest = hashlib.sha256((directory / artifact).read_bytes()).hexdigest() + command = [ + str(binary), + "call", + str(CALL_DOC), + "main", + "--plugin", + str(directory), + "--trust-native-plugin", + "--allow-plugin", + "sdk.demo", + ] + + write_manifest(directory, digest, host_triple(), artifact) + positive = run(command, check=False) + if positive.returncode != 0 or positive.stdout.strip() != "42": + raise GateError( + "frozen CLI could not invoke the SDK plugin: " + f"exit={positive.returncode} stdout={positive.stdout!r} " + f"stderr={positive.stderr!r}" + ) + print("PASS sdk-frozen-cli-invocation (Int 42)") + + write_manifest(directory, digest, host_triple(), artifact, tamper=True) + negative = run(command, check=False) + if negative.returncode == 0: + raise GateError("tampered artifact digest was accepted") + combined = negative.stdout + negative.stderr + if "sha256" not in combined.lower() and "artifact" not in combined.lower(): + raise GateError( + "tampered artifact failed without an artifact/sha256 diagnostic: " + + combined + ) + print("PASS sdk-tampered-digest-rejected") + except GateError as error: + print(f"FAIL sdk-integration: {error}", file=sys.stderr) + return 1 + print("PASS sdk-integration") + return 0 + + +if __name__ == "__main__": + sys.exit(main())