🔊 Log exceptions that occur when running a reaction
[rhynodge.git] / src / main / java / net / pterodactylus / rhynodge / engine / Engine.java
index 23fa69b..e132b08 100644 (file)
 
 package net.pterodactylus.rhynodge.engine;
 
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.SortedMap;
-
-import net.pterodactylus.rhynodge.Filter;
-import net.pterodactylus.rhynodge.Query;
+import jakarta.inject.Inject;
+import jakarta.inject.Singleton;
+import kotlin.Unit;
+import kotlin.jvm.functions.Function0;
+import kotlin.jvm.functions.Function1;
 import net.pterodactylus.rhynodge.Reaction;
-import net.pterodactylus.rhynodge.Trigger;
-import net.pterodactylus.rhynodge.states.AbstractState;
-import net.pterodactylus.rhynodge.states.FailedState;
+import net.pterodactylus.rhynodge.actions.EmailAction;
 import net.pterodactylus.rhynodge.states.StateManager;
-
-import org.apache.commons.lang3.tuple.Pair;
 import org.apache.log4j.Logger;
 
-import com.google.common.collect.Maps;
-import com.google.common.util.concurrent.AbstractExecutionThreadService;
+import java.util.Map;
+import java.util.Optional;
+import java.util.concurrent.*;
+
+import static java.lang.System.currentTimeMillis;
+import static java.util.concurrent.TimeUnit.MILLISECONDS;
+import static net.pterodactylus.util.exception.ExceptionsKt.suppressException;
 
 /**
  * Rhynodge main engine.
  *
  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
  */
