Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions crates/bot/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ tracing = "0.1"
webpki-roots = "1"

[dev-dependencies]
crossbeam-channel = "0.5"
hyper = { version = "0.14", features = ["server", "http1", "tcp"] }
rcgen = { version = "0.14", default-features = false, features = ["ring"] }
tokio-tungstenite = { version = "0.30", default-features = false, features = ["handshake"] }
Expand Down
20 changes: 10 additions & 10 deletions crates/bot/src/automod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3503,8 +3503,8 @@ mod tests {
assert!(!engine.invite_allowed(&rule, "https://discord.gg/9007199254740993"));
}

#[test]
fn releasing_a_fired_ban_lets_the_next_message_select_it_again() {
#[tokio::test(start_paused = true)]
async fn releasing_a_fired_ban_lets_the_next_message_select_it_again() {
let engine = AutomodEngine::new();
let mut rules = HashMap::new();
rules.insert(
Expand Down Expand Up @@ -3535,7 +3535,7 @@ mod tests {
let cfg = CachedGuildConfig {
version: 1,
durable_version: 1,
loaded_at: Instant::now(),
loaded_at: tokio::time::Instant::now().into_std(),
settings: GuildSettings::default(),
rules,
commands: HashMap::new(),
Expand Down Expand Up @@ -4551,10 +4551,16 @@ mod tests {
open_case: true,
},
);
let path = std::env::temp_dir().join(format!(
"mention_unknown_{:032x}.db",
rand::random::<u128>()
));
let app =
BotState::new(Default::default(), crate::db::Db::open(&path, 2).unwrap()).unwrap();
let cfg = CachedGuildConfig {
version: 1,
durable_version: 1,
loaded_at: Instant::now(),
loaded_at: app.start,
settings: GuildSettings::default(),
rules,
commands: HashMap::new(),
Expand Down Expand Up @@ -4594,12 +4600,6 @@ mod tests {
assert!(pending.mention_permission_unknown);
assert_eq!(pending.action.action, "ban");

let path = std::env::temp_dir().join(format!(
"mention_unknown_{:032x}.db",
rand::random::<u128>()
));
let app =
BotState::new(Default::default(), crate::db::Db::open(&path, 2).unwrap()).unwrap();
assert!(
crate::db::claim_active_bot(
&app.db,
Expand Down
65 changes: 36 additions & 29 deletions crates/bot/src/cases.rs
Original file line number Diff line number Diff line change
Expand Up @@ -860,7 +860,7 @@ mod tests {
outcome: CaseOutcome::Succeeded,
subject_id: 99,
actor_id: Some(42),
occurred_at_ms: chrono::Utc::now().timestamp_millis().max(1),
occurred_at_ms: 1_700_000_000_000,
reason: Some("kick".into()),
evidence: CaseEvidence::Unavailable,
};
Expand Down Expand Up @@ -974,7 +974,7 @@ mod tests {
outcome: CaseOutcome::Succeeded,
subject_id: 99,
actor_id: Some(42),
occurred_at_ms: chrono::Utc::now().timestamp_millis().max(1),
occurred_at_ms: 1_700_000_000_000,
reason: Some("first".into()),
evidence: CaseEvidence::Unavailable,
};
Expand Down Expand Up @@ -1468,7 +1468,6 @@ mod tests {
)
.await
.unwrap();
tokio::time::sleep(std::time::Duration::from_millis(5)).await;
let attempt = begin_application_attempt(
&app,
Some(enrollment.clone()),
Expand Down Expand Up @@ -1627,41 +1626,49 @@ mod tests {

#[tokio::test]
async fn stalled_attempted_case_insert_does_not_delay_the_ban_and_settles_once() {
struct ClearStall;
impl Drop for ClearStall {
fn drop(&mut self) {
db::guild_data::set_case_record_stall(None);
}
}
let _clear = ClearStall;
let path =
std::env::temp_dir().join(format!("ban_stall_{:032x}.db", rand::random::<u128>()));
let app = BotState::new(Default::default(), db::Db::open(&path, 2).unwrap()).unwrap();
claim(&app, jmodguard::control::now_ms()).await;
let enrollment = db::enroll_guild(&app.db, 10, 100).await.unwrap().unwrap();
app.tenant.activate(enrollment.clone()).await.unwrap();
let operation = CaseId::new();
db::guild_data::set_case_record_stall(Some(format!("app:{}", operation.as_str())));
let started = std::time::Instant::now();
let attempt = begin_application_attempt(
&app,
Some(enrollment.clone()),
CaseAction::Ban,
99,
Some(42),
Some("raid".into()),
CaseEvidence::Unavailable,
operation.clone(),
)
.await
.unwrap();
assert!(
started.elapsed() < std::time::Duration::from_millis(1_400),
"the ban deadline must not wait for the stalled case insert"
let (entered, stalled) = tokio::sync::oneshot::channel();
let (release, resume) = std::sync::mpsc::channel();
let mut finished = db::guild_data::stall_next_case_record(
format!("app:{}", operation.as_str()),
move || {
let _ = entered.send(());
let _ = resume.recv();
},
);
let attempt = tokio::time::timeout(std::time::Duration::from_millis(1_400), async {
let (attempt, ()) = tokio::join!(
begin_application_attempt(
&app,
Some(enrollment.clone()),
CaseAction::Ban,
99,
Some(42),
Some("raid".into()),
CaseEvidence::Unavailable,
operation.clone(),
),
async {
stalled
.await
.expect("the attempted insert must reach the database");
}
);
attempt.unwrap()
})
.await
.expect("the ban deadline must expire with the insert still blocked");
assert!(matches!(attempt.record, super::AttemptRecord::Unconfirmed));
db::guild_data::set_case_record_stall(None);
tokio::time::sleep(std::time::Duration::from_millis(800)).await;
release.send(()).unwrap();
tokio::time::timeout(std::time::Duration::from_millis(800), finished.closed())
.await
.expect("the original insert must leave the database before settlement");
attempt.finish(&app, CaseOutcome::Succeeded).await.unwrap();
let cases = stored_cases(&app, enrollment).await;
assert_eq!(cases.len(), 1);
Expand Down
23 changes: 8 additions & 15 deletions crates/bot/src/commands/ban_expiry_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -196,9 +196,11 @@ async fn timed_ban_saves_its_deadline_before_moderation_log_delivery() {
false,
None,
);
let before = chrono::Utc::now().timestamp();
let outcome = run(&env).await;
let after = chrono::Utc::now().timestamp();
const NOW_SECS: i64 = 1_700_000_000;
let outcome = run_with_clock(&env, None, None, || {
chrono::DateTime::from_timestamp(NOW_SECS, 0).unwrap()
})
.await;
server.abort();
let _ = server.await;
let requests = requests.lock().unwrap().clone();
Expand Down Expand Up @@ -243,21 +245,15 @@ async fn timed_ban_saves_its_deadline_before_moderation_log_delivery() {
// An already recorded ban takes the new deadline; nothing new is logged.
assert_eq!(Some(active.0), observed);
let deadline = active.1.expect("deadline saved on the observed ban");
assert!(
(before + 3600..=after + 3600).contains(&deadline),
"deadline {deadline} outside [{before}, {after}] + 1h"
);
assert_eq!(deadline, NOW_SECS + 3600);
assert!(seen_at_log.lock().unwrap().is_empty(), "{requests:?}");
}
if scenario == "lagging" {
// The recorded ban was still the active row when the command
// recorded it again: the new row is that ban and takes the deadline.
assert_ne!(Some(active.0), observed);
let deadline = active.1.expect("deadline saved on the re-recorded ban");
assert!(
(before + 3600..=after + 3600).contains(&deadline),
"deadline {deadline} outside [{before}, {after}] + 1h"
);
assert_eq!(deadline, NOW_SECS + 3600);
assert_eq!(
*seen_at_log.lock().unwrap(),
[Some(deadline)],
Expand Down Expand Up @@ -291,10 +287,7 @@ async fn timed_ban_saves_its_deadline_before_moderation_log_delivery() {
let seen = seen_at_log.lock().unwrap().clone();
assert_eq!(seen.len(), 1, "one moderation log delivery: {requests:?}");
let deadline = seen[0].expect("deadline saved before log delivery");
assert!(
(before + 3600..=after + 3600).contains(&deadline),
"deadline {deadline} outside [{before}, {after}] + 1h"
);
assert_eq!(deadline, NOW_SECS + 3600);
drop(env);
drop(config);
drop(app);
Expand Down
61 changes: 39 additions & 22 deletions crates/bot/src/commands/behaviors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -210,6 +210,15 @@ pub(super) async fn run_with_userinfo_identity(
env: &CmdEnv<'_>,
userinfo_identity: Option<super::userinfo::InvocationIdentity>,
status_enrollment: Option<&db::GuildEnrollment>,
) -> Result<BehaviorOutcome> {
run_with_clock(env, userinfo_identity, status_enrollment, chrono::Utc::now).await
}

async fn run_with_clock(
env: &CmdEnv<'_>,
userinfo_identity: Option<super::userinfo::InvocationIdentity>,
status_enrollment: Option<&db::GuildEnrollment>,
now: fn() -> chrono::DateTime<chrono::Utc>,
) -> Result<BehaviorOutcome> {
let mut vars = behaviors_base_vars(env);
let enrollment = if skips_case_enrollment(&env.cmd.behavior) {
Expand Down Expand Up @@ -457,7 +466,7 @@ pub(super) async fn run_with_userinfo_identity(
enrollment,
ban,
target.get() as i64,
chrono::Utc::now().timestamp() + i64::from(minutes) * 60,
now().timestamp() + i64::from(minutes) * 60,
)
.await
}
Expand Down Expand Up @@ -2627,19 +2636,9 @@ mod tests {

#[tokio::test]
async fn stats_hanging_api_read_returns_within_fetch_timeout() {
use std::io::Read;
use std::net::TcpListener;
use std::time::Instant;

let listener = TcpListener::bind("127.0.0.1:0").unwrap();
use tokio::io::AsyncReadExt as _;
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
std::thread::spawn(move || {
for mut stream in listener.incoming().flatten() {
let mut buf = [0u8; 256];
while stream.read(&mut buf).unwrap_or(0) > 0 {}
}
});

let path = std::env::temp_dir().join(format!(
"stats_hanging_api_{:032x}.db",
rand::random::<u128>()
Expand All @@ -2649,14 +2648,28 @@ mod tests {
cfg.bot.read_target = addr.to_string();
cfg.bot.control_secret = jmodguard::config::ControlSecret::new("x".repeat(32));
let app = crate::state::BotState::new(cfg, db.clone()).unwrap();
let started = Instant::now();
let enrollment = db::enroll_guild(&app.db, 10, 100).await.unwrap().unwrap();
let text = stats_response(&app, &enrollment, 5).await.unwrap().0;
let elapsed = started.elapsed();
assert!(
elapsed
< jmodguard::read_link::STATS_FETCH_TIMEOUT + std::time::Duration::from_millis(150),
"stats waited {elapsed:?} for a hung API read"
let budget =
jmodguard::read_link::STATS_FETCH_TIMEOUT + std::time::Duration::from_millis(150);
let deadline = crossbeam_channel::after(budget);
let (_, (text, _)) = tokio::time::timeout(budget, async {
tokio::join!(
async {
let (mut stream, _) = listener.accept().await.unwrap();
let mut byte = [0];
stream.read_exact(&mut byte).await.unwrap();
stream
},
async { stats_response(&app, &enrollment, 5).await.unwrap() }
)
})
.await
.expect("stats must return while the API peer withholds its response");
// A final synchronous poll can finish late even when Tokio returns Ok.
assert_eq!(
deadline.try_recv(),
Err(crossbeam_channel::TryRecvError::Empty),
"stats returned after the fetch deadline"
);
assert!(
stats_field(&text, "Container use").contains("**API CPU:** `unavailable`"),
Expand All @@ -2673,13 +2686,17 @@ mod tests {

#[test]
fn status_does_not_wait_for_a_cpu_sample() {
let started = std::time::Instant::now();
let deadline = crossbeam_channel::after(std::time::Duration::from_millis(200));
let embed = crate::templates::stats_with_container_use(
crate::templates::stats_embed(0, Some(0), 0, 0, Some(&[]), 0),
&jmodguard::cgroup::latest_container_sample(),
None,
);
assert!(started.elapsed() < std::time::Duration::from_millis(200));
assert_eq!(
deadline.try_recv(),
Err(crossbeam_channel::TryRecvError::Empty),
"status must return without waiting for a CPU sample"
);
let text = stats_field(&embed, "Container use");
assert!(text.contains("**Bot CPU:** `unavailable`"), "{text}");
assert!(
Expand Down
Loading
Loading