From a79566a84b32e5127280928420fc1163a3852e39 Mon Sep 17 00:00:00 2001 From: Ben McIlwain Date: Fri, 27 Nov 2026 12:14:03 -0500 Subject: [PATCH] Make BSA stage transitions and retries explicit BSA download and refresh pipelines currently rely on ordinal Enum.compareTo checks for stage advancement, silently discard updated schedule state mid-run, miscompute maxNopInterval on retried downloads, ignore non-2xx daily upload failures, and retry permanent 4xx HTTP responses as if they were transient. These gaps allow illegal transitions such as DONE -> NOP and stage skips, risk wiping previous completed download metadata, hide failed daily uploads behind success notifications, and burn retry budgets under the global BSA lock on permanent client errors. Replacing ordinal comparisons with explicit transition tables and fixing the state-handling and HTTP classification bugs ensures every BSA stage transition is validated, stale schedule handles cannot overwrite a concurrent worker's progress, metadata and checksums stay consistent across download stages, failed daily uploads surface immediately, and permanent 4xx responses fail fast without starving retries. Changes: - Replace ordinal Enum.compareTo checks in DownloadSchedule and RefreshSchedule with explicit ImmutableMultimap allowed-transition tables, forbid DONE -> NOP and illegal stage skips, verify the persisted DB stage still matches this.stage() to reject stale schedule handles, fix the swapped format arguments in transition verification messages, and preserve latestCompleted and alwaysDownload when returning updated schedules. - Capture returned schedules across stage transitions in BsaDownloadAction and BsaRefreshAction so in-memory stage and metadata stay synchronized with persisted state. - Fix DownloadScheduler to evaluate maxNopInterval against the previous completed job rather than the in-progress job when resuming downloads. - Inspect HTTP response status via Response.isSuccessful() in UploadBsaUnavailableDomainsAction so non-2xx responses fail and report errors (sanitizing CR/LF characters before logging at SEVERE), and move ReservedList.loadReservedLists outside replicaTm().transact(...) to avoid nesting primary tm() cache-miss transactions inside replica transactions. - Classify HTTP status codes in BsaException.isRetriableHttpStatus (retrying 408, 429, and 5xx while failing fast on permanent 4xx and unexpected status codes) across BsaReportSender, BlockListFetcher, and BsaCredential, guard getResponseMessage() against IOException across all three clients and disconnect in a finally block in BlockListFetcher.tryFetch, sanitize CR/LF characters when logging BSA report responses to prevent log injection, and log non-retriable BsaExceptions at SEVERE in BsaDownloadAction and BsaRefreshAction. - Add unit and functional tests covering all legal/illegal stage transitions, stale schedule rejection, metadata preservation, resumed maxNopInterval checks, non-2xx daily uploads, non-nested reserved-list loading, 4xx vs 5xx retry classification, BlockListFetcher disconnect ordering and cleanup, and log-injection sanitization. BUG= http://b/591075515 --- .../google/registry/bsa/BlockListFetcher.java | 31 ++- .../registry/bsa/BsaDownloadAction.java | 29 +- .../google/registry/bsa/BsaRefreshAction.java | 15 +- .../UploadBsaUnavailableDomainsAction.java | 44 ++- .../registry/bsa/api/BsaCredential.java | 12 +- .../google/registry/bsa/api/BsaException.java | 15 + .../registry/bsa/api/BsaReportSender.java | 39 ++- .../bsa/persistence/DownloadSchedule.java | 93 +++++-- .../bsa/persistence/DownloadScheduler.java | 4 +- .../bsa/persistence/RefreshSchedule.java | 30 +- .../registry/bsa/BlockListFetcherTest.java | 80 +++++- .../bsa/BsaDownloadFunctionalTest.java | 92 +++++- .../registry/bsa/BsaRefreshActionTest.java | 52 ++++ .../bsa/BsaRefreshFunctionalTest.java | 4 +- ...UploadBsaUnavailableDomainsActionTest.java | 189 ++++++++++++- .../registry/bsa/api/BsaCredentialTest.java | 43 ++- .../registry/bsa/api/BsaReportSenderTest.java | 225 +++++++++++++++ .../bsa/persistence/DownloadScheduleTest.java | 263 ++++++++++++++++++ .../persistence/DownloadSchedulerTest.java | 17 +- .../bsa/persistence/RefreshScheduleTest.java | 149 ++++++++++ 20 files changed, 1313 insertions(+), 113 deletions(-) create mode 100644 core/src/test/java/google/registry/bsa/api/BsaReportSenderTest.java create mode 100644 core/src/test/java/google/registry/bsa/persistence/DownloadScheduleTest.java create mode 100644 core/src/test/java/google/registry/bsa/persistence/RefreshScheduleTest.java diff --git a/core/src/main/java/google/registry/bsa/BlockListFetcher.java b/core/src/main/java/google/registry/bsa/BlockListFetcher.java index b2a6de60029..d1560d19a5d 100644 --- a/core/src/main/java/google/registry/bsa/BlockListFetcher.java +++ b/core/src/main/java/google/registry/bsa/BlockListFetcher.java @@ -66,34 +66,47 @@ LazyBlockList fetch(BlockListType blockListType) { } LazyBlockList tryFetch(BlockListType blockListType) { + HttpsURLConnection connection = null; + boolean handedOff = false; try { URL dataUrl = new URL(blockListUrls.get(blockListType.name())); logger.atInfo().log("Downloading from %s", dataUrl); - HttpsURLConnection connection = - (HttpsURLConnection) urlConnectionService.createConnection(dataUrl); + connection = (HttpsURLConnection) urlConnectionService.createConnection(dataUrl); connection.setRequestMethod(HttpMethods.GET); connection.setRequestProperty("Authorization", "Bearer " + credential.getAuthToken()); int code = connection.getResponseCode(); if (code != SC_OK) { String errorDetails = ""; try (InputStream errorStream = connection.getErrorStream()) { - errorDetails = new String(ByteStreams.toByteArray(errorStream), UTF_8); - } catch (NullPointerException e) { - // No error message. - } catch (Exception e) { + if (errorStream != null) { + errorDetails = new String(ByteStreams.toByteArray(errorStream), UTF_8); + } + } catch (IOException e) { errorDetails = "Failed to retrieve error message: " + e.getMessage(); } + String responseMessage; + try { + responseMessage = connection.getResponseMessage(); + } catch (IOException e) { + responseMessage = "Failed to retrieve response message: " + e.getMessage(); + } throw new BsaException( String.format( "Status code: [%s], error: [%s], details: [%s]", - code, connection.getResponseMessage(), errorDetails), - /* retriable= */ true); + code, responseMessage, errorDetails), + BsaException.isRetriableHttpStatus(code)); } - return new LazyBlockList(blockListType, connection); + LazyBlockList blockList = new LazyBlockList(blockListType, connection); + handedOff = true; + return blockList; } catch (IOException e) { throw new BsaException(e, /* retriable= */ true); } catch (GeneralSecurityException e) { throw new BsaException(e, /* retriable= */ false); + } finally { + if (!handedOff && connection != null) { + connection.disconnect(); + } } } diff --git a/core/src/main/java/google/registry/bsa/BsaDownloadAction.java b/core/src/main/java/google/registry/bsa/BsaDownloadAction.java index 967974f265a..9b1e7ea9c06 100644 --- a/core/src/main/java/google/registry/bsa/BsaDownloadAction.java +++ b/core/src/main/java/google/registry/bsa/BsaDownloadAction.java @@ -34,6 +34,7 @@ import google.registry.bsa.BsaDiffCreator.BsaDiff; import google.registry.bsa.api.BlockLabel; import google.registry.bsa.api.BlockOrder; +import google.registry.bsa.api.BsaException; import google.registry.bsa.api.BsaReportSender; import google.registry.bsa.api.UnblockableDomain; import google.registry.bsa.persistence.DownloadSchedule; @@ -106,6 +107,14 @@ public void run() { logger.atInfo().log("%s.", message); emailSender.sendNotification(message, /* body= */ ""); } + } catch (BsaException e) { + if (e.isRetriable()) { + logger.atWarning().withCause(e).log("Transient failure downloading/processing BSA data."); + } else { + logger.atSevere().withCause(e).log( + "Non-retriable BSA error during download; manual intervention may be required."); + } + emailSender.sendNotification("BSA download aborted", getStackTraceAsString(e)); } catch (Throwable throwable) { logger.atWarning().withCause(throwable).log("Failed to download and process BSA data."); emailSender.sendNotification("BSA download aborted", getStackTraceAsString(throwable)); @@ -162,7 +171,8 @@ Void runWithinLock() { // TODO(01/15/24): add email alert. return null; } - schedule.updateJobStage(DownloadStage.MAKE_ORDER_AND_LABEL_DIFF, actualChecksum); + schedule = + schedule.updateJobStage(DownloadStage.MAKE_ORDER_AND_LABEL_DIFF, actualChecksum); } // Fall through case MAKE_ORDER_AND_LABEL_DIFF: @@ -170,19 +180,22 @@ Void runWithinLock() { // TODO(weiminyu): log the diff stats gcsClient.writeOrderDiffs(schedule.jobName(), diff.getOrders()); gcsClient.writeLabelDiffs(schedule.jobName(), diff.getLabels()); - schedule.updateJobStage(DownloadStage.APPLY_ORDER_AND_LABEL_DIFF); + schedule = schedule.updateJobStage(DownloadStage.APPLY_ORDER_AND_LABEL_DIFF); // Fall through case APPLY_ORDER_AND_LABEL_DIFF: + DownloadSchedule applySchedule = schedule; try (Stream labels = - diff != null ? diff.getLabels() : gcsClient.readLabelDiffs(schedule.jobName())) { + diff != null ? diff.getLabels() : gcsClient.readLabelDiffs(applySchedule.jobName())) { Stream> batches = toBatches(labels, transactionBatchSize); gcsClient.writeUnblockableDomains( - schedule.jobName(), + applySchedule.jobName(), batches - .map(batch -> applyLabelDiff(batch, lazyIdnChecker.get(), schedule, clock.now())) + .map( + batch -> + applyLabelDiff(batch, lazyIdnChecker.get(), applySchedule, clock.now())) .flatMap(ImmutableList::stream)); } - schedule.updateJobStage(DownloadStage.REPORT_START_OF_ORDER_PROCESSING); + schedule = schedule.updateJobStage(DownloadStage.REPORT_START_OF_ORDER_PROCESSING); // Fall through case REPORT_START_OF_ORDER_PROCESSING: try (Stream orders = gcsClient.readOrderDiffs(schedule.jobName())) { @@ -197,7 +210,7 @@ Void runWithinLock() { logger.atInfo().log("No new or deleted orders in this round."); } } - schedule.updateJobStage(DownloadStage.UPLOAD_UNBLOCKABLE_DOMAINS_FOR_NEW_ORDERS); + schedule = schedule.updateJobStage(DownloadStage.UPLOAD_UNBLOCKABLE_DOMAINS_FOR_NEW_ORDERS); // Fall through case UPLOAD_UNBLOCKABLE_DOMAINS_FOR_NEW_ORDERS: try (Stream unblockables = @@ -216,7 +229,7 @@ Void runWithinLock() { logger.atInfo().log("No changes in the set of unblockable domains in this round."); } } - schedule.updateJobStage(DownloadStage.REPORT_END_OF_ORDER_PROCESSING); + schedule = schedule.updateJobStage(DownloadStage.REPORT_END_OF_ORDER_PROCESSING); // Fall through case REPORT_END_OF_ORDER_PROCESSING: try (Stream orders = gcsClient.readOrderDiffs(schedule.jobName())) { diff --git a/core/src/main/java/google/registry/bsa/BsaRefreshAction.java b/core/src/main/java/google/registry/bsa/BsaRefreshAction.java index 57ff6f252e4..3370e140cef 100644 --- a/core/src/main/java/google/registry/bsa/BsaRefreshAction.java +++ b/core/src/main/java/google/registry/bsa/BsaRefreshAction.java @@ -22,6 +22,7 @@ import com.google.common.collect.ImmutableList; import com.google.common.flogger.FluentLogger; +import google.registry.bsa.api.BsaException; import google.registry.bsa.api.BsaReportSender; import google.registry.bsa.api.JsonSerializations; import google.registry.bsa.api.UnblockableDomainChange; @@ -91,6 +92,14 @@ public void run() { logger.atInfo().log("%s.", message); emailSender.sendNotification(message, /* body= */ ""); } + } catch (BsaException e) { + if (e.isRetriable()) { + logger.atWarning().withCause(e).log("Transient failure refreshing BSA data."); + } else { + logger.atSevere().withCause(e).log( + "Non-retriable BSA error during refresh; manual intervention may be required."); + } + emailSender.sendNotification("BSA refresh aborted", getStackTraceAsString(e)); } catch (Throwable throwable) { logger.atWarning().withCause(throwable).log("Failed to refresh BSA data."); emailSender.sendNotification("BSA refresh aborted", getStackTraceAsString(throwable)); @@ -129,14 +138,14 @@ Void runWithinLock() { return null; } gcsClient.writeRefreshChanges(schedule.jobName(), blockabilityChanges.stream()); - schedule.updateJobStage(RefreshStage.APPLY_CHANGES); + schedule = schedule.updateJobStage(RefreshStage.APPLY_CHANGES); // Fall through case APPLY_CHANGES: try (Stream changes = gcsClient.readRefreshChanges(schedule.jobName())) { BatchedStreams.toBatches(changes, 500).forEach(refresher::applyUnblockableChanges); } - schedule.updateJobStage(RefreshStage.UPLOAD_REMOVALS); + schedule = schedule.updateJobStage(RefreshStage.UPLOAD_REMOVALS); // Fall through case UPLOAD_REMOVALS: try (Stream changes = @@ -156,7 +165,7 @@ Void runWithinLock() { logger.atInfo().log("No Unblockable domains to remove."); } } - schedule.updateJobStage(RefreshStage.UPLOAD_ADDITIONS); + schedule = schedule.updateJobStage(RefreshStage.UPLOAD_ADDITIONS); // Fall through case UPLOAD_ADDITIONS: try (Stream changes = diff --git a/core/src/main/java/google/registry/bsa/UploadBsaUnavailableDomainsAction.java b/core/src/main/java/google/registry/bsa/UploadBsaUnavailableDomainsAction.java index 49d206fb461..6b18a76d74c 100644 --- a/core/src/main/java/google/registry/bsa/UploadBsaUnavailableDomainsAction.java +++ b/core/src/main/java/google/registry/bsa/UploadBsaUnavailableDomainsAction.java @@ -195,10 +195,22 @@ boolean uploadToBsa(ImmutableSortedSet unavailableDomains, Instant runTi logger.atInfo().log( "Uploading unavailable domains list %s to %s with hash %s", filename, apiUrl, sha512Hash); try (Response uploadResponse = client.newCall(request).execute()) { + String responseBody = + uploadResponse.body() == null ? "(none)" : uploadResponse.body().string(); + if (!uploadResponse.isSuccessful()) { + String sanitizedResponseBody = responseBody.replace('\r', '_').replace('\n', '_'); + logger.atSevere().log( + "Failed to upload unavailable domains to BSA: status code %d from server: %s", + uploadResponse.code(), sanitizedResponseBody); + response.setStatus(SC_INTERNAL_SERVER_ERROR); + response.setPayload( + String.format( + "BSA upload failed with status code %d: %s", + uploadResponse.code(), responseBody)); + return false; + } logger.atInfo().log( - "Received response with code %s from server: %s", - uploadResponse.code(), - uploadResponse.body() == null ? "(none)" : uploadResponse.body().string()); + "Received response with code %s from server: %s", uploadResponse.code(), responseBody); } return true; } catch (IOException e) { @@ -216,6 +228,10 @@ private static String createFilename(Instant runTime) { private ImmutableSortedSet getUnavailableDomains(Instant runTime) { // Get list of TLDs to process. ImmutableSet bsaEnabledTlds = getActivatedBsaTlds(); + if (bsaEnabledTlds.isEmpty()) { + logger.atInfo().log("No activated BSA TLDs found."); + return ImmutableSortedSet.of(); + } logger.atInfo().log( "Getting unavailable domains in TLDs: %s ...", @@ -225,18 +241,16 @@ private ImmutableSortedSet getUnavailableDomains(Instant runTime) { new ImmutableSortedSet.Builder<>(Ordering.natural()); // Add domains on reserved lists to unavailable names list. - replicaTm() - .transact( - () -> { - for (Tld tld : bsaEnabledTlds) { - for (ReservedList reservedList : loadReservedLists(tld.getReservedListNames())) { - unavailableDomains.addAll( - reservedList.getReservedListEntries().keySet().stream() - .map(label -> toDomain(label, tld)) - .collect(toImmutableSet())); - } - } - }); + // Loaded outside replicaTm() because ReservedList.loadReservedLists() falls back to tm() on + // cache misses, which must not nest inside a replicaTm() transaction. + for (Tld tld : bsaEnabledTlds) { + for (ReservedList reservedList : loadReservedLists(tld.getReservedListNames())) { + unavailableDomains.addAll( + reservedList.getReservedListEntries().keySet().stream() + .map(label -> toDomain(label, tld)) + .collect(toImmutableSet())); + } + } // Add existing domains to unavailable names list, in batches so as to not time out on replica. ImmutableSet tldNames = diff --git a/core/src/main/java/google/registry/bsa/api/BsaCredential.java b/core/src/main/java/google/registry/bsa/api/BsaCredential.java index 39fc8fe18a6..49b812c4e8b 100644 --- a/core/src/main/java/google/registry/bsa/api/BsaCredential.java +++ b/core/src/main/java/google/registry/bsa/api/BsaCredential.java @@ -135,14 +135,20 @@ String fetchNewAuthToken() throws IOException, GeneralSecurityException { String errorDetails; try { errorDetails = new String(getResponseBytes(connection), UTF_8); - } catch (Exception e) { + } catch (IOException e) { errorDetails = "Failed to retrieve error message: " + e.getMessage(); } + String responseMessage; + try { + responseMessage = connection.getResponseMessage(); + } catch (IOException e) { + responseMessage = "Failed to retrieve response message: " + e.getMessage(); + } throw new BsaException( String.format( "Status code: [%s], error: [%s], details: [%s]", - code, connection.getResponseMessage(), errorDetails), - /* retriable= */ true); + code, responseMessage, errorDetails), + BsaException.isRetriableHttpStatus(code)); } // TODO: catch json syntax exception @SuppressWarnings("unchecked") diff --git a/core/src/main/java/google/registry/bsa/api/BsaException.java b/core/src/main/java/google/registry/bsa/api/BsaException.java index 0ed11dd90d8..4a0430f6c6e 100644 --- a/core/src/main/java/google/registry/bsa/api/BsaException.java +++ b/core/src/main/java/google/registry/bsa/api/BsaException.java @@ -14,8 +14,12 @@ package google.registry.bsa.api; +import static jakarta.servlet.http.HttpServletResponse.SC_REQUEST_TIMEOUT; + public class BsaException extends RuntimeException { + private static final int SC_TOO_MANY_REQUESTS = 429; + private final boolean retriable; public BsaException(Throwable cause, boolean retriable) { @@ -31,4 +35,15 @@ public BsaException(String message, boolean retriable) { public boolean isRetriable() { return this.retriable; } + + /** + * Returns whether an unsuccessful HTTP status code represents a transient failure that should be + * retried ({@code 408}, {@code 429}, or {@code 5xx}) rather than a permanent client/request error + * (such as {@code 400}, {@code 401}, {@code 403}, {@code 404}, or {@code 422}). + */ + public static boolean isRetriableHttpStatus(int statusCode) { + return statusCode == SC_REQUEST_TIMEOUT + || statusCode == SC_TOO_MANY_REQUESTS + || (statusCode >= 500 && statusCode < 600); + } } diff --git a/core/src/main/java/google/registry/bsa/api/BsaReportSender.java b/core/src/main/java/google/registry/bsa/api/BsaReportSender.java index 90a9718efa7..46b84644c3e 100644 --- a/core/src/main/java/google/registry/bsa/api/BsaReportSender.java +++ b/core/src/main/java/google/registry/bsa/api/BsaReportSender.java @@ -87,10 +87,10 @@ public void removeUnblockableDomainsUpdates(String payload) { } Void trySendData(String urlString, String payload) { + HttpsURLConnection connection = null; try { URL url = new URL(urlString); - HttpsURLConnection connection = - (HttpsURLConnection) urlConnectionService.createConnection(url); + connection = (HttpsURLConnection) urlConnectionService.createConnection(url); connection.setRequestMethod(HttpMethods.POST); connection.setRequestProperty("Authorization", "Bearer " + credential.getAuthToken()); UrlConnectionUtils.setPayload(connection, payload.getBytes(UTF_8), CONTENT_TYPE.toString()); @@ -98,23 +98,34 @@ Void trySendData(String urlString, String payload) { if (code != SC_OK && code != SC_ACCEPTED) { String errorDetails = ""; try (InputStream errorStream = connection.getErrorStream()) { - errorDetails = new String(ByteStreams.toByteArray(errorStream), UTF_8); - } catch (NullPointerException e) { - // No error message. - } catch (Exception e) { + if (errorStream != null) { + errorDetails = new String(ByteStreams.toByteArray(errorStream), UTF_8); + } + } catch (IOException e) { errorDetails = "Failed to retrieve error message: " + e.getMessage(); } + String responseMessage; + try { + responseMessage = connection.getResponseMessage(); + } catch (IOException e) { + responseMessage = "Failed to retrieve response message: " + e.getMessage(); + } // TODO(b/318404541): sanitize errorDetails to prevent log injection attack. throw new BsaException( String.format( "Status code: [%s], error: [%s], details: [%s]", - code, connection.getResponseMessage(), errorDetails), - /* retriable= */ true); + code, responseMessage, errorDetails), + BsaException.isRetriableHttpStatus(code)); } - try (InputStream errorStream = connection.getInputStream()) { - String responseMessage = new String(ByteStreams.toByteArray(errorStream), UTF_8); - logger.atInfo().log("Received response: [%s]", responseMessage); - } catch (Exception e) { + try (InputStream inputStream = connection.getInputStream()) { + if (inputStream != null) { + String responseMessage = + new String(ByteStreams.toByteArray(inputStream), UTF_8) + .replace('\r', '_') + .replace('\n', '_'); + logger.atInfo().log("Received response: [%s]", responseMessage); + } + } catch (IOException e) { logger.atInfo().withCause(e).log("Failed to retrieve response message."); } return null; @@ -122,6 +133,10 @@ Void trySendData(String urlString, String payload) { throw new BsaException(e, /* retriable= */ true); } catch (GeneralSecurityException e) { throw new BsaException(e, /* retriable= */ false); + } finally { + if (connection != null) { + connection.disconnect(); + } } } } diff --git a/core/src/main/java/google/registry/bsa/persistence/DownloadSchedule.java b/core/src/main/java/google/registry/bsa/persistence/DownloadSchedule.java index daf1d13c893..cbfe65c5d7a 100644 --- a/core/src/main/java/google/registry/bsa/persistence/DownloadSchedule.java +++ b/core/src/main/java/google/registry/bsa/persistence/DownloadSchedule.java @@ -16,12 +16,20 @@ import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Verify.verify; +import static google.registry.bsa.DownloadStage.APPLY_ORDER_AND_LABEL_DIFF; import static google.registry.bsa.DownloadStage.CHECKSUMS_DO_NOT_MATCH; +import static google.registry.bsa.DownloadStage.DONE; +import static google.registry.bsa.DownloadStage.DOWNLOAD_BLOCK_LISTS; import static google.registry.bsa.DownloadStage.MAKE_ORDER_AND_LABEL_DIFF; import static google.registry.bsa.DownloadStage.NOP; +import static google.registry.bsa.DownloadStage.REPORT_END_OF_ORDER_PROCESSING; +import static google.registry.bsa.DownloadStage.REPORT_START_OF_ORDER_PROCESSING; +import static google.registry.bsa.DownloadStage.UPLOAD_UNBLOCKABLE_DOMAINS_FOR_NEW_ORDERS; import static google.registry.persistence.transaction.TransactionManagerFactory.tm; import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableMultimap; +import com.google.errorprone.annotations.CanIgnoreReturnValue; import google.registry.bsa.BlockListType; import google.registry.bsa.DownloadStage; import java.time.Instant; @@ -42,68 +50,101 @@ public record DownloadSchedule( Optional latestCompleted, boolean alwaysDownload) { + static final ImmutableMultimap ALLOWED_TRANSITIONS = + ImmutableMultimap.builder() + .put(DOWNLOAD_BLOCK_LISTS, MAKE_ORDER_AND_LABEL_DIFF) + .put(DOWNLOAD_BLOCK_LISTS, NOP) + .put(DOWNLOAD_BLOCK_LISTS, CHECKSUMS_DO_NOT_MATCH) + .put(MAKE_ORDER_AND_LABEL_DIFF, APPLY_ORDER_AND_LABEL_DIFF) + .put(APPLY_ORDER_AND_LABEL_DIFF, REPORT_START_OF_ORDER_PROCESSING) + .put(REPORT_START_OF_ORDER_PROCESSING, UPLOAD_UNBLOCKABLE_DOMAINS_FOR_NEW_ORDERS) + .put(UPLOAD_UNBLOCKABLE_DOMAINS_FOR_NEW_ORDERS, REPORT_END_OF_ORDER_PROCESSING) + .put(REPORT_END_OF_ORDER_PROCESSING, DONE) + .build(); + /** Updates the current job to the new stage. */ - public void updateJobStage(DownloadStage stage) { - tm().transact( + @CanIgnoreReturnValue + public DownloadSchedule updateJobStage(DownloadStage stage) { + return tm().transact( () -> { BsaDownload bsaDownload = tm().loadByKey(BsaDownload.vKey(jobId())); + DownloadStage currentStage = bsaDownload.getStage(); + verify( + currentStage.equals(this.stage()), + "Stale download schedule for job [%s]: expected stage [%s], found [%s]", + jobId(), + this.stage(), + currentStage); verify( - stage.compareTo(bsaDownload.getStage()) > 0, - "Invalid new stage [%s]. Must move forward from [%s]", - bsaDownload.getStage(), - stage); + ALLOWED_TRANSITIONS.containsEntry(currentStage, stage), + "Invalid new stage [%s]. Cannot transition from [%s]", + stage, + currentStage); + verify( + !currentStage.equals(DOWNLOAD_BLOCK_LISTS), + "Must provide checksums when leaving [%s] stage", + DOWNLOAD_BLOCK_LISTS); bsaDownload.setStage(stage); tm().put(bsaDownload); + return create(bsaDownload, latestCompleted(), alwaysDownload()); }); } /** * Updates the current job to the new stage and sets the checksums of the downloaded files. * - *

