1#![forbid(unsafe_code)]
8
9use std::collections::BTreeSet;
10
11use phoenix_console::CommandEntry;
12#[cfg(feature = "database")]
13use phoenix_database::Migration;
14use phoenix_http::Middleware;
15use phoenix_routing::{RouteGroup, Routes};
16use thiserror::Error;
17
18#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
20pub enum Capability {
21 Routes,
23 Commands,
25 #[cfg(feature = "database")]
27 Migrations,
28}
29
30impl Capability {
31 #[must_use]
32 pub const fn as_str(self) -> &'static str {
33 match self {
34 Self::Routes => "routes",
35 Self::Commands => "commands",
36 #[cfg(feature = "database")]
37 Self::Migrations => "migrations",
38 }
39 }
40}
41
42pub trait Plugin: Send + Sync {
44 fn name(&self) -> &'static str;
46
47 fn version(&self) -> &'static str {
49 "0.0.0"
50 }
51
52 fn capabilities(&self) -> &'static [Capability];
54
55 fn routes(&self) -> Routes {
58 Routes::new()
59 }
60
61 fn commands(&self) -> Vec<CommandEntry> {
63 Vec::new()
64 }
65
66 #[cfg(feature = "database")]
68 fn migrations(&self) -> Vec<Migration> {
69 Vec::new()
70 }
71}
72
73pub struct FeatureSet {
75 allow: Option<BTreeSet<Capability>>,
76 namespace_route_names: bool,
77 plugin_names: BTreeSet<&'static str>,
78 command_names: BTreeSet<&'static str>,
79 #[cfg(feature = "database")]
80 migration_ids: BTreeSet<String>,
81 routes: Routes,
82 commands: Vec<CommandEntry>,
83 #[cfg(feature = "database")]
84 migrations: Vec<Migration>,
85}
86
87impl Default for FeatureSet {
88 fn default() -> Self {
89 Self::new()
90 }
91}
92
93impl FeatureSet {
94 #[must_use]
97 pub fn new() -> Self {
98 Self {
99 allow: None,
100 namespace_route_names: true,
101 plugin_names: BTreeSet::new(),
102 command_names: BTreeSet::new(),
103 #[cfg(feature = "database")]
104 migration_ids: BTreeSet::new(),
105 routes: Routes::new(),
106 commands: Vec::new(),
107 #[cfg(feature = "database")]
108 migrations: Vec::new(),
109 }
110 }
111
112 #[must_use]
114 pub fn allow(mut self, capabilities: impl IntoIterator<Item = Capability>) -> Self {
115 self.allow = Some(capabilities.into_iter().collect());
116 self
117 }
118
119 #[must_use]
121 pub fn namespace_route_names(mut self, enabled: bool) -> Self {
122 self.namespace_route_names = enabled;
123 self
124 }
125
126 #[allow(clippy::needless_pass_by_value)] pub fn plugin(mut self, plugin: impl Plugin) -> Result<Self, FeatureError> {
134 let name = plugin.name();
135 if name.trim().is_empty() {
136 return Err(FeatureError::InvalidName(name));
137 }
138 if !self.plugin_names.insert(name) {
139 return Err(FeatureError::DuplicatePlugin(name));
140 }
141
142 let declared: BTreeSet<_> = plugin.capabilities().iter().copied().collect();
143 if let Some(allow) = &self.allow {
144 for capability in &declared {
145 if !allow.contains(capability) {
146 return Err(FeatureError::CapabilityDenied {
147 plugin: name,
148 capability: *capability,
149 });
150 }
151 }
152 }
153
154 let routes = plugin.routes();
155 let commands = plugin.commands();
156 #[cfg(feature = "database")]
157 let migrations = plugin.migrations();
158
159 ensure_capability(name, &declared, Capability::Routes, !routes.is_empty())?;
160 ensure_capability(name, &declared, Capability::Commands, !commands.is_empty())?;
161 #[cfg(feature = "database")]
162 ensure_capability(
163 name,
164 &declared,
165 Capability::Migrations,
166 !migrations.is_empty(),
167 )?;
168
169 for command in &commands {
170 if !self.command_names.insert(command.name()) {
171 return Err(FeatureError::DuplicateCommand {
172 plugin: name,
173 command: command.name(),
174 });
175 }
176 }
177 #[cfg(feature = "database")]
178 {
179 for migration in &migrations {
180 let id = migration.id().to_owned();
181 if !self.migration_ids.insert(id.clone()) {
182 return Err(FeatureError::DuplicateMigration { plugin: name, id });
183 }
184 }
185 }
186
187 let routes = if self.namespace_route_names {
188 routes.scoped(RouteGroup::new().name(format!("{name}.")))
189 } else {
190 routes
191 };
192 self.routes = self.routes.merge(routes);
193 self.commands.extend(commands);
194 #[cfg(feature = "database")]
195 self.migrations.extend(migrations);
196 let _ = plugin.version();
197 Ok(self)
198 }
199
200 #[must_use]
202 pub fn with_middleware<M>(mut self, middleware: M) -> Self
203 where
204 M: Middleware,
205 {
206 self.routes = self.routes.with_middleware(middleware);
207 self
208 }
209
210 #[must_use]
212 pub fn into_routes(self) -> Routes {
213 self.routes
214 }
215
216 #[must_use]
218 pub fn merge_into(self, routes: Routes) -> Routes {
219 routes.merge(self.routes)
220 }
221
222 #[must_use]
224 pub fn into_commands(self) -> Vec<CommandEntry> {
225 self.commands
226 }
227
228 #[must_use]
230 pub fn into_parts(self) -> FeatureParts {
231 FeatureParts {
232 routes: self.routes,
233 commands: self.commands,
234 #[cfg(feature = "database")]
235 migrations: self.migrations,
236 }
237 }
238
239 #[must_use]
241 #[cfg(feature = "database")]
242 pub fn into_migrations(self) -> Vec<Migration> {
243 self.migrations
244 }
245
246 #[must_use]
248 pub fn installed(&self) -> Vec<&'static str> {
249 self.plugin_names.iter().copied().collect()
250 }
251}
252
253pub struct FeatureParts {
255 pub routes: Routes,
256 pub commands: Vec<CommandEntry>,
257 #[cfg(feature = "database")]
258 pub migrations: Vec<Migration>,
259}
260
261fn ensure_capability(
262 plugin: &'static str,
263 declared: &BTreeSet<Capability>,
264 capability: Capability,
265 contributes: bool,
266) -> Result<(), FeatureError> {
267 if contributes && !declared.contains(&capability) {
268 return Err(FeatureError::UndeclaredCapability { plugin, capability });
269 }
270 Ok(())
271}
272
273#[derive(Debug, Error, Eq, PartialEq)]
275pub enum FeatureError {
276 #[error("plugin name must not be empty")]
277 InvalidName(&'static str),
278 #[error("duplicate plugin `{0}`")]
279 DuplicatePlugin(&'static str),
280 #[error(
281 "plugin `{plugin}` is not allowed to use capability `{}`",
282 capability.as_str()
283 )]
284 CapabilityDenied {
285 plugin: &'static str,
286 capability: Capability,
287 },
288 #[error(
289 "plugin `{plugin}` contributes `{}` but did not declare that capability",
290 capability.as_str()
291 )]
292 UndeclaredCapability {
293 plugin: &'static str,
294 capability: Capability,
295 },
296 #[error("plugin `{plugin}` registers duplicate command `{command}`")]
297 DuplicateCommand {
298 plugin: &'static str,
299 command: &'static str,
300 },
301 #[error("plugin `{plugin}` registers duplicate migration `{id}`")]
302 #[cfg(feature = "database")]
303 DuplicateMigration { plugin: &'static str, id: String },
304}
305
306#[cfg(test)]
307mod tests {
308 use super::*;
309 use phoenix_http::{IntoResponse, Json, Request};
310 use serde_json::json;
311
312 struct HelloPlugin;
313
314 impl Plugin for HelloPlugin {
315 fn name(&self) -> &'static str {
316 "hello"
317 }
318
319 fn capabilities(&self) -> &'static [Capability] {
320 &[Capability::Routes, Capability::Commands]
321 }
322
323 fn routes(&self) -> Routes {
324 Routes::new()
325 .get("/hello", |_request: Request| async {
326 Json(json!({ "ok": true })).into_response()
327 })
328 .name("index")
329 }
330
331 fn commands(&self) -> Vec<CommandEntry> {
332 vec![CommandEntry::new("hello", |_ctx| {
333 Box::pin(async { Ok(()) })
334 })]
335 }
336 }
337
338 struct UndeclaredRoutes;
339
340 impl Plugin for UndeclaredRoutes {
341 fn name(&self) -> &'static str {
342 "bad"
343 }
344
345 fn capabilities(&self) -> &'static [Capability] {
346 &[]
347 }
348
349 fn routes(&self) -> Routes {
350 Routes::new()
351 .get("/x", |_request: Request| async { "x".into_response() })
352 .name("x")
353 }
354 }
355
356 #[test]
357 fn installs_routes_and_commands_with_namespace() {
358 let parts = FeatureSet::new().plugin(HelloPlugin).unwrap().into_parts();
359 assert_eq!(parts.commands.len(), 1);
360 assert_eq!(parts.commands[0].name(), "hello");
361 let router = parts.routes.build().unwrap();
362 assert_eq!(router.url("hello.index", &[]).unwrap(), "/hello");
363 }
364
365 #[test]
366 fn rejects_undeclared_and_denied_capabilities() {
367 assert!(matches!(
368 FeatureSet::new().plugin(UndeclaredRoutes),
369 Err(FeatureError::UndeclaredCapability {
370 capability: Capability::Routes,
371 ..
372 })
373 ));
374 assert!(matches!(
375 FeatureSet::new()
376 .allow([Capability::Commands])
377 .plugin(HelloPlugin),
378 Err(FeatureError::CapabilityDenied {
379 capability: Capability::Routes,
380 ..
381 })
382 ));
383 }
384
385 #[test]
386 fn rejects_duplicate_plugins() {
387 let result = FeatureSet::new()
388 .plugin(HelloPlugin)
389 .and_then(|set| set.plugin(HelloPlugin));
390 assert_eq!(result.err(), Some(FeatureError::DuplicatePlugin("hello")));
391 }
392}