pub mod error;
pub mod handler;
pub mod middleware;
#[allow(clippy::needless_for_each)]
pub mod openapi;
pub mod router;
pub mod usage;
pub(crate) mod util;
pub use byokey_provider::VersionStore;
pub use error::ApiError;
pub use handler::amp::threads::AmpThreadIndex;
pub use openapi::ApiDoc;
pub use router::make_router;
pub use usage::{UsageRecorder, UsageStats};
use arc_swap::ArcSwap;
use byokey_auth::AuthManager;
use byokey_provider::DeviceProfileCache;
use byokey_types::{RateLimitStore, UsageStore};
use std::sync::Arc;
pub struct AppState {
pub config: Arc<ArcSwap<byokey_config::Config>>,
pub auth: Arc<AuthManager>,
pub http: rquest::Client,
pub usage: Arc<UsageRecorder>,
pub ratelimits: Arc<RateLimitStore>,
pub device_profiles: Arc<DeviceProfileCache>,
pub amp_threads: Arc<AmpThreadIndex>,
pub versions: VersionStore,
}
impl AppState {
pub fn new(
config: Arc<ArcSwap<byokey_config::Config>>,
auth: Arc<AuthManager>,
usage_store: Option<Arc<dyn UsageStore>>,
versions: VersionStore,
) -> Arc<Self> {
Self::with_thread_index(config, auth, usage_store, versions, {
let idx = Arc::new(AmpThreadIndex::build());
idx.watch();
idx
})
}
pub fn with_thread_index(
config: Arc<ArcSwap<byokey_config::Config>>,
auth: Arc<AuthManager>,
usage_store: Option<Arc<dyn UsageStore>>,
versions: VersionStore,
amp_threads: Arc<AmpThreadIndex>,
) -> Arc<Self> {
let snapshot = config.load();
let http = build_http_client(snapshot.proxy_url.as_deref());
Arc::new(Self {
config,
auth,
http,
usage: Arc::new(UsageRecorder::new(usage_store)),
ratelimits: Arc::new(RateLimitStore::new()),
device_profiles: Arc::new(DeviceProfileCache::new()),
amp_threads,
versions,
})
}
}
fn build_http_client(proxy_url: Option<&str>) -> rquest::Client {
if let Some(url) = proxy_url {
match rquest::Proxy::all(url) {
Ok(proxy) => {
return rquest::Client::builder()
.proxy(proxy)
.build()
.unwrap_or_else(|_| rquest::Client::new());
}
Err(e) => {
tracing::warn!(url = url, error = %e, "invalid proxy_url, using direct connection");
}
}
}
rquest::Client::new()
}