Skip to main content

allsource_core/infrastructure/persistence/
system_bootstrap.rs

1#[cfg(feature = "server")]
2use crate::infrastructure::repositories::EventSourcedAuthRepository;
3use crate::{
4    application::services::consumer::ConsumerRegistry,
5    domain::{entities::TenantQuotas, repositories::TenantRepository, value_objects::TenantId},
6    error::Result,
7    infrastructure::{
8        persistence::{
9            SystemCheckpointSettings, SystemCheckpointer, SystemMetadataStore, SystemStoreOptions,
10        },
11        repositories::{
12            EventSourcedAuditRepository, EventSourcedConfigRepository, EventSourcedTenantRepository,
13        },
14    },
15};
16use std::{path::PathBuf, sync::Arc};
17
18/// Holds all event-sourced repositories for system metadata.
19///
20/// This is the result of a successful system bootstrap. All repositories
21/// share a single `SystemMetadataStore` for storage, ensuring atomic
22/// write-ahead logging and coordinated recovery.
23pub struct SystemRepositories {
24    /// The underlying durable store
25    pub system_store: Arc<SystemMetadataStore>,
26
27    /// Event-sourced tenant repository
28    pub tenant_repository: Arc<EventSourcedTenantRepository>,
29
30    /// Event-sourced audit repository
31    pub audit_repository: Arc<EventSourcedAuditRepository>,
32
33    /// Event-sourced config repository
34    pub config_repository: Arc<EventSourcedConfigRepository>,
35
36    /// Event-sourced auth repository (API keys)
37    #[cfg(feature = "server")]
38    pub auth_repository: Arc<EventSourcedAuthRepository>,
39
40    /// Durable consumer registry for subscription cursor tracking
41    pub consumer_registry: Arc<ConsumerRegistry>,
42
43    /// Writes the checkpoints the next boot starts from
44    pub checkpointer: Arc<SystemCheckpointer>,
45}
46
47/// Staged system initialization with static stability.
48///
49/// Follows the AWS data plane / control plane separation pattern:
50///
51/// ```text
52/// Stage 1: Initialize SystemMetadataStore from local storage
53/// Stage 2: Replay _system/* streams → populate in-memory caches
54/// Stage 3: If empty, run first-boot bootstrap (create default tenant)
55/// Stage 4: Return SystemRepositories → start accepting traffic
56/// ```
57///
58/// # Static Stability
59///
60/// After bootstrap, all metadata reads go through in-memory caches (DashMap).
61/// If a system stream write fails, the error is logged but does NOT block
62/// the data plane. User event ingestion and queries continue with cached
63/// metadata until the system store recovers.
64pub struct SystemBootstrap;
65
66impl SystemBootstrap {
67    /// Execute the staged initialization sequence.
68    ///
69    /// # Arguments
70    /// * `system_data_dir` — Path to the system metadata storage directory
71    /// * `bootstrap_tenant` — Optional default tenant name for first-boot
72    ///
73    /// # Returns
74    /// `SystemRepositories` with all event-sourced repos initialized and caches populated.
75    #[cfg_attr(feature = "hotpath", hotpath::measure)]
76    pub async fn initialize(
77        system_data_dir: PathBuf,
78        bootstrap_tenant: Option<String>,
79    ) -> Result<SystemRepositories> {
80        Self::initialize_with(
81            system_data_dir,
82            bootstrap_tenant,
83            SystemCheckpointSettings::default(),
84        )
85        .await
86    }
87
88    pub async fn initialize_with(
89        system_data_dir: PathBuf,
90        bootstrap_tenant: Option<String>,
91        checkpoints: SystemCheckpointSettings,
92    ) -> Result<SystemRepositories> {
93        // Stage 1: Initialize SystemMetadataStore
94        tracing::info!(
95            "Stage 1: Initializing system metadata store at {}",
96            system_data_dir.display()
97        );
98        let started = std::time::Instant::now();
99        let system_store = Arc::new(SystemMetadataStore::open(
100            &system_data_dir,
101            SystemStoreOptions {
102                load_checkpoint: checkpoints.enabled,
103                ..SystemStoreOptions::default()
104            },
105        )?);
106        tracing::info!("Stage 1: system store opened in {:?}", started.elapsed());
107        tracing::info!(
108            "System store initialized: {} events recovered",
109            system_store.total_events()
110        );
111
112        // Stage 2: Replay system streams → populate in-memory caches
113        tracing::info!("Stage 2: Replaying system streams into repository caches");
114        let timed = |name: &str, started: std::time::Instant| {
115            tracing::info!("Stage 2: {name} cache rebuilt in {:?}", started.elapsed());
116        };
117        let started = std::time::Instant::now();
118        let tenant_repository = Arc::new(EventSourcedTenantRepository::new(system_store.clone()));
119        timed("tenant", started);
120        let started = std::time::Instant::now();
121        let audit_repository = Arc::new(EventSourcedAuditRepository::new(system_store.clone()));
122        timed("audit", started);
123        let started = std::time::Instant::now();
124        let config_repository = Arc::new(EventSourcedConfigRepository::new(system_store.clone()));
125        timed("config", started);
126        #[cfg(feature = "server")]
127        let auth_repository = {
128            let started = std::time::Instant::now();
129            let repository = Arc::new(EventSourcedAuthRepository::new(system_store.clone()));
130            timed("auth", started);
131            repository
132        };
133        let started = std::time::Instant::now();
134        let consumer_registry = Arc::new(ConsumerRegistry::new_durable(system_store.clone()));
135        timed("consumer", started);
136
137        let tenant_count = tenant_repository.count().await.unwrap_or(0);
138        #[cfg(feature = "server")]
139        tracing::info!(
140            "System caches populated: {} tenants, {} config entries, {} API keys ({} active), {} consumers",
141            tenant_count,
142            config_repository.count(),
143            auth_repository.count(),
144            auth_repository.active_count(),
145            consumer_registry.count()
146        );
147        #[cfg(not(feature = "server"))]
148        tracing::info!(
149            "System caches populated: {} tenants, {} config entries, {} consumers",
150            tenant_count,
151            config_repository.count(),
152            consumer_registry.count()
153        );
154
155        // Stage 3: First-boot bootstrap (if needed)
156        if tenant_count == 0 {
157            if let Some(ref tenant_name) = bootstrap_tenant {
158                tracing::info!(
159                    "Stage 3: First boot detected — creating default tenant '{}'",
160                    tenant_name
161                );
162
163                // Use the tenant name as the tenant ID (lowercase, hyphens)
164                let tenant_id_str = tenant_name
165                    .to_lowercase()
166                    .replace(' ', "-")
167                    .chars()
168                    .filter(|c| c.is_alphanumeric() || *c == '-' || *c == '_')
169                    .collect::<String>();
170
171                match TenantId::new(tenant_id_str) {
172                    Ok(tenant_id) => {
173                        match tenant_repository
174                            .create(tenant_id, tenant_name.clone(), TenantQuotas::unlimited())
175                            .await
176                        {
177                            Ok(_) => {
178                                tracing::info!("Default tenant '{}' created", tenant_name);
179                            }
180                            Err(e) => {
181                                tracing::warn!("Failed to create default tenant: {}", e);
182                            }
183                        }
184                    }
185                    Err(e) => {
186                        tracing::warn!("Invalid default tenant ID: {}", e);
187                    }
188                }
189            } else {
190                tracing::info!(
191                    "Stage 3: No bootstrap tenant configured, skipping first-boot setup"
192                );
193            }
194        } else {
195            tracing::info!("Stage 3: Skipped — {} existing tenants found", tenant_count);
196        }
197
198        // Nothing else holds these repositories yet, so the tenant cache is
199        // exactly the fold of every resident tenant event.
200        let checkpointer = Arc::new(SystemCheckpointer::new(system_store.clone(), checkpoints));
201        checkpointer.checkpoint_at_boot(&tenant_repository);
202
203        // Stage 4: Ready
204        tracing::info!("Stage 4: System metadata initialized — ready to accept traffic");
205
206        Ok(SystemRepositories {
207            system_store,
208            tenant_repository,
209            audit_repository,
210            config_repository,
211            #[cfg(feature = "server")]
212            auth_repository,
213            consumer_registry,
214            checkpointer,
215        })
216    }
217
218    /// Try to initialize system repositories, falling back to None if the
219    /// system data directory is not configured.
220    ///
221    /// This implements the backward-compatibility path: if no system_data_dir
222    /// is set, the system continues with in-memory repositories.
223    pub async fn try_initialize(
224        system_data_dir: Option<PathBuf>,
225        bootstrap_tenant: Option<String>,
226    ) -> Option<SystemRepositories> {
227        Self::try_initialize_with(
228            system_data_dir,
229            bootstrap_tenant,
230            SystemCheckpointSettings::default(),
231        )
232        .await
233    }
234
235    pub async fn try_initialize_with(
236        system_data_dir: Option<PathBuf>,
237        bootstrap_tenant: Option<String>,
238        checkpoints: SystemCheckpointSettings,
239    ) -> Option<SystemRepositories> {
240        if let Some(dir) = system_data_dir {
241            match Self::initialize_with(dir, bootstrap_tenant, checkpoints).await {
242                Ok(repos) => Some(repos),
243                Err(e) => {
244                    tracing::error!(
245                        "Failed to initialize system metadata store: {}. \
246                     Falling back to in-memory repositories.",
247                        e
248                    );
249                    None
250                }
251            }
252        } else {
253            tracing::info!(
254                "No system_data_dir configured. Using in-memory repositories for metadata."
255            );
256            None
257        }
258    }
259}
260
261#[cfg(test)]
262mod tests {
263    use super::*;
264    use tempfile::TempDir;
265
266    #[tokio::test]
267    async fn test_staged_initialization_empty() {
268        let temp_dir = TempDir::new().unwrap();
269        let system_dir = temp_dir.path().join("__system");
270
271        let repos = SystemBootstrap::initialize(system_dir, None).await.unwrap();
272
273        assert_eq!(repos.tenant_repository.count().await.unwrap(), 0);
274        assert_eq!(repos.config_repository.count(), 0);
275    }
276
277    #[tokio::test]
278    async fn test_staged_initialization_with_bootstrap_tenant() {
279        let temp_dir = TempDir::new().unwrap();
280        let system_dir = temp_dir.path().join("__system");
281
282        let repos = SystemBootstrap::initialize(system_dir, Some("Default Tenant".to_string()))
283            .await
284            .unwrap();
285
286        assert_eq!(repos.tenant_repository.count().await.unwrap(), 1);
287
288        let tenant_id = TenantId::new("default-tenant".to_string()).unwrap();
289        let tenant = repos
290            .tenant_repository
291            .find_by_id(&tenant_id)
292            .await
293            .unwrap();
294        assert!(tenant.is_some());
295        assert_eq!(tenant.unwrap().name(), "Default Tenant");
296    }
297
298    #[tokio::test]
299    async fn test_staged_initialization_recovery() {
300        let temp_dir = TempDir::new().unwrap();
301        let system_dir = temp_dir.path().join("__system");
302
303        // First boot
304        {
305            let repos =
306                SystemBootstrap::initialize(system_dir.clone(), Some("ACME Corp".to_string()))
307                    .await
308                    .unwrap();
309
310            assert_eq!(repos.tenant_repository.count().await.unwrap(), 1);
311
312            // Add some config
313            repos
314                .config_repository
315                .set("feature_flag", serde_json::json!(true), None)
316                .unwrap();
317        }
318
319        // Restart — should recover everything
320        {
321            let repos = SystemBootstrap::initialize(system_dir, None).await.unwrap();
322
323            // Tenant should survive
324            assert_eq!(repos.tenant_repository.count().await.unwrap(), 1);
325
326            // Config should survive
327            assert_eq!(repos.config_repository.count(), 1);
328            assert_eq!(
329                repos.config_repository.get_value("feature_flag").unwrap(),
330                serde_json::json!(true)
331            );
332        }
333    }
334
335    #[tokio::test]
336    async fn test_try_initialize_none() {
337        let result = SystemBootstrap::try_initialize(None, None).await;
338        assert!(result.is_none());
339    }
340
341    #[tokio::test]
342    async fn test_try_initialize_some() {
343        let temp_dir = TempDir::new().unwrap();
344        let system_dir = temp_dir.path().join("__system");
345
346        let result = SystemBootstrap::try_initialize(Some(system_dir), None).await;
347        assert!(result.is_some());
348    }
349
350    #[tokio::test]
351    async fn test_no_duplicate_bootstrap_on_restart() {
352        let temp_dir = TempDir::new().unwrap();
353        let system_dir = temp_dir.path().join("__system");
354
355        // First boot with bootstrap
356        SystemBootstrap::initialize(system_dir.clone(), Some("ACME".to_string()))
357            .await
358            .unwrap();
359
360        // Second boot with same bootstrap config — should NOT create duplicate
361        let repos = SystemBootstrap::initialize(system_dir, Some("ACME".to_string()))
362            .await
363            .unwrap();
364
365        assert_eq!(repos.tenant_repository.count().await.unwrap(), 1);
366    }
367}