|
| 1 | +package dev.skidfuscator.failsafe; |
| 2 | + |
| 3 | +import java.util.ArrayList; |
| 4 | +import java.util.List; |
| 5 | +import java.util.function.Consumer; |
| 6 | + |
| 7 | +public final class Failsafe { |
| 8 | + public interface Action { |
| 9 | + /** |
| 10 | + * Execute the logic associated with this action when handling an exception. |
| 11 | + * |
| 12 | + * @param builder The current failsafe builder. |
| 13 | + * @param e The exception that triggered this action. |
| 14 | + * @param attempt The current attempt count (1-based). |
| 15 | + * @param maxAttempts The maximum number of attempts allowed by this action. |
| 16 | + * @return true if done (stop), false if continue retrying. |
| 17 | + */ |
| 18 | + boolean execute(FailsafeBuilder builder, Exception e, int attempt, int maxAttempts); |
| 19 | + } |
| 20 | + |
| 21 | + public static final Action RETRY = new Action() { |
| 22 | + @Override |
| 23 | + public boolean execute(FailsafeBuilder builder, Exception e, int attempt, int maxAttempts) { |
| 24 | + int effectiveMax = (maxAttempts > 0) ? maxAttempts : builder.defaultMaxAttempts; |
| 25 | + if (attempt < effectiveMax) { |
| 26 | + return false; // try again |
| 27 | + } else { |
| 28 | + // max attempts reached, rethrow |
| 29 | + throw asRuntimeException(e); |
| 30 | + } |
| 31 | + } |
| 32 | + }; |
| 33 | + |
| 34 | + public static final Action CANCEL = (builder, e, attempt, maxAttempts) -> true; |
| 35 | + public static final Action UNDO = (builder, e, attempt, maxAttempts) -> true; |
| 36 | + |
| 37 | + public static FailsafeBuilder run(Runnable code) { |
| 38 | + return new FailsafeBuilder().run(code); |
| 39 | + } |
| 40 | + |
| 41 | + public static <T> FailsafeBuilder run(Iterable<T> values, Consumer<T> code) { |
| 42 | + return new FailsafeBuilder().run(values, code); |
| 43 | + } |
| 44 | + |
| 45 | + public static <T> FailsafeBuilder run(T value, Consumer<T> code) { |
| 46 | + return new FailsafeBuilder().run(value, code); |
| 47 | + } |
| 48 | + |
| 49 | + public static class FailsafeBuilder { |
| 50 | + private Runnable baseAction; |
| 51 | + private Runnable finalAction; |
| 52 | + private Runnable successAction; |
| 53 | + |
| 54 | + private final List<ExceptionHandler<? extends Exception>> exceptionHandlers = new ArrayList<>(); |
| 55 | + private int defaultMaxAttempts = 1; |
| 56 | + |
| 57 | + private FailsafeBuilder run(Runnable code) { |
| 58 | + this.baseAction = code; |
| 59 | + return this; |
| 60 | + } |
| 61 | + |
| 62 | + private <T> FailsafeBuilder run(Iterable<T> values, Consumer<T> code) { |
| 63 | + this.baseAction = () -> { |
| 64 | + for (T val : values) { |
| 65 | + code.accept(val); |
| 66 | + } |
| 67 | + }; |
| 68 | + return this; |
| 69 | + } |
| 70 | + |
| 71 | + private <T> FailsafeBuilder run(T value, Consumer<T> code) { |
| 72 | + this.baseAction = () -> code.accept(value); |
| 73 | + return this; |
| 74 | + } |
| 75 | + |
| 76 | + public OnExceptionBuilder<Exception> onException() { |
| 77 | + return new OnExceptionBuilder<>(Exception.class, this); |
| 78 | + } |
| 79 | + |
| 80 | + public <E extends Exception> OnExceptionBuilder<E> onException(Class<E> exceptionType) { |
| 81 | + return new OnExceptionBuilder<>(exceptionType, this); |
| 82 | + } |
| 83 | + |
| 84 | + public FailsafeBuilder onSuccess(Runnable action) { |
| 85 | + this.successAction = action; |
| 86 | + return this; |
| 87 | + } |
| 88 | + |
| 89 | + public FailsafeBuilder finallyDo(Runnable action) { |
| 90 | + this.finalAction = action; |
| 91 | + return this; |
| 92 | + } |
| 93 | + |
| 94 | + public void finish() { |
| 95 | + if (baseAction == null) { |
| 96 | + throw new IllegalStateException("No base action provided. Call run(...) before execute()."); |
| 97 | + } |
| 98 | + |
| 99 | + boolean success = false; |
| 100 | + try { |
| 101 | + runWithHandlers(); |
| 102 | + success = true; |
| 103 | + if (successAction != null) { |
| 104 | + successAction.run(); |
| 105 | + } |
| 106 | + } finally { |
| 107 | + if (finalAction != null) { |
| 108 | + finalAction.run(); |
| 109 | + } |
| 110 | + } |
| 111 | + } |
| 112 | + |
| 113 | + private void runWithHandlers() { |
| 114 | + int attempt = 0; |
| 115 | + boolean done = false; |
| 116 | + |
| 117 | + while (!done) { |
| 118 | + attempt++; |
| 119 | + try { |
| 120 | + baseAction.run(); |
| 121 | + done = true; |
| 122 | + } catch (Exception e) { |
| 123 | + ExceptionHandler<? extends Exception> handler = findMatchingHandler(e); |
| 124 | + if (handler == null) { |
| 125 | + throw asRuntimeException(e); |
| 126 | + } |
| 127 | + |
| 128 | + // Apply strategy modifiers |
| 129 | + handler.applyStrategy(e); |
| 130 | + |
| 131 | + // Execute the action |
| 132 | + boolean result = handler.getAction().execute(this, e, attempt, handler.getMaxAttempts()); |
| 133 | + |
| 134 | + // If exception occurred and action triggered, run the post callback if any |
| 135 | + if (handler.getPostCallback() != null) { |
| 136 | + handler.getPostCallback().run(); |
| 137 | + } |
| 138 | + |
| 139 | + done = result; |
| 140 | + } |
| 141 | + } |
| 142 | + } |
| 143 | + |
| 144 | + private ExceptionHandler<? extends Exception> findMatchingHandler(Exception e) { |
| 145 | + for (ExceptionHandler<? extends Exception> handler : exceptionHandlers) { |
| 146 | + if (handler.handles(e)) { |
| 147 | + return handler; |
| 148 | + } |
| 149 | + } |
| 150 | + return null; |
| 151 | + } |
| 152 | + |
| 153 | + void addExceptionHandler(ExceptionHandler<? extends Exception> handler) { |
| 154 | + exceptionHandlers.add(handler); |
| 155 | + } |
| 156 | + } |
| 157 | + |
| 158 | + private static RuntimeException asRuntimeException(Exception e) { |
| 159 | + return (e instanceof RuntimeException) ? (RuntimeException) e : new RuntimeException(e); |
| 160 | + } |
| 161 | + |
| 162 | + private static class ExceptionHandler<E extends Exception> { |
| 163 | + private final Class<E> type; |
| 164 | + private final Action action; |
| 165 | + private final Runnable strategyModifierRunnable; |
| 166 | + private final Consumer<E> strategyModifierConsumer; |
| 167 | + private final int maxAttempts; |
| 168 | + private final Runnable postCallback; |
| 169 | + |
| 170 | + ExceptionHandler( |
| 171 | + Class<E> type, |
| 172 | + Action action, |
| 173 | + Runnable strategyModifierRunnable, |
| 174 | + Consumer<E> strategyModifierConsumer, |
| 175 | + int maxAttempts, |
| 176 | + Runnable postCallback |
| 177 | + ) { |
| 178 | + this.type = type; |
| 179 | + this.action = action; |
| 180 | + this.strategyModifierRunnable = strategyModifierRunnable; |
| 181 | + this.strategyModifierConsumer = strategyModifierConsumer; |
| 182 | + this.maxAttempts = maxAttempts; |
| 183 | + this.postCallback = postCallback; |
| 184 | + } |
| 185 | + |
| 186 | + boolean handles(Exception e) { |
| 187 | + return type.isAssignableFrom(e.getClass()); |
| 188 | + } |
| 189 | + |
| 190 | + Action getAction() { |
| 191 | + return action; |
| 192 | + } |
| 193 | + |
| 194 | + int getMaxAttempts() { |
| 195 | + return maxAttempts; |
| 196 | + } |
| 197 | + |
| 198 | + Runnable getPostCallback() { |
| 199 | + return postCallback; |
| 200 | + } |
| 201 | + |
| 202 | + void applyStrategy(Exception e) { |
| 203 | + if (strategyModifierRunnable != null) { |
| 204 | + strategyModifierRunnable.run(); |
| 205 | + } else if (strategyModifierConsumer != null) { |
| 206 | + @SuppressWarnings("unchecked") |
| 207 | + E castException = (E) e; |
| 208 | + strategyModifierConsumer.accept(castException); |
| 209 | + } |
| 210 | + } |
| 211 | + } |
| 212 | + |
| 213 | + public static class OnExceptionBuilder<E extends Exception> { |
| 214 | + private final Class<E> exceptionType; |
| 215 | + private final FailsafeBuilder parent; |
| 216 | + |
| 217 | + private Action pendingAction; |
| 218 | + private Runnable strategyModifierRunnable; |
| 219 | + private Consumer<E> strategyModifierConsumer; |
| 220 | + private int maxAttempts = -1; |
| 221 | + private Runnable postCallback; |
| 222 | + |
| 223 | + OnExceptionBuilder(Class<E> exceptionType, FailsafeBuilder parent) { |
| 224 | + this.exceptionType = exceptionType; |
| 225 | + this.parent = parent; |
| 226 | + } |
| 227 | + |
| 228 | + public OnExceptionBuilder<E> retry(int attempts) { |
| 229 | + this.pendingAction = RETRY; |
| 230 | + this.maxAttempts = attempts; |
| 231 | + return this; |
| 232 | + } |
| 233 | + |
| 234 | + public OnExceptionBuilder<E> cancel() { |
| 235 | + this.pendingAction = CANCEL; |
| 236 | + return this; |
| 237 | + } |
| 238 | + |
| 239 | + public OnExceptionBuilder<E> undo() { |
| 240 | + this.pendingAction = UNDO; |
| 241 | + return this; |
| 242 | + } |
| 243 | + |
| 244 | + public OnExceptionBuilder<E> modify(Consumer<E> modifier) { |
| 245 | + this.strategyModifierConsumer = modifier; |
| 246 | + return this; |
| 247 | + } |
| 248 | + |
| 249 | + public OnExceptionBuilder<E> modify(Runnable modifier) { |
| 250 | + this.strategyModifierRunnable = modifier; |
| 251 | + return this; |
| 252 | + } |
| 253 | + |
| 254 | + /** |
| 255 | + * Sets a callback to run if this exception handler is triggered. |
| 256 | + * This does not override the action. If no action was specified before, |
| 257 | + * defaults to CANCEL. |
| 258 | + */ |
| 259 | + public FailsafeBuilder execute(Runnable callback) { |
| 260 | + this.postCallback = callback; |
| 261 | + finalizeHandler(); |
| 262 | + return parent; |
| 263 | + } |
| 264 | + |
| 265 | + /** |
| 266 | + * If the user calls execute() without arguments (not requested, but we can keep it), |
| 267 | + * we finalize without a callback. |
| 268 | + */ |
| 269 | + public FailsafeBuilder execute() { |
| 270 | + finalizeHandler(); |
| 271 | + return parent; |
| 272 | + } |
| 273 | + |
| 274 | + private void finalizeHandler() { |
| 275 | + if (pendingAction == null) { |
| 276 | + // No action was set, default to CANCEL |
| 277 | + pendingAction = CANCEL; |
| 278 | + } |
| 279 | + ExceptionHandler<E> handler = new ExceptionHandler<>( |
| 280 | + exceptionType, |
| 281 | + pendingAction, |
| 282 | + strategyModifierRunnable, |
| 283 | + strategyModifierConsumer, |
| 284 | + maxAttempts, |
| 285 | + postCallback |
| 286 | + ); |
| 287 | + parent.addExceptionHandler(handler); |
| 288 | + } |
| 289 | + } |
| 290 | +} |
| 291 | + |
0 commit comments