Skip to content

Commit 9181e85

Browse files
authored
Use a single global timer wheel for query timeouts (#225)
Each connection previously constructed its own QueryTimeoutManager, and since pre.36 that manager spawns a dedicated std::thread. The result was one OS thread per open connection, exhausting the process thread limit after a few hundred connections (pre.33 used a tokio task and opened 1500+ cleanly). Make QueryTimeoutManager a process-wide singleton with one background thread. Each registered timeout now carries a Weak<Connection> on its heap entry, so a single wheel interrupts the right connection regardless of how many are open. Connections no longer hold a manager or shut one down on close. Also add an integration test that opens many connections at once as a reproducer for the exhaustion.
2 parents c6ef6e6 + 8e61295 commit 9181e85

4 files changed

Lines changed: 184 additions & 65 deletions

File tree

‎integration-tests/package.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
"test:async": "cross-env LIBSQL_JS_DEV=1 ava tests/async.test.js",
99
"test:extensions": "cross-env LIBSQL_JS_DEV=1 ava tests/extensions.test.js",
1010
"test:concurrency": "ava tests/concurrency.test.js",
11+
"test:connections": "cross-env LIBSQL_JS_DEV=1 ava tests/connections.test.js",
1112
"test": "run-s test:* -cln"
1213
},
1314
"devDependencies": {
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
import test from "ava";
2+
import crypto from "crypto";
3+
import fs from "fs";
4+
5+
// Reproducer for the connection-exhaustion regression reported between
6+
// 0.6.0-pre.33 (opens 1500 connections cleanly) and 0.6.0-pre.36 (fails
7+
// around 400 opens). Each test opens a large number of connections to the
8+
// same on-disk database and keeps them all open at once, then closes them.
9+
//
10+
// The count can be overridden with the CONNECTION_COUNT env var.
11+
const CONNECTION_COUNT = Number(process.env.CONNECTION_COUNT ?? 1500);
12+
13+
test.serial("Open many connections [async]", async (t) => {
14+
const libsql = await import("libsql/promise");
15+
const path = genDatabaseFilename();
16+
17+
const connections = [];
18+
try {
19+
for (let i = 0; i < CONNECTION_COUNT; i++) {
20+
const db = await libsql.connect(path);
21+
// Touch the connection so we know it is actually usable.
22+
await db.exec("SELECT 1");
23+
connections.push(db);
24+
}
25+
t.is(connections.length, CONNECTION_COUNT);
26+
} finally {
27+
for (const db of connections) {
28+
db.close();
29+
}
30+
cleanup(path);
31+
}
32+
});
33+
34+
test.serial("Open many connections [sync]", async (t) => {
35+
const x = await import("libsql");
36+
const Database = x.default;
37+
const path = genDatabaseFilename();
38+
39+
const connections = [];
40+
try {
41+
for (let i = 0; i < CONNECTION_COUNT; i++) {
42+
const db = new Database(path);
43+
// Touch the connection so we know it is actually usable.
44+
db.exec("SELECT 1");
45+
connections.push(db);
46+
}
47+
t.is(connections.length, CONNECTION_COUNT);
48+
} finally {
49+
for (const db of connections) {
50+
db.close();
51+
}
52+
cleanup(path);
53+
}
54+
});
55+
56+
/// Generate a unique database filename
57+
const genDatabaseFilename = () => {
58+
return `test-${crypto.randomBytes(8).toString("hex")}.db`;
59+
};
60+
61+
const cleanup = (path) => {
62+
for (const suffix of ["", "-wal", "-shm"]) {
63+
try {
64+
fs.unlinkSync(path + suffix);
65+
} catch {
66+
// ignore
67+
}
68+
}
69+
};

‎src/lib.rs‎

Lines changed: 19 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,15 @@ use napi::{
3030
use napi_derive::napi;
3131
use once_cell::sync::OnceCell;
3232
use query_timeout::{QueryTimeoutGuard, QueryTimeoutManager};
33+
34+
/// Registers a query timeout against the process-wide timer wheel, if one was
35+
/// requested. Returns a guard that cancels the timeout when dropped.
36+
fn register_query_timeout(
37+
conn: &Arc<libsql::Connection>,
38+
query_timeout: Option<Duration>,
39+
) -> Option<QueryTimeoutGuard> {
40+
query_timeout.map(|t| QueryTimeoutManager::global().register(conn, t))
41+
}
3342
use std::{
3443
str::FromStr,
3544
sync::{
@@ -237,15 +246,12 @@ pub struct Database {
237246
memory: bool,
238247
// Maximum time in milliseconds that a query is allowed to run.
239248
query_timeout: Option<Duration>,
240-
// Shared timeout manager for efficient query timeout handling.
241-
timeout_manager: Arc<QueryTimeoutManager>,
242249
// Ensures only one operation executes per connection at a time.
243250
execution_lock: Arc<tokio::sync::Mutex<()>>,
244251
}
245252

246253
impl Drop for Database {
247254
fn drop(&mut self) {
248-
self.timeout_manager.shutdown();
249255
self.conn = None;
250256
self.db = None;
251257
}
@@ -343,15 +349,13 @@ pub async fn connect(path: String, opts: Option<Options>) -> Result<Database> {
343349
.as_ref()
344350
.and_then(|o| o.defaultQueryTimeout)
345351
.and_then(query_timeout_duration);
346-
let timeout_manager = Arc::new(QueryTimeoutManager::new(&conn));
347352
let execution_lock = Arc::new(tokio::sync::Mutex::new(()));
348353
Ok(Database {
349354
db: Some(db),
350355
conn: Some(conn),
351356
default_safe_integers,
352357
memory,
353358
query_timeout,
354-
timeout_manager,
355359
execution_lock,
356360
})
357361
}
@@ -428,7 +432,6 @@ impl Database {
428432
stmt,
429433
mode,
430434
self.query_timeout,
431-
self.timeout_manager.clone(),
432435
self.execution_lock.clone(),
433436
))
434437
}
@@ -573,7 +576,7 @@ impl Database {
573576
None => self.query_timeout,
574577
};
575578
let _execution_guard = self.execution_lock.clone().lock_owned().await;
576-
let _timeout_guard = query_timeout.map(|t| self.timeout_manager.register(t));
579+
let _timeout_guard = register_query_timeout(&conn, query_timeout);
577580
conn.execute_batch(&sql).await.map_err(Error::from)?;
578581
Ok(())
579582
}
@@ -620,7 +623,6 @@ impl Database {
620623
/// Closes the database connection.
621624
#[napi]
622625
pub fn close(&mut self) -> Result<()> {
623-
self.timeout_manager.shutdown();
624626
self.conn = None;
625627
self.db = None;
626628
Ok(())
@@ -889,8 +891,6 @@ pub struct Statement {
889891
mode: AccessMode,
890892
// Maximum time in milliseconds that a query is allowed to run.
891893
query_timeout: Option<Duration>,
892-
// Shared timeout manager.
893-
timeout_manager: Arc<QueryTimeoutManager>,
894894
// Shared per-connection execution lock.
895895
execution_lock: Arc<tokio::sync::Mutex<()>>,
896896
}
@@ -909,7 +909,6 @@ impl Statement {
909909
stmt: libsql::Statement,
910910
mode: AccessMode,
911911
query_timeout: Option<Duration>,
912-
timeout_manager: Arc<QueryTimeoutManager>,
913912
execution_lock: Arc<tokio::sync::Mutex<()>>,
914913
) -> Self {
915914
let column_names: Vec<std::ffi::CString> = stmt
@@ -924,7 +923,6 @@ impl Statement {
924923
column_names,
925924
mode,
926925
query_timeout,
927-
timeout_manager,
928926
execution_lock,
929927
}
930928
}
@@ -948,12 +946,11 @@ impl Statement {
948946
let stmt = self.stmt.clone();
949947
let conn = self.conn.clone();
950948
let query_timeout = self.resolve_query_timeout(query_options);
951-
let timeout_manager = self.timeout_manager.clone();
952949
let execution_lock = self.execution_lock.clone();
953950

954951
let future = async move {
955952
let _execution_guard = execution_lock.lock_owned().await;
956-
let _timeout_guard = query_timeout.map(|t| timeout_manager.register(t));
953+
let _timeout_guard = register_query_timeout(&conn, query_timeout);
957954
stmt.run(params).await.map_err(Error::from)?;
958955
let changes = if conn.total_changes() == total_changes_before {
959956
0
@@ -1001,13 +998,13 @@ impl Statement {
1001998

1002999
let stmt = self.stmt.clone();
10031000
let stmt_fut = stmt.clone();
1001+
let conn = self.conn.clone();
10041002
let query_timeout = self.resolve_query_timeout(query_options);
1005-
let timeout_manager = self.timeout_manager.clone();
10061003
let execution_lock = self.execution_lock.clone();
10071004
let future = async move {
10081005
let result: std::result::Result<(Option<libsql::Row>, Option<f64>), Error> = {
10091006
let _execution_guard = execution_lock.lock_owned().await;
1010-
let _timeout_guard = query_timeout.map(|t| timeout_manager.register(t));
1007+
let _timeout_guard = register_query_timeout(&conn, query_timeout);
10111008
async {
10121009
let mut rows = stmt_fut.query(params).await.map_err(Error::from)?;
10131010
let row = rows.next().await.map_err(Error::from)?;
@@ -1085,12 +1082,12 @@ impl Statement {
10851082
let params = map_params(&stmt, params)?;
10861083
let stmt_for_query = self.stmt.clone();
10871084
let stmt_for_iter = stmt_for_query.clone();
1085+
let conn = self.conn.clone();
10881086
let query_timeout = self.resolve_query_timeout(query_options);
1089-
let timeout_manager = self.timeout_manager.clone();
10901087
let execution_lock = self.execution_lock.clone();
10911088
let future = async move {
10921089
let execution_guard = execution_lock.lock_owned().await;
1093-
let timeout_guard = query_timeout.map(|t| timeout_manager.register(t));
1090+
let timeout_guard = register_query_timeout(&conn, query_timeout);
10941091
let rows = stmt_for_query.query(params).await.map_err(Error::from)?;
10951092
Ok::<_, napi::Error>((rows, execution_guard, timeout_guard))
10961093
};
@@ -1221,12 +1218,11 @@ pub fn statement_get_sync(
12211218

12221219
let rt = runtime()?;
12231220
let query_timeout = stmt.resolve_query_timeout(query_options);
1224-
let timeout_manager = stmt.timeout_manager.clone();
12251221
let execution_lock = stmt.execution_lock.clone();
12261222
let result: Result<(Option<libsql::Row>, Option<f64>)> = {
12271223
rt.block_on(async move {
12281224
let _execution_guard = execution_lock.lock_owned().await;
1229-
let _timeout_guard = query_timeout.map(|t| timeout_manager.register(t));
1225+
let _timeout_guard = register_query_timeout(&stmt.conn, query_timeout);
12301226
let params = map_params(&stmt.stmt, params)?;
12311227
let mut rows = stmt.stmt.query(params).await.map_err(Error::from)?;
12321228
let row = rows.next().await.map_err(Error::from)?;
@@ -1265,11 +1261,10 @@ pub fn statement_run_sync(
12651261
stmt.stmt.reset();
12661262
let rt = runtime()?;
12671263
let query_timeout = stmt.resolve_query_timeout(query_options);
1268-
let timeout_manager = stmt.timeout_manager.clone();
12691264
let execution_lock = stmt.execution_lock.clone();
12701265
rt.block_on(async move {
12711266
let _execution_guard = execution_lock.lock_owned().await;
1272-
let _timeout_guard = query_timeout.map(|t| timeout_manager.register(t));
1267+
let _timeout_guard = register_query_timeout(&stmt.conn, query_timeout);
12731268
let params = map_params(&stmt.stmt, params)?;
12741269
let total_changes_before = stmt.conn.total_changes();
12751270
let start = std::time::Instant::now();
@@ -1302,13 +1297,13 @@ pub fn statement_iterate_sync(
13021297
let raw = stmt.mode.raw.load(Ordering::SeqCst);
13031298
let pluck = stmt.mode.pluck.load(Ordering::SeqCst);
13041299
let query_timeout = stmt.resolve_query_timeout(query_options);
1305-
let timeout_manager = stmt.timeout_manager.clone();
1300+
let conn = stmt.conn.clone();
13061301
let execution_lock = stmt.execution_lock.clone();
13071302
let inner_stmt = stmt.stmt.clone();
13081303
let iter_stmt = inner_stmt.clone();
13091304
let (rows, column_names, execution_guard, timeout_guard) = rt.block_on(async move {
13101305
let execution_guard = execution_lock.lock_owned().await;
1311-
let timeout_guard = query_timeout.map(|t| timeout_manager.register(t));
1306+
let timeout_guard = register_query_timeout(&conn, query_timeout);
13121307
inner_stmt.reset();
13131308
let params = map_params(&inner_stmt, params)?;
13141309
let rows = inner_stmt.query(params).await.map_err(Error::from)?;

0 commit comments

Comments
 (0)