Skip to main content

uni_plugin/
manifest.rs

1//! Plugin manifest — TOML and JSON (de)serialization.
2//!
3//! The manifest is the *typed contract* between a plugin and the host. It
4//! declares the plugin's identity, the ABI range it targets, capabilities it
5//! requests, declarative dependencies on other plugins, the determinism /
6//! side-effect / scope characterizations, and a summary of what surfaces it
7//! plans to register.
8//!
9//! Manifests are persisted in TOML for human authoring and on-the-wire JSON
10//! for programmatic exchange (WASM plugins return JSON from their
11//! `manifest-json` export). Both forms round-trip through `serde`.
12
13use std::collections::BTreeMap;
14
15use semver::{Version, VersionReq};
16use serde::{Deserialize, Serialize};
17use smol_str::SmolStr;
18
19use crate::capability::{CapabilitySet, Determinism, Scope, SideEffects};
20use crate::errors::PluginError;
21use crate::plugin::PluginId;
22
23/// A semver range expressing which ABI majors this plugin supports.
24///
25/// Stored as the original requirement string so manifests round-trip
26/// losslessly through serialization. Use [`AbiRange::matches`] to test
27/// against a host major.
28///
29/// # Examples
30///
31/// ```
32/// use uni_plugin::AbiRange;
33/// let r = AbiRange::parse("^1.2").unwrap();
34/// assert!(r.matches(1));
35/// assert!(!r.matches(2));
36/// ```
37#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
38#[serde(transparent)]
39pub struct AbiRange(String);
40
41impl AbiRange {
42    /// Parse an ABI range from a semver requirement string.
43    ///
44    /// # Errors
45    ///
46    /// Returns [`PluginError::ManifestParse`] if the input is not a valid
47    /// semver `VersionReq`.
48    pub fn parse(s: impl AsRef<str>) -> Result<Self, PluginError> {
49        let s = s.as_ref();
50        VersionReq::parse(s)
51            .map_err(|e| PluginError::ManifestParse(format!("invalid abi range `{s}`: {e}")))?;
52        Ok(Self(s.to_owned()))
53    }
54
55    /// Check whether a host ABI major satisfies this range.
56    ///
57    /// The check passes if any version with major == `host_major` falls
58    /// within the requirement. We probe with a high minor / patch so that
59    /// ranges like `^1.2` (which excludes `1.0.0`) still recognize the
60    /// host's major as compatible.
61    #[must_use]
62    pub fn matches(&self, host_major: u64) -> bool {
63        // `unwrap_or(STAR)` is defensive — the range was validated at parse.
64        let req = VersionReq::parse(&self.0).unwrap_or(VersionReq::STAR);
65        // A very-high minor/patch ensures we hit any minor-tightened range
66        // (`^1.2`, `>=1.5.3`). Using u64::MAX / 2 leaves headroom for
67        // arithmetic in callers without overflow.
68        let probe = Version::new(host_major, u64::MAX / 2, u64::MAX / 2);
69        req.matches(&probe)
70    }
71
72    /// Returns the underlying range string.
73    #[must_use]
74    pub fn as_str(&self) -> &str {
75        &self.0
76    }
77}
78
79/// A dependency on another plugin.
80#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
81pub struct PluginDep {
82    /// Required dependency plugin id.
83    pub id: PluginId,
84    /// Version requirement (semver range).
85    pub version_req: String,
86    /// If `true`, the dependency is best-effort (init still runs even if missing).
87    #[serde(default)]
88    pub optional: bool,
89}
90
91impl PluginDep {
92    /// Construct a required dependency.
93    #[must_use]
94    pub fn new(id: PluginId, version_req: impl Into<String>) -> Self {
95        Self {
96            id,
97            version_req: version_req.into(),
98            optional: false,
99        }
100    }
101
102    /// Check whether the supplied `version` satisfies this dependency.
103    #[must_use]
104    pub fn satisfied_by(&self, version: &Version) -> bool {
105        VersionReq::parse(&self.version_req).is_ok_and(|r| r.matches(version))
106    }
107}
108
109/// Declarative summary of what surfaces a plugin's `register()` will add.
110///
111/// Built by the plugin author and serialized into the manifest. The host can
112/// use this to validate registrations against the manifest and to build a
113/// fast pre-registration routing table.
114#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
115#[serde(default)]
116pub struct ProvidedSurfaces {
117    /// Scalar function locals (un-namespaced, joined with manifest id at
118    /// registration).
119    pub scalar_fns: Vec<SmolStr>,
120    /// Aggregate function locals.
121    pub aggregate_fns: Vec<SmolStr>,
122    /// Window function locals.
123    pub window_fns: Vec<SmolStr>,
124    /// Procedure locals.
125    pub procedures: Vec<SmolStr>,
126    /// Locy aggregate locals.
127    pub locy_aggregates: Vec<SmolStr>,
128    /// Locy predicate locals.
129    pub locy_predicates: Vec<SmolStr>,
130    /// Algorithm locals.
131    pub algorithms: Vec<SmolStr>,
132    /// Storage backends declared (by URI scheme).
133    pub storage_backends: Vec<SmolStr>,
134    /// Index kinds declared.
135    pub index_kinds: Vec<SmolStr>,
136    /// CRDT kinds declared.
137    pub crdt_kinds: Vec<SmolStr>,
138    /// Logical (Arrow extension) types declared.
139    pub logical_types: Vec<SmolStr>,
140    /// Whether the plugin contributes phased hooks.
141    pub hooks: bool,
142    /// Whether the plugin contributes triggers.
143    pub triggers: bool,
144    /// Whether the plugin contributes background jobs.
145    pub background_jobs: bool,
146    /// Wire-protocol connectors declared.
147    pub connectors: Vec<SmolStr>,
148}
149
150/// Top-level plugin manifest.
151///
152/// Authored as TOML, exchanged as JSON (the WASM `manifest-json` export
153/// returns this serialized to JSON). Round-trips through `serde` in either
154/// format.
155#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
156pub struct PluginManifest {
157    /// Reverse-DNS plugin id.
158    pub id: PluginId,
159    /// Plugin semantic version.
160    pub version: Version,
161    /// ABI range this plugin supports.
162    pub abi: AbiRange,
163    /// Plugins this depends on. May be empty.
164    #[serde(default)]
165    pub depends_on: Vec<PluginDep>,
166    /// Capability requests; granted set is intersection with host grants.
167    #[serde(default)]
168    pub capabilities: CapabilitySet,
169    /// Determinism characterization.
170    #[serde(default)]
171    pub determinism: Determinism,
172    /// Side-effect characterization.
173    #[serde(default)]
174    pub side_effects: SideEffects,
175    /// Lifetime scope.
176    #[serde(default)]
177    pub scope: Scope,
178    /// Optional hash pin (blake3 hex string of the plugin payload).
179    #[serde(default)]
180    pub hash: Option<String>,
181    /// Optional Ed25519 signature over canonical-JSON manifest + payload hash.
182    #[serde(default)]
183    pub signature: Option<ManifestSignature>,
184    /// Declarative surface summary.
185    #[serde(default)]
186    pub provides: ProvidedSurfaces,
187    /// Markdown docs surfaced via `uni plugin help <qname>` and
188    /// `CALL uni.plugin.help('qname')`.
189    #[serde(default)]
190    pub docs: String,
191    /// Free-form metadata (author, license, repo, etc.).
192    #[serde(default)]
193    pub metadata: BTreeMap<String, String>,
194}
195
196impl PluginManifest {
197    /// Parse a manifest from a TOML string.
198    ///
199    /// # Errors
200    ///
201    /// Returns [`PluginError::ManifestParse`] if the input fails to parse.
202    pub fn from_toml(s: impl AsRef<str>) -> Result<Self, PluginError> {
203        toml::from_str(s.as_ref()).map_err(|e| PluginError::ManifestParse(format!("toml: {e}")))
204    }
205
206    /// Parse a manifest from a JSON string.
207    ///
208    /// # Errors
209    ///
210    /// Returns [`PluginError::ManifestParse`] if the input fails to parse.
211    pub fn from_json(s: impl AsRef<str>) -> Result<Self, PluginError> {
212        serde_json::from_str(s.as_ref())
213            .map_err(|e| PluginError::ManifestParse(format!("json: {e}")))
214    }
215
216    /// Serialize this manifest to TOML.
217    ///
218    /// # Errors
219    ///
220    /// Returns [`PluginError::ManifestParse`] if serialization fails
221    /// (unusual — only happens with non-stringifiable map keys, which the
222    /// manifest doesn't produce).
223    pub fn to_toml(&self) -> Result<String, PluginError> {
224        toml::to_string_pretty(self)
225            .map_err(|e| PluginError::ManifestParse(format!("toml serialize: {e}")))
226    }
227
228    /// Serialize this manifest to JSON (compact).
229    ///
230    /// # Errors
231    ///
232    /// Returns [`PluginError::ManifestParse`] if serialization fails.
233    pub fn to_json(&self) -> Result<String, PluginError> {
234        serde_json::to_string(self)
235            .map_err(|e| PluginError::ManifestParse(format!("json serialize: {e}")))
236    }
237}
238
239/// Manifest signature material.
240#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
241pub struct ManifestSignature {
242    /// Algorithm identifier — `"ed25519"` for v1.
243    pub algorithm: String,
244    /// Key identifier (key fingerprint or human-readable name).
245    pub key_id: String,
246    /// Base64-encoded signature bytes.
247    pub value: String,
248}
249
250#[cfg(test)]
251mod tests {
252    use super::*;
253
254    fn sample_manifest() -> PluginManifest {
255        PluginManifest {
256            id: PluginId::new("ai.dragonscale.geo"),
257            version: Version::parse("0.3.1").unwrap(),
258            abi: AbiRange::parse("^1").unwrap(),
259            depends_on: vec![],
260            capabilities: CapabilitySet::new(),
261            determinism: Determinism::Pure,
262            side_effects: SideEffects::ReadOnly,
263            scope: Scope::Instance,
264            hash: None,
265            signature: None,
266            provides: ProvidedSurfaces::default(),
267            docs: String::new(),
268            metadata: BTreeMap::new(),
269        }
270    }
271
272    #[test]
273    fn abi_range_parse_and_match() {
274        let r = AbiRange::parse("^1.2").unwrap();
275        assert!(r.matches(1));
276        assert!(!r.matches(2));
277    }
278
279    #[test]
280    fn abi_range_rejects_garbage() {
281        assert!(AbiRange::parse("not-semver").is_err());
282    }
283
284    #[test]
285    fn manifest_round_trip_json() {
286        let m = sample_manifest();
287        let s = m.to_json().unwrap();
288        let parsed = PluginManifest::from_json(&s).unwrap();
289        assert_eq!(parsed, m);
290    }
291
292    #[test]
293    fn manifest_round_trip_toml() {
294        let m = sample_manifest();
295        let s = m.to_toml().unwrap();
296        let parsed = PluginManifest::from_toml(&s).unwrap();
297        assert_eq!(parsed, m);
298    }
299
300    #[test]
301    fn plugin_dep_version_satisfaction() {
302        let dep = PluginDep::new(PluginId::new("units"), "^0.4".to_owned());
303        assert!(dep.satisfied_by(&Version::parse("0.4.2").unwrap()));
304        assert!(!dep.satisfied_by(&Version::parse("0.3.0").unwrap()));
305    }
306}