Skip to content

Commit 29d8c19

Browse files
committed
Use tokio::sync::Mutex instead of std::sync::Mutex, and make optimization
Signed-off-by: xizheyin <[email protected]>
1 parent c04fc4d commit 29d8c19

File tree

1 file changed

+16
-5
lines changed

1 file changed

+16
-5
lines changed

src/db.rs

+16-5
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,9 @@ use anyhow::Context as _;
33
use chrono::Utc;
44
use native_tls::{Certificate, TlsConnector};
55
use postgres_native_tls::MakeTlsConnector;
6-
use std::sync::{Arc, LazyLock, Mutex};
7-
use tokio::sync::{OwnedSemaphorePermit, Semaphore};
6+
use serde_json;
7+
use std::sync::{Arc, LazyLock};
8+
use tokio::sync::{Mutex, OwnedSemaphorePermit, Semaphore};
89
use tokio_postgres::Client as DbClient;
910

1011
pub mod issue_data;
@@ -37,8 +38,14 @@ pub struct PooledClient {
3738

3839
impl Drop for PooledClient {
3940
fn drop(&mut self) {
40-
let mut clients = self.pool.lock().unwrap_or_else(|e| e.into_inner());
41-
clients.push(self.client.take().unwrap());
41+
// We can't await in drop, so we need to spawn a task to handle async lock
42+
if let Some(client) = self.client.take() {
43+
let pool = self.pool.clone();
44+
tokio::spawn(async move {
45+
let mut clients = pool.lock().await;
46+
clients.push(client);
47+
});
48+
}
4249
}
4350
}
4451

@@ -68,17 +75,21 @@ impl ClientPool {
6875
pub async fn get(&self) -> PooledClient {
6976
let permit = self.permits.clone().acquire_owned().await.unwrap();
7077
{
71-
let mut slots = self.connections.lock().unwrap_or_else(|e| e.into_inner());
78+
let mut slots = self.connections.lock().await;
7279
// Pop connections until we hit a non-closed connection (or there are no
7380
// "possibly open" connections left).
7481
while let Some(c) = slots.pop() {
82+
// drop the lock
83+
drop(slots);
7584
if !c.is_closed() && validate_connection(&c).await {
7685
return PooledClient {
7786
client: Some(c),
7887
permit,
7988
pool: self.connections.clone(),
8089
};
8190
}
91+
// re-lock
92+
slots = self.connections.lock().await;
8293
}
8394
}
8495

0 commit comments

Comments
 (0)