use std::sync::Arc;
use std::time::Duration;
use sqlx::PgPool;
use sqlx::postgres::PgPoolOptions;
use codoseo_core::crawl::AddressPolicy;
use codoseo_notify::{ChannelKey, GuardedHttp};
use crate::auth::mailer::Mailer;
use crate::config::{Config, Mode};
#[derive(Clone)]
pub struct AppState {
pub pool: PgPool,
pub config: Arc<Config>,
pub mailer: Mailer,
pub http: reqwest::Client,
pub channel_key: ChannelKey,
pub notify_http: GuardedHttp,
pub shutdown: tokio_util::sync::CancellationToken,
pub anon_calls: Arc<crate::agent::limiter::CallLimiter>,
}
impl AppState {
pub fn new(pool: PgPool, config: Config, mailer: Mailer) -> AppState {
let policy = match config.mode {
Mode::Cloud => AddressPolicy::Public,
Mode::SelfHost => AddressPolicy::AllowPrivate,
};
AppState {
pool,
channel_key: ChannelKey::derive(&config.secret_key),
notify_http: GuardedHttp::new(policy).expect("http client builds"),
config: Arc::new(config),
mailer,
shutdown: tokio_util::sync::CancellationToken::new(),
anon_calls: Arc::new(crate::agent::limiter::CallLimiter::for_anon_tools()),
http: reqwest::Client::builder()
.timeout(Duration::from_secs(10))
.user_agent(concat!("CodoSEO/", env!("CARGO_PKG_VERSION")))
.build()
.expect("http client builds"),
}
}
}
pub fn lazy_pool(database_url: &str) -> Result<PgPool, sqlx::Error> {
PgPoolOptions::new()
.max_connections(5)
.acquire_timeout(Duration::from_secs(3))
.connect_lazy(database_url)
}