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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
use crate::{util::fmt_debug_view, *};
use std::any::Any;
use std::cell::{Cell, RefCell, UnsafeCell};
use std::collections::{HashMap, HashSet};
use std::fmt::{Debug, Formatter, Result as FormatResult};
use std::ops::Deref;
use std::rc::{Rc, Weak};
use std::sync::Mutex;
use tokens::{ChangeToken, SharedChangeToken};

struct Mediator {
    sync: Mutex<String>,
    token: RefCell<SharedChangeToken>,
    providers: UnsafeCell<Vec<Box<dyn ConfigurationProvider>>>,
    tokens: Cell<Vec<Box<dyn ChangeToken>>>,
    me: Weak<Mediator>,
}

impl Mediator {
    fn new(providers: Vec<Box<dyn ConfigurationProvider>>) -> Rc<Self> {
        Rc::new_cyclic(|me| {
            let tokens = Cell::new(Mediator::to_tokens(me, &providers));
            Self {
                sync: Mutex::default(),
                token: RefCell::default(),
                providers: UnsafeCell::new(providers),
                tokens,
                me: me.clone(),
            }
        })
    }

    fn to_tokens(
        me: &Weak<Mediator>,
        providers: &Vec<Box<dyn ConfigurationProvider>>,
    ) -> Vec<Box<dyn ChangeToken>> {
        providers
            .iter()
            .filter_map(|provider| provider.reload_token())
            .map(|token| {
                let this: Weak<Mediator> = me.clone();
                token.register(Box::new(move || this.upgrade().unwrap().raise_changed()));
                token
            })
            .collect()
    }

    fn providers(&self) -> &[Box<dyn ConfigurationProvider>] {
        unsafe { &*self.providers.get() }
    }

    fn reload(&self) {
        let _ = self.sync.lock().unwrap();

        // SAFETY: this is a 'chicken and egg' problem. there doesn't seem to be a better way that to moment.
        // 1. 'reload()' requires mutability, but mutability cannot be shared (e.g. Rc/Arc)
        // 2. interior mutability cannot be used because there is no way to then reference the slice of providers
        // 3. pushing interior mutability to providers breaks accessing values without copying the values
        //
        // reloading is not expected to be a common occurrence. while possible, it's also unlikely to be reloading
        // and reading a value at the same time. holding onto a configuration value reference instead of
        // copying/cloning it could be problematic. some providers (ex: in-memory) may do nothing when loaded or
        // do not support reloading. all providers are safely loaded at least once.
        //
        // consider refactoring to address this issue in the future.
        unsafe {
            for provider in &mut (*self.providers.get()).iter_mut() {
                provider.load();
            }
        }
    }

    fn reload_token(&self) -> Box<dyn ChangeToken> {
        let token;

        {
            let _ = self.sync.lock().unwrap();
            token = self.token.borrow().clone();
        }

        Box::new(token)
    }

    fn raise_changed(&self) {
        let tokens;

        unsafe {
            let _ = self.sync.lock().unwrap();
            tokens = Mediator::to_tokens(&self.me, &*self.providers.get());
        }

        let token = self.token.replace(SharedChangeToken::default());
        self.tokens.set(tokens);
        let callback = token.trigger().upgrade().unwrap();
        (callback)()
    }
}

/// Represents the root of a configuration.
#[derive(Clone)]
pub struct DefaultConfigurationRoot {
    mediator: Rc<Mediator>,
}

impl DefaultConfigurationRoot {
    /// Initializes a new root configuration.
    ///
    /// # Arguments
    ///
    /// * `providers` - The list of [configuration providers](trait.ConfigurationProvider.html) used in the configuration
    pub fn new(mut providers: Vec<Box<dyn ConfigurationProvider>>) -> Self {
        for provider in providers.iter_mut() {
            provider.load();
        }

        Self {
            mediator: Mediator::new(providers),
        }
    }
}

impl ConfigurationRoot for DefaultConfigurationRoot {
    fn reload(&mut self) {
        self.mediator.reload();
        self.mediator.raise_changed()
    }

    fn providers(&self) -> &[Box<dyn ConfigurationProvider>] {
        self.mediator.providers()
    }

    fn as_config(&self) -> Box<dyn Configuration> {
        Box::new(self.clone())
    }
}

impl Configuration for DefaultConfigurationRoot {
    fn get(&self, key: &str) -> Option<&str> {
        for provider in self.providers().iter().rev() {
            if let Some(value) = provider.get(key) {
                return Some(value);
            }
        }

        None
    }

