Skip to main content

serenade_lock/
compile_pass.rs

1//! DI tag and compile pass for the default lock store.
2
3use std::sync::Arc;
4
5use serenade_di::{CompilePass, ContainerBuilder, DiError, ServiceDefinition};
6
7use crate::{InMemoryLockStore, LockFactory, LockStore};
8
9/// Service tag applied to lock store definitions.
10pub const LOCK_STORE_TAG: &str = "lock.store";
11
12/// Container id of the default lock store when registered by the pass.
13pub const DEFAULT_LOCK_STORE_SERVICE: &str = "lock.store";
14
15/// Newtype so [`LockStore`] trait objects can be stored in the container.
16#[derive(Clone)]
17pub struct LockStoreService(pub Arc<dyn LockStore>);
18
19impl LockStoreService {
20    /// Builds a [`LockFactory`] against the wrapped store.
21    #[must_use]
22    pub fn factory(&self) -> LockFactory {
23        LockFactory::new(Arc::clone(&self.0))
24    }
25}
26
27/// Seeds [`DEFAULT_LOCK_STORE_SERVICE`] with an [`InMemoryLockStore`] when missing.
28#[derive(Debug, Default)]
29pub struct RegisterDefaultLockPass;
30
31impl CompilePass for RegisterDefaultLockPass {
32    fn name(&self) -> &'static str {
33        "register_default_lock_store"
34    }
35
36    fn process(&self, builder: &mut ContainerBuilder) -> Result<(), DiError> {
37        let has_default = builder
38            .definitions()
39            .iter()
40            .any(|definition| definition.id() == DEFAULT_LOCK_STORE_SERVICE);
41        if has_default {
42            return Ok(());
43        }
44
45        // `expect`: default id cannot collide after the has_default guard above.
46        builder
47            .register(
48                ServiceDefinition::new(DEFAULT_LOCK_STORE_SERVICE).with_tag(LOCK_STORE_TAG),
49                |_container| {
50                    Ok(Box::new(LockStoreService(
51                        Arc::new(InMemoryLockStore::new()) as Arc<dyn LockStore>,
52                    )))
53                },
54            )
55            .expect("default lock.store id is unique");
56
57        Ok(())
58    }
59}