diff --git a/server/src/main/java/eu/jonahbauer/chat/server/bot/ChatBotSupervisor.java b/server/src/main/java/eu/jonahbauer/chat/server/bot/ChatBotSupervisor.java index bc42f59..b9b3f74 100644 --- a/server/src/main/java/eu/jonahbauer/chat/server/bot/ChatBotSupervisor.java +++ b/server/src/main/java/eu/jonahbauer/chat/server/bot/ChatBotSupervisor.java @@ -185,18 +185,17 @@ public final class ChatBotSupervisor implements AutoCloseable { */ private class RunningBot implements Runnable { private final @NotNull String name; - private final @NotNull BotConfig config; - private final @NotNull ChatBotFactory factory; + private final @NotNull ChatBot bot; private final @NotNull Thread thread; private final @NotNull BlockingQueue<@NotNull PendingPost> queue = new ArrayBlockingQueue<>(MESSAGE_QUEUE_SIZE); - private final AtomicBoolean stopped = new AtomicBoolean(); - private volatile ChatBot bot; + private final @NotNull AtomicBoolean stopped = new AtomicBoolean(); public RunningBot(@NotNull String name, @NotNull BotConfig config) { this.name = name; - this.config = config; - this.factory = getChatBotFactory(config.getType()); + + var factory = getChatBotFactory(config.getType()); + this.bot = factory.create(config); log.info("starting bot {}...", name); ChatBotSupport.register(ChatBotSupervisor.this, name, config); @@ -206,26 +205,6 @@ public final class ChatBotSupervisor implements AutoCloseable { @Override public void run() { log.info("started bot {}", name); - while (!stopped.get()) { - var bot = factory.create(config); - this.bot = bot; - try { - loop(bot); - } catch (Exception ex) { - log.warn("bot {} threw an exception and will be recreated", name, ex); - continue; - } - - try { - bot.onStop(); - } catch (Exception ex) { - log.warn("bot {} threw an exception during shutdown", name, ex); - } - } - log.info("stopped bot {}", name); - } - - private void loop(@NotNull ChatBot bot) { while (!stopped.get()) { try { var post = queue.take(); @@ -239,8 +218,21 @@ public final class ChatBotSupervisor implements AutoCloseable { bot.onMessage(ChatBotSupervisor.this.socketSupervisor.get(), post.post()); } } catch (InterruptedException _) { + // ignore + } catch (Exception ex) { + log.warn("bot {} threw an exception during message handling", name, ex); + } catch (Throwable ex) { + log.error("bot {} threw an error during message handling", name, ex); } } + + try { + bot.onStop(); + } catch (Exception ex) { + log.warn("bot {} threw an exception during shutdown", name, ex); + } + + log.info("stopped bot {}", name); } @NonBlocking @@ -269,8 +261,7 @@ public final class ChatBotSupervisor implements AutoCloseable { } public @NotNull BotConfig getConfig() { - var bot = this.bot; - return bot != null ? bot.getConfig() : config; + return bot.getConfig(); } private record PendingPost(@NotNull Message.Post post, @NotNull Instant expiration) {}