-
Notifications
You must be signed in to change notification settings - Fork 640
/
Copy pathapp.rs
244 lines (203 loc) · 8.38 KB
/
app.rs
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
//! Application-wide components in a struct accessible from each request
use crate::config;
use crate::db::{ConnectionConfig, connection_url, make_manager_config};
use std::collections::HashMap;
use std::sync::Arc;
use crate::email::Emails;
use crate::metrics::{InstanceMetrics, ServiceMetrics};
use crate::rate_limiter::{LimitedAction, RateLimiter, RateLimiterConfig};
use crate::storage::{Storage, StorageConfig};
use axum::extract::{FromRef, FromRequestParts, State};
use bon::Builder;
use crates_io_github::GitHubClient;
use deadpool_diesel::Runtime;
use derive_more::Deref;
use diesel_async::AsyncPgConnection;
use diesel_async::pooled_connection::AsyncDieselConnectionManager;
use diesel_async::pooled_connection::deadpool::Pool as DeadpoolPool;
use oauth2::basic::BasicClient;
use oauth2::{EndpointNotSet, EndpointSet};
type DeadpoolResult = Result<
diesel_async::pooled_connection::deadpool::Object<AsyncPgConnection>,
diesel_async::pooled_connection::deadpool::PoolError,
>;
/// The `App` struct holds the main components of the application like
/// the database connection pool and configurations
#[derive(Builder)]
pub struct App {
/// Database connection pool connected to the primary database
pub primary_database: DeadpoolPool<AsyncPgConnection>,
/// Database connection pool connected to the read-only replica database
pub replica_database: Option<DeadpoolPool<AsyncPgConnection>>,
/// GitHub API client
pub github: Box<dyn GitHubClient>,
/// The GitHub OAuth2 configuration
pub github_oauth:
BasicClient<EndpointSet, EndpointNotSet, EndpointNotSet, EndpointNotSet, EndpointSet>,
/// The server configuration
pub config: Arc<config::Server>,
/// Backend used to send emails
pub emails: Emails,
/// Storage backend for crate files and other large objects.
pub storage: Arc<Storage>,
/// Metrics related to the service as a whole
#[builder(default = ServiceMetrics::new().expect("could not initialize service metrics"))]
pub service_metrics: ServiceMetrics,
/// Metrics related to this specific instance of the service
#[builder(default = InstanceMetrics::new().expect("could not initialize instance metrics"))]
pub instance_metrics: InstanceMetrics,
/// Rate limit select actions.
pub rate_limiter: RateLimiter,
}
impl<S: app_builder::State> AppBuilder<S> {
pub fn github_oauth_from_config(
self,
config: &config::Server,
) -> AppBuilder<app_builder::SetGithubOauth<S>>
where
S::GithubOauth: app_builder::IsUnset,
{
use oauth2::{AuthUrl, TokenUrl};
let auth_url = "https://github.com/login/oauth/authorize";
let auth_url = AuthUrl::new(auth_url.into()).unwrap();
let token_url = "https://github.com/login/oauth/access_token";
let token_url = TokenUrl::new(token_url.into()).unwrap();
let github_oauth = BasicClient::new(config.gh_client_id.clone())
.set_client_secret(config.gh_client_secret.clone())
.set_auth_uri(auth_url)
.set_token_uri(token_url);
self.github_oauth(github_oauth)
}
pub fn databases_from_config(
self,
config: &config::DatabasePools,
) -> AppBuilder<app_builder::SetReplicaDatabase<app_builder::SetPrimaryDatabase<S>>>
where
S::PrimaryDatabase: app_builder::IsUnset,
S::ReplicaDatabase: app_builder::IsUnset,
{
let primary_database = {
use secrecy::ExposeSecret;
let primary_db_connection_config = ConnectionConfig {
statement_timeout: config.statement_timeout,
read_only: config.primary.read_only_mode,
};
let url = connection_url(config, config.primary.url.expose_secret());
let manager_config = make_manager_config(config.enforce_tls);
let manager = AsyncDieselConnectionManager::new_with_config(url, manager_config);
DeadpoolPool::builder(manager)
.runtime(Runtime::Tokio1)
.max_size(config.primary.pool_size)
.wait_timeout(Some(config.connection_timeout))
.post_create(primary_db_connection_config)
.build()
.unwrap()
};
let replica_database = if let Some(pool_config) = config.replica.as_ref() {
use secrecy::ExposeSecret;
let replica_db_connection_config = ConnectionConfig {
statement_timeout: config.statement_timeout,
read_only: pool_config.read_only_mode,
};
let url = connection_url(config, pool_config.url.expose_secret());
let manager_config = make_manager_config(config.enforce_tls);
let manager = AsyncDieselConnectionManager::new_with_config(url, manager_config);
let pool = DeadpoolPool::builder(manager)
.runtime(Runtime::Tokio1)
.max_size(pool_config.pool_size)
.wait_timeout(Some(config.connection_timeout))
.post_create(replica_db_connection_config)
.build()
.unwrap();
Some(pool)
} else {
None
};
self.primary_database(primary_database)
.maybe_replica_database(replica_database)
}
pub fn storage_from_config(
self,
config: &StorageConfig,
) -> AppBuilder<app_builder::SetStorage<S>>
where
S::Storage: app_builder::IsUnset,
{
self.storage(Arc::new(Storage::from_config(config)))
}
pub fn rate_limiter_from_config(
self,
config: HashMap<LimitedAction, RateLimiterConfig>,
) -> AppBuilder<app_builder::SetRateLimiter<S>>
where
S::RateLimiter: app_builder::IsUnset,
{
self.rate_limiter(RateLimiter::new(config))
}
}
impl App {
/// A unique key to generate signed cookies
pub fn session_key(&self) -> &cookie::Key {
&self.config.session_key
}
/// Obtain a read/write database connection from the async primary pool
#[instrument(skip_all)]
pub async fn db_write(&self) -> DeadpoolResult {
self.primary_database.get().await
}
/// Obtain a readonly database connection from the replica pool
///
/// If the replica pool is disabled or unavailable, the primary pool is used instead.
#[instrument(skip_all)]
pub async fn db_read(&self) -> DeadpoolResult {
let Some(read_only_pool) = self.replica_database.as_ref() else {
// Replica is disabled, but primary might be available
return self.primary_database.get().await;
};
match read_only_pool.get().await {
// Replica is available
Ok(connection) => Ok(connection),
// Replica is not available, but primary might be available
Err(error) => {
let _ = self
.instance_metrics
.database_fallback_used
.get_metric_with_label_values(&["follower"])
.map(|metric| metric.inc());
warn!("Replica is unavailable, falling back to primary ({error})");
self.primary_database.get().await
}
}
}
/// Obtain a readonly database connection from the primary pool
///
/// If the primary pool is unavailable, the replica pool is used instead, if not disabled.
#[instrument(skip_all)]
pub async fn db_read_prefer_primary(&self) -> DeadpoolResult {
let Some(read_only_pool) = self.replica_database.as_ref() else {
return self.primary_database.get().await;
};
match self.primary_database.get().await {
// Primary is available
Ok(connection) => Ok(connection),
// Primary is not available, but replica might be available
Err(error) => {
let _ = self
.instance_metrics
.database_fallback_used
.get_metric_with_label_values(&["primary"])
.map(|metric| metric.inc());
warn!("Primary is unavailable, falling back to replica ({error})");
read_only_pool.get().await
}
}
}
}
#[derive(Clone, FromRequestParts, Deref)]
#[from_request(via(State))]
pub struct AppState(pub Arc<App>);
impl FromRef<AppState> for cookie::Key {
fn from_ref(app: &AppState) -> Self {
app.session_key().clone()
}
}