Cleanup: one predicate property helper, a Windows-only allow, tolerant locks in the bots

predicate_property was the same fifteen lines in block_feature and
state_provider; it is worldgen::bound_property now. The mojang link helpers are
unix-only in use but worth testing everywhere, so they are allowed to look dead
elsewhere, which clears the launcher's -D warnings red on Windows. The bots
harness recovers from a poisoned lock instead of panicking.
This commit is contained in:
Alexander Krylov
2026-10-25 03:58:02 +03:00
parent 947d65e64d
commit c10261f008
5 changed files with 92 additions and 52 deletions
+69 -30
View File
@@ -329,7 +329,7 @@ fn read(
) {
use ids::play::clientbound as cb;
use ids::play::serverbound as sb;
let send = |body: Vec<u8>| writer.lock().unwrap().send(&body);
let send = |body: Vec<u8>| writer.lock().unwrap_or_else(|e| e.into_inner()).send(&body);
let mut seen = HashSet::new();
let mut batch = BatchSize::new();
let mut teleports = 0u64;
@@ -338,7 +338,7 @@ fn read(
Ok(packet) => packet,
Err(e) => {
if bot.online.swap(false, Ordering::SeqCst) {
*bot.error.lock().unwrap() = Some(e.to_string());
*bot.error.lock().unwrap_or_else(|e| e.into_inner()) = Some(e.to_string());
}
return;
}
@@ -356,7 +356,12 @@ fn read(
cb::LEVEL_CHUNK_WITH_LIGHT => {
bot.chunks.fetch_add(1, Ordering::Relaxed);
if let (Ok(x), Ok(z)) = (r.i32(), r.i32()) {
if !bot.held.lock().unwrap().insert((x, z)) {
if !bot
.held
.lock()
.unwrap_or_else(|e| e.into_inner())
.insert((x, z))
{
bot.resent.fetch_add(1, Ordering::Relaxed);
}
if seen.insert((x, z)) {
@@ -368,7 +373,11 @@ fn read(
cb::FORGET_LEVEL_CHUNK => {
if let Ok(play::Clientbound::ForgetLevelChunk(p)) =
play::Clientbound::decode(id, &body)
&& bot.held.lock().unwrap().remove(&(p.pos[0], p.pos[1]))
&& bot
.held
.lock()
.unwrap_or_else(|e| e.into_inner())
.remove(&(p.pos[0], p.pos[1]))
{
bot.forgotten.fetch_add(1, Ordering::Relaxed);
}
@@ -389,7 +398,7 @@ fn read(
}
cb::PLAYER_POSITION => match play::Clientbound::decode(id, &body) {
Ok(play::Clientbound::PlayerPosition(p)) => {
let mut at = bot.teleport.lock().unwrap();
let mut at = bot.teleport.lock().unwrap_or_else(|e| e.into_inner());
let previous = at.unwrap_or([0.0; 3]);
// Relative flags: X 1, Y 2, Z 4.
let pos: [f64; 3] = std::array::from_fn(|i| {
@@ -420,17 +429,18 @@ fn read(
},
cb::DISCONNECT | cb::START_CONFIGURATION => {
bot.online.store(false, Ordering::SeqCst);
*bot.error.lock().unwrap() = Some(if id == cb::DISCONNECT {
format!(
"disconnected: {}",
String::from_utf8_lossy(&body)
.chars()
.filter(|c| !c.is_control())
.collect::<String>()
)
} else {
"sent back to configuration".into()
});
*bot.error.lock().unwrap_or_else(|e| e.into_inner()) =
Some(if id == cb::DISCONNECT {
format!(
"disconnected: {}",
String::from_utf8_lossy(&body)
.chars()
.filter(|c| !c.is_control())
.collect::<String>()
)
} else {
"sent back to configuration".into()
});
return;
}
_ => Ok(()),
@@ -455,7 +465,7 @@ fn run_bot(
let connection = match join(&o, &name) {
Ok(c) => c,
Err(e) => {
*bot.error.lock().unwrap() = Some(e);
*bot.error.lock().unwrap_or_else(|e| e.into_inner()) = Some(e);
return;
}
};
@@ -469,12 +479,18 @@ fn run_bot(
use ids::play::serverbound as sb;
// Wait for the spawn position.
let spawn = loop {
if let Some(at) = *bot.teleport.lock().unwrap() {
if let Some(at) = *bot.teleport.lock().unwrap_or_else(|e| e.into_inner()) {
break at;
}
if !bot.online.load(Ordering::SeqCst) || asked.elapsed() > Duration::from_secs(60) {
if bot.error.lock().unwrap().is_none() {
*bot.error.lock().unwrap() = Some("no spawn position within 60 s".into());
if bot
.error
.lock()
.unwrap_or_else(|e| e.into_inner())
.is_none()
{
*bot.error.lock().unwrap_or_else(|e| e.into_inner()) =
Some("no spawn position within 60 s".into());
}
return;
}
@@ -482,7 +498,13 @@ fn run_bot(
};
bot.joined_after_ms
.store(asked.elapsed().as_millis() as u64, Ordering::SeqCst);
let send = |body: Vec<u8>| writer.lock().unwrap().send(&body).is_ok();
let send = |body: Vec<u8>| {
writer
.lock()
.unwrap_or_else(|e| e.into_inner())
.send(&body)
.is_ok()
};
send(raw(sb::PLAYER_LOADED, |_| {}));
let mut random = Random(o.seed ^ (index as u64).wrapping_mul(0x2545_F491_4F6C_DD1D));
let mut pos = spawn;
@@ -491,17 +513,30 @@ fn run_bot(
let mut target = pos;
let mut next = Instant::now();
loop {
if until.lock().unwrap().is_some_and(|u| Instant::now() >= u)
if until
.lock()
.unwrap_or_else(|e| e.into_inner())
.is_some_and(|u| Instant::now() >= u)
|| !bot.online.load(Ordering::SeqCst)
{
break;
}
// A teleport from the server wins over where the bot thought it was.
if let Some(at) = bot.teleport.lock().unwrap().take() {
if let Some(at) = bot
.teleport
.lock()
.unwrap_or_else(|e| e.into_inner())
.take()
{
pos = at;
}
let here = ((pos[0].floor() as i32) >> 4, (pos[2].floor() as i32) >> 4);
if !bot.held.lock().unwrap().contains(&here) {
if !bot
.held
.lock()
.unwrap_or_else(|e| e.into_inner())
.contains(&here)
{
bot.waited.fetch_add(1, Ordering::Relaxed);
} else if pos[1] < cruise {
pos[1] = (pos[1] + 0.5).min(cruise);
@@ -558,7 +593,7 @@ fn run_bot(
}
// Offline first, so the reader doesn't count the closed connection as a failure.
bot.online.store(false, Ordering::SeqCst);
writer.lock().unwrap().shutdown();
writer.lock().unwrap_or_else(|e| e.into_inner()).shutdown();
}
fn behaviour_of(mode: &str, index: usize) -> Behaviour {
@@ -614,11 +649,12 @@ fn main() {
};
let failed = bots
.iter()
.filter(|b| b.error.lock().unwrap().is_some())
.filter(|b| b.error.lock().unwrap_or_else(|e| e.into_inner()).is_some())
.count();
if first.is_none() && online > 0 {
first = Some(Instant::now());
*until.lock().unwrap() = Some(Instant::now() + Duration::from_secs(o.seconds));
*until.lock().unwrap_or_else(|e| e.into_inner()) =
Some(Instant::now() + Duration::from_secs(o.seconds));
}
println!(
"{}",
@@ -636,10 +672,13 @@ fn main() {
})
);
previous_chunks = chunks;
let over = until.lock().unwrap().is_some_and(|u| Instant::now() >= u);
let over = until
.lock()
.unwrap_or_else(|e| e.into_inner())
.is_some_and(|u| Instant::now() >= u);
let all_failed = failed == o.bots;
if over || all_failed || (first.is_none() && start.elapsed() > Duration::from_secs(120)) {
*until.lock().unwrap() = Some(Instant::now());
*until.lock().unwrap_or_else(|e| e.into_inner()) = Some(Instant::now());
break;
}
}
@@ -669,7 +708,7 @@ fn main() {
"forgotten": b.forgotten.load(Ordering::Relaxed),
"pulled_back": b.pulled_back.load(Ordering::Relaxed),
"waited_ticks": b.waited.load(Ordering::Relaxed),
"error": *b.error.lock().unwrap(),
"error": *b.error.lock().unwrap_or_else(|e| e.into_inner()),
})).collect::<Vec<_>>(),
});
if o.report.as_deref() == Some("-") {
+17
View File
@@ -103,6 +103,23 @@ impl std::fmt::Display for DecodeError {
}
}
impl std::error::Error for DecodeError {}
/// The bound value of one physical block property, for the two decode contexts that read
/// block predicates (`block_feature` and `state_provider`).
pub(crate) fn bound_property(
values: Option<&[crate::block_properties::BoundBlockProperty; 4]>,
property: crate::block_properties::BlockProperty,
) -> Result<crate::block_properties::BoundBlockProperty, DecodeError> {
use crate::block_properties::BlockProperty;
let values = values.ok_or(DecodeError::Field("predicate block property registry"))?;
let index = match property {
BlockProperty::Solid => 0,
BlockProperty::Replaceable => 1,
BlockProperty::Liquid => 2,
BlockProperty::SolidRender => 3,
};
Ok(values[index].clone())
}
impl From<serde_json::Error> for DecodeError {
fn from(value: serde_json::Error) -> Self {
Self::Json(value)
@@ -192,17 +192,7 @@ impl super::block_predicate::PredicateBlockResolver for FeatureBlockBindings<'_>
&self,
property: BlockProperty,
) -> Result<BoundBlockProperty, DecodeError> {
let values = self
.physical_properties
.as_ref()
.ok_or(DecodeError::Field("predicate block property registry"))?;
Ok(values[match property {
BlockProperty::Solid => 0,
BlockProperty::Replaceable => 1,
BlockProperty::Liquid => 2,
BlockProperty::SolidRender => 3,
}]
.clone())
super::bound_property(self.physical_properties.as_ref(), property)
}
fn predicate_biome_set(
&self,
@@ -186,17 +186,7 @@ impl PredicateBlockResolver for StateProviderBindings<'_> {
&self,
property: BlockProperty,
) -> Result<BoundBlockProperty, DecodeError> {
let values = self
.physical_properties
.as_ref()
.ok_or(DecodeError::Field("predicate block property registry"))?;
Ok(values[match property {
BlockProperty::Solid => 0,
BlockProperty::Replaceable => 1,
BlockProperty::Liquid => 2,
BlockProperty::SolidRender => 3,
}]
.clone())
super::bound_property(self.physical_properties.as_ref(), property)
}
fn predicate_biome_set(
&self,
+4
View File
@@ -181,12 +181,16 @@ pub fn java_runtime(
Ok(home)
}
// Used by the unix link step below; the path-traversal check itself is tested on every
// platform, so these stay compiled and are allowed to look unused elsewhere.
#[cfg_attr(not(unix), allow(dead_code))]
fn name_in<'a>(home: &Path, path: &'a Path) -> &'a Path {
path.strip_prefix(home).unwrap_or(path)
}
/// Whether a link at `link` (relative to the runtime's home) pointing at `target` stays in the
/// home.
#[cfg_attr(not(unix), allow(dead_code))]
fn link_stays_inside(link: &Path, target: &str) -> bool {
let mut depth = link.components().count().saturating_sub(1);
for c in Path::new(target).components() {