Send an email if a reaction fails with an exception
[rhynodge.git] / src / main / java / net / pterodactylus / rhynodge / engine / ReactionRunner.java
1 package net.pterodactylus.rhynodge.engine;
2
3 import static java.lang.String.format;
4 import static java.util.Optional.ofNullable;
5 import static net.pterodactylus.rhynodge.states.FailedState.INSTANCE;
6 import static org.apache.log4j.Logger.getLogger;
7
8 import java.io.IOException;
9 import java.io.PrintWriter;
10 import java.io.StringWriter;
11 import java.util.Optional;
12
13 import net.pterodactylus.rhynodge.Action;
14 import net.pterodactylus.rhynodge.Filter;
15 import net.pterodactylus.rhynodge.Query;
16 import net.pterodactylus.rhynodge.Reaction;
17 import net.pterodactylus.rhynodge.State;
18 import net.pterodactylus.rhynodge.Trigger;
19 import net.pterodactylus.rhynodge.actions.EmailAction;
20 import net.pterodactylus.rhynodge.output.DefaultOutput;
21 import net.pterodactylus.rhynodge.output.Output;
22 import net.pterodactylus.rhynodge.states.FailedState;
23
24 import org.apache.log4j.Logger;
25
26 /**
27  * Runs a {@link Reaction}, starting with its {@link Query}, running the {@link
28  * State} through its {@link Filter}s, and finally checking the {@link Trigger}
29  * for whether an {@link Action} needs to be executed.
30  *
31  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
32  */
33 public class ReactionRunner implements Runnable {
34
35         private static final Logger logger = getLogger(ReactionRunner.class);
36         private final Reaction reaction;
37         private final ReactionState reactionState;
38         private final EmailAction errorEmailAction;
39
40         public ReactionRunner(Reaction reaction, ReactionState reactionState, EmailAction errorEmailAction) {
41                 this.reactionState = reactionState;
42                 this.reaction = reaction;
43                 this.errorEmailAction = errorEmailAction;
44         }
45
46         @Override
47         public void run() {
48                 State state = runQuery();
49                 state = runStateThroughFilters(state);
50                 if (!state.success()) {
51                         logger.info(format("Reaction %s failed.", reaction.name()));
52                         saveStateWithIncreasedFailCount(state);
53                         errorEmailAction.execute(createErrorOutput(reaction, state));
54                         return;
55                 }
56                 Optional<State> lastSuccessfulState = reactionState.loadLastSuccessfulState();
57                 if (!lastSuccessfulState.isPresent()) {
58                         logger.info(format("No last state for %s.", reaction.name()));
59                         reactionState.saveState(state);
60                         return;
61                 }
62                 Trigger trigger = reaction.trigger();
63                 State newState = trigger.mergeStates(lastSuccessfulState.get(), state);
64                 reactionState.saveState(newState);
65                 if (trigger.triggers()) {
66                         logger.info(format("Trigger was hit for %s, executing action...", reaction.name()));
67                         reaction.action().execute(trigger.output(reaction));
68                 }
69                 logger.info(format("Reaction %s finished.", reaction.name()));
70         }
71
72         private void saveStateWithIncreasedFailCount(State state) {
73                 Optional<State> lastState = reactionState.loadLastState();
74                 state.setFailCount(lastState.map(State::failCount).orElse(0) + 1);
75                 reactionState.saveState(state);
76         }
77
78         private Output createErrorOutput(Reaction reaction, State state) {
79                 DefaultOutput output = new DefaultOutput(String.format("Error while processing “%s!”", reaction.name()));
80                 output.addText("text/plain; charset=utf-8", createEmailText(reaction, state));
81                 return output;
82         }
83
84         private String createEmailText(Reaction reaction, State state) {
85                 StringBuilder emailText = new StringBuilder();
86                 emailText.append(String.format("An error occured while processing “.”\n\n", reaction.name()));
87                 appendExceptionToEmailText(state.exception(), emailText);
88                 return emailText.toString();
89         }
90
91         private void appendExceptionToEmailText(Throwable exception, StringBuilder emailText) {
92                 if (exception != null) {
93                         try (StringWriter stringWriter = new StringWriter();
94                                  PrintWriter printWriter = new PrintWriter(stringWriter)) {
95                                 exception.printStackTrace(printWriter);
96                                 emailText.append(stringWriter.toString());
97                         } catch (IOException ioe1) {
98                                 /* StringWriter doesn’t throw. */
99                                 throw new RuntimeException(ioe1);
100                         }
101                 }
102         }
103
104         private State runQuery() {
105                 logger.info(format("Querying %s...", reaction.name()));
106                 try {
107                         return ofNullable(reaction.query().state()).orElse(INSTANCE);
108                 } catch (Throwable t1) {
109                         logger.warn(format("Could not query %s.", reaction.name()), t1);
110                         return new FailedState(t1);
111                 }
112         }
113
114         private State runStateThroughFilters(State state) {
115                 State currentState = state;
116                 for (Filter filter : reaction.filters()) {
117                         if (currentState.success()) {
118                                 logger.debug(format("Filtering state through %s...", filter.getClass().getSimpleName()));
119                                 try {
120                                         currentState = filter.filter(currentState);
121                                 } catch (Throwable t1) {
122                                         logger.warn(format("Error during filter %s for %s.", filter.getClass().getSimpleName(), reaction.name()), t1);
123                                         return new FailedState(t1);
124                                 }
125                         }
126                 }
127                 return currentState;
128         }
129
130 }