swadhinbiswas feat(core): add protocol handlers, data layer, validation, and plugin system · 7/7/2026
086453c
89 lines · 2.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
use std::collections::HashMap;

use anyhow::Result;
use async_trait::async_trait;

use crate::Server;

/// Lifecycle trait for JustAPI plugins.
/// Plugins can hook into the server lifecycle and modify the application setup.
#[async_trait]
pub trait Plugin: Send + Sync {
    /// Unique name of the plugin.
    fn name(&self) -> &'static str;

    /// Called when the plugin is registered with the server.
    /// The plugin can register middlewares, routers, or modify the Server configuration here.
    fn build(&self, _server: &mut Server) -> Result<()> {
        Ok(())
    }

    /// Called when the server is starting up.
    async fn on_startup(&self) -> Result<()> {
        Ok(())
    }

    /// Called when the server is shutting down.
    async fn on_shutdown(&self) -> Result<()> {
        Ok(())
    }
}

/// A registration entry for a plugin. This is used by the `inventory` crate
/// to collect statically registered plugins at compile time.
pub struct PluginRegistration {
    pub name: &'static str,
    pub builder: fn() -> Box<dyn Plugin>,
}

inventory::collect!(PluginRegistration);

/// A registry of loaded plugins.
#[derive(Default)]
pub struct PluginRegistry {
    plugins: HashMap<String, Box<dyn Plugin>>,
}

impl PluginRegistry {
    pub fn new() -> Self {
        Self::default()
    }

    /// Register a plugin instance explicitly.
    pub fn register(&mut self, plugin: Box<dyn Plugin>) {
        self.plugins.insert(plugin.name().to_string(), plugin);
    }

    /// Load all plugins that were registered statically via the `inventory` crate.
    pub fn load_static_plugins(&mut self) {
        for reg in inventory::iter::<PluginRegistration> {
            let plugin = (reg.builder)();
            self.plugins.insert(plugin.name().to_string(), plugin);
        }
    }

    /// Invoke the `build` lifecycle hook on all registered plugins.
    pub fn build_all(&self, server: &mut Server) -> Result<()> {
        for plugin in self.plugins.values() {
            plugin.build(server)?;
        }
        Ok(())
    }

    /// Invoke the `on_startup` lifecycle hook on all registered plugins.
    pub async fn on_startup_all(&self) -> Result<()> {
        for plugin in self.plugins.values() {
            plugin.on_startup().await?;
        }
        Ok(())
    }

    /// Invoke the `on_shutdown` lifecycle hook on all registered plugins.
    pub async fn on_shutdown_all(&self) -> Result<()> {
        for plugin in self.plugins.values() {
            plugin.on_shutdown().await?;
        }
        Ok(())
    }
}