use crate::error::{GarrisonError, GarrisonResult};
use crate::listener::{DispatchOutcome, GarrisonEvent, GarrisonListenerManager};
use dbnexus::DbPool;
use std::sync::Arc;
pub struct GarrisonEventTx {
session: Option<dbnexus::Session>,
lm: Arc<GarrisonListenerManager>,
buffer: Vec<GarrisonEvent>,
committed: bool,
dispatched: usize,
}
impl GarrisonEventTx {
pub async fn begin(pool: &DbPool, lm: Arc<GarrisonListenerManager>) -> GarrisonResult<Self> {
let session = pool
.get_session("admin")
.await
.map_err(|e| GarrisonError::Dao(format!("event-tx-get-session::{}", e)))?;
session
.begin_transaction()
.await
.map_err(|e| GarrisonError::Dao(format!("event-tx-begin::{}", e)))?;
Ok(Self {
session: Some(session),
lm,
buffer: Vec::new(),
committed: false,
dispatched: 0,
})
}
pub fn on_commit(&mut self, event: GarrisonEvent) {
self.buffer.push(event);
}
pub async fn execute(&self, sql: &str) -> GarrisonResult<u64> {
let session = self
.session
.as_ref()
.ok_or_else(|| GarrisonError::Internal("event-tx-already-finished".to_string()))?;
let result = session
.execute_raw(sql)
.await
.map_err(|e| GarrisonError::Dao(format!("event-tx-execute::{}", e)))?;
Ok(result.rows_affected())
}
pub async fn commit(mut self) -> GarrisonResult<DispatchOutcome> {
let session = self
.session
.take()
.ok_or_else(|| GarrisonError::Internal("event-tx-already-finished".to_string()))?;
session
.commit()
.await
.map_err(|e| GarrisonError::Dao(format!("event-tx-commit::{}", e)))?;
drop(session);
self.committed = true;
let mut outcome = DispatchOutcome::default();
for index in self.dispatched..self.buffer.len() {
let one = self
.lm
.broadcast_after_commit(std::slice::from_ref(&self.buffer[index]))
.await;
outcome.dispatched += one.dispatched;
outcome.failed += one.failed;
self.dispatched = index + 1;
}
Ok(outcome)
}
pub async fn rollback(mut self) -> GarrisonResult<()> {
let session = self
.session
.take()
.ok_or_else(|| GarrisonError::Internal("event-tx-already-finished".to_string()))?;
self.buffer.clear();
session
.rollback()
.await
.map_err(|e| GarrisonError::Dao(format!("event-tx-rollback::{}", e)))?;
Ok(())
}
}
impl Drop for GarrisonEventTx {
fn drop(&mut self) {
let open_tx = self.session.take().is_some();
if open_tx {
let count = self.buffer.len().to_string();
let kinds = event_summary(&self.buffer);
tracing::warn!(
"{}",
crate::i18n::translate_detail(
"logs-event-tx-dropped-without-commit",
&[("count", count.as_str()), ("kinds", kinds.as_str())]
)
);
} else if !self.buffer.is_empty() && !self.committed {
let count = self.buffer.len().to_string();
let kinds = event_summary(&self.buffer);
tracing::warn!(
"{}",
crate::i18n::translate_detail(
"logs-event-tx-discarded-after-commit-failure",
&[("count", count.as_str()), ("kinds", kinds.as_str())]
)
);
} else if self.committed && self.dispatched < self.buffer.len() {
let dispatched = self.dispatched.to_string();
let total = self.buffer.len().to_string();
let kinds = event_summary(&self.buffer[self.dispatched..]);
tracing::warn!(
"{}",
crate::i18n::translate_detail(
"logs-event-tx-dispatch-cancelled-after-commit",
&[
("dispatched", dispatched.as_str()),
("total", total.as_str()),
("kinds", kinds.as_str()),
]
)
);
}
self.buffer.clear();
}
}
fn event_summary(events: &[GarrisonEvent]) -> String {
let mut counts: Vec<(&'static str, usize)> = Vec::new();
for event in events {
let kind = event_kind(event);
match counts.iter_mut().find(|(k, _)| *k == kind) {
Some((_, count)) => *count += 1,
None => counts.push((kind, 1)),
}
}
counts
.iter()
.map(|(kind, count)| format!("{kind}={count}"))
.collect::<Vec<_>>()
.join(", ")
}
fn event_kind(event: &GarrisonEvent) -> &'static str {
match event {
GarrisonEvent::Login { .. } => "Login",
GarrisonEvent::Logout { .. } => "Logout",
GarrisonEvent::Kickout { .. } => "Kickout",
GarrisonEvent::PermissionCheck { .. } => "PermissionCheck",
GarrisonEvent::RoleCheck { .. } => "RoleCheck",
GarrisonEvent::TokenExpired { .. } => "TokenExpired",
GarrisonEvent::LoginFailure { .. } => "LoginFailure",
GarrisonEvent::PasswordRehashed { .. } => "PasswordRehashed",
GarrisonEvent::TokenRefresh { .. } => "TokenRefresh",
GarrisonEvent::RevokeToken { .. } => "RevokeToken",
GarrisonEvent::SessionTimeout { .. } => "SessionTimeout",
GarrisonEvent::AccountLocked { .. } => "AccountLocked",
GarrisonEvent::FirewallBlock { .. } => "FirewallBlock",
GarrisonEvent::Replaced { .. } => "Replaced",
GarrisonEvent::ConfigReload { .. } => "ConfigReload",
GarrisonEvent::SocialLogin { .. } => "SocialLogin",
GarrisonEvent::TenantSwitch { .. } => "TenantSwitch",
GarrisonEvent::TokenRotate { .. } => "TokenRotate",
GarrisonEvent::TempCredentialConsumed { .. } => "TempCredentialConsumed",
GarrisonEvent::InvitationCreated { .. } => "InvitationCreated",
GarrisonEvent::InvitationRedeemed { .. } => "InvitationRedeemed",
GarrisonEvent::InvitationRevoked { .. } => "InvitationRevoked",
GarrisonEvent::QrLoginCreated { .. } => "QrLoginCreated",
GarrisonEvent::QrLoginScanned { .. } => "QrLoginScanned",
GarrisonEvent::QrLoginConfirmed { .. } => "QrLoginConfirmed",
GarrisonEvent::QrLoginCancelled { .. } => "QrLoginCancelled",
GarrisonEvent::DeviceBlock { .. } => "DeviceBlock",
GarrisonEvent::DeviceUnblock { .. } => "DeviceUnblock",
#[cfg(feature = "anomalous-detector-dual")]
GarrisonEvent::AnomalousLoginDetected { .. } => "AnomalousLoginDetected",
#[cfg(feature = "credit-metering")]
GarrisonEvent::CreditConsumed { .. } => "CreditConsumed",
#[cfg(feature = "credit-metering")]
GarrisonEvent::CreditAlert { .. } => "CreditAlert",
}
}
#[cfg(all(test, feature = "db-sqlite", feature = "listener"))]
mod tests {
use super::*;
use crate::dao::{init_dbnexus, GarrisonMigration};
use crate::listener::GarrisonListener;
use async_trait::async_trait;
use dbnexus::sea_orm::{ConnectionTrait, DbBackend, Statement};
use parking_lot::Mutex;
use std::path::PathBuf;
async fn setup_pool() -> dbnexus::DbPool {
let pool = init_dbnexus("sqlite::memory:")
.await
.expect("init_dbnexus 应成功");
let migrations_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("migrations")
.join("sqlite");
let migration = GarrisonMigration::with_base_dir(pool.clone(), migrations_dir);
migration.migrate_core().await.expect("migrate_core 应成功");
let session = pool.get_session("admin").await.expect("get_session 应成功");
session
.execute_raw_ddl(
"CREATE TABLE garrison_event_tx_test \
(id INTEGER PRIMARY KEY, tag TEXT NOT NULL)",
)
.await
.expect("建测试表应成功");
drop(session);
pool
}
fn manager_with(listener: Arc<dyn GarrisonListener>) -> Arc<GarrisonListenerManager> {
let lm = Arc::new(GarrisonListenerManager::new());
lm.register(listener);
lm
}
async fn count_rows(pool: &dbnexus::DbPool, tag: &str) -> i64 {
let session = pool.get_session("admin").await.expect("get_session 应成功");
let conn = session.connection().expect("connection 应可用");
let stmt = Statement::from_sql_and_values(
DbBackend::Sqlite,
"SELECT count(*) AS cnt FROM garrison_event_tx_test WHERE tag = ?",
vec![tag.to_string().into()],
);
let row = conn
.query_one_raw(stmt)
.await
.expect("count 查询应成功")
.expect("count 应返回一行");
row.try_get::<i64>("", "cnt").expect("cnt 列应存在")
}
struct RecordingListener {
tags: Mutex<Vec<String>>,
}
impl RecordingListener {
fn new() -> Self {
Self {
tags: Mutex::new(Vec::new()),
}
}
fn snapshot(&self) -> Vec<String> {
self.tags.lock().clone()
}
}
#[async_trait]
impl GarrisonListener for RecordingListener {
async fn on_event(&self, event: &GarrisonEvent) -> GarrisonResult<()> {
self.tags.lock().push(event_tag(event));
Ok(())
}
}
struct BlockingListener {
entered: Mutex<Option<tokio::sync::oneshot::Sender<()>>>,
}
#[async_trait]
impl GarrisonListener for BlockingListener {
async fn on_event(&self, _event: &GarrisonEvent) -> GarrisonResult<()> {
if let Some(tx) = self.entered.lock().take() {
let _ = tx.send(());
}
std::future::pending::<()>().await;
Ok(())
}
}
fn event_tag(event: &GarrisonEvent) -> String {
match event {
GarrisonEvent::Login { login_id, .. } => format!("login:{login_id}"),
GarrisonEvent::PermissionCheck { permission, .. } => {
format!("perm:{permission}")
},
GarrisonEvent::Logout { login_id, .. } => format!("logout:{login_id}"),
_ => "other".to_string(),
}
}
fn login_event(login_id: &str) -> GarrisonEvent {
GarrisonEvent::Login {
login_id: login_id.to_string(),
token: "T1".to_string(),
device: None,
request_context: None,
}
}
fn perm_event(permission: &str) -> GarrisonEvent {
GarrisonEvent::PermissionCheck {
login_id: "1001".to_string(),
permission: permission.to_string(),
request_context: None,
}
}
#[tokio::test(flavor = "multi_thread")]
async fn commit_dispatches_after_db_commit() {
let pool = setup_pool().await;
let recorder = Arc::new(RecordingListener::new());
let lm = manager_with(recorder.clone());
let mut guard = GarrisonEventTx::begin(&pool, lm)
.await
.expect("begin 应成功");
guard.on_commit(login_event("1001"));
assert!(
recorder.snapshot().is_empty(),
"commit 前 listener 不应收到缓冲事件"
);
let affected = guard
.execute("INSERT INTO garrison_event_tx_test (id, tag) VALUES (1, 'committed')")
.await
.expect("事务内 INSERT 应成功");
assert_eq!(affected, 1, "INSERT 应影响 1 行");
guard.commit().await.expect("commit 应成功");
assert_eq!(
recorder.snapshot(),
vec!["login:1001".to_string()],
"commit 后 listener 应恰好收到缓冲的 Login 事件"
);
assert_eq!(
count_rows(&pool, "committed").await,
1,
"事务提交后写入的行应可见"
);
}
#[tokio::test(flavor = "multi_thread")]
async fn rollback_discards_events_and_writes() {
let pool = setup_pool().await;
let recorder = Arc::new(RecordingListener::new());
let lm = manager_with(recorder.clone());
let mut guard = GarrisonEventTx::begin(&pool, lm)
.await
.expect("begin 应成功");
guard.on_commit(login_event("2001"));
guard
.execute("INSERT INTO garrison_event_tx_test (id, tag) VALUES (2, 'rolled-back')")
.await
.expect("事务内 INSERT 应成功");
guard.rollback().await.expect("rollback 应成功");
assert!(
recorder.snapshot().is_empty(),
"rollback 后缓冲事件不应派发"
);
assert_eq!(
count_rows(&pool, "rolled-back").await,
0,
"回滚后事务内写入的行不应存在"
);
}
#[tokio::test(flavor = "multi_thread")]
async fn drop_without_commit_is_safe() {
let pool = setup_pool().await;
let recorder = Arc::new(RecordingListener::new());
let lm = manager_with(recorder.clone());
let mut guard = GarrisonEventTx::begin(&pool, lm)
.await
.expect("begin 应成功");
guard.on_commit(login_event("3001"));
guard
.execute("INSERT INTO garrison_event_tx_test (id, tag) VALUES (3, 'dropped')")
.await
.expect("事务内 INSERT 应成功");
drop(guard);
assert!(
recorder.snapshot().is_empty(),
"未提交即 drop,缓冲事件不应派发"
);
assert_eq!(
count_rows(&pool, "dropped").await,
0,
"级联回滚后事务内写入的行不应存在"
);
}
#[tokio::test(flavor = "multi_thread")]
async fn dispatch_order_is_fifo() {
let pool = setup_pool().await;
let recorder = Arc::new(RecordingListener::new());
let lm = manager_with(recorder.clone());
let mut guard = GarrisonEventTx::begin(&pool, lm)
.await
.expect("begin 应成功");
guard.on_commit(perm_event("p1"));
guard.on_commit(perm_event("p2"));
guard.on_commit(perm_event("p3"));
guard.commit().await.expect("commit 应成功");
assert_eq!(
recorder.snapshot(),
vec![
"perm:p1".to_string(),
"perm:p2".to_string(),
"perm:p3".to_string()
],
"派发顺序应与缓冲顺序一致(FIFO)"
);
}
#[tokio::test(flavor = "multi_thread")]
async fn concurrent_txs_no_crosstalk() {
let pool_a = setup_pool().await;
let pool_b = setup_pool().await;
let recorder_a = Arc::new(RecordingListener::new());
let recorder_b = Arc::new(RecordingListener::new());
let lm_a = manager_with(recorder_a.clone());
let lm_b = manager_with(recorder_b.clone());
let (outcome_a, outcome_b) = tokio::join!(
async {
let mut guard = GarrisonEventTx::begin(&pool_a, lm_a)
.await
.expect("begin a 应成功");
guard.on_commit(login_event("tx-a"));
guard
.execute("INSERT INTO garrison_event_tx_test (id, tag) VALUES (10, 'tx-a')")
.await
.expect("事务 a 内 INSERT 应成功");
guard.commit().await.expect("commit a 应成功")
},
async {
let mut guard = GarrisonEventTx::begin(&pool_b, lm_b)
.await
.expect("begin b 应成功");
guard.on_commit(login_event("tx-b"));
guard
.execute("INSERT INTO garrison_event_tx_test (id, tag) VALUES (11, 'tx-b')")
.await
.expect("事务 b 内 INSERT 应成功");
guard.commit().await.expect("commit b 应成功")
},
);
assert_eq!(
outcome_a.dispatched + outcome_a.failed,
1,
"guard a 派发事件总数应为 1"
);
assert_eq!(
outcome_b.dispatched + outcome_b.failed,
1,
"guard b 派发事件总数应为 1"
);
assert_eq!(
recorder_a.snapshot(),
vec!["login:tx-a".to_string()],
"listener a 应恰好收到 guard a 的事件"
);
assert_eq!(
recorder_b.snapshot(),
vec!["login:tx-b".to_string()],
"listener b 应恰好收到 guard b 的事件"
);
assert_eq!(count_rows(&pool_a, "tx-a").await, 1, "事务 a 写应可见");
assert_eq!(count_rows(&pool_b, "tx-b").await, 1, "事务 b 写应可见");
}
#[test]
fn garrison_event_tx_is_send_sync() {
fn assert_send_sync<T: Send + Sync>() {}
assert_send_sync::<GarrisonEventTx>();
}
#[test]
fn event_summary_names_all_variants_and_aggregates() {
let ctx = None;
#[cfg_attr(
not(any(feature = "anomalous-detector-dual", feature = "credit-metering")),
allow(unused_mut)
)]
let mut events: Vec<GarrisonEvent> = vec![
GarrisonEvent::Login {
login_id: "u".into(),
token: "t".into(),
device: None,
request_context: ctx.clone(),
},
GarrisonEvent::Logout {
login_id: "u".into(),
token: "t".into(),
request_context: ctx.clone(),
},
GarrisonEvent::Kickout {
login_id: "u".into(),
token: "t".into(),
reason: "r".into(),
request_context: ctx.clone(),
},
GarrisonEvent::PermissionCheck {
login_id: "u".into(),
permission: "p".into(),
request_context: ctx.clone(),
},
GarrisonEvent::RoleCheck {
login_id: "u".into(),
role: "r".into(),
request_context: ctx.clone(),
},
GarrisonEvent::TokenExpired {
token: "t".into(),
request_context: ctx.clone(),
},
GarrisonEvent::LoginFailure {
login_id: "u".into(),
reason: "invalid_credentials".into(),
request_context: ctx.clone(),
},
GarrisonEvent::PasswordRehashed {
login_id: "u".into(),
request_context: ctx.clone(),
},
GarrisonEvent::TokenRefresh {
login_id: "u".into(),
old_token: "o".into(),
new_token: "n".into(),
request_context: ctx.clone(),
},
GarrisonEvent::RevokeToken {
token: "t".into(),
request_context: ctx.clone(),
},
GarrisonEvent::SessionTimeout {
login_id: "u".into(),
token: "t".into(),
request_context: ctx.clone(),
},
GarrisonEvent::AccountLocked {
login_id: "u".into(),
reason: "r".into(),
request_context: ctx.clone(),
},
GarrisonEvent::FirewallBlock {
login_id: "u".into(),
reason: "r".into(),
request_context: ctx.clone(),
},
GarrisonEvent::Replaced {
login_id: "u".into(),
token: "t".into(),
reason: "r".into(),
request_context: ctx.clone(),
},
GarrisonEvent::ConfigReload {
config_version: 1,
request_context: ctx.clone(),
},
GarrisonEvent::SocialLogin {
provider: "wechat".into(),
user_id: "uid".into(),
login_id: None,
request_context: ctx.clone(),
},
GarrisonEvent::TenantSwitch {
login_id: "u".into(),
from_tenant: 1,
to_tenant: 2,
request_context: ctx.clone(),
},
GarrisonEvent::TokenRotate {
old_key: "o".into(),
new_key: "n".into(),
request_context: ctx.clone(),
},
GarrisonEvent::TempCredentialConsumed {
key: "k".into(),
value: "v".into(),
request_context: ctx.clone(),
},
GarrisonEvent::InvitationCreated {
code: "c".into(),
issuer_id: "i".into(),
},
GarrisonEvent::InvitationRedeemed {
code: "c".into(),
redeemer_id: "r".into(),
},
GarrisonEvent::InvitationRevoked {
code: "c".into(),
issuer_id: "i".into(),
},
GarrisonEvent::QrLoginCreated {
qr_id: "q".into(),
request_context: ctx.clone(),
},
GarrisonEvent::QrLoginScanned {
qr_id: "q".into(),
app_login_id: "u".into(),
request_context: ctx.clone(),
},
GarrisonEvent::QrLoginConfirmed {
qr_id: "q".into(),
app_login_id: "u".into(),
request_context: ctx.clone(),
},
GarrisonEvent::QrLoginCancelled {
qr_id: "q".into(),
app_login_id: "u".into(),
request_context: ctx.clone(),
},
GarrisonEvent::DeviceBlock {
login_id: "u".into(),
device: "d".into(),
request_context: ctx.clone(),
},
GarrisonEvent::DeviceUnblock {
login_id: "u".into(),
device: "d".into(),
request_context: ctx.clone(),
},
];
#[cfg(feature = "anomalous-detector-dual")]
events.push(GarrisonEvent::AnomalousLoginDetected {
login_id: "u".into(),
reason: "burst_login".into(),
detail: serde_json::json!({}),
timestamp: 1,
request_context: ctx.clone(),
});
#[cfg(feature = "credit-metering")]
events.extend([
GarrisonEvent::CreditConsumed {
tenant_id: 1,
resource: "r".into(),
cost: 1,
credits: 1,
total_consumed: 1,
request_context: ctx.clone(),
},
GarrisonEvent::CreditAlert {
tenant_id: 1,
threshold: 80,
usage_percent: 81.0,
total_consumed: 1,
credit_limit: 100,
request_context: ctx.clone(),
},
]);
let summary = event_summary(&events);
let expected_names = [
"Login",
"Logout",
"Kickout",
"PermissionCheck",
"RoleCheck",
"TokenExpired",
"LoginFailure",
"PasswordRehashed",
"TokenRefresh",
"RevokeToken",
"SessionTimeout",
"AccountLocked",
"FirewallBlock",
"Replaced",
"ConfigReload",
"SocialLogin",
"TenantSwitch",
"TokenRotate",
"TempCredentialConsumed",
"InvitationCreated",
"InvitationRedeemed",
"InvitationRevoked",
"QrLoginCreated",
"QrLoginScanned",
"QrLoginConfirmed",
"QrLoginCancelled",
"DeviceBlock",
"DeviceUnblock",
];
for name in expected_names {
assert!(
summary.contains(&format!("{name}=1")),
"摘要应含 {name}=1,实际: {summary}"
);
}
#[cfg(feature = "anomalous-detector-dual")]
assert!(
summary.contains("AnomalousLoginDetected=1"),
"摘要应含 AnomalousLoginDetected=1,实际: {summary}"
);
#[cfg(feature = "credit-metering")]
assert!(
summary.contains("CreditConsumed=1") && summary.contains("CreditAlert=1"),
"摘要应含 Credit 变体计数,实际: {summary}"
);
let repeated = vec![login_event("a"), login_event("b"), login_event("c")];
assert_eq!(event_summary(&repeated), "Login=3");
}
struct CollectLayer(Arc<Mutex<Vec<(String, String)>>>);
impl<S> tracing_subscriber::layer::Layer<S> for CollectLayer
where
S: tracing::Subscriber + for<'a> tracing_subscriber::registry::LookupSpan<'a>,
{
fn on_event(
&self,
event: &tracing::Event<'_>,
_ctx: tracing_subscriber::layer::Context<'_, S>,
) {
let level = event.metadata().level().to_string();
let mut rendered = String::new();
event.record(
&mut |field: &tracing::field::Field, value: &dyn std::fmt::Debug| {
rendered.push_str(&format!("{}={:?} ", field.name(), value));
},
);
self.0.lock().push((level, rendered));
}
}
fn init_capture(logs: &Arc<Mutex<Vec<(String, String)>>>) -> tracing::subscriber::DefaultGuard {
use tracing_subscriber::layer::SubscriberExt;
use tracing_subscriber::util::SubscriberInitExt;
let guard = tracing_subscriber::registry()
.with(CollectLayer(logs.clone()))
.set_default();
tracing::callsite::rebuild_interest_cache();
guard
}
#[tokio::test(flavor = "multi_thread")]
#[serial_test::serial]
async fn commit_failure_discards_events_with_warn() {
let pool = setup_pool().await;
let recorder = Arc::new(RecordingListener::new());
let lm = manager_with(recorder.clone());
let mut warn_captured = false;
for _ in 0..3 {
let logs: Arc<Mutex<Vec<(String, String)>>> = Arc::new(Mutex::new(Vec::new()));
let _capture = init_capture(&logs);
let mut guard = GarrisonEventTx::begin(&pool, lm.clone())
.await
.expect("begin 应成功");
guard.on_commit(login_event("4001"));
guard
.session
.as_ref()
.expect("session 应存在")
.commit()
.await
.expect("session 层预提交应成功");
let result = guard.commit().await;
assert!(
matches!(&result, Err(GarrisonError::Dao(msg)) if msg.contains("event-tx-commit")),
"session 层事务已被消费,guard.commit() 应返回 Dao 错误,实际: {result:?}"
);
let lines = logs.lock().clone();
if lines.iter().any(|(level, msg)| {
level == "WARN"
&& msg.contains("garrison-event-tx-discarded-after-commit-failure")
&& msg.contains("Login=1")
}) {
warn_captured = true;
break;
}
tracing::callsite::rebuild_interest_cache();
}
assert!(
warn_captured,
"commit 失败路径应产生 commit-failed 丢弃 warn(含事件类型摘要)"
);
assert!(
recorder.snapshot().is_empty(),
"commit 失败后缓冲事件不应派发"
);
}
#[tokio::test(flavor = "multi_thread")]
#[serial_test::serial]
async fn drop_without_commit_warns_with_event_summary() {
let pool = setup_pool().await;
let recorder = Arc::new(RecordingListener::new());
let lm = manager_with(recorder.clone());
let mut warn_captured = false;
for _ in 0..3 {
let logs: Arc<Mutex<Vec<(String, String)>>> = Arc::new(Mutex::new(Vec::new()));
let _capture = init_capture(&logs);
let mut guard = GarrisonEventTx::begin(&pool, lm.clone())
.await
.expect("begin 应成功");
guard.on_commit(login_event("5001"));
drop(guard);
let lines = logs.lock().clone();
if lines.iter().any(|(level, msg)| {
level == "WARN"
&& msg.contains("garrison-event-tx-dropped-without-commit")
&& msg.contains("Login=1")
}) {
warn_captured = true;
break;
}
tracing::callsite::rebuild_interest_cache();
}
assert!(
warn_captured,
"未 commit 即 drop 应产生 uncommitted 丢弃 warn(含事件类型摘要)"
);
assert!(
recorder.snapshot().is_empty(),
"未提交即 drop,缓冲事件不应派发"
);
}
#[tokio::test(flavor = "multi_thread")]
#[serial_test::serial]
async fn cancel_mid_dispatch_warns_with_dispatched_count() {
let pool = setup_pool().await;
let mut warn_captured = false;
for _ in 0..3 {
let logs: Arc<Mutex<Vec<(String, String)>>> = Arc::new(Mutex::new(Vec::new()));
let _capture = init_capture(&logs);
let (entered_tx, mut entered_rx) = tokio::sync::oneshot::channel();
let lm = manager_with(Arc::new(BlockingListener {
entered: Mutex::new(Some(entered_tx)),
}));
let mut guard = GarrisonEventTx::begin(&pool, lm)
.await
.expect("begin 应成功");
guard.on_commit(login_event("6001"));
let result =
tokio::time::timeout(std::time::Duration::from_secs(5), guard.commit()).await;
assert!(
result.is_err(),
"listener 永久挂起,commit 应被超时取消而非完成: {result:?}"
);
assert!(
matches!(entered_rx.try_recv(), Ok(())),
"取消应发生在 listener 进入 on_event(派发 await 点)之后"
);
let lines = logs.lock().clone();
if lines.iter().any(|(level, msg)| {
level == "WARN"
&& msg.contains("garrison-event-tx-dispatch-cancelled-after-commit")
&& (msg.contains("0 of 1") || msg.contains("0/1"))
&& msg.contains("Login=1")
}) {
warn_captured = true;
break;
}
tracing::callsite::rebuild_interest_cache();
}
assert!(
warn_captured,
"派发中途被取消应产生 dispatch-cancelled 丢弃 warn(含已派发/总数与摘要)"
);
}
}