use std::collections::BTreeMap;
use std::fmt;
use std::sync::Arc;
use std::time::Duration;
use http::Method;
use navree_kernel::ModuleId;
use crate::Guard;
use crate::error_pages::RouteKind;
use crate::handler::{Endpoint, Handler};
#[derive(Clone)]
pub struct RouteDef {
pub method: Method,
pub path: String,
pub handler: Endpoint,
pub meta: RouteMeta,
}
impl RouteDef {
pub fn on<H, T>(method: Method, path: impl Into<String>, handler: H) -> Self
where
H: Handler<T>,
T: 'static,
{
Self::with_endpoint(method, path, Endpoint::new(handler))
}
pub fn with_endpoint(method: Method, path: impl Into<String>, endpoint: Endpoint) -> Self {
Self {
meta: RouteMeta {
method: method.to_string(),
..RouteMeta::default()
},
method,
path: path.into(),
handler: endpoint,
}
}
pub fn public(mut self) -> Self {
self.meta.access.public = true;
self
}
pub fn authenticated(mut self) -> Self {
self.meta.access.authenticated = true;
self
}
pub fn roles(mut self, roles: &[&str]) -> Self {
self.meta
.access
.roles
.extend(roles.iter().map(|r| (*r).to_owned()));
self
}
pub fn permissions(mut self, permissions: &[&str]) -> Self {
self.meta
.access
.permissions
.extend(permissions.iter().map(|p| (*p).to_owned()));
self
}
pub fn can(mut self, action: &str, subject: &str, from: Option<&str>) -> Self {
self.meta.access.can = Some(CanSpec {
action: action.to_owned(),
subject: subject.to_owned(),
from: from.map(str::to_owned),
});
self
}
pub fn name(mut self, name: &str) -> Self {
self.meta.name = Some(name.to_owned());
self
}
pub fn handler_name(mut self, handler: &str) -> Self {
self.meta.handler = Some(handler.to_owned());
self
}
pub fn throttle(mut self, limit: u32, per: Duration) -> Self {
self.meta.throttle = Some(Throttle { limit, per });
self
}
pub fn timeout(mut self, d: Duration) -> Self {
self.meta.timeout = Some(d);
self
}
pub fn transactional(mut self) -> Self {
self.meta.transactional = true;
self
}
pub fn guard(mut self, guard: Arc<dyn Guard>) -> Self {
self.meta.guards.push(guard);
self
}
pub fn api(mut self, meta: ApiMeta) -> Self {
self.meta.api = Some(meta);
self
}
pub fn audit(mut self, action: &str) -> Self {
self.meta.audit_action = Some(action.to_owned());
self
}
pub fn body_limit(mut self, bytes: usize) -> Self {
self.meta.body_limit = Some(bytes);
self
}
pub fn no_compression(mut self) -> Self {
self.meta.no_compression = true;
self
}
pub fn page(mut self) -> Self {
self.meta.kind = RouteKind::Page;
self
}
pub fn json_only(mut self) -> Self {
self.meta.kind = RouteKind::Json;
self
}
pub fn extension(
mut self,
name: impl Into<String>,
value: impl Into<serde_json::Value>,
) -> Self {
self.meta.extensions.insert(name.into(), value.into());
self
}
}
impl fmt::Debug for RouteDef {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("RouteDef")
.field("method", &self.method)
.field("path", &self.path)
.field("meta", &self.meta)
.finish_non_exhaustive()
}
}
#[derive(Clone, Debug, Default)]
pub struct RouteMeta {
pub name: Option<String>,
pub handler: Option<String>,
pub access: AccessSpec,
pub guards: Vec<Arc<dyn Guard>>,
pub throttle: Option<Throttle>,
pub timeout: Option<Duration>,
pub transactional: bool,
pub api: Option<ApiMeta>,
pub audit_action: Option<String>,
pub body_limit: Option<usize>,
pub no_compression: bool,
pub kind: RouteKind,
pub module: Option<&'static str>,
pub module_id: Option<ModuleId>,
pub full_path: String,
pub method: String,
pub extensions: BTreeMap<String, serde_json::Value>,
}
#[derive(Clone, Debug, Default)]
pub struct AccessSpec {
pub public: bool,
pub authenticated: bool,
pub roles: Vec<String>,
pub permissions: Vec<String>,
pub can: Option<CanSpec>,
}
impl AccessSpec {
pub fn is_declared(&self) -> bool {
self.public || self.authenticated || self.needs_authorizer()
}
pub fn needs_authorizer(&self) -> bool {
!self.roles.is_empty() || !self.permissions.is_empty() || self.can.is_some()
}
pub fn describe(&self) -> String {
let mut parts = Vec::new();
if self.public {
parts.push("public".to_owned());
}
if self.authenticated {
parts.push("auth".to_owned());
}
if !self.roles.is_empty() {
parts.push(format!("roles:{}", self.roles.join("|")));
}
if !self.permissions.is_empty() {
parts.push(format!("permissions:{}", self.permissions.join(",")));
}
if let Some(can) = &self.can {
let mut s = format!("can:{} {}", can.action, can.subject);
if let Some(from) = &can.from {
s.push_str(" from ");
s.push_str(from);
}
parts.push(s);
}
if parts.is_empty() {
"none".to_owned()
} else {
parts.join(" ")
}
}
}
#[derive(Clone, Debug)]
pub struct CanSpec {
pub action: String,
pub subject: String,
pub from: Option<String>,
}
#[derive(Clone, Copy, Debug)]
pub struct Throttle {
pub limit: u32,
pub per: Duration,
}
#[derive(Clone, Debug, Default)]
pub struct ApiMeta {
pub summary: Option<String>,
pub description: Option<String>,
pub tags: Vec<String>,
pub responses: Vec<u16>,
pub success_status: u16,
pub request: Option<SchemaFn>,
pub response: Option<SchemaFn>,
pub query: Option<ListSpecFn>,
}
pub type SchemaFn = fn() -> (String, serde_json::Value);
pub type ListSpecFn = fn() -> crate::list::ListSpec;
pub fn list_spec<R: crate::list::ListResource>() -> crate::list::ListSpec {
R::SPEC
}
pub fn schema_fn<T: navree_openapi::ToSchema>() -> (String, serde_json::Value) {
let mut schema = serde_json::to_value(T::schema()).unwrap_or_default();
let mut referenced = Vec::new();
T::schemas(&mut referenced);
navree_openapi::__private::attach_components(&mut schema, referenced);
if let Some(object) = schema.as_object_mut() {
object.insert(
"x-navree-type".to_owned(),
std::any::type_name::<T>().into(),
);
}
(T::name().into_owned(), schema)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn builders_fill_the_access_spec() {
let route = RouteDef::on(Method::POST, "/", || async {})
.roles(&["admin", "manager"])
.permissions(&["deals.manage"])
.can("update", "Deal", Some("id"));
assert_eq!(route.meta.method, "POST");
assert!(route.meta.access.is_declared());
assert!(route.meta.access.needs_authorizer());
assert_eq!(
route.meta.access.describe(),
"roles:admin|manager permissions:deals.manage can:update Deal from id"
);
}
#[tokio::test]
async fn on_routes_exactly_the_declared_method() {
use tower::ServiceExt;
let route = RouteDef::on(Method::PATCH, "/x", || async { "patched" }).public();
assert_eq!(route.method, Method::PATCH);
assert_eq!(route.meta.method, "PATCH");
let mut router = crate::routing::Router::new();
router
.try_route(route.method.clone(), "/x", route.handler.clone())
.unwrap();
let call = |method: Method| {
let router = router.clone();
async move {
let request = http::Request::builder()
.method(method)
.uri("/x")
.body(crate::body::Body::empty())
.unwrap();
router.oneshot(request).await.unwrap().status()
}
};
assert_eq!(call(Method::PATCH).await, http::StatusCode::OK);
assert_eq!(
call(Method::GET).await,
http::StatusCode::METHOD_NOT_ALLOWED
);
}
#[test]
fn extensions_are_collected_by_name() {
let route = RouteDef::on(Method::GET, "/", || async {})
.public()
.extension("x-navree-flag", "new-pipeline")
.extension("x-internal", serde_json::json!({"team": "deals"}))
.extension("x-navree-flag", "ai-summaries");
assert_eq!(route.meta.extensions.len(), 2);
assert_eq!(
route.meta.extensions["x-navree-flag"],
serde_json::json!("ai-summaries")
);
assert_eq!(
route.meta.extensions["x-internal"]["team"],
serde_json::json!("deals")
);
assert!(RouteMeta::default().extensions.is_empty());
}
#[test]
fn nothing_declared_is_not_declared() {
let route = RouteDef::on(Method::GET, "/", || async {}).name("x");
assert!(!route.meta.access.is_declared());
assert_eq!(route.meta.access.describe(), "none");
let route = route.authenticated();
assert!(route.meta.access.is_declared() && !route.meta.access.needs_authorizer());
}
#[derive(navree_openapi::ToSchema)]
#[allow(dead_code)]
struct Owner {
id: String,
}
#[derive(navree_openapi::ToSchema)]
#[allow(dead_code)]
struct Deal {
title: String,
owner: Owner,
}
#[test]
fn schema_fn_returns_name_schema_and_referenced_components() {
let f: SchemaFn = schema_fn::<Deal>;
let (name, schema) = f();
assert_eq!(name, "Deal");
assert_eq!(schema["type"], "object");
assert!(schema["properties"]["title"].is_object());
assert_eq!(
schema["properties"]["owner"]["$ref"],
"#/components/schemas/Owner"
);
assert_eq!(
schema["x-navree-components"]["Owner"]["properties"]["id"]["type"],
"string"
);
let (name, schema) = schema_fn::<Owner>();
assert_eq!(name, "Owner");
assert!(schema.get("x-navree-components").is_none());
}
}