-public class Engine extends AbstractExecutionThreadService {
+@Singleton
+public class Engine {
 
-       /** The logger. */
-       private static final Logger logger = Logger.getLogger(Engine.class);
-
-       /** The state manager. */
        private final StateManager stateManager;
+       private final ScheduledExecutorService executorService;
+       private final Map<String, Future<?>> scheduledFutures = new ConcurrentHashMap<>();
+       private final EmailAction errorEmailAction;
 
-       /** All defined reactions. */
-       /* synchronize on itself. */
-       private final Map<String, Reaction> reactions = new HashMap<String, Reaction>();
-
-       /**
-        * Creates a new engine.
-        *
-        * @param stateManager
-        *            The state manager
-        */
-       public Engine(StateManager stateManager) {
+       @Inject
+       public Engine(StateManager stateManager, EmailAction errorEmailAction) {
                this.stateManager = stateManager;
+               this.errorEmailAction = errorEmailAction;
+               executorService = new ScheduledThreadPoolExecutor(1);
        }
 
        //
@@ -71,147 +63,47 @@ public class Engine extends AbstractExecutionThreadService {
         * Adds the given reaction to this engine.
         *
         * @param name
-        *            The name of the reaction
+        *              The name of the reaction
         * @param reaction
-        *            The reaction to add to this engine
+        *              The reaction to add to this engine
         */
        public void addReaction(String name, Reaction reaction) {
-               synchronized (reactions) {
-                       reactions.put(name, reaction);
-                       reactions.notifyAll();
-               }
+               ReactionState reactionState = new ReactionState(stateManager, name);
+               Optional<net.pterodactylus.rhynodge.State> lastState = reactionState.loadLastState();
+               long lastExecutionTime = lastState.map(net.pterodactylus.rhynodge.State::time).orElse(0L);
+               long nextExecutionTime = lastExecutionTime + reaction.updateInterval();
+               ReactionRunner reactionRunner = new ReactionRunner(reaction, reactionState, errorEmailAction);
+               ScheduledFuture<?> future = executorService.scheduleWithFixedDelay(suppressException(wrapRunnable(reactionRunner), logExceptionForReaction(reaction))::invoke, nextExecutionTime - currentTimeMillis(), reaction.updateInterval(), MILLISECONDS);
+               scheduledFutures.put(name, future);
+       }
+
+       private Function1<Exception, Unit> logExceptionForReaction(Reaction reaction) {
+               return (Exception e) -> {
+                       logger.warn("Exception during Reaction “%s”!".formatted(reaction.name()), e);
+                       return Unit.INSTANCE;
+               };
+       }
+
+       private Function0<Unit> wrapRunnable(Runnable runnable) {
+               return () -> {
+                       runnable.run();
+                       return Unit.INSTANCE;
+               };
        }
 
        /**
         * Removes the reaction with the given name.
         *
         * @param name
-        *            The name of the reaction to remove
+        *              The name of the reaction to remove
         */
        public void removeReaction(String name) {
-               synchronized (reactions) {
-                       if (!reactions.containsKey(name)) {
-                               return;
-                       }
-                       reactions.remove(name);
-                       reactions.notifyAll();
+               if (!scheduledFutures.containsKey(name)) {
+                       return;
                }
+               scheduledFutures.remove(name).cancel(true);
        }
 
-       //
-       // ABSTRACTSERVICE METHODS
-       //
-
-       /**
-        * {@inheritDoc}
-        */
-       @Override
-       public void run() {
-               while (isRunning()) {
-
-                       /* delay if we have no reactions. */
-                       synchronized (reactions) {
-                               if (reactions.isEmpty()) {
-                                       logger.debug("Sleeping while no Reactions available.");
-                                       try {
-                                               reactions.wait();
-                                       } catch (InterruptedException ie1) {
-                                               /* ignore, we’re looping anyway. */
-                                       }
-                                       continue;
-                               }
-                       }
-
-                       /* find next reaction. */
-                       SortedMap<Long, Pair<String, Reaction>> nextReactions = Maps.newTreeMap();
-                       String reactionName;
-                       Reaction nextReaction;
-                       synchronized (reactions) {
-                               for (Entry<String, Reaction> reactionEntry : reactions.entrySet()) {
-                                       net.pterodactylus.rhynodge.State state = stateManager.loadLastState(reactionEntry.getKey());
-                                       long stateTime = (state != null) ? state.time() : 0;
-                                       nextReactions.put(stateTime + reactionEntry.getValue().updateInterval(), Pair.of(reactionEntry.getKey(), reactionEntry.getValue()));
-                               }
-                               reactionName = nextReactions.get(nextReactions.firstKey()).getLeft();
-                               nextReaction = nextReactions.get(nextReactions.firstKey()).getRight();
-                       }
-                       logger.debug(String.format("Next Reaction: %s.", reactionName));
-
-                       /* wait until the next reaction has to run. */
-                       net.pterodactylus.rhynodge.State lastState = stateManager.loadLastState(reactionName);
-                       long lastStateTime = (lastState != null) ? lastState.time() : 0;
-                       int lastStateFailCount = (lastState != null) ? lastState.failCount() : 0;
-                       long waitTime = (lastStateTime + nextReaction.updateInterval()) - System.currentTimeMillis();
-                       logger.debug(String.format("Time to wait for next Reaction: %d millseconds.", waitTime));
-                       if (waitTime > 0) {
-                               synchronized (reactions) {
-                                       try {
-                                               logger.info(String.format("Waiting until %tc.", lastStateTime + nextReaction.updateInterval()));
-                                               reactions.wait(waitTime);
-                                       } catch (InterruptedException ie1) {
-                                               /* we’re looping! */
-                                       }
-                               }
-
-                               /* re-start loop to check for new reactions. */
-                               continue;
-                       }
-
-                       /* run reaction. */
-                       logger.info(String.format("Running Query for %s...", reactionName));
-                       Query query = nextReaction.query();
-                       net.pterodactylus.rhynodge.State state;
-                       try {
-                               logger.debug("Querying system...");
-                               state = query.state();
-                               if (state == null) {
-                                       state = FailedState.INSTANCE;
-                               }
-                               logger.debug("System queried.");
-                       } catch (Throwable t1) {
-                               logger.warn("Querying system failed!", t1);
-                               state = new AbstractState(t1) {
-                                       /* no further state. */
-                               };
-                       }
-                       logger.debug(String.format("State is %s.", state));
-
-                       /* convert states. */
-                       for (Filter filter : nextReaction.filters()) {
-                               if (state.success()) {
-                                       net.pterodactylus.rhynodge.State newState = filter.filter(state);
-                                       logger.debug(String.format("Old state is %s, new state is %s.", state, newState));
-                                       state = newState;
-                               }
-                       }
-                       if (!state.success()) {
-                               state.setFailCount(lastStateFailCount + 1);
-                       }
-                       net.pterodactylus.rhynodge.State lastSuccessfulState = stateManager.loadLastSuccessfulState(reactionName);
-
-                       /* merge states. */
-                       boolean triggerHit = false;
-                       Trigger trigger = nextReaction.trigger();
-                       if ((lastSuccessfulState != null) && lastSuccessfulState.success() && state.success()) {
-                               net.pterodactylus.rhynodge.State newState = trigger.mergeStates(lastSuccessfulState, state);
-
-                               /* save new state. */
-                               stateManager.saveState(reactionName, newState);
-
-                               triggerHit = trigger.triggers();
-                       } else {
-                               /* save first or error state. */
-                               stateManager.saveState(reactionName, state);
-                       }
-
-                       /* run action if trigger was hit. */
-                       logger.debug(String.format("Trigger was hit: %s.", triggerHit));
-                       if (triggerHit) {
-                               logger.info("Executing Action...");
-                               nextReaction.action().execute(trigger.output(nextReaction));
-                       }
-
-               }
-       }
+       private static final Logger logger = Logger.getLogger(Engine.class);
 
 }