feat: added new packages

This commit is contained in:
Andrew Rioux
2025-02-01 15:59:56 -05:00
parent f5afd60086
commit b416f35b63
28 changed files with 425 additions and 358 deletions

View File

@@ -1,99 +0,0 @@
use std::{
collections::HashMap,
sync::{Arc, RwLock},
};
use axum::routing::{get, post, Router};
use axum_server::{service::MakeService, tls_rustls::RustlsConfig};
use sqlx::SqlitePool;
use tokio::task::JoinHandle;
pub struct BeaconListenerHandle {
join_handle: JoinHandle<()>
}
impl BeaconListenerHandle {
pub fn is_finished(&self) -> bool {
self.join_handle.is_finished()
}
pub fn abort(&self) {
self.join_handle.abort()
}
}
pub type BeaconListenerMap = Arc<RwLock<HashMap<i64, BeaconListenerHandle>>>;
pub async fn start_all_listeners(beacon_listener_map: BeaconListenerMap, db: SqlitePool) -> Result<(), crate::error::Error> {
let listener_ids = sqlx::query!("SELECT listener_id FROM beacon_listener")
.fetch_all(&db)
.await?;
tracing::info!("Starting {} listener(s)...", listener_ids.len());
for listener in listener_ids {
start_listener(Arc::clone(&beacon_listener_map), listener.listener_id, db.clone()).await?;
}
Ok(())
}
#[derive(Clone)]
struct ListenerState {
db: SqlitePool
}
pub async fn start_listener(beacon_listener_map: BeaconListenerMap, listener_id: i64, db: SqlitePool) -> Result<(), crate::error::Error> {
{
let Ok(blm_handle) = beacon_listener_map.read() else {
return Err(crate::error::Error::Generic("Could not acquire write lock on beacon listener map".to_string()));
};
if blm_handle.get(&listener_id).is_some() {
return Err(crate::error::Error::Generic("Beacon listener already started".to_string()));
}
}
let listener = sqlx::query!("SELECT * FROM beacon_listener WHERE listener_id = ?", listener_id)
.fetch_one(&db)
.await?;
let app: Router<()> = Router::new()
.route("/register_beacon", post(|| async {}))
.route("/test", get(|| async {
"hi there"
}))
.with_state(ListenerState {
db
});
let hidden_app = Router::new().nest("/hidden_sparse", app);
let tls_config = RustlsConfig::from_pem(
listener.certificate.as_bytes().to_vec(),
listener.privkey.as_bytes().to_vec()
).await?;
let addr = std::net::SocketAddr::from(([0, 0, 0, 0], listener.port as u16));
tracing::debug!("Starting listener {}, {}, on port {}", listener_id, listener.domain_name, listener.port);
let join_handle = tokio::task::spawn(async move {
let res = axum_server::tls_rustls::bind_rustls(addr, tls_config)
.serve(hidden_app.into_make_service())
.await;
if let Err(e) = res {
tracing::error!("error running sparse listener: {e:?}");
}
});
let Ok(mut blm_handle) = beacon_listener_map.write() else {
return Err(crate::error::Error::Generic("Could not acquire write lock on beacon listener map".to_string()));
};
blm_handle.insert(listener_id, BeaconListenerHandle {
join_handle
});
Ok(())
}

View File