    fn section(&self, key: &str) -> Box<dyn ConfigurationSection> {
        Box::new(DefaultConfigurationSection::new(
            Box::new(self.clone()),
            key,
        ))
    }

    fn children(&self) -> Vec<Box<dyn ConfigurationSection>> {
        let keys: HashSet<_> = self
            .providers()
            .iter()
            .fold(Vec::new(), |mut earlier_keys, provider| {
                provider.child_keys(&mut earlier_keys, None);
                earlier_keys
            })
            .into_iter()
            .collect();

        keys.iter().map(|key| self.section(key)).collect()
    }

    fn reload_token(&self) -> Box<dyn ChangeToken> {
        self.mediator.reload_token()
    }

    fn iter_relative(
        &self,
        make_paths_relative: bool,
    ) -> Box<dyn Iterator<Item = (String, String)>> {
        Box::new(ConfigurationIterator::new(self, make_paths_relative))
    }
}

impl Debug for DefaultConfigurationRoot {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> FormatResult {
        fmt_debug_view(self, formatter)
    }
}

impl Deref for DefaultConfigurationRoot {
    type Target = dyn Configuration;

    fn deref(&self) -> &Self::Target {
        self
    }
}

/// Represent a configuration section.
pub struct DefaultConfigurationSection {
    root: Box<dyn ConfigurationRoot>,
    path: String,
}

impl DefaultConfigurationSection {
    /// Initializes a new configuration section.
    ///
    /// # Arguments
    ///
    /// * `root` - A reference to the [configuration root](trait.ConfigurationRoot.html)
    /// * `path` - The path of the configuration section
    pub fn new(root: Box<dyn ConfigurationRoot>, path: &str) -> Self {
        Self {
            root,
            path: path.to_owned(),
        }
    }

    #[inline]
    fn subkey(&self, key: &str) -> String {
        ConfigurationPath::combine(&[&self.path, key])
    }
}

impl Configuration for DefaultConfigurationSection {
    fn get(&self, key: &str) -> Option<&str> {
        self.root.get(&self.subkey(key))
    }

    fn section(&self, key: &str) -> Box<dyn ConfigurationSection> {
        self.root.section(&self.subkey(key))
    }

    fn children(&self) -> Vec<Box<dyn ConfigurationSection>> {
        let keys: HashSet<_> = self
            .root
            .providers()
            .iter()
            .fold(Vec::new(), |mut earlier_keys, provider| {
                provider.child_keys(&mut earlier_keys, Some(&self.path));
                earlier_keys
            })
            .into_iter()
            .collect();

        keys.iter().map(|key| self.section(key)).collect()
    }

    fn reload_token(&self) -> Box<dyn ChangeToken> {
        self.root.reload_token()
    }

    fn as_section(&self) -> Option<&dyn ConfigurationSection> {
        Some(self)
    }

    fn iter_relative(
        &self,
        make_paths_relative: bool,
    ) -> Box<dyn Iterator<Item = (String, String)>> {
        Box::new(ConfigurationIterator::new(self, make_paths_relative))
    }
}

impl ConfigurationSection for DefaultConfigurationSection {
    fn key(&self) -> &str {
        ConfigurationPath::section_key(&self.path)
    }

    fn path(&self) -> &str {
        &self.path
    }

    fn value(&self) -> &str {
        self.root.get(&self.path).unwrap_or("")
    }
}

impl Deref for DefaultConfigurationSection {
    type Target = dyn Configuration;

    fn deref(&self) -> &Self::Target {
        self
    }
}

/// Represents a configuration builder.
#[derive(Default)]
pub struct DefaultConfigurationBuilder {
    /// Gets the associated configuration sources.
    pub sources: Vec<Box<dyn ConfigurationSource>>,

    /// Gets the properties that can be passed to configuration sources.
    pub properties: HashMap<String, Box<dyn Any>>,
}

impl DefaultConfigurationBuilder {
    /// Initializes a new, default configuration builder.
    pub fn new() -> Self {
        Self::default()
    }
}

impl ConfigurationBuilder for DefaultConfigurationBuilder {
    fn properties(&self) -> &HashMap<String, Box<dyn Any>> {
        &self.properties
    }

    fn sources(&self) -> &[Box<dyn ConfigurationSource>] {
        &self.sources
    }

    fn add(&mut self, source: Box<dyn ConfigurationSource>) {
        self.sources.push(source)
    }

    fn build(&self) -> Box<dyn ConfigurationRoot> {
        Box::new(DefaultConfigurationRoot::new(
            self.sources.iter().map(|s| s.build(self)).collect(),
        ))
    }
}