Skip to content

Commit

Permalink
perf: use rayon and fastrand to imporve exectute speed
Browse files Browse the repository at this point in the history
  • Loading branch information
fu050409 committed Apr 28, 2024
1 parent caadb10 commit 56348fe
Show file tree
Hide file tree
Showing 7 changed files with 71 additions and 15 deletions.
26 changes: 26 additions & 0 deletions .github/workflows/benchmark.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
name: Benchmark

on:
push:
branches: ["main"]
pull_request:
branches: ["main"]

env:
CARGO_TERM_COLOR: always

jobs:
build:
runs-on: ubuntu-latest

steps:
- uses: actions/checkout@v4
- name: Build
run: cargo build --verbose
- name: Run benchmarks
run: cargo bench --verbose
- name: Upload benchmark results
uses: actions/upload-artifact@v2
with:
path: target/criterion/report/
name: benchmark-results
8 changes: 8 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ ring = "0.17"
sha2 = "0.10"
scrypt = "0.11"
hkdf = "0.12.4"
fastrand = "2.1.0"

# Utils
oblivion-codegen = { path = "oblivion-codegen" }
Expand All @@ -27,6 +28,7 @@ thiserror = "1"
anyhow = "1.0"
colored = "2.1"
chrono = "0.4"
rayon = "1.10.0"

# Optional
pyo3 = { version = "0.20", optional = true }
Expand Down Expand Up @@ -62,3 +64,7 @@ harness = false
[[bench]]
name = "socket"
harness = false

[[bench]]
name = "rand"
harness = false
9 changes: 9 additions & 0 deletions benches/rand.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
use criterion::{criterion_group, criterion_main, Criterion};
use oblivion::utils::generator::generate_random_salt;

fn criterion_benchmark_salt(c: &mut Criterion) {
c.bench_function("salt", |b| b.iter(|| generate_random_salt()));
}

criterion_group!(benches, criterion_benchmark_salt);
criterion_main!(benches);
28 changes: 18 additions & 10 deletions src/models/router.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use super::handler::not_found;
use super::session::Session;
use crate::types::server;
use anyhow::Result;
use rayon::iter::{IntoParallelRefIterator, ParallelIterator};
use regex::Regex;
use std::collections::HashMap;

Expand All @@ -18,7 +19,7 @@ impl Route {
Self { handler }
}

pub fn get_handler(&mut self) -> Handler {
pub fn get_handler(&self) -> Handler {
self.handler.clone()
}
}
Expand All @@ -44,7 +45,7 @@ impl RoutePath {
}
}

pub fn check(&mut self, olps: &str) -> Result<bool> {
pub fn check(&self, olps: &str) -> Result<bool> {
if self.route_type == RouteType::RegexPath {
let regex = Regex::new(&self.route)?;
Ok(regex.is_match(olps))
Expand All @@ -69,7 +70,7 @@ impl Router {
}

pub fn route(&mut self, path: RoutePath, handler: Handler) -> &mut Self {
self.routes.insert(path.clone(), Route { handler: handler });
self.routes.insert(path.clone(), Route { handler });
self
}

Expand All @@ -78,13 +79,20 @@ impl Router {
self.routes.insert(path.clone(), route);
}

pub fn get_handler(&self, path: &str) -> Result<Route> {
for (route_path, route) in &self.routes {
let mut route_path = route_path.clone();
if route_path.check(path)? {
return Ok(route.clone());
};
pub fn get_handler(&self, path: &str) -> Result<Handler> {
let handler = self
.routes
.par_iter()
.find_any(|values| {
let (route_path, _) = values;
route_path.check(path).unwrap_or(false)
})
.map(|route| route.1.get_handler());

if let Some(route) = handler {
Ok(route)
} else {
Ok(not_found)
}
Ok(Route::new(not_found))
}
}
3 changes: 1 addition & 2 deletions src/models/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,8 +69,7 @@ async fn _handle(router: &Router, stream: TcpStream, peer: SocketAddr) -> Result

let socket = Arc::clone(&session.socket);

let mut route = router.get_handler(&session.request.as_ref().unwrap().olps)?;
let callback = route.get_handler()(session).await?;
let callback = router.get_handler(&session.request.as_ref().unwrap().olps)?(session).await?;

#[cfg(not(any(feature = "perf", feature = "bench")))]
let status_code = callback.get_status_code()?;
Expand Down
6 changes: 3 additions & 3 deletions src/utils/generator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ use p256::{ecdh::EphemeralSecret, PublicKey};
use ring::agreement::{agree_ephemeral, EphemeralPrivateKey, PublicKey, UnparsedPublicKey, X25519};

use ring::aead::AES_128_GCM;
use ring::rand::{SecureRandom, SystemRandom};
use ring::rand::SystemRandom;
use scrypt::{scrypt, Params};
use sha2::Sha256;

Expand Down Expand Up @@ -113,8 +113,8 @@ impl SharedKey {
/// let salt = generate_random_salt();
/// ```
pub fn generate_random_salt() -> Vec<u8> {
let rand = SystemRandom::new();
let mut rng = fastrand::Rng::new();
let mut key_bytes = vec![0; AES_128_GCM.key_len()];
rand.fill(&mut key_bytes).unwrap();
rng.fill(&mut key_bytes);
key_bytes
}

0 comments on commit 56348fe

Please sign in to comment.