diff --git a/README.md b/README.md index 48f6dc2..1957518 100644 --- a/README.md +++ b/README.md @@ -15,16 +15,34 @@ nodes continue to work without it. ## Forwarding retries -When a forwarding connection fails before the vote payload starts writing, -VotifierPlus retries that destination after 15 minutes. It uses 15-minute -delays for the first five retries, then 30-minute delays while the destination -remains eligible. Other destinations continue independently. Protocol or -payload preparation errors are terminal. Once a payload write begins, the -receiver may have accepted the vote, so VotifierPlus does not retry an error -from that point. +Eligible transport failures before a payload write can be retried. The first +retry always waits 60 seconds after the original failure. Later retries wait +`ForwardingRetry.RetryIntervalSeconds` seconds after the preceding failure +(default 300, valid range 1–3600). `ForwardingRetry.MaxRetries` counts retries +after the initial send (default 12, valid range 0–3600). Zero disables retrying. +Missing or invalid settings use their defaults. No retry begins at or after +one hour from the original failure, even when the configured count would +allow more attempts. With the defaults, up to 12 retries fit within that hour. -The receiver keeps up to 256 pending vote/destination pairs in memory. If the -queue fills, new failures are dropped from the retry queue. Pending retries -are discarded when the receiver reloads or shuts down. No retry state survives -a restart. Each retry checks the destination and uses its current credentials -for the same forwarding protocol. +Each destination can override those three settings under +`Forwarding..ForwardingRetry`. Missing or invalid overrides inherit +the validated global values. Explicit `false` turns off the success gate and +explicit `0` for `MaxRetries` disables retries for that destination. The +60-second first delay and one-hour cutoff apply to every destination. + +`ForwardingRetry.RequirePreviousSuccessBeforeRetry` defaults to `true`. Each +destination must first complete a normal vote payload write and flush on its +current configuration. A connection or handshake alone does not qualify. +Forwarding has no receiver acknowledgement, so transport success does not +confirm authentication or processing at the destination. New incoming votes +are still forwarded normally. Failures before the first transport success are +discarded and are never replayed. Set this option to `false` to retry eligible +failures before the first transport success. + +The receiver keeps up to 256 pending vote–destination pairs in RAM. New +failures are dropped from the retry queue when full. A change to the target +host, port, protocol, credential, or effective retry settings invalidates cached success for that +destination and pending retries for the previous identity. Disabled or removed +targets cannot retry. Reload and shutdown clear pending retries and prior +successes. Protocol or payload errors and failures after writing begins are +terminal because the receiver may already have accepted the vote. diff --git a/VotifierPlus/src/main/java/com/vexsoftware/votifier/ForwardServer.java b/VotifierPlus/src/main/java/com/vexsoftware/votifier/ForwardServer.java index eee5a1f..9686de5 100644 --- a/VotifierPlus/src/main/java/com/vexsoftware/votifier/ForwardServer.java +++ b/VotifierPlus/src/main/java/com/vexsoftware/votifier/ForwardServer.java @@ -2,6 +2,8 @@ import java.security.Key; +import com.vexsoftware.votifier.net.ForwardRetryConfig; + import lombok.Getter; import lombok.Setter; @@ -18,13 +20,20 @@ public class ForwardServer { @Getter @Setter private Key Token; + @Getter + private final ForwardRetryConfig retryConfig; public ForwardServer(boolean enabled, String host, int port, String key, Key token) { + this(enabled, host, port, key, token, null); + } + + public ForwardServer(boolean enabled, String host, int port, String key, Key token, ForwardRetryConfig retryConfig) { this.enabled = enabled; this.host = host; this.port = port; this.key = key; this.Token = token; + this.retryConfig = retryConfig; } public boolean isUseTokens() { diff --git a/VotifierPlus/src/main/java/com/vexsoftware/votifier/VotifierPlus.java b/VotifierPlus/src/main/java/com/vexsoftware/votifier/VotifierPlus.java index fff2497..74d5e9c 100644 --- a/VotifierPlus/src/main/java/com/vexsoftware/votifier/VotifierPlus.java +++ b/VotifierPlus/src/main/java/com/vexsoftware/votifier/VotifierPlus.java @@ -59,6 +59,7 @@ import com.vexsoftware.votifier.diagnostic.VotifierDiagnosticsSnapshot; import com.vexsoftware.votifier.model.Vote; import com.vexsoftware.votifier.model.VotifierEvent; +import com.vexsoftware.votifier.net.ForwardRetryConfig; import com.vexsoftware.votifier.net.ThrottleConfig; import com.vexsoftware.votifier.net.VoteReceiver; import com.vexsoftware.votifier.util.ZipResourceReader; @@ -308,7 +309,11 @@ public ForwardServer getServerData(String s) { tokenKey = TokenUtil.createKeyFrom(token); } return new ForwardServer(d.getBoolean("Enabled"), d.getString("Host", ""), d.getInt("Port"), - d.getString("Key", ""), tokenKey); + d.getString("Key", ""), tokenKey, + getForwardRetryConfig().withOverrides( + d.get("ForwardingRetry.RetryIntervalSeconds"), + d.get("ForwardingRetry.MaxRetries"), + d.get("ForwardingRetry.RequirePreviousSuccessBeforeRetry"))); } @Override @@ -350,6 +355,14 @@ public java.util.Set getTrustedProxyIps() { return new java.util.HashSet(getConfigFile().getData().getStringList("TrustedProxyIps")); } + @Override + protected ForwardRetryConfig getForwardRetryConfig() { + return ForwardRetryConfig.parse( + getConfigFile().getData().get("ForwardingRetry.RetryIntervalSeconds"), + getConfigFile().getData().get("ForwardingRetry.MaxRetries"), + getConfigFile().getData().get("ForwardingRetry.RequirePreviousSuccessBeforeRetry")); + } + @Override public ThrottleConfig getThrottleConfig() { ConfigurationSection root = getConfigFile().getData().getConfigurationSection("ConnectionThrottle"); diff --git a/VotifierPlus/src/main/java/com/vexsoftware/votifier/bungee/VotifierPlusBungee.java b/VotifierPlus/src/main/java/com/vexsoftware/votifier/bungee/VotifierPlusBungee.java index 238d650..9926abb 100644 --- a/VotifierPlus/src/main/java/com/vexsoftware/votifier/bungee/VotifierPlusBungee.java +++ b/VotifierPlus/src/main/java/com/vexsoftware/votifier/bungee/VotifierPlusBungee.java @@ -22,6 +22,7 @@ import com.vexsoftware.votifier.diagnostic.VotifierDiagnostics; import com.vexsoftware.votifier.diagnostic.VotifierDiagnosticsSnapshot; import com.vexsoftware.votifier.model.Vote; +import com.vexsoftware.votifier.net.ForwardRetryConfig; import com.vexsoftware.votifier.net.ThrottleConfig; import com.vexsoftware.votifier.net.VoteReceiver; import com.vexsoftware.votifier.util.ZipResourceReader; @@ -177,7 +178,11 @@ public ForwardServer getServerData(String s) { tokenKey = TokenUtil.createKeyFrom(token); } return new ForwardServer(d.getBoolean("Enabled"), d.getString("Host", ""), d.getInt("Port"), - d.getString("Key", ""), tokenKey); + d.getString("Key", ""), tokenKey, + getForwardRetryConfig().withOverrides( + d.get("ForwardingRetry.RetryIntervalSeconds"), + d.get("ForwardingRetry.MaxRetries"), + d.get("ForwardingRetry.RequirePreviousSuccessBeforeRetry"))); } @Override @@ -221,6 +226,14 @@ public java.util.Set getTrustedProxyIps() { return ips == null ? Collections.emptySet() : new HashSet(ips); } + @Override + protected ForwardRetryConfig getForwardRetryConfig() { + return ForwardRetryConfig.parse( + getConfig().getData().get("ForwardingRetry.RetryIntervalSeconds"), + getConfig().getData().get("ForwardingRetry.MaxRetries"), + getConfig().getData().get("ForwardingRetry.RequirePreviousSuccessBeforeRetry")); + } + @Override public ThrottleConfig getThrottleConfig() { Configuration root = getConfig().getData().getSection("ConnectionThrottle"); diff --git a/VotifierPlus/src/main/java/com/vexsoftware/votifier/net/ForwardRetryConfig.java b/VotifierPlus/src/main/java/com/vexsoftware/votifier/net/ForwardRetryConfig.java new file mode 100644 index 0000000..0ead894 --- /dev/null +++ b/VotifierPlus/src/main/java/com/vexsoftware/votifier/net/ForwardRetryConfig.java @@ -0,0 +1,55 @@ +package com.vexsoftware.votifier.net; + +/** Settings for the receiver-owned, in-memory forwarding retry queue. */ +public record ForwardRetryConfig(int retryIntervalSeconds, int maxRetries, boolean requirePreviousSuccessBeforeRetry) { + private static final int DEFAULT_INTERVAL_SECONDS = 300; + private static final int DEFAULT_MAX_RETRIES = 12; + private static final int MAX_SETTING = 3600; + + public static final ForwardRetryConfig DEFAULT = new ForwardRetryConfig(DEFAULT_INTERVAL_SECONDS, DEFAULT_MAX_RETRIES, true); + + public ForwardRetryConfig { + retryIntervalSeconds = validate(retryIntervalSeconds, 1, DEFAULT_INTERVAL_SECONDS); + maxRetries = validate(maxRetries, 0, DEFAULT_MAX_RETRIES); + } + + public static ForwardRetryConfig parse(Object interval, Object count, Object requireSuccess) { + return DEFAULT.withOverrides(interval, count, requireSuccess); + } + + public ForwardRetryConfig withOverrides(Object interval, Object count, Object requireSuccess) { + return new ForwardRetryConfig( + validate(parseInt(interval, retryIntervalSeconds), 1, retryIntervalSeconds), + validate(parseInt(count, maxRetries), 0, maxRetries), + parseBoolean(requireSuccess, requirePreviousSuccessBeforeRetry)); + } + + private static boolean parseBoolean(Object value, boolean fallback) { + if (value instanceof Boolean option) { + return option; + } + if (value instanceof String text) { + return switch (text.trim().toLowerCase(java.util.Locale.ROOT)) { + case "true" -> true; + case "false" -> false; + default -> fallback; + }; + } + return fallback; + } + + private static int validate(int value, int minimum, int fallback) { + return value >= minimum && value <= MAX_SETTING ? value : fallback; + } + + private static int parseInt(Object value, int fallback) { + if (value instanceof Number || value instanceof String) { + try { + return Integer.parseInt(value.toString().trim()); + } catch (NumberFormatException ignored) { + return fallback; + } + } + return fallback; + } +} diff --git a/VotifierPlus/src/main/java/com/vexsoftware/votifier/net/VoteForwarder.java b/VotifierPlus/src/main/java/com/vexsoftware/votifier/net/VoteForwarder.java index 6789012..9820c77 100644 --- a/VotifierPlus/src/main/java/com/vexsoftware/votifier/net/VoteForwarder.java +++ b/VotifierPlus/src/main/java/com/vexsoftware/votifier/net/VoteForwarder.java @@ -11,6 +11,11 @@ import java.nio.charset.StandardCharsets; import java.util.Base64; import java.util.HashSet; +import java.util.HashMap; +import java.util.Map; +import java.security.Key; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; import java.util.List; import java.util.Objects; import java.util.Set; @@ -20,6 +25,7 @@ import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.RejectedExecutionException; +import java.util.function.LongSupplier; import java.util.function.Supplier; import java.util.function.BiFunction; import java.util.concurrent.TimeUnit; @@ -48,7 +54,8 @@ public class VoteForwarder { private static final int CONNECT_TIMEOUT_MILLIS = 1000; private static final int HANDSHAKE_TIMEOUT_MILLIS = 3000; private static final int MAX_PENDING_RETRIES = 256; - private static final int FAST_RETRY_COUNT = 5; + private static final int FIRST_RETRY_DELAY_SECONDS = 60; + private static final long RETRY_LIFETIME_NANOS = TimeUnit.HOURS.toNanos(1); private final VoteReceiver receiver; private final VoteThrottleService failureLogs = new VoteThrottleService(null); @@ -57,14 +64,25 @@ public class VoteForwarder { private final ScheduledThreadPoolExecutor deadlines; private final ScheduledThreadPoolExecutor retries; private final int retryCapacity; + private final ForwardRetryConfig retryConfig; + private final LongSupplier retryClock; + private final Map previousSuccesses = new HashMap<>(); private int pendingRetries; - private record Retry(String name, String host, int port, boolean tokenMode, Vote vote) { - boolean matches(ForwardServer server) { - return server != null && server.isEnabled() && port == server.getPort() - && tokenMode == server.isUseTokens() && Objects.equals(host, server.getHost()); + private record Credentials(boolean tokenMode, Key token) { + private static Credentials capture(ForwardServer server) { + if (server == null || !server.isEnabled()) { + return null; + } + boolean tokenMode = server.isUseTokens(); + return new Credentials(tokenMode, tokenMode ? server.getToken() : null); } } + + private record Destination(String host, int port, boolean tokenMode, String fingerprint, ForwardRetryConfig policy) {} + + private record Retry(String name, Destination destination, Vote vote, long failedAt) {} + private final ThreadPoolExecutor closers; private final int workers; private final Supplier socketFactory; @@ -124,8 +142,17 @@ public VoteForwarder(VoteReceiver receiver) { VoteForwarder(VoteReceiver receiver, int workers, BiFunction resolveAddress, Supplier socketFactory, ScheduledThreadPoolExecutor retries) { + this(receiver, workers, resolveAddress, socketFactory, retries, + receiver == null ? ForwardRetryConfig.DEFAULT : receiver.getForwardRetryConfig(), System::nanoTime); + } + + VoteForwarder(VoteReceiver receiver, int workers, BiFunction resolveAddress, + Supplier socketFactory, ScheduledThreadPoolExecutor retries, ForwardRetryConfig retryConfig, + LongSupplier retryClock) { this.receiver = receiver; this.retries = retries; + this.retryConfig = retryConfig; + this.retryClock = retryClock; retryCapacity = receiver == null ? 0 : Math.min(MAX_PENDING_RETRIES, receiver.getForwardQueueCapacity()); this.workers = workers; this.resolveAddress = resolveAddress; @@ -191,30 +218,103 @@ private void forward(Vote vote, boolean direct) { private void forwardTargets(Vote vote, boolean direct) { Vote snapshot = new Vote(vote.getServiceName(), vote.getUsername(), vote.getAddress(), vote.getTimeStamp()); - for (String name : receiver.getServers()) { + Set names = receiver.getServers(); + synchronized (lifecycleLock) { + previousSuccesses.keySet().retainAll(names); + } + for (String name : names) { if (stopped || Thread.currentThread().isInterrupted()) { return; } ForwardServer server = receiver.getServerData(name); + Credentials credentials = captureCredentials(name, server); + Destination destination = direct ? null : observeDestination(name, server, credentials); if (server == null || !server.isEnabled()) { receiver.debug("Skipping disabled or missing forward server: " + VoteLogSafety.field(name)); continue; } - boolean retryable = send(snapshot, name, server, direct ? Origin.DIRECT : Origin.INITIAL); - if (retryable && !direct) { - queueRetry(new Retry(name, server.getHost(), server.getPort(), server.isUseTokens(), snapshot)); + if (credentials == null) { + continue; + } + Long failedAt = send(snapshot, name, server, credentials, destination, direct ? Origin.DIRECT : Origin.INITIAL, + deadlineAfter(ATTEMPT_TIMEOUT_MILLIS)); + if (failedAt != null && destination != null) { + queueRetry(new Retry(name, destination, snapshot, failedAt)); } } } + private Credentials captureCredentials(String name, ForwardServer server) { + try { + return Credentials.capture(server); + } catch (RuntimeException ex) { + logFailure("retry-identity|" + name, "Unable to read forwarding credentials: " + VoteLogSafety.exceptionType(ex)); + return null; + } + } + + private Destination observeDestination(String name, ForwardServer server, Credentials credentials) { + Destination destination = destinationOf(name, server, credentials); + synchronized (lifecycleLock) { + if (!Objects.equals(destination, previousSuccesses.get(name))) { + previousSuccesses.remove(name); + } + } + return destination; + } + + private Destination destinationOf(String name, ForwardServer server, Credentials credentials) { + if (credentials == null) { + return null; + } + try { + boolean tokenMode = credentials.tokenMode(); + String rsaKey = server.getKey(); + byte[] credential = tokenMode ? credentials.token().getEncoded() + : rsaKey == null ? null : rsaKey.getBytes(StandardCharsets.UTF_8); + if (credential == null) { + return null; + } + byte[] digest = MessageDigest.getInstance("SHA-256").digest(credential); + ForwardRetryConfig policy = server.getRetryConfig() == null ? retryConfig : server.getRetryConfig(); + return new Destination(server.getHost(), server.getPort(), tokenMode, Base64.getEncoder().encodeToString(digest), policy); + } catch (RuntimeException | NoSuchAlgorithmException ex) { + logFailure("retry-identity|" + name, "Unable to establish forwarding retry identity: " + VoteLogSafety.exceptionType(ex)); + return null; + } + } + + private void rememberSuccess(String name, Destination destination) { + // Read the effective target again in case configuration changed during the send. + ForwardServer server = receiver.getServers().contains(name) ? receiver.getServerData(name) : null; + if (destination.equals(destinationOf(name, server, captureCredentials(name, server)))) { + synchronized (lifecycleLock) { + if (!retries.isShutdown()) { + previousSuccesses.put(name, destination); + } + } + } + } + + private boolean hasRequiredSuccess(Retry retry) { + return hasRequiredSuccess(retry.name(), retry.destination()); + } + + private boolean hasRequiredSuccess(String name, Destination destination) { + return !destination.policy().requirePreviousSuccessBeforeRetry() + || destination.equals(previousSuccesses.get(name)); + } + private void queueRetry(Retry retry) { synchronized (lifecycleLock) { - if (retries.isShutdown()) { + if (retries.isShutdown() || retry.destination().policy().maxRetries() == 0 || !hasRequiredSuccess(retry)) { return; } if (pendingRetries < retryCapacity) { - pendingRetries++; - scheduleRetry(retry, 1); + long delay = TimeUnit.SECONDS.toNanos(FIRST_RETRY_DELAY_SECONDS) - (retryClock.getAsLong() - retry.failedAt()); + if (scheduleRetry(retry, 1, Math.max(0, delay))) { + pendingRetries++; + } return; } } @@ -222,36 +322,53 @@ private void queueRetry(Retry retry) { } // Caller holds lifecycleLock. One slot covers both delayed and running work. - private void scheduleRetry(Retry retry, int number) { - retries.schedule(() -> runRetry(retry, number), number <= FAST_RETRY_COUNT ? 15 : 30, TimeUnit.MINUTES); + private boolean scheduleRetry(Retry retry, int number, long delayNanos) { + if (number > retry.destination().policy().maxRetries() || delayNanos >= retryTimeLeft(retry) || !hasRequiredSuccess(retry)) { + return false; + } + retries.schedule(() -> runRetry(retry, number), delayNanos, TimeUnit.NANOSECONDS); + return true; + } + + private long retryTimeLeft(Retry retry) { + return RETRY_LIFETIME_NANOS - (retryClock.getAsLong() - retry.failedAt()); } private void runRetry(Retry retry, int number) { - boolean retryable = false; + Long failedAt = null; try { - if (!retries.isShutdown() && !receiver.isStopping() && receiver.getServers().contains(retry.name())) { - ForwardServer server = receiver.getServerData(retry.name()); - if (retry.matches(server)) { - retryable = send(retry.vote(), retry.name(), server, Origin.RETRY); + if (!retries.isShutdown() && !receiver.isStopping() && retryTimeLeft(retry) > 0) { + ForwardServer server = receiver.getServers().contains(retry.name()) + ? receiver.getServerData(retry.name()) : null; + Credentials credentials = captureCredentials(retry.name(), server); + Destination destination = observeDestination(retry.name(), server, credentials); + boolean eligible; + synchronized (lifecycleLock) { + eligible = retry.destination().equals(destination) && hasRequiredSuccess(retry); + } + long attemptStart = System.nanoTime(); + long timeLeft = retryTimeLeft(retry); + if (eligible && timeLeft > 0) { + long deadline = attemptStart + Math.min(timeLeft, TimeUnit.MILLISECONDS.toNanos(ATTEMPT_TIMEOUT_MILLIS)); + failedAt = send(retry.vote(), retry.name(), server, credentials, destination, Origin.RETRY, deadline); } } } catch (RuntimeException ex) { logFailure("retry-config", "Unable to check forwarding retry target: " + VoteLogSafety.exceptionType(ex)); } finally { synchronized (lifecycleLock) { - if (retryable && !retries.isShutdown()) { - scheduleRetry(retry, Math.min(number + 1, FAST_RETRY_COUNT + 1)); - } else { + long interval = TimeUnit.SECONDS.toNanos(retry.destination().policy().retryIntervalSeconds()); + if (failedAt == null || retries.isShutdown() + || !scheduleRetry(retry, number + 1, Math.max(0, interval - (retryClock.getAsLong() - failedAt)))) { pendingRetries--; } } } } - // True means another attempt is safe. Neither protocol acknowledges delivery. - private boolean send(Vote vote, String name, ForwardServer server, Origin origin) { - receiver.debug("Preparing to forward vote to: " + VoteLogSafety.field(name) + ", tokens mode: " + server.isUseTokens()); - long deadline = deadlineAfter(ATTEMPT_TIMEOUT_MILLIS); + private Long send(Vote vote, String name, ForwardServer server, Credentials credentials, Destination destination, + Origin origin, long deadline) { + receiver.debug("Preparing to forward vote to: " + VoteLogSafety.field(name) + ", tokens mode: " + credentials.tokenMode()); Attempt attempt = null; boolean preparingPayload = false; boolean writing = false; @@ -267,12 +384,12 @@ private boolean send(Vote vote, String name, ForwardServer server, Origin origin receiver.debug("Received handshake from " + VoteLogSafety.field(name) + " (" + (greeting == null ? 0 : greeting.length()) + " chars)"); - if (greeting == null && server.isUseTokens()) { + if (greeting == null && credentials.tokenMode()) { throw new EOFException("Missing token-mode greeting"); } preparingPayload = true; byte[] payload; - if (server.isUseTokens()) { + if (credentials.tokenMode()) { String[] parts = greeting.split(" "); if (parts.length < 3 || !HANDSHAKE_PREFIX.equals(parts[0]) || !HANDSHAKE_V2.equals(parts[1])) { throw new IllegalStateException("Invalid token-mode handshake"); @@ -290,7 +407,7 @@ private boolean send(Vote vote, String name, ForwardServer server, Origin origin String innerJson = inner.toString(); Mac mac = Mac.getInstance("HmacSHA256"); - mac.init(server.getToken()); + mac.init(credentials.token()); String sig = Base64.getEncoder() .encodeToString(mac.doFinal(innerJson.getBytes(StandardCharsets.UTF_8))); @@ -324,11 +441,20 @@ private boolean send(Vote vote, String name, ForwardServer server, Origin origin finishAttempt(attempt, !stopped && expired); } if (completed) { + if (origin == Origin.INITIAL && destination != null && destination.policy().requirePreviousSuccessBeforeRetry()) { + rememberSuccess(name, destination); + } receiver.debug("Payload forwarded to " + VoteLogSafety.field(name) + " (" + payload.length + " bytes)"); } else { logFailure("target|" + name, "Forwarding attempt ended before completion: " + VoteLogSafety.field(name)); } } catch (Exception ex) { + long failedAt; + boolean eligible; + synchronized (lifecycleLock) { + failedAt = retryClock.getAsLong(); + eligible = destination != null && hasRequiredSuccess(name, destination); + } logFailure("target|" + name, "Failed to forward vote to " + VoteLogSafety.field(name) + ": " + VoteLogSafety.exceptionType(ex)); if (ex instanceof InterruptedException) { @@ -336,7 +462,8 @@ private boolean send(Vote vote, String name, ForwardServer server, Origin origin } // DNS waits signal their deadline via Future.get's TimeoutException. return (ex instanceof IOException || ex instanceof TimeoutException) - && !preparingPayload && !writing && !Thread.currentThread().isInterrupted(); + && !preparingPayload && !writing && !Thread.currentThread().isInterrupted() && eligible + ? failedAt : null; } finally { if (attempt != null) { synchronized (lifecycleLock) { @@ -348,7 +475,7 @@ private boolean send(Vote vote, String name, ForwardServer server, Origin origin } } } - return false; + return null; } private Attempt registerAttempt(Origin origin, String name, long deadline) throws Exception { @@ -495,6 +622,7 @@ void sealDirectCalls() { synchronized (lifecycleLock) { directSealed = true; pendingRetries -= retries.shutdownNow().size(); + previousSuccesses.clear(); for (Attempt attempt : attempts) { if (attempt.origin == Origin.RETRY) { finishAttempt(attempt); @@ -515,6 +643,7 @@ int stop() { } stopped = true; pendingRetries -= retries.shutdownNow().size(); + previousSuccesses.clear(); lifecycleLock.notifyAll(); for (Attempt attempt : attempts) { if (!attempt.ended) { diff --git a/VotifierPlus/src/main/java/com/vexsoftware/votifier/net/VoteReceiver.java b/VotifierPlus/src/main/java/com/vexsoftware/votifier/net/VoteReceiver.java index ff822b9..b163743 100644 --- a/VotifierPlus/src/main/java/com/vexsoftware/votifier/net/VoteReceiver.java +++ b/VotifierPlus/src/main/java/com/vexsoftware/votifier/net/VoteReceiver.java @@ -194,7 +194,7 @@ public String toString() { private static ForwardServer copyTarget(ForwardServer target) { return new ForwardServer(target.isEnabled(), target.getHost(), target.getPort(), target.getKey(), - target.getToken()); + target.getToken(), target.getRetryConfig()); } @@ -375,6 +375,10 @@ public int getForwardWorkerCount() { return 1; } + protected ForwardRetryConfig getForwardRetryConfig() { + return ForwardRetryConfig.DEFAULT; + } + public int getForwardQueueCapacity() { return 256; } diff --git a/VotifierPlus/src/main/java/com/vexsoftware/votifier/velocity/VotifierPlusVelocity.java b/VotifierPlus/src/main/java/com/vexsoftware/votifier/velocity/VotifierPlusVelocity.java index e4db590..9d532f8 100644 --- a/VotifierPlus/src/main/java/com/vexsoftware/votifier/velocity/VotifierPlusVelocity.java +++ b/VotifierPlus/src/main/java/com/vexsoftware/votifier/velocity/VotifierPlusVelocity.java @@ -37,6 +37,7 @@ import com.vexsoftware.votifier.diagnostic.VotifierDiagnostics; import com.vexsoftware.votifier.diagnostic.VotifierDiagnosticsSnapshot; import com.vexsoftware.votifier.model.Vote; +import com.vexsoftware.votifier.net.ForwardRetryConfig; import com.vexsoftware.votifier.net.ThrottleConfig; import com.vexsoftware.votifier.net.VoteReceiver; import com.vexsoftware.votifier.util.ZipResourceReader; @@ -247,7 +248,11 @@ public ForwardServer getServerData(String s) { tokenKey = TokenUtil.createKeyFrom(token); } return new ForwardServer(d.node("Enabled").getBoolean(), d.node("Host").getString(), - d.node("Port").getInt(), d.node("Key").getString(), tokenKey); + d.node("Port").getInt(), d.node("Key").getString(), tokenKey, + getForwardRetryConfig().withOverrides( + d.node("ForwardingRetry", "RetryIntervalSeconds").raw(), + d.node("ForwardingRetry", "MaxRetries").raw(), + d.node("ForwardingRetry", "RequirePreviousSuccessBeforeRetry").raw())); } @Override @@ -297,6 +302,14 @@ public java.util.Set getTrustedProxyIps() { return ips; } + @Override + protected ForwardRetryConfig getForwardRetryConfig() { + return ForwardRetryConfig.parse( + getConfig().getNode("ForwardingRetry", "RetryIntervalSeconds").raw(), + getConfig().getNode("ForwardingRetry", "MaxRetries").raw(), + getConfig().getNode("ForwardingRetry", "RequirePreviousSuccessBeforeRetry").raw()); + } + @Override public ThrottleConfig getThrottleConfig() { ConfigurationNode root = getConfig().getNode("ConnectionThrottle"); diff --git a/VotifierPlus/src/main/resources/bungeeconfig.yml b/VotifierPlus/src/main/resources/bungeeconfig.yml index 2fc721d..51a4d97 100644 --- a/VotifierPlus/src/main/resources/bungeeconfig.yml +++ b/VotifierPlus/src/main/resources/bungeeconfig.yml @@ -121,8 +121,15 @@ ConnectionThrottle: LogWindow: "60s" -# If your using VotingPlugin you don't need this -# Doesn't support tokens yet +# The first retry always waits 60 seconds. Pending retries expire after one hour. +ForwardingRetry: + # Delay between subsequent retries, in seconds (1 to 3600). + RetryIntervalSeconds: 300 + # Number of retries after the initial send (0 disables retries, maximum 3600). + MaxRetries: 12 + # Require a prior completed write and flush to this destination during this run. + RequirePreviousSuccessBeforeRetry: true + Forwarding: server1: Enabled: false @@ -131,3 +138,8 @@ Forwarding: Key: '' # If token is set a token will be used instead of the key Token: '' + # Optional overrides. Omitted or invalid values inherit the global settings. + # ForwardingRetry: + # RetryIntervalSeconds: 300 + # MaxRetries: 12 + # RequirePreviousSuccessBeforeRetry: true diff --git a/VotifierPlus/src/main/resources/config.yml b/VotifierPlus/src/main/resources/config.yml index 1526183..d613a54 100644 --- a/VotifierPlus/src/main/resources/config.yml +++ b/VotifierPlus/src/main/resources/config.yml @@ -124,8 +124,15 @@ ConnectionThrottle: # --------------------------------------------------------------------------- LogWindow: "60s" -# If your using VotingPlugin you don't need this -# Doesn't support tokens yet +# The first retry always waits 60 seconds. Pending retries expire after one hour. +ForwardingRetry: + # Delay between subsequent retries, in seconds (1 to 3600). + RetryIntervalSeconds: 300 + # Number of retries after the initial send (0 disables retries, maximum 3600). + MaxRetries: 12 + # Require a prior completed write and flush to this destination during this run. + RequirePreviousSuccessBeforeRetry: true + Forwarding: server1: Enabled: false @@ -134,3 +141,8 @@ Forwarding: Key: '' # If token is set a token will be used instead of the key Token: '' + # Optional overrides. Omitted or invalid values inherit the global settings. + # ForwardingRetry: + # RetryIntervalSeconds: 300 + # MaxRetries: 12 + # RequirePreviousSuccessBeforeRetry: true diff --git a/VotifierPlus/src/test/java/com/bencodez/votifierplus/tests/net/VoteForwarderRetryTest.java b/VotifierPlus/src/test/java/com/bencodez/votifierplus/tests/net/VoteForwarderRetryTest.java index 7ddc6a9..d3175b1 100644 --- a/VotifierPlus/src/test/java/com/bencodez/votifierplus/tests/net/VoteForwarderRetryTest.java +++ b/VotifierPlus/src/test/java/com/bencodez/votifierplus/tests/net/VoteForwarderRetryTest.java @@ -19,6 +19,7 @@ import java.util.ArrayList; import java.util.Base64; import java.util.Collections; +import java.util.Comparator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -28,22 +29,25 @@ import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.function.BiFunction; +import java.util.function.LongSupplier; import java.util.function.Supplier; import javax.crypto.KeyGenerator; import javax.crypto.Mac; +import javax.crypto.spec.SecretKeySpec; import org.junit.jupiter.api.Test; import com.google.gson.JsonParser; import com.vexsoftware.votifier.ForwardServer; import com.vexsoftware.votifier.model.Vote; +import com.vexsoftware.votifier.net.ForwardRetryConfig; import com.vexsoftware.votifier.net.VoteForwarder; import com.vexsoftware.votifier.net.VoteReceiver; class VoteForwarderRetryTest { @Test - void retriesOnlyFailedTargetWithOriginalVoteAndCurrentToken() throws Exception { + void retriesOnlyFailedTargetWithOriginalVoteAndConfiguredToken() throws Exception { try (var run = new Forwarding(2)) { run.addTarget("healthy", 2001); run.addTarget("recovering", 2002); @@ -56,12 +60,11 @@ void retriesOnlyFailedTargetWithOriginalVoteAndCurrentToken() throws Exception { for (int i = 0; i < 7; i++) { run.scheduler.runNext(); } - assertEquals(List.of(15L, 15L, 15L, 15L, 15L, 30L, 30L, 30L), run.scheduler.delays); + assertEquals(List.of(60L, 300L, 300L, 300L, 300L, 300L, 300L, 300L), run.scheduler.delays); assertEquals(1, Collections.frequency(run.connects, 2001)); assertEquals(8, Collections.frequency(run.connects, 2002)); assertEquals(1, run.payloads.size()); - run.addTarget("recovering", 2002); run.unavailablePort = -1; run.scheduler.runNext(); assertTrue(run.scheduler.getQueue().isEmpty()); @@ -154,7 +157,7 @@ void retriesInitialAndRepeatedAddressResolutionTimeout() throws Exception { run.slowResolution = true; run.forward(testVote()); run.scheduler.runNext(); - assertEquals(List.of(15L, 15L), run.scheduler.delays); + assertEquals(List.of(60L, 300L), run.scheduler.delays); assertTrue(run.connects.isEmpty()); run.slowResolution = false; @@ -184,12 +187,261 @@ void retirementClosesActiveRetrySocketDuringDrain() throws Exception { } } + @Test + void fixedFirstRetryThenConfiguredIntervalAndCount() throws Exception { + for (int interval : new int[] {1, 300, 3600}) { + for (int count : new int[] {0, 1, 2, 3600}) { + try (var run = new Forwarding(1, new ForwardRetryConfig(interval, count, false))) { + run.addTarget("backend", 2001); + run.unavailablePort = 2001; + run.forward(testVote()); + run.scheduler.runIfDue(TimeUnit.SECONDS.toNanos(60) - 1); + assertEquals(1, run.connects.size()); + run.scheduler.runIfDue(TimeUnit.SECONDS.toNanos(60)); + assertEquals(count == 0 ? 1 : 2, run.connects.size()); + if (count >= 2 && interval < 3540) { + assertEquals(List.of(60L, (long) interval), run.scheduler.delays); + run.scheduler.runIfDue(TimeUnit.SECONDS.toNanos(60 + interval) - 1); + assertEquals(2, run.connects.size()); + run.scheduler.runNext(); + assertEquals(3, run.connects.size()); + } + if (count <= 2 || interval == 3600) { + assertTrue(run.scheduler.getQueue().isEmpty()); + } + } + } + } + } + + @Test + void defaultCountFitsAndLateSchedulerCannotStartAtOrBeyondExpiry() throws Exception { + try (var run = new Forwarding(1)) { + run.addTarget("backend", 2001); + run.unavailablePort = 2001; + run.forward(testVote()); + for (int i = 0; i < 12; i++) { + run.scheduler.runNext(); + } + assertEquals(13, run.connects.size()); + assertTrue(run.scheduler.getQueue().isEmpty()); + } + for (long elapsed : new long[] {3599, 3600, 3601}) { + try (var run = new Forwarding(1, new ForwardRetryConfig(1, 3600, false))) { + run.addTarget("backend", 2001); + run.unavailablePort = 2001; + run.forward(testVote()); + run.scheduler.runIfDue(TimeUnit.SECONDS.toNanos(elapsed)); + assertEquals(elapsed < 3600 ? 2 : 1, run.connects.size()); + assertTrue(run.scheduler.getQueue().isEmpty()); + } + } + } + + @Test + void previousTransportSuccessIsPerTargetAndClearedOnChangeAndRetirement() throws Exception { + try (var run = new Forwarding(2, ForwardRetryConfig.DEFAULT)) { + run.addTarget("cold", 2001); + run.addTarget("healthy", 2002); + run.unavailablePort = 2001; + run.forward(testVote()); + assertTrue(run.scheduler.getQueue().isEmpty()); + run.failWrite = true; + run.unavailablePort = -1; + run.forward(testVote()); // Greeting and failed write cannot establish success. + run.failWrite = false; + run.unavailablePort = 2001; + run.forward(testVote()); + assertTrue(run.scheduler.getQueue().isEmpty()); + run.targets.remove("cold"); + run.unavailablePort = 2002; + run.forward(testVote()); + assertEquals(1, run.scheduler.getQueue().size()); + run.addTarget("healthy", 2002); // Change only the token. + int sends = run.connects.size(); + run.scheduler.runNext(); + assertEquals(sends, run.connects.size()); + run.forward(testVote()); + assertTrue(run.scheduler.getQueue().isEmpty()); + run.unavailablePort = 2001; + run.forward(testVote()); // A completed send establishes the new token's success. + run.unavailablePort = 2002; + run.forward(testVote()); + assertEquals(1, run.scheduler.getQueue().size()); + run.retire(); + assertTrue(run.scheduler.getQueue().isEmpty()); + } + try (var replacement = new Forwarding(1, ForwardRetryConfig.DEFAULT)) { + replacement.addTarget("healthy", 2002); + replacement.unavailablePort = 2002; + replacement.forward(testVote()); + assertTrue(replacement.scheduler.getQueue().isEmpty()); + } + } + + @Test + void invalidSettingsUseSafeDefaultsAndZeroCountDisables() { + assertEquals(ForwardRetryConfig.DEFAULT, ForwardRetryConfig.parse(null, null, null)); + assertEquals(ForwardRetryConfig.DEFAULT, ForwardRetryConfig.parse(-1, -1, "invalid")); + assertEquals(ForwardRetryConfig.DEFAULT, ForwardRetryConfig.parse(0, Long.MAX_VALUE, 0)); + assertEquals(ForwardRetryConfig.DEFAULT, ForwardRetryConfig.parse(1.5, "2147483648", List.of(false))); + assertEquals(new ForwardRetryConfig(17, 0, false), ForwardRetryConfig.parse("17", 0, false)); + } + + @Test + void destinationPoliciesInheritAndOverrideIndependently() throws Exception { + var global = new ForwardRetryConfig(300, 4, true); + assertEquals(global, global.withOverrides(null, null, null)); + assertEquals(global, global.withOverrides(-1, "2147483648", "invalid")); + try (var run = new Forwarding(4, global)) { + run.addTarget("quick", 2001, global.withOverrides(1, 2, false)); + run.addTarget("slow", 2001, global.withOverrides(3539, 4, "false")); + run.addTarget("inherited", 2001, global.withOverrides(null, -1, null)); + run.addTarget("disabled", 2001, global.withOverrides(3, 0, false)); + run.unavailablePort = 2001; + run.forward(testVote()); + assertEquals(4, run.connects.size()); + assertEquals(List.of(60L, 60L), run.scheduler.delays); + run.scheduler.runIfDue(TimeUnit.SECONDS.toNanos(60) - 1); + assertEquals(4, run.connects.size()); + run.scheduler.runNext(); + run.scheduler.runNext(); + assertEquals(6, run.connects.size()); + assertEquals(List.of(60L, 60L, 1L, 3539L), run.scheduler.delays); + run.scheduler.runNext(); + assertEquals(7, run.connects.size()); + run.scheduler.runIfDue(TimeUnit.HOURS.toNanos(1)); + assertEquals(7, run.connects.size()); + assertTrue(run.scheduler.getQueue().isEmpty()); + } + } + + @Test + void policyChangeInvalidatesPreviousSuccessAndQueuedVotes() throws Exception { + try (var run = new Forwarding(2, ForwardRetryConfig.DEFAULT)) { + run.addTarget("backend", 2001, ForwardRetryConfig.DEFAULT); + run.forward(testVote()); + run.unavailablePort = 2001; + run.forward(testVote()); + assertEquals(1, run.scheduler.getQueue().size()); + var previous = run.targets.get("backend"); + run.targets.put("backend", new ForwardServer(true, "localhost", 2001, "", previous.getToken(), + ForwardRetryConfig.DEFAULT.withOverrides(10, null, null))); + run.scheduler.runNext(); + assertEquals(2, run.connects.size()); + run.forward(testVote()); + assertTrue(run.scheduler.getQueue().isEmpty()); + } + } + + @Test + void opaqueKeyDoesNotPreventLaterTargetsFromReceivingVote() throws Exception { + try (var run = new Forwarding(2, ForwardRetryConfig.DEFAULT)) { + Key opaque = mock(Key.class); + when(opaque.getEncoded()).thenThrow(new UnsupportedOperationException()); + run.targets.put("opaque", new ForwardServer(true, "localhost", 2001, "", opaque)); + run.addTarget("healthy", 2002); + run.unavailablePort = 2001; + + run.forward(testVote()); + assertEquals(List.of(2001, 2002), run.connects); + assertEquals(1, run.payloads.size()); + assertTrue(run.scheduler.getQueue().isEmpty()); + + run.forwarder.forwardVote(testVote()); + assertEquals(List.of(2001, 2002, 2001, 2002), run.connects); + assertEquals(2, run.payloads.size()); + } + } + + @Test + void tokenReplacementDuringIdentityReadCannotChangeInFlightCredential() throws Exception { + try (var run = new Forwarding(1, ForwardRetryConfig.DEFAULT)) { + run.addTarget("backend", 2001); + ForwardServer target = run.targets.get("backend"); + Key original = target.getToken(); + Key replacement = run.token(); + target.setToken(new SecretKeySpec(original.getEncoded(), "HmacSHA256") { + @Override + public byte[] getEncoded() { + target.setToken(replacement); + return super.getEncoded(); + } + }); + + run.forward(testVote()); + var packet = JsonParser.parseString(run.payloads.getLast().toString(StandardCharsets.UTF_8)).getAsJsonObject(); + byte[] payload = packet.get("payload").getAsString().getBytes(StandardCharsets.UTF_8); + Mac signer = Mac.getInstance("HmacSHA256"); + signer.init(original); + assertEquals(Base64.getEncoder().encodeToString(signer.doFinal(payload)), packet.get("signature").getAsString()); + + run.unavailablePort = 2001; + run.forward(testVote()); + assertTrue(run.scheduler.getQueue().isEmpty()); + } + } + + @Test + void customLegacyModeWithRetainedTokenUsesLegacyPathOnInitialSendAndRetry() throws Exception { + try (var run = new Forwarding(1, ForwardRetryConfig.DEFAULT)) { + var target = new ForwardServer(true, "localhost", 2001, "synthetic-key", run.token()) { + @Override + public boolean isUseTokens() { + return false; + } + }; + run.targets.put("backend", target); + run.greeting = "VOTIFIER 1"; + var publicKey = mock(java.security.PublicKey.class); + when(run.receiver.getPublicKey(target)).thenReturn(publicKey); + when(run.receiver.encrypt(org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.same(publicKey))) + .thenAnswer(call -> call.getArgument(0)); + + run.forward(testVote()); + run.unavailablePort = 2001; + run.forward(testVote()); + assertEquals(List.of(60L), run.scheduler.delays); + run.unavailablePort = -1; + run.scheduler.runNext(); + assertEquals(2, run.payloads.size()); + assertTrue(run.payloads.getLast().toString(StandardCharsets.UTF_8).startsWith("VOTE\n")); + assertTrue(run.scheduler.getQueue().isEmpty()); + } + } + + @Test + void successDuringCleanupDoesNotRetroactivelyQualifyEarlierFailure() throws Exception { + try (var run = new Forwarding(2, ForwardRetryConfig.DEFAULT); var workers = Executors.newSingleThreadExecutor()) { + run.addTarget("backend", 2001); + run.unavailablePort = 2001; + run.holdNextClose = true; + var earlier = workers.submit(() -> { run.forward(testVote()); return null; }); + try { + assertTrue(run.closeStarted.await(3, TimeUnit.SECONDS)); + run.unavailablePort = -1; + run.forward(testVote()); + assertEquals(1, run.payloads.size()); + } finally { + run.releaseClose.countDown(); + } + earlier.get(3, TimeUnit.SECONDS); + assertTrue(run.scheduler.getQueue().isEmpty()); + + run.unavailablePort = 2001; + run.forward(testVote()); + assertEquals(List.of(60L), run.scheduler.delays); + } + } + private static Vote testVote() { return new Vote("example.test", "TestVoter", "192.0.2.10", "test-time"); } private static final class ManualScheduler extends ScheduledThreadPoolExecutor { final List delays = new ArrayList<>(); + final Map due = new LinkedHashMap<>(); + volatile long now; ManualScheduler() { super(1); @@ -197,15 +449,34 @@ private static final class ManualScheduler extends ScheduledThreadPoolExecutor { @Override public ScheduledFuture schedule(Runnable command, long delay, TimeUnit unit) { - delays.add(unit.toMinutes(delay)); - return super.schedule(command, delay, unit); + delays.add(unit.toSeconds(delay)); + ScheduledFuture scheduled = super.schedule(command, 1, TimeUnit.DAYS); + due.put((Runnable) scheduled, now + unit.toNanos(delay)); + return scheduled; } void runNext() { - Runnable next = getQueue().peek(); + Runnable next = next(); assertNotNull(next); - assertTrue(remove(next)); - next.run(); + runIfDue(Math.max(now, due.get(next))); + } + + void runIfDue(long time) { + now = time; + Runnable next = next(); + if (next != null && doneWaiting(next)) { + assertTrue(remove(next)); + due.remove(next); + next.run(); + } + } + + private Runnable next() { + return getQueue().stream().min(Comparator.comparingLong(due::get)).orElse(null); + } + + private boolean doneWaiting(Runnable next) { + return due.get(next) <= now; } } @@ -215,23 +486,30 @@ private static final class Forwarding implements AutoCloseable { final List payloads = new ArrayList<>(); final ManualScheduler scheduler = new ManualScheduler(); final VoteForwarder forwarder; + final VoteReceiver receiver = mock(VoteReceiver.class); int unavailablePort = -1; int writeCalls; boolean failWrite; boolean blockWrite; + boolean holdNextClose; + final CountDownLatch closeStarted = new CountDownLatch(1); + final CountDownLatch releaseClose = new CountDownLatch(1); volatile boolean slowResolution; final CountDownLatch writeStarted = new CountDownLatch(1); final CountDownLatch retrySocketClosed = new CountDownLatch(1); String greeting = "VOTIFIER 2 test-challenge"; Forwarding(int capacity) throws Exception { - var receiver = mock(VoteReceiver.class); + this(capacity, new ForwardRetryConfig(300, 12, false)); + } + + Forwarding(int capacity, ForwardRetryConfig retryConfig) throws Exception { when(receiver.getServers()).thenReturn(targets.keySet()); when(receiver.getServerData(org.mockito.ArgumentMatchers.anyString())) .thenAnswer(call -> targets.get(call.getArgument(0))); when(receiver.getForwardQueueCapacity()).thenReturn(capacity); var constructor = VoteForwarder.class.getDeclaredConstructor(VoteReceiver.class, int.class, - BiFunction.class, Supplier.class, ScheduledThreadPoolExecutor.class); + BiFunction.class, Supplier.class, ScheduledThreadPoolExecutor.class, ForwardRetryConfig.class, LongSupplier.class); constructor.setAccessible(true); BiFunction resolver = (host, port) -> { if (slowResolution) { @@ -243,11 +521,16 @@ private static final class Forwarding implements AutoCloseable { } return new InetSocketAddress(java.net.InetAddress.getLoopbackAddress(), port); }; - forwarder = constructor.newInstance(receiver, 2, resolver, (Supplier) this::socket, scheduler); + forwarder = constructor.newInstance(receiver, 2, resolver, (Supplier) this::socket, + scheduler, retryConfig, (LongSupplier) () -> scheduler.now); } void addTarget(String name, int port) throws Exception { - targets.put(name, new ForwardServer(true, "localhost", port, "", token())); + addTarget(name, port, null); + } + + void addTarget(String name, int port, ForwardRetryConfig retryConfig) throws Exception { + targets.put(name, new ForwardServer(true, "localhost", port, "", token(), retryConfig)); } Key token() throws Exception { @@ -279,6 +562,8 @@ private void invoke(String name, Vote vote) throws Exception { } private Socket socket() { + boolean holdClose = holdNextClose; + holdNextClose = false; return new Socket() { @Override public void connect(SocketAddress address, int timeout) throws IOException { @@ -296,6 +581,17 @@ public ByteArrayInputStream getInputStream() { @Override public synchronized void close() throws IOException { + if (holdClose) { + closeStarted.countDown(); + try { + if (!releaseClose.await(4, TimeUnit.SECONDS)) { + throw new IOException("Test did not release socket cleanup"); + } + } catch (InterruptedException ex) { + Thread.currentThread().interrupt(); + throw new IOException(ex); + } + } super.close(); if (blockWrite) { retrySocketClosed.countDown();