1use crate::{
4 OAuthClient,
5 domain::{models_requests::JwtKey, request_span_middleware::RequestSpan},
6};
7use actix_http::{StatusCode, body::MessageBody};
8use actix_web::{
9 HttpResponse,
10 error::InternalError,
11 web::{self, Data, PayloadConfig, ServiceConfig},
12};
13use anyhow::Context;
14use headless_lms_utils::{
15 ApplicationConfiguration, cache::Cache, file_store::FileStore, icu4x::Icu4xBlob,
16 ip_to_country::IpToCountryMapper, tmc::TmcClient,
17};
18use oauth2::{AuthUrl, ClientId, ClientSecret, TokenUrl, basic::BasicClient};
19use sqlx::{PgPool, postgres::PgPoolOptions};
20use std::{env, sync::Arc};
21use url::Url;
22
23pub struct ServerConfigBuilder {
24 pub database_url: String,
25 pub oauth_application_id: String,
26 pub oauth_secret: String,
27 pub auth_url: Url,
28 pub token_url: Url,
29 pub icu4x_postcard_path: String,
30 pub file_store: Arc<dyn FileStore + Send + Sync>,
31 pub app_conf: ApplicationConfiguration,
32 pub redis_url: String,
33 pub jwt_password: String,
34 pub tmc_client: TmcClient,
35}
36
37impl ServerConfigBuilder {
38 pub fn try_from_env() -> anyhow::Result<Self> {
39 Ok(Self {
40 database_url: env::var("DATABASE_URL").context("DATABASE_URL must be defined")?,
41 oauth_application_id: env::var("OAUTH_APPLICATION_ID")
42 .context("OAUTH_APPLICATION_ID must be defined")?,
43 oauth_secret: env::var("OAUTH_SECRET").context("OAUTH_SECRET must be defined")?,
44 auth_url: "https://tmc.mooc.fi/oauth/authorize"
45 .parse()
46 .context("Failed to parse auth_url")?,
47 token_url: "https://tmc.mooc.fi/oauth/token"
48 .parse()
49 .context("Failed to parse token url")?,
50 icu4x_postcard_path: env::var("ICU4X_POSTCARD_PATH")
51 .context("ICU4X_POSTCARD_PATH must be defined")?,
52 file_store: crate::setup_file_store(),
53 app_conf: ApplicationConfiguration::try_from_env()?,
54 redis_url: env::var("REDIS_URL").context("REDIS_URL must be defined")?,
55 jwt_password: env::var("JWT_PASSWORD").context("JWT_PASSWORD must be defined")?,
56 tmc_client: TmcClient::new_from_env()?,
57 })
58 }
59
60 pub async fn build(self) -> anyhow::Result<ServerConfig> {
61 let json_config = web::JsonConfig::default().limit(2_097_152).error_handler(
62 |err, _req| -> actix_web::Error {
63 info!("Bad request: {}", &err);
64 let body = format!("{{\"title\": \"Bad Request\", \"message\": \"{}\"}}", &err);
65 let response = HttpResponse::with_body(StatusCode::BAD_REQUEST, body.boxed());
67 InternalError::from_response(err, response).into()
68 },
69 );
70 let json_config = Data::new(json_config);
71
72 let payload_config = PayloadConfig::default().limit(2_097_152);
73 let payload_config = Data::new(payload_config);
74
75 let db_pool = PgPoolOptions::new()
76 .max_connections(15)
77 .min_connections(5)
78 .connect(&self.database_url)
79 .await?;
80 let db_pool = Data::new(db_pool);
81
82 let oauth_client: OAuthClient = BasicClient::new(ClientId::new(self.oauth_application_id))
83 .set_client_secret(ClientSecret::new(self.oauth_secret))
84 .set_auth_uri(AuthUrl::from_url(self.auth_url.clone()))
85 .set_token_uri(TokenUrl::from_url(self.token_url.clone()));
86 let oauth_client = Data::new(oauth_client);
87
88 let icu4x_blob = Icu4xBlob::new(&self.icu4x_postcard_path)?;
89 let icu4x_blob = Data::new(icu4x_blob);
90
91 let app_conf = Data::new(self.app_conf);
92
93 let ip_to_country_mapper = IpToCountryMapper::new(&app_conf)?;
94 let ip_to_country_mapper = Data::new(ip_to_country_mapper);
95
96 let cache = Cache::new(&self.redis_url)?;
97 let cache = Data::new(cache);
98
99 let jwt_key = JwtKey::new(&self.jwt_password)?;
100 let jwt_key = Data::new(jwt_key);
101
102 let tmc_client = Data::new(self.tmc_client);
103
104 let config = ServerConfig {
105 json_config,
106 db_pool,
107 oauth_client,
108 icu4x_blob,
109 ip_to_country_mapper,
110 file_store: self.file_store,
111 app_conf,
112 jwt_key,
113 cache,
114 payload_config,
115 tmc_client,
116 };
117 Ok(config)
118 }
119}
120
121#[derive(Clone)]
122pub struct ServerConfig {
123 pub payload_config: Data<PayloadConfig>,
124 pub json_config: Data<web::JsonConfig>,
125 pub db_pool: Data<PgPool>,
126 pub oauth_client: Data<OAuthClient>,
127 pub icu4x_blob: Data<Icu4xBlob>,
128 pub ip_to_country_mapper: Data<IpToCountryMapper>,
129 pub file_store: Arc<dyn FileStore + Send + Sync>,
130 pub app_conf: Data<ApplicationConfiguration>,
131 pub cache: Data<Cache>,
132 pub jwt_key: Data<JwtKey>,
133 pub tmc_client: Data<TmcClient>,
134}
135
136pub fn configure(config: &mut ServiceConfig, server_config: ServerConfig) {
138 let ServerConfig {
139 json_config,
140 db_pool,
141 oauth_client,
142 icu4x_blob,
143 ip_to_country_mapper,
144 file_store,
145 app_conf,
146 jwt_key,
147 cache,
148 payload_config,
149 tmc_client,
150 } = server_config;
151 let file_store = Data::from(file_store as Arc<dyn FileStore>);
154 config
155 .app_data(payload_config)
156 .app_data(json_config)
157 .app_data(db_pool)
158 .app_data(oauth_client)
159 .app_data(icu4x_blob)
160 .app_data(ip_to_country_mapper)
161 .app_data(file_store)
162 .app_data(app_conf.clone())
163 .app_data(jwt_key)
164 .app_data(cache)
165 .app_data(tmc_client)
166 .service(
167 web::scope("/api/v0")
168 .wrap(RequestSpan)
169 .configure(|c| crate::controllers::configure_controllers(c, app_conf)),
170 );
171}