1#![doc = include_str!("../../Plugin.md")]
2
3pub mod component;
5pub mod service;
6
7use crate::error::Result;
8use crate::{app::AppBuilder, error::AppError};
9use async_trait::async_trait;
10use component::ComponentRef;
11use std::{
12 any::{self, Any},
13 ops::Deref,
14 sync::Arc,
15};
16
17#[derive(Clone)]
19pub struct PluginRef(Arc<dyn Plugin>);
20
21#[async_trait]
23pub trait Plugin: Any + Send + Sync {
24 async fn build(&self, _app: &mut AppBuilder) {}
26
27 fn immediately_build(&self, _app: &mut AppBuilder) {}
31
32 fn name(&self) -> &str {
35 std::any::type_name::<Self>()
36 }
37
38 fn dependencies(&self) -> Vec<&str> {
40 vec![]
41 }
42
43 fn immediately(&self) -> bool {
45 false
46 }
47}
48
49impl PluginRef {
50 pub(crate) fn new<T: Plugin>(plugin: T) -> Self {
51 Self(Arc::new(plugin))
52 }
53}
54
55impl Deref for PluginRef {
56 type Target = dyn Plugin;
57
58 fn deref(&self) -> &Self::Target {
59 &*self.0
60 }
61}
62
63pub trait ComponentRegistry {
65 fn get_component_ref<T>(&self) -> Option<ComponentRef<T>>
67 where
68 T: Any + Send + Sync;
69
70 fn get_expect_component_ref<T>(&self) -> ComponentRef<T>
73 where
74 T: Clone + Send + Sync + 'static,
75 {
76 self.get_component_ref().unwrap_or_else(|| {
77 panic!(
78 "{} component not exists in registry",
79 std::any::type_name::<T>()
80 )
81 })
82 }
83
84 fn try_get_component_ref<T>(&self) -> Result<ComponentRef<T>>
87 where
88 T: Clone + Send + Sync + 'static,
89 {
90 self.get_component_ref()
91 .ok_or_else(|| AppError::ComponentNotExist(std::any::type_name::<T>()))
92 }
93
94 fn get_component<T>(&self) -> Option<T>
96 where
97 T: Clone + Send + Sync + 'static;
98
99 fn get_expect_component<T>(&self) -> T
102 where
103 T: Clone + Send + Sync + 'static,
104 {
105 self.get_component().unwrap_or_else(|| {
106 panic!(
107 "{} component not exists in registry",
108 std::any::type_name::<T>()
109 )
110 })
111 }
112
113 fn try_get_component<T>(&self) -> Result<T>
116 where
117 T: Clone + Send + Sync + 'static,
118 {
119 self.get_component()
120 .ok_or_else(|| AppError::ComponentNotExist(std::any::type_name::<T>()))
121 }
122
123 fn has_component<T>(&self) -> bool
125 where
126 T: Any + Send + Sync;
127}
128
129pub trait MutableComponentRegistry: ComponentRegistry {
131 fn add_component<C>(&mut self, component: C) -> &mut Self
133 where
134 C: Clone + any::Any + Send + Sync;
135}