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