use std::fmt;
use std::sync::Arc;
use navree_kernel::{AppContext, BoxError, BoxFuture, ModuleId};
use crate::mount::collect_mounts;
use crate::router::routes_under;
use crate::{AccessSpec, HttpServer};
#[derive(Clone, Debug)]
pub struct DeclaredAccess {
pub what: String,
pub module: Option<ModuleId>,
pub module_name: &'static str,
pub access: AccessSpec,
}
type ReadDeclared = Arc<
dyn Fn(AppContext) -> BoxFuture<'static, Result<Vec<DeclaredAccess>, BoxError>> + Send + Sync,
>;
#[derive(Clone)]
pub struct AccessDeclarations(ReadDeclared);
impl AccessDeclarations {
pub fn new<F, Fut>(read: F) -> Self
where
F: Fn(AppContext) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<Vec<DeclaredAccess>, BoxError>> + Send + 'static,
{
Self(Arc::new(move |ctx| Box::pin(read(ctx))))
}
}
impl fmt::Debug for AccessDeclarations {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("AccessDeclarations").finish_non_exhaustive()
}
}
pub async fn declared_access(ctx: &AppContext) -> Result<Vec<DeclaredAccess>, BoxError> {
let mut declared = Vec::new();
for source in ctx.contributions::<AccessDeclarations>() {
declared.extend((source.value.0)(ctx.clone()).await?);
}
Ok(declared)
}
pub(crate) async fn routes_and_mounts(ctx: AppContext) -> Result<Vec<DeclaredAccess>, BoxError> {
let server = ctx
.get::<HttpServer>()
.await
.map_err(|error| format!("the app's routes cannot be read without HttpServer: {error}"))?;
let mut declared = Vec::new();
for route in routes_under(&ctx, server.options()).await? {
declared.push(DeclaredAccess {
what: format!("the route `{} {}`", route.method, route.full_path),
module: route.module_id,
module_name: route.module.unwrap_or("?"),
access: route.access,
});
}
for mount in collect_mounts(&ctx) {
declared.push(DeclaredAccess {
what: format!("the mount `{}`", mount.prefix),
module: mount.meta.module_id,
module_name: mount.module,
access: mount.meta.access,
});
}
Ok(declared)
}