fedimint_core/module/
registry.rs

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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
use std::collections::BTreeMap;

use anyhow::anyhow;

pub use crate::core::ModuleInstanceId;
use crate::core::{Decoder, ModuleKind};
use crate::server::DynServerModule;

/// Module Registry hold module-specific data `M` by the `ModuleInstanceId`
#[derive(Debug)]
pub struct ModuleRegistry<M, State = ()> {
    inner: BTreeMap<ModuleInstanceId, (ModuleKind, M)>,
    // It is sometimes useful for registries to have some state to modify
    // their behavior.
    state: State,
}

impl<M, State> Clone for ModuleRegistry<M, State>
where
    State: Clone,
    M: Clone,
{
    fn clone(&self) -> Self {
        Self {
            inner: self.inner.clone(),
            state: self.state.clone(),
        }
    }
}

impl<M, State> Default for ModuleRegistry<M, State>
where
    State: Default,
{
    fn default() -> Self {
        Self {
            inner: BTreeMap::new(),
            state: State::default(),
        }
    }
}

impl<M, State> From<BTreeMap<ModuleInstanceId, (ModuleKind, M)>> for ModuleRegistry<M, State>
where
    State: Default,
{
    fn from(value: BTreeMap<ModuleInstanceId, (ModuleKind, M)>) -> Self {
        Self {
            inner: value,
            state: Default::default(),
        }
    }
}

impl<M, State> FromIterator<(ModuleInstanceId, ModuleKind, M)> for ModuleRegistry<M, State>
where
    State: Default,
{
    fn from_iter<T: IntoIterator<Item = (ModuleInstanceId, ModuleKind, M)>>(iter: T) -> Self {
        Self::new(iter)
    }
}

impl<M, State> ModuleRegistry<M, State> {
    /// Create [`Self`] from an iterator of pairs
    pub fn new(iter: impl IntoIterator<Item = (ModuleInstanceId, ModuleKind, M)>) -> Self
    where
        State: Default,
    {
        Self {
            inner: iter
                .into_iter()
                .map(|(id, kind, module)| (id, (kind, module)))
                .collect(),
            state: Default::default(),
        }
    }

    /// Is registry empty?
    pub fn is_empty(&self) -> bool {
        self.inner.is_empty()
    }

    /// Return an iterator over all module data
    pub fn iter_modules(&self) -> impl Iterator<Item = (ModuleInstanceId, &ModuleKind, &M)> {
        self.inner.iter().map(|(id, (kind, m))| (*id, kind, m))
    }

    /// Return an iterator over module ids an kinds
    pub fn iter_modules_id_kind(&self) -> impl Iterator<Item = (ModuleInstanceId, &ModuleKind)> {
        self.inner.iter().map(|(id, (kind, _))| (*id, kind))
    }

    /// Return an iterator over all module data
    pub fn iter_modules_mut(
        &mut self,
    ) -> impl Iterator<Item = (ModuleInstanceId, &ModuleKind, &mut M)> {
        self.inner
            .iter_mut()
            .map(|(id, (kind, m))| (*id, &*kind, m))
    }

    /// Return an iterator over all module data
    pub fn into_iter_modules(self) -> impl Iterator<Item = (ModuleInstanceId, ModuleKind, M)> {
        self.inner.into_iter().map(|(id, (kind, m))| (id, kind, m))
    }

    /// Get module data by instance id
    pub fn get(&self, id: ModuleInstanceId) -> Option<&M> {
        self.inner.get(&id).map(|m| &m.1)
    }

    /// Get module data by instance id, including [`ModuleKind`]
    pub fn get_with_kind(&self, id: ModuleInstanceId) -> Option<&(ModuleKind, M)> {
        self.inner.get(&id)
    }
}

impl<M: std::fmt::Debug, State> ModuleRegistry<M, State> {
    /// Return the module data belonging to the module identified by the
    /// supplied `module_id`
    ///
    /// # Panics
    /// If the module isn't in the registry
    pub fn get_expect(&self, id: ModuleInstanceId) -> &M {
        &self
            .inner
            .get(&id)
            .ok_or_else(|| {
                anyhow!(
                    "Instance ID not found: got {}, expected one of {:?}",
                    id,
                    self.inner.keys().collect::<Vec<_>>()
                )
            })
            .expect("Only existing instance should be fetched")
            .1
    }

    /// Add a module to the registry
    pub fn register_module(&mut self, id: ModuleInstanceId, kind: ModuleKind, module: M) {
        // FIXME: return result
        assert!(
            self.inner.insert(id, (kind, module)).is_none(),
            "Module was already registered!"
        );
    }

    pub fn append_module(&mut self, kind: ModuleKind, module: M) {
        let last_id = self
            .inner
            .last_key_value()
            .map(|id| id.0.checked_add(1).expect("Module id overflow"))
            .unwrap_or_default();
        assert!(
            self.inner.insert(last_id, (kind, module)).is_none(),
            "Module was already registered?!"
        );
    }
}

/// Collection of server modules
pub type ServerModuleRegistry = ModuleRegistry<DynServerModule>;

impl ServerModuleRegistry {
    /// Generate a `ModuleDecoderRegistry` from this `ModuleRegistry`
    pub fn decoder_registry(&self) -> ModuleDecoderRegistry {
        // TODO: cache decoders
        self.inner
            .iter()
            .map(|(&id, (kind, module))| (id, kind.clone(), module.decoder()))
            .collect::<ModuleDecoderRegistry>()
    }
}

#[derive(Default, Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub enum DecodingMode {
    /// Reject unknown module instance ids
    #[default]
    Reject,
    /// Fallback to decoding unknown module instance ids as
    /// [`crate::core::DynUnknown`]
    Fallback,
}

/// Collection of decoders belonging to modules, typically obtained from a
/// `ModuleRegistry`
pub type ModuleDecoderRegistry = ModuleRegistry<Decoder, DecodingMode>;

impl ModuleDecoderRegistry {
    pub fn with_fallback(self) -> Self {
        Self {
            state: DecodingMode::Fallback,
            ..self
        }
    }

    pub fn decoding_mode(&self) -> DecodingMode {
        self.state
    }

    /// Panic if the [`Self::decoding_mode`] is not `Reject`
    pub fn assert_reject_mode(&self) {
        assert_eq!(self.state, DecodingMode::Reject);
    }
}