Skip to content

Commit

Permalink
reduce redis connection lifetime to avoid holding it for too long
Browse files Browse the repository at this point in the history
  • Loading branch information
tonyke-bot committed Jan 19, 2024
1 parent cf8d11a commit 72d550a
Showing 1 changed file with 21 additions and 13 deletions.
34 changes: 21 additions & 13 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -102,11 +102,11 @@ fn read_cache(

#[actix_web::post("/{chain}")]
async fn rpc_call(
path: web::Path<(String,)>,
path: web::Path<(String, )>,
data: web::Data<AppState>,
body: web::Json<Value>,
) -> Result<HttpResponse, Error> {
let (chain,) = path.into_inner();
let (chain, ) = path.into_inner();
let chain_state = data
.chains
.get(&chain.to_uppercase())
Expand All @@ -122,10 +122,7 @@ async fn rpc_call(
let mut uncached_requests = HashMap::new();
let mut ids_in_original_order = vec![];

let mut redis_con = data.redis.get().map_err(|err| {
tracing::error!("fail to get redis connection because: {}", err);
error::ErrorInternalServerError("fail to get redis connection")
})?;


for mut request in requests {
let id = match request["id"].take() {
Expand All @@ -150,6 +147,11 @@ async fn rpc_call(
}
};

let mut redis_con = data.redis.get().map_err(|err| {
tracing::error!("fail to get redis connection because: {}", err);
error::ErrorInternalServerError("fail to get redis connection")
})?;

let result = read_cache(
&mut redis_con,
cache_entry.handler.as_ref(),
Expand Down Expand Up @@ -197,11 +199,11 @@ async fn rpc_call(
chain_state.rpc_url.clone(),
&request_body,
)
.await
.map_err(|err| {
tracing::error!("fail to make rpc request because: {}", err);
error::ErrorInternalServerError(format!("fail to make rpc request because: {}", err))
})?;
.await
.map_err(|err| {
tracing::error!("fail to make rpc request because: {}", err);
error::ErrorInternalServerError(format!("fail to make rpc request because: {}", err))
})?;

let result_values = match rpc_result {
Value::Array(v) => v,
Expand All @@ -214,6 +216,11 @@ async fn rpc_call(
}
};

let mut redis_con = data.redis.get().map_err(|err| {
tracing::error!("fail to get redis connection because: {}", err);
error::ErrorInternalServerError("fail to get redis connection")
})?;

for mut response in result_values {
let id = response["id"]
.as_u64()
Expand Down Expand Up @@ -281,8 +288,9 @@ async fn main() -> std::io::Result<()> {
env_logger::init_from_env(Env::default().default_filter_or("info"));

let redis_client = redis::Client::open(arg.redis_url).expect("Failed to create Redis client");
let redis_con_pool =
r2d2::Pool::new(redis_client).expect("Failed to create Redis connection pool");
let redis_con_pool = r2d2::Pool::builder()
.max_size(10)
.build(redis_client).expect("Failed to create Redis connection pool");

let mut app_state = AppState {
chains: Default::default(),
Expand Down

0 comments on commit 72d550a

Please sign in to comment.