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
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
//! Verdure Application Context - Context Management for the Verdure Ecosystem
//!
//! This crate provides application context management as a core part of the Verdure ecosystem
//! framework. It serves as the central hub for application-wide state, configuration,
//! and environment management that integrates with all other Verdure modules.
//!
//! This module provides the foundation
//! for configuration-driven development and environment-aware component behavior
//! across the entire Verdure ecosystem.
//!
//! # Core Features
//!
//! * **Application Context**: Centralized application state management
//! * **Configuration Management**: Hierarchical configuration system with multiple sources
//! * **Event Broadcasting**: Application-wide event system for decoupled communication
//! * **IoC Integration**: Seamless integration with the Verdure IoC container
//! * **Type-Safe Configuration**: Strongly-typed configuration value access
//!
//! # Quick Start
//!
//! ## Basic Usage
//!
//! ```rust
//! use verdure_context::{ApplicationContext, ConfigSource};
//! use std::collections::HashMap;
//!
//! // Create and configure application context
//! let context = ApplicationContext::builder()
//! .with_property("app.name", "MyApp")
//! .with_property("app.port", "8080")
//! .build()
//! .unwrap();
//!
//! // Initialize the context
//! context.initialize().unwrap();
//!
//! // Access configuration
//! let app_name = context.get_config("app.name");
//! let port: i64 = context.get_config_as("app.port").unwrap();
//!
//! println!("Starting {} on port {}", app_name, port);
//! ```
//!
//! ## Configuration from Files
//!
//! Verdure Context supports multiple configuration file formats:
//!
//! ### TOML Configuration
//!
//! ```rust,no_run
//! use verdure_context::ApplicationContext;
//!
//! let context = ApplicationContext::builder()
//! .with_toml_config_file("config/app.toml")
//! .build()
//! .unwrap();
//! ```
//!
//! ### YAML Configuration
//!
//! ```rust,no_run
//! use verdure_context::ApplicationContext;
//!
//! let context = ApplicationContext::builder()
//! .with_yaml_config_file("config/app.yaml")
//! .build()
//! .unwrap();
//! ```
//!
//! ### Properties Configuration
//!
//! ```rust,no_run
//! use verdure_context::ApplicationContext;
//!
//! let context = ApplicationContext::builder()
//! .with_properties_config_file("config/app.properties")
//! .build()
//! .unwrap();
//! ```
//!
//! ### Auto-Detection
//!
//! ```rust,no_run
//! use verdure_context::ApplicationContext;
//!
//! // Format is auto-detected based on file extension
//! let context = ApplicationContext::builder()
//! .with_config_file("config/app.yaml") // YAML
//! .with_config_file("config/db.properties") // Properties
//! .with_config_file("config/server.toml") // TOML
//! .build()
//! .unwrap();
//! ```
//!
//! ## Event System
//!
//! ```rust
//! use verdure_context::{ApplicationContext, Event, EventListener};
//! use std::any::Any;
//!
//! // Define an event
//! #[derive(Debug, Clone)]
//! struct UserRegisteredEvent {
//! pub user_id: u64,
//! pub email: String,
//! }
//!
//! impl Event for UserRegisteredEvent {
//! fn name(&self) -> &'static str {
//! "UserRegistered"
//! }
//!
//! fn as_any(&self) -> &dyn Any {
//! self
//! }
//!
//! fn into_any(self: Box<Self>) -> Box<dyn Any> {
//! self
//! }
//! }
//!
//! // Create event listener
//! struct EmailNotificationListener;
//!
//! impl EventListener<UserRegisteredEvent> for EmailNotificationListener {
//! fn on_event(&self, event: &UserRegisteredEvent) {
//! println!("Sending welcome email to user {} ({})",
//! event.user_id, event.email);
//! }
//! }
//!
//! // Set up context with event handling
//! let mut context = ApplicationContext::new();
//! context.subscribe_to_events(EmailNotificationListener);
//!
//! // Publish events
//! let event = UserRegisteredEvent {
//! user_id: 123,
//! email: "user@example.com".to_string(),
//! };
//! context.publish_event(&event);
//! ```
//!
//! ## IoC Container Integration
//!
//! ```rust
//! use verdure_context::ApplicationContext;
//! use std::sync::Arc;
//!
//! #[derive(Debug)]
//! struct DatabaseService {
//! connection_url: String,
//! }
//!
//! let context = ApplicationContext::builder()
//! .with_property("database.url", "postgres://localhost/myapp")
//! .build()
//! .unwrap();
//!
//! // Register components with the container
//! let db_service = Arc::new(DatabaseService {
//! connection_url: context.get_config("database.url"),
//! });
//! context.container().register_component(db_service);
//!
//! // Retrieve components
//! let retrieved: Option<Arc<DatabaseService>> = context.get_component();
//! assert!(retrieved.is_some());
//! ```
//!
//! # Advanced Features
//!
//! ## Configuration Sources Priority
//!
//! Configuration sources are resolved in the following order (highest to lowest precedence):
//!
//! 1. **Runtime Properties**: Values set via `set_config()`
//! 2. **Configuration Sources**: Sources added via `add_config_source()` (last added wins)
//! 3. **Environment Variables**: System environment variables
//! 4. **Configuration Files**: Files loaded via various methods (last added wins)
//! - TOML files (`.toml`)
//! - YAML files (`.yaml`, `.yml`)
//! - Properties files (`.properties`)
//!
//! ## Supported Configuration Formats
//!
//! ### TOML Format Example
//!
//! ```toml
//! # app.toml
//! [app]
//! name = "MyApplication"
//! port = 8080
//! debug = true
//!
//! [database]
//! host = "localhost"
//! port = 5432
//! name = "myapp"
//! ```
//!
//! ### YAML Format Example
//!
//! ```yaml
//! # app.yaml
//! app:
//! name: MyApplication
//! port: 8080
//! debug: true
//! features:
//! - auth
//! - logging
//!
//! database:
//! host: localhost
//! port: 5432
//! name: myapp
//! ```
//!
//! ### Properties Format Example
//!
//! ```properties
//! # app.properties
//! app.name=MyApplication
//! app.port=8080
//! app.debug=true
//!
//! database.host=localhost
//! database.port=5432
//! database.name=myapp
//! ```
//!
//! All formats are converted to a flat key-value structure using dot notation
//! (e.g., `app.name`, `database.host`) for consistent access patterns.
//!
//! # Ecosystem Context Events
//!
//! The context system publishes several built-in events that applications can listen to.
//! There are two ways to listen to events:
//!
//! 1. **Regular Event Listeners**: Receive only the event data
//! 2. **Context-Aware Event Listeners**: Receive both the event and ApplicationContext reference
//!
//! ## Built-in Lifecycle Events
//!
//! ### ContextInitializingEvent
//!
//! **When**: Fired at the very beginning of context initialization, before any actual work begins.
//! **Purpose**: Allows listeners to prepare for context startup or log initialization start.
//! **Data**: Configuration sources count, active profiles count, and timestamp.
//!
//! ### ContextInitializedEvent
//!
//! **When**: Fired after the context is fully initialized, including all configuration sources, profiles, and IoC container.
//! **Purpose**: Ideal for application startup tasks that require a fully configured context.
//! **Data**: Final configuration sources count, active profiles count, and timestamp.
//!
//! ### ProfileActivatedEvent
//!
//! **When**: Fired whenever a profile is activated during context building.
//! **Purpose**: Allows listeners to react to environment changes or profile-specific setup.
//! **Data**: Profile name, properties count in the profile, and timestamp.
//!
//! ### ConfigurationChangedEvent
//!
//! **When**: Fired when configuration values are updated at runtime after context initialization.
//! **Purpose**: Enables reactive configuration updates and change tracking.
//! **Data**: Configuration key, old value (if any), new value, and timestamp.
//!
//! ## Context-Aware Event Listeners (Recommended for Lifecycle Events)
//!
//! Context-aware listeners can access the ApplicationContext during event handling,
//! making them perfect for lifecycle events where you need to interact with the context:
//!
//! ```rust
//! use verdure_context::{ApplicationContext, ContextInitializedEvent, ContextAwareEventListener};
//!
//! struct StartupTasks;
//!
//! impl ContextAwareEventListener<ContextInitializedEvent> for StartupTasks {
//! fn on_context_event(&self, event: &ContextInitializedEvent, context: &ApplicationContext) {
//! println!("🚀 Context initialized with {} sources!", event.config_sources_count);
//!
//! // Access configuration
//! let app_name = context.get_config("app.name");
//! println!("📱 Starting application: {}", app_name);
//!
//! // Access IoC container for dependency injection setup
//! let container = context.container();
//! // Setup your components...
//!
//! // Check environment
//! let env = context.environment();
//! println!("🌍 Running in {} environment", env);
//! }
//! }
//!
//! let mut context = ApplicationContext::builder()
//! .with_property("app.name", "MyApp")
//! .build()
//! .unwrap();
//!
//! context.subscribe_to_context_events(StartupTasks);
//! context.initialize().unwrap(); // Triggers the context-aware listener
//! ```
//!
//! ## ContextInitializingEvent Usage
//!
//! Listen to preparation phases before initialization:
//!
//! ```rust
//! use verdure_context::{ApplicationContext, ContextInitializingEvent, ContextAwareEventListener};
//!
//! struct PreStartupListener;
//!
//! impl ContextAwareEventListener<ContextInitializingEvent> for PreStartupListener {
//! fn on_context_event(&self, event: &ContextInitializingEvent, context: &ApplicationContext) {
//! println!("🔧 Context initializing with {} sources...",
//! event.config_sources_count);
//!
//! // Pre-initialization tasks
//! let startup_time = event.timestamp;
//! println!("⏰ Startup began at: {:?}", startup_time);
//! }
//! }
//! ```
//!
//!
//! ## ConfigurationChangedEvent Usage
//!
//! Track runtime configuration changes:
//!
//! ```rust
//! use verdure_context::{ApplicationContext, ConfigurationChangedEvent, EventListener};
//!
//! struct ConfigListener;
//!
//! impl EventListener<ConfigurationChangedEvent> for ConfigListener {
//! fn on_event(&self, event: &ConfigurationChangedEvent) {
//! match &event.old_value {
//! Some(old) => println!("⚙️ Configuration '{}' changed from '{}' to '{}'",
//! event.key, old, event.new_value),
//! None => println!("➕ Configuration '{}' set to '{}'",
//! event.key, event.new_value),
//! }
//! }
//! }
//!
//! let mut context = ApplicationContext::new();
//! context.subscribe_to_events(ConfigListener);
//! context.set_config("app.mode", "production");
//! ```
//!
//! ## Event System Architecture
//!
//! The event system supports both regular and context-aware listeners simultaneously:
//!
//! - **Regular listeners** (`EventListener<T>`) receive only the event data
//! - **Context-aware listeners** (`ContextAwareEventListener<T>`) receive both event data and ApplicationContext reference
//! - Both types can be registered for the same event type
//! - Events are published to all registered listeners of the appropriate type
//! - Lifecycle events automatically provide context access for enhanced integration capabilities
// Re-export main types for convenience
pub use ;
pub use ;
pub use ;
pub use ;