1use 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
21pub(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>;
25type PanicHook = Box<dyn FnOnce(String) + Send>;
27
28const MAX_ROUNDS: usize = 256;
31
32#[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 self.held_cooldown = ctx.held_cooldown();
86 if self.dimension != ctx.dimension() {
87 ctx.dimension().clone_into(&mut self.dimension);
88 }
89 }
90}
91
92pub(crate) struct Shared {
94 pub(crate) session: u64,
96 pub(crate) closed: Option<String>,
98 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 pub(crate) teleports: u64,
109 pub(crate) deaths: u64,
110 pub(crate) extra_interests: Interests,
112 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 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
255pub(crate) fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
257 m.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
258}
259
260#[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 #[must_use]
309 pub fn tick(&self) -> u64 {
310 self.lock().tick
311 }
312
313 #[must_use]
321 pub fn version(&self) -> GameVersion {
322 self.lock().snap.version
323 }
324
325 #[must_use]
334 pub fn pose(&self) -> Pose {
335 self.lock().snap.pose
336 }
337
338 #[must_use]
346 pub fn sent(&self) -> Pose {
347 self.lock().snap.sent
348 }
349
350 #[must_use]
358 pub fn eyes(&self) -> Vec3 {
359 self.lock().snap.eyes
360 }
361
362 #[must_use]
370 pub fn health(&self) -> Health {
371 self.lock().snap.health
372 }
373
374 #[must_use]
387 pub fn world_time(&self) -> Option<ghast_client::WorldTime> {
388 self.lock().snap.world_time
389 }
390
391 #[must_use]
399 pub fn is_dead(&self) -> bool {
400 self.lock().snap.dead
401 }
402
403 #[must_use]
411 pub fn game_mode(&self) -> GameMode {
412 self.lock().snap.game_mode
413 }
414
415 #[must_use]
423 pub fn held_slot(&self) -> u8 {
424 self.lock().snap.held_slot
425 }
426
427 #[must_use]
440 pub fn held_cooldown(&self) -> Option<ghast_client::cooldown::ItemCooldown> {
441 self.lock().snap.held_cooldown.clone()
442 }
443
444 pub async fn wait_cooldown(&self) -> Result<(), Error> {
455 self.wait_until(|ctx| ctx.held_cooldown().is_none()).await
456 }
457
458 #[must_use]
466 pub fn open_window(&self) -> Option<i32> {
467 self.lock().snap.open_window
468 }
469
470 #[must_use]
478 pub fn entity_id(&self) -> i32 {
479 self.lock().snap.entity_id
480 }
481
482 #[must_use]
490 pub fn dimension(&self) -> String {
491 self.lock().snap.dimension.clone()
492 }
493
494 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 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 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 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 pub fn next_tick(&self) -> WaitTicks {
591 self.wait_ticks(1)
592 }
593
594 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 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 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 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 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 pub fn require(&self, interests: Interests) {
713 let mut s = self.lock();
714 s.extra_interests |= interests;
715 }
716
717 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 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 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#[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 dropped: bool,
768}
769
770struct 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#[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#[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#[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
896struct 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 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#[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 pub fn abort(&self) {
952 self.bot.lock().aborted.push(self.id);
953 }
954
955 #[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
985struct 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1010#[non_exhaustive]
1011pub enum WhenDone {
1012 #[default]
1015 Disconnect,
1016 Stay,
1019}
1020
1021pub 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 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 #[must_use]
1109 pub fn name(mut self, name: impl Into<String>) -> Self {
1110 self.name = name.into();
1111 self
1112 }
1113
1114 #[must_use]
1124 pub fn interests(mut self, interests: Interests) -> Self {
1125 self.interests = interests;
1126 self
1127 }
1128
1129 #[must_use]
1136 pub fn when_done(mut self, when: WhenDone) -> Self {
1137 self.when_done = when;
1138 self
1139 }
1140
1141 #[must_use]
1149 pub fn auto_respawn(mut self, on: bool) -> Self {
1150 self.auto_respawn = on;
1151 self
1152 }
1153
1154 #[must_use]
1163 pub fn interrupt_on_teleport(mut self, on: bool) -> Self {
1164 self.interrupt_on_teleport = on;
1165 self
1166 }
1167
1168 #[must_use]
1177 pub fn bot(&self) -> Bot {
1178 self.bot.clone()
1179 }
1180
1181 #[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 drop(reqs);
1225 drop(spawned);
1226 self.tasks.clear();
1227 }
1228
1229 fn run(&mut self, ctx: &mut TickContext<'_>) {
1231 for _ in 0..MAX_ROUNDS {
1232 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 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 log::debug!(
1302 "[{}] t{} tasks still busy after {MAX_ROUNDS} rounds: continuing next tick",
1303 self.name,
1304 ctx.tick()
1305 );
1306 }
1307}
1308
1309pub(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 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}