Skip to main content

soma_provider_core/registry/
builder.rs

1use std::{collections::BTreeMap, sync::Arc};
2
3use crate::{
4    Provider, ProviderId, ProviderRegistry, ProviderValidationError, validate_provider_manifest,
5};
6
7use super::RegistrySnapshot;
8
9#[derive(Default)]
10pub struct ProviderRegistryBuilder {
11    providers: BTreeMap<String, Arc<dyn Provider>>,
12}
13
14impl ProviderRegistryBuilder {
15    pub fn new() -> Self {
16        Self::default()
17    }
18
19    pub fn register(
20        self,
21        provider: impl Provider + 'static,
22    ) -> Result<Self, ProviderValidationError> {
23        self.register_arc(Arc::new(provider))
24    }
25
26    pub fn register_arc(
27        mut self,
28        provider: Arc<dyn Provider>,
29    ) -> Result<Self, ProviderValidationError> {
30        let catalog = provider.catalog();
31        validate_provider_manifest(&catalog)?;
32        let id = ProviderId::new(&catalog.provider.name).map_err(|error| {
33            ProviderValidationError::new("invalid_provider_name", error.to_string())
34        })?;
35        if self.providers.insert(id.to_string(), provider).is_some() {
36            return Err(ProviderValidationError::new(
37                "duplicate_provider_name",
38                format!("duplicate provider `{id}`"),
39            ));
40        }
41        Ok(self)
42    }
43
44    pub fn build(self) -> Result<ProviderRegistry, ProviderValidationError> {
45        let providers = Arc::new(self.providers);
46        let catalogs = providers
47            .values()
48            .map(|provider| provider.catalog())
49            .collect::<Vec<_>>();
50        let snapshot = Arc::new(RegistrySnapshot::build(catalogs)?);
51        Ok(ProviderRegistry {
52            providers,
53            snapshot,
54        })
55    }
56}