tideway 0.7.17

A batteries-included Rust web framework built on Axum for building SaaS applications quickly
Documentation
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
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
use std::sync::Arc;

#[cfg(feature = "metrics")]
use crate::metrics::MetricsCollector;
#[cfg(feature = "cache")]
use crate::traits::cache::Cache;
#[cfg(feature = "database")]
use crate::traits::database::DatabasePool;
#[cfg(feature = "jobs")]
use crate::traits::job::JobQueue;
#[cfg(feature = "email")]
use crate::traits::mailer::Mailer;
#[cfg(feature = "sessions")]
use crate::traits::session::SessionStore;
#[cfg(feature = "websocket")]
use crate::websocket::ConnectionManager;

/// Application context for dependency injection and shared state
///
/// This struct holds references to application-wide dependencies like
/// database connections, cache, and session stores. All dependencies
/// are optional and can be accessed via trait objects.
#[derive(Clone)]
pub struct AppContext {
    #[cfg(feature = "database")]
    pub(crate) database: Option<Arc<dyn DatabasePool>>,

    #[cfg(feature = "cache")]
    pub(crate) cache: Option<Arc<dyn Cache>>,

    #[cfg(feature = "sessions")]
    pub(crate) sessions: Option<Arc<dyn SessionStore>>,

    #[cfg(feature = "jobs")]
    pub(crate) jobs: Option<Arc<dyn JobQueue>>,

    #[cfg(feature = "websocket")]
    pub(crate) websocket_manager: Option<Arc<ConnectionManager>>,

    #[cfg(feature = "metrics")]
    pub(crate) metrics: Option<Arc<MetricsCollector>>,

    #[cfg(feature = "email")]
    pub(crate) mailer: Option<Arc<dyn Mailer>>,

    /// Authentication provider (application-specific)
    ///
    /// Note: Stored as `Arc<dyn Any>` due to AuthProvider's associated types.
    /// Applications should downcast to their concrete auth provider type when needed.
    pub(crate) auth_provider: Option<Arc<dyn std::any::Any + Send + Sync>>,
}

/// Internal request-extension wrapper for typed auth-provider lookup.
#[cfg(feature = "auth")]
#[derive(Clone)]
pub(crate) struct AuthProviderExtension(pub Arc<dyn std::any::Any + Send + Sync>);

impl AppContext {
    pub fn new() -> Self {
        Self {
            #[cfg(feature = "database")]
            database: None,
            #[cfg(feature = "cache")]
            cache: None,
            #[cfg(feature = "sessions")]
            sessions: None,
            #[cfg(feature = "jobs")]
            jobs: None,
            #[cfg(feature = "websocket")]
            websocket_manager: None,
            #[cfg(feature = "metrics")]
            metrics: None,
            #[cfg(feature = "email")]
            mailer: None,
            auth_provider: None,
        }
    }

    /// Builder pattern for constructing AppContext
    pub fn builder() -> AppContextBuilder {
        AppContextBuilder::new()
    }

    /// Create a builder pre-populated with the current context values.
    pub fn to_builder(&self) -> AppContextBuilder {
        AppContextBuilder {
            #[cfg(feature = "database")]
            database: self.database.clone(),
            #[cfg(feature = "cache")]
            cache: self.cache.clone(),
            #[cfg(feature = "sessions")]
            sessions: self.sessions.clone(),
            #[cfg(feature = "jobs")]
            jobs: self.jobs.clone(),
            #[cfg(feature = "websocket")]
            websocket_manager: self.websocket_manager.clone(),
            #[cfg(feature = "metrics")]
            metrics: self.metrics.clone(),
            #[cfg(feature = "email")]
            mailer: self.mailer.clone(),
            auth_provider: self.auth_provider.clone(),
        }
    }

    /// Get the database pool, returning an error if not configured
    #[cfg(feature = "database")]
    pub fn database(&self) -> crate::error::Result<&Arc<dyn DatabasePool>> {
        self.database
            .as_ref()
            .ok_or_else(|| crate::error::TidewayError::internal("Database pool not configured"))
    }

    /// Get the database pool as an Option
    #[cfg(feature = "database")]
    pub fn database_opt(&self) -> Option<&Arc<dyn DatabasePool>> {
        self.database.as_ref()
    }

    /// Get the cache, returning an error if not configured
    #[cfg(feature = "cache")]
    pub fn cache(&self) -> crate::error::Result<&Arc<dyn Cache>> {
        self.cache
            .as_ref()
            .ok_or_else(|| crate::error::TidewayError::internal("Cache not configured"))
    }

    /// Get the cache as an Option
    #[cfg(feature = "cache")]
    pub fn cache_opt(&self) -> Option<&Arc<dyn Cache>> {
        self.cache.as_ref()
    }

    /// Get the session store, returning an error if not configured
    #[cfg(feature = "sessions")]
    pub fn sessions(&self) -> crate::error::Result<&Arc<dyn SessionStore>> {
        self.sessions
            .as_ref()
            .ok_or_else(|| crate::error::TidewayError::internal("Session store not configured"))
    }

