Skip to content

Commit

Permalink
Merge pull request #192 from neon-mmd/optimize-and-make-code-idiomatic
Browse files Browse the repository at this point in the history
⚙️ Optimize and make code more idiomatic (part - III)
  • Loading branch information
alamin655 authored Sep 10, 2023
2 parents b3b914d + 82a78e3 commit e581de3
Show file tree
Hide file tree
Showing 6 changed files with 60 additions and 7 deletions.
27 changes: 27 additions & 0 deletions Cargo.lock

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

8 changes: 5 additions & 3 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,11 @@ once_cell = {version="1.18.0"}
error-stack = {version="0.4.0"}
async-trait = {version="0.1.73"}
regex = {version="1.9.4", features=["perf"]}
smallvec = {version="1.11.0", features=["union", "serde"]}
futures = {version="0.3.28"}
dhat = {version="0.3.2", optional = true}
smallvec = {version="1.11.0", features=["union", "serde"]}
mimalloc = { version = "0.1.38", default-features = false }
async-once-cell = {version="0.5.3"}

[dev-dependencies]
rusty-hook = "^0.11.2"
Expand All @@ -55,10 +57,10 @@ debug = false # This should only be commented when testing with dhat profiler
split-debuginfo = '...'
debug-assertions = false
overflow-checks = false
lto = 'thin'
lto = true
panic = 'abort'
incremental = false
codegen-units = 16
codegen-units = 1
rpath = false
strip = "debuginfo"

Expand Down
5 changes: 5 additions & 0 deletions src/bin/websurfx.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
//! This module contains the main function which handles the logging of the application to the
//! stdout and handles the command line arguments provided and launches the `websurfx` server.
use mimalloc::MiMalloc;
use std::net::TcpListener;
use websurfx::{config::parser::Config, run};

Expand All @@ -11,6 +12,10 @@ use websurfx::{config::parser::Config, run};
#[global_allocator]
static ALLOC: dhat::Alloc = dhat::Alloc;

#[cfg(not(feature = "dhat-heap"))]
#[global_allocator]
static GLOBAL: MiMalloc = MiMalloc;

/// The function that launches the main server and registers all the routes of the website.
///
/// # Error
Expand Down
1 change: 1 addition & 0 deletions src/cache/cacher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ use super::error::PoolError;
/// * `pool_size` - It stores the size of the connection pool (in other words the number of
/// connections that should be stored in the pool).
/// * `current_connection` - It stores the index of which connection is being used at the moment.
#[derive(Clone)]
pub struct RedisCache {
connection_pool: Vec<ConnectionManager>,
pool_size: u8,
Expand Down
8 changes: 7 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,12 @@ use crate::server::routes;

use actix_cors::Cors;
use actix_files as fs;
use actix_web::{dev::Server, http::header, middleware::Logger, web, App, HttpServer};
use actix_web::{
dev::Server,
http::header,
middleware::{Compress, Logger},
web, App, HttpServer,
};
use config::parser::Config;
use handlebars::Handlebars;
use handler::paths::{file_path, FileType};
Expand Down Expand Up @@ -68,6 +73,7 @@ pub fn run(listener: TcpListener, config: Config) -> std::io::Result<Server> {
.app_data(web::Data::new(config.clone()))
.wrap(cors)
.wrap(Logger::default()) // added logging middleware for logging.
.wrap(Compress::default()) // compress request headers to reduce memory usage.
// Serve images and static files (css and js files).
.service(
fs::Files::new("/static", format!("{}/static", public_folder_path))
Expand Down
18 changes: 15 additions & 3 deletions src/server/routes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,10 @@ use handlebars::Handlebars;
use serde::Deserialize;
use tokio::join;

// ---- Constants ----
/// Initialize redis cache connection once and store it on the heap.
const REDIS_CACHE: async_once_cell::OnceCell<RedisCache> = async_once_cell::OnceCell::new();

/// A named struct which deserializes all the user provided search parameters and stores them.
///
/// # Fields
Expand Down Expand Up @@ -158,10 +162,17 @@ async fn results(
page: u32,
req: &HttpRequest,
) -> Result<SearchResults, Box<dyn std::error::Error>> {
//Initialize redis cache connection struct
let mut redis_cache = RedisCache::new(&config.redis_url, 5).await?;
let redis_cache: RedisCache = REDIS_CACHE
.get_or_init(async {
// Initialize redis cache connection pool only one and store it in the heap.
RedisCache::new(&config.redis_url, 5).await.unwrap()
})
.await
.clone();

// fetch the cached results json.
let cached_results_json = redis_cache.cached_json(&url).await;
let cached_results_json: Result<String, error_stack::Report<crate::cache::error::PoolError>> =
redis_cache.clone().cached_json(&url).await;
// check if fetched cache results was indeed fetched or it was an error and if so
// handle the data accordingly.
match cached_results_json {
Expand Down Expand Up @@ -206,6 +217,7 @@ async fn results(

results.add_style(&config.style);
redis_cache
.clone()
.cache_results(&serde_json::to_string(&results)?, &url)
.await?;
Ok(results)
Expand Down

0 comments on commit e581de3

Please sign in to comment.