Skip to main content

ghast_ext/
executor.rs

1//! The tick-driven executor: [`Ext`] (a [`Behavior`]) polls async tasks inside
2//! [`Behavior::tick`], and [`Bot`] is the handle the tasks use.
3//!
4//! A task never holds the [`TickContext`]. It sends a closure ([`Bot::with`]) that the
5//! executor runs with the context during the same tick, then resumes the task with the
6//! result. So every action is still written inside the tick, before the tick's movement
7//! packet, in call order, and the crate needs no `unsafe`.
8
9use std::collections::{HashSet, VecDeque};
10use std::future::Future;
11use std::panic::{AssertUnwindSafe, catch_unwind};
12use std::pin::Pin;
13use std::sync::{Arc, Mutex, MutexGuard, Weak};
14use std::task::{Context, Poll, Wake, Waker};
15
16use ghast_client::{Behavior, GameMode, GameVersion, Health, Interests, Pose, TickContext, Vec3};
17
18use crate::Error;
19use crate::events::{Event, SubState};
20
21/// A closure run with the tick's context.
22pub(crate) type Request = Box<dyn FnOnce(&mut TickContext<'_>) + Send>;
23type BoxFuture<T> = Pin<Box<dyn Future<Output = T> + Send>>;
24type Factory = Box<dyn FnMut(Bot) -> BoxFuture<Result<(), Error>> + Send>;
25/// Gives a spawned task's handle [`Error::Panicked`].
26type PanicHook = Box<dyn FnOnce(String) + Send>;
27
28/// Most poll / request rounds in one tick (a task that loops on [`Bot::with`] without
29/// waiting for a tick cannot hang the tick).
30const MAX_ROUNDS: usize = 256;
31
32/// What the bot looked like at the start of this tick (cheap copies for sync reads).
33#[derive(Debug, Clone)]
34pub(crate) struct Snapshot {
35    pub(crate) version: GameVersion,
36    pub(crate) ctx_tick: u64,
37    pub(crate) pose: Pose,
38    pub(crate) sent: Pose,
39    pub(crate) eyes: Vec3,
40    pub(crate) health: Health,
41    pub(crate) world_time: Option<ghast_client::WorldTime>,
42    pub(crate) dead: bool,
43    pub(crate) game_mode: GameMode,
44    pub(crate) held_slot: u8,
45    pub(crate) open_window: Option<i32>,
46    pub(crate) entity_id: i32,
47    pub(crate) dimension: String,
48    pub(crate) held_cooldown: Option<ghast_client::cooldown::ItemCooldown>,
49}
50
51impl Snapshot {
52    fn empty() -> Self {
53        Snapshot {
54            version: GameVersion::V1_8_9,
55            ctx_tick: 0,
56            pose: Pose::default(),
57            sent: Pose::default(),
58            eyes: Vec3::default(),
59            health: Health::default(),
60            world_time: None,
61            dead: false,
62            game_mode: GameMode::Survival,
63            held_slot: 0,
64            open_window: None,
65            entity_id: 0,
66            dimension: String::new(),
67            held_cooldown: None,
68        }
69    }
70
71    fn refresh(&mut self, ctx: &TickContext<'_>) {
72        self.version = ctx.version();
73        self.ctx_tick = ctx.tick();
74        self.pose = *ctx.pose();
75        self.sent = *ctx.sent();
76        self.eyes = ctx.eyes(ctx.pose());
77        self.health = ctx.health();
78        self.world_time = ctx.world_time();
79        self.dead = ctx.is_dead();
80        self.game_mode = ctx.game_mode();
81        self.held_slot = ctx.held_slot();
82        self.open_window = ctx.open_window();
83        self.entity_id = ctx.entity_id();
84        // `None` at once while no item cools down
85        self.held_cooldown = ctx.held_cooldown();
86        if self.dimension != ctx.dimension() {
87            ctx.dimension().clone_into(&mut self.dimension);
88        }
89    }
90}
91
92/// State shared between the executor and the handles.
93pub(crate) struct Shared {
94    /// Session counter (a handle's futures fail once their session ended).
95    pub(crate) session: u64,
96    /// The session ended (reason), or none started yet.
97    pub(crate) closed: Option<String>,
98    /// Behaviour ticks of this session (frozen while the server is silent).
99    pub(crate) tick: u64,
100    pub(crate) snap: Snapshot,
101    pub(crate) requests: VecDeque<Request>,
102    pub(crate) tick_wakers: Vec<Waker>,
103    pub(crate) spawned: Vec<(u64, BoxFuture<()>, PanicHook)>,
104    pub(crate) aborted: Vec<u64>,
105    pub(crate) next_task: u64,
106    pub(crate) subs: Vec<Weak<Mutex<SubState>>>,
107    /// Teleports and deaths so far (helpers fail when these change under them).
108    pub(crate) teleports: u64,
109    pub(crate) deaths: u64,
110    /// Interests the helpers asked for on top of the configured ones.
111    pub(crate) extra_interests: Interests,
112    /// Entity ids seen last tick (only while someone listens to events).
113    entity_ids: Option<HashSet<i32>>,
114    pub(crate) interrupt_on_teleport: bool,
115}
116
117impl Shared {
118    fn new() -> Self {
119        Shared {
120            session: 0,
121            closed: Some("not started".into()),
122            tick: 0,
123            snap: Snapshot::empty(),
124            requests: VecDeque::new(),
125            tick_wakers: Vec::new(),
126            spawned: Vec::new(),
127            aborted: Vec::new(),
128            next_task: 1,
129            subs: Vec::new(),
130            teleports: 0,
131            deaths: 0,
132            extra_interests: Interests::NONE,
133            entity_ids: None,
134            interrupt_on_teleport: true,
135        }
136    }
137
138    fn wake_ticks(&mut self) {
139        for w in self.tick_wakers.drain(..) {
140            w.wake();
141        }
142    }
143
144    fn wake_subs(&mut self) {
145        self.subs.retain(|s| s.strong_count() > 0);
146        for s in &self.subs {
147            if let Some(s) = s.upgrade() {
148                let mut s = lock(&s);
149                if let Some(w) = s.waker.take() {
150                    w.wake();
151                }
152            }
153        }
154    }
155
156    /// Turns this tick's events into [`Event`]s for the subscribers.
157    fn publish(&mut self, ctx: &TickContext<'_>) {
158        self.subs.retain(|s| s.strong_count() > 0);
159        if self.subs.is_empty() {
160            self.entity_ids = None;
161            return;
162        }
163        let ev = ctx.events();
164        let mut out = Vec::new();
165        if ev.joined {
166            out.push(Event::Joined);
167        }
168        if ev.respawned {
169            out.push(Event::Respawned);
170        }
171        for t in &ev.teleports {
172            out.push(Event::Teleport(*t));
173        }
174        if ev.died {
175            out.push(Event::Died);
176        }
177        if ev.health_changed {
178            out.push(Event::Health(ctx.health()));
179        }
180        if ev.game_mode_changed {
181            out.push(Event::GameMode(ctx.game_mode()));
182        }
183        for m in &ev.chat {
184            out.push(Event::Chat(m.clone()));
185        }
186        if let Some(id) = ev.inventory.opened {
187            out.push(Event::WindowOpened(id));
188        }
189        if ev.inventory.closed {
190            out.push(Event::WindowClosed);
191        }
192        if ev.inventory.player_changed {
193            out.push(Event::InventoryChanged);
194        }
195        for c in &ev.inventory.clicks {
196            out.push(Event::Click(*c));
197        }
198        for (pos, raw) in &ev.block_updates {
199            out.push(Event::BlockUpdate {
200                pos: *pos,
201                raw: *raw,
202            });
203        }
204        for h in ev.hud() {
205            out.push(Event::Hud(h.clone()));
206        }
207        for t in ev.tab_completions() {
208            out.push(Event::TabComplete(t.clone()));
209        }
210        for s in ev.signs() {
211            out.push(Event::Sign(*s));
212        }
213        for s in ev.sleep() {
214            out.push(Event::Sleep(*s));
215        }
216        for f in ev.fishing() {
217            out.push(Event::Fishing(*f));
218        }
219        if let Some(es) = ctx.entities() {
220            let me = es.self_id();
221            let now: HashSet<i32> = es
222                .iter()
223                .map(|e| e.id())
224                .filter(|id| Some(*id) != me)
225                .collect();
226            if let Some(before) = &self.entity_ids {
227                for id in now.difference(before) {
228                    if let Some(e) = crate::find::entity_info(ctx, *id) {
229                        out.push(Event::EntitySpawned(e));
230                    }
231                }
232                for id in before.difference(&now) {
233                    out.push(Event::EntityGone(*id));
234                }
235            }
236            self.entity_ids = Some(now);
237        } else {
238            self.entity_ids = None;
239        }
240        if out.is_empty() {
241            return;
242        }
243        for s in &self.subs {
244            if let Some(s) = s.upgrade() {
245                let mut s = lock(&s);
246                s.queue.extend(out.iter().cloned());
247                if let Some(w) = s.waker.take() {
248                    w.wake();
249                }
250            }
251        }
252    }
253}
254
255/// Locks a mutex, ignoring poisoning (no lock is held while user code runs).
256pub(crate) fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
257    m.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
258}
259
260/// A handle to the bot for async tasks: cheap to clone, `Send + Sync`.
261///
262/// Reads of the per-tick snapshot ([`Bot::pose`], [`Bot::health`], ...) are synchronous.
263/// Everything that touches the world, the inventory or the server goes through
264/// [`Bot::with`] (or a helper built on it) and runs inside the tick.
265///
266/// Handles work best in tasks the [`Ext`] executor polls ([`Ext::new`], [`Bot::spawn`]):
267/// those resume within the same tick. A handle moved into a task of another executor (e.g.
268/// a tokio task reading stdin) works too, one tick later.
269#[derive(Clone)]
270pub struct Bot {
271    pub(crate) shared: Arc<Mutex<Shared>>,
272}
273
274impl std::fmt::Debug for Bot {
275    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
276        let s = lock(&self.shared);
277        f.debug_struct("Bot")
278            .field("session", &s.session)
279            .field("tick", &s.tick)
280            .field("pos", &s.snap.pose.pos)
281            .finish_non_exhaustive()
282    }
283}
284
285impl Bot {
286    fn new() -> Self {
287        Bot {
288            shared: Arc::new(Mutex::new(Shared::new())),
289        }
290    }
291
292    pub(crate) fn lock(&self) -> MutexGuard<'_, Shared> {
293        lock(&self.shared)
294    }
295
296    // ---- sync reads (start of this tick) ----
297
298    /// Ticks this behaviour ran in the current session (it does not advance while the
299    /// server is silent and the behaviour is on hold).
300    ///
301    /// ```no_run
302    /// # async fn f(bot: ghast_ext::Bot) {
303    /// let t = bot.tick();
304    /// bot.wait_ticks(20).await;
305    /// assert!(bot.tick() >= t + 20);
306    /// # }
307    /// ```
308    #[must_use]
309    pub fn tick(&self) -> u64 {
310        self.lock().tick
311    }
312
313    /// The protocol version of the session.
314    ///
315    /// ```no_run
316    /// # fn f(bot: ghast_ext::Bot) {
317    /// if bot.version() == ghast_client::GameVersion::V1_8_9 { /* ... */ }
318    /// # }
319    /// ```
320    #[must_use]
321    pub fn version(&self) -> GameVersion {
322        self.lock().snap.version
323    }
324
325    /// The client pose at the start of this tick.
326    ///
327    /// ```no_run
328    /// # fn f(bot: ghast_ext::Bot) {
329    /// let p = bot.pose().pos;
330    /// println!("at {:.1} {:.1} {:.1}", p.x, p.y, p.z);
331    /// # }
332    /// ```
333    #[must_use]
334    pub fn pose(&self) -> Pose {
335        self.lock().snap.pose
336    }
337
338    /// The pose the server has (the last movement packet): what it judges actions against.
339    ///
340    /// ```no_run
341    /// # fn f(bot: ghast_ext::Bot) {
342    /// let server_yaw = bot.sent().yaw;
343    /// # }
344    /// ```
345    #[must_use]
346    pub fn sent(&self) -> Pose {
347        self.lock().snap.sent
348    }
349
350    /// Eye position at the start of this tick.
351    ///
352    /// ```no_run
353    /// # fn f(bot: ghast_ext::Bot) {
354    /// let eyes = bot.eyes();
355    /// # }
356    /// ```
357    #[must_use]
358    pub fn eyes(&self) -> Vec3 {
359        self.lock().snap.eyes
360    }
361
362    /// Health, food and saturation.
363    ///
364    /// ```no_run
365    /// # fn f(bot: ghast_ext::Bot) {
366    /// if bot.health().food < 15 { /* eat */ }
367    /// # }
368    /// ```
369    #[must_use]
370    pub fn health(&self) -> Health {
371        self.lock().snap.health
372    }
373
374    /// The world's time at the start of this tick: game time and the dimension's time of day
375    /// (`None` before the server's first `update_time`).
376    ///
377    /// ```no_run
378    /// # fn f(bot: ghast_ext::Bot) {
379    /// let night = bot
380    ///     .world_time()
381    ///     .and_then(|t| t.time_of_day())
382    ///     .is_some_and(|t| (13_000..23_000).contains(&t));
383    /// # let _ = night;
384    /// # }
385    /// ```
386    #[must_use]
387    pub fn world_time(&self) -> Option<ghast_client::WorldTime> {
388        self.lock().snap.world_time
389    }
390
391    /// The player is dead (see [`Bot::respawn`]).
392    ///
393    /// ```no_run
394    /// # fn f(bot: ghast_ext::Bot) {
395    /// if bot.is_dead() { bot.respawn(); }
396    /// # }
397    /// ```
398    #[must_use]
399    pub fn is_dead(&self) -> bool {
400        self.lock().snap.dead
401    }
402
403    /// Game mode.
404    ///
405    /// ```no_run
406    /// # fn f(bot: ghast_ext::Bot) {
407    /// let creative = bot.game_mode() == ghast_client::GameMode::Creative;
408    /// # }
409    /// ```
410    #[must_use]
411    pub fn game_mode(&self) -> GameMode {
412        self.lock().snap.game_mode
413    }
414
415    /// The selected hotbar slot (0 … 8).
416    ///
417    /// ```no_run
418    /// # fn f(bot: ghast_ext::Bot) {
419    /// let slot = bot.held_slot();
420    /// # }
421    /// ```
422    #[must_use]
423    pub fn held_slot(&self) -> u8 {
424        self.lock().snap.held_slot
425    }
426
427    /// The cooldown of the held stack, while it cools down (1.9+: an ender pearl after a throw,
428    /// chorus fruit, a shield the server disabled, a 26.x `use_cooldown`; see
429    /// [`ghast_client::cooldown`]). A right click with it does nothing but its packets until
430    /// then. Always `None` on 1.8.9.
431    ///
432    /// ```no_run
433    /// # fn f(bot: ghast_ext::Bot) {
434    /// if let Some(c) = bot.held_cooldown() {
435    ///     println!("{} ticks left", c.ticks_left);
436    /// }
437    /// # }
438    /// ```
439    #[must_use]
440    pub fn held_cooldown(&self) -> Option<ghast_client::cooldown::ItemCooldown> {
441        self.lock().snap.held_cooldown.clone()
442    }
443
444    /// Waits until the held stack no longer cools down ([`Bot::held_cooldown`]; at once when
445    /// it does not).
446    ///
447    /// ```no_run
448    /// # async fn f(bot: ghast_ext::Bot) -> Result<(), ghast_ext::Error> {
449    /// bot.equip("ender_pearl").await?;
450    /// bot.wait_cooldown().await?;
451    /// bot.activate_item(); // thrown, not refused
452    /// # Ok(()) }
453    /// ```
454    pub async fn wait_cooldown(&self) -> Result<(), Error> {
455        self.wait_until(|ctx| ctx.held_cooldown().is_none()).await
456    }
457
458    /// Id of the open container window.
459    ///
460    /// ```no_run
461    /// # fn f(bot: ghast_ext::Bot) {
462    /// if bot.open_window().is_some() { /* a chest is open */ }
463    /// # }
464    /// ```
465    #[must_use]
466    pub fn open_window(&self) -> Option<i32> {
467        self.lock().snap.open_window
468    }
469
470    /// Our entity id.
471    ///
472    /// ```no_run
473    /// # fn f(bot: ghast_ext::Bot) {
474    /// let me = bot.entity_id();
475    /// # }
476    /// ```
477    #[must_use]
478    pub fn entity_id(&self) -> i32 {
479        self.lock().snap.entity_id
480    }
481
482    /// The current dimension (`"0"` / `"-1"` / `"1"` on 1.8, the world name on 1.16).
483    ///
484    /// ```no_run
485    /// # fn f(bot: ghast_ext::Bot) {
486    /// let nether = bot.dimension() == "-1";
487    /// # }
488    /// ```
489    #[must_use]
490    pub fn dimension(&self) -> String {
491        self.lock().snap.dimension.clone()
492    }
493
494    // ---- the tick context ----
495
496    /// Runs `f` with this tick's [`TickContext`] and returns its result. From a task the
497    /// [`Ext`] executor polls, `f` runs in the same tick (before the movement packet), so
498    /// several `with` calls in a row cost no ticks. Actions inside `f` follow the usual
499    /// rules (`set_aim` only for this tick, aim first and act on a later tick, ...).
500    ///
501    /// A panic in `f` resumes in the awaiting task. Fails with [`Error::Disconnected`] once
502    /// the session ended.
503    ///
504    /// ```no_run
505    /// # async fn f(bot: ghast_ext::Bot) -> Result<(), ghast_ext::Error> {
506    /// let (stone, raw) = bot
507    ///     .with(|ctx| {
508    ///         let p = ghast_client::BlockPos::new(0, 63, 0);
509    ///         (ctx.world().raw_block(p.x, p.y, p.z), ctx.broken())
510    ///     })
511    ///     .await?;
512    /// # Ok(()) }
513    /// ```
514    pub fn with<R, F>(&self, f: F) -> With<R>
515    where
516        R: Send + 'static,
517        F: FnOnce(&mut TickContext<'_>) -> R + Send + 'static,
518    {
519        let slot = Arc::new(Mutex::new(WithSlot {
520            result: None,
521            waker: None,
522            dropped: false,
523        }));
524        let mut guard = DropWake(Some(slot.clone()));
525        let req: Request = Box::new(move |ctx| {
526            let r = catch_unwind(AssertUnwindSafe(|| f(ctx)));
527            // Ran: the guard gives up its slot handle (it must still be released, or every
528            // request leaks its slot with the result's space).
529            if let Some(slot) = guard.0.take() {
530                let mut s = lock(&slot);
531                s.result = Some(r);
532                if let Some(w) = s.waker.take() {
533                    w.wake();
534                }
535            }
536        });
537        With {
538            bot: self.clone(),
539            session: self.lock().session,
540            req: Some(req),
541            slot,
542        }
543    }
544
545    /// Queues `f` for this tick (or the next one) without waiting for it: requests run in
546    /// the order they were made. For fire-and-forget actions.
547    ///
548    /// ```no_run
549    /// # fn f(bot: ghast_ext::Bot) {
550    /// bot.act(|ctx| ctx.swing());
551    /// # }
552    /// ```
553    pub fn act<F>(&self, f: F)
554    where
555        F: FnOnce(&mut TickContext<'_>) + Send + 'static,
556    {
557        let mut s = self.lock();
558        if s.closed.is_none() {
559            s.requests.push_back(Box::new(f));
560        }
561    }
562
563    /// Waits `n` behaviour ticks (`0` returns at once). Resolves at once when the session
564    /// ended.
565    ///
566    /// ```no_run
567    /// # async fn f(bot: ghast_ext::Bot) {
568    /// bot.wait_ticks(20).await; // one second
569    /// # }
570    /// ```
571    pub fn wait_ticks(&self, n: u64) -> WaitTicks {
572        let s = self.lock();
573        WaitTicks {
574            bot: self.clone(),
575            session: s.session,
576            until: s.tick + n,
577        }
578    }
579
580    /// Waits for the next tick.
581    ///
582    /// ```no_run
583    /// # async fn f(bot: ghast_ext::Bot) {
584    /// loop {
585    ///     if bot.health().health < 10.0 { break; }
586    ///     bot.next_tick().await;
587    /// }
588    /// # }
589    /// ```
590    pub fn next_tick(&self) -> WaitTicks {
591        self.wait_ticks(1)
592    }
593
594    /// Waits about `d` of game time, in whole ticks (50 ms each, rounded up).
595    ///
596    /// ```no_run
597    /// # async fn f(bot: ghast_ext::Bot) {
598    /// bot.sleep(std::time::Duration::from_secs(2)).await;
599    /// # }
600    /// ```
601    pub fn sleep(&self, d: std::time::Duration) -> WaitTicks {
602        let ms = d.as_millis();
603        self.wait_ticks(u64::try_from(ms.div_ceil(50)).unwrap_or(u64::MAX))
604    }
605
606    /// Runs `fut` and gives up after `ticks` ticks with [`Error::Timeout`] (`fut` is dropped,
607    /// which cancels it; helpers release their buttons when dropped).
608    ///
609    /// ```no_run
610    /// # async fn f(bot: ghast_ext::Bot) -> Result<(), ghast_ext::Error> {
611    /// let pos = ghast_client::BlockPos::new(3, 64, 0);
612    /// bot.timeout(200, bot.dig(pos)).await??;
613    /// # Ok(()) }
614    /// ```
615    pub fn timeout<F: Future>(&self, ticks: u64, fut: F) -> Timeout<F> {
616        Timeout {
617            fut: Box::pin(fut),
618            wait: self.wait_ticks(ticks),
619        }
620    }
621
622    /// Waits until `cond` holds, checked once per tick with the tick's context (also at
623    /// once).
624    ///
625    /// ```no_run
626    /// # async fn f(bot: ghast_ext::Bot) -> Result<(), ghast_ext::Error> {
627    /// bot.wait_until(|ctx| ctx.pose().on_ground).await?;
628    /// # Ok(()) }
629    /// ```
630    pub async fn wait_until<F>(&self, cond: F) -> Result<(), Error>
631    where
632        F: Fn(&TickContext<'_>) -> bool + Send + Sync + 'static,
633    {
634        let cond = Arc::new(cond);
635        loop {
636            let c = cond.clone();
637            if self.with(move |ctx| c(ctx)).await? {
638                return Ok(());
639            }
640            self.next_tick().await;
641        }
642    }
643
644    /// Runs `fut` as another task of this bot (polled by the same executor, inside the
645    /// ticks). It is cancelled when the session ends. The handle gives its result.
646    ///
647    /// ```no_run
648    /// # async fn f(bot: ghast_ext::Bot) {
649    /// let b = bot.clone();
650    /// let guard = bot.spawn(async move {
651    ///     loop {
652    ///         if b.is_dead() { b.respawn(); }
653    ///         b.wait_ticks(20).await;
654    ///     }
655    /// });
656    /// // ... later
657    /// guard.abort();
658    /// # }
659    /// ```
660    pub fn spawn<T, F>(&self, fut: F) -> JoinHandle<T>
661    where
662        T: Send + 'static,
663        F: Future<Output = T> + Send + 'static,
664    {
665        let slot = Arc::new(Mutex::new(JoinSlot {
666            result: None,
667            waker: None,
668        }));
669        let done = Completer(slot.clone());
670        let on_panic = slot.clone();
671        let hook: PanicHook = Box::new(move |msg| {
672            let mut s = lock(&on_panic);
673            // Unset, or the placeholder the completer left while unwinding.
674            if s.result.is_none()
675                || matches!(&s.result, Some(Err(Error::Panicked(m))) if m.is_empty())
676            {
677                s.result = Some(Err(Error::Panicked(msg)));
678                if let Some(w) = s.waker.take() {
679                    w.wake();
680                }
681            }
682        });
683        let wrapped = async move {
684            let v = fut.await;
685            done.complete(Ok(v));
686        };
687        let mut s = self.lock();
688        let id = s.next_task;
689        s.next_task += 1;
690        if s.closed.is_some() {
691            drop(s);
692            lock(&slot).result = Some(Err(Error::Disconnected));
693        } else {
694            s.spawned.push((id, Box::pin(wrapped), hook));
695        }
696        JoinHandle {
697            bot: self.clone(),
698            id,
699            slot,
700        }
701    }
702
703    /// Asks the helpers' packet groups on top of the configured [`Ext::interests`] (e.g.
704    /// [`Interests::ENTITIES`] for entity helpers). Better set up front with
705    /// [`Ext::interests`]: a tracker started late misses entities that already exist.
706    ///
707    /// ```no_run
708    /// # fn f(bot: ghast_ext::Bot) {
709    /// bot.require(ghast_client::Interests::BLOCK_UPDATES);
710    /// # }
711    /// ```
712    pub fn require(&self, interests: Interests) {
713        let mut s = self.lock();
714        s.extra_interests |= interests;
715    }
716
717    /// The point where helpers that must not survive a teleport or a death started.
718    pub(crate) fn mark(&self) -> Mark {
719        let s = self.lock();
720        Mark {
721            teleports: s.teleports,
722            deaths: s.deaths,
723        }
724    }
725
726    /// Fails when the player was teleported (if [`Ext::interrupt_on_teleport`]) or died
727    /// since `m`.
728    pub(crate) fn check(&self, m: Mark) -> Result<(), Error> {
729        let s = self.lock();
730        if s.closed.is_some() {
731            return Err(Error::Disconnected);
732        }
733        if s.deaths != m.deaths {
734            return Err(Error::Died);
735        }
736        if s.interrupt_on_teleport && s.teleports != m.teleports {
737            return Err(Error::Teleported);
738        }
739        Ok(())
740    }
741
742    /// Like [`Bot::check`] without the teleport check (a helper whose own action makes the
743    /// server teleport the player, e.g. getting off a vehicle).
744    pub(crate) fn check_alive(&self, m: Mark) -> Result<(), Error> {
745        let s = self.lock();
746        if s.closed.is_some() {
747            return Err(Error::Disconnected);
748        }
749        if s.deaths != m.deaths {
750            return Err(Error::Died);
751        }
752        Ok(())
753    }
754}
755
756/// Teleport / death counters at a helper's start.
757#[derive(Debug, Clone, Copy)]
758pub(crate) struct Mark {
759    teleports: u64,
760    deaths: u64,
761}
762
763struct WithSlot<R> {
764    result: Option<std::thread::Result<R>>,
765    waker: Option<Waker>,
766    /// The request was dropped without running (the session ended).
767    dropped: bool,
768}
769
770/// Wakes the waiting future when a request is dropped without running.
771struct DropWake<R>(Option<Arc<Mutex<WithSlot<R>>>>);
772
773impl<R> Drop for DropWake<R> {
774    fn drop(&mut self) {
775        if let Some(slot) = self.0.take() {
776            let mut s = lock(&slot);
777            s.dropped = true;
778            if let Some(w) = s.waker.take() {
779                w.wake();
780            }
781        }
782    }
783}
784
785/// The future of [`Bot::with`].
786#[must_use = "futures do nothing unless awaited"]
787pub struct With<R> {
788    bot: Bot,
789    session: u64,
790    req: Option<Request>,
791    slot: Arc<Mutex<WithSlot<R>>>,
792}
793
794impl<R> std::fmt::Debug for With<R> {
795    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
796        f.debug_struct("With")
797            .field("sent", &self.req.is_none())
798            .finish()
799    }
800}
801
802impl<R> Future for With<R> {
803    type Output = Result<R, Error>;
804
805    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
806        let this = &mut *self;
807        if let Some(req) = this.req.take() {
808            let mut s = this.bot.lock();
809            if s.closed.is_some() || s.session != this.session {
810                return Poll::Ready(Err(Error::Disconnected));
811            }
812            lock(&this.slot).waker = Some(cx.waker().clone());
813            s.requests.push_back(req);
814            return Poll::Pending;
815        }
816        let mut slot = lock(&this.slot);
817        match slot.result.take() {
818            Some(Ok(v)) => Poll::Ready(Ok(v)),
819            Some(Err(panic)) => {
820                drop(slot);
821                std::panic::resume_unwind(panic)
822            }
823            None if slot.dropped => Poll::Ready(Err(Error::Disconnected)),
824            None => {
825                slot.waker = Some(cx.waker().clone());
826                Poll::Pending
827            }
828        }
829    }
830}
831
832/// The future of [`Bot::wait_ticks`].
833#[must_use = "futures do nothing unless awaited"]
834#[derive(Debug)]
835pub struct WaitTicks {
836    bot: Bot,
837    session: u64,
838    until: u64,
839}
840
841impl Future for WaitTicks {
842    type Output = ();
843
844    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
845        let mut s = self.bot.lock();
846        if s.closed.is_some() || s.session != self.session || s.tick >= self.until {
847            return Poll::Ready(());
848        }
849        if !s.tick_wakers.iter().any(|w| w.will_wake(cx.waker())) {
850            s.tick_wakers.push(cx.waker().clone());
851        }
852        Poll::Pending
853    }
854}
855
856/// The future of [`Bot::timeout`].
857#[must_use = "futures do nothing unless awaited"]
858pub struct Timeout<F> {
859    fut: Pin<Box<F>>,
860    wait: WaitTicks,
861}
862
863impl<F> std::fmt::Debug for Timeout<F> {
864    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
865        f.debug_struct("Timeout")
866            .field("until", &self.wait.until)
867            .finish()
868    }
869}
870
871impl<F: Future> Future for Timeout<F> {
872    type Output = Result<F::Output, Error>;
873
874    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
875        let this = self.get_mut();
876        if let Poll::Ready(v) = this.fut.as_mut().poll(cx) {
877            return Poll::Ready(Ok(v));
878        }
879        let closed = {
880            let s = this.wait.bot.lock();
881            s.closed.is_some() || s.session != this.wait.session
882        };
883        match Pin::new(&mut this.wait).poll(cx) {
884            Poll::Ready(()) if closed => Poll::Ready(Err(Error::Disconnected)),
885            Poll::Ready(()) => Poll::Ready(Err(Error::Timeout)),
886            Poll::Pending => Poll::Pending,
887        }
888    }
889}
890
891struct JoinSlot<T> {
892    result: Option<Result<T, Error>>,
893    waker: Option<Waker>,
894}
895
896/// Completes a [`JoinHandle`]; when dropped unfinished (the task was cancelled or
897/// panicked) the handle gets [`Error::Cancelled`].
898struct Completer<T>(Arc<Mutex<JoinSlot<T>>>);
899
900impl<T> Completer<T> {
901    fn complete(self, r: Result<T, Error>) {
902        let mut s = lock(&self.0);
903        s.result = Some(r);
904        if let Some(w) = s.waker.take() {
905            w.wake();
906        }
907    }
908}
909
910impl<T> Drop for Completer<T> {
911    fn drop(&mut self) {
912        let mut s = lock(&self.0);
913        if s.result.is_none() {
914            // Dropped while the task unwinds: the executor's panic hook fills in the message.
915            s.result = Some(Err(if std::thread::panicking() {
916                Error::Panicked(String::new())
917            } else {
918                Error::Cancelled
919            }));
920            if let Some(w) = s.waker.take() {
921                w.wake();
922            }
923        }
924    }
925}
926
927/// A spawned task ([`Bot::spawn`]): await it for its result, or [`JoinHandle::abort`] it.
928/// Dropping the handle does not stop the task.
929#[must_use = "dropping the handle detaches the task"]
930pub struct JoinHandle<T> {
931    bot: Bot,
932    id: u64,
933    slot: Arc<Mutex<JoinSlot<T>>>,
934}
935
936impl<T> std::fmt::Debug for JoinHandle<T> {
937    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
938        f.debug_struct("JoinHandle").field("id", &self.id).finish()
939    }
940}
941
942impl<T> JoinHandle<T> {
943    /// Stops the task at the next tick (it is dropped, which cancels what it awaits).
944    ///
945    /// ```no_run
946    /// # async fn f(bot: ghast_ext::Bot) {
947    /// let h = bot.spawn(async {});
948    /// h.abort();
949    /// # }
950    /// ```
951    pub fn abort(&self) {
952        self.bot.lock().aborted.push(self.id);
953    }
954
955    /// Whether the task finished (or was cancelled).
956    ///
957    /// ```no_run
958    /// # async fn f(bot: ghast_ext::Bot) {
959    /// let h = bot.spawn(async {});
960    /// bot.next_tick().await;
961    /// assert!(h.is_finished());
962    /// # }
963    /// ```
964    #[must_use]
965    pub fn is_finished(&self) -> bool {
966        lock(&self.slot).result.is_some()
967    }
968}
969
970impl<T> Future for JoinHandle<T> {
971    type Output = Result<T, Error>;
972
973    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
974        let mut s = lock(&self.slot);
975        match s.result.take() {
976            Some(r) => Poll::Ready(r),
977            None => {
978                s.waker = Some(cx.waker().clone());
979                Poll::Pending
980            }
981        }
982    }
983}
984
985/// Wakes a task of the executor: queues its id.
986struct TaskWaker {
987    id: u64,
988    ready: Arc<Mutex<Vec<u64>>>,
989}
990
991impl Wake for TaskWaker {
992    fn wake(self: Arc<Self>) {
993        lock(&self.ready).push(self.id);
994    }
995
996    fn wake_by_ref(self: &Arc<Self>) {
997        lock(&self.ready).push(self.id);
998    }
999}
1000
1001struct Task {
1002    id: u64,
1003    fut: BoxFuture<()>,
1004    waker: Waker,
1005    on_panic: Option<PanicHook>,
1006}
1007
1008/// What [`Ext`] does when the main task returns.
1009#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1010#[non_exhaustive]
1011pub enum WhenDone {
1012    /// End the session (`SessionEnd::Quit` with "done", or the error). The default: the
1013    /// main task is the bot's `main`.
1014    #[default]
1015    Disconnect,
1016    /// Keep the session: other spawned tasks go on; once none are left the behaviour
1017    /// finishes and the player stands and answers the server.
1018    Stay,
1019}
1020
1021/// A [`Behavior`] that runs async tasks inside the ticks: write a bot as sequential code.
1022///
1023/// Each session (each `Client::run`), the factory is called with a fresh [`Bot`] handle on
1024/// the first tick and its future becomes the main task. Every tick the executor polls the
1025/// tasks that are ready and runs the closures they sent ([`Bot::with`]) with the tick's
1026/// context, until no task can make progress in this tick. When the session ends all tasks
1027/// are dropped (cancelled).
1028///
1029/// ```no_run
1030/// use ghast_client::{Account, Client, GameVersion, Interests};
1031/// use ghast_ext::Ext;
1032///
1033/// # async fn run() -> Result<(), Box<dyn std::error::Error>> {
1034/// let mut bot = Ext::new(|bot| async move {
1035///     bot.chat("hello");
1036///     let msg = bot.wait_for_chat(|m| m.plain().contains("bye")).await?;
1037///     println!("{}", msg.plain());
1038///     Ok(())
1039/// })
1040/// .interests(Interests::CHAT);
1041/// let client = Client::new("localhost:25565".parse()?, GameVersion::V1_8_9, Account::offline("Bot")?);
1042/// client.run(&mut bot).await?;
1043/// # Ok(()) }
1044/// ```
1045pub struct Ext {
1046    name: String,
1047    factory: Factory,
1048    interests: Interests,
1049    when_done: WhenDone,
1050    auto_respawn: bool,
1051    interrupt_on_teleport: bool,
1052    bot: Bot,
1053    tasks: Vec<Task>,
1054    ready: Arc<Mutex<Vec<u64>>>,
1055    main: Option<JoinHandle<Result<(), Error>>>,
1056    result: Option<Result<(), Error>>,
1057    finished: bool,
1058    started: bool,
1059}
1060
1061impl std::fmt::Debug for Ext {
1062    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1063        f.debug_struct("Ext")
1064            .field("name", &self.name)
1065            .field("tasks", &self.tasks.len())
1066            .field("result", &self.result)
1067            .finish_non_exhaustive()
1068    }
1069}
1070
1071impl Ext {
1072    /// A behaviour whose main task is `main(bot)`, called once per session.
1073    ///
1074    /// ```no_run
1075    /// let ext = ghast_ext::Ext::new(|bot| async move {
1076    ///     bot.wait_ticks(100).await;
1077    ///     Ok(())
1078    /// });
1079    /// ```
1080    pub fn new<F, Fut>(mut main: F) -> Self
1081    where
1082        F: FnMut(Bot) -> Fut + Send + 'static,
1083        Fut: Future<Output = Result<(), Error>> + Send + 'static,
1084    {
1085        Ext {
1086            name: "ext".into(),
1087            factory: Box::new(move |bot| Box::pin(main(bot))),
1088            interests: Interests::CHAT,
1089            when_done: WhenDone::Disconnect,
1090            auto_respawn: false,
1091            interrupt_on_teleport: true,
1092            bot: Bot::new(),
1093            tasks: Vec::new(),
1094            ready: Arc::new(Mutex::new(Vec::new())),
1095            main: None,
1096            result: None,
1097            finished: false,
1098            started: false,
1099        }
1100    }
1101
1102    /// Name for logs (default `"ext"`).
1103    ///
1104    /// ```no_run
1105    /// # let ext = ghast_ext::Ext::new(|_bot| async { Ok(()) });
1106    /// let ext = ext.name("miner");
1107    /// ```
1108    #[must_use]
1109    pub fn name(mut self, name: impl Into<String>) -> Self {
1110        self.name = name.into();
1111        self
1112    }
1113
1114    /// Packet groups to decode (default [`Interests::CHAT`]). Entity helpers need
1115    /// [`Interests::ENTITIES`] (player names also [`Interests::PLAYER_LIST`]),
1116    /// [`crate::Event::BlockUpdate`] needs [`Interests::BLOCK_UPDATES`].
1117    ///
1118    /// ```no_run
1119    /// use ghast_client::Interests;
1120    /// # let ext = ghast_ext::Ext::new(|_bot| async { Ok(()) });
1121    /// let ext = ext.interests(Interests::CHAT | Interests::ENTITIES | Interests::PLAYER_LIST);
1122    /// ```
1123    #[must_use]
1124    pub fn interests(mut self, interests: Interests) -> Self {
1125        self.interests = interests;
1126        self
1127    }
1128
1129    /// What happens when the main task returns (default [`WhenDone::Disconnect`]).
1130    ///
1131    /// ```no_run
1132    /// # let ext = ghast_ext::Ext::new(|_bot| async { Ok(()) });
1133    /// let ext = ext.when_done(ghast_ext::WhenDone::Stay);
1134    /// ```
1135    #[must_use]
1136    pub fn when_done(mut self, when: WhenDone) -> Self {
1137        self.when_done = when;
1138        self
1139    }
1140
1141    /// Respawn at once after a death (default off: helpers fail with [`Error::Died`] and the
1142    /// task decides).
1143    ///
1144    /// ```no_run
1145    /// # let ext = ghast_ext::Ext::new(|_bot| async { Ok(()) });
1146    /// let ext = ext.auto_respawn(true);
1147    /// ```
1148    #[must_use]
1149    pub fn auto_respawn(mut self, on: bool) -> Self {
1150        self.auto_respawn = on;
1151        self
1152    }
1153
1154    /// Whether running helpers (look, dig, place, walk, ...) fail with
1155    /// [`Error::Teleported`] when the server teleports the player (default on: after a
1156    /// setback the plan they made is stale).
1157    ///
1158    /// ```no_run
1159    /// # let ext = ghast_ext::Ext::new(|_bot| async { Ok(()) });
1160    /// let ext = ext.interrupt_on_teleport(false);
1161    /// ```
1162    #[must_use]
1163    pub fn interrupt_on_teleport(mut self, on: bool) -> Self {
1164        self.interrupt_on_teleport = on;
1165        self
1166    }
1167
1168    /// A handle to the bot (the same one the tasks get), e.g. for a task of another
1169    /// executor that sends chat lines.
1170    ///
1171    /// ```no_run
1172    /// # let ext = ghast_ext::Ext::new(|_bot| async { Ok(()) });
1173    /// let bot = ext.bot();
1174    /// std::thread::spawn(move || bot.act(|ctx| ctx.chat("from another thread")));
1175    /// ```
1176    #[must_use]
1177    pub fn bot(&self) -> Bot {
1178        self.bot.clone()
1179    }
1180
1181    /// The main task's result in the last session (`None` while running or if it never
1182    /// finished).
1183    ///
1184    /// ```no_run
1185    /// # let ext = ghast_ext::Ext::new(|_bot| async { Ok(()) });
1186    /// if let Some(Err(e)) = ext.result() { eprintln!("bot failed: {e}"); }
1187    /// ```
1188    #[must_use]
1189    pub fn result(&self) -> Option<&Result<(), Error>> {
1190        self.result.as_ref()
1191    }
1192
1193    fn begin_session(&mut self, ctx: &TickContext<'_>) {
1194        self.tasks.clear();
1195        lock(&self.ready).clear();
1196        self.result = None;
1197        self.finished = false;
1198        {
1199            let mut s = self.bot.lock();
1200            s.session += 1;
1201            s.closed = None;
1202            s.tick = 0;
1203            s.requests.clear();
1204            s.spawned.clear();
1205            s.aborted.clear();
1206            s.teleports = 0;
1207            s.deaths = 0;
1208            s.interrupt_on_teleport = self.interrupt_on_teleport;
1209            s.snap.refresh(ctx);
1210        }
1211        let fut = (self.factory)(self.bot.clone());
1212        self.main = Some(self.bot.spawn(fut));
1213    }
1214
1215    fn end_session(&mut self, reason: &str) {
1216        let mut s = self.bot.lock();
1217        s.closed = Some(reason.to_owned());
1218        let reqs: Vec<Request> = s.requests.drain(..).collect();
1219        let spawned = std::mem::take(&mut s.spawned);
1220        s.wake_ticks();
1221        s.wake_subs();
1222        drop(s);
1223        // Dropped outside the lock: their guards wake the waiters.
1224        drop(reqs);
1225        drop(spawned);
1226        self.tasks.clear();
1227    }
1228
1229    /// Polls ready tasks and runs their requests until nothing moves in this tick.
1230    fn run(&mut self, ctx: &mut TickContext<'_>) {
1231        for _ in 0..MAX_ROUNDS {
1232            // New tasks are ready at once; aborted ones go.
1233            let (spawned, aborted) = {
1234                let mut s = self.bot.lock();
1235                (
1236                    std::mem::take(&mut s.spawned),
1237                    std::mem::take(&mut s.aborted),
1238                )
1239            };
1240            if !aborted.is_empty() {
1241                self.tasks.retain(|t| !aborted.contains(&t.id));
1242            }
1243            for (id, fut, on_panic) in spawned {
1244                let waker = Waker::from(Arc::new(TaskWaker {
1245                    id,
1246                    ready: self.ready.clone(),
1247                }));
1248                self.tasks.push(Task {
1249                    id,
1250                    fut,
1251                    waker,
1252                    on_panic: Some(on_panic),
1253                });
1254                lock(&self.ready).push(id);
1255            }
1256            let mut ready = std::mem::take(&mut *lock(&self.ready));
1257            ready.sort_unstable();
1258            ready.dedup();
1259            for id in ready {
1260                let Some(i) = self.tasks.iter().position(|t| t.id == id) else {
1261                    continue;
1262                };
1263                let t = &mut self.tasks[i];
1264                let mut cx = Context::from_waker(&t.waker);
1265                match catch_unwind(AssertUnwindSafe(|| t.fut.as_mut().poll(&mut cx))) {
1266                    Ok(Poll::Pending) => {}
1267                    Ok(Poll::Ready(())) => {
1268                        self.tasks.swap_remove(i);
1269                    }
1270                    Err(p) => {
1271                        let msg = panic_message(&*p);
1272                        log::error!("[{}] task {id} panicked: {msg}", self.name);
1273                        let mut t = self.tasks.swap_remove(i);
1274                        if let Some(h) = t.on_panic.take() {
1275                            h(msg);
1276                        }
1277                    }
1278                }
1279            }
1280            // Run the requests in order (one at a time: a request may queue more).
1281            let mut ran = false;
1282            loop {
1283                let r = self.bot.lock().requests.pop_front();
1284                let Some(r) = r else { break };
1285                ran = true;
1286                r(ctx);
1287            }
1288            if ran {
1289                self.bot.lock().snap.refresh(ctx);
1290            }
1291            let idle = lock(&self.ready).is_empty() && {
1292                let s = self.bot.lock();
1293                s.spawned.is_empty() && s.aborted.is_empty() && s.requests.is_empty()
1294            };
1295            if idle {
1296                return;
1297            }
1298        }
1299        // Normal for code that calls `with` / `block_at` in a loop (each call is a round): the
1300        // rest simply runs next tick, so this is no warning.
1301        log::debug!(
1302            "[{}] t{} tasks still busy after {MAX_ROUNDS} rounds: continuing next tick",
1303            self.name,
1304            ctx.tick()
1305        );
1306    }
1307}
1308
1309/// The text of a panic payload.
1310pub(crate) fn panic_message(p: &(dyn std::any::Any + Send)) -> String {
1311    if let Some(s) = p.downcast_ref::<&str>() {
1312        (*s).to_owned()
1313    } else if let Some(s) = p.downcast_ref::<String>() {
1314        s.clone()
1315    } else {
1316        "unknown panic".to_owned()
1317    }
1318}
1319
1320impl Behavior for Ext {
1321    fn name(&self) -> &str {
1322        &self.name
1323    }
1324
1325    fn interests(&self) -> Interests {
1326        self.interests | self.bot.lock().extra_interests
1327    }
1328
1329    fn start(&mut self, ctx: &mut TickContext<'_>) {
1330        if self.started {
1331            self.end_session("new session");
1332        }
1333        self.started = true;
1334        self.begin_session(ctx);
1335    }
1336
1337    fn tick(&mut self, ctx: &mut TickContext<'_>) {
1338        {
1339            let mut s = self.bot.lock();
1340            s.tick += 1;
1341            s.snap.refresh(ctx);
1342            let ev = ctx.events();
1343            s.teleports += ev.teleports.len() as u64;
1344            if ev.died {
1345                s.deaths += 1;
1346            }
1347            s.publish(ctx);
1348            s.wake_ticks();
1349        }
1350        if self.auto_respawn && ctx.is_dead() {
1351            ctx.respawn();
1352        }
1353        self.run(ctx);
1354        // The main task finished?
1355        if self.result.is_none()
1356            && let Some(h) = &self.main
1357            && h.is_finished()
1358        {
1359            let r = lock(&h.slot).result.take();
1360            let r = match r {
1361                Some(Ok(r)) => r,
1362                Some(Err(e)) => Err(e),
1363                None => Err(Error::Cancelled),
1364            };
1365            self.main = None;
1366            match (&r, self.when_done) {
1367                (Ok(()), WhenDone::Disconnect) => ctx.disconnect("done"),
1368                (Err(e), WhenDone::Disconnect) => ctx.disconnect(format!("failed: {e}")),
1369                (Ok(()), WhenDone::Stay) => {
1370                    log::info!("[{}] main task done", self.name);
1371                }
1372                (Err(e), WhenDone::Stay) => log::warn!("[{}] main task failed: {e}", self.name),
1373            }
1374            self.result = Some(r);
1375        }
1376        if self.result.is_some() && self.when_done == WhenDone::Stay && self.tasks.is_empty() {
1377            self.finished = true;
1378        }
1379    }
1380
1381    fn running(&self) -> bool {
1382        !self.finished
1383    }
1384
1385    fn stop(&mut self, reason: &str) {
1386        self.end_session(reason);
1387        if self.result.is_none() && self.main.take().is_some() {
1388            self.result = Some(Err(Error::Disconnected));
1389        }
1390        self.started = false;
1391    }
1392}