    /// Get the session store as an Option
    #[cfg(feature = "sessions")]
    pub fn sessions_opt(&self) -> Option<&Arc<dyn SessionStore>> {
        self.sessions.as_ref()
    }

    /// Get the job queue, returning an error if not configured
    #[cfg(feature = "jobs")]
    pub fn jobs(&self) -> crate::error::Result<&Arc<dyn JobQueue>> {
        self.jobs
            .as_ref()
            .ok_or_else(|| crate::error::TidewayError::internal("Job queue not configured"))
    }

    /// Get the job queue as an Option
    #[cfg(feature = "jobs")]
    pub fn jobs_opt(&self) -> Option<&Arc<dyn JobQueue>> {
        self.jobs.as_ref()
    }

    /// Get the WebSocket manager, returning an error if not configured
    #[cfg(feature = "websocket")]
    pub fn websocket_manager(&self) -> crate::error::Result<Arc<ConnectionManager>> {
        self.websocket_manager
            .clone()
            .ok_or_else(|| crate::error::TidewayError::internal("WebSocket manager not configured"))
    }

    /// Get the WebSocket manager as an Option
    #[cfg(feature = "websocket")]
    pub fn websocket_manager_opt(&self) -> Option<Arc<ConnectionManager>> {
        self.websocket_manager.clone()
    }

    /// Get the metrics collector, returning an error if not configured
    #[cfg(feature = "metrics")]
    pub fn metrics(&self) -> crate::error::Result<&Arc<MetricsCollector>> {
        self.metrics
            .as_ref()
            .ok_or_else(|| crate::error::TidewayError::internal("Metrics collector not configured"))
    }

    /// Get the metrics collector as an Option
    #[cfg(feature = "metrics")]
    pub fn metrics_opt(&self) -> Option<&Arc<MetricsCollector>> {
        self.metrics.as_ref()
    }

    /// Get the mailer, returning an error if not configured
    #[cfg(feature = "email")]
    pub fn mailer(&self) -> crate::error::Result<&Arc<dyn Mailer>> {
        self.mailer
            .as_ref()
            .ok_or_else(|| crate::error::TidewayError::internal("Mailer not configured"))
    }

    /// Get the mailer as an Option
    #[cfg(feature = "email")]
    pub fn mailer_opt(&self) -> Option<&Arc<dyn Mailer>> {
        self.mailer.as_ref()
    }

    /// Get the auth provider, downcast to the concrete type
    ///
    /// # Example
    /// ```ignore
    /// if let Some(provider) = ctx.auth_provider_opt::<OutsetaAuthProvider>() {
    ///     // Use provider
    /// }
    /// ```
    pub fn auth_provider_opt<T: 'static>(&self) -> Option<&T> {
        self.auth_provider
            .as_ref()
            .and_then(|p| p.downcast_ref::<T>())
    }

    /// Get the auth provider, returning an error if not configured or wrong type
    pub fn auth_provider<T: 'static>(&self) -> crate::error::Result<&T> {
        self.auth_provider_opt::<T>().ok_or_else(|| {
            crate::error::TidewayError::internal("Auth provider not configured or wrong type")
        })
    }

    /// Internal helper to expose the configured auth provider for middleware injection.
    #[cfg(feature = "auth")]
    pub(crate) fn auth_provider_extension(&self) -> Option<AuthProviderExtension> {
        self.auth_provider
            .as_ref()
            .map(Arc::clone)
            .map(AuthProviderExtension)
    }

    /// Get SeaORM connection from the database pool
    ///
    /// This is a convenience method for applications using SeaORM.
    /// Returns an error if the database pool is not SeaOrmPool.
    #[cfg(feature = "database")]
    pub fn sea_orm_connection(&self) -> crate::error::Result<sea_orm::DatabaseConnection> {
        use crate::database::SeaOrmPool;
        let pool = self.database()?;
        // Downcast to SeaOrmPool
        let sea_orm_pool = pool.as_any().downcast_ref::<SeaOrmPool>().ok_or_else(|| {
            crate::error::TidewayError::internal("Database pool is not SeaOrmPool")
        })?;
        Ok(sea_orm_pool.inner().clone())
    }
}

impl Default for AppContext {
    fn default() -> Self {
        Self::new()
    }
}

/// Builder for AppContext with fluent API
#[must_use = "builder does nothing until you call build()"]
pub struct AppContextBuilder {
    #[cfg(feature = "database")]
    database: Option<Arc<dyn DatabasePool>>,
    #[cfg(feature = "cache")]
    cache: Option<Arc<dyn Cache>>,
    #[cfg(feature = "sessions")]
    sessions: Option<Arc<dyn SessionStore>>,

    #[cfg(feature = "jobs")]
    jobs: Option<Arc<dyn JobQueue>>,

    #[cfg(feature = "websocket")]
    websocket_manager: Option<Arc<ConnectionManager>>,

