Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cache g #183

Merged
merged 6 commits into from
Jul 14, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
[![Docs](https://docs.rs/casbin/badge.svg)](https://docs.rs/casbin)
[![CI](https://github.com/casbin/casbin-rs/workflows/CI/badge.svg)](https://github.com/casbin/casbin-rs/actions)
[![Codecov](https://codecov.io/gh/casbin/casbin-rs/branch/master/graph/badge.svg)](https://codecov.io/gh/casbin/casbin-rs)
[![Gitter](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/casbin/lobby)
[![forum](https://img.shields.io/badge/forum-join-%23cde201)](https://forum.casbin.org/)

**Casbin-RS** is a powerful and efficient open-source access control library for Rust projects. It provides support for enforcing authorization based on various [access control models](https://en.wikipedia.org/wiki/Computer_security_model).

Expand All @@ -27,7 +29,7 @@ Add this package to `Cargo.toml` of your project. (Check https://crates.io/crate

```toml
[dependencies]
casbin = { version = "1.0.0", default-features = false, features = ["runtime-async-std", "logging"] }
casbin = { version = "1.1.0", default-features = false, features = ["runtime-async-std", "logging"] }
async-std = { version = "1.5.0", features = ["attributes"] }
env_logger = "0.7.1"
```
Expand Down
24 changes: 12 additions & 12 deletions src/enforcer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,16 @@ impl Enforcer {
}
}))
}

pub(crate) fn register_g_functions(&mut self) -> Result<()> {
if let Some(ast_map) = self.model.get_model().get("g") {
for (fname, ast) in ast_map {
register_g_function!(self, fname, ast);
}
}

Ok(())
}
}

#[async_trait]
Expand Down Expand Up @@ -238,11 +248,7 @@ impl CoreApi for Enforcer {
#[cfg(any(feature = "logging", feature = "watcher"))]
e.on(Event::PolicyChange, notify_logger_and_watcher);

if let Some(ast_map) = e.model.get_model().get("g") {
for fname in ast_map.keys() {
register_g_function!(e, fname);
}
}
e.register_g_functions()?;

e.load_policy().await?;

Expand Down Expand Up @@ -325,13 +331,7 @@ impl CoreApi for Enforcer {
self.build_role_links()?;
}

if let Some(ast_map) = self.model.get_model().get("g") {
for fname in ast_map.keys() {
register_g_function!(self, fname);
}
}

Ok(())
self.register_g_functions()
}

async fn set_model<M: TryIntoModel>(&mut self, m: M) -> Result<()> {
Expand Down
36 changes: 22 additions & 14 deletions src/macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,22 +20,30 @@ macro_rules! get_or_err {

#[macro_export]
macro_rules! register_g_function {
($enforcer:ident, $fname:expr) => {{
($enforcer:ident, $fname:ident, $ast:ident) => {{
let rm = Arc::clone(&$enforcer.rm);
$enforcer.engine.register_fn(
$fname,
move |arg1: ImmutableString, arg2: ImmutableString| {
rm.write().unwrap().has_link(&arg1, &arg2, None)
},
);
let count = $ast.value.chars().filter(|&x| x == '_').count();

let rm = Arc::clone(&$enforcer.rm);
$enforcer.engine.register_fn(
$fname,
move |arg1: ImmutableString, arg2: ImmutableString, arg3: ImmutableString| {
rm.write().unwrap().has_link(&arg1, &arg2, Some(&arg3))
},
);
if count == 2 {
$enforcer.engine.register_fn(
$fname,
move |arg1: ImmutableString, arg2: ImmutableString| {
rm.write().unwrap().has_link(&arg1, &arg2, None)
},
);
} else if count == 3 {
$enforcer.engine.register_fn(
$fname,
move |arg1: ImmutableString, arg2: ImmutableString, arg3: ImmutableString| {
rm.write().unwrap().has_link(&arg1, &arg2, Some(&arg3))
},
);
} else {
return Err(ModelError::P(
r#"the number of "_" in role definition should be at least 2"#.to_owned(),
)
.into());
}
}};
}

Expand Down
43 changes: 36 additions & 7 deletions src/rbac/default_role_manager.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,19 @@
use crate::{error::RbacError, rbac::RoleManager, Result};

#[cfg(feature = "cached")]
use crate::cache::{Cache, DefaultCache};

use std::{
collections::HashMap,
sync::{Arc, RwLock},
};

const DEFAULT_DOMAIN: &str = "DEFAULT";

#[derive(Clone)]
pub struct DefaultRoleManager {
all_roles: HashMap<String, HashMap<String, Arc<RwLock<Role>>>>,
#[cfg(feature = "cached")]
cache: Box<dyn Cache<(String, String, Option<String>), bool>>,
max_hierarchy_level: usize,
}

Expand All @@ -18,6 +22,8 @@ impl DefaultRoleManager {
DefaultRoleManager {
all_roles: HashMap::new(),
max_hierarchy_level,
#[cfg(feature = "cached")]
cache: Box::new(DefaultCache::new(50)),
}
}

Expand Down Expand Up @@ -46,6 +52,8 @@ impl RoleManager for DefaultRoleManager {
let role2 = self.create_role(name2, domain);

role1.write().unwrap().add_role(Arc::clone(&role2));
#[cfg(feature = "cached")]
self.cache.clear();
}

fn delete_link(&mut self, name1: &str, name2: &str, domain: Option<&str>) -> Result<()> {
Expand All @@ -57,6 +65,8 @@ impl RoleManager for DefaultRoleManager {
let role2 = self.create_role(name2, domain);

role1.write().unwrap().delete_role(role2);
#[cfg(feature = "cached")]
self.cache.clear();

Ok(())
}
Expand All @@ -66,14 +76,31 @@ impl RoleManager for DefaultRoleManager {
return true;
}

if !self.has_role(name1, domain) || !self.has_role(name2, domain) {
return false;
#[cfg(feature = "cached")]
let cache_key = (
name1.to_owned(),
name2.to_owned(),
domain.map(|x| x.to_owned()),
);

#[cfg(feature = "cached")]
if let Some(res) = self.cache.get(&cache_key) {
return *res;
}

self.create_role(name1, domain)
.write()
.unwrap()
.has_role(name2, self.max_hierarchy_level)
#[allow(clippy::let_and_return)]
let res = self.has_role(name1, domain)
&& self.has_role(name2, domain)
&& self
.create_role(name1, domain)
.write()
.unwrap()
.has_role(name2, self.max_hierarchy_level);

#[cfg(feature = "cached")]
self.cache.set(cache_key, res);

res
}

fn get_roles(&mut self, name: &str, domain: Option<&str>) -> Vec<String> {
Expand Down Expand Up @@ -104,6 +131,8 @@ impl RoleManager for DefaultRoleManager {

fn clear(&mut self) {
self.all_roles.clear();
#[cfg(feature = "cached")]
self.cache.clear();
}
}

Expand Down