sova_core/plugin.rs
1//! Plugin extension trait and SDK metadata.
2//!
3//! Full VitePress guide: <https://s00d.github.io/sova/api/plugin-sdk.html>
4//! (source: `docs/.vitepress/plugin-sdk-guides/`).
5//!
6//! # Writing a plugin
7//!
8//! A plugin is any type that implements [`Plugin`]. On install it typically:
9//!
10//! 1. Registers middleware via [`crate::App::use_middleware`] / [`crate::extend::with_leaked`]
11//! 2. Inserts shared state with [`crate::App::state`]
12//! 3. Adds routes (`get` / `post` / …)
13//! 4. Optionally registers lifecycle hooks, CLI commands, or checks
14//!
15//! ## Identity and dependencies
16//!
17//! Override [`Plugin::id`] with a short stable string (`"cookies"`, `"session"`).
18//! Use [`Plugin::requires`] so dependents fail at [`crate::App::build`] if a
19//! dependency was not installed first. Prefer short ids over `type_name`.
20//!
21//! ## SDK versioning
22//!
23//! [`PLUGIN_SDK_VERSION`] is the plugin-author surface version (independent of
24//! the crate semver). Declare the version your plugin was built against via
25//! [`PluginMeta::sdk`] (default = current). Compatibility on install:
26//!
27//! - **different major** → hard error at build
28//! - **plugin newer** than core (same major) → hard error
29//! - **core newer** than plugin (same major) → `tracing` warning
30//!
31//! Bump `PLUGIN_SDK_VERSION` major only when the author-facing API breaks.
32//!
33//! ## Metadata
34//!
35//! [`Plugin::meta`] returns human-readable info for CLI (`plugins`) and docs.
36//!
37//! Scaffold: `cargo sovax generate plugin <name>`.
38
39use crate::app::App;
40use std::cmp::Ordering;
41use std::fmt;
42
43/// Current Plugin SDK version (author-facing surface, not crate semver).
44pub const PLUGIN_SDK_VERSION: PluginSdkVersion = PluginSdkVersion::new(1, 1, 0);
45
46/// Semantic version of the Plugin SDK (`major.minor.patch`).
47#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
48pub struct PluginSdkVersion {
49 pub major: u32,
50 pub minor: u32,
51 pub patch: u32,
52}
53
54impl PluginSdkVersion {
55 pub const fn new(major: u32, minor: u32, patch: u32) -> Self {
56 Self {
57 major,
58 minor,
59 patch,
60 }
61 }
62
63 /// Parse `"1.2.3"` / `"1.2"` / `"1"`. Invalid input → `None`.
64 pub fn parse(s: &str) -> Option<Self> {
65 let mut parts = s.trim().split('.');
66 let major = parts.next()?.parse().ok()?;
67 let minor = parts.next().unwrap_or("0").parse().ok()?;
68 let patch = parts.next().unwrap_or("0").parse().ok()?;
69 if parts.next().is_some() {
70 return None;
71 }
72 Some(Self::new(major, minor, patch))
73 }
74}
75
76impl fmt::Display for PluginSdkVersion {
77 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
78 write!(f, "{}.{}.{}", self.major, self.minor, self.patch)
79 }
80}
81
82/// Result of comparing a plugin's declared SDK against core.
83#[derive(Debug, Clone, PartialEq, Eq)]
84pub enum SdkCompat {
85 /// Exact match (or plugin == core).
86 Ok,
87 /// Same major; core is newer — plugin may miss new APIs later; warn only.
88 Warn { core: PluginSdkVersion, plugin: PluginSdkVersion },
89 /// Hard failure: major mismatch or plugin requires a newer core.
90 Error(String),
91}
92
93/// Compare `plugin` SDK declaration against `core` ([`PLUGIN_SDK_VERSION`]).
94pub fn check_plugin_sdk(plugin: PluginSdkVersion, core: PluginSdkVersion) -> SdkCompat {
95 if plugin.major != core.major {
96 return SdkCompat::Error(format!(
97 "plugin SDK {plugin} is incompatible with core SDK {core} (major version mismatch)"
98 ));
99 }
100 match plugin.cmp(&core) {
101 Ordering::Greater => SdkCompat::Error(format!(
102 "plugin SDK {plugin} requires core SDK >= {plugin} (running {core})"
103 )),
104 Ordering::Less => SdkCompat::Warn { core, plugin },
105 Ordering::Equal => SdkCompat::Ok,
106 }
107}
108
109/// Human-readable plugin metadata (CLI, docs, introspection).
110#[derive(Debug, Clone)]
111pub struct PluginMeta {
112 /// Display name (defaults to plugin id).
113 pub name: &'static str,
114 /// One-line description of what the plugin does.
115 pub description: &'static str,
116 /// Plugin crate / package version (not SDK), e.g. `env!("CARGO_PKG_VERSION")`.
117 pub version: &'static str,
118 /// Optional author / maintainer.
119 pub author: &'static str,
120 /// Plugin SDK version this plugin was written against.
121 pub sdk: PluginSdkVersion,
122}
123
124impl PluginMeta {
125 /// Start a builder with a display `name`; SDK defaults to [`PLUGIN_SDK_VERSION`].
126 pub fn new(name: &'static str) -> Self {
127 Self {
128 name,
129 description: "",
130 version: "",
131 author: "",
132 sdk: PLUGIN_SDK_VERSION,
133 }
134 }
135
136 /// Minimal meta for plugins that only set [`Plugin::id`].
137 pub fn for_id(id: &'static str) -> Self {
138 Self::new(id)
139 }
140
141 pub fn description(mut self, description: &'static str) -> Self {
142 self.description = description;
143 self
144 }
145
146 pub fn version(mut self, version: &'static str) -> Self {
147 self.version = version;
148 self
149 }
150
151 pub fn author(mut self, author: &'static str) -> Self {
152 self.author = author;
153 self
154 }
155
156 pub fn sdk(mut self, sdk: PluginSdkVersion) -> Self {
157 self.sdk = sdk;
158 self
159 }
160}
161
162/// Snapshot of an installed plugin (for CLI / introspection).
163#[derive(Debug, Clone)]
164pub struct InstalledPlugin {
165 pub id: &'static str,
166 pub meta: PluginMeta,
167}
168
169/// Single extension trait for the framework.
170///
171/// Prefer `app.install(|app| { ... })` or `app.install(Cors::new())` —
172/// application code rarely needs to name this trait; plugin authors implement it.
173pub trait Plugin {
174 /// Stable plugin identifier used for dependency checks and [`crate::App::has_plugin`].
175 ///
176 /// Prefer a short constant (`"session"`) over the default [`std::any::type_name`].
177 fn id(&self) -> &'static str {
178 std::any::type_name::<Self>()
179 }
180
181 /// Required plugin ids that must be installed beforehand.
182 ///
183 /// Missing deps are collected at install and reported on [`crate::App::build`].
184 fn requires(&self) -> &'static [&'static str] {
185 &[]
186 }
187
188 /// Display name, description, and declared [`PluginMeta::sdk`] version.
189 fn meta(&self) -> PluginMeta {
190 PluginMeta::for_id(self.id())
191 }
192
193 /// Register middleware, state, routes, and hooks on `app`.
194 fn install(self, app: &mut App);
195}
196
197impl<F> Plugin for F
198where
199 F: FnOnce(&mut App),
200{
201 fn install(self, app: &mut App) {
202 self(app);
203 }
204}
205
206#[cfg(test)]
207mod tests {
208 use super::*;
209
210 #[test]
211 fn parse_sdk_version() {
212 assert_eq!(
213 PluginSdkVersion::parse("1.2.3"),
214 Some(PluginSdkVersion::new(1, 2, 3))
215 );
216 assert_eq!(
217 PluginSdkVersion::parse("2"),
218 Some(PluginSdkVersion::new(2, 0, 0))
219 );
220 assert!(PluginSdkVersion::parse("x").is_none());
221 }
222
223 #[test]
224 fn sdk_compat_rules() {
225 let core = PluginSdkVersion::new(1, 1, 0);
226 assert_eq!(
227 check_plugin_sdk(PluginSdkVersion::new(1, 1, 0), core),
228 SdkCompat::Ok
229 );
230 assert!(matches!(
231 check_plugin_sdk(PluginSdkVersion::new(1, 0, 0), core),
232 SdkCompat::Warn { .. }
233 ));
234 assert!(matches!(
235 check_plugin_sdk(PluginSdkVersion::new(1, 2, 0), core),
236 SdkCompat::Error(_)
237 ));
238 assert!(matches!(
239 check_plugin_sdk(PluginSdkVersion::new(0, 9, 0), core),
240 SdkCompat::Error(_)
241 ));
242 }
243}