Skip to main content

phoenix_plugin/
lib.rs

1//! Compile-time Feature / plugin installation for Phoenix-rs.
2//!
3//! Third-party crates implement [`Plugin`] and apps install them with
4//! [`FeatureSet::plugin`]. There is no runtime dynamic loading.
5//! See `docs/FEATURES.md`.
6
7#![forbid(unsafe_code)]
8
9use std::collections::BTreeSet;
10
11use phoenix_console::CommandEntry;
12use phoenix_database::Migration;
13use phoenix_http::Middleware;
14use phoenix_routing::{RouteGroup, Routes};
15use thiserror::Error;
16
17/// Declared ability a plugin may contribute.
18#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
19pub enum Capability {
20    /// HTTP routes via [`Plugin::routes`].
21    Routes,
22    /// Application console commands via [`Plugin::commands`].
23    Commands,
24    /// Database migrations via [`Plugin::migrations`].
25    Migrations,
26}
27
28impl Capability {
29    #[must_use]
30    pub const fn as_str(self) -> &'static str {
31        match self {
32            Self::Routes => "routes",
33            Self::Commands => "commands",
34            Self::Migrations => "migrations",
35        }
36    }
37}
38
39/// An installable Feature (plugin) distributed as a Cargo crate.
40pub trait Plugin: Send + Sync {
41    /// Stable plugin id used in diagnostics and optional route-name prefixes.
42    fn name(&self) -> &'static str;
43
44    /// Plugin crate / package version string for diagnostics.
45    fn version(&self) -> &'static str {
46        "0.0.0"
47    }
48
49    /// Capabilities this plugin claims. Must cover every non-empty contribution.
50    fn capabilities(&self) -> &'static [Capability];
51
52    /// Routes contributed by this plugin. Prefer naming routes; path layout is
53    /// the plugin author's choice (no forced URL prefix).
54    fn routes(&self) -> Routes {
55        Routes::new()
56    }
57
58    /// Console commands contributed by this plugin.
59    fn commands(&self) -> Vec<CommandEntry> {
60        Vec::new()
61    }
62
63    /// Migrations contributed by this plugin.
64    fn migrations(&self) -> Vec<Migration> {
65        Vec::new()
66    }
67}
68
69/// Collected contributions from one or more plugins.
70pub struct FeatureSet {
71    allow: Option<BTreeSet<Capability>>,
72    namespace_route_names: bool,
73    plugin_names: BTreeSet<&'static str>,
74    command_names: BTreeSet<&'static str>,
75    migration_ids: BTreeSet<String>,
76    routes: Routes,
77    commands: Vec<CommandEntry>,
78    migrations: Vec<Migration>,
79}
80
81impl Default for FeatureSet {
82    fn default() -> Self {
83        Self::new()
84    }
85}
86
87impl FeatureSet {
88    /// Start an empty feature set. By default all known capabilities are allowed
89    /// and route names are prefixed with `{plugin}.`.
90    #[must_use]
91    pub fn new() -> Self {
92        Self {
93            allow: None,
94            namespace_route_names: true,
95            plugin_names: BTreeSet::new(),
96            command_names: BTreeSet::new(),
97            migration_ids: BTreeSet::new(),
98            routes: Routes::new(),
99            commands: Vec::new(),
100            migrations: Vec::new(),
101        }
102    }
103
104    /// Restrict which capabilities plugins may use. Unknown declarations fail.
105    #[must_use]
106    pub fn allow(mut self, capabilities: impl IntoIterator<Item = Capability>) -> Self {
107        self.allow = Some(capabilities.into_iter().collect());
108        self
109    }
110
111    /// When `true` (default), route names become `{plugin}.{name}`.
112    #[must_use]
113    pub fn namespace_route_names(mut self, enabled: bool) -> Self {
114        self.namespace_route_names = enabled;
115        self
116    }
117
118    /// Install one plugin. Fails closed on name / capability / contribution conflicts.
119    ///
120    /// # Errors
121    ///
122    /// Returns [`FeatureError`] when the plugin is invalid or conflicts with an
123    /// already installed plugin.
124    #[allow(clippy::needless_pass_by_value)] // owned install is the public ergonomic API
125    pub fn plugin(mut self, plugin: impl Plugin) -> Result<Self, FeatureError> {
126        let name = plugin.name();
127        if name.trim().is_empty() {
128            return Err(FeatureError::InvalidName(name));
129        }
130        if !self.plugin_names.insert(name) {
131            return Err(FeatureError::DuplicatePlugin(name));
132        }
133
134        let declared: BTreeSet<_> = plugin.capabilities().iter().copied().collect();
135        if let Some(allow) = &self.allow {
136            for capability in &declared {
137                if !allow.contains(capability) {
138                    return Err(FeatureError::CapabilityDenied {
139                        plugin: name,
140                        capability: *capability,
141                    });
142                }
143            }
144        }
145
146        let routes = plugin.routes();
147        let commands = plugin.commands();
148        let migrations = plugin.migrations();
149
150        ensure_capability(name, &declared, Capability::Routes, !routes.is_empty())?;
151        ensure_capability(name, &declared, Capability::Commands, !commands.is_empty())?;
152        ensure_capability(
153            name,
154            &declared,
155            Capability::Migrations,
156            !migrations.is_empty(),
157        )?;
158
159        for command in &commands {
160            if !self.command_names.insert(command.name()) {
161                return Err(FeatureError::DuplicateCommand {
162                    plugin: name,
163                    command: command.name(),
164                });
165            }
166        }
167        for migration in &migrations {
168            let id = migration.id().to_owned();
169            if !self.migration_ids.insert(id.clone()) {
170                return Err(FeatureError::DuplicateMigration { plugin: name, id });
171            }
172        }
173
174        let routes = if self.namespace_route_names {
175            routes.scoped(RouteGroup::new().name(format!("{name}.")))
176        } else {
177            routes
178        };
179        self.routes = self.routes.merge(routes);
180        self.commands.extend(commands);
181        self.migrations.extend(migrations);
182        let _ = plugin.version();
183        Ok(self)
184    }
185
186    /// Attach shared middleware to every route contributed so far.
187    #[must_use]
188    pub fn with_middleware<M>(mut self, middleware: M) -> Self
189    where
190        M: Middleware,
191    {
192        self.routes = self.routes.with_middleware(middleware);
193        self
194    }
195
196    /// Take contributed routes for merging into the application router.
197    #[must_use]
198    pub fn into_routes(self) -> Routes {
199        self.routes
200    }
201
202    /// Merge feature routes into an existing application routes table.
203    #[must_use]
204    pub fn merge_into(self, routes: Routes) -> Routes {
205        routes.merge(self.routes)
206    }
207
208    /// Take console commands for chaining into [`phoenix_console::Console::commands`].
209    #[must_use]
210    pub fn into_commands(self) -> Vec<CommandEntry> {
211        self.commands
212    }
213
214    /// Unpack routes, commands, and migrations when the app needs all three.
215    #[must_use]
216    pub fn into_parts(self) -> FeatureParts {
217        FeatureParts {
218            routes: self.routes,
219            commands: self.commands,
220            migrations: self.migrations,
221        }
222    }
223
224    /// Take migrations for the application [`phoenix_database::MigrationRunner`].
225    #[must_use]
226    pub fn into_migrations(self) -> Vec<Migration> {
227        self.migrations
228    }
229
230    /// Installed plugin names in sorted order.
231    #[must_use]
232    pub fn installed(&self) -> Vec<&'static str> {
233        self.plugin_names.iter().copied().collect()
234    }
235}
236
237/// Routes, commands, and migrations unpacked from a [`FeatureSet`].
238pub struct FeatureParts {
239    pub routes: Routes,
240    pub commands: Vec<CommandEntry>,
241    pub migrations: Vec<Migration>,
242}
243
244fn ensure_capability(
245    plugin: &'static str,
246    declared: &BTreeSet<Capability>,
247    capability: Capability,
248    contributes: bool,
249) -> Result<(), FeatureError> {
250    if contributes && !declared.contains(&capability) {
251        return Err(FeatureError::UndeclaredCapability { plugin, capability });
252    }
253    Ok(())
254}
255
256/// Feature installation error (fail closed).
257#[derive(Debug, Error, Eq, PartialEq)]
258pub enum FeatureError {
259    #[error("plugin name must not be empty")]
260    InvalidName(&'static str),
261    #[error("duplicate plugin `{0}`")]
262    DuplicatePlugin(&'static str),
263    #[error(
264        "plugin `{plugin}` is not allowed to use capability `{}`",
265        capability.as_str()
266    )]
267    CapabilityDenied {
268        plugin: &'static str,
269        capability: Capability,
270    },
271    #[error(
272        "plugin `{plugin}` contributes `{}` but did not declare that capability",
273        capability.as_str()
274    )]
275    UndeclaredCapability {
276        plugin: &'static str,
277        capability: Capability,
278    },
279    #[error("plugin `{plugin}` registers duplicate command `{command}`")]
280    DuplicateCommand {
281        plugin: &'static str,
282        command: &'static str,
283    },
284    #[error("plugin `{plugin}` registers duplicate migration `{id}`")]
285    DuplicateMigration { plugin: &'static str, id: String },
286}
287
288#[cfg(test)]
289mod tests {
290    use super::*;
291    use phoenix_http::{IntoResponse, Json, Request};
292    use serde_json::json;
293
294    struct HelloPlugin;
295
296    impl Plugin for HelloPlugin {
297        fn name(&self) -> &'static str {
298            "hello"
299        }
300
301        fn capabilities(&self) -> &'static [Capability] {
302            &[Capability::Routes, Capability::Commands]
303        }
304
305        fn routes(&self) -> Routes {
306            Routes::new()
307                .get("/hello", |_request: Request| async {
308                    Json(json!({ "ok": true })).into_response()
309                })
310                .name("index")
311        }
312
313        fn commands(&self) -> Vec<CommandEntry> {
314            vec![CommandEntry::new("hello", |_ctx| {
315                Box::pin(async { Ok(()) })
316            })]
317        }
318    }
319
320    struct UndeclaredRoutes;
321
322    impl Plugin for UndeclaredRoutes {
323        fn name(&self) -> &'static str {
324            "bad"
325        }
326
327        fn capabilities(&self) -> &'static [Capability] {
328            &[]
329        }
330
331        fn routes(&self) -> Routes {
332            Routes::new()
333                .get("/x", |_request: Request| async { "x".into_response() })
334                .name("x")
335        }
336    }
337
338    #[test]
339    fn installs_routes_and_commands_with_namespace() {
340        let parts = FeatureSet::new().plugin(HelloPlugin).unwrap().into_parts();
341        assert_eq!(parts.commands.len(), 1);
342        assert_eq!(parts.commands[0].name(), "hello");
343        let router = parts.routes.build().unwrap();
344        assert_eq!(router.url("hello.index", &[]).unwrap(), "/hello");
345    }
346
347    #[test]
348    fn rejects_undeclared_and_denied_capabilities() {
349        assert!(matches!(
350            FeatureSet::new().plugin(UndeclaredRoutes),
351            Err(FeatureError::UndeclaredCapability {
352                capability: Capability::Routes,
353                ..
354            })
355        ));
356        assert!(matches!(
357            FeatureSet::new()
358                .allow([Capability::Commands])
359                .plugin(HelloPlugin),
360            Err(FeatureError::CapabilityDenied {
361                capability: Capability::Routes,
362                ..
363            })
364        ));
365    }
366
367    #[test]
368    fn rejects_duplicate_plugins() {
369        let result = FeatureSet::new()
370            .plugin(HelloPlugin)
371            .and_then(|set| set.plugin(HelloPlugin));
372        assert_eq!(result.err(), Some(FeatureError::DuplicatePlugin("hello")));
373    }
374}