This method may only be invoked during the {@code DOWNLOAD} stage, and the target stage must - * be one of {@code MAKE_DIFF}, {@code CHECK_FOR_STALE_UNBLOCKABLES}, {@code NOP}, or {@code - * CHECKSUMS_NOT_MATCH}. + *

This method may only be invoked during the {@code DOWNLOAD_BLOCK_LISTS} stage, and the + * target stage must be one of {@code MAKE_ORDER_AND_LABEL_DIFF}, {@code NOP}, or {@code + * CHECKSUMS_DO_NOT_MATCH}. */ + @CanIgnoreReturnValue public DownloadSchedule updateJobStage( DownloadStage stage, ImmutableMap checksums) { checkArgument( - stage.equals(MAKE_ORDER_AND_LABEL_DIFF) - || stage.equals(NOP) - || stage.equals(CHECKSUMS_DO_NOT_MATCH), - "Invalid stage [%s]", - stage); + ALLOWED_TRANSITIONS.containsEntry(DOWNLOAD_BLOCK_LISTS, stage), + "Invalid new stage [%s]. Cannot transition from [%s]", + stage, + DOWNLOAD_BLOCK_LISTS); return tm().transact( () -> { BsaDownload bsaDownload = tm().loadByKey(BsaDownload.vKey(jobId())); + DownloadStage currentStage = bsaDownload.getStage(); + verify( + currentStage.equals(this.stage()), + "Stale download schedule for job [%s]: expected stage [%s], found [%s]", + jobId(), + this.stage(), + currentStage); verify( - bsaDownload.getStage().equals(DownloadStage.DOWNLOAD_BLOCK_LISTS), - "Invalid invocation. May only invoke during the DOWNLOAD stage."); + currentStage.equals(DOWNLOAD_BLOCK_LISTS), + "Invalid invocation: may only update checksums during [%s] stage, found [%s]", + DOWNLOAD_BLOCK_LISTS, + currentStage); bsaDownload.setStage(stage); bsaDownload.setChecksums(checksums); tm().put(bsaDownload); - return create(bsaDownload); + return create(bsaDownload, latestCompleted(), alwaysDownload()); }); } static DownloadSchedule create(BsaDownload currentJob) { - return new DownloadSchedule( - currentJob.getJobId(), - currentJob.getCreationTime(), - currentJob.getJobName(), - currentJob.getStage(), - Optional.empty(), - /* alwaysDownload= */ true); + return create(currentJob, Optional.empty(), /* alwaysDownload= */ true); } static DownloadSchedule create( BsaDownload currentJob, CompletedJob latestCompleted, boolean alwaysDownload) { + return create(currentJob, Optional.of(latestCompleted), alwaysDownload); + } + + private static DownloadSchedule create( + BsaDownload currentJob, Optional latestCompleted, boolean alwaysDownload) { return new DownloadSchedule( currentJob.getJobId(), currentJob.getCreationTime(), currentJob.getJobName(), currentJob.getStage(), - Optional.of(latestCompleted), - /* alwaysDownload= */ alwaysDownload); + latestCompleted, + alwaysDownload); } /** Information about a completed BSA download job. */ diff --git a/core/src/main/java/google/registry/bsa/persistence/DownloadScheduler.java b/core/src/main/java/google/registry/bsa/persistence/DownloadScheduler.java index 8710aef38ea..bf759fe7c80 100644 --- a/core/src/main/java/google/registry/bsa/persistence/DownloadScheduler.java +++ b/core/src/main/java/google/registry/bsa/persistence/DownloadScheduler.java @@ -106,9 +106,7 @@ public Optional schedule() { verify(prev.getStage().equals(DONE), "Unexpectedly found two ongoing jobs."); return Optional.of( DownloadSchedule.create( - mostRecent, - CompletedJob.create(prev), - isTimeAgain(mostRecent, maxNopInterval))); + mostRecent, CompletedJob.create(prev), isTimeAgain(prev, maxNopInterval))); } }); } diff --git a/core/src/main/java/google/registry/bsa/persistence/RefreshSchedule.java b/core/src/main/java/google/registry/bsa/persistence/RefreshSchedule.java index 8bdad21d29e..2fcaf1181f8 100644 --- a/core/src/main/java/google/registry/bsa/persistence/RefreshSchedule.java +++ b/core/src/main/java/google/registry/bsa/persistence/RefreshSchedule.java @@ -15,8 +15,14 @@ package google.registry.bsa.persistence; import static com.google.common.base.Verify.verify; +import static google.registry.bsa.RefreshStage.APPLY_CHANGES; +import static google.registry.bsa.RefreshStage.CHECK_FOR_CHANGES; +import static google.registry.bsa.RefreshStage.DONE; +import static google.registry.bsa.RefreshStage.UPLOAD_ADDITIONS; +import static google.registry.bsa.RefreshStage.UPLOAD_REMOVALS; import static google.registry.persistence.transaction.TransactionManagerFactory.tm; +import com.google.common.collect.ImmutableMultimap; import com.google.errorprone.annotations.CanIgnoreReturnValue; import google.registry.bsa.RefreshStage; import java.time.Instant; @@ -33,17 +39,33 @@ public record RefreshSchedule( RefreshStage stage, Instant prevRefreshTime) { + static final ImmutableMultimap ALLOWED_TRANSITIONS = + ImmutableMultimap.builder() + .put(CHECK_FOR_CHANGES, DONE) + .put(CHECK_FOR_CHANGES, APPLY_CHANGES) + .put(APPLY_CHANGES, UPLOAD_REMOVALS) + .put(UPLOAD_REMOVALS, UPLOAD_ADDITIONS) + .put(UPLOAD_ADDITIONS, DONE) + .build(); + /** Updates the current job to the new stage. */ @CanIgnoreReturnValue public RefreshSchedule updateJobStage(RefreshStage stage) { return tm().transact( () -> { BsaDomainRefresh bsaRefresh = tm().loadByKey(BsaDomainRefresh.vKey(jobId())); + RefreshStage currentStage = bsaRefresh.getStage(); + verify( + currentStage.equals(this.stage()), + "Stale refresh schedule for job [%s]: expected stage [%s], found [%s]", + jobId(), + this.stage(), + currentStage); verify( - stage.compareTo(bsaRefresh.getStage()) > 0, - "Invalid new stage [%s]. Must move forward from [%s]", - bsaRefresh.getStage(), - stage); + ALLOWED_TRANSITIONS.containsEntry(currentStage, stage), + "Invalid new stage [%s]. Cannot transition from [%s]", + stage, + currentStage); bsaRefresh.setStage(stage); tm().put(bsaRefresh); return create(bsaRefresh, prevRefreshTime()); diff --git a/core/src/test/java/google/registry/bsa/BlockListFetcherTest.java b/core/src/test/java/google/registry/bsa/BlockListFetcherTest.java index 8ceb6a86fc8..ef47047faef 100644 --- a/core/src/test/java/google/registry/bsa/BlockListFetcherTest.java +++ b/core/src/test/java/google/registry/bsa/BlockListFetcherTest.java @@ -15,10 +15,18 @@ package google.registry.bsa; import static com.google.common.truth.Truth.assertThat; +import static jakarta.servlet.http.HttpServletResponse.SC_BAD_REQUEST; +import static jakarta.servlet.http.HttpServletResponse.SC_CREATED; +import static jakarta.servlet.http.HttpServletResponse.SC_FORBIDDEN; +import static jakarta.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR; +import static jakarta.servlet.http.HttpServletResponse.SC_NOT_FOUND; import static jakarta.servlet.http.HttpServletResponse.SC_OK; +import static jakarta.servlet.http.HttpServletResponse.SC_REQUEST_TIMEOUT; +import static jakarta.servlet.http.HttpServletResponse.SC_SERVICE_UNAVAILABLE; import static java.nio.charset.StandardCharsets.UTF_8; -import static org.junit.Assert.assertThrows; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -28,8 +36,9 @@ import google.registry.bsa.api.BsaCredential; import google.registry.bsa.api.BsaException; import google.registry.request.UrlConnectionService; +import google.registry.testing.FakeClock; +import google.registry.testing.FakeSleeper; import google.registry.util.Retrier; -import google.registry.util.SystemSleeper; import java.io.ByteArrayInputStream; import java.io.IOException; import java.net.URL; @@ -38,6 +47,9 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.mockito.InOrder; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; @@ -57,7 +69,7 @@ void setup() { connectionService, credential, ImmutableMap.of("BLOCK", "https://block", "BLOCK_PLUS", "https://blockplus"), - new Retrier(new SystemSleeper(), 2)); + new Retrier(new FakeSleeper(new FakeClock()), 2)); } void setupMocks() throws Exception { @@ -78,14 +90,68 @@ void tryFetch_bsaChecksumFetched() throws Exception { verify(connection, times(1)).setRequestProperty("Authorization", "Bearer authToken"); } - @Test - void tryFetch_ifStatusNotOK_throwRetriable() throws Exception { + @ParameterizedTest + @ValueSource(ints = {SC_REQUEST_TIMEOUT, 429, SC_INTERNAL_SERVER_ERROR, SC_SERVICE_UNAVAILABLE}) + void fetch_transientHttpStatus_retried(int statusCode) throws Exception { setupMocks(); - when(connection.getResponseCode()).thenReturn(201); + when(connection.getResponseCode()).thenReturn(statusCode); assertThat( - assertThrows(BsaException.class, () -> fetcher.tryFetch(BlockListType.BLOCK)) + assertThrows(BsaException.class, () -> fetcher.fetch(BlockListType.BLOCK)) .isRetriable()) .isTrue(); + verify(connectionService, times(2)).createConnection(any(URL.class)); + verify(connection, times(2)).disconnect(); + } + + @ParameterizedTest + @ValueSource(ints = {SC_CREATED, SC_BAD_REQUEST, SC_FORBIDDEN, SC_NOT_FOUND}) + void fetch_permanentHttpStatus_notRetried(int statusCode) throws Exception { + setupMocks(); + when(connection.getResponseCode()).thenReturn(statusCode); + assertThat( + assertThrows(BsaException.class, () -> fetcher.fetch(BlockListType.BLOCK)) + .isRetriable()) + .isFalse(); + verify(connectionService, times(1)).createConnection(any(URL.class)); + verify(connection, times(1)).disconnect(); + } + + @Test + void tryFetch_nonOkStatus_readsResponseMessageBeforeDisconnect() throws Exception { + setupMocks(); + when(connection.getResponseCode()).thenReturn(SC_FORBIDDEN); + when(connection.getResponseMessage()).thenReturn("Forbidden"); + BsaException thrown = + assertThrows(BsaException.class, () -> fetcher.tryFetch(BlockListType.BLOCK)); + assertThat(thrown.isRetriable()).isFalse(); + assertThat(thrown).hasMessageThat().contains("Status code: [403], error: [Forbidden]"); + InOrder inOrder = inOrder(connection); + inOrder.verify(connection).getResponseMessage(); + inOrder.verify(connection).disconnect(); + } + + @Test + void tryFetch_permanentStatusWithResponseMessageIoException_staysNonRetriable() throws Exception { + setupMocks(); + when(connection.getResponseCode()).thenReturn(SC_FORBIDDEN); + when(connection.getResponseMessage()).thenThrow(new IOException("boom")); + BsaException thrown = + assertThrows(BsaException.class, () -> fetcher.tryFetch(BlockListType.BLOCK)); + assertThat(thrown.isRetriable()).isFalse(); + assertThat(thrown) + .hasMessageThat() + .contains("error: [Failed to retrieve response message: boom]"); + verify(connection, times(1)).disconnect(); + } + + @Test + void tryFetch_uncheckedAuthException_disconnectsConnection() throws Exception { + when(connectionService.createConnection(any(URL.class))).thenReturn(connection); + when(credential.getAuthToken()).thenThrow(new BsaException("auth failed", false)); + BsaException thrown = + assertThrows(BsaException.class, () -> fetcher.tryFetch(BlockListType.BLOCK)); + assertThat(thrown.isRetriable()).isFalse(); + verify(connection, times(1)).disconnect(); } @Test diff --git a/core/src/test/java/google/registry/bsa/BsaDownloadFunctionalTest.java b/core/src/test/java/google/registry/bsa/BsaDownloadFunctionalTest.java index 017ede6907e..d20baab125b 100644 --- a/core/src/test/java/google/registry/bsa/BsaDownloadFunctionalTest.java +++ b/core/src/test/java/google/registry/bsa/BsaDownloadFunctionalTest.java @@ -20,19 +20,32 @@ import static google.registry.persistence.transaction.TransactionManagerFactory.tm; import static google.registry.testing.DatabaseHelper.createTlds; import static google.registry.testing.DatabaseHelper.persistResource; +import static google.registry.testing.LogsSubject.assertAboutLogs; import static google.registry.util.DateTimeUtils.START_INSTANT; import static java.nio.charset.StandardCharsets.UTF_8; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import com.google.cloud.storage.contrib.nio.testing.LocalStorageHelper; import com.google.common.base.Joiner; import com.google.common.collect.ImmutableList; +import com.google.common.testing.TestLogHandler; import google.registry.bsa.BlockListFetcher.LazyBlockList; +import google.registry.bsa.api.BlockOrder; +import google.registry.bsa.api.BlockOrder.OrderType; +import google.registry.bsa.api.BsaException; import google.registry.bsa.api.BsaReportSender; import google.registry.bsa.persistence.BsaTld; +import google.registry.bsa.persistence.DownloadSchedule; +import google.registry.bsa.persistence.DownloadScheduler; import google.registry.gcs.GcsUtils; import google.registry.model.tld.Tld.TldType; import google.registry.model.tld.Tlds; @@ -47,11 +60,14 @@ import java.time.Instant; import java.util.Optional; import java.util.function.BiConsumer; +import java.util.logging.Level; +import java.util.logging.Logger; import java.util.stream.Stream; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.extension.RegisterExtension; +import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; @@ -73,6 +89,7 @@ class BsaDownloadFunctionalTest { new JpaTestExtensions.Builder().withClock(fakeClock).buildIntegrationWithCoverageExtension(); private GcsClient gcsClient; + private BsaDiffCreator diffCreator; private BsaDownloadAction action; private Response response; @@ -91,12 +108,13 @@ void setup() throws Exception { tld.asBuilder().setBsaEnrollStartTime(Optional.of(START_INSTANT)).build())); gcsClient = new GcsClient(new GcsUtils(LocalStorageHelper.getOptions()), "my-bucket", "SHA-256"); + diffCreator = spy(new BsaDiffCreator(gcsClient)); response = new FakeResponse(); action = new BsaDownloadAction( createDownloadScheduler(fakeClock), blockListFetcher, - new BsaDiffCreator(gcsClient), + diffCreator, bsaReportSender, gcsClient, IdnChecker::new, @@ -140,6 +158,78 @@ void initialDownload_thenDeleteLabel_noUnblockables() throws Exception { fakeClock.advanceBy(Duration.ofDays(1)); action.run(); assertThat(getPersistedLabels()).containsExactly("abc"); + try (Stream orders = gcsClient.readOrderDiffs("2024-01-02t000000.000z")) { + assertThat(orders).containsExactly(BlockOrder.create(3, OrderType.DELETE)); + } + assertThat(tm().transact(DownloadScheduler::fetchMostRecentDownloadJobIdIfCompleted)) + .hasValue("2024-01-02t000000.000z"); + ArgumentCaptor scheduleCaptor = + ArgumentCaptor.forClass(DownloadSchedule.class); + verify(diffCreator, times(2)).createDiff(scheduleCaptor.capture(), any(IdnChecker.class)); + DownloadSchedule secondDiffSchedule = scheduleCaptor.getAllValues().get(1); + assertThat(secondDiffSchedule.stage()).isEqualTo(DownloadStage.MAKE_ORDER_AND_LABEL_DIFF); + assertThat(secondDiffSchedule.latestCompleted()).isPresent(); + assertThat(secondDiffSchedule.latestCompleted().get().jobName()) + .isEqualTo("2024-01-01t000000.000z"); + } + + @Test + void reportSenderNonRetriable4xx_logsSevereAndDoesNotMarkDone() throws Exception { + TestLogHandler logHandler = new TestLogHandler(); + Logger actionLogger = Logger.getLogger(BsaDownloadAction.class.getCanonicalName()); + actionLogger.addHandler(logHandler); + try { + LazyBlockList blockList = mockBlockList(BlockListType.BLOCK, ImmutableList.of("abc,1")); + LazyBlockList blockPlusList = + mockBlockList(BlockListType.BLOCK_PLUS, ImmutableList.of("abc,2")); + mockBlockListFetcher(blockList, blockPlusList); + doThrow(new BsaException("Status code: [400], error: [Bad Request]", /* retriable= */ false)) + .when(bsaReportSender) + .sendOrderStatusReport(anyString()); + + action.run(); + + assertAboutLogs() + .that(logHandler) + .hasLogAtLevelWithMessage( + Level.SEVERE, + "Non-retriable BSA error during download; manual intervention may be required."); + verify(bsaEmailSender).sendNotification(eq("BSA download aborted"), anyString()); + assertThat(tm().transact(DownloadScheduler::fetchMostRecentDownloadJobIdIfCompleted)) + .isEmpty(); + } finally { + actionLogger.removeHandler(logHandler); + } + } + + @Test + void reportSenderRetriable5xx_logsWarningAndDoesNotMarkDone() throws Exception { + TestLogHandler logHandler = new TestLogHandler(); + Logger actionLogger = Logger.getLogger(BsaDownloadAction.class.getCanonicalName()); + actionLogger.addHandler(logHandler); + try { + LazyBlockList blockList = mockBlockList(BlockListType.BLOCK, ImmutableList.of("abc,1")); + LazyBlockList blockPlusList = + mockBlockList(BlockListType.BLOCK_PLUS, ImmutableList.of("abc,2")); + mockBlockListFetcher(blockList, blockPlusList); + doThrow( + new BsaException( + "Status code: [503], error: [Service Unavailable]", /* retriable= */ true)) + .when(bsaReportSender) + .sendOrderStatusReport(anyString()); + + action.run(); + + assertAboutLogs() + .that(logHandler) + .hasLogAtLevelWithMessage( + Level.WARNING, "Transient failure downloading/processing BSA data."); + verify(bsaEmailSender).sendNotification(eq("BSA download aborted"), anyString()); + assertThat(tm().transact(DownloadScheduler::fetchMostRecentDownloadJobIdIfCompleted)) + .isEmpty(); + } finally { + actionLogger.removeHandler(logHandler); + } } private ImmutableList getPersistedLabels() { diff --git a/core/src/test/java/google/registry/bsa/BsaRefreshActionTest.java b/core/src/test/java/google/registry/bsa/BsaRefreshActionTest.java index 0724273568c..b5c49b1db6f 100644 --- a/core/src/test/java/google/registry/bsa/BsaRefreshActionTest.java +++ b/core/src/test/java/google/registry/bsa/BsaRefreshActionTest.java @@ -15,12 +15,15 @@ package google.registry.bsa; import static com.google.common.base.Throwables.getStackTraceAsString; +import static google.registry.testing.LogsSubject.assertAboutLogs; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import com.google.common.testing.TestLogHandler; +import google.registry.bsa.api.BsaException; import google.registry.bsa.api.BsaReportSender; import google.registry.bsa.persistence.RefreshScheduler; import google.registry.groups.GmailClient; @@ -30,6 +33,8 @@ import jakarta.mail.internet.InternetAddress; import java.time.Duration; import java.time.Instant; +import java.util.logging.Level; +import java.util.logging.Logger; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -96,6 +101,53 @@ void notificationSent_abortedByException() { "BSA refresh aborted", getStackTraceAsString(throwable), emailRecipient)); } + @Test + void notificationSent_abortedByNonRetriableBsaException_logsSevere() { + TestLogHandler logHandler = new TestLogHandler(); + Logger actionLogger = Logger.getLogger(BsaRefreshAction.class.getCanonicalName()); + actionLogger.addHandler(logHandler); + try { + BsaException exception = + new BsaException("Status code: [400], error: [Bad Request]", /* retriable= */ false); + when(bsaLock.executeWithLock(any())).thenThrow(exception); + action.run(); + assertAboutLogs() + .that(logHandler) + .hasLogAtLevelWithMessage( + Level.SEVERE, + "Non-retriable BSA error during refresh; manual intervention may be required."); + verify(gmailClient, times(1)) + .sendEmail( + EmailMessage.create( + "BSA refresh aborted", getStackTraceAsString(exception), emailRecipient)); + } finally { + actionLogger.removeHandler(logHandler); + } + } + + @Test + void notificationSent_abortedByRetriableBsaException_logsWarning() { + TestLogHandler logHandler = new TestLogHandler(); + Logger actionLogger = Logger.getLogger(BsaRefreshAction.class.getCanonicalName()); + actionLogger.addHandler(logHandler); + try { + BsaException exception = + new BsaException( + "Status code: [503], error: [Service Unavailable]", /* retriable= */ true); + when(bsaLock.executeWithLock(any())).thenThrow(exception); + action.run(); + assertAboutLogs() + .that(logHandler) + .hasLogAtLevelWithMessage(Level.WARNING, "Transient failure refreshing BSA data."); + verify(gmailClient, times(1)) + .sendEmail( + EmailMessage.create( + "BSA refresh aborted", getStackTraceAsString(exception), emailRecipient)); + } finally { + actionLogger.removeHandler(logHandler); + } + } + @Test void notification_notSent_whenNoError() { when(bsaLock.executeWithLock(any())) diff --git a/core/src/test/java/google/registry/bsa/BsaRefreshFunctionalTest.java b/core/src/test/java/google/registry/bsa/BsaRefreshFunctionalTest.java index c25d4a16ba2..5a2c4ca34ab 100644 --- a/core/src/test/java/google/registry/bsa/BsaRefreshFunctionalTest.java +++ b/core/src/test/java/google/registry/bsa/BsaRefreshFunctionalTest.java @@ -19,8 +19,8 @@ import static google.registry.bsa.ReservedDomainsTestingUtils.addReservedListsToTld; import static google.registry.bsa.ReservedDomainsTestingUtils.createReservedList; import static google.registry.bsa.ReservedDomainsTestingUtils.removeReservedDomainFromList; -import static google.registry.bsa.persistence.BsaTestingUtils.createDownloadScheduler; import static google.registry.bsa.persistence.BsaTestingUtils.persistBsaLabel; +import static google.registry.bsa.persistence.BsaTestingUtils.persistDownloadSchedule; import static google.registry.bsa.persistence.BsaTestingUtils.queryUnblockableDomains; import static google.registry.model.tld.Tlds.getTldEntitiesOfType; import static google.registry.model.tld.label.ReservationType.RESERVED_FOR_SPECIFIC_USE; @@ -137,7 +137,7 @@ private void initDb() { persistBsaLabel("blocked1"); persistBsaLabel("blocked2"); // Creates a download record so that refresher will not quit immediately. - createDownloadScheduler(fakeClock).schedule().get().updateJobStage(DownloadStage.DONE); + persistDownloadSchedule(DownloadStage.DONE); fakeClock.advanceOneMilli(); } diff --git a/core/src/test/java/google/registry/bsa/UploadBsaUnavailableDomainsActionTest.java b/core/src/test/java/google/registry/bsa/UploadBsaUnavailableDomainsActionTest.java index 365cc767239..6403918e6ef 100644 --- a/core/src/test/java/google/registry/bsa/UploadBsaUnavailableDomainsActionTest.java +++ b/core/src/test/java/google/registry/bsa/UploadBsaUnavailableDomainsActionTest.java @@ -15,6 +15,9 @@ package google.registry.bsa; import static com.google.common.truth.Truth.assertThat; +import static google.registry.persistence.transaction.TransactionManagerFactory.replicaTm; +import static google.registry.persistence.transaction.TransactionManagerFactory.setJpaTm; +import static google.registry.persistence.transaction.TransactionManagerFactory.setReplicaJpaTm; import static google.registry.persistence.transaction.TransactionManagerFactory.tm; import static google.registry.testing.DatabaseHelper.createTld; import static google.registry.testing.DatabaseHelper.persistActiveDomain; @@ -24,8 +27,14 @@ import static google.registry.testing.LogsSubject.assertAboutLogs; import static google.registry.util.DateTimeUtils.START_INSTANT; import static google.registry.util.DateTimeUtils.minusDays; +import static jakarta.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR; import static java.nio.charset.StandardCharsets.UTF_8; import static java.util.concurrent.Executors.newSingleThreadExecutor; +import static org.mockito.AdditionalAnswers.delegatesTo; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; @@ -47,6 +56,8 @@ import google.registry.model.tld.label.ReservedList; import google.registry.persistence.transaction.JpaTestExtensions; import google.registry.persistence.transaction.JpaTestExtensions.JpaIntegrationTestExtension; +import google.registry.persistence.transaction.JpaTransactionManager; +import google.registry.persistence.transaction.TransactionManager.ThrowingRunnable; import google.registry.request.UrlConnectionService; import google.registry.server.Route; import google.registry.server.TestServer; @@ -65,6 +76,8 @@ import java.time.Instant; import java.util.Map; import java.util.Optional; +import java.util.concurrent.Callable; +import java.util.concurrent.atomic.AtomicBoolean; import java.util.logging.Level; import java.util.logging.Logger; import java.util.zip.GZIPInputStream; @@ -83,7 +96,9 @@ public class UploadBsaUnavailableDomainsActionTest { private static final String API_URL = "https://upload.test/bsa"; - private final FakeClock clock = new FakeClock(Instant.parse("2024-02-02T02:02:02Z")); + private static final Instant START_TIME = Instant.parse("2024-02-02T02:02:02Z"); + + private final FakeClock clock = new FakeClock(START_TIME); @RegisterExtension final JpaIntegrationTestExtension jpa = @@ -146,25 +161,144 @@ void uploadToBsaTest() throws Exception { Logger loggerToIntercept = Logger.getLogger(UploadBsaUnavailableDomainsAction.class.getCanonicalName()); loggerToIntercept.addHandler(logHandler); + try { + persistActiveDomain("foobar.tld"); + persistActiveDomain("ace.tld"); + persistDeletedDomain("not-blocked.tld", minusDays(START_TIME, 1)); - persistActiveDomain("foobar.tld"); - persistActiveDomain("ace.tld"); - persistDeletedDomain("not-blocked.tld", minusDays(clock.now(), 1)); + var testServer = startTestServer(); + action.apiUrl = testServer.getUrl("/upload").toURI().toString(); + try { + action.run(); + } finally { + testServer.stop(); + } + String dataSent = "ace.tld\nflagrant.tld\nfoobar.tld\njimmy.tld\ntine.tld\n"; + String checkSum = Hashing.sha512().hashString(dataSent, UTF_8).toString(); + String expectedResponse = + "Received response with code 200 from server: " + + String.format("Checksum: [%s]\n%s\n", checkSum, dataSent); + assertAboutLogs().that(logHandler).hasLogAtLevelWithMessage(Level.INFO, expectedResponse); + verify(emailSender, times(1)).sendNotification("BSA daily upload completed successfully", ""); + } finally { + loggerToIntercept.removeHandler(logHandler); + } + } + + @Test + void uploadToBsa_non2xxResponse_failsAndNotifiesErrors() throws Exception { + TestLogHandler logHandler = new TestLogHandler(); + Logger loggerToIntercept = + Logger.getLogger(UploadBsaUnavailableDomainsAction.class.getCanonicalName()); + loggerToIntercept.addHandler(logHandler); + try { + persistActiveDomain("foobar.tld"); + + var testServer = startTestServer(); + action.apiUrl = testServer.getUrl("/upload-error").toURI().toString(); + try { + action.run(); + } finally { + testServer.stop(); + } + + assertThat(response.getStatus()).isEqualTo(SC_INTERNAL_SERVER_ERROR); + assertThat(response.getPayload()).contains("500"); + assertThat(response.getPayload()).contains("upstream failure"); + assertAboutLogs() + .that(logHandler) + .hasLogAtLevelWithMessage( + Level.SEVERE, + "Failed to upload unavailable domains to BSA: status code 500 from server: upstream" + + " failure"); + verify(emailSender, times(1)) + .sendNotification( + "BSA daily upload completed with errors", "Please see logs for details."); + verify(emailSender, never()).sendNotification("BSA daily upload completed successfully", ""); + } finally { + loggerToIntercept.removeHandler(logHandler); + } + } - var testServer = startTestServer(); - action.apiUrl = testServer.getUrl("/upload").toURI().toString(); + @Test + void uploadToBsa_non2xxResponseWithLineBreaks_sanitizesLog() throws Exception { + TestLogHandler logHandler = new TestLogHandler(); + Logger loggerToIntercept = + Logger.getLogger(UploadBsaUnavailableDomainsAction.class.getCanonicalName()); + loggerToIntercept.addHandler(logHandler); + try { + persistActiveDomain("foobar.tld"); + + var testServer = startTestServer(); + action.apiUrl = testServer.getUrl("/upload-error-multiline").toURI().toString(); + try { + action.run(); + } finally { + testServer.stop(); + } + + assertThat(response.getStatus()).isEqualTo(SC_INTERNAL_SERVER_ERROR); + assertAboutLogs() + .that(logHandler) + .hasLogAtLevelWithMessage( + Level.SEVERE, + "Failed to upload unavailable domains to BSA: status code 500 from server: upstream" + + " failure__forged log line"); + } finally { + loggerToIntercept.removeHandler(logHandler); + } + } + + @Test + void reservedListLoad_doesNotNestInsideReplicaTransaction() throws Exception { + ReservedList uncachedReservedList = + persistReservedList("tld-uncached-reserved-list", "freshlabel,FULLY_BLOCKED"); + persistResource(Tld.get("tld").asBuilder().setReservedLists(uncachedReservedList).build()); + + JpaTransactionManager originalPrimary = tm(); + JpaTransactionManager originalReplica = replicaTm(); + JpaTransactionManager spiedPrimary = + mock(JpaTransactionManager.class, delegatesTo(originalPrimary)); + JpaTransactionManager spiedReplica = + mock(JpaTransactionManager.class, delegatesTo(originalReplica)); + AtomicBoolean nestedInReplica = new AtomicBoolean(false); + AtomicBoolean primaryReTransactCalled = new AtomicBoolean(false); + doAnswer( + invocation -> { + primaryReTransactCalled.set(true); + if (originalReplica.inTransaction()) { + nestedInReplica.set(true); + } + return originalPrimary.reTransact(invocation.>getArgument(0)); + }) + .when(spiedPrimary) + .reTransact(any(Callable.class)); + + setJpaTm(() -> spiedPrimary); + setReplicaJpaTm(() -> spiedReplica); try { action.run(); } finally { - testServer.stop(); + setJpaTm(() -> originalPrimary); + setReplicaJpaTm(() -> originalReplica); } - String dataSent = "ace.tld\nflagrant.tld\nfoobar.tld\njimmy.tld\ntine.tld\n"; - String checkSum = Hashing.sha512().hashString(dataSent, UTF_8).toString(); - String expectedResponse = - "Received response with code 200 from server: " - + String.format("Checksum: [%s]\n%s\n", checkSum, dataSent); - assertAboutLogs().that(logHandler).hasLogAtLevelWithMessage(Level.INFO, expectedResponse); - verify(emailSender, times(1)).sendNotification("BSA daily upload completed successfully", ""); + + assertThat(primaryReTransactCalled.get()).isTrue(); + assertThat(nestedInReplica.get()).isFalse(); + verify(spiedReplica, never()).transact(any(ThrowingRunnable.class)); + BlobId existingFile = BlobId.of(BUCKET, "unavailable_domains_2024-02-02T02:02:02Z.txt"); + String blockList = new String(gcsUtils.readBytesFrom(existingFile), UTF_8); + assertThat(blockList).isEqualTo("freshlabel.tld\n"); + } + + @Test + void noActivatedBsaTlds_sendsNoDomainsNotification() { + tm().transact(() -> tm().delete(BsaTld.createVkey("tld"))); + action.run(); + verify(emailSender, times(1)) + .sendNotification( + "BSA daily upload found no domains to upload", + "This is unexpected. Please investigate."); } private TestServer startTestServer() throws Exception { @@ -172,7 +306,10 @@ private TestServer startTestServer() throws Exception { new TestServer( HostAndPort.fromParts(InetAddress.getLocalHost().getHostAddress(), 0), ImmutableMap.of(), - ImmutableList.of(Route.route("/upload", Servlet.class))); + ImmutableList.of( + Route.route("/upload", Servlet.class), + Route.route("/upload-error", ErrorServlet.class), + Route.route("/upload-error-multiline", MultilineErrorServlet.class))); testServer.start(); newSingleThreadExecutor() .execute( @@ -240,4 +377,26 @@ private String readGzipped(Part part) { } } } + + public static class ErrorServlet extends HttpServlet { + @Override + protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { + resp.setStatus(SC_INTERNAL_SERVER_ERROR); + resp.setContentType("text/plain"); + try (PrintWriter writer = resp.getWriter()) { + writer.print("upstream failure"); + } + } + } + + public static class MultilineErrorServlet extends HttpServlet { + @Override + protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { + resp.setStatus(SC_INTERNAL_SERVER_ERROR); + resp.setContentType("text/plain"); + try (PrintWriter writer = resp.getWriter()) { + writer.print("upstream failure\r\nforged log line"); + } + } + } } diff --git a/core/src/test/java/google/registry/bsa/api/BsaCredentialTest.java b/core/src/test/java/google/registry/bsa/api/BsaCredentialTest.java index 2d0cbbdae20..bb757d6cdeb 100644 --- a/core/src/test/java/google/registry/bsa/api/BsaCredentialTest.java +++ b/core/src/test/java/google/registry/bsa/api/BsaCredentialTest.java @@ -15,9 +15,16 @@ package google.registry.bsa.api; import static com.google.common.truth.Truth.assertThat; +import static jakarta.servlet.http.HttpServletResponse.SC_ACCEPTED; +import static jakarta.servlet.http.HttpServletResponse.SC_BAD_REQUEST; +import static jakarta.servlet.http.HttpServletResponse.SC_FORBIDDEN; +import static jakarta.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR; import static jakarta.servlet.http.HttpServletResponse.SC_OK; +import static jakarta.servlet.http.HttpServletResponse.SC_REQUEST_TIMEOUT; +import static jakarta.servlet.http.HttpServletResponse.SC_SERVICE_UNAVAILABLE; +import static jakarta.servlet.http.HttpServletResponse.SC_UNAUTHORIZED; import static java.nio.charset.StandardCharsets.UTF_8; -import static org.junit.Assert.assertThrows; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.eq; @@ -43,6 +50,8 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; @@ -116,14 +125,40 @@ void fetchNewAuthToken_success() throws Exception { verify(connection, times(1)).disconnect(); } - @Test - void fetchNewAuthToken_whenStatusIsNotOK_throwsRetriableException() throws Exception { + @ParameterizedTest + @ValueSource(ints = {SC_REQUEST_TIMEOUT, 429, SC_INTERNAL_SERVER_ERROR, SC_SERVICE_UNAVAILABLE}) + void fetchNewAuthToken_transientHttpStatus_throwsRetriableException(int statusCode) + throws Exception { setupHttp(); - when(connection.getResponseCode()).thenReturn(202); + when(connection.getResponseCode()).thenReturn(statusCode); assertThat(assertThrows(BsaException.class, () -> credential.getAuthToken()).isRetriable()) .isTrue(); } + @ParameterizedTest + @ValueSource(ints = {SC_ACCEPTED, SC_BAD_REQUEST, SC_UNAUTHORIZED, SC_FORBIDDEN}) + void fetchNewAuthToken_permanentHttpStatus_throwsNonRetriableException(int statusCode) + throws Exception { + setupHttp(); + when(connection.getResponseCode()).thenReturn(statusCode); + assertThat(assertThrows(BsaException.class, () -> credential.getAuthToken()).isRetriable()) + .isFalse(); + } + + @Test + void fetchNewAuthToken_permanent4xxWithResponseMessageIoException_staysNonRetriable() + throws Exception { + setupHttp(); + when(connection.getResponseCode()).thenReturn(SC_FORBIDDEN); + when(connection.getResponseMessage()).thenThrow(new IOException("boom")); + BsaException thrown = assertThrows(BsaException.class, () -> credential.getAuthToken()); + assertThat(thrown.isRetriable()).isFalse(); + assertThat(thrown) + .hasMessageThat() + .contains("error: [Failed to retrieve response message: boom]"); + verify(connection, times(1)).disconnect(); + } + @Test void fetchNewAuthToken_IOException_isRetriable() throws Exception { setupHttp(); diff --git a/core/src/test/java/google/registry/bsa/api/BsaReportSenderTest.java b/core/src/test/java/google/registry/bsa/api/BsaReportSenderTest.java new file mode 100644 index 00000000000..25a0971fbc8 --- /dev/null +++ b/core/src/test/java/google/registry/bsa/api/BsaReportSenderTest.java @@ -0,0 +1,225 @@ +// Copyright 2026 The Nomulus Authors. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package google.registry.bsa.api; + +import static com.google.common.truth.Truth.assertThat; +import static google.registry.testing.LogsSubject.assertAboutLogs; +import static jakarta.servlet.http.HttpServletResponse.SC_ACCEPTED; +import static jakarta.servlet.http.HttpServletResponse.SC_BAD_GATEWAY; +import static jakarta.servlet.http.HttpServletResponse.SC_BAD_REQUEST; +import static jakarta.servlet.http.HttpServletResponse.SC_FORBIDDEN; +import static jakarta.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR; +import static jakarta.servlet.http.HttpServletResponse.SC_NOT_FOUND; +import static jakarta.servlet.http.HttpServletResponse.SC_OK; +import static jakarta.servlet.http.HttpServletResponse.SC_REQUEST_TIMEOUT; +import static jakarta.servlet.http.HttpServletResponse.SC_SERVICE_UNAVAILABLE; +import static jakarta.servlet.http.HttpServletResponse.SC_UNAUTHORIZED; +import static java.nio.charset.StandardCharsets.UTF_8; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import com.google.common.testing.TestLogHandler; +import google.registry.request.UrlConnectionService; +import google.registry.testing.FakeClock; +import google.registry.testing.FakeSleeper; +import google.registry.util.Retrier; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.net.URI; +import java.net.URL; +import java.security.GeneralSecurityException; +import java.util.logging.Level; +import java.util.logging.Logger; +import javax.net.ssl.HttpsURLConnection; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +/** Unit tests for {@link BsaReportSender} and HTTP retry classification. */ +@ExtendWith(MockitoExtension.class) +class BsaReportSenderTest { + + @Mock private UrlConnectionService urlConnectionService; + @Mock private BsaCredential credential; + @Mock private HttpsURLConnection connection; + + private BsaReportSender sender; + + @BeforeEach + void setup() { + sender = + new BsaReportSender( + urlConnectionService, + credential, + "https://bsa.example/orders", + "https://bsa.example/add", + "https://bsa.example/remove", + new Retrier(new FakeSleeper(new FakeClock()), 3)); + } + + private void setupConnection() throws Exception { + when(urlConnectionService.createConnection(any(URL.class))).thenReturn(connection); + when(credential.getAuthToken()).thenReturn("token"); + when(connection.getOutputStream()).thenReturn(new ByteArrayOutputStream()); + } + + @ParameterizedTest + @ValueSource(ints = {SC_OK, SC_ACCEPTED}) + void sendOrderStatusReport_200And202_succeed(int statusCode) throws Exception { + setupConnection(); + when(connection.getResponseCode()).thenReturn(statusCode); + when(connection.getInputStream()) + .thenReturn(new ByteArrayInputStream("{\"ok\":true}".getBytes(UTF_8))); + + sender.sendOrderStatusReport("[]"); + + verify(urlConnectionService, times(1)) + .createConnection(URI.create("https://bsa.example/orders").toURL()); + verify(connection, times(1)).disconnect(); + } + + @Test + void sendOrderStatusReport_responseWithLineBreaks_sanitizedInLog() throws Exception { + TestLogHandler logHandler = new TestLogHandler(); + Logger senderLogger = Logger.getLogger(BsaReportSender.class.getCanonicalName()); + senderLogger.addHandler(logHandler); + try { + setupConnection(); + when(connection.getResponseCode()).thenReturn(SC_OK); + when(connection.getInputStream()) + .thenReturn(new ByteArrayInputStream("ok\r\nFAKE_LOG_ENTRY\nnext\rline".getBytes(UTF_8))); + + sender.sendOrderStatusReport("[]"); + + assertAboutLogs() + .that(logHandler) + .hasLogAtLevelWithMessage( + Level.INFO, "Received response: [ok__FAKE_LOG_ENTRY_next_line]"); + } finally { + senderLogger.removeHandler(logHandler); + } + } + + @ParameterizedTest + @ValueSource(ints = {SC_BAD_REQUEST, SC_UNAUTHORIZED, SC_FORBIDDEN, SC_NOT_FOUND, 422}) + void sendOrderStatusReport_permanent4xx_notRetried(int statusCode) throws Exception { + setupConnection(); + when(connection.getResponseCode()).thenReturn(statusCode); + when(connection.getResponseMessage()).thenReturn("Client Error"); + when(connection.getErrorStream()) + .thenReturn(new ByteArrayInputStream("invalid payload".getBytes(UTF_8))); + + BsaException thrown = + assertThrows(BsaException.class, () -> sender.sendOrderStatusReport("[]")); + + assertThat(thrown.isRetriable()).isFalse(); + assertThat(thrown).hasMessageThat().contains("Status code: [" + statusCode + "]"); + verify(urlConnectionService, times(1)).createConnection(any(URL.class)); + verify(connection, times(1)).disconnect(); + } + + @Test + void sendOrderStatusReport_permanent4xxWithResponseMessageIoException_staysNonRetriable() + throws Exception { + setupConnection(); + when(connection.getResponseCode()).thenReturn(SC_FORBIDDEN); + when(connection.getResponseMessage()).thenThrow(new IOException("boom")); + when(connection.getErrorStream()).thenReturn(null); + + BsaException thrown = + assertThrows(BsaException.class, () -> sender.sendOrderStatusReport("[]")); + + assertThat(thrown.isRetriable()).isFalse(); + assertThat(thrown) + .hasMessageThat() + .contains("error: [Failed to retrieve response message: boom]"); + verify(urlConnectionService, times(1)).createConnection(any(URL.class)); + verify(connection, times(1)).disconnect(); + } + + @ParameterizedTest + @ValueSource( + ints = { + SC_REQUEST_TIMEOUT, + 429, + SC_INTERNAL_SERVER_ERROR, + SC_BAD_GATEWAY, + SC_SERVICE_UNAVAILABLE + }) + void addUnblockableDomainsUpdates_transientStatus_retriedAndRecovers(int statusCode) + throws Exception { + setupConnection(); + when(connection.getResponseCode()).thenReturn(statusCode, SC_OK); + when(connection.getResponseMessage()).thenReturn("Transient Error"); + when(connection.getErrorStream()) + .thenReturn(new ByteArrayInputStream("try again".getBytes(UTF_8))); + when(connection.getInputStream()) + .thenReturn(new ByteArrayInputStream("accepted".getBytes(UTF_8))); + + sender.addUnblockableDomainsUpdates("{}"); + + verify(urlConnectionService, times(2)) + .createConnection(URI.create("https://bsa.example/add").toURL()); + verify(connection, times(2)).disconnect(); + } + + @Test + void removeUnblockableDomainsUpdates_persistent503_exhaustsRetries() throws Exception { + setupConnection(); + when(connection.getResponseCode()).thenReturn(SC_SERVICE_UNAVAILABLE); + when(connection.getResponseMessage()).thenReturn("Service Unavailable"); + when(connection.getErrorStream()).thenReturn(null); + + BsaException thrown = + assertThrows(BsaException.class, () -> sender.removeUnblockableDomainsUpdates("[]")); + + assertThat(thrown.isRetriable()).isTrue(); + verify(urlConnectionService, times(3)) + .createConnection(URI.create("https://bsa.example/remove").toURL()); + verify(connection, times(3)).disconnect(); + } + + @Test + void sendOrderStatusReport_ioException_retried() throws Exception { + setupConnection(); + when(connection.getResponseCode()).thenThrow(new IOException("reset")); + + BsaException thrown = + assertThrows(BsaException.class, () -> sender.sendOrderStatusReport("[]")); + + assertThat(thrown.isRetriable()).isTrue(); + verify(urlConnectionService, times(3)).createConnection(any(URL.class)); + } + + @Test + void sendOrderStatusReport_securityException_notRetried() throws Exception { + when(urlConnectionService.createConnection(any(URL.class))) + .thenThrow(new GeneralSecurityException("tls")); + + BsaException thrown = + assertThrows(BsaException.class, () -> sender.sendOrderStatusReport("[]")); + + assertThat(thrown.isRetriable()).isFalse(); + verify(urlConnectionService, times(1)).createConnection(any(URL.class)); + } +} diff --git a/core/src/test/java/google/registry/bsa/persistence/DownloadScheduleTest.java b/core/src/test/java/google/registry/bsa/persistence/DownloadScheduleTest.java new file mode 100644 index 00000000000..7cfbddacd9e --- /dev/null +++ b/core/src/test/java/google/registry/bsa/persistence/DownloadScheduleTest.java @@ -0,0 +1,263 @@ +// Copyright 2026 The Nomulus Authors. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package google.registry.bsa.persistence; + +import static com.google.common.truth.Truth.assertThat; +import static google.registry.bsa.BlockListType.BLOCK; +import static google.registry.bsa.BlockListType.BLOCK_PLUS; +import static google.registry.bsa.DownloadStage.APPLY_ORDER_AND_LABEL_DIFF; +import static google.registry.bsa.DownloadStage.CHECKSUMS_DO_NOT_MATCH; +import static google.registry.bsa.DownloadStage.DONE; +import static google.registry.bsa.DownloadStage.DOWNLOAD_BLOCK_LISTS; +import static google.registry.bsa.DownloadStage.MAKE_ORDER_AND_LABEL_DIFF; +import static google.registry.bsa.DownloadStage.NOP; +import static google.registry.bsa.DownloadStage.REPORT_END_OF_ORDER_PROCESSING; +import static google.registry.bsa.DownloadStage.REPORT_START_OF_ORDER_PROCESSING; +import static google.registry.bsa.DownloadStage.UPLOAD_UNBLOCKABLE_DOMAINS_FOR_NEW_ORDERS; +import static google.registry.persistence.transaction.TransactionManagerFactory.tm; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import com.google.common.base.VerifyException; +import com.google.common.collect.ImmutableMap; +import google.registry.bsa.BlockListType; +import google.registry.bsa.DownloadStage; +import google.registry.bsa.persistence.DownloadSchedule.CompletedJob; +import google.registry.persistence.transaction.JpaTestExtensions; +import google.registry.persistence.transaction.JpaTestExtensions.JpaIntegrationWithCoverageExtension; +import google.registry.testing.FakeClock; +import java.time.Instant; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; + +/** Unit tests for {@link DownloadSchedule} stage transitions. */ +class DownloadScheduleTest { + + private static final Instant START_TIME = Instant.parse("2024-01-01T00:00:00Z"); + private static final ImmutableMap CHECKSUMS = + ImmutableMap.of(BLOCK, "hash1", BLOCK_PLUS, "hash2"); + private static final CompletedJob PREV_COMPLETED = + new CompletedJob( + "2023-12-31t000000.000z", ImmutableMap.of(BLOCK, "old1", BLOCK_PLUS, "old2")); + + private final FakeClock fakeClock = new FakeClock(START_TIME); + + @RegisterExtension + final JpaIntegrationWithCoverageExtension jpa = + new JpaTestExtensions.Builder().withClock(fakeClock).buildIntegrationWithCoverageExtension(); + + private DownloadSchedule persistSchedule(DownloadStage initialStage, boolean alwaysDownload) { + BsaDownload download = new BsaDownload().setStage(initialStage); + tm().transact(() -> tm().insert(download)); + return DownloadSchedule.create(download, PREV_COMPLETED, alwaysDownload); + } + + @Test + void updateJobStage_fullHappyPath_preservesLatestCompletedAndAlwaysDownload() { + DownloadSchedule schedule = persistSchedule(DOWNLOAD_BLOCK_LISTS, /* alwaysDownload= */ false); + + schedule = schedule.updateJobStage(MAKE_ORDER_AND_LABEL_DIFF, CHECKSUMS); + assertThat(schedule.stage()).isEqualTo(MAKE_ORDER_AND_LABEL_DIFF); + assertThat(schedule.latestCompleted()).hasValue(PREV_COMPLETED); + assertThat(schedule.alwaysDownload()).isFalse(); + + schedule = schedule.updateJobStage(APPLY_ORDER_AND_LABEL_DIFF); + assertThat(schedule.stage()).isEqualTo(APPLY_ORDER_AND_LABEL_DIFF); + assertThat(schedule.latestCompleted()).hasValue(PREV_COMPLETED); + assertThat(schedule.alwaysDownload()).isFalse(); + + schedule = schedule.updateJobStage(REPORT_START_OF_ORDER_PROCESSING); + assertThat(schedule.stage()).isEqualTo(REPORT_START_OF_ORDER_PROCESSING); + assertThat(schedule.latestCompleted()).hasValue(PREV_COMPLETED); + + schedule = schedule.updateJobStage(UPLOAD_UNBLOCKABLE_DOMAINS_FOR_NEW_ORDERS); + assertThat(schedule.stage()).isEqualTo(UPLOAD_UNBLOCKABLE_DOMAINS_FOR_NEW_ORDERS); + assertThat(schedule.latestCompleted()).hasValue(PREV_COMPLETED); + + schedule = schedule.updateJobStage(REPORT_END_OF_ORDER_PROCESSING); + assertThat(schedule.stage()).isEqualTo(REPORT_END_OF_ORDER_PROCESSING); + assertThat(schedule.latestCompleted()).hasValue(PREV_COMPLETED); + + schedule = schedule.updateJobStage(DONE); + assertThat(schedule.stage()).isEqualTo(DONE); + assertThat(schedule.latestCompleted()).hasValue(PREV_COMPLETED); + assertThat(schedule.alwaysDownload()).isFalse(); + + long jobId = schedule.jobId(); + BsaDownload persisted = tm().transact(() -> tm().loadByKey(BsaDownload.vKey(jobId))); + assertThat(persisted.getStage()).isEqualTo(DONE); + assertThat(persisted.getChecksums()).isEqualTo(CHECKSUMS); + } + + @Test + void updateJobStage_terminalDownloadBranches_preserveMetadata() { + DownloadSchedule nopSchedule = + persistSchedule(DOWNLOAD_BLOCK_LISTS, /* alwaysDownload= */ false) + .updateJobStage(NOP, CHECKSUMS); + assertThat(nopSchedule.stage()).isEqualTo(NOP); + assertThat(nopSchedule.latestCompleted()).hasValue(PREV_COMPLETED); + assertThat(nopSchedule.alwaysDownload()).isFalse(); + + fakeClock.advanceOneMilli(); + DownloadSchedule mismatchSchedule = + persistSchedule(DOWNLOAD_BLOCK_LISTS, /* alwaysDownload= */ true) + .updateJobStage(CHECKSUMS_DO_NOT_MATCH, CHECKSUMS); + assertThat(mismatchSchedule.stage()).isEqualTo(CHECKSUMS_DO_NOT_MATCH); + assertThat(mismatchSchedule.latestCompleted()).hasValue(PREV_COMPLETED); + assertThat(mismatchSchedule.alwaysDownload()).isTrue(); + } + + @Test + void updateJobStage_doneToNop_rejectedWithOrderedMessage() { + DownloadSchedule schedule = persistSchedule(DONE, /* alwaysDownload= */ false); + VerifyException thrown = + assertThrows(VerifyException.class, () -> schedule.updateJobStage(NOP)); + assertThat(thrown) + .hasMessageThat() + .isEqualTo("Invalid new stage [NOP]. Cannot transition from [DONE]"); + } + + @Test + void updateJobStage_doneToChecksumsDoNotMatch_rejected() { + DownloadSchedule schedule = persistSchedule(DONE, /* alwaysDownload= */ false); + VerifyException thrown = + assertThrows(VerifyException.class, () -> schedule.updateJobStage(CHECKSUMS_DO_NOT_MATCH)); + assertThat(thrown) + .hasMessageThat() + .isEqualTo("Invalid new stage [CHECKSUMS_DO_NOT_MATCH]. Cannot transition from [DONE]"); + } + + @Test + void updateJobStage_nopToChecksumsDoNotMatch_rejected() { + DownloadSchedule schedule = persistSchedule(NOP, /* alwaysDownload= */ false); + VerifyException thrown = + assertThrows(VerifyException.class, () -> schedule.updateJobStage(CHECKSUMS_DO_NOT_MATCH)); + assertThat(thrown) + .hasMessageThat() + .isEqualTo("Invalid new stage [CHECKSUMS_DO_NOT_MATCH]. Cannot transition from [NOP]"); + } + + @Test + void updateJobStage_stageSkipsAndBackwardTransitions_rejected() { + DownloadSchedule downloadSchedule = + persistSchedule(DOWNLOAD_BLOCK_LISTS, /* alwaysDownload= */ false); + VerifyException skipFromDownload = + assertThrows(VerifyException.class, () -> downloadSchedule.updateJobStage(DONE)); + assertThat(skipFromDownload) + .hasMessageThat() + .isEqualTo("Invalid new stage [DONE]. Cannot transition from [DOWNLOAD_BLOCK_LISTS]"); + + fakeClock.advanceOneMilli(); + DownloadSchedule diffSchedule = + persistSchedule(MAKE_ORDER_AND_LABEL_DIFF, /* alwaysDownload= */ false); + VerifyException skipFromDiff = + assertThrows( + VerifyException.class, + () -> diffSchedule.updateJobStage(REPORT_START_OF_ORDER_PROCESSING)); + assertThat(skipFromDiff) + .hasMessageThat() + .isEqualTo( + "Invalid new stage [REPORT_START_OF_ORDER_PROCESSING]. Cannot transition from" + + " [MAKE_ORDER_AND_LABEL_DIFF]"); + + VerifyException selfTransition = + assertThrows( + VerifyException.class, () -> diffSchedule.updateJobStage(MAKE_ORDER_AND_LABEL_DIFF)); + assertThat(selfTransition) + .hasMessageThat() + .isEqualTo( + "Invalid new stage [MAKE_ORDER_AND_LABEL_DIFF]. Cannot transition from" + + " [MAKE_ORDER_AND_LABEL_DIFF]"); + + VerifyException backwardTransition = + assertThrows( + VerifyException.class, () -> diffSchedule.updateJobStage(DOWNLOAD_BLOCK_LISTS)); + assertThat(backwardTransition) + .hasMessageThat() + .isEqualTo( + "Invalid new stage [DOWNLOAD_BLOCK_LISTS]. Cannot transition from" + + " [MAKE_ORDER_AND_LABEL_DIFF]"); + } + + @Test + void updateJobStage_leavingDownloadWithoutChecksums_rejected() { + DownloadSchedule schedule = persistSchedule(DOWNLOAD_BLOCK_LISTS, /* alwaysDownload= */ false); + VerifyException thrown = + assertThrows( + VerifyException.class, () -> schedule.updateJobStage(MAKE_ORDER_AND_LABEL_DIFF)); + assertThat(thrown) + .hasMessageThat() + .isEqualTo("Must provide checksums when leaving [DOWNLOAD_BLOCK_LISTS] stage"); + } + + @Test + void updateJobStageWithChecksums_invalidTargetOrCurrentStage_rejected() { + DownloadSchedule downloadSchedule = + persistSchedule(DOWNLOAD_BLOCK_LISTS, /* alwaysDownload= */ false); + IllegalArgumentException invalidTarget = + assertThrows( + IllegalArgumentException.class, () -> downloadSchedule.updateJobStage(DONE, CHECKSUMS)); + assertThat(invalidTarget) + .hasMessageThat() + .isEqualTo("Invalid new stage [DONE]. Cannot transition from [DOWNLOAD_BLOCK_LISTS]"); + + fakeClock.advanceOneMilli(); + DownloadSchedule diffSchedule = + persistSchedule(MAKE_ORDER_AND_LABEL_DIFF, /* alwaysDownload= */ false); + VerifyException invalidCurrentStage = + assertThrows( + VerifyException.class, + () -> diffSchedule.updateJobStage(MAKE_ORDER_AND_LABEL_DIFF, CHECKSUMS)); + assertThat(invalidCurrentStage) + .hasMessageThat() + .isEqualTo( + "Invalid invocation: may only update checksums during [DOWNLOAD_BLOCK_LISTS] stage," + + " found [MAKE_ORDER_AND_LABEL_DIFF]"); + } + + @Test + void updateJobStage_staleSchedule_rejectedForBothOverloads() { + DownloadSchedule staleDownload = + persistSchedule(DOWNLOAD_BLOCK_LISTS, /* alwaysDownload= */ false); + DownloadSchedule diffSchedule = + staleDownload.updateJobStage(MAKE_ORDER_AND_LABEL_DIFF, CHECKSUMS); + + VerifyException staleWithChecksums = + assertThrows(VerifyException.class, () -> staleDownload.updateJobStage(NOP, CHECKSUMS)); + assertThat(staleWithChecksums) + .hasMessageThat() + .isEqualTo( + String.format( + "Stale download schedule for job [%s]: expected stage [DOWNLOAD_BLOCK_LISTS]," + + " found [MAKE_ORDER_AND_LABEL_DIFF]", + staleDownload.jobId())); + + diffSchedule.updateJobStage(APPLY_ORDER_AND_LABEL_DIFF); + VerifyException staleWithoutChecksums = + assertThrows( + VerifyException.class, + () -> diffSchedule.updateJobStage(REPORT_START_OF_ORDER_PROCESSING)); + assertThat(staleWithoutChecksums) + .hasMessageThat() + .isEqualTo( + String.format( + "Stale download schedule for job [%s]: expected stage [MAKE_ORDER_AND_LABEL_DIFF]," + + " found [APPLY_ORDER_AND_LABEL_DIFF]", + staleDownload.jobId())); + + long jobId = staleDownload.jobId(); + assertThat(tm().transact(() -> tm().loadByKey(BsaDownload.vKey(jobId))).getStage()) + .isEqualTo(APPLY_ORDER_AND_LABEL_DIFF); + } +} diff --git a/core/src/test/java/google/registry/bsa/persistence/DownloadSchedulerTest.java b/core/src/test/java/google/registry/bsa/persistence/DownloadSchedulerTest.java index d3add84a6b9..e50ba93c009 100644 --- a/core/src/test/java/google/registry/bsa/persistence/DownloadSchedulerTest.java +++ b/core/src/test/java/google/registry/bsa/persistence/DownloadSchedulerTest.java @@ -116,6 +116,21 @@ void oneInProgressJobOneCompletedJob() { assertThat(lastCompleted.checksums()).isEqualTo(completed.getChecksums()); } + @Test + void oneInProgressJobOneCompletedJob_pastMaxNopInterval_alwaysDownloadTrue() { + BsaDownload completed = insertOneJobAndAdvanceClock(DONE); + fakeClock.advanceBy(MAX_NOP_INTERVAL); + BsaDownload inProgressJob = insertOneJobAndAdvanceClock(DOWNLOAD_BLOCK_LISTS); + fakeClock.advanceBy(Duration.ofMinutes(1)); + Optional scheduleOptional = scheduler.schedule(); + assertThat(scheduleOptional).isPresent(); + DownloadSchedule schedule = scheduleOptional.get(); + assertThat(schedule.jobId()).isEqualTo(inProgressJob.jobId); + assertThat(schedule.stage()).isEqualTo(DOWNLOAD_BLOCK_LISTS); + assertThat(schedule.alwaysDownload()).isTrue(); + assertThat(schedule.latestCompleted()).hasValue(CompletedJob.create(completed)); + } + @Test void doneJob_noNewSchedule() { insertOneJobAndAdvanceClock(DONE); @@ -134,7 +149,7 @@ void doneJob_newSchedule() { assertThat(schedule.latestCompleted()).isPresent(); CompletedJob completedJob = schedule.latestCompleted().get(); assertThat(completedJob.jobName()).isEqualTo(completed.getJobName()); - assertThat(completedJob.checksums()).isEqualTo(completedJob.checksums()); + assertThat(completedJob.checksums()).isEqualTo(completed.getChecksums()); } @Test diff --git a/core/src/test/java/google/registry/bsa/persistence/RefreshScheduleTest.java b/core/src/test/java/google/registry/bsa/persistence/RefreshScheduleTest.java new file mode 100644 index 00000000000..54e2c2d0e9b --- /dev/null +++ b/core/src/test/java/google/registry/bsa/persistence/RefreshScheduleTest.java @@ -0,0 +1,149 @@ +// Copyright 2026 The Nomulus Authors. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package google.registry.bsa.persistence; + +import static com.google.common.truth.Truth.assertThat; +import static google.registry.bsa.RefreshStage.APPLY_CHANGES; +import static google.registry.bsa.RefreshStage.CHECK_FOR_CHANGES; +import static google.registry.bsa.RefreshStage.DONE; +import static google.registry.bsa.RefreshStage.UPLOAD_ADDITIONS; +import static google.registry.bsa.RefreshStage.UPLOAD_REMOVALS; +import static google.registry.persistence.transaction.TransactionManagerFactory.tm; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import com.google.common.base.VerifyException; +import google.registry.bsa.RefreshStage; +import google.registry.persistence.transaction.JpaTestExtensions; +import google.registry.persistence.transaction.JpaTestExtensions.JpaIntegrationWithCoverageExtension; +import google.registry.testing.FakeClock; +import java.time.Instant; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; + +/** Unit tests for {@link RefreshSchedule} stage transitions. */ +class RefreshScheduleTest { + + private static final Instant START_TIME = Instant.parse("2024-01-01T00:00:00Z"); + private static final Instant PREV_REFRESH_TIME = Instant.parse("2023-12-31T23:30:00Z"); + + private final FakeClock fakeClock = new FakeClock(START_TIME); + + @RegisterExtension + final JpaIntegrationWithCoverageExtension jpa = + new JpaTestExtensions.Builder().withClock(fakeClock).buildIntegrationWithCoverageExtension(); + + private RefreshSchedule persistSchedule(RefreshStage initialStage) { + BsaDomainRefresh refresh = new BsaDomainRefresh().setStage(initialStage); + tm().transact(() -> tm().insert(refresh)); + return RefreshSchedule.create(refresh, PREV_REFRESH_TIME); + } + + @Test + void updateJobStage_fullHappyPath_succeeds() { + RefreshSchedule schedule = persistSchedule(CHECK_FOR_CHANGES); + + schedule = schedule.updateJobStage(APPLY_CHANGES); + assertThat(schedule.stage()).isEqualTo(APPLY_CHANGES); + assertThat(schedule.prevRefreshTime()).isEqualTo(PREV_REFRESH_TIME); + + schedule = schedule.updateJobStage(UPLOAD_REMOVALS); + assertThat(schedule.stage()).isEqualTo(UPLOAD_REMOVALS); + assertThat(schedule.prevRefreshTime()).isEqualTo(PREV_REFRESH_TIME); + + schedule = schedule.updateJobStage(UPLOAD_ADDITIONS); + assertThat(schedule.stage()).isEqualTo(UPLOAD_ADDITIONS); + assertThat(schedule.prevRefreshTime()).isEqualTo(PREV_REFRESH_TIME); + + schedule = schedule.updateJobStage(DONE); + assertThat(schedule.stage()).isEqualTo(DONE); + assertThat(schedule.prevRefreshTime()).isEqualTo(PREV_REFRESH_TIME); + + long jobId = schedule.jobId(); + assertThat(tm().transact(() -> tm().loadByKey(BsaDomainRefresh.vKey(jobId))).getStage()) + .isEqualTo(DONE); + } + + @Test + void updateJobStage_noChangesShortcut_succeeds() { + RefreshSchedule schedule = persistSchedule(CHECK_FOR_CHANGES).updateJobStage(DONE); + assertThat(schedule.stage()).isEqualTo(DONE); + assertThat(schedule.prevRefreshTime()).isEqualTo(PREV_REFRESH_TIME); + } + + @Test + void updateJobStage_stageSkips_rejectedWithOrderedMessage() { + RefreshSchedule checkSchedule = persistSchedule(CHECK_FOR_CHANGES); + VerifyException skipToRemovals = + assertThrows(VerifyException.class, () -> checkSchedule.updateJobStage(UPLOAD_REMOVALS)); + assertThat(skipToRemovals) + .hasMessageThat() + .isEqualTo( + "Invalid new stage [UPLOAD_REMOVALS]. Cannot transition from [CHECK_FOR_CHANGES]"); + + fakeClock.advanceOneMilli(); + RefreshSchedule applySchedule = persistSchedule(APPLY_CHANGES); + VerifyException skipToDone = + assertThrows(VerifyException.class, () -> applySchedule.updateJobStage(DONE)); + assertThat(skipToDone) + .hasMessageThat() + .isEqualTo("Invalid new stage [DONE]. Cannot transition from [APPLY_CHANGES]"); + + fakeClock.advanceOneMilli(); + RefreshSchedule removalsSchedule = persistSchedule(UPLOAD_REMOVALS); + VerifyException skipAdditions = + assertThrows(VerifyException.class, () -> removalsSchedule.updateJobStage(DONE)); + assertThat(skipAdditions) + .hasMessageThat() + .isEqualTo("Invalid new stage [DONE]. Cannot transition from [UPLOAD_REMOVALS]"); + } + + @Test + void updateJobStage_selfAndBackwardTransitions_rejected() { + RefreshSchedule doneSchedule = persistSchedule(DONE); + VerifyException backward = + assertThrows(VerifyException.class, () -> doneSchedule.updateJobStage(CHECK_FOR_CHANGES)); + assertThat(backward) + .hasMessageThat() + .isEqualTo("Invalid new stage [CHECK_FOR_CHANGES]. Cannot transition from [DONE]"); + + VerifyException self = + assertThrows(VerifyException.class, () -> doneSchedule.updateJobStage(DONE)); + assertThat(self) + .hasMessageThat() + .isEqualTo("Invalid new stage [DONE]. Cannot transition from [DONE]"); + } + + @Test + void updateJobStage_staleSchedule_rejectedAndLeavesPersistedStageUnchanged() { + RefreshSchedule staleSchedule = persistSchedule(CHECK_FOR_CHANGES); + staleSchedule + .updateJobStage(APPLY_CHANGES) + .updateJobStage(UPLOAD_REMOVALS) + .updateJobStage(UPLOAD_ADDITIONS); + + VerifyException thrown = + assertThrows(VerifyException.class, () -> staleSchedule.updateJobStage(DONE)); + assertThat(thrown) + .hasMessageThat() + .isEqualTo( + String.format( + "Stale refresh schedule for job [%s]: expected stage [CHECK_FOR_CHANGES]," + + " found [UPLOAD_ADDITIONS]", + staleSchedule.jobId())); + long jobId = staleSchedule.jobId(); + assertThat(tm().transact(() -> tm().loadByKey(BsaDomainRefresh.vKey(jobId))).getStage()) + .isEqualTo(UPLOAD_ADDITIONS); + } +}