@@ -6,9 +6,13 @@ use serde::{Serialize, Deserialize};
#[cfg(feature = "ssr")]
use {
sqlx::SqlitePool,
leptos::server_fn::error::NoCustomError,
rcgen::{generate_simple_self_signed, CertifiedKey},
crate::{db::user, beacon_handler::BeaconListenerMap},
sparse_handler::BeaconListenerMap,
crate::db::user,
};
use super::BeaconResources;
@@ -106,6 +110,28 @@ pub async fn add_listener(public_ip: String, port: i16, domain_name: String) ->
#[server]
pub async fn remove_listener(listener_id: i64) -> Result<(), ServerFnError> {
let user = user::get_auth_session().await?;
if user.is_none() {
return Err(ServerFnError::<NoCustomError>::ServerError("You are not signed in!".to_owned()));
}
let pool = expect_context::<SqlitePool>();
let blm = expect_context::<BeaconListenerMap>();
let Ok(mut blm_handle) = blm.write() else {
return Err(ServerFnError::<NoCustomError>::ServerError("Failed to get write handle for beacon listener map".to_owned()));
};
if let Some(mut bl) = blm_handle.get_mut(&listener_id) {
bl.abort();
} else {
return Err(ServerFnError::<NoCustomError>::ServerError("Failed to get write handle for beacon listener map".to_owned()));
}
blm_handle.remove(&listener_id);
drop(blm_handle);
unimplemented!()
}
@@ -117,7 +143,7 @@ pub async fn start_listener(listener_id: i64) -> Result<(), ServerFnError> {
return Err(ServerFnError::<NoCustomError>::ServerError("You are not signed in!".to_owned()));
}
crate::beacon_handler::start_listener(
sparse_handler::start_listener(
expect_context(),
listener_id,
expect_context()

View File

@@ -1,6 +1,4 @@
pub mod app;
#[cfg(feature = "ssr")]
pub mod beacon_handler;
pub mod beacons;
pub mod db;
pub mod error;

View File

@@ -1,4 +1,4 @@
#[cfg(feature = "ssr")]
#[cfg(feature = "hydrate")]
pub(crate) mod beacon_binaries {
#[allow(dead_code)]
pub const LINUX_BEACON: &'static [u8] = include_bytes!(std::env!("SPARSE_BEACON_LINUX"));
@@ -11,6 +11,8 @@ pub(crate) mod beacon_binaries {
pub const LINUX_INSTALLER: &'static [u8] = include_bytes!(std::env!("SPARSE_INSTALLER_LINUX"));
#[allow(dead_code)]
pub const FREEBSD_INSTALLER: &'static [u8] = include_bytes!(std::env!("SPARSE_INSTALLER_FREEBSD"));
#[allow(dead_code)]
pub const WINDOWS_INSTALLER: &'static [u8] = include_bytes!(std::env!("SPARSE_INSTALLER_WINDOWS"));
}
#[cfg(feature = "ssr")]
@@ -23,7 +25,6 @@ mod beacons;
pub mod users;
pub mod error;
pub mod db;
pub mod beacon_handler;
#[cfg(feature = "ssr")]
#[tokio::main]
@@ -37,7 +38,7 @@ async fn main() -> anyhow::Result<std::process::ExitCode> {
tracing_subscriber::registry()
.with(
tracing_subscriber::EnvFilter::try_from_default_env()
.unwrap_or_else(|_| format!("{}=debug,tower_http=trace", env!("CARGO_CRATE_NAME")).into()),
.unwrap_or_else(|_| format!("{}=debug,sparse_handler=debug,tower_http=trace", env!("CARGO_CRATE_NAME")).into()),
)
.with(tracing_subscriber::fmt::layer())
.init();

View File

@@ -12,7 +12,7 @@ pub async fn serve_web(management_address: SocketAddrV4, db: SqlitePool) -> anyh
let conf = get_configuration(None).unwrap();
let leptos_options = conf.leptos_options;
let routes = generate_route_list(App);
let beacon_listeners = crate::beacon_handler::BeaconListenerMap::default();
let beacon_listeners = sparse_handler::BeaconListenerMap::default();
let compression_layer = tower_http::compression::CompressionLayer::new()
.gzip(true)
@@ -20,15 +20,15 @@ pub async fn serve_web(management_address: SocketAddrV4, db: SqlitePool) -> anyh
.br(true)
.zstd(true);
crate::beacon_handler::start_all_listeners(std::sync::Arc::clone(&beacon_listeners), db.clone()).await?;
sparse_handler::start_all_listeners(beacon_listeners.clone(), db.clone()).await?;
let app = Router::new()
.leptos_routes_with_context(
&leptos_options,
routes,
move || {
provide_context(std::sync::Arc::clone(&beacon_listeners));
provide_context(db.clone())
provide_context(beacon_listeners.clone());
provide_context::<SqlitePool>(db.clone());
},
{
let leptos_options = leptos_options.clone();