moduforge_state/
plugin.rs1use async_trait::async_trait;
2use std::sync::Arc;
3
4use super::state::{State, StateConfig};
5use super::transaction::Transaction;
6
7#[async_trait]
10pub trait PluginTrait: Send + Sync + Debug {
11 async fn append_transaction(
14 &self,
15 _: &[Transaction],
16 _: &State,
17 _: &State,
18 ) -> Option<Transaction> {
19 None
20 }
21 async fn filter_transaction(
24 &self,
25 _: &Transaction,
26 _: &State,
27 ) -> bool {
28 true
29 }
30}
31#[async_trait]
34pub trait StateField: Send + Sync + Debug {
35 async fn init(
37 &self,
38 config: &StateConfig,
39 instance: Option<&State>,
40 ) -> PluginState;
41 async fn apply(
44 &self,
45 tr: &Transaction,
46 value: PluginState,
47 old_state: &State,
48 new_state: &State,
49 ) -> PluginState;
50 fn serialize(
52 &self,
53 _value: PluginState,
54 ) -> Option<Vec<u8>> {
55 None
56 }
57 fn deserialize(
59 &self,
60 _value: &Vec<u8>,
61 ) -> Option<PluginState> {
62 None
63 }
64}
65#[derive(Clone, Debug)]
68pub struct PluginSpec {
69 pub state: Option<Arc<dyn StateField>>,
70 pub key: PluginKey,
71 pub tr: Option<Arc<dyn PluginTrait>>,
72 pub priority: i32,
73}
74
75unsafe impl Send for PluginSpec {}
76unsafe impl Sync for PluginSpec {}
77
78impl PluginSpec {
79 async fn filter_transaction(
81 &self,
82 tr: &Transaction,
83 state: &State,
84 ) -> bool {
85 match &self.tr {
86 Some(filter) => filter.filter_transaction(tr, state).await,
87 None => false,
88 }
89 }
90 async fn append_transaction<'a>(
92 &self,
93 trs: &'a [Transaction],
94 old_state: &State,
95 new_state: &State,
96 ) -> Option<Transaction> {
97 match &self.tr {
98 Some(transaction) => {
99 transaction.append_transaction(trs, old_state, new_state).await
100 },
101 None => None,
102 }
103 }
104}
105#[derive(Clone, Debug)]
108pub struct Plugin {
109 pub spec: PluginSpec,
110 pub key: String,
111}
112
113unsafe impl Send for Plugin {}
114unsafe impl Sync for Plugin {}
115
116impl Plugin {
117 pub fn new(spec: PluginSpec) -> Self {
119 let key = spec.key.0.clone();
120
121 Plugin { spec, key }
122 }
123
124 pub fn get_state(
126 &self,
127 state: &State,
128 ) -> Option<PluginState> {
129 state.get_field(&self.key)
130 }
131 pub async fn apply_filter_transaction(
133 &self,
134 tr: &Transaction,
135 state: &State,
136 ) -> bool {
137 self.spec.filter_transaction(tr, state).await
138 }
139
140 pub async fn apply_append_transaction(
142 &self,
143 trs: &[Transaction],
144 old_state: &State,
145 new_state: &State,
146 ) -> Option<Transaction> {
147 self.spec.append_transaction(trs, old_state, new_state).await
148 }
149}
150
151pub type PluginState = Arc<dyn std::any::Any + Send + Sync>;
154
155use std::fmt::Debug;
156
157pub type PluginKey = (String, String);