documentation and remove redundant methods

This commit is contained in:
realaravinth 2021-08-31 19:40:32 +05:30
parent 66d02ec543
commit a1f9bcb247
No known key found for this signature in database
GPG key ID: AD9F0F08E855ED88
5 changed files with 47 additions and 42 deletions

6
Cargo.lock generated
View file

@ -330,7 +330,7 @@ dependencies = [
[[package]]
name = "libmcaptcha"
version = "0.1.4"
source = "git+https://github.com/mCaptcha/libmcaptcha?branch=master#b2684d93482cec8e40cd6ccbc2cee4be3b1eef25"
source = "git+https://github.com/mCaptcha/libmcaptcha?branch=master#48220d78e706745a5208850c832ee8ba7e704601"
dependencies = [
"derive_builder",
"derive_more",
@ -427,9 +427,9 @@ checksum = "ac74c624d6b2d21f425f752262f42188365d7b8ff1aff74c82e45136510a4857"
[[package]]
name = "proc-macro2"
version = "1.0.28"
version = "1.0.29"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5c7ed8b8c7b886ea3ed7dde405212185f423ab44682667c8c6dd14aa1d9f6612"
checksum = "b9f5105d4fdaab20335ca9565e106a5d9b82b6219b5ba735731124ac6711d23d"
dependencies = [
"unicode-xid 0.2.2",
]

View file

@ -14,10 +14,11 @@
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
//! Leaky bucket algorithim is implemantation for mcatpcha using batch processing Everytime count
//! is increased for an mcaptcha object, a decrement job is added to a batch that is scheduled to
//! be executed at that mcaptcha object's expiry rate(MCaptcha.get_duration())
use std::collections::HashMap;
use std::time::Duration;
//use std::time::{SystemTime, UNIX_EPOCH};
use redis_module::key::RedisKeyWritable;
use redis_module::native_types::RedisType;
@ -66,7 +67,12 @@ pub struct Bucket {
}
impl Bucket {
/// run when bucket is deleted from expiration
pub fn on_delete(ctx: &Context, _event_type: NotifyEvent, _event: &str, key_name: &str) {
// TODO: this callback is executed after the bucket is deleted. So all jobs scheduled within
// the bucket are lost. This means, we could end up with stagnent increments in mcaptcha objects
// Rather than setting a timer, use a safety, upon who's expiry, the bucket's callback(job
// runner) will be executed
if !is_bucket_timer(key_name) {
return;
}

View file

@ -50,9 +50,8 @@ impl MCaptcha {
#[inline]
fn new(mut m: CreateMCaptcha) -> CacheResult<Self> {
let mut defense_builder = DefenseBuilder::default();
let mut defense_builder = &mut defense_builder;
for l in m.levels.drain(0..) {
defense_builder = defense_builder.add_level(l)?;
defense_builder.add_level(l)?;
}
let defense = defense_builder.build()?;
@ -70,13 +69,6 @@ impl MCaptcha {
self.m.add_visitor()
}
/// decrements the visitor count by one
#[inline]
#[allow(dead_code)]
pub fn decrement_visitor(&mut self) {
self.m.decrement_visitor()
}
/// get current difficulty factor
#[inline]
#[allow(dead_code)]
@ -86,14 +78,12 @@ impl MCaptcha {
/// get [MCaptcha]'s lifetime
#[inline]
#[allow(dead_code)]
pub fn get_duration(&self) -> u64 {
self.m.get_duration()
}
/// get [MCaptcha]'s current visitor_threshold
#[inline]
#[allow(dead_code)]
pub fn get_visitors(&self) -> u32 {
self.m.get_visitors()
}
@ -127,7 +117,7 @@ impl MCaptcha {
return CacheError::new(format!("key {} not found", key_name)).into();
}
match stored_captcha.get_value::<Self>(&MCAPTCHA_MCAPTCHA_TYPE)? {
match Self::get_mcaptcha(&stored_captcha)? {
Some(val) => Ok(RedisValue::Integer(val.get_visitors().into())),
None => Err(CacheError::CaptchaNotFound.into()),
}

View file

@ -14,6 +14,8 @@
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
//! Custom datastructure that controls mCaptcha lifetime through it's expiration event handler
//! and callbacks
use std::time::Duration;
use redis_module::key::RedisKeyWritable;
@ -34,6 +36,8 @@ const MCAPTCHA_SAFETY_VERSION: i32 = 0;
pub struct MCaptchaSafety;
impl MCaptchaSafety {
/// When safety is deleted due to expiration, if mcaptcha exists in cache a new safety should
/// be created.
pub fn on_delete(ctx: &Context, _event_type: NotifyEvent, _event: &str, key_name: &str) {
if !is_mcaptcha_safety(key_name) {
return;
@ -128,31 +132,36 @@ impl MCaptchaSafety {
fn boost(ctx: &Context, (safety_name, duration): (String, u64)) {
let safety = ctx.open_key_writable(&RedisString::create(ctx.ctx, &safety_name));
match safety.get_value::<Self>(&MCAPTCHA_SAFETY_TYPE) {
Ok(Some(_safety_val)) => match Self::set_timer(ctx, &safety, (safety_name, duration)) {
Ok(_) => (),
Err(e) => ctx.log_warning(&format!("{}", e)),
},
_ => {
let mcaptcha_name = get_mcaptcha_from_safety(&safety_name);
if mcaptcha_name.is_none() {
return;
}
let mcaptcha_name = mcaptcha_name.unwrap();
let mcaptcha = ctx.open_key(&RedisString::create(ctx.ctx, mcaptcha_name));
if mcaptcha.key_type() == KeyType::Empty {
return;
}
// if safety is available in cache then refresh timer
if let Ok(Some(_safety_val)) = safety.get_value::<Self>(&MCAPTCHA_SAFETY_TYPE) {
if let Err(e) = Self::set_timer(ctx, &safety, (safety_name, duration)) {
// if unable to create timer, then safety will expire and mcaptcha will be deleted
// as well. So when user requests pow config, there will be a cache miss, then
// config will be loaded from db. This is fine.
ctx.log_warning(&format!("{}", e))
}
// else create new safety
} else {
// see if mcaptcha exists before creating a safety for it.
// Cases where mcaptcha doesn't exist or key is empty are ignored
let mcaptcha_name = get_mcaptcha_from_safety(&safety_name);
if mcaptcha_name.is_none() {
return;
}
let mcaptcha_name = mcaptcha_name.unwrap();
let mcaptcha = ctx.open_key(&RedisString::create(ctx.ctx, mcaptcha_name));
if mcaptcha.key_type() == KeyType::Empty {
return;
}
if let Ok(Some(_)) = MCaptcha::get_mcaptcha(&mcaptcha) {
let res = Self::new(ctx, duration, mcaptcha_name);
if res.is_err() {
ctx.log_warning(&format!(
"Error when creating safety timer for mcaptcha key: {}. Error: {}",
mcaptcha_name,
res.err().unwrap()
));
}
if let Ok(Some(_)) = MCaptcha::get_mcaptcha(&mcaptcha) {
let res = Self::new(ctx, duration, mcaptcha_name);
if res.is_err() {
ctx.log_warning(&format!(
"Error when creating safety timer for mcaptcha key: {}. Error: {}",
mcaptcha_name,
res.err().unwrap()
));
}
}
}