    #[cfg(feature = "metrics")]
    metrics: Option<Arc<MetricsCollector>>,

    #[cfg(feature = "email")]
    mailer: Option<Arc<dyn Mailer>>,

    auth_provider: Option<Arc<dyn std::any::Any + Send + Sync>>,
}

impl AppContextBuilder {
    pub fn new() -> Self {
        Self {
            #[cfg(feature = "database")]
            database: None,
            #[cfg(feature = "cache")]
            cache: None,
            #[cfg(feature = "sessions")]
            sessions: None,
            #[cfg(feature = "jobs")]
            jobs: None,
            #[cfg(feature = "websocket")]
            websocket_manager: None,
            #[cfg(feature = "metrics")]
            metrics: None,
            #[cfg(feature = "email")]
            mailer: None,
            auth_provider: None,
        }
    }

    /// Set the database pool
    #[cfg(feature = "database")]
    pub fn with_database(mut self, pool: Arc<dyn DatabasePool>) -> Self {
        self.database = Some(pool);
        self
    }

    /// Set the database pool if provided.
    #[cfg(feature = "database")]
    pub fn with_optional_database(self, pool: Option<Arc<dyn DatabasePool>>) -> Self {
        if let Some(pool) = pool {
            self.with_database(pool)
        } else {
            self
        }
    }

    /// Set the cache
    #[cfg(feature = "cache")]
    pub fn with_cache(mut self, cache: Arc<dyn Cache>) -> Self {
        self.cache = Some(cache);
        self
    }

    /// Set the session store
    #[cfg(feature = "sessions")]
    pub fn with_sessions(mut self, sessions: Arc<dyn SessionStore>) -> Self {
        self.sessions = Some(sessions);
        self
    }

    /// Set the job queue
    #[cfg(feature = "jobs")]
    pub fn with_job_queue(mut self, queue: Arc<dyn JobQueue>) -> Self {
        self.jobs = Some(queue);
        self
    }

    /// Set the job queue if provided.
    #[cfg(feature = "jobs")]
    pub fn with_optional_job_queue(self, queue: Option<Arc<dyn JobQueue>>) -> Self {
        if let Some(queue) = queue {
            self.with_job_queue(queue)
        } else {
            self
        }
    }

    /// Set the WebSocket manager
    #[cfg(feature = "websocket")]
    pub fn with_websocket_manager(mut self, manager: Arc<ConnectionManager>) -> Self {
        self.websocket_manager = Some(manager);
        self
    }

    /// Set the metrics collector
    #[cfg(feature = "metrics")]
    pub fn with_metrics(mut self, collector: Arc<MetricsCollector>) -> Self {
        self.metrics = Some(collector);
        self
    }

    /// Set the mailer
    ///
    /// # Example
    /// ```ignore
    /// use tideway::{ConsoleMailer, SmtpMailer, SmtpConfig};
    ///
    /// // For development
    /// let mailer = Arc::new(ConsoleMailer::new());
    ///
    /// // For production
    /// let mailer = Arc::new(SmtpMailer::new(SmtpConfig::from_env()?)?);
    ///
    /// let context = AppContext::builder()
    ///     .with_mailer(mailer)
    ///     .build();
    /// ```
    #[cfg(feature = "email")]
    pub fn with_mailer(mut self, mailer: Arc<dyn Mailer>) -> Self {
        self.mailer = Some(mailer);
        self
    }

    /// Set the auth provider
    ///
    /// # Example
    /// ```ignore
    /// let auth_provider = Arc::new(OutsetaAuthProvider::new(config).await?);
    /// let context = AppContext::builder()
    ///     .with_auth_provider(auth_provider)
    ///     .build();
    /// ```
    pub fn with_auth_provider<T: Send + Sync + 'static>(mut self, provider: Arc<T>) -> Self {
        self.auth_provider = Some(provider as Arc<dyn std::any::Any + Send + Sync>);
        self
    }

    /// Set the auth provider if provided.
    pub fn with_optional_auth_provider<T: Send + Sync + 'static>(
        self,
        provider: Option<Arc<T>>,
    ) -> Self {
        if let Some(provider) = provider {
            self.with_auth_provider(provider)
        } else {
            self
        }
    }

    pub fn build(self) -> AppContext {
        AppContext {
            #[cfg(feature = "database")]
            database: self.database,
            #[cfg(feature = "cache")]
            cache: self.cache,
            #[cfg(feature = "sessions")]
            sessions: self.sessions,
            #[cfg(feature = "jobs")]
            jobs: self.jobs,
            #[cfg(feature = "websocket")]
            websocket_manager: self.websocket_manager,
            #[cfg(feature = "metrics")]
            metrics: self.metrics,
            #[cfg(feature = "email")]
            mailer: self.mailer,
            auth_provider: self.auth_provider,
        }
    }
}

impl Default for AppContextBuilder {
    fn default() -> Self {
        Self::new()
    }
}