feat(oracle): support manual query transactions
This commit is contained in:
22 files changed
+1011
-99
No files matched your search
@@ -178,6 +178,14 @@ enum ConnectionDatabaseInfoSource {
|
||||
pub enum TxnConnection {
|
||||
Postgres(Box<deadpool_postgres::Object>),
|
||||
Mysql(mysql_async::Conn),
|
||||
/// Dedicated agent multi_session workload client with an open sticky TX.
|
||||
Agent {
|
||||
client: Arc<db::agent_driver::PooledAgentClient>,
|
||||
/// Client-session id used when opening the dedicated agent pool.
|
||||
client_session_id: String,
|
||||
database: Option<String>,
|
||||
cleanup_guard: ClientSessionPoolCleanupGuard,
|
||||
},
|
||||
}
|
||||
|
||||
pub struct TransactionSession {
|
||||
@@ -376,7 +384,7 @@ struct PoolRoutingControl {
|
||||
task_supervisor: TaskSupervisor,
|
||||
}
|
||||
|
||||
pub(crate) struct ClientSessionPoolCleanupGuard {
|
||||
pub struct ClientSessionPoolCleanupGuard {
|
||||
pool_key: String,
|
||||
routing: PoolRoutingControl,
|
||||
armed: bool,
|
||||
@@ -435,12 +443,20 @@ impl PoolRoutingControl {
|
||||
let mut removed = vec![(pool_key.to_string(), pool)];
|
||||
if replace_agent_runtime {
|
||||
let sibling_keys = shared_runtime_sibling_keys(&connections, &removed[0].1);
|
||||
for key in sibling_keys {
|
||||
if let Some(pool) = connections.remove(&key) {
|
||||
removed.push((key, pool));
|
||||
let protects_manual_txn = sibling_keys.iter().any(|key| is_manual_transaction_pool_key(key))
|
||||
|| is_manual_transaction_pool_key(pool_key);
|
||||
if protects_manual_txn {
|
||||
log::warn!(
|
||||
"Skipping shared Agent runtime kill for '{pool_key}' because a manual-transaction session is active on the same runtime"
|
||||
);
|
||||
} else {
|
||||
for key in sibling_keys {
|
||||
if let Some(pool) = connections.remove(&key) {
|
||||
removed.push((key, pool));
|
||||
}
|
||||
}
|
||||
fail_stop_removed_agent_pool(pool_key, &removed[0].1);
|
||||
}
|
||||
fail_stop_removed_agent_pool(pool_key, &removed[0].1);
|
||||
}
|
||||
removed
|
||||
};
|
||||
@@ -472,14 +488,30 @@ impl PoolRoutingControl {
|
||||
_ => None,
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let removed = runtime_keys
|
||||
.into_iter()
|
||||
.filter_map(|key| connections.remove(&key).map(|pool| (key, pool)))
|
||||
.collect::<Vec<_>>();
|
||||
if !expected_client.fail_stop() {
|
||||
log::warn!("Failed to terminate the shared Agent runtime while detaching pool '{pool_key}'");
|
||||
// Sticky manual-transaction sessions pin work on the shared runtime.
|
||||
// Prefer quarantining only the failed route over killing every sibling TX.
|
||||
let protects_manual_txn = runtime_keys.iter().any(|key| is_manual_transaction_pool_key(key))
|
||||
|| is_manual_transaction_pool_key(pool_key);
|
||||
if protects_manual_txn {
|
||||
log::warn!(
|
||||
"Agent pool '{pool_key}' requested runtime replacement, but a manual-transaction session shares the runtime; detaching only this pool"
|
||||
);
|
||||
if is_current {
|
||||
let pool = connections.remove(pool_key).expect("current Agent pool must still exist");
|
||||
vec![(pool_key.to_string(), pool)]
|
||||
} else {
|
||||
Vec::new()
|
||||
}
|
||||
} else {
|
||||
let removed = runtime_keys
|
||||
.into_iter()
|
||||
.filter_map(|key| connections.remove(&key).map(|pool| (key, pool)))
|
||||
.collect::<Vec<_>>();
|
||||
if !expected_client.fail_stop() {
|
||||
log::warn!("Failed to terminate the shared Agent runtime while detaching pool '{pool_key}'");
|
||||
}
|
||||
removed
|
||||
}
|
||||
removed
|
||||
} else {
|
||||
let pool = connections.remove(pool_key).expect("current Agent pool must still exist");
|
||||
vec![(pool_key.to_string(), pool)]
|
||||
@@ -511,20 +543,40 @@ impl PoolRoutingControl {
|
||||
PoolKind::Agent(client) => Some(client.clone()),
|
||||
_ => None,
|
||||
};
|
||||
let protects_manual_txn = match agent_client.as_ref() {
|
||||
Some(client) if client.uses_shared_runtime() => {
|
||||
let connections = self.connections.read().await;
|
||||
connections.iter().any(|(key, pool)| {
|
||||
is_manual_transaction_pool_key(key)
|
||||
&& matches!(pool, PoolKind::Agent(sibling) if client.shares_runtime_with(sibling))
|
||||
})
|
||||
}
|
||||
_ => false,
|
||||
};
|
||||
match tokio::time::timeout(Duration::from_secs(POOL_CLOSE_TIMEOUT_SECS), close_pool_kind(pool)).await {
|
||||
Ok(Ok(())) => {}
|
||||
Ok(Err(error)) => {
|
||||
log::warn!("Failed to close connection pool '{pool_key}': {error}");
|
||||
if let Some(client) = agent_client.filter(|_| should_replace_agent_runtime(&error)) {
|
||||
if protects_manual_txn {
|
||||
log::warn!(
|
||||
"Leaving shared Agent runtime running after close failure for '{pool_key}' to protect sibling sessions"
|
||||
);
|
||||
} else if let Some(client) = agent_client.filter(|_| should_replace_agent_runtime(&error)) {
|
||||
self.replace_runtime_after_close_failure(&pool_key, &client).await;
|
||||
}
|
||||
}
|
||||
Err(_) => {
|
||||
log::warn!(
|
||||
"Timed out closing connection pool '{pool_key}' after {POOL_CLOSE_TIMEOUT_SECS}s; replacing a shared Agent runtime when present."
|
||||
);
|
||||
if let Some(client) = agent_client {
|
||||
self.replace_runtime_after_close_failure(&pool_key, &client).await;
|
||||
if protects_manual_txn {
|
||||
log::warn!(
|
||||
"Timed out closing shared Agent pool '{pool_key}' after {POOL_CLOSE_TIMEOUT_SECS}s; leaving the runtime running so sibling sessions (e.g. manual transactions) stay alive"
|
||||
);
|
||||
} else {
|
||||
log::warn!(
|
||||
"Timed out closing connection pool '{pool_key}' after {POOL_CLOSE_TIMEOUT_SECS}s; replacing a shared Agent runtime when present."
|
||||
);
|
||||
if let Some(client) = agent_client {
|
||||
self.replace_runtime_after_close_failure(&pool_key, &client).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1500,13 +1552,19 @@ impl AppState {
|
||||
// candidate never reaches this point, so the existing route keeps its state.
|
||||
routing.stop_keepalive(&pool_key);
|
||||
activity.insert(pool_key.clone(), PoolActivity::now());
|
||||
self.start_keepalive_task(
|
||||
&pool_key,
|
||||
&pool,
|
||||
config,
|
||||
#[cfg(feature = "mq-admin")]
|
||||
mq_keepalive_adapter.clone(),
|
||||
);
|
||||
// Manual-transaction sessions pin a sticky connection/TX. Keepalive
|
||||
// detach on these pools was able to tear down the shared agent runtime
|
||||
// (and any open TX) when close timed out — skip probes for them.
|
||||
let skip_keepalive = pool_key.contains(":session:manual-txn-");
|
||||
if !skip_keepalive {
|
||||
self.start_keepalive_task(
|
||||
&pool_key,
|
||||
&pool,
|
||||
config,
|
||||
#[cfg(feature = "mq-admin")]
|
||||
mq_keepalive_adapter.clone(),
|
||||
);
|
||||
}
|
||||
break Ok(connections.insert(pool_key.clone(), pool));
|
||||
};
|
||||
let previous = match previous {
|
||||
@@ -3626,6 +3684,21 @@ impl AppState {
|
||||
.await
|
||||
}
|
||||
|
||||
pub(crate) async fn workload_session_pool_cleanup_guard(
|
||||
&self,
|
||||
connection_id: &str,
|
||||
database: Option<&str>,
|
||||
client_session_id: &str,
|
||||
) -> Option<ClientSessionPoolCleanupGuard> {
|
||||
self.client_session_pool_cleanup_guard_for_role(
|
||||
connection_id,
|
||||
database,
|
||||
client_session_id,
|
||||
AgentSessionRole::Workload,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn client_session_pool_cleanup_guard_for_role(
|
||||
&self,
|
||||
connection_id: &str,
|
||||
@@ -4986,6 +5059,10 @@ fn is_session_scoped_pool_key(pool_key: &str) -> bool {
|
||||
pool_key.contains(":session:")
|
||||
}
|
||||
|
||||
fn is_manual_transaction_pool_key(pool_key: &str) -> bool {
|
||||
pool_key.contains(":session:manual-txn-")
|
||||
}
|
||||
|
||||
pub(crate) fn config_for_pool_key<'a>(
|
||||
pool_key: &str,
|
||||
configs: &'a HashMap<String, ConnectionConfig>,
|
||||
@@ -5493,7 +5570,7 @@ mod tests {
|
||||
redis_sentinel_transport_id, redis_sentinel_transport_prefix, sqlserver_legacy_agent_config,
|
||||
sqlserver_legacy_driver_error, sqlserver_uses_legacy_driver, task_client_session_id,
|
||||
upsert_connection_url_param, uses_bare_mysql_pool, uses_tcp_probe, validate_connection_url_params,
|
||||
validate_h2_database_path, AppState, MysqlMode, PoolKind, GAUSSDB_M_JDBC_DRIVER_CLASS,
|
||||
validate_h2_database_path, AppState, MysqlMode, PoolKind, TxnConnection, GAUSSDB_M_JDBC_DRIVER_CLASS,
|
||||
GAUSSDB_M_JDBC_DRIVER_PROFILE, PRESTOSQL_JDBC_DRIVER_CLASS,
|
||||
};
|
||||
use crate::agent_connection::{
|
||||
@@ -7662,6 +7739,39 @@ for line in sys.stdin:
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn metadata_close_replace_runtime_preserves_manual_transaction_sibling() {
|
||||
let (state, dir) = test_app_state().await;
|
||||
let (runtime, metadata_client, manual_txn_client) =
|
||||
replace_runtime_on_error_clients(&dir, "close_session").await;
|
||||
let mut config = mysql_config(Some("analytics"));
|
||||
config.id = "conn".to_string();
|
||||
config.db_type = DatabaseType::Dameng;
|
||||
state.configs.write().await.insert(config.id.clone(), config);
|
||||
let metadata_pool_key = "conn:analytics:session:metadata-session:role:metadata";
|
||||
let manual_txn_pool_key = "conn:analytics:session:manual-txn-test";
|
||||
{
|
||||
let mut connections = state.connections.write().await;
|
||||
connections.insert(metadata_pool_key.to_string(), PoolKind::Agent(metadata_client));
|
||||
connections.insert(manual_txn_pool_key.to_string(), PoolKind::Agent(manual_txn_client));
|
||||
}
|
||||
{
|
||||
let mut activity = state.pool_activity.write().await;
|
||||
activity.insert(metadata_pool_key.to_string(), super::PoolActivity::now());
|
||||
activity.insert(manual_txn_pool_key.to_string(), super::PoolActivity::now());
|
||||
}
|
||||
|
||||
assert!(state.close_metadata_session_pool("conn", Some("analytics"), "metadata-session").await.unwrap());
|
||||
|
||||
assert!(!state.connections.read().await.contains_key(metadata_pool_key));
|
||||
assert!(state.connections.read().await.contains_key(manual_txn_pool_key));
|
||||
assert!(state.pool_activity.read().await.contains_key(manual_txn_pool_key));
|
||||
assert!(!runtime.is_failed());
|
||||
|
||||
state.shutdown(Duration::from_secs(1)).await;
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn reclaim_close_replace_runtime_never_restores_failed_pool() {
|
||||
let (state, dir) = test_app_state().await;
|
||||
@@ -8151,6 +8261,43 @@ for line in sys.stdin:
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn manual_transaction_connection_drop_detaches_session_pool() {
|
||||
let (state, dir) = test_app_state().await;
|
||||
let (runtime, manual_txn_client, _sibling_client) = replace_runtime_on_error_clients(&dir, "unused").await;
|
||||
let mut config = mysql_config(Some("analytics"));
|
||||
config.id = "conn".to_string();
|
||||
config.db_type = DatabaseType::Dameng;
|
||||
state.configs.write().await.insert(config.id.clone(), config);
|
||||
|
||||
let client_session_id = "manual-txn-test";
|
||||
let pool_key = "conn:analytics:session:manual-txn-test";
|
||||
state.connections.write().await.insert(pool_key.to_string(), PoolKind::Agent(manual_txn_client.clone()));
|
||||
state.pool_activity.write().await.insert(pool_key.to_string(), super::PoolActivity::now());
|
||||
let cleanup_guard =
|
||||
state.workload_session_pool_cleanup_guard("conn", Some("analytics"), client_session_id).await.unwrap();
|
||||
|
||||
drop(TxnConnection::Agent {
|
||||
client: manual_txn_client,
|
||||
client_session_id: client_session_id.to_string(),
|
||||
database: Some("analytics".to_string()),
|
||||
cleanup_guard,
|
||||
});
|
||||
|
||||
for _ in 0..100 {
|
||||
if !state.connections.read().await.contains_key(pool_key) {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
assert!(!state.connections.read().await.contains_key(pool_key));
|
||||
assert!(!state.pool_activity.read().await.contains_key(pool_key));
|
||||
assert!(!runtime.is_failed());
|
||||
|
||||
state.shutdown(Duration::from_secs(1)).await;
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn closing_oracle_table_tab_keeps_connection_scoped_pool() {
|
||||
let (state, dir) = test_app_state().await;
|
||||
|
||||
@@ -880,6 +880,11 @@ impl PooledAgentClient {
|
||||
self.shared_runtime.as_ref().is_none_or(|runtime| !runtime.is_failed())
|
||||
}
|
||||
|
||||
/// True when this client is attached to a multi-session shared agent process.
|
||||
pub fn uses_shared_runtime(&self) -> bool {
|
||||
self.shared_runtime.is_some()
|
||||
}
|
||||
|
||||
/// Terminates a protocol-v2 shared runtime without waiting for the logical session lock.
|
||||
/// Legacy single-session clients can only be killed immediately when they are not busy.
|
||||
pub fn fail_stop(&self) -> bool {
|
||||
@@ -1151,12 +1156,15 @@ pub enum AgentMethod {
|
||||
GetExplainInfo,
|
||||
ExecuteBatch,
|
||||
ExecuteTransaction,
|
||||
BeginManualTransaction,
|
||||
CommitManualTransaction,
|
||||
RollbackManualTransaction,
|
||||
Disconnect,
|
||||
Shutdown,
|
||||
}
|
||||
|
||||
impl AgentMethod {
|
||||
pub const ALL: [Self; 36] = [
|
||||
pub const ALL: [Self; 39] = [
|
||||
Self::Handshake,
|
||||
Self::Connect,
|
||||
Self::OpenSession,
|
||||
@@ -1191,6 +1199,9 @@ impl AgentMethod {
|
||||
Self::GetExplainInfo,
|
||||
Self::ExecuteBatch,
|
||||
Self::ExecuteTransaction,
|
||||
Self::BeginManualTransaction,
|
||||
Self::CommitManualTransaction,
|
||||
Self::RollbackManualTransaction,
|
||||
Self::Disconnect,
|
||||
Self::Shutdown,
|
||||
];
|
||||
@@ -1232,6 +1243,9 @@ impl AgentMethod {
|
||||
Self::GetExplainInfo => "get_explain_info",
|
||||
Self::ExecuteBatch => "execute_batch",
|
||||
Self::ExecuteTransaction => "execute_transaction",
|
||||
Self::BeginManualTransaction => "begin_manual_transaction",
|
||||
Self::CommitManualTransaction => "commit_manual_transaction",
|
||||
Self::RollbackManualTransaction => "rollback_manual_transaction",
|
||||
Self::Disconnect => "disconnect",
|
||||
Self::Shutdown => "shutdown",
|
||||
}
|
||||
@@ -2448,6 +2462,24 @@ impl AgentDriverClient {
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn begin_manual_transaction<T: DeserializeOwned + Send + 'static>(
|
||||
&mut self,
|
||||
schema: Option<&str>,
|
||||
) -> Result<T, String> {
|
||||
self.invalidate_cached_query();
|
||||
self.call_method(AgentMethod::BeginManualTransaction, agent_manual_transaction_params(schema)).await
|
||||
}
|
||||
|
||||
pub async fn commit_manual_transaction<T: DeserializeOwned + Send + 'static>(&mut self) -> Result<T, String> {
|
||||
self.invalidate_cached_query();
|
||||
self.call_method(AgentMethod::CommitManualTransaction, serde_json::json!({})).await
|
||||
}
|
||||
|
||||
pub async fn rollback_manual_transaction<T: DeserializeOwned + Send + 'static>(&mut self) -> Result<T, String> {
|
||||
self.invalidate_cached_query();
|
||||
self.call_method(AgentMethod::RollbackManualTransaction, serde_json::json!({})).await
|
||||
}
|
||||
|
||||
pub async fn execute_batch<T: DeserializeOwned + Send + 'static>(
|
||||
&mut self,
|
||||
database: Option<&str>,
|
||||
@@ -2853,6 +2885,14 @@ pub fn agent_transaction_params(database: Option<&str>, statements: &[String], s
|
||||
})
|
||||
}
|
||||
|
||||
pub fn agent_manual_transaction_params(schema: Option<&str>) -> Value {
|
||||
let schema = schema.map(str::trim).filter(|schema| !schema.is_empty());
|
||||
match schema {
|
||||
Some(schema) => serde_json::json!({ "schema": schema }),
|
||||
None => serde_json::json!({}),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn mongo_database_params(database: &str) -> Value {
|
||||
serde_json::json!({ "database": database })
|
||||
}
|
||||
@@ -4476,6 +4516,9 @@ for line in sys.stdin:
|
||||
assert_eq!(AgentMethod::CloseTableReadSession.as_str(), "close_table_read_session");
|
||||
assert_eq!(AgentMethod::ExecuteBatch.as_str(), "execute_batch");
|
||||
assert_eq!(AgentMethod::ExecuteTransaction.as_str(), "execute_transaction");
|
||||
assert_eq!(AgentMethod::BeginManualTransaction.as_str(), "begin_manual_transaction");
|
||||
assert_eq!(AgentMethod::CommitManualTransaction.as_str(), "commit_manual_transaction");
|
||||
assert_eq!(AgentMethod::RollbackManualTransaction.as_str(), "rollback_manual_transaction");
|
||||
assert_eq!(AgentMethod::Disconnect.as_str(), "disconnect");
|
||||
assert_eq!(AgentMethod::Shutdown.as_str(), "shutdown");
|
||||
}
|
||||
|
||||
+116
-11
@@ -4315,24 +4315,28 @@ async fn begin_transaction_session(
|
||||
) -> Result<String, String> {
|
||||
let mysql_catalog_dialect = connection_mysql_catalog_dialect(state, connection_id).await;
|
||||
let pool_database = query_pool_database(database, catalog);
|
||||
let pool_key = state.get_or_create_pool(connection_id, pool_database).await?;
|
||||
// Probe the primary pool to learn the backend kind. Agent manual TX opens a
|
||||
// dedicated multi_session workload pool so sticky TX state is isolated.
|
||||
let probe_pool_key = state.get_or_create_pool(connection_id, pool_database).await?;
|
||||
|
||||
// Clone the pool handle under a brief read lock, then drop the lock before
|
||||
// any async I/O — same pattern as do_execute throughout this file.
|
||||
enum TxnPoolHandle {
|
||||
Postgres(deadpool_postgres::Pool),
|
||||
Mysql(db::mysql::MySqlPool),
|
||||
Agent,
|
||||
}
|
||||
let pool_handle = {
|
||||
let connections = state.connections.read().await;
|
||||
match connections.get(&pool_key).ok_or("Connection not found")? {
|
||||
match connections.get(&probe_pool_key).ok_or("Connection not found")? {
|
||||
PoolKind::Postgres(pg) => TxnPoolHandle::Postgres(pg.clone()),
|
||||
PoolKind::Mysql(mp, _) => TxnPoolHandle::Mysql(mp.clone()),
|
||||
PoolKind::Agent(_) if !consistent_snapshot => TxnPoolHandle::Agent,
|
||||
_ => return Err("Manual transaction is not supported for this database type".to_string()),
|
||||
}
|
||||
}; // connections lock released here
|
||||
|
||||
let txn_conn = match pool_handle {
|
||||
let (txn_conn, pool_key) = match pool_handle {
|
||||
TxnPoolHandle::Postgres(pg_pool) => {
|
||||
let conn = pg_pool.get().await.map_err(|e| format!("Failed to get Postgres connection: {e}"))?;
|
||||
let begin_sql = postgres_transaction_begin_sql(consistent_snapshot);
|
||||
@@ -4347,7 +4351,7 @@ async fn begin_transaction_session(
|
||||
.await
|
||||
.map_err(|e| format!("SET search_path failed: {e}"))?;
|
||||
}
|
||||
TxnConnection::Postgres(Box::new(conn))
|
||||
(TxnConnection::Postgres(Box::new(conn)), probe_pool_key.clone())
|
||||
}
|
||||
TxnPoolHandle::Mysql(mysql_pool) => {
|
||||
let mut conn = mysql_pool.get_conn().await.map_err(|e| format!("Failed to get MySQL connection: {e}"))?;
|
||||
@@ -4371,7 +4375,45 @@ async fn begin_transaction_session(
|
||||
if !syntax_errors.is_empty() {
|
||||
return Err(format!("START TRANSACTION failed for all compatible forms: {}", syntax_errors.join("; ")));
|
||||
}
|
||||
TxnConnection::Mysql(conn)
|
||||
(TxnConnection::Mysql(conn), probe_pool_key.clone())
|
||||
}
|
||||
TxnPoolHandle::Agent => {
|
||||
let client_session_id = format!("manual-txn-{}", uuid::Uuid::new_v4());
|
||||
let agent_pool_key =
|
||||
state.get_or_create_pool_for_session(connection_id, pool_database, Some(&client_session_id)).await?;
|
||||
let client = {
|
||||
let connections = state.connections.read().await;
|
||||
match connections.get(&agent_pool_key) {
|
||||
Some(PoolKind::Agent(client)) => client.clone(),
|
||||
_ => {
|
||||
let _ = state.close_client_session_pool(connection_id, pool_database, &client_session_id).await;
|
||||
return Err("Agent connection not found for manual transaction".to_string());
|
||||
}
|
||||
}
|
||||
};
|
||||
let begin_result = {
|
||||
let mut locked = client.lock().await;
|
||||
locked.begin_manual_transaction::<serde_json::Value>(schema).await
|
||||
};
|
||||
if let Err(error) = begin_result {
|
||||
let _ = state.close_client_session_pool(connection_id, pool_database, &client_session_id).await;
|
||||
return Err(format!("BEGIN manual transaction failed: {error}"));
|
||||
}
|
||||
let Some(cleanup_guard) =
|
||||
state.workload_session_pool_cleanup_guard(connection_id, pool_database, &client_session_id).await
|
||||
else {
|
||||
let _ = state.close_client_session_pool(connection_id, pool_database, &client_session_id).await;
|
||||
return Err("Manual transaction requires a dedicated Agent session".to_string());
|
||||
};
|
||||
(
|
||||
TxnConnection::Agent {
|
||||
client,
|
||||
client_session_id,
|
||||
database: pool_database.map(str::to_string),
|
||||
cleanup_guard,
|
||||
},
|
||||
agent_pool_key,
|
||||
)
|
||||
}
|
||||
};
|
||||
|
||||
@@ -4503,16 +4545,17 @@ pub async fn execute_in_manual_transaction(
|
||||
}
|
||||
if session.last_activity.elapsed() > TXN_IDLE_TIMEOUT {
|
||||
let session = sessions.remove(txn_session_id).expect("session exists");
|
||||
Some(session.connection)
|
||||
Some(session)
|
||||
} else {
|
||||
session.busy = true;
|
||||
session.last_activity = std::time::Instant::now();
|
||||
None
|
||||
}
|
||||
};
|
||||
if let Some(connection) = connection {
|
||||
let mut conn = connection.lock().await;
|
||||
if let Some(session) = connection {
|
||||
let mut conn = session.connection.lock().await;
|
||||
let _ = rollback_manual_txn_connection(&mut conn).await;
|
||||
release_manual_txn_agent_pool(state, &session.connection_id, &mut conn).await;
|
||||
return Err("Transaction was auto-rolled back due to 5 minutes of inactivity".to_string());
|
||||
}
|
||||
|
||||
@@ -4533,6 +4576,9 @@ pub async fn execute_in_manual_transaction(
|
||||
execute_manual_txn_postgres_statement(conn.as_ref(), statement, row_limit).await
|
||||
}
|
||||
TxnConnection::Mysql(conn) => execute_manual_txn_mysql_statement(conn, statement, row_limit).await,
|
||||
TxnConnection::Agent { client, .. } => {
|
||||
execute_manual_txn_agent_statement(client, db_type, statement, _database, _schema, row_limit).await
|
||||
}
|
||||
};
|
||||
match result {
|
||||
Ok(query_result) => results.push(query_result),
|
||||
@@ -4545,8 +4591,9 @@ pub async fn execute_in_manual_transaction(
|
||||
};
|
||||
if should_rollback {
|
||||
let _ = rollback_manual_txn_connection(&mut conn).await;
|
||||
release_manual_txn_agent_pool(state, &connection_id, &mut conn).await;
|
||||
}
|
||||
return Err(format!("Statement {} failed: {}. Transaction was auto-rolled back.", i + 1, e));
|
||||
return Err(format!("Statement {} failed: {}. The manual transaction was rolled back.", i + 1, e));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4679,12 +4726,19 @@ where
|
||||
},
|
||||
Err(err) => Err(format!("Query failed: {err}")),
|
||||
},
|
||||
TxnConnection::Agent { .. } => {
|
||||
Err("Streaming rows inside an agent manual transaction is not supported".to_string())
|
||||
}
|
||||
};
|
||||
|
||||
if let Err(err) = &stream_result {
|
||||
let should_rollback = state.transaction_sessions.write().await.remove(txn_session_id).is_some();
|
||||
if should_rollback {
|
||||
let removed = {
|
||||
let mut sessions = state.transaction_sessions.write().await;
|
||||
sessions.remove(txn_session_id)
|
||||
};
|
||||
if let Some(session) = removed {
|
||||
let _ = rollback_manual_txn_connection(&mut conn).await;
|
||||
release_manual_txn_agent_pool(state, &session.connection_id, &mut conn).await;
|
||||
}
|
||||
return Err(format!("{err}. Transaction was auto-rolled back."));
|
||||
}
|
||||
@@ -4714,10 +4768,51 @@ async fn rollback_manual_txn_connection(conn: &mut TxnConnection) -> Result<(),
|
||||
TxnConnection::Mysql(conn) => {
|
||||
conn.query_drop("ROLLBACK").await.map_err(|e| format!("ROLLBACK failed: {e}"))?;
|
||||
}
|
||||
TxnConnection::Agent { client, .. } => {
|
||||
let mut locked = client.lock().await;
|
||||
match locked.rollback_manual_transaction::<serde_json::Value>().await {
|
||||
Ok(_) => {}
|
||||
Err(error) if error.to_ascii_lowercase().contains("no manual transaction") => {}
|
||||
Err(error) => return Err(format!("ROLLBACK failed: {error}")),
|
||||
}
|
||||
// Close the dedicated agent session so Oracle resources are released even if
|
||||
// the pool map entry is cleaned up later.
|
||||
let _ = locked.disconnect().await;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn release_manual_txn_agent_pool(state: &AppState, connection_id: &str, conn: &mut TxnConnection) {
|
||||
let TxnConnection::Agent { client_session_id, database, cleanup_guard, .. } = conn else {
|
||||
return;
|
||||
};
|
||||
if state.detach_client_session_pool(connection_id, database.as_deref(), client_session_id).await.unwrap_or(false) {
|
||||
cleanup_guard.disarm();
|
||||
}
|
||||
}
|
||||
|
||||
async fn execute_manual_txn_agent_statement(
|
||||
client: &Arc<crate::db::agent_driver::PooledAgentClient>,
|
||||
db_type: Option<DatabaseType>,
|
||||
statement: &str,
|
||||
database: &str,
|
||||
schema: Option<&str>,
|
||||
row_limit: usize,
|
||||
) -> Result<db::QueryResult, String> {
|
||||
let sql = sql_for_execution_context(db_type, statement, schema);
|
||||
let execution_schema = schema_for_execution_context(db_type, schema);
|
||||
let options = QueryExecutionOptions { max_rows: Some(row_limit.max(1)), ..QueryExecutionOptions::default() };
|
||||
let params =
|
||||
agent_execute_query_params(&sql, Some(database).filter(|value| !value.is_empty()), execution_schema, options);
|
||||
let mut locked = client.lock().await;
|
||||
locked
|
||||
.execute_query_typed_with_timeout::<db::QueryResult>(params, None)
|
||||
.await
|
||||
.map(|result| truncate_result_with_max_rows(result, Some(row_limit.max(1))))
|
||||
.map_err(|error| error.into_legacy_string())
|
||||
}
|
||||
|
||||
/// Spawn a background task that removes and rolls back a transaction session
|
||||
/// after 5 minutes of inactivity. The task does not hold the global lock across
|
||||
/// I/O: it briefly checks the map, and if the session exists and is expired,
|
||||
@@ -4865,7 +4960,16 @@ pub async fn commit_manual_transaction(state: &AppState, txn_session_id: &str) -
|
||||
TxnConnection::Mysql(conn) => {
|
||||
conn.query_drop("COMMIT").await.map_err(|e| format!("COMMIT failed: {e}"))?;
|
||||
}
|
||||
TxnConnection::Agent { client, .. } => {
|
||||
let mut locked = client.lock().await;
|
||||
locked
|
||||
.commit_manual_transaction::<serde_json::Value>()
|
||||
.await
|
||||
.map_err(|error| format!("COMMIT failed: {error}"))?;
|
||||
let _ = locked.disconnect().await;
|
||||
}
|
||||
}
|
||||
release_manual_txn_agent_pool(state, &session.connection_id, &mut conn).await;
|
||||
|
||||
log::info!("[query][manual_txn:commit] session_id={}", txn_session_id);
|
||||
Ok(db::QueryResult {
|
||||
@@ -4894,6 +4998,7 @@ pub async fn rollback_manual_transaction(state: &AppState, txn_session_id: &str)
|
||||
|
||||
let mut conn = session.connection.lock().await;
|
||||
rollback_manual_txn_connection(&mut conn).await?;
|
||||
release_manual_txn_agent_pool(state, &session.connection_id, &mut conn).await;
|
||||
|
||||
log::info!("[query][manual_txn:rollback] session_id={}", txn_session_id);
|
||||
Ok(db::QueryResult {
|
||||
|
||||
Reference in new issue
Block a user